cmMakefile.h 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #pragma once
  4. #include "cmConfigure.h" // IWYU pragma: keep
  5. #include <cstddef>
  6. #include <deque>
  7. #include <functional>
  8. #include <map>
  9. #include <memory>
  10. #include <set>
  11. #include <stack>
  12. #include <string>
  13. #include <unordered_map>
  14. #include <utility>
  15. #include <vector>
  16. #include <cm/optional>
  17. #include <cm/string_view>
  18. #include "cmsys/RegularExpression.hxx"
  19. #include "cm_sys_stat.h"
  20. #include "cmAlgorithms.h"
  21. #include "cmCustomCommand.h"
  22. #include "cmFindPackageStack.h"
  23. #include "cmFunctionBlocker.h"
  24. #include "cmListFileCache.h"
  25. #include "cmMessageType.h" // IWYU pragma: keep
  26. #include "cmNewLineStyle.h"
  27. #include "cmPolicies.h"
  28. #include "cmSourceFileLocationKind.h"
  29. #include "cmStateSnapshot.h"
  30. #include "cmStateTypes.h"
  31. #include "cmValue.h"
  32. // IWYU does not see that 'std::unordered_map<std::string, cmTarget>'
  33. // will not compile without the complete type.
  34. #include "cmTarget.h" // IWYU pragma: keep
  35. #if !defined(CMAKE_BOOTSTRAP)
  36. # include "cmSourceGroup.h"
  37. #endif
  38. enum class cmCustomCommandType;
  39. enum class cmObjectLibraryCommands;
  40. class cmCompiledGeneratorExpression;
  41. class cmCustomCommandLines;
  42. class cmExecutionStatus;
  43. class cmExpandedCommandArgument;
  44. class cmExportBuildFileGenerator;
  45. class cmGeneratorExpressionEvaluationFile;
  46. class cmGlobalGenerator;
  47. class cmInstallGenerator;
  48. class cmLocalGenerator;
  49. class cmMessenger;
  50. class cmSourceFile;
  51. class cmState;
  52. class cmTest;
  53. class cmTestGenerator;
  54. class cmVariableWatch;
  55. class cmake;
  56. /** A type-safe wrapper for a string representing a directory id. */
  57. class cmDirectoryId
  58. {
  59. public:
  60. cmDirectoryId(std::string s);
  61. std::string String;
  62. };
  63. /** \class cmMakefile
  64. * \brief Process the input CMakeLists.txt file.
  65. *
  66. * Process and store into memory the input CMakeLists.txt file.
  67. * Each CMakeLists.txt file is parsed and the commands found there
  68. * are added into the build process.
  69. */
  70. class cmMakefile
  71. {
  72. public:
  73. /* Mark a variable as used */
  74. void MarkVariableAsUsed(const std::string& var);
  75. /* return true if a variable has been initialized */
  76. bool VariableInitialized(const std::string&) const;
  77. /**
  78. * Construct an empty makefile.
  79. */
  80. cmMakefile(cmGlobalGenerator* globalGenerator,
  81. const cmStateSnapshot& snapshot);
  82. /**
  83. * Destructor.
  84. */
  85. ~cmMakefile();
  86. cmMakefile(cmMakefile const&) = delete;
  87. cmMakefile& operator=(cmMakefile const&) = delete;
  88. cmDirectoryId GetDirectoryId() const;
  89. bool ReadListFile(const std::string& filename);
  90. bool ReadListFileAsString(const std::string& content,
  91. const std::string& virtualFileName);
  92. bool ReadDependentFile(const std::string& filename,
  93. bool noPolicyScope = true);
  94. /**
  95. * Add a function blocker to this makefile
  96. */
  97. void AddFunctionBlocker(std::unique_ptr<cmFunctionBlocker> fb);
  98. /// @return whether we are processing the top CMakeLists.txt file.
  99. bool IsRootMakefile() const;
  100. /**
  101. * Remove the function blocker whose scope ends with the given command.
  102. * This returns ownership of the function blocker object.
  103. */
  104. std::unique_ptr<cmFunctionBlocker> RemoveFunctionBlocker();
  105. /**
  106. * Try running cmake and building a file. This is used for dynamically
  107. * loaded commands, not as part of the usual build process.
  108. */
  109. int TryCompile(const std::string& srcdir, const std::string& bindir,
  110. const std::string& projectName, const std::string& targetName,
  111. bool fast, int jobs,
  112. const std::vector<std::string>* cmakeArgs,
  113. std::string& output);
  114. bool GetIsSourceFileTryCompile() const;
  115. /**
  116. * Help enforce global target name uniqueness.
  117. */
  118. bool EnforceUniqueName(std::string const& name, std::string& msg,
  119. bool isCustom = false) const;
  120. enum class GeneratorActionWhen
  121. {
  122. // Run after all CMake code has been parsed.
  123. AfterConfigure,
  124. // Run after generator targets have been constructed.
  125. AfterGeneratorTargets,
  126. };
  127. class GeneratorAction
  128. {
  129. using ActionT =
  130. std::function<void(cmLocalGenerator&, const cmListFileBacktrace&)>;
  131. using CCActionT =
  132. std::function<void(cmLocalGenerator&, const cmListFileBacktrace&,
  133. std::unique_ptr<cmCustomCommand> cc)>;
  134. public:
  135. GeneratorAction(
  136. ActionT&& action,
  137. GeneratorActionWhen when = GeneratorActionWhen::AfterConfigure)
  138. : When(when)
  139. , Action(std::move(action))
  140. {
  141. }
  142. GeneratorAction(
  143. std::unique_ptr<cmCustomCommand> tcc, CCActionT&& action,
  144. GeneratorActionWhen when = GeneratorActionWhen::AfterConfigure)
  145. : When(when)
  146. , CCAction(std::move(action))
  147. , cc(std::move(tcc))
  148. {
  149. }
  150. void operator()(cmLocalGenerator& lg, const cmListFileBacktrace& lfbt,
  151. GeneratorActionWhen when);
  152. private:
  153. GeneratorActionWhen When;
  154. ActionT Action;
  155. // FIXME: Use std::variant
  156. CCActionT CCAction;
  157. std::unique_ptr<cmCustomCommand> cc;
  158. };
  159. /**
  160. * Register an action that is executed during Generate
  161. */
  162. void AddGeneratorAction(GeneratorAction&& action);
  163. /// Helper to insert the constructor GeneratorAction(args...)
  164. template <class... Args>
  165. void AddGeneratorAction(Args&&... args)
  166. {
  167. AddGeneratorAction(GeneratorAction(std::move(args)...));
  168. }
  169. /**
  170. * Perform generate actions, Library dependency analysis etc before output of
  171. * the makefile.
  172. */
  173. void Generate(cmLocalGenerator& lg);
  174. void GenerateAfterGeneratorTargets(cmLocalGenerator& lg);
  175. /**
  176. * Get the target for PRE_BUILD, PRE_LINK, or POST_BUILD commands.
  177. */
  178. cmTarget* GetCustomCommandTarget(const std::string& target,
  179. cmObjectLibraryCommands objLibCommands,
  180. const cmListFileBacktrace& lfbt) const;
  181. /**
  182. * Dispatch adding a custom PRE_BUILD, PRE_LINK, or POST_BUILD command to a
  183. * target.
  184. */
  185. cmTarget* AddCustomCommandToTarget(const std::string& target,
  186. cmCustomCommandType type,
  187. std::unique_ptr<cmCustomCommand> cc);
  188. /**
  189. * Called for each file with custom command.
  190. */
  191. using CommandSourceCallback = std::function<void(cmSourceFile*)>;
  192. /**
  193. * Dispatch adding a custom command to a source file.
  194. */
  195. void AddCustomCommandToOutput(
  196. std::unique_ptr<cmCustomCommand> cc,
  197. const CommandSourceCallback& callback = nullptr, bool replace = false);
  198. void AddCustomCommandOldStyle(const std::string& target,
  199. const std::vector<std::string>& outputs,
  200. const std::vector<std::string>& depends,
  201. const std::string& source,
  202. const cmCustomCommandLines& commandLines,
  203. const char* comment);
  204. void AppendCustomCommandToOutput(
  205. const std::string& output, const std::vector<std::string>& depends,
  206. const cmImplicitDependsList& implicit_depends,
  207. const cmCustomCommandLines& commandLines);
  208. /**
  209. * Add a define flag to the build.
  210. */
  211. void AddDefineFlag(std::string const& definition);
  212. void RemoveDefineFlag(std::string const& definition);
  213. void AddCompileDefinition(std::string const& definition);
  214. void AddCompileOption(std::string const& option);
  215. void AddLinkOption(std::string const& option);
  216. void AddLinkDirectory(std::string const& directory, bool before = false);
  217. /** Create a new imported target with the name and type given. */
  218. cmTarget* AddImportedTarget(const std::string& name,
  219. cmStateEnums::TargetType type, bool global);
  220. std::pair<cmTarget&, bool> CreateNewTarget(
  221. const std::string& name, cmStateEnums::TargetType type,
  222. cmTarget::PerConfig perConfig = cmTarget::PerConfig::Yes,
  223. cmTarget::Visibility vis = cmTarget::Visibility::Normal);
  224. cmTarget* AddNewTarget(cmStateEnums::TargetType type,
  225. const std::string& name);
  226. cmTarget* AddSynthesizedTarget(cmStateEnums::TargetType type,
  227. const std::string& name);
  228. /** Create a target instance for the utility. */
  229. cmTarget* AddNewUtilityTarget(const std::string& utilityName,
  230. bool excludeFromAll);
  231. /**
  232. * Add an executable to the build.
  233. */
  234. cmTarget* AddExecutable(const std::string& exename,
  235. const std::vector<std::string>& srcs,
  236. bool excludeFromAll = false);
  237. /**
  238. * Dispatch adding a utility to the build. A utility target is a command
  239. * that is run every time the target is built.
  240. */
  241. cmTarget* AddUtilityCommand(const std::string& utilityName,
  242. bool excludeFromAll,
  243. std::unique_ptr<cmCustomCommand> cc);
  244. /**
  245. * Add a subdirectory to the build.
  246. */
  247. void AddSubDirectory(const std::string& fullSrcDir,
  248. const std::string& fullBinDir, bool excludeFromAll,
  249. bool immediate, bool system);
  250. void Configure();
  251. /**
  252. * Configure a subdirectory
  253. */
  254. void ConfigureSubDirectory(cmMakefile* mf);
  255. /**
  256. * Add an include directory to the build.
  257. */
  258. void AddIncludeDirectories(const std::vector<std::string>& incs,
  259. bool before = false);
  260. /**
  261. * Add a variable definition to the build. This variable
  262. * can be used in CMake to refer to lists, directories, etc.
  263. */
  264. void AddDefinition(const std::string& name, cm::string_view value);
  265. void AddDefinition(const std::string& name, cmValue value)
  266. {
  267. this->AddDefinition(name, *value);
  268. }
  269. /**
  270. * Add bool variable definition to the build.
  271. */
  272. void AddDefinitionBool(const std::string& name, bool);
  273. //! Add a definition to this makefile and the global cmake cache.
  274. void AddCacheDefinition(const std::string& name, cmValue value, cmValue doc,
  275. cmStateEnums::CacheEntryType type,
  276. bool force = false);
  277. void AddCacheDefinition(const std::string& name, cmValue value,
  278. const std::string& doc,
  279. cmStateEnums::CacheEntryType type,
  280. bool force = false)
  281. {
  282. this->AddCacheDefinition(name, value, cmValue{ doc }, type, force);
  283. }
  284. void AddCacheDefinition(const std::string& name, const std::string& value,
  285. const std::string& doc,
  286. cmStateEnums::CacheEntryType type,
  287. bool force = false)
  288. {
  289. this->AddCacheDefinition(name, cmValue{ value }, cmValue{ doc }, type,
  290. force);
  291. }
  292. /**
  293. * Remove a variable definition from the build. This is not valid
  294. * for cache entries, and will only affect the current makefile.
  295. */
  296. void RemoveDefinition(const std::string& name);
  297. //! Remove a definition from the cache.
  298. void RemoveCacheDefinition(const std::string& name) const;
  299. /**
  300. * Specify the name of the project for this build.
  301. */
  302. void SetProjectName(std::string const& name);
  303. void InitCMAKE_CONFIGURATION_TYPES(std::string const& genDefault);
  304. /* Get the default configuration */
  305. std::string GetDefaultConfiguration() const;
  306. enum GeneratorConfigQuery
  307. {
  308. IncludeEmptyConfig, // Include "" aka noconfig
  309. ExcludeEmptyConfig, // Exclude "" aka noconfig
  310. OnlyMultiConfig,
  311. };
  312. /** Get the configurations for dependency checking. */
  313. std::vector<std::string> GetGeneratorConfigs(
  314. GeneratorConfigQuery mode) const;
  315. /**
  316. * Set the name of the library.
  317. */
  318. cmTarget* AddLibrary(const std::string& libname,
  319. cmStateEnums::TargetType type,
  320. const std::vector<std::string>& srcs,
  321. bool excludeFromAll = false);
  322. void AddAlias(const std::string& libname, const std::string& tgt,
  323. bool globallyVisible = true);
  324. //@{
  325. /**
  326. * Set, Push, Pop policy values for CMake.
  327. */
  328. bool SetPolicy(cmPolicies::PolicyID id, cmPolicies::PolicyStatus status);
  329. bool SetPolicy(const char* id, cmPolicies::PolicyStatus status);
  330. cmPolicies::PolicyStatus GetPolicyStatus(cmPolicies::PolicyID id,
  331. bool parent_scope = false) const;
  332. bool SetPolicyVersion(std::string const& version_min,
  333. std::string const& version_max);
  334. void RecordPolicies(cmPolicies::PolicyMap& pm) const;
  335. //@}
  336. /** Helper class to push and pop policies automatically. */
  337. class PolicyPushPop
  338. {
  339. public:
  340. PolicyPushPop(cmMakefile* m);
  341. ~PolicyPushPop();
  342. PolicyPushPop(const PolicyPushPop&) = delete;
  343. PolicyPushPop& operator=(const PolicyPushPop&) = delete;
  344. private:
  345. cmMakefile* Makefile;
  346. };
  347. friend class PolicyPushPop;
  348. /** Helper class to push and pop variables scopes automatically. */
  349. class VariablePushPop
  350. {
  351. public:
  352. VariablePushPop(cmMakefile* m);
  353. ~VariablePushPop();
  354. VariablePushPop(VariablePushPop const&) = delete;
  355. VariablePushPop& operator=(VariablePushPop const&) = delete;
  356. private:
  357. cmMakefile* Makefile;
  358. };
  359. /**
  360. * Determine if the given context, name pair has already been reported
  361. * in context of CMP0054.
  362. */
  363. bool HasCMP0054AlreadyBeenReported(const cmListFileContext& context) const;
  364. bool IgnoreErrorsCMP0061() const;
  365. std::string const& GetHomeDirectory() const;
  366. std::string const& GetHomeOutputDirectory() const;
  367. /**
  368. * Set CMAKE_SCRIPT_MODE_FILE variable when running a -P script.
  369. */
  370. void SetScriptModeFile(std::string const& scriptfile);
  371. /**
  372. * Set CMAKE_ARGC, CMAKE_ARGV0 ... variables.
  373. */
  374. void SetArgcArgv(const std::vector<std::string>& args);
  375. std::string const& GetCurrentSourceDirectory() const;
  376. std::string const& GetCurrentBinaryDirectory() const;
  377. //@}
  378. /**
  379. * Set a regular expression that include files must match
  380. * in order to be considered as part of the depend information.
  381. */
  382. void SetIncludeRegularExpression(const std::string& regex)
  383. {
  384. this->SetProperty("INCLUDE_REGULAR_EXPRESSION", regex);
  385. }
  386. const std::string& GetIncludeRegularExpression() const
  387. {
  388. return this->GetProperty("INCLUDE_REGULAR_EXPRESSION");
  389. }
  390. /**
  391. * Set a regular expression that include files that are not found
  392. * must match in order to be considered a problem.
  393. */
  394. void SetComplainRegularExpression(const std::string& regex)
  395. {
  396. this->ComplainFileRegularExpression = regex;
  397. }
  398. const std::string& GetComplainRegularExpression() const
  399. {
  400. return this->ComplainFileRegularExpression;
  401. }
  402. // -- List of targets
  403. using cmTargetMap = std::unordered_map<std::string, cmTarget>;
  404. /** Get the target map */
  405. cmTargetMap& GetTargets() { return this->Targets; }
  406. /** Get the target map - const version */
  407. cmTargetMap const& GetTargets() const { return this->Targets; }
  408. const std::vector<std::unique_ptr<cmTarget>>& GetOwnedImportedTargets() const
  409. {
  410. return this->ImportedTargetsOwned;
  411. }
  412. std::vector<cmTarget*> GetImportedTargets() const;
  413. cmTarget* FindLocalNonAliasTarget(const std::string& name) const;
  414. /** Find a target to use in place of the given name. The target
  415. returned may be imported or built within the project. */
  416. cmTarget* FindTargetToUse(const std::string& name,
  417. bool excludeAliases = false) const;
  418. bool IsAlias(const std::string& name) const;
  419. std::map<std::string, std::string> GetAliasTargets() const
  420. {
  421. return this->AliasTargets;
  422. }
  423. /**
  424. * Mark include directories as system directories.
  425. */
  426. void AddSystemIncludeDirectories(const std::set<std::string>& incs);
  427. /** Get a cmSourceFile pointer for a given source name, if the name is
  428. * not found, then a null pointer is returned.
  429. */
  430. cmSourceFile* GetSource(
  431. const std::string& sourceName,
  432. cmSourceFileLocationKind kind = cmSourceFileLocationKind::Ambiguous) const;
  433. /** Create the source file and return it. generated
  434. * indicates if it is a generated file, this is used in determining
  435. * how to create the source file instance e.g. name
  436. */
  437. cmSourceFile* CreateSource(
  438. const std::string& sourceName, bool generated = false,
  439. cmSourceFileLocationKind kind = cmSourceFileLocationKind::Ambiguous);
  440. /** Get a cmSourceFile pointer for a given source name, if the name is
  441. * not found, then create the source file and return it. generated
  442. * indicates if it is a generated file, this is used in determining
  443. * how to create the source file instance e.g. name
  444. */
  445. cmSourceFile* GetOrCreateSource(
  446. const std::string& sourceName, bool generated = false,
  447. cmSourceFileLocationKind kind = cmSourceFileLocationKind::Ambiguous);
  448. /** Get a cmSourceFile pointer for a given source name and always mark the
  449. * file as generated, if the name is not found, then create the source file
  450. * and return it.
  451. */
  452. cmSourceFile* GetOrCreateGeneratedSource(const std::string& sourceName);
  453. void AddTargetObject(std::string const& tgtName, std::string const& objFile);
  454. /**
  455. * Given a variable name, return its value (as a string).
  456. * If the variable is not found in this makefile instance, the
  457. * cache is then queried.
  458. */
  459. cmValue GetDefinition(const std::string&) const;
  460. const std::string& GetSafeDefinition(const std::string&) const;
  461. const std::string& GetRequiredDefinition(const std::string& name) const;
  462. bool IsDefinitionSet(const std::string&) const;
  463. bool IsNormalDefinitionSet(const std::string&) const;
  464. /**
  465. * Get the list of all variables in the current space. If argument
  466. * cacheonly is specified and is greater than 0, then only cache
  467. * variables will be listed.
  468. */
  469. std::vector<std::string> GetDefinitions() const;
  470. /**
  471. * Test a boolean variable to see if it is true or false.
  472. * If the variable is not found in this makefile instance, the
  473. * cache is then queried.
  474. * Returns false if no entry defined.
  475. */
  476. bool IsOn(const std::string& name) const;
  477. bool IsSet(const std::string& name) const;
  478. /** Return whether the target platform is 32-bit. */
  479. bool PlatformIs32Bit() const;
  480. /** Return whether the target platform is 64-bit. */
  481. bool PlatformIs64Bit() const;
  482. /** Return whether the target platform is x32. */
  483. bool PlatformIsx32() const;
  484. /** Apple SDK Type */
  485. enum class AppleSDK
  486. {
  487. MacOS,
  488. IPhoneOS,
  489. IPhoneSimulator,
  490. AppleTVOS,
  491. AppleTVSimulator,
  492. WatchOS,
  493. WatchSimulator,
  494. XROS,
  495. XRSimulator,
  496. };
  497. /** What SDK type points CMAKE_OSX_SYSROOT to? */
  498. AppleSDK GetAppleSDKType() const;
  499. /** Return whether the target platform is Apple iOS. */
  500. bool PlatformIsAppleEmbedded() const;
  501. /** Return whether the target platform is an Apple simulator. */
  502. bool PlatformIsAppleSimulator() const;
  503. /** Return whether the target platform is an Apple catalyst. */
  504. bool PlatformIsAppleCatalyst() const;
  505. /** Return whether the target platform supports generation of text base stubs
  506. (.tbd file) describing exports (Apple specific). */
  507. bool PlatformSupportsAppleTextStubs() const;
  508. /** Retrieve soname flag for the specified language if supported */
  509. const char* GetSONameFlag(const std::string& language) const;
  510. /**
  511. * Get a list of preprocessor define flags.
  512. */
  513. std::string GetDefineFlags() const { return this->DefineFlags; }
  514. /**
  515. * Make sure CMake can write this file
  516. */
  517. bool CanIWriteThisFile(std::string const& fileName) const;
  518. #if !defined(CMAKE_BOOTSTRAP)
  519. /**
  520. * Get the vector source groups.
  521. */
  522. const std::vector<cmSourceGroup>& GetSourceGroups() const
  523. {
  524. return this->SourceGroups;
  525. }
  526. /**
  527. * Get the source group
  528. */
  529. cmSourceGroup* GetSourceGroup(const std::vector<std::string>& name) const;
  530. /**
  531. * Add a root source group for consideration when adding a new source.
  532. */
  533. void AddSourceGroup(const std::string& name, const char* regex = nullptr);
  534. /**
  535. * Add a source group for consideration when adding a new source.
  536. * name is tokenized.
  537. */
  538. void AddSourceGroup(const std::vector<std::string>& name,
  539. const char* regex = nullptr);
  540. /**
  541. * Get and existing or create a new source group.
  542. */
  543. cmSourceGroup* GetOrCreateSourceGroup(
  544. const std::vector<std::string>& folders);
  545. /**
  546. * Get and existing or create a new source group.
  547. * The name will be tokenized.
  548. */
  549. cmSourceGroup* GetOrCreateSourceGroup(const std::string& name);
  550. /**
  551. * find what source group this source is in
  552. */
  553. cmSourceGroup* FindSourceGroup(const std::string& source,
  554. std::vector<cmSourceGroup>& groups) const;
  555. #endif
  556. /**
  557. * Get the vector of list files on which this makefile depends
  558. */
  559. const std::vector<std::string>& GetListFiles() const
  560. {
  561. return this->ListFiles;
  562. }
  563. //! When the file changes cmake will be re-run from the build system.
  564. void AddCMakeDependFile(const std::string& file)
  565. {
  566. this->ListFiles.push_back(file);
  567. }
  568. void AddCMakeDependFilesFromUser();
  569. std::string FormatListFileStack() const;
  570. /**
  571. * Get the current context backtrace.
  572. */
  573. cmListFileBacktrace GetBacktrace() const;
  574. /**
  575. * Get the current stack of find_package calls.
  576. */
  577. cmFindPackageStack GetFindPackageStack() const;
  578. /**
  579. * Get the vector of files created by this makefile
  580. */
  581. const std::vector<std::string>& GetOutputFiles() const
  582. {
  583. return this->OutputFiles;
  584. }
  585. void AddCMakeOutputFile(const std::string& file)
  586. {
  587. this->OutputFiles.push_back(file);
  588. }
  589. /**
  590. * Expand all defined variables in the string.
  591. * Defined variables come from the this->Definitions map.
  592. * They are expanded with ${var} where var is the
  593. * entry in the this->Definitions map. Also \@var\@ is
  594. * expanded to match autoconf style expansions.
  595. */
  596. const std::string& ExpandVariablesInString(std::string& source) const;
  597. const std::string& ExpandVariablesInString(
  598. std::string& source, bool escapeQuotes, bool noEscapes,
  599. bool atOnly = false, const char* filename = nullptr, long line = -1,
  600. bool removeEmpty = false, bool replaceAt = false) const;
  601. /**
  602. * Remove any remaining variables in the string. Anything with ${var} or
  603. * \@var\@ will be removed.
  604. */
  605. void RemoveVariablesInString(std::string& source, bool atOnly = false) const;
  606. /**
  607. * Replace variables and #cmakedefine lines in the given string.
  608. * See cmConfigureFileCommand for details.
  609. */
  610. void ConfigureString(const std::string& input, std::string& output,
  611. bool atOnly, bool escapeQuotes) const;
  612. /**
  613. * Copy file but change lines according to ConfigureString
  614. */
  615. int ConfigureFile(const std::string& infile, const std::string& outfile,
  616. bool copyonly, bool atOnly, bool escapeQuotes,
  617. mode_t permissions = 0, cmNewLineStyle = cmNewLineStyle());
  618. enum class CommandMissingFromStack
  619. {
  620. No,
  621. Yes,
  622. };
  623. /**
  624. * Print a command's invocation
  625. */
  626. void PrintCommandTrace(
  627. cmListFileFunction const& lff, cmListFileBacktrace const& bt,
  628. CommandMissingFromStack missing = CommandMissingFromStack::No) const;
  629. /**
  630. * Set a callback that is invoked whenever ExecuteCommand is called.
  631. */
  632. void OnExecuteCommand(std::function<void()> callback);
  633. /**
  634. * Execute a single CMake command. Returns true if the command
  635. * succeeded or false if it failed.
  636. */
  637. bool ExecuteCommand(const cmListFileFunction& lff, cmExecutionStatus& status,
  638. cm::optional<std::string> deferId = {});
  639. //! Enable support for named language, if nil then all languages are
  640. /// enabled.
  641. void EnableLanguage(std::vector<std::string> const& languages,
  642. bool optional);
  643. cmState* GetState() const;
  644. /**
  645. * Get the variable watch. This is used to determine when certain variables
  646. * are accessed.
  647. */
  648. #ifndef CMAKE_BOOTSTRAP
  649. cmVariableWatch* GetVariableWatch() const;
  650. #endif
  651. //! Display progress or status message.
  652. void DisplayStatus(const std::string&, float) const;
  653. /**
  654. * Expand the given list file arguments into the full set after
  655. * variable replacement and list expansion.
  656. */
  657. bool ExpandArguments(std::vector<cmListFileArgument> const& inArgs,
  658. std::vector<std::string>& outArgs) const;
  659. bool ExpandArguments(std::vector<cmListFileArgument> const& inArgs,
  660. std::vector<cmExpandedCommandArgument>& outArgs) const;
  661. /**
  662. * Get the instance
  663. */
  664. cmake* GetCMakeInstance() const;
  665. cmMessenger* GetMessenger() const;
  666. cmGlobalGenerator* GetGlobalGenerator() const;
  667. /**
  668. * Get all the source files this makefile knows about
  669. */
  670. const std::vector<std::unique_ptr<cmSourceFile>>& GetSourceFiles() const
  671. {
  672. return this->SourceFiles;
  673. }
  674. std::vector<cmTarget*> const& GetOrderedTargets() const
  675. {
  676. return this->OrderedTargets;
  677. }
  678. //! Add a new cmTest to the list of tests for this makefile.
  679. cmTest* CreateTest(const std::string& testName);
  680. /** Get a cmTest pointer for a given test name, if the name is
  681. * not found, then a null pointer is returned.
  682. */
  683. cmTest* GetTest(const std::string& testName) const;
  684. /**
  685. * Get all tests that run under the given configuration.
  686. */
  687. void GetTests(const std::string& config, std::vector<cmTest*>& tests) const;
  688. /**
  689. * Return a location of a file in cmake or custom modules directory
  690. */
  691. std::string GetModulesFile(cm::string_view name) const
  692. {
  693. bool system;
  694. std::string debugBuffer;
  695. return this->GetModulesFile(name, system, false, debugBuffer);
  696. }
  697. /**
  698. * Return a location of a file in cmake or custom modules directory
  699. */
  700. std::string GetModulesFile(cm::string_view name, bool& system) const
  701. {
  702. std::string debugBuffer;
  703. return this->GetModulesFile(name, system, false, debugBuffer);
  704. }
  705. std::string GetModulesFile(cm::string_view name, bool& system, bool debug,
  706. std::string& debugBuffer) const;
  707. //! Set/Get a property of this directory
  708. void SetProperty(const std::string& prop, cmValue value);
  709. void SetProperty(const std::string& prop, std::nullptr_t)
  710. {
  711. this->SetProperty(prop, cmValue{ nullptr });
  712. }
  713. void SetProperty(const std::string& prop, const std::string& value)
  714. {
  715. this->SetProperty(prop, cmValue(value));
  716. }
  717. void AppendProperty(const std::string& prop, const std::string& value,
  718. bool asString = false);
  719. cmValue GetProperty(const std::string& prop) const;
  720. cmValue GetProperty(const std::string& prop, bool chain) const;
  721. bool GetPropertyAsBool(const std::string& prop) const;
  722. std::vector<std::string> GetPropertyKeys() const;
  723. //! Initialize a makefile from its parent
  724. void InitializeFromParent(cmMakefile* parent);
  725. void AddInstallGenerator(std::unique_ptr<cmInstallGenerator> g);
  726. std::vector<std::unique_ptr<cmInstallGenerator>>& GetInstallGenerators()
  727. {
  728. return this->InstallGenerators;
  729. }
  730. const std::vector<std::unique_ptr<cmInstallGenerator>>&
  731. GetInstallGenerators() const
  732. {
  733. return this->InstallGenerators;
  734. }
  735. void AddTestGenerator(std::unique_ptr<cmTestGenerator> g);
  736. const std::vector<std::unique_ptr<cmTestGenerator>>& GetTestGenerators()
  737. const
  738. {
  739. return this->TestGenerators;
  740. }
  741. class FunctionPushPop
  742. {
  743. public:
  744. FunctionPushPop(cmMakefile* mf, std::string const& fileName,
  745. cmPolicies::PolicyMap const& pm);
  746. ~FunctionPushPop();
  747. FunctionPushPop(const FunctionPushPop&) = delete;
  748. FunctionPushPop& operator=(const FunctionPushPop&) = delete;
  749. void Quiet() { this->ReportError = false; }
  750. private:
  751. cmMakefile* Makefile;
  752. bool ReportError = true;
  753. };
  754. class MacroPushPop
  755. {
  756. public:
  757. MacroPushPop(cmMakefile* mf, std::string const& fileName,
  758. cmPolicies::PolicyMap const& pm);
  759. ~MacroPushPop();
  760. MacroPushPop(const MacroPushPop&) = delete;
  761. MacroPushPop& operator=(const MacroPushPop&) = delete;
  762. void Quiet() { this->ReportError = false; }
  763. private:
  764. cmMakefile* Makefile;
  765. bool ReportError = true;
  766. };
  767. void PushFunctionScope(std::string const& fileName,
  768. cmPolicies::PolicyMap const& pm);
  769. void PopFunctionScope(bool reportError);
  770. void PushMacroScope(std::string const& fileName,
  771. cmPolicies::PolicyMap const& pm);
  772. void PopMacroScope(bool reportError);
  773. void PushScope();
  774. void PopScope();
  775. void RaiseScope(const std::string& var, const char* value);
  776. void RaiseScope(const std::string& var, cmValue value)
  777. {
  778. this->RaiseScope(var, value.GetCStr());
  779. }
  780. void RaiseScope(const std::vector<std::string>& variables);
  781. // push and pop loop scopes
  782. void PushLoopBlockBarrier();
  783. void PopLoopBlockBarrier();
  784. bool IsImportedTargetGlobalScope() const;
  785. enum class ImportedTargetScope
  786. {
  787. Local,
  788. Global,
  789. };
  790. /** Helper class to manage whether imported packages
  791. * should be globally scoped based off the find package command
  792. */
  793. class SetGlobalTargetImportScope
  794. {
  795. public:
  796. SetGlobalTargetImportScope(cmMakefile* mk, ImportedTargetScope const scope)
  797. : Makefile(mk)
  798. {
  799. if (scope == ImportedTargetScope::Global &&
  800. !this->Makefile->IsImportedTargetGlobalScope()) {
  801. this->Makefile->CurrentImportedTargetScope = scope;
  802. this->Set = true;
  803. } else {
  804. this->Set = false;
  805. }
  806. }
  807. ~SetGlobalTargetImportScope()
  808. {
  809. if (this->Set) {
  810. this->Makefile->CurrentImportedTargetScope =
  811. ImportedTargetScope::Local;
  812. }
  813. }
  814. private:
  815. cmMakefile* Makefile;
  816. bool Set;
  817. };
  818. /** Helper class to push and pop scopes automatically. */
  819. class ScopePushPop
  820. {
  821. public:
  822. ScopePushPop(cmMakefile* m)
  823. : Makefile(m)
  824. {
  825. this->Makefile->PushScope();
  826. }
  827. ~ScopePushPop() { this->Makefile->PopScope(); }
  828. ScopePushPop(ScopePushPop const&) = delete;
  829. ScopePushPop& operator=(ScopePushPop const&) = delete;
  830. private:
  831. cmMakefile* Makefile;
  832. };
  833. void IssueMessage(MessageType t, std::string const& text) const;
  834. Message::LogLevel GetCurrentLogLevel() const;
  835. /** Set whether or not to report a CMP0000 violation. */
  836. void SetCheckCMP0000(bool b) { this->CheckCMP0000 = b; }
  837. void IssueInvalidTargetNameError(std::string const& targetName) const;
  838. cmBTStringRange GetIncludeDirectoriesEntries() const;
  839. cmBTStringRange GetCompileOptionsEntries() const;
  840. cmBTStringRange GetCompileDefinitionsEntries() const;
  841. cmBTStringRange GetLinkOptionsEntries() const;
  842. cmBTStringRange GetLinkDirectoriesEntries() const;
  843. std::set<std::string> const& GetSystemIncludeDirectories() const
  844. {
  845. return this->SystemIncludeDirectories;
  846. }
  847. bool PolicyOptionalWarningEnabled(std::string const& var) const;
  848. void PushLoopBlock();
  849. void PopLoopBlock();
  850. bool IsLoopBlock() const;
  851. void ClearMatches();
  852. void StoreMatches(cmsys::RegularExpression& re);
  853. cmStateSnapshot GetStateSnapshot() const;
  854. const char* GetDefineFlagsCMP0059() const;
  855. void EnforceDirectoryLevelRules() const;
  856. void AddEvaluationFile(
  857. const std::string& inputFile, const std::string& targetName,
  858. std::unique_ptr<cmCompiledGeneratorExpression> outputName,
  859. std::unique_ptr<cmCompiledGeneratorExpression> condition,
  860. const std::string& newLineCharacter, mode_t permissions,
  861. bool inputIsContent);
  862. const std::vector<std::unique_ptr<cmGeneratorExpressionEvaluationFile>>&
  863. GetEvaluationFiles() const;
  864. std::vector<std::unique_ptr<cmExportBuildFileGenerator>> const&
  865. GetExportBuildFileGenerators() const;
  866. void AddExportBuildFileGenerator(
  867. std::unique_ptr<cmExportBuildFileGenerator> gen);
  868. // Maintain a stack of package roots to allow nested PACKAGE_ROOT_PATH
  869. // searches
  870. std::deque<std::vector<std::string>> FindPackageRootPathStack;
  871. class FindPackageStackRAII
  872. {
  873. cmMakefile* Makefile;
  874. public:
  875. FindPackageStackRAII(cmMakefile* mf, std::string const& pkg);
  876. ~FindPackageStackRAII();
  877. FindPackageStackRAII(FindPackageStackRAII const&) = delete;
  878. FindPackageStackRAII& operator=(FindPackageStackRAII const&) = delete;
  879. };
  880. class DebugFindPkgRAII
  881. {
  882. cmMakefile* Makefile;
  883. bool OldValue;
  884. public:
  885. DebugFindPkgRAII(cmMakefile* mf, std::string const& pkg);
  886. ~DebugFindPkgRAII();
  887. DebugFindPkgRAII(DebugFindPkgRAII const&) = delete;
  888. DebugFindPkgRAII& operator=(DebugFindPkgRAII const&) = delete;
  889. };
  890. class CallRAII
  891. {
  892. public:
  893. CallRAII(cmMakefile* mf, std::string const& file,
  894. cmExecutionStatus& status);
  895. ~CallRAII();
  896. CallRAII(CallRAII const&) = delete;
  897. CallRAII& operator=(CallRAII const&) = delete;
  898. protected:
  899. CallRAII(cmMakefile* mf, cmListFileContext const& lfc,
  900. cmExecutionStatus& status);
  901. cmMakefile* Detach();
  902. cmMakefile* Makefile;
  903. };
  904. bool GetDebugFindPkgMode() const;
  905. void MaybeWarnCMP0074(std::string const& rootVar, cmValue rootDef,
  906. cm::optional<std::string> const& rootEnv);
  907. void MaybeWarnCMP0144(std::string const& rootVAR, cmValue rootDEF,
  908. cm::optional<std::string> const& rootENV);
  909. void MaybeWarnUninitialized(std::string const& variable,
  910. const char* sourceFilename) const;
  911. bool IsProjectFile(const char* filename) const;
  912. size_t GetRecursionDepthLimit() const;
  913. size_t GetRecursionDepth() const;
  914. void SetRecursionDepth(size_t recursionDepth);
  915. std::string NewDeferId() const;
  916. bool DeferCall(std::string id, std::string fileName, cmListFileFunction lff);
  917. bool DeferCancelCall(std::string const& id);
  918. cm::optional<std::string> DeferGetCallIds() const;
  919. cm::optional<std::string> DeferGetCall(std::string const& id) const;
  920. protected:
  921. // add link libraries and directories to the target
  922. void AddGlobalLinkInformation(cmTarget& target);
  923. mutable std::set<cmListFileContext> CMP0054ReportedIds;
  924. // libraries, classes, and executables
  925. mutable cmTargetMap Targets;
  926. std::map<std::string, std::string> AliasTargets;
  927. std::vector<cmTarget*> OrderedTargets;
  928. std::vector<std::unique_ptr<cmSourceFile>> SourceFiles;
  929. // Because cmSourceFile names are compared in a fuzzy way (see
  930. // cmSourceFileLocation::Match()) we can't have a straight mapping from
  931. // filename to cmSourceFile. To make lookups more efficient we store the
  932. // Name portion of the cmSourceFileLocation and then compare on the list of
  933. // cmSourceFiles that might match that name. Note that on platforms which
  934. // have a case-insensitive filesystem we store the key in all lowercase.
  935. using SourceFileMap =
  936. std::unordered_map<std::string, std::vector<cmSourceFile*>>;
  937. SourceFileMap SourceFileSearchIndex;
  938. // For "Known" paths we can store a direct filename to cmSourceFile map
  939. std::unordered_map<std::string, cmSourceFile*> KnownFileSearchIndex;
  940. // Tests
  941. std::map<std::string, std::unique_ptr<cmTest>> Tests;
  942. // The set of include directories that are marked as system include
  943. // directories.
  944. std::set<std::string> SystemIncludeDirectories;
  945. std::vector<std::string> ListFiles;
  946. std::vector<std::string> OutputFiles;
  947. std::vector<std::unique_ptr<cmInstallGenerator>> InstallGenerators;
  948. std::vector<std::unique_ptr<cmTestGenerator>> TestGenerators;
  949. std::string ComplainFileRegularExpression;
  950. std::string DefineFlags;
  951. // Track the value of the computed DEFINITIONS property.
  952. std::string DefineFlagsOrig;
  953. #if !defined(CMAKE_BOOTSTRAP)
  954. std::vector<cmSourceGroup> SourceGroups;
  955. size_t ObjectLibrariesSourceGroupIndex;
  956. #endif
  957. cmGlobalGenerator* GlobalGenerator;
  958. bool IsFunctionBlocked(const cmListFileFunction& lff,
  959. cmExecutionStatus& status);
  960. private:
  961. cmStateSnapshot StateSnapshot;
  962. cmListFileBacktrace Backtrace;
  963. size_t RecursionDepth = 0;
  964. struct DeferCommand
  965. {
  966. // Id is empty for an already-executed or canceled operation.
  967. std::string Id;
  968. std::string FilePath;
  969. cmListFileFunction Command;
  970. };
  971. struct DeferCommands
  972. {
  973. std::vector<DeferCommand> Commands;
  974. };
  975. std::unique_ptr<DeferCommands> Defer;
  976. bool DeferRunning = false;
  977. void DoGenerate(cmLocalGenerator& lg);
  978. void RunListFile(cmListFile const& listFile,
  979. const std::string& filenametoread,
  980. DeferCommands* defer = nullptr);
  981. bool ParseDefineFlag(std::string const& definition, bool remove);
  982. bool EnforceUniqueDir(const std::string& srcPath,
  983. const std::string& binPath) const;
  984. std::function<void()> ExecuteCommandCallback;
  985. using FunctionBlockerPtr = std::unique_ptr<cmFunctionBlocker>;
  986. using FunctionBlockersType =
  987. std::stack<FunctionBlockerPtr, std::vector<FunctionBlockerPtr>>;
  988. FunctionBlockersType FunctionBlockers;
  989. std::vector<FunctionBlockersType::size_type> FunctionBlockerBarriers;
  990. void PushFunctionBlockerBarrier();
  991. void PopFunctionBlockerBarrier(bool reportError = true);
  992. std::stack<int> LoopBlockCounter;
  993. mutable cmsys::RegularExpression cmDefineRegex;
  994. mutable cmsys::RegularExpression cmDefine01Regex;
  995. mutable cmsys::RegularExpression cmAtVarRegex;
  996. mutable cmsys::RegularExpression cmNamedCurly;
  997. std::vector<cmMakefile*> UnConfiguredDirectories;
  998. std::vector<std::unique_ptr<cmExportBuildFileGenerator>>
  999. ExportBuildFileGenerators;
  1000. std::vector<std::unique_ptr<cmGeneratorExpressionEvaluationFile>>
  1001. EvaluationFiles;
  1002. class CallScope;
  1003. friend class CallScope;
  1004. std::vector<cmExecutionStatus*> ExecutionStatusStack;
  1005. friend class cmParseFileScope;
  1006. std::vector<std::unique_ptr<cmTarget>> ImportedTargetsOwned;
  1007. using TargetMap = std::unordered_map<std::string, cmTarget*>;
  1008. TargetMap ImportedTargets;
  1009. // Internal policy stack management.
  1010. void PushPolicy(bool weak = false,
  1011. cmPolicies::PolicyMap const& pm = cmPolicies::PolicyMap());
  1012. void PopPolicy();
  1013. void PopSnapshot(bool reportError = true);
  1014. friend bool cmCMakePolicyCommand(std::vector<std::string> const& args,
  1015. cmExecutionStatus& status);
  1016. class IncludeScope;
  1017. friend class IncludeScope;
  1018. class ListFileScope;
  1019. friend class ListFileScope;
  1020. class DeferScope;
  1021. friend class DeferScope;
  1022. class DeferCallScope;
  1023. friend class DeferCallScope;
  1024. class BuildsystemFileScope;
  1025. friend class BuildsystemFileScope;
  1026. // CMP0053 == old
  1027. MessageType ExpandVariablesInStringOld(std::string& errorstr,
  1028. std::string& source,
  1029. bool escapeQuotes, bool noEscapes,
  1030. bool atOnly, const char* filename,
  1031. long line, bool removeEmpty,
  1032. bool replaceAt) const;
  1033. // CMP0053 == new
  1034. MessageType ExpandVariablesInStringNew(std::string& errorstr,
  1035. std::string& source,
  1036. bool escapeQuotes, bool noEscapes,
  1037. bool atOnly, const char* filename,
  1038. long line, bool replaceAt) const;
  1039. bool ValidateCustomCommand(const cmCustomCommandLines& commandLines) const;
  1040. void CreateGeneratedOutputs(const std::vector<std::string>& outputs);
  1041. std::vector<BT<GeneratorAction>> GeneratorActions;
  1042. bool GeneratorActionsInvoked = false;
  1043. cmFindPackageStack FindPackageStack;
  1044. unsigned int FindPackageStackNextIndex = 0;
  1045. bool DebugFindPkg = false;
  1046. bool CheckSystemVars;
  1047. bool CheckCMP0000;
  1048. std::set<std::string> WarnedCMP0074;
  1049. std::set<std::string> WarnedCMP0144;
  1050. bool IsSourceFileTryCompile;
  1051. mutable bool SuppressSideEffects;
  1052. ImportedTargetScope CurrentImportedTargetScope = ImportedTargetScope::Local;
  1053. };