cmGlobalNinjaGenerator.cxx 67 KB

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