cmGlobalNinjaGenerator.cxx 69 KB

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