1
0

cmProjectCommand.cxx 12 KB

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