value.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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::map<std::string, value> & as_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 value & at(const std::string & key, value & default_val) {
  135. auto it = val_obj.unordered.find(key);
  136. if (it == val_obj.unordered.end()) {
  137. return default_val;
  138. }
  139. return val_obj.unordered.at(key);
  140. }
  141. virtual value & at(const std::string & key) {
  142. auto it = val_obj.unordered.find(key);
  143. if (it == val_obj.unordered.end()) {
  144. throw std::runtime_error("Key '" + key + "' not found in value of type " + type());
  145. }
  146. return val_obj.unordered.at(key);
  147. }
  148. virtual value & at(size_t index) {
  149. if (index >= val_arr.size()) {
  150. throw std::runtime_error("Index " + std::to_string(index) + " out of bounds for array of size " + std::to_string(val_arr.size()));
  151. }
  152. return val_arr[index];
  153. }
  154. virtual std::string as_repr() const { return as_string().str(); }
  155. };
  156. //
  157. // primitive value types
  158. //
  159. struct value_int_t : public value_t {
  160. value_int_t(int64_t v) { val_int = v; }
  161. virtual std::string type() const override { return "Integer"; }
  162. virtual int64_t as_int() const override { return val_int; }
  163. virtual double as_float() const override { return static_cast<double>(val_int); }
  164. virtual string as_string() const override { return std::to_string(val_int); }
  165. virtual const func_builtins & get_builtins() const override;
  166. };
  167. using value_int = std::shared_ptr<value_int_t>;
  168. struct value_float_t : public value_t {
  169. value_float_t(double v) { val_flt = v; }
  170. virtual std::string type() const override { return "Float"; }
  171. virtual double as_float() const override { return val_flt; }
  172. virtual int64_t as_int() const override { return static_cast<int64_t>(val_flt); }
  173. virtual string as_string() const override {
  174. std::string out = std::to_string(val_flt);
  175. out.erase(out.find_last_not_of('0') + 1, std::string::npos); // remove trailing zeros
  176. if (out.back() == '.') out.push_back('0'); // leave one zero if no decimals
  177. return out;
  178. }
  179. virtual const func_builtins & get_builtins() const override;
  180. };
  181. using value_float = std::shared_ptr<value_float_t>;
  182. struct value_string_t : public value_t {
  183. value_string_t() { val_str = string(); }
  184. value_string_t(const std::string & v) { val_str = string(v); }
  185. value_string_t(const string & v) { val_str = v; }
  186. virtual std::string type() const override { return "String"; }
  187. virtual string as_string() const override { return val_str; }
  188. virtual std::string as_repr() const override {
  189. std::ostringstream ss;
  190. for (const auto & part : val_str.parts) {
  191. ss << (part.is_input ? "INPUT: " : "TMPL: ") << part.val << "\n";
  192. }
  193. return ss.str();
  194. }
  195. virtual bool as_bool() const override {
  196. return val_str.length() > 0;
  197. }
  198. virtual const func_builtins & get_builtins() const override;
  199. void mark_input() {
  200. val_str.mark_input();
  201. }
  202. };
  203. using value_string = std::shared_ptr<value_string_t>;
  204. struct value_bool_t : public value_t {
  205. value_bool_t(bool v) { val_bool = v; }
  206. virtual std::string type() const override { return "Boolean"; }
  207. virtual bool as_bool() const override { return val_bool; }
  208. virtual string as_string() const override { return std::string(val_bool ? "True" : "False"); }
  209. virtual const func_builtins & get_builtins() const override;
  210. };
  211. using value_bool = std::shared_ptr<value_bool_t>;
  212. struct value_array_t : public value_t {
  213. value_array_t() = default;
  214. value_array_t(value & v) {
  215. val_arr = v->val_arr;
  216. }
  217. value_array_t(const std::vector<value> & arr) {
  218. val_arr = arr;
  219. }
  220. void reverse() { std::reverse(val_arr.begin(), val_arr.end()); }
  221. void push_back(const value & val) { val_arr.push_back(val); }
  222. void push_back(value && val) { val_arr.push_back(std::move(val)); }
  223. value pop_at(int64_t index) {
  224. if (index < 0) {
  225. index = static_cast<int64_t>(val_arr.size()) + index;
  226. }
  227. if (index < 0 || index >= static_cast<int64_t>(val_arr.size())) {
  228. throw std::runtime_error("Index " + std::to_string(index) + " out of bounds for array of size " + std::to_string(val_arr.size()));
  229. }
  230. value val = val_arr.at(static_cast<size_t>(index));
  231. val_arr.erase(val_arr.begin() + index);
  232. return val;
  233. }
  234. virtual std::string type() const override { return "Array"; }
  235. virtual const std::vector<value> & as_array() const override { return val_arr; }
  236. virtual string as_string() const override {
  237. std::ostringstream ss;
  238. ss << "[";
  239. for (size_t i = 0; i < val_arr.size(); i++) {
  240. if (i > 0) ss << ", ";
  241. ss << val_arr.at(i)->as_repr();
  242. }
  243. ss << "]";
  244. return ss.str();
  245. }
  246. virtual bool as_bool() const override {
  247. return !val_arr.empty();
  248. }
  249. virtual const func_builtins & get_builtins() const override;
  250. };
  251. using value_array = std::shared_ptr<value_array_t>;
  252. struct value_object_t : public value_t {
  253. bool has_builtins = true; // context and loop objects do not have builtins
  254. value_object_t() = default;
  255. value_object_t(value & v) {
  256. val_obj = v->val_obj;
  257. }
  258. value_object_t(const std::map<std::string, value> & obj) {
  259. for (const auto & pair : obj) {
  260. val_obj.insert(pair.first, pair.second);
  261. }
  262. }
  263. void insert(const std::string & key, const value & val) {
  264. val_obj.insert(key, val);
  265. }
  266. virtual std::string type() const override { return "Object"; }
  267. virtual const std::map<std::string, value> & as_object() const override { return val_obj.unordered; }
  268. virtual bool as_bool() const override {
  269. return !val_obj.unordered.empty();
  270. }
  271. virtual const func_builtins & get_builtins() const override;
  272. };
  273. using value_object = std::shared_ptr<value_object_t>;
  274. //
  275. // null and undefined types
  276. //
  277. struct value_none_t : public value_t {
  278. virtual std::string type() const override { return "None"; }
  279. virtual bool is_none() const override { return true; }
  280. virtual bool as_bool() const override { return false; }
  281. virtual std::string as_repr() const override { return type(); }
  282. virtual const func_builtins & get_builtins() const override;
  283. };
  284. using value_none = std::shared_ptr<value_none_t>;
  285. struct value_undefined_t : public value_t {
  286. std::string hint; // for debugging, to indicate where undefined came from
  287. value_undefined_t(const std::string & h = "") : hint(h) {}
  288. virtual std::string type() const override { return hint.empty() ? "Undefined" : "Undefined (hint: '" + hint + "')"; }
  289. virtual bool is_undefined() const override { return true; }
  290. virtual bool as_bool() const override { return false; }
  291. virtual std::string as_repr() const override { return type(); }
  292. virtual const func_builtins & get_builtins() const override;
  293. };
  294. using value_undefined = std::shared_ptr<value_undefined_t>;
  295. //
  296. // function type
  297. //
  298. struct func_args {
  299. public:
  300. std::string func_name; // for error messages
  301. context & ctx;
  302. func_args(context & ctx) : ctx(ctx) {}
  303. value get_kwarg(const std::string & key, value default_val) const;
  304. value get_kwarg_or_pos(const std::string & key, size_t pos) const;
  305. value get_pos(size_t pos) const;
  306. value get_pos(size_t pos, value default_val) const;
  307. const std::vector<value> & get_args() const;
  308. size_t count() const { return args.size(); }
  309. void push_back(const value & val);
  310. void push_front(const value & val);
  311. void ensure_count(size_t min, size_t max = 999) const {
  312. size_t n = args.size();
  313. if (n < min || n > max) {
  314. throw std::runtime_error("Function '" + func_name + "' expected between " + std::to_string(min) + " and " + std::to_string(max) + " arguments, got " + std::to_string(n));
  315. }
  316. }
  317. template<typename T> void ensure_val(const value & ptr) const {
  318. if (!is_val<T>(ptr)) {
  319. throw std::runtime_error("Function '" + func_name + "' expected value of type " + std::string(typeid(T).name()) + ", got " + ptr->type());
  320. }
  321. }
  322. void ensure_count(bool require0, bool require1, bool require2, bool require3) const {
  323. static auto bool_to_int = [](bool b) { return b ? 1 : 0; };
  324. size_t required = bool_to_int(require0) + bool_to_int(require1) + bool_to_int(require2) + bool_to_int(require3);
  325. ensure_count(required);
  326. }
  327. template<typename T0> void ensure_vals(bool required0 = true) const {
  328. ensure_count(required0, false, false, false);
  329. if (required0 && args.size() > 0) ensure_val<T0>(args[0]);
  330. }
  331. template<typename T0, typename T1> void ensure_vals(bool required0 = true, bool required1 = true) const {
  332. ensure_count(required0, required1, false, false);
  333. if (required0 && args.size() > 0) ensure_val<T0>(args[0]);
  334. if (required1 && args.size() > 1) ensure_val<T1>(args[1]);
  335. }
  336. template<typename T0, typename T1, typename T2> void ensure_vals(bool required0 = true, bool required1 = true, bool required2 = true) const {
  337. ensure_count(required0, required1, required2, false);
  338. if (required0 && args.size() > 0) ensure_val<T0>(args[0]);
  339. if (required1 && args.size() > 1) ensure_val<T1>(args[1]);
  340. if (required2 && args.size() > 2) ensure_val<T2>(args[2]);
  341. }
  342. 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 {
  343. ensure_count(required0, required1, required2, required3);
  344. if (required0 && args.size() > 0) ensure_val<T0>(args[0]);
  345. if (required1 && args.size() > 1) ensure_val<T1>(args[1]);
  346. if (required2 && args.size() > 2) ensure_val<T2>(args[2]);
  347. if (required3 && args.size() > 3) ensure_val<T3>(args[3]);
  348. }
  349. private:
  350. std::vector<value> args;
  351. };
  352. struct value_func_t : public value_t {
  353. std::string name;
  354. value arg0; // bound "this" argument, if any
  355. value_func_t(const std::string & name, const func_handler & func) : name(name) {
  356. val_func = func;
  357. }
  358. value_func_t(const std::string & name, const func_handler & func, const value & arg_this) : name(name), arg0(arg_this) {
  359. val_func = func;
  360. }
  361. virtual value invoke(const func_args & args) const override {
  362. func_args new_args(args); // copy
  363. new_args.func_name = name;
  364. if (arg0) {
  365. new_args.push_front(arg0);
  366. }
  367. return val_func(new_args);
  368. }
  369. virtual std::string type() const override { return "Function"; }
  370. virtual std::string as_repr() const override { return type(); }
  371. };
  372. using value_func = std::shared_ptr<value_func_t>;
  373. // special value for kwarg
  374. struct value_kwarg_t : public value_t {
  375. std::string key;
  376. value val;
  377. value_kwarg_t(const std::string & k, const value & v) : key(k), val(v) {}
  378. virtual std::string type() const override { return "KwArg"; }
  379. virtual std::string as_repr() const override { return type(); }
  380. };
  381. using value_kwarg = std::shared_ptr<value_kwarg_t>;
  382. // utils
  383. const func_builtins & global_builtins();
  384. std::string value_to_json(const value & val, int indent = -1, const std::string_view item_sep = ", ", const std::string_view key_sep = ": ");
  385. struct not_implemented_exception : public std::runtime_error {
  386. not_implemented_exception(const std::string & msg) : std::runtime_error("NotImplemented: " + msg) {}
  387. };
  388. } // namespace jinja