cmGlobalNinjaGenerator.cxx 43 KB

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