cmGlobalNinjaGenerator.cxx 44 KB

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