cmGlobalNinjaGenerator.cxx 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746
  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 <algorithm>
  5. #include <cctype>
  6. #include <cstdio>
  7. #include <sstream>
  8. #include <cm/iterator>
  9. #include <cm/memory>
  10. #include <cmext/algorithm>
  11. #include <cmext/memory>
  12. #include <cm3p/json/reader.h>
  13. #include <cm3p/json/value.h>
  14. #include <cm3p/json/writer.h>
  15. #include "cmsys/FStream.hxx"
  16. #include "cmDocumentationEntry.h"
  17. #include "cmFortranParser.h"
  18. #include "cmGeneratedFileStream.h"
  19. #include "cmGeneratorExpressionEvaluationFile.h"
  20. #include "cmGeneratorTarget.h"
  21. #include "cmGlobalGenerator.h"
  22. #include "cmLinkLineComputer.h"
  23. #include "cmListFileCache.h"
  24. #include "cmLocalGenerator.h"
  25. #include "cmLocalNinjaGenerator.h"
  26. #include "cmMakefile.h"
  27. #include "cmMessageType.h"
  28. #include "cmNinjaLinkLineComputer.h"
  29. #include "cmOutputConverter.h"
  30. #include "cmProperty.h"
  31. #include "cmRange.h"
  32. #include "cmState.h"
  33. #include "cmStateDirectory.h"
  34. #include "cmStateSnapshot.h"
  35. #include "cmStateTypes.h"
  36. #include "cmStringAlgorithms.h"
  37. #include "cmSystemTools.h"
  38. #include "cmTarget.h"
  39. #include "cmTargetDepend.h"
  40. #include "cmVersion.h"
  41. #include "cmake.h"
  42. const char* cmGlobalNinjaGenerator::NINJA_BUILD_FILE = "build.ninja";
  43. const char* cmGlobalNinjaGenerator::NINJA_RULES_FILE =
  44. "CMakeFiles/rules.ninja";
  45. const char* cmGlobalNinjaGenerator::INDENT = " ";
  46. #ifdef _WIN32
  47. std::string const cmGlobalNinjaGenerator::SHELL_NOOP = "cd .";
  48. #else
  49. std::string const cmGlobalNinjaGenerator::SHELL_NOOP = ":";
  50. #endif
  51. void cmGlobalNinjaGenerator::Indent(std::ostream& os, int count)
  52. {
  53. for (int i = 0; i < count; ++i) {
  54. os << cmGlobalNinjaGenerator::INDENT;
  55. }
  56. }
  57. void cmGlobalNinjaGenerator::WriteDivider(std::ostream& os)
  58. {
  59. os << "# ======================================"
  60. "=======================================\n";
  61. }
  62. void cmGlobalNinjaGenerator::WriteComment(std::ostream& os,
  63. const std::string& comment)
  64. {
  65. if (comment.empty()) {
  66. return;
  67. }
  68. std::string::size_type lpos = 0;
  69. std::string::size_type rpos;
  70. os << "\n#############################################\n";
  71. while ((rpos = comment.find('\n', lpos)) != std::string::npos) {
  72. os << "# " << comment.substr(lpos, rpos - lpos) << "\n";
  73. lpos = rpos + 1;
  74. }
  75. os << "# " << comment.substr(lpos) << "\n\n";
  76. }
  77. std::unique_ptr<cmLinkLineComputer>
  78. cmGlobalNinjaGenerator::CreateLinkLineComputer(
  79. cmOutputConverter* outputConverter,
  80. cmStateDirectory const& /* stateDir */) const
  81. {
  82. return std::unique_ptr<cmLinkLineComputer>(
  83. cm::make_unique<cmNinjaLinkLineComputer>(
  84. outputConverter,
  85. this->LocalGenerators[0]->GetStateSnapshot().GetDirectory(), this));
  86. }
  87. std::string cmGlobalNinjaGenerator::EncodeRuleName(std::string const& name)
  88. {
  89. // Ninja rule names must match "[a-zA-Z0-9_.-]+". Use ".xx" to encode
  90. // "." and all invalid characters as hexadecimal.
  91. std::string encoded;
  92. for (char i : name) {
  93. if (isalnum(i) || i == '_' || i == '-') {
  94. encoded += i;
  95. } else {
  96. char buf[16];
  97. sprintf(buf, ".%02x", static_cast<unsigned int>(i));
  98. encoded += buf;
  99. }
  100. }
  101. return encoded;
  102. }
  103. std::string cmGlobalNinjaGenerator::EncodeLiteral(const std::string& lit)
  104. {
  105. std::string result = lit;
  106. cmSystemTools::ReplaceString(result, "$", "$$");
  107. cmSystemTools::ReplaceString(result, "\n", "$\n");
  108. if (this->IsMultiConfig()) {
  109. cmSystemTools::ReplaceString(result,
  110. cmStrCat('$', this->GetCMakeCFGIntDir()),
  111. this->GetCMakeCFGIntDir());
  112. }
  113. return result;
  114. }
  115. std::string cmGlobalNinjaGenerator::EncodePath(const std::string& path)
  116. {
  117. std::string result = path;
  118. #ifdef _WIN32
  119. if (this->IsGCCOnWindows())
  120. std::replace(result.begin(), result.end(), '\\', '/');
  121. else
  122. std::replace(result.begin(), result.end(), '/', '\\');
  123. #endif
  124. result = EncodeLiteral(result);
  125. cmSystemTools::ReplaceString(result, " ", "$ ");
  126. cmSystemTools::ReplaceString(result, ":", "$:");
  127. return result;
  128. }
  129. void cmGlobalNinjaGenerator::WriteBuild(std::ostream& os,
  130. cmNinjaBuild const& build,
  131. int cmdLineLimit,
  132. bool* usedResponseFile)
  133. {
  134. // Make sure there is a rule.
  135. if (build.Rule.empty()) {
  136. cmSystemTools::Error(cmStrCat(
  137. "No rule for WriteBuild! called with comment: ", build.Comment));
  138. return;
  139. }
  140. // Make sure there is at least one output file.
  141. if (build.Outputs.empty()) {
  142. cmSystemTools::Error(cmStrCat(
  143. "No output files for WriteBuild! called with comment: ", build.Comment));
  144. return;
  145. }
  146. cmGlobalNinjaGenerator::WriteComment(os, build.Comment);
  147. // Write output files.
  148. std::string buildStr("build");
  149. {
  150. // Write explicit outputs
  151. for (std::string const& output : build.Outputs) {
  152. buildStr += cmStrCat(' ', EncodePath(output));
  153. if (this->ComputingUnknownDependencies) {
  154. this->CombinedBuildOutputs.insert(output);
  155. }
  156. }
  157. // Write implicit outputs
  158. if (!build.ImplicitOuts.empty()) {
  159. buildStr += " |";
  160. for (std::string const& implicitOut : build.ImplicitOuts) {
  161. buildStr += cmStrCat(' ', EncodePath(implicitOut));
  162. }
  163. }
  164. buildStr += ':';
  165. // Write the rule.
  166. buildStr += cmStrCat(' ', build.Rule);
  167. }
  168. std::string arguments;
  169. {
  170. // TODO: Better formatting for when there are multiple input/output files.
  171. // Write explicit dependencies.
  172. for (std::string const& explicitDep : build.ExplicitDeps) {
  173. arguments += cmStrCat(' ', EncodePath(explicitDep));
  174. }
  175. // Write implicit dependencies.
  176. if (!build.ImplicitDeps.empty()) {
  177. arguments += " |";
  178. for (std::string const& implicitDep : build.ImplicitDeps) {
  179. arguments += cmStrCat(' ', EncodePath(implicitDep));
  180. }
  181. }
  182. // Write order-only dependencies.
  183. if (!build.OrderOnlyDeps.empty()) {
  184. arguments += " ||";
  185. for (std::string const& orderOnlyDep : build.OrderOnlyDeps) {
  186. arguments += cmStrCat(' ', EncodePath(orderOnlyDep));
  187. }
  188. }
  189. arguments += '\n';
  190. }
  191. // Write the variables bound to this build statement.
  192. std::string assignments;
  193. {
  194. std::ostringstream variable_assignments;
  195. for (auto const& variable : build.Variables) {
  196. cmGlobalNinjaGenerator::WriteVariable(
  197. variable_assignments, variable.first, variable.second, "", 1);
  198. }
  199. // check if a response file rule should be used
  200. assignments = variable_assignments.str();
  201. bool useResponseFile = false;
  202. if (cmdLineLimit < 0 ||
  203. (cmdLineLimit > 0 &&
  204. (arguments.size() + buildStr.size() + assignments.size() + 1000) >
  205. static_cast<size_t>(cmdLineLimit))) {
  206. variable_assignments.str(std::string());
  207. cmGlobalNinjaGenerator::WriteVariable(variable_assignments, "RSP_FILE",
  208. build.RspFile, "", 1);
  209. assignments += variable_assignments.str();
  210. useResponseFile = true;
  211. }
  212. if (usedResponseFile) {
  213. *usedResponseFile = useResponseFile;
  214. }
  215. }
  216. if (build.Variables.count("dyndep") > 0) {
  217. // The ninja 'cleandead' operation does not account for outputs
  218. // discovered by 'dyndep' bindings. Avoid removing them.
  219. this->DisableCleandead = true;
  220. }
  221. os << buildStr << arguments << assignments << "\n";
  222. }
  223. void cmGlobalNinjaGenerator::AddCustomCommandRule()
  224. {
  225. cmNinjaRule rule("CUSTOM_COMMAND");
  226. rule.Command = "$COMMAND";
  227. rule.Description = "$DESC";
  228. rule.Comment = "Rule for running custom commands.";
  229. this->AddRule(rule);
  230. }
  231. void cmGlobalNinjaGenerator::WriteCustomCommandBuild(
  232. const std::string& command, const std::string& description,
  233. const std::string& comment, const std::string& depfile,
  234. const std::string& job_pool, bool uses_terminal, bool restat,
  235. const cmNinjaDeps& outputs, const std::string& config,
  236. const cmNinjaDeps& explicitDeps, const cmNinjaDeps& orderOnlyDeps)
  237. {
  238. this->AddCustomCommandRule();
  239. {
  240. cmNinjaBuild build("CUSTOM_COMMAND");
  241. build.Comment = comment;
  242. build.Outputs = outputs;
  243. build.ExplicitDeps = explicitDeps;
  244. build.OrderOnlyDeps = orderOnlyDeps;
  245. cmNinjaVars& vars = build.Variables;
  246. {
  247. std::string cmd = command; // NOLINT(*)
  248. #ifdef _WIN32
  249. if (cmd.empty())
  250. // TODO Shouldn't an empty command be handled by ninja?
  251. cmd = "cmd.exe /c";
  252. #endif
  253. vars["COMMAND"] = std::move(cmd);
  254. }
  255. vars["DESC"] = EncodeLiteral(description);
  256. if (restat) {
  257. vars["restat"] = "1";
  258. }
  259. if (uses_terminal && SupportsConsolePool()) {
  260. vars["pool"] = "console";
  261. } else if (!job_pool.empty()) {
  262. vars["pool"] = job_pool;
  263. }
  264. if (!depfile.empty()) {
  265. vars["depfile"] = depfile;
  266. }
  267. if (config.empty()) {
  268. this->WriteBuild(*this->GetCommonFileStream(), build);
  269. } else {
  270. this->WriteBuild(*this->GetImplFileStream(config), build);
  271. }
  272. }
  273. if (this->ComputingUnknownDependencies) {
  274. // we need to track every dependency that comes in, since we are trying
  275. // to find dependencies that are side effects of build commands
  276. for (std::string const& dep : explicitDeps) {
  277. this->CombinedCustomCommandExplicitDependencies.insert(dep);
  278. }
  279. }
  280. }
  281. void cmGlobalNinjaGenerator::AddMacOSXContentRule()
  282. {
  283. cmNinjaRule rule("COPY_OSX_CONTENT");
  284. rule.Command = cmStrCat(CMakeCmd(), " -E copy $in $out");
  285. rule.Description = "Copying OS X Content $out";
  286. rule.Comment = "Rule for copying OS X bundle content file.";
  287. this->AddRule(rule);
  288. }
  289. void cmGlobalNinjaGenerator::WriteMacOSXContentBuild(std::string input,
  290. std::string output,
  291. const std::string& config)
  292. {
  293. this->AddMacOSXContentRule();
  294. {
  295. cmNinjaBuild build("COPY_OSX_CONTENT");
  296. build.Outputs.push_back(std::move(output));
  297. build.ExplicitDeps.push_back(std::move(input));
  298. this->WriteBuild(*this->GetImplFileStream(config), build);
  299. }
  300. }
  301. void cmGlobalNinjaGenerator::WriteRule(std::ostream& os,
  302. cmNinjaRule const& rule)
  303. {
  304. // -- Parameter checks
  305. // Make sure the rule has a name.
  306. if (rule.Name.empty()) {
  307. cmSystemTools::Error(cmStrCat(
  308. "No name given for WriteRule! called with comment: ", rule.Comment));
  309. return;
  310. }
  311. // Make sure a command is given.
  312. if (rule.Command.empty()) {
  313. cmSystemTools::Error(cmStrCat(
  314. "No command given for WriteRule! called with comment: ", rule.Comment));
  315. return;
  316. }
  317. // Make sure response file content is given
  318. if (!rule.RspFile.empty() && rule.RspContent.empty()) {
  319. cmSystemTools::Error(
  320. cmStrCat("rspfile but no rspfile_content given for WriteRule! "
  321. "called with comment: ",
  322. rule.Comment));
  323. return;
  324. }
  325. // -- Write rule
  326. // Write rule intro
  327. cmGlobalNinjaGenerator::WriteComment(os, rule.Comment);
  328. os << "rule " << rule.Name << '\n';
  329. // Write rule key/value pairs
  330. auto writeKV = [&os](const char* key, std::string const& value) {
  331. if (!value.empty()) {
  332. cmGlobalNinjaGenerator::Indent(os, 1);
  333. os << key << " = " << value << '\n';
  334. }
  335. };
  336. writeKV("depfile", rule.DepFile);
  337. writeKV("deps", rule.DepType);
  338. writeKV("command", rule.Command);
  339. writeKV("description", rule.Description);
  340. if (!rule.RspFile.empty()) {
  341. writeKV("rspfile", rule.RspFile);
  342. writeKV("rspfile_content", rule.RspContent);
  343. }
  344. writeKV("restat", rule.Restat);
  345. if (rule.Generator) {
  346. writeKV("generator", "1");
  347. }
  348. // Finish rule
  349. os << '\n';
  350. }
  351. void cmGlobalNinjaGenerator::WriteVariable(std::ostream& os,
  352. const std::string& name,
  353. const std::string& value,
  354. const std::string& comment,
  355. int indent)
  356. {
  357. // Make sure we have a name.
  358. if (name.empty()) {
  359. cmSystemTools::Error(cmStrCat("No name given for WriteVariable! called "
  360. "with comment: ",
  361. comment));
  362. return;
  363. }
  364. // Do not add a variable if the value is empty.
  365. std::string val = cmTrimWhitespace(value);
  366. if (val.empty()) {
  367. return;
  368. }
  369. cmGlobalNinjaGenerator::WriteComment(os, comment);
  370. cmGlobalNinjaGenerator::Indent(os, indent);
  371. os << name << " = " << val << "\n";
  372. }
  373. void cmGlobalNinjaGenerator::WriteInclude(std::ostream& os,
  374. const std::string& filename,
  375. const std::string& comment)
  376. {
  377. cmGlobalNinjaGenerator::WriteComment(os, comment);
  378. os << "include " << filename << "\n";
  379. }
  380. void cmGlobalNinjaGenerator::WriteDefault(std::ostream& os,
  381. const cmNinjaDeps& targets,
  382. const std::string& comment)
  383. {
  384. cmGlobalNinjaGenerator::WriteComment(os, comment);
  385. os << "default";
  386. for (std::string const& target : targets) {
  387. os << " " << target;
  388. }
  389. os << "\n";
  390. }
  391. cmGlobalNinjaGenerator::cmGlobalNinjaGenerator(cmake* cm)
  392. : cmGlobalCommonGenerator(cm)
  393. {
  394. #ifdef _WIN32
  395. cm->GetState()->SetWindowsShell(true);
  396. #endif
  397. this->FindMakeProgramFile = "CMakeNinjaFindMake.cmake";
  398. }
  399. // Virtual public methods.
  400. std::unique_ptr<cmLocalGenerator> cmGlobalNinjaGenerator::CreateLocalGenerator(
  401. cmMakefile* mf)
  402. {
  403. return std::unique_ptr<cmLocalGenerator>(
  404. cm::make_unique<cmLocalNinjaGenerator>(this, mf));
  405. }
  406. codecvt::Encoding cmGlobalNinjaGenerator::GetMakefileEncoding() const
  407. {
  408. #ifdef _WIN32
  409. // Ninja on Windows does not support non-ANSI characters.
  410. // https://github.com/ninja-build/ninja/issues/1195
  411. return codecvt::ANSI;
  412. #else
  413. // No encoding conversion needed on other platforms.
  414. return codecvt::None;
  415. #endif
  416. }
  417. void cmGlobalNinjaGenerator::GetDocumentation(cmDocumentationEntry& entry)
  418. {
  419. entry.Name = cmGlobalNinjaGenerator::GetActualName();
  420. entry.Brief = "Generates build.ninja files.";
  421. }
  422. // Implemented in all cmGlobaleGenerator sub-classes.
  423. // Used in:
  424. // Source/cmLocalGenerator.cxx
  425. // Source/cmake.cxx
  426. void cmGlobalNinjaGenerator::Generate()
  427. {
  428. // Check minimum Ninja version.
  429. if (cmSystemTools::VersionCompare(cmSystemTools::OP_LESS,
  430. this->NinjaVersion.c_str(),
  431. RequiredNinjaVersion().c_str())) {
  432. std::ostringstream msg;
  433. msg << "The detected version of Ninja (" << this->NinjaVersion;
  434. msg << ") is less than the version of Ninja required by CMake (";
  435. msg << cmGlobalNinjaGenerator::RequiredNinjaVersion() << ").";
  436. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  437. msg.str());
  438. return;
  439. }
  440. if (!this->InspectConfigTypeVariables()) {
  441. return;
  442. }
  443. if (!this->OpenBuildFileStreams()) {
  444. return;
  445. }
  446. if (!this->OpenRulesFileStream()) {
  447. return;
  448. }
  449. for (auto& it : this->Configs) {
  450. it.second.TargetDependsClosures.clear();
  451. }
  452. this->InitOutputPathPrefix();
  453. this->TargetAll = this->NinjaOutputPath("all");
  454. this->CMakeCacheFile = this->NinjaOutputPath("CMakeCache.txt");
  455. this->DisableCleandead = false;
  456. this->PolicyCMP0058 =
  457. this->LocalGenerators[0]->GetMakefile()->GetPolicyStatus(
  458. cmPolicies::CMP0058);
  459. this->ComputingUnknownDependencies =
  460. (this->PolicyCMP0058 == cmPolicies::OLD ||
  461. this->PolicyCMP0058 == cmPolicies::WARN);
  462. this->cmGlobalGenerator::Generate();
  463. this->WriteAssumedSourceDependencies();
  464. this->WriteTargetAliases(*this->GetCommonFileStream());
  465. this->WriteFolderTargets(*this->GetCommonFileStream());
  466. this->WriteUnknownExplicitDependencies(*this->GetCommonFileStream());
  467. this->WriteBuiltinTargets(*this->GetCommonFileStream());
  468. if (cmSystemTools::GetErrorOccuredFlag()) {
  469. this->RulesFileStream->setstate(std::ios::failbit);
  470. for (auto const& config : this->Makefiles[0]->GetGeneratorConfigs(
  471. cmMakefile::IncludeEmptyConfig)) {
  472. this->GetImplFileStream(config)->setstate(std::ios::failbit);
  473. this->GetConfigFileStream(config)->setstate(std::ios::failbit);
  474. }
  475. this->GetCommonFileStream()->setstate(std::ios::failbit);
  476. }
  477. this->CloseCompileCommandsStream();
  478. this->CloseRulesFileStream();
  479. this->CloseBuildFileStreams();
  480. #ifdef _WIN32
  481. // Older ninja tools will not be able to update metadata on Windows
  482. // when we are re-generating inside an existing 'ninja' invocation
  483. // because the outer tool has the files open for write.
  484. if (this->NinjaSupportsMetadataOnRegeneration ||
  485. !this->GetCMakeInstance()->GetRegenerateDuringBuild())
  486. #endif
  487. {
  488. this->CleanMetaData();
  489. }
  490. }
  491. void cmGlobalNinjaGenerator::CleanMetaData()
  492. {
  493. auto run_ninja_tool = [this](std::vector<char const*> const& args) {
  494. std::vector<std::string> command;
  495. command.push_back(this->NinjaCommand);
  496. command.emplace_back("-C");
  497. command.emplace_back(this->GetCMakeInstance()->GetHomeOutputDirectory());
  498. command.emplace_back("-t");
  499. for (auto const& arg : args) {
  500. command.emplace_back(arg);
  501. }
  502. std::string error;
  503. if (!cmSystemTools::RunSingleCommand(command, nullptr, &error, nullptr,
  504. nullptr,
  505. cmSystemTools::OUTPUT_NONE)) {
  506. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  507. cmStrCat("Running\n '",
  508. cmJoin(command, "' '"),
  509. "'\n"
  510. "failed with:\n ",
  511. error));
  512. cmSystemTools::SetFatalErrorOccured();
  513. }
  514. };
  515. // Can the tools below expect 'build.ninja' to be loadable?
  516. bool const expectBuildManifest =
  517. !this->IsMultiConfig() && this->OutputPathPrefix.empty();
  518. // Skip some ninja tools if they need 'build.ninja' but it is missing.
  519. bool const missingBuildManifest = expectBuildManifest &&
  520. this->NinjaSupportsUnconditionalRecompactTool &&
  521. !cmSystemTools::FileExists("build.ninja");
  522. // The `recompact` tool loads the manifest. As above, we don't have a single
  523. // `build.ninja` to load for this in Ninja-Multi. This may be relaxed in the
  524. // future pending further investigation into how Ninja works upstream
  525. // (ninja#1721).
  526. if (this->NinjaSupportsUnconditionalRecompactTool &&
  527. !this->GetCMakeInstance()->GetRegenerateDuringBuild() &&
  528. expectBuildManifest && !missingBuildManifest) {
  529. run_ninja_tool({ "recompact" });
  530. }
  531. if (this->NinjaSupportsRestatTool && this->OutputPathPrefix.empty()) {
  532. // XXX(ninja): We only list `build.ninja` entry files here because CMake
  533. // *always* rewrites these files on a reconfigure. If CMake ever gets
  534. // smarter about this, all CMake-time created/edited files listed as
  535. // outputs for the reconfigure build statement will need to be listed here.
  536. cmNinjaDeps outputs;
  537. this->AddRebuildManifestOutputs(outputs);
  538. std::vector<const char*> args;
  539. args.reserve(outputs.size() + 1);
  540. args.push_back("restat");
  541. for (auto const& output : outputs) {
  542. args.push_back(output.c_str());
  543. }
  544. run_ninja_tool(args);
  545. }
  546. }
  547. bool cmGlobalNinjaGenerator::FindMakeProgram(cmMakefile* mf)
  548. {
  549. if (!this->cmGlobalGenerator::FindMakeProgram(mf)) {
  550. return false;
  551. }
  552. if (cmProp ninjaCommand = mf->GetDefinition("CMAKE_MAKE_PROGRAM")) {
  553. this->NinjaCommand = *ninjaCommand;
  554. std::vector<std::string> command;
  555. command.push_back(this->NinjaCommand);
  556. command.emplace_back("--version");
  557. std::string version;
  558. std::string error;
  559. if (!cmSystemTools::RunSingleCommand(command, &version, &error, nullptr,
  560. nullptr,
  561. cmSystemTools::OUTPUT_NONE)) {
  562. mf->IssueMessage(MessageType::FATAL_ERROR,
  563. cmStrCat("Running\n '", cmJoin(command, "' '"),
  564. "'\n"
  565. "failed with:\n ",
  566. error));
  567. cmSystemTools::SetFatalErrorOccured();
  568. return false;
  569. }
  570. this->NinjaVersion = cmTrimWhitespace(version);
  571. this->CheckNinjaFeatures();
  572. }
  573. return true;
  574. }
  575. void cmGlobalNinjaGenerator::CheckNinjaFeatures()
  576. {
  577. this->NinjaSupportsConsolePool = !cmSystemTools::VersionCompare(
  578. cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
  579. RequiredNinjaVersionForConsolePool().c_str());
  580. this->NinjaSupportsImplicitOuts = !cmSystemTools::VersionCompare(
  581. cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
  582. cmGlobalNinjaGenerator::RequiredNinjaVersionForImplicitOuts().c_str());
  583. this->NinjaSupportsManifestRestat = !cmSystemTools::VersionCompare(
  584. cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
  585. RequiredNinjaVersionForManifestRestat().c_str());
  586. this->NinjaSupportsMultilineDepfile = !cmSystemTools::VersionCompare(
  587. cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
  588. RequiredNinjaVersionForMultilineDepfile().c_str());
  589. this->NinjaSupportsDyndeps = !cmSystemTools::VersionCompare(
  590. cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
  591. RequiredNinjaVersionForDyndeps().c_str());
  592. if (!this->NinjaSupportsDyndeps) {
  593. // The ninja version number is not new enough to have upstream support.
  594. // Our ninja branch adds ".dyndep-#" to its version number,
  595. // where '#' is a feature-specific version number. Extract it.
  596. static std::string const k_DYNDEP_ = ".dyndep-";
  597. std::string::size_type pos = this->NinjaVersion.find(k_DYNDEP_);
  598. if (pos != std::string::npos) {
  599. const char* fv = &this->NinjaVersion[pos + k_DYNDEP_.size()];
  600. unsigned long dyndep = 0;
  601. cmStrToULong(fv, &dyndep);
  602. if (dyndep == 1) {
  603. this->NinjaSupportsDyndeps = true;
  604. }
  605. }
  606. }
  607. this->NinjaSupportsUnconditionalRecompactTool =
  608. !cmSystemTools::VersionCompare(
  609. cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
  610. RequiredNinjaVersionForUnconditionalRecompactTool().c_str());
  611. this->NinjaSupportsRestatTool = !cmSystemTools::VersionCompare(
  612. cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
  613. RequiredNinjaVersionForRestatTool().c_str());
  614. this->NinjaSupportsMultipleOutputs = !cmSystemTools::VersionCompare(
  615. cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
  616. RequiredNinjaVersionForMultipleOutputs().c_str());
  617. this->NinjaSupportsMetadataOnRegeneration = !cmSystemTools::VersionCompare(
  618. cmSystemTools::OP_LESS, this->NinjaVersion.c_str(),
  619. RequiredNinjaVersionForMetadataOnRegeneration().c_str());
  620. }
  621. bool cmGlobalNinjaGenerator::CheckLanguages(
  622. std::vector<std::string> const& languages, cmMakefile* mf) const
  623. {
  624. if (cm::contains(languages, "Fortran")) {
  625. return this->CheckFortran(mf);
  626. }
  627. if (cm::contains(languages, "ISPC")) {
  628. return this->CheckISPC(mf);
  629. }
  630. if (cm::contains(languages, "Swift")) {
  631. const std::string architectures =
  632. mf->GetSafeDefinition("CMAKE_OSX_ARCHITECTURES");
  633. if (architectures.find_first_of(';') != std::string::npos) {
  634. mf->IssueMessage(MessageType::FATAL_ERROR,
  635. "multiple values for CMAKE_OSX_ARCHITECTURES not "
  636. "supported with Swift");
  637. cmSystemTools::SetFatalErrorOccured();
  638. return false;
  639. }
  640. }
  641. return true;
  642. }
  643. bool cmGlobalNinjaGenerator::CheckFortran(cmMakefile* mf) const
  644. {
  645. if (this->NinjaSupportsDyndeps) {
  646. return true;
  647. }
  648. std::ostringstream e;
  649. /* clang-format off */
  650. e <<
  651. "The Ninja generator does not support Fortran using Ninja version\n"
  652. " " << this->NinjaVersion << "\n"
  653. "due to lack of required features. Ninja 1.10 or higher is required."
  654. ;
  655. /* clang-format on */
  656. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  657. cmSystemTools::SetFatalErrorOccured();
  658. return false;
  659. }
  660. bool cmGlobalNinjaGenerator::CheckISPC(cmMakefile* mf) const
  661. {
  662. if (this->NinjaSupportsMultipleOutputs) {
  663. return true;
  664. }
  665. std::ostringstream e;
  666. /* clang-format off */
  667. e <<
  668. "The Ninja generator does not support ISPC using Ninja version\n"
  669. " " << this->NinjaVersion << "\n"
  670. "due to lack of required features. Ninja 1.10 or higher is required."
  671. ;
  672. /* clang-format on */
  673. mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
  674. cmSystemTools::SetFatalErrorOccured();
  675. return false;
  676. }
  677. void cmGlobalNinjaGenerator::EnableLanguage(
  678. std::vector<std::string> const& langs, cmMakefile* mf, bool optional)
  679. {
  680. if (this->IsMultiConfig()) {
  681. if (!mf->GetDefinition("CMAKE_CONFIGURATION_TYPES")) {
  682. mf->AddCacheDefinition(
  683. "CMAKE_CONFIGURATION_TYPES", "Debug;Release;RelWithDebInfo",
  684. "Semicolon separated list of supported configuration types, only "
  685. "supports Debug, Release, MinSizeRel, and RelWithDebInfo, anything "
  686. "else will be ignored",
  687. cmStateEnums::STRING);
  688. }
  689. }
  690. this->cmGlobalGenerator::EnableLanguage(langs, mf, optional);
  691. for (std::string const& l : langs) {
  692. if (l == "NONE") {
  693. continue;
  694. }
  695. this->ResolveLanguageCompiler(l, mf, optional);
  696. }
  697. #ifdef _WIN32
  698. const bool clangGnuMode =
  699. ((mf->GetSafeDefinition("CMAKE_C_COMPILER_ID") == "Clang") &&
  700. (mf->GetSafeDefinition("CMAKE_C_COMPILER_FRONTEND_VARIANT") == "GNU")) ||
  701. ((mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID") == "Clang") &&
  702. (mf->GetSafeDefinition("CMAKE_CXX_COMPILER_FRONTEND_VARIANT") == "GNU"));
  703. if (clangGnuMode ||
  704. ((mf->GetSafeDefinition("CMAKE_C_SIMULATE_ID") != "MSVC") &&
  705. (mf->GetSafeDefinition("CMAKE_CXX_SIMULATE_ID") != "MSVC") &&
  706. (mf->IsOn("CMAKE_COMPILER_IS_MINGW") ||
  707. (mf->GetSafeDefinition("CMAKE_C_COMPILER_ID") == "GNU") ||
  708. (mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID") == "GNU") ||
  709. (mf->GetSafeDefinition("CMAKE_C_COMPILER_ID") == "Clang") ||
  710. (mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID") == "Clang") ||
  711. (mf->GetSafeDefinition("CMAKE_C_COMPILER_ID") == "QCC") ||
  712. (mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID") == "QCC")))) {
  713. this->UsingGCCOnWindows = true;
  714. }
  715. #endif
  716. }
  717. // Implemented by:
  718. // cmGlobalUnixMakefileGenerator3
  719. // cmGlobalGhsMultiGenerator
  720. // cmGlobalVisualStudio10Generator
  721. // cmGlobalVisualStudio7Generator
  722. // cmGlobalXCodeGenerator
  723. // Called by:
  724. // cmGlobalGenerator::Build()
  725. std::vector<cmGlobalGenerator::GeneratedMakeCommand>
  726. cmGlobalNinjaGenerator::GenerateBuildCommand(
  727. const std::string& makeProgram, const std::string& /*projectName*/,
  728. const std::string& /*projectDir*/,
  729. std::vector<std::string> const& targetNames, const std::string& config,
  730. bool /*fast*/, int jobs, bool verbose,
  731. std::vector<std::string> const& makeOptions)
  732. {
  733. GeneratedMakeCommand makeCommand;
  734. makeCommand.Add(this->SelectMakeProgram(makeProgram));
  735. if (verbose) {
  736. makeCommand.Add("-v");
  737. }
  738. if ((jobs != cmake::NO_BUILD_PARALLEL_LEVEL) &&
  739. (jobs != cmake::DEFAULT_BUILD_PARALLEL_LEVEL)) {
  740. makeCommand.Add("-j", std::to_string(jobs));
  741. }
  742. this->AppendNinjaFileArgument(makeCommand, config);
  743. makeCommand.Add(makeOptions.begin(), makeOptions.end());
  744. for (const auto& tname : targetNames) {
  745. if (!tname.empty()) {
  746. makeCommand.Add(tname);
  747. }
  748. }
  749. return { std::move(makeCommand) };
  750. }
  751. // Non-virtual public methods.
  752. void cmGlobalNinjaGenerator::AddRule(cmNinjaRule const& rule)
  753. {
  754. // Do not add the same rule twice.
  755. if (!this->Rules.insert(rule.Name).second) {
  756. return;
  757. }
  758. // Store command length
  759. this->RuleCmdLength[rule.Name] = static_cast<int>(rule.Command.size());
  760. // Write rule
  761. cmGlobalNinjaGenerator::WriteRule(*this->RulesFileStream, rule);
  762. }
  763. bool cmGlobalNinjaGenerator::HasRule(const std::string& name)
  764. {
  765. return (this->Rules.find(name) != this->Rules.end());
  766. }
  767. // Private virtual overrides
  768. std::string cmGlobalNinjaGenerator::GetEditCacheCommand() const
  769. {
  770. // Ninja by design does not run interactive tools in the terminal,
  771. // so our only choice is cmake-gui.
  772. return cmSystemTools::GetCMakeGUICommand();
  773. }
  774. void cmGlobalNinjaGenerator::ComputeTargetObjectDirectory(
  775. cmGeneratorTarget* gt) const
  776. {
  777. // Compute full path to object file directory for this target.
  778. std::string dir = cmStrCat(gt->LocalGenerator->GetCurrentBinaryDirectory(),
  779. '/', gt->LocalGenerator->GetTargetDirectory(gt),
  780. '/', this->GetCMakeCFGIntDir(), '/');
  781. gt->ObjectDirectory = dir;
  782. }
  783. // Private methods
  784. bool cmGlobalNinjaGenerator::OpenBuildFileStreams()
  785. {
  786. if (!this->OpenFileStream(this->BuildFileStream,
  787. cmGlobalNinjaGenerator::NINJA_BUILD_FILE)) {
  788. return false;
  789. }
  790. // Write a comment about this file.
  791. *this->BuildFileStream
  792. << "# This file contains all the build statements describing the\n"
  793. << "# compilation DAG.\n\n";
  794. return true;
  795. }
  796. bool cmGlobalNinjaGenerator::OpenFileStream(
  797. std::unique_ptr<cmGeneratedFileStream>& stream, const std::string& name)
  798. {
  799. // Get a stream where to generate things.
  800. if (!stream) {
  801. // Compute Ninja's build file path.
  802. std::string path =
  803. cmStrCat(this->GetCMakeInstance()->GetHomeOutputDirectory(), '/', name);
  804. stream = cm::make_unique<cmGeneratedFileStream>(
  805. path, false, this->GetMakefileEncoding());
  806. if (!(*stream)) {
  807. // An error message is generated by the constructor if it cannot
  808. // open the file.
  809. return false;
  810. }
  811. // Write the do not edit header.
  812. this->WriteDisclaimer(*stream);
  813. }
  814. return true;
  815. }
  816. cm::optional<std::set<std::string>> cmGlobalNinjaGenerator::ListSubsetWithAll(
  817. const std::set<std::string>& all, const std::set<std::string>& defaults,
  818. const std::vector<std::string>& items)
  819. {
  820. std::set<std::string> result;
  821. for (auto const& item : items) {
  822. if (item == "all") {
  823. if (items.size() == 1) {
  824. result = defaults;
  825. } else {
  826. return cm::nullopt;
  827. }
  828. } else if (all.count(item)) {
  829. result.insert(item);
  830. } else {
  831. return cm::nullopt;
  832. }
  833. }
  834. return cm::make_optional(result);
  835. }
  836. void cmGlobalNinjaGenerator::CloseBuildFileStreams()
  837. {
  838. if (this->BuildFileStream) {
  839. this->BuildFileStream.reset();
  840. } else {
  841. cmSystemTools::Error("Build file stream was not open.");
  842. }
  843. }
  844. bool cmGlobalNinjaGenerator::OpenRulesFileStream()
  845. {
  846. if (!this->OpenFileStream(this->RulesFileStream,
  847. cmGlobalNinjaGenerator::NINJA_RULES_FILE)) {
  848. return false;
  849. }
  850. // Write comment about this file.
  851. /* clang-format off */
  852. *this->RulesFileStream
  853. << "# This file contains all the rules used to get the outputs files\n"
  854. << "# built from the input files.\n"
  855. << "# It is included in the main '" << NINJA_BUILD_FILE << "'.\n\n"
  856. ;
  857. /* clang-format on */
  858. return true;
  859. }
  860. void cmGlobalNinjaGenerator::CloseRulesFileStream()
  861. {
  862. if (this->RulesFileStream) {
  863. this->RulesFileStream.reset();
  864. } else {
  865. cmSystemTools::Error("Rules file stream was not open.");
  866. }
  867. }
  868. static void EnsureTrailingSlash(std::string& path)
  869. {
  870. if (path.empty()) {
  871. return;
  872. }
  873. std::string::value_type last = path.back();
  874. #ifdef _WIN32
  875. if (last != '\\') {
  876. path += '\\';
  877. }
  878. #else
  879. if (last != '/') {
  880. path += '/';
  881. }
  882. #endif
  883. }
  884. std::string const& cmGlobalNinjaGenerator::ConvertToNinjaPath(
  885. const std::string& path) const
  886. {
  887. auto const f = ConvertToNinjaPathCache.find(path);
  888. if (f != ConvertToNinjaPathCache.end()) {
  889. return f->second;
  890. }
  891. const auto& ng =
  892. cm::static_reference_cast<cmLocalNinjaGenerator>(this->LocalGenerators[0]);
  893. std::string const& bin_dir = ng.GetState()->GetBinaryDirectory();
  894. std::string convPath = ng.MaybeConvertToRelativePath(bin_dir, path);
  895. convPath = this->NinjaOutputPath(convPath);
  896. #ifdef _WIN32
  897. std::replace(convPath.begin(), convPath.end(), '/', '\\');
  898. #endif
  899. return ConvertToNinjaPathCache.emplace(path, std::move(convPath))
  900. .first->second;
  901. }
  902. void cmGlobalNinjaGenerator::AddAdditionalCleanFile(std::string fileName,
  903. const std::string& config)
  904. {
  905. this->Configs[config].AdditionalCleanFiles.emplace(std::move(fileName));
  906. }
  907. void cmGlobalNinjaGenerator::AddCXXCompileCommand(
  908. const std::string& commandLine, const std::string& sourceFile)
  909. {
  910. // Compute Ninja's build file path.
  911. std::string buildFileDir =
  912. this->GetCMakeInstance()->GetHomeOutputDirectory();
  913. if (!this->CompileCommandsStream) {
  914. std::string buildFilePath =
  915. cmStrCat(buildFileDir, "/compile_commands.json");
  916. if (this->ComputingUnknownDependencies) {
  917. this->CombinedBuildOutputs.insert(
  918. this->NinjaOutputPath("compile_commands.json"));
  919. }
  920. // Get a stream where to generate things.
  921. this->CompileCommandsStream =
  922. cm::make_unique<cmGeneratedFileStream>(buildFilePath);
  923. *this->CompileCommandsStream << "[\n";
  924. } else {
  925. *this->CompileCommandsStream << ",\n";
  926. }
  927. std::string sourceFileName = sourceFile;
  928. if (!cmSystemTools::FileIsFullPath(sourceFileName)) {
  929. sourceFileName = cmSystemTools::CollapseFullPath(
  930. sourceFileName, this->GetCMakeInstance()->GetHomeOutputDirectory());
  931. }
  932. /* clang-format off */
  933. *this->CompileCommandsStream << "{\n"
  934. << R"( "directory": ")"
  935. << cmGlobalGenerator::EscapeJSON(buildFileDir) << "\",\n"
  936. << R"( "command": ")"
  937. << cmGlobalGenerator::EscapeJSON(commandLine) << "\",\n"
  938. << R"( "file": ")"
  939. << cmGlobalGenerator::EscapeJSON(sourceFileName) << "\"\n"
  940. << "}";
  941. /* clang-format on */
  942. }
  943. void cmGlobalNinjaGenerator::CloseCompileCommandsStream()
  944. {
  945. if (this->CompileCommandsStream) {
  946. *this->CompileCommandsStream << "\n]";
  947. this->CompileCommandsStream.reset();
  948. }
  949. }
  950. void cmGlobalNinjaGenerator::WriteDisclaimer(std::ostream& os)
  951. {
  952. os << "# CMAKE generated file: DO NOT EDIT!\n"
  953. << "# Generated by \"" << this->GetName() << "\""
  954. << " Generator, CMake Version " << cmVersion::GetMajorVersion() << "."
  955. << cmVersion::GetMinorVersion() << "\n\n";
  956. }
  957. void cmGlobalNinjaGenerator::WriteAssumedSourceDependencies()
  958. {
  959. for (auto const& asd : this->AssumedSourceDependencies) {
  960. cmNinjaDeps orderOnlyDeps;
  961. std::copy(asd.second.begin(), asd.second.end(),
  962. std::back_inserter(orderOnlyDeps));
  963. WriteCustomCommandBuild(/*command=*/"", /*description=*/"",
  964. "Assume dependencies for generated source file.",
  965. /*depfile*/ "", /*job_pool*/ "",
  966. /*uses_terminal*/ false,
  967. /*restat*/ true, cmNinjaDeps(1, asd.first), "",
  968. cmNinjaDeps(), orderOnlyDeps);
  969. }
  970. }
  971. std::string cmGlobalNinjaGenerator::OrderDependsTargetForTarget(
  972. cmGeneratorTarget const* target, const std::string& /*config*/) const
  973. {
  974. return cmStrCat("cmake_object_order_depends_target_", target->GetName());
  975. }
  976. void cmGlobalNinjaGenerator::AppendTargetOutputs(
  977. cmGeneratorTarget const* target, cmNinjaDeps& outputs,
  978. const std::string& config, cmNinjaTargetDepends depends)
  979. {
  980. // for frameworks, we want the real name, not smple name
  981. // frameworks always appear versioned, and the build.ninja
  982. // will always attempt to manage symbolic links instead
  983. // of letting cmOSXBundleGenerator do it.
  984. bool realname = target->IsFrameworkOnApple();
  985. switch (target->GetType()) {
  986. case cmStateEnums::SHARED_LIBRARY:
  987. case cmStateEnums::STATIC_LIBRARY:
  988. case cmStateEnums::MODULE_LIBRARY: {
  989. if (depends == DependOnTargetOrdering) {
  990. outputs.push_back(OrderDependsTargetForTarget(target, config));
  991. break;
  992. }
  993. }
  994. // FALLTHROUGH
  995. case cmStateEnums::EXECUTABLE: {
  996. outputs.push_back(this->ConvertToNinjaPath(target->GetFullPath(
  997. config, cmStateEnums::RuntimeBinaryArtifact, realname)));
  998. break;
  999. }
  1000. case cmStateEnums::OBJECT_LIBRARY: {
  1001. if (depends == DependOnTargetOrdering) {
  1002. outputs.push_back(OrderDependsTargetForTarget(target, config));
  1003. break;
  1004. }
  1005. }
  1006. // FALLTHROUGH
  1007. case cmStateEnums::GLOBAL_TARGET:
  1008. case cmStateEnums::INTERFACE_LIBRARY:
  1009. case cmStateEnums::UTILITY: {
  1010. std::string path =
  1011. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), '/',
  1012. target->GetName());
  1013. std::string output = this->ConvertToNinjaPath(path);
  1014. if (target->Target->IsPerConfig()) {
  1015. output = this->BuildAlias(output, config);
  1016. }
  1017. outputs.push_back(output);
  1018. break;
  1019. }
  1020. case cmStateEnums::UNKNOWN_LIBRARY:
  1021. break;
  1022. }
  1023. }
  1024. void cmGlobalNinjaGenerator::AppendTargetDepends(
  1025. cmGeneratorTarget const* target, cmNinjaDeps& outputs,
  1026. const std::string& config, const std::string& fileConfig,
  1027. cmNinjaTargetDepends depends)
  1028. {
  1029. if (target->GetType() == cmStateEnums::GLOBAL_TARGET) {
  1030. // These depend only on other CMake-provided targets, e.g. "all".
  1031. for (BT<std::pair<std::string, bool>> const& util :
  1032. target->GetUtilities()) {
  1033. std::string d =
  1034. cmStrCat(target->GetLocalGenerator()->GetCurrentBinaryDirectory(), '/',
  1035. util.Value.first);
  1036. outputs.push_back(this->BuildAlias(this->ConvertToNinjaPath(d), config));
  1037. }
  1038. } else {
  1039. cmNinjaDeps outs;
  1040. auto computeISPCOuputs = [](cmGlobalNinjaGenerator* gg,
  1041. cmGeneratorTarget const* depTarget,
  1042. cmNinjaDeps& outputDeps,
  1043. const std::string& targetConfig) {
  1044. if (depTarget->CanCompileSources()) {
  1045. auto headers = depTarget->GetGeneratedISPCHeaders(targetConfig);
  1046. if (!headers.empty()) {
  1047. std::transform(headers.begin(), headers.end(), headers.begin(),
  1048. gg->MapToNinjaPath());
  1049. outputDeps.insert(outputDeps.end(), headers.begin(), headers.end());
  1050. }
  1051. auto objs = depTarget->GetGeneratedISPCObjects(targetConfig);
  1052. if (!objs.empty()) {
  1053. std::transform(objs.begin(), objs.end(), objs.begin(),
  1054. gg->MapToNinjaPath());
  1055. outputDeps.insert(outputDeps.end(), objs.begin(), objs.end());
  1056. }
  1057. }
  1058. };
  1059. for (cmTargetDepend const& targetDep :
  1060. this->GetTargetDirectDepends(target)) {
  1061. if (!targetDep->IsInBuildSystem()) {
  1062. continue;
  1063. }
  1064. if (targetDep.IsCross()) {
  1065. this->AppendTargetOutputs(targetDep, outs, fileConfig, depends);
  1066. computeISPCOuputs(this, targetDep, outs, fileConfig);
  1067. } else {
  1068. this->AppendTargetOutputs(targetDep, outs, config, depends);
  1069. computeISPCOuputs(this, targetDep, outs, config);
  1070. }
  1071. }
  1072. std::sort(outs.begin(), outs.end());
  1073. cm::append(outputs, outs);
  1074. }
  1075. }
  1076. void cmGlobalNinjaGenerator::AppendTargetDependsClosure(
  1077. cmGeneratorTarget const* target, cmNinjaDeps& outputs,
  1078. const std::string& config)
  1079. {
  1080. cmNinjaOuts outs;
  1081. this->AppendTargetDependsClosure(target, outs, config, true);
  1082. cm::append(outputs, outs);
  1083. }
  1084. void cmGlobalNinjaGenerator::AppendTargetDependsClosure(
  1085. cmGeneratorTarget const* target, cmNinjaOuts& outputs,
  1086. const std::string& config, bool omit_self)
  1087. {
  1088. // try to locate the target in the cache
  1089. auto find = this->Configs[config].TargetDependsClosures.lower_bound(target);
  1090. if (find == this->Configs[config].TargetDependsClosures.end() ||
  1091. find->first != target) {
  1092. // We now calculate the closure outputs by inspecting the dependent
  1093. // targets recursively.
  1094. // For that we have to distinguish between a local result set that is only
  1095. // relevant for filling the cache entries properly isolated and a global
  1096. // result set that is relevant for the result of the top level call to
  1097. // AppendTargetDependsClosure.
  1098. cmNinjaOuts this_outs; // this will be the new cache entry
  1099. for (auto const& dep_target : this->GetTargetDirectDepends(target)) {
  1100. if (!dep_target->IsInBuildSystem() ||
  1101. (target->GetType() != cmStateEnums::UTILITY &&
  1102. dep_target->GetType() != cmStateEnums::UTILITY &&
  1103. this->EnableCrossConfigBuild() && !dep_target.IsCross())) {
  1104. continue;
  1105. }
  1106. // Collect the dependent targets for _this_ target
  1107. this->AppendTargetDependsClosure(dep_target, this_outs, config, false);
  1108. }
  1109. find = this->Configs[config].TargetDependsClosures.emplace_hint(
  1110. find, target, std::move(this_outs));
  1111. }
  1112. // now fill the outputs of the final result from the newly generated cache
  1113. // entry
  1114. outputs.insert(find->second.begin(), find->second.end());
  1115. // finally generate the outputs of the target itself, if applicable
  1116. cmNinjaDeps outs;
  1117. if (!omit_self) {
  1118. this->AppendTargetOutputs(target, outs, config, DependOnTargetArtifact);
  1119. }
  1120. outputs.insert(outs.begin(), outs.end());
  1121. }
  1122. void cmGlobalNinjaGenerator::AddTargetAlias(const std::string& alias,
  1123. cmGeneratorTarget* target,
  1124. const std::string& config)
  1125. {
  1126. std::string outputPath = this->NinjaOutputPath(alias);
  1127. std::string buildAlias = this->BuildAlias(outputPath, config);
  1128. cmNinjaDeps outputs;
  1129. if (config != "all") {
  1130. this->AppendTargetOutputs(target, outputs, config, DependOnTargetArtifact);
  1131. }
  1132. // Mark the target's outputs as ambiguous to ensure that no other target
  1133. // uses the output as an alias.
  1134. for (std::string const& output : outputs) {
  1135. this->TargetAliases[output].GeneratorTarget = nullptr;
  1136. this->DefaultTargetAliases[output].GeneratorTarget = nullptr;
  1137. for (const std::string& config2 :
  1138. this->Makefiles.front()->GetGeneratorConfigs(
  1139. cmMakefile::IncludeEmptyConfig)) {
  1140. this->Configs[config2].TargetAliases[output].GeneratorTarget = nullptr;
  1141. }
  1142. }
  1143. // Insert the alias into the map. If the alias was already present in the
  1144. // map and referred to another target, mark it as ambiguous.
  1145. TargetAlias ta;
  1146. ta.GeneratorTarget = target;
  1147. ta.Config = config;
  1148. auto newAliasGlobal =
  1149. this->TargetAliases.insert(std::make_pair(buildAlias, ta));
  1150. if (newAliasGlobal.second &&
  1151. newAliasGlobal.first->second.GeneratorTarget != target) {
  1152. newAliasGlobal.first->second.GeneratorTarget = nullptr;
  1153. }
  1154. auto newAliasConfig =
  1155. this->Configs[config].TargetAliases.insert(std::make_pair(outputPath, ta));
  1156. if (newAliasConfig.second &&
  1157. newAliasConfig.first->second.GeneratorTarget != target) {
  1158. newAliasConfig.first->second.GeneratorTarget = nullptr;
  1159. }
  1160. if (this->DefaultConfigs.count(config)) {
  1161. auto newAliasDefaultGlobal =
  1162. this->DefaultTargetAliases.insert(std::make_pair(outputPath, ta));
  1163. if (newAliasDefaultGlobal.second &&
  1164. newAliasDefaultGlobal.first->second.GeneratorTarget != target) {
  1165. newAliasDefaultGlobal.first->second.GeneratorTarget = nullptr;
  1166. }
  1167. }
  1168. }
  1169. void cmGlobalNinjaGenerator::WriteTargetAliases(std::ostream& os)
  1170. {
  1171. cmGlobalNinjaGenerator::WriteDivider(os);
  1172. os << "# Target aliases.\n\n";
  1173. cmNinjaBuild build("phony");
  1174. build.Outputs.emplace_back();
  1175. for (auto const& ta : this->TargetAliases) {
  1176. // Don't write ambiguous aliases.
  1177. if (!ta.second.GeneratorTarget) {
  1178. continue;
  1179. }
  1180. // Don't write alias if there is a already a custom command with
  1181. // matching output
  1182. if (this->HasCustomCommandOutput(ta.first)) {
  1183. continue;
  1184. }
  1185. build.Outputs.front() = ta.first;
  1186. build.ExplicitDeps.clear();
  1187. if (ta.second.Config == "all") {
  1188. for (auto const& config : this->CrossConfigs) {
  1189. this->AppendTargetOutputs(ta.second.GeneratorTarget,
  1190. build.ExplicitDeps, config,
  1191. DependOnTargetArtifact);
  1192. }
  1193. } else {
  1194. this->AppendTargetOutputs(ta.second.GeneratorTarget, build.ExplicitDeps,
  1195. ta.second.Config, DependOnTargetArtifact);
  1196. }
  1197. this->WriteBuild(this->EnableCrossConfigBuild() &&
  1198. (ta.second.Config == "all" ||
  1199. this->CrossConfigs.count(ta.second.Config))
  1200. ? os
  1201. : *this->GetImplFileStream(ta.second.Config),
  1202. build);
  1203. }
  1204. if (this->IsMultiConfig()) {
  1205. for (auto const& config : this->Makefiles.front()->GetGeneratorConfigs(
  1206. cmMakefile::IncludeEmptyConfig)) {
  1207. for (auto const& ta : this->Configs[config].TargetAliases) {
  1208. // Don't write ambiguous aliases.
  1209. if (!ta.second.GeneratorTarget) {
  1210. continue;
  1211. }
  1212. // Don't write alias if there is a already a custom command with
  1213. // matching output
  1214. if (this->HasCustomCommandOutput(ta.first)) {
  1215. continue;
  1216. }
  1217. build.Outputs.front() = ta.first;
  1218. build.ExplicitDeps.clear();
  1219. this->AppendTargetOutputs(ta.second.GeneratorTarget,
  1220. build.ExplicitDeps, config,
  1221. DependOnTargetArtifact);
  1222. this->WriteBuild(*this->GetConfigFileStream(config), build);
  1223. }
  1224. }
  1225. if (!this->DefaultConfigs.empty()) {
  1226. for (auto const& ta : this->DefaultTargetAliases) {
  1227. // Don't write ambiguous aliases.
  1228. if (!ta.second.GeneratorTarget) {
  1229. continue;
  1230. }
  1231. // Don't write alias if there is a already a custom command with
  1232. // matching output
  1233. if (this->HasCustomCommandOutput(ta.first)) {
  1234. continue;
  1235. }
  1236. build.Outputs.front() = ta.first;
  1237. build.ExplicitDeps.clear();
  1238. for (auto const& config : this->DefaultConfigs) {
  1239. this->AppendTargetOutputs(ta.second.GeneratorTarget,
  1240. build.ExplicitDeps, config,
  1241. DependOnTargetArtifact);
  1242. }
  1243. this->WriteBuild(*this->GetDefaultFileStream(), build);
  1244. }
  1245. }
  1246. }
  1247. }
  1248. void cmGlobalNinjaGenerator::WriteFolderTargets(std::ostream& os)
  1249. {
  1250. cmGlobalNinjaGenerator::WriteDivider(os);
  1251. os << "# Folder targets.\n\n";
  1252. std::map<std::string, DirectoryTarget> dirTargets =
  1253. this->ComputeDirectoryTargets();
  1254. for (auto const& it : dirTargets) {
  1255. cmNinjaBuild build("phony");
  1256. cmGlobalNinjaGenerator::WriteDivider(os);
  1257. std::string const& currentBinaryDir = it.first;
  1258. DirectoryTarget const& dt = it.second;
  1259. std::vector<std::string> configs =
  1260. dt.LG->GetMakefile()->GetGeneratorConfigs(
  1261. cmMakefile::IncludeEmptyConfig);
  1262. // Setup target
  1263. cmNinjaDeps configDeps;
  1264. build.Comment = cmStrCat("Folder: ", currentBinaryDir);
  1265. build.Outputs.emplace_back();
  1266. std::string const buildDirAllTarget =
  1267. this->ConvertToNinjaPath(cmStrCat(currentBinaryDir, "/all"));
  1268. for (auto const& config : configs) {
  1269. build.ExplicitDeps.clear();
  1270. build.Outputs.front() = this->BuildAlias(buildDirAllTarget, config);
  1271. configDeps.emplace_back(build.Outputs.front());
  1272. for (DirectoryTarget::Target const& t : dt.Targets) {
  1273. if (!IsExcludedFromAllInConfig(t, config)) {
  1274. this->AppendTargetOutputs(t.GT, build.ExplicitDeps, config,
  1275. DependOnTargetArtifact);
  1276. }
  1277. }
  1278. for (DirectoryTarget::Dir const& d : dt.Children) {
  1279. if (!d.ExcludeFromAll) {
  1280. build.ExplicitDeps.emplace_back(this->BuildAlias(
  1281. this->ConvertToNinjaPath(cmStrCat(d.Path, "/all")), config));
  1282. }
  1283. }
  1284. // Write target
  1285. this->WriteBuild(this->EnableCrossConfigBuild() &&
  1286. this->CrossConfigs.count(config)
  1287. ? os
  1288. : *this->GetImplFileStream(config),
  1289. build);
  1290. }
  1291. // Add shortcut target
  1292. if (this->IsMultiConfig()) {
  1293. for (auto const& config : configs) {
  1294. build.ExplicitDeps = { this->BuildAlias(buildDirAllTarget, config) };
  1295. build.Outputs.front() = buildDirAllTarget;
  1296. this->WriteBuild(*this->GetConfigFileStream(config), build);
  1297. }
  1298. if (!this->DefaultFileConfig.empty()) {
  1299. build.ExplicitDeps.clear();
  1300. for (auto const& config : this->DefaultConfigs) {
  1301. build.ExplicitDeps.push_back(
  1302. this->BuildAlias(buildDirAllTarget, config));
  1303. }
  1304. build.Outputs.front() = buildDirAllTarget;
  1305. this->WriteBuild(*this->GetDefaultFileStream(), build);
  1306. }
  1307. }
  1308. // Add target for all configs
  1309. if (this->EnableCrossConfigBuild()) {
  1310. build.ExplicitDeps.clear();
  1311. for (auto const& config : this->CrossConfigs) {
  1312. build.ExplicitDeps.push_back(
  1313. this->BuildAlias(buildDirAllTarget, config));
  1314. }
  1315. build.Outputs.front() = this->BuildAlias(buildDirAllTarget, "all");
  1316. this->WriteBuild(os, build);
  1317. }
  1318. }
  1319. }
  1320. void cmGlobalNinjaGenerator::WriteUnknownExplicitDependencies(std::ostream& os)
  1321. {
  1322. if (!this->ComputingUnknownDependencies) {
  1323. return;
  1324. }
  1325. // We need to collect the set of known build outputs.
  1326. // Start with those generated by WriteBuild calls.
  1327. // No other method needs this so we can take ownership
  1328. // of the set locally and throw it out when we are done.
  1329. std::set<std::string> knownDependencies;
  1330. knownDependencies.swap(this->CombinedBuildOutputs);
  1331. // now write out the unknown explicit dependencies.
  1332. // union the configured files, evaluations files and the
  1333. // CombinedBuildOutputs,
  1334. // and then difference with CombinedExplicitDependencies to find the explicit
  1335. // dependencies that we have no rule for
  1336. cmGlobalNinjaGenerator::WriteDivider(os);
  1337. /* clang-format off */
  1338. os << "# Unknown Build Time Dependencies.\n"
  1339. << "# Tell Ninja that they may appear as side effects of build rules\n"
  1340. << "# otherwise ordered by order-only dependencies.\n\n";
  1341. /* clang-format on */
  1342. // get the list of files that cmake itself has generated as a
  1343. // product of configuration.
  1344. for (const auto& lg : this->LocalGenerators) {
  1345. // get the vector of files created by this makefile and convert them
  1346. // to ninja paths, which are all relative in respect to the build directory
  1347. for (std::string const& file : lg->GetMakefile()->GetOutputFiles()) {
  1348. knownDependencies.insert(this->ConvertToNinjaPath(file));
  1349. }
  1350. if (!this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION")) {
  1351. // get list files which are implicit dependencies as well and will be
  1352. // phony for rebuild manifest
  1353. for (std::string const& j : lg->GetMakefile()->GetListFiles()) {
  1354. knownDependencies.insert(this->ConvertToNinjaPath(j));
  1355. }
  1356. }
  1357. for (const auto& li : lg->GetMakefile()->GetEvaluationFiles()) {
  1358. // get all the files created by generator expressions and convert them
  1359. // to ninja paths
  1360. for (std::string const& evaluationFile : li->GetFiles()) {
  1361. knownDependencies.insert(this->ConvertToNinjaPath(evaluationFile));
  1362. }
  1363. }
  1364. }
  1365. knownDependencies.insert(this->CMakeCacheFile);
  1366. for (auto const& ta : this->TargetAliases) {
  1367. knownDependencies.insert(this->ConvertToNinjaPath(ta.first));
  1368. }
  1369. // remove all source files we know will exist.
  1370. for (auto const& i : this->AssumedSourceDependencies) {
  1371. knownDependencies.insert(this->ConvertToNinjaPath(i.first));
  1372. }
  1373. // now we difference with CombinedCustomCommandExplicitDependencies to find
  1374. // the list of items we know nothing about.
  1375. // We have encoded all the paths in CombinedCustomCommandExplicitDependencies
  1376. // and knownDependencies so no matter if unix or windows paths they
  1377. // should all match now.
  1378. std::vector<std::string> unknownExplicitDepends;
  1379. this->CombinedCustomCommandExplicitDependencies.erase(this->TargetAll);
  1380. std::set_difference(this->CombinedCustomCommandExplicitDependencies.begin(),
  1381. this->CombinedCustomCommandExplicitDependencies.end(),
  1382. knownDependencies.begin(), knownDependencies.end(),
  1383. std::back_inserter(unknownExplicitDepends));
  1384. std::vector<std::string> warnExplicitDepends;
  1385. if (!unknownExplicitDepends.empty()) {
  1386. cmake* cmk = this->GetCMakeInstance();
  1387. std::string const& buildRoot = cmk->GetHomeOutputDirectory();
  1388. bool const inSource = (buildRoot == cmk->GetHomeDirectory());
  1389. bool const warn = (!inSource && (this->PolicyCMP0058 == cmPolicies::WARN));
  1390. cmNinjaBuild build("phony");
  1391. build.Outputs.emplace_back("");
  1392. for (std::string const& ued : unknownExplicitDepends) {
  1393. // verify the file is in the build directory
  1394. std::string const absDepPath =
  1395. cmSystemTools::CollapseFullPath(ued, buildRoot);
  1396. if (cmSystemTools::IsSubDirectory(absDepPath, buildRoot)) {
  1397. // Generate phony build statement
  1398. build.Outputs[0] = ued;
  1399. this->WriteBuild(os, build);
  1400. // Add to warning on demand
  1401. if (warn && warnExplicitDepends.size() < 10) {
  1402. warnExplicitDepends.push_back(ued);
  1403. }
  1404. }
  1405. }
  1406. }
  1407. if (!warnExplicitDepends.empty()) {
  1408. std::ostringstream w;
  1409. /* clang-format off */
  1410. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0058) << "\n"
  1411. "This project specifies custom command DEPENDS on files "
  1412. "in the build tree that are not specified as the OUTPUT or "
  1413. "BYPRODUCTS of any add_custom_command or add_custom_target:\n"
  1414. " " << cmJoin(warnExplicitDepends, "\n ") <<
  1415. "\n"
  1416. "For compatibility with versions of CMake that did not have "
  1417. "the BYPRODUCTS option, CMake is generating phony rules for "
  1418. "such files to convince 'ninja' to build."
  1419. "\n"
  1420. "Project authors should add the missing BYPRODUCTS or OUTPUT "
  1421. "options to the custom commands that produce these files."
  1422. ;
  1423. /* clang-format on */
  1424. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  1425. w.str());
  1426. }
  1427. }
  1428. void cmGlobalNinjaGenerator::WriteBuiltinTargets(std::ostream& os)
  1429. {
  1430. // Write headers.
  1431. cmGlobalNinjaGenerator::WriteDivider(os);
  1432. os << "# Built-in targets\n\n";
  1433. this->WriteTargetRebuildManifest(os);
  1434. this->WriteTargetClean(os);
  1435. this->WriteTargetHelp(os);
  1436. for (auto const& config : this->Makefiles[0]->GetGeneratorConfigs(
  1437. cmMakefile::IncludeEmptyConfig)) {
  1438. this->WriteTargetDefault(*this->GetConfigFileStream(config));
  1439. }
  1440. if (!this->DefaultFileConfig.empty()) {
  1441. this->WriteTargetDefault(*this->GetDefaultFileStream());
  1442. }
  1443. }
  1444. void cmGlobalNinjaGenerator::WriteTargetDefault(std::ostream& os)
  1445. {
  1446. if (!this->HasOutputPathPrefix()) {
  1447. cmNinjaDeps all;
  1448. all.push_back(this->TargetAll);
  1449. cmGlobalNinjaGenerator::WriteDefault(os, all,
  1450. "Make the all target the default.");
  1451. }
  1452. }
  1453. void cmGlobalNinjaGenerator::WriteTargetRebuildManifest(std::ostream& os)
  1454. {
  1455. if (this->GlobalSettingIsOn("CMAKE_SUPPRESS_REGENERATION")) {
  1456. return;
  1457. }
  1458. const auto& lg = this->LocalGenerators[0];
  1459. {
  1460. cmNinjaRule rule("RERUN_CMAKE");
  1461. rule.Command =
  1462. cmStrCat(CMakeCmd(), " --regenerate-during-build -S",
  1463. lg->ConvertToOutputFormat(lg->GetSourceDirectory(),
  1464. cmOutputConverter::SHELL),
  1465. " -B",
  1466. lg->ConvertToOutputFormat(lg->GetBinaryDirectory(),
  1467. cmOutputConverter::SHELL));
  1468. rule.Description = "Re-running CMake...";
  1469. rule.Comment = "Rule for re-running cmake.";
  1470. rule.Generator = true;
  1471. WriteRule(*this->RulesFileStream, rule);
  1472. }
  1473. cmNinjaBuild reBuild("RERUN_CMAKE");
  1474. reBuild.Comment = "Re-run CMake if any of its inputs changed.";
  1475. this->AddRebuildManifestOutputs(reBuild.Outputs);
  1476. for (const auto& localGen : this->LocalGenerators) {
  1477. for (std::string const& fi : localGen->GetMakefile()->GetListFiles()) {
  1478. reBuild.ImplicitDeps.push_back(this->ConvertToNinjaPath(fi));
  1479. }
  1480. }
  1481. reBuild.ImplicitDeps.push_back(this->CMakeCacheFile);
  1482. // Use 'console' pool to get non buffered output of the CMake re-run call
  1483. // Available since Ninja 1.5
  1484. if (SupportsConsolePool()) {
  1485. reBuild.Variables["pool"] = "console";
  1486. }
  1487. cmake* cm = this->GetCMakeInstance();
  1488. if (this->SupportsManifestRestat() && cm->DoWriteGlobVerifyTarget()) {
  1489. {
  1490. cmNinjaRule rule("VERIFY_GLOBS");
  1491. rule.Command =
  1492. cmStrCat(CMakeCmd(), " -P ",
  1493. lg->ConvertToOutputFormat(cm->GetGlobVerifyScript(),
  1494. cmOutputConverter::SHELL));
  1495. rule.Description = "Re-checking globbed directories...";
  1496. rule.Comment = "Rule for re-checking globbed directories.";
  1497. rule.Generator = true;
  1498. this->WriteRule(*this->RulesFileStream, rule);
  1499. }
  1500. cmNinjaBuild phonyBuild("phony");
  1501. phonyBuild.Comment = "Phony target to force glob verification run.";
  1502. phonyBuild.Outputs.push_back(
  1503. cmStrCat(cm->GetGlobVerifyScript(), "_force"));
  1504. this->WriteBuild(os, phonyBuild);
  1505. reBuild.Variables["restat"] = "1";
  1506. std::string const verifyScriptFile =
  1507. this->NinjaOutputPath(cm->GetGlobVerifyScript());
  1508. std::string const verifyStampFile =
  1509. this->NinjaOutputPath(cm->GetGlobVerifyStamp());
  1510. {
  1511. cmNinjaBuild vgBuild("VERIFY_GLOBS");
  1512. vgBuild.Comment =
  1513. "Re-run CMake to check if globbed directories changed.";
  1514. vgBuild.Outputs.push_back(verifyStampFile);
  1515. vgBuild.ImplicitDeps = phonyBuild.Outputs;
  1516. vgBuild.Variables = reBuild.Variables;
  1517. this->WriteBuild(os, vgBuild);
  1518. }
  1519. reBuild.Variables.erase("restat");
  1520. reBuild.ImplicitDeps.push_back(verifyScriptFile);
  1521. reBuild.ExplicitDeps.push_back(verifyStampFile);
  1522. } else if (!this->SupportsManifestRestat() &&
  1523. cm->DoWriteGlobVerifyTarget()) {
  1524. std::ostringstream msg;
  1525. msg << "The detected version of Ninja:\n"
  1526. << " " << this->NinjaVersion << "\n"
  1527. << "is less than the version of Ninja required by CMake for adding "
  1528. "restat dependencies to the build.ninja manifest regeneration "
  1529. "target:\n"
  1530. << " "
  1531. << cmGlobalNinjaGenerator::RequiredNinjaVersionForManifestRestat()
  1532. << "\n";
  1533. msg << "Any pre-check scripts, such as those generated for file(GLOB "
  1534. "CONFIGURE_DEPENDS), will not be run by Ninja.";
  1535. this->GetCMakeInstance()->IssueMessage(MessageType::AUTHOR_WARNING,
  1536. msg.str());
  1537. }
  1538. std::sort(reBuild.ImplicitDeps.begin(), reBuild.ImplicitDeps.end());
  1539. reBuild.ImplicitDeps.erase(
  1540. std::unique(reBuild.ImplicitDeps.begin(), reBuild.ImplicitDeps.end()),
  1541. reBuild.ImplicitDeps.end());
  1542. this->WriteBuild(os, reBuild);
  1543. {
  1544. cmNinjaBuild build("phony");
  1545. build.Comment = "A missing CMake input file is not an error.";
  1546. std::set_difference(std::make_move_iterator(reBuild.ImplicitDeps.begin()),
  1547. std::make_move_iterator(reBuild.ImplicitDeps.end()),
  1548. CustomCommandOutputs.begin(),
  1549. CustomCommandOutputs.end(),
  1550. std::back_inserter(build.Outputs));
  1551. this->WriteBuild(os, build);
  1552. }
  1553. }
  1554. std::string cmGlobalNinjaGenerator::CMakeCmd() const
  1555. {
  1556. const auto& lgen = this->LocalGenerators.at(0);
  1557. return lgen->ConvertToOutputFormat(cmSystemTools::GetCMakeCommand(),
  1558. cmOutputConverter::SHELL);
  1559. }
  1560. std::string cmGlobalNinjaGenerator::NinjaCmd() const
  1561. {
  1562. const auto& lgen = this->LocalGenerators[0];
  1563. if (lgen != nullptr) {
  1564. return lgen->ConvertToOutputFormat(this->NinjaCommand,
  1565. cmOutputConverter::SHELL);
  1566. }
  1567. return "ninja";
  1568. }
  1569. bool cmGlobalNinjaGenerator::SupportsConsolePool() const
  1570. {
  1571. return this->NinjaSupportsConsolePool;
  1572. }
  1573. bool cmGlobalNinjaGenerator::SupportsImplicitOuts() const
  1574. {
  1575. return this->NinjaSupportsImplicitOuts;
  1576. }
  1577. bool cmGlobalNinjaGenerator::SupportsManifestRestat() const
  1578. {
  1579. return this->NinjaSupportsManifestRestat;
  1580. }
  1581. bool cmGlobalNinjaGenerator::SupportsMultilineDepfile() const
  1582. {
  1583. return this->NinjaSupportsMultilineDepfile;
  1584. }
  1585. bool cmGlobalNinjaGenerator::WriteTargetCleanAdditional(std::ostream& os)
  1586. {
  1587. const auto& lgr = this->LocalGenerators.at(0);
  1588. std::string cleanScriptRel = "CMakeFiles/clean_additional.cmake";
  1589. std::string cleanScriptAbs =
  1590. cmStrCat(lgr->GetBinaryDirectory(), '/', cleanScriptRel);
  1591. std::vector<std::string> configs =
  1592. this->Makefiles[0]->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  1593. // Check if there are additional files to clean
  1594. bool empty = true;
  1595. for (auto const& config : configs) {
  1596. auto const it = this->Configs.find(config);
  1597. if (it != this->Configs.end() &&
  1598. !it->second.AdditionalCleanFiles.empty()) {
  1599. empty = false;
  1600. break;
  1601. }
  1602. }
  1603. if (empty) {
  1604. // Remove cmake clean script file if it exists
  1605. cmSystemTools::RemoveFile(cleanScriptAbs);
  1606. return false;
  1607. }
  1608. // Write cmake clean script file
  1609. {
  1610. cmGeneratedFileStream fout(cleanScriptAbs);
  1611. if (!fout) {
  1612. return false;
  1613. }
  1614. fout << "# Additional clean files\ncmake_minimum_required(VERSION 3.16)\n";
  1615. for (auto const& config : configs) {
  1616. auto const it = this->Configs.find(config);
  1617. if (it != this->Configs.end() &&
  1618. !it->second.AdditionalCleanFiles.empty()) {
  1619. fout << "\nif(\"${CONFIG}\" STREQUAL \"\" OR \"${CONFIG}\" STREQUAL \""
  1620. << config << "\")\n";
  1621. fout << " file(REMOVE_RECURSE\n";
  1622. for (std::string const& acf : it->second.AdditionalCleanFiles) {
  1623. fout << " "
  1624. << cmOutputConverter::EscapeForCMake(ConvertToNinjaPath(acf))
  1625. << '\n';
  1626. }
  1627. fout << " )\n";
  1628. fout << "endif()\n";
  1629. }
  1630. }
  1631. }
  1632. // Register clean script file
  1633. lgr->GetMakefile()->AddCMakeOutputFile(cleanScriptAbs);
  1634. // Write rule
  1635. {
  1636. cmNinjaRule rule("CLEAN_ADDITIONAL");
  1637. rule.Command = cmStrCat(
  1638. CMakeCmd(), " -DCONFIG=$CONFIG -P ",
  1639. lgr->ConvertToOutputFormat(this->NinjaOutputPath(cleanScriptRel),
  1640. cmOutputConverter::SHELL));
  1641. rule.Description = "Cleaning additional files...";
  1642. rule.Comment = "Rule for cleaning additional files.";
  1643. WriteRule(*this->RulesFileStream, rule);
  1644. }
  1645. // Write build
  1646. {
  1647. cmNinjaBuild build("CLEAN_ADDITIONAL");
  1648. build.Comment = "Clean additional files.";
  1649. build.Outputs.emplace_back();
  1650. for (auto const& config : configs) {
  1651. build.Outputs.front() = this->BuildAlias(
  1652. this->NinjaOutputPath(this->GetAdditionalCleanTargetName()), config);
  1653. build.Variables["CONFIG"] = config;
  1654. WriteBuild(os, build);
  1655. }
  1656. if (this->IsMultiConfig()) {
  1657. build.Outputs.front() =
  1658. this->NinjaOutputPath(this->GetAdditionalCleanTargetName());
  1659. build.Variables["CONFIG"] = "";
  1660. WriteBuild(os, build);
  1661. }
  1662. }
  1663. // Return success
  1664. return true;
  1665. }
  1666. void cmGlobalNinjaGenerator::WriteTargetClean(std::ostream& os)
  1667. {
  1668. // -- Additional clean target
  1669. bool additionalFiles = WriteTargetCleanAdditional(os);
  1670. // -- Default clean target
  1671. // Write rule
  1672. {
  1673. cmNinjaRule rule("CLEAN");
  1674. rule.Command = cmStrCat(NinjaCmd(), " $FILE_ARG -t clean $TARGETS");
  1675. rule.Description = "Cleaning all built files...";
  1676. rule.Comment = "Rule for cleaning all built files.";
  1677. WriteRule(*this->RulesFileStream, rule);
  1678. }
  1679. auto const configs = this->Makefiles.front()->GetGeneratorConfigs(
  1680. cmMakefile::IncludeEmptyConfig);
  1681. // Write build
  1682. {
  1683. cmNinjaBuild build("CLEAN");
  1684. build.Comment = "Clean all the built files.";
  1685. build.Outputs.emplace_back();
  1686. for (auto const& config : configs) {
  1687. build.Outputs.front() = this->BuildAlias(
  1688. this->NinjaOutputPath(this->GetCleanTargetName()), config);
  1689. if (this->IsMultiConfig()) {
  1690. build.Variables["TARGETS"] =
  1691. cmStrCat(this->BuildAlias(GetByproductsForCleanTargetName(), config),
  1692. " ", GetByproductsForCleanTargetName());
  1693. }
  1694. build.ExplicitDeps.clear();
  1695. if (additionalFiles) {
  1696. build.ExplicitDeps.push_back(this->BuildAlias(
  1697. this->NinjaOutputPath(this->GetAdditionalCleanTargetName()),
  1698. config));
  1699. }
  1700. for (auto const& fileConfig : configs) {
  1701. if (fileConfig != config && !this->EnableCrossConfigBuild()) {
  1702. continue;
  1703. }
  1704. if (this->IsMultiConfig()) {
  1705. build.Variables["FILE_ARG"] = cmStrCat(
  1706. "-f ",
  1707. cmGlobalNinjaMultiGenerator::GetNinjaImplFilename(fileConfig));
  1708. }
  1709. this->WriteBuild(*this->GetImplFileStream(fileConfig), build);
  1710. }
  1711. }
  1712. if (this->EnableCrossConfigBuild()) {
  1713. build.Outputs.front() = this->BuildAlias(
  1714. this->NinjaOutputPath(this->GetCleanTargetName()), "all");
  1715. build.ExplicitDeps.clear();
  1716. if (additionalFiles) {
  1717. for (auto const& config : this->CrossConfigs) {
  1718. build.ExplicitDeps.push_back(this->BuildAlias(
  1719. this->NinjaOutputPath(this->GetAdditionalCleanTargetName()),
  1720. config));
  1721. }
  1722. }
  1723. std::vector<std::string> byproducts;
  1724. for (auto const& config : this->CrossConfigs) {
  1725. byproducts.push_back(
  1726. this->BuildAlias(GetByproductsForCleanTargetName(), config));
  1727. }
  1728. byproducts.emplace_back(GetByproductsForCleanTargetName());
  1729. build.Variables["TARGETS"] = cmJoin(byproducts, " ");
  1730. for (auto const& fileConfig : configs) {
  1731. build.Variables["FILE_ARG"] = cmStrCat(
  1732. "-f ",
  1733. cmGlobalNinjaMultiGenerator::GetNinjaImplFilename(fileConfig));
  1734. this->WriteBuild(*this->GetImplFileStream(fileConfig), build);
  1735. }
  1736. }
  1737. }
  1738. if (this->IsMultiConfig()) {
  1739. cmNinjaBuild build("phony");
  1740. build.Outputs.emplace_back(
  1741. this->NinjaOutputPath(this->GetCleanTargetName()));
  1742. build.ExplicitDeps.emplace_back();
  1743. for (auto const& config : configs) {
  1744. build.ExplicitDeps.front() = this->BuildAlias(
  1745. this->NinjaOutputPath(this->GetCleanTargetName()), config);
  1746. this->WriteBuild(*this->GetConfigFileStream(config), build);
  1747. }
  1748. if (!this->DefaultConfigs.empty()) {
  1749. build.ExplicitDeps.clear();
  1750. for (auto const& config : this->DefaultConfigs) {
  1751. build.ExplicitDeps.push_back(this->BuildAlias(
  1752. this->NinjaOutputPath(this->GetCleanTargetName()), config));
  1753. }
  1754. this->WriteBuild(*this->GetDefaultFileStream(), build);
  1755. }
  1756. }
  1757. // Write byproducts
  1758. if (this->IsMultiConfig()) {
  1759. cmNinjaBuild build("phony");
  1760. build.Comment = "Clean byproducts.";
  1761. build.Outputs.emplace_back(
  1762. this->ConvertToNinjaPath(GetByproductsForCleanTargetName()));
  1763. build.ExplicitDeps = this->ByproductsForCleanTarget;
  1764. WriteBuild(os, build);
  1765. for (auto const& config : configs) {
  1766. build.Outputs.front() = this->BuildAlias(
  1767. this->ConvertToNinjaPath(GetByproductsForCleanTargetName()), config);
  1768. build.ExplicitDeps = this->Configs[config].ByproductsForCleanTarget;
  1769. WriteBuild(os, build);
  1770. }
  1771. }
  1772. }
  1773. void cmGlobalNinjaGenerator::WriteTargetHelp(std::ostream& os)
  1774. {
  1775. {
  1776. cmNinjaRule rule("HELP");
  1777. rule.Command = cmStrCat(NinjaCmd(), " -t targets");
  1778. rule.Description = "All primary targets available:";
  1779. rule.Comment = "Rule for printing all primary targets available.";
  1780. WriteRule(*this->RulesFileStream, rule);
  1781. }
  1782. {
  1783. cmNinjaBuild build("HELP");
  1784. build.Comment = "Print all primary targets available.";
  1785. build.Outputs.push_back(this->NinjaOutputPath("help"));
  1786. WriteBuild(os, build);
  1787. }
  1788. }
  1789. void cmGlobalNinjaGenerator::InitOutputPathPrefix()
  1790. {
  1791. this->OutputPathPrefix =
  1792. this->LocalGenerators[0]->GetMakefile()->GetSafeDefinition(
  1793. "CMAKE_NINJA_OUTPUT_PATH_PREFIX");
  1794. EnsureTrailingSlash(this->OutputPathPrefix);
  1795. }
  1796. std::string cmGlobalNinjaGenerator::NinjaOutputPath(
  1797. std::string const& path) const
  1798. {
  1799. if (!this->HasOutputPathPrefix() || cmSystemTools::FileIsFullPath(path)) {
  1800. return path;
  1801. }
  1802. return cmStrCat(this->OutputPathPrefix, path);
  1803. }
  1804. void cmGlobalNinjaGenerator::StripNinjaOutputPathPrefixAsSuffix(
  1805. std::string& path)
  1806. {
  1807. if (path.empty()) {
  1808. return;
  1809. }
  1810. EnsureTrailingSlash(path);
  1811. cmStripSuffixIfExists(path, this->OutputPathPrefix);
  1812. }
  1813. /*
  1814. We use the following approach to support Fortran. Each target already
  1815. has a <target>.dir/ directory used to hold intermediate files for CMake.
  1816. For each target, a FortranDependInfo.json file is generated by CMake with
  1817. information about include directories, module directories, and the locations
  1818. the per-target directories for target dependencies.
  1819. Compilation of source files within a target is split into the following steps:
  1820. 1. Preprocess all sources, scan preprocessed output for module dependencies.
  1821. This step is done with independent build statements for each source,
  1822. and can therefore be done in parallel.
  1823. rule Fortran_PREPROCESS
  1824. depfile = $DEP_FILE
  1825. command = gfortran -cpp $DEFINES $INCLUDES $FLAGS -E $in -o $out &&
  1826. cmake -E cmake_ninja_depends \
  1827. --tdi=FortranDependInfo.json --pp=$out --dep=$DEP_FILE \
  1828. --obj=$OBJ_FILE --ddi=$DYNDEP_INTERMEDIATE_FILE \
  1829. --lang=Fortran
  1830. build src.f90-pp.f90 | src.f90.o.ddi: Fortran_PREPROCESS src.f90
  1831. OBJ_FILE = src.f90.o
  1832. DEP_FILE = src.f90.o.d
  1833. DYNDEP_INTERMEDIATE_FILE = src.f90.o.ddi
  1834. The ``cmake -E cmake_ninja_depends`` tool reads the preprocessed output
  1835. and generates the ninja depfile for preprocessor dependencies. It also
  1836. generates a "ddi" file (in a format private to CMake) that lists the
  1837. object file that compilation will produce along with the module names
  1838. it provides and/or requires. The "ddi" file is an implicit output
  1839. because it should not appear in "$out" but is generated by the rule.
  1840. 2. Consolidate the per-source module dependencies saved in the "ddi"
  1841. files from all sources to produce a ninja "dyndep" file, ``Fortran.dd``.
  1842. rule Fortran_DYNDEP
  1843. command = cmake -E cmake_ninja_dyndep \
  1844. --tdi=FortranDependInfo.json --lang=Fortran --dd=$out $in
  1845. build Fortran.dd: Fortran_DYNDEP src1.f90.o.ddi src2.f90.o.ddi
  1846. The ``cmake -E cmake_ninja_dyndep`` tool reads the "ddi" files from all
  1847. sources in the target and the ``FortranModules.json`` files from targets
  1848. on which the target depends. It computes dependency edges on compilations
  1849. that require modules to those that provide the modules. This information
  1850. is placed in the ``Fortran.dd`` file for ninja to load later. It also
  1851. writes the expected location of modules provided by this target into
  1852. ``FortranModules.json`` for use by dependent targets.
  1853. 3. Compile all sources after loading dynamically discovered dependencies
  1854. of the compilation build statements from their ``dyndep`` bindings.
  1855. rule Fortran_COMPILE
  1856. command = gfortran $INCLUDES $FLAGS -c $in -o $out
  1857. build src1.f90.o: Fortran_COMPILE src1.f90-pp.f90 || Fortran.dd
  1858. dyndep = Fortran.dd
  1859. The "dyndep" binding tells ninja to load dynamically discovered
  1860. dependency information from ``Fortran.dd``. This adds information
  1861. such as:
  1862. build src1.f90.o | mod1.mod: dyndep
  1863. restat = 1
  1864. This tells ninja that ``mod1.mod`` is an implicit output of compiling
  1865. the object file ``src1.f90.o``. The ``restat`` binding tells it that
  1866. the timestamp of the output may not always change. Additionally:
  1867. build src2.f90.o: dyndep | mod1.mod
  1868. This tells ninja that ``mod1.mod`` is a dependency of compiling the
  1869. object file ``src2.f90.o``. This ensures that ``src1.f90.o`` and
  1870. ``mod1.mod`` will always be up to date before ``src2.f90.o`` is built
  1871. (because the latter consumes the module).
  1872. */
  1873. struct cmSourceInfo
  1874. {
  1875. // Set of provided and required modules.
  1876. std::set<std::string> Provides;
  1877. std::set<std::string> Requires;
  1878. // Set of files included in the translation unit.
  1879. std::set<std::string> Includes;
  1880. };
  1881. static std::unique_ptr<cmSourceInfo> cmcmd_cmake_ninja_depends_fortran(
  1882. std::string const& arg_tdi, std::string const& arg_pp);
  1883. int cmcmd_cmake_ninja_depends(std::vector<std::string>::const_iterator argBeg,
  1884. std::vector<std::string>::const_iterator argEnd)
  1885. {
  1886. std::string arg_tdi;
  1887. std::string arg_pp;
  1888. std::string arg_dep;
  1889. std::string arg_obj;
  1890. std::string arg_ddi;
  1891. std::string arg_lang;
  1892. for (std::string const& arg : cmMakeRange(argBeg, argEnd)) {
  1893. if (cmHasLiteralPrefix(arg, "--tdi=")) {
  1894. arg_tdi = arg.substr(6);
  1895. } else if (cmHasLiteralPrefix(arg, "--pp=")) {
  1896. arg_pp = arg.substr(5);
  1897. } else if (cmHasLiteralPrefix(arg, "--dep=")) {
  1898. arg_dep = arg.substr(6);
  1899. } else if (cmHasLiteralPrefix(arg, "--obj=")) {
  1900. arg_obj = arg.substr(6);
  1901. } else if (cmHasLiteralPrefix(arg, "--ddi=")) {
  1902. arg_ddi = arg.substr(6);
  1903. } else if (cmHasLiteralPrefix(arg, "--lang=")) {
  1904. arg_lang = arg.substr(7);
  1905. } else {
  1906. cmSystemTools::Error(
  1907. cmStrCat("-E cmake_ninja_depends unknown argument: ", arg));
  1908. return 1;
  1909. }
  1910. }
  1911. if (arg_tdi.empty()) {
  1912. cmSystemTools::Error("-E cmake_ninja_depends requires value for --tdi=");
  1913. return 1;
  1914. }
  1915. if (arg_pp.empty()) {
  1916. cmSystemTools::Error("-E cmake_ninja_depends requires value for --pp=");
  1917. return 1;
  1918. }
  1919. if (arg_dep.empty()) {
  1920. cmSystemTools::Error("-E cmake_ninja_depends requires value for --dep=");
  1921. return 1;
  1922. }
  1923. if (arg_obj.empty()) {
  1924. cmSystemTools::Error("-E cmake_ninja_depends requires value for --obj=");
  1925. return 1;
  1926. }
  1927. if (arg_ddi.empty()) {
  1928. cmSystemTools::Error("-E cmake_ninja_depends requires value for --ddi=");
  1929. return 1;
  1930. }
  1931. if (arg_lang.empty()) {
  1932. cmSystemTools::Error("-E cmake_ninja_depends requires value for --lang=");
  1933. return 1;
  1934. }
  1935. std::unique_ptr<cmSourceInfo> info;
  1936. if (arg_lang == "Fortran") {
  1937. info = cmcmd_cmake_ninja_depends_fortran(arg_tdi, arg_pp);
  1938. } else {
  1939. cmSystemTools::Error(
  1940. cmStrCat("-E cmake_ninja_depends does not understand the ", arg_lang,
  1941. " language"));
  1942. return 1;
  1943. }
  1944. if (!info) {
  1945. // The error message is already expected to have been output.
  1946. return 1;
  1947. }
  1948. {
  1949. cmGeneratedFileStream depfile(arg_dep);
  1950. depfile << cmSystemTools::ConvertToUnixOutputPath(arg_pp) << ":";
  1951. for (std::string const& include : info->Includes) {
  1952. depfile << " \\\n " << cmSystemTools::ConvertToUnixOutputPath(include);
  1953. }
  1954. depfile << "\n";
  1955. }
  1956. Json::Value ddi(Json::objectValue);
  1957. ddi["object"] = arg_obj;
  1958. Json::Value& ddi_provides = ddi["provides"] = Json::arrayValue;
  1959. for (std::string const& provide : info->Provides) {
  1960. ddi_provides.append(provide);
  1961. }
  1962. Json::Value& ddi_requires = ddi["requires"] = Json::arrayValue;
  1963. for (std::string const& r : info->Requires) {
  1964. // Require modules not provided in the same source.
  1965. if (!info->Provides.count(r)) {
  1966. ddi_requires.append(r);
  1967. }
  1968. }
  1969. cmGeneratedFileStream ddif(arg_ddi);
  1970. ddif << ddi;
  1971. if (!ddif) {
  1972. cmSystemTools::Error(
  1973. cmStrCat("-E cmake_ninja_depends failed to write ", arg_ddi));
  1974. return 1;
  1975. }
  1976. return 0;
  1977. }
  1978. std::unique_ptr<cmSourceInfo> cmcmd_cmake_ninja_depends_fortran(
  1979. std::string const& arg_tdi, std::string const& arg_pp)
  1980. {
  1981. cmFortranCompiler fc;
  1982. std::vector<std::string> includes;
  1983. {
  1984. Json::Value tdio;
  1985. Json::Value const& tdi = tdio;
  1986. {
  1987. cmsys::ifstream tdif(arg_tdi.c_str(), std::ios::in | std::ios::binary);
  1988. Json::Reader reader;
  1989. if (!reader.parse(tdif, tdio, false)) {
  1990. cmSystemTools::Error(
  1991. cmStrCat("-E cmake_ninja_depends failed to parse ", arg_tdi,
  1992. reader.getFormattedErrorMessages()));
  1993. return nullptr;
  1994. }
  1995. }
  1996. Json::Value const& tdi_include_dirs = tdi["include-dirs"];
  1997. if (tdi_include_dirs.isArray()) {
  1998. for (auto const& tdi_include_dir : tdi_include_dirs) {
  1999. includes.push_back(tdi_include_dir.asString());
  2000. }
  2001. }
  2002. Json::Value const& tdi_compiler_id = tdi["compiler-id"];
  2003. fc.Id = tdi_compiler_id.asString();
  2004. Json::Value const& tdi_submodule_sep = tdi["submodule-sep"];
  2005. fc.SModSep = tdi_submodule_sep.asString();
  2006. Json::Value const& tdi_submodule_ext = tdi["submodule-ext"];
  2007. fc.SModExt = tdi_submodule_ext.asString();
  2008. }
  2009. cmFortranSourceInfo finfo;
  2010. std::set<std::string> defines;
  2011. cmFortranParser parser(fc, includes, defines, finfo);
  2012. if (!cmFortranParser_FilePush(&parser, arg_pp.c_str())) {
  2013. cmSystemTools::Error(
  2014. cmStrCat("-E cmake_ninja_depends failed to open ", arg_pp));
  2015. return nullptr;
  2016. }
  2017. if (cmFortran_yyparse(parser.Scanner) != 0) {
  2018. // Failed to parse the file.
  2019. return nullptr;
  2020. }
  2021. auto info = cm::make_unique<cmSourceInfo>();
  2022. info->Provides = finfo.Provides;
  2023. info->Requires = finfo.Requires;
  2024. info->Includes = finfo.Includes;
  2025. return info;
  2026. }
  2027. struct cmDyndepObjectInfo
  2028. {
  2029. std::string Object;
  2030. std::vector<std::string> Provides;
  2031. std::vector<std::string> Requires;
  2032. };
  2033. bool cmGlobalNinjaGenerator::WriteDyndepFile(
  2034. std::string const& dir_top_src, std::string const& dir_top_bld,
  2035. std::string const& dir_cur_src, std::string const& dir_cur_bld,
  2036. std::string const& arg_dd, std::vector<std::string> const& arg_ddis,
  2037. std::string const& module_dir,
  2038. std::vector<std::string> const& linked_target_dirs,
  2039. std::string const& arg_lang)
  2040. {
  2041. // Setup path conversions.
  2042. {
  2043. cmStateSnapshot snapshot = this->GetCMakeInstance()->GetCurrentSnapshot();
  2044. snapshot.GetDirectory().SetCurrentSource(dir_cur_src);
  2045. snapshot.GetDirectory().SetCurrentBinary(dir_cur_bld);
  2046. snapshot.GetDirectory().SetRelativePathTopSource(dir_top_src.c_str());
  2047. snapshot.GetDirectory().SetRelativePathTopBinary(dir_top_bld.c_str());
  2048. auto mfd = cm::make_unique<cmMakefile>(this, snapshot);
  2049. auto lgd = this->CreateLocalGenerator(mfd.get());
  2050. this->Makefiles.push_back(std::move(mfd));
  2051. this->LocalGenerators.push_back(std::move(lgd));
  2052. }
  2053. std::vector<cmDyndepObjectInfo> objects;
  2054. for (std::string const& arg_ddi : arg_ddis) {
  2055. // Load the ddi file and compute the module file paths it provides.
  2056. Json::Value ddio;
  2057. Json::Value const& ddi = ddio;
  2058. cmsys::ifstream ddif(arg_ddi.c_str(), std::ios::in | std::ios::binary);
  2059. Json::Reader reader;
  2060. if (!reader.parse(ddif, ddio, false)) {
  2061. cmSystemTools::Error(cmStrCat("-E cmake_ninja_dyndep failed to parse ",
  2062. arg_ddi,
  2063. reader.getFormattedErrorMessages()));
  2064. return false;
  2065. }
  2066. cmDyndepObjectInfo info;
  2067. info.Object = ddi["object"].asString();
  2068. Json::Value const& ddi_provides = ddi["provides"];
  2069. if (ddi_provides.isArray()) {
  2070. for (auto const& ddi_provide : ddi_provides) {
  2071. info.Provides.push_back(ddi_provide.asString());
  2072. }
  2073. }
  2074. Json::Value const& ddi_requires = ddi["requires"];
  2075. if (ddi_requires.isArray()) {
  2076. for (auto const& ddi_require : ddi_requires) {
  2077. info.Requires.push_back(ddi_require.asString());
  2078. }
  2079. }
  2080. objects.push_back(std::move(info));
  2081. }
  2082. // Map from module name to module file path, if known.
  2083. std::map<std::string, std::string> mod_files;
  2084. // Populate the module map with those provided by linked targets first.
  2085. for (std::string const& linked_target_dir : linked_target_dirs) {
  2086. std::string const ltmn =
  2087. cmStrCat(linked_target_dir, "/", arg_lang, "Modules.json");
  2088. Json::Value ltm;
  2089. cmsys::ifstream ltmf(ltmn.c_str(), std::ios::in | std::ios::binary);
  2090. Json::Reader reader;
  2091. if (ltmf && !reader.parse(ltmf, ltm, false)) {
  2092. cmSystemTools::Error(cmStrCat("-E cmake_ninja_dyndep failed to parse ",
  2093. linked_target_dir,
  2094. reader.getFormattedErrorMessages()));
  2095. return false;
  2096. }
  2097. if (ltm.isObject()) {
  2098. for (Json::Value::iterator i = ltm.begin(); i != ltm.end(); ++i) {
  2099. mod_files[i.key().asString()] = i->asString();
  2100. }
  2101. }
  2102. }
  2103. // Extend the module map with those provided by this target.
  2104. // We do this after loading the modules provided by linked targets
  2105. // in case we have one of the same name that must be preferred.
  2106. Json::Value tm = Json::objectValue;
  2107. for (cmDyndepObjectInfo const& object : objects) {
  2108. for (std::string const& p : object.Provides) {
  2109. std::string const mod = cmStrCat(module_dir, p);
  2110. mod_files[p] = mod;
  2111. tm[p] = mod;
  2112. }
  2113. }
  2114. cmGeneratedFileStream ddf(arg_dd);
  2115. ddf << "ninja_dyndep_version = 1.0\n";
  2116. {
  2117. cmNinjaBuild build("dyndep");
  2118. build.Outputs.emplace_back("");
  2119. for (cmDyndepObjectInfo const& object : objects) {
  2120. build.Outputs[0] = object.Object;
  2121. build.ImplicitOuts.clear();
  2122. for (std::string const& p : object.Provides) {
  2123. build.ImplicitOuts.push_back(this->ConvertToNinjaPath(mod_files[p]));
  2124. }
  2125. build.ImplicitDeps.clear();
  2126. for (std::string const& r : object.Requires) {
  2127. auto mit = mod_files.find(r);
  2128. if (mit != mod_files.end()) {
  2129. build.ImplicitDeps.push_back(this->ConvertToNinjaPath(mit->second));
  2130. }
  2131. }
  2132. build.Variables.clear();
  2133. if (!object.Provides.empty()) {
  2134. build.Variables.emplace("restat", "1");
  2135. }
  2136. this->WriteBuild(ddf, build);
  2137. }
  2138. }
  2139. // Store the map of modules provided by this target in a file for
  2140. // use by dependents that reference this target in linked-target-dirs.
  2141. std::string const target_mods_file = cmStrCat(
  2142. cmSystemTools::GetFilenamePath(arg_dd), '/', arg_lang, "Modules.json");
  2143. cmGeneratedFileStream tmf(target_mods_file);
  2144. tmf << tm;
  2145. return true;
  2146. }
  2147. bool cmGlobalNinjaGenerator::EnableCrossConfigBuild() const
  2148. {
  2149. return !this->CrossConfigs.empty();
  2150. }
  2151. int cmcmd_cmake_ninja_dyndep(std::vector<std::string>::const_iterator argBeg,
  2152. std::vector<std::string>::const_iterator argEnd)
  2153. {
  2154. std::vector<std::string> arg_full =
  2155. cmSystemTools::HandleResponseFile(argBeg, argEnd);
  2156. std::string arg_dd;
  2157. std::string arg_lang;
  2158. std::string arg_tdi;
  2159. std::vector<std::string> arg_ddis;
  2160. for (std::string const& arg : arg_full) {
  2161. if (cmHasLiteralPrefix(arg, "--tdi=")) {
  2162. arg_tdi = arg.substr(6);
  2163. } else if (cmHasLiteralPrefix(arg, "--lang=")) {
  2164. arg_lang = arg.substr(7);
  2165. } else if (cmHasLiteralPrefix(arg, "--dd=")) {
  2166. arg_dd = arg.substr(5);
  2167. } else if (!cmHasLiteralPrefix(arg, "--") &&
  2168. cmHasLiteralSuffix(arg, ".ddi")) {
  2169. arg_ddis.push_back(arg);
  2170. } else {
  2171. cmSystemTools::Error(
  2172. cmStrCat("-E cmake_ninja_dyndep unknown argument: ", arg));
  2173. return 1;
  2174. }
  2175. }
  2176. if (arg_tdi.empty()) {
  2177. cmSystemTools::Error("-E cmake_ninja_dyndep requires value for --tdi=");
  2178. return 1;
  2179. }
  2180. if (arg_lang.empty()) {
  2181. cmSystemTools::Error("-E cmake_ninja_dyndep requires value for --lang=");
  2182. return 1;
  2183. }
  2184. if (arg_dd.empty()) {
  2185. cmSystemTools::Error("-E cmake_ninja_dyndep requires value for --dd=");
  2186. return 1;
  2187. }
  2188. Json::Value tdio;
  2189. Json::Value const& tdi = tdio;
  2190. {
  2191. cmsys::ifstream tdif(arg_tdi.c_str(), std::ios::in | std::ios::binary);
  2192. Json::Reader reader;
  2193. if (!reader.parse(tdif, tdio, false)) {
  2194. cmSystemTools::Error(cmStrCat("-E cmake_ninja_dyndep failed to parse ",
  2195. arg_tdi,
  2196. reader.getFormattedErrorMessages()));
  2197. return 1;
  2198. }
  2199. }
  2200. std::string const dir_cur_bld = tdi["dir-cur-bld"].asString();
  2201. std::string const dir_cur_src = tdi["dir-cur-src"].asString();
  2202. std::string const dir_top_bld = tdi["dir-top-bld"].asString();
  2203. std::string const dir_top_src = tdi["dir-top-src"].asString();
  2204. std::string module_dir = tdi["module-dir"].asString();
  2205. if (!module_dir.empty() && !cmHasLiteralSuffix(module_dir, "/")) {
  2206. module_dir += '/';
  2207. }
  2208. std::vector<std::string> linked_target_dirs;
  2209. Json::Value const& tdi_linked_target_dirs = tdi["linked-target-dirs"];
  2210. if (tdi_linked_target_dirs.isArray()) {
  2211. for (auto const& tdi_linked_target_dir : tdi_linked_target_dirs) {
  2212. linked_target_dirs.push_back(tdi_linked_target_dir.asString());
  2213. }
  2214. }
  2215. cmake cm(cmake::RoleInternal, cmState::Unknown);
  2216. cm.SetHomeDirectory(dir_top_src);
  2217. cm.SetHomeOutputDirectory(dir_top_bld);
  2218. auto ggd = cm.CreateGlobalGenerator("Ninja");
  2219. if (!ggd ||
  2220. !cm::static_reference_cast<cmGlobalNinjaGenerator>(ggd).WriteDyndepFile(
  2221. dir_top_src, dir_top_bld, dir_cur_src, dir_cur_bld, arg_dd, arg_ddis,
  2222. module_dir, linked_target_dirs, arg_lang)) {
  2223. return 1;
  2224. }
  2225. return 0;
  2226. }
  2227. void cmGlobalNinjaGenerator::AppendDirectoryForConfig(
  2228. const std::string& prefix, const std::string& config,
  2229. const std::string& suffix, std::string& dir)
  2230. {
  2231. if (!config.empty() && this->IsMultiConfig()) {
  2232. dir += cmStrCat(prefix, config, suffix);
  2233. }
  2234. }
  2235. std::set<std::string> cmGlobalNinjaGenerator::GetCrossConfigs(
  2236. const std::string& fileConfig) const
  2237. {
  2238. auto result = this->CrossConfigs;
  2239. result.insert(fileConfig);
  2240. return result;
  2241. }
  2242. const char* cmGlobalNinjaMultiGenerator::NINJA_COMMON_FILE =
  2243. "CMakeFiles/common.ninja";
  2244. const char* cmGlobalNinjaMultiGenerator::NINJA_FILE_EXTENSION = ".ninja";
  2245. cmGlobalNinjaMultiGenerator::cmGlobalNinjaMultiGenerator(cmake* cm)
  2246. : cmGlobalNinjaGenerator(cm)
  2247. {
  2248. cm->GetState()->SetIsGeneratorMultiConfig(true);
  2249. cm->GetState()->SetNinjaMulti(true);
  2250. }
  2251. void cmGlobalNinjaMultiGenerator::GetDocumentation(cmDocumentationEntry& entry)
  2252. {
  2253. entry.Name = cmGlobalNinjaMultiGenerator::GetActualName();
  2254. entry.Brief = "Generates build-<Config>.ninja files.";
  2255. }
  2256. std::string cmGlobalNinjaMultiGenerator::ExpandCFGIntDir(
  2257. const std::string& str, const std::string& config) const
  2258. {
  2259. std::string result = str;
  2260. cmSystemTools::ReplaceString(result, this->GetCMakeCFGIntDir(), config);
  2261. return result;
  2262. }
  2263. bool cmGlobalNinjaMultiGenerator::OpenBuildFileStreams()
  2264. {
  2265. if (!this->OpenFileStream(this->CommonFileStream,
  2266. cmGlobalNinjaMultiGenerator::NINJA_COMMON_FILE)) {
  2267. return false;
  2268. }
  2269. if (!this->OpenFileStream(this->DefaultFileStream, NINJA_BUILD_FILE)) {
  2270. return false;
  2271. }
  2272. *this->DefaultFileStream << "# Build using rules for '"
  2273. << this->DefaultFileConfig << "'.\n\n"
  2274. << "include "
  2275. << GetNinjaImplFilename(this->DefaultFileConfig)
  2276. << "\n\n";
  2277. // Write a comment about this file.
  2278. *this->CommonFileStream
  2279. << "# This file contains build statements common to all "
  2280. "configurations.\n\n";
  2281. for (auto const& config : this->Makefiles[0]->GetGeneratorConfigs(
  2282. cmMakefile::IncludeEmptyConfig)) {
  2283. // Open impl file.
  2284. if (!this->OpenFileStream(this->ImplFileStreams[config],
  2285. GetNinjaImplFilename(config))) {
  2286. return false;
  2287. }
  2288. // Write a comment about this file.
  2289. *this->ImplFileStreams[config]
  2290. << "# This file contains build statements specific to the \"" << config
  2291. << "\"\n# configuration.\n\n";
  2292. // Open config file.
  2293. if (!this->OpenFileStream(this->ConfigFileStreams[config],
  2294. GetNinjaConfigFilename(config))) {
  2295. return false;
  2296. }
  2297. // Write a comment about this file.
  2298. *this->ConfigFileStreams[config]
  2299. << "# This file contains aliases specific to the \"" << config
  2300. << "\"\n# configuration.\n\n"
  2301. << "include " << GetNinjaImplFilename(config) << "\n\n";
  2302. }
  2303. return true;
  2304. }
  2305. void cmGlobalNinjaMultiGenerator::CloseBuildFileStreams()
  2306. {
  2307. if (this->CommonFileStream) {
  2308. this->CommonFileStream.reset();
  2309. } else {
  2310. cmSystemTools::Error("Common file stream was not open.");
  2311. }
  2312. if (this->DefaultFileStream) {
  2313. this->DefaultFileStream.reset();
  2314. } // No error if it wasn't open
  2315. for (auto const& config : this->Makefiles[0]->GetGeneratorConfigs(
  2316. cmMakefile::IncludeEmptyConfig)) {
  2317. if (this->ImplFileStreams[config]) {
  2318. this->ImplFileStreams[config].reset();
  2319. } else {
  2320. cmSystemTools::Error(
  2321. cmStrCat("Impl file stream for \"", config, "\" was not open."));
  2322. }
  2323. if (this->ConfigFileStreams[config]) {
  2324. this->ConfigFileStreams[config].reset();
  2325. } else {
  2326. cmSystemTools::Error(
  2327. cmStrCat("Config file stream for \"", config, "\" was not open."));
  2328. }
  2329. }
  2330. }
  2331. void cmGlobalNinjaMultiGenerator::AppendNinjaFileArgument(
  2332. GeneratedMakeCommand& command, const std::string& config) const
  2333. {
  2334. if (!config.empty()) {
  2335. command.Add("-f");
  2336. command.Add(GetNinjaConfigFilename(config));
  2337. }
  2338. }
  2339. std::string cmGlobalNinjaMultiGenerator::GetNinjaImplFilename(
  2340. const std::string& config)
  2341. {
  2342. return cmStrCat("CMakeFiles/impl-", config,
  2343. cmGlobalNinjaMultiGenerator::NINJA_FILE_EXTENSION);
  2344. }
  2345. std::string cmGlobalNinjaMultiGenerator::GetNinjaConfigFilename(
  2346. const std::string& config)
  2347. {
  2348. return cmStrCat("build-", config,
  2349. cmGlobalNinjaMultiGenerator::NINJA_FILE_EXTENSION);
  2350. }
  2351. void cmGlobalNinjaMultiGenerator::AddRebuildManifestOutputs(
  2352. cmNinjaDeps& outputs) const
  2353. {
  2354. for (auto const& config : this->Makefiles.front()->GetGeneratorConfigs(
  2355. cmMakefile::IncludeEmptyConfig)) {
  2356. outputs.push_back(this->NinjaOutputPath(GetNinjaImplFilename(config)));
  2357. outputs.push_back(this->NinjaOutputPath(GetNinjaConfigFilename(config)));
  2358. }
  2359. if (!this->DefaultFileConfig.empty()) {
  2360. outputs.push_back(this->NinjaOutputPath(NINJA_BUILD_FILE));
  2361. }
  2362. }
  2363. void cmGlobalNinjaMultiGenerator::GetQtAutoGenConfigs(
  2364. std::vector<std::string>& configs) const
  2365. {
  2366. auto allConfigs =
  2367. this->Makefiles[0]->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  2368. configs.insert(configs.end(), cm::cbegin(allConfigs), cm::cend(allConfigs));
  2369. }
  2370. bool cmGlobalNinjaMultiGenerator::InspectConfigTypeVariables()
  2371. {
  2372. this->GetCMakeInstance()->MarkCliAsUsed("CMAKE_DEFAULT_BUILD_TYPE");
  2373. this->GetCMakeInstance()->MarkCliAsUsed("CMAKE_CROSS_CONFIGS");
  2374. this->GetCMakeInstance()->MarkCliAsUsed("CMAKE_DEFAULT_CONFIGS");
  2375. return this->ReadCacheEntriesForBuild(*this->Makefiles.front()->GetState());
  2376. }
  2377. std::string cmGlobalNinjaMultiGenerator::GetDefaultBuildConfig() const
  2378. {
  2379. return "";
  2380. }
  2381. bool cmGlobalNinjaMultiGenerator::ReadCacheEntriesForBuild(
  2382. const cmState& state)
  2383. {
  2384. std::vector<std::string> configsVec;
  2385. cmExpandList(state.GetSafeCacheEntryValue("CMAKE_CONFIGURATION_TYPES"),
  2386. configsVec);
  2387. if (configsVec.empty()) {
  2388. configsVec.emplace_back();
  2389. }
  2390. std::set<std::string> configs(configsVec.cbegin(), configsVec.cend());
  2391. this->DefaultFileConfig =
  2392. state.GetSafeCacheEntryValue("CMAKE_DEFAULT_BUILD_TYPE");
  2393. if (this->DefaultFileConfig.empty()) {
  2394. this->DefaultFileConfig = configsVec.front();
  2395. }
  2396. if (!configs.count(this->DefaultFileConfig)) {
  2397. std::ostringstream msg;
  2398. msg << "The configuration specified by "
  2399. << "CMAKE_DEFAULT_BUILD_TYPE (" << this->DefaultFileConfig
  2400. << ") is not present in CMAKE_CONFIGURATION_TYPES";
  2401. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  2402. msg.str());
  2403. return false;
  2404. }
  2405. std::vector<std::string> crossConfigsVec;
  2406. cmExpandList(state.GetSafeCacheEntryValue("CMAKE_CROSS_CONFIGS"),
  2407. crossConfigsVec);
  2408. auto crossConfigs = ListSubsetWithAll(configs, configs, crossConfigsVec);
  2409. if (!crossConfigs) {
  2410. std::ostringstream msg;
  2411. msg << "CMAKE_CROSS_CONFIGS is not a subset of "
  2412. << "CMAKE_CONFIGURATION_TYPES";
  2413. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  2414. msg.str());
  2415. return false;
  2416. }
  2417. this->CrossConfigs = *crossConfigs;
  2418. auto defaultConfigsString =
  2419. state.GetSafeCacheEntryValue("CMAKE_DEFAULT_CONFIGS");
  2420. if (defaultConfigsString.empty()) {
  2421. defaultConfigsString = this->DefaultFileConfig;
  2422. }
  2423. if (!defaultConfigsString.empty() &&
  2424. defaultConfigsString != this->DefaultFileConfig &&
  2425. (this->DefaultFileConfig.empty() || this->CrossConfigs.empty())) {
  2426. std::ostringstream msg;
  2427. msg << "CMAKE_DEFAULT_CONFIGS cannot be used without "
  2428. << "CMAKE_DEFAULT_BUILD_TYPE or CMAKE_CROSS_CONFIGS";
  2429. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  2430. msg.str());
  2431. return false;
  2432. }
  2433. std::vector<std::string> defaultConfigsVec;
  2434. cmExpandList(defaultConfigsString, defaultConfigsVec);
  2435. if (!this->DefaultFileConfig.empty()) {
  2436. auto defaultConfigs =
  2437. ListSubsetWithAll(this->GetCrossConfigs(this->DefaultFileConfig),
  2438. this->CrossConfigs, defaultConfigsVec);
  2439. if (!defaultConfigs) {
  2440. std::ostringstream msg;
  2441. msg << "CMAKE_DEFAULT_CONFIGS is not a subset of CMAKE_CROSS_CONFIGS";
  2442. this->GetCMakeInstance()->IssueMessage(MessageType::FATAL_ERROR,
  2443. msg.str());
  2444. return false;
  2445. }
  2446. this->DefaultConfigs = *defaultConfigs;
  2447. }
  2448. return true;
  2449. }
  2450. std::string cmGlobalNinjaMultiGenerator::OrderDependsTargetForTarget(
  2451. cmGeneratorTarget const* target, const std::string& config) const
  2452. {
  2453. return cmStrCat("cmake_object_order_depends_target_", target->GetName(), '_',
  2454. cmSystemTools::UpperCase(config));
  2455. }