cmGlobalNinjaGenerator.cxx 43 KB

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