cmGlobalNinjaGenerator.cxx 68 KB

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