cmGlobalNinjaGenerator.cxx 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  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 "cmLocalNinjaGenerator.h"
  13. #include "cmMakefile.h"
  14. #include "cmGeneratedFileStream.h"
  15. #include "cmGeneratorTarget.h"
  16. #include "cmVersion.h"
  17. #include <algorithm>
  18. const char* cmGlobalNinjaGenerator::NINJA_BUILD_FILE = "build.ninja";
  19. const char* cmGlobalNinjaGenerator::NINJA_RULES_FILE = "rules.ninja";
  20. const char* cmGlobalNinjaGenerator::INDENT = " ";
  21. void cmGlobalNinjaGenerator::Indent(std::ostream& os, int count)
  22. {
  23. for(int i = 0; i < count; ++i)
  24. os << cmGlobalNinjaGenerator::INDENT;
  25. }
  26. void cmGlobalNinjaGenerator::WriteDivider(std::ostream& os)
  27. {
  28. os
  29. << "# ======================================"
  30. << "=======================================\n";
  31. }
  32. void cmGlobalNinjaGenerator::WriteComment(std::ostream& os,
  33. const std::string& comment)
  34. {
  35. if (comment.empty())
  36. return;
  37. std::string replace = comment;
  38. std::string::size_type lpos = 0;
  39. std::string::size_type rpos;
  40. os << "\n#############################################\n";
  41. while((rpos = replace.find('\n', lpos)) != std::string::npos)
  42. {
  43. os << "# " << replace.substr(lpos, rpos - lpos) << "\n";
  44. lpos = rpos + 1;
  45. }
  46. os << "# " << replace.substr(lpos) << "\n\n";
  47. }
  48. static bool IsIdentChar(char c)
  49. {
  50. return
  51. ('a' <= c && c <= 'z') ||
  52. ('+' <= c && c <= '9') || // +,-./ and numbers
  53. ('A' <= c && c <= 'Z') ||
  54. (c == '_') || (c == '$') || (c == '\\') ||
  55. (c == ' ') || (c == ':');
  56. }
  57. std::string cmGlobalNinjaGenerator::EncodeIdent(const std::string &ident,
  58. std::ostream &vars) {
  59. if (std::find_if(ident.begin(), ident.end(),
  60. std::not1(std::ptr_fun(IsIdentChar))) != ident.end()) {
  61. static unsigned VarNum = 0;
  62. cmOStringStream names;
  63. names << "ident" << VarNum++;
  64. vars << names.str() << " = " << ident << "\n";
  65. return "$" + names.str();
  66. } else {
  67. std::string result = ident;
  68. cmSystemTools::ReplaceString(result, " ", "$ ");
  69. cmSystemTools::ReplaceString(result, ":", "$:");
  70. return result;
  71. }
  72. }
  73. std::string cmGlobalNinjaGenerator::EncodeLiteral(const std::string &lit)
  74. {
  75. std::string result = lit;
  76. cmSystemTools::ReplaceString(result, "$", "$$");
  77. cmSystemTools::ReplaceString(result, "\n", "$\n");
  78. return result;
  79. }
  80. std::string cmGlobalNinjaGenerator::EncodePath(const std::string &path)
  81. {
  82. std::string result = path;
  83. #ifdef _WIN32
  84. if(UsingMinGW)
  85. cmSystemTools::ReplaceString(result, "\\", "/");
  86. else
  87. cmSystemTools::ReplaceString(result, "/", "\\");
  88. #endif
  89. return EncodeLiteral(result);
  90. }
  91. void cmGlobalNinjaGenerator::WriteBuild(std::ostream& os,
  92. const std::string& comment,
  93. const std::string& rule,
  94. const cmNinjaDeps& outputs,
  95. const cmNinjaDeps& explicitDeps,
  96. const cmNinjaDeps& implicitDeps,
  97. const cmNinjaDeps& orderOnlyDeps,
  98. const cmNinjaVars& variables,
  99. const std::string& rspfile,
  100. int cmdLineLimit)
  101. {
  102. // Make sure there is a rule.
  103. if(rule.empty())
  104. {
  105. cmSystemTools::Error("No rule for WriteBuildStatement! called "
  106. "with comment: ",
  107. comment.c_str());
  108. return;
  109. }
  110. // Make sure there is at least one output file.
  111. if(outputs.empty())
  112. {
  113. cmSystemTools::Error("No output files for WriteBuildStatement! called "
  114. "with comment: ",
  115. comment.c_str());
  116. return;
  117. }
  118. cmGlobalNinjaGenerator::WriteComment(os, comment);
  119. cmOStringStream arguments;
  120. // TODO: Better formatting for when there are multiple input/output files.
  121. // Write explicit dependencies.
  122. for(cmNinjaDeps::const_iterator i = explicitDeps.begin();
  123. i != explicitDeps.end();
  124. ++i)
  125. arguments << " " << EncodeIdent(EncodePath(*i), os);
  126. // Write implicit dependencies.
  127. if(!implicitDeps.empty())
  128. {
  129. arguments << " |";
  130. for(cmNinjaDeps::const_iterator i = implicitDeps.begin();
  131. i != implicitDeps.end();
  132. ++i)
  133. arguments << " " << EncodeIdent(EncodePath(*i), os);
  134. }
  135. // Write order-only dependencies.
  136. if(!orderOnlyDeps.empty())
  137. {
  138. arguments << " ||";
  139. for(cmNinjaDeps::const_iterator i = orderOnlyDeps.begin();
  140. i != orderOnlyDeps.end();
  141. ++i)
  142. arguments << " " << EncodeIdent(EncodePath(*i), os);
  143. }
  144. arguments << "\n";
  145. cmOStringStream build;
  146. // Write outputs files.
  147. build << "build";
  148. for(cmNinjaDeps::const_iterator i = outputs.begin();
  149. i != outputs.end(); ++i)
  150. build << " " << EncodeIdent(EncodePath(*i), os);
  151. build << ":";
  152. // Write the rule.
  153. build << " " << rule;
  154. // Write the variables bound to this build statement.
  155. cmOStringStream variable_assignments;
  156. for(cmNinjaVars::const_iterator i = variables.begin();
  157. i != variables.end(); ++i)
  158. cmGlobalNinjaGenerator::WriteVariable(variable_assignments,
  159. i->first, i->second, "", 1);
  160. // check if a response file rule should be used
  161. std::string buildstr = build.str();
  162. std::string assignments = variable_assignments.str();
  163. const std::string args = arguments.str();
  164. if (cmdLineLimit > 0
  165. && args.size() + buildstr.size() + assignments.size()
  166. > (size_t) cmdLineLimit) {
  167. buildstr += "_RSP_FILE";
  168. variable_assignments.clear();
  169. cmGlobalNinjaGenerator::WriteVariable(variable_assignments,
  170. "RSP_FILE", rspfile, "", 1);
  171. assignments += variable_assignments.str();
  172. }
  173. os << buildstr << args << assignments;
  174. }
  175. void cmGlobalNinjaGenerator::WritePhonyBuild(std::ostream& os,
  176. const std::string& comment,
  177. const cmNinjaDeps& outputs,
  178. const cmNinjaDeps& explicitDeps,
  179. const cmNinjaDeps& implicitDeps,
  180. const cmNinjaDeps& orderOnlyDeps,
  181. const cmNinjaVars& variables)
  182. {
  183. cmGlobalNinjaGenerator::WriteBuild(os,
  184. comment,
  185. "phony",
  186. outputs,
  187. explicitDeps,
  188. implicitDeps,
  189. orderOnlyDeps,
  190. variables);
  191. }
  192. void cmGlobalNinjaGenerator::AddCustomCommandRule()
  193. {
  194. this->AddRule("CUSTOM_COMMAND",
  195. "$COMMAND",
  196. "$DESC",
  197. "Rule for running custom commands.",
  198. /*depfile*/ "",
  199. /*rspfile*/ "",
  200. /*rspcontent*/ "",
  201. /*restat*/ true);
  202. }
  203. void
  204. cmGlobalNinjaGenerator::WriteCustomCommandBuild(const std::string& command,
  205. const std::string& description,
  206. const std::string& comment,
  207. const cmNinjaDeps& outputs,
  208. const cmNinjaDeps& deps,
  209. const cmNinjaDeps& orderOnlyDeps)
  210. {
  211. std::string cmd = command;
  212. #ifdef _WIN32
  213. if (cmd.empty())
  214. // TODO Shouldn't an empty command be handled by ninja?
  215. cmd = "cmd.exe /c";
  216. #endif
  217. this->AddCustomCommandRule();
  218. cmNinjaVars vars;
  219. vars["COMMAND"] = cmd;
  220. vars["DESC"] = EncodeLiteral(description);
  221. cmGlobalNinjaGenerator::WriteBuild(*this->BuildFileStream,
  222. comment,
  223. "CUSTOM_COMMAND",
  224. outputs,
  225. deps,
  226. cmNinjaDeps(),
  227. orderOnlyDeps,
  228. vars);
  229. }
  230. void
  231. cmGlobalNinjaGenerator::AddMacOSXContentRule()
  232. {
  233. cmLocalGenerator *lg = this->LocalGenerators[0];
  234. cmMakefile* mfRoot = lg->GetMakefile();
  235. cmOStringStream cmd;
  236. cmd << lg->ConvertToOutputFormat(
  237. mfRoot->GetRequiredDefinition("CMAKE_COMMAND"),
  238. cmLocalGenerator::SHELL)
  239. << " -E copy $in $out";
  240. this->AddRule("COPY_OSX_CONTENT",
  241. cmd.str(),
  242. "Copying OS X Content $out",
  243. "Rule for copying OS X bundle content file."
  244. /*depfile*/ "",
  245. /*rspfile*/ "");
  246. }
  247. void
  248. cmGlobalNinjaGenerator::WriteMacOSXContentBuild(const std::string& input,
  249. const std::string& output)
  250. {
  251. this->AddMacOSXContentRule();
  252. cmNinjaDeps outputs;
  253. outputs.push_back(output);
  254. cmNinjaDeps deps;
  255. deps.push_back(input);
  256. cmNinjaVars vars;
  257. cmGlobalNinjaGenerator::WriteBuild(*this->BuildFileStream,
  258. "",
  259. "COPY_OSX_CONTENT",
  260. outputs,
  261. deps,
  262. cmNinjaDeps(),
  263. cmNinjaDeps(),
  264. cmNinjaVars());
  265. }
  266. void cmGlobalNinjaGenerator::WriteRule(std::ostream& os,
  267. const std::string& name,
  268. const std::string& command,
  269. const std::string& description,
  270. const std::string& comment,
  271. const std::string& depfile,
  272. const std::string& rspfile,
  273. const std::string& rspcontent,
  274. bool restat,
  275. bool generator)
  276. {
  277. // Make sure the rule has a name.
  278. if(name.empty())
  279. {
  280. cmSystemTools::Error("No name given for WriteRuleStatement! called "
  281. "with comment: ",
  282. comment.c_str());
  283. return;
  284. }
  285. // Make sure a command is given.
  286. if(command.empty())
  287. {
  288. cmSystemTools::Error("No command given for WriteRuleStatement! called "
  289. "with comment: ",
  290. comment.c_str());
  291. return;
  292. }
  293. cmGlobalNinjaGenerator::WriteComment(os, comment);
  294. // Write the rule.
  295. os << "rule " << name << "\n";
  296. // Write the depfile if any.
  297. if(!depfile.empty())
  298. {
  299. cmGlobalNinjaGenerator::Indent(os, 1);
  300. os << "depfile = " << depfile << "\n";
  301. }
  302. // Write the command.
  303. cmGlobalNinjaGenerator::Indent(os, 1);
  304. os << "command = " << command << "\n";
  305. // Write the description if any.
  306. if(!description.empty())
  307. {
  308. cmGlobalNinjaGenerator::Indent(os, 1);
  309. os << "description = " << description << "\n";
  310. }
  311. if(!rspfile.empty())
  312. {
  313. if (rspcontent.empty())
  314. {
  315. cmSystemTools::Error("No rspfile_content given!", comment.c_str());
  316. return;
  317. }
  318. cmGlobalNinjaGenerator::Indent(os, 1);
  319. os << "rspfile = " << rspfile << "\n";
  320. cmGlobalNinjaGenerator::Indent(os, 1);
  321. os << "rspfile_content = " << rspcontent << "\n";
  322. }
  323. if(restat)
  324. {
  325. cmGlobalNinjaGenerator::Indent(os, 1);
  326. os << "restat = 1\n";
  327. }
  328. if(generator)
  329. {
  330. cmGlobalNinjaGenerator::Indent(os, 1);
  331. os << "generator = 1\n";
  332. }
  333. os << "\n";
  334. }
  335. void cmGlobalNinjaGenerator::WriteVariable(std::ostream& os,
  336. const std::string& name,
  337. const std::string& value,
  338. const std::string& comment,
  339. int indent)
  340. {
  341. // Make sure we have a name.
  342. if(name.empty())
  343. {
  344. cmSystemTools::Error("No name given for WriteVariable! called "
  345. "with comment: ",
  346. comment.c_str());
  347. return;
  348. }
  349. // Do not add a variable if the value is empty.
  350. std::string val = cmSystemTools::TrimWhitespace(value);
  351. if(val.empty())
  352. {
  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(); ++i)
  373. os << " " << *i;
  374. os << "\n";
  375. }
  376. cmGlobalNinjaGenerator::cmGlobalNinjaGenerator()
  377. : cmGlobalGenerator()
  378. , BuildFileStream(0)
  379. , RulesFileStream(0)
  380. , CompileCommandsStream(0)
  381. , Rules()
  382. , AllDependencies()
  383. {
  384. // // Ninja is not ported to non-Unix OS yet.
  385. // this->ForceUnixPaths = true;
  386. this->FindMakeProgramFile = "CMakeNinjaFindMake.cmake";
  387. }
  388. //----------------------------------------------------------------------------
  389. // Virtual public methods.
  390. cmLocalGenerator* cmGlobalNinjaGenerator::CreateLocalGenerator()
  391. {
  392. cmLocalGenerator* lg = new cmLocalNinjaGenerator;
  393. lg->SetGlobalGenerator(this);
  394. return lg;
  395. }
  396. void cmGlobalNinjaGenerator
  397. ::GetDocumentation(cmDocumentationEntry& entry)
  398. {
  399. entry.Name = cmGlobalNinjaGenerator::GetActualName();
  400. entry.Brief = "Generates build.ninja files (experimental).";
  401. entry.Full =
  402. "A build.ninja file is generated into the build tree. Recent "
  403. "versions of the ninja program can build the project through the "
  404. "\"all\" target. An \"install\" target is also provided.";
  405. }
  406. // Implemented in all cmGlobaleGenerator sub-classes.
  407. // Used in:
  408. // Source/cmLocalGenerator.cxx
  409. // Source/cmake.cxx
  410. void cmGlobalNinjaGenerator::Generate()
  411. {
  412. this->OpenBuildFileStream();
  413. this->OpenRulesFileStream();
  414. this->cmGlobalGenerator::Generate();
  415. this->WriteAssumedSourceDependencies();
  416. this->WriteTargetAliases(*this->BuildFileStream);
  417. this->WriteBuiltinTargets(*this->BuildFileStream);
  418. if (cmSystemTools::GetErrorOccuredFlag()) {
  419. this->RulesFileStream->setstate(std::ios_base::failbit);
  420. this->BuildFileStream->setstate(std::ios_base::failbit);
  421. }
  422. this->CloseCompileCommandsStream();
  423. this->CloseRulesFileStream();
  424. this->CloseBuildFileStream();
  425. }
  426. // Implemented in all cmGlobaleGenerator sub-classes.
  427. // Used in:
  428. // Source/cmMakefile.cxx:
  429. void cmGlobalNinjaGenerator
  430. ::EnableLanguage(std::vector<std::string>const& langs,
  431. cmMakefile* makefile,
  432. bool optional)
  433. {
  434. if (makefile->IsOn("CMAKE_COMPILER_IS_MINGW"))
  435. {
  436. UsingMinGW = true;
  437. this->EnableMinGWLanguage(makefile);
  438. }
  439. if (std::find(langs.begin(), langs.end(), "Fortran") != langs.end())
  440. {
  441. cmSystemTools::Error("The Ninja generator does not support Fortran yet.");
  442. }
  443. this->cmGlobalGenerator::EnableLanguage(langs, makefile, optional);
  444. }
  445. bool cmGlobalNinjaGenerator::UsingMinGW = false;
  446. // Implemented by:
  447. // cmGlobalUnixMakefileGenerator3
  448. // cmGlobalVisualStudio10Generator
  449. // cmGlobalVisualStudio6Generator
  450. // cmGlobalVisualStudio7Generator
  451. // cmGlobalXCodeGenerator
  452. // Called by:
  453. // cmGlobalGenerator::Build()
  454. std::string cmGlobalNinjaGenerator
  455. ::GenerateBuildCommand(const char* makeProgram,
  456. const char* projectName,
  457. const char* additionalOptions,
  458. const char* targetName,
  459. const char* config,
  460. bool ignoreErrors,
  461. bool fast)
  462. {
  463. // Project name and config are not used yet.
  464. (void)projectName;
  465. (void)config;
  466. // Ninja does not have -i equivalent option yet.
  467. (void)ignoreErrors;
  468. // We do not handle fast build yet.
  469. (void)fast;
  470. std::string makeCommand =
  471. cmSystemTools::ConvertToUnixOutputPath(makeProgram);
  472. if(additionalOptions)
  473. {
  474. makeCommand += " ";
  475. makeCommand += additionalOptions;
  476. }
  477. if(targetName)
  478. {
  479. if(strcmp(targetName, "clean") == 0)
  480. {
  481. makeCommand += " -t clean";
  482. }
  483. else
  484. {
  485. makeCommand += " ";
  486. makeCommand += targetName;
  487. }
  488. }
  489. return makeCommand;
  490. }
  491. //----------------------------------------------------------------------------
  492. // Non-virtual public methods.
  493. void cmGlobalNinjaGenerator::AddRule(const std::string& name,
  494. const std::string& command,
  495. const std::string& description,
  496. const std::string& comment,
  497. const std::string& depfile,
  498. const std::string& rspfile,
  499. const std::string& rspcontent,
  500. bool restat,
  501. bool generator)
  502. {
  503. // Do not add the same rule twice.
  504. if (this->HasRule(name))
  505. {
  506. return;
  507. }
  508. this->Rules.insert(name);
  509. cmGlobalNinjaGenerator::WriteRule(*this->RulesFileStream,
  510. name,
  511. command,
  512. description,
  513. comment,
  514. depfile,
  515. rspfile,
  516. rspcontent,
  517. restat,
  518. generator);
  519. this->RuleCmdLength[name] = (int) command.size();
  520. }
  521. bool cmGlobalNinjaGenerator::HasRule(const std::string &name)
  522. {
  523. RulesSetType::const_iterator rule = this->Rules.find(name);
  524. return (rule != this->Rules.end());
  525. }
  526. //----------------------------------------------------------------------------
  527. // Private virtual overrides
  528. // TODO: Refactor to combine with cmGlobalUnixMakefileGenerator3 impl.
  529. void cmGlobalNinjaGenerator::ComputeTargetObjects(cmGeneratorTarget* gt) const
  530. {
  531. cmTarget* target = gt->Target;
  532. // Compute full path to object file directory for this target.
  533. std::string dir_max;
  534. dir_max += gt->Makefile->GetCurrentOutputDirectory();
  535. dir_max += "/";
  536. dir_max += gt->LocalGenerator->GetTargetDirectory(*target);
  537. dir_max += "/";
  538. gt->ObjectDirectory = dir_max;
  539. // Compute the name of each object file.
  540. for(std::vector<cmSourceFile*>::iterator
  541. si = gt->ObjectSources.begin();
  542. si != gt->ObjectSources.end(); ++si)
  543. {
  544. cmSourceFile* sf = *si;
  545. std::string objectName = gt->LocalGenerator
  546. ->GetObjectFileNameWithoutTarget(*sf, dir_max);
  547. gt->Objects[sf] = objectName;
  548. }
  549. }
  550. //----------------------------------------------------------------------------
  551. // Private methods
  552. void cmGlobalNinjaGenerator::OpenBuildFileStream()
  553. {
  554. // Compute Ninja's build file path.
  555. std::string buildFilePath =
  556. this->GetCMakeInstance()->GetHomeOutputDirectory();
  557. buildFilePath += "/";
  558. buildFilePath += cmGlobalNinjaGenerator::NINJA_BUILD_FILE;
  559. // Get a stream where to generate things.
  560. if (!this->BuildFileStream)
  561. {
  562. this->BuildFileStream = new cmGeneratedFileStream(buildFilePath.c_str());
  563. if (!this->BuildFileStream)
  564. {
  565. // An error message is generated by the constructor if it cannot
  566. // open the file.
  567. return;
  568. }
  569. }
  570. // Write the do not edit header.
  571. this->WriteDisclaimer(*this->BuildFileStream);
  572. // Write a comment about this file.
  573. *this->BuildFileStream
  574. << "# This file contains all the build statements describing the\n"
  575. << "# compilation DAG.\n\n"
  576. ;
  577. }
  578. void cmGlobalNinjaGenerator::CloseBuildFileStream()
  579. {
  580. if (this->BuildFileStream)
  581. {
  582. delete this->BuildFileStream;
  583. this->BuildFileStream = 0;
  584. }
  585. else
  586. {
  587. cmSystemTools::Error("Build file stream was not open.");
  588. }
  589. }
  590. void cmGlobalNinjaGenerator::OpenRulesFileStream()
  591. {
  592. // Compute Ninja's build file path.
  593. std::string rulesFilePath =
  594. this->GetCMakeInstance()->GetHomeOutputDirectory();
  595. rulesFilePath += "/";
  596. rulesFilePath += cmGlobalNinjaGenerator::NINJA_RULES_FILE;
  597. // Get a stream where to generate things.
  598. if (!this->RulesFileStream)
  599. {
  600. this->RulesFileStream = new cmGeneratedFileStream(rulesFilePath.c_str());
  601. if (!this->RulesFileStream)
  602. {
  603. // An error message is generated by the constructor if it cannot
  604. // open the file.
  605. return;
  606. }
  607. }
  608. // Write the do not edit header.
  609. this->WriteDisclaimer(*this->RulesFileStream);
  610. // Write comment about this file.
  611. *this->RulesFileStream
  612. << "# This file contains all the rules used to get the outputs files\n"
  613. << "# built from the input files.\n"
  614. << "# It is included in the main '" << NINJA_BUILD_FILE << "'.\n\n"
  615. ;
  616. }
  617. void cmGlobalNinjaGenerator::CloseRulesFileStream()
  618. {
  619. if (this->RulesFileStream)
  620. {
  621. delete this->RulesFileStream;
  622. this->RulesFileStream = 0;
  623. }
  624. else
  625. {
  626. cmSystemTools::Error("Rules file stream was not open.");
  627. }
  628. }
  629. void cmGlobalNinjaGenerator::AddCXXCompileCommand(
  630. const std::string &commandLine,
  631. const std::string &sourceFile)
  632. {
  633. // Compute Ninja's build file path.
  634. std::string buildFileDir =
  635. this->GetCMakeInstance()->GetHomeOutputDirectory();
  636. if (!this->CompileCommandsStream)
  637. {
  638. std::string buildFilePath = buildFileDir + "/compile_commands.json";
  639. // Get a stream where to generate things.
  640. this->CompileCommandsStream =
  641. new cmGeneratedFileStream(buildFilePath.c_str());
  642. *this->CompileCommandsStream << "[";
  643. } else {
  644. *this->CompileCommandsStream << "," << std::endl;
  645. }
  646. std::string sourceFileName = sourceFile;
  647. if (!cmSystemTools::FileIsFullPath(sourceFileName.c_str()))
  648. {
  649. sourceFileName = cmSystemTools::CollapseFullPath(
  650. sourceFileName.c_str(),
  651. this->GetCMakeInstance()->GetHomeOutputDirectory());
  652. }
  653. *this->CompileCommandsStream << "\n{\n"
  654. << " \"directory\": \""
  655. << cmGlobalGenerator::EscapeJSON(buildFileDir) << "\",\n"
  656. << " \"command\": \""
  657. << cmGlobalGenerator::EscapeJSON(commandLine) << "\",\n"
  658. << " \"file\": \""
  659. << cmGlobalGenerator::EscapeJSON(sourceFileName) << "\"\n"
  660. << "}";
  661. }
  662. void cmGlobalNinjaGenerator::CloseCompileCommandsStream()
  663. {
  664. if (this->CompileCommandsStream)
  665. {
  666. *this->CompileCommandsStream << "\n]";
  667. delete this->CompileCommandsStream;
  668. this->CompileCommandsStream = 0;
  669. }
  670. }
  671. void cmGlobalNinjaGenerator::WriteDisclaimer(std::ostream& os)
  672. {
  673. os
  674. << "# CMAKE generated file: DO NOT EDIT!\n"
  675. << "# Generated by \"" << this->GetName() << "\""
  676. << " Generator, CMake Version "
  677. << cmVersion::GetMajorVersion() << "."
  678. << cmVersion::GetMinorVersion() << "\n\n";
  679. }
  680. void cmGlobalNinjaGenerator::AddDependencyToAll(cmTarget* target)
  681. {
  682. this->AppendTargetOutputs(target, this->AllDependencies);
  683. }
  684. void cmGlobalNinjaGenerator::AddDependencyToAll(const std::string& input)
  685. {
  686. this->AllDependencies.push_back(input);
  687. }
  688. void cmGlobalNinjaGenerator::WriteAssumedSourceDependencies()
  689. {
  690. for (std::map<std::string, std::set<std::string> >::iterator
  691. i = this->AssumedSourceDependencies.begin();
  692. i != this->AssumedSourceDependencies.end(); ++i) {
  693. cmNinjaDeps deps;
  694. std::copy(i->second.begin(), i->second.end(), std::back_inserter(deps));
  695. WriteCustomCommandBuild(/*command=*/"", /*description=*/"",
  696. "Assume dependencies for generated source file.",
  697. cmNinjaDeps(1, i->first), deps);
  698. }
  699. }
  700. void
  701. cmGlobalNinjaGenerator
  702. ::AppendTargetOutputs(cmTarget* target, cmNinjaDeps& outputs)
  703. {
  704. const char* configName =
  705. target->GetMakefile()->GetDefinition("CMAKE_BUILD_TYPE");
  706. cmLocalNinjaGenerator *ng =
  707. static_cast<cmLocalNinjaGenerator *>(this->LocalGenerators[0]);
  708. switch (target->GetType()) {
  709. case cmTarget::EXECUTABLE:
  710. case cmTarget::SHARED_LIBRARY:
  711. case cmTarget::STATIC_LIBRARY:
  712. case cmTarget::MODULE_LIBRARY:
  713. outputs.push_back(ng->ConvertToNinjaPath(
  714. target->GetFullPath(configName).c_str()));
  715. break;
  716. case cmTarget::OBJECT_LIBRARY:
  717. case cmTarget::UTILITY: {
  718. std::string path = ng->ConvertToNinjaPath(
  719. target->GetMakefile()->GetStartOutputDirectory());
  720. if (path.empty() || path == ".")
  721. outputs.push_back(target->GetName());
  722. else {
  723. path += "/";
  724. path += target->GetName();
  725. outputs.push_back(path);
  726. }
  727. break;
  728. }
  729. case cmTarget::GLOBAL_TARGET:
  730. // Always use the target in HOME instead of an unused duplicate in a
  731. // subdirectory.
  732. outputs.push_back(target->GetName());
  733. break;
  734. default:
  735. return;
  736. }
  737. }
  738. void
  739. cmGlobalNinjaGenerator
  740. ::AppendTargetDepends(cmTarget* target, cmNinjaDeps& outputs)
  741. {
  742. if (target->GetType() == cmTarget::GLOBAL_TARGET) {
  743. // Global targets only depend on other utilities, which may not appear in
  744. // the TargetDepends set (e.g. "all").
  745. std::set<cmStdString> const& utils = target->GetUtilities();
  746. std::copy(utils.begin(), utils.end(), std::back_inserter(outputs));
  747. } else {
  748. cmTargetDependSet const& targetDeps =
  749. this->GetTargetDirectDepends(*target);
  750. for (cmTargetDependSet::const_iterator i = targetDeps.begin();
  751. i != targetDeps.end(); ++i) {
  752. this->AppendTargetOutputs(*i, outputs);
  753. }
  754. }
  755. }
  756. void cmGlobalNinjaGenerator::AddTargetAlias(const std::string& alias,
  757. cmTarget* target) {
  758. cmNinjaDeps outputs;
  759. this->AppendTargetOutputs(target, outputs);
  760. // Mark the target's outputs as ambiguous to ensure that no other target uses
  761. // the output as an alias.
  762. for (cmNinjaDeps::iterator i = outputs.begin(); i != outputs.end(); ++i)
  763. TargetAliases[*i] = 0;
  764. // Insert the alias into the map. If the alias was already present in the
  765. // map and referred to another target, mark it as ambiguous.
  766. std::pair<TargetAliasMap::iterator, bool> newAlias =
  767. TargetAliases.insert(std::make_pair(alias, target));
  768. if (newAlias.second && newAlias.first->second != target)
  769. newAlias.first->second = 0;
  770. }
  771. void cmGlobalNinjaGenerator::WriteTargetAliases(std::ostream& os)
  772. {
  773. cmGlobalNinjaGenerator::WriteDivider(os);
  774. os << "# Target aliases.\n\n";
  775. for (TargetAliasMap::iterator i = TargetAliases.begin();
  776. i != TargetAliases.end(); ++i) {
  777. // Don't write ambiguous aliases.
  778. if (!i->second)
  779. continue;
  780. cmNinjaDeps deps;
  781. this->AppendTargetOutputs(i->second, deps);
  782. cmGlobalNinjaGenerator::WritePhonyBuild(os,
  783. "",
  784. cmNinjaDeps(1, i->first),
  785. deps);
  786. }
  787. }
  788. void cmGlobalNinjaGenerator::WriteBuiltinTargets(std::ostream& os)
  789. {
  790. // Write headers.
  791. cmGlobalNinjaGenerator::WriteDivider(os);
  792. os << "# Built-in targets\n\n";
  793. this->WriteTargetAll(os);
  794. this->WriteTargetRebuildManifest(os);
  795. this->WriteTargetClean(os);
  796. this->WriteTargetHelp(os);
  797. }
  798. void cmGlobalNinjaGenerator::WriteTargetAll(std::ostream& os)
  799. {
  800. cmNinjaDeps outputs;
  801. outputs.push_back("all");
  802. cmGlobalNinjaGenerator::WritePhonyBuild(os,
  803. "The main all target.",
  804. outputs,
  805. this->AllDependencies);
  806. cmGlobalNinjaGenerator::WriteDefault(os,
  807. outputs,
  808. "Make the all target the default.");
  809. }
  810. void cmGlobalNinjaGenerator::WriteTargetRebuildManifest(std::ostream& os)
  811. {
  812. cmLocalGenerator *lg = this->LocalGenerators[0];
  813. cmMakefile* mfRoot = lg->GetMakefile();
  814. cmOStringStream cmd;
  815. cmd << lg->ConvertToOutputFormat(
  816. mfRoot->GetRequiredDefinition("CMAKE_COMMAND"),
  817. cmLocalGenerator::SHELL)
  818. << " -H"
  819. << lg->ConvertToOutputFormat(mfRoot->GetHomeDirectory(),
  820. cmLocalGenerator::SHELL)
  821. << " -B"
  822. << lg->ConvertToOutputFormat(mfRoot->GetHomeOutputDirectory(),
  823. cmLocalGenerator::SHELL);
  824. WriteRule(*this->RulesFileStream,
  825. "RERUN_CMAKE",
  826. cmd.str(),
  827. "Re-running CMake...",
  828. "Rule for re-running cmake.",
  829. /*depfile=*/ "",
  830. /*rspfile=*/ "",
  831. /*rspcontent*/ "",
  832. /*restat=*/ false,
  833. /*generator=*/ true);
  834. cmNinjaDeps implicitDeps;
  835. for (std::vector<cmLocalGenerator *>::const_iterator i =
  836. this->LocalGenerators.begin(); i != this->LocalGenerators.end(); ++i) {
  837. const std::vector<std::string>& lf = (*i)->GetMakefile()->GetListFiles();
  838. implicitDeps.insert(implicitDeps.end(), lf.begin(), lf.end());
  839. }
  840. std::sort(implicitDeps.begin(), implicitDeps.end());
  841. implicitDeps.erase(std::unique(implicitDeps.begin(), implicitDeps.end()),
  842. implicitDeps.end());
  843. implicitDeps.push_back("CMakeCache.txt");
  844. WriteBuild(os,
  845. "Re-run CMake if any of its inputs changed.",
  846. "RERUN_CMAKE",
  847. /*outputs=*/ cmNinjaDeps(1, NINJA_BUILD_FILE),
  848. /*explicitDeps=*/ cmNinjaDeps(),
  849. implicitDeps,
  850. /*orderOnlyDeps=*/ cmNinjaDeps(),
  851. /*variables=*/ cmNinjaVars());
  852. WritePhonyBuild(os,
  853. "A missing CMake input file is not an error.",
  854. implicitDeps,
  855. cmNinjaDeps());
  856. }
  857. std::string cmGlobalNinjaGenerator::ninjaCmd() const
  858. {
  859. cmLocalGenerator* lgen = this->LocalGenerators[0];
  860. if (lgen) {
  861. return lgen->ConvertToOutputFormat(
  862. lgen->GetMakefile()->GetRequiredDefinition("CMAKE_MAKE_PROGRAM"),
  863. cmLocalGenerator::SHELL);
  864. }
  865. return "ninja";
  866. }
  867. void cmGlobalNinjaGenerator::WriteTargetClean(std::ostream& os)
  868. {
  869. WriteRule(*this->RulesFileStream,
  870. "CLEAN",
  871. (ninjaCmd() + " -t clean").c_str(),
  872. "Cleaning all built files...",
  873. "Rule for cleaning all built files.",
  874. /*depfile=*/ "",
  875. /*rspfile=*/ "",
  876. /*rspcontent*/ "",
  877. /*restat=*/ false,
  878. /*generator=*/ false);
  879. WriteBuild(os,
  880. "Clean all the built files.",
  881. "CLEAN",
  882. /*outputs=*/ cmNinjaDeps(1, "clean"),
  883. /*explicitDeps=*/ cmNinjaDeps(),
  884. /*implicitDeps=*/ cmNinjaDeps(),
  885. /*orderOnlyDeps=*/ cmNinjaDeps(),
  886. /*variables=*/ cmNinjaVars());
  887. }
  888. void cmGlobalNinjaGenerator::WriteTargetHelp(std::ostream& os)
  889. {
  890. WriteRule(*this->RulesFileStream,
  891. "HELP",
  892. (ninjaCmd() + " -t targets").c_str(),
  893. "All primary targets available:",
  894. "Rule for printing all primary targets available.",
  895. /*depfile=*/ "",
  896. /*rspfile=*/ "",
  897. /*rspcontent*/ "",
  898. /*restat=*/ false,
  899. /*generator=*/ false);
  900. WriteBuild(os,
  901. "Print all primary targets available.",
  902. "HELP",
  903. /*outputs=*/ cmNinjaDeps(1, "help"),
  904. /*explicitDeps=*/ cmNinjaDeps(),
  905. /*implicitDeps=*/ cmNinjaDeps(),
  906. /*orderOnlyDeps=*/ cmNinjaDeps(),
  907. /*variables=*/ cmNinjaVars());
  908. }