value.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. #pragma once
  2. #include "string.h"
  3. #include <algorithm>
  4. #include <cstdint>
  5. #include <functional>
  6. #include <map>
  7. #include <memory>
  8. #include <set>
  9. #include <sstream>
  10. #include <string>
  11. #include <vector>
  12. namespace jinja {
  13. struct value_t;
  14. using value = std::shared_ptr<value_t>;
  15. // Helper to check the type of a value
  16. template<typename T>
  17. struct extract_pointee {
  18. using type = T;
  19. };
  20. template<typename U>
  21. struct extract_pointee<std::shared_ptr<U>> {
  22. using type = U;
  23. };
  24. template<typename T>
  25. bool is_val(const value & ptr) {
  26. using PointeeType = typename extract_pointee<T>::type;
  27. return dynamic_cast<const PointeeType*>(ptr.get()) != nullptr;
  28. }
  29. template<typename T>
  30. bool is_val(const value_t * ptr) {
  31. using PointeeType = typename extract_pointee<T>::type;
  32. return dynamic_cast<const PointeeType*>(ptr) != nullptr;
  33. }
  34. template<typename T, typename... Args>
  35. std::shared_ptr<typename extract_pointee<T>::type> mk_val(Args&&... args) {
  36. using PointeeType = typename extract_pointee<T>::type;
  37. return std::make_shared<PointeeType>(std::forward<Args>(args)...);
  38. }
  39. template<typename T>
  40. const typename extract_pointee<T>::type * cast_val(const value & ptr) {
  41. using PointeeType = typename extract_pointee<T>::type;
  42. return dynamic_cast<const PointeeType*>(ptr.get());
  43. }
  44. template<typename T>
  45. typename extract_pointee<T>::type * cast_val(value & ptr) {
  46. using PointeeType = typename extract_pointee<T>::type;
  47. return dynamic_cast<PointeeType*>(ptr.get());
  48. }
  49. // End Helper
  50. struct context; // forward declaration
  51. // for converting from JSON to jinja values
  52. // example input JSON:
  53. // {
  54. // "messages": [
  55. // {"role": "user", "content": "Hello!"},
  56. // {"role": "assistant", "content": "Hi there!"}
  57. // ],
  58. // "bos_token": "<s>",
  59. // "eos_token": "</s>",
  60. // }
  61. //
  62. // to mark strings as user input, wrap them in a special object:
  63. // {
  64. // "messages": [
  65. // {
  66. // "role": "user",
  67. // "content": {"__input__": "Hello!"} // this string is user input
  68. // },
  69. // ...
  70. // ],
  71. // }
  72. //
  73. // marking input can be useful for tracking data provenance
  74. // and preventing template injection attacks
  75. //
  76. // Note: T_JSON can be nlohmann::ordered_json
  77. template<typename T_JSON>
  78. void global_from_json(context & ctx, const T_JSON & json_obj, bool mark_input);
  79. //
  80. // base value type
  81. //
  82. struct func_args; // function argument values
  83. using func_handler = std::function<value(const func_args &)>;
  84. using func_builtins = std::map<std::string, func_handler>;
  85. enum value_compare_op { eq, ge, gt, lt, ne };
  86. bool value_compare(const value & a, const value & b, value_compare_op op);
  87. struct value_t {
  88. int64_t val_int;
  89. double val_flt;
  90. string val_str;
  91. bool val_bool;
  92. std::vector<value> val_arr;
  93. struct map {
  94. // once set to true, all keys must be numeric
  95. // caveat: we only allow either all numeric keys or all non-numeric keys
  96. // for now, this only applied to for_statement in case of iterating over object keys/items
  97. bool is_key_numeric = false;
  98. std::map<std::string, value> unordered;
  99. std::vector<std::pair<std::string, value>> ordered;
  100. void insert(const std::string & key, const value & val) {
  101. if (unordered.find(key) != unordered.end()) {
  102. // if key exists, remove from ordered list
  103. ordered.erase(std::remove_if(ordered.begin(), ordered.end(),
  104. [&](const std::pair<std::string, value> & p) { return p.first == key; }),
  105. ordered.end());
  106. }
  107. unordered[key] = val;
  108. ordered.push_back({key, val});
  109. }
  110. } val_obj;
  111. func_handler val_func;
  112. // only used if ctx.is_get_stats = true
  113. struct stats_t {
  114. bool used = false;
  115. // ops can be builtin calls or operators: "array_access", "object_access"
  116. std::set<std::string> ops;
  117. } stats;
  118. value_t() = default;
  119. value_t(const value_t &) = default;
  120. virtual ~value_t() = default;
  121. virtual std::string type() const { return ""; }
  122. virtual int64_t as_int() const { throw std::runtime_error(type() + " is not an int value"); }
  123. virtual double as_float() const { throw std::runtime_error(type() + " is not a float value"); }
  124. virtual string as_string() const { throw std::runtime_error(type() + " is not a string value"); }
  125. virtual bool as_bool() const { throw std::runtime_error(type() + " is not a bool value"); }
  126. virtual const std::vector<value> & as_array() const { throw std::runtime_error(type() + " is not an array value"); }
  127. virtual const std::vector<std::pair<std::string, value>> & as_ordered_object() const { throw std::runtime_error(type() + " is not an object value"); }
  128. virtual value invoke(const func_args &) const { throw std::runtime_error(type() + " is not a function value"); }
  129. virtual bool is_none() const { return false; }
  130. virtual bool is_undefined() const { return false; }
  131. virtual const func_builtins & get_builtins() const {
  132. throw std::runtime_error("No builtins available for type " + type());
  133. }
  134. virtual bool has_key(const std::string & key) {
  135. return val_obj.unordered.find(key) != val_obj.unordered.end();
  136. }
  137. virtual value & at(const std::string & key, value & default_val) {
  138. auto it = val_obj.unordered.find(key);
  139. if (it == val_obj.unordered.end()) {
  140. return default_val;
  141. }
  142. return val_obj.unordered.at(key);
  143. }
  144. virtual value & at(const std::string & key) {
  145. auto it = val_obj.unordered.find(key);
  146. if (it == val_obj.unordered.end()) {
  147. throw std::runtime_error("Key '" + key + "' not found in value of type " + type());
  148. }
  149. return val_obj.unordered.at(key);
  150. }
  151. virtual value & at(int64_t index, value & default_val) {
  152. if (index < 0) {
  153. index += val_arr.size();
  154. }
  155. if (index < 0 || static_cast<size_t>(index) >= val_arr.size()) {
  156. return default_val;
  157. }
  158. return val_arr[index];
  159. }
  160. virtual value & at(int64_t index) {
  161. if (index < 0) {
  162. index += val_arr.size();
  163. }
  164. if (index < 0 || static_cast<size_t>(index) >= val_arr.size()) {
  165. throw std::runtime_error("Index " + std::to_string(index) + " out of bounds for array of size " + std::to_string(val_arr.size()));
  166. }
  167. return val_arr[index];
  168. }
  169. virtual std::string as_repr() const { return as_string().str(); }
  170. };
  171. //
  172. // primitive value types
  173. //
  174. struct value_int_t : public value_t {
  175. value_int_t(int64_t v) { val_int = v; }
  176. virtual std::string type() const override { return "Integer"; }
  177. virtual int64_t as_int() const override { return val_int; }
  178. virtual double as_float() const override { return static_cast<double>(val_int); }
  179. virtual string as_string() const override { return std::to_string(val_int); }
  180. virtual const func_builtins & get_builtins() const override;
  181. };
  182. using value_int = std::shared_ptr<value_int_t>;
  183. struct value_float_t : public value_t {
  184. value_float_t(double v) { val_flt = v; }
  185. virtual std::string type() const override { return "Float"; }
  186. virtual double as_float() const override { return val_flt; }
  187. virtual int64_t as_int() const override { return static_cast<int64_t>(val_flt); }
  188. virtual string as_string() const override {
  189. std::string out = std::to_string(val_flt);
  190. out.erase(out.find_last_not_of('0') + 1, std::string::npos); // remove trailing zeros
  191. if (out.back() == '.') out.push_back('0'); // leave one zero if no decimals
  192. return out;
  193. }
  194. virtual const func_builtins & get_builtins() const override;
  195. };
  196. using value_float = std::shared_ptr<value_float_t>;
  197. struct value_string_t : public value_t {
  198. value_string_t() { val_str = string(); }
  199. value_string_t(const std::string & v) { val_str = string(v); }
  200. value_string_t(const string & v) { val_str = v; }
  201. virtual std::string type() const override { return "String"; }
  202. virtual string as_string() const override { return val_str; }
  203. virtual std::string as_repr() const override {
  204. std::ostringstream ss;
  205. for (const auto & part : val_str.parts) {
  206. ss << (part.is_input ? "INPUT: " : "TMPL: ") << part.val << "\n";
  207. }
  208. return ss.str();
  209. }
  210. virtual bool as_bool() const override {
  211. return val_str.length() > 0;
  212. }
  213. virtual const func_builtins & get_builtins() const override;
  214. void mark_input() {
  215. val_str.mark_input();
  216. }
  217. };
  218. using value_string = std::shared_ptr<value_string_t>;
  219. struct value_bool_t : public value_t {
  220. value_bool_t(bool v) { val_bool = v; }
  221. virtual std::string type() const override { return "Boolean"; }
  222. virtual bool as_bool() const override { return val_bool; }
  223. virtual string as_string() const override { return std::string(val_bool ? "True" : "False"); }
  224. virtual const func_builtins & get_builtins() const override;
  225. };
  226. using value_bool = std::shared_ptr<value_bool_t>;
  227. struct value_array_t : public value_t {
  228. value_array_t() = default;
  229. value_array_t(value & v) {
  230. val_arr = v->val_arr;
  231. }
  232. value_array_t(const std::vector<value> & arr) {
  233. val_arr = arr;
  234. }
  235. void reverse() { std::reverse(val_arr.begin(), val_arr.end()); }
  236. void push_back(const value & val) { val_arr.push_back(val); }
  237. void push_back(value && val) { val_arr.push_back(std::move(val)); }
  238. value pop_at(int64_t index) {
  239. if (index < 0) {
  240. index = static_cast<int64_t>(val_arr.size()) + index;
  241. }
  242. if (index < 0 || index >= static_cast<int64_t>(val_arr.size())) {
  243. throw std::runtime_error("Index " + std::to_string(index) + " out of bounds for array of size " + std::to_string(val_arr.size()));
  244. }
  245. value val = val_arr.at(static_cast<size_t>(index));
  246. val_arr.erase(val_arr.begin() + index);
  247. return val;
  248. }
  249. virtual std::string type() const override { return "Array"; }
  250. virtual const std::vector<value> & as_array() const override { return val_arr; }
  251. virtual string as_string() const override {
  252. std::ostringstream ss;
  253. ss << "[";
  254. for (size_t i = 0; i < val_arr.size(); i++) {
  255. if (i > 0) ss << ", ";
  256. ss << val_arr.at(i)->as_repr();
  257. }
  258. ss << "]";
  259. return ss.str();
  260. }
  261. virtual bool as_bool() const override {
  262. return !val_arr.empty();
  263. }
  264. virtual const func_builtins & get_builtins() const override;
  265. };
  266. using value_array = std::shared_ptr<value_array_t>;
  267. struct value_object_t : public value_t {
  268. bool has_builtins = true; // context and loop objects do not have builtins
  269. value_object_t() = default;
  270. value_object_t(value & v) {
  271. val_obj = v->val_obj;
  272. }
  273. value_object_t(const std::map<std::string, value> & obj) {
  274. for (const auto & pair : obj) {
  275. val_obj.insert(pair.first, pair.second);
  276. }
  277. }
  278. value_object_t(const std::vector<std::pair<std::string, value>> & obj) {
  279. for (const auto & pair : obj) {
  280. val_obj.insert(pair.first, pair.second);
  281. }
  282. }
  283. void insert(const std::string & key, const value & val) {
  284. val_obj.insert(key, val);
  285. }
  286. virtual std::string type() const override { return "Object"; }
  287. virtual const std::vector<std::pair<std::string, value>> & as_ordered_object() const override { return val_obj.ordered; }
  288. virtual bool as_bool() const override {
  289. return !val_obj.unordered.empty();
  290. }
  291. virtual const func_builtins & get_builtins() const override;
  292. };
  293. using value_object = std::shared_ptr<value_object_t>;
  294. //
  295. // null and undefined types
  296. //
  297. struct value_none_t : public value_t {
  298. virtual std::string type() const override { return "None"; }
  299. virtual bool is_none() const override { return true; }
  300. virtual bool as_bool() const override { return false; }
  301. virtual std::string as_repr() const override { return type(); }
  302. virtual const func_builtins & get_builtins() const override;
  303. };
  304. using value_none = std::shared_ptr<value_none_t>;
  305. struct value_undefined_t : public value_t {
  306. std::string hint; // for debugging, to indicate where undefined came from
  307. value_undefined_t(const std::string & h = "") : hint(h) {}
  308. virtual std::string type() const override { return hint.empty() ? "Undefined" : "Undefined (hint: '" + hint + "')"; }
  309. virtual bool is_undefined() const override { return true; }
  310. virtual bool as_bool() const override { return false; }
  311. virtual std::string as_repr() const override { return type(); }
  312. virtual const func_builtins & get_builtins() const override;
  313. };
  314. using value_undefined = std::shared_ptr<value_undefined_t>;
  315. //
  316. // function type
  317. //
  318. struct func_args {
  319. public:
  320. std::string func_name; // for error messages
  321. context & ctx;
  322. func_args(context & ctx) : ctx(ctx) {}
  323. value get_kwarg(const std::string & key, value default_val) const;
  324. value get_kwarg_or_pos(const std::string & key, size_t pos) const;
  325. value get_pos(size_t pos) const;
  326. value get_pos(size_t pos, value default_val) const;
  327. const std::vector<value> & get_args() const;
  328. size_t count() const { return args.size(); }
  329. void push_back(const value & val);
  330. void push_front(const value & val);
  331. void ensure_count(size_t min, size_t max = 999) const {
  332. size_t n = args.size();
  333. if (n < min || n > max) {
  334. throw std::runtime_error("Function '" + func_name + "' expected between " + std::to_string(min) + " and " + std::to_string(max) + " arguments, got " + std::to_string(n));
  335. }
  336. }
  337. template<typename T> void ensure_val(const value & ptr) const {
  338. if (!is_val<T>(ptr)) {
  339. throw std::runtime_error("Function '" + func_name + "' expected value of type " + std::string(typeid(T).name()) + ", got " + ptr->type());
  340. }
  341. }
  342. void ensure_count(bool require0, bool require1, bool require2, bool require3) const {
  343. static auto bool_to_int = [](bool b) { return b ? 1 : 0; };
  344. size_t required = bool_to_int(require0) + bool_to_int(require1) + bool_to_int(require2) + bool_to_int(require3);
  345. ensure_count(required);
  346. }
  347. template<typename T0> void ensure_vals(bool required0 = true) const {
  348. ensure_count(required0, false, false, false);
  349. if (required0 && args.size() > 0) ensure_val<T0>(args[0]);
  350. }
  351. template<typename T0, typename T1> void ensure_vals(bool required0 = true, bool required1 = true) const {
  352. ensure_count(required0, required1, false, false);
  353. if (required0 && args.size() > 0) ensure_val<T0>(args[0]);
  354. if (required1 && args.size() > 1) ensure_val<T1>(args[1]);
  355. }
  356. template<typename T0, typename T1, typename T2> void ensure_vals(bool required0 = true, bool required1 = true, bool required2 = true) const {
  357. ensure_count(required0, required1, required2, false);
  358. if (required0 && args.size() > 0) ensure_val<T0>(args[0]);
  359. if (required1 && args.size() > 1) ensure_val<T1>(args[1]);
  360. if (required2 && args.size() > 2) ensure_val<T2>(args[2]);
  361. }
  362. template<typename T0, typename T1, typename T2, typename T3> void ensure_vals(bool required0 = true, bool required1 = true, bool required2 = true, bool required3 = true) const {
  363. ensure_count(required0, required1, required2, required3);
  364. if (required0 && args.size() > 0) ensure_val<T0>(args[0]);
  365. if (required1 && args.size() > 1) ensure_val<T1>(args[1]);
  366. if (required2 && args.size() > 2) ensure_val<T2>(args[2]);
  367. if (required3 && args.size() > 3) ensure_val<T3>(args[3]);
  368. }
  369. private:
  370. std::vector<value> args;
  371. };
  372. struct value_func_t : public value_t {
  373. std::string name;
  374. value arg0; // bound "this" argument, if any
  375. value_func_t(const std::string & name, const func_handler & func) : name(name) {
  376. val_func = func;
  377. }
  378. value_func_t(const std::string & name, const func_handler & func, const value & arg_this) : name(name), arg0(arg_this) {
  379. val_func = func;
  380. }
  381. virtual value invoke(const func_args & args) const override {
  382. func_args new_args(args); // copy
  383. new_args.func_name = name;
  384. if (arg0) {
  385. new_args.push_front(arg0);
  386. }
  387. return val_func(new_args);
  388. }
  389. virtual std::string type() const override { return "Function"; }
  390. virtual std::string as_repr() const override { return type(); }
  391. };
  392. using value_func = std::shared_ptr<value_func_t>;
  393. // special value for kwarg
  394. struct value_kwarg_t : public value_t {
  395. std::string key;
  396. value val;
  397. value_kwarg_t(const std::string & k, const value & v) : key(k), val(v) {}
  398. virtual std::string type() const override { return "KwArg"; }
  399. virtual std::string as_repr() const override { return type(); }
  400. };
  401. using value_kwarg = std::shared_ptr<value_kwarg_t>;
  402. // utils
  403. const func_builtins & global_builtins();
  404. std::string value_to_json(const value & val, int indent = -1, const std::string_view item_sep = ", ", const std::string_view key_sep = ": ");
  405. struct not_implemented_exception : public std::runtime_error {
  406. not_implemented_exception(const std::string & msg) : std::runtime_error("NotImplemented: " + msg) {}
  407. };
  408. } // namespace jinja