cmProjectCommand.cxx 11 KB

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