cmGlobalNinjaGenerator.cxx 63 KB

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