cmGlobalNinjaGenerator.cxx 66 KB

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