expr.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/GenericLexer.h>
  27. #include <AK/LogStream.h>
  28. #include <AK/NonnullOwnPtr.h>
  29. #include <AK/OwnPtr.h>
  30. #include <AK/Queue.h>
  31. #include <AK/String.h>
  32. #include <AK/StringView.h>
  33. #include <LibRegex/Regex.h>
  34. #include <stdio.h>
  35. #include <unistd.h>
  36. static void print_help_and_exit()
  37. {
  38. outln(R"(
  39. Usage: expr EXPRESSION
  40. expr [--help]
  41. Print the value of EXPRESSION to standard output.)");
  42. exit(0);
  43. }
  44. template<typename Fmt, typename... Args>
  45. [[noreturn]] void fail(Fmt&& fmt, Args&&... args)
  46. {
  47. warn("ERROR: \e[31m");
  48. warnln(StringView { fmt }, args...);
  49. warn("\e[0m");
  50. exit(1);
  51. }
  52. class Expression {
  53. public:
  54. enum Precedence {
  55. Or,
  56. And,
  57. Comp,
  58. ArithS,
  59. ArithM,
  60. StringO,
  61. Paren,
  62. };
  63. static NonnullOwnPtr<Expression> parse(Queue<StringView>& args, Precedence prec = Or);
  64. enum class Type {
  65. Integer,
  66. String,
  67. };
  68. virtual bool truth() const = 0;
  69. virtual int integer() const = 0;
  70. virtual String string() const = 0;
  71. virtual Type type() const = 0;
  72. virtual ~Expression() { }
  73. };
  74. class ValueExpression : public Expression {
  75. public:
  76. ValueExpression(int v)
  77. : as_integer(v)
  78. , m_type(Type::Integer)
  79. {
  80. }
  81. ValueExpression(String&& v)
  82. : as_string(move(v))
  83. , m_type(Type::String)
  84. {
  85. }
  86. virtual ~ValueExpression() { }
  87. private:
  88. virtual bool truth() const override
  89. {
  90. if (m_type == Type::String)
  91. return !as_string.is_empty();
  92. return integer() != 0;
  93. }
  94. virtual int integer() const override
  95. {
  96. switch (m_type) {
  97. case Type::Integer:
  98. return as_integer;
  99. case Type::String:
  100. if (auto converted = as_string.to_int(); converted.has_value())
  101. return converted.value();
  102. fail("Not an integer: '{}'", as_string);
  103. }
  104. ASSERT_NOT_REACHED();
  105. }
  106. virtual String string() const override
  107. {
  108. switch (m_type) {
  109. case Type::Integer:
  110. return String::formatted("{}", as_integer);
  111. case Type::String:
  112. return as_string;
  113. }
  114. ASSERT_NOT_REACHED();
  115. }
  116. virtual Type type() const override { return m_type; }
  117. union {
  118. int as_integer;
  119. String as_string;
  120. };
  121. Type m_type { Type::String };
  122. };
  123. class BooleanExpression : public Expression {
  124. public:
  125. enum class BooleanOperator {
  126. And,
  127. Or,
  128. };
  129. static BooleanOperator op_from(const StringView& sv)
  130. {
  131. if (sv == "&")
  132. return BooleanOperator::And;
  133. return BooleanOperator::Or;
  134. }
  135. BooleanExpression(BooleanOperator op, NonnullOwnPtr<Expression>&& left, NonnullOwnPtr<Expression>&& right)
  136. : m_op(op)
  137. , m_left(move(left))
  138. , m_right(move(right))
  139. {
  140. if (m_op == BooleanOperator::Or)
  141. m_left_truth = m_left->truth();
  142. else
  143. m_right_truth = m_right->truth();
  144. }
  145. private:
  146. virtual bool truth() const override
  147. {
  148. if (m_op == BooleanOperator::Or)
  149. return m_left_truth ? true : m_right->truth();
  150. return m_right_truth ? m_left->truth() : false;
  151. }
  152. virtual int integer() const override
  153. {
  154. switch (m_op) {
  155. case BooleanOperator::And:
  156. if (m_right_truth)
  157. return m_left->integer();
  158. return 0;
  159. case BooleanOperator::Or:
  160. if (m_left_truth)
  161. return m_left->integer();
  162. return m_right->integer();
  163. }
  164. ASSERT_NOT_REACHED();
  165. }
  166. virtual String string() const override
  167. {
  168. switch (m_op) {
  169. case BooleanOperator::And:
  170. if (m_right_truth)
  171. return m_left->string();
  172. return "0";
  173. case BooleanOperator::Or:
  174. if (m_left_truth)
  175. return m_left->string();
  176. return m_right->string();
  177. }
  178. ASSERT_NOT_REACHED();
  179. }
  180. virtual Type type() const override
  181. {
  182. switch (m_op) {
  183. case BooleanOperator::And:
  184. if (m_right_truth)
  185. return m_left->type();
  186. return m_right->type();
  187. case BooleanOperator::Or:
  188. if (m_left_truth)
  189. return m_left->type();
  190. return m_right->type();
  191. }
  192. ASSERT_NOT_REACHED();
  193. }
  194. BooleanOperator m_op { BooleanOperator::And };
  195. NonnullOwnPtr<Expression> m_left, m_right;
  196. bool m_left_truth { false }, m_right_truth { false };
  197. };
  198. class ComparisonExpression : public Expression {
  199. public:
  200. enum class ComparisonOperation {
  201. Less,
  202. LessEq,
  203. Eq,
  204. Neq,
  205. GreaterEq,
  206. Greater,
  207. };
  208. static ComparisonOperation op_from(const StringView& sv)
  209. {
  210. if (sv == "<")
  211. return ComparisonOperation::Less;
  212. if (sv == "<=")
  213. return ComparisonOperation::LessEq;
  214. if (sv == "=")
  215. return ComparisonOperation::Eq;
  216. if (sv == "!=")
  217. return ComparisonOperation::Neq;
  218. if (sv == ">=")
  219. return ComparisonOperation::GreaterEq;
  220. return ComparisonOperation::Greater;
  221. }
  222. ComparisonExpression(ComparisonOperation op, NonnullOwnPtr<Expression>&& left, NonnullOwnPtr<Expression>&& right)
  223. : m_op(op)
  224. , m_left(move(left))
  225. , m_right(move(right))
  226. {
  227. }
  228. private:
  229. template<typename T>
  230. bool compare(const T& left, const T& right) const
  231. {
  232. switch (m_op) {
  233. case ComparisonOperation::Less:
  234. return left < right;
  235. case ComparisonOperation::LessEq:
  236. return left == right || left < right;
  237. case ComparisonOperation::Eq:
  238. return left == right;
  239. case ComparisonOperation::Neq:
  240. return left != right;
  241. case ComparisonOperation::GreaterEq:
  242. return !(left < right);
  243. case ComparisonOperation::Greater:
  244. return left != right && !(left < right);
  245. }
  246. ASSERT_NOT_REACHED();
  247. }
  248. virtual bool truth() const override
  249. {
  250. switch (m_left->type()) {
  251. case Type::Integer:
  252. return compare(m_left->integer(), m_right->integer());
  253. case Type::String:
  254. return compare(m_left->string(), m_right->string());
  255. }
  256. ASSERT_NOT_REACHED();
  257. }
  258. virtual int integer() const override { return truth(); }
  259. virtual String string() const override { return truth() ? "1" : "0"; }
  260. virtual Type type() const override { return Type::Integer; }
  261. ComparisonOperation m_op { ComparisonOperation::Less };
  262. NonnullOwnPtr<Expression> m_left, m_right;
  263. };
  264. class ArithmeticExpression : public Expression {
  265. public:
  266. enum class ArithmeticOperation {
  267. Sum,
  268. Difference,
  269. Product,
  270. Quotient,
  271. Remainder,
  272. };
  273. static ArithmeticOperation op_from(const StringView& sv)
  274. {
  275. if (sv == "+")
  276. return ArithmeticOperation::Sum;
  277. if (sv == "-")
  278. return ArithmeticOperation::Difference;
  279. if (sv == "*")
  280. return ArithmeticOperation::Product;
  281. if (sv == "/")
  282. return ArithmeticOperation::Quotient;
  283. return ArithmeticOperation::Remainder;
  284. }
  285. ArithmeticExpression(ArithmeticOperation op, NonnullOwnPtr<Expression>&& left, NonnullOwnPtr<Expression>&& right)
  286. : m_op(op)
  287. , m_left(move(left))
  288. , m_right(move(right))
  289. {
  290. }
  291. private:
  292. virtual bool truth() const override
  293. {
  294. switch (m_op) {
  295. case ArithmeticOperation::Sum:
  296. return m_left->truth() || m_right->truth();
  297. default:
  298. return integer() != 0;
  299. }
  300. }
  301. virtual int integer() const override
  302. {
  303. auto right = m_right->integer();
  304. if (right == 0) {
  305. if (m_op == ArithmeticOperation::Product)
  306. return 0;
  307. if (m_op == ArithmeticOperation::Quotient || m_op == ArithmeticOperation::Remainder)
  308. fail("Division by zero");
  309. }
  310. auto left = m_left->integer();
  311. switch (m_op) {
  312. case ArithmeticOperation::Product:
  313. return right * left;
  314. case ArithmeticOperation::Sum:
  315. return right + left;
  316. case ArithmeticOperation::Difference:
  317. return left - right;
  318. case ArithmeticOperation::Quotient:
  319. return left / right;
  320. case ArithmeticOperation::Remainder:
  321. return left % right;
  322. }
  323. ASSERT_NOT_REACHED();
  324. }
  325. virtual String string() const override
  326. {
  327. return String::formatted("{}", integer());
  328. }
  329. virtual Type type() const override
  330. {
  331. return Type::Integer;
  332. }
  333. ArithmeticOperation m_op { ArithmeticOperation::Sum };
  334. NonnullOwnPtr<Expression> m_left, m_right;
  335. };
  336. class StringExpression : public Expression {
  337. public:
  338. enum class StringOperation {
  339. Substring,
  340. Index,
  341. Length,
  342. Match,
  343. };
  344. StringExpression(StringOperation op, NonnullOwnPtr<Expression> string, OwnPtr<Expression> pos_or_chars = {}, OwnPtr<Expression> length = {})
  345. : m_op(op)
  346. , m_str(move(string))
  347. , m_pos_or_chars(move(pos_or_chars))
  348. , m_length(move(length))
  349. {
  350. }
  351. private:
  352. virtual bool truth() const override { return integer() != 0; }
  353. virtual int integer() const override
  354. {
  355. if (m_op == StringOperation::Substring || m_op == StringOperation::Match) {
  356. auto substr = string();
  357. if (auto integer = substr.to_int(); integer.has_value())
  358. return integer.value();
  359. else
  360. fail("Not an integer: '{}'", substr);
  361. }
  362. if (m_op == StringOperation::Index) {
  363. if (auto idx = m_str->string().index_of(m_pos_or_chars->string()); idx.has_value())
  364. return idx.value() + 1;
  365. return 0;
  366. }
  367. if (m_op == StringOperation::Length)
  368. return m_str->string().length();
  369. ASSERT_NOT_REACHED();
  370. }
  371. static auto safe_substring(const String& str, int start, int length)
  372. {
  373. if (start < 1 || (size_t)start > str.length())
  374. fail("Index out of range");
  375. --start;
  376. if (str.length() - start < (size_t)length)
  377. fail("Index out of range");
  378. return str.substring(start, length);
  379. }
  380. virtual String string() const override
  381. {
  382. if (m_op == StringOperation::Substring)
  383. return safe_substring(m_str->string(), m_pos_or_chars->integer(), m_length->integer());
  384. if (m_op == StringOperation::Match) {
  385. auto match = m_compiled_regex->match(m_str->string(), PosixFlags::Global);
  386. if (m_compiled_regex->parser_result.capture_groups_count == 0) {
  387. if (!match.success)
  388. return "0";
  389. size_t count = 0;
  390. for (auto& m : match.matches)
  391. count += m.view.length();
  392. return String::number(count);
  393. } else {
  394. if (!match.success)
  395. return "";
  396. StringBuilder result;
  397. for (auto& m : match.capture_group_matches) {
  398. for (auto& e : m)
  399. result.append(e.view.to_string());
  400. }
  401. return result.build();
  402. }
  403. }
  404. return String::number(integer());
  405. }
  406. virtual Type type() const override
  407. {
  408. if (m_op == StringOperation::Substring)
  409. return Type::String;
  410. if (m_op == StringOperation::Match) {
  411. if (!m_pos_or_chars)
  412. fail("'match' expects a string pattern");
  413. ensure_regex();
  414. if (m_compiled_regex->parser_result.capture_groups_count == 0)
  415. return Type::Integer;
  416. return Type::String;
  417. }
  418. return Type::Integer;
  419. }
  420. void ensure_regex() const
  421. {
  422. if (!m_compiled_regex)
  423. m_compiled_regex = make<regex::Regex<PosixExtended>>(m_pos_or_chars->string());
  424. }
  425. StringOperation m_op { StringOperation::Substring };
  426. NonnullOwnPtr<Expression> m_str;
  427. OwnPtr<Expression> m_pos_or_chars, m_length;
  428. mutable OwnPtr<regex::Regex<PosixExtended>> m_compiled_regex;
  429. };
  430. NonnullOwnPtr<Expression> Expression::parse(Queue<StringView>& args, Precedence prec)
  431. {
  432. switch (prec) {
  433. case Or: {
  434. auto left = parse(args, And);
  435. while (!args.is_empty() && args.head() == "|") {
  436. args.dequeue();
  437. auto right = parse(args, And);
  438. left = make<BooleanExpression>(BooleanExpression::BooleanOperator::Or, move(left), move(right));
  439. }
  440. return left;
  441. }
  442. case And: {
  443. auto left = parse(args, Comp);
  444. while (!args.is_empty() && args.head() == "&") {
  445. args.dequeue();
  446. auto right = parse(args, Comp);
  447. left = make<BooleanExpression>(BooleanExpression::BooleanOperator::And, move(left), move(right));
  448. }
  449. return left;
  450. }
  451. case Comp: {
  452. auto left = parse(args, ArithS);
  453. while (!args.is_empty() && args.head().is_one_of("<", "<=", "=", "!=", "=>", ">")) {
  454. auto op = args.dequeue();
  455. auto right = parse(args, ArithM);
  456. left = make<ComparisonExpression>(ComparisonExpression::op_from(op), move(left), move(right));
  457. }
  458. return left;
  459. }
  460. case ArithS: {
  461. auto left = parse(args, ArithM);
  462. while (!args.is_empty() && args.head().is_one_of("+", "-")) {
  463. auto op = args.dequeue();
  464. auto right = parse(args, ArithM);
  465. left = make<ArithmeticExpression>(ArithmeticExpression::op_from(op), move(left), move(right));
  466. }
  467. return left;
  468. }
  469. case ArithM: {
  470. auto left = parse(args, StringO);
  471. while (!args.is_empty() && args.head().is_one_of("*", "/", "%")) {
  472. auto op = args.dequeue();
  473. auto right = parse(args, StringO);
  474. left = make<ArithmeticExpression>(ArithmeticExpression::op_from(op), move(left), move(right));
  475. }
  476. return left;
  477. }
  478. case StringO: {
  479. if (args.is_empty())
  480. fail("Expected a term");
  481. OwnPtr<Expression> left;
  482. while (!args.is_empty()) {
  483. auto& op = args.head();
  484. if (op == "+") {
  485. args.dequeue();
  486. left = make<ValueExpression>(args.dequeue());
  487. } else if (op == "substr") {
  488. args.dequeue();
  489. auto str = parse(args, Paren);
  490. auto pos = parse(args, Paren);
  491. auto len = parse(args, Paren);
  492. left = make<StringExpression>(StringExpression::StringOperation::Substring, move(str), move(pos), move(len));
  493. } else if (op == "index") {
  494. args.dequeue();
  495. auto str = parse(args, Paren);
  496. auto chars = parse(args, Paren);
  497. left = make<StringExpression>(StringExpression::StringOperation::Index, move(str), move(chars));
  498. } else if (op == "match") {
  499. args.dequeue();
  500. auto str = parse(args, Paren);
  501. auto pattern = parse(args, Paren);
  502. left = make<StringExpression>(StringExpression::StringOperation::Match, move(str), move(pattern));
  503. } else if (op == "length") {
  504. args.dequeue();
  505. auto str = parse(args, Paren);
  506. left = make<StringExpression>(StringExpression::StringOperation::Length, move(str));
  507. } else if (!left) {
  508. left = parse(args, Paren);
  509. }
  510. if (!args.is_empty() && args.head() == ":") {
  511. args.dequeue();
  512. auto right = parse(args, Paren);
  513. left = make<StringExpression>(StringExpression::StringOperation::Match, left.release_nonnull(), move(right));
  514. } else {
  515. return left.release_nonnull();
  516. }
  517. }
  518. return left.release_nonnull();
  519. }
  520. case Paren: {
  521. if (args.is_empty())
  522. fail("Expected a term");
  523. if (args.head() == "(") {
  524. args.dequeue();
  525. auto expr = parse(args);
  526. if (args.head() != ")")
  527. fail("Expected a close paren");
  528. args.dequeue();
  529. return expr;
  530. }
  531. return make<ValueExpression>(args.dequeue());
  532. }
  533. }
  534. fail("Invalid expression");
  535. }
  536. int main(int argc, char** argv)
  537. {
  538. if (pledge("stdio", nullptr) < 0) {
  539. perror("pledge");
  540. return 1;
  541. }
  542. if (unveil(nullptr, nullptr) < 0) {
  543. perror("unveil");
  544. return 1;
  545. }
  546. if ((argc == 2 && StringView { "--help" } == argv[1]) || argc == 1)
  547. print_help_and_exit();
  548. Queue<StringView> args;
  549. for (int i = 1; i < argc; ++i)
  550. args.enqueue(argv[i]);
  551. auto expression = Expression::parse(args);
  552. if (!args.is_empty())
  553. fail("Extra tokens at the end of the expression");
  554. switch (expression->type()) {
  555. case Expression::Type::Integer:
  556. outln("{}", expression->integer());
  557. break;
  558. case Expression::Type::String:
  559. outln("{}", expression->string());
  560. break;
  561. }
  562. return 0;
  563. }