cmGlobalNinjaGenerator.cxx 64 KB

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