cmProjectCommand.cxx 14 KB

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