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