cmProjectCommand.cxx 14 KB

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