DataParser.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "precompiled.h"
  29. #include "../../Include/RmlUi/Core/DataModel.h"
  30. #include "DataParser.h"
  31. #include <stack>
  32. #ifdef _MSC_VER
  33. #pragma warning(default : 4061)
  34. #pragma warning(default : 4062)
  35. #endif
  36. namespace Rml {
  37. namespace Core {
  38. class Interpreter;
  39. class DataParser;
  40. /*
  41. The abstract machine for RmlUi data scripts.
  42. The machine can execute a program which contains a list of instructions listed below.
  43. The abstract machine has three registers:
  44. R Typically results and right-hand side arguments.
  45. L Typically left-hand side arguments.
  46. C Typically center arguments (eg. in ternary operator).
  47. And two stacks:
  48. S The main program stack.
  49. A The arguments stack, only used to pass arguments to an external transform function.
  50. In addition, each instruction has an optional payload:
  51. D Instruction data (payload).
  52. Notation used in the instruction list below:
  53. S+ Push to stack S.
  54. S- Pop stack S (returns the popped value).
  55. */
  56. enum class Instruction { // Assignment (register/stack) = Read (register R/L/C, instruction data D, or stack)
  57. Push = 'P', // S+ = R
  58. Pop = 'o', // <R/L/C> = S- (D determines R/L/C)
  59. Literal = 'D', // R = D
  60. Variable = 'V', // R = DataModel.GetVariable(D) (D is an index into the variable address list)
  61. Add = '+', // R = L + R
  62. Subtract = '-', // R = L - R
  63. Multiply = '*', // R = L * R
  64. Divide = '/', // R = L / R
  65. Not = '!', // R = !R
  66. And = '&', // R = L && R
  67. Or = '|', // R = L || R
  68. Less = '<', // R = L < R
  69. LessEq = 'L', // R = L <= R
  70. Greater = '>', // R = L > R
  71. GreaterEq = 'G', // R = L >= R
  72. Equal = '=', // R = L == R
  73. NotEqual = 'N', // R = L != R
  74. Ternary = '?', // R = L ? C : R
  75. Arguments = 'a', // A+ = S- (Repeated D times, where D gives the num. arguments)
  76. Function = 'F', // R = DataModel.Execute( D, R, A ); A.Clear(); (D determines function name, R the input value, A the arguments)
  77. };
  78. enum class Register {
  79. R,
  80. L,
  81. C
  82. };
  83. struct InstructionData {
  84. Instruction instruction;
  85. Variant data;
  86. };
  87. namespace Parse {
  88. static void Expression(DataParser& parser);
  89. };
  90. class DataParser {
  91. public:
  92. DataParser(String expression, DataVariableInterface variable_interface = {}) : expression(std::move(expression)), variable_interface(variable_interface) {}
  93. char Look() {
  94. if (reached_end)
  95. return '\0';
  96. return expression[index];
  97. }
  98. bool Match(char c, bool skip_whitespace = true) {
  99. if (c == Look()) {
  100. Next();
  101. if (skip_whitespace)
  102. SkipWhitespace();
  103. return true;
  104. }
  105. Expected(c);
  106. return false;
  107. }
  108. char Next() {
  109. ++index;
  110. if (index >= expression.size())
  111. reached_end = true;
  112. return Look();
  113. }
  114. void SkipWhitespace() {
  115. char c = Look();
  116. while (StringUtilities::IsWhitespace(c))
  117. c = Next();
  118. }
  119. void Error(String message)
  120. {
  121. parse_error = true;
  122. message = CreateString(message.size() + expression.size() + 50, "Error in expression '%s' at %d. %s", expression.c_str(), index, message.c_str());
  123. Log::Message(Log::LT_WARNING, message.c_str());
  124. const size_t cursor_offset = size_t(index) + sizeof("Error in expression ");
  125. const String cursor_string = String(cursor_offset, ' ') + '^';
  126. Log::Message(Log::LT_WARNING, cursor_string.c_str());
  127. }
  128. void Expected(char expected) {
  129. char c = Look();
  130. if (c == '\0')
  131. Error(CreateString(50, "Expected '%c' but found end of string.", expected));
  132. else
  133. Error(CreateString(50, "Expected '%c' but found '%c'.", expected, c));
  134. }
  135. void Expected(String expected_symbols) {
  136. Error(CreateString(expected_symbols.size() + 50, "Expected %s but found character '%c'.", expected_symbols.c_str(), Look()));
  137. }
  138. bool Parse()
  139. {
  140. Log::Message(Log::LT_DEBUG, "Parsing expression: %s", expression.c_str());
  141. program.clear();
  142. variable_addresses.clear();
  143. index = 0;
  144. reached_end = false;
  145. parse_error = false;
  146. SkipWhitespace();
  147. Parse::Expression(*this);
  148. if (!reached_end) {
  149. parse_error = true;
  150. Error(CreateString(50, "Unexpected character '%c' encountered.", Look()));
  151. }
  152. if (!parse_error)
  153. Log::Message(Log::LT_DEBUG, "Finished parsing expression! Instructions: %d Stack depth: %d", program.size(), program_stack_size);
  154. return !parse_error;
  155. }
  156. Program ReleaseProgram() {
  157. RMLUI_ASSERT(!parse_error);
  158. return std::move(program);
  159. }
  160. AddressList ReleaseAddresses() {
  161. RMLUI_ASSERT(!parse_error);
  162. return std::move(variable_addresses);
  163. }
  164. void Emit(Instruction instruction, Variant data = Variant())
  165. {
  166. RMLUI_ASSERTMSG(instruction != Instruction::Push && instruction != Instruction::Pop &&
  167. instruction != Instruction::Arguments && instruction != Instruction::Variable,
  168. "Use the Push(), Pop(), Arguments(), and Variable() procedures for stack manipulation and variable instructions.");
  169. program.push_back(InstructionData{ instruction, std::move(data) });
  170. }
  171. void Push() {
  172. program_stack_size += 1;
  173. program.push_back(InstructionData{ Instruction::Push, Variant() });
  174. }
  175. void Pop(Register destination) {
  176. if (program_stack_size <= 0) {
  177. Error("Internal parser error: Tried to pop an empty stack.");
  178. return;
  179. }
  180. program_stack_size -= 1;
  181. program.push_back(InstructionData{ Instruction::Pop, Variant(int(destination)) });
  182. }
  183. void Arguments(int num_arguments) {
  184. if (program_stack_size < num_arguments) {
  185. Error(CreateString(128, "Internal parser error: Popping %d arguments, but the stack contains only %d elements.", num_arguments, program_stack_size));
  186. return;
  187. }
  188. program_stack_size -= num_arguments;
  189. program.push_back(InstructionData{ Instruction::Arguments, Variant(int(num_arguments)) });
  190. }
  191. void Variable(const String& name) {
  192. Address address = variable_interface.ParseAddress(name);
  193. if (address.empty()) {
  194. Error(CreateString(name.size() + 50, "Invalid variable name '%s'.", name.c_str()));
  195. return;
  196. }
  197. int index = int(variable_addresses.size());
  198. variable_addresses.push_back(std::move(address));
  199. program.push_back(InstructionData{ Instruction::Variable, Variant(int(index)) });
  200. }
  201. private:
  202. const String expression;
  203. DataVariableInterface variable_interface;
  204. size_t index = 0;
  205. bool reached_end = false;
  206. bool parse_error = true;
  207. int program_stack_size = 0;
  208. Program program;
  209. AddressList variable_addresses;
  210. };
  211. namespace Parse {
  212. // Forward declare all parse functions.
  213. static void Expression(DataParser& parser);
  214. static void Factor(DataParser& parser);
  215. static void Term(DataParser& parser);
  216. static void NumberLiteral(DataParser& parser);
  217. static void StringLiteral(DataParser& parser);
  218. static void Variable(DataParser& parser);
  219. static void Add(DataParser& parser);
  220. static void Subtract(DataParser& parser);
  221. static void Multiply(DataParser& parser);
  222. static void Divide(DataParser& parser);
  223. static void Not(DataParser& parser);
  224. static void And(DataParser& parser);
  225. static void Or(DataParser& parser);
  226. static void Less(DataParser& parser);
  227. static void Greater(DataParser& parser);
  228. static void Equal(DataParser& parser);
  229. static void NotEqual(DataParser& parser);
  230. static void Ternary(DataParser& parser);
  231. static void Function(DataParser& parser);
  232. // Helper functions
  233. static bool IsVariableCharacter(char c, bool is_first_character)
  234. {
  235. const bool is_alpha = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
  236. if (is_first_character)
  237. return is_alpha;
  238. if (is_alpha || (c >= '0' && c <= '9'))
  239. return true;
  240. for (char valid_char : "_.[] ")
  241. {
  242. if (c == valid_char && valid_char != '\0')
  243. return true;
  244. }
  245. return false;
  246. }
  247. static String VariableName(DataParser& parser)
  248. {
  249. String name;
  250. bool is_first_character = true;
  251. char c = parser.Look();
  252. while (IsVariableCharacter(c, is_first_character))
  253. {
  254. name += c;
  255. c = parser.Next();
  256. is_first_character = false;
  257. }
  258. // Right trim spaces in name
  259. size_t new_size = String::npos;
  260. for (int i = int(name.size()) - 1; i >= 1; i--)
  261. {
  262. if (name[i] == ' ')
  263. new_size = size_t(i);
  264. else
  265. break;
  266. }
  267. if (new_size != String::npos)
  268. name.resize(new_size);
  269. return name;
  270. }
  271. // Parser functions
  272. static void Expression(DataParser& parser)
  273. {
  274. Term(parser);
  275. bool looping = true;
  276. while (looping)
  277. {
  278. switch (char c = parser.Look())
  279. {
  280. case '+': Add(parser); break;
  281. case '-': Subtract(parser); break;
  282. case '?': Ternary(parser); break;
  283. case '|':
  284. {
  285. parser.Match('|', false);
  286. if (parser.Look() == '|')
  287. Or(parser);
  288. else
  289. {
  290. parser.SkipWhitespace();
  291. Function(parser);
  292. }
  293. }
  294. break;
  295. case '&': And(parser); break;
  296. case '=': Equal(parser); break;
  297. case '!': NotEqual(parser); break;
  298. case '<': Less(parser); break;
  299. case '>': Greater(parser); break;
  300. case '\0':
  301. looping = false;
  302. break;
  303. default:
  304. looping = false;
  305. }
  306. }
  307. }
  308. static void Term(DataParser& parser)
  309. {
  310. Factor(parser);
  311. bool looping = true;
  312. while (looping)
  313. {
  314. switch (const char c = parser.Look())
  315. {
  316. case '*': Multiply(parser); break;
  317. case '/': Divide(parser); break;
  318. case '\0': looping = false; break;
  319. default:
  320. looping = false;
  321. }
  322. }
  323. }
  324. static void Factor(DataParser& parser)
  325. {
  326. const char c = parser.Look();
  327. if (c == '(')
  328. {
  329. parser.Match('(');
  330. Expression(parser);
  331. parser.Match(')');
  332. }
  333. else if (c == '\'')
  334. {
  335. parser.Match('\'', false);
  336. StringLiteral(parser);
  337. parser.Match('\'');
  338. }
  339. else if (c == '!')
  340. {
  341. Not(parser);
  342. parser.SkipWhitespace();
  343. }
  344. else if (c == '-' || (c >= '0' && c <= '9'))
  345. {
  346. NumberLiteral(parser);
  347. parser.SkipWhitespace();
  348. }
  349. else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
  350. {
  351. Variable(parser);
  352. parser.SkipWhitespace();
  353. }
  354. else
  355. parser.Expected("literal, variable name, parenthesis, or '!'");
  356. }
  357. static void NumberLiteral(DataParser& parser)
  358. {
  359. String str;
  360. bool first_match = false;
  361. bool has_dot = false;
  362. char c = parser.Look();
  363. if (c == '-')
  364. {
  365. str += c;
  366. c = parser.Next();
  367. }
  368. while ((c >= '0' && c <= '9') || (c == '.' && !has_dot))
  369. {
  370. first_match = true;
  371. str += c;
  372. if (c == '.')
  373. has_dot = true;
  374. c = parser.Next();
  375. }
  376. if (!first_match)
  377. {
  378. parser.Error(CreateString(100, "Invalid number literal. Expected '0-9' or '.' but found '%c'.", c));
  379. return;
  380. }
  381. const double number = FromString(str, 0.0);
  382. parser.Emit(Instruction::Literal, Variant(number));
  383. }
  384. static void StringLiteral(DataParser& parser)
  385. {
  386. String str;
  387. char c = parser.Look();
  388. char c_prev = '\0';
  389. while (c != '\0' && (c != '\'' || c_prev == '\\'))
  390. {
  391. if (c_prev == '\\' && (c == '\\' || c == '\'')) {
  392. str.pop_back();
  393. c_prev = '\0';
  394. }
  395. else {
  396. c_prev = c;
  397. }
  398. str += c;
  399. c = parser.Next();
  400. }
  401. parser.Emit(Instruction::Literal, Variant(str));
  402. }
  403. static void Variable(DataParser& parser)
  404. {
  405. String name = VariableName(parser);
  406. if (name.empty()) {
  407. parser.Error("Expected a variable but got an empty name.");
  408. return;
  409. }
  410. // Keywords are parsed like variables, but are really literals.
  411. // Check for them here.
  412. if (name == "true")
  413. parser.Emit(Instruction::Literal, Variant(true));
  414. else if (name == "false")
  415. parser.Emit(Instruction::Literal, Variant(false));
  416. else
  417. parser.Variable(name);
  418. }
  419. static void Add(DataParser& parser)
  420. {
  421. parser.Match('+');
  422. parser.Push();
  423. Term(parser);
  424. parser.Pop(Register::L);
  425. parser.Emit(Instruction::Add);
  426. }
  427. static void Subtract(DataParser& parser)
  428. {
  429. parser.Match('-');
  430. parser.Push();
  431. Term(parser);
  432. parser.Pop(Register::L);
  433. parser.Emit(Instruction::Subtract);
  434. }
  435. static void Multiply(DataParser& parser)
  436. {
  437. parser.Match('*');
  438. parser.Push();
  439. Factor(parser);
  440. parser.Pop(Register::L);
  441. parser.Emit(Instruction::Multiply);
  442. }
  443. static void Divide(DataParser& parser)
  444. {
  445. parser.Match('/');
  446. parser.Push();
  447. Factor(parser);
  448. parser.Pop(Register::L);
  449. parser.Emit(Instruction::Divide);
  450. }
  451. static void Not(DataParser& parser)
  452. {
  453. parser.Match('!');
  454. Factor(parser);
  455. parser.Emit(Instruction::Not);
  456. }
  457. static void Or(DataParser& parser)
  458. {
  459. // We already skipped the first '|' during expression
  460. parser.Match('|');
  461. parser.Push();
  462. Term(parser);
  463. parser.Pop(Register::L);
  464. parser.Emit(Instruction::Or);
  465. }
  466. static void And(DataParser& parser)
  467. {
  468. parser.Match('&', false);
  469. parser.Match('&');
  470. parser.Push();
  471. Term(parser);
  472. parser.Pop(Register::L);
  473. parser.Emit(Instruction::And);
  474. }
  475. static void Less(DataParser& parser)
  476. {
  477. Instruction instruction = Instruction::Less;
  478. parser.Match('<', false);
  479. if (parser.Look() == '=') {
  480. parser.Match('=');
  481. instruction = Instruction::LessEq;
  482. }
  483. else {
  484. parser.SkipWhitespace();
  485. }
  486. parser.Push();
  487. Term(parser);
  488. parser.Pop(Register::L);
  489. parser.Emit(instruction);
  490. }
  491. static void Greater(DataParser& parser)
  492. {
  493. Instruction instruction = Instruction::Greater;
  494. parser.Match('>', false);
  495. if (parser.Look() == '=') {
  496. parser.Match('=');
  497. instruction = Instruction::GreaterEq;
  498. }
  499. else {
  500. parser.SkipWhitespace();
  501. }
  502. parser.Push();
  503. Term(parser);
  504. parser.Pop(Register::L);
  505. parser.Emit(instruction);
  506. }
  507. static void Equal(DataParser& parser)
  508. {
  509. parser.Match('=', false);
  510. parser.Match('=');
  511. parser.Push();
  512. Term(parser);
  513. parser.Pop(Register::L);
  514. parser.Emit(Instruction::Equal);
  515. }
  516. static void NotEqual(DataParser& parser)
  517. {
  518. parser.Match('!', false);
  519. parser.Match('=');
  520. parser.Push();
  521. Term(parser);
  522. parser.Pop(Register::L);
  523. parser.Emit(Instruction::NotEqual);
  524. }
  525. static void Ternary(DataParser& parser)
  526. {
  527. parser.Match('?');
  528. parser.Push();
  529. Expression(parser);
  530. parser.Push();
  531. parser.Match(':');
  532. Expression(parser);
  533. parser.Pop(Register::C);
  534. parser.Pop(Register::L);
  535. parser.Emit(Instruction::Ternary);
  536. }
  537. static void Function(DataParser& parser)
  538. {
  539. // We already matched '|' during expression
  540. String name = VariableName(parser);
  541. if (name.empty()) {
  542. parser.Error("Expected a transform name but got an empty name.");
  543. return;
  544. }
  545. if (parser.Look() == '(')
  546. {
  547. int num_arguments = 0;
  548. bool looping = true;
  549. parser.Match('(');
  550. if (parser.Look() == ')') {
  551. parser.Match(')');
  552. looping = false;
  553. }
  554. else
  555. parser.Push();
  556. while (looping)
  557. {
  558. num_arguments += 1;
  559. Expression(parser);
  560. parser.Push();
  561. switch (parser.Look()) {
  562. case ')': parser.Match(')'); looping = false; break;
  563. case ',': parser.Match(','); break;
  564. default:
  565. parser.Expected("one of ')' or ','");
  566. looping = false;
  567. }
  568. }
  569. if (num_arguments > 0) {
  570. parser.Arguments(num_arguments);
  571. parser.Pop(Register::R);
  572. }
  573. }
  574. else {
  575. parser.SkipWhitespace();
  576. }
  577. parser.Emit(Instruction::Function, Variant(name));
  578. }
  579. } // </namespace Parse>
  580. class DataInterpreter {
  581. public:
  582. DataInterpreter(const Program& program, const AddressList& addresses, DataVariableInterface variable_interface) : program(program), addresses(addresses), variable_interface(variable_interface) {}
  583. bool Error(String message) const
  584. {
  585. message = "Error during execution. " + message;
  586. Log::Message(Log::LT_WARNING, message.c_str());
  587. RMLUI_ERROR;
  588. return false;
  589. }
  590. bool Run()
  591. {
  592. Log::Message(Log::LT_DEBUG, "Executing program");
  593. DumpProgram();
  594. bool success = true;
  595. for (size_t i = 0; i < program.size(); i++)
  596. {
  597. if (!Execute(program[i].instruction, program[i].data))
  598. {
  599. success = false;
  600. break;
  601. }
  602. }
  603. if (success)
  604. Log::Message(Log::LT_DEBUG, "Successfully finished execution of program with %d instructions.", program.size());
  605. else
  606. Log::Message(Log::LT_WARNING, "Failed executing program with %d instructions.", program.size());
  607. Log::Message(Log::LT_DEBUG, "R: %s", R.Get<String>().c_str());
  608. Log::Message(Log::LT_DEBUG, "L: %s", L.Get<String>().c_str());
  609. Log::Message(Log::LT_DEBUG, "C: %s", C.Get<String>().c_str());
  610. Log::Message(Log::LT_DEBUG, "Stack #: %d", stack.size());
  611. return success;
  612. }
  613. Variant Result() const {
  614. return R;
  615. }
  616. void DumpProgram()
  617. {
  618. int i = 0;
  619. for (auto& instruction : program)
  620. {
  621. Log::Message(Log::LT_DEBUG, " %4d '%c' %s", i, char(instruction.instruction), instruction.data.Get<String>().c_str());
  622. i++;
  623. }
  624. }
  625. private:
  626. Variant R, L, C;
  627. std::stack<Variant> stack;
  628. std::vector<Variant> arguments;
  629. const Program& program;
  630. const AddressList& addresses;
  631. DataVariableInterface variable_interface;
  632. bool Execute(const Instruction instruction, const Variant& data)
  633. {
  634. auto AnyString = [](const Variant& v1, const Variant& v2) {
  635. return v1.GetType() == Variant::STRING || v2.GetType() == Variant::STRING;
  636. };
  637. switch (instruction)
  638. {
  639. case Instruction::Push:
  640. {
  641. stack.push(std::move(R));
  642. R.Clear();
  643. }
  644. break;
  645. case Instruction::Pop:
  646. {
  647. if (stack.empty())
  648. return Error("Cannot pop stack, it is empty.");
  649. Register reg = Register(data.Get<int>(-1));
  650. switch (reg) {
  651. case Register::R: R = stack.top(); stack.pop(); break;
  652. case Register::L: L = stack.top(); stack.pop(); break;
  653. case Register::C: C = stack.top(); stack.pop(); break;
  654. default:
  655. return Error(CreateString(50, "Invalid register %d", int(reg)));
  656. }
  657. }
  658. break;
  659. case Instruction::Literal:
  660. {
  661. R = data;
  662. }
  663. break;
  664. case Instruction::Variable:
  665. {
  666. size_t variable_index = size_t(data.Get<int>(-1));
  667. if (variable_index < addresses.size())
  668. R = variable_interface.GetValue(addresses[variable_index]);
  669. else
  670. return Error("Variable address not found.");
  671. }
  672. break;
  673. case Instruction::Add:
  674. {
  675. if (AnyString(L, R))
  676. R = Variant(L.Get<String>() + R.Get<String>());
  677. else
  678. R = Variant(L.Get<double>() + R.Get<double>());
  679. }
  680. break;
  681. case Instruction::Subtract: R = Variant(L.Get<double>() - R.Get<double>()); break;
  682. case Instruction::Multiply: R = Variant(L.Get<double>() * R.Get<double>()); break;
  683. case Instruction::Divide: R = Variant(L.Get<double>() / R.Get<double>()); break;
  684. case Instruction::Not: R = Variant(!R.Get<bool>()); break;
  685. case Instruction::And: R = Variant(L.Get<bool>() && R.Get<bool>()); break;
  686. case Instruction::Or: R = Variant(L.Get<bool>() || R.Get<bool>()); break;
  687. case Instruction::Less: R = Variant(L.Get<double>() < R.Get<double>()); break;
  688. case Instruction::LessEq: R = Variant(L.Get<double>() <= R.Get<double>()); break;
  689. case Instruction::Greater: R = Variant(L.Get<double>() > R.Get<double>()); break;
  690. case Instruction::GreaterEq: R = Variant(L.Get<double>() >= R.Get<double>()); break;
  691. case Instruction::Equal:
  692. {
  693. if (AnyString(L, R))
  694. R = Variant(L.Get<String>() == R.Get<String>());
  695. else
  696. R = Variant(L.Get<double>() == R.Get<double>());
  697. }
  698. break;
  699. case Instruction::NotEqual:
  700. {
  701. if (AnyString(L, R))
  702. R = Variant(L.Get<String>() != R.Get<String>());
  703. else
  704. R = Variant(L.Get<double>() != R.Get<double>());
  705. }
  706. break;
  707. case Instruction::Ternary:
  708. {
  709. if (L.Get<bool>())
  710. R = C;
  711. }
  712. break;
  713. case Instruction::Arguments:
  714. {
  715. if (!arguments.empty())
  716. return Error("Invalid program: Argument stack is not empty.");
  717. int num_arguments = data.Get<int>(-1);
  718. if (num_arguments < 0)
  719. return Error("Invalid number of arguments.");
  720. if (stack.size() < size_t(num_arguments))
  721. return Error(CreateString(100, "Cannot pop %d arguments, stack contains only %d elements.", num_arguments, stack.size()));
  722. arguments.resize(num_arguments);
  723. for (int i = num_arguments - 1; i >= 0; i--)
  724. {
  725. arguments[i] = std::move(stack.top());
  726. stack.pop();
  727. }
  728. }
  729. break;
  730. case Instruction::Function:
  731. {
  732. const String function_name = data.Get<String>();
  733. String arguments_str;
  734. for (size_t i = 0; i < arguments.size(); i++)
  735. {
  736. arguments_str += arguments[i].Get<String>();
  737. if (i < arguments.size() - 1)
  738. arguments_str += ", ";
  739. }
  740. // TODO: execute function
  741. Log::Message(Log::LT_DEBUG, "Executing '%s' with %d argument(s): %s(%s)", function_name.c_str(), arguments.size(), function_name.c_str(), arguments_str.c_str());
  742. arguments.clear();
  743. }
  744. break;
  745. default:
  746. RMLUI_ERRORMSG("Instruction not implemented."); break;
  747. }
  748. return true;
  749. }
  750. };
  751. struct TestParser {
  752. TestParser() {
  753. //DataParser("'hello' + ' ' + 'world'").Parse();
  754. //DataParser("5+(1+2)").Parse();
  755. //DataParser("5.2 + 19 + 'test'").Parse();
  756. //DataParser("(color_name) + (': rgba(' + color_value + ')')").Parse();
  757. //DataParser("!!10 - 1 ? 'hello' : 'world'").Parse();
  758. //int test = 1 + (true ? 0-5 : 10 + 5);
  759. //DataParser("1 + (true ? 0-5 : 10 + 5)").Parse();
  760. String result;
  761. result = TestExpression("'hello world' | uppercase(5 + 12 == 17 ? 'yes' : 'no', 9*2)");
  762. result = TestExpression(R"('hello wor\'ld')");
  763. String alt = "hello wor\ld";
  764. }
  765. String TestExpression(String expression)
  766. {
  767. DataParser parser(expression);
  768. if (parser.Parse())
  769. {
  770. DataVariableInterface interface;
  771. Program program = parser.ReleaseProgram();
  772. AddressList addresses = parser.ReleaseAddresses();
  773. DataInterpreter interpreter(program, addresses, interface);
  774. if (interpreter.Run())
  775. return interpreter.Result().Get<String>();
  776. }
  777. return "<invalid expression>";
  778. };
  779. };
  780. DataExpression::DataExpression(String expression) : expression(expression) {}
  781. DataExpression::~DataExpression()
  782. {
  783. }
  784. bool DataExpression::Parse(const DataVariableInterface& variable_interface)
  785. {
  786. // @todo: Remove, debugging only
  787. static TestParser test_parser;
  788. // TODO:
  789. // 3. Create a plug-in wrapper for use by scripting languages to replace this parser. Design wrapper as for events.
  790. // 5. Add tests
  791. // 6. Function callback
  792. DataParser parser(expression, variable_interface);
  793. if (!parser.Parse())
  794. return false;
  795. program = parser.ReleaseProgram();
  796. addresses = parser.ReleaseAddresses();
  797. return true;
  798. }
  799. bool DataExpression::Run(const DataVariableInterface& variable_interface, Variant& out_value)
  800. {
  801. DataInterpreter interpreter(program, addresses, variable_interface);
  802. if (!interpreter.Run())
  803. return false;
  804. out_value = interpreter.Result();
  805. return true;
  806. }
  807. StringList DataExpression::GetVariableNameList() const
  808. {
  809. StringList list;
  810. list.reserve(addresses.size());
  811. for (const Address& address : addresses)
  812. {
  813. if (!address.empty())
  814. list.push_back(address[0].name);
  815. }
  816. return list;
  817. }
  818. DataVariableInterface::DataVariableInterface(DataModel* data_model, Element* element) : data_model(data_model), element(element)
  819. {}
  820. Address DataVariableInterface::ParseAddress(const String& address_str) const {
  821. return data_model ? data_model->ResolveAddress(address_str, element) : Address();
  822. }
  823. Variant DataVariableInterface::GetValue(const Address& address) const {
  824. Variant result;
  825. if (data_model)
  826. data_model->GetValue(address, result);
  827. return result;
  828. }
  829. }
  830. }