cmGlobalNinjaGenerator.cxx 39 KB

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