cmGlobalNinjaGenerator.cxx 38 KB

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