cmMakefile.h 38 KB

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