cmGlobalNinjaGenerator.cxx 67 KB

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