cmDependsC.cxx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. /*============================================================================
  2. CMake - Cross Platform Makefile Generator
  3. Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
  4. Distributed under the OSI-approved BSD License (the "License");
  5. see accompanying file Copyright.txt for details.
  6. This software is distributed WITHOUT ANY WARRANTY; without even the
  7. implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  8. See the License for more information.
  9. ============================================================================*/
  10. #include "cmDependsC.h"
  11. #include "cmFileTimeComparison.h"
  12. #include "cmLocalGenerator.h"
  13. #include "cmMakefile.h"
  14. #include "cmSystemTools.h"
  15. #include <ctype.h> // isspace
  16. #define INCLUDE_REGEX_LINE \
  17. "^[ \t]*#[ \t]*(include|import)[ \t]*[<\"]([^\">]+)([\">])"
  18. #define INCLUDE_REGEX_LINE_MARKER "#IncludeRegexLine: "
  19. #define INCLUDE_REGEX_SCAN_MARKER "#IncludeRegexScan: "
  20. #define INCLUDE_REGEX_COMPLAIN_MARKER "#IncludeRegexComplain: "
  21. #define INCLUDE_REGEX_TRANSFORM_MARKER "#IncludeRegexTransform: "
  22. //----------------------------------------------------------------------------
  23. cmDependsC::cmDependsC()
  24. : ValidDeps(0)
  25. {
  26. }
  27. //----------------------------------------------------------------------------
  28. cmDependsC::cmDependsC(cmLocalGenerator* lg,
  29. const char* targetDir,
  30. const char* lang,
  31. const std::map<std::string, DependencyVector>* validDeps)
  32. : cmDepends(lg, targetDir)
  33. , ValidDeps(validDeps)
  34. {
  35. cmMakefile* mf = lg->GetMakefile();
  36. // Configure the include file search path.
  37. this->SetIncludePathFromLanguage(lang);
  38. // Configure regular expressions.
  39. std::string scanRegex = "^.*$";
  40. std::string complainRegex = "^$";
  41. {
  42. std::string scanRegexVar = "CMAKE_";
  43. scanRegexVar += lang;
  44. scanRegexVar += "_INCLUDE_REGEX_SCAN";
  45. if(const char* sr = mf->GetDefinition(scanRegexVar.c_str()))
  46. {
  47. scanRegex = sr;
  48. }
  49. std::string complainRegexVar = "CMAKE_";
  50. complainRegexVar += lang;
  51. complainRegexVar += "_INCLUDE_REGEX_COMPLAIN";
  52. if(const char* cr = mf->GetDefinition(complainRegexVar.c_str()))
  53. {
  54. complainRegex = cr;
  55. }
  56. }
  57. this->IncludeRegexLine.compile(INCLUDE_REGEX_LINE);
  58. this->IncludeRegexScan.compile(scanRegex.c_str());
  59. this->IncludeRegexComplain.compile(complainRegex.c_str());
  60. this->IncludeRegexLineString = INCLUDE_REGEX_LINE_MARKER INCLUDE_REGEX_LINE;
  61. this->IncludeRegexScanString = INCLUDE_REGEX_SCAN_MARKER;
  62. this->IncludeRegexScanString += scanRegex;
  63. this->IncludeRegexComplainString = INCLUDE_REGEX_COMPLAIN_MARKER;
  64. this->IncludeRegexComplainString += complainRegex;
  65. this->SetupTransforms();
  66. this->CacheFileName = this->TargetDirectory;
  67. this->CacheFileName += "/";
  68. this->CacheFileName += lang;
  69. this->CacheFileName += ".includecache";
  70. this->ReadCacheFile();
  71. }
  72. //----------------------------------------------------------------------------
  73. cmDependsC::~cmDependsC()
  74. {
  75. this->WriteCacheFile();
  76. for (std::map<cmStdString, cmIncludeLines*>::iterator it=
  77. this->FileCache.begin(); it!=this->FileCache.end(); ++it)
  78. {
  79. delete it->second;
  80. }
  81. }
  82. //----------------------------------------------------------------------------
  83. bool cmDependsC::WriteDependencies(const char *src, const char *obj,
  84. std::ostream& makeDepends, std::ostream& internalDepends)
  85. {
  86. // Make sure this is a scanning instance.
  87. if(!src || src[0] == '\0')
  88. {
  89. cmSystemTools::Error("Cannot scan dependencies without a source file.");
  90. return false;
  91. }
  92. if(!obj || obj[0] == '\0')
  93. {
  94. cmSystemTools::Error("Cannot scan dependencies without an object file.");
  95. return false;
  96. }
  97. if (this->ValidDeps != 0)
  98. {
  99. std::map<std::string, DependencyVector>::const_iterator tmpIt =
  100. this->ValidDeps->find(obj);
  101. if (tmpIt!= this->ValidDeps->end())
  102. {
  103. // Write the dependencies to the output stream. Makefile rules
  104. // written by the original local generator for this directory
  105. // convert the dependencies to paths relative to the home output
  106. // directory. We must do the same here.
  107. internalDepends << obj << std::endl;
  108. for(DependencyVector::const_iterator i=tmpIt->second.begin();
  109. i != tmpIt->second.end(); ++i)
  110. {
  111. makeDepends << obj << ": " <<
  112. this->LocalGenerator->Convert(i->c_str(),
  113. cmLocalGenerator::HOME_OUTPUT,
  114. cmLocalGenerator::MAKEFILE)
  115. << std::endl;
  116. internalDepends << " " << i->c_str() << std::endl;
  117. }
  118. makeDepends << std::endl;
  119. return true;
  120. }
  121. }
  122. // Walk the dependency graph starting with the source file.
  123. bool first = true;
  124. UnscannedEntry root;
  125. root.FileName = src;
  126. this->Unscanned.push(root);
  127. this->Encountered.clear();
  128. this->Encountered.insert(src);
  129. std::set<cmStdString> dependencies;
  130. std::set<cmStdString> scanned;
  131. // Use reserve to allocate enough memory for both strings,
  132. // so that during the loops no memory is allocated or freed
  133. std::string cacheKey;
  134. cacheKey.reserve(4*1024);
  135. std::string tempPathStr;
  136. tempPathStr.reserve(4*1024);
  137. while(!this->Unscanned.empty())
  138. {
  139. // Get the next file to scan.
  140. UnscannedEntry current = this->Unscanned.front();
  141. this->Unscanned.pop();
  142. // If not a full path, find the file in the include path.
  143. std::string fullName;
  144. if(first || cmSystemTools::FileIsFullPath(current.FileName.c_str()))
  145. {
  146. if(cmSystemTools::FileExists(current.FileName.c_str(), true))
  147. {
  148. fullName = current.FileName;
  149. }
  150. }
  151. else if(!current.QuotedLocation.empty() &&
  152. cmSystemTools::FileExists(current.QuotedLocation.c_str(), true))
  153. {
  154. // The include statement producing this entry was a double-quote
  155. // include and the included file is present in the directory of
  156. // the source containing the include statement.
  157. fullName = current.QuotedLocation;
  158. }
  159. else
  160. {
  161. // With GCC distribution of STL, assigning to a string directly
  162. // throws away the internal buffer of the left-hand-side. We
  163. // want to keep the pre-allocated buffer so we use C-style
  164. // string assignment and then operator+=. We could call
  165. // .clear() instead of assigning to an empty string but the
  166. // method does not exist on some older compilers.
  167. cacheKey = "";
  168. cacheKey += current.FileName;
  169. for(std::vector<std::string>::const_iterator i =
  170. this->IncludePath.begin(); i != this->IncludePath.end(); ++i)
  171. {
  172. cacheKey+=*i;
  173. }
  174. std::map<cmStdString, cmStdString>::iterator
  175. headerLocationIt=this->HeaderLocationCache.find(cacheKey);
  176. if (headerLocationIt!=this->HeaderLocationCache.end())
  177. {
  178. fullName=headerLocationIt->second;
  179. }
  180. else for(std::vector<std::string>::const_iterator i =
  181. this->IncludePath.begin(); i != this->IncludePath.end(); ++i)
  182. {
  183. // Construct the name of the file as if it were in the current
  184. // include directory. Avoid using a leading "./".
  185. tempPathStr = "";
  186. if((*i) == ".")
  187. {
  188. tempPathStr += current.FileName;
  189. }
  190. else
  191. {
  192. tempPathStr += *i;
  193. tempPathStr+="/";
  194. tempPathStr+=current.FileName;
  195. }
  196. // Look for the file in this location.
  197. if(cmSystemTools::FileExists(tempPathStr.c_str(), true))
  198. {
  199. fullName = tempPathStr;
  200. HeaderLocationCache[cacheKey]=fullName;
  201. break;
  202. }
  203. }
  204. }
  205. // Complain if the file cannot be found and matches the complain
  206. // regex.
  207. if(fullName.empty() &&
  208. this->IncludeRegexComplain.find(current.FileName.c_str()))
  209. {
  210. cmSystemTools::Error("Cannot find file \"",
  211. current.FileName.c_str(), "\".");
  212. return false;
  213. }
  214. // Scan the file if it was found and has not been scanned already.
  215. if(!fullName.empty() && (scanned.find(fullName) == scanned.end()))
  216. {
  217. // Record scanned files.
  218. scanned.insert(fullName);
  219. // Check whether this file is already in the cache
  220. std::map<cmStdString, cmIncludeLines*>::iterator fileIt=
  221. this->FileCache.find(fullName);
  222. if (fileIt!=this->FileCache.end())
  223. {
  224. fileIt->second->Used=true;
  225. dependencies.insert(fullName);
  226. for (std::vector<UnscannedEntry>::const_iterator incIt=
  227. fileIt->second->UnscannedEntries.begin();
  228. incIt!=fileIt->second->UnscannedEntries.end(); ++incIt)
  229. {
  230. if (this->Encountered.find(incIt->FileName) ==
  231. this->Encountered.end())
  232. {
  233. this->Encountered.insert(incIt->FileName);
  234. this->Unscanned.push(*incIt);
  235. }
  236. }
  237. }
  238. else
  239. {
  240. // Try to scan the file. Just leave it out if we cannot find
  241. // it.
  242. std::ifstream fin(fullName.c_str());
  243. if(fin)
  244. {
  245. // Add this file as a dependency.
  246. dependencies.insert(fullName);
  247. // Scan this file for new dependencies. Pass the directory
  248. // containing the file to handle double-quote includes.
  249. std::string dir = cmSystemTools::GetFilenamePath(fullName);
  250. this->Scan(fin, dir.c_str(), fullName);
  251. }
  252. }
  253. }
  254. first = false;
  255. }
  256. // Write the dependencies to the output stream. Makefile rules
  257. // written by the original local generator for this directory
  258. // convert the dependencies to paths relative to the home output
  259. // directory. We must do the same here.
  260. internalDepends << obj << std::endl;
  261. for(std::set<cmStdString>::iterator i=dependencies.begin();
  262. i != dependencies.end(); ++i)
  263. {
  264. makeDepends << obj << ": " <<
  265. this->LocalGenerator->Convert(i->c_str(),
  266. cmLocalGenerator::HOME_OUTPUT,
  267. cmLocalGenerator::MAKEFILE)
  268. << std::endl;
  269. internalDepends << " " << i->c_str() << std::endl;
  270. }
  271. makeDepends << std::endl;
  272. return true;
  273. }
  274. //----------------------------------------------------------------------------
  275. void cmDependsC::ReadCacheFile()
  276. {
  277. if(this->CacheFileName.size() == 0)
  278. {
  279. return;
  280. }
  281. std::ifstream fin(this->CacheFileName.c_str());
  282. if(!fin)
  283. {
  284. return;
  285. }
  286. std::string line;
  287. cmIncludeLines* cacheEntry=0;
  288. bool haveFileName=false;
  289. while(cmSystemTools::GetLineFromStream(fin, line))
  290. {
  291. if (line.empty())
  292. {
  293. cacheEntry=0;
  294. haveFileName=false;
  295. continue;
  296. }
  297. //the first line after an empty line is the name of the parsed file
  298. if (haveFileName==false)
  299. {
  300. haveFileName=true;
  301. int newer=0;
  302. cmFileTimeComparison comp;
  303. bool res=comp.FileTimeCompare(this->CacheFileName.c_str(),
  304. line.c_str(), &newer);
  305. if ((res==true) && (newer==1)) //cache is newer than the parsed file
  306. {
  307. cacheEntry=new cmIncludeLines;
  308. this->FileCache[line]=cacheEntry;
  309. }
  310. // file doesn't exist, check that the regular expressions
  311. // haven't changed
  312. else if (res==false)
  313. {
  314. if (line.find(INCLUDE_REGEX_LINE_MARKER) == 0)
  315. {
  316. if (line != this->IncludeRegexLineString)
  317. {
  318. return;
  319. }
  320. }
  321. else if (line.find(INCLUDE_REGEX_SCAN_MARKER) == 0)
  322. {
  323. if (line != this->IncludeRegexScanString)
  324. {
  325. return;
  326. }
  327. }
  328. else if (line.find(INCLUDE_REGEX_COMPLAIN_MARKER) == 0)
  329. {
  330. if (line != this->IncludeRegexComplainString)
  331. {
  332. return;
  333. }
  334. }
  335. else if (line.find(INCLUDE_REGEX_TRANSFORM_MARKER) == 0)
  336. {
  337. if (line != this->IncludeRegexTransformString)
  338. {
  339. return;
  340. }
  341. }
  342. }
  343. }
  344. else if (cacheEntry!=0)
  345. {
  346. UnscannedEntry entry;
  347. entry.FileName = line;
  348. if (cmSystemTools::GetLineFromStream(fin, line))
  349. {
  350. if (line!="-")
  351. {
  352. entry.QuotedLocation=line;
  353. }
  354. cacheEntry->UnscannedEntries.push_back(entry);
  355. }
  356. }
  357. }
  358. }
  359. //----------------------------------------------------------------------------
  360. void cmDependsC::WriteCacheFile() const
  361. {
  362. if(this->CacheFileName.size() == 0)
  363. {
  364. return;
  365. }
  366. std::ofstream cacheOut(this->CacheFileName.c_str());
  367. if(!cacheOut)
  368. {
  369. return;
  370. }
  371. cacheOut << this->IncludeRegexLineString << "\n\n";
  372. cacheOut << this->IncludeRegexScanString << "\n\n";
  373. cacheOut << this->IncludeRegexComplainString << "\n\n";
  374. cacheOut << this->IncludeRegexTransformString << "\n\n";
  375. for (std::map<cmStdString, cmIncludeLines*>::const_iterator fileIt=
  376. this->FileCache.begin();
  377. fileIt!=this->FileCache.end(); ++fileIt)
  378. {
  379. if (fileIt->second->Used)
  380. {
  381. cacheOut<<fileIt->first.c_str()<<std::endl;
  382. for (std::vector<UnscannedEntry>::const_iterator
  383. incIt=fileIt->second->UnscannedEntries.begin();
  384. incIt!=fileIt->second->UnscannedEntries.end(); ++incIt)
  385. {
  386. cacheOut<<incIt->FileName.c_str()<<std::endl;
  387. if (incIt->QuotedLocation.empty())
  388. {
  389. cacheOut<<"-"<<std::endl;
  390. }
  391. else
  392. {
  393. cacheOut<<incIt->QuotedLocation.c_str()<<std::endl;
  394. }
  395. }
  396. cacheOut<<std::endl;
  397. }
  398. }
  399. }
  400. //----------------------------------------------------------------------------
  401. void cmDependsC::Scan(std::istream& is, const char* directory,
  402. const cmStdString& fullName)
  403. {
  404. cmIncludeLines* newCacheEntry=new cmIncludeLines;
  405. newCacheEntry->Used=true;
  406. this->FileCache[fullName]=newCacheEntry;
  407. // Read one line at a time.
  408. std::string line;
  409. while(cmSystemTools::GetLineFromStream(is, line))
  410. {
  411. // Transform the line content first.
  412. if(!this->TransformRules.empty())
  413. {
  414. this->TransformLine(line);
  415. }
  416. // Match include directives.
  417. if(this->IncludeRegexLine.find(line.c_str()))
  418. {
  419. // Get the file being included.
  420. UnscannedEntry entry;
  421. entry.FileName = this->IncludeRegexLine.match(2);
  422. if(this->IncludeRegexLine.match(3) == "\"" &&
  423. !cmSystemTools::FileIsFullPath(entry.FileName.c_str()))
  424. {
  425. // This was a double-quoted include with a relative path. We
  426. // must check for the file in the directory containing the
  427. // file we are scanning.
  428. entry.QuotedLocation = directory;
  429. entry.QuotedLocation += "/";
  430. entry.QuotedLocation += entry.FileName;
  431. }
  432. // Queue the file if it has not yet been encountered and it
  433. // matches the regular expression for recursive scanning. Note
  434. // that this check does not account for the possibility of two
  435. // headers with the same name in different directories when one
  436. // is included by double-quotes and the other by angle brackets.
  437. // This kind of problem will be fixed when a more
  438. // preprocessor-like implementation of this scanner is created.
  439. if (this->IncludeRegexScan.find(entry.FileName.c_str()))
  440. {
  441. newCacheEntry->UnscannedEntries.push_back(entry);
  442. if(this->Encountered.find(entry.FileName) == this->Encountered.end())
  443. {
  444. this->Encountered.insert(entry.FileName);
  445. this->Unscanned.push(entry);
  446. }
  447. }
  448. }
  449. }
  450. }
  451. //----------------------------------------------------------------------------
  452. void cmDependsC::SetupTransforms()
  453. {
  454. // Get the transformation rules.
  455. std::vector<std::string> transformRules;
  456. cmMakefile* mf = this->LocalGenerator->GetMakefile();
  457. if(const char* xform =
  458. mf->GetDefinition("CMAKE_INCLUDE_TRANSFORMS"))
  459. {
  460. cmSystemTools::ExpandListArgument(xform, transformRules, true);
  461. }
  462. for(std::vector<std::string>::const_iterator tri = transformRules.begin();
  463. tri != transformRules.end(); ++tri)
  464. {
  465. this->ParseTransform(*tri);
  466. }
  467. this->IncludeRegexTransformString = INCLUDE_REGEX_TRANSFORM_MARKER;
  468. if(!this->TransformRules.empty())
  469. {
  470. // Construct the regular expression to match lines to be
  471. // transformed.
  472. std::string xform = "^([ \t]*#[ \t]*(include|import)[ \t]*)(";
  473. const char* sep = "";
  474. for(TransformRulesType::const_iterator tri = this->TransformRules.begin();
  475. tri != this->TransformRules.end(); ++tri)
  476. {
  477. xform += sep;
  478. xform += tri->first;
  479. sep = "|";
  480. }
  481. xform += ")[ \t]*\\(([^),]*)\\)";
  482. this->IncludeRegexTransform.compile(xform.c_str());
  483. // Build a string that encodes all transformation rules and will
  484. // change when rules are changed.
  485. this->IncludeRegexTransformString += xform;
  486. for(TransformRulesType::const_iterator tri = this->TransformRules.begin();
  487. tri != this->TransformRules.end(); ++tri)
  488. {
  489. this->IncludeRegexTransformString += " ";
  490. this->IncludeRegexTransformString += tri->first;
  491. this->IncludeRegexTransformString += "(%)=";
  492. this->IncludeRegexTransformString += tri->second;
  493. }
  494. }
  495. }
  496. //----------------------------------------------------------------------------
  497. void cmDependsC::ParseTransform(std::string const& xform)
  498. {
  499. // A transform rule is of the form SOME_MACRO(%)=value-with-%
  500. // We can simply separate with "(%)=".
  501. std::string::size_type pos = xform.find("(%)=");
  502. if(pos == xform.npos || pos == 0)
  503. {
  504. return;
  505. }
  506. std::string name = xform.substr(0, pos);
  507. std::string value = xform.substr(pos+4, xform.npos);
  508. this->TransformRules[name] = value;
  509. }
  510. //----------------------------------------------------------------------------
  511. void cmDependsC::TransformLine(std::string& line)
  512. {
  513. // Check for a transform rule match. Return if none.
  514. if(!this->IncludeRegexTransform.find(line.c_str()))
  515. {
  516. return;
  517. }
  518. TransformRulesType::const_iterator tri =
  519. this->TransformRules.find(this->IncludeRegexTransform.match(3));
  520. if(tri == this->TransformRules.end())
  521. {
  522. return;
  523. }
  524. // Construct the transformed line.
  525. std::string newline = this->IncludeRegexTransform.match(1);
  526. std::string arg = this->IncludeRegexTransform.match(4);
  527. for(const char* c = tri->second.c_str(); *c; ++c)
  528. {
  529. if(*c == '%')
  530. {
  531. newline += arg;
  532. }
  533. else
  534. {
  535. newline += *c;
  536. }
  537. }
  538. // Return the transformed line.
  539. line = newline;
  540. }