cmGlobalNinjaGenerator.cxx 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmGlobalNinjaGenerator.h"
  4. #include "cm_jsoncpp_reader.h"
  5. #include "cm_jsoncpp_value.h"
  6. #include "cm_jsoncpp_writer.h"
  7. #include "cmsys/FStream.hxx"
  8. #include <algorithm>
  9. #include <ctype.h>
  10. #include <iterator>
  11. #include <memory> // IWYU pragma: keep
  12. #include <sstream>
  13. #include <stdio.h>
  14. #include "cmAlgorithms.h"
  15. #include "cmDocumentationEntry.h"
  16. #include "cmFortranParser.h"
  17. #include "cmGeneratedFileStream.h"
  18. #include "cmGeneratorExpressionEvaluationFile.h"
  19. #include "cmGeneratorTarget.h"
  20. #include "cmLocalGenerator.h"
  21. #include "cmLocalNinjaGenerator.h"
  22. #include "cmMakefile.h"
  23. #include "cmNinjaLinkLineComputer.h"
  24. #include "cmOutputConverter.h"
  25. #include "cmState.h"
  26. #include "cmStateDirectory.h"
  27. #include "cmStateSnapshot.h"
  28. #include "cmStateTypes.h"
  29. #include "cmSystemTools.h"
  30. #include "cmTarget.h"
  31. #include "cmTargetDepend.h"
  32. #include "cmVersion.h"
  33. #include "cmake.h"
  34. class cmLinkLineComputer;
  35. const char* cmGlobalNinjaGenerator::NINJA_BUILD_FILE = "build.ninja";
  36. const char* cmGlobalNinjaGenerator::NINJA_RULES_FILE = "rules.ninja";
  37. const char* cmGlobalNinjaGenerator::INDENT = " ";
  38. #ifdef _WIN32
  39. std::string const cmGlobalNinjaGenerator::SHELL_NOOP = "cd .";
  40. #else
  41. std::string const cmGlobalNinjaGenerator::SHELL_NOOP = ":";
  42. #endif
  43. void cmGlobalNinjaGenerator::Indent(std::ostream& os, int count)
  44. {
  45. for (int i = 0; i < count; ++i) {
  46. os << cmGlobalNinjaGenerator::INDENT;
  47. }
  48. }
  49. void cmGlobalNinjaGenerator::WriteDivider(std::ostream& os)
  50. {
  51. os << "# ======================================"
  52. "=======================================\n";
  53. }
  54. void cmGlobalNinjaGenerator::WriteComment(std::ostream& os,
  55. const std::string& comment)
  56. {
  57. if (comment.empty()) {
  58. return;
  59. }
  60. std::string::size_type lpos = 0;
  61. std::string::size_type rpos;
  62. os << "\n#############################################\n";
  63. while ((rpos = comment.find('\n', lpos)) != std::string::npos) {
  64. os << "# " << comment.substr(lpos, rpos - lpos) << "\n";
  65. lpos = rpos + 1;
  66. }
  67. os << "# " << comment.substr(lpos) << "\n\n";
  68. }
  69. cmLinkLineComputer* cmGlobalNinjaGenerator::CreateLinkLineComputer(
  70. cmOutputConverter* outputConverter,
  71. cmStateDirectory const& /* stateDir */) const
  72. {
  73. return new cmNinjaLinkLineComputer(
  74. outputConverter,
  75. this->LocalGenerators[0]->GetStateSnapshot().GetDirectory(), this);
  76. }
  77. std::string cmGlobalNinjaGenerator::EncodeRuleName(std::string const& name)
  78. {
  79. // Ninja rule names must match "[a-zA-Z0-9_.-]+". Use ".xx" to encode
  80. // "." and all invalid characters as hexadecimal.
  81. std::string encoded;
  82. for (char i : name) {
  83. if (isalnum(i) || i == '_' || i == '-') {
  84. encoded += i;
  85. } else {
  86. char buf[16];
  87. sprintf(buf, ".%02x", static_cast<unsigned int>(i));
  88. encoded += buf;
  89. }
  90. }
  91. return encoded;
  92. }
  93. static bool IsIdentChar(char c)
  94. {
  95. return ('a' <= c && c <= 'z') ||
  96. ('+' <= c && c <= '9') || // +,-./ and numbers
  97. ('A' <= c && c <= 'Z') || (c == '_') || (c == '$') || (c == '\\') ||
  98. (c == ' ') || (c == ':');
  99. }
  100. std::string cmGlobalNinjaGenerator::EncodeIdent(const std::string& ident,
  101. std::ostream& vars)
  102. {
  103. if (std::find_if(ident.begin(), ident.end(),
  104. [](char c) { return !IsIdentChar(c); }) != ident.end()) {
  105. static unsigned VarNum = 0;
  106. std::ostringstream names;
  107. names << "ident" << VarNum++;
  108. vars << names.str() << " = " << ident << "\n";
  109. return "$" + names.str();
  110. }
  111. std::string result = ident;
  112. cmSystemTools::ReplaceString(result, " ", "$ ");
  113. cmSystemTools::ReplaceString(result, ":", "$:");
  114. return result;
  115. }
  116. std::string cmGlobalNinjaGenerator::EncodeLiteral(const std::string& lit)
  117. {
  118. std::string result = lit;
  119. cmSystemTools::ReplaceString(result, "$", "$$");
  120. cmSystemTools::ReplaceString(result, "\n", "$\n");
  121. return result;
  122. }
  123. std::string cmGlobalNinjaGenerator::EncodePath(const std::string& path)
  124. {
  125. std::string result = path; // NOLINT(clang-tidy)
  126. #ifdef _WIN32
  127. if (this->IsGCCOnWindows())
  128. std::replace(result.begin(), result.end(), '\\', '/');
  129. else
  130. std::replace(result.begin(), result.end(), '/', '\\');
  131. #endif
  132. return EncodeLiteral(result);
  133. }
  134. void cmGlobalNinjaGenerator::WriteBuild(
  135. std::ostream& os, const std::string& comment, const std::string& rule,
  136. const cmNinjaDeps& outputs, const cmNinjaDeps& implicitOuts,
  137. const cmNinjaDeps& explicitDeps, const cmNinjaDeps& implicitDeps,
  138. const cmNinjaDeps& orderOnlyDeps, const cmNinjaVars& variables,
  139. const std::string& rspfile, int cmdLineLimit, bool* usedResponseFile)
  140. {
  141. // Make sure there is a rule.
  142. if (rule.empty()) {
  143. cmSystemTools::Error("No rule for WriteBuildStatement! called "
  144. "with comment: ",
  145. comment.c_str());
  146. return;
  147. }
  148. // Make sure there is at least one output file.
  149. if (outputs.empty()) {
  150. cmSystemTools::Error("No output files for WriteBuildStatement! called "
  151. "with comment: ",
  152. comment.c_str());
  153. return;
  154. }
  155. cmGlobalNinjaGenerator::WriteComment(os, comment);
  156. std::string arguments;
  157. // TODO: Better formatting for when there are multiple input/output files.
  158. // Write explicit dependencies.
  159. for (std::string const& explicitDep : explicitDeps) {
  160. arguments += " " + EncodeIdent(EncodePath(explicitDep), os);
  161. }
  162. // Write implicit dependencies.
  163. if (!implicitDeps.empty()) {
  164. arguments += " |";
  165. for (std::string const& implicitDep : implicitDeps) {
  166. arguments += " " + EncodeIdent(EncodePath(implicitDep), os);
  167. }
  168. }
  169. // Write order-only dependencies.
  170. if (!orderOnlyDeps.empty()) {
  171. arguments += " ||";
  172. for (std::string const& orderOnlyDep : orderOnlyDeps) {
  173. arguments += " " + EncodeIdent(EncodePath(orderOnlyDep), os);
  174. }
  175. }
  176. arguments += "\n";
  177. std::string build;
  178. // Write outputs files.
  179. build += "build";
  180. for (std::string const& output : outputs) {
  181. build += " " + EncodeIdent(EncodePath(output), os);
  182. if (this->ComputingUnknownDependencies) {
  183. this->CombinedBuildOutputs.insert(output);
  184. }
  185. }
  186. if (!implicitOuts.empty()) {
  187. build += " |";
  188. for (std::string const& implicitOut : implicitOuts) {
  189. build += " " + EncodeIdent(EncodePath(implicitOut), os);
  190. }
  191. }
  192. build += ":";
  193. // Write the rule.
  194. build += " " + rule;
  195. // Write the variables bound to this build statement.
  196. std::ostringstream variable_assignments;
  197. for (auto const& variable : variables) {
  198. cmGlobalNinjaGenerator::WriteVariable(variable_assignments, variable.first,
  199. variable.second, "", 1);
  200. }
  201. // check if a response file rule should be used
  202. std::string buildstr = build;
  203. std::string assignments = variable_assignments.str();
  204. bool useResponseFile = false;
  205. if (cmdLineLimit < 0 ||
  206. (cmdLineLimit > 0 &&
  207. (arguments.size() + buildstr.size() + assignments.size() + 1000) >
  208. static_cast<size_t>(cmdLineLimit))) {
  209. variable_assignments.str(std::string());
  210. cmGlobalNinjaGenerator::WriteVariable(variable_assignments, "RSP_FILE",
  211. rspfile, "", 1);
  212. assignments += variable_assignments.str();
  213. useResponseFile = true;
  214. }
  215. if (usedResponseFile) {
  216. *usedResponseFile = useResponseFile;
  217. }
  218. os << buildstr << arguments << assignments;
  219. }
  220. void cmGlobalNinjaGenerator::WritePhonyBuild(
  221. std::ostream& os, const std::string& comment, const cmNinjaDeps& outputs,
  222. const cmNinjaDeps& explicitDeps, const cmNinjaDeps& implicitDeps,
  223. const cmNinjaDeps& orderOnlyDeps, const cmNinjaVars& variables)
  224. {
  225. this->WriteBuild(os, comment, "phony", outputs,
  226. /*implicitOuts=*/cmNinjaDeps(), explicitDeps, implicitDeps,
  227. orderOnlyDeps, variables);
  228. }
  229. void cmGlobalNinjaGenerator::AddCustomCommandRule()
  230. {
  231. this->AddRule("CUSTOM_COMMAND", "$COMMAND", "$DESC",
  232. "Rule for running custom commands.",
  233. /*depfile*/ "",
  234. /*deptype*/ "",
  235. /*rspfile*/ "",
  236. /*rspcontent*/ "",
  237. /*restat*/ "", // bound on each build statement as needed
  238. /*generator*/ false);
  239. }
  240. void cmGlobalNinjaGenerator::WriteCustomCommandBuild(
  241. const std::string& command, const std::string& description,
  242. const std::string& comment, const std::string& depfile, bool uses_terminal,
  243. bool restat, const cmNinjaDeps& outputs, const cmNinjaDeps& deps,
  244. const cmNinjaDeps& orderOnly)
  245. {
  246. std::string cmd = command; // NOLINT(clang-tidy)
  247. #ifdef _WIN32
  248. if (cmd.empty())
  249. // TODO Shouldn't an empty command be handled by ninja?
  250. cmd = "cmd.exe /c";
  251. #endif
  252. this->AddCustomCommandRule();
  253. cmNinjaVars vars;
  254. vars["COMMAND"] = cmd;
  255. vars["DESC"] = EncodeLiteral(description);
  256. if (restat) {
  257. vars["restat"] = "1";
  258. }
  259. if (uses_terminal && SupportsConsolePool()) {
  260. vars["pool"] = "console";
  261. }
  262. if (!depfile.empty()) {
  263. vars["depfile"] = depfile;
  264. }
  265. this->WriteBuild(*this->BuildFileStream, comment, "CUSTOM_COMMAND", outputs,
  266. /*implicitOuts=*/cmNinjaDeps(), deps, cmNinjaDeps(),
  267. orderOnly, vars);
  268. if (this->ComputingUnknownDependencies) {
  269. // we need to track every dependency that comes in, since we are trying
  270. // to find dependencies that are side effects of build commands
  271. for (std::string const& dep : deps) {
  272. this->CombinedCustomCommandExplicitDependencies.insert(dep);
  273. }
  274. }
  275. }
  276. void cmGlobalNinjaGenerator::AddMacOSXContentRule()
  277. {
  278. cmLocalGenerator* lg = this->LocalGenerators[0];
  279. std::ostringstream cmd;
  280. cmd << lg->ConvertToOutputFormat(cmSystemTools::GetCMakeCommand(),
  281. cmOutputConverter::SHELL)
  282. << " -E copy $in $out";
  283. this->AddRule("COPY_OSX_CONTENT", cmd.str(), "Copying OS X Content $out",
  284. "Rule for copying OS X bundle content file.",
  285. /*depfile*/ "",
  286. /*deptype*/ "",
  287. /*rspfile*/ "",
  288. /*rspcontent*/ "",
  289. /*restat*/ "",
  290. /*generator*/ false);
  291. }
  292. void cmGlobalNinjaGenerator::WriteMacOSXContentBuild(const std::string& input,
  293. const std::string& output)
  294. {
  295. this->AddMacOSXContentRule();
  296. cmNinjaDeps outputs;
  297. outputs.push_back(output);
  298. cmNinjaDeps deps;
  299. deps.push_back(input);
  300. cmNinjaVars vars;
  301. this->WriteBuild(*this->BuildFileStream, "", "COPY_OSX_CONTENT", outputs,
  302. /*implicitOuts=*/cmNinjaDeps(), deps, cmNinjaDeps(),
  303. cmNinjaDeps(), cmNinjaVars());
  304. }
  305. void cmGlobalNinjaGenerator::WriteRule(
  306. std::ostream& os, const std::string& name, const std::string& command,
  307. const std::string& description, const std::string& comment,
  308. const std::string& depfile, const std::string& deptype,
  309. const std::string& rspfile, const std::string& rspcontent,
  310. const std::string& restat, bool generator)
  311. {
  312. // Make sure the rule has a name.
  313. if (name.empty()) {
  314. cmSystemTools::Error("No name given for WriteRuleStatement! called "
  315. "with comment: ",
  316. comment.c_str());
  317. return;
  318. }
  319. // Make sure a command is given.
  320. if (command.empty()) {
  321. cmSystemTools::Error("No command given for WriteRuleStatement! called "
  322. "with comment: ",
  323. comment.c_str());
  324. return;
  325. }
  326. cmGlobalNinjaGenerator::WriteComment(os, comment);
  327. // Write the rule.
  328. os << "rule " << name << "\n";
  329. // Write the depfile if any.
  330. if (!depfile.empty()) {
  331. cmGlobalNinjaGenerator::Indent(os, 1);
  332. os << "depfile = " << depfile << "\n";
  333. }
  334. // Write the deptype if any.
  335. if (!deptype.empty()) {
  336. cmGlobalNinjaGenerator::Indent(os, 1);
  337. os << "deps = " << deptype << "\n";
  338. }
  339. // Write the command.
  340. cmGlobalNinjaGenerator::Indent(os, 1);
  341. os << "command = " << command << "\n";
  342. // Write the description if any.
  343. if (!description.empty()) {
  344. cmGlobalNinjaGenerator::Indent(os, 1);
  345. os << "description = " << description << "\n";
  346. }
  347. if (!rspfile.empty()) {
  348. if (rspcontent.empty()) {
  349. cmSystemTools::Error("No rspfile_content given!", comment.c_str());
  350. return;
  351. }
  352. cmGlobalNinjaGenerator::Indent(os, 1);
  353. os << "rspfile = " << rspfile << "\n";
  354. cmGlobalNinjaGenerator::Indent(os, 1);
  355. os << "rspfile_content = " << rspcontent << "\n";
  356. }
  357. if (!restat.empty()) {
  358. cmGlobalNinjaGenerator::Indent(os, 1);
  359. os << "restat = " << restat << "\n";
  360. }
  361. if (generator) {
  362. cmGlobalNinjaGenerator::Indent(os, 1);
  363. os << "generator = 1\n";
  364. }
  365. os << "\n";
  366. }
  367. void cmGlobalNinjaGenerator::WriteVariable(std::ostream& os,
  368. const std::string& name,
  369. const std::string& value,
  370. const std::string& comment,
  371. int indent)
  372. {
  373. // Make sure we have a name.
  374. if (name.empty()) {
  375. cmSystemTools::Error("No name given for WriteVariable! called "
  376. "with comment: ",
  377. comment.c_str());
  378. return;
  379. }
  380. // Do not add a variable if the value is empty.
  381. std::string val = cmSystemTools::TrimWhitespace(value);
  382. if (val.empty()) {
  383. return;
  384. }
  385. cmGlobalNinjaGenerator::WriteComment(os, comment);
  386. cmGlobalNinjaGenerator::Indent(os, indent);
  387. os << name << " = " << val << "\n";
  388. }
  389. void cmGlobalNinjaGenerator::WriteInclude(std::ostream& os,
  390. const std::string& filename,
  391. const std::string& comment)
  392. {
  393. cmGlobalNinjaGenerator::WriteComment(os, comment);
  394. os << "include " << filename << "\n";
  395. }
  396. void cmGlobalNinjaGenerator::WriteDefault(std::ostream& os,
  397. const cmNinjaDeps& targets,
  398. const std::string& comment)
  399. {
  400. cmGlobalNinjaGenerator::WriteComment(os, comment);
  401. os << "default";
  402. for (std::string const& target : targets) {
  403. os << " " << target;
  404. }
  405. os << "\n";
  406. }
  407. cmGlobalNinjaGenerator::cmGlobalNinjaGenerator(cmake* cm)
  408. : cmGlobalCommonGenerator(cm)
  409. , BuildFileStream(nullptr)
  410. , RulesFileStream(nullptr)
  411. , CompileCommandsStream(nullptr)
  412. , Rules()
  413. , AllDependencies()
  414. , UsingGCCOnWindows(false)
  415. , ComputingUnknownDependencies(false)
  416. , PolicyCMP0058(cmPolicies::WARN)
  417. , NinjaSupportsConsolePool(false)
  418. , NinjaSupportsImplicitOuts(false)
  419. , NinjaSupportsDyndeps(0)
  420. {
  421. #ifdef _WIN32
  422. cm->GetState()->SetWindowsShell(true);
  423. #endif
  424. // // Ninja is not ported to non-Unix OS yet.
  425. // this->ForceUnixPaths = true;
  426. this->FindMakeProgramFile = "CMakeNinjaFindMake.cmake";
  427. }
  428. // Virtual public methods.
  429. cmLocalGenerator* cmGlobalNinjaGenerator::CreateLocalGenerator(cmMakefile* mf)
  430. {
  431. return new cmLocalNinjaGenerator(this, mf);
  432. }
  433. codecvt::Encoding cmGlobalNinjaGenerator::GetMakefileEncoding() const
  434. {
  435. #ifdef _WIN32
  436. // Ninja on Windows does not support non-ANSI characters.
  437. // https://github.com/ninja-build/ninja/issues/1195
  438. return codecvt::ANSI;
  439. #else
  440. // No encoding conversion needed on other platforms.
  441. return codecvt::None;
  442. #endif
  443. }
  444. void cmGlobalNinjaGenerator::GetDocumentation(cmDocumentationEntry& entry)
  445. {
  446. entry.Name = cmGlobalNinjaGenerator::GetActualName();
  447. entry.Brief = "Generates build.ninja files.";
  448. }
  449. // Implemented in all cmGlobaleGenerator sub-classes.
  450. // Used in:
  451. // Source/cmLocalGenerator.cxx
  452. // Source/cmake.cxx
  453. void cmGlobalNinjaGenerator::Generate()
  454. {
  455. // Check minimum Ninja version.
  456. if (cmSystemTools::VersionCompare(cmSystemTools::OP_LESS,
  457. this->NinjaVersion.c_str(),
  458. RequiredNinjaVersion().c_str())) {
  459. std::ostringstream msg;
  460. msg << "The detected version of Ninja (" << this->NinjaVersion;
  461. msg << ") is less than the version of Ninja required by CMake (";
  462. msg << this->RequiredNinjaVersion() << ").";
  463. this->GetCMakeInstance()->IssueMessage(cmake::FATAL_ERROR, msg.str());
  464. return;
  465. }
  466. this->OpenBuildFileStream();
  467. this->OpenRulesFileStream();
  468. this->TargetDependsClosures.clear();
  469. this->InitOutputPathPrefix();
  470. this->TargetAll = this->NinjaOutputPath("all");
  471. this->CMakeCacheFile = this->NinjaOutputPath("CMakeCache.txt");
  472. this->PolicyCMP0058 =
  473. this->LocalGenerators[0]->GetMakefile()->GetPolicyStatus(
  474. cmPolicies::CMP0058);
  475. this->ComputingUnknownDependencies =
  476. (this->PolicyCMP0058 == cmPolicies::OLD ||
  477. this->PolicyCMP0058 == cmPolicies::WARN);
  478. this->cmGlobalGenerator::Generate();
  479. this->WriteAssumedSourceDependencies();
  480. this->WriteTargetAliases(*this->BuildFileStream);
  481. this->WriteFolderTargets(*this->BuildFileStream);
  482. this->WriteUnknownExplicitDependencies(*this->BuildFileStream);
  483. this->WriteBuiltinTargets(*this->BuildFileStream);
  484. if (cmSystemTools::GetErrorOccuredFlag()) {
  485. this->RulesFileStream->setstate(std::ios::failbit);
  486. this->BuildFileStream->setstate(std::ios::failbit);
  487. }
  488. this->CloseCompileCommandsStream();
  489. this->CloseRulesFileStream();
  490. this->CloseBuildFileStream();
  491. }
  492. bool cmGlobalNinjaGenerator::FindMakeProgram(cmMakefile* mf)
  493. {
  494. if (!this->cmGlobalGenerator::FindMakeProgram(mf)) {
  495. return false;
  496. }
  497. if (const char* ninjaCommand = mf->GetDefinition("CMAKE_MAKE_PROGRAM")) {
  498. this->NinjaCommand = ninjaCommand;
  499. std::vector<std::string> command;
  500. command.push_back(this->NinjaCommand);
  501. command.push_back("--version");
  502. std::string version;
  503. std::string error;
  504. if (!cmSystemTools::RunSingleCommand(command, &version, &error, nullptr,
  505. nullptr,
  506. cmSystemTools::OUTPUT_NONE)) {
  507. mf->IssueMessage(cmake::FATAL_ERROR, "Running\n '" +
  508. cmJoin(command, "' '") + "'\n"
  509. "failed with:\n " +
  510. error);
  511. cmSystemTools::SetFatalErrorOccured();
  512. return false;
  513. }
  514. this->NinjaVersion = cmSystemTools::TrimWhitespace(version);
  515. this->CheckNinjaFeatures();
  516. }
  517. return true;
  518. }
  519. void cmGlobalNinjaGenerator::CheckNinjaFeatures()
  520. {
  521. this->NinjaSupportsConsolePool = !cmSystemTools::VersionCompare(
  522. cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
  523. RequiredNinjaVersionForConsolePool().c_str());
  524. this->NinjaSupportsImplicitOuts = !cmSystemTools::VersionCompare(
  525. cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
  526. this->RequiredNinjaVersionForImplicitOuts().c_str());
  527. {
  528. // Our ninja branch adds ".dyndep-#" to its version number,
  529. // where '#' is a feature-specific version number. Extract it.
  530. static std::string const k_DYNDEP_ = ".dyndep-";
  531. std::string::size_type pos = this->NinjaVersion.find(k_DYNDEP_);
  532. if (pos != std::string::npos) {
  533. const char* fv = this->NinjaVersion.c_str() + pos + k_DYNDEP_.size();
  534. cmSystemTools::StringToULong(fv, &this->NinjaSupportsDyndeps);
  535. }
  536. }
  537. }
  538. bool cmGlobalNinjaGenerator::CheckLanguages(
  539. std::vector<std::string> const& languages, cmMakefile* mf) const
  540. {
  541. if (std::find(languages.begin(), languages.end(), "Fortran") !=
  542. languages.end()) {
  543. return this->CheckFortran(mf);
  544. }
  545. return true;
  546. }
  547. bool cmGlobalNinjaGenerator::CheckFortran(cmMakefile* mf) const
  548. {
  549. if (this->NinjaSupportsDyndeps == 1) {
  550. return true;
  551. }
  552. std::ostringstream e;
  553. if (this->NinjaSupportsDyndeps == 0) {
  554. /* clang-format off */
  555. e <<
  556. "The Ninja generator does not support Fortran using Ninja version\n"
  557. " " + this->NinjaVersion + "\n"
  558. "due to lack of required features. "
  559. "Kitware has implemented the required features but as of this version "
  560. "of CMake they have not been integrated to upstream ninja. "
  561. "Pending integration, Kitware maintains a branch at:\n"
  562. " https://github.com/Kitware/ninja/tree/features-for-fortran#readme\n"
  563. "with the required features. "
  564. "One may build ninja from that branch to get support for Fortran."
  565. ;
  566. /* clang-format on */
  567. } else {
  568. /* clang-format off */
  569. e <<
  570. "The Ninja generator in this version of CMake does not support Fortran "
  571. "using Ninja version\n"
  572. " " + this->NinjaVersion + "\n"
  573. "because its 'dyndep' feature version is " <<
  574. this->NinjaSupportsDyndeps << ". "
  575. "This version of CMake is aware only of 'dyndep' feature version 1."
  576. ;
  577. /* clang-format on */
  578. }
  579. mf->IssueMessage(cmake::FATAL_ERROR, e.str());
  580. cmSystemTools::SetFatalErrorOccured();
  581. return false;
  582. }
  583. void cmGlobalNinjaGenerator::EnableLanguage(
  584. std::vector<std::string> const& langs, cmMakefile* mf, bool optional)
  585. {
  586. this->cmGlobalGenerator::EnableLanguage(langs, mf, optional);
  587. for (std::string const& l : langs) {
  588. if (l == "NONE") {
  589. continue;
  590. }
  591. this->ResolveLanguageCompiler(l, mf, optional);
  592. }
  593. #ifdef _WIN32
  594. if (strcmp(mf->GetSafeDefinition("CMAKE_C_SIMULATE_ID"), "MSVC") != 0 &&
  595. strcmp(mf->GetSafeDefinition("CMAKE_CXX_SIMULATE_ID"), "MSVC") != 0 &&
  596. (mf->IsOn("CMAKE_COMPILER_IS_MINGW") ||
  597. strcmp(mf->GetSafeDefinition("CMAKE_C_COMPILER_ID"), "GNU") == 0 ||
  598. strcmp(mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID"), "GNU") == 0 ||
  599. strcmp(mf->GetSafeDefinition("CMAKE_C_COMPILER_ID"), "Clang") == 0 ||
  600. strcmp(mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID"), "Clang") == 0)) {
  601. this->UsingGCCOnWindows = true;
  602. }
  603. #endif
  604. }
  605. // Implemented by:
  606. // cmGlobalUnixMakefileGenerator3
  607. // cmGlobalGhsMultiGenerator
  608. // cmGlobalVisualStudio10Generator
  609. // cmGlobalVisualStudio7Generator
  610. // cmGlobalXCodeGenerator
  611. // Called by:
  612. // cmGlobalGenerator::Build()
  613. void cmGlobalNinjaGenerator::GenerateBuildCommand(
  614. std::vector<std::string>& makeCommand, const std::string& makeProgram,
  615. const std::string& /*projectName*/, const std::string& /*projectDir*/,
  616. const std::string& targetName, const std::string& /*config*/, bool /*fast*/,
  617. bool verbose, std::vector<std::string> const& makeOptions)
  618. {
  619. makeCommand.push_back(this->SelectMakeProgram(makeProgram));
  620. if (verbose) {
  621. makeCommand.push_back("-v");
  622. }
  623. makeCommand.insert(makeCommand.end(), makeOptions.begin(),
  624. makeOptions.end());
  625. if (!targetName.empty()) {
  626. if (targetName == "clean") {
  627. makeCommand.push_back("-t");
  628. makeCommand.push_back("clean");
  629. } else {
  630. makeCommand.push_back(targetName);
  631. }
  632. }
  633. }
  634. // Non-virtual public methods.
  635. void cmGlobalNinjaGenerator::AddRule(
  636. const std::string& name, const std::string& command,
  637. const std::string& description, const std::string& comment,
  638. const std::string& depfile, const std::string& deptype,
  639. const std::string& rspfile, const std::string& rspcontent,
  640. const std::string& restat, bool generator)
  641. {
  642. // Do not add the same rule twice.
  643. if (this->HasRule(name)) {
  644. return;
  645. }
  646. this->Rules.insert(name);
  647. cmGlobalNinjaGenerator::WriteRule(*this->RulesFileStream, name, command,
  648. description, comment, depfile, deptype,
  649. rspfile, rspcontent, restat, generator);
  650. this->RuleCmdLength[name] = static_cast<int>(command.size());
  651. }
  652. bool cmGlobalNinjaGenerator::HasRule(const std::string& name)
  653. {
  654. RulesSetType::const_iterator rule = this->Rules.find(name);
  655. return (rule != this->Rules.end());
  656. }
  657. // Private virtual overrides
  658. std::string cmGlobalNinjaGenerator::GetEditCacheCommand() const
  659. {
  660. // Ninja by design does not run interactive tools in the terminal,
  661. // so our only choice is cmake-gui.
  662. return cmSystemTools::GetCMakeGUICommand();
  663. }
  664. void cmGlobalNinjaGenerator::ComputeTargetObjectDirectory(
  665. cmGeneratorTarget* gt) const
  666. {
  667. // Compute full path to object file directory for this target.
  668. std::string dir;
  669. dir += gt->LocalGenerator->GetCurrentBinaryDirectory();
  670. dir += "/";
  671. dir += gt->LocalGenerator->GetTargetDirectory(gt);
  672. dir += "/";
  673. gt->ObjectDirectory = dir;
  674. }
  675. // Private methods
  676. void cmGlobalNinjaGenerator::OpenBuildFileStream()
  677. {
  678. // Compute Ninja's build file path.
  679. std::string buildFilePath =
  680. this->GetCMakeInstance()->GetHomeOutputDirectory();
  681. buildFilePath += "/";
  682. buildFilePath += cmGlobalNinjaGenerator::NINJA_BUILD_FILE;
  683. // Get a stream where to generate things.
  684. if (!this->BuildFileStream) {
  685. this->BuildFileStream = new cmGeneratedFileStream(
  686. buildFilePath.c_str(), false, this->GetMakefileEncoding());
  687. if (!this->BuildFileStream) {
  688. // An error message is generated by the constructor if it cannot
  689. // open the file.
  690. return;
  691. }
  692. }
  693. // Write the do not edit header.
  694. this->WriteDisclaimer(*this->BuildFileStream);
  695. // Write a comment about this file.
  696. *this->BuildFileStream
  697. << "# This file contains all the build statements describing the\n"
  698. << "# compilation DAG.\n\n";
  699. }
  700. void cmGlobalNinjaGenerator::CloseBuildFileStream()
  701. {
  702. if (this->BuildFileStream) {
  703. delete this->BuildFileStream;
  704. this->BuildFileStream = nullptr;
  705. } else {
  706. cmSystemTools::Error("Build file stream was not open.");
  707. }
  708. }
  709. void cmGlobalNinjaGenerator::OpenRulesFileStream()
  710. {
  711. // Compute Ninja's build file path.
  712. std::string rulesFilePath =
  713. this->GetCMakeInstance()->GetHomeOutputDirectory();
  714. rulesFilePath += "/";
  715. rulesFilePath += cmGlobalNinjaGenerator::NINJA_RULES_FILE;
  716. // Get a stream where to generate things.
  717. if (!this->RulesFileStream) {
  718. this->RulesFileStream = new cmGeneratedFileStream(
  719. rulesFilePath.c_str(), false, this->GetMakefileEncoding());
  720. if (!this->RulesFileStream) {
  721. // An error message is generated by the constructor if it cannot
  722. // open the file.
  723. return;
  724. }
  725. }
  726. // Write the do not edit header.
  727. this->WriteDisclaimer(*this->RulesFileStream);
  728. // Write comment about this file.
  729. /* clang-format off */
  730. *this->RulesFileStream
  731. << "# This file contains all the rules used to get the outputs files\n"
  732. << "# built from the input files.\n"
  733. << "# It is included in the main '" << NINJA_BUILD_FILE << "'.\n\n"
  734. ;
  735. /* clang-format on */
  736. }
  737. void cmGlobalNinjaGenerator::CloseRulesFileStream()
  738. {
  739. if (this->RulesFileStream) {
  740. delete this->RulesFileStream;
  741. this->RulesFileStream = nullptr;
  742. } else {
  743. cmSystemTools::Error("Rules file stream was not open.");
  744. }
  745. }
  746. static void EnsureTrailingSlash(std::string& path)
  747. {
  748. if (path.empty()) {
  749. return;
  750. }
  751. std::string::value_type last = path[path.size() - 1];
  752. #ifdef _WIN32
  753. if (last != '\\') {
  754. path += '\\';
  755. }
  756. #else
  757. if (last != '/') {
  758. path += '/';
  759. }
  760. #endif
  761. }
  762. std::string const& cmGlobalNinjaGenerator::ConvertToNinjaPath(
  763. const std::string& path) const
  764. {
  765. auto const f = ConvertToNinjaPathCache.find(path);
  766. if (f != ConvertToNinjaPathCache.end()) {
  767. return f->second;
  768. }
  769. cmLocalNinjaGenerator* ng =
  770. static_cast<cmLocalNinjaGenerator*>(this->LocalGenerators[0]);
  771. std::string const& bin_dir = ng->GetState()->GetBinaryDirectory();
  772. std::string convPath = ng->ConvertToRelativePath(bin_dir, path);
  773. convPath = this->NinjaOutputPath(convPath);
  774. #ifdef _WIN32
  775. std::replace(convPath.begin(), convPath.end(), '/', '\\');
  776. #endif
  777. return ConvertToNinjaPathCache.emplace(path, std::move(convPath))
  778. .first->second;
  779. }
  780. void cmGlobalNinjaGenerator::AddCXXCompileCommand(
  781. const std::string& commandLine, const std::string& sourceFile)
  782. {
  783. // Compute Ninja's build file path.
  784. std::string buildFileDir =
  785. this->GetCMakeInstance()->GetHomeOutputDirectory();
  786. if (!this->CompileCommandsStream) {
  787. std::string buildFilePath = buildFileDir + "/compile_commands.json";
  788. if (this->ComputingUnknownDependencies) {
  789. this->CombinedBuildOutputs.insert(
  790. this->NinjaOutputPath("compile_commands.json"));
  791. }
  792. // Get a stream where to generate things.
  793. this->CompileCommandsStream =
  794. new cmGeneratedFileStream(buildFilePath.c_str());
  795. *this->CompileCommandsStream << "[";
  796. } else {
  797. *this->CompileCommandsStream << "," << std::endl;
  798. }
  799. std::string sourceFileName = sourceFile;
  800. if (!cmSystemTools::FileIsFullPath(sourceFileName)) {
  801. sourceFileName = cmSystemTools::CollapseFullPath(
  802. sourceFileName, this->GetCMakeInstance()->GetHomeOutputDirectory());
  803. }
  804. /* clang-format off */
  805. *this->CompileCommandsStream << "\n{\n"
  806. << " \"directory\": \""
  807. << cmGlobalGenerator::EscapeJSON(buildFileDir) << "\",\n"
  808. << " \"command\": \""
  809. << cmGlobalGenerator::EscapeJSON(commandLine) << "\",\n"
  810. << " \"file\": \""
  811. << cmGlobalGenerator::EscapeJSON(sourceFileName) << "\"\n"
  812. << "}";
  813. /* clang-format on */
  814. }
  815. void cmGlobalNinjaGenerator::CloseCompileCommandsStream()
  816. {
  817. if (this->CompileCommandsStream) {
  818. *this->CompileCommandsStream << "\n]";
  819. delete this->CompileCommandsStream;
  820. this->CompileCommandsStream = nullptr;
  821. }
  822. }
  823. void cmGlobalNinjaGenerator::WriteDisclaimer(std::ostream& os)
  824. {
  825. os << "# CMAKE generated file: DO NOT EDIT!\n"
  826. << "# Generated by \"" << this->GetName() << "\""
  827. << " Generator, CMake Version " << cmVersion::GetMajorVersion() << "."
  828. << cmVersion::GetMinorVersion() << "\n\n";
  829. }
  830. void cmGlobalNinjaGenerator::AddDependencyToAll(cmGeneratorTarget* target)
  831. {
  832. this->AppendTargetOutputs(target, this->AllDependencies);
  833. }
  834. void cmGlobalNinjaGenerator::AddDependencyToAll(const std::string& input)
  835. {
  836. this->AllDependencies.push_back(input);
  837. }
  838. void cmGlobalNinjaGenerator::WriteAssumedSourceDependencies()
  839. {
  840. for (auto const& asd : this->AssumedSourceDependencies) {
  841. cmNinjaDeps deps;
  842. std::copy(asd.second.begin(), asd.second.end(), std::back_inserter(deps));
  843. WriteCustomCommandBuild(/*command=*/"", /*description=*/"",
  844. "Assume dependencies for generated source file.",
  845. /*depfile*/ "", /*uses_terminal*/ false,
  846. /*restat*/ true, cmNinjaDeps(1, asd.first), deps);
  847. }
  848. }
  849. std::string OrderDependsTargetForTarget(cmGeneratorTarget const* target)
  850. {
  851. return "cmake_object_order_depends_target_" + target->GetName();
  852. }
  853. void cmGlobalNinjaGenerator::AppendTargetOutputs(
  854. cmGeneratorTarget const* target, cmNinjaDeps& outputs,
  855. cmNinjaTargetDepends depends)
  856. {
  857. std::string configName =
  858. target->Target->GetMakefile()->GetSafeDefinition("CMAKE_BUILD_TYPE");
  859. // for frameworks, we want the real name, not smple name
  860. // frameworks always appear versioned, and the build.ninja
  861. // will always attempt to manage symbolic links instead
  862. // of letting cmOSXBundleGenerator do it.
  863. bool realname = target->IsFrameworkOnApple();
  864. switch (target->GetType()) {
  865. case cmStateEnums::SHARED_LIBRARY:
  866. case cmStateEnums::STATIC_LIBRARY:
  867. case cmStateEnums::MODULE_LIBRARY: {
  868. if (depends == DependOnTargetOrdering) {
  869. outputs.push_back(OrderDependsTargetForTarget(target));
  870. break;
  871. }
  872. }
  873. // FALLTHROUGH
  874. case cmStateEnums::EXECUTABLE: {
  875. outputs.push_back(this->ConvertToNinjaPath(target->GetFullPath(
  876. configName, cmStateEnums::RuntimeBinaryArtifact, realname)));
  877. break;
  878. }
  879. case cmStateEnums::OBJECT_LIBRARY: {
  880. if (depends == DependOnTargetOrdering) {
  881. outputs.push_back(OrderDependsTargetForTarget(target));
  882. break;
  883. }
  884. }
  885. // FALLTHROUGH
  886. case cmStateEnums::GLOBAL_TARGET:
  887. case cmStateEnums::UTILITY: {
  888. std::string path =
  889. target->GetLocalGenerator()->GetCurrentBinaryDirectory() +
  890. std::string("/") + target->GetName();
  891. outputs.push_back(this->ConvertToNinjaPath(path));
  892. break;
  893. }
  894. default:
  895. return;
  896. }
  897. }
  898. void cmGlobalNinjaGenerator::AppendTargetDepends(
  899. cmGeneratorTarget const* target, cmNinjaDeps& outputs,
  900. cmNinjaTargetDepends depends)
  901. {
  902. if (target->GetType() == cmStateEnums::GLOBAL_TARGET) {
  903. // These depend only on other CMake-provided targets, e.g. "all".
  904. std::set<std::string> const& utils = target->GetUtilities();
  905. for (std::string const& util : utils) {
  906. std::string d =
  907. target->GetLocalGenerator()->GetCurrentBinaryDirectory() +
  908. std::string("/") + util;
  909. outputs.push_back(this->ConvertToNinjaPath(d));
  910. }
  911. } else {
  912. cmNinjaDeps outs;
  913. cmTargetDependSet const& targetDeps = this->GetTargetDirectDepends(target);
  914. for (cmTargetDepend const& targetDep : targetDeps) {
  915. if (targetDep->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  916. continue;
  917. }
  918. this->AppendTargetOutputs(targetDep, outs, depends);
  919. }
  920. std::sort(outs.begin(), outs.end());
  921. outputs.insert(outputs.end(), outs.begin(), outs.end());
  922. }
  923. }
  924. void cmGlobalNinjaGenerator::AppendTargetDependsClosure(
  925. cmGeneratorTarget const* target, cmNinjaDeps& outputs)
  926. {
  927. cmNinjaOuts outs;
  928. this->AppendTargetDependsClosure(target, outs, true);
  929. outputs.insert(outputs.end(), outs.begin(), outs.end());
  930. }
  931. void cmGlobalNinjaGenerator::AppendTargetDependsClosure(
  932. cmGeneratorTarget const* target, cmNinjaOuts& outputs, bool omit_self)
  933. {
  934. // try to locate the target in the cache
  935. auto find = this->TargetDependsClosures.lower_bound(target);
  936. if (find == this->TargetDependsClosures.end() || find->first != target) {
  937. // We now calculate the closure outputs by inspecting the dependent
  938. // targets recursively.
  939. // For that we have to distinguish between a local result set that is only
  940. // relevant for filling the cache entries properly isolated and a global
  941. // result set that is relevant for the result of the top level call to
  942. // AppendTargetDependsClosure.
  943. auto const& targetDeps = this->GetTargetDirectDepends(target);
  944. cmNinjaOuts this_outs; // this will be the new cache entry
  945. for (auto const& dep_target : targetDeps) {
  946. if (dep_target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  947. continue;
  948. }
  949. // Collect the dependent targets for _this_ target
  950. this->AppendTargetDependsClosure(dep_target, this_outs, false);
  951. }
  952. find = this->TargetDependsClosures.emplace_hint(find, target,
  953. std::move(this_outs));
  954. }
  955. // now fill the outputs of the final result from the newly generated cache
  956. // entry
  957. outputs.insert(find->second.begin(), find->second.end());
  958. // finally generate the outputs of the target itself, if applicable
  959. cmNinjaDeps outs;
  960. if (!omit_self) {
  961. this->AppendTargetOutputs(target, outs);
  962. }
  963. outputs.insert(outs.begin(), outs.end());
  964. }
  965. void cmGlobalNinjaGenerator::AddTargetAlias(const std::string& alias,
  966. cmGeneratorTarget* target)
  967. {
  968. std::string buildAlias = this->NinjaOutputPath(alias);
  969. cmNinjaDeps outputs;
  970. this->AppendTargetOutputs(target, outputs);
  971. // Mark the target's outputs as ambiguous to ensure that no other target uses
  972. // the output as an alias.
  973. for (std::string const& output : outputs) {
  974. TargetAliases[output] = nullptr;
  975. }
  976. // Insert the alias into the map. If the alias was already present in the
  977. // map and referred to another target, mark it as ambiguous.
  978. std::pair<TargetAliasMap::iterator, bool> newAlias =
  979. TargetAliases.insert(std::make_pair(buildAlias, target));
  980. if (newAlias.second && newAlias.first->second != target) {
  981. newAlias.first->second = nullptr;
  982. }
  983. }
  984. void cmGlobalNinjaGenerator::WriteTargetAliases(std::ostream& os)
  985. {
  986. cmGlobalNinjaGenerator::WriteDivider(os);
  987. os << "# Target aliases.\n\n";
  988. for (auto const& ta : TargetAliases) {
  989. // Don't write ambiguous aliases.
  990. if (!ta.second) {
  991. continue;
  992. }
  993. cmNinjaDeps deps;
  994. this->AppendTargetOutputs(ta.second, deps);
  995. this->WritePhonyBuild(os, "", cmNinjaDeps(1, ta.first), deps);
  996. }
  997. }
  998. void cmGlobalNinjaGenerator::WriteFolderTargets(std::ostream& os)
  999. {
  1000. cmGlobalNinjaGenerator::WriteDivider(os);
  1001. os << "# Folder targets.\n\n";
  1002. std::map<std::string, cmNinjaDeps> targetsPerFolder;
  1003. for (cmLocalGenerator const* lg : this->LocalGenerators) {
  1004. const std::string currentBinaryFolder(
  1005. lg->GetStateSnapshot().GetDirectory().GetCurrentBinary());
  1006. // The directory-level rule should depend on the target-level rules
  1007. // for all targets in the directory.
  1008. targetsPerFolder[currentBinaryFolder] = cmNinjaDeps();
  1009. for (auto gt : lg->GetGeneratorTargets()) {
  1010. cmStateEnums::TargetType const type = gt->GetType();
  1011. if ((type == cmStateEnums::EXECUTABLE ||
  1012. type == cmStateEnums::STATIC_LIBRARY ||
  1013. type == cmStateEnums::SHARED_LIBRARY ||
  1014. type == cmStateEnums::MODULE_LIBRARY ||
  1015. type == cmStateEnums::OBJECT_LIBRARY ||
  1016. type == cmStateEnums::UTILITY) &&
  1017. !gt->GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  1018. targetsPerFolder[currentBinaryFolder].push_back(gt->GetName());
  1019. }
  1020. }
  1021. // The directory-level rule should depend on the directory-level
  1022. // rules of the subdirectories.
  1023. std::vector<cmStateSnapshot> const& children =
  1024. lg->GetStateSnapshot().GetChildren();
  1025. for (cmStateSnapshot const& state : children) {
  1026. std::string const currentBinaryDir =
  1027. state.GetDirectory().GetCurrentBinary();
  1028. targetsPerFolder[currentBinaryFolder].push_back(
  1029. this->ConvertToNinjaPath(currentBinaryDir + "/all"));
  1030. }
  1031. }
  1032. std::string const rootBinaryDir =
  1033. this->LocalGenerators[0]->GetBinaryDirectory();
  1034. for (auto const& it : targetsPerFolder) {
  1035. cmGlobalNinjaGenerator::WriteDivider(os);
  1036. std::string const& currentBinaryDir = it.first;
  1037. // Do not generate a rule for the root binary dir.
  1038. if (rootBinaryDir.length() >= currentBinaryDir.length()) {
  1039. continue;
  1040. }
  1041. std::string const comment = "Folder: " + currentBinaryDir;
  1042. cmNinjaDeps output(1);
  1043. output.push_back(this->ConvertToNinjaPath(currentBinaryDir + "/all"));
  1044. this->WritePhonyBuild(os, comment, output, it.second);
  1045. }
  1046. }
  1047. void cmGlobalNinjaGenerator::WriteUnknownExplicitDependencies(std::ostream& os)
  1048. {
  1049. if (!this->ComputingUnknownDependencies) {
  1050. return;
  1051. }
  1052. // We need to collect the set of known build outputs.
  1053. // Start with those generated by WriteBuild calls.
  1054. // No other method needs this so we can take ownership
  1055. // of the set locally and throw it out when we are done.
  1056. std::set<std::string> knownDependencies;
  1057. knownDependencies.swap(this->CombinedBuildOutputs);
  1058. // now write out the unknown explicit dependencies.
  1059. // union the configured files, evaluations files and the
  1060. // CombinedBuildOutputs,
  1061. // and then difference with CombinedExplicitDependencies to find the explicit
  1062. // dependencies that we have no rule for
  1063. cmGlobalNinjaGenerator::WriteDivider(os);
  1064. /* clang-format off */
  1065. os << "# Unknown Build Time Dependencies.\n"
  1066. << "# Tell Ninja that they may appear as side effects of build rules\n"
  1067. << "# otherwise ordered by order-only dependencies.\n\n";
  1068. /* clang-format on */
  1069. // get the list of files that cmake itself has generated as a
  1070. // product of configuration.
  1071. for (cmLocalGenerator* lg : this->LocalGenerators) {
  1072. // get the vector of files created by this makefile and convert them
  1073. // to ninja paths, which are all relative in respect to the build directory
  1074. const std::vector<std::string>& files =
  1075. lg->GetMakefile()->GetOutputFiles();
  1076. for (std::string const& file : files) {
  1077. knownDependencies.insert(this->ConvertToNinjaPath(file));
  1078. }
  1079. // get list files which are implicit dependencies as well and will be phony
  1080. // for rebuild manifest
  1081. std::vector<std::string> const& lf = lg->GetMakefile()->GetListFiles();
  1082. for (std::string const& j : lf) {
  1083. knownDependencies.insert(this->ConvertToNinjaPath(j));
  1084. }
  1085. std::vector<cmGeneratorExpressionEvaluationFile*> const& ef =
  1086. lg->GetMakefile()->GetEvaluationFiles();
  1087. for (cmGeneratorExpressionEvaluationFile* li : ef) {
  1088. // get all the files created by generator expressions and convert them
  1089. // to ninja paths
  1090. std::vector<std::string> evaluationFiles = li->GetFiles();
  1091. for (std::string const& evaluationFile : evaluationFiles) {
  1092. knownDependencies.insert(this->ConvertToNinjaPath(evaluationFile));
  1093. }
  1094. }
  1095. }
  1096. knownDependencies.insert(this->CMakeCacheFile);
  1097. for (auto const& ta : this->TargetAliases) {
  1098. knownDependencies.insert(this->ConvertToNinjaPath(ta.first));
  1099. }
  1100. // remove all source files we know will exist.
  1101. for (auto const& i : this->AssumedSourceDependencies) {
  1102. knownDependencies.insert(this->ConvertToNinjaPath(i.first));
  1103. }
  1104. // now we difference with CombinedCustomCommandExplicitDependencies to find
  1105. // the list of items we know nothing about.
  1106. // We have encoded all the paths in CombinedCustomCommandExplicitDependencies
  1107. // and knownDependencies so no matter if unix or windows paths they
  1108. // should all match now.
  1109. std::vector<std::string> unknownExplicitDepends;
  1110. this->CombinedCustomCommandExplicitDependencies.erase(this->TargetAll);
  1111. std::set_difference(this->CombinedCustomCommandExplicitDependencies.begin(),
  1112. this->CombinedCustomCommandExplicitDependencies.end(),
  1113. knownDependencies.begin(), knownDependencies.end(),
  1114. std::back_inserter(unknownExplicitDepends));
  1115. std::string const rootBuildDirectory =
  1116. this->GetCMakeInstance()->GetHomeOutputDirectory();
  1117. bool const inSourceBuild =
  1118. (rootBuildDirectory == this->GetCMakeInstance()->GetHomeDirectory());
  1119. std::vector<std::string> warnExplicitDepends;
  1120. for (std::string const& i : unknownExplicitDepends) {
  1121. // verify the file is in the build directory
  1122. std::string const absDepPath =
  1123. cmSystemTools::CollapseFullPath(i, rootBuildDirectory.c_str());
  1124. bool const inBuildDir =
  1125. cmSystemTools::IsSubDirectory(absDepPath, rootBuildDirectory);
  1126. if (inBuildDir) {
  1127. cmNinjaDeps deps(1, i);
  1128. this->WritePhonyBuild(os, "", deps, cmNinjaDeps());
  1129. if (this->PolicyCMP0058 == cmPolicies::WARN && !inSourceBuild &&
  1130. warnExplicitDepends.size() < 10) {
  1131. warnExplicitDepends.push_back(i);
  1132. }
  1133. }
  1134. }
  1135. if (!warnExplicitDepends.empty()) {
  1136. std::ostringstream w;
  1137. /* clang-format off */
  1138. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0058) << "\n"
  1139. "This project specifies custom command DEPENDS on files "
  1140. "in the build tree that are not specified as the OUTPUT or "
  1141. "BYPRODUCTS of any add_custom_command or add_custom_target:\n"
  1142. " " << cmJoin(warnExplicitDepends, "\n ") <<
  1143. "\n"
  1144. "For compatibility with versions of CMake that did not have "
  1145. "the BYPRODUCTS option, CMake is generating phony rules for "
  1146. "such files to convince 'ninja' to build."
  1147. "\n"
  1148. "Project authors should add the missing BYPRODUCTS or OUTPUT "
  1149. "options to the custom commands that produce these files."
  1150. ;
  1151. /* clang-format on */
  1152. this->GetCMakeInstance()->IssueMessage(cmake::AUTHOR_WARNING, w.str());
  1153. }
  1154. }
  1155. void cmGlobalNinjaGenerator::WriteBuiltinTargets(std::ostream& os)
  1156. {
  1157. // Write headers.
  1158. cmGlobalNinjaGenerator::WriteDivider(os);
  1159. os << "# Built-in targets\n\n";
  1160. this->WriteTargetAll(os);
  1161. this->WriteTargetRebuildManifest(os);
  1162. this->WriteTargetClean(os);
  1163. this->WriteTargetHelp(os);
  1164. }
  1165. void cmGlobalNinjaGenerator::WriteTargetAll(std::ostream& os)
  1166. {
  1167. cmNinjaDeps outputs;
  1168. outputs.push_back(this->TargetAll);
  1169. this->WritePhonyBuild(os, "The main all target.", outputs,
  1170. this->AllDependencies);
  1171. if (!this->HasOutputPathPrefix()) {
  1172. cmGlobalNinjaGenerator::WriteDefault(os, outputs,
  1173. "Make the all target the default.");
  1174. }
  1175. }
  1176. void cmGlobalNinjaGenerator::WriteTargetRebuildManifest(std::ostream& os)
  1177. {
  1178. cmLocalGenerator* lg = this->LocalGenerators[0];
  1179. std::ostringstream cmd;
  1180. cmd << lg->ConvertToOutputFormat(cmSystemTools::GetCMakeCommand(),
  1181. cmOutputConverter::SHELL)
  1182. << " -H"
  1183. << lg->ConvertToOutputFormat(lg->GetSourceDirectory(),
  1184. cmOutputConverter::SHELL)
  1185. << " -B"
  1186. << lg->ConvertToOutputFormat(lg->GetBinaryDirectory(),
  1187. cmOutputConverter::SHELL);
  1188. WriteRule(*this->RulesFileStream, "RERUN_CMAKE", cmd.str(),
  1189. "Re-running CMake...", "Rule for re-running cmake.",
  1190. /*depfile=*/"",
  1191. /*deptype=*/"",
  1192. /*rspfile=*/"",
  1193. /*rspcontent*/ "",
  1194. /*restat=*/"",
  1195. /*generator=*/true);
  1196. cmNinjaDeps implicitDeps;
  1197. for (cmLocalGenerator* localGen : this->LocalGenerators) {
  1198. std::vector<std::string> const& lf =
  1199. localGen->GetMakefile()->GetListFiles();
  1200. for (std::string const& fi : lf) {
  1201. implicitDeps.push_back(this->ConvertToNinjaPath(fi));
  1202. }
  1203. }
  1204. implicitDeps.push_back(this->CMakeCacheFile);
  1205. std::sort(implicitDeps.begin(), implicitDeps.end());
  1206. implicitDeps.erase(std::unique(implicitDeps.begin(), implicitDeps.end()),
  1207. implicitDeps.end());
  1208. cmNinjaVars variables;
  1209. // Use 'console' pool to get non buffered output of the CMake re-run call
  1210. // Available since Ninja 1.5
  1211. if (SupportsConsolePool()) {
  1212. variables["pool"] = "console";
  1213. }
  1214. std::string const ninjaBuildFile = this->NinjaOutputPath(NINJA_BUILD_FILE);
  1215. this->WriteBuild(os, "Re-run CMake if any of its inputs changed.",
  1216. "RERUN_CMAKE",
  1217. /*outputs=*/cmNinjaDeps(1, ninjaBuildFile),
  1218. /*implicitOuts=*/cmNinjaDeps(),
  1219. /*explicitDeps=*/cmNinjaDeps(), implicitDeps,
  1220. /*orderOnlyDeps=*/cmNinjaDeps(), variables);
  1221. this->WritePhonyBuild(os, "A missing CMake input file is not an error.",
  1222. implicitDeps, cmNinjaDeps());
  1223. }
  1224. std::string cmGlobalNinjaGenerator::ninjaCmd() const
  1225. {
  1226. cmLocalGenerator* lgen = this->LocalGenerators[0];
  1227. if (lgen) {
  1228. return lgen->ConvertToOutputFormat(this->NinjaCommand,
  1229. cmOutputConverter::SHELL);
  1230. }
  1231. return "ninja";
  1232. }
  1233. bool cmGlobalNinjaGenerator::SupportsConsolePool() const
  1234. {
  1235. return this->NinjaSupportsConsolePool;
  1236. }
  1237. bool cmGlobalNinjaGenerator::SupportsImplicitOuts() const
  1238. {
  1239. return this->NinjaSupportsImplicitOuts;
  1240. }
  1241. void cmGlobalNinjaGenerator::WriteTargetClean(std::ostream& os)
  1242. {
  1243. WriteRule(*this->RulesFileStream, "CLEAN", ninjaCmd() + " -t clean",
  1244. "Cleaning all built files...",
  1245. "Rule for cleaning all built files.",
  1246. /*depfile=*/"",
  1247. /*deptype=*/"",
  1248. /*rspfile=*/"",
  1249. /*rspcontent*/ "",
  1250. /*restat=*/"",
  1251. /*generator=*/false);
  1252. WriteBuild(os, "Clean all the built files.", "CLEAN",
  1253. /*outputs=*/cmNinjaDeps(1, this->NinjaOutputPath("clean")),
  1254. /*implicitOuts=*/cmNinjaDeps(),
  1255. /*explicitDeps=*/cmNinjaDeps(),
  1256. /*implicitDeps=*/cmNinjaDeps(),
  1257. /*orderOnlyDeps=*/cmNinjaDeps(),
  1258. /*variables=*/cmNinjaVars());
  1259. }
  1260. void cmGlobalNinjaGenerator::WriteTargetHelp(std::ostream& os)
  1261. {
  1262. WriteRule(*this->RulesFileStream, "HELP", ninjaCmd() + " -t targets",
  1263. "All primary targets available:",
  1264. "Rule for printing all primary targets available.",
  1265. /*depfile=*/"",
  1266. /*deptype=*/"",
  1267. /*rspfile=*/"",
  1268. /*rspcontent*/ "",
  1269. /*restat=*/"",
  1270. /*generator=*/false);
  1271. WriteBuild(os, "Print all primary targets available.", "HELP",
  1272. /*outputs=*/cmNinjaDeps(1, this->NinjaOutputPath("help")),
  1273. /*implicitOuts=*/cmNinjaDeps(),
  1274. /*explicitDeps=*/cmNinjaDeps(),
  1275. /*implicitDeps=*/cmNinjaDeps(),
  1276. /*orderOnlyDeps=*/cmNinjaDeps(),
  1277. /*variables=*/cmNinjaVars());
  1278. }
  1279. void cmGlobalNinjaGenerator::InitOutputPathPrefix()
  1280. {
  1281. this->OutputPathPrefix =
  1282. this->LocalGenerators[0]->GetMakefile()->GetSafeDefinition(
  1283. "CMAKE_NINJA_OUTPUT_PATH_PREFIX");
  1284. EnsureTrailingSlash(this->OutputPathPrefix);
  1285. }
  1286. std::string cmGlobalNinjaGenerator::NinjaOutputPath(
  1287. std::string const& path) const
  1288. {
  1289. if (!this->HasOutputPathPrefix() || cmSystemTools::FileIsFullPath(path)) {
  1290. return path;
  1291. }
  1292. return this->OutputPathPrefix + path;
  1293. }
  1294. void cmGlobalNinjaGenerator::StripNinjaOutputPathPrefixAsSuffix(
  1295. std::string& path)
  1296. {
  1297. if (path.empty()) {
  1298. return;
  1299. }
  1300. EnsureTrailingSlash(path);
  1301. cmStripSuffixIfExists(path, this->OutputPathPrefix);
  1302. }
  1303. /*
  1304. We use the following approach to support Fortran. Each target already
  1305. has a <target>.dir/ directory used to hold intermediate files for CMake.
  1306. For each target, a FortranDependInfo.json file is generated by CMake with
  1307. information about include directories, module directories, and the locations
  1308. the per-target directories for target dependencies.
  1309. Compilation of source files within a target is split into the following steps:
  1310. 1. Preprocess all sources, scan preprocessed output for module dependencies.
  1311. This step is done with independent build statements for each source,
  1312. and can therefore be done in parallel.
  1313. rule Fortran_PREPROCESS
  1314. depfile = $DEP_FILE
  1315. command = gfortran -cpp $DEFINES $INCLUDES $FLAGS -E $in -o $out &&
  1316. cmake -E cmake_ninja_depends \
  1317. --tdi=FortranDependInfo.json --pp=$out --dep=$DEP_FILE \
  1318. --obj=$OBJ_FILE --ddi=$DYNDEP_INTERMEDIATE_FILE
  1319. build src.f90-pp.f90 | src.f90-pp.f90.ddi: Fortran_PREPROCESS src.f90
  1320. OBJ_FILE = src.f90.o
  1321. DEP_FILE = src.f90-pp.f90.d
  1322. DYNDEP_INTERMEDIATE_FILE = src.f90-pp.f90.ddi
  1323. The ``cmake -E cmake_ninja_depends`` tool reads the preprocessed output
  1324. and generates the ninja depfile for preprocessor dependencies. It also
  1325. generates a "ddi" file (in a format private to CMake) that lists the
  1326. object file that compilation will produce along with the module names
  1327. it provides and/or requires. The "ddi" file is an implicit output
  1328. because it should not appear in "$out" but is generated by the rule.
  1329. 2. Consolidate the per-source module dependencies saved in the "ddi"
  1330. files from all sources to produce a ninja "dyndep" file, ``Fortran.dd``.
  1331. rule Fortran_DYNDEP
  1332. command = cmake -E cmake_ninja_dyndep \
  1333. --tdi=FortranDependInfo.json --dd=$out $in
  1334. build Fortran.dd: Fortran_DYNDEP src1.f90-pp.f90.ddi src2.f90-pp.f90.ddi
  1335. The ``cmake -E cmake_ninja_dyndep`` tool reads the "ddi" files from all
  1336. sources in the target and the ``FortranModules.json`` files from targets
  1337. on which the target depends. It computes dependency edges on compilations
  1338. that require modules to those that provide the modules. This information
  1339. is placed in the ``Fortran.dd`` file for ninja to load later. It also
  1340. writes the expected location of modules provided by this target into
  1341. ``FortranModules.json`` for use by dependent targets.
  1342. 3. Compile all sources after loading dynamically discovered dependencies
  1343. of the compilation build statements from their ``dyndep`` bindings.
  1344. rule Fortran_COMPILE
  1345. command = gfortran $INCLUDES $FLAGS -c $in -o $out
  1346. build src1.f90.o: Fortran_COMPILE src1.f90-pp.f90 || Fortran.dd
  1347. dyndep = Fortran.dd
  1348. The "dyndep" binding tells ninja to load dynamically discovered
  1349. dependency information from ``Fortran.dd``. This adds information
  1350. such as:
  1351. build src1.f90.o | mod1.mod: dyndep
  1352. restat = 1
  1353. This tells ninja that ``mod1.mod`` is an implicit output of compiling
  1354. the object file ``src1.f90.o``. The ``restat`` binding tells it that
  1355. the timestamp of the output may not always change. Additionally:
  1356. build src2.f90.o: dyndep | mod1.mod
  1357. This tells ninja that ``mod1.mod`` is a dependency of compiling the
  1358. object file ``src2.f90.o``. This ensures that ``src1.f90.o`` and
  1359. ``mod1.mod`` will always be up to date before ``src2.f90.o`` is built
  1360. (because the latter consumes the module).
  1361. */
  1362. int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg,
  1363. std::vector<std::string>::const_iterator argEnd)
  1364. {
  1365. std::string arg_tdi;
  1366. std::string arg_pp;
  1367. std::string arg_dep;
  1368. std::string arg_obj;
  1369. std::string arg_ddi;
  1370. for (std::vector<std::string>::const_iterator a = argBeg; a != argEnd; ++a) {
  1371. std::string const& arg = *a;
  1372. if (cmHasLiteralPrefix(arg, "--tdi=")) {
  1373. arg_tdi = arg.substr(6);
  1374. } else if (cmHasLiteralPrefix(arg, "--pp=")) {
  1375. arg_pp = arg.substr(5);
  1376. } else if (cmHasLiteralPrefix(arg, "--dep=")) {
  1377. arg_dep = arg.substr(6);
  1378. } else if (cmHasLiteralPrefix(arg, "--obj=")) {
  1379. arg_obj = arg.substr(6);
  1380. } else if (cmHasLiteralPrefix(arg, "--ddi=")) {
  1381. arg_ddi = arg.substr(6);
  1382. } else {
  1383. cmSystemTools::Error("-E cmake_ninja_depends unknown argument: ",
  1384. arg.c_str());
  1385. return 1;
  1386. }
  1387. }
  1388. if (arg_tdi.empty()) {
  1389. cmSystemTools::Error("-E cmake_ninja_depends requires value for --tdi=");
  1390. return 1;
  1391. }
  1392. if (arg_pp.empty()) {
  1393. cmSystemTools::Error("-E cmake_ninja_depends requires value for --pp=");
  1394. return 1;
  1395. }
  1396. if (arg_dep.empty()) {
  1397. cmSystemTools::Error("-E cmake_ninja_depends requires value for --dep=");
  1398. return 1;
  1399. }
  1400. if (arg_obj.empty()) {
  1401. cmSystemTools::Error("-E cmake_ninja_depends requires value for --obj=");
  1402. return 1;
  1403. }
  1404. if (arg_ddi.empty()) {
  1405. cmSystemTools::Error("-E cmake_ninja_depends requires value for --ddi=");
  1406. return 1;
  1407. }
  1408. std::vector<std::string> includes;
  1409. {
  1410. Json::Value tdio;
  1411. Json::Value const& tdi = tdio;
  1412. {
  1413. cmsys::ifstream tdif(arg_tdi.c_str(), std::ios::in | std::ios::binary);
  1414. Json::Reader reader;
  1415. if (!reader.parse(tdif, tdio, false)) {
  1416. cmSystemTools::Error("-E cmake_ninja_depends failed to parse ",
  1417. arg_tdi.c_str(),
  1418. reader.getFormattedErrorMessages().c_str());
  1419. return 1;
  1420. }
  1421. }
  1422. Json::Value const& tdi_include_dirs = tdi["include-dirs"];
  1423. if (tdi_include_dirs.isArray()) {
  1424. for (auto const& tdi_include_dir : tdi_include_dirs) {
  1425. includes.push_back(tdi_include_dir.asString());
  1426. }
  1427. }
  1428. }
  1429. cmFortranSourceInfo info;
  1430. std::set<std::string> defines;
  1431. cmFortranParser parser(includes, defines, info);
  1432. if (!cmFortranParser_FilePush(&parser, arg_pp.c_str())) {
  1433. cmSystemTools::Error("-E cmake_ninja_depends failed to open ",
  1434. arg_pp.c_str());
  1435. return 1;
  1436. }
  1437. if (cmFortran_yyparse(parser.Scanner) != 0) {
  1438. // Failed to parse the file.
  1439. return 1;
  1440. }
  1441. {
  1442. cmGeneratedFileStream depfile(arg_dep.c_str());
  1443. depfile << cmSystemTools::ConvertToUnixOutputPath(arg_pp) << ":";
  1444. for (std::string const& include : info.Includes) {
  1445. depfile << " \\\n " << cmSystemTools::ConvertToUnixOutputPath(include);
  1446. }
  1447. depfile << "\n";
  1448. }
  1449. Json::Value ddi(Json::objectValue);
  1450. ddi["object"] = arg_obj;
  1451. Json::Value& ddi_provides = ddi["provides"] = Json::arrayValue;
  1452. for (std::string const& provide : info.Provides) {
  1453. ddi_provides.append(provide);
  1454. }
  1455. Json::Value& ddi_requires = ddi["requires"] = Json::arrayValue;
  1456. for (std::string const& r : info.Requires) {
  1457. // Require modules not provided in the same source.
  1458. if (!info.Provides.count(r)) {
  1459. ddi_requires.append(r);
  1460. }
  1461. }
  1462. cmGeneratedFileStream ddif(arg_ddi.c_str());
  1463. ddif << ddi;
  1464. if (!ddif) {
  1465. cmSystemTools::Error("-E cmake_ninja_depends failed to write ",
  1466. arg_ddi.c_str());
  1467. return 1;
  1468. }
  1469. return 0;
  1470. }
  1471. struct cmFortranObjectInfo
  1472. {
  1473. std::string Object;
  1474. std::vector<std::string> Provides;
  1475. std::vector<std::string> Requires;
  1476. };
  1477. bool cmGlobalNinjaGenerator::WriteDyndepFile(
  1478. std::string const& dir_top_src, std::string const& dir_top_bld,
  1479. std::string const& dir_cur_src, std::string const& dir_cur_bld,
  1480. std::string const& arg_dd, std::vector<std::string> const& arg_ddis,
  1481. std::string const& module_dir,
  1482. std::vector<std::string> const& linked_target_dirs)
  1483. {
  1484. // Setup path conversions.
  1485. {
  1486. cmStateSnapshot snapshot = this->GetCMakeInstance()->GetCurrentSnapshot();
  1487. snapshot.GetDirectory().SetCurrentSource(dir_cur_src);
  1488. snapshot.GetDirectory().SetCurrentBinary(dir_cur_bld);
  1489. snapshot.GetDirectory().SetRelativePathTopSource(dir_top_src.c_str());
  1490. snapshot.GetDirectory().SetRelativePathTopBinary(dir_top_bld.c_str());
  1491. auto mfd = cm::make_unique<cmMakefile>(this, snapshot);
  1492. std::unique_ptr<cmLocalNinjaGenerator> lgd(
  1493. static_cast<cmLocalNinjaGenerator*>(
  1494. this->CreateLocalGenerator(mfd.get())));
  1495. this->Makefiles.push_back(mfd.release());
  1496. this->LocalGenerators.push_back(lgd.release());
  1497. }
  1498. std::vector<cmFortranObjectInfo> objects;
  1499. for (std::string const& arg_ddi : arg_ddis) {
  1500. // Load the ddi file and compute the module file paths it provides.
  1501. Json::Value ddio;
  1502. Json::Value const& ddi = ddio;
  1503. cmsys::ifstream ddif(arg_ddi.c_str(), std::ios::in | std::ios::binary);
  1504. Json::Reader reader;
  1505. if (!reader.parse(ddif, ddio, false)) {
  1506. cmSystemTools::Error("-E cmake_ninja_dyndep failed to parse ",
  1507. arg_ddi.c_str(),
  1508. reader.getFormattedErrorMessages().c_str());
  1509. return false;
  1510. }
  1511. cmFortranObjectInfo info;
  1512. info.Object = ddi["object"].asString();
  1513. Json::Value const& ddi_provides = ddi["provides"];
  1514. if (ddi_provides.isArray()) {
  1515. for (auto const& ddi_provide : ddi_provides) {
  1516. info.Provides.push_back(ddi_provide.asString());
  1517. }
  1518. }
  1519. Json::Value const& ddi_requires = ddi["requires"];
  1520. if (ddi_requires.isArray()) {
  1521. for (auto const& ddi_require : ddi_requires) {
  1522. info.Requires.push_back(ddi_require.asString());
  1523. }
  1524. }
  1525. objects.push_back(std::move(info));
  1526. }
  1527. // Map from module name to module file path, if known.
  1528. std::map<std::string, std::string> mod_files;
  1529. // Populate the module map with those provided by linked targets first.
  1530. for (std::string const& linked_target_dir : linked_target_dirs) {
  1531. std::string const ltmn = linked_target_dir + "/FortranModules.json";
  1532. Json::Value ltm;
  1533. cmsys::ifstream ltmf(ltmn.c_str(), std::ios::in | std::ios::binary);
  1534. Json::Reader reader;
  1535. if (ltmf && !reader.parse(ltmf, ltm, false)) {
  1536. cmSystemTools::Error("-E cmake_ninja_dyndep failed to parse ",
  1537. linked_target_dir.c_str(),
  1538. reader.getFormattedErrorMessages().c_str());
  1539. return false;
  1540. }
  1541. if (ltm.isObject()) {
  1542. for (Json::Value::iterator i = ltm.begin(); i != ltm.end(); ++i) {
  1543. mod_files[i.key().asString()] = i->asString();
  1544. }
  1545. }
  1546. }
  1547. // Extend the module map with those provided by this target.
  1548. // We do this after loading the modules provided by linked targets
  1549. // in case we have one of the same name that must be preferred.
  1550. Json::Value tm = Json::objectValue;
  1551. for (cmFortranObjectInfo const& object : objects) {
  1552. for (std::string const& p : object.Provides) {
  1553. std::string const mod = module_dir + p + ".mod";
  1554. mod_files[p] = mod;
  1555. tm[p] = mod;
  1556. }
  1557. }
  1558. cmGeneratedFileStream ddf(arg_dd.c_str());
  1559. ddf << "ninja_dyndep_version = 1.0\n";
  1560. for (cmFortranObjectInfo const& object : objects) {
  1561. std::string const ddComment;
  1562. std::string const ddRule = "dyndep";
  1563. cmNinjaDeps ddOutputs;
  1564. cmNinjaDeps ddImplicitOuts;
  1565. cmNinjaDeps ddExplicitDeps;
  1566. cmNinjaDeps ddImplicitDeps;
  1567. cmNinjaDeps ddOrderOnlyDeps;
  1568. cmNinjaVars ddVars;
  1569. ddOutputs.push_back(object.Object);
  1570. for (std::string const& p : object.Provides) {
  1571. ddImplicitOuts.push_back(this->ConvertToNinjaPath(mod_files[p]));
  1572. }
  1573. for (std::string const& r : object.Requires) {
  1574. std::map<std::string, std::string>::iterator m = mod_files.find(r);
  1575. if (m != mod_files.end()) {
  1576. ddImplicitDeps.push_back(this->ConvertToNinjaPath(m->second));
  1577. }
  1578. }
  1579. if (!object.Provides.empty()) {
  1580. ddVars["restat"] = "1";
  1581. }
  1582. this->WriteBuild(ddf, ddComment, ddRule, ddOutputs, ddImplicitOuts,
  1583. ddExplicitDeps, ddImplicitDeps, ddOrderOnlyDeps, ddVars);
  1584. }
  1585. // Store the map of modules provided by this target in a file for
  1586. // use by dependents that reference this target in linked-target-dirs.
  1587. std::string const target_mods_file =
  1588. cmSystemTools::GetFilenamePath(arg_dd) + "/FortranModules.json";
  1589. cmGeneratedFileStream tmf(target_mods_file.c_str());
  1590. tmf << tm;
  1591. return true;
  1592. }
  1593. int cmcmd_cmake_ninja_dyndep(std::vector<std::string>::const_iterator argBeg,
  1594. std::vector<std::string>::const_iterator argEnd)
  1595. {
  1596. std::vector<std::string> arg_full =
  1597. cmSystemTools::HandleResponseFile(argBeg, argEnd);
  1598. std::string arg_dd;
  1599. std::string arg_tdi;
  1600. std::vector<std::string> arg_ddis;
  1601. for (std::string const& arg : arg_full) {
  1602. if (cmHasLiteralPrefix(arg, "--tdi=")) {
  1603. arg_tdi = arg.substr(6);
  1604. } else if (cmHasLiteralPrefix(arg, "--dd=")) {
  1605. arg_dd = arg.substr(5);
  1606. } else if (!cmHasLiteralPrefix(arg, "--") &&
  1607. cmHasLiteralSuffix(arg, ".ddi")) {
  1608. arg_ddis.push_back(arg);
  1609. } else {
  1610. cmSystemTools::Error("-E cmake_ninja_dyndep unknown argument: ",
  1611. arg.c_str());
  1612. return 1;
  1613. }
  1614. }
  1615. if (arg_tdi.empty()) {
  1616. cmSystemTools::Error("-E cmake_ninja_dyndep requires value for --tdi=");
  1617. return 1;
  1618. }
  1619. if (arg_dd.empty()) {
  1620. cmSystemTools::Error("-E cmake_ninja_dyndep requires value for --dd=");
  1621. return 1;
  1622. }
  1623. Json::Value tdio;
  1624. Json::Value const& tdi = tdio;
  1625. {
  1626. cmsys::ifstream tdif(arg_tdi.c_str(), std::ios::in | std::ios::binary);
  1627. Json::Reader reader;
  1628. if (!reader.parse(tdif, tdio, false)) {
  1629. cmSystemTools::Error("-E cmake_ninja_dyndep failed to parse ",
  1630. arg_tdi.c_str(),
  1631. reader.getFormattedErrorMessages().c_str());
  1632. return 1;
  1633. }
  1634. }
  1635. std::string const dir_cur_bld = tdi["dir-cur-bld"].asString();
  1636. std::string const dir_cur_src = tdi["dir-cur-src"].asString();
  1637. std::string const dir_top_bld = tdi["dir-top-bld"].asString();
  1638. std::string const dir_top_src = tdi["dir-top-src"].asString();
  1639. std::string module_dir = tdi["module-dir"].asString();
  1640. if (!module_dir.empty()) {
  1641. module_dir += "/";
  1642. }
  1643. std::vector<std::string> linked_target_dirs;
  1644. Json::Value const& tdi_linked_target_dirs = tdi["linked-target-dirs"];
  1645. if (tdi_linked_target_dirs.isArray()) {
  1646. for (auto const& tdi_linked_target_dir : tdi_linked_target_dirs) {
  1647. linked_target_dirs.push_back(tdi_linked_target_dir.asString());
  1648. }
  1649. }
  1650. cmake cm(cmake::RoleInternal);
  1651. cm.SetHomeDirectory(dir_top_src);
  1652. cm.SetHomeOutputDirectory(dir_top_bld);
  1653. std::unique_ptr<cmGlobalNinjaGenerator> ggd(
  1654. static_cast<cmGlobalNinjaGenerator*>(cm.CreateGlobalGenerator("Ninja")));
  1655. if (!ggd.get() ||
  1656. !ggd->WriteDyndepFile(dir_top_src, dir_top_bld, dir_cur_src, dir_cur_bld,
  1657. arg_dd, arg_ddis, module_dir,
  1658. linked_target_dirs)) {
  1659. return 1;
  1660. }
  1661. return 0;
  1662. }