cmConditionEvaluator.cxx 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmConditionEvaluator.h"
  4. #include <array>
  5. #include <cstdio>
  6. #include <cstdlib>
  7. #include <functional>
  8. #include <iterator>
  9. #include <list>
  10. #include <sstream>
  11. #include <utility>
  12. #include <cm/string_view>
  13. #include <cmext/algorithm>
  14. #include "cmsys/RegularExpression.hxx"
  15. #include "cmExpandedCommandArgument.h"
  16. #include "cmMakefile.h"
  17. #include "cmMessageType.h"
  18. #include "cmState.h"
  19. #include "cmStringAlgorithms.h"
  20. #include "cmSystemTools.h"
  21. #include "cmValue.h"
  22. #include "cmake.h"
  23. namespace {
  24. auto const keyAND = "AND"_s;
  25. auto const keyCOMMAND = "COMMAND"_s;
  26. auto const keyDEFINED = "DEFINED"_s;
  27. auto const keyEQUAL = "EQUAL"_s;
  28. auto const keyEXISTS = "EXISTS"_s;
  29. auto const keyGREATER = "GREATER"_s;
  30. auto const keyGREATER_EQUAL = "GREATER_EQUAL"_s;
  31. auto const keyIN_LIST = "IN_LIST"_s;
  32. auto const keyIS_ABSOLUTE = "IS_ABSOLUTE"_s;
  33. auto const keyIS_DIRECTORY = "IS_DIRECTORY"_s;
  34. auto const keyIS_NEWER_THAN = "IS_NEWER_THAN"_s;
  35. auto const keyIS_SYMLINK = "IS_SYMLINK"_s;
  36. auto const keyLESS = "LESS"_s;
  37. auto const keyLESS_EQUAL = "LESS_EQUAL"_s;
  38. auto const keyMATCHES = "MATCHES"_s;
  39. auto const keyNOT = "NOT"_s;
  40. auto const keyOR = "OR"_s;
  41. auto const keyParenL = "("_s;
  42. auto const keyParenR = ")"_s;
  43. auto const keyPOLICY = "POLICY"_s;
  44. auto const keySTREQUAL = "STREQUAL"_s;
  45. auto const keySTRGREATER = "STRGREATER"_s;
  46. auto const keySTRGREATER_EQUAL = "STRGREATER_EQUAL"_s;
  47. auto const keySTRLESS = "STRLESS"_s;
  48. auto const keySTRLESS_EQUAL = "STRLESS_EQUAL"_s;
  49. auto const keyTARGET = "TARGET"_s;
  50. auto const keyTEST = "TEST"_s;
  51. auto const keyVERSION_EQUAL = "VERSION_EQUAL"_s;
  52. auto const keyVERSION_GREATER = "VERSION_GREATER"_s;
  53. auto const keyVERSION_GREATER_EQUAL = "VERSION_GREATER_EQUAL"_s;
  54. auto const keyVERSION_LESS = "VERSION_LESS"_s;
  55. auto const keyVERSION_LESS_EQUAL = "VERSION_LESS_EQUAL"_s;
  56. cmSystemTools::CompareOp const MATCH2CMPOP[5] = {
  57. cmSystemTools::OP_LESS, cmSystemTools::OP_LESS_EQUAL,
  58. cmSystemTools::OP_GREATER, cmSystemTools::OP_GREATER_EQUAL,
  59. cmSystemTools::OP_EQUAL
  60. };
  61. // Run-Time to Compile-Time template selector
  62. template <template <typename> class Comp, template <typename> class... Ops>
  63. struct cmRt2CtSelector
  64. {
  65. template <typename T>
  66. static bool eval(int r, T lhs, T rhs)
  67. {
  68. switch (r) {
  69. case 0:
  70. return false;
  71. case 1:
  72. return Comp<T>()(lhs, rhs);
  73. default:
  74. return cmRt2CtSelector<Ops...>::eval(r - 1, lhs, rhs);
  75. }
  76. }
  77. };
  78. template <template <typename> class Comp>
  79. struct cmRt2CtSelector<Comp>
  80. {
  81. template <typename T>
  82. static bool eval(int r, T lhs, T rhs)
  83. {
  84. return r == 1 && Comp<T>()(lhs, rhs);
  85. }
  86. };
  87. std::string bool2string(bool const value)
  88. {
  89. return std::string(std::size_t(1), static_cast<char>('0' + int(value)));
  90. }
  91. bool looksLikeSpecialVariable(const std::string& var,
  92. cm::static_string_view prefix,
  93. const std::size_t varNameLen)
  94. {
  95. // NOTE Expecting a variable name at least 1 char length:
  96. // <prefix> + `{` + <varname> + `}`
  97. return ((prefix.size() + 3) <= varNameLen) &&
  98. cmHasPrefix(var, cmStrCat(prefix, '{')) && var[varNameLen - 1] == '}';
  99. }
  100. } // anonymous namespace
  101. #if defined(__SUNPRO_CC)
  102. # define CM_INHERIT_CTOR(Class, Base, Tpl) \
  103. template <typename... Args> \
  104. Class(Args&&... args) \
  105. : Base Tpl(std::forward<Args>(args)...) \
  106. { \
  107. }
  108. #else
  109. # define CM_INHERIT_CTOR(Class, Base, Tpl) using Base Tpl ::Base;
  110. #endif
  111. // BEGIN cmConditionEvaluator::cmArgumentList
  112. class cmConditionEvaluator::cmArgumentList
  113. : public std::list<cmExpandedCommandArgument>
  114. {
  115. using base_t = std::list<cmExpandedCommandArgument>;
  116. public:
  117. CM_INHERIT_CTOR(cmArgumentList, list, <cmExpandedCommandArgument>);
  118. class CurrentAndNextIter
  119. {
  120. friend class cmConditionEvaluator::cmArgumentList;
  121. public:
  122. base_t::iterator current;
  123. base_t::iterator next;
  124. CurrentAndNextIter advance(base_t& args)
  125. {
  126. this->current = std::next(this->current);
  127. this->next =
  128. std::next(this->current, difference_type(this->current != args.end()));
  129. return *this;
  130. }
  131. private:
  132. CurrentAndNextIter(base_t& args)
  133. : current(args.begin())
  134. , next(std::next(this->current,
  135. difference_type(this->current != args.end())))
  136. {
  137. }
  138. };
  139. class CurrentAndTwoMoreIter
  140. {
  141. friend class cmConditionEvaluator::cmArgumentList;
  142. public:
  143. base_t::iterator current;
  144. base_t::iterator next;
  145. base_t::iterator nextnext;
  146. CurrentAndTwoMoreIter advance(base_t& args)
  147. {
  148. this->current = std::next(this->current);
  149. this->next =
  150. std::next(this->current, difference_type(this->current != args.end()));
  151. this->nextnext =
  152. std::next(this->next, difference_type(this->next != args.end()));
  153. return *this;
  154. }
  155. private:
  156. CurrentAndTwoMoreIter(base_t& args)
  157. : current(args.begin())
  158. , next(std::next(this->current,
  159. difference_type(this->current != args.end())))
  160. , nextnext(
  161. std::next(this->next, difference_type(this->next != args.end())))
  162. {
  163. }
  164. };
  165. CurrentAndNextIter make2ArgsIterator() { return *this; }
  166. CurrentAndTwoMoreIter make3ArgsIterator() { return *this; }
  167. template <typename Iter>
  168. void ReduceOneArg(const bool value, Iter args)
  169. {
  170. *args.current = cmExpandedCommandArgument(bool2string(value), true);
  171. this->erase(args.next);
  172. }
  173. void ReduceTwoArgs(const bool value, CurrentAndTwoMoreIter args)
  174. {
  175. *args.current = cmExpandedCommandArgument(bool2string(value), true);
  176. this->erase(args.nextnext);
  177. this->erase(args.next);
  178. }
  179. };
  180. // END cmConditionEvaluator::cmArgumentList
  181. cmConditionEvaluator::cmConditionEvaluator(cmMakefile& makefile,
  182. cmListFileBacktrace bt)
  183. : Makefile(makefile)
  184. , Backtrace(std::move(bt))
  185. , Policy12Status(makefile.GetPolicyStatus(cmPolicies::CMP0012))
  186. , Policy54Status(makefile.GetPolicyStatus(cmPolicies::CMP0054))
  187. , Policy57Status(makefile.GetPolicyStatus(cmPolicies::CMP0057))
  188. , Policy64Status(makefile.GetPolicyStatus(cmPolicies::CMP0064))
  189. {
  190. }
  191. //=========================================================================
  192. // order of operations,
  193. // 1. ( ) -- parenthetical groups
  194. // 2. IS_DIRECTORY EXISTS COMMAND DEFINED etc predicates
  195. // 3. MATCHES LESS GREATER EQUAL STRLESS STRGREATER STREQUAL etc binary ops
  196. // 4. NOT
  197. // 5. AND OR
  198. //
  199. // There is an issue on whether the arguments should be values of references,
  200. // for example IF (FOO AND BAR) should that compare the strings FOO and BAR
  201. // or should it really do IF (${FOO} AND ${BAR}) Currently IS_DIRECTORY
  202. // EXISTS COMMAND and DEFINED all take values. EQUAL, LESS and GREATER can
  203. // take numeric values or variable names. STRLESS and STRGREATER take
  204. // variable names but if the variable name is not found it will use the name
  205. // directly. AND OR take variables or the values 0 or 1.
  206. bool cmConditionEvaluator::IsTrue(
  207. const std::vector<cmExpandedCommandArgument>& args, std::string& errorString,
  208. MessageType& status)
  209. {
  210. errorString.clear();
  211. // handle empty invocation
  212. if (args.empty()) {
  213. return false;
  214. }
  215. // store the reduced args in this vector
  216. cmArgumentList newArgs(args.begin(), args.end());
  217. // now loop through the arguments and see if we can reduce any of them
  218. // we do this multiple times. Once for each level of precedence
  219. // parens
  220. using handlerFn_t = bool (cmConditionEvaluator::*)(
  221. cmArgumentList&, std::string&, MessageType&);
  222. const std::array<handlerFn_t, 5> handlers = { {
  223. &cmConditionEvaluator::HandleLevel0, // parenthesis
  224. &cmConditionEvaluator::HandleLevel1, // predicates
  225. &cmConditionEvaluator::HandleLevel2, // binary ops
  226. &cmConditionEvaluator::HandleLevel3, // NOT
  227. &cmConditionEvaluator::HandleLevel4 // AND OR
  228. } };
  229. for (auto fn : handlers) {
  230. // Call the reducer 'till there is anything to reduce...
  231. // (i.e., if after an iteration the size becomes smaller)
  232. auto levelResult = true;
  233. for (auto beginSize = newArgs.size();
  234. (levelResult = (this->*fn)(newArgs, errorString, status)) &&
  235. newArgs.size() < beginSize;
  236. beginSize = newArgs.size()) {
  237. }
  238. if (!levelResult) {
  239. // NOTE `errorString` supposed to be set already
  240. return false;
  241. }
  242. }
  243. // now at the end there should only be one argument left
  244. if (newArgs.size() != 1) {
  245. errorString = "Unknown arguments specified";
  246. status = MessageType::FATAL_ERROR;
  247. return false;
  248. }
  249. return this->GetBooleanValueWithAutoDereference(newArgs.front(), errorString,
  250. status, true);
  251. }
  252. //=========================================================================
  253. cmValue cmConditionEvaluator::GetDefinitionIfUnquoted(
  254. cmExpandedCommandArgument const& argument) const
  255. {
  256. if ((this->Policy54Status != cmPolicies::WARN &&
  257. this->Policy54Status != cmPolicies::OLD) &&
  258. argument.WasQuoted()) {
  259. return nullptr;
  260. }
  261. cmValue def = this->Makefile.GetDefinition(argument.GetValue());
  262. if (def && argument.WasQuoted() &&
  263. this->Policy54Status == cmPolicies::WARN) {
  264. if (!this->Makefile.HasCMP0054AlreadyBeenReported(this->Backtrace.Top())) {
  265. std::ostringstream e;
  266. // clang-format off
  267. e << (cmPolicies::GetPolicyWarning(cmPolicies::CMP0054))
  268. << "\n"
  269. "Quoted variables like \"" << argument.GetValue() << "\" "
  270. "will no longer be dereferenced when the policy is set to NEW. "
  271. "Since the policy is not set the OLD behavior will be used.";
  272. // clang-format on
  273. this->Makefile.GetCMakeInstance()->IssueMessage(
  274. MessageType::AUTHOR_WARNING, e.str(), this->Backtrace);
  275. }
  276. }
  277. return def;
  278. }
  279. //=========================================================================
  280. cmValue cmConditionEvaluator::GetVariableOrString(
  281. const cmExpandedCommandArgument& argument) const
  282. {
  283. cmValue def = this->GetDefinitionIfUnquoted(argument);
  284. if (!def) {
  285. def = cmValue(argument.GetValue());
  286. }
  287. return def;
  288. }
  289. //=========================================================================
  290. bool cmConditionEvaluator::IsKeyword(
  291. cm::static_string_view keyword,
  292. const cmExpandedCommandArgument& argument) const
  293. {
  294. if ((this->Policy54Status != cmPolicies::WARN &&
  295. this->Policy54Status != cmPolicies::OLD) &&
  296. argument.WasQuoted()) {
  297. return false;
  298. }
  299. const auto isKeyword = argument.GetValue() == keyword;
  300. if (isKeyword && argument.WasQuoted() &&
  301. this->Policy54Status == cmPolicies::WARN) {
  302. if (!this->Makefile.HasCMP0054AlreadyBeenReported(this->Backtrace.Top())) {
  303. std::ostringstream e;
  304. // clang-format off
  305. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0054)
  306. << "\n"
  307. "Quoted keywords like \"" << argument.GetValue() << "\" "
  308. "will no longer be interpreted as keywords "
  309. "when the policy is set to NEW. "
  310. "Since the policy is not set the OLD behavior will be used.";
  311. // clang-format on
  312. this->Makefile.GetCMakeInstance()->IssueMessage(
  313. MessageType::AUTHOR_WARNING, e.str(), this->Backtrace);
  314. }
  315. }
  316. return isKeyword;
  317. }
  318. //=========================================================================
  319. bool cmConditionEvaluator::GetBooleanValue(
  320. cmExpandedCommandArgument& arg) const
  321. {
  322. // Check basic and named constants.
  323. if (cmIsOn(arg.GetValue())) {
  324. return true;
  325. }
  326. if (cmIsOff(arg.GetValue())) {
  327. return false;
  328. }
  329. // Check for numbers.
  330. if (!arg.empty()) {
  331. char* end;
  332. const double d = std::strtod(arg.GetValue().c_str(), &end);
  333. if (*end == '\0') {
  334. // The whole string is a number. Use C conversion to bool.
  335. return static_cast<bool>(d);
  336. }
  337. }
  338. // Check definition.
  339. cmValue def = this->GetDefinitionIfUnquoted(arg);
  340. return !cmIsOff(def);
  341. }
  342. //=========================================================================
  343. // Boolean value behavior from CMake 2.6.4 and below.
  344. bool cmConditionEvaluator::GetBooleanValueOld(
  345. cmExpandedCommandArgument const& arg, bool const one) const
  346. {
  347. if (one) {
  348. // Old IsTrue behavior for single argument.
  349. if (arg == "0") {
  350. return false;
  351. }
  352. if (arg == "1") {
  353. return true;
  354. }
  355. cmValue def = this->GetDefinitionIfUnquoted(arg);
  356. return !cmIsOff(def);
  357. }
  358. // Old GetVariableOrNumber behavior.
  359. cmValue def = this->GetDefinitionIfUnquoted(arg);
  360. if (!def && std::atoi(arg.GetValue().c_str())) {
  361. def = cmValue(arg.GetValue());
  362. }
  363. return !cmIsOff(def);
  364. }
  365. //=========================================================================
  366. // returns the resulting boolean value
  367. bool cmConditionEvaluator::GetBooleanValueWithAutoDereference(
  368. cmExpandedCommandArgument& newArg, std::string& errorString,
  369. MessageType& status, bool const oneArg) const
  370. {
  371. // Use the policy if it is set.
  372. if (this->Policy12Status == cmPolicies::NEW) {
  373. return this->GetBooleanValue(newArg);
  374. }
  375. if (this->Policy12Status == cmPolicies::OLD) {
  376. return this->GetBooleanValueOld(newArg, oneArg);
  377. }
  378. // Check policy only if old and new results differ.
  379. const auto newResult = this->GetBooleanValue(newArg);
  380. const auto oldResult = this->GetBooleanValueOld(newArg, oneArg);
  381. if (newResult != oldResult) {
  382. switch (this->Policy12Status) {
  383. case cmPolicies::WARN:
  384. errorString = "An argument named \"" + newArg.GetValue() +
  385. "\" appears in a conditional statement. " +
  386. cmPolicies::GetPolicyWarning(cmPolicies::CMP0012);
  387. status = MessageType::AUTHOR_WARNING;
  388. CM_FALLTHROUGH;
  389. case cmPolicies::OLD:
  390. return oldResult;
  391. case cmPolicies::REQUIRED_IF_USED:
  392. case cmPolicies::REQUIRED_ALWAYS: {
  393. errorString = "An argument named \"" + newArg.GetValue() +
  394. "\" appears in a conditional statement. " +
  395. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0012);
  396. status = MessageType::FATAL_ERROR;
  397. }
  398. case cmPolicies::NEW:
  399. break;
  400. }
  401. }
  402. return newResult;
  403. }
  404. template <int N>
  405. inline int cmConditionEvaluator::matchKeysImpl(
  406. const cmExpandedCommandArgument&)
  407. {
  408. // Zero means "not found"
  409. return 0;
  410. }
  411. template <int N, typename T, typename... Keys>
  412. inline int cmConditionEvaluator::matchKeysImpl(
  413. const cmExpandedCommandArgument& arg, T current, Keys... key)
  414. {
  415. if (this->IsKeyword(current, arg)) {
  416. // Stop searching as soon as smth has found
  417. return N;
  418. }
  419. return matchKeysImpl<N + 1>(arg, key...);
  420. }
  421. template <typename... Keys>
  422. inline int cmConditionEvaluator::matchKeys(
  423. const cmExpandedCommandArgument& arg, Keys... key)
  424. {
  425. // Get index of the matched key (1-based)
  426. return matchKeysImpl<1>(arg, key...);
  427. }
  428. //=========================================================================
  429. // level 0 processes parenthetical expressions
  430. bool cmConditionEvaluator::HandleLevel0(cmArgumentList& newArgs,
  431. std::string& errorString,
  432. MessageType& status)
  433. {
  434. for (auto arg = newArgs.begin(); arg != newArgs.end(); ++arg) {
  435. if (this->IsKeyword(keyParenL, *arg)) {
  436. // search for the closing paren for this opening one
  437. auto depth = 1;
  438. auto argClose = std::next(arg);
  439. for (; argClose != newArgs.end() && depth; ++argClose) {
  440. depth += int(this->IsKeyword(keyParenL, *argClose)) -
  441. int(this->IsKeyword(keyParenR, *argClose));
  442. }
  443. if (depth) {
  444. errorString = "mismatched parenthesis in condition";
  445. status = MessageType::FATAL_ERROR;
  446. return false;
  447. }
  448. // store the reduced args in this vector
  449. auto argOpen = std::next(arg);
  450. const std::vector<cmExpandedCommandArgument> subExpr(
  451. argOpen, std::prev(argClose));
  452. // now recursively invoke IsTrue to handle the values inside the
  453. // parenthetical expression
  454. const auto value = this->IsTrue(subExpr, errorString, status);
  455. *arg = cmExpandedCommandArgument(bool2string(value), true);
  456. argOpen = std::next(arg);
  457. // remove the now evaluated parenthetical expression
  458. newArgs.erase(argOpen, argClose);
  459. }
  460. }
  461. return true;
  462. }
  463. //=========================================================================
  464. // level one handles most predicates except for NOT
  465. bool cmConditionEvaluator::HandleLevel1(cmArgumentList& newArgs, std::string&,
  466. MessageType&)
  467. {
  468. const auto policy64IsOld = this->Policy64Status == cmPolicies::OLD ||
  469. this->Policy64Status == cmPolicies::WARN;
  470. for (auto args = newArgs.make2ArgsIterator(); args.current != newArgs.end();
  471. args.advance(newArgs)) {
  472. auto policyCheck = [&, this](const cmPolicies::PolicyID id,
  473. const cmPolicies::PolicyStatus status,
  474. const cm::static_string_view kw) {
  475. if (status == cmPolicies::WARN && this->IsKeyword(kw, *args.current)) {
  476. std::ostringstream e;
  477. e << cmPolicies::GetPolicyWarning(id) << "\n"
  478. << kw
  479. << " will be interpreted as an operator "
  480. "when the policy is set to NEW. "
  481. "Since the policy is not set the OLD behavior will be used.";
  482. this->Makefile.IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  483. }
  484. };
  485. // NOTE Checking policies for warnings are not require an access to the
  486. // next arg. Check them first!
  487. policyCheck(cmPolicies::CMP0064, this->Policy64Status, keyTEST);
  488. // NOTE Fail fast: All the predicates below require the next arg to be
  489. // valid
  490. if (args.next == newArgs.end()) {
  491. continue;
  492. }
  493. // does a file exist
  494. if (this->IsKeyword(keyEXISTS, *args.current)) {
  495. newArgs.ReduceOneArg(cmSystemTools::FileExists(args.next->GetValue()),
  496. args);
  497. }
  498. // does a directory with this name exist
  499. else if (this->IsKeyword(keyIS_DIRECTORY, *args.current)) {
  500. newArgs.ReduceOneArg(
  501. cmSystemTools::FileIsDirectory(args.next->GetValue()), args);
  502. }
  503. // does a symlink with this name exist
  504. else if (this->IsKeyword(keyIS_SYMLINK, *args.current)) {
  505. newArgs.ReduceOneArg(cmSystemTools::FileIsSymlink(args.next->GetValue()),
  506. args);
  507. }
  508. // is the given path an absolute path ?
  509. else if (this->IsKeyword(keyIS_ABSOLUTE, *args.current)) {
  510. newArgs.ReduceOneArg(
  511. cmSystemTools::FileIsFullPath(args.next->GetValue()), args);
  512. }
  513. // does a command exist
  514. else if (this->IsKeyword(keyCOMMAND, *args.current)) {
  515. newArgs.ReduceOneArg(
  516. bool(this->Makefile.GetState()->GetCommand(args.next->GetValue())),
  517. args);
  518. }
  519. // does a policy exist
  520. else if (this->IsKeyword(keyPOLICY, *args.current)) {
  521. cmPolicies::PolicyID pid;
  522. newArgs.ReduceOneArg(
  523. cmPolicies::GetPolicyID(args.next->GetValue().c_str(), pid), args);
  524. }
  525. // does a target exist
  526. else if (this->IsKeyword(keyTARGET, *args.current)) {
  527. newArgs.ReduceOneArg(
  528. bool(this->Makefile.FindTargetToUse(args.next->GetValue())), args);
  529. }
  530. // is a variable defined
  531. else if (this->IsKeyword(keyDEFINED, *args.current)) {
  532. const auto& var = args.next->GetValue();
  533. const auto varNameLen = var.size();
  534. auto result = false;
  535. if (looksLikeSpecialVariable(var, "ENV"_s, varNameLen)) {
  536. const auto env = args.next->GetValue().substr(4, varNameLen - 5);
  537. result = cmSystemTools::HasEnv(env);
  538. }
  539. else if (looksLikeSpecialVariable(var, "CACHE"_s, varNameLen)) {
  540. const auto cache = args.next->GetValue().substr(6, varNameLen - 7);
  541. result = bool(this->Makefile.GetState()->GetCacheEntryValue(cache));
  542. }
  543. else {
  544. result = this->Makefile.IsDefinitionSet(args.next->GetValue());
  545. }
  546. newArgs.ReduceOneArg(result, args);
  547. }
  548. // does a test exist
  549. else if (this->IsKeyword(keyTEST, *args.current)) {
  550. if (policy64IsOld) {
  551. continue;
  552. }
  553. newArgs.ReduceOneArg(bool(this->Makefile.GetTest(args.next->GetValue())),
  554. args);
  555. }
  556. }
  557. return true;
  558. }
  559. //=========================================================================
  560. // level two handles most binary operations except for AND OR
  561. bool cmConditionEvaluator::HandleLevel2(cmArgumentList& newArgs,
  562. std::string& errorString,
  563. MessageType& status)
  564. {
  565. for (auto args = newArgs.make3ArgsIterator(); args.current != newArgs.end();
  566. args.advance(newArgs)) {
  567. int matchNo;
  568. // NOTE Handle special case `if(... BLAH_BLAH MATCHES)`
  569. // (i.e., w/o regex to match which is possibly result of
  570. // variable expansion to an empty string)
  571. if (args.next != newArgs.end() &&
  572. this->IsKeyword(keyMATCHES, *args.current)) {
  573. newArgs.ReduceOneArg(false, args);
  574. }
  575. // NOTE Fail fast: All the binary ops below require 2 arguments.
  576. else if (args.next == newArgs.end() || args.nextnext == newArgs.end()) {
  577. continue;
  578. }
  579. else if (this->IsKeyword(keyMATCHES, *args.next)) {
  580. cmValue def = this->GetDefinitionIfUnquoted(*args.current);
  581. std::string def_buf;
  582. if (!def) {
  583. def = cmValue(args.current->GetValue());
  584. } else if (cmHasLiteralPrefix(args.current->GetValue(),
  585. "CMAKE_MATCH_")) {
  586. // The string to match is owned by our match result variables.
  587. // Move it to our own buffer before clearing them.
  588. def_buf = *def;
  589. def = cmValue(def_buf);
  590. }
  591. this->Makefile.ClearMatches();
  592. const auto& rex = args.nextnext->GetValue();
  593. cmsys::RegularExpression regEntry;
  594. if (!regEntry.compile(rex)) {
  595. std::ostringstream error;
  596. error << "Regular expression \"" << rex << "\" cannot compile";
  597. errorString = error.str();
  598. status = MessageType::FATAL_ERROR;
  599. return false;
  600. }
  601. const auto match = regEntry.find(*def);
  602. if (match) {
  603. this->Makefile.StoreMatches(regEntry);
  604. }
  605. newArgs.ReduceTwoArgs(match, args);
  606. }
  607. else if ((matchNo =
  608. this->matchKeys(*args.next, keyLESS, keyLESS_EQUAL, keyGREATER,
  609. keyGREATER_EQUAL, keyEQUAL))) {
  610. cmValue ldef = this->GetVariableOrString(*args.current);
  611. cmValue rdef = this->GetVariableOrString(*args.nextnext);
  612. double lhs;
  613. double rhs;
  614. auto parseDoubles = [&]() {
  615. return std::sscanf(ldef->c_str(), "%lg", &lhs) == 1 &&
  616. std::sscanf(rdef->c_str(), "%lg", &rhs) == 1;
  617. };
  618. // clang-format off
  619. const auto result = parseDoubles() &&
  620. cmRt2CtSelector<
  621. std::less, std::less_equal,
  622. std::greater, std::greater_equal,
  623. std::equal_to
  624. >::eval(matchNo, lhs, rhs);
  625. // clang-format on
  626. newArgs.ReduceTwoArgs(result, args);
  627. }
  628. else if ((matchNo = this->matchKeys(*args.next, keySTRLESS,
  629. keySTRLESS_EQUAL, keySTRGREATER,
  630. keySTRGREATER_EQUAL, keySTREQUAL))) {
  631. const cmValue lhs = this->GetVariableOrString(*args.current);
  632. const cmValue rhs = this->GetVariableOrString(*args.nextnext);
  633. const auto val = (*lhs).compare(*rhs);
  634. // clang-format off
  635. const auto result = cmRt2CtSelector<
  636. std::less, std::less_equal,
  637. std::greater, std::greater_equal,
  638. std::equal_to
  639. >::eval(matchNo, val, 0);
  640. // clang-format on
  641. newArgs.ReduceTwoArgs(result, args);
  642. }
  643. else if ((matchNo =
  644. this->matchKeys(*args.next, keyVERSION_LESS,
  645. keyVERSION_LESS_EQUAL, keyVERSION_GREATER,
  646. keyVERSION_GREATER_EQUAL, keyVERSION_EQUAL))) {
  647. const auto op = MATCH2CMPOP[matchNo - 1];
  648. const std::string& lhs = this->GetVariableOrString(*args.current);
  649. const std::string& rhs = this->GetVariableOrString(*args.nextnext);
  650. const auto result = cmSystemTools::VersionCompare(op, lhs, rhs);
  651. newArgs.ReduceTwoArgs(result, args);
  652. }
  653. // is file A newer than file B
  654. else if (this->IsKeyword(keyIS_NEWER_THAN, *args.next)) {
  655. auto fileIsNewer = 0;
  656. cmsys::Status ftcStatus = cmSystemTools::FileTimeCompare(
  657. args.current->GetValue(), args.nextnext->GetValue(), &fileIsNewer);
  658. newArgs.ReduceTwoArgs(
  659. (!ftcStatus || fileIsNewer == 1 || fileIsNewer == 0), args);
  660. }
  661. else if (this->IsKeyword(keyIN_LIST, *args.next)) {
  662. if (this->Policy57Status != cmPolicies::OLD &&
  663. this->Policy57Status != cmPolicies::WARN) {
  664. cmValue lhs = this->GetVariableOrString(*args.current);
  665. cmValue rhs = this->Makefile.GetDefinition(args.nextnext->GetValue());
  666. newArgs.ReduceTwoArgs(
  667. rhs && cm::contains(cmExpandedList(*rhs, true), *lhs), args);
  668. }
  669. else if (this->Policy57Status == cmPolicies::WARN) {
  670. std::ostringstream e;
  671. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0057)
  672. << "\n"
  673. "IN_LIST will be interpreted as an operator "
  674. "when the policy is set to NEW. "
  675. "Since the policy is not set the OLD behavior will be used.";
  676. this->Makefile.IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  677. }
  678. }
  679. }
  680. return true;
  681. }
  682. //=========================================================================
  683. // level 3 handles NOT
  684. bool cmConditionEvaluator::HandleLevel3(cmArgumentList& newArgs,
  685. std::string& errorString,
  686. MessageType& status)
  687. {
  688. for (auto args = newArgs.make2ArgsIterator(); args.next != newArgs.end();
  689. args.advance(newArgs)) {
  690. if (this->IsKeyword(keyNOT, *args.current)) {
  691. const auto rhs = this->GetBooleanValueWithAutoDereference(
  692. *args.next, errorString, status);
  693. newArgs.ReduceOneArg(!rhs, args);
  694. }
  695. }
  696. return true;
  697. }
  698. //=========================================================================
  699. // level 4 handles AND OR
  700. bool cmConditionEvaluator::HandleLevel4(cmArgumentList& newArgs,
  701. std::string& errorString,
  702. MessageType& status)
  703. {
  704. for (auto args = newArgs.make3ArgsIterator(); args.nextnext != newArgs.end();
  705. args.advance(newArgs)) {
  706. int matchNo;
  707. if ((matchNo = this->matchKeys(*args.next, keyAND, keyOR))) {
  708. const auto lhs = this->GetBooleanValueWithAutoDereference(
  709. *args.current, errorString, status);
  710. const auto rhs = this->GetBooleanValueWithAutoDereference(
  711. *args.nextnext, errorString, status);
  712. // clang-format off
  713. const auto result =
  714. cmRt2CtSelector<
  715. std::logical_and, std::logical_or
  716. >::eval(matchNo, lhs, rhs);
  717. // clang-format on
  718. newArgs.ReduceTwoArgs(result, args);
  719. }
  720. }
  721. return true;
  722. }