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