ExpressionParser.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  1. // Copyright 2013 Dolphin Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "InputCommon/ControlReference/ExpressionParser.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <cmath>
  7. #include <functional>
  8. #include <map>
  9. #include <memory>
  10. #include <regex>
  11. #include <string>
  12. #include <utility>
  13. #include <vector>
  14. #include "Common/MsgHandler.h"
  15. #include "Common/StringUtil.h"
  16. #include "InputCommon/ControlReference/FunctionExpression.h"
  17. namespace ciface::ExpressionParser
  18. {
  19. using namespace ciface::Core;
  20. class ControlExpression;
  21. // Check if operator is usable with assignment, e.g. += -= *=
  22. static bool IsCompoundAssignmentUsableBinaryOperator(TokenType type)
  23. {
  24. return type >= TOK_COMPOUND_ASSIGN_OPS_BEGIN && type < TOK_COMPOUND_ASSIGN_OPS_END;
  25. }
  26. static TokenType GetBinaryOperatorTokenTypeFromChar(char c)
  27. {
  28. switch (c)
  29. {
  30. case '+':
  31. return TOK_ADD;
  32. case '-':
  33. return TOK_SUB;
  34. case '*':
  35. return TOK_MUL;
  36. case '/':
  37. return TOK_DIV;
  38. case '%':
  39. return TOK_MOD;
  40. case '=':
  41. return TOK_ASSIGN;
  42. case '<':
  43. return TOK_LTHAN;
  44. case '>':
  45. return TOK_GTHAN;
  46. case ',':
  47. return TOK_COMMA;
  48. case '^':
  49. return TOK_XOR;
  50. case '&':
  51. return TOK_AND;
  52. case '|':
  53. return TOK_OR;
  54. default:
  55. return TOK_INVALID;
  56. }
  57. }
  58. class HotkeySuppressions
  59. {
  60. public:
  61. using Modifiers = std::vector<std::unique_ptr<ControlExpression>>;
  62. struct InvokingDeleter
  63. {
  64. template <typename T>
  65. void operator()(T* func)
  66. {
  67. (*func)();
  68. delete func;
  69. }
  70. };
  71. using Suppressor = std::unique_ptr<std::function<void()>, InvokingDeleter>;
  72. bool IsSuppressed(Device::Input* input) const
  73. {
  74. // Input is suppressed if it exists in the map at all.
  75. return m_suppressions.lower_bound({input, nullptr}) !=
  76. m_suppressions.lower_bound({input + 1, nullptr});
  77. }
  78. bool IsSuppressedIgnoringModifiers(Device::Input* input, const Modifiers& ignore_modifiers) const;
  79. // Suppresses each input + modifier pair.
  80. // The returned object removes the suppression on destruction.
  81. Suppressor MakeSuppressor(const Modifiers* modifiers,
  82. const std::unique_ptr<ControlExpression>* final_input);
  83. private:
  84. using Suppression = std::pair<Device::Input*, Device::Input*>;
  85. using SuppressionLevel = u16;
  86. void RemoveSuppression(Device::Input* modifier, Device::Input* final_input)
  87. {
  88. auto it = m_suppressions.find({final_input, modifier});
  89. if (it != m_suppressions.end() && (--it->second) == 0)
  90. m_suppressions.erase(it);
  91. }
  92. // Holds counts of suppressions for each input/modifier pair.
  93. std::map<Suppression, SuppressionLevel> m_suppressions;
  94. };
  95. static HotkeySuppressions s_hotkey_suppressions;
  96. Token::Token(TokenType type_) : type(type_)
  97. {
  98. }
  99. Token::Token(TokenType type_, std::string data_) : type(type_), data(std::move(data_))
  100. {
  101. }
  102. bool Token::IsBinaryOperator() const
  103. {
  104. return type >= TOK_BINARY_OPS_BEGIN && type < TOK_BINARY_OPS_END;
  105. }
  106. Lexer::Lexer(std::string expr_) : expr(std::move(expr_))
  107. {
  108. it = expr.begin();
  109. }
  110. Token Lexer::GetDelimitedToken(TokenType type, char delimeter)
  111. {
  112. const std::string value = FetchCharsWhile([&](char c) { return c != delimeter && c != '\n'; });
  113. if (it == expr.end() || *it != delimeter)
  114. return Token(TOK_INVALID);
  115. ++it;
  116. return Token(type, value);
  117. }
  118. std::string Lexer::FetchWordChars()
  119. {
  120. return FetchCharsWhile([](char c) {
  121. return std::isalpha(c, std::locale::classic()) || std::isdigit(c, std::locale::classic()) ||
  122. c == '_';
  123. });
  124. }
  125. Token Lexer::GetDelimitedLiteral()
  126. {
  127. return GetDelimitedToken(TOK_LITERAL, '\'');
  128. }
  129. Token Lexer::GetVariable()
  130. {
  131. return Token(TOK_VARIABLE, FetchWordChars());
  132. }
  133. Token Lexer::GetFullyQualifiedControl()
  134. {
  135. return GetDelimitedToken(TOK_CONTROL, '`');
  136. }
  137. Token Lexer::GetBareword(char first_char)
  138. {
  139. return Token(TOK_BAREWORD, first_char + FetchWordChars());
  140. }
  141. Token Lexer::GetRealLiteral(char first_char)
  142. {
  143. std::string value;
  144. value += first_char;
  145. value += FetchCharsWhile([](char c) { return isdigit(c, std::locale::classic()) || ('.' == c); });
  146. static const std::regex re(R"(\d+(\.\d+)?)");
  147. if (std::regex_match(value, re))
  148. return Token(TOK_LITERAL, value);
  149. return Token(TOK_INVALID);
  150. }
  151. Token Lexer::PeekToken()
  152. {
  153. const auto old_it = it;
  154. const auto tok = NextToken();
  155. it = old_it;
  156. return tok;
  157. }
  158. Token Lexer::NextToken()
  159. {
  160. if (it == expr.end())
  161. return Token(TOK_EOF);
  162. const char c = *it++;
  163. // Handle /* */ style comments.
  164. if (c == '/' && it != expr.end() && *it == '*')
  165. {
  166. ++it;
  167. const auto end_of_comment = expr.find("*/", it - expr.begin());
  168. if (end_of_comment == std::string::npos)
  169. return Token(TOK_INVALID);
  170. it = expr.begin() + end_of_comment + 2;
  171. return Token(TOK_COMMENT);
  172. }
  173. const auto tok_type = GetBinaryOperatorTokenTypeFromChar(c);
  174. if (tok_type != TOK_INVALID)
  175. {
  176. // Check for compound assignment op, e.g. + immediately followed by =.
  177. if (IsCompoundAssignmentUsableBinaryOperator(tok_type) && it != expr.end() && *it == '=')
  178. {
  179. ++it;
  180. return Token(TOK_ASSIGN, std::string{c});
  181. }
  182. return Token(tok_type);
  183. }
  184. switch (c)
  185. {
  186. case ' ':
  187. case '\t':
  188. case '\n':
  189. case '\r':
  190. return Token(TOK_WHITESPACE);
  191. case '(':
  192. return Token(TOK_LPAREN);
  193. case ')':
  194. return Token(TOK_RPAREN);
  195. case '@':
  196. return Token(TOK_HOTKEY);
  197. case '?':
  198. return Token(TOK_QUESTION);
  199. case ':':
  200. return Token(TOK_COLON);
  201. case '!':
  202. return Token(TOK_NOT);
  203. case '\'':
  204. return GetDelimitedLiteral();
  205. case '$':
  206. return GetVariable();
  207. case '`':
  208. return GetFullyQualifiedControl();
  209. default:
  210. if (isalpha(c, std::locale::classic()))
  211. return GetBareword(c);
  212. else if (isdigit(c, std::locale::classic()))
  213. return GetRealLiteral(c);
  214. else
  215. return Token(TOK_INVALID);
  216. }
  217. }
  218. ParseStatus Lexer::Tokenize(std::vector<Token>& tokens)
  219. {
  220. while (true)
  221. {
  222. const std::string::iterator prev_it = it;
  223. Token tok = NextToken();
  224. tok.string_position = prev_it - expr.begin();
  225. tok.string_length = it - prev_it;
  226. tokens.push_back(tok);
  227. if (tok.type == TOK_INVALID)
  228. return ParseStatus::SyntaxError;
  229. if (tok.type == TOK_EOF)
  230. break;
  231. }
  232. return ParseStatus::Successful;
  233. }
  234. Expression* Expression::GetLValue()
  235. {
  236. return this;
  237. }
  238. class ControlExpression : public Expression
  239. {
  240. public:
  241. explicit ControlExpression(ControlQualifier qualifier) : m_qualifier(std::move(qualifier)) {}
  242. ControlState GetValue() override
  243. {
  244. if (s_hotkey_suppressions.IsSuppressed(m_input))
  245. return 0;
  246. return GetValueIgnoringSuppression();
  247. }
  248. ControlState GetValueIgnoringSuppression() const
  249. {
  250. if (!m_input)
  251. return 0.0;
  252. // Note: Inputs may return negative values in situations where opposing directions are
  253. // activated. We clamp off the negative values here.
  254. // FYI: Clamping values greater than 1.0 is purposely not done to support unbounded values in
  255. // the future. (e.g. raw accelerometer/gyro data)
  256. return std::max(0.0, m_input->GetState());
  257. }
  258. void SetValue(ControlState value) override
  259. {
  260. if (m_output)
  261. m_output->SetState(value);
  262. }
  263. int CountNumControls() const override { return (m_input || m_output) ? 1 : 0; }
  264. void UpdateReferences(ControlEnvironment& env) override
  265. {
  266. m_device = env.FindDevice(m_qualifier);
  267. m_input = env.FindInput(m_qualifier);
  268. m_output = env.FindOutput(m_qualifier);
  269. }
  270. Device::Input* GetInput() const { return m_input; }
  271. private:
  272. // Keep a shared_ptr to the device so the control pointer doesn't become invalid.
  273. std::shared_ptr<Device> m_device;
  274. ControlQualifier m_qualifier;
  275. Device::Input* m_input = nullptr;
  276. Device::Output* m_output = nullptr;
  277. };
  278. bool HotkeySuppressions::IsSuppressedIgnoringModifiers(Device::Input* input,
  279. const Modifiers& ignore_modifiers) const
  280. {
  281. // Input is suppressed if it exists in the map with a modifier that we aren't ignoring.
  282. auto it = m_suppressions.lower_bound({input, nullptr});
  283. auto it_end = m_suppressions.lower_bound({input + 1, nullptr});
  284. // We need to ignore L_Ctrl R_Ctrl when supplied Ctrl and vice-versa.
  285. const auto is_same_modifier = [](Device::Input* i1, Device::Input* i2) {
  286. return i1 && i2 && (i1 == i2 || i1->IsChild(i2) || i2->IsChild(i1));
  287. };
  288. return std::any_of(it, it_end, [&](const auto& s) {
  289. return std::ranges::none_of(ignore_modifiers, [&](const auto& m) {
  290. return is_same_modifier(m->GetInput(), s.first.second);
  291. });
  292. });
  293. }
  294. HotkeySuppressions::Suppressor
  295. HotkeySuppressions::MakeSuppressor(const Modifiers* modifiers,
  296. const std::unique_ptr<ControlExpression>* final_input)
  297. {
  298. for (auto& modifier : *modifiers)
  299. {
  300. // Inputs might be null, don't add nullptr to the map
  301. if ((*final_input)->GetInput() && modifier->GetInput())
  302. {
  303. ++m_suppressions[{(*final_input)->GetInput(), modifier->GetInput()}];
  304. }
  305. }
  306. return Suppressor(std::make_unique<std::function<void()>>([this, modifiers, final_input]() {
  307. for (auto& modifier : *modifiers)
  308. RemoveSuppression(modifier->GetInput(), (*final_input)->GetInput());
  309. }).release(),
  310. InvokingDeleter{});
  311. }
  312. class BinaryExpression : public Expression
  313. {
  314. public:
  315. TokenType op;
  316. std::unique_ptr<Expression> lhs;
  317. std::unique_ptr<Expression> rhs;
  318. BinaryExpression(TokenType op_, std::unique_ptr<Expression>&& lhs_,
  319. std::unique_ptr<Expression>&& rhs_)
  320. : op(op_), lhs(std::move(lhs_)), rhs(std::move(rhs_))
  321. {
  322. }
  323. ControlState GetValue() override
  324. {
  325. if (op == TOK_ASSIGN || op == TOK_COMMA)
  326. {
  327. return GetLValue()->GetValue();
  328. }
  329. // Strict evaluation order of lhs,rhs in case of side effects.
  330. const ControlState lhs_value = lhs->GetValue();
  331. const ControlState rhs_value = rhs->GetValue();
  332. return CalculateValue(op, lhs_value, rhs_value);
  333. }
  334. static ControlState CalculateValue(TokenType op, ControlState lhs_value, ControlState rhs_value)
  335. {
  336. switch (op)
  337. {
  338. case TOK_AND:
  339. return std::min(lhs_value, rhs_value);
  340. case TOK_OR:
  341. return std::max(lhs_value, rhs_value);
  342. case TOK_ADD:
  343. return lhs_value + rhs_value;
  344. case TOK_SUB:
  345. return lhs_value - rhs_value;
  346. case TOK_MUL:
  347. return lhs_value * rhs_value;
  348. case TOK_DIV:
  349. {
  350. const ControlState result = lhs_value / rhs_value;
  351. return std::isinf(result) ? 0.0 : result;
  352. }
  353. case TOK_MOD:
  354. {
  355. const ControlState result = std::fmod(lhs_value, rhs_value);
  356. return std::isnan(result) ? 0.0 : result;
  357. }
  358. case TOK_LTHAN:
  359. return lhs_value < rhs_value;
  360. case TOK_GTHAN:
  361. return lhs_value > rhs_value;
  362. case TOK_XOR:
  363. return std::max(std::min(1 - lhs_value, rhs_value), std::min(lhs_value, 1 - rhs_value));
  364. default:
  365. assert(false);
  366. return 0;
  367. }
  368. }
  369. Expression* GetLValue() override
  370. {
  371. switch (op)
  372. {
  373. case TOK_ASSIGN:
  374. {
  375. Expression* const lvalue = lhs->GetLValue();
  376. const ControlState rvalue = rhs->GetValue();
  377. lvalue->SetValue(rvalue);
  378. return lvalue;
  379. }
  380. case TOK_COMMA:
  381. lhs->GetValue();
  382. return rhs->GetLValue();
  383. default:
  384. return this;
  385. }
  386. }
  387. void SetValue(ControlState value) override
  388. {
  389. // Don't do anything special with the op we have.
  390. // Treat "A & B" the same as "A | B".
  391. lhs->SetValue(value);
  392. rhs->SetValue(value);
  393. }
  394. int CountNumControls() const override
  395. {
  396. return lhs->CountNumControls() + rhs->CountNumControls();
  397. }
  398. void UpdateReferences(ControlEnvironment& env) override
  399. {
  400. lhs->UpdateReferences(env);
  401. rhs->UpdateReferences(env);
  402. }
  403. };
  404. class CompoundAssignmentExpression : public BinaryExpression
  405. {
  406. public:
  407. using BinaryExpression::BinaryExpression;
  408. ControlState GetValue() override { return GetLValue()->GetValue(); }
  409. Expression* GetLValue() override
  410. {
  411. Expression* const lvalue = lhs->GetLValue();
  412. const ControlState lhs_value = lvalue->GetValue();
  413. const ControlState rhs_value = rhs->GetValue();
  414. lvalue->SetValue(CalculateValue(op, lhs_value, rhs_value));
  415. return lvalue;
  416. }
  417. };
  418. class LiteralExpression : public Expression
  419. {
  420. public:
  421. void SetValue(ControlState) override
  422. {
  423. // Do nothing.
  424. }
  425. int CountNumControls() const override { return 1; }
  426. void UpdateReferences(ControlEnvironment&) override
  427. {
  428. // Nothing needed.
  429. }
  430. protected:
  431. virtual std::string GetName() const = 0;
  432. };
  433. class LiteralReal : public LiteralExpression
  434. {
  435. public:
  436. explicit LiteralReal(ControlState value) : m_value(value) {}
  437. ControlState GetValue() override { return m_value; }
  438. std::string GetName() const override { return ValueToString(m_value); }
  439. private:
  440. const ControlState m_value{};
  441. };
  442. static ParseResult MakeLiteralExpression(const Token& token)
  443. {
  444. ControlState val{};
  445. if (TryParse(token.data, &val))
  446. return ParseResult::MakeSuccessfulResult(std::make_unique<LiteralReal>(val));
  447. else
  448. return ParseResult::MakeErrorResult(token, Common::GetStringT("Invalid literal."));
  449. }
  450. class VariableExpression : public Expression
  451. {
  452. public:
  453. explicit VariableExpression(std::string name) : m_name(std::move(name)) {}
  454. ControlState GetValue() override { return m_variable_ptr ? *m_variable_ptr : 0; }
  455. void SetValue(ControlState value) override
  456. {
  457. if (m_variable_ptr)
  458. *m_variable_ptr = value;
  459. }
  460. int CountNumControls() const override { return 1; }
  461. void UpdateReferences(ControlEnvironment& env) override
  462. {
  463. m_variable_ptr = env.GetVariablePtr(m_name);
  464. }
  465. protected:
  466. const std::string m_name;
  467. std::shared_ptr<ControlState> m_variable_ptr;
  468. };
  469. class HotkeyExpression : public Expression
  470. {
  471. public:
  472. explicit HotkeyExpression(std::vector<std::unique_ptr<ControlExpression>> inputs)
  473. : m_modifiers(std::move(inputs))
  474. {
  475. m_final_input = std::move(m_modifiers.back());
  476. m_modifiers.pop_back();
  477. }
  478. ControlState GetValue() override
  479. {
  480. // True if we have no modifiers
  481. const bool modifiers_pressed = std::ranges::all_of(
  482. m_modifiers, [](const auto& input) { return input->GetValue() > CONDITION_THRESHOLD; });
  483. const auto final_input_state = m_final_input->GetValueIgnoringSuppression();
  484. if (modifiers_pressed)
  485. {
  486. // Ignore suppression of our own modifiers. This also allows superset modifiers to function.
  487. const bool is_suppressed = s_hotkey_suppressions.IsSuppressedIgnoringModifiers(
  488. m_final_input->GetInput(), m_modifiers);
  489. if (final_input_state <= CONDITION_THRESHOLD)
  490. m_is_blocked = false;
  491. // If some other hotkey suppressed us, require a release of final input to be ready again.
  492. if (is_suppressed)
  493. m_is_blocked = true;
  494. if (m_is_blocked)
  495. return 0;
  496. EnableSuppression();
  497. // Our modifiers are active. Pass through the final input.
  498. return final_input_state;
  499. }
  500. else
  501. {
  502. m_suppressor = {};
  503. m_is_blocked = final_input_state > CONDITION_THRESHOLD;
  504. }
  505. return 0;
  506. }
  507. void SetValue(ControlState) override {}
  508. int CountNumControls() const override
  509. {
  510. int result = 0;
  511. for (auto& input : m_modifiers)
  512. result += input->CountNumControls();
  513. return result + m_final_input->CountNumControls();
  514. }
  515. void UpdateReferences(ControlEnvironment& env) override
  516. {
  517. for (auto& input : m_modifiers)
  518. input->UpdateReferences(env);
  519. m_final_input->UpdateReferences(env);
  520. // We must update our suppression with valid pointers.
  521. if (m_suppressor)
  522. EnableSuppression(true);
  523. }
  524. private:
  525. void EnableSuppression(bool force = false)
  526. {
  527. if (!m_suppressor || force)
  528. m_suppressor = s_hotkey_suppressions.MakeSuppressor(&m_modifiers, &m_final_input);
  529. }
  530. HotkeySuppressions::Modifiers m_modifiers;
  531. std::unique_ptr<ControlExpression> m_final_input;
  532. HotkeySuppressions::Suppressor m_suppressor;
  533. bool m_is_blocked = false;
  534. };
  535. // This class proxies all methods to its either left-hand child if it has bound controls, or its
  536. // right-hand child. Its intended use is for supporting old-style barewords expressions.
  537. // Note that if you have a keyboard device as default device and the expression is a single digit
  538. // number, this will usually resolve in a numerical key instead of a numerical value.
  539. // Though if this expression belongs to NumericSetting, it will likely be simplifed back to a value.
  540. class CoalesceExpression : public Expression
  541. {
  542. public:
  543. CoalesceExpression(std::unique_ptr<Expression>&& lhs, std::unique_ptr<Expression>&& rhs)
  544. : m_lhs(std::move(lhs)), m_rhs(std::move(rhs))
  545. {
  546. }
  547. ControlState GetValue() override { return GetActiveChild()->GetValue(); }
  548. void SetValue(ControlState value) override { GetActiveChild()->SetValue(value); }
  549. int CountNumControls() const override { return GetActiveChild()->CountNumControls(); }
  550. void UpdateReferences(ControlEnvironment& env) override
  551. {
  552. m_lhs->UpdateReferences(env);
  553. m_rhs->UpdateReferences(env);
  554. }
  555. private:
  556. const std::unique_ptr<Expression>& GetActiveChild() const
  557. {
  558. return m_lhs->CountNumControls() > 0 ? m_lhs : m_rhs;
  559. }
  560. std::unique_ptr<Expression> m_lhs;
  561. std::unique_ptr<Expression> m_rhs;
  562. };
  563. std::shared_ptr<Device> ControlEnvironment::FindDevice(const ControlQualifier& qualifier) const
  564. {
  565. if (qualifier.has_device)
  566. return container.FindDevice(qualifier.device_qualifier);
  567. else
  568. return container.FindDevice(default_device);
  569. }
  570. Device::Input* ControlEnvironment::FindInput(const ControlQualifier& qualifier) const
  571. {
  572. const std::shared_ptr<Device> device = FindDevice(qualifier);
  573. if (!device)
  574. return nullptr;
  575. return device->FindInput(qualifier.control_name);
  576. }
  577. Device::Output* ControlEnvironment::FindOutput(const ControlQualifier& qualifier) const
  578. {
  579. const std::shared_ptr<Device> device = FindDevice(qualifier);
  580. if (!device)
  581. return nullptr;
  582. return device->FindOutput(qualifier.control_name);
  583. }
  584. std::shared_ptr<ControlState> ControlEnvironment::GetVariablePtr(const std::string& name)
  585. {
  586. // Do not accept an empty string as key, even if the expression parser already prevents this case.
  587. if (name.empty())
  588. return nullptr;
  589. std::shared_ptr<ControlState>& variable = m_variables[name];
  590. // If new, make a shared ptr
  591. if (!variable)
  592. {
  593. variable = std::make_shared<ControlState>();
  594. }
  595. return variable;
  596. }
  597. void ControlEnvironment::CleanUnusedVariables()
  598. {
  599. for (auto it = m_variables.begin(); it != m_variables.end();)
  600. {
  601. // Don't count ourselves as reference
  602. if (it->second.use_count() <= 1)
  603. m_variables.erase(it++);
  604. else
  605. ++it;
  606. }
  607. }
  608. ParseResult ParseResult::MakeEmptyResult()
  609. {
  610. ParseResult result;
  611. result.status = ParseStatus::EmptyExpression;
  612. return result;
  613. }
  614. ParseResult ParseResult::MakeSuccessfulResult(std::unique_ptr<Expression>&& expr)
  615. {
  616. ParseResult result;
  617. result.status = ParseStatus::Successful;
  618. result.expr = std::move(expr);
  619. return result;
  620. }
  621. ParseResult ParseResult::MakeErrorResult(Token token, std::string description)
  622. {
  623. ParseResult result;
  624. result.status = ParseStatus::SyntaxError;
  625. result.token = std::move(token);
  626. result.description = std::move(description);
  627. return result;
  628. }
  629. static bool IsInertToken(const Token& tok)
  630. {
  631. return tok.type == TOK_COMMENT || tok.type == TOK_WHITESPACE;
  632. }
  633. class Parser
  634. {
  635. public:
  636. explicit Parser(const std::vector<Token>& tokens_) : tokens(tokens_) { m_it = tokens.begin(); }
  637. ParseResult Parse()
  638. {
  639. ParseResult result = ParseToplevel();
  640. if (ParseStatus::Successful != result.status)
  641. return result;
  642. if (Peek().type == TOK_EOF)
  643. return result;
  644. return ParseResult::MakeErrorResult(Peek(), Common::GetStringT("Expected end of expression."));
  645. }
  646. private:
  647. const std::vector<Token>& tokens;
  648. std::vector<Token>::const_iterator m_it;
  649. Token Chew()
  650. {
  651. const Token tok = Peek();
  652. if (TOK_EOF != tok.type)
  653. ++m_it;
  654. return tok;
  655. }
  656. Token Peek()
  657. {
  658. while (IsInertToken(*m_it))
  659. ++m_it;
  660. return *m_it;
  661. }
  662. bool Expects(TokenType type)
  663. {
  664. Token tok = Chew();
  665. return tok.type == type;
  666. }
  667. ParseResult ParseFunctionArguments(const std::string_view& func_name,
  668. std::unique_ptr<FunctionExpression>&& func,
  669. const Token& func_tok)
  670. {
  671. std::vector<std::unique_ptr<Expression>> args;
  672. if (TOK_LPAREN != Peek().type)
  673. {
  674. // Single argument with no parens (useful for unary ! function)
  675. const auto tok = Chew();
  676. auto arg = ParseAtom(tok);
  677. if (ParseStatus::Successful != arg.status)
  678. return arg;
  679. args.emplace_back(std::move(arg.expr));
  680. }
  681. else
  682. {
  683. // Chew the L-Paren
  684. Chew();
  685. // Check for empty argument list:
  686. if (TOK_RPAREN == Peek().type)
  687. {
  688. Chew();
  689. }
  690. else
  691. {
  692. while (true)
  693. {
  694. // Read one argument.
  695. // Grab an expression, but stop at comma.
  696. auto arg = ParseInfixOperations(OperatorPrecedence(TOK_COMMA));
  697. if (ParseStatus::Successful != arg.status)
  698. return arg;
  699. args.emplace_back(std::move(arg.expr));
  700. // Right paren is the end of our arguments.
  701. const Token tok = Chew();
  702. if (TOK_RPAREN == tok.type)
  703. break;
  704. // Comma before the next argument.
  705. if (TOK_COMMA != tok.type)
  706. return ParseResult::MakeErrorResult(tok, Common::GetStringT("Expected closing paren."));
  707. };
  708. }
  709. }
  710. func->SetArguments(std::move(args));
  711. const auto argument_validation = func->ValidateArguments();
  712. if (std::holds_alternative<FunctionExpression::ExpectedArguments>(argument_validation))
  713. {
  714. const auto text = std::string(func_name) + '(' +
  715. std::get<FunctionExpression::ExpectedArguments>(argument_validation).text +
  716. ')';
  717. return ParseResult::MakeErrorResult(func_tok,
  718. Common::FmtFormatT("Expected arguments: {0}", text));
  719. }
  720. return ParseResult::MakeSuccessfulResult(std::move(func));
  721. }
  722. ParseResult ParseAtom(const Token& tok)
  723. {
  724. switch (tok.type)
  725. {
  726. case TOK_BAREWORD:
  727. {
  728. auto func = MakeFunctionExpression(tok.data);
  729. if (!func)
  730. {
  731. // Invalid function, interpret this as a bareword control.
  732. Token control_tok(tok);
  733. control_tok.type = TOK_CONTROL;
  734. return ParseAtom(control_tok);
  735. }
  736. return ParseFunctionArguments(tok.data, std::move(func), tok);
  737. }
  738. case TOK_CONTROL:
  739. {
  740. ControlQualifier cq;
  741. cq.FromString(tok.data);
  742. return ParseResult::MakeSuccessfulResult(std::make_unique<ControlExpression>(cq));
  743. }
  744. case TOK_NOT:
  745. {
  746. return ParseFunctionArguments("not", MakeFunctionExpression("not"), tok);
  747. }
  748. case TOK_LITERAL:
  749. {
  750. return MakeLiteralExpression(tok);
  751. }
  752. case TOK_VARIABLE:
  753. {
  754. if (tok.data.empty())
  755. return ParseResult::MakeErrorResult(tok, Common::GetStringT("Expected variable name."));
  756. else
  757. return ParseResult::MakeSuccessfulResult(std::make_unique<VariableExpression>(tok.data));
  758. }
  759. case TOK_LPAREN:
  760. {
  761. return ParseParens();
  762. }
  763. case TOK_HOTKEY:
  764. {
  765. return ParseHotkeys();
  766. }
  767. case TOK_SUB:
  768. {
  769. // An atom was expected but we got a subtraction symbol.
  770. // Interpret it as a unary minus function.
  771. return ParseFunctionArguments("minus", MakeFunctionExpression("minus"), tok);
  772. }
  773. case TOK_ADD:
  774. {
  775. // An atom was expected but we got an addition symbol.
  776. // Interpret it as a unary plus.
  777. return ParseFunctionArguments("plus", MakeFunctionExpression("plus"), tok);
  778. }
  779. default:
  780. {
  781. return ParseResult::MakeErrorResult(tok, Common::GetStringT("Expected start of expression."));
  782. }
  783. }
  784. }
  785. static constexpr int OperatorPrecedence(TokenType type = TOK_EOF)
  786. {
  787. switch (type)
  788. {
  789. case TOK_MUL:
  790. case TOK_DIV:
  791. case TOK_MOD:
  792. return 1;
  793. case TOK_ADD:
  794. case TOK_SUB:
  795. return 2;
  796. case TOK_GTHAN:
  797. case TOK_LTHAN:
  798. return 3;
  799. case TOK_AND:
  800. return 4;
  801. case TOK_XOR:
  802. return 5;
  803. case TOK_OR:
  804. return 6;
  805. case TOK_ASSIGN:
  806. case TOK_QUESTION:
  807. return 7;
  808. case TOK_COMMA:
  809. return 8;
  810. default:
  811. return 999;
  812. }
  813. }
  814. static bool IsRTLBinaryOp(TokenType type) { return type == TOK_ASSIGN; }
  815. static bool IsBinaryOpWithPrecedence(Token tok, int precedence)
  816. {
  817. if (!tok.IsBinaryOperator())
  818. return false;
  819. const int tok_precedence = OperatorPrecedence(tok.type);
  820. return (tok_precedence < precedence) ||
  821. (IsRTLBinaryOp(tok.type) && tok_precedence <= precedence);
  822. }
  823. ParseResult ParseInfixOperations(int precedence = OperatorPrecedence())
  824. {
  825. ParseResult lhs = ParseAtom(Chew());
  826. if (lhs.status == ParseStatus::SyntaxError)
  827. return lhs;
  828. std::unique_ptr<Expression> expr = std::move(lhs.expr);
  829. while (true)
  830. {
  831. const Token op = Peek();
  832. if (IsBinaryOpWithPrecedence(op, precedence))
  833. {
  834. Chew();
  835. ParseResult rhs = ParseInfixOperations(OperatorPrecedence(op.type));
  836. if (rhs.status == ParseStatus::SyntaxError)
  837. return rhs;
  838. // Compound assignment token has operator in the data string.
  839. if (op.type == TOK_ASSIGN && !op.data.empty())
  840. {
  841. const TokenType op_type = GetBinaryOperatorTokenTypeFromChar(op.data[0]);
  842. expr = std::make_unique<CompoundAssignmentExpression>(op_type, std::move(expr),
  843. std::move(rhs.expr));
  844. }
  845. else
  846. {
  847. expr = std::make_unique<BinaryExpression>(op.type, std::move(expr), std::move(rhs.expr));
  848. }
  849. }
  850. else if (op.type == TOK_QUESTION && OperatorPrecedence(TOK_QUESTION) <= precedence)
  851. {
  852. // Handle conditional operator: (a ? b : c)
  853. Chew();
  854. auto true_result = ParseInfixOperations(OperatorPrecedence(op.type));
  855. if (true_result.status != ParseStatus::Successful)
  856. return true_result;
  857. const Token should_be_colon = Chew();
  858. if (should_be_colon.type != TOK_COLON)
  859. return ParseResult::MakeErrorResult(should_be_colon,
  860. Common::GetStringT("Expected colon."));
  861. auto false_result = ParseInfixOperations(OperatorPrecedence(op.type));
  862. if (false_result.status != ParseStatus::Successful)
  863. return false_result;
  864. auto conditional = MakeFunctionExpression("if");
  865. std::vector<std::unique_ptr<Expression>> args;
  866. args.emplace_back(std::move(expr));
  867. args.emplace_back(std::move(true_result.expr));
  868. args.emplace_back(std::move(false_result.expr));
  869. conditional->SetArguments(std::move(args));
  870. expr = std::move(conditional);
  871. }
  872. else
  873. {
  874. break;
  875. }
  876. }
  877. return ParseResult::MakeSuccessfulResult(std::move(expr));
  878. }
  879. ParseResult ParseParens()
  880. {
  881. // lparen already chewed
  882. ParseResult result = ParseToplevel();
  883. if (result.status != ParseStatus::Successful)
  884. return result;
  885. const auto rparen = Chew();
  886. if (rparen.type != TOK_RPAREN)
  887. {
  888. return ParseResult::MakeErrorResult(rparen, Common::GetStringT("Expected closing paren."));
  889. }
  890. return result;
  891. }
  892. ParseResult ParseHotkeys()
  893. {
  894. Token tok = Chew();
  895. if (tok.type != TOK_LPAREN)
  896. return ParseResult::MakeErrorResult(tok, Common::GetStringT("Expected opening paren."));
  897. std::vector<std::unique_ptr<ControlExpression>> inputs;
  898. while (true)
  899. {
  900. tok = Chew();
  901. if (tok.type != TOK_CONTROL && tok.type != TOK_BAREWORD)
  902. return ParseResult::MakeErrorResult(tok, Common::GetStringT("Expected name of input."));
  903. ControlQualifier cq;
  904. cq.FromString(tok.data);
  905. inputs.emplace_back(std::make_unique<ControlExpression>(std::move(cq)));
  906. tok = Chew();
  907. if (tok.type == TOK_ADD)
  908. continue;
  909. if (tok.type == TOK_RPAREN)
  910. break;
  911. return ParseResult::MakeErrorResult(tok, Common::GetStringT("Expected + or closing paren."));
  912. }
  913. return ParseResult::MakeSuccessfulResult(std::make_unique<HotkeyExpression>(std::move(inputs)));
  914. }
  915. ParseResult ParseToplevel() { return ParseInfixOperations(); }
  916. }; // namespace ExpressionParser
  917. ParseResult ParseTokens(const std::vector<Token>& tokens)
  918. {
  919. return Parser(tokens).Parse();
  920. }
  921. static ParseResult ParseComplexExpression(const std::string& str)
  922. {
  923. Lexer l(str);
  924. std::vector<Token> tokens;
  925. const ParseStatus tokenize_status = l.Tokenize(tokens);
  926. if (tokenize_status != ParseStatus::Successful)
  927. return ParseResult::MakeErrorResult(Token(TOK_INVALID),
  928. Common::GetStringT("Tokenizing failed."));
  929. return ParseTokens(tokens);
  930. }
  931. static std::unique_ptr<Expression> ParseBarewordExpression(const std::string& str)
  932. {
  933. ControlQualifier qualifier;
  934. qualifier.control_name = str;
  935. qualifier.has_device = false;
  936. // This control expression will only work (find the specified control) with the default device.
  937. return std::make_unique<ControlExpression>(qualifier);
  938. }
  939. ParseResult ParseExpression(const std::string& str)
  940. {
  941. if (StripWhitespace(str).empty())
  942. return ParseResult::MakeEmptyResult();
  943. auto bareword_expr = ParseBarewordExpression(str);
  944. ParseResult complex_result = ParseComplexExpression(str);
  945. if (complex_result.status != ParseStatus::Successful)
  946. {
  947. // This is a bit odd.
  948. // Return the error status of the complex expression with the fallback barewords expression.
  949. complex_result.expr = std::move(bareword_expr);
  950. return complex_result;
  951. }
  952. complex_result.expr = std::make_unique<CoalesceExpression>(std::move(bareword_expr),
  953. std::move(complex_result.expr));
  954. return complex_result;
  955. }
  956. } // namespace ciface::ExpressionParser