cmGlobalNinjaGenerator.cxx 38 KB

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