cmGlobalNinjaGenerator.cxx 44 KB

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