cmGlobalNinjaGenerator.cxx 45 KB

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