DataParser.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  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(const String message)
  120. {
  121. parse_error = true;
  122. Log::Message(Log::LT_WARNING, "Error in data expression at %d. %s", index, message.c_str());
  123. Log::Message(Log::LT_WARNING, " \"%s\"", expression.c_str());
  124. const size_t cursor_offset = size_t(index) + 3;
  125. const String cursor_string = String(cursor_offset, ' ') + '^';
  126. Log::Message(Log::LT_WARNING, cursor_string.c_str());
  127. }
  128. void Expected(String expected_symbols) {
  129. const char c = Look();
  130. if (c == '\0')
  131. Error(CreateString(expected_symbols.size() + 50, "Expected %s but found end of string.", expected_symbols.c_str()));
  132. else
  133. Error(CreateString(expected_symbols.size() + 50, "Expected %s but found character '%c'.", expected_symbols.c_str(), c));
  134. }
  135. void Expected(char expected) {
  136. Expected(String(1, '\'') + expected + '\'');
  137. }
  138. bool Parse()
  139. {
  140. program.clear();
  141. variable_addresses.clear();
  142. index = 0;
  143. reached_end = false;
  144. parse_error = false;
  145. if (expression.empty())
  146. reached_end = true;
  147. SkipWhitespace();
  148. Parse::Expression(*this);
  149. if (!reached_end) {
  150. parse_error = true;
  151. Error(CreateString(50, "Unexpected character '%c' encountered.", Look()));
  152. }
  153. if (!parse_error && program_stack_size != 0) {
  154. parse_error = true;
  155. Error(CreateString(120, "Internal parser error, inconsistent stack operations. Stack size is %d at parse end.", program_stack_size));
  156. }
  157. return !parse_error;
  158. }
  159. Program ReleaseProgram() {
  160. RMLUI_ASSERT(!parse_error);
  161. return std::move(program);
  162. }
  163. AddressList ReleaseAddresses() {
  164. RMLUI_ASSERT(!parse_error);
  165. return std::move(variable_addresses);
  166. }
  167. void Emit(Instruction instruction, Variant data = Variant())
  168. {
  169. RMLUI_ASSERTMSG(instruction != Instruction::Push && instruction != Instruction::Pop &&
  170. instruction != Instruction::Arguments && instruction != Instruction::Variable,
  171. "Use the Push(), Pop(), Arguments(), and Variable() procedures for stack manipulation and variable instructions.");
  172. program.push_back(InstructionData{ instruction, std::move(data) });
  173. }
  174. void Push() {
  175. program_stack_size += 1;
  176. program.push_back(InstructionData{ Instruction::Push, Variant() });
  177. }
  178. void Pop(Register destination) {
  179. if (program_stack_size <= 0) {
  180. Error("Internal parser error: Tried to pop an empty stack.");
  181. return;
  182. }
  183. program_stack_size -= 1;
  184. program.push_back(InstructionData{ Instruction::Pop, Variant(int(destination)) });
  185. }
  186. void Arguments(int num_arguments) {
  187. if (program_stack_size < num_arguments) {
  188. Error(CreateString(128, "Internal parser error: Popping %d arguments, but the stack contains only %d elements.", num_arguments, program_stack_size));
  189. return;
  190. }
  191. program_stack_size -= num_arguments;
  192. program.push_back(InstructionData{ Instruction::Arguments, Variant(int(num_arguments)) });
  193. }
  194. void Variable(const String& name) {
  195. DataAddress address = variable_interface.ParseAddress(name);
  196. if (address.empty()) {
  197. Error(CreateString(name.size() + 50, "Could not find data variable with name '%s'.", name.c_str()));
  198. return;
  199. }
  200. int index = int(variable_addresses.size());
  201. variable_addresses.push_back(std::move(address));
  202. program.push_back(InstructionData{ Instruction::Variable, Variant(int(index)) });
  203. }
  204. private:
  205. const String expression;
  206. DataVariableInterface variable_interface;
  207. size_t index = 0;
  208. bool reached_end = false;
  209. bool parse_error = true;
  210. int program_stack_size = 0;
  211. Program program;
  212. AddressList variable_addresses;
  213. };
  214. namespace Parse {
  215. // Forward declare all parse functions.
  216. static void Expression(DataParser& parser);
  217. static void Factor(DataParser& parser);
  218. static void Term(DataParser& parser);
  219. static void NumberLiteral(DataParser& parser);
  220. static void StringLiteral(DataParser& parser);
  221. static void Variable(DataParser& parser);
  222. static void Add(DataParser& parser);
  223. static void Subtract(DataParser& parser);
  224. static void Multiply(DataParser& parser);
  225. static void Divide(DataParser& parser);
  226. static void Not(DataParser& parser);
  227. static void And(DataParser& parser);
  228. static void Or(DataParser& parser);
  229. static void Less(DataParser& parser);
  230. static void Greater(DataParser& parser);
  231. static void Equal(DataParser& parser);
  232. static void NotEqual(DataParser& parser);
  233. static void Ternary(DataParser& parser);
  234. static void Function(DataParser& parser);
  235. // Helper functions
  236. static bool IsVariableCharacter(char c, bool is_first_character)
  237. {
  238. const bool is_alpha = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
  239. if (is_first_character)
  240. return is_alpha;
  241. if (is_alpha || (c >= '0' && c <= '9'))
  242. return true;
  243. for (char valid_char : "_.[] ")
  244. {
  245. if (c == valid_char && valid_char != '\0')
  246. return true;
  247. }
  248. return false;
  249. }
  250. static String VariableName(DataParser& parser)
  251. {
  252. String name;
  253. bool is_first_character = true;
  254. char c = parser.Look();
  255. while (IsVariableCharacter(c, is_first_character))
  256. {
  257. name += c;
  258. c = parser.Next();
  259. is_first_character = false;
  260. }
  261. // Right trim spaces in name
  262. size_t new_size = String::npos;
  263. for (int i = int(name.size()) - 1; i >= 1; i--)
  264. {
  265. if (name[i] == ' ')
  266. new_size = size_t(i);
  267. else
  268. break;
  269. }
  270. if (new_size != String::npos)
  271. name.resize(new_size);
  272. return name;
  273. }
  274. // Parser functions
  275. static void Expression(DataParser& parser)
  276. {
  277. Term(parser);
  278. bool looping = true;
  279. while (looping)
  280. {
  281. switch (char c = parser.Look())
  282. {
  283. case '+': Add(parser); break;
  284. case '-': Subtract(parser); break;
  285. case '?': Ternary(parser); break;
  286. case '|':
  287. {
  288. parser.Match('|', false);
  289. if (parser.Look() == '|')
  290. Or(parser);
  291. else
  292. {
  293. parser.SkipWhitespace();
  294. Function(parser);
  295. }
  296. }
  297. break;
  298. case '&': And(parser); break;
  299. case '=': Equal(parser); break;
  300. case '!': NotEqual(parser); break;
  301. case '<': Less(parser); break;
  302. case '>': Greater(parser); break;
  303. case '\0':
  304. looping = false;
  305. break;
  306. default:
  307. looping = false;
  308. }
  309. }
  310. }
  311. static void Term(DataParser& parser)
  312. {
  313. Factor(parser);
  314. bool looping = true;
  315. while (looping)
  316. {
  317. switch (const char c = parser.Look())
  318. {
  319. case '*': Multiply(parser); break;
  320. case '/': Divide(parser); break;
  321. case '\0': looping = false; break;
  322. default:
  323. looping = false;
  324. }
  325. }
  326. }
  327. static void Factor(DataParser& parser)
  328. {
  329. const char c = parser.Look();
  330. if (c == '(')
  331. {
  332. parser.Match('(');
  333. Expression(parser);
  334. parser.Match(')');
  335. }
  336. else if (c == '\'')
  337. {
  338. parser.Match('\'', false);
  339. StringLiteral(parser);
  340. parser.Match('\'');
  341. }
  342. else if (c == '!')
  343. {
  344. Not(parser);
  345. parser.SkipWhitespace();
  346. }
  347. else if (c == '-' || (c >= '0' && c <= '9'))
  348. {
  349. NumberLiteral(parser);
  350. parser.SkipWhitespace();
  351. }
  352. else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
  353. {
  354. Variable(parser);
  355. parser.SkipWhitespace();
  356. }
  357. else
  358. parser.Expected("literal, variable name, parenthesis, or '!'");
  359. }
  360. static void NumberLiteral(DataParser& parser)
  361. {
  362. String str;
  363. bool first_match = false;
  364. bool has_dot = false;
  365. char c = parser.Look();
  366. if (c == '-')
  367. {
  368. str += c;
  369. c = parser.Next();
  370. }
  371. while ((c >= '0' && c <= '9') || (c == '.' && !has_dot))
  372. {
  373. first_match = true;
  374. str += c;
  375. if (c == '.')
  376. has_dot = true;
  377. c = parser.Next();
  378. }
  379. if (!first_match)
  380. {
  381. parser.Error(CreateString(100, "Invalid number literal. Expected '0-9' or '.' but found '%c'.", c));
  382. return;
  383. }
  384. const double number = FromString(str, 0.0);
  385. parser.Emit(Instruction::Literal, Variant(number));
  386. }
  387. static void StringLiteral(DataParser& parser)
  388. {
  389. String str;
  390. char c = parser.Look();
  391. char c_prev = '\0';
  392. while (c != '\0' && (c != '\'' || c_prev == '\\'))
  393. {
  394. if (c_prev == '\\' && (c == '\\' || c == '\'')) {
  395. str.pop_back();
  396. c_prev = '\0';
  397. }
  398. else {
  399. c_prev = c;
  400. }
  401. str += c;
  402. c = parser.Next();
  403. }
  404. parser.Emit(Instruction::Literal, Variant(str));
  405. }
  406. static void Variable(DataParser& parser)
  407. {
  408. String name = VariableName(parser);
  409. if (name.empty()) {
  410. parser.Error("Expected a variable but got an empty name.");
  411. return;
  412. }
  413. // Keywords are parsed like variables, but are really literals.
  414. // Check for them here.
  415. if (name == "true")
  416. parser.Emit(Instruction::Literal, Variant(true));
  417. else if (name == "false")
  418. parser.Emit(Instruction::Literal, Variant(false));
  419. else
  420. parser.Variable(name);
  421. }
  422. static void Add(DataParser& parser)
  423. {
  424. parser.Match('+');
  425. parser.Push();
  426. Term(parser);
  427. parser.Pop(Register::L);
  428. parser.Emit(Instruction::Add);
  429. }
  430. static void Subtract(DataParser& parser)
  431. {
  432. parser.Match('-');
  433. parser.Push();
  434. Term(parser);
  435. parser.Pop(Register::L);
  436. parser.Emit(Instruction::Subtract);
  437. }
  438. static void Multiply(DataParser& parser)
  439. {
  440. parser.Match('*');
  441. parser.Push();
  442. Factor(parser);
  443. parser.Pop(Register::L);
  444. parser.Emit(Instruction::Multiply);
  445. }
  446. static void Divide(DataParser& parser)
  447. {
  448. parser.Match('/');
  449. parser.Push();
  450. Factor(parser);
  451. parser.Pop(Register::L);
  452. parser.Emit(Instruction::Divide);
  453. }
  454. static void Not(DataParser& parser)
  455. {
  456. parser.Match('!');
  457. Factor(parser);
  458. parser.Emit(Instruction::Not);
  459. }
  460. static void Or(DataParser& parser)
  461. {
  462. // We already skipped the first '|' during expression
  463. parser.Match('|');
  464. parser.Push();
  465. Term(parser);
  466. parser.Pop(Register::L);
  467. parser.Emit(Instruction::Or);
  468. }
  469. static void And(DataParser& parser)
  470. {
  471. parser.Match('&', false);
  472. parser.Match('&');
  473. parser.Push();
  474. Term(parser);
  475. parser.Pop(Register::L);
  476. parser.Emit(Instruction::And);
  477. }
  478. static void Less(DataParser& parser)
  479. {
  480. Instruction instruction = Instruction::Less;
  481. parser.Match('<', false);
  482. if (parser.Look() == '=') {
  483. parser.Match('=');
  484. instruction = Instruction::LessEq;
  485. }
  486. else {
  487. parser.SkipWhitespace();
  488. }
  489. parser.Push();
  490. Term(parser);
  491. parser.Pop(Register::L);
  492. parser.Emit(instruction);
  493. }
  494. static void Greater(DataParser& parser)
  495. {
  496. Instruction instruction = Instruction::Greater;
  497. parser.Match('>', false);
  498. if (parser.Look() == '=') {
  499. parser.Match('=');
  500. instruction = Instruction::GreaterEq;
  501. }
  502. else {
  503. parser.SkipWhitespace();
  504. }
  505. parser.Push();
  506. Term(parser);
  507. parser.Pop(Register::L);
  508. parser.Emit(instruction);
  509. }
  510. static void Equal(DataParser& parser)
  511. {
  512. parser.Match('=', false);
  513. parser.Match('=');
  514. parser.Push();
  515. Term(parser);
  516. parser.Pop(Register::L);
  517. parser.Emit(Instruction::Equal);
  518. }
  519. static void NotEqual(DataParser& parser)
  520. {
  521. parser.Match('!', false);
  522. parser.Match('=');
  523. parser.Push();
  524. Term(parser);
  525. parser.Pop(Register::L);
  526. parser.Emit(Instruction::NotEqual);
  527. }
  528. static void Ternary(DataParser& parser)
  529. {
  530. parser.Match('?');
  531. parser.Push();
  532. Expression(parser);
  533. parser.Push();
  534. parser.Match(':');
  535. Expression(parser);
  536. parser.Pop(Register::C);
  537. parser.Pop(Register::L);
  538. parser.Emit(Instruction::Ternary);
  539. }
  540. static void Function(DataParser& parser)
  541. {
  542. // We already matched '|' during expression
  543. String name = VariableName(parser);
  544. if (name.empty()) {
  545. parser.Error("Expected a transform name but got an empty name.");
  546. return;
  547. }
  548. if (parser.Look() == '(')
  549. {
  550. int num_arguments = 0;
  551. bool looping = true;
  552. parser.Match('(');
  553. if (parser.Look() == ')') {
  554. parser.Match(')');
  555. looping = false;
  556. }
  557. else
  558. parser.Push();
  559. while (looping)
  560. {
  561. num_arguments += 1;
  562. Expression(parser);
  563. parser.Push();
  564. switch (parser.Look()) {
  565. case ')': parser.Match(')'); looping = false; break;
  566. case ',': parser.Match(','); break;
  567. default:
  568. parser.Expected("one of ')' or ','");
  569. looping = false;
  570. }
  571. }
  572. if (num_arguments > 0) {
  573. parser.Arguments(num_arguments);
  574. parser.Pop(Register::R);
  575. }
  576. }
  577. else {
  578. parser.SkipWhitespace();
  579. }
  580. parser.Emit(Instruction::Function, Variant(name));
  581. }
  582. } // </namespace Parse>
  583. static String DumpProgram(const Program& program)
  584. {
  585. String str;
  586. for (size_t i = 0; i < program.size(); i++)
  587. {
  588. String instruction_str = program[i].data.Get<String>();
  589. str += CreateString(instruction_str.size(), " %4d '%c' %s\n", i, char(program[i].instruction), instruction_str.c_str());
  590. }
  591. return str;
  592. }
  593. class DataInterpreter {
  594. public:
  595. DataInterpreter(const Program& program, const AddressList& addresses, DataVariableInterface variable_interface) : program(program), addresses(addresses), variable_interface(variable_interface) {}
  596. bool Error(String message) const
  597. {
  598. message = "Error during execution. " + message;
  599. Log::Message(Log::LT_WARNING, message.c_str());
  600. RMLUI_ERROR;
  601. return false;
  602. }
  603. bool Run()
  604. {
  605. bool success = true;
  606. for (size_t i = 0; i < program.size(); i++)
  607. {
  608. if (!Execute(program[i].instruction, program[i].data))
  609. {
  610. success = false;
  611. break;
  612. }
  613. }
  614. if(success && !stack.empty())
  615. Log::Message(Log::LT_WARNING, "Possible data interpreter stack corruption. Stack size is %d at end of execution (should be zero).", stack.size());
  616. if(!success)
  617. {
  618. String program_str = DumpProgram(program);
  619. Log::Message(Log::LT_WARNING, "Failed to execute program with %d instructions:", program.size());
  620. Log::Message(Log::LT_WARNING, program_str.c_str());
  621. }
  622. return success;
  623. }
  624. Variant Result() const {
  625. return R;
  626. }
  627. private:
  628. Variant R, L, C;
  629. std::stack<Variant> stack;
  630. std::vector<Variant> arguments;
  631. const Program& program;
  632. const AddressList& addresses;
  633. DataVariableInterface variable_interface;
  634. bool Execute(const Instruction instruction, const Variant& data)
  635. {
  636. auto AnyString = [](const Variant& v1, const Variant& v2) {
  637. return v1.GetType() == Variant::STRING || v2.GetType() == Variant::STRING;
  638. };
  639. switch (instruction)
  640. {
  641. case Instruction::Push:
  642. {
  643. stack.push(std::move(R));
  644. R.Clear();
  645. }
  646. break;
  647. case Instruction::Pop:
  648. {
  649. if (stack.empty())
  650. return Error("Cannot pop stack, it is empty.");
  651. Register reg = Register(data.Get<int>(-1));
  652. switch (reg) {
  653. case Register::R: R = stack.top(); stack.pop(); break;
  654. case Register::L: L = stack.top(); stack.pop(); break;
  655. case Register::C: C = stack.top(); stack.pop(); break;
  656. default:
  657. return Error(CreateString(50, "Invalid register %d.", int(reg)));
  658. }
  659. }
  660. break;
  661. case Instruction::Literal:
  662. {
  663. R = data;
  664. }
  665. break;
  666. case Instruction::Variable:
  667. {
  668. size_t variable_index = size_t(data.Get<int>(-1));
  669. if (variable_index < addresses.size())
  670. R = variable_interface.GetValue(addresses[variable_index]);
  671. else
  672. return Error("Variable address not found.");
  673. }
  674. break;
  675. case Instruction::Add:
  676. {
  677. if (AnyString(L, R))
  678. R = Variant(L.Get<String>() + R.Get<String>());
  679. else
  680. R = Variant(L.Get<double>() + R.Get<double>());
  681. }
  682. break;
  683. case Instruction::Subtract: R = Variant(L.Get<double>() - R.Get<double>()); break;
  684. case Instruction::Multiply: R = Variant(L.Get<double>() * R.Get<double>()); break;
  685. case Instruction::Divide: R = Variant(L.Get<double>() / R.Get<double>()); break;
  686. case Instruction::Not: R = Variant(!R.Get<bool>()); break;
  687. case Instruction::And: R = Variant(L.Get<bool>() && R.Get<bool>()); break;
  688. case Instruction::Or: R = Variant(L.Get<bool>() || R.Get<bool>()); break;
  689. case Instruction::Less: R = Variant(L.Get<double>() < R.Get<double>()); break;
  690. case Instruction::LessEq: R = Variant(L.Get<double>() <= R.Get<double>()); break;
  691. case Instruction::Greater: R = Variant(L.Get<double>() > R.Get<double>()); break;
  692. case Instruction::GreaterEq: R = Variant(L.Get<double>() >= R.Get<double>()); break;
  693. case Instruction::Equal:
  694. {
  695. if (AnyString(L, R))
  696. R = Variant(L.Get<String>() == R.Get<String>());
  697. else
  698. R = Variant(L.Get<double>() == R.Get<double>());
  699. }
  700. break;
  701. case Instruction::NotEqual:
  702. {
  703. if (AnyString(L, R))
  704. R = Variant(L.Get<String>() != R.Get<String>());
  705. else
  706. R = Variant(L.Get<double>() != R.Get<double>());
  707. }
  708. break;
  709. case Instruction::Ternary:
  710. {
  711. if (L.Get<bool>())
  712. R = C;
  713. }
  714. break;
  715. case Instruction::Arguments:
  716. {
  717. if (!arguments.empty())
  718. return Error("Argument stack is not empty.");
  719. int num_arguments = data.Get<int>(-1);
  720. if (num_arguments < 0)
  721. return Error("Invalid number of arguments.");
  722. if (stack.size() < size_t(num_arguments))
  723. return Error(CreateString(100, "Cannot pop %d arguments, stack contains only %d elements.", num_arguments, stack.size()));
  724. arguments.resize(num_arguments);
  725. for (int i = num_arguments - 1; i >= 0; i--)
  726. {
  727. arguments[i] = std::move(stack.top());
  728. stack.pop();
  729. }
  730. }
  731. break;
  732. case Instruction::Function:
  733. {
  734. const String function_name = data.Get<String>();
  735. if (!variable_interface.CallTransform(function_name, R, arguments))
  736. {
  737. String arguments_str;
  738. for (size_t i = 0; i < arguments.size(); i++)
  739. {
  740. arguments_str += arguments[i].Get<String>();
  741. if (i < arguments.size() - 1)
  742. arguments_str += ", ";
  743. }
  744. Error(CreateString(50 + function_name.size() + arguments_str.size(), "Failed to execute data function: %s(%s)", function_name.c_str(), arguments_str.c_str()));
  745. }
  746. arguments.clear();
  747. }
  748. break;
  749. default:
  750. RMLUI_ERRORMSG("Instruction not implemented."); break;
  751. }
  752. return true;
  753. }
  754. };
  755. struct TestParser {
  756. TestParser() : model(type_register.GetTransformFuncRegister())
  757. {
  758. DataModelHandle handle(&model, &type_register);
  759. handle.Bind("color_name", &color_name);
  760. handle.BindFunc("color_value", [this](Rml::Core::Variant& variant) {
  761. variant = ToString(color_value);
  762. });
  763. String result;
  764. result = TestExpression("!!10 - 1 ? 'hello' : 'world' | to_upper");
  765. result = TestExpression("(color_name) + (': rgba(' + color_value + ')')");
  766. result = TestExpression("'hello world' | to_upper(5 + 12 == 17 ? 'yes' : 'no', 9*2)");
  767. result = TestExpression("true == false");
  768. result = TestExpression("true != false");
  769. result = TestExpression("true");
  770. result = TestExpression(R"(true || false ? (true && true ? 'Absolutely!' : 'well..') : 'no')");
  771. result = TestExpression("2 * 2");
  772. result = TestExpression("50000 / 1500");
  773. result = TestExpression("5*1+2");
  774. result = TestExpression("5*(1+2)");
  775. result = TestExpression("5.2 + 19 + 'px'");
  776. }
  777. String TestExpression(String expression)
  778. {
  779. DataVariableInterface interface(&model, nullptr);
  780. DataParser parser(expression, interface);
  781. if (parser.Parse())
  782. {
  783. Program program = parser.ReleaseProgram();
  784. AddressList addresses = parser.ReleaseAddresses();
  785. DataInterpreter interpreter(program, addresses, interface);
  786. if (interpreter.Run())
  787. return interpreter.Result().Get<String>();
  788. }
  789. return "<invalid expression>";
  790. };
  791. DataTypeRegister type_register;
  792. DataModel model;
  793. String color_name = "color";
  794. Colourb color_value = Colourb(180, 100, 255);
  795. };
  796. DataExpression::DataExpression(String expression) : expression(expression) {}
  797. DataExpression::~DataExpression()
  798. {
  799. }
  800. bool DataExpression::Parse(const DataVariableInterface& variable_interface)
  801. {
  802. // @todo: Remove, debugging only
  803. static TestParser test_parser;
  804. // TODO:
  805. // 3. Create a plug-in wrapper for use by scripting languages to replace this parser. Design wrapper as for events.
  806. // 5. Add tests
  807. DataParser parser(expression, variable_interface);
  808. if (!parser.Parse())
  809. return false;
  810. program = parser.ReleaseProgram();
  811. addresses = parser.ReleaseAddresses();
  812. return true;
  813. }
  814. bool DataExpression::Run(const DataVariableInterface& variable_interface, Variant& out_value)
  815. {
  816. DataInterpreter interpreter(program, addresses, variable_interface);
  817. if (!interpreter.Run())
  818. return false;
  819. out_value = interpreter.Result();
  820. return true;
  821. }
  822. StringList DataExpression::GetVariableNameList() const
  823. {
  824. StringList list;
  825. list.reserve(addresses.size());
  826. for (const DataAddress& address : addresses)
  827. {
  828. if (!address.empty())
  829. list.push_back(address[0].name);
  830. }
  831. return list;
  832. }
  833. DataVariableInterface::DataVariableInterface(DataModel* data_model, Element* element) : data_model(data_model), element(element)
  834. {}
  835. DataAddress DataVariableInterface::ParseAddress(const String& address_str) const {
  836. return data_model ? data_model->ResolveAddress(address_str, element) : DataAddress();
  837. }
  838. Variant DataVariableInterface::GetValue(const DataAddress& address) const {
  839. Variant result;
  840. if (data_model)
  841. data_model->GetValue(address, result);
  842. return result;
  843. }
  844. bool DataVariableInterface::CallTransform(const String& name, Variant& inout_variant, const VariantList& arguments)
  845. {
  846. return data_model ? data_model->CallTransform(name, inout_variant, arguments) : false;
  847. }
  848. }
  849. }