Debian Codegraph @

Source/Core/InputCommon/ControlReference/ExpressionParser.cpp

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