cmMakefile.h 38 KB

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