cmConditionEvaluator.cxx 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  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::REQUIRED_IF_USED:
  404. case cmPolicies::REQUIRED_ALWAYS: {
  405. errorString = "An argument named \"" + newArg.GetValue() +
  406. "\" appears in a conditional statement. " +
  407. cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0012);
  408. status = MessageType::FATAL_ERROR;
  409. break;
  410. }
  411. case cmPolicies::NEW:
  412. break;
  413. }
  414. }
  415. return newResult;
  416. }
  417. template <int N>
  418. inline int cmConditionEvaluator::matchKeysImpl(
  419. const cmExpandedCommandArgument&)
  420. {
  421. // Zero means "not found"
  422. return 0;
  423. }
  424. template <int N, typename T, typename... Keys>
  425. inline int cmConditionEvaluator::matchKeysImpl(
  426. const cmExpandedCommandArgument& arg, T current, Keys... key)
  427. {
  428. if (this->IsKeyword(current, arg)) {
  429. // Stop searching as soon as smth has found
  430. return N;
  431. }
  432. return matchKeysImpl<N + 1>(arg, key...);
  433. }
  434. template <typename... Keys>
  435. inline int cmConditionEvaluator::matchKeys(
  436. const cmExpandedCommandArgument& arg, Keys... key)
  437. {
  438. // Get index of the matched key (1-based)
  439. return matchKeysImpl<1>(arg, key...);
  440. }
  441. //=========================================================================
  442. // level 0 processes parenthetical expressions
  443. bool cmConditionEvaluator::HandleLevel0(cmArgumentList& newArgs,
  444. std::string& errorString,
  445. MessageType& status)
  446. {
  447. for (auto arg = newArgs.begin(); arg != newArgs.end(); ++arg) {
  448. if (this->IsKeyword(keyParenL, *arg)) {
  449. // search for the closing paren for this opening one
  450. auto depth = 1;
  451. auto argClose = std::next(arg);
  452. for (; argClose != newArgs.end() && depth; ++argClose) {
  453. depth += int(this->IsKeyword(keyParenL, *argClose)) -
  454. int(this->IsKeyword(keyParenR, *argClose));
  455. }
  456. if (depth) {
  457. errorString = "mismatched parenthesis in condition";
  458. status = MessageType::FATAL_ERROR;
  459. return false;
  460. }
  461. // store the reduced args in this vector
  462. auto argOpen = std::next(arg);
  463. const std::vector<cmExpandedCommandArgument> subExpr(
  464. argOpen, std::prev(argClose));
  465. // now recursively invoke IsTrue to handle the values inside the
  466. // parenthetical expression
  467. const auto value = this->IsTrue(subExpr, errorString, status);
  468. *arg = cmExpandedCommandArgument(bool2string(value), true);
  469. argOpen = std::next(arg);
  470. // remove the now evaluated parenthetical expression
  471. newArgs.erase(argOpen, argClose);
  472. }
  473. }
  474. return true;
  475. }
  476. //=========================================================================
  477. // level one handles most predicates except for NOT
  478. bool cmConditionEvaluator::HandleLevel1(cmArgumentList& newArgs, std::string&,
  479. MessageType&)
  480. {
  481. for (auto args = newArgs.make2ArgsIterator(); args.current != newArgs.end();
  482. args.advance(newArgs)) {
  483. auto policyCheck = [&, this](const cmPolicies::PolicyID id,
  484. const cmPolicies::PolicyStatus status,
  485. const cm::static_string_view kw) {
  486. if (status == cmPolicies::WARN && this->IsKeyword(kw, *args.current)) {
  487. std::ostringstream e;
  488. e << cmPolicies::GetPolicyWarning(id) << "\n"
  489. << kw
  490. << " will be interpreted as an operator "
  491. "when the policy is set to NEW. "
  492. "Since the policy is not set the OLD behavior will be used.";
  493. this->Makefile.IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  494. }
  495. };
  496. // NOTE Checking policies for warnings are not require an access to the
  497. // next arg. Check them first!
  498. policyCheck(cmPolicies::CMP0064, this->Policy64Status, keyTEST);
  499. // NOTE Fail fast: All the predicates below require the next arg to be
  500. // valid
  501. if (args.next == newArgs.end()) {
  502. continue;
  503. }
  504. // does a file exist
  505. if (this->IsKeyword(keyEXISTS, *args.current)) {
  506. newArgs.ReduceOneArg(cmSystemTools::FileExists(args.next->GetValue()),
  507. args);
  508. }
  509. // check if a file is readable
  510. else if (this->IsKeyword(keyIS_READABLE, *args.current)) {
  511. newArgs.ReduceOneArg(cmSystemTools::TestFileAccess(
  512. args.next->GetValue(), cmsys::TEST_FILE_READ),
  513. args);
  514. }
  515. // check if a file is writable
  516. else if (this->IsKeyword(keyIS_WRITABLE, *args.current)) {
  517. newArgs.ReduceOneArg(cmSystemTools::TestFileAccess(
  518. args.next->GetValue(), cmsys::TEST_FILE_WRITE),
  519. args);
  520. }
  521. // check if a file is executable
  522. else if (this->IsKeyword(keyIS_EXECUTABLE, *args.current)) {
  523. newArgs.ReduceOneArg(cmSystemTools::TestFileAccess(
  524. args.next->GetValue(), cmsys::TEST_FILE_EXECUTE),
  525. args);
  526. }
  527. // does a directory with this name exist
  528. else if (this->IsKeyword(keyIS_DIRECTORY, *args.current)) {
  529. newArgs.ReduceOneArg(
  530. cmSystemTools::FileIsDirectory(args.next->GetValue()), args);
  531. }
  532. // does a symlink with this name exist
  533. else if (this->IsKeyword(keyIS_SYMLINK, *args.current)) {
  534. newArgs.ReduceOneArg(cmSystemTools::FileIsSymlink(args.next->GetValue()),
  535. args);
  536. }
  537. // is the given path an absolute path ?
  538. else if (this->IsKeyword(keyIS_ABSOLUTE, *args.current)) {
  539. newArgs.ReduceOneArg(
  540. cmSystemTools::FileIsFullPath(args.next->GetValue()), args);
  541. }
  542. // does a command exist
  543. else if (this->IsKeyword(keyCOMMAND, *args.current)) {
  544. newArgs.ReduceOneArg(
  545. static_cast<bool>(
  546. this->Makefile.GetState()->GetCommand(args.next->GetValue())),
  547. args);
  548. }
  549. // does a policy exist
  550. else if (this->IsKeyword(keyPOLICY, *args.current)) {
  551. cmPolicies::PolicyID pid;
  552. newArgs.ReduceOneArg(
  553. cmPolicies::GetPolicyID(args.next->GetValue().c_str(), pid), args);
  554. }
  555. // does a target exist
  556. else if (this->IsKeyword(keyTARGET, *args.current)) {
  557. newArgs.ReduceOneArg(static_cast<bool>(this->Makefile.FindTargetToUse(
  558. args.next->GetValue())),
  559. args);
  560. }
  561. // is a variable defined
  562. else if (this->IsKeyword(keyDEFINED, *args.current)) {
  563. const auto& var = args.next->GetValue();
  564. const auto varNameLen = var.size();
  565. auto result = false;
  566. if (looksLikeSpecialVariable(var, "ENV"_s, varNameLen)) {
  567. const auto env = args.next->GetValue().substr(4, varNameLen - 5);
  568. result = cmSystemTools::HasEnv(env);
  569. }
  570. else if (looksLikeSpecialVariable(var, "CACHE"_s, varNameLen)) {
  571. const auto cache = args.next->GetValue().substr(6, varNameLen - 7);
  572. result = static_cast<bool>(
  573. this->Makefile.GetState()->GetCacheEntryValue(cache));
  574. }
  575. else {
  576. result = this->Makefile.IsDefinitionSet(args.next->GetValue());
  577. }
  578. newArgs.ReduceOneArg(result, args);
  579. }
  580. // does a test exist
  581. else if (this->IsKeyword(keyTEST, *args.current)) {
  582. if (this->Policy64Status == cmPolicies::OLD ||
  583. this->Policy64Status == cmPolicies::WARN) {
  584. continue;
  585. }
  586. newArgs.ReduceOneArg(
  587. static_cast<bool>(this->Makefile.GetTest(args.next->GetValue())),
  588. args);
  589. }
  590. }
  591. return true;
  592. }
  593. //=========================================================================
  594. // level two handles most binary operations except for AND OR
  595. bool cmConditionEvaluator::HandleLevel2(cmArgumentList& newArgs,
  596. std::string& errorString,
  597. MessageType& status)
  598. {
  599. for (auto args = newArgs.make3ArgsIterator(); args.current != newArgs.end();
  600. args.advance(newArgs)) {
  601. int matchNo;
  602. // NOTE Handle special case `if(... BLAH_BLAH MATCHES)`
  603. // (i.e., w/o regex to match which is possibly result of
  604. // variable expansion to an empty string)
  605. if (args.next != newArgs.end() &&
  606. this->IsKeyword(keyMATCHES, *args.current)) {
  607. newArgs.ReduceOneArg(false, args);
  608. }
  609. // NOTE Fail fast: All the binary ops below require 2 arguments.
  610. else if (args.next == newArgs.end() || args.nextnext == newArgs.end()) {
  611. continue;
  612. }
  613. else if (this->IsKeyword(keyMATCHES, *args.next)) {
  614. cmValue def = this->GetDefinitionIfUnquoted(*args.current);
  615. std::string def_buf;
  616. if (!def) {
  617. def = cmValue(args.current->GetValue());
  618. } else if (cmHasLiteralPrefix(args.current->GetValue(),
  619. "CMAKE_MATCH_")) {
  620. // The string to match is owned by our match result variables.
  621. // Move it to our own buffer before clearing them.
  622. def_buf = *def;
  623. def = cmValue(def_buf);
  624. }
  625. this->Makefile.ClearMatches();
  626. const auto& rex = args.nextnext->GetValue();
  627. cmsys::RegularExpression regEntry;
  628. if (!regEntry.compile(rex)) {
  629. std::ostringstream error;
  630. error << "Regular expression \"" << rex << "\" cannot compile";
  631. errorString = error.str();
  632. status = MessageType::FATAL_ERROR;
  633. return false;
  634. }
  635. const auto match = regEntry.find(*def);
  636. if (match) {
  637. this->Makefile.StoreMatches(regEntry);
  638. }
  639. newArgs.ReduceTwoArgs(match, args);
  640. }
  641. else if ((matchNo =
  642. this->matchKeys(*args.next, keyLESS, keyLESS_EQUAL, keyGREATER,
  643. keyGREATER_EQUAL, keyEQUAL))) {
  644. cmValue ldef = this->GetVariableOrString(*args.current);
  645. cmValue rdef = this->GetVariableOrString(*args.nextnext);
  646. double lhs;
  647. double rhs;
  648. auto parseDoubles = [&]() {
  649. return std::sscanf(ldef->c_str(), "%lg", &lhs) == 1 &&
  650. std::sscanf(rdef->c_str(), "%lg", &rhs) == 1;
  651. };
  652. // clang-format off
  653. const auto result = parseDoubles() &&
  654. cmRt2CtSelector<
  655. std::less, std::less_equal,
  656. std::greater, std::greater_equal,
  657. std::equal_to
  658. >::eval(matchNo, lhs, rhs);
  659. // clang-format on
  660. newArgs.ReduceTwoArgs(result, args);
  661. }
  662. else if ((matchNo = this->matchKeys(*args.next, keySTRLESS,
  663. keySTRLESS_EQUAL, keySTRGREATER,
  664. keySTRGREATER_EQUAL, keySTREQUAL))) {
  665. const cmValue lhs = this->GetVariableOrString(*args.current);
  666. const cmValue rhs = this->GetVariableOrString(*args.nextnext);
  667. const auto val = (*lhs).compare(*rhs);
  668. // clang-format off
  669. const auto result = cmRt2CtSelector<
  670. std::less, std::less_equal,
  671. std::greater, std::greater_equal,
  672. std::equal_to
  673. >::eval(matchNo, val, 0);
  674. // clang-format on
  675. newArgs.ReduceTwoArgs(result, args);
  676. }
  677. else if ((matchNo =
  678. this->matchKeys(*args.next, keyVERSION_LESS,
  679. keyVERSION_LESS_EQUAL, keyVERSION_GREATER,
  680. keyVERSION_GREATER_EQUAL, keyVERSION_EQUAL))) {
  681. const auto op = MATCH2CMPOP[matchNo - 1];
  682. const cmValue lhs = this->GetVariableOrString(*args.current);
  683. const cmValue rhs = this->GetVariableOrString(*args.nextnext);
  684. const auto result = cmSystemTools::VersionCompare(op, lhs, rhs);
  685. newArgs.ReduceTwoArgs(result, args);
  686. }
  687. // is file A newer than file B
  688. else if (this->IsKeyword(keyIS_NEWER_THAN, *args.next)) {
  689. auto fileIsNewer = 0;
  690. cmsys::Status ftcStatus = cmSystemTools::FileTimeCompare(
  691. args.current->GetValue(), args.nextnext->GetValue(), &fileIsNewer);
  692. newArgs.ReduceTwoArgs(
  693. (!ftcStatus || fileIsNewer == 1 || fileIsNewer == 0), args);
  694. }
  695. else if (this->IsKeyword(keyIN_LIST, *args.next)) {
  696. if (this->Policy57Status != cmPolicies::OLD &&
  697. this->Policy57Status != cmPolicies::WARN) {
  698. cmValue lhs = this->GetVariableOrString(*args.current);
  699. cmValue rhs = this->Makefile.GetDefinition(args.nextnext->GetValue());
  700. newArgs.ReduceTwoArgs(
  701. rhs &&
  702. cm::contains(cmList{ *rhs, cmList::EmptyElements::Yes }, *lhs),
  703. args);
  704. }
  705. else if (this->Policy57Status == cmPolicies::WARN) {
  706. std::ostringstream e;
  707. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0057)
  708. << "\n"
  709. "IN_LIST will be interpreted as an operator "
  710. "when the policy is set to NEW. "
  711. "Since the policy is not set the OLD behavior will be used.";
  712. this->Makefile.IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  713. }
  714. }
  715. else if (this->IsKeyword(keyPATH_EQUAL, *args.next)) {
  716. if (this->Policy139Status != cmPolicies::OLD &&
  717. this->Policy139Status != cmPolicies::WARN) {
  718. cmValue lhs = this->GetVariableOrString(*args.current);
  719. cmValue rhs = this->GetVariableOrString(*args.nextnext);
  720. const auto result = cmCMakePath{ *lhs } == cmCMakePath{ *rhs };
  721. newArgs.ReduceTwoArgs(result, args);
  722. }
  723. else if (this->Policy139Status == cmPolicies::WARN) {
  724. std::ostringstream e;
  725. e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0139)
  726. << "\n"
  727. "PATH_EQUAL will be interpreted as an operator "
  728. "when the policy is set to NEW. "
  729. "Since the policy is not set the OLD behavior will be used.";
  730. this->Makefile.IssueMessage(MessageType::AUTHOR_WARNING, e.str());
  731. }
  732. }
  733. }
  734. return true;
  735. }
  736. //=========================================================================
  737. // level 3 handles NOT
  738. bool cmConditionEvaluator::HandleLevel3(cmArgumentList& newArgs,
  739. std::string& errorString,
  740. MessageType& status)
  741. {
  742. for (auto args = newArgs.make2ArgsIterator(); args.next != newArgs.end();
  743. args.advance(newArgs)) {
  744. if (this->IsKeyword(keyNOT, *args.current)) {
  745. const auto rhs = this->GetBooleanValueWithAutoDereference(
  746. *args.next, errorString, status);
  747. newArgs.ReduceOneArg(!rhs, args);
  748. }
  749. }
  750. return true;
  751. }
  752. //=========================================================================
  753. // level 4 handles AND OR
  754. bool cmConditionEvaluator::HandleLevel4(cmArgumentList& newArgs,
  755. std::string& errorString,
  756. MessageType& status)
  757. {
  758. for (auto args = newArgs.make3ArgsIterator(); args.nextnext != newArgs.end();
  759. args.advance(newArgs)) {
  760. int matchNo;
  761. if ((matchNo = this->matchKeys(*args.next, keyAND, keyOR))) {
  762. const auto lhs = this->GetBooleanValueWithAutoDereference(
  763. *args.current, errorString, status);
  764. const auto rhs = this->GetBooleanValueWithAutoDereference(
  765. *args.nextnext, errorString, status);
  766. // clang-format off
  767. const auto result =
  768. cmRt2CtSelector<
  769. std::logical_and, std::logical_or
  770. >::eval(matchNo, lhs, rhs);
  771. // clang-format on
  772. newArgs.ReduceTwoArgs(result, args);
  773. }
  774. }
  775. return true;
  776. }