cmGlobalNinjaGenerator.cxx 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193
  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 char* targetName,
  486. const char* /*config*/,
  487. bool /*fast*/,
  488. std::vector<std::string> const& makeOptions)
  489. {
  490. makeCommand.push_back(makeProgram);
  491. makeCommand.insert(makeCommand.end(),
  492. makeOptions.begin(), makeOptions.end());
  493. if(targetName && *targetName)
  494. {
  495. if(strcmp(targetName, "clean") == 0)
  496. {
  497. makeCommand.push_back("-t");
  498. makeCommand.push_back("clean");
  499. }
  500. else
  501. {
  502. makeCommand.push_back(targetName);
  503. }
  504. }
  505. }
  506. //----------------------------------------------------------------------------
  507. // Non-virtual public methods.
  508. void cmGlobalNinjaGenerator::AddRule(const std::string& name,
  509. const std::string& command,
  510. const std::string& description,
  511. const std::string& comment,
  512. const std::string& depfile,
  513. const std::string& deptype,
  514. const std::string& rspfile,
  515. const std::string& rspcontent,
  516. bool restat,
  517. bool generator)
  518. {
  519. // Do not add the same rule twice.
  520. if (this->HasRule(name))
  521. {
  522. return;
  523. }
  524. this->Rules.insert(name);
  525. cmGlobalNinjaGenerator::WriteRule(*this->RulesFileStream,
  526. name,
  527. command,
  528. description,
  529. comment,
  530. depfile,
  531. deptype,
  532. rspfile,
  533. rspcontent,
  534. restat,
  535. generator);
  536. this->RuleCmdLength[name] = (int) command.size();
  537. }
  538. bool cmGlobalNinjaGenerator::HasRule(const std::string &name)
  539. {
  540. RulesSetType::const_iterator rule = this->Rules.find(name);
  541. return (rule != this->Rules.end());
  542. }
  543. //----------------------------------------------------------------------------
  544. // Private virtual overrides
  545. std::string cmGlobalNinjaGenerator::GetEditCacheCommand() const
  546. {
  547. // Ninja by design does not run interactive tools in the terminal,
  548. // so our only choice is cmake-gui.
  549. return cmSystemTools::GetCMakeGUICommand();
  550. }
  551. // TODO: Refactor to combine with cmGlobalUnixMakefileGenerator3 impl.
  552. void cmGlobalNinjaGenerator::ComputeTargetObjects(cmGeneratorTarget* gt) const
  553. {
  554. cmTarget* target = gt->Target;
  555. // Compute full path to object file directory for this target.
  556. std::string dir_max;
  557. dir_max += gt->Makefile->GetCurrentOutputDirectory();
  558. dir_max += "/";
  559. dir_max += gt->LocalGenerator->GetTargetDirectory(*target);
  560. dir_max += "/";
  561. gt->ObjectDirectory = dir_max;
  562. // Compute the name of each object file.
  563. for(std::vector<cmSourceFile*>::iterator
  564. si = gt->ObjectSources.begin();
  565. si != gt->ObjectSources.end(); ++si)
  566. {
  567. cmSourceFile* sf = *si;
  568. std::string objectName = gt->LocalGenerator
  569. ->GetObjectFileNameWithoutTarget(*sf, dir_max);
  570. gt->Objects[sf] = objectName;
  571. }
  572. }
  573. //----------------------------------------------------------------------------
  574. // Private methods
  575. void cmGlobalNinjaGenerator::OpenBuildFileStream()
  576. {
  577. // Compute Ninja's build file path.
  578. std::string buildFilePath =
  579. this->GetCMakeInstance()->GetHomeOutputDirectory();
  580. buildFilePath += "/";
  581. buildFilePath += cmGlobalNinjaGenerator::NINJA_BUILD_FILE;
  582. // Get a stream where to generate things.
  583. if (!this->BuildFileStream)
  584. {
  585. this->BuildFileStream = new cmGeneratedFileStream(buildFilePath.c_str());
  586. if (!this->BuildFileStream)
  587. {
  588. // An error message is generated by the constructor if it cannot
  589. // open the file.
  590. return;
  591. }
  592. }
  593. // Write the do not edit header.
  594. this->WriteDisclaimer(*this->BuildFileStream);
  595. // Write a comment about this file.
  596. *this->BuildFileStream
  597. << "# This file contains all the build statements describing the\n"
  598. << "# compilation DAG.\n\n"
  599. ;
  600. }
  601. void cmGlobalNinjaGenerator::CloseBuildFileStream()
  602. {
  603. if (this->BuildFileStream)
  604. {
  605. delete this->BuildFileStream;
  606. this->BuildFileStream = 0;
  607. }
  608. else
  609. {
  610. cmSystemTools::Error("Build file stream was not open.");
  611. }
  612. }
  613. void cmGlobalNinjaGenerator::OpenRulesFileStream()
  614. {
  615. // Compute Ninja's build file path.
  616. std::string rulesFilePath =
  617. this->GetCMakeInstance()->GetHomeOutputDirectory();
  618. rulesFilePath += "/";
  619. rulesFilePath += cmGlobalNinjaGenerator::NINJA_RULES_FILE;
  620. // Get a stream where to generate things.
  621. if (!this->RulesFileStream)
  622. {
  623. this->RulesFileStream = new cmGeneratedFileStream(rulesFilePath.c_str());
  624. if (!this->RulesFileStream)
  625. {
  626. // An error message is generated by the constructor if it cannot
  627. // open the file.
  628. return;
  629. }
  630. }
  631. // Write the do not edit header.
  632. this->WriteDisclaimer(*this->RulesFileStream);
  633. // Write comment about this file.
  634. *this->RulesFileStream
  635. << "# This file contains all the rules used to get the outputs files\n"
  636. << "# built from the input files.\n"
  637. << "# It is included in the main '" << NINJA_BUILD_FILE << "'.\n\n"
  638. ;
  639. }
  640. void cmGlobalNinjaGenerator::CloseRulesFileStream()
  641. {
  642. if (this->RulesFileStream)
  643. {
  644. delete this->RulesFileStream;
  645. this->RulesFileStream = 0;
  646. }
  647. else
  648. {
  649. cmSystemTools::Error("Rules file stream was not open.");
  650. }
  651. }
  652. void cmGlobalNinjaGenerator::AddCXXCompileCommand(
  653. const std::string &commandLine,
  654. const std::string &sourceFile)
  655. {
  656. // Compute Ninja's build file path.
  657. std::string buildFileDir =
  658. this->GetCMakeInstance()->GetHomeOutputDirectory();
  659. if (!this->CompileCommandsStream)
  660. {
  661. std::string buildFilePath = buildFileDir + "/compile_commands.json";
  662. // Get a stream where to generate things.
  663. this->CompileCommandsStream =
  664. new cmGeneratedFileStream(buildFilePath.c_str());
  665. *this->CompileCommandsStream << "[";
  666. } else {
  667. *this->CompileCommandsStream << "," << std::endl;
  668. }
  669. std::string sourceFileName = sourceFile;
  670. if (!cmSystemTools::FileIsFullPath(sourceFileName.c_str()))
  671. {
  672. sourceFileName = cmSystemTools::CollapseFullPath(
  673. sourceFileName.c_str(),
  674. this->GetCMakeInstance()->GetHomeOutputDirectory());
  675. }
  676. *this->CompileCommandsStream << "\n{\n"
  677. << " \"directory\": \""
  678. << cmGlobalGenerator::EscapeJSON(buildFileDir) << "\",\n"
  679. << " \"command\": \""
  680. << cmGlobalGenerator::EscapeJSON(commandLine) << "\",\n"
  681. << " \"file\": \""
  682. << cmGlobalGenerator::EscapeJSON(sourceFileName) << "\"\n"
  683. << "}";
  684. }
  685. void cmGlobalNinjaGenerator::CloseCompileCommandsStream()
  686. {
  687. if (this->CompileCommandsStream)
  688. {
  689. *this->CompileCommandsStream << "\n]";
  690. delete this->CompileCommandsStream;
  691. this->CompileCommandsStream = 0;
  692. }
  693. }
  694. void cmGlobalNinjaGenerator::WriteDisclaimer(std::ostream& os)
  695. {
  696. os
  697. << "# CMAKE generated file: DO NOT EDIT!\n"
  698. << "# Generated by \"" << this->GetName() << "\""
  699. << " Generator, CMake Version "
  700. << cmVersion::GetMajorVersion() << "."
  701. << cmVersion::GetMinorVersion() << "\n\n";
  702. }
  703. void cmGlobalNinjaGenerator::AddDependencyToAll(cmTarget* target)
  704. {
  705. this->AppendTargetOutputs(target, this->AllDependencies);
  706. }
  707. void cmGlobalNinjaGenerator::AddDependencyToAll(const std::string& input)
  708. {
  709. this->AllDependencies.push_back(input);
  710. }
  711. void cmGlobalNinjaGenerator::WriteAssumedSourceDependencies()
  712. {
  713. for (std::map<std::string, std::set<std::string> >::iterator
  714. i = this->AssumedSourceDependencies.begin();
  715. i != this->AssumedSourceDependencies.end(); ++i) {
  716. cmNinjaDeps deps;
  717. std::copy(i->second.begin(), i->second.end(), std::back_inserter(deps));
  718. WriteCustomCommandBuild(/*command=*/"", /*description=*/"",
  719. "Assume dependencies for generated source file.",
  720. cmNinjaDeps(1, i->first), deps);
  721. }
  722. }
  723. void
  724. cmGlobalNinjaGenerator
  725. ::AppendTargetOutputs(cmTarget* target, cmNinjaDeps& outputs)
  726. {
  727. const char* configName =
  728. target->GetMakefile()->GetDefinition("CMAKE_BUILD_TYPE");
  729. cmLocalNinjaGenerator *ng =
  730. static_cast<cmLocalNinjaGenerator *>(this->LocalGenerators[0]);
  731. // for frameworks, we want the real name, not smple name
  732. // frameworks always appear versioned, and the build.ninja
  733. // will always attempt to manage symbolic links instead
  734. // of letting cmOSXBundleGenerator do it.
  735. bool realname = target->IsFrameworkOnApple();
  736. switch (target->GetType()) {
  737. case cmTarget::EXECUTABLE:
  738. case cmTarget::SHARED_LIBRARY:
  739. case cmTarget::STATIC_LIBRARY:
  740. case cmTarget::MODULE_LIBRARY:
  741. outputs.push_back(ng->ConvertToNinjaPath(
  742. target->GetFullPath(configName, false, realname).c_str()));
  743. break;
  744. case cmTarget::OBJECT_LIBRARY:
  745. case cmTarget::UTILITY: {
  746. std::string path = ng->ConvertToNinjaPath(
  747. target->GetMakefile()->GetStartOutputDirectory());
  748. if (path.empty() || path == ".")
  749. outputs.push_back(target->GetName());
  750. else {
  751. path += "/";
  752. path += target->GetName();
  753. outputs.push_back(path);
  754. }
  755. break;
  756. }
  757. case cmTarget::GLOBAL_TARGET:
  758. // Always use the target in HOME instead of an unused duplicate in a
  759. // subdirectory.
  760. outputs.push_back(target->GetName());
  761. break;
  762. default:
  763. return;
  764. }
  765. }
  766. void
  767. cmGlobalNinjaGenerator
  768. ::AppendTargetDepends(cmTarget* target, cmNinjaDeps& outputs)
  769. {
  770. if (target->GetType() == cmTarget::GLOBAL_TARGET) {
  771. // Global targets only depend on other utilities, which may not appear in
  772. // the TargetDepends set (e.g. "all").
  773. std::set<cmStdString> const& utils = target->GetUtilities();
  774. std::copy(utils.begin(), utils.end(), std::back_inserter(outputs));
  775. } else {
  776. cmTargetDependSet const& targetDeps =
  777. this->GetTargetDirectDepends(*target);
  778. for (cmTargetDependSet::const_iterator i = targetDeps.begin();
  779. i != targetDeps.end(); ++i)
  780. {
  781. if ((*i)->GetType() == cmTarget::INTERFACE_LIBRARY)
  782. {
  783. continue;
  784. }
  785. this->AppendTargetOutputs(*i, outputs);
  786. }
  787. }
  788. }
  789. void cmGlobalNinjaGenerator::AddTargetAlias(const std::string& alias,
  790. cmTarget* target) {
  791. cmNinjaDeps outputs;
  792. this->AppendTargetOutputs(target, outputs);
  793. // Mark the target's outputs as ambiguous to ensure that no other target uses
  794. // the output as an alias.
  795. for (cmNinjaDeps::iterator i = outputs.begin(); i != outputs.end(); ++i)
  796. TargetAliases[*i] = 0;
  797. // Insert the alias into the map. If the alias was already present in the
  798. // map and referred to another target, mark it as ambiguous.
  799. std::pair<TargetAliasMap::iterator, bool> newAlias =
  800. TargetAliases.insert(std::make_pair(alias, target));
  801. if (newAlias.second && newAlias.first->second != target)
  802. newAlias.first->second = 0;
  803. }
  804. void cmGlobalNinjaGenerator::WriteTargetAliases(std::ostream& os)
  805. {
  806. cmGlobalNinjaGenerator::WriteDivider(os);
  807. os << "# Target aliases.\n\n";
  808. for (TargetAliasMap::const_iterator i = TargetAliases.begin();
  809. i != TargetAliases.end(); ++i) {
  810. // Don't write ambiguous aliases.
  811. if (!i->second)
  812. continue;
  813. cmNinjaDeps deps;
  814. this->AppendTargetOutputs(i->second, deps);
  815. this->WritePhonyBuild(os,
  816. "",
  817. cmNinjaDeps(1, i->first),
  818. deps);
  819. }
  820. }
  821. void cmGlobalNinjaGenerator::WriteUnknownExplicitDependencies(std::ostream& os)
  822. {
  823. //now write out the unknown explicit dependencies.
  824. //union the configured files, evaluations files and the CombinedBuildOutputs,
  825. //and then difference with CombinedExplicitDependencies to find the explicit
  826. //dependencies that we have no rule for
  827. cmGlobalNinjaGenerator::WriteDivider(os);
  828. os << "# Unknown Build Time Dependencies.\n"
  829. << "# Tell Ninja that they may appear as side effects of build rules\n"
  830. << "# otherwise ordered by order-only dependencies.\n\n";
  831. //get the list of files that cmake itself has generated as a
  832. //product of configuration.
  833. cmLocalNinjaGenerator *ng =
  834. static_cast<cmLocalNinjaGenerator *>(this->LocalGenerators[0]);
  835. std::set<std::string> knownDependencies;
  836. for (std::vector<cmLocalGenerator *>::const_iterator i =
  837. this->LocalGenerators.begin(); i != this->LocalGenerators.end(); ++i)
  838. {
  839. //get the vector of files created by this makefile and convert them
  840. //to ninja paths, which are all relative in respect to the build directory
  841. const std::vector<std::string>& files =
  842. (*i)->GetMakefile()->GetOutputFiles();
  843. typedef std::vector<std::string>::const_iterator vect_it;
  844. for(vect_it j = files.begin(); j != files.end(); ++j)
  845. {
  846. knownDependencies.insert( ng->ConvertToNinjaPath( j->c_str() ) );
  847. }
  848. }
  849. for(std::vector<cmGeneratorExpressionEvaluationFile*>::const_iterator
  850. li = this->EvaluationFiles.begin();
  851. li != this->EvaluationFiles.end();
  852. ++li)
  853. {
  854. //get all the files created by generator expressions and convert them
  855. //to ninja paths
  856. std::vector<std::string> files = (*li)->GetFiles();
  857. typedef std::vector<std::string>::const_iterator vect_it;
  858. for(vect_it j = files.begin(); j != files.end(); ++j)
  859. {
  860. knownDependencies.insert( ng->ConvertToNinjaPath( j->c_str() ) );
  861. }
  862. }
  863. for(TargetAliasMap::const_iterator i= this->TargetAliases.begin();
  864. i != this->TargetAliases.end();
  865. ++i)
  866. {
  867. knownDependencies.insert( ng->ConvertToNinjaPath(i->first.c_str()) );
  868. }
  869. //remove all source files we know will exist.
  870. typedef std::map<std::string, std::set<std::string> >::const_iterator map_it;
  871. for(map_it i = this->AssumedSourceDependencies.begin();
  872. i != this->AssumedSourceDependencies.end();
  873. ++i)
  874. {
  875. knownDependencies.insert( ng->ConvertToNinjaPath(i->first.c_str()) );
  876. }
  877. //insert outputs from all WirteBuild commands
  878. for(std::set<std::string>::iterator i = this->CombinedBuildOutputs.begin();
  879. i != this->CombinedBuildOutputs.end(); ++i)
  880. {
  881. //these paths have already be encoded when added to CombinedBuildOutputs
  882. knownDependencies.insert(*i);
  883. }
  884. //after we have combined the data into knownDependencies we have no need
  885. //to keep this data around
  886. this->CombinedBuildOutputs.clear();
  887. //now we difference with CombinedBuildExplicitDependencies to find
  888. //the list of items we know nothing about.
  889. //We have encoded all the paths in CombinedBuildExplicitDependencies
  890. //and knownDependencies so no matter if unix or windows paths they
  891. //should all match now.
  892. std::vector<std::string> unkownExplicitDepends;
  893. this->CombinedBuildExplicitDependencies.erase("all");
  894. std::set_difference(this->CombinedBuildExplicitDependencies.begin(),
  895. this->CombinedBuildExplicitDependencies.end(),
  896. knownDependencies.begin(),
  897. knownDependencies.end(),
  898. std::back_inserter(unkownExplicitDepends));
  899. std::string const rootBuildDirectory =
  900. this->GetCMakeInstance()->GetHomeOutputDirectory();
  901. for (std::vector<std::string>::const_iterator
  902. i = unkownExplicitDepends.begin();
  903. i != unkownExplicitDepends.end();
  904. ++i)
  905. {
  906. //verify the file is in the build directory
  907. std::string const absDepPath = cmSystemTools::CollapseFullPath(
  908. i->c_str(), rootBuildDirectory.c_str());
  909. bool const inBuildDir = cmSystemTools::IsSubDirectory(absDepPath.c_str(),
  910. rootBuildDirectory.c_str());
  911. if(inBuildDir)
  912. {
  913. cmNinjaDeps deps(1,*i);
  914. this->WritePhonyBuild(os,
  915. "",
  916. deps,
  917. deps);
  918. }
  919. }
  920. }
  921. void cmGlobalNinjaGenerator::WriteBuiltinTargets(std::ostream& os)
  922. {
  923. // Write headers.
  924. cmGlobalNinjaGenerator::WriteDivider(os);
  925. os << "# Built-in targets\n\n";
  926. this->WriteTargetAll(os);
  927. this->WriteTargetRebuildManifest(os);
  928. this->WriteTargetClean(os);
  929. this->WriteTargetHelp(os);
  930. }
  931. void cmGlobalNinjaGenerator::WriteTargetAll(std::ostream& os)
  932. {
  933. cmNinjaDeps outputs;
  934. outputs.push_back("all");
  935. this->WritePhonyBuild(os,
  936. "The main all target.",
  937. outputs,
  938. this->AllDependencies);
  939. cmGlobalNinjaGenerator::WriteDefault(os,
  940. outputs,
  941. "Make the all target the default.");
  942. }
  943. void cmGlobalNinjaGenerator::WriteTargetRebuildManifest(std::ostream& os)
  944. {
  945. cmLocalGenerator *lg = this->LocalGenerators[0];
  946. cmMakefile* mfRoot = lg->GetMakefile();
  947. cmOStringStream cmd;
  948. cmd << lg->ConvertToOutputFormat(
  949. mfRoot->GetRequiredDefinition("CMAKE_COMMAND"),
  950. cmLocalGenerator::SHELL)
  951. << " -H"
  952. << lg->ConvertToOutputFormat(mfRoot->GetHomeDirectory(),
  953. cmLocalGenerator::SHELL)
  954. << " -B"
  955. << lg->ConvertToOutputFormat(mfRoot->GetHomeOutputDirectory(),
  956. cmLocalGenerator::SHELL);
  957. WriteRule(*this->RulesFileStream,
  958. "RERUN_CMAKE",
  959. cmd.str(),
  960. "Re-running CMake...",
  961. "Rule for re-running cmake.",
  962. /*depfile=*/ "",
  963. /*deptype=*/ "",
  964. /*rspfile=*/ "",
  965. /*rspcontent*/ "",
  966. /*restat=*/ false,
  967. /*generator=*/ true);
  968. cmNinjaDeps implicitDeps;
  969. for (std::vector<cmLocalGenerator *>::const_iterator i =
  970. this->LocalGenerators.begin(); i != this->LocalGenerators.end(); ++i) {
  971. const std::vector<std::string>& lf = (*i)->GetMakefile()->GetListFiles();
  972. implicitDeps.insert(implicitDeps.end(), lf.begin(), lf.end());
  973. const std::vector<std::string>& of = (*i)->GetMakefile()->GetOutputFiles();
  974. implicitDeps.insert(implicitDeps.end(), of.begin(), of.end());
  975. }
  976. std::sort(implicitDeps.begin(), implicitDeps.end());
  977. implicitDeps.erase(std::unique(implicitDeps.begin(), implicitDeps.end()),
  978. implicitDeps.end());
  979. implicitDeps.push_back("CMakeCache.txt");
  980. this->WriteBuild(os,
  981. "Re-run CMake if any of its inputs changed.",
  982. "RERUN_CMAKE",
  983. /*outputs=*/ cmNinjaDeps(1, NINJA_BUILD_FILE),
  984. /*explicitDeps=*/ cmNinjaDeps(),
  985. implicitDeps,
  986. /*orderOnlyDeps=*/ cmNinjaDeps(),
  987. /*variables=*/ cmNinjaVars());
  988. this->WritePhonyBuild(os,
  989. "A missing CMake input file is not an error.",
  990. implicitDeps,
  991. cmNinjaDeps());
  992. }
  993. std::string cmGlobalNinjaGenerator::ninjaCmd() const
  994. {
  995. cmLocalGenerator* lgen = this->LocalGenerators[0];
  996. if (lgen) {
  997. return lgen->ConvertToOutputFormat(
  998. lgen->GetMakefile()->GetRequiredDefinition("CMAKE_MAKE_PROGRAM"),
  999. cmLocalGenerator::SHELL);
  1000. }
  1001. return "ninja";
  1002. }
  1003. void cmGlobalNinjaGenerator::WriteTargetClean(std::ostream& os)
  1004. {
  1005. WriteRule(*this->RulesFileStream,
  1006. "CLEAN",
  1007. (ninjaCmd() + " -t clean").c_str(),
  1008. "Cleaning all built files...",
  1009. "Rule for cleaning all built files.",
  1010. /*depfile=*/ "",
  1011. /*deptype=*/ "",
  1012. /*rspfile=*/ "",
  1013. /*rspcontent*/ "",
  1014. /*restat=*/ false,
  1015. /*generator=*/ false);
  1016. WriteBuild(os,
  1017. "Clean all the built files.",
  1018. "CLEAN",
  1019. /*outputs=*/ cmNinjaDeps(1, "clean"),
  1020. /*explicitDeps=*/ cmNinjaDeps(),
  1021. /*implicitDeps=*/ cmNinjaDeps(),
  1022. /*orderOnlyDeps=*/ cmNinjaDeps(),
  1023. /*variables=*/ cmNinjaVars());
  1024. }
  1025. void cmGlobalNinjaGenerator::WriteTargetHelp(std::ostream& os)
  1026. {
  1027. WriteRule(*this->RulesFileStream,
  1028. "HELP",
  1029. (ninjaCmd() + " -t targets").c_str(),
  1030. "All primary targets available:",
  1031. "Rule for printing all primary targets available.",
  1032. /*depfile=*/ "",
  1033. /*deptype=*/ "",
  1034. /*rspfile=*/ "",
  1035. /*rspcontent*/ "",
  1036. /*restat=*/ false,
  1037. /*generator=*/ false);
  1038. WriteBuild(os,
  1039. "Print all primary targets available.",
  1040. "HELP",
  1041. /*outputs=*/ cmNinjaDeps(1, "help"),
  1042. /*explicitDeps=*/ cmNinjaDeps(),
  1043. /*implicitDeps=*/ cmNinjaDeps(),
  1044. /*orderOnlyDeps=*/ cmNinjaDeps(),
  1045. /*variables=*/ cmNinjaVars());
  1046. }