cmGlobalNinjaGenerator.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #ifndef cmGlobalNinjaGenerator_h
  4. #define cmGlobalNinjaGenerator_h
  5. #include "cmConfigure.h" // IWYU pragma: keep
  6. #include <iosfwd>
  7. #include <map>
  8. #include <memory> // IWYU pragma: keep
  9. #include <set>
  10. #include <string>
  11. #include <unordered_map>
  12. #include <unordered_set>
  13. #include <utility>
  14. #include <vector>
  15. #include "cmGeneratedFileStream.h"
  16. #include "cmGlobalCommonGenerator.h"
  17. #include "cmGlobalGenerator.h"
  18. #include "cmGlobalGeneratorFactory.h"
  19. #include "cmNinjaTypes.h"
  20. #include "cmPolicies.h"
  21. #include "cm_codecvt.hxx"
  22. class cmCustomCommand;
  23. class cmGeneratorTarget;
  24. class cmLinkLineComputer;
  25. class cmLocalGenerator;
  26. class cmMakefile;
  27. class cmOutputConverter;
  28. class cmStateDirectory;
  29. class cmake;
  30. struct cmDocumentationEntry;
  31. /**
  32. * \class cmGlobalNinjaGenerator
  33. * \brief Write a build.ninja file.
  34. *
  35. * The main differences between this generator and the UnixMakefile
  36. * generator family are:
  37. * - We don't care about VERBOSE variable or RULE_MESSAGES property since
  38. * it is handle by Ninja's -v option.
  39. * - We don't care about computing any progress status since Ninja manages
  40. * it itself.
  41. * - We generate one build.ninja and one rules.ninja per project.
  42. * - We try to minimize the number of generated rules: one per target and
  43. * language.
  44. * - We use Ninja special variable $in and $out to produce nice output.
  45. * - We extensively use Ninja variable overloading system to minimize the
  46. * number of generated rules.
  47. */
  48. class cmGlobalNinjaGenerator : public cmGlobalCommonGenerator
  49. {
  50. public:
  51. /// The default name of Ninja's build file. Typically: build.ninja.
  52. static const char* NINJA_BUILD_FILE;
  53. /// The default name of Ninja's rules file. Typically: rules.ninja.
  54. /// It is included in the main build.ninja file.
  55. static const char* NINJA_RULES_FILE;
  56. /// The indentation string used when generating Ninja's build file.
  57. static const char* INDENT;
  58. /// The shell command used for a no-op.
  59. static std::string const SHELL_NOOP;
  60. /// Write @a count times INDENT level to output stream @a os.
  61. static void Indent(std::ostream& os, int count);
  62. /// Write a divider in the given output stream @a os.
  63. static void WriteDivider(std::ostream& os);
  64. static std::string EncodeRuleName(std::string const& name);
  65. static std::string EncodeLiteral(const std::string& lit);
  66. std::string EncodePath(const std::string& path);
  67. cmLinkLineComputer* CreateLinkLineComputer(
  68. cmOutputConverter* outputConverter,
  69. cmStateDirectory const& stateDir) const override;
  70. /**
  71. * Write the given @a comment to the output stream @a os. It
  72. * handles new line character properly.
  73. */
  74. static void WriteComment(std::ostream& os, const std::string& comment);
  75. /**
  76. * Utilized by the generator factory to determine if this generator
  77. * supports toolsets.
  78. */
  79. static bool SupportsToolset() { return false; }
  80. /**
  81. * Utilized by the generator factory to determine if this generator
  82. * supports platforms.
  83. */
  84. static bool SupportsPlatform() { return false; }
  85. bool IsIPOSupported() const override { return true; }
  86. /**
  87. * Write a build statement to @a os with the @a comment using
  88. * the @a rule the list of @a outputs files and inputs.
  89. * It also writes the variables bound to this build statement.
  90. * @warning no escaping of any kind is done here.
  91. */
  92. void WriteBuild(std::ostream& os, const std::string& comment,
  93. const std::string& rule, const cmNinjaDeps& outputs,
  94. const cmNinjaDeps& implicitOuts,
  95. const cmNinjaDeps& explicitDeps,
  96. const cmNinjaDeps& implicitDeps,
  97. const cmNinjaDeps& orderOnlyDeps,
  98. const cmNinjaVars& variables,
  99. const std::string& rspfile = std::string(),
  100. int cmdLineLimit = 0, bool* usedResponseFile = nullptr);
  101. /**
  102. * Helper to write a build statement with the special 'phony' rule.
  103. */
  104. void WritePhonyBuild(std::ostream& os, const std::string& comment,
  105. const cmNinjaDeps& outputs,
  106. const cmNinjaDeps& explicitDeps,
  107. const cmNinjaDeps& implicitDeps = cmNinjaDeps(),
  108. const cmNinjaDeps& orderOnlyDeps = cmNinjaDeps(),
  109. const cmNinjaVars& variables = cmNinjaVars());
  110. void WriteCustomCommandBuild(const std::string& command,
  111. const std::string& description,
  112. const std::string& comment,
  113. const std::string& depfile,
  114. const std::string& pool, bool uses_terminal,
  115. bool restat, const cmNinjaDeps& outputs,
  116. const cmNinjaDeps& deps = cmNinjaDeps(),
  117. const cmNinjaDeps& orderOnly = cmNinjaDeps());
  118. void WriteMacOSXContentBuild(const std::string& input,
  119. const std::string& output);
  120. /**
  121. * Write a rule statement named @a name to @a os with the @a comment,
  122. * the mandatory @a command, the @a depfile and the @a description.
  123. * It also writes the variables bound to this rule statement.
  124. * @warning no escaping of any kind is done here.
  125. */
  126. static void WriteRule(std::ostream& os, const std::string& name,
  127. const std::string& command,
  128. const std::string& description,
  129. const std::string& comment, const std::string& depfile,
  130. const std::string& deptype, const std::string& rspfile,
  131. const std::string& rspcontent,
  132. const std::string& restat, bool generator);
  133. /**
  134. * Write a variable named @a name to @a os with value @a value and an
  135. * optional @a comment. An @a indent level can be specified.
  136. * @warning no escaping of any kind is done here.
  137. */
  138. static void WriteVariable(std::ostream& os, const std::string& name,
  139. const std::string& value,
  140. const std::string& comment = "", int indent = 0);
  141. /**
  142. * Write an include statement including @a filename with an optional
  143. * @a comment to the @a os stream.
  144. */
  145. static void WriteInclude(std::ostream& os, const std::string& filename,
  146. const std::string& comment = "");
  147. /**
  148. * Write a default target statement specifying @a targets as
  149. * the default targets.
  150. */
  151. static void WriteDefault(std::ostream& os, const cmNinjaDeps& targets,
  152. const std::string& comment = "");
  153. bool IsGCCOnWindows() const { return UsingGCCOnWindows; }
  154. public:
  155. cmGlobalNinjaGenerator(cmake* cm);
  156. static cmGlobalGeneratorFactory* NewFactory()
  157. {
  158. return new cmGlobalGeneratorSimpleFactory<cmGlobalNinjaGenerator>();
  159. }
  160. cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf) override;
  161. std::string GetName() const override
  162. {
  163. return cmGlobalNinjaGenerator::GetActualName();
  164. }
  165. static std::string GetActualName() { return "Ninja"; }
  166. /** Get encoding used by generator for ninja files */
  167. codecvt::Encoding GetMakefileEncoding() const override;
  168. static void GetDocumentation(cmDocumentationEntry& entry);
  169. void EnableLanguage(std::vector<std::string> const& languages,
  170. cmMakefile* mf, bool optional) override;
  171. std::vector<GeneratedMakeCommand> GenerateBuildCommand(
  172. const std::string& makeProgram, const std::string& projectName,
  173. const std::string& projectDir, std::vector<std::string> const& targetNames,
  174. const std::string& config, bool fast, int jobs, bool verbose,
  175. std::vector<std::string> const& makeOptions =
  176. std::vector<std::string>()) override;
  177. // Setup target names
  178. const char* GetAllTargetName() const override { return "all"; }
  179. const char* GetInstallTargetName() const override { return "install"; }
  180. const char* GetInstallLocalTargetName() const override
  181. {
  182. return "install/local";
  183. }
  184. const char* GetInstallStripTargetName() const override
  185. {
  186. return "install/strip";
  187. }
  188. const char* GetTestTargetName() const override { return "test"; }
  189. const char* GetPackageTargetName() const override { return "package"; }
  190. const char* GetPackageSourceTargetName() const override
  191. {
  192. return "package_source";
  193. }
  194. const char* GetEditCacheTargetName() const override { return "edit_cache"; }
  195. const char* GetRebuildCacheTargetName() const override
  196. {
  197. return "rebuild_cache";
  198. }
  199. const char* GetCleanTargetName() const override { return "clean"; }
  200. cmGeneratedFileStream* GetBuildFileStream() const
  201. {
  202. return this->BuildFileStream.get();
  203. }
  204. cmGeneratedFileStream* GetRulesFileStream() const
  205. {
  206. return this->RulesFileStream.get();
  207. }
  208. std::string const& ConvertToNinjaPath(const std::string& path) const;
  209. struct MapToNinjaPathImpl
  210. {
  211. cmGlobalNinjaGenerator* GG;
  212. MapToNinjaPathImpl(cmGlobalNinjaGenerator* gg)
  213. : GG(gg)
  214. {
  215. }
  216. std::string operator()(std::string const& path)
  217. {
  218. return this->GG->ConvertToNinjaPath(path);
  219. }
  220. };
  221. MapToNinjaPathImpl MapToNinjaPath() { return MapToNinjaPathImpl(this); }
  222. void AddCXXCompileCommand(const std::string& commandLine,
  223. const std::string& sourceFile);
  224. /**
  225. * Add a rule to the generated build system.
  226. * Call WriteRule() behind the scene but perform some check before like:
  227. * - Do not add twice the same rule.
  228. */
  229. void AddRule(const std::string& name, const std::string& command,
  230. const std::string& description, const std::string& comment,
  231. const std::string& depfile, const std::string& deptype,
  232. const std::string& rspfile, const std::string& rspcontent,
  233. const std::string& restat, bool generator);
  234. bool HasRule(const std::string& name);
  235. void AddCustomCommandRule();
  236. void AddMacOSXContentRule();
  237. bool HasCustomCommandOutput(const std::string& output)
  238. {
  239. return this->CustomCommandOutputs.find(output) !=
  240. this->CustomCommandOutputs.end();
  241. }
  242. /// Called when we have seen the given custom command. Returns true
  243. /// if we has seen it before.
  244. bool SeenCustomCommand(cmCustomCommand const* cc)
  245. {
  246. return !this->CustomCommands.insert(cc).second;
  247. }
  248. /// Called when we have seen the given custom command output.
  249. void SeenCustomCommandOutput(const std::string& output)
  250. {
  251. this->CustomCommandOutputs.insert(output);
  252. // We don't need the assumed dependencies anymore, because we have
  253. // an output.
  254. this->AssumedSourceDependencies.erase(output);
  255. }
  256. void AddAssumedSourceDependencies(const std::string& source,
  257. const cmNinjaDeps& deps)
  258. {
  259. std::set<std::string>& ASD = this->AssumedSourceDependencies[source];
  260. // Because we may see the same source file multiple times (same source
  261. // specified in multiple targets), compute the union of any assumed
  262. // dependencies.
  263. ASD.insert(deps.begin(), deps.end());
  264. }
  265. void AppendTargetOutputs(
  266. cmGeneratorTarget const* target, cmNinjaDeps& outputs,
  267. cmNinjaTargetDepends depends = DependOnTargetArtifact);
  268. void AppendTargetDepends(
  269. cmGeneratorTarget const* target, cmNinjaDeps& outputs,
  270. cmNinjaTargetDepends depends = DependOnTargetArtifact);
  271. void AppendTargetDependsClosure(cmGeneratorTarget const* target,
  272. cmNinjaDeps& outputs);
  273. void AppendTargetDependsClosure(cmGeneratorTarget const* target,
  274. cmNinjaOuts& outputs, bool omit_self);
  275. void AddDependencyToAll(cmGeneratorTarget* target);
  276. void AddDependencyToAll(const std::string& input);
  277. const std::vector<cmLocalGenerator*>& GetLocalGenerators() const
  278. {
  279. return LocalGenerators;
  280. }
  281. bool IsExcluded(cmGeneratorTarget* target)
  282. {
  283. return cmGlobalGenerator::IsExcluded(target);
  284. }
  285. int GetRuleCmdLength(const std::string& name) { return RuleCmdLength[name]; }
  286. void AddTargetAlias(const std::string& alias, cmGeneratorTarget* target);
  287. void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const override;
  288. // Ninja generator uses 'deps' and 'msvc_deps_prefix' introduced in 1.3
  289. static std::string RequiredNinjaVersion() { return "1.3"; }
  290. static std::string RequiredNinjaVersionForConsolePool() { return "1.5"; }
  291. static std::string RequiredNinjaVersionForImplicitOuts() { return "1.7"; }
  292. static std::string RequiredNinjaVersionForManifestRestat() { return "1.8"; }
  293. static std::string RequiredNinjaVersionForMultilineDepfile()
  294. {
  295. return "1.9";
  296. }
  297. bool SupportsConsolePool() const;
  298. bool SupportsImplicitOuts() const;
  299. bool SupportsManifestRestat() const;
  300. bool SupportsMultilineDepfile() const;
  301. std::string NinjaOutputPath(std::string const& path) const;
  302. bool HasOutputPathPrefix() const { return !this->OutputPathPrefix.empty(); }
  303. void StripNinjaOutputPathPrefixAsSuffix(std::string& path);
  304. bool WriteDyndepFile(std::string const& dir_top_src,
  305. std::string const& dir_top_bld,
  306. std::string const& dir_cur_src,
  307. std::string const& dir_cur_bld,
  308. std::string const& arg_dd,
  309. std::vector<std::string> const& arg_ddis,
  310. std::string const& module_dir,
  311. std::vector<std::string> const& linked_target_dirs,
  312. std::string const& arg_lang);
  313. protected:
  314. void Generate() override;
  315. bool CheckALLOW_DUPLICATE_CUSTOM_TARGETS() const override { return true; }
  316. private:
  317. std::string GetEditCacheCommand() const override;
  318. bool FindMakeProgram(cmMakefile* mf) override;
  319. void CheckNinjaFeatures();
  320. bool CheckLanguages(std::vector<std::string> const& languages,
  321. cmMakefile* mf) const override;
  322. bool CheckFortran(cmMakefile* mf) const;
  323. bool OpenBuildFileStream();
  324. void CloseBuildFileStream();
  325. void CloseCompileCommandsStream();
  326. bool OpenRulesFileStream();
  327. void CloseRulesFileStream();
  328. /// Write the common disclaimer text at the top of each build file.
  329. void WriteDisclaimer(std::ostream& os);
  330. void WriteAssumedSourceDependencies();
  331. void WriteTargetAliases(std::ostream& os);
  332. void WriteFolderTargets(std::ostream& os);
  333. void WriteUnknownExplicitDependencies(std::ostream& os);
  334. void WriteBuiltinTargets(std::ostream& os);
  335. void WriteTargetAll(std::ostream& os);
  336. void WriteTargetRebuildManifest(std::ostream& os);
  337. void WriteTargetClean(std::ostream& os);
  338. void WriteTargetHelp(std::ostream& os);
  339. void ComputeTargetDependsClosure(
  340. cmGeneratorTarget const* target,
  341. std::set<cmGeneratorTarget const*>& depends);
  342. std::string CMakeCmd() const;
  343. std::string NinjaCmd() const;
  344. /// The file containing the build statement. (the relationship of the
  345. /// compilation DAG).
  346. std::unique_ptr<cmGeneratedFileStream> BuildFileStream;
  347. /// The file containing the rule statements. (The action attached to each
  348. /// edge of the compilation DAG).
  349. std::unique_ptr<cmGeneratedFileStream> RulesFileStream;
  350. std::unique_ptr<cmGeneratedFileStream> CompileCommandsStream;
  351. /// The set of rules added to the generated build system.
  352. std::unordered_set<std::string> Rules;
  353. /// Length of rule command, used by rsp file evaluation
  354. std::unordered_map<std::string, int> RuleCmdLength;
  355. /// The set of dependencies to add to the "all" target.
  356. cmNinjaDeps AllDependencies;
  357. bool UsingGCCOnWindows;
  358. /// The set of custom commands we have seen.
  359. std::set<cmCustomCommand const*> CustomCommands;
  360. /// The set of custom command outputs we have seen.
  361. std::set<std::string> CustomCommandOutputs;
  362. /// Whether we are collecting known build outputs and needed
  363. /// dependencies to determine unknown dependencies.
  364. bool ComputingUnknownDependencies;
  365. cmPolicies::PolicyStatus PolicyCMP0058;
  366. /// The combined explicit dependencies of custom build commands
  367. std::set<std::string> CombinedCustomCommandExplicitDependencies;
  368. /// When combined with CombinedCustomCommandExplicitDependencies it allows
  369. /// us to detect the set of explicit dependencies that have
  370. std::set<std::string> CombinedBuildOutputs;
  371. /// The mapping from source file to assumed dependencies.
  372. std::map<std::string, std::set<std::string>> AssumedSourceDependencies;
  373. typedef std::map<std::string, cmGeneratorTarget*> TargetAliasMap;
  374. TargetAliasMap TargetAliases;
  375. std::map<cmGeneratorTarget const*, cmNinjaOuts> TargetDependsClosures;
  376. /// the local cache for calls to ConvertToNinjaPath
  377. mutable std::unordered_map<std::string, std::string> ConvertToNinjaPathCache;
  378. std::string NinjaCommand;
  379. std::string NinjaVersion;
  380. bool NinjaSupportsConsolePool;
  381. bool NinjaSupportsImplicitOuts;
  382. bool NinjaSupportsManifestRestat;
  383. bool NinjaSupportsMultilineDepfile;
  384. unsigned long NinjaSupportsDyndeps;
  385. private:
  386. void InitOutputPathPrefix();
  387. std::string OutputPathPrefix;
  388. std::string TargetAll;
  389. std::string CMakeCacheFile;
  390. };
  391. #endif // ! cmGlobalNinjaGenerator_h