cmConditionEvaluator.cxx 29 KB

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