cmProjectCommand.cxx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. if (prArgs.Version) {
  174. if (!vx.find(*prArgs.Version)) {
  175. std::string e =
  176. R"(VERSION ")" + *prArgs.Version + R"(" format invalid.)";
  177. mf.IssueMessage(MessageType::FATAL_ERROR, e);
  178. cmSystemTools::SetFatalErrorOccurred();
  179. return true;
  180. }
  181. cmPolicies::PolicyStatus const cmp0096 =
  182. mf.GetPolicyStatus(cmPolicies::CMP0096);
  183. if (cmp0096 == cmPolicies::OLD || cmp0096 == cmPolicies::WARN) {
  184. constexpr size_t maxIntLength =
  185. std::numeric_limits<unsigned>::digits10 + 2;
  186. char vb[MAX_VERSION_COMPONENTS][maxIntLength];
  187. unsigned v[MAX_VERSION_COMPONENTS] = { 0, 0, 0, 0 };
  188. int const vc = std::sscanf(prArgs.Version->c_str(), "%u.%u.%u.%u", &v[0],
  189. &v[1], &v[2], &v[3]);
  190. for (auto i = 0u; i < MAX_VERSION_COMPONENTS; ++i) {
  191. if (static_cast<int>(i) < vc) {
  192. std::snprintf(vb[i], maxIntLength, "%u", v[i]);
  193. version_string += &"."[static_cast<std::size_t>(i == 0)];
  194. version_string += vb[i];
  195. version_components[i] = vb[i];
  196. } else {
  197. vb[i][0] = '\x00';
  198. }
  199. }
  200. } else {
  201. // The regex above verified that we have a .-separated string of
  202. // non-negative integer components. Keep the original string.
  203. version_string = std::move(*prArgs.Version);
  204. // Split the integer components.
  205. auto components = cmSystemTools::SplitString(version_string, '.');
  206. for (auto i = 0u; i < components.size(); ++i) {
  207. version_components[i] = std::move(components[i]);
  208. }
  209. }
  210. }
  211. if (prArgs.CompatVersion) {
  212. if (!vx.find(*prArgs.CompatVersion)) {
  213. std::string e =
  214. R"(COMPAT_VERSION ")" + *prArgs.CompatVersion + R"(" format invalid.)";
  215. mf.IssueMessage(MessageType::FATAL_ERROR, e);
  216. cmSystemTools::SetFatalErrorOccurred();
  217. return true;
  218. }
  219. if (cmSystemTools::VersionCompareGreater(*prArgs.CompatVersion,
  220. version_string)) {
  221. mf.IssueMessage(MessageType::FATAL_ERROR,
  222. "COMPAT_VERSION must be less than or equal to VERSION");
  223. cmSystemTools::SetFatalErrorOccurred();
  224. return true;
  225. }
  226. }
  227. auto createVariables = [&](cm::string_view var, std::string const& val) {
  228. mf.AddDefinition(cmStrCat("PROJECT_"_s, var), val);
  229. mf.AddDefinition(cmStrCat(projectName, "_"_s, var), val);
  230. TopLevelCMakeVarCondSet(mf, cmStrCat("CMAKE_PROJECT_"_s, var), val);
  231. };
  232. createVariables("VERSION"_s, version_string);
  233. createVariables("VERSION_MAJOR"_s, version_components[0]);
  234. createVariables("VERSION_MINOR"_s, version_components[1]);
  235. createVariables("VERSION_PATCH"_s, version_components[2]);
  236. createVariables("VERSION_TWEAK"_s, version_components[3]);
  237. createVariables("COMPAT_VERSION"_s, prArgs.CompatVersion.value_or(""));
  238. createVariables("SPDX_LICENSE"_s, prArgs.License.value_or(""));
  239. createVariables("DESCRIPTION"_s, prArgs.Description.value_or(""));
  240. createVariables("HOMEPAGE_URL"_s, prArgs.HomepageURL.value_or(""));
  241. if (unparsedArgs.empty() && !prArgs.Languages) {
  242. // if no language is specified do c and c++
  243. mf.EnableLanguage({ "C", "CXX" }, false);
  244. } else {
  245. if (!unparsedArgs.empty()) {
  246. mf.EnableLanguage(unparsedArgs, false);
  247. }
  248. if (prArgs.Languages) {
  249. mf.EnableLanguage(*prArgs.Languages, false);
  250. }
  251. }
  252. if (!IncludeByVariable(status, "CMAKE_PROJECT_INCLUDE")) {
  253. return false;
  254. }
  255. if (!IncludeByVariable(status,
  256. "CMAKE_PROJECT_" + projectName + "_INCLUDE")) {
  257. return false;
  258. }
  259. return true;
  260. }
  261. namespace {
  262. bool IncludeByVariable(cmExecutionStatus& status, std::string const& variable)
  263. {
  264. cmMakefile& mf = status.GetMakefile();
  265. cmValue include = mf.GetDefinition(variable);
  266. if (!include) {
  267. return true;
  268. }
  269. cmList includeFiles{ *include };
  270. bool failed = false;
  271. for (auto filePath : includeFiles) {
  272. // Any relative path without a .cmake extension is checked for valid cmake
  273. // modules. This logic should be consistent with CMake's include() command.
  274. // Otherwise default to checking relative path w.r.t. source directory
  275. if (!cmSystemTools::FileIsFullPath(filePath) &&
  276. !cmHasLiteralSuffix(filePath, ".cmake")) {
  277. std::string mfile = mf.GetModulesFile(cmStrCat(filePath, ".cmake"));
  278. if (mfile.empty()) {
  279. status.SetError(
  280. cmStrCat("could not find requested module:\n ", filePath));
  281. failed = true;
  282. continue;
  283. }
  284. filePath = mfile;
  285. }
  286. std::string includeFile = cmSystemTools::CollapseFullPath(
  287. filePath, mf.GetCurrentSourceDirectory());
  288. if (!cmSystemTools::FileExists(includeFile)) {
  289. status.SetError(
  290. cmStrCat("could not find requested file:\n ", filePath));
  291. failed = true;
  292. continue;
  293. }
  294. if (cmSystemTools::FileIsDirectory(includeFile)) {
  295. status.SetError(
  296. cmStrCat("requested file is a directory:\n ", filePath));
  297. failed = true;
  298. continue;
  299. }
  300. bool const readit = mf.ReadDependentFile(filePath);
  301. if (readit) {
  302. // If the included file ran successfully, continue to the next file
  303. continue;
  304. }
  305. if (cmSystemTools::GetFatalErrorOccurred()) {
  306. failed = true;
  307. continue;
  308. }
  309. status.SetError(cmStrCat("could not load requested file:\n ", filePath));
  310. failed = true;
  311. }
  312. // At this point all files were processed
  313. return !failed;
  314. }
  315. void TopLevelCMakeVarCondSet(cmMakefile& mf, std::string const& name,
  316. std::string const& value)
  317. {
  318. // Set the CMAKE_PROJECT_XXX variable to be the highest-level
  319. // project name in the tree. If there are two project commands
  320. // in the same CMakeLists.txt file, and it is the top level
  321. // CMakeLists.txt file, then go with the last one.
  322. if (!mf.GetDefinition(name) || mf.IsRootMakefile()) {
  323. mf.RemoveDefinition(name);
  324. mf.AddCacheDefinition(name, value, "Value Computed by CMake",
  325. cmStateEnums::STATIC);
  326. }
  327. }
  328. }