cmGlobalNinjaGenerator.cxx 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957
  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. , NinjaSupportsManifestRestat(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. this->NinjaSupportsManifestRestat = !cmSystemTools::VersionCompare(
  529. cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
  530. RequiredNinjaVersionForManifestRestat().c_str());
  531. {
  532. // Our ninja branch adds ".dyndep-#" to its version number,
  533. // where '#' is a feature-specific version number. Extract it.
  534. static std::string const k_DYNDEP_ = ".dyndep-";
  535. std::string::size_type pos = this->NinjaVersion.find(k_DYNDEP_);
  536. if (pos != std::string::npos) {
  537. const char* fv = this->NinjaVersion.c_str() + pos + k_DYNDEP_.size();
  538. cmSystemTools::StringToULong(fv, &this->NinjaSupportsDyndeps);
  539. }
  540. }
  541. }
  542. bool cmGlobalNinjaGenerator::CheckLanguages(
  543. std::vector<std::string> const& languages, cmMakefile* mf) const
  544. {
  545. if (std::find(languages.begin(), languages.end(), "Fortran") !=
  546. languages.end()) {
  547. return this->CheckFortran(mf);
  548. }
  549. return true;
  550. }
  551. bool cmGlobalNinjaGenerator::CheckFortran(cmMakefile* mf) const
  552. {
  553. if (this->NinjaSupportsDyndeps == 1) {
  554. return true;
  555. }
  556. std::ostringstream e;
  557. if (this->NinjaSupportsDyndeps == 0) {
  558. /* clang-format off */
  559. e <<
  560. "The Ninja generator does not support Fortran using Ninja version\n"
  561. " " + this->NinjaVersion + "\n"
  562. "due to lack of required features. "
  563. "Kitware has implemented the required features but as of this version "
  564. "of CMake they have not been integrated to upstream ninja. "
  565. "Pending integration, Kitware maintains a branch at:\n"
  566. " https://github.com/Kitware/ninja/tree/features-for-fortran#readme\n"
  567. "with the required features. "
  568. "One may build ninja from that branch to get support for Fortran."
  569. ;
  570. /* clang-format on */
  571. } else {
  572. /* clang-format off */
  573. e <<
  574. "The Ninja generator in this version of CMake does not support Fortran "
  575. "using Ninja version\n"
  576. " " + this->NinjaVersion + "\n"
  577. "because its 'dyndep' feature version is " <<
  578. this->NinjaSupportsDyndeps << ". "
  579. "This version of CMake is aware only of 'dyndep' feature version 1."
  580. ;
  581. /* clang-format on */
  582. }
  583. mf->IssueMessage(cmake::FATAL_ERROR, e.str());
  584. cmSystemTools::SetFatalErrorOccured();
  585. return false;
  586. }
  587. void cmGlobalNinjaGenerator::EnableLanguage(
  588. std::vector<std::string> const& langs, cmMakefile* mf, bool optional)
  589. {
  590. this->cmGlobalGenerator::EnableLanguage(langs, mf, optional);
  591. for (std::string const& l : langs) {
  592. if (l == "NONE") {
  593. continue;
  594. }
  595. this->ResolveLanguageCompiler(l, mf, optional);
  596. }
  597. #ifdef _WIN32
  598. if (strcmp(mf->GetSafeDefinition("CMAKE_C_SIMULATE_ID"), "MSVC") != 0 &&
  599. strcmp(mf->GetSafeDefinition("CMAKE_CXX_SIMULATE_ID"), "MSVC") != 0 &&
  600. (mf->IsOn("CMAKE_COMPILER_IS_MINGW") ||
  601. strcmp(mf->GetSafeDefinition("CMAKE_C_COMPILER_ID"), "GNU") == 0 ||
  602. strcmp(mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID"), "GNU") == 0 ||
  603. strcmp(mf->GetSafeDefinition("CMAKE_C_COMPILER_ID"), "Clang") == 0 ||
  604. strcmp(mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID"), "Clang") == 0)) {
  605. this->UsingGCCOnWindows = true;
  606. }
  607. #endif
  608. }
  609. // Implemented by:
  610. // cmGlobalUnixMakefileGenerator3
  611. // cmGlobalGhsMultiGenerator
  612. // cmGlobalVisualStudio10Generator
  613. // cmGlobalVisualStudio7Generator
  614. // cmGlobalXCodeGenerator
  615. // Called by:
  616. // cmGlobalGenerator::Build()
  617. void cmGlobalNinjaGenerator::GenerateBuildCommand(
  618. std::vector<std::string>& makeCommand, const std::string& makeProgram,
  619. const std::string& /*projectName*/, const std::string& /*projectDir*/,
  620. const std::string& targetName, const std::string& /*config*/, bool /*fast*/,
  621. bool verbose, std::vector<std::string> const& makeOptions)
  622. {
  623. makeCommand.push_back(this->SelectMakeProgram(makeProgram));
  624. if (verbose) {
  625. makeCommand.push_back("-v");
  626. }
  627. makeCommand.insert(makeCommand.end(), makeOptions.begin(),
  628. makeOptions.end());
  629. if (!targetName.empty()) {
  630. if (targetName == "clean") {
  631. makeCommand.push_back("-t");
  632. makeCommand.push_back("clean");
  633. } else {
  634. makeCommand.push_back(targetName);
  635. }
  636. }
  637. }
  638. // Non-virtual public methods.
  639. void cmGlobalNinjaGenerator::AddRule(
  640. const std::string& name, const std::string& command,
  641. const std::string& description, const std::string& comment,
  642. const std::string& depfile, const std::string& deptype,
  643. const std::string& rspfile, const std::string& rspcontent,
  644. const std::string& restat, bool generator)
  645. {
  646. // Do not add the same rule twice.
  647. if (this->HasRule(name)) {
  648. return;
  649. }
  650. this->Rules.insert(name);
  651. cmGlobalNinjaGenerator::WriteRule(*this->RulesFileStream, name, command,
  652. description, comment, depfile, deptype,
  653. rspfile, rspcontent, restat, generator);
  654. this->RuleCmdLength[name] = static_cast<int>(command.size());
  655. }
  656. bool cmGlobalNinjaGenerator::HasRule(const std::string& name)
  657. {
  658. RulesSetType::const_iterator rule = this->Rules.find(name);
  659. return (rule != this->Rules.end());
  660. }
  661. // Private virtual overrides
  662. std::string cmGlobalNinjaGenerator::GetEditCacheCommand() const
  663. {
  664. // Ninja by design does not run interactive tools in the terminal,
  665. // so our only choice is cmake-gui.
  666. return cmSystemTools::GetCMakeGUICommand();
  667. }
  668. void cmGlobalNinjaGenerator::ComputeTargetObjectDirectory(
  669. cmGeneratorTarget* gt) const
  670. {
  671. // Compute full path to object file directory for this target.
  672. std::string dir;
  673. dir += gt->LocalGenerator->GetCurrentBinaryDirectory();
  674. dir += "/";
  675. dir += gt->LocalGenerator->GetTargetDirectory(gt);
  676. dir += "/";
  677. gt->ObjectDirectory = dir;
  678. }
  679. // Private methods
  680. void cmGlobalNinjaGenerator::OpenBuildFileStream()
  681. {
  682. // Compute Ninja's build file path.
  683. std::string buildFilePath =
  684. this->GetCMakeInstance()->GetHomeOutputDirectory();
  685. buildFilePath += "/";
  686. buildFilePath += cmGlobalNinjaGenerator::NINJA_BUILD_FILE;
  687. // Get a stream where to generate things.
  688. if (!this->BuildFileStream) {
  689. this->BuildFileStream = new cmGeneratedFileStream(
  690. buildFilePath.c_str(), false, this->GetMakefileEncoding());
  691. if (!this->BuildFileStream) {
  692. // An error message is generated by the constructor if it cannot
  693. // open the file.
  694. return;
  695. }
  696. }
  697. // Write the do not edit header.
  698. this->WriteDisclaimer(*this->BuildFileStream);
  699. // Write a comment about this file.
  700. *this->BuildFileStream
  701. << "# This file contains all the build statements describing the\n"
  702. << "# compilation DAG.\n\n";
  703. }
  704. void cmGlobalNinjaGenerator::CloseBuildFileStream()
  705. {
  706. if (this->BuildFileStream) {
  707. delete this->BuildFileStream;
  708. this->BuildFileStream = nullptr;
  709. } else {
  710. cmSystemTools::Error("Build file stream was not open.");
  711. }
  712. }
  713. void cmGlobalNinjaGenerator::OpenRulesFileStream()
  714. {
  715. // Compute Ninja's build file path.
  716. std::string rulesFilePath =
  717. this->GetCMakeInstance()->GetHomeOutputDirectory();
  718. rulesFilePath += "/";
  719. rulesFilePath += cmGlobalNinjaGenerator::NINJA_RULES_FILE;
  720. // Get a stream where to generate things.
  721. if (!this->RulesFileStream) {
  722. this->RulesFileStream = new cmGeneratedFileStream(
  723. rulesFilePath.c_str(), false, this->GetMakefileEncoding());
  724. if (!this->RulesFileStream) {
  725. // An error message is generated by the constructor if it cannot
  726. // open the file.
  727. return;
  728. }
  729. }
  730. // Write the do not edit header.
  731. this->WriteDisclaimer(*this->RulesFileStream);
  732. // Write comment about this file.
  733. /* clang-format off */
  734. *this->RulesFileStream
  735. << "# This file contains all the rules used to get the outputs files\n"
  736. << "# built from the input files.\n"
  737. << "# It is included in the main '" << NINJA_BUILD_FILE << "'.\n\n"
  738. ;
  739. /* clang-format on */
  740. }
  741. void cmGlobalNinjaGenerator::CloseRulesFileStream()
  742. {
  743. if (this->RulesFileStream) {
  744. delete this->RulesFileStream;
  745. this->RulesFileStream = nullptr;
  746. } else {
  747. cmSystemTools::Error("Rules file stream was not open.");
  748. }
  749. }
  750. static void EnsureTrailingSlash(std::string& path)
  751. {
  752. if (path.empty()) {
  753. return;
  754. }
  755. std::string::value_type last = path[path.size() - 1];
  756. #ifdef _WIN32
  757. if (last != '\\') {
  758. path += '\\';
  759. }
  760. #else
  761. if (last != '/') {
  762. path += '/';
  763. }
  764. #endif
  765. }
  766. std::string const& cmGlobalNinjaGenerator::ConvertToNinjaPath(
  767. const std::string& path) const
  768. {
  769. auto const f = ConvertToNinjaPathCache.find(path);
  770. if (f != ConvertToNinjaPathCache.end()) {
  771. return f->second;
  772. }
  773. cmLocalNinjaGenerator* ng =
  774. static_cast<cmLocalNinjaGenerator*>(this->LocalGenerators[0]);
  775. std::string const& bin_dir = ng->GetState()->GetBinaryDirectory();
  776. std::string convPath = ng->ConvertToRelativePath(bin_dir, path);
  777. convPath = this->NinjaOutputPath(convPath);
  778. #ifdef _WIN32
  779. std::replace(convPath.begin(), convPath.end(), '/', '\\');
  780. #endif
  781. return ConvertToNinjaPathCache.emplace(path, std::move(convPath))
  782. .first->second;
  783. }
  784. void cmGlobalNinjaGenerator::AddCXXCompileCommand(
  785. const std::string& commandLine, const std::string& sourceFile)
  786. {
  787. // Compute Ninja's build file path.
  788. std::string buildFileDir =
  789. this->GetCMakeInstance()->GetHomeOutputDirectory();
  790. if (!this->CompileCommandsStream) {
  791. std::string buildFilePath = buildFileDir + "/compile_commands.json";
  792. if (this->ComputingUnknownDependencies) {
  793. this->CombinedBuildOutputs.insert(
  794. this->NinjaOutputPath("compile_commands.json"));
  795. }
  796. // Get a stream where to generate things.
  797. this->CompileCommandsStream =
  798. new cmGeneratedFileStream(buildFilePath.c_str());
  799. *this->CompileCommandsStream << "[";
  800. } else {
  801. *this->CompileCommandsStream << "," << std::endl;
  802. }
  803. std::string sourceFileName = sourceFile;
  804. if (!cmSystemTools::FileIsFullPath(sourceFileName)) {
  805. sourceFileName = cmSystemTools::CollapseFullPath(
  806. sourceFileName, this->GetCMakeInstance()->GetHomeOutputDirectory());
  807. }
  808. /* clang-format off */
  809. *this->CompileCommandsStream << "\n{\n"
  810. << " \"directory\": \""
  811. << cmGlobalGenerator::EscapeJSON(buildFileDir) << "\",\n"
  812. << " \"command\": \""
  813. << cmGlobalGenerator::EscapeJSON(commandLine) << "\",\n"
  814. << " \"file\": \""
  815. << cmGlobalGenerator::EscapeJSON(sourceFileName) << "\"\n"
  816. << "}";
  817. /* clang-format on */
  818. }
  819. void cmGlobalNinjaGenerator::CloseCompileCommandsStream()
  820. {
  821. if (this->CompileCommandsStream) {
  822. *this->CompileCommandsStream << "\n]";
  823. delete this->CompileCommandsStream;
  824. this->CompileCommandsStream = nullptr;
  825. }
  826. }
  827. void cmGlobalNinjaGenerator::WriteDisclaimer(std::ostream& os)
  828. {
  829. os << "# CMAKE generated file: DO NOT EDIT!\n"
  830. << "# Generated by \"" << this->GetName() << "\""
  831. << " Generator, CMake Version " << cmVersion::GetMajorVersion() << "."
  832. << cmVersion::GetMinorVersion() << "\n\n";
  833. }
  834. void cmGlobalNinjaGenerator::AddDependencyToAll(cmGeneratorTarget* target)
  835. {
  836. this->AppendTargetOutputs(target, this->AllDependencies);
  837. }
  838. void cmGlobalNinjaGenerator::AddDependencyToAll(const std::string& input)
  839. {
  840. this->AllDependencies.push_back(input);
  841. }
  842. void cmGlobalNinjaGenerator::WriteAssumedSourceDependencies()
  843. {
  844. for (auto const& asd : this->AssumedSourceDependencies) {
  845. cmNinjaDeps deps;
  846. std::copy(asd.second.begin(), asd.second.end(), std::back_inserter(deps));
  847. WriteCustomCommandBuild(/*command=*/"", /*description=*/"",
  848. "Assume dependencies for generated source file.",
  849. /*depfile*/ "", /*uses_terminal*/ false,
  850. /*restat*/ true, cmNinjaDeps(1, asd.first), deps);
  851. }
  852. }
  853. std::string OrderDependsTargetForTarget(cmGeneratorTarget const* target)
  854. {
  855. return "cmake_object_order_depends_target_" + target->GetName();
  856. }
  857. void cmGlobalNinjaGenerator::AppendTargetOutputs(
  858. cmGeneratorTarget const* target, cmNinjaDeps& outputs,
  859. cmNinjaTargetDepends depends)
  860. {
  861. std::string configName =
  862. target->Target->GetMakefile()->GetSafeDefinition("CMAKE_BUILD_TYPE");
  863. // for frameworks, we want the real name, not smple name
  864. // frameworks always appear versioned, and the build.ninja
  865. // will always attempt to manage symbolic links instead
  866. // of letting cmOSXBundleGenerator do it.
  867. bool realname = target->IsFrameworkOnApple();
  868. switch (target->GetType()) {
  869. case cmStateEnums::SHARED_LIBRARY:
  870. case cmStateEnums::STATIC_LIBRARY:
  871. case cmStateEnums::MODULE_LIBRARY: {
  872. if (depends == DependOnTargetOrdering) {
  873. outputs.push_back(OrderDependsTargetForTarget(target));
  874. break;
  875. }
  876. }
  877. // FALLTHROUGH
  878. case cmStateEnums::EXECUTABLE: {
  879. outputs.push_back(this->ConvertToNinjaPath(target->GetFullPath(
  880. configName, cmStateEnums::RuntimeBinaryArtifact, realname)));
  881. break;
  882. }
  883. case cmStateEnums::OBJECT_LIBRARY: {
  884. if (depends == DependOnTargetOrdering) {
  885. outputs.push_back(OrderDependsTargetForTarget(target));
  886. break;
  887. }
  888. }
  889. // FALLTHROUGH
  890. case cmStateEnums::GLOBAL_TARGET:
  891. case cmStateEnums::UTILITY: {
  892. std::string path =
  893. target->GetLocalGenerator()->GetCurrentBinaryDirectory() +
  894. std::string("/") + target->GetName();
  895. outputs.push_back(this->ConvertToNinjaPath(path));
  896. break;
  897. }
  898. default:
  899. return;
  900. }
  901. }
  902. void cmGlobalNinjaGenerator::AppendTargetDepends(
  903. cmGeneratorTarget const* target, cmNinjaDeps& outputs,
  904. cmNinjaTargetDepends depends)
  905. {
  906. if (target->GetType() == cmStateEnums::GLOBAL_TARGET) {
  907. // These depend only on other CMake-provided targets, e.g. "all".
  908. std::set<std::string> const& utils = target->GetUtilities();
  909. for (std::string const& util : utils) {
  910. std::string d =
  911. target->GetLocalGenerator()->GetCurrentBinaryDirectory() +
  912. std::string("/") + util;
  913. outputs.push_back(this->ConvertToNinjaPath(d));
  914. }
  915. } else {
  916. cmNinjaDeps outs;
  917. cmTargetDependSet const& targetDeps = this->GetTargetDirectDepends(target);
  918. for (cmTargetDepend const& targetDep : targetDeps) {
  919. if (targetDep->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  920. continue;
  921. }
  922. this->AppendTargetOutputs(targetDep, outs, depends);
  923. }
  924. std::sort(outs.begin(), outs.end());
  925. outputs.insert(outputs.end(), outs.begin(), outs.end());
  926. }
  927. }
  928. void cmGlobalNinjaGenerator::AppendTargetDependsClosure(
  929. cmGeneratorTarget const* target, cmNinjaDeps& outputs)
  930. {
  931. cmNinjaOuts outs;
  932. this->AppendTargetDependsClosure(target, outs, true);
  933. outputs.insert(outputs.end(), outs.begin(), outs.end());
  934. }
  935. void cmGlobalNinjaGenerator::AppendTargetDependsClosure(
  936. cmGeneratorTarget const* target, cmNinjaOuts& outputs, bool omit_self)
  937. {
  938. // try to locate the target in the cache
  939. auto find = this->TargetDependsClosures.lower_bound(target);
  940. if (find == this->TargetDependsClosures.end() || find->first != target) {
  941. // We now calculate the closure outputs by inspecting the dependent
  942. // targets recursively.
  943. // For that we have to distinguish between a local result set that is only
  944. // relevant for filling the cache entries properly isolated and a global
  945. // result set that is relevant for the result of the top level call to
  946. // AppendTargetDependsClosure.
  947. auto const& targetDeps = this->GetTargetDirectDepends(target);
  948. cmNinjaOuts this_outs; // this will be the new cache entry
  949. for (auto const& dep_target : targetDeps) {
  950. if (dep_target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  951. continue;
  952. }
  953. // Collect the dependent targets for _this_ target
  954. this->AppendTargetDependsClosure(dep_target, this_outs, false);
  955. }
  956. find = this->TargetDependsClosures.emplace_hint(find, target,
  957. std::move(this_outs));
  958. }
  959. // now fill the outputs of the final result from the newly generated cache
  960. // entry
  961. outputs.insert(find->second.begin(), find->second.end());
  962. // finally generate the outputs of the target itself, if applicable
  963. cmNinjaDeps outs;
  964. if (!omit_self) {
  965. this->AppendTargetOutputs(target, outs);
  966. }
  967. outputs.insert(outs.begin(), outs.end());
  968. }
  969. void cmGlobalNinjaGenerator::AddTargetAlias(const std::string& alias,
  970. cmGeneratorTarget* target)
  971. {
  972. std::string buildAlias = this->NinjaOutputPath(alias);
  973. cmNinjaDeps outputs;
  974. this->AppendTargetOutputs(target, outputs);
  975. // Mark the target's outputs as ambiguous to ensure that no other target uses
  976. // the output as an alias.
  977. for (std::string const& output : outputs) {
  978. TargetAliases[output] = nullptr;
  979. }
  980. // Insert the alias into the map. If the alias was already present in the
  981. // map and referred to another target, mark it as ambiguous.
  982. std::pair<TargetAliasMap::iterator, bool> newAlias =
  983. TargetAliases.insert(std::make_pair(buildAlias, target));
  984. if (newAlias.second && newAlias.first->second != target) {
  985. newAlias.first->second = nullptr;
  986. }
  987. }
  988. void cmGlobalNinjaGenerator::WriteTargetAliases(std::ostream& os)
  989. {
  990. cmGlobalNinjaGenerator::WriteDivider(os);
  991. os << "# Target aliases.\n\n";
  992. for (auto const& ta : TargetAliases) {
  993. // Don't write ambiguous aliases.
  994. if (!ta.second) {
  995. continue;
  996. }
  997. cmNinjaDeps deps;
  998. this->AppendTargetOutputs(ta.second, deps);
  999. this->WritePhonyBuild(os, "", cmNinjaDeps(1, ta.first), deps);
  1000. }
  1001. }
  1002. void cmGlobalNinjaGenerator::WriteFolderTargets(std::ostream& os)
  1003. {
  1004. cmGlobalNinjaGenerator::WriteDivider(os);
  1005. os << "# Folder targets.\n\n";
  1006. std::map<std::string, cmNinjaDeps> targetsPerFolder;
  1007. for (cmLocalGenerator const* lg : this->LocalGenerators) {
  1008. const std::string currentBinaryFolder(
  1009. lg->GetStateSnapshot().GetDirectory().GetCurrentBinary());
  1010. // The directory-level rule should depend on the target-level rules
  1011. // for all targets in the directory.
  1012. targetsPerFolder[currentBinaryFolder] = cmNinjaDeps();
  1013. for (auto gt : lg->GetGeneratorTargets()) {
  1014. cmStateEnums::TargetType const type = gt->GetType();
  1015. if ((type == cmStateEnums::EXECUTABLE ||
  1016. type == cmStateEnums::STATIC_LIBRARY ||
  1017. type == cmStateEnums::SHARED_LIBRARY ||
  1018. type == cmStateEnums::MODULE_LIBRARY ||
  1019. type == cmStateEnums::OBJECT_LIBRARY ||
  1020. type == cmStateEnums::UTILITY) &&
  1021. !gt->GetPropertyAsBool("EXCLUDE_FROM_ALL")) {
  1022. targetsPerFolder[currentBinaryFolder].push_back(gt->GetName());
  1023. }
  1024. }
  1025. // The directory-level rule should depend on the directory-level
  1026. // rules of the subdirectories.
  1027. std::vector<cmStateSnapshot> const& children =
  1028. lg->GetStateSnapshot().GetChildren();
  1029. for (cmStateSnapshot const& state : children) {
  1030. std::string const currentBinaryDir =
  1031. state.GetDirectory().GetCurrentBinary();
  1032. targetsPerFolder[currentBinaryFolder].push_back(
  1033. this->ConvertToNinjaPath(currentBinaryDir + "/all"));
  1034. }
  1035. }
  1036. std::string const rootBinaryDir =
  1037. this->LocalGenerators[0]->GetBinaryDirectory();
  1038. for (auto const& it : targetsPerFolder) {
  1039. cmGlobalNinjaGenerator::WriteDivider(os);
  1040. std::string const& currentBinaryDir = it.first;
  1041. // Do not generate a rule for the root binary dir.
  1042. if (rootBinaryDir.length() >= currentBinaryDir.length()) {
  1043. continue;
  1044. }
  1045. std::string const comment = "Folder: " + currentBinaryDir;
  1046. cmNinjaDeps output(1);
  1047. output.push_back(this->ConvertToNinjaPath(currentBinaryDir + "/all"));
  1048. this->WritePhonyBuild(os, comment, output, it.second);
  1049. }
  1050. }
  1051. void cmGlobalNinjaGenerator::WriteUnknownExplicitDependencies(std::ostream& os)
  1052. {
  1053. if (!this->ComputingUnknownDependencies) {
  1054. return;
  1055. }
  1056. // We need to collect the set of known build outputs.
  1057. // Start with those generated by WriteBuild calls.
  1058. // No other method needs this so we can take ownership
  1059. // of the set locally and throw it out when we are done.
  1060. std::set<std::string> knownDependencies;
  1061. knownDependencies.swap(this->CombinedBuildOutputs);
  1062. // now write out the unknown explicit dependencies.
  1063. // union the configured files, evaluations files and the
  1064. // CombinedBuildOutputs,
  1065. // and then difference with CombinedExplicitDependencies to find the explicit
  1066. // dependencies that we have no rule for
  1067. cmGlobalNinjaGenerator::WriteDivider(os);
  1068. /* clang-format off */
  1069. os << "# Unknown Build Time Dependencies.\n"
  1070. << "# Tell Ninja that they may appear as side effects of build rules\n"
  1071. << "# otherwise ordered by order-only dependencies.\n\n";
  1072. /* clang-format on */
  1073. // get the list of files that cmake itself has generated as a
  1074. // product of configuration.
  1075. for (cmLocalGenerator* lg : this->LocalGenerators) {
  1076. // get the vector of files created by this makefile and convert them
  1077. // to ninja paths, which are all relative in respect to the build directory
  1078. const std::vector<std::string>& files =
  1079. lg->GetMakefile()->GetOutputFiles();
  1080. for (std::string const& file : files) {
  1081. knownDependencies.insert(this->ConvertToNinjaPath(file));
  1082. }
  1083. if (!this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION")) {
  1084. // get list files which are implicit dependencies as well and will be
  1085. // phony for rebuild manifest
  1086. std::vector<std::string> const& lf = lg->GetMakefile()->GetListFiles();
  1087. for (std::string const& j : lf) {
  1088. knownDependencies.insert(this->ConvertToNinjaPath(j));
  1089. }
  1090. }
  1091. std::vector<cmGeneratorExpressionEvaluationFile*> const& ef =
  1092. lg->GetMakefile()->GetEvaluationFiles();
  1093. for (cmGeneratorExpressionEvaluationFile* li : ef) {
  1094. // get all the files created by generator expressions and convert them
  1095. // to ninja paths
  1096. std::vector<std::string> evaluationFiles = li->GetFiles();
  1097. for (std::string const& evaluationFile : evaluationFiles) {
  1098. knownDependencies.insert(this->ConvertToNinjaPath(evaluationFile));
  1099. }
  1100. }
  1101. }
  1102. knownDependencies.insert(this->CMakeCacheFile);
  1103. for (auto const& ta : this->TargetAliases) {
  1104. knownDependencies.insert(this->ConvertToNinjaPath(ta.first));
  1105. }
  1106. // remove all source files we know will exist.
  1107. for (auto const& i : this->AssumedSourceDependencies) {
  1108. knownDependencies.insert(this->ConvertToNinjaPath(i.first));
  1109. }
  1110. // now we difference with CombinedCustomCommandExplicitDependencies to find
  1111. // the list of items we know nothing about.
  1112. // We have encoded all the paths in CombinedCustomCommandExplicitDependencies
  1113. // and knownDependencies so no matter if unix or windows paths they
  1114. // should all match now.
  1115. std::vector<std::string> unknownExplicitDepends;
  1116. this->CombinedCustomCommandExplicitDependencies.erase(this->TargetAll);
  1117. std::set_difference(this->CombinedCustomCommandExplicitDependencies.begin(),
  1118. this->CombinedCustomCommandExplicitDependencies.end(),
  1119. knownDependencies.begin(), knownDependencies.end(),
  1120. std::back_inserter(unknownExplicitDepends));
  1121. std::string const rootBuildDirectory =
  1122. this->GetCMakeInstance()->GetHomeOutputDirectory();
  1123. bool const inSourceBuild =
  1124. (rootBuildDirectory == this->GetCMakeInstance()->GetHomeDirectory());
  1125. std::vector<std::string> warnExplicitDepends;
  1126. for (std::string const& i : unknownExplicitDepends) {
  1127. // verify the file is in the build directory
  1128. std::string const absDepPath =
  1129. cmSystemTools::CollapseFullPath(i, rootBuildDirectory.c_str());
  1130. bool const inBuildDir =
  1131. cmSystemTools::IsSubDirectory(absDepPath, rootBuildDirectory);
  1132. if (inBuildDir) {
  1133. cmNinjaDeps deps(1, i);
  1134. this->WritePhonyBuild(os, "", deps, cmNinjaDeps());
  1135. if (this->PolicyCMP0058 == cmPolicies::WARN && !inSourceBuild &&
  1136. warnExplicitDepends.size() < 10) {
  1137. warnExplicitDepends.push_back(i);
  1138. }
  1139. }
  1140. }
  1141. if (!warnExplicitDepends.empty()) {
  1142. std::ostringstream w;
  1143. /* clang-format off */
  1144. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0058) << "\n"
  1145. "This project specifies custom command DEPENDS on files "
  1146. "in the build tree that are not specified as the OUTPUT or "
  1147. "BYPRODUCTS of any add_custom_command or add_custom_target:\n"
  1148. " " << cmJoin(warnExplicitDepends, "\n ") <<
  1149. "\n"
  1150. "For compatibility with versions of CMake that did not have "
  1151. "the BYPRODUCTS option, CMake is generating phony rules for "
  1152. "such files to convince 'ninja' to build."
  1153. "\n"
  1154. "Project authors should add the missing BYPRODUCTS or OUTPUT "
  1155. "options to the custom commands that produce these files."
  1156. ;
  1157. /* clang-format on */
  1158. this->GetCMakeInstance()->IssueMessage(cmake::AUTHOR_WARNING, w.str());
  1159. }
  1160. }
  1161. void cmGlobalNinjaGenerator::WriteBuiltinTargets(std::ostream& os)
  1162. {
  1163. // Write headers.
  1164. cmGlobalNinjaGenerator::WriteDivider(os);
  1165. os << "# Built-in targets\n\n";
  1166. this->WriteTargetAll(os);
  1167. this->WriteTargetRebuildManifest(os);
  1168. this->WriteTargetClean(os);
  1169. this->WriteTargetHelp(os);
  1170. }
  1171. void cmGlobalNinjaGenerator::WriteTargetAll(std::ostream& os)
  1172. {
  1173. cmNinjaDeps outputs;
  1174. outputs.push_back(this->TargetAll);
  1175. this->WritePhonyBuild(os, "The main all target.", outputs,
  1176. this->AllDependencies);
  1177. if (!this->HasOutputPathPrefix()) {
  1178. cmGlobalNinjaGenerator::WriteDefault(os, outputs,
  1179. "Make the all target the default.");
  1180. }
  1181. }
  1182. void cmGlobalNinjaGenerator::WriteTargetRebuildManifest(std::ostream& os)
  1183. {
  1184. if (this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION")) {
  1185. return;
  1186. }
  1187. cmLocalGenerator* lg = this->LocalGenerators[0];
  1188. std::ostringstream cmd;
  1189. cmd << lg->ConvertToOutputFormat(cmSystemTools::GetCMakeCommand(),
  1190. cmOutputConverter::SHELL)
  1191. << " -H"
  1192. << lg->ConvertToOutputFormat(lg->GetSourceDirectory(),
  1193. cmOutputConverter::SHELL)
  1194. << " -B"
  1195. << lg->ConvertToOutputFormat(lg->GetBinaryDirectory(),
  1196. cmOutputConverter::SHELL);
  1197. WriteRule(*this->RulesFileStream, "RERUN_CMAKE", cmd.str(),
  1198. "Re-running CMake...", "Rule for re-running cmake.",
  1199. /*depfile=*/"",
  1200. /*deptype=*/"",
  1201. /*rspfile=*/"",
  1202. /*rspcontent*/ "",
  1203. /*restat=*/"",
  1204. /*generator=*/true);
  1205. cmNinjaDeps implicitDeps;
  1206. cmNinjaDeps explicitDeps;
  1207. for (cmLocalGenerator* localGen : this->LocalGenerators) {
  1208. std::vector<std::string> const& lf =
  1209. localGen->GetMakefile()->GetListFiles();
  1210. for (std::string const& fi : lf) {
  1211. implicitDeps.push_back(this->ConvertToNinjaPath(fi));
  1212. }
  1213. }
  1214. implicitDeps.push_back(this->CMakeCacheFile);
  1215. cmNinjaVars variables;
  1216. // Use 'console' pool to get non buffered output of the CMake re-run call
  1217. // Available since Ninja 1.5
  1218. if (SupportsConsolePool()) {
  1219. variables["pool"] = "console";
  1220. }
  1221. cmake* cm = this->GetCMakeInstance();
  1222. if (this->SupportsManifestRestat() && cm->DoWriteGlobVerifyTarget()) {
  1223. std::ostringstream verify_cmd;
  1224. verify_cmd << lg->ConvertToOutputFormat(cmSystemTools::GetCMakeCommand(),
  1225. cmOutputConverter::SHELL)
  1226. << " -P "
  1227. << lg->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
  1228. cmOutputConverter::SHELL);
  1229. WriteRule(*this->RulesFileStream, "VERIFY_GLOBS", verify_cmd.str(),
  1230. "Re-checking globbed directories...",
  1231. "Rule for re-checking globbed directories.",
  1232. /*depfile=*/"",
  1233. /*deptype=*/"",
  1234. /*rspfile=*/"",
  1235. /*rspcontent*/ "",
  1236. /*restat=*/"",
  1237. /*generator=*/true);
  1238. std::string verifyForce = cm->GetGlobVerifyScript() + "_force";
  1239. cmNinjaDeps verifyForceDeps(1, this->NinjaOutputPath(verifyForce));
  1240. this->WritePhonyBuild(os, "Phony target to force glob verification run.",
  1241. verifyForceDeps, cmNinjaDeps());
  1242. variables["restat"] = "1";
  1243. std::string const verifyScriptFile =
  1244. this->NinjaOutputPath(cm->GetGlobVerifyScript());
  1245. std::string const verifyStampFile =
  1246. this->NinjaOutputPath(cm->GetGlobVerifyStamp());
  1247. this->WriteBuild(os,
  1248. "Re-run CMake to check if globbed directories changed.",
  1249. "VERIFY_GLOBS",
  1250. /*outputs=*/cmNinjaDeps(1, verifyStampFile),
  1251. /*implicitOuts=*/cmNinjaDeps(),
  1252. /*explicitDeps=*/cmNinjaDeps(),
  1253. /*implicitDeps=*/verifyForceDeps,
  1254. /*orderOnlyDeps=*/cmNinjaDeps(), variables);
  1255. variables.erase("restat");
  1256. implicitDeps.push_back(verifyScriptFile);
  1257. explicitDeps.push_back(verifyStampFile);
  1258. } else if (!this->SupportsManifestRestat() &&
  1259. cm->DoWriteGlobVerifyTarget()) {
  1260. std::ostringstream msg;
  1261. msg << "The detected version of Ninja:\n"
  1262. << " " << this->NinjaVersion << "\n"
  1263. << "is less than the version of Ninja required by CMake for adding "
  1264. "restat dependencies to the build.ninja manifest regeneration "
  1265. "target:\n"
  1266. << " " << this->RequiredNinjaVersionForManifestRestat() << "\n";
  1267. msg << "Any pre-check scripts, such as those generated for file(GLOB "
  1268. "CONFIGURE_DEPENDS), will not be run by Ninja.";
  1269. this->GetCMakeInstance()->IssueMessage(cmake::AUTHOR_WARNING, msg.str());
  1270. }
  1271. std::sort(implicitDeps.begin(), implicitDeps.end());
  1272. implicitDeps.erase(std::unique(implicitDeps.begin(), implicitDeps.end()),
  1273. implicitDeps.end());
  1274. std::string const ninjaBuildFile = this->NinjaOutputPath(NINJA_BUILD_FILE);
  1275. this->WriteBuild(os, "Re-run CMake if any of its inputs changed.",
  1276. "RERUN_CMAKE",
  1277. /*outputs=*/cmNinjaDeps(1, ninjaBuildFile),
  1278. /*implicitOuts=*/cmNinjaDeps(), explicitDeps, implicitDeps,
  1279. /*orderOnlyDeps=*/cmNinjaDeps(), variables);
  1280. cmNinjaDeps missingInputs;
  1281. std::set_difference(std::make_move_iterator(implicitDeps.begin()),
  1282. std::make_move_iterator(implicitDeps.end()),
  1283. CustomCommandOutputs.begin(), CustomCommandOutputs.end(),
  1284. std::back_inserter(missingInputs));
  1285. this->WritePhonyBuild(os, "A missing CMake input file is not an error.",
  1286. missingInputs, cmNinjaDeps());
  1287. }
  1288. std::string cmGlobalNinjaGenerator::ninjaCmd() const
  1289. {
  1290. cmLocalGenerator* lgen = this->LocalGenerators[0];
  1291. if (lgen) {
  1292. return lgen->ConvertToOutputFormat(this->NinjaCommand,
  1293. cmOutputConverter::SHELL);
  1294. }
  1295. return "ninja";
  1296. }
  1297. bool cmGlobalNinjaGenerator::SupportsConsolePool() const
  1298. {
  1299. return this->NinjaSupportsConsolePool;
  1300. }
  1301. bool cmGlobalNinjaGenerator::SupportsImplicitOuts() const
  1302. {
  1303. return this->NinjaSupportsImplicitOuts;
  1304. }
  1305. bool cmGlobalNinjaGenerator::SupportsManifestRestat() const
  1306. {
  1307. return this->NinjaSupportsManifestRestat;
  1308. }
  1309. void cmGlobalNinjaGenerator::WriteTargetClean(std::ostream& os)
  1310. {
  1311. WriteRule(*this->RulesFileStream, "CLEAN", ninjaCmd() + " -t clean",
  1312. "Cleaning all built files...",
  1313. "Rule for cleaning all built files.",
  1314. /*depfile=*/"",
  1315. /*deptype=*/"",
  1316. /*rspfile=*/"",
  1317. /*rspcontent*/ "",
  1318. /*restat=*/"",
  1319. /*generator=*/false);
  1320. WriteBuild(os, "Clean all the built files.", "CLEAN",
  1321. /*outputs=*/cmNinjaDeps(1, this->NinjaOutputPath("clean")),
  1322. /*implicitOuts=*/cmNinjaDeps(),
  1323. /*explicitDeps=*/cmNinjaDeps(),
  1324. /*implicitDeps=*/cmNinjaDeps(),
  1325. /*orderOnlyDeps=*/cmNinjaDeps(),
  1326. /*variables=*/cmNinjaVars());
  1327. }
  1328. void cmGlobalNinjaGenerator::WriteTargetHelp(std::ostream& os)
  1329. {
  1330. WriteRule(*this->RulesFileStream, "HELP", ninjaCmd() + " -t targets",
  1331. "All primary targets available:",
  1332. "Rule for printing all primary targets available.",
  1333. /*depfile=*/"",
  1334. /*deptype=*/"",
  1335. /*rspfile=*/"",
  1336. /*rspcontent*/ "",
  1337. /*restat=*/"",
  1338. /*generator=*/false);
  1339. WriteBuild(os, "Print all primary targets available.", "HELP",
  1340. /*outputs=*/cmNinjaDeps(1, this->NinjaOutputPath("help")),
  1341. /*implicitOuts=*/cmNinjaDeps(),
  1342. /*explicitDeps=*/cmNinjaDeps(),
  1343. /*implicitDeps=*/cmNinjaDeps(),
  1344. /*orderOnlyDeps=*/cmNinjaDeps(),
  1345. /*variables=*/cmNinjaVars());
  1346. }
  1347. void cmGlobalNinjaGenerator::InitOutputPathPrefix()
  1348. {
  1349. this->OutputPathPrefix =
  1350. this->LocalGenerators[0]->GetMakefile()->GetSafeDefinition(
  1351. "CMAKE_NINJA_OUTPUT_PATH_PREFIX");
  1352. EnsureTrailingSlash(this->OutputPathPrefix);
  1353. }
  1354. std::string cmGlobalNinjaGenerator::NinjaOutputPath(
  1355. std::string const& path) const
  1356. {
  1357. if (!this->HasOutputPathPrefix() || cmSystemTools::FileIsFullPath(path)) {
  1358. return path;
  1359. }
  1360. return this->OutputPathPrefix + path;
  1361. }
  1362. void cmGlobalNinjaGenerator::StripNinjaOutputPathPrefixAsSuffix(
  1363. std::string& path)
  1364. {
  1365. if (path.empty()) {
  1366. return;
  1367. }
  1368. EnsureTrailingSlash(path);
  1369. cmStripSuffixIfExists(path, this->OutputPathPrefix);
  1370. }
  1371. /*
  1372. We use the following approach to support Fortran. Each target already
  1373. has a <target>.dir/ directory used to hold intermediate files for CMake.
  1374. For each target, a FortranDependInfo.json file is generated by CMake with
  1375. information about include directories, module directories, and the locations
  1376. the per-target directories for target dependencies.
  1377. Compilation of source files within a target is split into the following steps:
  1378. 1. Preprocess all sources, scan preprocessed output for module dependencies.
  1379. This step is done with independent build statements for each source,
  1380. and can therefore be done in parallel.
  1381. rule Fortran_PREPROCESS
  1382. depfile = $DEP_FILE
  1383. command = gfortran -cpp $DEFINES $INCLUDES $FLAGS -E $in -o $out &&
  1384. cmake -E cmake_ninja_depends \
  1385. --tdi=FortranDependInfo.json --pp=$out --dep=$DEP_FILE \
  1386. --obj=$OBJ_FILE --ddi=$DYNDEP_INTERMEDIATE_FILE
  1387. build src.f90-pp.f90 | src.f90-pp.f90.ddi: Fortran_PREPROCESS src.f90
  1388. OBJ_FILE = src.f90.o
  1389. DEP_FILE = src.f90-pp.f90.d
  1390. DYNDEP_INTERMEDIATE_FILE = src.f90-pp.f90.ddi
  1391. The ``cmake -E cmake_ninja_depends`` tool reads the preprocessed output
  1392. and generates the ninja depfile for preprocessor dependencies. It also
  1393. generates a "ddi" file (in a format private to CMake) that lists the
  1394. object file that compilation will produce along with the module names
  1395. it provides and/or requires. The "ddi" file is an implicit output
  1396. because it should not appear in "$out" but is generated by the rule.
  1397. 2. Consolidate the per-source module dependencies saved in the "ddi"
  1398. files from all sources to produce a ninja "dyndep" file, ``Fortran.dd``.
  1399. rule Fortran_DYNDEP
  1400. command = cmake -E cmake_ninja_dyndep \
  1401. --tdi=FortranDependInfo.json --dd=$out $in
  1402. build Fortran.dd: Fortran_DYNDEP src1.f90-pp.f90.ddi src2.f90-pp.f90.ddi
  1403. The ``cmake -E cmake_ninja_dyndep`` tool reads the "ddi" files from all
  1404. sources in the target and the ``FortranModules.json`` files from targets
  1405. on which the target depends. It computes dependency edges on compilations
  1406. that require modules to those that provide the modules. This information
  1407. is placed in the ``Fortran.dd`` file for ninja to load later. It also
  1408. writes the expected location of modules provided by this target into
  1409. ``FortranModules.json`` for use by dependent targets.
  1410. 3. Compile all sources after loading dynamically discovered dependencies
  1411. of the compilation build statements from their ``dyndep`` bindings.
  1412. rule Fortran_COMPILE
  1413. command = gfortran $INCLUDES $FLAGS -c $in -o $out
  1414. build src1.f90.o: Fortran_COMPILE src1.f90-pp.f90 || Fortran.dd
  1415. dyndep = Fortran.dd
  1416. The "dyndep" binding tells ninja to load dynamically discovered
  1417. dependency information from ``Fortran.dd``. This adds information
  1418. such as:
  1419. build src1.f90.o | mod1.mod: dyndep
  1420. restat = 1
  1421. This tells ninja that ``mod1.mod`` is an implicit output of compiling
  1422. the object file ``src1.f90.o``. The ``restat`` binding tells it that
  1423. the timestamp of the output may not always change. Additionally:
  1424. build src2.f90.o: dyndep | mod1.mod
  1425. This tells ninja that ``mod1.mod`` is a dependency of compiling the
  1426. object file ``src2.f90.o``. This ensures that ``src1.f90.o`` and
  1427. ``mod1.mod`` will always be up to date before ``src2.f90.o`` is built
  1428. (because the latter consumes the module).
  1429. */
  1430. int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg,
  1431. std::vector<std::string>::const_iterator argEnd)
  1432. {
  1433. std::string arg_tdi;
  1434. std::string arg_pp;
  1435. std::string arg_dep;
  1436. std::string arg_obj;
  1437. std::string arg_ddi;
  1438. for (std::vector<std::string>::const_iterator a = argBeg; a != argEnd; ++a) {
  1439. std::string const& arg = *a;
  1440. if (cmHasLiteralPrefix(arg, "--tdi=")) {
  1441. arg_tdi = arg.substr(6);
  1442. } else if (cmHasLiteralPrefix(arg, "--pp=")) {
  1443. arg_pp = arg.substr(5);
  1444. } else if (cmHasLiteralPrefix(arg, "--dep=")) {
  1445. arg_dep = arg.substr(6);
  1446. } else if (cmHasLiteralPrefix(arg, "--obj=")) {
  1447. arg_obj = arg.substr(6);
  1448. } else if (cmHasLiteralPrefix(arg, "--ddi=")) {
  1449. arg_ddi = arg.substr(6);
  1450. } else {
  1451. cmSystemTools::Error("-E cmake_ninja_depends unknown argument: ",
  1452. arg.c_str());
  1453. return 1;
  1454. }
  1455. }
  1456. if (arg_tdi.empty()) {
  1457. cmSystemTools::Error("-E cmake_ninja_depends requires value for --tdi=");
  1458. return 1;
  1459. }
  1460. if (arg_pp.empty()) {
  1461. cmSystemTools::Error("-E cmake_ninja_depends requires value for --pp=");
  1462. return 1;
  1463. }
  1464. if (arg_dep.empty()) {
  1465. cmSystemTools::Error("-E cmake_ninja_depends requires value for --dep=");
  1466. return 1;
  1467. }
  1468. if (arg_obj.empty()) {
  1469. cmSystemTools::Error("-E cmake_ninja_depends requires value for --obj=");
  1470. return 1;
  1471. }
  1472. if (arg_ddi.empty()) {
  1473. cmSystemTools::Error("-E cmake_ninja_depends requires value for --ddi=");
  1474. return 1;
  1475. }
  1476. std::vector<std::string> includes;
  1477. {
  1478. Json::Value tdio;
  1479. Json::Value const& tdi = tdio;
  1480. {
  1481. cmsys::ifstream tdif(arg_tdi.c_str(), std::ios::in | std::ios::binary);
  1482. Json::Reader reader;
  1483. if (!reader.parse(tdif, tdio, false)) {
  1484. cmSystemTools::Error("-E cmake_ninja_depends failed to parse ",
  1485. arg_tdi.c_str(),
  1486. reader.getFormattedErrorMessages().c_str());
  1487. return 1;
  1488. }
  1489. }
  1490. Json::Value const& tdi_include_dirs = tdi["include-dirs"];
  1491. if (tdi_include_dirs.isArray()) {
  1492. for (auto const& tdi_include_dir : tdi_include_dirs) {
  1493. includes.push_back(tdi_include_dir.asString());
  1494. }
  1495. }
  1496. }
  1497. cmFortranSourceInfo info;
  1498. std::set<std::string> defines;
  1499. cmFortranParser parser(includes, defines, info);
  1500. if (!cmFortranParser_FilePush(&parser, arg_pp.c_str())) {
  1501. cmSystemTools::Error("-E cmake_ninja_depends failed to open ",
  1502. arg_pp.c_str());
  1503. return 1;
  1504. }
  1505. if (cmFortran_yyparse(parser.Scanner) != 0) {
  1506. // Failed to parse the file.
  1507. return 1;
  1508. }
  1509. {
  1510. cmGeneratedFileStream depfile(arg_dep.c_str());
  1511. depfile << cmSystemTools::ConvertToUnixOutputPath(arg_pp) << ":";
  1512. for (std::string const& include : info.Includes) {
  1513. depfile << " \\\n " << cmSystemTools::ConvertToUnixOutputPath(include);
  1514. }
  1515. depfile << "\n";
  1516. }
  1517. Json::Value ddi(Json::objectValue);
  1518. ddi["object"] = arg_obj;
  1519. Json::Value& ddi_provides = ddi["provides"] = Json::arrayValue;
  1520. for (std::string const& provide : info.Provides) {
  1521. ddi_provides.append(provide);
  1522. }
  1523. Json::Value& ddi_requires = ddi["requires"] = Json::arrayValue;
  1524. for (std::string const& r : info.Requires) {
  1525. // Require modules not provided in the same source.
  1526. if (!info.Provides.count(r)) {
  1527. ddi_requires.append(r);
  1528. }
  1529. }
  1530. cmGeneratedFileStream ddif(arg_ddi.c_str());
  1531. ddif << ddi;
  1532. if (!ddif) {
  1533. cmSystemTools::Error("-E cmake_ninja_depends failed to write ",
  1534. arg_ddi.c_str());
  1535. return 1;
  1536. }
  1537. return 0;
  1538. }
  1539. struct cmFortranObjectInfo
  1540. {
  1541. std::string Object;
  1542. std::vector<std::string> Provides;
  1543. std::vector<std::string> Requires;
  1544. };
  1545. bool cmGlobalNinjaGenerator::WriteDyndepFile(
  1546. std::string const& dir_top_src, std::string const& dir_top_bld,
  1547. std::string const& dir_cur_src, std::string const& dir_cur_bld,
  1548. std::string const& arg_dd, std::vector<std::string> const& arg_ddis,
  1549. std::string const& module_dir,
  1550. std::vector<std::string> const& linked_target_dirs)
  1551. {
  1552. // Setup path conversions.
  1553. {
  1554. cmStateSnapshot snapshot = this->GetCMakeInstance()->GetCurrentSnapshot();
  1555. snapshot.GetDirectory().SetCurrentSource(dir_cur_src);
  1556. snapshot.GetDirectory().SetCurrentBinary(dir_cur_bld);
  1557. snapshot.GetDirectory().SetRelativePathTopSource(dir_top_src.c_str());
  1558. snapshot.GetDirectory().SetRelativePathTopBinary(dir_top_bld.c_str());
  1559. auto mfd = cm::make_unique<cmMakefile>(this, snapshot);
  1560. std::unique_ptr<cmLocalNinjaGenerator> lgd(
  1561. static_cast<cmLocalNinjaGenerator*>(
  1562. this->CreateLocalGenerator(mfd.get())));
  1563. this->Makefiles.push_back(mfd.release());
  1564. this->LocalGenerators.push_back(lgd.release());
  1565. }
  1566. std::vector<cmFortranObjectInfo> objects;
  1567. for (std::string const& arg_ddi : arg_ddis) {
  1568. // Load the ddi file and compute the module file paths it provides.
  1569. Json::Value ddio;
  1570. Json::Value const& ddi = ddio;
  1571. cmsys::ifstream ddif(arg_ddi.c_str(), std::ios::in | std::ios::binary);
  1572. Json::Reader reader;
  1573. if (!reader.parse(ddif, ddio, false)) {
  1574. cmSystemTools::Error("-E cmake_ninja_dyndep failed to parse ",
  1575. arg_ddi.c_str(),
  1576. reader.getFormattedErrorMessages().c_str());
  1577. return false;
  1578. }
  1579. cmFortranObjectInfo info;
  1580. info.Object = ddi["object"].asString();
  1581. Json::Value const& ddi_provides = ddi["provides"];
  1582. if (ddi_provides.isArray()) {
  1583. for (auto const& ddi_provide : ddi_provides) {
  1584. info.Provides.push_back(ddi_provide.asString());
  1585. }
  1586. }
  1587. Json::Value const& ddi_requires = ddi["requires"];
  1588. if (ddi_requires.isArray()) {
  1589. for (auto const& ddi_require : ddi_requires) {
  1590. info.Requires.push_back(ddi_require.asString());
  1591. }
  1592. }
  1593. objects.push_back(std::move(info));
  1594. }
  1595. // Map from module name to module file path, if known.
  1596. std::map<std::string, std::string> mod_files;
  1597. // Populate the module map with those provided by linked targets first.
  1598. for (std::string const& linked_target_dir : linked_target_dirs) {
  1599. std::string const ltmn = linked_target_dir + "/FortranModules.json";
  1600. Json::Value ltm;
  1601. cmsys::ifstream ltmf(ltmn.c_str(), std::ios::in | std::ios::binary);
  1602. Json::Reader reader;
  1603. if (ltmf && !reader.parse(ltmf, ltm, false)) {
  1604. cmSystemTools::Error("-E cmake_ninja_dyndep failed to parse ",
  1605. linked_target_dir.c_str(),
  1606. reader.getFormattedErrorMessages().c_str());
  1607. return false;
  1608. }
  1609. if (ltm.isObject()) {
  1610. for (Json::Value::iterator i = ltm.begin(); i != ltm.end(); ++i) {
  1611. mod_files[i.key().asString()] = i->asString();
  1612. }
  1613. }
  1614. }
  1615. // Extend the module map with those provided by this target.
  1616. // We do this after loading the modules provided by linked targets
  1617. // in case we have one of the same name that must be preferred.
  1618. Json::Value tm = Json::objectValue;
  1619. for (cmFortranObjectInfo const& object : objects) {
  1620. for (std::string const& p : object.Provides) {
  1621. std::string const mod = module_dir + p + ".mod";
  1622. mod_files[p] = mod;
  1623. tm[p] = mod;
  1624. }
  1625. }
  1626. cmGeneratedFileStream ddf(arg_dd.c_str());
  1627. ddf << "ninja_dyndep_version = 1.0\n";
  1628. for (cmFortranObjectInfo const& object : objects) {
  1629. std::string const ddComment;
  1630. std::string const ddRule = "dyndep";
  1631. cmNinjaDeps ddOutputs;
  1632. cmNinjaDeps ddImplicitOuts;
  1633. cmNinjaDeps ddExplicitDeps;
  1634. cmNinjaDeps ddImplicitDeps;
  1635. cmNinjaDeps ddOrderOnlyDeps;
  1636. cmNinjaVars ddVars;
  1637. ddOutputs.push_back(object.Object);
  1638. for (std::string const& p : object.Provides) {
  1639. ddImplicitOuts.push_back(this->ConvertToNinjaPath(mod_files[p]));
  1640. }
  1641. for (std::string const& r : object.Requires) {
  1642. std::map<std::string, std::string>::iterator m = mod_files.find(r);
  1643. if (m != mod_files.end()) {
  1644. ddImplicitDeps.push_back(this->ConvertToNinjaPath(m->second));
  1645. }
  1646. }
  1647. if (!object.Provides.empty()) {
  1648. ddVars["restat"] = "1";
  1649. }
  1650. this->WriteBuild(ddf, ddComment, ddRule, ddOutputs, ddImplicitOuts,
  1651. ddExplicitDeps, ddImplicitDeps, ddOrderOnlyDeps, ddVars);
  1652. }
  1653. // Store the map of modules provided by this target in a file for
  1654. // use by dependents that reference this target in linked-target-dirs.
  1655. std::string const target_mods_file =
  1656. cmSystemTools::GetFilenamePath(arg_dd) + "/FortranModules.json";
  1657. cmGeneratedFileStream tmf(target_mods_file.c_str());
  1658. tmf << tm;
  1659. return true;
  1660. }
  1661. int cmcmd_cmake_ninja_dyndep(std::vector<std::string>::const_iterator argBeg,
  1662. std::vector<std::string>::const_iterator argEnd)
  1663. {
  1664. std::vector<std::string> arg_full =
  1665. cmSystemTools::HandleResponseFile(argBeg, argEnd);
  1666. std::string arg_dd;
  1667. std::string arg_tdi;
  1668. std::vector<std::string> arg_ddis;
  1669. for (std::string const& arg : arg_full) {
  1670. if (cmHasLiteralPrefix(arg, "--tdi=")) {
  1671. arg_tdi = arg.substr(6);
  1672. } else if (cmHasLiteralPrefix(arg, "--dd=")) {
  1673. arg_dd = arg.substr(5);
  1674. } else if (!cmHasLiteralPrefix(arg, "--") &&
  1675. cmHasLiteralSuffix(arg, ".ddi")) {
  1676. arg_ddis.push_back(arg);
  1677. } else {
  1678. cmSystemTools::Error("-E cmake_ninja_dyndep unknown argument: ",
  1679. arg.c_str());
  1680. return 1;
  1681. }
  1682. }
  1683. if (arg_tdi.empty()) {
  1684. cmSystemTools::Error("-E cmake_ninja_dyndep requires value for --tdi=");
  1685. return 1;
  1686. }
  1687. if (arg_dd.empty()) {
  1688. cmSystemTools::Error("-E cmake_ninja_dyndep requires value for --dd=");
  1689. return 1;
  1690. }
  1691. Json::Value tdio;
  1692. Json::Value const& tdi = tdio;
  1693. {
  1694. cmsys::ifstream tdif(arg_tdi.c_str(), std::ios::in | std::ios::binary);
  1695. Json::Reader reader;
  1696. if (!reader.parse(tdif, tdio, false)) {
  1697. cmSystemTools::Error("-E cmake_ninja_dyndep failed to parse ",
  1698. arg_tdi.c_str(),
  1699. reader.getFormattedErrorMessages().c_str());
  1700. return 1;
  1701. }
  1702. }
  1703. std::string const dir_cur_bld = tdi["dir-cur-bld"].asString();
  1704. std::string const dir_cur_src = tdi["dir-cur-src"].asString();
  1705. std::string const dir_top_bld = tdi["dir-top-bld"].asString();
  1706. std::string const dir_top_src = tdi["dir-top-src"].asString();
  1707. std::string module_dir = tdi["module-dir"].asString();
  1708. if (!module_dir.empty()) {
  1709. module_dir += "/";
  1710. }
  1711. std::vector<std::string> linked_target_dirs;
  1712. Json::Value const& tdi_linked_target_dirs = tdi["linked-target-dirs"];
  1713. if (tdi_linked_target_dirs.isArray()) {
  1714. for (auto const& tdi_linked_target_dir : tdi_linked_target_dirs) {
  1715. linked_target_dirs.push_back(tdi_linked_target_dir.asString());
  1716. }
  1717. }
  1718. cmake cm(cmake::RoleInternal);
  1719. cm.SetHomeDirectory(dir_top_src);
  1720. cm.SetHomeOutputDirectory(dir_top_bld);
  1721. std::unique_ptr<cmGlobalNinjaGenerator> ggd(
  1722. static_cast<cmGlobalNinjaGenerator*>(cm.CreateGlobalGenerator("Ninja")));
  1723. if (!ggd.get() ||
  1724. !ggd->WriteDyndepFile(dir_top_src, dir_top_bld, dir_cur_src, dir_cur_bld,
  1725. arg_dd, arg_ddis, module_dir,
  1726. linked_target_dirs)) {
  1727. return 1;
  1728. }
  1729. return 0;
  1730. }