cmGlobalNinjaGenerator.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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>
  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 @a build to @a os.
  88. * @warning no escaping of any kind is done here.
  89. */
  90. void WriteBuild(std::ostream& os, cmNinjaBuild const& build,
  91. int cmdLineLimit = 0, bool* usedResponseFile = nullptr);
  92. void WriteCustomCommandBuild(
  93. const std::string& command, const std::string& description,
  94. const std::string& comment, const std::string& depfile,
  95. const std::string& pool, bool uses_terminal, bool restat,
  96. const cmNinjaDeps& outputs,
  97. const cmNinjaDeps& explicitDeps = cmNinjaDeps(),
  98. const cmNinjaDeps& orderOnlyDeps = cmNinjaDeps());
  99. void WriteMacOSXContentBuild(std::string input, std::string output);
  100. /**
  101. * Write a rule statement to @a os.
  102. * @warning no escaping of any kind is done here.
  103. */
  104. static void WriteRule(std::ostream& os, cmNinjaRule const& rule);
  105. /**
  106. * Write a variable named @a name to @a os with value @a value and an
  107. * optional @a comment. An @a indent level can be specified.
  108. * @warning no escaping of any kind is done here.
  109. */
  110. static void WriteVariable(std::ostream& os, const std::string& name,
  111. const std::string& value,
  112. const std::string& comment = "", int indent = 0);
  113. /**
  114. * Write an include statement including @a filename with an optional
  115. * @a comment to the @a os stream.
  116. */
  117. static void WriteInclude(std::ostream& os, const std::string& filename,
  118. const std::string& comment = "");
  119. /**
  120. * Write a default target statement specifying @a targets as
  121. * the default targets.
  122. */
  123. static void WriteDefault(std::ostream& os, const cmNinjaDeps& targets,
  124. const std::string& comment = "");
  125. bool IsGCCOnWindows() const { return UsingGCCOnWindows; }
  126. public:
  127. cmGlobalNinjaGenerator(cmake* cm);
  128. static cmGlobalGeneratorFactory* NewFactory()
  129. {
  130. return new cmGlobalGeneratorSimpleFactory<cmGlobalNinjaGenerator>();
  131. }
  132. cmLocalGenerator* CreateLocalGenerator(cmMakefile* mf) override;
  133. std::string GetName() const override
  134. {
  135. return cmGlobalNinjaGenerator::GetActualName();
  136. }
  137. static std::string GetActualName() { return "Ninja"; }
  138. /** Get encoding used by generator for ninja files */
  139. codecvt::Encoding GetMakefileEncoding() const override;
  140. static void GetDocumentation(cmDocumentationEntry& entry);
  141. void EnableLanguage(std::vector<std::string> const& languages,
  142. cmMakefile* mf, bool optional) override;
  143. std::vector<GeneratedMakeCommand> GenerateBuildCommand(
  144. const std::string& makeProgram, const std::string& projectName,
  145. const std::string& projectDir, std::vector<std::string> const& targetNames,
  146. const std::string& config, bool fast, int jobs, bool verbose,
  147. std::vector<std::string> const& makeOptions =
  148. std::vector<std::string>()) override;
  149. // Setup target names
  150. const char* GetAllTargetName() const override { return "all"; }
  151. const char* GetInstallTargetName() const override { return "install"; }
  152. const char* GetInstallLocalTargetName() const override
  153. {
  154. return "install/local";
  155. }
  156. const char* GetInstallStripTargetName() const override
  157. {
  158. return "install/strip";
  159. }
  160. const char* GetTestTargetName() const override { return "test"; }
  161. const char* GetPackageTargetName() const override { return "package"; }
  162. const char* GetPackageSourceTargetName() const override
  163. {
  164. return "package_source";
  165. }
  166. const char* GetEditCacheTargetName() const override { return "edit_cache"; }
  167. const char* GetRebuildCacheTargetName() const override
  168. {
  169. return "rebuild_cache";
  170. }
  171. const char* GetCleanTargetName() const override { return "clean"; }
  172. cmGeneratedFileStream* GetBuildFileStream() const
  173. {
  174. return this->BuildFileStream.get();
  175. }
  176. cmGeneratedFileStream* GetRulesFileStream() const
  177. {
  178. return this->RulesFileStream.get();
  179. }
  180. std::string const& ConvertToNinjaPath(const std::string& path) const;
  181. struct MapToNinjaPathImpl
  182. {
  183. cmGlobalNinjaGenerator* GG;
  184. MapToNinjaPathImpl(cmGlobalNinjaGenerator* gg)
  185. : GG(gg)
  186. {
  187. }
  188. std::string operator()(std::string const& path)
  189. {
  190. return this->GG->ConvertToNinjaPath(path);
  191. }
  192. };
  193. MapToNinjaPathImpl MapToNinjaPath() { return MapToNinjaPathImpl(this); }
  194. // -- Additional clean files
  195. void AddAdditionalCleanFile(std::string fileName);
  196. const char* GetAdditionalCleanTargetName() const
  197. {
  198. return "CMakeFiles/clean.additional";
  199. }
  200. void AddCXXCompileCommand(const std::string& commandLine,
  201. const std::string& sourceFile);
  202. /**
  203. * Add a rule to the generated build system.
  204. * Call WriteRule() behind the scene but perform some check before like:
  205. * - Do not add twice the same rule.
  206. */
  207. void AddRule(cmNinjaRule const& rule);
  208. bool HasRule(const std::string& name);
  209. void AddCustomCommandRule();
  210. void AddMacOSXContentRule();
  211. bool HasCustomCommandOutput(const std::string& output)
  212. {
  213. return this->CustomCommandOutputs.find(output) !=
  214. this->CustomCommandOutputs.end();
  215. }
  216. /// Called when we have seen the given custom command. Returns true
  217. /// if we has seen it before.
  218. bool SeenCustomCommand(cmCustomCommand const* cc)
  219. {
  220. return !this->CustomCommands.insert(cc).second;
  221. }
  222. /// Called when we have seen the given custom command output.
  223. void SeenCustomCommandOutput(const std::string& output)
  224. {
  225. this->CustomCommandOutputs.insert(output);
  226. // We don't need the assumed dependencies anymore, because we have
  227. // an output.
  228. this->AssumedSourceDependencies.erase(output);
  229. }
  230. void AddAssumedSourceDependencies(const std::string& source,
  231. const cmNinjaDeps& deps)
  232. {
  233. std::set<std::string>& ASD = this->AssumedSourceDependencies[source];
  234. // Because we may see the same source file multiple times (same source
  235. // specified in multiple targets), compute the union of any assumed
  236. // dependencies.
  237. ASD.insert(deps.begin(), deps.end());
  238. }
  239. void AppendTargetOutputs(
  240. cmGeneratorTarget const* target, cmNinjaDeps& outputs,
  241. cmNinjaTargetDepends depends = DependOnTargetArtifact);
  242. void AppendTargetDepends(
  243. cmGeneratorTarget const* target, cmNinjaDeps& outputs,
  244. cmNinjaTargetDepends depends = DependOnTargetArtifact);
  245. void AppendTargetDependsClosure(cmGeneratorTarget const* target,
  246. cmNinjaDeps& outputs);
  247. void AppendTargetDependsClosure(cmGeneratorTarget const* target,
  248. cmNinjaOuts& outputs, bool omit_self);
  249. void AddDependencyToAll(cmGeneratorTarget* target);
  250. void AddDependencyToAll(const std::string& input);
  251. const std::vector<cmLocalGenerator*>& GetLocalGenerators() const
  252. {
  253. return LocalGenerators;
  254. }
  255. bool IsExcluded(cmGeneratorTarget* target)
  256. {
  257. return cmGlobalGenerator::IsExcluded(target);
  258. }
  259. int GetRuleCmdLength(const std::string& name) { return RuleCmdLength[name]; }
  260. void AddTargetAlias(const std::string& alias, cmGeneratorTarget* target);
  261. void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const override;
  262. // Ninja generator uses 'deps' and 'msvc_deps_prefix' introduced in 1.3
  263. static std::string RequiredNinjaVersion() { return "1.3"; }
  264. static std::string RequiredNinjaVersionForConsolePool() { return "1.5"; }
  265. static std::string RequiredNinjaVersionForImplicitOuts() { return "1.7"; }
  266. static std::string RequiredNinjaVersionForManifestRestat() { return "1.8"; }
  267. static std::string RequiredNinjaVersionForMultilineDepfile()
  268. {
  269. return "1.9";
  270. }
  271. static std::string RequiredNinjaVersionForDyndeps() { return "1.10"; }
  272. bool SupportsConsolePool() const;
  273. bool SupportsImplicitOuts() const;
  274. bool SupportsManifestRestat() const;
  275. bool SupportsMultilineDepfile() const;
  276. std::string NinjaOutputPath(std::string const& path) const;
  277. bool HasOutputPathPrefix() const { return !this->OutputPathPrefix.empty(); }
  278. void StripNinjaOutputPathPrefixAsSuffix(std::string& path);
  279. bool WriteDyndepFile(std::string const& dir_top_src,
  280. std::string const& dir_top_bld,
  281. std::string const& dir_cur_src,
  282. std::string const& dir_cur_bld,
  283. std::string const& arg_dd,
  284. std::vector<std::string> const& arg_ddis,
  285. std::string const& module_dir,
  286. std::vector<std::string> const& linked_target_dirs,
  287. std::string const& arg_lang);
  288. protected:
  289. void Generate() override;
  290. bool CheckALLOW_DUPLICATE_CUSTOM_TARGETS() const override { return true; }
  291. private:
  292. std::string GetEditCacheCommand() const override;
  293. bool FindMakeProgram(cmMakefile* mf) override;
  294. void CheckNinjaFeatures();
  295. bool CheckLanguages(std::vector<std::string> const& languages,
  296. cmMakefile* mf) const override;
  297. bool CheckFortran(cmMakefile* mf) const;
  298. bool OpenBuildFileStream();
  299. void CloseBuildFileStream();
  300. void CloseCompileCommandsStream();
  301. bool OpenRulesFileStream();
  302. void CloseRulesFileStream();
  303. /// Write the common disclaimer text at the top of each build file.
  304. void WriteDisclaimer(std::ostream& os);
  305. void WriteAssumedSourceDependencies();
  306. void WriteTargetAliases(std::ostream& os);
  307. void WriteFolderTargets(std::ostream& os);
  308. void WriteUnknownExplicitDependencies(std::ostream& os);
  309. void WriteBuiltinTargets(std::ostream& os);
  310. void WriteTargetAll(std::ostream& os);
  311. void WriteTargetRebuildManifest(std::ostream& os);
  312. bool WriteTargetCleanAdditional(std::ostream& os);
  313. void WriteTargetClean(std::ostream& os);
  314. void WriteTargetHelp(std::ostream& os);
  315. void ComputeTargetDependsClosure(
  316. cmGeneratorTarget const* target,
  317. std::set<cmGeneratorTarget const*>& depends);
  318. std::string CMakeCmd() const;
  319. std::string NinjaCmd() const;
  320. /// The file containing the build statement. (the relationship of the
  321. /// compilation DAG).
  322. std::unique_ptr<cmGeneratedFileStream> BuildFileStream;
  323. /// The file containing the rule statements. (The action attached to each
  324. /// edge of the compilation DAG).
  325. std::unique_ptr<cmGeneratedFileStream> RulesFileStream;
  326. std::unique_ptr<cmGeneratedFileStream> CompileCommandsStream;
  327. /// The set of rules added to the generated build system.
  328. std::unordered_set<std::string> Rules;
  329. /// Length of rule command, used by rsp file evaluation
  330. std::unordered_map<std::string, int> RuleCmdLength;
  331. /// The set of dependencies to add to the "all" target.
  332. cmNinjaDeps AllDependencies;
  333. bool UsingGCCOnWindows = false;
  334. /// The set of custom commands we have seen.
  335. std::set<cmCustomCommand const*> CustomCommands;
  336. /// The set of custom command outputs we have seen.
  337. std::set<std::string> CustomCommandOutputs;
  338. /// Whether we are collecting known build outputs and needed
  339. /// dependencies to determine unknown dependencies.
  340. bool ComputingUnknownDependencies = false;
  341. cmPolicies::PolicyStatus PolicyCMP0058 = cmPolicies::WARN;
  342. /// The combined explicit dependencies of custom build commands
  343. std::set<std::string> CombinedCustomCommandExplicitDependencies;
  344. /// When combined with CombinedCustomCommandExplicitDependencies it allows
  345. /// us to detect the set of explicit dependencies that have
  346. std::set<std::string> CombinedBuildOutputs;
  347. /// The mapping from source file to assumed dependencies.
  348. std::map<std::string, std::set<std::string>> AssumedSourceDependencies;
  349. using TargetAliasMap = std::map<std::string, cmGeneratorTarget*>;
  350. TargetAliasMap TargetAliases;
  351. std::map<cmGeneratorTarget const*, cmNinjaOuts> TargetDependsClosures;
  352. /// the local cache for calls to ConvertToNinjaPath
  353. mutable std::unordered_map<std::string, std::string> ConvertToNinjaPathCache;
  354. std::string NinjaCommand;
  355. std::string NinjaVersion;
  356. bool NinjaSupportsConsolePool = false;
  357. bool NinjaSupportsImplicitOuts = false;
  358. bool NinjaSupportsManifestRestat = false;
  359. bool NinjaSupportsMultilineDepfile = false;
  360. bool NinjaSupportsDyndeps = false;
  361. private:
  362. void InitOutputPathPrefix();
  363. std::string OutputPathPrefix;
  364. std::string TargetAll;
  365. std::string CMakeCacheFile;
  366. std::set<std::string> AdditionalCleanFiles;
  367. };
  368. #endif // ! cmGlobalNinjaGenerator_h