minja.hpp 113 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788
  1. /*
  2. Copyright 2024 Google LLC
  3. Use of this source code is governed by an MIT-style
  4. license that can be found in the LICENSE file or at
  5. https://opensource.org/licenses/MIT.
  6. */
  7. // SPDX-License-Identifier: MIT
  8. #pragma once
  9. #include <iostream>
  10. #include <string>
  11. #include <vector>
  12. #include <regex>
  13. #include <memory>
  14. #include <stdexcept>
  15. #include <sstream>
  16. #include <unordered_set>
  17. #include <json.hpp>
  18. using json = nlohmann::ordered_json;
  19. namespace minja {
  20. class Context;
  21. struct Options {
  22. bool trim_blocks; // removes the first newline after a block
  23. bool lstrip_blocks; // removes leading whitespace on the line of the block
  24. bool keep_trailing_newline; // don't remove last newline
  25. };
  26. struct ArgumentsValue;
  27. inline std::string normalize_newlines(const std::string & s) {
  28. #ifdef _WIN32
  29. static const std::regex nl_regex("\r\n");
  30. return std::regex_replace(s, nl_regex, "\n");
  31. #else
  32. return s;
  33. #endif
  34. }
  35. /* Values that behave roughly like in Python. */
  36. class Value : public std::enable_shared_from_this<Value> {
  37. public:
  38. using CallableType = std::function<Value(const std::shared_ptr<Context> &, ArgumentsValue &)>;
  39. using FilterType = std::function<Value(const std::shared_ptr<Context> &, ArgumentsValue &)>;
  40. private:
  41. using ObjectType = nlohmann::ordered_map<json, Value>; // Only contains primitive keys
  42. using ArrayType = std::vector<Value>;
  43. std::shared_ptr<ArrayType> array_;
  44. std::shared_ptr<ObjectType> object_;
  45. std::shared_ptr<CallableType> callable_;
  46. json primitive_;
  47. Value(const std::shared_ptr<ArrayType> & array) : array_(array) {}
  48. Value(const std::shared_ptr<ObjectType> & object) : object_(object) {}
  49. Value(const std::shared_ptr<CallableType> & callable) : object_(std::make_shared<ObjectType>()), callable_(callable) {}
  50. /* Python-style string repr */
  51. static void dump_string(const json & primitive, std::ostringstream & out, char string_quote = '\'') {
  52. if (!primitive.is_string()) throw std::runtime_error("Value is not a string: " + primitive.dump());
  53. auto s = primitive.dump();
  54. if (string_quote == '"' || s.find('\'') != std::string::npos) {
  55. out << s;
  56. return;
  57. }
  58. // Reuse json dump, just changing string quotes
  59. out << string_quote;
  60. for (size_t i = 1, n = s.size() - 1; i < n; ++i) {
  61. if (s[i] == '\\' && s[i + 1] == '"') {
  62. out << '"';
  63. i++;
  64. } else if (s[i] == string_quote) {
  65. out << '\\' << string_quote;
  66. } else {
  67. out << s[i];
  68. }
  69. }
  70. out << string_quote;
  71. }
  72. void dump(std::ostringstream & out, int indent = -1, int level = 0, bool to_json = false) const {
  73. auto print_indent = [&](int level) {
  74. if (indent > 0) {
  75. out << "\n";
  76. for (int i = 0, n = level * indent; i < n; ++i) out << ' ';
  77. }
  78. };
  79. auto print_sub_sep = [&]() {
  80. out << ',';
  81. if (indent < 0) out << ' ';
  82. else print_indent(level + 1);
  83. };
  84. auto string_quote = to_json ? '"' : '\'';
  85. if (is_null()) out << "null";
  86. else if (array_) {
  87. out << "[";
  88. print_indent(level + 1);
  89. for (size_t i = 0; i < array_->size(); ++i) {
  90. if (i) print_sub_sep();
  91. (*array_)[i].dump(out, indent, level + 1, to_json);
  92. }
  93. print_indent(level);
  94. out << "]";
  95. } else if (object_) {
  96. out << "{";
  97. print_indent(level + 1);
  98. for (auto begin = object_->begin(), it = begin; it != object_->end(); ++it) {
  99. if (it != begin) print_sub_sep();
  100. if (it->first.is_string()) {
  101. dump_string(it->first, out, string_quote);
  102. } else {
  103. out << string_quote << it->first.dump() << string_quote;
  104. }
  105. out << ": ";
  106. it->second.dump(out, indent, level + 1, to_json);
  107. }
  108. print_indent(level);
  109. out << "}";
  110. } else if (callable_) {
  111. throw std::runtime_error("Cannot dump callable to JSON");
  112. } else if (is_boolean() && !to_json) {
  113. out << (this->to_bool() ? "True" : "False");
  114. } else if (is_string() && !to_json) {
  115. dump_string(primitive_, out, string_quote);
  116. } else {
  117. out << primitive_.dump();
  118. }
  119. }
  120. public:
  121. Value() {}
  122. Value(const bool& v) : primitive_(v) {}
  123. Value(const int64_t & v) : primitive_(v) {}
  124. Value(const double& v) : primitive_(v) {}
  125. Value(const std::nullptr_t &) {}
  126. Value(const std::string & v) : primitive_(v) {}
  127. Value(const char * v) : primitive_(std::string(v)) {}
  128. Value(const json & v) {
  129. if (v.is_object()) {
  130. auto object = std::make_shared<ObjectType>();
  131. for (auto it = v.begin(); it != v.end(); ++it) {
  132. (*object)[it.key()] = it.value();
  133. }
  134. object_ = std::move(object);
  135. } else if (v.is_array()) {
  136. auto array = std::make_shared<ArrayType>();
  137. for (const auto& item : v) {
  138. array->push_back(Value(item));
  139. }
  140. array_ = array;
  141. } else {
  142. primitive_ = v;
  143. }
  144. }
  145. std::vector<Value> keys() {
  146. if (!object_) throw std::runtime_error("Value is not an object: " + dump());
  147. std::vector<Value> res;
  148. for (const auto& item : *object_) {
  149. res.push_back(item.first);
  150. }
  151. return res;
  152. }
  153. size_t size() const {
  154. if (is_object()) return object_->size();
  155. if (is_array()) return array_->size();
  156. if (is_string()) return primitive_.get<std::string>().length();
  157. throw std::runtime_error("Value is not an array or object: " + dump());
  158. }
  159. static Value array(const std::vector<Value> values = {}) {
  160. auto array = std::make_shared<ArrayType>();
  161. for (const auto& item : values) {
  162. array->push_back(item);
  163. }
  164. return Value(array);
  165. }
  166. static Value object(const std::shared_ptr<ObjectType> object = std::make_shared<ObjectType>()) {
  167. return Value(object);
  168. }
  169. static Value callable(const CallableType & callable) {
  170. return Value(std::make_shared<CallableType>(callable));
  171. }
  172. void insert(size_t index, const Value& v) {
  173. if (!array_)
  174. throw std::runtime_error("Value is not an array: " + dump());
  175. array_->insert(array_->begin() + index, v);
  176. }
  177. void push_back(const Value& v) {
  178. if (!array_)
  179. throw std::runtime_error("Value is not an array: " + dump());
  180. array_->push_back(v);
  181. }
  182. Value pop(const Value& index) {
  183. if (is_array()) {
  184. if (array_->empty())
  185. throw std::runtime_error("pop from empty list");
  186. if (index.is_null()) {
  187. auto ret = array_->back();
  188. array_->pop_back();
  189. return ret;
  190. } else if (!index.is_number_integer()) {
  191. throw std::runtime_error("pop index must be an integer: " + index.dump());
  192. } else {
  193. auto i = index.get<int>();
  194. if (i < 0 || i >= static_cast<int>(array_->size()))
  195. throw std::runtime_error("pop index out of range: " + index.dump());
  196. auto it = array_->begin() + (i < 0 ? array_->size() + i : i);
  197. auto ret = *it;
  198. array_->erase(it);
  199. return ret;
  200. }
  201. } else if (is_object()) {
  202. if (!index.is_hashable())
  203. throw std::runtime_error("Unashable type: " + index.dump());
  204. auto it = object_->find(index.primitive_);
  205. if (it == object_->end())
  206. throw std::runtime_error("Key not found: " + index.dump());
  207. auto ret = it->second;
  208. object_->erase(it);
  209. return ret;
  210. } else {
  211. throw std::runtime_error("Value is not an array or object: " + dump());
  212. }
  213. }
  214. Value get(const Value& key) {
  215. if (array_) {
  216. if (!key.is_number_integer()) {
  217. return Value();
  218. }
  219. auto index = key.get<int>();
  220. return array_->at(index < 0 ? array_->size() + index : index);
  221. } else if (object_) {
  222. if (!key.is_hashable()) throw std::runtime_error("Unashable type: " + dump());
  223. auto it = object_->find(key.primitive_);
  224. if (it == object_->end()) return Value();
  225. return it->second;
  226. }
  227. return Value();
  228. }
  229. void set(const Value& key, const Value& value) {
  230. if (!object_) throw std::runtime_error("Value is not an object: " + dump());
  231. if (!key.is_hashable()) throw std::runtime_error("Unashable type: " + dump());
  232. (*object_)[key.primitive_] = value;
  233. }
  234. Value call(const std::shared_ptr<Context> & context, ArgumentsValue & args) const {
  235. if (!callable_) throw std::runtime_error("Value is not callable: " + dump());
  236. return (*callable_)(context, args);
  237. }
  238. bool is_object() const { return !!object_; }
  239. bool is_array() const { return !!array_; }
  240. bool is_callable() const { return !!callable_; }
  241. bool is_null() const { return !object_ && !array_ && primitive_.is_null() && !callable_; }
  242. bool is_boolean() const { return primitive_.is_boolean(); }
  243. bool is_number_integer() const { return primitive_.is_number_integer(); }
  244. bool is_number_float() const { return primitive_.is_number_float(); }
  245. bool is_number() const { return primitive_.is_number(); }
  246. bool is_string() const { return primitive_.is_string(); }
  247. bool is_iterable() const { return is_array() || is_object() || is_string(); }
  248. bool is_primitive() const { return !array_ && !object_ && !callable_; }
  249. bool is_hashable() const { return is_primitive(); }
  250. bool empty() const {
  251. if (is_null())
  252. throw std::runtime_error("Undefined value or reference");
  253. if (is_string()) return primitive_.empty();
  254. if (is_array()) return array_->empty();
  255. if (is_object()) return object_->empty();
  256. return false;
  257. }
  258. void for_each(const std::function<void(Value &)> & callback) const {
  259. if (is_null())
  260. throw std::runtime_error("Undefined value or reference");
  261. if (array_) {
  262. for (auto& item : *array_) {
  263. callback(item);
  264. }
  265. } else if (object_) {
  266. for (auto & item : *object_) {
  267. Value key(item.first);
  268. callback(key);
  269. }
  270. } else if (is_string()) {
  271. for (char c : primitive_.get<std::string>()) {
  272. auto val = Value(std::string(1, c));
  273. callback(val);
  274. }
  275. } else {
  276. throw std::runtime_error("Value is not iterable: " + dump());
  277. }
  278. }
  279. bool to_bool() const {
  280. if (is_null()) return false;
  281. if (is_boolean()) return get<bool>();
  282. if (is_number()) return get<double>() != 0;
  283. if (is_string()) return !get<std::string>().empty();
  284. if (is_array()) return !empty();
  285. return true;
  286. }
  287. int64_t to_int() const {
  288. if (is_null()) return 0;
  289. if (is_boolean()) return get<bool>() ? 1 : 0;
  290. if (is_number()) return static_cast<int64_t>(get<double>());
  291. if (is_string()) {
  292. try {
  293. return std::stol(get<std::string>());
  294. } catch (const std::exception &) {
  295. return 0;
  296. }
  297. }
  298. return 0;
  299. }
  300. bool operator<(const Value & other) const {
  301. if (is_null())
  302. throw std::runtime_error("Undefined value or reference");
  303. if (is_number() && other.is_number()) return get<double>() < other.get<double>();
  304. if (is_string() && other.is_string()) return get<std::string>() < other.get<std::string>();
  305. throw std::runtime_error("Cannot compare values: " + dump() + " < " + other.dump());
  306. }
  307. bool operator>=(const Value & other) const { return !(*this < other); }
  308. bool operator>(const Value & other) const {
  309. if (is_null())
  310. throw std::runtime_error("Undefined value or reference");
  311. if (is_number() && other.is_number()) return get<double>() > other.get<double>();
  312. if (is_string() && other.is_string()) return get<std::string>() > other.get<std::string>();
  313. throw std::runtime_error("Cannot compare values: " + dump() + " > " + other.dump());
  314. }
  315. bool operator<=(const Value & other) const { return !(*this > other); }
  316. bool operator==(const Value & other) const {
  317. if (callable_ || other.callable_) {
  318. if (callable_.get() != other.callable_.get()) return false;
  319. }
  320. if (array_) {
  321. if (!other.array_) return false;
  322. if (array_->size() != other.array_->size()) return false;
  323. for (size_t i = 0; i < array_->size(); ++i) {
  324. if (!(*array_)[i].to_bool() || !(*other.array_)[i].to_bool() || (*array_)[i] != (*other.array_)[i]) return false;
  325. }
  326. return true;
  327. } else if (object_) {
  328. if (!other.object_) return false;
  329. if (object_->size() != other.object_->size()) return false;
  330. for (const auto& item : *object_) {
  331. if (!item.second.to_bool() || !other.object_->count(item.first) || item.second != other.object_->at(item.first)) return false;
  332. }
  333. return true;
  334. } else {
  335. return primitive_ == other.primitive_;
  336. }
  337. }
  338. bool operator!=(const Value & other) const { return !(*this == other); }
  339. bool contains(const char * key) const { return contains(std::string(key)); }
  340. bool contains(const std::string & key) const {
  341. if (array_) {
  342. return false;
  343. } else if (object_) {
  344. return object_->find(key) != object_->end();
  345. } else {
  346. throw std::runtime_error("contains can only be called on arrays and objects: " + dump());
  347. }
  348. }
  349. bool contains(const Value & value) const {
  350. if (is_null())
  351. throw std::runtime_error("Undefined value or reference");
  352. if (array_) {
  353. for (const auto& item : *array_) {
  354. if (item.to_bool() && item == value) return true;
  355. }
  356. return false;
  357. } else if (object_) {
  358. if (!value.is_hashable()) throw std::runtime_error("Unashable type: " + value.dump());
  359. return object_->find(value.primitive_) != object_->end();
  360. } else {
  361. throw std::runtime_error("contains can only be called on arrays and objects: " + dump());
  362. }
  363. }
  364. void erase(size_t index) {
  365. if (!array_) throw std::runtime_error("Value is not an array: " + dump());
  366. array_->erase(array_->begin() + index);
  367. }
  368. void erase(const std::string & key) {
  369. if (!object_) throw std::runtime_error("Value is not an object: " + dump());
  370. object_->erase(key);
  371. }
  372. const Value& at(const Value & index) const {
  373. return const_cast<Value*>(this)->at(index);
  374. }
  375. Value& at(const Value & index) {
  376. if (!index.is_hashable()) throw std::runtime_error("Unashable type: " + dump());
  377. if (is_array()) return array_->at(index.get<int>());
  378. if (is_object()) return object_->at(index.primitive_);
  379. throw std::runtime_error("Value is not an array or object: " + dump());
  380. }
  381. const Value& at(size_t index) const {
  382. return const_cast<Value*>(this)->at(index);
  383. }
  384. Value& at(size_t index) {
  385. if (is_null())
  386. throw std::runtime_error("Undefined value or reference");
  387. if (is_array()) return array_->at(index);
  388. if (is_object()) return object_->at(index);
  389. throw std::runtime_error("Value is not an array or object: " + dump());
  390. }
  391. template <typename T>
  392. T get(const std::string & key, T default_value) const {
  393. if (!contains(key)) return default_value;
  394. return at(key).get<T>();
  395. }
  396. template <typename T>
  397. T get() const {
  398. if (is_primitive()) return primitive_.get<T>();
  399. throw std::runtime_error("get<T> not defined for this value type: " + dump());
  400. }
  401. std::string dump(int indent=-1, bool to_json=false) const {
  402. std::ostringstream out;
  403. dump(out, indent, 0, to_json);
  404. return out.str();
  405. }
  406. Value operator-() const {
  407. if (is_number_integer())
  408. return -get<int64_t>();
  409. else
  410. return -get<double>();
  411. }
  412. std::string to_str() const {
  413. if (is_string()) return get<std::string>();
  414. if (is_number_integer()) return std::to_string(get<int64_t>());
  415. if (is_number_float()) return std::to_string(get<double>());
  416. if (is_boolean()) return get<bool>() ? "True" : "False";
  417. if (is_null()) return "None";
  418. return dump();
  419. }
  420. Value operator+(const Value& rhs) const {
  421. if (is_string() || rhs.is_string()) {
  422. return to_str() + rhs.to_str();
  423. } else if (is_number_integer() && rhs.is_number_integer()) {
  424. return get<int64_t>() + rhs.get<int64_t>();
  425. } else if (is_array() && rhs.is_array()) {
  426. auto res = Value::array();
  427. for (const auto& item : *array_) res.push_back(item);
  428. for (const auto& item : *rhs.array_) res.push_back(item);
  429. return res;
  430. } else {
  431. return get<double>() + rhs.get<double>();
  432. }
  433. }
  434. Value operator-(const Value& rhs) const {
  435. if (is_number_integer() && rhs.is_number_integer())
  436. return get<int64_t>() - rhs.get<int64_t>();
  437. else
  438. return get<double>() - rhs.get<double>();
  439. }
  440. Value operator*(const Value& rhs) const {
  441. if (is_string() && rhs.is_number_integer()) {
  442. std::ostringstream out;
  443. for (int64_t i = 0, n = rhs.get<int64_t>(); i < n; ++i) {
  444. out << to_str();
  445. }
  446. return out.str();
  447. }
  448. else if (is_number_integer() && rhs.is_number_integer())
  449. return get<int64_t>() * rhs.get<int64_t>();
  450. else
  451. return get<double>() * rhs.get<double>();
  452. }
  453. Value operator/(const Value& rhs) const {
  454. if (is_number_integer() && rhs.is_number_integer())
  455. return get<int64_t>() / rhs.get<int64_t>();
  456. else
  457. return get<double>() / rhs.get<double>();
  458. }
  459. Value operator%(const Value& rhs) const {
  460. return get<int64_t>() % rhs.get<int64_t>();
  461. }
  462. };
  463. struct ArgumentsValue {
  464. std::vector<Value> args;
  465. std::vector<std::pair<std::string, Value>> kwargs;
  466. bool has_named(const std::string & name) {
  467. for (const auto & p : kwargs) {
  468. if (p.first == name) return true;
  469. }
  470. return false;
  471. }
  472. Value get_named(const std::string & name) {
  473. for (const auto & [key, value] : kwargs) {
  474. if (key == name) return value;
  475. }
  476. return Value();
  477. }
  478. bool empty() {
  479. return args.empty() && kwargs.empty();
  480. }
  481. void expectArgs(const std::string & method_name, const std::pair<size_t, size_t> & pos_count, const std::pair<size_t, size_t> & kw_count) {
  482. if (args.size() < pos_count.first || args.size() > pos_count.second || kwargs.size() < kw_count.first || kwargs.size() > kw_count.second) {
  483. std::ostringstream out;
  484. out << method_name << " must have between " << pos_count.first << " and " << pos_count.second << " positional arguments and between " << kw_count.first << " and " << kw_count.second << " keyword arguments";
  485. throw std::runtime_error(out.str());
  486. }
  487. }
  488. };
  489. template <>
  490. inline json Value::get<json>() const {
  491. if (is_primitive()) return primitive_;
  492. if (is_null()) return json();
  493. if (array_) {
  494. std::vector<json> res;
  495. for (const auto& item : *array_) {
  496. res.push_back(item.get<json>());
  497. }
  498. return res;
  499. }
  500. if (object_) {
  501. json res = json::object();
  502. for (const auto& [key, value] : *object_) {
  503. if (key.is_string()) {
  504. res[key.get<std::string>()] = value.get<json>();
  505. } else if (key.is_primitive()) {
  506. res[key.dump()] = value.get<json>();
  507. } else {
  508. throw std::runtime_error("Invalid key type for conversion to JSON: " + key.dump());
  509. }
  510. }
  511. if (is_callable()) {
  512. res["__callable__"] = true;
  513. }
  514. return res;
  515. }
  516. throw std::runtime_error("get<json> not defined for this value type: " + dump());
  517. }
  518. } // namespace minja
  519. namespace std {
  520. template <>
  521. struct hash<minja::Value> {
  522. size_t operator()(const minja::Value & v) const {
  523. if (!v.is_hashable())
  524. throw std::runtime_error("Unsupported type for hashing: " + v.dump());
  525. return std::hash<json>()(v.get<json>());
  526. }
  527. };
  528. } // namespace std
  529. namespace minja {
  530. static std::string error_location_suffix(const std::string & source, size_t pos) {
  531. auto get_line = [&](size_t line) {
  532. auto start = source.begin();
  533. for (size_t i = 1; i < line; ++i) {
  534. start = std::find(start, source.end(), '\n') + 1;
  535. }
  536. auto end = std::find(start, source.end(), '\n');
  537. return std::string(start, end);
  538. };
  539. auto start = source.begin();
  540. auto end = source.end();
  541. auto it = start + pos;
  542. auto line = std::count(start, it, '\n') + 1;
  543. auto max_line = std::count(start, end, '\n') + 1;
  544. auto col = pos - std::string(start, it).rfind('\n');
  545. std::ostringstream out;
  546. out << " at row " << line << ", column " << col << ":\n";
  547. if (line > 1) out << get_line(line - 1) << "\n";
  548. out << get_line(line) << "\n";
  549. out << std::string(col - 1, ' ') << "^\n";
  550. if (line < max_line) out << get_line(line + 1) << "\n";
  551. return out.str();
  552. }
  553. class Context : public std::enable_shared_from_this<Context> {
  554. protected:
  555. Value values_;
  556. std::shared_ptr<Context> parent_;
  557. public:
  558. Context(Value && values, const std::shared_ptr<Context> & parent = nullptr) : values_(std::move(values)), parent_(parent) {
  559. if (!values_.is_object()) throw std::runtime_error("Context values must be an object: " + values_.dump());
  560. }
  561. virtual ~Context() {}
  562. static std::shared_ptr<Context> builtins();
  563. static std::shared_ptr<Context> make(Value && values, const std::shared_ptr<Context> & parent = builtins());
  564. std::vector<Value> keys() {
  565. return values_.keys();
  566. }
  567. virtual Value get(const Value & key) {
  568. if (values_.contains(key)) return values_.at(key);
  569. if (parent_) return parent_->get(key);
  570. return Value();
  571. }
  572. virtual Value & at(const Value & key) {
  573. if (values_.contains(key)) return values_.at(key);
  574. if (parent_) return parent_->at(key);
  575. throw std::runtime_error("Undefined variable: " + key.dump());
  576. }
  577. virtual bool contains(const Value & key) {
  578. if (values_.contains(key)) return true;
  579. if (parent_) return parent_->contains(key);
  580. return false;
  581. }
  582. virtual void set(const Value & key, Value & value) {
  583. values_.set(key, value);
  584. }
  585. };
  586. struct Location {
  587. std::shared_ptr<std::string> source;
  588. size_t pos;
  589. };
  590. class Expression {
  591. protected:
  592. virtual Value do_evaluate(const std::shared_ptr<Context> & context) const = 0;
  593. public:
  594. using Parameters = std::vector<std::pair<std::string, std::shared_ptr<Expression>>>;
  595. Location location;
  596. Expression(const Location & location) : location(location) {}
  597. virtual ~Expression() = default;
  598. Value evaluate(const std::shared_ptr<Context> & context) const {
  599. try {
  600. return do_evaluate(context);
  601. } catch (const std::exception & e) {
  602. std::ostringstream out;
  603. out << e.what();
  604. if (location.source) out << error_location_suffix(*location.source, location.pos);
  605. throw std::runtime_error(out.str());
  606. }
  607. }
  608. };
  609. class VariableExpr : public Expression {
  610. std::string name;
  611. public:
  612. VariableExpr(const Location & location, const std::string& n)
  613. : Expression(location), name(n) {}
  614. std::string get_name() const { return name; }
  615. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  616. if (!context->contains(name)) {
  617. return Value();
  618. }
  619. return context->at(name);
  620. }
  621. };
  622. static void destructuring_assign(const std::vector<std::string> & var_names, const std::shared_ptr<Context> & context, Value& item) {
  623. if (var_names.size() == 1) {
  624. Value name(var_names[0]);
  625. context->set(name, item);
  626. } else {
  627. if (!item.is_array() || item.size() != var_names.size()) {
  628. throw std::runtime_error("Mismatched number of variables and items in destructuring assignment");
  629. }
  630. for (size_t i = 0; i < var_names.size(); ++i) {
  631. context->set(var_names[i], item.at(i));
  632. }
  633. }
  634. }
  635. enum SpaceHandling { Keep, Strip, StripSpaces, StripNewline };
  636. class TemplateToken {
  637. public:
  638. enum class Type { Text, Expression, If, Else, Elif, EndIf, For, EndFor, Set, EndSet, Comment, Macro, EndMacro, Filter, EndFilter };
  639. static std::string typeToString(Type t) {
  640. switch (t) {
  641. case Type::Text: return "text";
  642. case Type::Expression: return "expression";
  643. case Type::If: return "if";
  644. case Type::Else: return "else";
  645. case Type::Elif: return "elif";
  646. case Type::EndIf: return "endif";
  647. case Type::For: return "for";
  648. case Type::EndFor: return "endfor";
  649. case Type::Set: return "set";
  650. case Type::EndSet: return "endset";
  651. case Type::Comment: return "comment";
  652. case Type::Macro: return "macro";
  653. case Type::EndMacro: return "endmacro";
  654. case Type::Filter: return "filter";
  655. case Type::EndFilter: return "endfilter";
  656. }
  657. return "Unknown";
  658. }
  659. TemplateToken(Type type, const Location & location, SpaceHandling pre, SpaceHandling post) : type(type), location(location), pre_space(pre), post_space(post) {}
  660. virtual ~TemplateToken() = default;
  661. Type type;
  662. Location location;
  663. SpaceHandling pre_space = SpaceHandling::Keep;
  664. SpaceHandling post_space = SpaceHandling::Keep;
  665. };
  666. struct TextTemplateToken : public TemplateToken {
  667. std::string text;
  668. TextTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, const std::string& t) : TemplateToken(Type::Text, location, pre, post), text(t) {}
  669. };
  670. struct ExpressionTemplateToken : public TemplateToken {
  671. std::shared_ptr<Expression> expr;
  672. ExpressionTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, std::shared_ptr<Expression> && e) : TemplateToken(Type::Expression, location, pre, post), expr(std::move(e)) {}
  673. };
  674. struct IfTemplateToken : public TemplateToken {
  675. std::shared_ptr<Expression> condition;
  676. IfTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, std::shared_ptr<Expression> && c) : TemplateToken(Type::If, location, pre, post), condition(std::move(c)) {}
  677. };
  678. struct ElifTemplateToken : public TemplateToken {
  679. std::shared_ptr<Expression> condition;
  680. ElifTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, std::shared_ptr<Expression> && c) : TemplateToken(Type::Elif, location, pre, post), condition(std::move(c)) {}
  681. };
  682. struct ElseTemplateToken : public TemplateToken {
  683. ElseTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::Else, location, pre, post) {}
  684. };
  685. struct EndIfTemplateToken : public TemplateToken {
  686. EndIfTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::EndIf, location, pre, post) {}
  687. };
  688. struct MacroTemplateToken : public TemplateToken {
  689. std::shared_ptr<VariableExpr> name;
  690. Expression::Parameters params;
  691. MacroTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, std::shared_ptr<VariableExpr> && n, Expression::Parameters && p)
  692. : TemplateToken(Type::Macro, location, pre, post), name(std::move(n)), params(std::move(p)) {}
  693. };
  694. struct EndMacroTemplateToken : public TemplateToken {
  695. EndMacroTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::EndMacro, location, pre, post) {}
  696. };
  697. struct FilterTemplateToken : public TemplateToken {
  698. std::shared_ptr<Expression> filter;
  699. FilterTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, std::shared_ptr<Expression> && filter)
  700. : TemplateToken(Type::Filter, location, pre, post), filter(std::move(filter)) {}
  701. };
  702. struct EndFilterTemplateToken : public TemplateToken {
  703. EndFilterTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::EndFilter, location, pre, post) {}
  704. };
  705. struct ForTemplateToken : public TemplateToken {
  706. std::vector<std::string> var_names;
  707. std::shared_ptr<Expression> iterable;
  708. std::shared_ptr<Expression> condition;
  709. bool recursive;
  710. ForTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, const std::vector<std::string> & vns, std::shared_ptr<Expression> && iter,
  711. std::shared_ptr<Expression> && c, bool r)
  712. : TemplateToken(Type::For, location, pre, post), var_names(vns), iterable(std::move(iter)), condition(std::move(c)), recursive(r) {}
  713. };
  714. struct EndForTemplateToken : public TemplateToken {
  715. EndForTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::EndFor, location, pre, post) {}
  716. };
  717. struct SetTemplateToken : public TemplateToken {
  718. std::string ns;
  719. std::vector<std::string> var_names;
  720. std::shared_ptr<Expression> value;
  721. SetTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, const std::string & ns, const std::vector<std::string> & vns, std::shared_ptr<Expression> && v)
  722. : TemplateToken(Type::Set, location, pre, post), ns(ns), var_names(vns), value(std::move(v)) {}
  723. };
  724. struct EndSetTemplateToken : public TemplateToken {
  725. EndSetTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::EndSet, location, pre, post) {}
  726. };
  727. struct CommentTemplateToken : public TemplateToken {
  728. std::string text;
  729. CommentTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, const std::string& t) : TemplateToken(Type::Comment, location, pre, post), text(t) {}
  730. };
  731. class TemplateNode {
  732. Location location_;
  733. protected:
  734. virtual void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const = 0;
  735. public:
  736. TemplateNode(const Location & location) : location_(location) {}
  737. void render(std::ostringstream & out, const std::shared_ptr<Context> & context) const {
  738. try {
  739. do_render(out, context);
  740. } catch (const std::exception & e) {
  741. std::ostringstream err;
  742. err << e.what();
  743. if (location_.source) err << error_location_suffix(*location_.source, location_.pos);
  744. throw std::runtime_error(err.str());
  745. }
  746. }
  747. const Location & location() const { return location_; }
  748. virtual ~TemplateNode() = default;
  749. std::string render(const std::shared_ptr<Context> & context) const {
  750. std::ostringstream out;
  751. render(out, context);
  752. return out.str();
  753. }
  754. };
  755. class SequenceNode : public TemplateNode {
  756. std::vector<std::shared_ptr<TemplateNode>> children;
  757. public:
  758. SequenceNode(const Location & location, std::vector<std::shared_ptr<TemplateNode>> && c)
  759. : TemplateNode(location), children(std::move(c)) {}
  760. void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const override {
  761. for (const auto& child : children) child->render(out, context);
  762. }
  763. };
  764. class TextNode : public TemplateNode {
  765. std::string text;
  766. public:
  767. TextNode(const Location & location, const std::string& t) : TemplateNode(location), text(t) {}
  768. void do_render(std::ostringstream & out, const std::shared_ptr<Context> &) const override {
  769. out << text;
  770. }
  771. };
  772. class ExpressionNode : public TemplateNode {
  773. std::shared_ptr<Expression> expr;
  774. public:
  775. ExpressionNode(const Location & location, std::shared_ptr<Expression> && e) : TemplateNode(location), expr(std::move(e)) {}
  776. void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const override {
  777. if (!expr) throw std::runtime_error("ExpressionNode.expr is null");
  778. auto result = expr->evaluate(context);
  779. if (result.is_string()) {
  780. out << result.get<std::string>();
  781. } else if (result.is_boolean()) {
  782. out << (result.get<bool>() ? "True" : "False");
  783. } else if (!result.is_null()) {
  784. out << result.dump();
  785. }
  786. }
  787. };
  788. class IfNode : public TemplateNode {
  789. std::vector<std::pair<std::shared_ptr<Expression>, std::shared_ptr<TemplateNode>>> cascade;
  790. public:
  791. IfNode(const Location & location, std::vector<std::pair<std::shared_ptr<Expression>, std::shared_ptr<TemplateNode>>> && c)
  792. : TemplateNode(location), cascade(std::move(c)) {}
  793. void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const override {
  794. for (const auto& branch : cascade) {
  795. auto enter_branch = true;
  796. if (branch.first) {
  797. enter_branch = branch.first->evaluate(context).to_bool();
  798. }
  799. if (enter_branch) {
  800. if (!branch.second) throw std::runtime_error("IfNode.cascade.second is null");
  801. branch.second->render(out, context);
  802. return;
  803. }
  804. }
  805. }
  806. };
  807. class ForNode : public TemplateNode {
  808. std::vector<std::string> var_names;
  809. std::shared_ptr<Expression> iterable;
  810. std::shared_ptr<Expression> condition;
  811. std::shared_ptr<TemplateNode> body;
  812. bool recursive;
  813. std::shared_ptr<TemplateNode> else_body;
  814. public:
  815. ForNode(const Location & location, std::vector<std::string> && var_names, std::shared_ptr<Expression> && iterable,
  816. std::shared_ptr<Expression> && condition, std::shared_ptr<TemplateNode> && body, bool recursive, std::shared_ptr<TemplateNode> && else_body)
  817. : TemplateNode(location), var_names(var_names), iterable(std::move(iterable)), condition(std::move(condition)), body(std::move(body)), recursive(recursive), else_body(std::move(else_body)) {}
  818. void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const override {
  819. // https://jinja.palletsprojects.com/en/3.0.x/templates/#for
  820. if (!iterable) throw std::runtime_error("ForNode.iterable is null");
  821. if (!body) throw std::runtime_error("ForNode.body is null");
  822. auto iterable_value = iterable->evaluate(context);
  823. Value::CallableType loop_function;
  824. std::function<void(Value&)> visit = [&](Value& iter) {
  825. auto filtered_items = Value::array();
  826. if (!iter.is_null()) {
  827. if (!iterable_value.is_iterable()) {
  828. throw std::runtime_error("For loop iterable must be iterable: " + iterable_value.dump());
  829. }
  830. iterable_value.for_each([&](Value & item) {
  831. destructuring_assign(var_names, context, item);
  832. if (!condition || condition->evaluate(context).to_bool()) {
  833. filtered_items.push_back(item);
  834. }
  835. });
  836. }
  837. if (filtered_items.empty()) {
  838. if (else_body) {
  839. else_body->render(out, context);
  840. }
  841. } else {
  842. auto loop = recursive ? Value::callable(loop_function) : Value::object();
  843. loop.set("length", (int64_t) filtered_items.size());
  844. size_t cycle_index = 0;
  845. loop.set("cycle", Value::callable([&](const std::shared_ptr<Context> &, ArgumentsValue & args) {
  846. if (args.args.empty() || !args.kwargs.empty()) {
  847. throw std::runtime_error("cycle() expects at least 1 positional argument and no named arg");
  848. }
  849. auto item = args.args[cycle_index];
  850. cycle_index = (cycle_index + 1) % args.args.size();
  851. return item;
  852. }));
  853. auto loop_context = Context::make(Value::object(), context);
  854. loop_context->set("loop", loop);
  855. for (size_t i = 0, n = filtered_items.size(); i < n; ++i) {
  856. auto & item = filtered_items.at(i);
  857. destructuring_assign(var_names, loop_context, item);
  858. loop.set("index", (int64_t) i + 1);
  859. loop.set("index0", (int64_t) i);
  860. loop.set("revindex", (int64_t) (n - i));
  861. loop.set("revindex0", (int64_t) (n - i - 1));
  862. loop.set("length", (int64_t) n);
  863. loop.set("first", i == 0);
  864. loop.set("last", i == (n - 1));
  865. loop.set("previtem", i > 0 ? filtered_items.at(i - 1) : Value());
  866. loop.set("nextitem", i < n - 1 ? filtered_items.at(i + 1) : Value());
  867. body->render(out, loop_context);
  868. }
  869. }
  870. };
  871. if (recursive) {
  872. loop_function = [&](const std::shared_ptr<Context> &, ArgumentsValue & args) {
  873. if (args.args.size() != 1 || !args.kwargs.empty() || !args.args[0].is_array()) {
  874. throw std::runtime_error("loop() expects exactly 1 positional iterable argument");
  875. }
  876. auto & items = args.args[0];
  877. visit(items);
  878. return Value();
  879. };
  880. }
  881. visit(iterable_value);
  882. }
  883. };
  884. class MacroNode : public TemplateNode {
  885. std::shared_ptr<VariableExpr> name;
  886. Expression::Parameters params;
  887. std::shared_ptr<TemplateNode> body;
  888. std::unordered_map<std::string, size_t> named_param_positions;
  889. public:
  890. MacroNode(const Location & location, std::shared_ptr<VariableExpr> && n, Expression::Parameters && p, std::shared_ptr<TemplateNode> && b)
  891. : TemplateNode(location), name(std::move(n)), params(std::move(p)), body(std::move(b)) {
  892. for (size_t i = 0; i < params.size(); ++i) {
  893. const auto & name = params[i].first;
  894. if (!name.empty()) {
  895. named_param_positions[name] = i;
  896. }
  897. }
  898. }
  899. void do_render(std::ostringstream &, const std::shared_ptr<Context> & macro_context) const override {
  900. if (!name) throw std::runtime_error("MacroNode.name is null");
  901. if (!body) throw std::runtime_error("MacroNode.body is null");
  902. auto callable = Value::callable([&](const std::shared_ptr<Context> & context, ArgumentsValue & args) {
  903. auto call_context = macro_context;
  904. std::vector<bool> param_set(params.size(), false);
  905. for (size_t i = 0, n = args.args.size(); i < n; i++) {
  906. auto & arg = args.args[i];
  907. if (i >= params.size()) throw std::runtime_error("Too many positional arguments for macro " + name->get_name());
  908. param_set[i] = true;
  909. auto & param_name = params[i].first;
  910. call_context->set(param_name, arg);
  911. }
  912. for (auto & [arg_name, value] : args.kwargs) {
  913. auto it = named_param_positions.find(arg_name);
  914. if (it == named_param_positions.end()) throw std::runtime_error("Unknown parameter name for macro " + name->get_name() + ": " + arg_name);
  915. call_context->set(arg_name, value);
  916. param_set[it->second] = true;
  917. }
  918. // Set default values for parameters that were not passed
  919. for (size_t i = 0, n = params.size(); i < n; i++) {
  920. if (!param_set[i] && params[i].second != nullptr) {
  921. auto val = params[i].second->evaluate(context);
  922. call_context->set(params[i].first, val);
  923. }
  924. }
  925. return body->render(call_context);
  926. });
  927. macro_context->set(name->get_name(), callable);
  928. }
  929. };
  930. class FilterNode : public TemplateNode {
  931. std::shared_ptr<Expression> filter;
  932. std::shared_ptr<TemplateNode> body;
  933. public:
  934. FilterNode(const Location & location, std::shared_ptr<Expression> && f, std::shared_ptr<TemplateNode> && b)
  935. : TemplateNode(location), filter(std::move(f)), body(std::move(b)) {}
  936. void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const override {
  937. if (!filter) throw std::runtime_error("FilterNode.filter is null");
  938. if (!body) throw std::runtime_error("FilterNode.body is null");
  939. auto filter_value = filter->evaluate(context);
  940. if (!filter_value.is_callable()) {
  941. throw std::runtime_error("Filter must be a callable: " + filter_value.dump());
  942. }
  943. std::string rendered_body = body->render(context);
  944. ArgumentsValue filter_args = {{Value(rendered_body)}, {}};
  945. auto result = filter_value.call(context, filter_args);
  946. out << result.to_str();
  947. }
  948. };
  949. class SetNode : public TemplateNode {
  950. std::string ns;
  951. std::vector<std::string> var_names;
  952. std::shared_ptr<Expression> value;
  953. public:
  954. SetNode(const Location & location, const std::string & ns, const std::vector<std::string> & vns, std::shared_ptr<Expression> && v)
  955. : TemplateNode(location), ns(ns), var_names(vns), value(std::move(v)) {}
  956. void do_render(std::ostringstream &, const std::shared_ptr<Context> & context) const override {
  957. if (!value) throw std::runtime_error("SetNode.value is null");
  958. if (!ns.empty()) {
  959. if (var_names.size() != 1) {
  960. throw std::runtime_error("Namespaced set only supports a single variable name");
  961. }
  962. auto & name = var_names[0];
  963. auto ns_value = context->get(ns);
  964. if (!ns_value.is_object()) throw std::runtime_error("Namespace '" + ns + "' is not an object");
  965. ns_value.set(name, this->value->evaluate(context));
  966. } else {
  967. auto val = value->evaluate(context);
  968. destructuring_assign(var_names, context, val);
  969. }
  970. }
  971. };
  972. class SetTemplateNode : public TemplateNode {
  973. std::string name;
  974. std::shared_ptr<TemplateNode> template_value;
  975. public:
  976. SetTemplateNode(const Location & location, const std::string & name, std::shared_ptr<TemplateNode> && tv)
  977. : TemplateNode(location), name(name), template_value(std::move(tv)) {}
  978. void do_render(std::ostringstream &, const std::shared_ptr<Context> & context) const override {
  979. if (!template_value) throw std::runtime_error("SetTemplateNode.template_value is null");
  980. Value value { template_value->render(context) };
  981. context->set(name, value);
  982. }
  983. };
  984. class IfExpr : public Expression {
  985. std::shared_ptr<Expression> condition;
  986. std::shared_ptr<Expression> then_expr;
  987. std::shared_ptr<Expression> else_expr;
  988. public:
  989. IfExpr(const Location & location, std::shared_ptr<Expression> && c, std::shared_ptr<Expression> && t, std::shared_ptr<Expression> && e)
  990. : Expression(location), condition(std::move(c)), then_expr(std::move(t)), else_expr(std::move(e)) {}
  991. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  992. if (!condition) throw std::runtime_error("IfExpr.condition is null");
  993. if (!then_expr) throw std::runtime_error("IfExpr.then_expr is null");
  994. if (condition->evaluate(context).to_bool()) {
  995. return then_expr->evaluate(context);
  996. }
  997. if (else_expr) {
  998. return else_expr->evaluate(context);
  999. }
  1000. return nullptr;
  1001. }
  1002. };
  1003. class LiteralExpr : public Expression {
  1004. Value value;
  1005. public:
  1006. LiteralExpr(const Location & location, const Value& v)
  1007. : Expression(location), value(v) {}
  1008. Value do_evaluate(const std::shared_ptr<Context> &) const override { return value; }
  1009. };
  1010. class ArrayExpr : public Expression {
  1011. std::vector<std::shared_ptr<Expression>> elements;
  1012. public:
  1013. ArrayExpr(const Location & location, std::vector<std::shared_ptr<Expression>> && e)
  1014. : Expression(location), elements(std::move(e)) {}
  1015. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1016. auto result = Value::array();
  1017. for (const auto& e : elements) {
  1018. if (!e) throw std::runtime_error("Array element is null");
  1019. result.push_back(e->evaluate(context));
  1020. }
  1021. return result;
  1022. }
  1023. };
  1024. class DictExpr : public Expression {
  1025. std::vector<std::pair<std::shared_ptr<Expression>, std::shared_ptr<Expression>>> elements;
  1026. public:
  1027. DictExpr(const Location & location, std::vector<std::pair<std::shared_ptr<Expression>, std::shared_ptr<Expression>>> && e)
  1028. : Expression(location), elements(std::move(e)) {}
  1029. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1030. auto result = Value::object();
  1031. for (const auto& [key, value] : elements) {
  1032. if (!key) throw std::runtime_error("Dict key is null");
  1033. if (!value) throw std::runtime_error("Dict value is null");
  1034. result.set(key->evaluate(context), value->evaluate(context));
  1035. }
  1036. return result;
  1037. }
  1038. };
  1039. class SliceExpr : public Expression {
  1040. public:
  1041. std::shared_ptr<Expression> start, end;
  1042. SliceExpr(const Location & location, std::shared_ptr<Expression> && s, std::shared_ptr<Expression> && e)
  1043. : Expression(location), start(std::move(s)), end(std::move(e)) {}
  1044. Value do_evaluate(const std::shared_ptr<Context> &) const override {
  1045. throw std::runtime_error("SliceExpr not implemented");
  1046. }
  1047. };
  1048. class SubscriptExpr : public Expression {
  1049. std::shared_ptr<Expression> base;
  1050. std::shared_ptr<Expression> index;
  1051. public:
  1052. SubscriptExpr(const Location & location, std::shared_ptr<Expression> && b, std::shared_ptr<Expression> && i)
  1053. : Expression(location), base(std::move(b)), index(std::move(i)) {}
  1054. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1055. if (!base) throw std::runtime_error("SubscriptExpr.base is null");
  1056. if (!index) throw std::runtime_error("SubscriptExpr.index is null");
  1057. auto target_value = base->evaluate(context);
  1058. if (auto slice = dynamic_cast<SliceExpr*>(index.get())) {
  1059. auto start = slice->start ? slice->start->evaluate(context).get<int64_t>() : 0;
  1060. auto end = slice->end ? slice->end->evaluate(context).get<int64_t>() : (int64_t) target_value.size();
  1061. if (target_value.is_string()) {
  1062. std::string s = target_value.get<std::string>();
  1063. if (start < 0) start = s.size() + start;
  1064. if (end < 0) end = s.size() + end;
  1065. return s.substr(start, end - start);
  1066. } else if (target_value.is_array()) {
  1067. if (start < 0) start = target_value.size() + start;
  1068. if (end < 0) end = target_value.size() + end;
  1069. auto result = Value::array();
  1070. for (auto i = start; i < end; ++i) {
  1071. result.push_back(target_value.at(i));
  1072. }
  1073. return result;
  1074. } else {
  1075. throw std::runtime_error(target_value.is_null() ? "Cannot subscript null" : "Subscripting only supported on arrays and strings");
  1076. }
  1077. } else {
  1078. auto index_value = index->evaluate(context);
  1079. if (target_value.is_null()) {
  1080. if (auto t = dynamic_cast<VariableExpr*>(base.get())) {
  1081. throw std::runtime_error("'" + t->get_name() + "' is " + (context->contains(t->get_name()) ? "null" : "not defined"));
  1082. }
  1083. throw std::runtime_error("Trying to access property '" + index_value.dump() + "' on null!");
  1084. }
  1085. return target_value.get(index_value);
  1086. }
  1087. }
  1088. };
  1089. class UnaryOpExpr : public Expression {
  1090. public:
  1091. enum class Op { Plus, Minus, LogicalNot, Expansion, ExpansionDict };
  1092. std::shared_ptr<Expression> expr;
  1093. Op op;
  1094. UnaryOpExpr(const Location & location, std::shared_ptr<Expression> && e, Op o)
  1095. : Expression(location), expr(std::move(e)), op(o) {}
  1096. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1097. if (!expr) throw std::runtime_error("UnaryOpExpr.expr is null");
  1098. auto e = expr->evaluate(context);
  1099. switch (op) {
  1100. case Op::Plus: return e;
  1101. case Op::Minus: return -e;
  1102. case Op::LogicalNot: return !e.to_bool();
  1103. case Op::Expansion:
  1104. case Op::ExpansionDict:
  1105. throw std::runtime_error("Expansion operator is only supported in function calls and collections");
  1106. }
  1107. throw std::runtime_error("Unknown unary operator");
  1108. }
  1109. };
  1110. class BinaryOpExpr : public Expression {
  1111. public:
  1112. enum class Op { StrConcat, Add, Sub, Mul, MulMul, Div, DivDiv, Mod, Eq, Ne, Lt, Gt, Le, Ge, And, Or, In, NotIn, Is, IsNot };
  1113. private:
  1114. std::shared_ptr<Expression> left;
  1115. std::shared_ptr<Expression> right;
  1116. Op op;
  1117. public:
  1118. BinaryOpExpr(const Location & location, std::shared_ptr<Expression> && l, std::shared_ptr<Expression> && r, Op o)
  1119. : Expression(location), left(std::move(l)), right(std::move(r)), op(o) {}
  1120. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1121. if (!left) throw std::runtime_error("BinaryOpExpr.left is null");
  1122. if (!right) throw std::runtime_error("BinaryOpExpr.right is null");
  1123. auto l = left->evaluate(context);
  1124. auto do_eval = [&](const Value & l) -> Value {
  1125. if (op == Op::Is || op == Op::IsNot) {
  1126. auto t = dynamic_cast<VariableExpr*>(right.get());
  1127. if (!t) throw std::runtime_error("Right side of 'is' operator must be a variable");
  1128. auto eval = [&]() {
  1129. const auto & name = t->get_name();
  1130. if (name == "none") return l.is_null();
  1131. if (name == "boolean") return l.is_boolean();
  1132. if (name == "integer") return l.is_number_integer();
  1133. if (name == "float") return l.is_number_float();
  1134. if (name == "number") return l.is_number();
  1135. if (name == "string") return l.is_string();
  1136. if (name == "mapping") return l.is_object();
  1137. if (name == "iterable") return l.is_iterable();
  1138. if (name == "sequence") return l.is_array();
  1139. if (name == "defined") return !l.is_null();
  1140. throw std::runtime_error("Unknown type for 'is' operator: " + name);
  1141. };
  1142. auto value = eval();
  1143. return Value(op == Op::Is ? value : !value);
  1144. }
  1145. if (op == Op::And) {
  1146. if (!l.to_bool()) return Value(false);
  1147. return right->evaluate(context).to_bool();
  1148. } else if (op == Op::Or) {
  1149. if (l.to_bool()) return l;
  1150. return right->evaluate(context);
  1151. }
  1152. auto r = right->evaluate(context);
  1153. switch (op) {
  1154. case Op::StrConcat: return l.to_str() + r.to_str();
  1155. case Op::Add: return l + r;
  1156. case Op::Sub: return l - r;
  1157. case Op::Mul: return l * r;
  1158. case Op::Div: return l / r;
  1159. case Op::MulMul: return std::pow(l.get<double>(), r.get<double>());
  1160. case Op::DivDiv: return l.get<int64_t>() / r.get<int64_t>();
  1161. case Op::Mod: return l.get<int64_t>() % r.get<int64_t>();
  1162. case Op::Eq: return l == r;
  1163. case Op::Ne: return l != r;
  1164. case Op::Lt: return l < r;
  1165. case Op::Gt: return l > r;
  1166. case Op::Le: return l <= r;
  1167. case Op::Ge: return l >= r;
  1168. case Op::In: return (r.is_array() || r.is_object()) && r.contains(l);
  1169. case Op::NotIn: return !(r.is_array() && r.contains(l));
  1170. default: break;
  1171. }
  1172. throw std::runtime_error("Unknown binary operator");
  1173. };
  1174. if (l.is_callable()) {
  1175. return Value::callable([l, do_eval](const std::shared_ptr<Context> & context, ArgumentsValue & args) {
  1176. auto ll = l.call(context, args);
  1177. return do_eval(ll); //args[0].second);
  1178. });
  1179. } else {
  1180. return do_eval(l);
  1181. }
  1182. }
  1183. };
  1184. struct ArgumentsExpression {
  1185. std::vector<std::shared_ptr<Expression>> args;
  1186. std::vector<std::pair<std::string, std::shared_ptr<Expression>>> kwargs;
  1187. ArgumentsValue evaluate(const std::shared_ptr<Context> & context) const {
  1188. ArgumentsValue vargs;
  1189. for (const auto& arg : this->args) {
  1190. if (auto un_expr = std::dynamic_pointer_cast<UnaryOpExpr>(arg)) {
  1191. if (un_expr->op == UnaryOpExpr::Op::Expansion) {
  1192. auto array = un_expr->expr->evaluate(context);
  1193. if (!array.is_array()) {
  1194. throw std::runtime_error("Expansion operator only supported on arrays");
  1195. }
  1196. array.for_each([&](Value & value) {
  1197. vargs.args.push_back(value);
  1198. });
  1199. continue;
  1200. } else if (un_expr->op == UnaryOpExpr::Op::ExpansionDict) {
  1201. auto dict = un_expr->expr->evaluate(context);
  1202. if (!dict.is_object()) {
  1203. throw std::runtime_error("ExpansionDict operator only supported on objects");
  1204. }
  1205. dict.for_each([&](const Value & key) {
  1206. vargs.kwargs.push_back({key.get<std::string>(), dict.at(key)});
  1207. });
  1208. continue;
  1209. }
  1210. }
  1211. vargs.args.push_back(arg->evaluate(context));
  1212. }
  1213. for (const auto& [name, value] : this->kwargs) {
  1214. vargs.kwargs.push_back({name, value->evaluate(context)});
  1215. }
  1216. return vargs;
  1217. }
  1218. };
  1219. static std::string strip(const std::string & s) {
  1220. auto start = s.find_first_not_of(" \t\n\r");
  1221. if (start == std::string::npos) return "";
  1222. auto end = s.find_last_not_of(" \t\n\r");
  1223. return s.substr(start, end - start + 1);
  1224. }
  1225. static std::string html_escape(const std::string & s) {
  1226. std::string result;
  1227. result.reserve(s.size());
  1228. for (const auto & c : s) {
  1229. switch (c) {
  1230. case '&': result += "&amp;"; break;
  1231. case '<': result += "&lt;"; break;
  1232. case '>': result += "&gt;"; break;
  1233. case '"': result += "&#34;"; break;
  1234. case '\'': result += "&apos;"; break;
  1235. default: result += c; break;
  1236. }
  1237. }
  1238. return result;
  1239. }
  1240. class MethodCallExpr : public Expression {
  1241. std::shared_ptr<Expression> object;
  1242. std::shared_ptr<VariableExpr> method;
  1243. ArgumentsExpression args;
  1244. public:
  1245. MethodCallExpr(const Location & location, std::shared_ptr<Expression> && obj, std::shared_ptr<VariableExpr> && m, ArgumentsExpression && a)
  1246. : Expression(location), object(std::move(obj)), method(std::move(m)), args(std::move(a)) {}
  1247. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1248. if (!object) throw std::runtime_error("MethodCallExpr.object is null");
  1249. if (!method) throw std::runtime_error("MethodCallExpr.method is null");
  1250. auto obj = object->evaluate(context);
  1251. auto vargs = args.evaluate(context);
  1252. if (obj.is_null()) {
  1253. throw std::runtime_error("Trying to call method '" + method->get_name() + "' on null");
  1254. }
  1255. if (obj.is_array()) {
  1256. if (method->get_name() == "append") {
  1257. vargs.expectArgs("append method", {1, 1}, {0, 0});
  1258. obj.push_back(vargs.args[0]);
  1259. return Value();
  1260. } else if (method->get_name() == "pop") {
  1261. vargs.expectArgs("pop method", {0, 1}, {0, 0});
  1262. return obj.pop(vargs.args.empty() ? Value() : vargs.args[0]);
  1263. } else if (method->get_name() == "insert") {
  1264. vargs.expectArgs("insert method", {2, 2}, {0, 0});
  1265. auto index = vargs.args[0].get<int64_t>();
  1266. if (index < 0 || index > (int64_t) obj.size()) throw std::runtime_error("Index out of range for insert method");
  1267. obj.insert(index, vargs.args[1]);
  1268. return Value();
  1269. }
  1270. } else if (obj.is_object()) {
  1271. if (method->get_name() == "items") {
  1272. vargs.expectArgs("items method", {0, 0}, {0, 0});
  1273. auto result = Value::array();
  1274. for (const auto& key : obj.keys()) {
  1275. result.push_back(Value::array({key, obj.at(key)}));
  1276. }
  1277. return result;
  1278. } else if (method->get_name() == "pop") {
  1279. vargs.expectArgs("pop method", {1, 1}, {0, 0});
  1280. return obj.pop(vargs.args[0]);
  1281. } else if (method->get_name() == "get") {
  1282. vargs.expectArgs("get method", {1, 2}, {0, 0});
  1283. auto key = vargs.args[0];
  1284. if (vargs.args.size() == 1) {
  1285. return obj.contains(key) ? obj.at(key) : Value();
  1286. } else {
  1287. return obj.contains(key) ? obj.at(key) : vargs.args[1];
  1288. }
  1289. } else if (obj.contains(method->get_name())) {
  1290. auto callable = obj.at(method->get_name());
  1291. if (!callable.is_callable()) {
  1292. throw std::runtime_error("Property '" + method->get_name() + "' is not callable");
  1293. }
  1294. return callable.call(context, vargs);
  1295. }
  1296. } else if (obj.is_string()) {
  1297. auto str = obj.get<std::string>();
  1298. if (method->get_name() == "strip") {
  1299. vargs.expectArgs("strip method", {0, 0}, {0, 0});
  1300. return Value(strip(str));
  1301. } else if (method->get_name() == "endswith") {
  1302. vargs.expectArgs("endswith method", {1, 1}, {0, 0});
  1303. auto suffix = vargs.args[0].get<std::string>();
  1304. return suffix.length() <= str.length() && std::equal(suffix.rbegin(), suffix.rend(), str.rbegin());
  1305. } else if (method->get_name() == "title") {
  1306. vargs.expectArgs("title method", {0, 0}, {0, 0});
  1307. auto res = str;
  1308. for (size_t i = 0, n = res.size(); i < n; ++i) {
  1309. if (i == 0 || std::isspace(res[i - 1])) res[i] = std::toupper(res[i]);
  1310. else res[i] = std::tolower(res[i]);
  1311. }
  1312. return res;
  1313. }
  1314. }
  1315. throw std::runtime_error("Unknown method: " + method->get_name());
  1316. }
  1317. };
  1318. class CallExpr : public Expression {
  1319. public:
  1320. std::shared_ptr<Expression> object;
  1321. ArgumentsExpression args;
  1322. CallExpr(const Location & location, std::shared_ptr<Expression> && obj, ArgumentsExpression && a)
  1323. : Expression(location), object(std::move(obj)), args(std::move(a)) {}
  1324. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1325. if (!object) throw std::runtime_error("CallExpr.object is null");
  1326. auto obj = object->evaluate(context);
  1327. if (!obj.is_callable()) {
  1328. throw std::runtime_error("Object is not callable: " + obj.dump(2));
  1329. }
  1330. auto vargs = args.evaluate(context);
  1331. return obj.call(context, vargs);
  1332. }
  1333. };
  1334. class FilterExpr : public Expression {
  1335. std::vector<std::shared_ptr<Expression>> parts;
  1336. public:
  1337. FilterExpr(const Location & location, std::vector<std::shared_ptr<Expression>> && p)
  1338. : Expression(location), parts(std::move(p)) {}
  1339. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1340. Value result;
  1341. bool first = true;
  1342. for (const auto& part : parts) {
  1343. if (!part) throw std::runtime_error("FilterExpr.part is null");
  1344. if (first) {
  1345. first = false;
  1346. result = part->evaluate(context);
  1347. } else {
  1348. if (auto ce = dynamic_cast<CallExpr*>(part.get())) {
  1349. auto target = ce->object->evaluate(context);
  1350. ArgumentsValue args = ce->args.evaluate(context);
  1351. args.args.insert(args.args.begin(), result);
  1352. result = target.call(context, args);
  1353. } else {
  1354. auto callable = part->evaluate(context);
  1355. ArgumentsValue args;
  1356. args.args.insert(args.args.begin(), result);
  1357. result = callable.call(context, args);
  1358. }
  1359. }
  1360. }
  1361. return result;
  1362. }
  1363. void prepend(std::shared_ptr<Expression> && e) {
  1364. parts.insert(parts.begin(), std::move(e));
  1365. }
  1366. };
  1367. class Parser {
  1368. private:
  1369. using CharIterator = std::string::const_iterator;
  1370. std::shared_ptr<std::string> template_str;
  1371. CharIterator start, end, it;
  1372. Options options;
  1373. Parser(const std::shared_ptr<std::string>& template_str, const Options & options) : template_str(template_str), options(options) {
  1374. if (!template_str) throw std::runtime_error("Template string is null");
  1375. start = it = this->template_str->begin();
  1376. end = this->template_str->end();
  1377. }
  1378. bool consumeSpaces(SpaceHandling space_handling = SpaceHandling::Strip) {
  1379. if (space_handling == SpaceHandling::Strip) {
  1380. while (it != end && std::isspace(*it)) ++it;
  1381. }
  1382. return true;
  1383. }
  1384. std::unique_ptr<std::string> parseString() {
  1385. auto doParse = [&](char quote) -> std::unique_ptr<std::string> {
  1386. if (it == end || *it != quote) return nullptr;
  1387. std::string result;
  1388. bool escape = false;
  1389. for (++it; it != end; ++it) {
  1390. if (escape) {
  1391. escape = false;
  1392. switch (*it) {
  1393. case 'n': result += '\n'; break;
  1394. case 'r': result += '\r'; break;
  1395. case 't': result += '\t'; break;
  1396. case 'b': result += '\b'; break;
  1397. case 'f': result += '\f'; break;
  1398. case '\\': result += '\\'; break;
  1399. default:
  1400. if (*it == quote) {
  1401. result += quote;
  1402. } else {
  1403. result += *it;
  1404. }
  1405. break;
  1406. }
  1407. } else if (*it == '\\') {
  1408. escape = true;
  1409. } else if (*it == quote) {
  1410. ++it;
  1411. return std::make_unique<std::string>(std::move(result));
  1412. } else {
  1413. result += *it;
  1414. }
  1415. }
  1416. return nullptr;
  1417. };
  1418. consumeSpaces();
  1419. if (it == end) return nullptr;
  1420. if (*it == '"') return doParse('"');
  1421. if (*it == '\'') return doParse('\'');
  1422. return nullptr;
  1423. }
  1424. json parseNumber(CharIterator& it, const CharIterator& end) {
  1425. auto before = it;
  1426. consumeSpaces();
  1427. auto start = it;
  1428. bool hasDecimal = false;
  1429. bool hasExponent = false;
  1430. if (it != end && (*it == '-' || *it == '+')) ++it;
  1431. while (it != end) {
  1432. if (std::isdigit(*it)) {
  1433. ++it;
  1434. } else if (*it == '.') {
  1435. if (hasDecimal) throw std::runtime_error("Multiple decimal points");
  1436. hasDecimal = true;
  1437. ++it;
  1438. } else if (it != start && (*it == 'e' || *it == 'E')) {
  1439. if (hasExponent) throw std::runtime_error("Multiple exponents");
  1440. hasExponent = true;
  1441. ++it;
  1442. } else {
  1443. break;
  1444. }
  1445. }
  1446. if (start == it) {
  1447. it = before;
  1448. return json(); // No valid characters found
  1449. }
  1450. std::string str(start, it);
  1451. try {
  1452. return json::parse(str);
  1453. } catch (json::parse_error& e) {
  1454. throw std::runtime_error("Failed to parse number: '" + str + "' (" + std::string(e.what()) + ")");
  1455. return json();
  1456. }
  1457. }
  1458. /** integer, float, bool, string */
  1459. std::shared_ptr<Value> parseConstant() {
  1460. auto start = it;
  1461. consumeSpaces();
  1462. if (it == end) return nullptr;
  1463. if (*it == '"' || *it == '\'') {
  1464. auto str = parseString();
  1465. if (str) return std::make_shared<Value>(*str);
  1466. }
  1467. static std::regex prim_tok(R"(true\b|True\b|false\b|False\b|None\b)");
  1468. auto token = consumeToken(prim_tok);
  1469. if (!token.empty()) {
  1470. if (token == "true" || token == "True") return std::make_shared<Value>(true);
  1471. if (token == "false" || token == "False") return std::make_shared<Value>(false);
  1472. if (token == "None") return std::make_shared<Value>(nullptr);
  1473. throw std::runtime_error("Unknown constant token: " + token);
  1474. }
  1475. auto number = parseNumber(it, end);
  1476. if (!number.is_null()) return std::make_shared<Value>(number);
  1477. it = start;
  1478. return nullptr;
  1479. }
  1480. class expression_parsing_error : public std::runtime_error {
  1481. const CharIterator it;
  1482. public:
  1483. expression_parsing_error(const std::string & message, const CharIterator & it)
  1484. : std::runtime_error(message), it(it) {}
  1485. size_t get_pos(const CharIterator & begin) const {
  1486. return std::distance(begin, it);
  1487. }
  1488. };
  1489. bool peekSymbols(const std::vector<std::string> & symbols) const {
  1490. for (const auto & symbol : symbols) {
  1491. if (std::distance(it, end) >= (int64_t) symbol.size() && std::string(it, it + symbol.size()) == symbol) {
  1492. return true;
  1493. }
  1494. }
  1495. return false;
  1496. }
  1497. std::vector<std::string> consumeTokenGroups(const std::regex & regex, SpaceHandling space_handling = SpaceHandling::Strip) {
  1498. auto start = it;
  1499. consumeSpaces(space_handling);
  1500. std::smatch match;
  1501. if (std::regex_search(it, end, match, regex) && match.position() == 0) {
  1502. it += match[0].length();
  1503. std::vector<std::string> ret;
  1504. for (size_t i = 0, n = match.size(); i < n; ++i) {
  1505. ret.push_back(match[i].str());
  1506. }
  1507. return ret;
  1508. }
  1509. it = start;
  1510. return {};
  1511. }
  1512. std::string consumeToken(const std::regex & regex, SpaceHandling space_handling = SpaceHandling::Strip) {
  1513. auto start = it;
  1514. consumeSpaces(space_handling);
  1515. std::smatch match;
  1516. if (std::regex_search(it, end, match, regex) && match.position() == 0) {
  1517. it += match[0].length();
  1518. return match[0].str();
  1519. }
  1520. it = start;
  1521. return "";
  1522. }
  1523. std::string consumeToken(const std::string & token, SpaceHandling space_handling = SpaceHandling::Strip) {
  1524. auto start = it;
  1525. consumeSpaces(space_handling);
  1526. if (std::distance(it, end) >= (int64_t) token.size() && std::string(it, it + token.size()) == token) {
  1527. it += token.size();
  1528. return token;
  1529. }
  1530. it = start;
  1531. return "";
  1532. }
  1533. std::shared_ptr<Expression> parseExpression(bool allow_if_expr = true) {
  1534. auto left = parseLogicalOr();
  1535. if (it == end) return left;
  1536. if (!allow_if_expr) return left;
  1537. static std::regex if_tok(R"(if\b)");
  1538. if (consumeToken(if_tok).empty()) {
  1539. return left;
  1540. }
  1541. auto location = get_location();
  1542. auto [condition, else_expr] = parseIfExpression();
  1543. return std::make_shared<IfExpr>(location, std::move(condition), std::move(left), std::move(else_expr));
  1544. }
  1545. Location get_location() const {
  1546. return {template_str, (size_t) std::distance(start, it)};
  1547. }
  1548. std::pair<std::shared_ptr<Expression>, std::shared_ptr<Expression>> parseIfExpression() {
  1549. auto condition = parseLogicalOr();
  1550. if (!condition) throw std::runtime_error("Expected condition expression");
  1551. static std::regex else_tok(R"(else\b)");
  1552. std::shared_ptr<Expression> else_expr;
  1553. if (!consumeToken(else_tok).empty()) {
  1554. else_expr = parseExpression();
  1555. if (!else_expr) throw std::runtime_error("Expected 'else' expression");
  1556. }
  1557. return std::pair(std::move(condition), std::move(else_expr));
  1558. }
  1559. std::shared_ptr<Expression> parseLogicalOr() {
  1560. auto left = parseLogicalAnd();
  1561. if (!left) throw std::runtime_error("Expected left side of 'logical or' expression");
  1562. static std::regex or_tok(R"(or\b)");
  1563. auto location = get_location();
  1564. while (!consumeToken(or_tok).empty()) {
  1565. auto right = parseLogicalAnd();
  1566. if (!right) throw std::runtime_error("Expected right side of 'or' expression");
  1567. left = std::make_shared<BinaryOpExpr>(location, std::move(left), std::move(right), BinaryOpExpr::Op::Or);
  1568. }
  1569. return left;
  1570. }
  1571. std::shared_ptr<Expression> parseLogicalNot() {
  1572. static std::regex not_tok(R"(not\b)");
  1573. auto location = get_location();
  1574. if (!consumeToken(not_tok).empty()) {
  1575. auto sub = parseLogicalNot();
  1576. if (!sub) throw std::runtime_error("Expected expression after 'not' keyword");
  1577. return std::make_shared<UnaryOpExpr>(location, std::move(sub), UnaryOpExpr::Op::LogicalNot);
  1578. }
  1579. return parseLogicalCompare();
  1580. }
  1581. std::shared_ptr<Expression> parseLogicalAnd() {
  1582. auto left = parseLogicalNot();
  1583. if (!left) throw std::runtime_error("Expected left side of 'logical and' expression");
  1584. static std::regex and_tok(R"(and\b)");
  1585. auto location = get_location();
  1586. while (!consumeToken(and_tok).empty()) {
  1587. auto right = parseLogicalNot();
  1588. if (!right) throw std::runtime_error("Expected right side of 'and' expression");
  1589. left = std::make_shared<BinaryOpExpr>(location, std::move(left), std::move(right), BinaryOpExpr::Op::And);
  1590. }
  1591. return left;
  1592. }
  1593. std::shared_ptr<Expression> parseLogicalCompare() {
  1594. auto left = parseStringConcat();
  1595. if (!left) throw std::runtime_error("Expected left side of 'logical compare' expression");
  1596. static std::regex compare_tok(R"(==|!=|<=?|>=?|in\b|is\b|not[\r\n\s]+in\b)");
  1597. static std::regex not_tok(R"(not\b)");
  1598. std::string op_str;
  1599. while (!(op_str = consumeToken(compare_tok)).empty()) {
  1600. auto location = get_location();
  1601. if (op_str == "is") {
  1602. auto negated = !consumeToken(not_tok).empty();
  1603. auto identifier = parseIdentifier();
  1604. if (!identifier) throw std::runtime_error("Expected identifier after 'is' keyword");
  1605. return std::make_shared<BinaryOpExpr>(
  1606. left->location,
  1607. std::move(left), std::move(identifier),
  1608. negated ? BinaryOpExpr::Op::IsNot : BinaryOpExpr::Op::Is);
  1609. }
  1610. auto right = parseStringConcat();
  1611. if (!right) throw std::runtime_error("Expected right side of 'logical compare' expression");
  1612. BinaryOpExpr::Op op;
  1613. if (op_str == "==") op = BinaryOpExpr::Op::Eq;
  1614. else if (op_str == "!=") op = BinaryOpExpr::Op::Ne;
  1615. else if (op_str == "<") op = BinaryOpExpr::Op::Lt;
  1616. else if (op_str == ">") op = BinaryOpExpr::Op::Gt;
  1617. else if (op_str == "<=") op = BinaryOpExpr::Op::Le;
  1618. else if (op_str == ">=") op = BinaryOpExpr::Op::Ge;
  1619. else if (op_str == "in") op = BinaryOpExpr::Op::In;
  1620. else if (op_str.substr(0, 3) == "not") op = BinaryOpExpr::Op::NotIn;
  1621. else throw std::runtime_error("Unknown comparison operator: " + op_str);
  1622. left = std::make_shared<BinaryOpExpr>(get_location(), std::move(left), std::move(right), op);
  1623. }
  1624. return left;
  1625. }
  1626. Expression::Parameters parseParameters() {
  1627. consumeSpaces();
  1628. if (consumeToken("(").empty()) throw std::runtime_error("Expected opening parenthesis in param list");
  1629. Expression::Parameters result;
  1630. while (it != end) {
  1631. if (!consumeToken(")").empty()) {
  1632. return result;
  1633. }
  1634. auto expr = parseExpression();
  1635. if (!expr) throw std::runtime_error("Expected expression in call args");
  1636. if (auto ident = dynamic_cast<VariableExpr*>(expr.get())) {
  1637. if (!consumeToken("=").empty()) {
  1638. auto value = parseExpression();
  1639. if (!value) throw std::runtime_error("Expected expression in for named arg");
  1640. result.emplace_back(ident->get_name(), std::move(value));
  1641. } else {
  1642. result.emplace_back(ident->get_name(), nullptr);
  1643. }
  1644. } else {
  1645. result.emplace_back(std::string(), std::move(expr));
  1646. }
  1647. if (consumeToken(",").empty()) {
  1648. if (consumeToken(")").empty()) {
  1649. throw std::runtime_error("Expected closing parenthesis in call args");
  1650. }
  1651. return result;
  1652. }
  1653. }
  1654. throw std::runtime_error("Expected closing parenthesis in call args");
  1655. }
  1656. ArgumentsExpression parseCallArgs() {
  1657. consumeSpaces();
  1658. if (consumeToken("(").empty()) throw std::runtime_error("Expected opening parenthesis in call args");
  1659. ArgumentsExpression result;
  1660. while (it != end) {
  1661. if (!consumeToken(")").empty()) {
  1662. return result;
  1663. }
  1664. auto expr = parseExpression();
  1665. if (!expr) throw std::runtime_error("Expected expression in call args");
  1666. if (auto ident = dynamic_cast<VariableExpr*>(expr.get())) {
  1667. if (!consumeToken("=").empty()) {
  1668. auto value = parseExpression();
  1669. if (!value) throw std::runtime_error("Expected expression in for named arg");
  1670. result.kwargs.emplace_back(ident->get_name(), std::move(value));
  1671. } else {
  1672. result.args.emplace_back(std::move(expr));
  1673. }
  1674. } else {
  1675. result.args.emplace_back(std::move(expr));
  1676. }
  1677. if (consumeToken(",").empty()) {
  1678. if (consumeToken(")").empty()) {
  1679. throw std::runtime_error("Expected closing parenthesis in call args");
  1680. }
  1681. return result;
  1682. }
  1683. }
  1684. throw std::runtime_error("Expected closing parenthesis in call args");
  1685. }
  1686. std::shared_ptr<VariableExpr> parseIdentifier() {
  1687. static std::regex ident_regex(R"((?!(?:not|is|and|or|del)\b)[a-zA-Z_]\w*)");
  1688. auto location = get_location();
  1689. auto ident = consumeToken(ident_regex);
  1690. if (ident.empty())
  1691. return nullptr;
  1692. return std::make_shared<VariableExpr>(location, ident);
  1693. }
  1694. std::shared_ptr<Expression> parseStringConcat() {
  1695. auto left = parseMathPow();
  1696. if (!left) throw std::runtime_error("Expected left side of 'string concat' expression");
  1697. static std::regex concat_tok(R"(~(?!\}))");
  1698. if (!consumeToken(concat_tok).empty()) {
  1699. auto right = parseLogicalAnd();
  1700. if (!right) throw std::runtime_error("Expected right side of 'string concat' expression");
  1701. left = std::make_shared<BinaryOpExpr>(get_location(), std::move(left), std::move(right), BinaryOpExpr::Op::StrConcat);
  1702. }
  1703. return left;
  1704. }
  1705. std::shared_ptr<Expression> parseMathPow() {
  1706. auto left = parseMathPlusMinus();
  1707. if (!left) throw std::runtime_error("Expected left side of 'math pow' expression");
  1708. while (!consumeToken("**").empty()) {
  1709. auto right = parseMathPlusMinus();
  1710. if (!right) throw std::runtime_error("Expected right side of 'math pow' expression");
  1711. left = std::make_shared<BinaryOpExpr>(get_location(), std::move(left), std::move(right), BinaryOpExpr::Op::MulMul);
  1712. }
  1713. return left;
  1714. }
  1715. std::shared_ptr<Expression> parseMathPlusMinus() {
  1716. static std::regex plus_minus_tok(R"(\+|-(?![}%#]\}))");
  1717. auto left = parseMathMulDiv();
  1718. if (!left) throw std::runtime_error("Expected left side of 'math plus/minus' expression");
  1719. std::string op_str;
  1720. while (!(op_str = consumeToken(plus_minus_tok)).empty()) {
  1721. auto right = parseMathMulDiv();
  1722. if (!right) throw std::runtime_error("Expected right side of 'math plus/minus' expression");
  1723. auto op = op_str == "+" ? BinaryOpExpr::Op::Add : BinaryOpExpr::Op::Sub;
  1724. left = std::make_shared<BinaryOpExpr>(get_location(), std::move(left), std::move(right), op);
  1725. }
  1726. return left;
  1727. }
  1728. std::shared_ptr<Expression> parseMathMulDiv() {
  1729. auto left = parseMathUnaryPlusMinus();
  1730. if (!left) throw std::runtime_error("Expected left side of 'math mul/div' expression");
  1731. static std::regex mul_div_tok(R"(\*\*?|//?|%(?!\}))");
  1732. std::string op_str;
  1733. while (!(op_str = consumeToken(mul_div_tok)).empty()) {
  1734. auto right = parseMathUnaryPlusMinus();
  1735. if (!right) throw std::runtime_error("Expected right side of 'math mul/div' expression");
  1736. auto op = op_str == "*" ? BinaryOpExpr::Op::Mul
  1737. : op_str == "**" ? BinaryOpExpr::Op::MulMul
  1738. : op_str == "/" ? BinaryOpExpr::Op::Div
  1739. : op_str == "//" ? BinaryOpExpr::Op::DivDiv
  1740. : BinaryOpExpr::Op::Mod;
  1741. left = std::make_shared<BinaryOpExpr>(get_location(), std::move(left), std::move(right), op);
  1742. }
  1743. if (!consumeToken("|").empty()) {
  1744. auto expr = parseMathMulDiv();
  1745. if (auto filter = dynamic_cast<FilterExpr*>(expr.get())) {
  1746. filter->prepend(std::move(left));
  1747. return expr;
  1748. } else {
  1749. std::vector<std::shared_ptr<Expression>> parts;
  1750. parts.emplace_back(std::move(left));
  1751. parts.emplace_back(std::move(expr));
  1752. return std::make_shared<FilterExpr>(get_location(), std::move(parts));
  1753. }
  1754. }
  1755. return left;
  1756. }
  1757. std::shared_ptr<Expression> call_func(const std::string & name, ArgumentsExpression && args) const {
  1758. return std::make_shared<CallExpr>(get_location(), std::make_shared<VariableExpr>(get_location(), name), std::move(args));
  1759. }
  1760. std::shared_ptr<Expression> parseMathUnaryPlusMinus() {
  1761. static std::regex unary_plus_minus_tok(R"(\+|-(?![}%#]\}))");
  1762. auto op_str = consumeToken(unary_plus_minus_tok);
  1763. auto expr = parseExpansion();
  1764. if (!expr) throw std::runtime_error("Expected expr of 'unary plus/minus/expansion' expression");
  1765. if (!op_str.empty()) {
  1766. auto op = op_str == "+" ? UnaryOpExpr::Op::Plus : UnaryOpExpr::Op::Minus;
  1767. return std::make_shared<UnaryOpExpr>(get_location(), std::move(expr), op);
  1768. }
  1769. return expr;
  1770. }
  1771. std::shared_ptr<Expression> parseExpansion() {
  1772. static std::regex expansion_tok(R"(\*\*?)");
  1773. auto op_str = consumeToken(expansion_tok);
  1774. auto expr = parseValueExpression();
  1775. if (op_str.empty()) return expr;
  1776. if (!expr) throw std::runtime_error("Expected expr of 'expansion' expression");
  1777. return std::make_shared<UnaryOpExpr>(get_location(), std::move(expr), op_str == "*" ? UnaryOpExpr::Op::Expansion : UnaryOpExpr::Op::ExpansionDict);
  1778. }
  1779. std::shared_ptr<Expression> parseValueExpression() {
  1780. auto parseValue = [&]() -> std::shared_ptr<Expression> {
  1781. auto location = get_location();
  1782. auto constant = parseConstant();
  1783. if (constant) return std::make_shared<LiteralExpr>(location, *constant);
  1784. static std::regex null_regex(R"(null\b)");
  1785. if (!consumeToken(null_regex).empty()) return std::make_shared<LiteralExpr>(location, Value());
  1786. auto identifier = parseIdentifier();
  1787. if (identifier) return identifier;
  1788. auto braced = parseBracedExpressionOrArray();
  1789. if (braced) return braced;
  1790. auto array = parseArray();
  1791. if (array) return array;
  1792. auto dictionary = parseDictionary();
  1793. if (dictionary) return dictionary;
  1794. throw std::runtime_error("Expected value expression");
  1795. };
  1796. auto value = parseValue();
  1797. while (it != end && consumeSpaces() && peekSymbols({ "[", "." })) {
  1798. if (!consumeToken("[").empty()) {
  1799. std::shared_ptr<Expression> index;
  1800. if (!consumeToken(":").empty()) {
  1801. auto slice_end = parseExpression();
  1802. index = std::make_shared<SliceExpr>(slice_end->location, nullptr, std::move(slice_end));
  1803. } else {
  1804. auto slice_start = parseExpression();
  1805. if (!consumeToken(":").empty()) {
  1806. consumeSpaces();
  1807. if (peekSymbols({ "]" })) {
  1808. index = std::make_shared<SliceExpr>(slice_start->location, std::move(slice_start), nullptr);
  1809. } else {
  1810. auto slice_end = parseExpression();
  1811. index = std::make_shared<SliceExpr>(slice_start->location, std::move(slice_start), std::move(slice_end));
  1812. }
  1813. } else {
  1814. index = std::move(slice_start);
  1815. }
  1816. }
  1817. if (!index) throw std::runtime_error("Empty index in subscript");
  1818. if (consumeToken("]").empty()) throw std::runtime_error("Expected closing bracket in subscript");
  1819. value = std::make_shared<SubscriptExpr>(value->location, std::move(value), std::move(index));
  1820. } else if (!consumeToken(".").empty()) {
  1821. auto identifier = parseIdentifier();
  1822. if (!identifier) throw std::runtime_error("Expected identifier in subscript");
  1823. consumeSpaces();
  1824. if (peekSymbols({ "(" })) {
  1825. auto callParams = parseCallArgs();
  1826. value = std::make_shared<MethodCallExpr>(identifier->location, std::move(value), std::move(identifier), std::move(callParams));
  1827. } else {
  1828. auto key = std::make_shared<LiteralExpr>(identifier->location, Value(identifier->get_name()));
  1829. value = std::make_shared<SubscriptExpr>(identifier->location, std::move(value), std::move(key));
  1830. }
  1831. }
  1832. consumeSpaces();
  1833. }
  1834. if (peekSymbols({ "(" })) {
  1835. auto location = get_location();
  1836. auto callParams = parseCallArgs();
  1837. value = std::make_shared<CallExpr>(location, std::move(value), std::move(callParams));
  1838. }
  1839. return value;
  1840. }
  1841. std::shared_ptr<Expression> parseBracedExpressionOrArray() {
  1842. if (consumeToken("(").empty()) return nullptr;
  1843. auto expr = parseExpression();
  1844. if (!expr) throw std::runtime_error("Expected expression in braced expression");
  1845. if (!consumeToken(")").empty()) {
  1846. return expr; // Drop the parentheses
  1847. }
  1848. std::vector<std::shared_ptr<Expression>> tuple;
  1849. tuple.emplace_back(std::move(expr));
  1850. while (it != end) {
  1851. if (consumeToken(",").empty()) throw std::runtime_error("Expected comma in tuple");
  1852. auto next = parseExpression();
  1853. if (!next) throw std::runtime_error("Expected expression in tuple");
  1854. tuple.push_back(std::move(next));
  1855. if (!consumeToken(")").empty()) {
  1856. return std::make_shared<ArrayExpr>(get_location(), std::move(tuple));
  1857. }
  1858. }
  1859. throw std::runtime_error("Expected closing parenthesis");
  1860. }
  1861. std::shared_ptr<Expression> parseArray() {
  1862. if (consumeToken("[").empty()) return nullptr;
  1863. std::vector<std::shared_ptr<Expression>> elements;
  1864. if (!consumeToken("]").empty()) {
  1865. return std::make_shared<ArrayExpr>(get_location(), std::move(elements));
  1866. }
  1867. auto first_expr = parseExpression();
  1868. if (!first_expr) throw std::runtime_error("Expected first expression in array");
  1869. elements.push_back(std::move(first_expr));
  1870. while (it != end) {
  1871. if (!consumeToken(",").empty()) {
  1872. auto expr = parseExpression();
  1873. if (!expr) throw std::runtime_error("Expected expression in array");
  1874. elements.push_back(std::move(expr));
  1875. } else if (!consumeToken("]").empty()) {
  1876. return std::make_shared<ArrayExpr>(get_location(), std::move(elements));
  1877. } else {
  1878. throw std::runtime_error("Expected comma or closing bracket in array");
  1879. }
  1880. }
  1881. throw std::runtime_error("Expected closing bracket");
  1882. }
  1883. std::shared_ptr<Expression> parseDictionary() {
  1884. if (consumeToken("{").empty()) return nullptr;
  1885. std::vector<std::pair<std::shared_ptr<Expression>, std::shared_ptr<Expression>>> elements;
  1886. if (!consumeToken("}").empty()) {
  1887. return std::make_shared<DictExpr>(get_location(), std::move(elements));
  1888. }
  1889. auto parseKeyValuePair = [&]() {
  1890. auto key = parseExpression();
  1891. if (!key) throw std::runtime_error("Expected key in dictionary");
  1892. if (consumeToken(":").empty()) throw std::runtime_error("Expected colon betweek key & value in dictionary");
  1893. auto value = parseExpression();
  1894. if (!value) throw std::runtime_error("Expected value in dictionary");
  1895. elements.emplace_back(std::pair(std::move(key), std::move(value)));
  1896. };
  1897. parseKeyValuePair();
  1898. while (it != end) {
  1899. if (!consumeToken(",").empty()) {
  1900. parseKeyValuePair();
  1901. } else if (!consumeToken("}").empty()) {
  1902. return std::make_shared<DictExpr>(get_location(), std::move(elements));
  1903. } else {
  1904. throw std::runtime_error("Expected comma or closing brace in dictionary");
  1905. }
  1906. }
  1907. throw std::runtime_error("Expected closing brace");
  1908. }
  1909. SpaceHandling parsePreSpace(const std::string& s) const {
  1910. if (s == "-")
  1911. return SpaceHandling::Strip;
  1912. return SpaceHandling::Keep;
  1913. }
  1914. SpaceHandling parsePostSpace(const std::string& s) const {
  1915. if (s == "-") return SpaceHandling::Strip;
  1916. return SpaceHandling::Keep;
  1917. }
  1918. using TemplateTokenVector = std::vector<std::unique_ptr<TemplateToken>>;
  1919. using TemplateTokenIterator = TemplateTokenVector::const_iterator;
  1920. std::vector<std::string> parseVarNames() {
  1921. static std::regex varnames_regex(R"(((?:\w+)(?:[\r\n\s]*,[\r\n\s]*(?:\w+))*)[\r\n\s]*)");
  1922. std::vector<std::string> group;
  1923. if ((group = consumeTokenGroups(varnames_regex)).empty()) throw std::runtime_error("Expected variable names");
  1924. std::vector<std::string> varnames;
  1925. std::istringstream iss(group[1]);
  1926. std::string varname;
  1927. while (std::getline(iss, varname, ',')) {
  1928. varnames.push_back(strip(varname));
  1929. }
  1930. return varnames;
  1931. }
  1932. std::runtime_error unexpected(const TemplateToken & token) const {
  1933. return std::runtime_error("Unexpected " + TemplateToken::typeToString(token.type)
  1934. + error_location_suffix(*template_str, token.location.pos));
  1935. }
  1936. std::runtime_error unterminated(const TemplateToken & token) const {
  1937. return std::runtime_error("Unterminated " + TemplateToken::typeToString(token.type)
  1938. + error_location_suffix(*template_str, token.location.pos));
  1939. }
  1940. TemplateTokenVector tokenize() {
  1941. static std::regex comment_tok(R"(\{#([-~]?)(.*?)([-~]?)#\})");
  1942. static std::regex expr_open_regex(R"(\{\{([-~])?)");
  1943. static std::regex block_open_regex(R"(^\{%([-~])?[\s\n\r]*)");
  1944. static std::regex block_keyword_tok(R"((if|else|elif|endif|for|endfor|set|endset|block|endblock|macro|endmacro|filter|endfilter)\b)");
  1945. static std::regex non_text_open_regex(R"(\{\{|\{%|\{#)");
  1946. static std::regex expr_close_regex(R"([\s\n\r]*([-~])?\}\})");
  1947. static std::regex block_close_regex(R"([\s\n\r]*([-~])?%\})");
  1948. TemplateTokenVector tokens;
  1949. std::vector<std::string> group;
  1950. std::string text;
  1951. std::smatch match;
  1952. try {
  1953. while (it != end) {
  1954. auto location = get_location();
  1955. if (!(group = consumeTokenGroups(comment_tok, SpaceHandling::Keep)).empty()) {
  1956. auto pre_space = parsePreSpace(group[1]);
  1957. auto content = group[2];
  1958. auto post_space = parsePostSpace(group[3]);
  1959. tokens.push_back(std::make_unique<CommentTemplateToken>(location, pre_space, post_space, content));
  1960. } else if (!(group = consumeTokenGroups(expr_open_regex, SpaceHandling::Keep)).empty()) {
  1961. auto pre_space = parsePreSpace(group[1]);
  1962. auto expr = parseExpression();
  1963. if ((group = consumeTokenGroups(expr_close_regex)).empty()) {
  1964. throw std::runtime_error("Expected closing expression tag");
  1965. }
  1966. auto post_space = parsePostSpace(group[1]);
  1967. tokens.push_back(std::make_unique<ExpressionTemplateToken>(location, pre_space, post_space, std::move(expr)));
  1968. } else if (!(group = consumeTokenGroups(block_open_regex, SpaceHandling::Keep)).empty()) {
  1969. auto pre_space = parsePreSpace(group[1]);
  1970. std::string keyword;
  1971. auto parseBlockClose = [&]() -> SpaceHandling {
  1972. if ((group = consumeTokenGroups(block_close_regex)).empty()) throw std::runtime_error("Expected closing block tag");
  1973. return parsePostSpace(group[1]);
  1974. };
  1975. if ((keyword = consumeToken(block_keyword_tok)).empty()) throw std::runtime_error("Expected block keyword");
  1976. if (keyword == "if") {
  1977. auto condition = parseExpression();
  1978. if (!condition) throw std::runtime_error("Expected condition in if block");
  1979. auto post_space = parseBlockClose();
  1980. tokens.push_back(std::make_unique<IfTemplateToken>(location, pre_space, post_space, std::move(condition)));
  1981. } else if (keyword == "elif") {
  1982. auto condition = parseExpression();
  1983. if (!condition) throw std::runtime_error("Expected condition in elif block");
  1984. auto post_space = parseBlockClose();
  1985. tokens.push_back(std::make_unique<ElifTemplateToken>(location, pre_space, post_space, std::move(condition)));
  1986. } else if (keyword == "else") {
  1987. auto post_space = parseBlockClose();
  1988. tokens.push_back(std::make_unique<ElseTemplateToken>(location, pre_space, post_space));
  1989. } else if (keyword == "endif") {
  1990. auto post_space = parseBlockClose();
  1991. tokens.push_back(std::make_unique<EndIfTemplateToken>(location, pre_space, post_space));
  1992. } else if (keyword == "for") {
  1993. static std::regex recursive_tok(R"(recursive\b)");
  1994. static std::regex if_tok(R"(if\b)");
  1995. auto varnames = parseVarNames();
  1996. static std::regex in_tok(R"(in\b)");
  1997. if (consumeToken(in_tok).empty()) throw std::runtime_error("Expected 'in' keyword in for block");
  1998. auto iterable = parseExpression(/* allow_if_expr = */ false);
  1999. if (!iterable) throw std::runtime_error("Expected iterable in for block");
  2000. std::shared_ptr<Expression> condition;
  2001. if (!consumeToken(if_tok).empty()) {
  2002. condition = parseExpression();
  2003. }
  2004. auto recursive = !consumeToken(recursive_tok).empty();
  2005. auto post_space = parseBlockClose();
  2006. tokens.push_back(std::make_unique<ForTemplateToken>(location, pre_space, post_space, std::move(varnames), std::move(iterable), std::move(condition), recursive));
  2007. } else if (keyword == "endfor") {
  2008. auto post_space = parseBlockClose();
  2009. tokens.push_back(std::make_unique<EndForTemplateToken>(location, pre_space, post_space));
  2010. } else if (keyword == "set") {
  2011. static std::regex namespaced_var_regex(R"((\w+)[\s\n\r]*\.[\s\n\r]*(\w+))");
  2012. std::string ns;
  2013. std::vector<std::string> var_names;
  2014. std::shared_ptr<Expression> value;
  2015. if (!(group = consumeTokenGroups(namespaced_var_regex)).empty()) {
  2016. ns = group[1];
  2017. var_names.push_back(group[2]);
  2018. if (consumeToken("=").empty()) throw std::runtime_error("Expected equals sign in set block");
  2019. value = parseExpression();
  2020. if (!value) throw std::runtime_error("Expected value in set block");
  2021. } else {
  2022. var_names = parseVarNames();
  2023. if (!consumeToken("=").empty()) {
  2024. value = parseExpression();
  2025. if (!value) throw std::runtime_error("Expected value in set block");
  2026. }
  2027. }
  2028. auto post_space = parseBlockClose();
  2029. tokens.push_back(std::make_unique<SetTemplateToken>(location, pre_space, post_space, ns, var_names, std::move(value)));
  2030. } else if (keyword == "endset") {
  2031. auto post_space = parseBlockClose();
  2032. tokens.push_back(std::make_unique<EndSetTemplateToken>(location, pre_space, post_space));
  2033. } else if (keyword == "macro") {
  2034. auto macroname = parseIdentifier();
  2035. if (!macroname) throw std::runtime_error("Expected macro name in macro block");
  2036. auto params = parseParameters();
  2037. auto post_space = parseBlockClose();
  2038. tokens.push_back(std::make_unique<MacroTemplateToken>(location, pre_space, post_space, std::move(macroname), std::move(params)));
  2039. } else if (keyword == "endmacro") {
  2040. auto post_space = parseBlockClose();
  2041. tokens.push_back(std::make_unique<EndMacroTemplateToken>(location, pre_space, post_space));
  2042. } else if (keyword == "filter") {
  2043. auto filter = parseExpression();
  2044. if (!filter) throw std::runtime_error("Expected expression in filter block");
  2045. auto post_space = parseBlockClose();
  2046. tokens.push_back(std::make_unique<FilterTemplateToken>(location, pre_space, post_space, std::move(filter)));
  2047. } else if (keyword == "endfilter") {
  2048. auto post_space = parseBlockClose();
  2049. tokens.push_back(std::make_unique<EndFilterTemplateToken>(location, pre_space, post_space));
  2050. } else {
  2051. throw std::runtime_error("Unexpected block: " + keyword);
  2052. }
  2053. } else if (std::regex_search(it, end, match, non_text_open_regex)) {
  2054. auto text_end = it + match.position();
  2055. text = std::string(it, text_end);
  2056. it = text_end;
  2057. tokens.push_back(std::make_unique<TextTemplateToken>(location, SpaceHandling::Keep, SpaceHandling::Keep, text));
  2058. } else {
  2059. text = std::string(it, end);
  2060. it = end;
  2061. tokens.push_back(std::make_unique<TextTemplateToken>(location, SpaceHandling::Keep, SpaceHandling::Keep, text));
  2062. }
  2063. }
  2064. return tokens;
  2065. } catch (const std::exception & e) {
  2066. throw std::runtime_error(e.what() + error_location_suffix(*template_str, std::distance(start, it)));
  2067. }
  2068. }
  2069. std::shared_ptr<TemplateNode> parseTemplate(
  2070. const TemplateTokenIterator & begin,
  2071. TemplateTokenIterator & it,
  2072. const TemplateTokenIterator & end,
  2073. bool fully = false) const {
  2074. std::vector<std::shared_ptr<TemplateNode>> children;
  2075. while (it != end) {
  2076. const auto start = it;
  2077. const auto & token = *(it++);
  2078. if (auto if_token = dynamic_cast<IfTemplateToken*>(token.get())) {
  2079. std::vector<std::pair<std::shared_ptr<Expression>, std::shared_ptr<TemplateNode>>> cascade;
  2080. cascade.emplace_back(std::move(if_token->condition), parseTemplate(begin, it, end));
  2081. while (it != end && (*it)->type == TemplateToken::Type::Elif) {
  2082. auto elif_token = dynamic_cast<ElifTemplateToken*>((*(it++)).get());
  2083. cascade.emplace_back(std::move(elif_token->condition), parseTemplate(begin, it, end));
  2084. }
  2085. if (it != end && (*it)->type == TemplateToken::Type::Else) {
  2086. cascade.emplace_back(nullptr, parseTemplate(begin, ++it, end));
  2087. }
  2088. if (it == end || (*(it++))->type != TemplateToken::Type::EndIf) {
  2089. throw unterminated(**start);
  2090. }
  2091. children.emplace_back(std::make_shared<IfNode>(token->location, std::move(cascade)));
  2092. } else if (auto for_token = dynamic_cast<ForTemplateToken*>(token.get())) {
  2093. auto body = parseTemplate(begin, it, end);
  2094. auto else_body = std::shared_ptr<TemplateNode>();
  2095. if (it != end && (*it)->type == TemplateToken::Type::Else) {
  2096. else_body = parseTemplate(begin, ++it, end);
  2097. }
  2098. if (it == end || (*(it++))->type != TemplateToken::Type::EndFor) {
  2099. throw unterminated(**start);
  2100. }
  2101. children.emplace_back(std::make_shared<ForNode>(token->location, std::move(for_token->var_names), std::move(for_token->iterable), std::move(for_token->condition), std::move(body), for_token->recursive, std::move(else_body)));
  2102. } else if (auto text_token = dynamic_cast<TextTemplateToken*>(token.get())) {
  2103. SpaceHandling pre_space = (it - 1) != begin ? (*(it - 2))->post_space : SpaceHandling::Keep;
  2104. SpaceHandling post_space = it != end ? (*it)->pre_space : SpaceHandling::Keep;
  2105. auto text = text_token->text;
  2106. if (post_space == SpaceHandling::Strip) {
  2107. static std::regex trailing_space_regex(R"((\s|\r|\n)+$)");
  2108. text = std::regex_replace(text, trailing_space_regex, "");
  2109. } else if (options.lstrip_blocks && it != end) {
  2110. auto i = text.size();
  2111. while (i > 0 && (text[i - 1] == ' ' || text[i - 1] == '\t')) i--;
  2112. if ((i == 0 && (it - 1) == begin) || (i > 0 && text[i - 1] == '\n')) {
  2113. text.resize(i);
  2114. }
  2115. }
  2116. if (pre_space == SpaceHandling::Strip) {
  2117. static std::regex leading_space_regex(R"(^(\s|\r|\n)+)");
  2118. text = std::regex_replace(text, leading_space_regex, "");
  2119. } else if (options.trim_blocks && (it - 1) != begin && !dynamic_cast<ExpressionTemplateToken*>((*(it - 2)).get())) {
  2120. if (text.length() > 0 && text[0] == '\n') {
  2121. text.erase(0, 1);
  2122. }
  2123. }
  2124. if (it == end && !options.keep_trailing_newline) {
  2125. auto i = text.size();
  2126. if (i > 0 && text[i - 1] == '\n') {
  2127. i--;
  2128. if (i > 0 && text[i - 1] == '\r') i--;
  2129. text.resize(i);
  2130. }
  2131. }
  2132. children.emplace_back(std::make_shared<TextNode>(token->location, text));
  2133. } else if (auto expr_token = dynamic_cast<ExpressionTemplateToken*>(token.get())) {
  2134. children.emplace_back(std::make_shared<ExpressionNode>(token->location, std::move(expr_token->expr)));
  2135. } else if (auto set_token = dynamic_cast<SetTemplateToken*>(token.get())) {
  2136. if (set_token->value) {
  2137. children.emplace_back(std::make_shared<SetNode>(token->location, set_token->ns, set_token->var_names, std::move(set_token->value)));
  2138. } else {
  2139. auto value_template = parseTemplate(begin, it, end);
  2140. if (it == end || (*(it++))->type != TemplateToken::Type::EndSet) {
  2141. throw unterminated(**start);
  2142. }
  2143. if (!set_token->ns.empty()) throw std::runtime_error("Namespaced set not supported in set with template value");
  2144. if (set_token->var_names.size() != 1) throw std::runtime_error("Structural assignment not supported in set with template value");
  2145. auto & name = set_token->var_names[0];
  2146. children.emplace_back(std::make_shared<SetTemplateNode>(token->location, name, std::move(value_template)));
  2147. }
  2148. } else if (auto macro_token = dynamic_cast<MacroTemplateToken*>(token.get())) {
  2149. auto body = parseTemplate(begin, it, end);
  2150. if (it == end || (*(it++))->type != TemplateToken::Type::EndMacro) {
  2151. throw unterminated(**start);
  2152. }
  2153. children.emplace_back(std::make_shared<MacroNode>(token->location, std::move(macro_token->name), std::move(macro_token->params), std::move(body)));
  2154. } else if (auto filter_token = dynamic_cast<FilterTemplateToken*>(token.get())) {
  2155. auto body = parseTemplate(begin, it, end);
  2156. if (it == end || (*(it++))->type != TemplateToken::Type::EndFilter) {
  2157. throw unterminated(**start);
  2158. }
  2159. children.emplace_back(std::make_shared<FilterNode>(token->location, std::move(filter_token->filter), std::move(body)));
  2160. } else if (dynamic_cast<CommentTemplateToken*>(token.get())) {
  2161. // Ignore comments
  2162. } else if (dynamic_cast<EndForTemplateToken*>(token.get())
  2163. || dynamic_cast<EndSetTemplateToken*>(token.get())
  2164. || dynamic_cast<EndMacroTemplateToken*>(token.get())
  2165. || dynamic_cast<EndFilterTemplateToken*>(token.get())
  2166. || dynamic_cast<EndIfTemplateToken*>(token.get())
  2167. || dynamic_cast<ElseTemplateToken*>(token.get())
  2168. || dynamic_cast<ElifTemplateToken*>(token.get())) {
  2169. it--; // unconsume the token
  2170. break; // exit the loop
  2171. } else {
  2172. throw unexpected(**(it-1));
  2173. }
  2174. }
  2175. if (fully && it != end) {
  2176. throw unexpected(**it);
  2177. }
  2178. if (children.empty()) {
  2179. return std::make_shared<TextNode>(Location { template_str, 0 }, std::string());
  2180. } else if (children.size() == 1) {
  2181. return std::move(children[0]);
  2182. } else {
  2183. return std::make_shared<SequenceNode>(children[0]->location(), std::move(children));
  2184. }
  2185. }
  2186. public:
  2187. static std::shared_ptr<TemplateNode> parse(const std::string& template_str, const Options & options) {
  2188. Parser parser(std::make_shared<std::string>(normalize_newlines(template_str)), options);
  2189. auto tokens = parser.tokenize();
  2190. TemplateTokenIterator begin = tokens.begin();
  2191. auto it = begin;
  2192. TemplateTokenIterator end = tokens.end();
  2193. return parser.parseTemplate(begin, it, end, /* full= */ true);
  2194. }
  2195. };
  2196. static Value simple_function(const std::string & fn_name, const std::vector<std::string> & params, const std::function<Value(const std::shared_ptr<Context> &, Value & args)> & fn) {
  2197. std::map<std::string, size_t> named_positions;
  2198. for (size_t i = 0, n = params.size(); i < n; i++) named_positions[params[i]] = i;
  2199. return Value::callable([=](const std::shared_ptr<Context> & context, ArgumentsValue & args) -> Value {
  2200. auto args_obj = Value::object();
  2201. std::vector<bool> provided_args(params.size());
  2202. for (size_t i = 0, n = args.args.size(); i < n; i++) {
  2203. auto & arg = args.args[i];
  2204. if (i < params.size()) {
  2205. args_obj.set(params[i], arg);
  2206. provided_args[i] = true;
  2207. } else {
  2208. throw std::runtime_error("Too many positional params for " + fn_name);
  2209. }
  2210. }
  2211. for (auto & [name, value] : args.kwargs) {
  2212. auto named_pos_it = named_positions.find(name);
  2213. if (named_pos_it == named_positions.end()) {
  2214. throw std::runtime_error("Unknown argument " + name + " for function " + fn_name);
  2215. }
  2216. provided_args[named_pos_it->second] = true;
  2217. args_obj.set(name, value);
  2218. }
  2219. return fn(context, args_obj);
  2220. });
  2221. }
  2222. inline std::shared_ptr<Context> Context::builtins() {
  2223. auto globals = Value::object();
  2224. globals.set("raise_exception", simple_function("raise_exception", { "message" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2225. throw std::runtime_error(args.at("message").get<std::string>());
  2226. }));
  2227. globals.set("tojson", simple_function("tojson", { "value", "indent" }, [](const std::shared_ptr<Context> &, Value & args) {
  2228. return Value(args.at("value").dump(args.get<int64_t>("indent", -1), /* tojson= */ true));
  2229. }));
  2230. globals.set("items", simple_function("items", { "object" }, [](const std::shared_ptr<Context> &, Value & args) {
  2231. auto items = Value::array();
  2232. if (args.contains("object")) {
  2233. auto & obj = args.at("object");
  2234. if (obj.is_string()) {
  2235. auto json_obj = json::parse(obj.get<std::string>());
  2236. for (const auto & kv : json_obj.items()) {
  2237. items.push_back(Value::array({kv.key(), kv.value()}));
  2238. }
  2239. } else if (!obj.is_null()) {
  2240. for (auto & key : obj.keys()) {
  2241. items.push_back(Value::array({key, obj.at(key)}));
  2242. }
  2243. }
  2244. }
  2245. return items;
  2246. }));
  2247. globals.set("last", simple_function("last", { "items" }, [](const std::shared_ptr<Context> &, Value & args) {
  2248. auto items = args.at("items");
  2249. if (!items.is_array()) throw std::runtime_error("object is not a list");
  2250. if (items.size() == 0) return Value();
  2251. return items.at(items.size() - 1);
  2252. }));
  2253. globals.set("trim", simple_function("trim", { "text" }, [](const std::shared_ptr<Context> &, Value & args) {
  2254. auto & text = args.at("text");
  2255. return text.is_null() ? text : Value(strip(text.get<std::string>()));
  2256. }));
  2257. globals.set("lower", simple_function("lower", { "text" }, [](const std::shared_ptr<Context> &, Value & args) {
  2258. auto text = args.at("text");
  2259. if (text.is_null()) return text;
  2260. std::string res;
  2261. auto str = text.get<std::string>();
  2262. std::transform(str.begin(), str.end(), std::back_inserter(res), ::tolower);
  2263. return Value(res);
  2264. }));
  2265. globals.set("default", Value::callable([=](const std::shared_ptr<Context> &, ArgumentsValue & args) {
  2266. args.expectArgs("default", {2, 3}, {0, 1});
  2267. auto & value = args.args[0];
  2268. auto & default_value = args.args[1];
  2269. bool boolean = false;
  2270. if (args.args.size() == 3) {
  2271. boolean = args.args[2].get<bool>();
  2272. } else {
  2273. Value bv = args.get_named("boolean");
  2274. if (!bv.is_null()) {
  2275. boolean = bv.get<bool>();
  2276. }
  2277. }
  2278. return boolean ? (value.to_bool() ? value : default_value) : value.is_null() ? default_value : value;
  2279. }));
  2280. auto escape = simple_function("escape", { "text" }, [](const std::shared_ptr<Context> &, Value & args) {
  2281. return Value(html_escape(args.at("text").get<std::string>()));
  2282. });
  2283. globals.set("e", escape);
  2284. globals.set("escape", escape);
  2285. globals.set("joiner", simple_function("joiner", { "sep" }, [](const std::shared_ptr<Context> &, Value & args) {
  2286. auto sep = args.get<std::string>("sep", "");
  2287. auto first = std::make_shared<bool>(true);
  2288. return simple_function("", {}, [sep, first](const std::shared_ptr<Context> &, const Value &) -> Value {
  2289. if (*first) {
  2290. *first = false;
  2291. return "";
  2292. }
  2293. return sep;
  2294. });
  2295. return Value(html_escape(args.at("text").get<std::string>()));
  2296. }));
  2297. globals.set("count", simple_function("count", { "items" }, [](const std::shared_ptr<Context> &, Value & args) {
  2298. return Value((int64_t) args.at("items").size());
  2299. }));
  2300. globals.set("dictsort", simple_function("dictsort", { "value" }, [](const std::shared_ptr<Context> &, Value & args) {
  2301. if (args.size() != 1) throw std::runtime_error("dictsort expects exactly 1 argument (TODO: fix implementation)");
  2302. auto & value = args.at("value");
  2303. auto keys = value.keys();
  2304. std::sort(keys.begin(), keys.end());
  2305. auto res = Value::array();
  2306. for (auto & key : keys) {
  2307. res.push_back(Value::array({key, value.at(key)}));
  2308. }
  2309. return res;
  2310. }));
  2311. globals.set("join", simple_function("join", { "items", "d" }, [](const std::shared_ptr<Context> &, Value & args) {
  2312. auto do_join = [](Value & items, const std::string & sep) {
  2313. std::ostringstream oss;
  2314. auto first = true;
  2315. for (size_t i = 0, n = items.size(); i < n; ++i) {
  2316. if (first) first = false;
  2317. else oss << sep;
  2318. oss << items.at(i).to_str();
  2319. }
  2320. return Value(oss.str());
  2321. };
  2322. auto sep = args.get<std::string>("d", "");
  2323. if (args.contains("items")) {
  2324. auto & items = args.at("items");
  2325. return do_join(items, sep);
  2326. } else {
  2327. return simple_function("", {"items"}, [sep, do_join](const std::shared_ptr<Context> &, Value & args) {
  2328. auto & items = args.at("items");
  2329. if (!items.to_bool() || !items.is_array()) throw std::runtime_error("join expects an array for items, got: " + items.dump());
  2330. return do_join(items, sep);
  2331. });
  2332. }
  2333. }));
  2334. globals.set("namespace", Value::callable([=](const std::shared_ptr<Context> &, ArgumentsValue & args) {
  2335. auto ns = Value::object();
  2336. args.expectArgs("namespace", {0, 0}, {0, (std::numeric_limits<size_t>::max)()});
  2337. for (auto & [name, value] : args.kwargs) {
  2338. ns.set(name, value);
  2339. }
  2340. return ns;
  2341. }));
  2342. auto equalto = simple_function("equalto", { "expected", "actual" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2343. return args.at("actual") == args.at("expected");
  2344. });
  2345. globals.set("equalto", equalto);
  2346. globals.set("==", equalto);
  2347. globals.set("length", simple_function("length", { "items" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2348. auto & items = args.at("items");
  2349. return (int64_t) items.size();
  2350. }));
  2351. globals.set("safe", simple_function("safe", { "value" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2352. return args.at("value").to_str();
  2353. }));
  2354. globals.set("string", simple_function("string", { "value" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2355. return args.at("value").to_str();
  2356. }));
  2357. globals.set("int", simple_function("int", { "value" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2358. return args.at("value").to_int();
  2359. }));
  2360. globals.set("list", simple_function("list", { "items" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2361. auto & items = args.at("items");
  2362. if (!items.is_array()) throw std::runtime_error("object is not iterable");
  2363. return items;
  2364. }));
  2365. globals.set("unique", simple_function("unique", { "items" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2366. auto & items = args.at("items");
  2367. if (!items.is_array()) throw std::runtime_error("object is not iterable");
  2368. std::unordered_set<Value> seen;
  2369. auto result = Value::array();
  2370. for (size_t i = 0, n = items.size(); i < n; i++) {
  2371. auto pair = seen.insert(items.at(i));
  2372. if (pair.second) {
  2373. result.push_back(items.at(i));
  2374. }
  2375. }
  2376. return result;
  2377. }));
  2378. auto make_filter = [](const Value & filter, Value & extra_args) -> Value {
  2379. return simple_function("", { "value" }, [=](const std::shared_ptr<Context> & context, Value & args) {
  2380. auto & value = args.at("value");
  2381. ArgumentsValue actual_args;
  2382. actual_args.args.emplace_back(value);
  2383. for (size_t i = 0, n = extra_args.size(); i < n; i++) {
  2384. actual_args.args.emplace_back(extra_args.at(i));
  2385. }
  2386. return filter.call(context, actual_args);
  2387. });
  2388. };
  2389. // https://jinja.palletsprojects.com/en/3.0.x/templates/#jinja-filters.reject
  2390. globals.set("reject", Value::callable([=](const std::shared_ptr<Context> & context, ArgumentsValue & args) {
  2391. args.expectArgs("reject", {2, (std::numeric_limits<size_t>::max)()}, {0, 0});
  2392. auto & items = args.args[0];
  2393. auto filter_fn = context->get(args.args[1]);
  2394. if (filter_fn.is_null()) throw std::runtime_error("Undefined filter: " + args.args[1].dump());
  2395. auto filter_args = Value::array();
  2396. for (size_t i = 2, n = args.args.size(); i < n; i++) {
  2397. filter_args.push_back(args.args[i]);
  2398. }
  2399. auto filter = make_filter(filter_fn, filter_args);
  2400. auto res = Value::array();
  2401. for (size_t i = 0, n = items.size(); i < n; i++) {
  2402. auto & item = items.at(i);
  2403. ArgumentsValue filter_args;
  2404. filter_args.args.emplace_back(item);
  2405. auto pred_res = filter.call(context, filter_args);
  2406. if (!pred_res.to_bool()) {
  2407. res.push_back(item);
  2408. }
  2409. }
  2410. return res;
  2411. }));
  2412. globals.set("map", Value::callable([=](const std::shared_ptr<Context> & context, ArgumentsValue & args) {
  2413. auto res = Value::array();
  2414. if (args.args.size() == 1 &&
  2415. ((args.has_named("attribute") && args.kwargs.size() == 1) || (args.has_named("default") && args.kwargs.size() == 2))) {
  2416. auto & items = args.args[0];
  2417. auto attr_name = args.get_named("attribute");
  2418. auto default_value = args.get_named("default");
  2419. for (size_t i = 0, n = items.size(); i < n; i++) {
  2420. auto & item = items.at(i);
  2421. auto attr = item.get(attr_name);
  2422. res.push_back(attr.is_null() ? default_value : attr);
  2423. }
  2424. } else if (args.kwargs.empty() && args.args.size() >= 2) {
  2425. auto fn = context->get(args.args[1]);
  2426. if (fn.is_null()) throw std::runtime_error("Undefined filter: " + args.args[1].dump());
  2427. ArgumentsValue filter_args { {Value()}, {} };
  2428. for (size_t i = 2, n = args.args.size(); i < n; i++) {
  2429. filter_args.args.emplace_back(args.args[i]);
  2430. }
  2431. for (size_t i = 0, n = args.args[0].size(); i < n; i++) {
  2432. auto & item = args.args[0].at(i);
  2433. filter_args.args[0] = item;
  2434. res.push_back(fn.call(context, filter_args));
  2435. }
  2436. } else {
  2437. throw std::runtime_error("Invalid or unsupported arguments for map");
  2438. }
  2439. return res;
  2440. }));
  2441. globals.set("indent", simple_function("indent", { "text", "indent", "first" }, [](const std::shared_ptr<Context> &, Value & args) {
  2442. auto text = args.at("text").get<std::string>();
  2443. auto first = args.get<bool>("first", false);
  2444. std::string out;
  2445. std::string indent(args.get<int64_t>("indent", 0), ' ');
  2446. std::istringstream iss(text);
  2447. std::string line;
  2448. auto is_first = true;
  2449. while (std::getline(iss, line, '\n')) {
  2450. auto needs_indent = !is_first || first;
  2451. if (is_first) is_first = false;
  2452. else out += "\n";
  2453. if (needs_indent) out += indent;
  2454. out += line;
  2455. }
  2456. if (!text.empty() && text.back() == '\n') out += "\n";
  2457. return out;
  2458. }));
  2459. globals.set("selectattr", Value::callable([=](const std::shared_ptr<Context> & context, ArgumentsValue & args) {
  2460. args.expectArgs("selectattr", {2, (std::numeric_limits<size_t>::max)()}, {0, 0});
  2461. auto & items = args.args[0];
  2462. if (items.is_null())
  2463. return Value::array();
  2464. auto attr_name = args.args[1].get<std::string>();
  2465. bool has_test = false;
  2466. Value test_fn;
  2467. ArgumentsValue test_args {{Value()}, {}};
  2468. if (args.args.size() >= 3) {
  2469. has_test = true;
  2470. test_fn = context->get(args.args[2]);
  2471. if (test_fn.is_null()) throw std::runtime_error("Undefined test: " + args.args[2].dump());
  2472. for (size_t i = 3, n = args.args.size(); i < n; i++) {
  2473. test_args.args.emplace_back(args.args[i]);
  2474. }
  2475. test_args.kwargs = args.kwargs;
  2476. }
  2477. auto res = Value::array();
  2478. for (size_t i = 0, n = items.size(); i < n; i++) {
  2479. auto & item = items.at(i);
  2480. auto attr = item.get(attr_name);
  2481. if (has_test) {
  2482. test_args.args[0] = attr;
  2483. if (test_fn.call(context, test_args).to_bool()) {
  2484. res.push_back(item);
  2485. }
  2486. } else {
  2487. res.push_back(attr);
  2488. }
  2489. }
  2490. return res;
  2491. }));
  2492. globals.set("range", Value::callable([=](const std::shared_ptr<Context> &, ArgumentsValue & args) {
  2493. std::vector<int64_t> startEndStep(3);
  2494. std::vector<bool> param_set(3);
  2495. if (args.args.size() == 1) {
  2496. startEndStep[1] = args.args[0].get<int64_t>();
  2497. param_set[1] = true;
  2498. } else {
  2499. for (size_t i = 0; i < args.args.size(); i++) {
  2500. auto & arg = args.args[i];
  2501. auto v = arg.get<int64_t>();
  2502. startEndStep[i] = v;
  2503. param_set[i] = true;
  2504. }
  2505. }
  2506. for (auto & [name, value] : args.kwargs) {
  2507. size_t i;
  2508. if (name == "start") i = 0;
  2509. else if (name == "end") i = 1;
  2510. else if (name == "step") i = 2;
  2511. else throw std::runtime_error("Unknown argument " + name + " for function range");
  2512. if (param_set[i]) {
  2513. throw std::runtime_error("Duplicate argument " + name + " for function range");
  2514. }
  2515. startEndStep[i] = value.get<int64_t>();
  2516. param_set[i] = true;
  2517. }
  2518. if (!param_set[1]) {
  2519. throw std::runtime_error("Missing required argument 'end' for function range");
  2520. }
  2521. int64_t start = param_set[0] ? startEndStep[0] : 0;
  2522. int64_t end = startEndStep[1];
  2523. int64_t step = param_set[2] ? startEndStep[2] : 1;
  2524. auto res = Value::array();
  2525. if (step > 0) {
  2526. for (int64_t i = start; i < end; i += step) {
  2527. res.push_back(Value(i));
  2528. }
  2529. } else {
  2530. for (int64_t i = start; i > end; i += step) {
  2531. res.push_back(Value(i));
  2532. }
  2533. }
  2534. return res;
  2535. }));
  2536. return std::make_shared<Context>(std::move(globals));
  2537. }
  2538. inline std::shared_ptr<Context> Context::make(Value && values, const std::shared_ptr<Context> & parent) {
  2539. return std::make_shared<Context>(values.is_null() ? Value::object() : std::move(values), parent);
  2540. }
  2541. } // namespace minja