cmGlobalNinjaGenerator.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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 "cm_codecvt.hxx"
  16. #include "cmGeneratedFileStream.h"
  17. #include "cmGlobalCommonGenerator.h"
  18. #include "cmGlobalGeneratorFactory.h"
  19. #include "cmNinjaTypes.h"
  20. #include "cmPolicies.h"
  21. class cmCustomCommand;
  22. class cmGeneratorTarget;
  23. class cmLinkLineComputer;
  24. class cmLocalGenerator;
  25. class cmMakefile;
  26. class cmOutputConverter;
  27. class cmStateDirectory;
  28. class cmake;
  29. struct cmDocumentationEntry;
  30. /**
  31. * \class cmGlobalNinjaGenerator
  32. * \brief Write a build.ninja file.
  33. *
  34. * The main differences between this generator and the UnixMakefile
  35. * generator family are:
  36. * - We don't care about VERBOSE variable or RULE_MESSAGES property since
  37. * it is handle by Ninja's -v option.
  38. * - We don't care about computing any progress status since Ninja manages
  39. * it itself.
  40. * - We generate one build.ninja and one rules.ninja per project.
  41. * - We try to minimize the number of generated rules: one per target and
  42. * language.
  43. * - We use Ninja special variable $in and $out to produce nice output.
  44. * - We extensively use Ninja variable overloading system to minimize the
  45. * number of generated rules.
  46. */
  47. class cmGlobalNinjaGenerator : public cmGlobalCommonGenerator
  48. {
  49. public:
  50. /// The default name of Ninja's build file. Typically: build.ninja.
  51. static const char* NINJA_BUILD_FILE;
  52. /// The default name of Ninja's rules file. Typically: rules.ninja.
  53. /// It is included in the main build.ninja file.
  54. static const char* NINJA_RULES_FILE;
  55. /// The indentation string used when generating Ninja's build file.
  56. static const char* INDENT;
  57. /// The shell command used for a no-op.
  58. static std::string const SHELL_NOOP;
  59. /// Write @a count times INDENT level to output stream @a os.
  60. static void Indent(std::ostream& os, int count);
  61. /// Write a divider in the given output stream @a os.
  62. static void WriteDivider(std::ostream& os);
  63. static std::string EncodeRuleName(std::string const& name);
  64. static std::string EncodeLiteral(const std::string& lit);
  65. std::string EncodePath(const std::string& path);
  66. cmLinkLineComputer* CreateLinkLineComputer(
  67. cmOutputConverter* outputConverter,
  68. cmStateDirectory const& stateDir) const override;
  69. /**
  70. * Write the given @a comment to the output stream @a os. It
  71. * handles new line character properly.
  72. */
  73. static void WriteComment(std::ostream& os, const std::string& comment);
  74. /**
  75. * Utilized by the generator factory to determine if this generator
  76. * supports toolsets.
  77. */
  78. static bool SupportsToolset() { return false; }
  79. /**
  80. * Utilized by the generator factory to determine if this generator
  81. * supports platforms.
  82. */
  83. static bool SupportsPlatform() { return false; }
  84. bool IsIPOSupported() const override { return true; }
  85. /**
  86. * Write a build statement @a build to @a os.
  87. * @warning no escaping of any kind is done here.
  88. */
  89. void WriteBuild(std::ostream& os, cmNinjaBuild const& build,
  90. int cmdLineLimit = 0, bool* usedResponseFile = nullptr);
  91. void WriteCustomCommandBuild(
  92. const std::string& command, const std::string& description,
  93. const std::string& comment, const std::string& depfile,
  94. const std::string& pool, bool uses_terminal, bool restat,
  95. const cmNinjaDeps& outputs,
  96. const cmNinjaDeps& explicitDeps = cmNinjaDeps(),
  97. const cmNinjaDeps& orderOnlyDeps = cmNinjaDeps());
  98. void WriteMacOSXContentBuild(std::string input, std::string output);
  99. /**
  100. * Write a rule statement to @a os.
  101. * @warning no escaping of any kind is done here.
  102. */
  103. static void WriteRule(std::ostream& os, cmNinjaRule const& rule);
  104. /**
  105. * Write a variable named @a name to @a os with value @a value and an
  106. * optional @a comment. An @a indent level can be specified.
  107. * @warning no escaping of any kind is done here.
  108. */
  109. static void WriteVariable(std::ostream& os, const std::string& name,
  110. const std::string& value,
  111. const std::string& comment = "", int indent = 0);
  112. /**
  113. * Write an include statement including @a filename with an optional
  114. * @a comment to the @a os stream.
  115. */
  116. static void WriteInclude(std::ostream& os, const std::string& filename,
  117. const std::string& comment = "");
  118. /**
  119. * Write a default target statement specifying @a targets as
  120. * the default targets.
  121. */
  122. static void WriteDefault(std::ostream& os, const cmNinjaDeps& targets,
  123. const std::string& comment = "");
  124. bool IsGCCOnWindows() const { return UsingGCCOnWindows; }
  125. public:
  126. cmGlobalNinjaGenerator(cmake* cm);
  127. static cmGlobalGeneratorFactory* NewFactory()
  128. {
  129. return new cmGlobalGeneratorSimpleFactory<cmGlobalNinjaGenerator>();
  130. }
  131. std::unique_ptr<cmLocalGenerator> CreateLocalGenerator(
  132. 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 { 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. int GetRuleCmdLength(const std::string& name) { return RuleCmdLength[name]; }
  250. void AddTargetAlias(const std::string& alias, cmGeneratorTarget* target);
  251. void ComputeTargetObjectDirectory(cmGeneratorTarget* gt) const override;
  252. // Ninja generator uses 'deps' and 'msvc_deps_prefix' introduced in 1.3
  253. static std::string RequiredNinjaVersion() { return "1.3"; }
  254. static std::string RequiredNinjaVersionForConsolePool() { return "1.5"; }
  255. static std::string RequiredNinjaVersionForImplicitOuts() { return "1.7"; }
  256. static std::string RequiredNinjaVersionForManifestRestat() { return "1.8"; }
  257. static std::string RequiredNinjaVersionForMultilineDepfile()
  258. {
  259. return "1.9";
  260. }
  261. static std::string RequiredNinjaVersionForDyndeps() { return "1.10"; }
  262. bool SupportsConsolePool() const;
  263. bool SupportsImplicitOuts() const;
  264. bool SupportsManifestRestat() const;
  265. bool SupportsMultilineDepfile() const;
  266. std::string NinjaOutputPath(std::string const& path) const;
  267. bool HasOutputPathPrefix() const { return !this->OutputPathPrefix.empty(); }
  268. void StripNinjaOutputPathPrefixAsSuffix(std::string& path);
  269. bool WriteDyndepFile(std::string const& dir_top_src,
  270. std::string const& dir_top_bld,
  271. std::string const& dir_cur_src,
  272. std::string const& dir_cur_bld,
  273. std::string const& arg_dd,
  274. std::vector<std::string> const& arg_ddis,
  275. std::string const& module_dir,
  276. std::vector<std::string> const& linked_target_dirs,
  277. std::string const& arg_lang);
  278. protected:
  279. void Generate() override;
  280. bool CheckALLOW_DUPLICATE_CUSTOM_TARGETS() const override { return true; }
  281. private:
  282. std::string GetEditCacheCommand() const override;
  283. bool FindMakeProgram(cmMakefile* mf) override;
  284. void CheckNinjaFeatures();
  285. bool CheckLanguages(std::vector<std::string> const& languages,
  286. cmMakefile* mf) const override;
  287. bool CheckFortran(cmMakefile* mf) const;
  288. bool OpenBuildFileStream();
  289. void CloseBuildFileStream();
  290. void CloseCompileCommandsStream();
  291. bool OpenRulesFileStream();
  292. void CloseRulesFileStream();
  293. /// Write the common disclaimer text at the top of each build file.
  294. void WriteDisclaimer(std::ostream& os);
  295. void WriteAssumedSourceDependencies();
  296. void WriteTargetAliases(std::ostream& os);
  297. void WriteFolderTargets(std::ostream& os);
  298. void WriteUnknownExplicitDependencies(std::ostream& os);
  299. void WriteBuiltinTargets(std::ostream& os);
  300. void WriteTargetDefault(std::ostream& os);
  301. void WriteTargetRebuildManifest(std::ostream& os);
  302. bool WriteTargetCleanAdditional(std::ostream& os);
  303. void WriteTargetClean(std::ostream& os);
  304. void WriteTargetHelp(std::ostream& os);
  305. void ComputeTargetDependsClosure(
  306. cmGeneratorTarget const* target,
  307. std::set<cmGeneratorTarget const*>& depends);
  308. std::string CMakeCmd() const;
  309. std::string NinjaCmd() const;
  310. /// The file containing the build statement. (the relationship of the
  311. /// compilation DAG).
  312. std::unique_ptr<cmGeneratedFileStream> BuildFileStream;
  313. /// The file containing the rule statements. (The action attached to each
  314. /// edge of the compilation DAG).
  315. std::unique_ptr<cmGeneratedFileStream> RulesFileStream;
  316. std::unique_ptr<cmGeneratedFileStream> CompileCommandsStream;
  317. /// The set of rules added to the generated build system.
  318. std::unordered_set<std::string> Rules;
  319. /// Length of rule command, used by rsp file evaluation
  320. std::unordered_map<std::string, int> RuleCmdLength;
  321. bool UsingGCCOnWindows = false;
  322. /// The set of custom commands we have seen.
  323. std::set<cmCustomCommand const*> CustomCommands;
  324. /// The set of custom command outputs we have seen.
  325. std::set<std::string> CustomCommandOutputs;
  326. /// Whether we are collecting known build outputs and needed
  327. /// dependencies to determine unknown dependencies.
  328. bool ComputingUnknownDependencies = false;
  329. cmPolicies::PolicyStatus PolicyCMP0058 = cmPolicies::WARN;
  330. /// The combined explicit dependencies of custom build commands
  331. std::set<std::string> CombinedCustomCommandExplicitDependencies;
  332. /// When combined with CombinedCustomCommandExplicitDependencies it allows
  333. /// us to detect the set of explicit dependencies that have
  334. std::set<std::string> CombinedBuildOutputs;
  335. /// The mapping from source file to assumed dependencies.
  336. std::map<std::string, std::set<std::string>> AssumedSourceDependencies;
  337. using TargetAliasMap = std::map<std::string, cmGeneratorTarget*>;
  338. TargetAliasMap TargetAliases;
  339. std::map<cmGeneratorTarget const*, cmNinjaOuts> TargetDependsClosures;
  340. /// the local cache for calls to ConvertToNinjaPath
  341. mutable std::unordered_map<std::string, std::string> ConvertToNinjaPathCache;
  342. std::string NinjaCommand;
  343. std::string NinjaVersion;
  344. bool NinjaSupportsConsolePool = false;
  345. bool NinjaSupportsImplicitOuts = false;
  346. bool NinjaSupportsManifestRestat = false;
  347. bool NinjaSupportsMultilineDepfile = false;
  348. bool NinjaSupportsDyndeps = false;
  349. private:
  350. void InitOutputPathPrefix();
  351. std::string OutputPathPrefix;
  352. std::string TargetAll;
  353. std::string CMakeCacheFile;
  354. std::set<std::string> AdditionalCleanFiles;
  355. };
  356. #endif // ! cmGlobalNinjaGenerator_h