cmGlobalNinjaGenerator.cxx 30 KB

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