cmProjectCommand.cxx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst or https://cmake.org/licensing for details. */
  3. #include "cmProjectCommand.h"
  4. #include <array>
  5. #include <cstdio>
  6. #include <limits>
  7. #include <set>
  8. #include <utility>
  9. #include <cm/optional>
  10. #include <cm/string_view>
  11. #include <cmext/string_view>
  12. #include "cmsys/RegularExpression.hxx"
  13. #include "cmArgumentParser.h"
  14. #include "cmArgumentParserTypes.h"
  15. #include "cmExecutionStatus.h"
  16. #include "cmExperimental.h"
  17. #include "cmList.h"
  18. #include "cmMakefile.h"
  19. #include "cmMessageType.h"
  20. #include "cmPolicies.h"
  21. #include "cmRange.h"
  22. #include "cmStateTypes.h"
  23. #include "cmStringAlgorithms.h"
  24. #include "cmSystemTools.h"
  25. #include "cmValue.h"
  26. namespace {
  27. bool IncludeByVariable(cmExecutionStatus& status, std::string const& variable);
  28. void TopLevelCMakeVarCondSet(cmMakefile& mf, std::string const& name,
  29. std::string const& value);
  30. struct ProjectArguments : ArgumentParser::ParseResult
  31. {
  32. cm::optional<std::string> Version;
  33. cm::optional<std::string> CompatVersion;
  34. cm::optional<std::string> Description;
  35. cm::optional<std::string> HomepageURL;
  36. cm::optional<ArgumentParser::MaybeEmpty<std::vector<std::string>>> Languages;
  37. };
  38. struct ProjectArgumentParser : public cmArgumentParser<void>
  39. {
  40. ProjectArgumentParser& BindKeywordMissingValue(
  41. std::vector<cm::string_view>& ref)
  42. {
  43. this->cmArgumentParser<void>::BindKeywordMissingValue(
  44. [&ref](Instance&, cm::string_view arg) { ref.emplace_back(arg); });
  45. return *this;
  46. }
  47. };
  48. } // namespace
  49. bool cmProjectCommand(std::vector<std::string> const& args,
  50. cmExecutionStatus& status)
  51. {
  52. std::vector<std::string> unparsedArgs;
  53. std::vector<cm::string_view> missingValueKeywords;
  54. std::vector<cm::string_view> parsedKeywords;
  55. ProjectArguments prArgs;
  56. ProjectArgumentParser parser;
  57. parser.BindKeywordMissingValue(missingValueKeywords)
  58. .BindParsedKeywords(parsedKeywords)
  59. .Bind("VERSION"_s, prArgs.Version)
  60. .Bind("DESCRIPTION"_s, prArgs.Description)
  61. .Bind("HOMEPAGE_URL"_s, prArgs.HomepageURL)
  62. .Bind("LANGUAGES"_s, prArgs.Languages);
  63. cmMakefile& mf = status.GetMakefile();
  64. bool enableCompatVersion = cmExperimental::HasSupportEnabled(
  65. mf, cmExperimental::Feature::ExportPackageInfo);
  66. if (enableCompatVersion) {
  67. parser.Bind("COMPAT_VERSION"_s, prArgs.CompatVersion);
  68. }
  69. if (args.empty()) {
  70. status.SetError("PROJECT called with incorrect number of arguments");
  71. return false;
  72. }
  73. std::string const& projectName = args[0];
  74. if (parser.HasKeyword(projectName)) {
  75. mf.IssueMessage(
  76. MessageType::AUTHOR_WARNING,
  77. cmStrCat(
  78. "project() called with '", projectName,
  79. "' as first argument. The first parameter should be the project name, "
  80. "not a keyword argument. See the cmake-commands(7) manual for correct "
  81. "usage of the project() command."));
  82. }
  83. parser.Parse(cmMakeRange(args).advance(1), &unparsedArgs, 1);
  84. if (mf.IsRootMakefile() &&
  85. !mf.GetDefinition("CMAKE_MINIMUM_REQUIRED_VERSION")) {
  86. mf.IssueMessage(
  87. MessageType::AUTHOR_WARNING,
  88. "cmake_minimum_required() should be called prior to this top-level "
  89. "project() call. Please see the cmake-commands(7) manual for usage "
  90. "documentation of both commands.");
  91. }
  92. if (!IncludeByVariable(status, "CMAKE_PROJECT_INCLUDE_BEFORE")) {
  93. return false;
  94. }
  95. if (!IncludeByVariable(status,
  96. "CMAKE_PROJECT_" + projectName + "_INCLUDE_BEFORE")) {
  97. return false;
  98. }
  99. mf.SetProjectName(projectName);
  100. cmPolicies::PolicyStatus cmp0180 = mf.GetPolicyStatus(cmPolicies::CMP0180);
  101. std::string varName = cmStrCat(projectName, "_BINARY_DIR"_s);
  102. bool nonCacheVarAlreadySet = mf.IsNormalDefinitionSet(varName);
  103. mf.AddCacheDefinition(varName, mf.GetCurrentBinaryDirectory(),
  104. "Value Computed by CMake", cmStateEnums::STATIC);
  105. if (cmp0180 == cmPolicies::NEW || nonCacheVarAlreadySet) {
  106. mf.AddDefinition(varName, mf.GetCurrentBinaryDirectory());
  107. }
  108. varName = cmStrCat(projectName, "_SOURCE_DIR"_s);
  109. nonCacheVarAlreadySet = mf.IsNormalDefinitionSet(varName);
  110. mf.AddCacheDefinition(varName, mf.GetCurrentSourceDirectory(),
  111. "Value Computed by CMake", cmStateEnums::STATIC);
  112. if (cmp0180 == cmPolicies::NEW || nonCacheVarAlreadySet) {
  113. mf.AddDefinition(varName, mf.GetCurrentSourceDirectory());
  114. }
  115. mf.AddDefinition("PROJECT_BINARY_DIR", mf.GetCurrentBinaryDirectory());
  116. mf.AddDefinition("PROJECT_SOURCE_DIR", mf.GetCurrentSourceDirectory());
  117. mf.AddDefinition("PROJECT_NAME", projectName);
  118. mf.AddDefinitionBool("PROJECT_IS_TOP_LEVEL", mf.IsRootMakefile());
  119. varName = cmStrCat(projectName, "_IS_TOP_LEVEL"_s);
  120. nonCacheVarAlreadySet = mf.IsNormalDefinitionSet(varName);
  121. mf.AddCacheDefinition(varName, mf.IsRootMakefile() ? "ON" : "OFF",
  122. "Value Computed by CMake", cmStateEnums::STATIC);
  123. if (cmp0180 == cmPolicies::NEW || nonCacheVarAlreadySet) {
  124. mf.AddDefinition(varName, mf.IsRootMakefile() ? "ON" : "OFF");
  125. }
  126. TopLevelCMakeVarCondSet(mf, "CMAKE_PROJECT_NAME", projectName);
  127. std::set<cm::string_view> seenKeywords;
  128. for (cm::string_view keyword : parsedKeywords) {
  129. if (seenKeywords.find(keyword) != seenKeywords.end()) {
  130. mf.IssueMessage(MessageType::FATAL_ERROR,
  131. cmStrCat(keyword, " may be specified at most once."));
  132. cmSystemTools::SetFatalErrorOccurred();
  133. return true;
  134. }
  135. seenKeywords.insert(keyword);
  136. }
  137. for (cm::string_view keyword : missingValueKeywords) {
  138. mf.IssueMessage(MessageType::WARNING,
  139. cmStrCat(keyword,
  140. " keyword not followed by a value or was "
  141. "followed by a value that expanded to nothing."));
  142. }
  143. if (!unparsedArgs.empty()) {
  144. if (prArgs.Languages) {
  145. mf.IssueMessage(
  146. MessageType::WARNING,
  147. cmStrCat("the following parameters must be specified after LANGUAGES "
  148. "keyword: ",
  149. cmJoin(unparsedArgs, ", "), '.'));
  150. } else if (prArgs.Version || prArgs.Description || prArgs.HomepageURL) {
  151. mf.IssueMessage(MessageType::FATAL_ERROR,
  152. "project with VERSION, DESCRIPTION or HOMEPAGE_URL must "
  153. "use LANGUAGES before language names.");
  154. cmSystemTools::SetFatalErrorOccurred();
  155. return true;
  156. }
  157. } else if (prArgs.Languages && prArgs.Languages->empty()) {
  158. prArgs.Languages->emplace_back("NONE");
  159. }
  160. if (prArgs.CompatVersion && !prArgs.Version) {
  161. mf.IssueMessage(MessageType::FATAL_ERROR,
  162. "project with COMPAT_VERSION must also provide VERSION.");
  163. cmSystemTools::SetFatalErrorOccurred();
  164. return true;
  165. }
  166. cmsys::RegularExpression vx(
  167. R"(^([0-9]+(\.[0-9]+(\.[0-9]+(\.[0-9]+)?)?)?)?$)");
  168. constexpr std::size_t MAX_VERSION_COMPONENTS = 4u;
  169. std::string version_string;
  170. std::array<std::string, MAX_VERSION_COMPONENTS> version_components;
  171. bool has_version = prArgs.Version.has_value();
  172. if (prArgs.Version) {
  173. if (!vx.find(*prArgs.Version)) {
  174. std::string e =
  175. R"(VERSION ")" + *prArgs.Version + R"(" format invalid.)";
  176. mf.IssueMessage(MessageType::FATAL_ERROR, e);
  177. cmSystemTools::SetFatalErrorOccurred();
  178. return true;
  179. }
  180. cmPolicies::PolicyStatus const cmp0096 =
  181. mf.GetPolicyStatus(cmPolicies::CMP0096);
  182. if (cmp0096 == cmPolicies::OLD || cmp0096 == cmPolicies::WARN) {
  183. constexpr size_t maxIntLength =
  184. std::numeric_limits<unsigned>::digits10 + 2;
  185. char vb[MAX_VERSION_COMPONENTS][maxIntLength];
  186. unsigned v[MAX_VERSION_COMPONENTS] = { 0, 0, 0, 0 };
  187. int const vc = std::sscanf(prArgs.Version->c_str(), "%u.%u.%u.%u", &v[0],
  188. &v[1], &v[2], &v[3]);
  189. for (auto i = 0u; i < MAX_VERSION_COMPONENTS; ++i) {
  190. if (static_cast<int>(i) < vc) {
  191. std::snprintf(vb[i], maxIntLength, "%u", v[i]);
  192. version_string += &"."[static_cast<std::size_t>(i == 0)];
  193. version_string += vb[i];
  194. version_components[i] = vb[i];
  195. } else {
  196. vb[i][0] = '\x00';
  197. }
  198. }
  199. } else {
  200. // The regex above verified that we have a .-separated string of
  201. // non-negative integer components. Keep the original string.
  202. version_string = std::move(*prArgs.Version);
  203. // Split the integer components.
  204. auto components = cmSystemTools::SplitString(version_string, '.');
  205. for (auto i = 0u; i < components.size(); ++i) {
  206. version_components[i] = std::move(components[i]);
  207. }
  208. }
  209. }
  210. if (prArgs.CompatVersion) {
  211. if (!vx.find(*prArgs.CompatVersion)) {
  212. std::string e =
  213. R"(COMPAT_VERSION ")" + *prArgs.CompatVersion + R"(" format invalid.)";
  214. mf.IssueMessage(MessageType::FATAL_ERROR, e);
  215. cmSystemTools::SetFatalErrorOccurred();
  216. return true;
  217. }
  218. if (cmSystemTools::VersionCompareGreater(*prArgs.CompatVersion,
  219. version_string)) {
  220. mf.IssueMessage(MessageType::FATAL_ERROR,
  221. "COMPAT_VERSION must be less than or equal to VERSION");
  222. cmSystemTools::SetFatalErrorOccurred();
  223. return true;
  224. }
  225. }
  226. auto createVariables = [&](cm::string_view var, std::string const& val) {
  227. mf.AddDefinition(cmStrCat("PROJECT_"_s, var), val);
  228. mf.AddDefinition(cmStrCat(projectName, "_"_s, var), val);
  229. TopLevelCMakeVarCondSet(mf, cmStrCat("CMAKE_PROJECT_"_s, var), val);
  230. };
  231. // Note, this intentionally doesn't touch cache variables as the legacy
  232. // behavior did not modify cache
  233. auto checkAndClearVariables = [&](cm::string_view var) {
  234. std::vector<std::string> vv = { "PROJECT_", cmStrCat(projectName, "_") };
  235. if (mf.IsRootMakefile()) {
  236. vv.push_back("CMAKE_PROJECT_");
  237. }
  238. for (std::string const& prefix : vv) {
  239. std::string def = cmStrCat(prefix, var);
  240. if (!mf.GetDefinition(def).IsEmpty()) {
  241. mf.AddDefinition(def, "");
  242. }
  243. }
  244. };
  245. // TODO: We should treat VERSION the same as all other project variables, but
  246. // setting it to empty string unconditionally causes various behavior
  247. // changes. It needs a policy. For now, maintain the old behavior and add a
  248. // policy in a future release.
  249. if (has_version) {
  250. createVariables("VERSION"_s, version_string);
  251. createVariables("VERSION_MAJOR"_s, version_components[0]);
  252. createVariables("VERSION_MINOR"_s, version_components[1]);
  253. createVariables("VERSION_PATCH"_s, version_components[2]);
  254. createVariables("VERSION_TWEAK"_s, version_components[3]);
  255. } else {
  256. checkAndClearVariables("VERSION"_s);
  257. checkAndClearVariables("VERSION_MAJOR"_s);
  258. checkAndClearVariables("VERSION_MINOR"_s);
  259. checkAndClearVariables("VERSION_PATCH"_s);
  260. checkAndClearVariables("VERSION_TWEAK"_s);
  261. }
  262. createVariables("COMPAT_VERSION"_s, prArgs.CompatVersion.value_or(""));
  263. createVariables("DESCRIPTION"_s, prArgs.Description.value_or(""));
  264. createVariables("HOMEPAGE_URL"_s, prArgs.HomepageURL.value_or(""));
  265. if (unparsedArgs.empty() && !prArgs.Languages) {
  266. // if no language is specified do c and c++
  267. mf.EnableLanguage({ "C", "CXX" }, false);
  268. } else {
  269. if (!unparsedArgs.empty()) {
  270. mf.EnableLanguage(unparsedArgs, false);
  271. }
  272. if (prArgs.Languages) {
  273. mf.EnableLanguage(*prArgs.Languages, false);
  274. }
  275. }
  276. if (!IncludeByVariable(status, "CMAKE_PROJECT_INCLUDE")) {
  277. return false;
  278. }
  279. if (!IncludeByVariable(status,
  280. "CMAKE_PROJECT_" + projectName + "_INCLUDE")) {
  281. return false;
  282. }
  283. return true;
  284. }
  285. namespace {
  286. bool IncludeByVariable(cmExecutionStatus& status, std::string const& variable)
  287. {
  288. cmMakefile& mf = status.GetMakefile();
  289. cmValue include = mf.GetDefinition(variable);
  290. if (!include) {
  291. return true;
  292. }
  293. cmList includeFiles{ *include };
  294. bool failed = false;
  295. for (auto filePath : includeFiles) {
  296. // Any relative path without a .cmake extension is checked for valid cmake
  297. // modules. This logic should be consistent with CMake's include() command.
  298. // Otherwise default to checking relative path w.r.t. source directory
  299. if (!cmSystemTools::FileIsFullPath(filePath) &&
  300. !cmHasLiteralSuffix(filePath, ".cmake")) {
  301. std::string mfile = mf.GetModulesFile(cmStrCat(filePath, ".cmake"));
  302. if (mfile.empty()) {
  303. status.SetError(
  304. cmStrCat("could not find requested module:\n ", filePath));
  305. failed = true;
  306. continue;
  307. }
  308. filePath = mfile;
  309. }
  310. std::string includeFile = cmSystemTools::CollapseFullPath(
  311. filePath, mf.GetCurrentSourceDirectory());
  312. if (!cmSystemTools::FileExists(includeFile)) {
  313. status.SetError(
  314. cmStrCat("could not find requested file:\n ", filePath));
  315. failed = true;
  316. continue;
  317. }
  318. if (cmSystemTools::FileIsDirectory(includeFile)) {
  319. status.SetError(
  320. cmStrCat("requested file is a directory:\n ", filePath));
  321. failed = true;
  322. continue;
  323. }
  324. bool const readit = mf.ReadDependentFile(filePath);
  325. if (readit) {
  326. // If the included file ran successfully, continue to the next file
  327. continue;
  328. }
  329. if (cmSystemTools::GetFatalErrorOccurred()) {
  330. failed = true;
  331. continue;
  332. }
  333. status.SetError(cmStrCat("could not load requested file:\n ", filePath));
  334. failed = true;
  335. }
  336. // At this point all files were processed
  337. return !failed;
  338. }
  339. void TopLevelCMakeVarCondSet(cmMakefile& mf, std::string const& name,
  340. std::string const& value)
  341. {
  342. // Set the CMAKE_PROJECT_XXX variable to be the highest-level
  343. // project name in the tree. If there are two project commands
  344. // in the same CMakeLists.txt file, and it is the top level
  345. // CMakeLists.txt file, then go with the last one.
  346. if (!mf.GetDefinition(name) || mf.IsRootMakefile()) {
  347. mf.RemoveDefinition(name);
  348. mf.AddCacheDefinition(name, value, "Value Computed by CMake",
  349. cmStateEnums::STATIC);
  350. }
  351. }
  352. }