cmGlobalNinjaGenerator.cxx 65 KB

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