cmGlobalNinjaGenerator.cxx 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  1. /*============================================================================
  2. CMake - Cross Platform Makefile Generator
  3. Copyright 2011 Peter Collingbourne <[email protected]>
  4. Copyright 2011 Nicolas Despres <[email protected]>
  5. Distributed under the OSI-approved BSD License (the "License");
  6. see accompanying file Copyright.txt for details.
  7. This software is distributed WITHOUT ANY WARRANTY; without even the
  8. implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  9. See the License for more information.
  10. ============================================================================*/
  11. #include "cmGeneratedFileStream.h"
  12. #include "cmGeneratorExpressionEvaluationFile.h"
  13. #include "cmGeneratorTarget.h"
  14. #include "cmGlobalNinjaGenerator.h"
  15. #include "cmLocalNinjaGenerator.h"
  16. #include "cmMakefile.h"
  17. #include "cmVersion.h"
  18. #include <algorithm>
  19. const char* cmGlobalNinjaGenerator::NINJA_BUILD_FILE = "build.ninja";
  20. const char* cmGlobalNinjaGenerator::NINJA_RULES_FILE = "rules.ninja";
  21. const char* cmGlobalNinjaGenerator::INDENT = " ";
  22. void cmGlobalNinjaGenerator::Indent(std::ostream& os, int count)
  23. {
  24. for(int i = 0; i < count; ++i)
  25. os << cmGlobalNinjaGenerator::INDENT;
  26. }
  27. void cmGlobalNinjaGenerator::WriteDivider(std::ostream& os)
  28. {
  29. os
  30. << "# ======================================"
  31. << "=======================================\n";
  32. }
  33. void cmGlobalNinjaGenerator::WriteComment(std::ostream& os,
  34. const std::string& comment)
  35. {
  36. if (comment.empty())
  37. return;
  38. std::string replace = comment;
  39. std::string::size_type lpos = 0;
  40. std::string::size_type rpos;
  41. os << "\n#############################################\n";
  42. while((rpos = replace.find('\n', lpos)) != std::string::npos)
  43. {
  44. os << "# " << replace.substr(lpos, rpos - lpos) << "\n";
  45. lpos = rpos + 1;
  46. }
  47. os << "# " << replace.substr(lpos) << "\n\n";
  48. }
  49. static bool IsIdentChar(char c)
  50. {
  51. return
  52. ('a' <= c && c <= 'z') ||
  53. ('+' <= c && c <= '9') || // +,-./ and numbers
  54. ('A' <= c && c <= 'Z') ||
  55. (c == '_') || (c == '$') || (c == '\\') ||
  56. (c == ' ') || (c == ':');
  57. }
  58. std::string cmGlobalNinjaGenerator::EncodeIdent(const std::string &ident,
  59. std::ostream &vars) {
  60. if (std::find_if(ident.begin(), ident.end(),
  61. std::not1(std::ptr_fun(IsIdentChar))) != ident.end()) {
  62. static unsigned VarNum = 0;
  63. cmOStringStream names;
  64. names << "ident" << VarNum++;
  65. vars << names.str() << " = " << ident << "\n";
  66. return "$" + names.str();
  67. } else {
  68. std::string result = ident;
  69. cmSystemTools::ReplaceString(result, " ", "$ ");
  70. cmSystemTools::ReplaceString(result, ":", "$:");
  71. return result;
  72. }
  73. }
  74. std::string cmGlobalNinjaGenerator::EncodeLiteral(const std::string &lit)
  75. {
  76. std::string result = lit;
  77. cmSystemTools::ReplaceString(result, "$", "$$");
  78. cmSystemTools::ReplaceString(result, "\n", "$\n");
  79. return result;
  80. }
  81. std::string cmGlobalNinjaGenerator::EncodePath(const std::string &path)
  82. {
  83. std::string result = path;
  84. #ifdef _WIN32
  85. if(UsingMinGW)
  86. cmSystemTools::ReplaceString(result, "\\", "/");
  87. else
  88. cmSystemTools::ReplaceString(result, "/", "\\");
  89. #endif
  90. return EncodeLiteral(result);
  91. }
  92. std::string cmGlobalNinjaGenerator::EncodeDepfileSpace(const std::string &path)
  93. {
  94. std::string result = path;
  95. cmSystemTools::ReplaceString(result, " ", "\\ ");
  96. return result;
  97. }
  98. void cmGlobalNinjaGenerator::WriteBuild(std::ostream& os,
  99. const std::string& comment,
  100. const std::string& rule,
  101. const cmNinjaDeps& outputs,
  102. const cmNinjaDeps& explicitDeps,
  103. const cmNinjaDeps& implicitDeps,
  104. const cmNinjaDeps& orderOnlyDeps,
  105. const cmNinjaVars& variables,
  106. const std::string& rspfile,
  107. int cmdLineLimit)
  108. {
  109. // Make sure there is a rule.
  110. if(rule.empty())
  111. {
  112. cmSystemTools::Error("No rule for WriteBuildStatement! called "
  113. "with comment: ",
  114. comment.c_str());
  115. return;
  116. }
  117. // Make sure there is at least one output file.
  118. if(outputs.empty())
  119. {
  120. cmSystemTools::Error("No output files for WriteBuildStatement! called "
  121. "with comment: ",
  122. comment.c_str());
  123. return;
  124. }
  125. cmGlobalNinjaGenerator::WriteComment(os, comment);
  126. cmOStringStream arguments;
  127. // TODO: Better formatting for when there are multiple input/output files.
  128. // Write explicit dependencies.
  129. for(cmNinjaDeps::const_iterator i = explicitDeps.begin();
  130. i != explicitDeps.end();
  131. ++i)
  132. {
  133. arguments << " " << EncodeIdent(EncodePath(*i), os);
  134. //we need to track every dependency that comes in, since we are trying
  135. //to find dependencies that are side effects of build commands
  136. //
  137. this->CombinedBuildExplicitDependencies.insert( EncodePath(*i) );
  138. }
  139. // Write implicit dependencies.
  140. if(!implicitDeps.empty())
  141. {
  142. arguments << " |";
  143. for(cmNinjaDeps::const_iterator i = implicitDeps.begin();
  144. i != implicitDeps.end();
  145. ++i)
  146. arguments << " " << EncodeIdent(EncodePath(*i), os);
  147. }
  148. // Write order-only dependencies.
  149. if(!orderOnlyDeps.empty())
  150. {
  151. arguments << " ||";
  152. for(cmNinjaDeps::const_iterator i = orderOnlyDeps.begin();
  153. i != orderOnlyDeps.end();
  154. ++i)
  155. arguments << " " << EncodeIdent(EncodePath(*i), os);
  156. }
  157. arguments << "\n";
  158. cmOStringStream build;
  159. // Write outputs files.
  160. build << "build";
  161. for(cmNinjaDeps::const_iterator i = outputs.begin();
  162. i != outputs.end(); ++i)
  163. {
  164. build << " " << EncodeIdent(EncodePath(*i), os);
  165. this->CombinedBuildOutputs.insert( EncodePath(*i) );
  166. }
  167. build << ":";
  168. // Write the rule.
  169. build << " " << rule;
  170. // Write the variables bound to this build statement.
  171. cmOStringStream variable_assignments;
  172. for(cmNinjaVars::const_iterator i = variables.begin();
  173. i != variables.end(); ++i)
  174. cmGlobalNinjaGenerator::WriteVariable(variable_assignments,
  175. i->first, i->second, "", 1);
  176. // check if a response file rule should be used
  177. std::string buildstr = build.str();
  178. std::string assignments = variable_assignments.str();
  179. const std::string args = arguments.str();
  180. if (cmdLineLimit > 0
  181. && args.size() + buildstr.size() + assignments.size()
  182. > (size_t) cmdLineLimit) {
  183. buildstr += "_RSP_FILE";
  184. variable_assignments.clear();
  185. cmGlobalNinjaGenerator::WriteVariable(variable_assignments,
  186. "RSP_FILE", rspfile, "", 1);
  187. assignments += variable_assignments.str();
  188. }
  189. os << buildstr << args << assignments;
  190. }
  191. void cmGlobalNinjaGenerator::WritePhonyBuild(std::ostream& os,
  192. const std::string& comment,
  193. const cmNinjaDeps& outputs,
  194. const cmNinjaDeps& explicitDeps,
  195. const cmNinjaDeps& implicitDeps,
  196. const cmNinjaDeps& orderOnlyDeps,
  197. const cmNinjaVars& variables)
  198. {
  199. this->WriteBuild(os,
  200. comment,
  201. "phony",
  202. outputs,
  203. explicitDeps,
  204. implicitDeps,
  205. orderOnlyDeps,
  206. variables);
  207. }
  208. void cmGlobalNinjaGenerator::AddCustomCommandRule()
  209. {
  210. this->AddRule("CUSTOM_COMMAND",
  211. "$COMMAND",
  212. "$DESC",
  213. "Rule for running custom commands.",
  214. /*depfile*/ "",
  215. /*deptype*/ "",
  216. /*rspfile*/ "",
  217. /*rspcontent*/ "",
  218. /*restat*/ true,
  219. /*generator*/ false);
  220. }
  221. void
  222. cmGlobalNinjaGenerator::WriteCustomCommandBuild(const std::string& command,
  223. const std::string& description,
  224. const std::string& comment,
  225. const cmNinjaDeps& outputs,
  226. const cmNinjaDeps& deps,
  227. const cmNinjaDeps& orderOnly)
  228. {
  229. std::string cmd = command;
  230. #ifdef _WIN32
  231. if (cmd.empty())
  232. // TODO Shouldn't an empty command be handled by ninja?
  233. cmd = "cmd.exe /c";
  234. #endif
  235. this->AddCustomCommandRule();
  236. cmNinjaVars vars;
  237. vars["COMMAND"] = cmd;
  238. vars["DESC"] = EncodeLiteral(description);
  239. this->WriteBuild(*this->BuildFileStream,
  240. comment,
  241. "CUSTOM_COMMAND",
  242. outputs,
  243. deps,
  244. cmNinjaDeps(),
  245. orderOnly,
  246. vars);
  247. }
  248. void
  249. cmGlobalNinjaGenerator::AddMacOSXContentRule()
  250. {
  251. cmLocalGenerator *lg = this->LocalGenerators[0];
  252. cmMakefile* mfRoot = lg->GetMakefile();
  253. cmOStringStream cmd;
  254. cmd << lg->ConvertToOutputFormat(
  255. mfRoot->GetRequiredDefinition("CMAKE_COMMAND"),
  256. cmLocalGenerator::SHELL)
  257. << " -E copy $in $out";
  258. this->AddRule("COPY_OSX_CONTENT",
  259. cmd.str(),
  260. "Copying OS X Content $out",
  261. "Rule for copying OS X bundle content file.",
  262. /*depfile*/ "",
  263. /*deptype*/ "",
  264. /*rspfile*/ "",
  265. /*rspcontent*/ "",
  266. /*restat*/ false,
  267. /*generator*/ false);
  268. }
  269. void
  270. cmGlobalNinjaGenerator::WriteMacOSXContentBuild(const std::string& input,
  271. const std::string& output)
  272. {
  273. this->AddMacOSXContentRule();
  274. cmNinjaDeps outputs;
  275. outputs.push_back(output);
  276. cmNinjaDeps deps;
  277. deps.push_back(input);
  278. cmNinjaVars vars;
  279. this->WriteBuild(*this->BuildFileStream,
  280. "",
  281. "COPY_OSX_CONTENT",
  282. outputs,
  283. deps,
  284. cmNinjaDeps(),
  285. cmNinjaDeps(),
  286. cmNinjaVars());
  287. }
  288. void cmGlobalNinjaGenerator::WriteRule(std::ostream& os,
  289. const std::string& name,
  290. const std::string& command,
  291. const std::string& description,
  292. const std::string& comment,
  293. const std::string& depfile,
  294. const std::string& deptype,
  295. const std::string& rspfile,
  296. const std::string& rspcontent,
  297. bool restat,
  298. bool generator)
  299. {
  300. // Make sure the rule has a name.
  301. if(name.empty())
  302. {
  303. cmSystemTools::Error("No name given for WriteRuleStatement! called "
  304. "with comment: ",
  305. comment.c_str());
  306. return;
  307. }
  308. // Make sure a command is given.
  309. if(command.empty())
  310. {
  311. cmSystemTools::Error("No command given for WriteRuleStatement! called "
  312. "with comment: ",
  313. comment.c_str());
  314. return;
  315. }
  316. cmGlobalNinjaGenerator::WriteComment(os, comment);
  317. // Write the rule.
  318. os << "rule " << name << "\n";
  319. // Write the depfile if any.
  320. if(!depfile.empty())
  321. {
  322. cmGlobalNinjaGenerator::Indent(os, 1);
  323. os << "depfile = " << depfile << "\n";
  324. }
  325. // Write the deptype if any.
  326. if (!deptype.empty())
  327. {
  328. cmGlobalNinjaGenerator::Indent(os, 1);
  329. os << "deps = " << deptype << "\n";
  330. }
  331. // Write the command.
  332. cmGlobalNinjaGenerator::Indent(os, 1);
  333. os << "command = " << command << "\n";
  334. // Write the description if any.
  335. if(!description.empty())
  336. {
  337. cmGlobalNinjaGenerator::Indent(os, 1);
  338. os << "description = " << description << "\n";
  339. }
  340. if(!rspfile.empty())
  341. {
  342. if (rspcontent.empty())
  343. {
  344. cmSystemTools::Error("No rspfile_content given!", comment.c_str());
  345. return;
  346. }
  347. cmGlobalNinjaGenerator::Indent(os, 1);
  348. os << "rspfile = " << rspfile << "\n";
  349. cmGlobalNinjaGenerator::Indent(os, 1);
  350. os << "rspfile_content = " << rspcontent << "\n";
  351. }
  352. if(restat)
  353. {
  354. cmGlobalNinjaGenerator::Indent(os, 1);
  355. os << "restat = 1\n";
  356. }
  357. if(generator)
  358. {
  359. cmGlobalNinjaGenerator::Indent(os, 1);
  360. os << "generator = 1\n";
  361. }
  362. os << "\n";
  363. }
  364. void cmGlobalNinjaGenerator::WriteVariable(std::ostream& os,
  365. const std::string& name,
  366. const std::string& value,
  367. const std::string& comment,
  368. int indent)
  369. {
  370. // Make sure we have a name.
  371. if(name.empty())
  372. {
  373. cmSystemTools::Error("No name given for WriteVariable! called "
  374. "with comment: ",
  375. comment.c_str());
  376. return;
  377. }
  378. // Do not add a variable if the value is empty.
  379. std::string val = cmSystemTools::TrimWhitespace(value);
  380. if(val.empty())
  381. {
  382. return;
  383. }
  384. cmGlobalNinjaGenerator::WriteComment(os, comment);
  385. cmGlobalNinjaGenerator::Indent(os, indent);
  386. os << name << " = " << val << "\n";
  387. }
  388. void cmGlobalNinjaGenerator::WriteInclude(std::ostream& os,
  389. const std::string& filename,
  390. const std::string& comment)
  391. {
  392. cmGlobalNinjaGenerator::WriteComment(os, comment);
  393. os << "include " << filename << "\n";
  394. }
  395. void cmGlobalNinjaGenerator::WriteDefault(std::ostream& os,
  396. const cmNinjaDeps& targets,
  397. const std::string& comment)
  398. {
  399. cmGlobalNinjaGenerator::WriteComment(os, comment);
  400. os << "default";
  401. for(cmNinjaDeps::const_iterator i = targets.begin(); i != targets.end(); ++i)
  402. os << " " << *i;
  403. os << "\n";
  404. }
  405. cmGlobalNinjaGenerator::cmGlobalNinjaGenerator()
  406. : cmGlobalGenerator()
  407. , BuildFileStream(0)
  408. , RulesFileStream(0)
  409. , CompileCommandsStream(0)
  410. , Rules()
  411. , AllDependencies()
  412. {
  413. // // Ninja is not ported to non-Unix OS yet.
  414. // this->ForceUnixPaths = true;
  415. this->FindMakeProgramFile = "CMakeNinjaFindMake.cmake";
  416. }
  417. //----------------------------------------------------------------------------
  418. // Virtual public methods.
  419. cmLocalGenerator* cmGlobalNinjaGenerator::CreateLocalGenerator()
  420. {
  421. cmLocalGenerator* lg = new cmLocalNinjaGenerator;
  422. lg->SetGlobalGenerator(this);
  423. return lg;
  424. }
  425. void cmGlobalNinjaGenerator
  426. ::GetDocumentation(cmDocumentationEntry& entry)
  427. {
  428. entry.Name = cmGlobalNinjaGenerator::GetActualName();
  429. entry.Brief = "Generates build.ninja files (experimental).";
  430. }
  431. // Implemented in all cmGlobaleGenerator sub-classes.
  432. // Used in:
  433. // Source/cmLocalGenerator.cxx
  434. // Source/cmake.cxx
  435. void cmGlobalNinjaGenerator::Generate()
  436. {
  437. this->OpenBuildFileStream();
  438. this->OpenRulesFileStream();
  439. this->cmGlobalGenerator::Generate();
  440. this->WriteAssumedSourceDependencies();
  441. this->WriteTargetAliases(*this->BuildFileStream);
  442. this->WriteUnknownExplicitDependencies(*this->BuildFileStream);
  443. this->WriteBuiltinTargets(*this->BuildFileStream);
  444. if (cmSystemTools::GetErrorOccuredFlag()) {
  445. this->RulesFileStream->setstate(std::ios_base::failbit);
  446. this->BuildFileStream->setstate(std::ios_base::failbit);
  447. }
  448. this->CloseCompileCommandsStream();
  449. this->CloseRulesFileStream();
  450. this->CloseBuildFileStream();
  451. }
  452. // Implemented in all cmGlobaleGenerator sub-classes.
  453. // Used in:
  454. // Source/cmMakefile.cxx:
  455. void cmGlobalNinjaGenerator
  456. ::EnableLanguage(std::vector<std::string>const& langs,
  457. cmMakefile* makefile,
  458. bool optional)
  459. {
  460. if (makefile->IsOn("CMAKE_COMPILER_IS_MINGW"))
  461. {
  462. UsingMinGW = true;
  463. this->EnableMinGWLanguage(makefile);
  464. }
  465. if (std::find(langs.begin(), langs.end(), "Fortran") != langs.end())
  466. {
  467. cmSystemTools::Error("The Ninja generator does not support Fortran yet.");
  468. }
  469. this->cmGlobalGenerator::EnableLanguage(langs, makefile, optional);
  470. }
  471. bool cmGlobalNinjaGenerator::UsingMinGW = false;
  472. // Implemented by:
  473. // cmGlobalUnixMakefileGenerator3
  474. // cmGlobalVisualStudio10Generator
  475. // cmGlobalVisualStudio6Generator
  476. // cmGlobalVisualStudio7Generator
  477. // cmGlobalXCodeGenerator
  478. // Called by:
  479. // cmGlobalGenerator::Build()
  480. void cmGlobalNinjaGenerator
  481. ::GenerateBuildCommand(std::vector<std::string>& makeCommand,
  482. const char* makeProgram,
  483. const char* /*projectName*/,
  484. const char* /*projectDir*/,
  485. const char* targetName,
  486. const char* /*config*/,
  487. bool /*fast*/,
  488. std::vector<std::string> const& makeOptions)
  489. {
  490. makeCommand.push_back(
  491. this->SelectMakeProgram(makeProgram)
  492. );
  493. makeCommand.insert(makeCommand.end(),
  494. makeOptions.begin(), makeOptions.end());
  495. if(targetName && *targetName)
  496. {
  497. if(strcmp(targetName, "clean") == 0)
  498. {
  499. makeCommand.push_back("-t");
  500. makeCommand.push_back("clean");
  501. }
  502. else
  503. {
  504. makeCommand.push_back(targetName);
  505. }
  506. }
  507. }
  508. //----------------------------------------------------------------------------
  509. // Non-virtual public methods.
  510. void cmGlobalNinjaGenerator::AddRule(const std::string& name,
  511. const std::string& command,
  512. const std::string& description,
  513. const std::string& comment,
  514. const std::string& depfile,
  515. const std::string& deptype,
  516. const std::string& rspfile,
  517. const std::string& rspcontent,
  518. bool restat,
  519. bool generator)
  520. {
  521. // Do not add the same rule twice.
  522. if (this->HasRule(name))
  523. {
  524. return;
  525. }
  526. this->Rules.insert(name);
  527. cmGlobalNinjaGenerator::WriteRule(*this->RulesFileStream,
  528. name,
  529. command,
  530. description,
  531. comment,
  532. depfile,
  533. deptype,
  534. rspfile,
  535. rspcontent,
  536. restat,
  537. generator);
  538. this->RuleCmdLength[name] = (int) command.size();
  539. }
  540. bool cmGlobalNinjaGenerator::HasRule(const std::string &name)
  541. {
  542. RulesSetType::const_iterator rule = this->Rules.find(name);
  543. return (rule != this->Rules.end());
  544. }
  545. //----------------------------------------------------------------------------
  546. // Private virtual overrides
  547. std::string cmGlobalNinjaGenerator::GetEditCacheCommand() const
  548. {
  549. // Ninja by design does not run interactive tools in the terminal,
  550. // so our only choice is cmake-gui.
  551. return cmSystemTools::GetCMakeGUICommand();
  552. }
  553. // TODO: Refactor to combine with cmGlobalUnixMakefileGenerator3 impl.
  554. void cmGlobalNinjaGenerator::ComputeTargetObjects(cmGeneratorTarget* gt) const
  555. {
  556. cmTarget* target = gt->Target;
  557. // Compute full path to object file directory for this target.
  558. std::string dir_max;
  559. dir_max += gt->Makefile->GetCurrentOutputDirectory();
  560. dir_max += "/";
  561. dir_max += gt->LocalGenerator->GetTargetDirectory(*target);
  562. dir_max += "/";
  563. gt->ObjectDirectory = dir_max;
  564. // Compute the name of each object file.
  565. for(std::vector<cmSourceFile*>::iterator
  566. si = gt->ObjectSources.begin();
  567. si != gt->ObjectSources.end(); ++si)
  568. {
  569. cmSourceFile* sf = *si;
  570. std::string objectName = gt->LocalGenerator
  571. ->GetObjectFileNameWithoutTarget(*sf, dir_max);
  572. gt->Objects[sf] = objectName;
  573. }
  574. }
  575. //----------------------------------------------------------------------------
  576. // Private methods
  577. void cmGlobalNinjaGenerator::OpenBuildFileStream()
  578. {
  579. // Compute Ninja's build file path.
  580. std::string buildFilePath =
  581. this->GetCMakeInstance()->GetHomeOutputDirectory();
  582. buildFilePath += "/";
  583. buildFilePath += cmGlobalNinjaGenerator::NINJA_BUILD_FILE;
  584. // Get a stream where to generate things.
  585. if (!this->BuildFileStream)
  586. {
  587. this->BuildFileStream = new cmGeneratedFileStream(buildFilePath.c_str());
  588. if (!this->BuildFileStream)
  589. {
  590. // An error message is generated by the constructor if it cannot
  591. // open the file.
  592. return;
  593. }
  594. }
  595. // Write the do not edit header.
  596. this->WriteDisclaimer(*this->BuildFileStream);
  597. // Write a comment about this file.
  598. *this->BuildFileStream
  599. << "# This file contains all the build statements describing the\n"
  600. << "# compilation DAG.\n\n"
  601. ;
  602. }
  603. void cmGlobalNinjaGenerator::CloseBuildFileStream()
  604. {
  605. if (this->BuildFileStream)
  606. {
  607. delete this->BuildFileStream;
  608. this->BuildFileStream = 0;
  609. }
  610. else
  611. {
  612. cmSystemTools::Error("Build file stream was not open.");
  613. }
  614. }
  615. void cmGlobalNinjaGenerator::OpenRulesFileStream()
  616. {
  617. // Compute Ninja's build file path.
  618. std::string rulesFilePath =
  619. this->GetCMakeInstance()->GetHomeOutputDirectory();
  620. rulesFilePath += "/";
  621. rulesFilePath += cmGlobalNinjaGenerator::NINJA_RULES_FILE;
  622. // Get a stream where to generate things.
  623. if (!this->RulesFileStream)
  624. {
  625. this->RulesFileStream = new cmGeneratedFileStream(rulesFilePath.c_str());
  626. if (!this->RulesFileStream)
  627. {
  628. // An error message is generated by the constructor if it cannot
  629. // open the file.
  630. return;
  631. }
  632. }
  633. // Write the do not edit header.
  634. this->WriteDisclaimer(*this->RulesFileStream);
  635. // Write comment about this file.
  636. *this->RulesFileStream
  637. << "# This file contains all the rules used to get the outputs files\n"
  638. << "# built from the input files.\n"
  639. << "# It is included in the main '" << NINJA_BUILD_FILE << "'.\n\n"
  640. ;
  641. }
  642. void cmGlobalNinjaGenerator::CloseRulesFileStream()
  643. {
  644. if (this->RulesFileStream)
  645. {
  646. delete this->RulesFileStream;
  647. this->RulesFileStream = 0;
  648. }
  649. else
  650. {
  651. cmSystemTools::Error("Rules file stream was not open.");
  652. }
  653. }
  654. void cmGlobalNinjaGenerator::AddCXXCompileCommand(
  655. const std::string &commandLine,
  656. const std::string &sourceFile)
  657. {
  658. // Compute Ninja's build file path.
  659. std::string buildFileDir =
  660. this->GetCMakeInstance()->GetHomeOutputDirectory();
  661. if (!this->CompileCommandsStream)
  662. {
  663. std::string buildFilePath = buildFileDir + "/compile_commands.json";
  664. // Get a stream where to generate things.
  665. this->CompileCommandsStream =
  666. new cmGeneratedFileStream(buildFilePath.c_str());
  667. *this->CompileCommandsStream << "[";
  668. } else {
  669. *this->CompileCommandsStream << "," << std::endl;
  670. }
  671. std::string sourceFileName = sourceFile;
  672. if (!cmSystemTools::FileIsFullPath(sourceFileName.c_str()))
  673. {
  674. sourceFileName = cmSystemTools::CollapseFullPath(
  675. sourceFileName.c_str(),
  676. this->GetCMakeInstance()->GetHomeOutputDirectory());
  677. }
  678. *this->CompileCommandsStream << "\n{\n"
  679. << " \"directory\": \""
  680. << cmGlobalGenerator::EscapeJSON(buildFileDir) << "\",\n"
  681. << " \"command\": \""
  682. << cmGlobalGenerator::EscapeJSON(commandLine) << "\",\n"
  683. << " \"file\": \""
  684. << cmGlobalGenerator::EscapeJSON(sourceFileName) << "\"\n"
  685. << "}";
  686. }
  687. void cmGlobalNinjaGenerator::CloseCompileCommandsStream()
  688. {
  689. if (this->CompileCommandsStream)
  690. {
  691. *this->CompileCommandsStream << "\n]";
  692. delete this->CompileCommandsStream;
  693. this->CompileCommandsStream = 0;
  694. }
  695. }
  696. void cmGlobalNinjaGenerator::WriteDisclaimer(std::ostream& os)
  697. {
  698. os
  699. << "# CMAKE generated file: DO NOT EDIT!\n"
  700. << "# Generated by \"" << this->GetName() << "\""
  701. << " Generator, CMake Version "
  702. << cmVersion::GetMajorVersion() << "."
  703. << cmVersion::GetMinorVersion() << "\n\n";
  704. }
  705. void cmGlobalNinjaGenerator::AddDependencyToAll(cmTarget* target)
  706. {
  707. this->AppendTargetOutputs(target, this->AllDependencies);
  708. }
  709. void cmGlobalNinjaGenerator::AddDependencyToAll(const std::string& input)
  710. {
  711. this->AllDependencies.push_back(input);
  712. }
  713. void cmGlobalNinjaGenerator::WriteAssumedSourceDependencies()
  714. {
  715. for (std::map<std::string, std::set<std::string> >::iterator
  716. i = this->AssumedSourceDependencies.begin();
  717. i != this->AssumedSourceDependencies.end(); ++i) {
  718. cmNinjaDeps deps;
  719. std::copy(i->second.begin(), i->second.end(), std::back_inserter(deps));
  720. WriteCustomCommandBuild(/*command=*/"", /*description=*/"",
  721. "Assume dependencies for generated source file.",
  722. cmNinjaDeps(1, i->first), deps);
  723. }
  724. }
  725. void
  726. cmGlobalNinjaGenerator
  727. ::AppendTargetOutputs(cmTarget* target, cmNinjaDeps& outputs)
  728. {
  729. const char* configName =
  730. target->GetMakefile()->GetDefinition("CMAKE_BUILD_TYPE");
  731. cmLocalNinjaGenerator *ng =
  732. static_cast<cmLocalNinjaGenerator *>(this->LocalGenerators[0]);
  733. // for frameworks, we want the real name, not smple name
  734. // frameworks always appear versioned, and the build.ninja
  735. // will always attempt to manage symbolic links instead
  736. // of letting cmOSXBundleGenerator do it.
  737. bool realname = target->IsFrameworkOnApple();
  738. switch (target->GetType()) {
  739. case cmTarget::EXECUTABLE:
  740. case cmTarget::SHARED_LIBRARY:
  741. case cmTarget::STATIC_LIBRARY:
  742. case cmTarget::MODULE_LIBRARY:
  743. outputs.push_back(ng->ConvertToNinjaPath(
  744. target->GetFullPath(configName, false, realname).c_str()));
  745. break;
  746. case cmTarget::OBJECT_LIBRARY:
  747. case cmTarget::UTILITY: {
  748. std::string path = ng->ConvertToNinjaPath(
  749. target->GetMakefile()->GetStartOutputDirectory());
  750. if (path.empty() || path == ".")
  751. outputs.push_back(target->GetName());
  752. else {
  753. path += "/";
  754. path += target->GetName();
  755. outputs.push_back(path);
  756. }
  757. break;
  758. }
  759. case cmTarget::GLOBAL_TARGET:
  760. // Always use the target in HOME instead of an unused duplicate in a
  761. // subdirectory.
  762. outputs.push_back(target->GetName());
  763. break;
  764. default:
  765. return;
  766. }
  767. }
  768. void
  769. cmGlobalNinjaGenerator
  770. ::AppendTargetDepends(cmTarget* target, cmNinjaDeps& outputs)
  771. {
  772. if (target->GetType() == cmTarget::GLOBAL_TARGET) {
  773. // Global targets only depend on other utilities, which may not appear in
  774. // the TargetDepends set (e.g. "all").
  775. std::set<cmStdString> const& utils = target->GetUtilities();
  776. std::copy(utils.begin(), utils.end(), std::back_inserter(outputs));
  777. } else {
  778. cmTargetDependSet const& targetDeps =
  779. this->GetTargetDirectDepends(*target);
  780. for (cmTargetDependSet::const_iterator i = targetDeps.begin();
  781. i != targetDeps.end(); ++i)
  782. {
  783. if ((*i)->GetType() == cmTarget::INTERFACE_LIBRARY)
  784. {
  785. continue;
  786. }
  787. this->AppendTargetOutputs(*i, outputs);
  788. }
  789. }
  790. }
  791. void cmGlobalNinjaGenerator::AddTargetAlias(const std::string& alias,
  792. cmTarget* target) {
  793. cmNinjaDeps outputs;
  794. this->AppendTargetOutputs(target, outputs);
  795. // Mark the target's outputs as ambiguous to ensure that no other target uses
  796. // the output as an alias.
  797. for (cmNinjaDeps::iterator i = outputs.begin(); i != outputs.end(); ++i)
  798. TargetAliases[*i] = 0;
  799. // Insert the alias into the map. If the alias was already present in the
  800. // map and referred to another target, mark it as ambiguous.
  801. std::pair<TargetAliasMap::iterator, bool> newAlias =
  802. TargetAliases.insert(std::make_pair(alias, target));
  803. if (newAlias.second && newAlias.first->second != target)
  804. newAlias.first->second = 0;
  805. }
  806. void cmGlobalNinjaGenerator::WriteTargetAliases(std::ostream& os)
  807. {
  808. cmGlobalNinjaGenerator::WriteDivider(os);
  809. os << "# Target aliases.\n\n";
  810. for (TargetAliasMap::const_iterator i = TargetAliases.begin();
  811. i != TargetAliases.end(); ++i) {
  812. // Don't write ambiguous aliases.
  813. if (!i->second)
  814. continue;
  815. cmNinjaDeps deps;
  816. this->AppendTargetOutputs(i->second, deps);
  817. this->WritePhonyBuild(os,
  818. "",
  819. cmNinjaDeps(1, i->first),
  820. deps);
  821. }
  822. }
  823. void cmGlobalNinjaGenerator::WriteUnknownExplicitDependencies(std::ostream& os)
  824. {
  825. //now write out the unknown explicit dependencies.
  826. //union the configured files, evaluations files and the CombinedBuildOutputs,
  827. //and then difference with CombinedExplicitDependencies to find the explicit
  828. //dependencies that we have no rule for
  829. cmGlobalNinjaGenerator::WriteDivider(os);
  830. os << "# Unknown Build Time Dependencies.\n"
  831. << "# Tell Ninja that they may appear as side effects of build rules\n"
  832. << "# otherwise ordered by order-only dependencies.\n\n";
  833. //get the list of files that cmake itself has generated as a
  834. //product of configuration.
  835. cmLocalNinjaGenerator *ng =
  836. static_cast<cmLocalNinjaGenerator *>(this->LocalGenerators[0]);
  837. std::set<std::string> knownDependencies;
  838. for (std::vector<cmLocalGenerator *>::const_iterator i =
  839. this->LocalGenerators.begin(); i != this->LocalGenerators.end(); ++i)
  840. {
  841. //get the vector of files created by this makefile and convert them
  842. //to ninja paths, which are all relative in respect to the build directory
  843. const std::vector<std::string>& files =
  844. (*i)->GetMakefile()->GetOutputFiles();
  845. typedef std::vector<std::string>::const_iterator vect_it;
  846. for(vect_it j = files.begin(); j != files.end(); ++j)
  847. {
  848. knownDependencies.insert( ng->ConvertToNinjaPath( j->c_str() ) );
  849. }
  850. }
  851. for(std::vector<cmGeneratorExpressionEvaluationFile*>::const_iterator
  852. li = this->EvaluationFiles.begin();
  853. li != this->EvaluationFiles.end();
  854. ++li)
  855. {
  856. //get all the files created by generator expressions and convert them
  857. //to ninja paths
  858. std::vector<std::string> files = (*li)->GetFiles();
  859. typedef std::vector<std::string>::const_iterator vect_it;
  860. for(vect_it j = files.begin(); j != files.end(); ++j)
  861. {
  862. knownDependencies.insert( ng->ConvertToNinjaPath( j->c_str() ) );
  863. }
  864. }
  865. for(TargetAliasMap::const_iterator i= this->TargetAliases.begin();
  866. i != this->TargetAliases.end();
  867. ++i)
  868. {
  869. knownDependencies.insert( ng->ConvertToNinjaPath(i->first.c_str()) );
  870. }
  871. //remove all source files we know will exist.
  872. typedef std::map<std::string, std::set<std::string> >::const_iterator map_it;
  873. for(map_it i = this->AssumedSourceDependencies.begin();
  874. i != this->AssumedSourceDependencies.end();
  875. ++i)
  876. {
  877. knownDependencies.insert( ng->ConvertToNinjaPath(i->first.c_str()) );
  878. }
  879. //insert outputs from all WirteBuild commands
  880. for(std::set<std::string>::iterator i = this->CombinedBuildOutputs.begin();
  881. i != this->CombinedBuildOutputs.end(); ++i)
  882. {
  883. //these paths have already be encoded when added to CombinedBuildOutputs
  884. knownDependencies.insert(*i);
  885. }
  886. //after we have combined the data into knownDependencies we have no need
  887. //to keep this data around
  888. this->CombinedBuildOutputs.clear();
  889. //now we difference with CombinedBuildExplicitDependencies to find
  890. //the list of items we know nothing about.
  891. //We have encoded all the paths in CombinedBuildExplicitDependencies
  892. //and knownDependencies so no matter if unix or windows paths they
  893. //should all match now.
  894. std::vector<std::string> unkownExplicitDepends;
  895. this->CombinedBuildExplicitDependencies.erase("all");
  896. std::set_difference(this->CombinedBuildExplicitDependencies.begin(),
  897. this->CombinedBuildExplicitDependencies.end(),
  898. knownDependencies.begin(),
  899. knownDependencies.end(),
  900. std::back_inserter(unkownExplicitDepends));
  901. std::string const rootBuildDirectory =
  902. this->GetCMakeInstance()->GetHomeOutputDirectory();
  903. for (std::vector<std::string>::const_iterator
  904. i = unkownExplicitDepends.begin();
  905. i != unkownExplicitDepends.end();
  906. ++i)
  907. {
  908. //verify the file is in the build directory
  909. std::string const absDepPath = cmSystemTools::CollapseFullPath(
  910. i->c_str(), rootBuildDirectory.c_str());
  911. bool const inBuildDir = cmSystemTools::IsSubDirectory(absDepPath.c_str(),
  912. rootBuildDirectory.c_str());
  913. if(inBuildDir)
  914. {
  915. cmNinjaDeps deps(1,*i);
  916. this->WritePhonyBuild(os,
  917. "",
  918. deps,
  919. deps);
  920. }
  921. }
  922. }
  923. void cmGlobalNinjaGenerator::WriteBuiltinTargets(std::ostream& os)
  924. {
  925. // Write headers.
  926. cmGlobalNinjaGenerator::WriteDivider(os);
  927. os << "# Built-in targets\n\n";
  928. this->WriteTargetAll(os);
  929. this->WriteTargetRebuildManifest(os);
  930. this->WriteTargetClean(os);
  931. this->WriteTargetHelp(os);
  932. }
  933. void cmGlobalNinjaGenerator::WriteTargetAll(std::ostream& os)
  934. {
  935. cmNinjaDeps outputs;
  936. outputs.push_back("all");
  937. this->WritePhonyBuild(os,
  938. "The main all target.",
  939. outputs,
  940. this->AllDependencies);
  941. cmGlobalNinjaGenerator::WriteDefault(os,
  942. outputs,
  943. "Make the all target the default.");
  944. }
  945. void cmGlobalNinjaGenerator::WriteTargetRebuildManifest(std::ostream& os)
  946. {
  947. cmLocalGenerator *lg = this->LocalGenerators[0];
  948. cmMakefile* mfRoot = lg->GetMakefile();
  949. cmOStringStream cmd;
  950. cmd << lg->ConvertToOutputFormat(
  951. mfRoot->GetRequiredDefinition("CMAKE_COMMAND"),
  952. cmLocalGenerator::SHELL)
  953. << " -H"
  954. << lg->ConvertToOutputFormat(mfRoot->GetHomeDirectory(),
  955. cmLocalGenerator::SHELL)
  956. << " -B"
  957. << lg->ConvertToOutputFormat(mfRoot->GetHomeOutputDirectory(),
  958. cmLocalGenerator::SHELL);
  959. WriteRule(*this->RulesFileStream,
  960. "RERUN_CMAKE",
  961. cmd.str(),
  962. "Re-running CMake...",
  963. "Rule for re-running cmake.",
  964. /*depfile=*/ "",
  965. /*deptype=*/ "",
  966. /*rspfile=*/ "",
  967. /*rspcontent*/ "",
  968. /*restat=*/ false,
  969. /*generator=*/ true);
  970. cmNinjaDeps implicitDeps;
  971. for (std::vector<cmLocalGenerator *>::const_iterator i =
  972. this->LocalGenerators.begin(); i != this->LocalGenerators.end(); ++i) {
  973. const std::vector<std::string>& lf = (*i)->GetMakefile()->GetListFiles();
  974. implicitDeps.insert(implicitDeps.end(), lf.begin(), lf.end());
  975. const std::vector<std::string>& of = (*i)->GetMakefile()->GetOutputFiles();
  976. implicitDeps.insert(implicitDeps.end(), of.begin(), of.end());
  977. }
  978. std::sort(implicitDeps.begin(), implicitDeps.end());
  979. implicitDeps.erase(std::unique(implicitDeps.begin(), implicitDeps.end()),
  980. implicitDeps.end());
  981. implicitDeps.push_back("CMakeCache.txt");
  982. this->WriteBuild(os,
  983. "Re-run CMake if any of its inputs changed.",
  984. "RERUN_CMAKE",
  985. /*outputs=*/ cmNinjaDeps(1, NINJA_BUILD_FILE),
  986. /*explicitDeps=*/ cmNinjaDeps(),
  987. implicitDeps,
  988. /*orderOnlyDeps=*/ cmNinjaDeps(),
  989. /*variables=*/ cmNinjaVars());
  990. this->WritePhonyBuild(os,
  991. "A missing CMake input file is not an error.",
  992. implicitDeps,
  993. cmNinjaDeps());
  994. }
  995. std::string cmGlobalNinjaGenerator::ninjaCmd() const
  996. {
  997. cmLocalGenerator* lgen = this->LocalGenerators[0];
  998. if (lgen) {
  999. return lgen->ConvertToOutputFormat(
  1000. lgen->GetMakefile()->GetRequiredDefinition("CMAKE_MAKE_PROGRAM"),
  1001. cmLocalGenerator::SHELL);
  1002. }
  1003. return "ninja";
  1004. }
  1005. void cmGlobalNinjaGenerator::WriteTargetClean(std::ostream& os)
  1006. {
  1007. WriteRule(*this->RulesFileStream,
  1008. "CLEAN",
  1009. (ninjaCmd() + " -t clean").c_str(),
  1010. "Cleaning all built files...",
  1011. "Rule for cleaning all built files.",
  1012. /*depfile=*/ "",
  1013. /*deptype=*/ "",
  1014. /*rspfile=*/ "",
  1015. /*rspcontent*/ "",
  1016. /*restat=*/ false,
  1017. /*generator=*/ false);
  1018. WriteBuild(os,
  1019. "Clean all the built files.",
  1020. "CLEAN",
  1021. /*outputs=*/ cmNinjaDeps(1, "clean"),
  1022. /*explicitDeps=*/ cmNinjaDeps(),
  1023. /*implicitDeps=*/ cmNinjaDeps(),
  1024. /*orderOnlyDeps=*/ cmNinjaDeps(),
  1025. /*variables=*/ cmNinjaVars());
  1026. }
  1027. void cmGlobalNinjaGenerator::WriteTargetHelp(std::ostream& os)
  1028. {
  1029. WriteRule(*this->RulesFileStream,
  1030. "HELP",
  1031. (ninjaCmd() + " -t targets").c_str(),
  1032. "All primary targets available:",
  1033. "Rule for printing all primary targets available.",
  1034. /*depfile=*/ "",
  1035. /*deptype=*/ "",
  1036. /*rspfile=*/ "",
  1037. /*rspcontent*/ "",
  1038. /*restat=*/ false,
  1039. /*generator=*/ false);
  1040. WriteBuild(os,
  1041. "Print all primary targets available.",
  1042. "HELP",
  1043. /*outputs=*/ cmNinjaDeps(1, "help"),
  1044. /*explicitDeps=*/ cmNinjaDeps(),
  1045. /*implicitDeps=*/ cmNinjaDeps(),
  1046. /*orderOnlyDeps=*/ cmNinjaDeps(),
  1047. /*variables=*/ cmNinjaVars());
  1048. }