cmMakefile.h 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  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. friend class cmFindPackageStackRAII;
  866. class DebugFindPkgRAII
  867. {
  868. cmMakefile* Makefile;
  869. bool OldValue;
  870. public:
  871. DebugFindPkgRAII(cmMakefile* mf, std::string const& pkg);
  872. ~DebugFindPkgRAII();
  873. DebugFindPkgRAII(DebugFindPkgRAII const&) = delete;
  874. DebugFindPkgRAII& operator=(DebugFindPkgRAII const&) = delete;
  875. };
  876. class CallRAII
  877. {
  878. public:
  879. CallRAII(cmMakefile* mf, std::string const& file,
  880. cmExecutionStatus& status);
  881. ~CallRAII();
  882. CallRAII(CallRAII const&) = delete;
  883. CallRAII& operator=(CallRAII const&) = delete;
  884. protected:
  885. CallRAII(cmMakefile* mf, cmListFileContext const& lfc,
  886. cmExecutionStatus& status);
  887. cmMakefile* Detach();
  888. cmMakefile* Makefile;
  889. };
  890. bool GetDebugFindPkgMode() const;
  891. void MaybeWarnCMP0074(std::string const& rootVar, cmValue rootDef,
  892. cm::optional<std::string> const& rootEnv);
  893. void MaybeWarnCMP0144(std::string const& rootVAR, cmValue rootDEF,
  894. cm::optional<std::string> const& rootENV);
  895. void MaybeWarnUninitialized(std::string const& variable,
  896. char const* sourceFilename) const;
  897. bool IsProjectFile(char const* filename) const;
  898. size_t GetRecursionDepthLimit() const;
  899. size_t GetRecursionDepth() const;
  900. void SetRecursionDepth(size_t recursionDepth);
  901. std::string NewDeferId() const;
  902. bool DeferCall(std::string id, std::string fileName, cmListFileFunction lff);
  903. bool DeferCancelCall(std::string const& id);
  904. cm::optional<std::string> DeferGetCallIds() const;
  905. cm::optional<std::string> DeferGetCall(std::string const& id) const;
  906. protected:
  907. // add link libraries and directories to the target
  908. void AddGlobalLinkInformation(cmTarget& target);
  909. // libraries, classes, and executables
  910. mutable cmTargetMap Targets;
  911. std::map<std::string, std::string> AliasTargets;
  912. std::vector<cmTarget*> OrderedTargets;
  913. std::vector<std::unique_ptr<cmSourceFile>> SourceFiles;
  914. // Because cmSourceFile names are compared in a fuzzy way (see
  915. // cmSourceFileLocation::Match()) we can't have a straight mapping from
  916. // filename to cmSourceFile. To make lookups more efficient we store the
  917. // Name portion of the cmSourceFileLocation and then compare on the list of
  918. // cmSourceFiles that might match that name. Note that on platforms which
  919. // have a case-insensitive filesystem we store the key in all lowercase.
  920. using SourceFileMap =
  921. std::unordered_map<std::string, std::vector<cmSourceFile*>>;
  922. SourceFileMap SourceFileSearchIndex;
  923. // For "Known" paths we can store a direct filename to cmSourceFile map
  924. std::unordered_map<std::string, cmSourceFile*> KnownFileSearchIndex;
  925. // Tests
  926. std::map<std::string, std::unique_ptr<cmTest>> Tests;
  927. // The set of include directories that are marked as system include
  928. // directories.
  929. std::set<std::string> SystemIncludeDirectories;
  930. std::vector<std::string> ListFiles;
  931. std::vector<std::string> OutputFiles;
  932. std::vector<std::unique_ptr<cmInstallGenerator>> InstallGenerators;
  933. std::vector<std::unique_ptr<cmTestGenerator>> TestGenerators;
  934. std::string ComplainFileRegularExpression;
  935. std::string DefineFlags;
  936. #if !defined(CMAKE_BOOTSTRAP)
  937. std::vector<cmSourceGroup> SourceGroups;
  938. size_t ObjectLibrariesSourceGroupIndex;
  939. #endif
  940. cmGlobalGenerator* GlobalGenerator;
  941. bool IsFunctionBlocked(cmListFileFunction const& lff,
  942. cmExecutionStatus& status);
  943. private:
  944. cmStateSnapshot StateSnapshot;
  945. cmListFileBacktrace Backtrace;
  946. size_t RecursionDepth = 0;
  947. struct DeferCommand
  948. {
  949. // Id is empty for an already-executed or canceled operation.
  950. std::string Id;
  951. std::string FilePath;
  952. cmListFileFunction Command;
  953. };
  954. struct DeferCommands
  955. {
  956. std::vector<DeferCommand> Commands;
  957. };
  958. std::unique_ptr<DeferCommands> Defer;
  959. bool DeferRunning = false;
  960. void DoGenerate(cmLocalGenerator& lg);
  961. void RunListFile(cmListFile const& listFile,
  962. std::string const& filenametoread,
  963. DeferCommands* defer = nullptr);
  964. bool ParseDefineFlag(std::string const& definition, bool remove);
  965. bool EnforceUniqueDir(std::string const& srcPath,
  966. std::string const& binPath) const;
  967. std::function<void()> ExecuteCommandCallback;
  968. using FunctionBlockerPtr = std::unique_ptr<cmFunctionBlocker>;
  969. using FunctionBlockersType =
  970. std::stack<FunctionBlockerPtr, std::vector<FunctionBlockerPtr>>;
  971. FunctionBlockersType FunctionBlockers;
  972. std::vector<FunctionBlockersType::size_type> FunctionBlockerBarriers;
  973. void PushFunctionBlockerBarrier();
  974. void PopFunctionBlockerBarrier(bool reportError = true);
  975. std::stack<int> LoopBlockCounter;
  976. mutable cmsys::RegularExpression cmDefineRegex;
  977. mutable cmsys::RegularExpression cmDefine01Regex;
  978. mutable cmsys::RegularExpression cmNamedCurly;
  979. std::vector<cmMakefile*> UnConfiguredDirectories;
  980. std::vector<std::unique_ptr<cmExportBuildFileGenerator>>
  981. ExportBuildFileGenerators;
  982. std::vector<std::unique_ptr<cmGeneratorExpressionEvaluationFile>>
  983. EvaluationFiles;
  984. class CallScope;
  985. friend class CallScope;
  986. std::vector<cmExecutionStatus*> ExecutionStatusStack;
  987. friend class cmParseFileScope;
  988. std::vector<std::unique_ptr<cmTarget>> ImportedTargetsOwned;
  989. using TargetMap = std::unordered_map<std::string, cmTarget*>;
  990. TargetMap ImportedTargets;
  991. // Internal policy stack management.
  992. void PushPolicy(bool weak = false,
  993. cmPolicies::PolicyMap const& pm = cmPolicies::PolicyMap());
  994. void PopPolicy();
  995. void PopSnapshot(bool reportError = true);
  996. friend bool cmCMakePolicyCommand(std::vector<std::string> const& args,
  997. cmExecutionStatus& status);
  998. class IncludeScope;
  999. friend class IncludeScope;
  1000. class ListFileScope;
  1001. friend class ListFileScope;
  1002. class DeferScope;
  1003. friend class DeferScope;
  1004. class DeferCallScope;
  1005. friend class DeferCallScope;
  1006. class BuildsystemFileScope;
  1007. friend class BuildsystemFileScope;
  1008. MessageType ExpandVariablesInStringImpl(std::string& errorstr,
  1009. std::string& source,
  1010. bool escapeQuotes, bool noEscapes,
  1011. bool atOnly, char const* filename,
  1012. long line, bool replaceAt) const;
  1013. bool ValidateCustomCommand(cmCustomCommandLines const& commandLines) const;
  1014. void CreateGeneratedOutputs(std::vector<std::string> const& outputs);
  1015. std::vector<BT<GeneratorAction>> GeneratorActions;
  1016. bool GeneratorActionsInvoked = false;
  1017. cmFindPackageStack FindPackageStack;
  1018. unsigned int FindPackageStackNextIndex = 0;
  1019. bool DebugFindPkg = false;
  1020. bool CheckSystemVars;
  1021. bool CheckCMP0000;
  1022. std::set<std::string> WarnedCMP0074;
  1023. std::set<std::string> WarnedCMP0144;
  1024. bool IsSourceFileTryCompile;
  1025. ImportedTargetScope CurrentImportedTargetScope = ImportedTargetScope::Local;
  1026. };