cmGlobalNinjaGenerator.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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 <set>
  9. #include <string>
  10. #include <unordered_map>
  11. #include <utility>
  12. #include <vector>
  13. #include "cmGlobalCommonGenerator.h"
  14. #include "cmGlobalGenerator.h"
  15. #include "cmGlobalGeneratorFactory.h"
  16. #include "cmNinjaTypes.h"
  17. #include "cmPolicies.h"
  18. #include "cm_codecvt.hxx"
  19. class cmCustomCommand;
  20. class cmGeneratedFileStream;
  21. class cmGeneratorTarget;
  22. class cmLinkLineComputer;
  23. class cmLocalGenerator;
  24. class cmMakefile;
  25. class cmOutputConverter;
  26. class cmStateDirectory;
  27. class cmake;
  28. struct cmDocumentationEntry;
  29. /**
  30. * \class cmGlobalNinjaGenerator
  31. * \brief Write a build.ninja file.
  32. *
  33. * The main differences between this generator and the UnixMakefile
  34. * generator family are:
  35. * - We don't care about VERBOSE variable or RULE_MESSAGES property since
  36. * it is handle by Ninja's -v option.
  37. * - We don't care about computing any progress status since Ninja manages
  38. * it itself.
  39. * - We don't care about generating a clean target since Ninja already have
  40. * a clean tool.
  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 EncodeIdent(const std::string& ident, std::ostream& vars);
  66. static std::string EncodeLiteral(const std::string& lit);
  67. std::string EncodePath(const std::string& path);
  68. cmLinkLineComputer* CreateLinkLineComputer(
  69. cmOutputConverter* outputConverter,
  70. cmStateDirectory const& stateDir) const override;
  71. /**
  72. * Write the given @a comment to the output stream @a os. It
  73. * handles new line character properly.
  74. */
  75. static void WriteComment(std::ostream& os, const std::string& comment);
  76. /**
  77. * Utilized by the generator factory to determine if this generator
  78. * supports toolsets.
  79. */
  80. static bool SupportsToolset() { return false; }
  81. /**
  82. * Utilized by the generator factory to determine if this generator
  83. * supports platforms.
  84. */
  85. static bool SupportsPlatform() { return false; }
  86. bool IsIPOSupported() const override { return true; }
  87. /**
  88. * Write a build statement to @a os with the @a comment using
  89. * the @a rule the list of @a outputs files and inputs.
  90. * It also writes the variables bound to this build statement.
  91. * @warning no escaping of any kind is done here.
  92. */
  93. void WriteBuild(std::ostream& os, const std::string& comment,
  94. const std::string& rule, const cmNinjaDeps& outputs,
  95. const cmNinjaDeps& implicitOuts,
  96. const cmNinjaDeps& explicitDeps,
  97. const cmNinjaDeps& implicitDeps,
  98. const cmNinjaDeps& orderOnlyDeps,
  99. const cmNinjaVars& variables,
  100. const std::string& rspfile = std::string(),
  101. int cmdLineLimit = 0, bool* usedResponseFile = nullptr);
  102. /**
  103. * Helper to write a build statement with the special 'phony' rule.
  104. */
  105. void WritePhonyBuild(std::ostream& os, const std::string& comment,
  106. const cmNinjaDeps& outputs,
  107. const cmNinjaDeps& explicitDeps,
  108. const cmNinjaDeps& implicitDeps = cmNinjaDeps(),
  109. const cmNinjaDeps& orderOnlyDeps = cmNinjaDeps(),
  110. const cmNinjaVars& variables = cmNinjaVars());
  111. void WriteCustomCommandBuild(const std::string& command,
  112. const std::string& description,
  113. const std::string& comment,
  114. const std::string& depfile, 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. ~cmGlobalNinjaGenerator() override {}
  161. cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf) override;
  162. std::string GetName() const override
  163. {
  164. return cmGlobalNinjaGenerator::GetActualName();
  165. }
  166. static std::string GetActualName() { return "Ninja"; }
  167. /** Get encoding used by generator for ninja files */
  168. codecvt::Encoding GetMakefileEncoding() const override;
  169. static void GetDocumentation(cmDocumentationEntry& entry);
  170. void EnableLanguage(std::vector<std::string> const& languages,
  171. cmMakefile* mf, bool optional) override;
  172. void GenerateBuildCommand(std::vector<std::string>& makeCommand,
  173. const std::string& makeProgram,
  174. const std::string& projectName,
  175. const std::string& projectDir,
  176. const std::string& targetName,
  177. const std::string& config, bool fast, bool verbose,
  178. std::vector<std::string> const& makeOptions =
  179. std::vector<std::string>()) override;
  180. // Setup target names
  181. const char* GetAllTargetName() const override { return "all"; }
  182. const char* GetInstallTargetName() const override { return "install"; }
  183. const char* GetInstallLocalTargetName() const override
  184. {
  185. return "install/local";
  186. }
  187. const char* GetInstallStripTargetName() const override
  188. {
  189. return "install/strip";
  190. }
  191. const char* GetTestTargetName() const override { return "test"; }
  192. const char* GetPackageTargetName() const override { return "package"; }
  193. const char* GetPackageSourceTargetName() const override
  194. {
  195. return "package_source";
  196. }
  197. const char* GetEditCacheTargetName() const override { return "edit_cache"; }
  198. const char* GetRebuildCacheTargetName() const override
  199. {
  200. return "rebuild_cache";
  201. }
  202. const char* GetCleanTargetName() const override { return "clean"; }
  203. cmGeneratedFileStream* GetBuildFileStream() const
  204. {
  205. return this->BuildFileStream;
  206. }
  207. cmGeneratedFileStream* GetRulesFileStream() const
  208. {
  209. return this->RulesFileStream;
  210. }
  211. std::string const& ConvertToNinjaPath(const std::string& path) const;
  212. struct MapToNinjaPathImpl
  213. {
  214. cmGlobalNinjaGenerator* GG;
  215. MapToNinjaPathImpl(cmGlobalNinjaGenerator* gg)
  216. : GG(gg)
  217. {
  218. }
  219. std::string operator()(std::string const& path)
  220. {
  221. return this->GG->ConvertToNinjaPath(path);
  222. }
  223. };
  224. MapToNinjaPathImpl MapToNinjaPath() { return MapToNinjaPathImpl(this); }
  225. void AddCXXCompileCommand(const std::string& commandLine,
  226. const std::string& sourceFile);
  227. /**
  228. * Add a rule to the generated build system.
  229. * Call WriteRule() behind the scene but perform some check before like:
  230. * - Do not add twice the same rule.
  231. */
  232. void AddRule(const std::string& name, const std::string& command,
  233. const std::string& description, const std::string& comment,
  234. const std::string& depfile, const std::string& deptype,
  235. const std::string& rspfile, const std::string& rspcontent,
  236. const std::string& restat, bool generator);
  237. bool HasRule(const std::string& name);
  238. void AddCustomCommandRule();
  239. void AddMacOSXContentRule();
  240. bool HasCustomCommandOutput(const std::string& output)
  241. {
  242. return this->CustomCommandOutputs.find(output) !=
  243. this->CustomCommandOutputs.end();
  244. }
  245. /// Called when we have seen the given custom command. Returns true
  246. /// if we has seen it before.
  247. bool SeenCustomCommand(cmCustomCommand const* cc)
  248. {
  249. return !this->CustomCommands.insert(cc).second;
  250. }
  251. /// Called when we have seen the given custom command output.
  252. void SeenCustomCommandOutput(const std::string& output)
  253. {
  254. this->CustomCommandOutputs.insert(output);
  255. // We don't need the assumed dependencies anymore, because we have
  256. // an output.
  257. this->AssumedSourceDependencies.erase(output);
  258. }
  259. void AddAssumedSourceDependencies(const std::string& source,
  260. const cmNinjaDeps& deps)
  261. {
  262. std::set<std::string>& ASD = this->AssumedSourceDependencies[source];
  263. // Because we may see the same source file multiple times (same source
  264. // specified in multiple targets), compute the union of any assumed
  265. // dependencies.
  266. ASD.insert(deps.begin(), deps.end());
  267. }
  268. void AppendTargetOutputs(
  269. cmGeneratorTarget const* target, cmNinjaDeps& outputs,
  270. cmNinjaTargetDepends depends = DependOnTargetArtifact);
  271. void AppendTargetDepends(
  272. cmGeneratorTarget const* target, cmNinjaDeps& outputs,
  273. cmNinjaTargetDepends depends = DependOnTargetArtifact);
  274. void AppendTargetDependsClosure(cmGeneratorTarget const* target,
  275. cmNinjaDeps& outputs);
  276. void AppendTargetDependsClosure(cmGeneratorTarget const* target,
  277. cmNinjaOuts& outputs, bool omit_self);
  278. void AddDependencyToAll(cmGeneratorTarget* target);
  279. void AddDependencyToAll(const std::string& input);
  280. const std::vector<cmLocalGenerator*>& GetLocalGenerators() const
  281. {
  282. return LocalGenerators;
  283. }
  284. bool IsExcluded(cmLocalGenerator* root, cmGeneratorTarget* target)
  285. {
  286. return cmGlobalGenerator::IsExcluded(root, target);
  287. }
  288. int GetRuleCmdLength(const std::string& name) { return RuleCmdLength[name]; }
  289. void AddTargetAlias(const std::string& alias, cmGeneratorTarget* target);
  290. void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const override;
  291. // Ninja generator uses 'deps' and 'msvc_deps_prefix' introduced in 1.3
  292. static std::string RequiredNinjaVersion() { return "1.3"; }
  293. static std::string RequiredNinjaVersionForConsolePool() { return "1.5"; }
  294. static std::string RequiredNinjaVersionForImplicitOuts() { return "1.7"; }
  295. bool SupportsConsolePool() const;
  296. bool SupportsImplicitOuts() const;
  297. std::string NinjaOutputPath(std::string const& path) const;
  298. bool HasOutputPathPrefix() const { return !this->OutputPathPrefix.empty(); }
  299. void StripNinjaOutputPathPrefixAsSuffix(std::string& path);
  300. bool WriteDyndepFile(std::string const& dir_top_src,
  301. std::string const& dir_top_bld,
  302. std::string const& dir_cur_src,
  303. std::string const& dir_cur_bld,
  304. std::string const& arg_dd,
  305. std::vector<std::string> const& arg_ddis,
  306. std::string const& module_dir,
  307. std::vector<std::string> const& linked_target_dirs);
  308. protected:
  309. void Generate() override;
  310. bool CheckALLOW_DUPLICATE_CUSTOM_TARGETS() const override { return true; }
  311. private:
  312. std::string GetEditCacheCommand() const override;
  313. bool FindMakeProgram(cmMakefile* mf) override;
  314. void CheckNinjaFeatures();
  315. bool CheckLanguages(std::vector<std::string> const& languages,
  316. cmMakefile* mf) const override;
  317. bool CheckFortran(cmMakefile* mf) const;
  318. void OpenBuildFileStream();
  319. void CloseBuildFileStream();
  320. void CloseCompileCommandsStream();
  321. void OpenRulesFileStream();
  322. void CloseRulesFileStream();
  323. /// Write the common disclaimer text at the top of each build file.
  324. void WriteDisclaimer(std::ostream& os);
  325. void WriteAssumedSourceDependencies();
  326. void WriteTargetAliases(std::ostream& os);
  327. void WriteFolderTargets(std::ostream& os);
  328. void WriteUnknownExplicitDependencies(std::ostream& os);
  329. void WriteBuiltinTargets(std::ostream& os);
  330. void WriteTargetAll(std::ostream& os);
  331. void WriteTargetRebuildManifest(std::ostream& os);
  332. void WriteTargetClean(std::ostream& os);
  333. void WriteTargetHelp(std::ostream& os);
  334. void ComputeTargetDependsClosure(
  335. cmGeneratorTarget const* target,
  336. std::set<cmGeneratorTarget const*>& depends);
  337. std::string ninjaCmd() const;
  338. /// The file containing the build statement. (the relationship of the
  339. /// compilation DAG).
  340. cmGeneratedFileStream* BuildFileStream;
  341. /// The file containing the rule statements. (The action attached to each
  342. /// edge of the compilation DAG).
  343. cmGeneratedFileStream* RulesFileStream;
  344. cmGeneratedFileStream* CompileCommandsStream;
  345. /// The type used to store the set of rules added to the generated build
  346. /// system.
  347. typedef std::set<std::string> RulesSetType;
  348. /// The set of rules added to the generated build system.
  349. RulesSetType Rules;
  350. /// Length of rule command, used by rsp file evaluation
  351. std::map<std::string, int> RuleCmdLength;
  352. /// The set of dependencies to add to the "all" target.
  353. cmNinjaDeps AllDependencies;
  354. bool UsingGCCOnWindows;
  355. /// The set of custom commands we have seen.
  356. std::set<cmCustomCommand const*> CustomCommands;
  357. /// The set of custom command outputs we have seen.
  358. std::set<std::string> CustomCommandOutputs;
  359. /// Whether we are collecting known build outputs and needed
  360. /// dependencies to determine unknown dependencies.
  361. bool ComputingUnknownDependencies;
  362. cmPolicies::PolicyStatus PolicyCMP0058;
  363. /// The combined explicit dependencies of custom build commands
  364. std::set<std::string> CombinedCustomCommandExplicitDependencies;
  365. /// When combined with CombinedCustomCommandExplicitDependencies it allows
  366. /// us to detect the set of explicit dependencies that have
  367. std::set<std::string> CombinedBuildOutputs;
  368. /// The mapping from source file to assumed dependencies.
  369. std::map<std::string, std::set<std::string>> AssumedSourceDependencies;
  370. typedef std::map<std::string, cmGeneratorTarget*> TargetAliasMap;
  371. TargetAliasMap TargetAliases;
  372. std::map<cmGeneratorTarget const*, cmNinjaOuts> TargetDependsClosures;
  373. /// the local cache for calls to ConvertToNinjaPath
  374. mutable std::unordered_map<std::string, std::string> ConvertToNinjaPathCache;
  375. std::string NinjaCommand;
  376. std::string NinjaVersion;
  377. bool NinjaSupportsConsolePool;
  378. bool NinjaSupportsImplicitOuts;
  379. unsigned long NinjaSupportsDyndeps;
  380. private:
  381. void InitOutputPathPrefix();
  382. std::string OutputPathPrefix;
  383. std::string TargetAll;
  384. std::string CMakeCacheFile;
  385. };
  386. #endif // ! cmGlobalNinjaGenerator_h