runtime.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. #pragma once
  2. #include "lexer.h"
  3. #include "value.h"
  4. #include <cassert>
  5. #include <ctime>
  6. #include <memory>
  7. #include <sstream>
  8. #include <string>
  9. #include <vector>
  10. #define JJ_DEBUG(msg, ...) do { if (g_jinja_debug) printf("%s:%-3d : " msg "\n", FILENAME, __LINE__, __VA_ARGS__); } while (0)
  11. extern bool g_jinja_debug;
  12. namespace jinja {
  13. struct statement;
  14. using statement_ptr = std::unique_ptr<statement>;
  15. using statements = std::vector<statement_ptr>;
  16. // Helpers for dynamic casting and type checking
  17. template<typename T>
  18. struct extract_pointee_unique {
  19. using type = T;
  20. };
  21. template<typename U>
  22. struct extract_pointee_unique<std::unique_ptr<U>> {
  23. using type = U;
  24. };
  25. template<typename T>
  26. bool is_stmt(const statement_ptr & ptr) {
  27. return dynamic_cast<const T*>(ptr.get()) != nullptr;
  28. }
  29. template<typename T>
  30. T * cast_stmt(statement_ptr & ptr) {
  31. return dynamic_cast<T*>(ptr.get());
  32. }
  33. template<typename T>
  34. const T * cast_stmt(const statement_ptr & ptr) {
  35. return dynamic_cast<const T*>(ptr.get());
  36. }
  37. // End Helpers
  38. // not thread-safe
  39. void enable_debug(bool enable);
  40. struct context {
  41. std::shared_ptr<std::string> src; // for debugging; use shared_ptr to avoid copying on scope creation
  42. std::time_t current_time; // for functions that need current time
  43. bool is_get_stats = false; // whether to collect stats
  44. // src is optional, used for error reporting
  45. context(std::string src = "") : src(std::make_shared<std::string>(std::move(src))) {
  46. env = mk_val<value_object>();
  47. env->insert("true", mk_val<value_bool>(true));
  48. env->insert("True", mk_val<value_bool>(true));
  49. env->insert("false", mk_val<value_bool>(false));
  50. env->insert("False", mk_val<value_bool>(false));
  51. env->insert("none", mk_val<value_none>());
  52. env->insert("None", mk_val<value_none>());
  53. current_time = std::time(nullptr);
  54. }
  55. ~context() = default;
  56. context(const context & parent) : context() {
  57. // inherit variables (for example, when entering a new scope)
  58. auto & pvar = parent.env->as_object();
  59. for (const auto & pair : pvar) {
  60. set_val(pair.first, pair.second);
  61. }
  62. current_time = parent.current_time;
  63. is_get_stats = parent.is_get_stats;
  64. src = parent.src;
  65. }
  66. value get_val(const std::string & name) {
  67. auto it = env->val_obj.unordered.find(name);
  68. if (it != env->val_obj.unordered.end()) {
  69. return it->second;
  70. } else {
  71. return mk_val<value_undefined>(name);
  72. }
  73. }
  74. void set_val(const std::string & name, const value & val) {
  75. env->insert(name, val);
  76. }
  77. void print_vars() const {
  78. printf("Context Variables:\n%s\n", value_to_json(env, 2).c_str());
  79. }
  80. private:
  81. value_object env;
  82. };
  83. /**
  84. * Base class for all nodes in the AST.
  85. */
  86. struct statement {
  87. size_t pos; // position in source, for debugging
  88. virtual ~statement() = default;
  89. virtual std::string type() const { return "Statement"; }
  90. // execute_impl must be overridden by derived classes
  91. virtual value execute_impl(context &) { throw std::runtime_error("cannot exec " + type()); }
  92. // execute is the public method to execute a statement with error handling
  93. value execute(context &);
  94. };
  95. // Type Checking Utilities
  96. template<typename T>
  97. static void chk_type(const statement_ptr & ptr) {
  98. if (!ptr) return; // Allow null for optional fields
  99. assert(dynamic_cast<T *>(ptr.get()) != nullptr);
  100. }
  101. template<typename T, typename U>
  102. static void chk_type(const statement_ptr & ptr) {
  103. if (!ptr) return;
  104. assert(dynamic_cast<T *>(ptr.get()) != nullptr || dynamic_cast<U *>(ptr.get()) != nullptr);
  105. }
  106. // Base Types
  107. /**
  108. * Expressions will result in a value at runtime (unlike statements).
  109. */
  110. struct expression : public statement {
  111. std::string type() const override { return "Expression"; }
  112. };
  113. // Statements
  114. struct program : public statement {
  115. statements body;
  116. program() = default;
  117. explicit program(statements && body) : body(std::move(body)) {}
  118. std::string type() const override { return "Program"; }
  119. value execute_impl(context &) override {
  120. throw std::runtime_error("Cannot execute program directly, use jinja::runtime instead");
  121. }
  122. };
  123. struct if_statement : public statement {
  124. statement_ptr test;
  125. statements body;
  126. statements alternate;
  127. if_statement(statement_ptr && test, statements && body, statements && alternate)
  128. : test(std::move(test)), body(std::move(body)), alternate(std::move(alternate)) {
  129. chk_type<expression>(this->test);
  130. }
  131. std::string type() const override { return "If"; }
  132. value execute_impl(context & ctx) override;
  133. };
  134. struct identifier;
  135. struct tuple_literal;
  136. /**
  137. * Loop over each item in a sequence
  138. * https://jinja.palletsprojects.com/en/3.0.x/templates/#for
  139. */
  140. struct for_statement : public statement {
  141. statement_ptr loopvar; // Identifier | TupleLiteral
  142. statement_ptr iterable;
  143. statements body;
  144. statements default_block; // if no iteration took place
  145. for_statement(statement_ptr && loopvar, statement_ptr && iterable, statements && body, statements && default_block)
  146. : loopvar(std::move(loopvar)), iterable(std::move(iterable)),
  147. body(std::move(body)), default_block(std::move(default_block)) {
  148. chk_type<identifier, tuple_literal>(this->loopvar);
  149. chk_type<expression>(this->iterable);
  150. }
  151. std::string type() const override { return "For"; }
  152. value execute_impl(context & ctx) override;
  153. };
  154. struct break_statement : public statement {
  155. std::string type() const override { return "Break"; }
  156. struct signal : public std::exception {
  157. const char* what() const noexcept override {
  158. return "Break statement executed";
  159. }
  160. };
  161. value execute_impl(context &) override {
  162. throw break_statement::signal();
  163. }
  164. };
  165. struct continue_statement : public statement {
  166. std::string type() const override { return "Continue"; }
  167. struct signal : public std::exception {
  168. const char* what() const noexcept override {
  169. return "Continue statement executed";
  170. }
  171. };
  172. value execute_impl(context &) override {
  173. throw continue_statement::signal();
  174. }
  175. };
  176. // do nothing
  177. struct noop_statement : public statement {
  178. std::string type() const override { return "Noop"; }
  179. value execute_impl(context &) override {
  180. return mk_val<value_undefined>();
  181. }
  182. };
  183. struct set_statement : public statement {
  184. statement_ptr assignee;
  185. statement_ptr val;
  186. statements body;
  187. set_statement(statement_ptr && assignee, statement_ptr && value, statements && body)
  188. : assignee(std::move(assignee)), val(std::move(value)), body(std::move(body)) {
  189. chk_type<expression>(this->assignee);
  190. chk_type<expression>(this->val);
  191. }
  192. std::string type() const override { return "Set"; }
  193. value execute_impl(context & ctx) override;
  194. };
  195. struct macro_statement : public statement {
  196. statement_ptr name;
  197. statements args;
  198. statements body;
  199. macro_statement(statement_ptr && name, statements && args, statements && body)
  200. : name(std::move(name)), args(std::move(args)), body(std::move(body)) {
  201. chk_type<identifier>(this->name);
  202. for (const auto& arg : this->args) chk_type<expression>(arg);
  203. }
  204. std::string type() const override { return "Macro"; }
  205. value execute_impl(context & ctx) override;
  206. };
  207. struct comment_statement : public statement {
  208. std::string val;
  209. explicit comment_statement(const std::string & v) : val(v) {}
  210. std::string type() const override { return "Comment"; }
  211. value execute_impl(context &) override {
  212. return mk_val<value_undefined>();
  213. }
  214. };
  215. // Expressions
  216. struct member_expression : public expression {
  217. statement_ptr object;
  218. statement_ptr property;
  219. bool computed;
  220. member_expression(statement_ptr && object, statement_ptr && property, bool computed)
  221. : object(std::move(object)), property(std::move(property)), computed(computed) {
  222. chk_type<expression>(this->object);
  223. chk_type<expression>(this->property);
  224. }
  225. std::string type() const override { return "MemberExpression"; }
  226. value execute_impl(context & ctx) override;
  227. };
  228. struct call_expression : public expression {
  229. statement_ptr callee;
  230. statements args;
  231. call_expression(statement_ptr && callee, statements && args)
  232. : callee(std::move(callee)), args(std::move(args)) {
  233. chk_type<expression>(this->callee);
  234. for (const auto& arg : this->args) chk_type<expression>(arg);
  235. }
  236. std::string type() const override { return "CallExpression"; }
  237. value execute_impl(context & ctx) override;
  238. };
  239. /**
  240. * Represents a user-defined variable or symbol in the template.
  241. */
  242. struct identifier : public expression {
  243. std::string val;
  244. explicit identifier(const std::string & val) : val(val) {}
  245. std::string type() const override { return "Identifier"; }
  246. value execute_impl(context & ctx) override;
  247. };
  248. // Literals
  249. struct integer_literal : public expression {
  250. int64_t val;
  251. explicit integer_literal(int64_t val) : val(val) {}
  252. std::string type() const override { return "IntegerLiteral"; }
  253. value execute_impl(context &) override {
  254. return mk_val<value_int>(val);
  255. }
  256. };
  257. struct float_literal : public expression {
  258. double val;
  259. explicit float_literal(double val) : val(val) {}
  260. std::string type() const override { return "FloatLiteral"; }
  261. value execute_impl(context &) override {
  262. return mk_val<value_float>(val);
  263. }
  264. };
  265. struct string_literal : public expression {
  266. std::string val;
  267. explicit string_literal(const std::string & val) : val(val) {}
  268. std::string type() const override { return "StringLiteral"; }
  269. value execute_impl(context &) override {
  270. return mk_val<value_string>(val);
  271. }
  272. };
  273. struct array_literal : public expression {
  274. statements val;
  275. explicit array_literal(statements && val) : val(std::move(val)) {
  276. for (const auto& item : this->val) chk_type<expression>(item);
  277. }
  278. std::string type() const override { return "ArrayLiteral"; }
  279. value execute_impl(context & ctx) override {
  280. auto arr = mk_val<value_array>();
  281. for (const auto & item_stmt : val) {
  282. arr->push_back(item_stmt->execute(ctx));
  283. }
  284. return arr;
  285. }
  286. };
  287. struct tuple_literal : public array_literal {
  288. explicit tuple_literal(statements && val) : array_literal(std::move(val)) {}
  289. std::string type() const override { return "TupleLiteral"; }
  290. };
  291. struct object_literal : public expression {
  292. std::vector<std::pair<statement_ptr, statement_ptr>> val;
  293. explicit object_literal(std::vector<std::pair<statement_ptr, statement_ptr>> && val)
  294. : val(std::move(val)) {
  295. for (const auto & pair : this->val) {
  296. chk_type<expression>(pair.first);
  297. chk_type<expression>(pair.second);
  298. }
  299. }
  300. std::string type() const override { return "ObjectLiteral"; }
  301. value execute_impl(context & ctx) override;
  302. };
  303. // Complex Expressions
  304. /**
  305. * An operation with two sides, separated by an operator.
  306. * Note: Either side can be a Complex Expression, with order
  307. * of operations being determined by the operator.
  308. */
  309. struct binary_expression : public expression {
  310. token op;
  311. statement_ptr left;
  312. statement_ptr right;
  313. binary_expression(token op, statement_ptr && left, statement_ptr && right)
  314. : op(std::move(op)), left(std::move(left)), right(std::move(right)) {
  315. chk_type<expression>(this->left);
  316. chk_type<expression>(this->right);
  317. }
  318. std::string type() const override { return "BinaryExpression"; }
  319. value execute_impl(context & ctx) override;
  320. };
  321. /**
  322. * An operation with two sides, separated by the | operator.
  323. * Operator precedence: https://github.com/pallets/jinja/issues/379#issuecomment-168076202
  324. */
  325. struct filter_expression : public expression {
  326. // either an expression or a value is allowed
  327. statement_ptr operand;
  328. value_string val; // will be set by filter_statement
  329. statement_ptr filter;
  330. filter_expression(statement_ptr && operand, statement_ptr && filter)
  331. : operand(std::move(operand)), filter(std::move(filter)) {
  332. chk_type<expression>(this->operand);
  333. chk_type<identifier, call_expression>(this->filter);
  334. }
  335. filter_expression(value_string && val, statement_ptr && filter)
  336. : val(std::move(val)), filter(std::move(filter)) {
  337. chk_type<identifier, call_expression>(this->filter);
  338. }
  339. std::string type() const override { return "FilterExpression"; }
  340. value execute_impl(context & ctx) override;
  341. };
  342. struct filter_statement : public statement {
  343. statement_ptr filter;
  344. statements body;
  345. filter_statement(statement_ptr && filter, statements && body)
  346. : filter(std::move(filter)), body(std::move(body)) {
  347. chk_type<identifier, call_expression>(this->filter);
  348. }
  349. std::string type() const override { return "FilterStatement"; }
  350. value execute_impl(context & ctx) override;
  351. };
  352. /**
  353. * An operation which filters a sequence of objects by applying a test to each object,
  354. * and only selecting the objects with the test succeeding.
  355. *
  356. * It may also be used as a shortcut for a ternary operator.
  357. */
  358. struct select_expression : public expression {
  359. statement_ptr lhs;
  360. statement_ptr test;
  361. select_expression(statement_ptr && lhs, statement_ptr && test)
  362. : lhs(std::move(lhs)), test(std::move(test)) {
  363. chk_type<expression>(this->lhs);
  364. chk_type<expression>(this->test);
  365. }
  366. std::string type() const override { return "SelectExpression"; }
  367. value execute_impl(context & ctx) override {
  368. auto predicate = test->execute_impl(ctx);
  369. if (!predicate->as_bool()) {
  370. return mk_val<value_undefined>();
  371. }
  372. return lhs->execute_impl(ctx);
  373. }
  374. };
  375. /**
  376. * An operation with two sides, separated by the "is" operator.
  377. * NOTE: "value is something" translates to function call "test_is_something(value)"
  378. */
  379. struct test_expression : public expression {
  380. statement_ptr operand;
  381. bool negate;
  382. statement_ptr test;
  383. test_expression(statement_ptr && operand, bool negate, statement_ptr && test)
  384. : operand(std::move(operand)), negate(negate), test(std::move(test)) {
  385. chk_type<expression>(this->operand);
  386. chk_type<identifier, call_expression>(this->test);
  387. }
  388. std::string type() const override { return "TestExpression"; }
  389. value execute_impl(context & ctx) override;
  390. };
  391. /**
  392. * An operation with one side (operator on the left).
  393. */
  394. struct unary_expression : public expression {
  395. token op;
  396. statement_ptr argument;
  397. unary_expression(token op, statement_ptr && argument)
  398. : op(std::move(op)), argument(std::move(argument)) {
  399. chk_type<expression>(this->argument);
  400. }
  401. std::string type() const override { return "UnaryExpression"; }
  402. value execute_impl(context & ctx) override;
  403. };
  404. struct slice_expression : public expression {
  405. statement_ptr start_expr;
  406. statement_ptr stop_expr;
  407. statement_ptr step_expr;
  408. slice_expression(statement_ptr && start_expr, statement_ptr && stop_expr, statement_ptr && step_expr)
  409. : start_expr(std::move(start_expr)), stop_expr(std::move(stop_expr)), step_expr(std::move(step_expr)) {
  410. chk_type<expression>(this->start_expr);
  411. chk_type<expression>(this->stop_expr);
  412. chk_type<expression>(this->step_expr);
  413. }
  414. std::string type() const override { return "SliceExpression"; }
  415. value execute_impl(context &) override {
  416. throw std::runtime_error("must be handled by MemberExpression");
  417. }
  418. };
  419. struct keyword_argument_expression : public expression {
  420. statement_ptr key;
  421. statement_ptr val;
  422. keyword_argument_expression(statement_ptr && key, statement_ptr && val)
  423. : key(std::move(key)), val(std::move(val)) {
  424. chk_type<identifier>(this->key);
  425. chk_type<expression>(this->val);
  426. }
  427. std::string type() const override { return "KeywordArgumentExpression"; }
  428. value execute_impl(context & ctx) override;
  429. };
  430. struct spread_expression : public expression {
  431. statement_ptr argument;
  432. explicit spread_expression(statement_ptr && argument) : argument(std::move(argument)) {
  433. chk_type<expression>(this->argument);
  434. }
  435. std::string type() const override { return "SpreadExpression"; }
  436. };
  437. struct call_statement : public statement {
  438. statement_ptr call;
  439. statements caller_args;
  440. statements body;
  441. call_statement(statement_ptr && call, statements && caller_args, statements && body)
  442. : call(std::move(call)), caller_args(std::move(caller_args)), body(std::move(body)) {
  443. chk_type<call_expression>(this->call);
  444. for (const auto & arg : this->caller_args) chk_type<expression>(arg);
  445. }
  446. std::string type() const override { return "CallStatement"; }
  447. };
  448. struct ternary_expression : public expression {
  449. statement_ptr condition;
  450. statement_ptr true_expr;
  451. statement_ptr false_expr;
  452. ternary_expression(statement_ptr && condition, statement_ptr && true_expr, statement_ptr && false_expr)
  453. : condition(std::move(condition)), true_expr(std::move(true_expr)), false_expr(std::move(false_expr)) {
  454. chk_type<expression>(this->condition);
  455. chk_type<expression>(this->true_expr);
  456. chk_type<expression>(this->false_expr);
  457. }
  458. std::string type() const override { return "Ternary"; }
  459. value execute_impl(context & ctx) override {
  460. value cond_val = condition->execute(ctx);
  461. if (cond_val->as_bool()) {
  462. return true_expr->execute(ctx);
  463. } else {
  464. return false_expr->execute(ctx);
  465. }
  466. }
  467. };
  468. struct raised_exception : public std::exception {
  469. std::string message;
  470. raised_exception(const std::string & msg) : message(msg) {}
  471. const char* what() const noexcept override {
  472. return message.c_str();
  473. }
  474. };
  475. // Used to rethrow exceptions with modified messages
  476. struct rethrown_exception : public std::exception {
  477. std::string message;
  478. rethrown_exception(const std::string & msg) : message(msg) {}
  479. const char* what() const noexcept override {
  480. return message.c_str();
  481. }
  482. };
  483. //////////////////////
  484. static void gather_string_parts_recursive(const value & val, value_string & parts) {
  485. // TODO: probably allow print value_none as "None" string? currently this breaks some templates
  486. if (is_val<value_string>(val)) {
  487. const auto & str_val = cast_val<value_string>(val)->val_str;
  488. parts->val_str.append(str_val);
  489. } else if (is_val<value_int>(val) || is_val<value_float>(val) || is_val<value_bool>(val)) {
  490. std::string str_val = val->as_string().str();
  491. parts->val_str.append(str_val);
  492. } else if (is_val<value_array>(val)) {
  493. auto items = cast_val<value_array>(val)->as_array();
  494. for (const auto & item : items) {
  495. gather_string_parts_recursive(item, parts);
  496. }
  497. }
  498. }
  499. static std::string render_string_parts(const value_string & parts) {
  500. std::ostringstream oss;
  501. for (const auto & part : parts->val_str.parts) {
  502. oss << part.val;
  503. }
  504. return oss.str();
  505. }
  506. struct runtime {
  507. context & ctx;
  508. explicit runtime(context & ctx) : ctx(ctx) {}
  509. value_array execute(const program & prog) {
  510. value_array results = mk_val<value_array>();
  511. for (const auto & stmt : prog.body) {
  512. value res = stmt->execute(ctx);
  513. results->push_back(std::move(res));
  514. }
  515. return results;
  516. }
  517. static value_string gather_string_parts(const value & val) {
  518. value_string parts = mk_val<value_string>();
  519. gather_string_parts_recursive(val, parts);
  520. // join consecutive parts with the same type
  521. auto & p = parts->val_str.parts;
  522. for (size_t i = 1; i < p.size(); ) {
  523. if (p[i].is_input == p[i - 1].is_input) {
  524. p[i - 1].val += p[i].val;
  525. p.erase(p.begin() + i);
  526. } else {
  527. i++;
  528. }
  529. }
  530. return parts;
  531. }
  532. };
  533. } // namespace jinja