cmConditionEvaluator.cxx 27 KB

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