minja.hpp 119 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883
  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, const 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, Generation, EndGeneration, Set, EndSet, Comment, Macro, EndMacro, Filter, EndFilter, Break, Continue };
  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. case Type::Generation: return "generation";
  657. case Type::EndGeneration: return "endgeneration";
  658. case Type::Break: return "break";
  659. case Type::Continue: return "continue";
  660. }
  661. return "Unknown";
  662. }
  663. TemplateToken(Type type, const Location & location, SpaceHandling pre, SpaceHandling post) : type(type), location(location), pre_space(pre), post_space(post) {}
  664. virtual ~TemplateToken() = default;
  665. Type type;
  666. Location location;
  667. SpaceHandling pre_space = SpaceHandling::Keep;
  668. SpaceHandling post_space = SpaceHandling::Keep;
  669. };
  670. struct TextTemplateToken : public TemplateToken {
  671. std::string text;
  672. TextTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, const std::string& t) : TemplateToken(Type::Text, location, pre, post), text(t) {}
  673. };
  674. struct ExpressionTemplateToken : public TemplateToken {
  675. std::shared_ptr<Expression> expr;
  676. ExpressionTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, std::shared_ptr<Expression> && e) : TemplateToken(Type::Expression, location, pre, post), expr(std::move(e)) {}
  677. };
  678. struct IfTemplateToken : public TemplateToken {
  679. std::shared_ptr<Expression> condition;
  680. IfTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, std::shared_ptr<Expression> && c) : TemplateToken(Type::If, location, pre, post), condition(std::move(c)) {}
  681. };
  682. struct ElifTemplateToken : public TemplateToken {
  683. std::shared_ptr<Expression> condition;
  684. ElifTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, std::shared_ptr<Expression> && c) : TemplateToken(Type::Elif, location, pre, post), condition(std::move(c)) {}
  685. };
  686. struct ElseTemplateToken : public TemplateToken {
  687. ElseTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::Else, location, pre, post) {}
  688. };
  689. struct EndIfTemplateToken : public TemplateToken {
  690. EndIfTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::EndIf, location, pre, post) {}
  691. };
  692. struct MacroTemplateToken : public TemplateToken {
  693. std::shared_ptr<VariableExpr> name;
  694. Expression::Parameters params;
  695. MacroTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, std::shared_ptr<VariableExpr> && n, Expression::Parameters && p)
  696. : TemplateToken(Type::Macro, location, pre, post), name(std::move(n)), params(std::move(p)) {}
  697. };
  698. struct EndMacroTemplateToken : public TemplateToken {
  699. EndMacroTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::EndMacro, location, pre, post) {}
  700. };
  701. struct FilterTemplateToken : public TemplateToken {
  702. std::shared_ptr<Expression> filter;
  703. FilterTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, std::shared_ptr<Expression> && filter)
  704. : TemplateToken(Type::Filter, location, pre, post), filter(std::move(filter)) {}
  705. };
  706. struct EndFilterTemplateToken : public TemplateToken {
  707. EndFilterTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::EndFilter, location, pre, post) {}
  708. };
  709. struct ForTemplateToken : public TemplateToken {
  710. std::vector<std::string> var_names;
  711. std::shared_ptr<Expression> iterable;
  712. std::shared_ptr<Expression> condition;
  713. bool recursive;
  714. ForTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, const std::vector<std::string> & vns, std::shared_ptr<Expression> && iter,
  715. std::shared_ptr<Expression> && c, bool r)
  716. : TemplateToken(Type::For, location, pre, post), var_names(vns), iterable(std::move(iter)), condition(std::move(c)), recursive(r) {}
  717. };
  718. struct EndForTemplateToken : public TemplateToken {
  719. EndForTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::EndFor, location, pre, post) {}
  720. };
  721. struct GenerationTemplateToken : public TemplateToken {
  722. GenerationTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::Generation, location, pre, post) {}
  723. };
  724. struct EndGenerationTemplateToken : public TemplateToken {
  725. EndGenerationTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::EndGeneration, location, pre, post) {}
  726. };
  727. struct SetTemplateToken : public TemplateToken {
  728. std::string ns;
  729. std::vector<std::string> var_names;
  730. std::shared_ptr<Expression> value;
  731. SetTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, const std::string & ns, const std::vector<std::string> & vns, std::shared_ptr<Expression> && v)
  732. : TemplateToken(Type::Set, location, pre, post), ns(ns), var_names(vns), value(std::move(v)) {}
  733. };
  734. struct EndSetTemplateToken : public TemplateToken {
  735. EndSetTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::EndSet, location, pre, post) {}
  736. };
  737. struct CommentTemplateToken : public TemplateToken {
  738. std::string text;
  739. CommentTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, const std::string& t) : TemplateToken(Type::Comment, location, pre, post), text(t) {}
  740. };
  741. enum class LoopControlType { Break, Continue };
  742. class LoopControlException : public std::runtime_error {
  743. public:
  744. LoopControlType control_type;
  745. LoopControlException(const std::string & message, LoopControlType control_type) : std::runtime_error(message), control_type(control_type) {}
  746. LoopControlException(LoopControlType control_type)
  747. : std::runtime_error((control_type == LoopControlType::Continue ? "continue" : "break") + std::string(" outside of a loop")),
  748. control_type(control_type) {}
  749. };
  750. struct LoopControlTemplateToken : public TemplateToken {
  751. LoopControlType control_type;
  752. LoopControlTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, LoopControlType control_type) : TemplateToken(Type::Break, location, pre, post), control_type(control_type) {}
  753. };
  754. class TemplateNode {
  755. Location location_;
  756. protected:
  757. virtual void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const = 0;
  758. public:
  759. TemplateNode(const Location & location) : location_(location) {}
  760. void render(std::ostringstream & out, const std::shared_ptr<Context> & context) const {
  761. try {
  762. do_render(out, context);
  763. } catch (const LoopControlException & e) {
  764. // TODO: make stack creation lazy. Only needed if it was thrown outside of a loop.
  765. std::ostringstream err;
  766. err << e.what();
  767. if (location_.source) err << error_location_suffix(*location_.source, location_.pos);
  768. throw LoopControlException(err.str(), e.control_type);
  769. } catch (const std::exception & e) {
  770. std::ostringstream err;
  771. err << e.what();
  772. if (location_.source) err << error_location_suffix(*location_.source, location_.pos);
  773. throw std::runtime_error(err.str());
  774. }
  775. }
  776. const Location & location() const { return location_; }
  777. virtual ~TemplateNode() = default;
  778. std::string render(const std::shared_ptr<Context> & context) const {
  779. std::ostringstream out;
  780. render(out, context);
  781. return out.str();
  782. }
  783. };
  784. class SequenceNode : public TemplateNode {
  785. std::vector<std::shared_ptr<TemplateNode>> children;
  786. public:
  787. SequenceNode(const Location & location, std::vector<std::shared_ptr<TemplateNode>> && c)
  788. : TemplateNode(location), children(std::move(c)) {}
  789. void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const override {
  790. for (const auto& child : children) child->render(out, context);
  791. }
  792. };
  793. class TextNode : public TemplateNode {
  794. std::string text;
  795. public:
  796. TextNode(const Location & location, const std::string& t) : TemplateNode(location), text(t) {}
  797. void do_render(std::ostringstream & out, const std::shared_ptr<Context> &) const override {
  798. out << text;
  799. }
  800. };
  801. class ExpressionNode : public TemplateNode {
  802. std::shared_ptr<Expression> expr;
  803. public:
  804. ExpressionNode(const Location & location, std::shared_ptr<Expression> && e) : TemplateNode(location), expr(std::move(e)) {}
  805. void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const override {
  806. if (!expr) throw std::runtime_error("ExpressionNode.expr is null");
  807. auto result = expr->evaluate(context);
  808. if (result.is_string()) {
  809. out << result.get<std::string>();
  810. } else if (result.is_boolean()) {
  811. out << (result.get<bool>() ? "True" : "False");
  812. } else if (!result.is_null()) {
  813. out << result.dump();
  814. }
  815. }
  816. };
  817. class IfNode : public TemplateNode {
  818. std::vector<std::pair<std::shared_ptr<Expression>, std::shared_ptr<TemplateNode>>> cascade;
  819. public:
  820. IfNode(const Location & location, std::vector<std::pair<std::shared_ptr<Expression>, std::shared_ptr<TemplateNode>>> && c)
  821. : TemplateNode(location), cascade(std::move(c)) {}
  822. void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const override {
  823. for (const auto& branch : cascade) {
  824. auto enter_branch = true;
  825. if (branch.first) {
  826. enter_branch = branch.first->evaluate(context).to_bool();
  827. }
  828. if (enter_branch) {
  829. if (!branch.second) throw std::runtime_error("IfNode.cascade.second is null");
  830. branch.second->render(out, context);
  831. return;
  832. }
  833. }
  834. }
  835. };
  836. class LoopControlNode : public TemplateNode {
  837. LoopControlType control_type_;
  838. public:
  839. LoopControlNode(const Location & location, LoopControlType control_type) : TemplateNode(location), control_type_(control_type) {}
  840. void do_render(std::ostringstream &, const std::shared_ptr<Context> &) const override {
  841. throw LoopControlException(control_type_);
  842. }
  843. };
  844. class ForNode : public TemplateNode {
  845. std::vector<std::string> var_names;
  846. std::shared_ptr<Expression> iterable;
  847. std::shared_ptr<Expression> condition;
  848. std::shared_ptr<TemplateNode> body;
  849. bool recursive;
  850. std::shared_ptr<TemplateNode> else_body;
  851. public:
  852. ForNode(const Location & location, std::vector<std::string> && var_names, std::shared_ptr<Expression> && iterable,
  853. std::shared_ptr<Expression> && condition, std::shared_ptr<TemplateNode> && body, bool recursive, std::shared_ptr<TemplateNode> && else_body)
  854. : 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)) {}
  855. void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const override {
  856. // https://jinja.palletsprojects.com/en/3.0.x/templates/#for
  857. if (!iterable) throw std::runtime_error("ForNode.iterable is null");
  858. if (!body) throw std::runtime_error("ForNode.body is null");
  859. auto iterable_value = iterable->evaluate(context);
  860. Value::CallableType loop_function;
  861. std::function<void(Value&)> visit = [&](Value& iter) {
  862. auto filtered_items = Value::array();
  863. if (!iter.is_null()) {
  864. if (!iterable_value.is_iterable()) {
  865. throw std::runtime_error("For loop iterable must be iterable: " + iterable_value.dump());
  866. }
  867. iterable_value.for_each([&](Value & item) {
  868. destructuring_assign(var_names, context, item);
  869. if (!condition || condition->evaluate(context).to_bool()) {
  870. filtered_items.push_back(item);
  871. }
  872. });
  873. }
  874. if (filtered_items.empty()) {
  875. if (else_body) {
  876. else_body->render(out, context);
  877. }
  878. } else {
  879. auto loop = recursive ? Value::callable(loop_function) : Value::object();
  880. loop.set("length", (int64_t) filtered_items.size());
  881. size_t cycle_index = 0;
  882. loop.set("cycle", Value::callable([&](const std::shared_ptr<Context> &, ArgumentsValue & args) {
  883. if (args.args.empty() || !args.kwargs.empty()) {
  884. throw std::runtime_error("cycle() expects at least 1 positional argument and no named arg");
  885. }
  886. auto item = args.args[cycle_index];
  887. cycle_index = (cycle_index + 1) % args.args.size();
  888. return item;
  889. }));
  890. auto loop_context = Context::make(Value::object(), context);
  891. loop_context->set("loop", loop);
  892. for (size_t i = 0, n = filtered_items.size(); i < n; ++i) {
  893. auto & item = filtered_items.at(i);
  894. destructuring_assign(var_names, loop_context, item);
  895. loop.set("index", (int64_t) i + 1);
  896. loop.set("index0", (int64_t) i);
  897. loop.set("revindex", (int64_t) (n - i));
  898. loop.set("revindex0", (int64_t) (n - i - 1));
  899. loop.set("length", (int64_t) n);
  900. loop.set("first", i == 0);
  901. loop.set("last", i == (n - 1));
  902. loop.set("previtem", i > 0 ? filtered_items.at(i - 1) : Value());
  903. loop.set("nextitem", i < n - 1 ? filtered_items.at(i + 1) : Value());
  904. try {
  905. body->render(out, loop_context);
  906. } catch (const LoopControlException & e) {
  907. if (e.control_type == LoopControlType::Break) break;
  908. if (e.control_type == LoopControlType::Continue) continue;
  909. }
  910. }
  911. }
  912. };
  913. if (recursive) {
  914. loop_function = [&](const std::shared_ptr<Context> &, ArgumentsValue & args) {
  915. if (args.args.size() != 1 || !args.kwargs.empty() || !args.args[0].is_array()) {
  916. throw std::runtime_error("loop() expects exactly 1 positional iterable argument");
  917. }
  918. auto & items = args.args[0];
  919. visit(items);
  920. return Value();
  921. };
  922. }
  923. visit(iterable_value);
  924. }
  925. };
  926. class MacroNode : public TemplateNode {
  927. std::shared_ptr<VariableExpr> name;
  928. Expression::Parameters params;
  929. std::shared_ptr<TemplateNode> body;
  930. std::unordered_map<std::string, size_t> named_param_positions;
  931. public:
  932. MacroNode(const Location & location, std::shared_ptr<VariableExpr> && n, Expression::Parameters && p, std::shared_ptr<TemplateNode> && b)
  933. : TemplateNode(location), name(std::move(n)), params(std::move(p)), body(std::move(b)) {
  934. for (size_t i = 0; i < params.size(); ++i) {
  935. const auto & name = params[i].first;
  936. if (!name.empty()) {
  937. named_param_positions[name] = i;
  938. }
  939. }
  940. }
  941. void do_render(std::ostringstream &, const std::shared_ptr<Context> & macro_context) const override {
  942. if (!name) throw std::runtime_error("MacroNode.name is null");
  943. if (!body) throw std::runtime_error("MacroNode.body is null");
  944. auto callable = Value::callable([&](const std::shared_ptr<Context> & context, ArgumentsValue & args) {
  945. auto call_context = macro_context;
  946. std::vector<bool> param_set(params.size(), false);
  947. for (size_t i = 0, n = args.args.size(); i < n; i++) {
  948. auto & arg = args.args[i];
  949. if (i >= params.size()) throw std::runtime_error("Too many positional arguments for macro " + name->get_name());
  950. param_set[i] = true;
  951. auto & param_name = params[i].first;
  952. call_context->set(param_name, arg);
  953. }
  954. for (auto & [arg_name, value] : args.kwargs) {
  955. auto it = named_param_positions.find(arg_name);
  956. if (it == named_param_positions.end()) throw std::runtime_error("Unknown parameter name for macro " + name->get_name() + ": " + arg_name);
  957. call_context->set(arg_name, value);
  958. param_set[it->second] = true;
  959. }
  960. // Set default values for parameters that were not passed
  961. for (size_t i = 0, n = params.size(); i < n; i++) {
  962. if (!param_set[i] && params[i].second != nullptr) {
  963. auto val = params[i].second->evaluate(context);
  964. call_context->set(params[i].first, val);
  965. }
  966. }
  967. return body->render(call_context);
  968. });
  969. macro_context->set(name->get_name(), callable);
  970. }
  971. };
  972. class FilterNode : public TemplateNode {
  973. std::shared_ptr<Expression> filter;
  974. std::shared_ptr<TemplateNode> body;
  975. public:
  976. FilterNode(const Location & location, std::shared_ptr<Expression> && f, std::shared_ptr<TemplateNode> && b)
  977. : TemplateNode(location), filter(std::move(f)), body(std::move(b)) {}
  978. void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const override {
  979. if (!filter) throw std::runtime_error("FilterNode.filter is null");
  980. if (!body) throw std::runtime_error("FilterNode.body is null");
  981. auto filter_value = filter->evaluate(context);
  982. if (!filter_value.is_callable()) {
  983. throw std::runtime_error("Filter must be a callable: " + filter_value.dump());
  984. }
  985. std::string rendered_body = body->render(context);
  986. ArgumentsValue filter_args = {{Value(rendered_body)}, {}};
  987. auto result = filter_value.call(context, filter_args);
  988. out << result.to_str();
  989. }
  990. };
  991. class SetNode : public TemplateNode {
  992. std::string ns;
  993. std::vector<std::string> var_names;
  994. std::shared_ptr<Expression> value;
  995. public:
  996. SetNode(const Location & location, const std::string & ns, const std::vector<std::string> & vns, std::shared_ptr<Expression> && v)
  997. : TemplateNode(location), ns(ns), var_names(vns), value(std::move(v)) {}
  998. void do_render(std::ostringstream &, const std::shared_ptr<Context> & context) const override {
  999. if (!value) throw std::runtime_error("SetNode.value is null");
  1000. if (!ns.empty()) {
  1001. if (var_names.size() != 1) {
  1002. throw std::runtime_error("Namespaced set only supports a single variable name");
  1003. }
  1004. auto & name = var_names[0];
  1005. auto ns_value = context->get(ns);
  1006. if (!ns_value.is_object()) throw std::runtime_error("Namespace '" + ns + "' is not an object");
  1007. ns_value.set(name, this->value->evaluate(context));
  1008. } else {
  1009. auto val = value->evaluate(context);
  1010. destructuring_assign(var_names, context, val);
  1011. }
  1012. }
  1013. };
  1014. class SetTemplateNode : public TemplateNode {
  1015. std::string name;
  1016. std::shared_ptr<TemplateNode> template_value;
  1017. public:
  1018. SetTemplateNode(const Location & location, const std::string & name, std::shared_ptr<TemplateNode> && tv)
  1019. : TemplateNode(location), name(name), template_value(std::move(tv)) {}
  1020. void do_render(std::ostringstream &, const std::shared_ptr<Context> & context) const override {
  1021. if (!template_value) throw std::runtime_error("SetTemplateNode.template_value is null");
  1022. Value value { template_value->render(context) };
  1023. context->set(name, value);
  1024. }
  1025. };
  1026. class IfExpr : public Expression {
  1027. std::shared_ptr<Expression> condition;
  1028. std::shared_ptr<Expression> then_expr;
  1029. std::shared_ptr<Expression> else_expr;
  1030. public:
  1031. IfExpr(const Location & location, std::shared_ptr<Expression> && c, std::shared_ptr<Expression> && t, std::shared_ptr<Expression> && e)
  1032. : Expression(location), condition(std::move(c)), then_expr(std::move(t)), else_expr(std::move(e)) {}
  1033. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1034. if (!condition) throw std::runtime_error("IfExpr.condition is null");
  1035. if (!then_expr) throw std::runtime_error("IfExpr.then_expr is null");
  1036. if (condition->evaluate(context).to_bool()) {
  1037. return then_expr->evaluate(context);
  1038. }
  1039. if (else_expr) {
  1040. return else_expr->evaluate(context);
  1041. }
  1042. return nullptr;
  1043. }
  1044. };
  1045. class LiteralExpr : public Expression {
  1046. Value value;
  1047. public:
  1048. LiteralExpr(const Location & location, const Value& v)
  1049. : Expression(location), value(v) {}
  1050. Value do_evaluate(const std::shared_ptr<Context> &) const override { return value; }
  1051. };
  1052. class ArrayExpr : public Expression {
  1053. std::vector<std::shared_ptr<Expression>> elements;
  1054. public:
  1055. ArrayExpr(const Location & location, std::vector<std::shared_ptr<Expression>> && e)
  1056. : Expression(location), elements(std::move(e)) {}
  1057. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1058. auto result = Value::array();
  1059. for (const auto& e : elements) {
  1060. if (!e) throw std::runtime_error("Array element is null");
  1061. result.push_back(e->evaluate(context));
  1062. }
  1063. return result;
  1064. }
  1065. };
  1066. class DictExpr : public Expression {
  1067. std::vector<std::pair<std::shared_ptr<Expression>, std::shared_ptr<Expression>>> elements;
  1068. public:
  1069. DictExpr(const Location & location, std::vector<std::pair<std::shared_ptr<Expression>, std::shared_ptr<Expression>>> && e)
  1070. : Expression(location), elements(std::move(e)) {}
  1071. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1072. auto result = Value::object();
  1073. for (const auto& [key, value] : elements) {
  1074. if (!key) throw std::runtime_error("Dict key is null");
  1075. if (!value) throw std::runtime_error("Dict value is null");
  1076. result.set(key->evaluate(context), value->evaluate(context));
  1077. }
  1078. return result;
  1079. }
  1080. };
  1081. class SliceExpr : public Expression {
  1082. public:
  1083. std::shared_ptr<Expression> start, end;
  1084. SliceExpr(const Location & location, std::shared_ptr<Expression> && s, std::shared_ptr<Expression> && e)
  1085. : Expression(location), start(std::move(s)), end(std::move(e)) {}
  1086. Value do_evaluate(const std::shared_ptr<Context> &) const override {
  1087. throw std::runtime_error("SliceExpr not implemented");
  1088. }
  1089. };
  1090. class SubscriptExpr : public Expression {
  1091. std::shared_ptr<Expression> base;
  1092. std::shared_ptr<Expression> index;
  1093. public:
  1094. SubscriptExpr(const Location & location, std::shared_ptr<Expression> && b, std::shared_ptr<Expression> && i)
  1095. : Expression(location), base(std::move(b)), index(std::move(i)) {}
  1096. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1097. if (!base) throw std::runtime_error("SubscriptExpr.base is null");
  1098. if (!index) throw std::runtime_error("SubscriptExpr.index is null");
  1099. auto target_value = base->evaluate(context);
  1100. if (auto slice = dynamic_cast<SliceExpr*>(index.get())) {
  1101. auto start = slice->start ? slice->start->evaluate(context).get<int64_t>() : 0;
  1102. auto end = slice->end ? slice->end->evaluate(context).get<int64_t>() : (int64_t) target_value.size();
  1103. if (target_value.is_string()) {
  1104. std::string s = target_value.get<std::string>();
  1105. if (start < 0) start = s.size() + start;
  1106. if (end < 0) end = s.size() + end;
  1107. return s.substr(start, end - start);
  1108. } else if (target_value.is_array()) {
  1109. if (start < 0) start = target_value.size() + start;
  1110. if (end < 0) end = target_value.size() + end;
  1111. auto result = Value::array();
  1112. for (auto i = start; i < end; ++i) {
  1113. result.push_back(target_value.at(i));
  1114. }
  1115. return result;
  1116. } else {
  1117. throw std::runtime_error(target_value.is_null() ? "Cannot subscript null" : "Subscripting only supported on arrays and strings");
  1118. }
  1119. } else {
  1120. auto index_value = index->evaluate(context);
  1121. if (target_value.is_null()) {
  1122. if (auto t = dynamic_cast<VariableExpr*>(base.get())) {
  1123. throw std::runtime_error("'" + t->get_name() + "' is " + (context->contains(t->get_name()) ? "null" : "not defined"));
  1124. }
  1125. throw std::runtime_error("Trying to access property '" + index_value.dump() + "' on null!");
  1126. }
  1127. return target_value.get(index_value);
  1128. }
  1129. }
  1130. };
  1131. class UnaryOpExpr : public Expression {
  1132. public:
  1133. enum class Op { Plus, Minus, LogicalNot, Expansion, ExpansionDict };
  1134. std::shared_ptr<Expression> expr;
  1135. Op op;
  1136. UnaryOpExpr(const Location & location, std::shared_ptr<Expression> && e, Op o)
  1137. : Expression(location), expr(std::move(e)), op(o) {}
  1138. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1139. if (!expr) throw std::runtime_error("UnaryOpExpr.expr is null");
  1140. auto e = expr->evaluate(context);
  1141. switch (op) {
  1142. case Op::Plus: return e;
  1143. case Op::Minus: return -e;
  1144. case Op::LogicalNot: return !e.to_bool();
  1145. case Op::Expansion:
  1146. case Op::ExpansionDict:
  1147. throw std::runtime_error("Expansion operator is only supported in function calls and collections");
  1148. }
  1149. throw std::runtime_error("Unknown unary operator");
  1150. }
  1151. };
  1152. class BinaryOpExpr : public Expression {
  1153. public:
  1154. enum class Op { StrConcat, Add, Sub, Mul, MulMul, Div, DivDiv, Mod, Eq, Ne, Lt, Gt, Le, Ge, And, Or, In, NotIn, Is, IsNot };
  1155. private:
  1156. std::shared_ptr<Expression> left;
  1157. std::shared_ptr<Expression> right;
  1158. Op op;
  1159. public:
  1160. BinaryOpExpr(const Location & location, std::shared_ptr<Expression> && l, std::shared_ptr<Expression> && r, Op o)
  1161. : Expression(location), left(std::move(l)), right(std::move(r)), op(o) {}
  1162. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1163. if (!left) throw std::runtime_error("BinaryOpExpr.left is null");
  1164. if (!right) throw std::runtime_error("BinaryOpExpr.right is null");
  1165. auto l = left->evaluate(context);
  1166. auto do_eval = [&](const Value & l) -> Value {
  1167. if (op == Op::Is || op == Op::IsNot) {
  1168. auto t = dynamic_cast<VariableExpr*>(right.get());
  1169. if (!t) throw std::runtime_error("Right side of 'is' operator must be a variable");
  1170. auto eval = [&]() {
  1171. const auto & name = t->get_name();
  1172. if (name == "none") return l.is_null();
  1173. if (name == "boolean") return l.is_boolean();
  1174. if (name == "integer") return l.is_number_integer();
  1175. if (name == "float") return l.is_number_float();
  1176. if (name == "number") return l.is_number();
  1177. if (name == "string") return l.is_string();
  1178. if (name == "mapping") return l.is_object();
  1179. if (name == "iterable") return l.is_iterable();
  1180. if (name == "sequence") return l.is_array();
  1181. if (name == "defined") return !l.is_null();
  1182. throw std::runtime_error("Unknown type for 'is' operator: " + name);
  1183. };
  1184. auto value = eval();
  1185. return Value(op == Op::Is ? value : !value);
  1186. }
  1187. if (op == Op::And) {
  1188. if (!l.to_bool()) return Value(false);
  1189. return right->evaluate(context).to_bool();
  1190. } else if (op == Op::Or) {
  1191. if (l.to_bool()) return l;
  1192. return right->evaluate(context);
  1193. }
  1194. auto r = right->evaluate(context);
  1195. switch (op) {
  1196. case Op::StrConcat: return l.to_str() + r.to_str();
  1197. case Op::Add: return l + r;
  1198. case Op::Sub: return l - r;
  1199. case Op::Mul: return l * r;
  1200. case Op::Div: return l / r;
  1201. case Op::MulMul: return std::pow(l.get<double>(), r.get<double>());
  1202. case Op::DivDiv: return l.get<int64_t>() / r.get<int64_t>();
  1203. case Op::Mod: return l.get<int64_t>() % r.get<int64_t>();
  1204. case Op::Eq: return l == r;
  1205. case Op::Ne: return l != r;
  1206. case Op::Lt: return l < r;
  1207. case Op::Gt: return l > r;
  1208. case Op::Le: return l <= r;
  1209. case Op::Ge: return l >= r;
  1210. case Op::In: return (r.is_array() || r.is_object()) && r.contains(l);
  1211. case Op::NotIn: return !(r.is_array() && r.contains(l));
  1212. default: break;
  1213. }
  1214. throw std::runtime_error("Unknown binary operator");
  1215. };
  1216. if (l.is_callable()) {
  1217. return Value::callable([l, do_eval](const std::shared_ptr<Context> & context, ArgumentsValue & args) {
  1218. auto ll = l.call(context, args);
  1219. return do_eval(ll); //args[0].second);
  1220. });
  1221. } else {
  1222. return do_eval(l);
  1223. }
  1224. }
  1225. };
  1226. struct ArgumentsExpression {
  1227. std::vector<std::shared_ptr<Expression>> args;
  1228. std::vector<std::pair<std::string, std::shared_ptr<Expression>>> kwargs;
  1229. ArgumentsValue evaluate(const std::shared_ptr<Context> & context) const {
  1230. ArgumentsValue vargs;
  1231. for (const auto& arg : this->args) {
  1232. if (auto un_expr = std::dynamic_pointer_cast<UnaryOpExpr>(arg)) {
  1233. if (un_expr->op == UnaryOpExpr::Op::Expansion) {
  1234. auto array = un_expr->expr->evaluate(context);
  1235. if (!array.is_array()) {
  1236. throw std::runtime_error("Expansion operator only supported on arrays");
  1237. }
  1238. array.for_each([&](Value & value) {
  1239. vargs.args.push_back(value);
  1240. });
  1241. continue;
  1242. } else if (un_expr->op == UnaryOpExpr::Op::ExpansionDict) {
  1243. auto dict = un_expr->expr->evaluate(context);
  1244. if (!dict.is_object()) {
  1245. throw std::runtime_error("ExpansionDict operator only supported on objects");
  1246. }
  1247. dict.for_each([&](const Value & key) {
  1248. vargs.kwargs.push_back({key.get<std::string>(), dict.at(key)});
  1249. });
  1250. continue;
  1251. }
  1252. }
  1253. vargs.args.push_back(arg->evaluate(context));
  1254. }
  1255. for (const auto& [name, value] : this->kwargs) {
  1256. vargs.kwargs.push_back({name, value->evaluate(context)});
  1257. }
  1258. return vargs;
  1259. }
  1260. };
  1261. static std::string strip(const std::string & s) {
  1262. auto start = s.find_first_not_of(" \t\n\r");
  1263. if (start == std::string::npos) return "";
  1264. auto end = s.find_last_not_of(" \t\n\r");
  1265. return s.substr(start, end - start + 1);
  1266. }
  1267. static std::string capitalize(const std::string & s) {
  1268. if (s.empty()) return s;
  1269. auto result = s;
  1270. result[0] = std::toupper(result[0]);
  1271. return result;
  1272. }
  1273. static std::string html_escape(const std::string & s) {
  1274. std::string result;
  1275. result.reserve(s.size());
  1276. for (const auto & c : s) {
  1277. switch (c) {
  1278. case '&': result += "&amp;"; break;
  1279. case '<': result += "&lt;"; break;
  1280. case '>': result += "&gt;"; break;
  1281. case '"': result += "&#34;"; break;
  1282. case '\'': result += "&apos;"; break;
  1283. default: result += c; break;
  1284. }
  1285. }
  1286. return result;
  1287. }
  1288. class MethodCallExpr : public Expression {
  1289. std::shared_ptr<Expression> object;
  1290. std::shared_ptr<VariableExpr> method;
  1291. ArgumentsExpression args;
  1292. public:
  1293. MethodCallExpr(const Location & location, std::shared_ptr<Expression> && obj, std::shared_ptr<VariableExpr> && m, ArgumentsExpression && a)
  1294. : Expression(location), object(std::move(obj)), method(std::move(m)), args(std::move(a)) {}
  1295. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1296. if (!object) throw std::runtime_error("MethodCallExpr.object is null");
  1297. if (!method) throw std::runtime_error("MethodCallExpr.method is null");
  1298. auto obj = object->evaluate(context);
  1299. auto vargs = args.evaluate(context);
  1300. if (obj.is_null()) {
  1301. throw std::runtime_error("Trying to call method '" + method->get_name() + "' on null");
  1302. }
  1303. if (obj.is_array()) {
  1304. if (method->get_name() == "append") {
  1305. vargs.expectArgs("append method", {1, 1}, {0, 0});
  1306. obj.push_back(vargs.args[0]);
  1307. return Value();
  1308. } else if (method->get_name() == "pop") {
  1309. vargs.expectArgs("pop method", {0, 1}, {0, 0});
  1310. return obj.pop(vargs.args.empty() ? Value() : vargs.args[0]);
  1311. } else if (method->get_name() == "insert") {
  1312. vargs.expectArgs("insert method", {2, 2}, {0, 0});
  1313. auto index = vargs.args[0].get<int64_t>();
  1314. if (index < 0 || index > (int64_t) obj.size()) throw std::runtime_error("Index out of range for insert method");
  1315. obj.insert(index, vargs.args[1]);
  1316. return Value();
  1317. }
  1318. } else if (obj.is_object()) {
  1319. if (method->get_name() == "items") {
  1320. vargs.expectArgs("items method", {0, 0}, {0, 0});
  1321. auto result = Value::array();
  1322. for (const auto& key : obj.keys()) {
  1323. result.push_back(Value::array({key, obj.at(key)}));
  1324. }
  1325. return result;
  1326. } else if (method->get_name() == "pop") {
  1327. vargs.expectArgs("pop method", {1, 1}, {0, 0});
  1328. return obj.pop(vargs.args[0]);
  1329. } else if (method->get_name() == "get") {
  1330. vargs.expectArgs("get method", {1, 2}, {0, 0});
  1331. auto key = vargs.args[0];
  1332. if (vargs.args.size() == 1) {
  1333. return obj.contains(key) ? obj.at(key) : Value();
  1334. } else {
  1335. return obj.contains(key) ? obj.at(key) : vargs.args[1];
  1336. }
  1337. } else if (obj.contains(method->get_name())) {
  1338. auto callable = obj.at(method->get_name());
  1339. if (!callable.is_callable()) {
  1340. throw std::runtime_error("Property '" + method->get_name() + "' is not callable");
  1341. }
  1342. return callable.call(context, vargs);
  1343. }
  1344. } else if (obj.is_string()) {
  1345. auto str = obj.get<std::string>();
  1346. if (method->get_name() == "strip") {
  1347. vargs.expectArgs("strip method", {0, 0}, {0, 0});
  1348. return Value(strip(str));
  1349. } else if (method->get_name() == "capitalize") {
  1350. vargs.expectArgs("capitalize method", {0, 0}, {0, 0});
  1351. return Value(capitalize(str));
  1352. } else if (method->get_name() == "endswith") {
  1353. vargs.expectArgs("endswith method", {1, 1}, {0, 0});
  1354. auto suffix = vargs.args[0].get<std::string>();
  1355. return suffix.length() <= str.length() && std::equal(suffix.rbegin(), suffix.rend(), str.rbegin());
  1356. } else if (method->get_name() == "title") {
  1357. vargs.expectArgs("title method", {0, 0}, {0, 0});
  1358. auto res = str;
  1359. for (size_t i = 0, n = res.size(); i < n; ++i) {
  1360. if (i == 0 || std::isspace(res[i - 1])) res[i] = std::toupper(res[i]);
  1361. else res[i] = std::tolower(res[i]);
  1362. }
  1363. return res;
  1364. }
  1365. }
  1366. throw std::runtime_error("Unknown method: " + method->get_name());
  1367. }
  1368. };
  1369. class CallExpr : public Expression {
  1370. public:
  1371. std::shared_ptr<Expression> object;
  1372. ArgumentsExpression args;
  1373. CallExpr(const Location & location, std::shared_ptr<Expression> && obj, ArgumentsExpression && a)
  1374. : Expression(location), object(std::move(obj)), args(std::move(a)) {}
  1375. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1376. if (!object) throw std::runtime_error("CallExpr.object is null");
  1377. auto obj = object->evaluate(context);
  1378. if (!obj.is_callable()) {
  1379. throw std::runtime_error("Object is not callable: " + obj.dump(2));
  1380. }
  1381. auto vargs = args.evaluate(context);
  1382. return obj.call(context, vargs);
  1383. }
  1384. };
  1385. class FilterExpr : public Expression {
  1386. std::vector<std::shared_ptr<Expression>> parts;
  1387. public:
  1388. FilterExpr(const Location & location, std::vector<std::shared_ptr<Expression>> && p)
  1389. : Expression(location), parts(std::move(p)) {}
  1390. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1391. Value result;
  1392. bool first = true;
  1393. for (const auto& part : parts) {
  1394. if (!part) throw std::runtime_error("FilterExpr.part is null");
  1395. if (first) {
  1396. first = false;
  1397. result = part->evaluate(context);
  1398. } else {
  1399. if (auto ce = dynamic_cast<CallExpr*>(part.get())) {
  1400. auto target = ce->object->evaluate(context);
  1401. ArgumentsValue args = ce->args.evaluate(context);
  1402. args.args.insert(args.args.begin(), result);
  1403. result = target.call(context, args);
  1404. } else {
  1405. auto callable = part->evaluate(context);
  1406. ArgumentsValue args;
  1407. args.args.insert(args.args.begin(), result);
  1408. result = callable.call(context, args);
  1409. }
  1410. }
  1411. }
  1412. return result;
  1413. }
  1414. void prepend(std::shared_ptr<Expression> && e) {
  1415. parts.insert(parts.begin(), std::move(e));
  1416. }
  1417. };
  1418. class Parser {
  1419. private:
  1420. using CharIterator = std::string::const_iterator;
  1421. std::shared_ptr<std::string> template_str;
  1422. CharIterator start, end, it;
  1423. Options options;
  1424. Parser(const std::shared_ptr<std::string>& template_str, const Options & options) : template_str(template_str), options(options) {
  1425. if (!template_str) throw std::runtime_error("Template string is null");
  1426. start = it = this->template_str->begin();
  1427. end = this->template_str->end();
  1428. }
  1429. bool consumeSpaces(SpaceHandling space_handling = SpaceHandling::Strip) {
  1430. if (space_handling == SpaceHandling::Strip) {
  1431. while (it != end && std::isspace(*it)) ++it;
  1432. }
  1433. return true;
  1434. }
  1435. std::unique_ptr<std::string> parseString() {
  1436. auto doParse = [&](char quote) -> std::unique_ptr<std::string> {
  1437. if (it == end || *it != quote) return nullptr;
  1438. std::string result;
  1439. bool escape = false;
  1440. for (++it; it != end; ++it) {
  1441. if (escape) {
  1442. escape = false;
  1443. switch (*it) {
  1444. case 'n': result += '\n'; break;
  1445. case 'r': result += '\r'; break;
  1446. case 't': result += '\t'; break;
  1447. case 'b': result += '\b'; break;
  1448. case 'f': result += '\f'; break;
  1449. case '\\': result += '\\'; break;
  1450. default:
  1451. if (*it == quote) {
  1452. result += quote;
  1453. } else {
  1454. result += *it;
  1455. }
  1456. break;
  1457. }
  1458. } else if (*it == '\\') {
  1459. escape = true;
  1460. } else if (*it == quote) {
  1461. ++it;
  1462. return std::make_unique<std::string>(std::move(result));
  1463. } else {
  1464. result += *it;
  1465. }
  1466. }
  1467. return nullptr;
  1468. };
  1469. consumeSpaces();
  1470. if (it == end) return nullptr;
  1471. if (*it == '"') return doParse('"');
  1472. if (*it == '\'') return doParse('\'');
  1473. return nullptr;
  1474. }
  1475. json parseNumber(CharIterator& it, const CharIterator& end) {
  1476. auto before = it;
  1477. consumeSpaces();
  1478. auto start = it;
  1479. bool hasDecimal = false;
  1480. bool hasExponent = false;
  1481. if (it != end && (*it == '-' || *it == '+')) ++it;
  1482. while (it != end) {
  1483. if (std::isdigit(*it)) {
  1484. ++it;
  1485. } else if (*it == '.') {
  1486. if (hasDecimal) throw std::runtime_error("Multiple decimal points");
  1487. hasDecimal = true;
  1488. ++it;
  1489. } else if (it != start && (*it == 'e' || *it == 'E')) {
  1490. if (hasExponent) throw std::runtime_error("Multiple exponents");
  1491. hasExponent = true;
  1492. ++it;
  1493. } else {
  1494. break;
  1495. }
  1496. }
  1497. if (start == it) {
  1498. it = before;
  1499. return json(); // No valid characters found
  1500. }
  1501. std::string str(start, it);
  1502. try {
  1503. return json::parse(str);
  1504. } catch (json::parse_error& e) {
  1505. throw std::runtime_error("Failed to parse number: '" + str + "' (" + std::string(e.what()) + ")");
  1506. return json();
  1507. }
  1508. }
  1509. /** integer, float, bool, string */
  1510. std::shared_ptr<Value> parseConstant() {
  1511. auto start = it;
  1512. consumeSpaces();
  1513. if (it == end) return nullptr;
  1514. if (*it == '"' || *it == '\'') {
  1515. auto str = parseString();
  1516. if (str) return std::make_shared<Value>(*str);
  1517. }
  1518. static std::regex prim_tok(R"(true\b|True\b|false\b|False\b|None\b)");
  1519. auto token = consumeToken(prim_tok);
  1520. if (!token.empty()) {
  1521. if (token == "true" || token == "True") return std::make_shared<Value>(true);
  1522. if (token == "false" || token == "False") return std::make_shared<Value>(false);
  1523. if (token == "None") return std::make_shared<Value>(nullptr);
  1524. throw std::runtime_error("Unknown constant token: " + token);
  1525. }
  1526. auto number = parseNumber(it, end);
  1527. if (!number.is_null()) return std::make_shared<Value>(number);
  1528. it = start;
  1529. return nullptr;
  1530. }
  1531. class expression_parsing_error : public std::runtime_error {
  1532. const CharIterator it;
  1533. public:
  1534. expression_parsing_error(const std::string & message, const CharIterator & it)
  1535. : std::runtime_error(message), it(it) {}
  1536. size_t get_pos(const CharIterator & begin) const {
  1537. return std::distance(begin, it);
  1538. }
  1539. };
  1540. bool peekSymbols(const std::vector<std::string> & symbols) const {
  1541. for (const auto & symbol : symbols) {
  1542. if (std::distance(it, end) >= (int64_t) symbol.size() && std::string(it, it + symbol.size()) == symbol) {
  1543. return true;
  1544. }
  1545. }
  1546. return false;
  1547. }
  1548. std::vector<std::string> consumeTokenGroups(const std::regex & regex, SpaceHandling space_handling = SpaceHandling::Strip) {
  1549. auto start = it;
  1550. consumeSpaces(space_handling);
  1551. std::smatch match;
  1552. if (std::regex_search(it, end, match, regex) && match.position() == 0) {
  1553. it += match[0].length();
  1554. std::vector<std::string> ret;
  1555. for (size_t i = 0, n = match.size(); i < n; ++i) {
  1556. ret.push_back(match[i].str());
  1557. }
  1558. return ret;
  1559. }
  1560. it = start;
  1561. return {};
  1562. }
  1563. std::string consumeToken(const std::regex & regex, SpaceHandling space_handling = SpaceHandling::Strip) {
  1564. auto start = it;
  1565. consumeSpaces(space_handling);
  1566. std::smatch match;
  1567. if (std::regex_search(it, end, match, regex) && match.position() == 0) {
  1568. it += match[0].length();
  1569. return match[0].str();
  1570. }
  1571. it = start;
  1572. return "";
  1573. }
  1574. std::string consumeToken(const std::string & token, SpaceHandling space_handling = SpaceHandling::Strip) {
  1575. auto start = it;
  1576. consumeSpaces(space_handling);
  1577. if (std::distance(it, end) >= (int64_t) token.size() && std::string(it, it + token.size()) == token) {
  1578. it += token.size();
  1579. return token;
  1580. }
  1581. it = start;
  1582. return "";
  1583. }
  1584. std::shared_ptr<Expression> parseExpression(bool allow_if_expr = true) {
  1585. auto left = parseLogicalOr();
  1586. if (it == end) return left;
  1587. if (!allow_if_expr) return left;
  1588. static std::regex if_tok(R"(if\b)");
  1589. if (consumeToken(if_tok).empty()) {
  1590. return left;
  1591. }
  1592. auto location = get_location();
  1593. auto [condition, else_expr] = parseIfExpression();
  1594. return std::make_shared<IfExpr>(location, std::move(condition), std::move(left), std::move(else_expr));
  1595. }
  1596. Location get_location() const {
  1597. return {template_str, (size_t) std::distance(start, it)};
  1598. }
  1599. std::pair<std::shared_ptr<Expression>, std::shared_ptr<Expression>> parseIfExpression() {
  1600. auto condition = parseLogicalOr();
  1601. if (!condition) throw std::runtime_error("Expected condition expression");
  1602. static std::regex else_tok(R"(else\b)");
  1603. std::shared_ptr<Expression> else_expr;
  1604. if (!consumeToken(else_tok).empty()) {
  1605. else_expr = parseExpression();
  1606. if (!else_expr) throw std::runtime_error("Expected 'else' expression");
  1607. }
  1608. return std::pair(std::move(condition), std::move(else_expr));
  1609. }
  1610. std::shared_ptr<Expression> parseLogicalOr() {
  1611. auto left = parseLogicalAnd();
  1612. if (!left) throw std::runtime_error("Expected left side of 'logical or' expression");
  1613. static std::regex or_tok(R"(or\b)");
  1614. auto location = get_location();
  1615. while (!consumeToken(or_tok).empty()) {
  1616. auto right = parseLogicalAnd();
  1617. if (!right) throw std::runtime_error("Expected right side of 'or' expression");
  1618. left = std::make_shared<BinaryOpExpr>(location, std::move(left), std::move(right), BinaryOpExpr::Op::Or);
  1619. }
  1620. return left;
  1621. }
  1622. std::shared_ptr<Expression> parseLogicalNot() {
  1623. static std::regex not_tok(R"(not\b)");
  1624. auto location = get_location();
  1625. if (!consumeToken(not_tok).empty()) {
  1626. auto sub = parseLogicalNot();
  1627. if (!sub) throw std::runtime_error("Expected expression after 'not' keyword");
  1628. return std::make_shared<UnaryOpExpr>(location, std::move(sub), UnaryOpExpr::Op::LogicalNot);
  1629. }
  1630. return parseLogicalCompare();
  1631. }
  1632. std::shared_ptr<Expression> parseLogicalAnd() {
  1633. auto left = parseLogicalNot();
  1634. if (!left) throw std::runtime_error("Expected left side of 'logical and' expression");
  1635. static std::regex and_tok(R"(and\b)");
  1636. auto location = get_location();
  1637. while (!consumeToken(and_tok).empty()) {
  1638. auto right = parseLogicalNot();
  1639. if (!right) throw std::runtime_error("Expected right side of 'and' expression");
  1640. left = std::make_shared<BinaryOpExpr>(location, std::move(left), std::move(right), BinaryOpExpr::Op::And);
  1641. }
  1642. return left;
  1643. }
  1644. std::shared_ptr<Expression> parseLogicalCompare() {
  1645. auto left = parseStringConcat();
  1646. if (!left) throw std::runtime_error("Expected left side of 'logical compare' expression");
  1647. static std::regex compare_tok(R"(==|!=|<=?|>=?|in\b|is\b|not\s+in\b)");
  1648. static std::regex not_tok(R"(not\b)");
  1649. std::string op_str;
  1650. while (!(op_str = consumeToken(compare_tok)).empty()) {
  1651. auto location = get_location();
  1652. if (op_str == "is") {
  1653. auto negated = !consumeToken(not_tok).empty();
  1654. auto identifier = parseIdentifier();
  1655. if (!identifier) throw std::runtime_error("Expected identifier after 'is' keyword");
  1656. return std::make_shared<BinaryOpExpr>(
  1657. left->location,
  1658. std::move(left), std::move(identifier),
  1659. negated ? BinaryOpExpr::Op::IsNot : BinaryOpExpr::Op::Is);
  1660. }
  1661. auto right = parseStringConcat();
  1662. if (!right) throw std::runtime_error("Expected right side of 'logical compare' expression");
  1663. BinaryOpExpr::Op op;
  1664. if (op_str == "==") op = BinaryOpExpr::Op::Eq;
  1665. else if (op_str == "!=") op = BinaryOpExpr::Op::Ne;
  1666. else if (op_str == "<") op = BinaryOpExpr::Op::Lt;
  1667. else if (op_str == ">") op = BinaryOpExpr::Op::Gt;
  1668. else if (op_str == "<=") op = BinaryOpExpr::Op::Le;
  1669. else if (op_str == ">=") op = BinaryOpExpr::Op::Ge;
  1670. else if (op_str == "in") op = BinaryOpExpr::Op::In;
  1671. else if (op_str.substr(0, 3) == "not") op = BinaryOpExpr::Op::NotIn;
  1672. else throw std::runtime_error("Unknown comparison operator: " + op_str);
  1673. left = std::make_shared<BinaryOpExpr>(get_location(), std::move(left), std::move(right), op);
  1674. }
  1675. return left;
  1676. }
  1677. Expression::Parameters parseParameters() {
  1678. consumeSpaces();
  1679. if (consumeToken("(").empty()) throw std::runtime_error("Expected opening parenthesis in param list");
  1680. Expression::Parameters result;
  1681. while (it != end) {
  1682. if (!consumeToken(")").empty()) {
  1683. return result;
  1684. }
  1685. auto expr = parseExpression();
  1686. if (!expr) throw std::runtime_error("Expected expression in call args");
  1687. if (auto ident = dynamic_cast<VariableExpr*>(expr.get())) {
  1688. if (!consumeToken("=").empty()) {
  1689. auto value = parseExpression();
  1690. if (!value) throw std::runtime_error("Expected expression in for named arg");
  1691. result.emplace_back(ident->get_name(), std::move(value));
  1692. } else {
  1693. result.emplace_back(ident->get_name(), nullptr);
  1694. }
  1695. } else {
  1696. result.emplace_back(std::string(), std::move(expr));
  1697. }
  1698. if (consumeToken(",").empty()) {
  1699. if (consumeToken(")").empty()) {
  1700. throw std::runtime_error("Expected closing parenthesis in call args");
  1701. }
  1702. return result;
  1703. }
  1704. }
  1705. throw std::runtime_error("Expected closing parenthesis in call args");
  1706. }
  1707. ArgumentsExpression parseCallArgs() {
  1708. consumeSpaces();
  1709. if (consumeToken("(").empty()) throw std::runtime_error("Expected opening parenthesis in call args");
  1710. ArgumentsExpression result;
  1711. while (it != end) {
  1712. if (!consumeToken(")").empty()) {
  1713. return result;
  1714. }
  1715. auto expr = parseExpression();
  1716. if (!expr) throw std::runtime_error("Expected expression in call args");
  1717. if (auto ident = dynamic_cast<VariableExpr*>(expr.get())) {
  1718. if (!consumeToken("=").empty()) {
  1719. auto value = parseExpression();
  1720. if (!value) throw std::runtime_error("Expected expression in for named arg");
  1721. result.kwargs.emplace_back(ident->get_name(), std::move(value));
  1722. } else {
  1723. result.args.emplace_back(std::move(expr));
  1724. }
  1725. } else {
  1726. result.args.emplace_back(std::move(expr));
  1727. }
  1728. if (consumeToken(",").empty()) {
  1729. if (consumeToken(")").empty()) {
  1730. throw std::runtime_error("Expected closing parenthesis in call args");
  1731. }
  1732. return result;
  1733. }
  1734. }
  1735. throw std::runtime_error("Expected closing parenthesis in call args");
  1736. }
  1737. std::shared_ptr<VariableExpr> parseIdentifier() {
  1738. static std::regex ident_regex(R"((?!(?:not|is|and|or|del)\b)[a-zA-Z_]\w*)");
  1739. auto location = get_location();
  1740. auto ident = consumeToken(ident_regex);
  1741. if (ident.empty())
  1742. return nullptr;
  1743. return std::make_shared<VariableExpr>(location, ident);
  1744. }
  1745. std::shared_ptr<Expression> parseStringConcat() {
  1746. auto left = parseMathPow();
  1747. if (!left) throw std::runtime_error("Expected left side of 'string concat' expression");
  1748. static std::regex concat_tok(R"(~(?!\}))");
  1749. if (!consumeToken(concat_tok).empty()) {
  1750. auto right = parseLogicalAnd();
  1751. if (!right) throw std::runtime_error("Expected right side of 'string concat' expression");
  1752. left = std::make_shared<BinaryOpExpr>(get_location(), std::move(left), std::move(right), BinaryOpExpr::Op::StrConcat);
  1753. }
  1754. return left;
  1755. }
  1756. std::shared_ptr<Expression> parseMathPow() {
  1757. auto left = parseMathPlusMinus();
  1758. if (!left) throw std::runtime_error("Expected left side of 'math pow' expression");
  1759. while (!consumeToken("**").empty()) {
  1760. auto right = parseMathPlusMinus();
  1761. if (!right) throw std::runtime_error("Expected right side of 'math pow' expression");
  1762. left = std::make_shared<BinaryOpExpr>(get_location(), std::move(left), std::move(right), BinaryOpExpr::Op::MulMul);
  1763. }
  1764. return left;
  1765. }
  1766. std::shared_ptr<Expression> parseMathPlusMinus() {
  1767. static std::regex plus_minus_tok(R"(\+|-(?![}%#]\}))");
  1768. auto left = parseMathMulDiv();
  1769. if (!left) throw std::runtime_error("Expected left side of 'math plus/minus' expression");
  1770. std::string op_str;
  1771. while (!(op_str = consumeToken(plus_minus_tok)).empty()) {
  1772. auto right = parseMathMulDiv();
  1773. if (!right) throw std::runtime_error("Expected right side of 'math plus/minus' expression");
  1774. auto op = op_str == "+" ? BinaryOpExpr::Op::Add : BinaryOpExpr::Op::Sub;
  1775. left = std::make_shared<BinaryOpExpr>(get_location(), std::move(left), std::move(right), op);
  1776. }
  1777. return left;
  1778. }
  1779. std::shared_ptr<Expression> parseMathMulDiv() {
  1780. auto left = parseMathUnaryPlusMinus();
  1781. if (!left) throw std::runtime_error("Expected left side of 'math mul/div' expression");
  1782. static std::regex mul_div_tok(R"(\*\*?|//?|%(?!\}))");
  1783. std::string op_str;
  1784. while (!(op_str = consumeToken(mul_div_tok)).empty()) {
  1785. auto right = parseMathUnaryPlusMinus();
  1786. if (!right) throw std::runtime_error("Expected right side of 'math mul/div' expression");
  1787. auto op = op_str == "*" ? BinaryOpExpr::Op::Mul
  1788. : op_str == "**" ? BinaryOpExpr::Op::MulMul
  1789. : op_str == "/" ? BinaryOpExpr::Op::Div
  1790. : op_str == "//" ? BinaryOpExpr::Op::DivDiv
  1791. : BinaryOpExpr::Op::Mod;
  1792. left = std::make_shared<BinaryOpExpr>(get_location(), std::move(left), std::move(right), op);
  1793. }
  1794. if (!consumeToken("|").empty()) {
  1795. auto expr = parseMathMulDiv();
  1796. if (auto filter = dynamic_cast<FilterExpr*>(expr.get())) {
  1797. filter->prepend(std::move(left));
  1798. return expr;
  1799. } else {
  1800. std::vector<std::shared_ptr<Expression>> parts;
  1801. parts.emplace_back(std::move(left));
  1802. parts.emplace_back(std::move(expr));
  1803. return std::make_shared<FilterExpr>(get_location(), std::move(parts));
  1804. }
  1805. }
  1806. return left;
  1807. }
  1808. std::shared_ptr<Expression> call_func(const std::string & name, ArgumentsExpression && args) const {
  1809. return std::make_shared<CallExpr>(get_location(), std::make_shared<VariableExpr>(get_location(), name), std::move(args));
  1810. }
  1811. std::shared_ptr<Expression> parseMathUnaryPlusMinus() {
  1812. static std::regex unary_plus_minus_tok(R"(\+|-(?![}%#]\}))");
  1813. auto op_str = consumeToken(unary_plus_minus_tok);
  1814. auto expr = parseExpansion();
  1815. if (!expr) throw std::runtime_error("Expected expr of 'unary plus/minus/expansion' expression");
  1816. if (!op_str.empty()) {
  1817. auto op = op_str == "+" ? UnaryOpExpr::Op::Plus : UnaryOpExpr::Op::Minus;
  1818. return std::make_shared<UnaryOpExpr>(get_location(), std::move(expr), op);
  1819. }
  1820. return expr;
  1821. }
  1822. std::shared_ptr<Expression> parseExpansion() {
  1823. static std::regex expansion_tok(R"(\*\*?)");
  1824. auto op_str = consumeToken(expansion_tok);
  1825. auto expr = parseValueExpression();
  1826. if (op_str.empty()) return expr;
  1827. if (!expr) throw std::runtime_error("Expected expr of 'expansion' expression");
  1828. return std::make_shared<UnaryOpExpr>(get_location(), std::move(expr), op_str == "*" ? UnaryOpExpr::Op::Expansion : UnaryOpExpr::Op::ExpansionDict);
  1829. }
  1830. std::shared_ptr<Expression> parseValueExpression() {
  1831. auto parseValue = [&]() -> std::shared_ptr<Expression> {
  1832. auto location = get_location();
  1833. auto constant = parseConstant();
  1834. if (constant) return std::make_shared<LiteralExpr>(location, *constant);
  1835. static std::regex null_regex(R"(null\b)");
  1836. if (!consumeToken(null_regex).empty()) return std::make_shared<LiteralExpr>(location, Value());
  1837. auto identifier = parseIdentifier();
  1838. if (identifier) return identifier;
  1839. auto braced = parseBracedExpressionOrArray();
  1840. if (braced) return braced;
  1841. auto array = parseArray();
  1842. if (array) return array;
  1843. auto dictionary = parseDictionary();
  1844. if (dictionary) return dictionary;
  1845. throw std::runtime_error("Expected value expression");
  1846. };
  1847. auto value = parseValue();
  1848. while (it != end && consumeSpaces() && peekSymbols({ "[", "." })) {
  1849. if (!consumeToken("[").empty()) {
  1850. std::shared_ptr<Expression> index;
  1851. if (!consumeToken(":").empty()) {
  1852. auto slice_end = parseExpression();
  1853. index = std::make_shared<SliceExpr>(slice_end->location, nullptr, std::move(slice_end));
  1854. } else {
  1855. auto slice_start = parseExpression();
  1856. if (!consumeToken(":").empty()) {
  1857. consumeSpaces();
  1858. if (peekSymbols({ "]" })) {
  1859. index = std::make_shared<SliceExpr>(slice_start->location, std::move(slice_start), nullptr);
  1860. } else {
  1861. auto slice_end = parseExpression();
  1862. index = std::make_shared<SliceExpr>(slice_start->location, std::move(slice_start), std::move(slice_end));
  1863. }
  1864. } else {
  1865. index = std::move(slice_start);
  1866. }
  1867. }
  1868. if (!index) throw std::runtime_error("Empty index in subscript");
  1869. if (consumeToken("]").empty()) throw std::runtime_error("Expected closing bracket in subscript");
  1870. value = std::make_shared<SubscriptExpr>(value->location, std::move(value), std::move(index));
  1871. } else if (!consumeToken(".").empty()) {
  1872. auto identifier = parseIdentifier();
  1873. if (!identifier) throw std::runtime_error("Expected identifier in subscript");
  1874. consumeSpaces();
  1875. if (peekSymbols({ "(" })) {
  1876. auto callParams = parseCallArgs();
  1877. value = std::make_shared<MethodCallExpr>(identifier->location, std::move(value), std::move(identifier), std::move(callParams));
  1878. } else {
  1879. auto key = std::make_shared<LiteralExpr>(identifier->location, Value(identifier->get_name()));
  1880. value = std::make_shared<SubscriptExpr>(identifier->location, std::move(value), std::move(key));
  1881. }
  1882. }
  1883. consumeSpaces();
  1884. }
  1885. if (peekSymbols({ "(" })) {
  1886. auto location = get_location();
  1887. auto callParams = parseCallArgs();
  1888. value = std::make_shared<CallExpr>(location, std::move(value), std::move(callParams));
  1889. }
  1890. return value;
  1891. }
  1892. std::shared_ptr<Expression> parseBracedExpressionOrArray() {
  1893. if (consumeToken("(").empty()) return nullptr;
  1894. auto expr = parseExpression();
  1895. if (!expr) throw std::runtime_error("Expected expression in braced expression");
  1896. if (!consumeToken(")").empty()) {
  1897. return expr; // Drop the parentheses
  1898. }
  1899. std::vector<std::shared_ptr<Expression>> tuple;
  1900. tuple.emplace_back(std::move(expr));
  1901. while (it != end) {
  1902. if (consumeToken(",").empty()) throw std::runtime_error("Expected comma in tuple");
  1903. auto next = parseExpression();
  1904. if (!next) throw std::runtime_error("Expected expression in tuple");
  1905. tuple.push_back(std::move(next));
  1906. if (!consumeToken(")").empty()) {
  1907. return std::make_shared<ArrayExpr>(get_location(), std::move(tuple));
  1908. }
  1909. }
  1910. throw std::runtime_error("Expected closing parenthesis");
  1911. }
  1912. std::shared_ptr<Expression> parseArray() {
  1913. if (consumeToken("[").empty()) return nullptr;
  1914. std::vector<std::shared_ptr<Expression>> elements;
  1915. if (!consumeToken("]").empty()) {
  1916. return std::make_shared<ArrayExpr>(get_location(), std::move(elements));
  1917. }
  1918. auto first_expr = parseExpression();
  1919. if (!first_expr) throw std::runtime_error("Expected first expression in array");
  1920. elements.push_back(std::move(first_expr));
  1921. while (it != end) {
  1922. if (!consumeToken(",").empty()) {
  1923. auto expr = parseExpression();
  1924. if (!expr) throw std::runtime_error("Expected expression in array");
  1925. elements.push_back(std::move(expr));
  1926. } else if (!consumeToken("]").empty()) {
  1927. return std::make_shared<ArrayExpr>(get_location(), std::move(elements));
  1928. } else {
  1929. throw std::runtime_error("Expected comma or closing bracket in array");
  1930. }
  1931. }
  1932. throw std::runtime_error("Expected closing bracket");
  1933. }
  1934. std::shared_ptr<Expression> parseDictionary() {
  1935. if (consumeToken("{").empty()) return nullptr;
  1936. std::vector<std::pair<std::shared_ptr<Expression>, std::shared_ptr<Expression>>> elements;
  1937. if (!consumeToken("}").empty()) {
  1938. return std::make_shared<DictExpr>(get_location(), std::move(elements));
  1939. }
  1940. auto parseKeyValuePair = [&]() {
  1941. auto key = parseExpression();
  1942. if (!key) throw std::runtime_error("Expected key in dictionary");
  1943. if (consumeToken(":").empty()) throw std::runtime_error("Expected colon betweek key & value in dictionary");
  1944. auto value = parseExpression();
  1945. if (!value) throw std::runtime_error("Expected value in dictionary");
  1946. elements.emplace_back(std::pair(std::move(key), std::move(value)));
  1947. };
  1948. parseKeyValuePair();
  1949. while (it != end) {
  1950. if (!consumeToken(",").empty()) {
  1951. parseKeyValuePair();
  1952. } else if (!consumeToken("}").empty()) {
  1953. return std::make_shared<DictExpr>(get_location(), std::move(elements));
  1954. } else {
  1955. throw std::runtime_error("Expected comma or closing brace in dictionary");
  1956. }
  1957. }
  1958. throw std::runtime_error("Expected closing brace");
  1959. }
  1960. SpaceHandling parsePreSpace(const std::string& s) const {
  1961. if (s == "-")
  1962. return SpaceHandling::Strip;
  1963. return SpaceHandling::Keep;
  1964. }
  1965. SpaceHandling parsePostSpace(const std::string& s) const {
  1966. if (s == "-") return SpaceHandling::Strip;
  1967. return SpaceHandling::Keep;
  1968. }
  1969. using TemplateTokenVector = std::vector<std::unique_ptr<TemplateToken>>;
  1970. using TemplateTokenIterator = TemplateTokenVector::const_iterator;
  1971. std::vector<std::string> parseVarNames() {
  1972. static std::regex varnames_regex(R"(((?:\w+)(?:\s*,\s*(?:\w+))*)\s*)");
  1973. std::vector<std::string> group;
  1974. if ((group = consumeTokenGroups(varnames_regex)).empty()) throw std::runtime_error("Expected variable names");
  1975. std::vector<std::string> varnames;
  1976. std::istringstream iss(group[1]);
  1977. std::string varname;
  1978. while (std::getline(iss, varname, ',')) {
  1979. varnames.push_back(strip(varname));
  1980. }
  1981. return varnames;
  1982. }
  1983. std::runtime_error unexpected(const TemplateToken & token) const {
  1984. return std::runtime_error("Unexpected " + TemplateToken::typeToString(token.type)
  1985. + error_location_suffix(*template_str, token.location.pos));
  1986. }
  1987. std::runtime_error unterminated(const TemplateToken & token) const {
  1988. return std::runtime_error("Unterminated " + TemplateToken::typeToString(token.type)
  1989. + error_location_suffix(*template_str, token.location.pos));
  1990. }
  1991. TemplateTokenVector tokenize() {
  1992. static std::regex comment_tok(R"(\{#([-~]?)([\s\S]*?)([-~]?)#\})");
  1993. static std::regex expr_open_regex(R"(\{\{([-~])?)");
  1994. static std::regex block_open_regex(R"(^\{%([-~])?\s*)");
  1995. static std::regex block_keyword_tok(R"((if|else|elif|endif|for|endfor|generation|endgeneration|set|endset|block|endblock|macro|endmacro|filter|endfilter|break|continue)\b)");
  1996. static std::regex non_text_open_regex(R"(\{\{|\{%|\{#)");
  1997. static std::regex expr_close_regex(R"(\s*([-~])?\}\})");
  1998. static std::regex block_close_regex(R"(\s*([-~])?%\})");
  1999. TemplateTokenVector tokens;
  2000. std::vector<std::string> group;
  2001. std::string text;
  2002. std::smatch match;
  2003. try {
  2004. while (it != end) {
  2005. auto location = get_location();
  2006. if (!(group = consumeTokenGroups(comment_tok, SpaceHandling::Keep)).empty()) {
  2007. auto pre_space = parsePreSpace(group[1]);
  2008. auto content = group[2];
  2009. auto post_space = parsePostSpace(group[3]);
  2010. tokens.push_back(std::make_unique<CommentTemplateToken>(location, pre_space, post_space, content));
  2011. } else if (!(group = consumeTokenGroups(expr_open_regex, SpaceHandling::Keep)).empty()) {
  2012. auto pre_space = parsePreSpace(group[1]);
  2013. auto expr = parseExpression();
  2014. if ((group = consumeTokenGroups(expr_close_regex)).empty()) {
  2015. throw std::runtime_error("Expected closing expression tag");
  2016. }
  2017. auto post_space = parsePostSpace(group[1]);
  2018. tokens.push_back(std::make_unique<ExpressionTemplateToken>(location, pre_space, post_space, std::move(expr)));
  2019. } else if (!(group = consumeTokenGroups(block_open_regex, SpaceHandling::Keep)).empty()) {
  2020. auto pre_space = parsePreSpace(group[1]);
  2021. std::string keyword;
  2022. auto parseBlockClose = [&]() -> SpaceHandling {
  2023. if ((group = consumeTokenGroups(block_close_regex)).empty()) throw std::runtime_error("Expected closing block tag");
  2024. return parsePostSpace(group[1]);
  2025. };
  2026. if ((keyword = consumeToken(block_keyword_tok)).empty()) throw std::runtime_error("Expected block keyword");
  2027. if (keyword == "if") {
  2028. auto condition = parseExpression();
  2029. if (!condition) throw std::runtime_error("Expected condition in if block");
  2030. auto post_space = parseBlockClose();
  2031. tokens.push_back(std::make_unique<IfTemplateToken>(location, pre_space, post_space, std::move(condition)));
  2032. } else if (keyword == "elif") {
  2033. auto condition = parseExpression();
  2034. if (!condition) throw std::runtime_error("Expected condition in elif block");
  2035. auto post_space = parseBlockClose();
  2036. tokens.push_back(std::make_unique<ElifTemplateToken>(location, pre_space, post_space, std::move(condition)));
  2037. } else if (keyword == "else") {
  2038. auto post_space = parseBlockClose();
  2039. tokens.push_back(std::make_unique<ElseTemplateToken>(location, pre_space, post_space));
  2040. } else if (keyword == "endif") {
  2041. auto post_space = parseBlockClose();
  2042. tokens.push_back(std::make_unique<EndIfTemplateToken>(location, pre_space, post_space));
  2043. } else if (keyword == "for") {
  2044. static std::regex recursive_tok(R"(recursive\b)");
  2045. static std::regex if_tok(R"(if\b)");
  2046. auto varnames = parseVarNames();
  2047. static std::regex in_tok(R"(in\b)");
  2048. if (consumeToken(in_tok).empty()) throw std::runtime_error("Expected 'in' keyword in for block");
  2049. auto iterable = parseExpression(/* allow_if_expr = */ false);
  2050. if (!iterable) throw std::runtime_error("Expected iterable in for block");
  2051. std::shared_ptr<Expression> condition;
  2052. if (!consumeToken(if_tok).empty()) {
  2053. condition = parseExpression();
  2054. }
  2055. auto recursive = !consumeToken(recursive_tok).empty();
  2056. auto post_space = parseBlockClose();
  2057. tokens.push_back(std::make_unique<ForTemplateToken>(location, pre_space, post_space, std::move(varnames), std::move(iterable), std::move(condition), recursive));
  2058. } else if (keyword == "endfor") {
  2059. auto post_space = parseBlockClose();
  2060. tokens.push_back(std::make_unique<EndForTemplateToken>(location, pre_space, post_space));
  2061. } else if (keyword == "generation") {
  2062. auto post_space = parseBlockClose();
  2063. tokens.push_back(std::make_unique<GenerationTemplateToken>(location, pre_space, post_space));
  2064. } else if (keyword == "endgeneration") {
  2065. auto post_space = parseBlockClose();
  2066. tokens.push_back(std::make_unique<EndGenerationTemplateToken>(location, pre_space, post_space));
  2067. } else if (keyword == "set") {
  2068. static std::regex namespaced_var_regex(R"((\w+)\s*\.\s*(\w+))");
  2069. std::string ns;
  2070. std::vector<std::string> var_names;
  2071. std::shared_ptr<Expression> value;
  2072. if (!(group = consumeTokenGroups(namespaced_var_regex)).empty()) {
  2073. ns = group[1];
  2074. var_names.push_back(group[2]);
  2075. if (consumeToken("=").empty()) throw std::runtime_error("Expected equals sign in set block");
  2076. value = parseExpression();
  2077. if (!value) throw std::runtime_error("Expected value in set block");
  2078. } else {
  2079. var_names = parseVarNames();
  2080. if (!consumeToken("=").empty()) {
  2081. value = parseExpression();
  2082. if (!value) throw std::runtime_error("Expected value in set block");
  2083. }
  2084. }
  2085. auto post_space = parseBlockClose();
  2086. tokens.push_back(std::make_unique<SetTemplateToken>(location, pre_space, post_space, ns, var_names, std::move(value)));
  2087. } else if (keyword == "endset") {
  2088. auto post_space = parseBlockClose();
  2089. tokens.push_back(std::make_unique<EndSetTemplateToken>(location, pre_space, post_space));
  2090. } else if (keyword == "macro") {
  2091. auto macroname = parseIdentifier();
  2092. if (!macroname) throw std::runtime_error("Expected macro name in macro block");
  2093. auto params = parseParameters();
  2094. auto post_space = parseBlockClose();
  2095. tokens.push_back(std::make_unique<MacroTemplateToken>(location, pre_space, post_space, std::move(macroname), std::move(params)));
  2096. } else if (keyword == "endmacro") {
  2097. auto post_space = parseBlockClose();
  2098. tokens.push_back(std::make_unique<EndMacroTemplateToken>(location, pre_space, post_space));
  2099. } else if (keyword == "filter") {
  2100. auto filter = parseExpression();
  2101. if (!filter) throw std::runtime_error("Expected expression in filter block");
  2102. auto post_space = parseBlockClose();
  2103. tokens.push_back(std::make_unique<FilterTemplateToken>(location, pre_space, post_space, std::move(filter)));
  2104. } else if (keyword == "endfilter") {
  2105. auto post_space = parseBlockClose();
  2106. tokens.push_back(std::make_unique<EndFilterTemplateToken>(location, pre_space, post_space));
  2107. } else if (keyword == "break" || keyword == "continue") {
  2108. auto post_space = parseBlockClose();
  2109. tokens.push_back(std::make_unique<LoopControlTemplateToken>(location, pre_space, post_space, keyword == "break" ? LoopControlType::Break : LoopControlType::Continue));
  2110. } else {
  2111. throw std::runtime_error("Unexpected block: " + keyword);
  2112. }
  2113. } else if (std::regex_search(it, end, match, non_text_open_regex)) {
  2114. if (!match.position()) {
  2115. if (match[0] != "{#")
  2116. throw std::runtime_error("Internal error: Expected a comment");
  2117. throw std::runtime_error("Missing end of comment tag");
  2118. }
  2119. auto text_end = it + match.position();
  2120. text = std::string(it, text_end);
  2121. it = text_end;
  2122. tokens.push_back(std::make_unique<TextTemplateToken>(location, SpaceHandling::Keep, SpaceHandling::Keep, text));
  2123. } else {
  2124. text = std::string(it, end);
  2125. it = end;
  2126. tokens.push_back(std::make_unique<TextTemplateToken>(location, SpaceHandling::Keep, SpaceHandling::Keep, text));
  2127. }
  2128. }
  2129. return tokens;
  2130. } catch (const std::exception & e) {
  2131. throw std::runtime_error(e.what() + error_location_suffix(*template_str, std::distance(start, it)));
  2132. }
  2133. }
  2134. std::shared_ptr<TemplateNode> parseTemplate(
  2135. const TemplateTokenIterator & begin,
  2136. TemplateTokenIterator & it,
  2137. const TemplateTokenIterator & end,
  2138. bool fully = false) const {
  2139. std::vector<std::shared_ptr<TemplateNode>> children;
  2140. while (it != end) {
  2141. const auto start = it;
  2142. const auto & token = *(it++);
  2143. if (auto if_token = dynamic_cast<IfTemplateToken*>(token.get())) {
  2144. std::vector<std::pair<std::shared_ptr<Expression>, std::shared_ptr<TemplateNode>>> cascade;
  2145. cascade.emplace_back(std::move(if_token->condition), parseTemplate(begin, it, end));
  2146. while (it != end && (*it)->type == TemplateToken::Type::Elif) {
  2147. auto elif_token = dynamic_cast<ElifTemplateToken*>((*(it++)).get());
  2148. cascade.emplace_back(std::move(elif_token->condition), parseTemplate(begin, it, end));
  2149. }
  2150. if (it != end && (*it)->type == TemplateToken::Type::Else) {
  2151. cascade.emplace_back(nullptr, parseTemplate(begin, ++it, end));
  2152. }
  2153. if (it == end || (*(it++))->type != TemplateToken::Type::EndIf) {
  2154. throw unterminated(**start);
  2155. }
  2156. children.emplace_back(std::make_shared<IfNode>(token->location, std::move(cascade)));
  2157. } else if (auto for_token = dynamic_cast<ForTemplateToken*>(token.get())) {
  2158. auto body = parseTemplate(begin, it, end);
  2159. auto else_body = std::shared_ptr<TemplateNode>();
  2160. if (it != end && (*it)->type == TemplateToken::Type::Else) {
  2161. else_body = parseTemplate(begin, ++it, end);
  2162. }
  2163. if (it == end || (*(it++))->type != TemplateToken::Type::EndFor) {
  2164. throw unterminated(**start);
  2165. }
  2166. 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)));
  2167. } else if (dynamic_cast<GenerationTemplateToken*>(token.get())) {
  2168. auto body = parseTemplate(begin, it, end);
  2169. if (it == end || (*(it++))->type != TemplateToken::Type::EndGeneration) {
  2170. throw unterminated(**start);
  2171. }
  2172. // Treat as a no-op, as our scope is templates for inference, not training (`{% generation %}` wraps generated tokens for masking).
  2173. children.emplace_back(std::move(body));
  2174. } else if (auto text_token = dynamic_cast<TextTemplateToken*>(token.get())) {
  2175. SpaceHandling pre_space = (it - 1) != begin ? (*(it - 2))->post_space : SpaceHandling::Keep;
  2176. SpaceHandling post_space = it != end ? (*it)->pre_space : SpaceHandling::Keep;
  2177. auto text = text_token->text;
  2178. if (post_space == SpaceHandling::Strip) {
  2179. static std::regex trailing_space_regex(R"(\s+$)");
  2180. text = std::regex_replace(text, trailing_space_regex, "");
  2181. } else if (options.lstrip_blocks && it != end) {
  2182. auto i = text.size();
  2183. while (i > 0 && (text[i - 1] == ' ' || text[i - 1] == '\t')) i--;
  2184. if ((i == 0 && (it - 1) == begin) || (i > 0 && text[i - 1] == '\n')) {
  2185. text.resize(i);
  2186. }
  2187. }
  2188. if (pre_space == SpaceHandling::Strip) {
  2189. static std::regex leading_space_regex(R"(^\s+)");
  2190. text = std::regex_replace(text, leading_space_regex, "");
  2191. } else if (options.trim_blocks && (it - 1) != begin && !dynamic_cast<ExpressionTemplateToken*>((*(it - 2)).get())) {
  2192. if (text.length() > 0 && text[0] == '\n') {
  2193. text.erase(0, 1);
  2194. }
  2195. }
  2196. if (it == end && !options.keep_trailing_newline) {
  2197. auto i = text.size();
  2198. if (i > 0 && text[i - 1] == '\n') {
  2199. i--;
  2200. if (i > 0 && text[i - 1] == '\r') i--;
  2201. text.resize(i);
  2202. }
  2203. }
  2204. children.emplace_back(std::make_shared<TextNode>(token->location, text));
  2205. } else if (auto expr_token = dynamic_cast<ExpressionTemplateToken*>(token.get())) {
  2206. children.emplace_back(std::make_shared<ExpressionNode>(token->location, std::move(expr_token->expr)));
  2207. } else if (auto set_token = dynamic_cast<SetTemplateToken*>(token.get())) {
  2208. if (set_token->value) {
  2209. children.emplace_back(std::make_shared<SetNode>(token->location, set_token->ns, set_token->var_names, std::move(set_token->value)));
  2210. } else {
  2211. auto value_template = parseTemplate(begin, it, end);
  2212. if (it == end || (*(it++))->type != TemplateToken::Type::EndSet) {
  2213. throw unterminated(**start);
  2214. }
  2215. if (!set_token->ns.empty()) throw std::runtime_error("Namespaced set not supported in set with template value");
  2216. if (set_token->var_names.size() != 1) throw std::runtime_error("Structural assignment not supported in set with template value");
  2217. auto & name = set_token->var_names[0];
  2218. children.emplace_back(std::make_shared<SetTemplateNode>(token->location, name, std::move(value_template)));
  2219. }
  2220. } else if (auto macro_token = dynamic_cast<MacroTemplateToken*>(token.get())) {
  2221. auto body = parseTemplate(begin, it, end);
  2222. if (it == end || (*(it++))->type != TemplateToken::Type::EndMacro) {
  2223. throw unterminated(**start);
  2224. }
  2225. children.emplace_back(std::make_shared<MacroNode>(token->location, std::move(macro_token->name), std::move(macro_token->params), std::move(body)));
  2226. } else if (auto filter_token = dynamic_cast<FilterTemplateToken*>(token.get())) {
  2227. auto body = parseTemplate(begin, it, end);
  2228. if (it == end || (*(it++))->type != TemplateToken::Type::EndFilter) {
  2229. throw unterminated(**start);
  2230. }
  2231. children.emplace_back(std::make_shared<FilterNode>(token->location, std::move(filter_token->filter), std::move(body)));
  2232. } else if (dynamic_cast<CommentTemplateToken*>(token.get())) {
  2233. // Ignore comments
  2234. } else if (auto ctrl_token = dynamic_cast<LoopControlTemplateToken*>(token.get())) {
  2235. children.emplace_back(std::make_shared<LoopControlNode>(token->location, ctrl_token->control_type));
  2236. } else if (dynamic_cast<EndForTemplateToken*>(token.get())
  2237. || dynamic_cast<EndSetTemplateToken*>(token.get())
  2238. || dynamic_cast<EndMacroTemplateToken*>(token.get())
  2239. || dynamic_cast<EndFilterTemplateToken*>(token.get())
  2240. || dynamic_cast<EndIfTemplateToken*>(token.get())
  2241. || dynamic_cast<ElseTemplateToken*>(token.get())
  2242. || dynamic_cast<EndGenerationTemplateToken*>(token.get())
  2243. || dynamic_cast<ElifTemplateToken*>(token.get())) {
  2244. it--; // unconsume the token
  2245. break; // exit the loop
  2246. } else {
  2247. throw unexpected(**(it-1));
  2248. }
  2249. }
  2250. if (fully && it != end) {
  2251. throw unexpected(**it);
  2252. }
  2253. if (children.empty()) {
  2254. return std::make_shared<TextNode>(Location { template_str, 0 }, std::string());
  2255. } else if (children.size() == 1) {
  2256. return std::move(children[0]);
  2257. } else {
  2258. return std::make_shared<SequenceNode>(children[0]->location(), std::move(children));
  2259. }
  2260. }
  2261. public:
  2262. static std::shared_ptr<TemplateNode> parse(const std::string& template_str, const Options & options) {
  2263. Parser parser(std::make_shared<std::string>(normalize_newlines(template_str)), options);
  2264. auto tokens = parser.tokenize();
  2265. TemplateTokenIterator begin = tokens.begin();
  2266. auto it = begin;
  2267. TemplateTokenIterator end = tokens.end();
  2268. return parser.parseTemplate(begin, it, end, /* full= */ true);
  2269. }
  2270. };
  2271. 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) {
  2272. std::map<std::string, size_t> named_positions;
  2273. for (size_t i = 0, n = params.size(); i < n; i++) named_positions[params[i]] = i;
  2274. return Value::callable([=](const std::shared_ptr<Context> & context, ArgumentsValue & args) -> Value {
  2275. auto args_obj = Value::object();
  2276. std::vector<bool> provided_args(params.size());
  2277. for (size_t i = 0, n = args.args.size(); i < n; i++) {
  2278. auto & arg = args.args[i];
  2279. if (i < params.size()) {
  2280. args_obj.set(params[i], arg);
  2281. provided_args[i] = true;
  2282. } else {
  2283. throw std::runtime_error("Too many positional params for " + fn_name);
  2284. }
  2285. }
  2286. for (auto & [name, value] : args.kwargs) {
  2287. auto named_pos_it = named_positions.find(name);
  2288. if (named_pos_it == named_positions.end()) {
  2289. throw std::runtime_error("Unknown argument " + name + " for function " + fn_name);
  2290. }
  2291. provided_args[named_pos_it->second] = true;
  2292. args_obj.set(name, value);
  2293. }
  2294. return fn(context, args_obj);
  2295. });
  2296. }
  2297. inline std::shared_ptr<Context> Context::builtins() {
  2298. auto globals = Value::object();
  2299. globals.set("raise_exception", simple_function("raise_exception", { "message" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2300. throw std::runtime_error(args.at("message").get<std::string>());
  2301. }));
  2302. globals.set("tojson", simple_function("tojson", { "value", "indent" }, [](const std::shared_ptr<Context> &, Value & args) {
  2303. return Value(args.at("value").dump(args.get<int64_t>("indent", -1), /* tojson= */ true));
  2304. }));
  2305. globals.set("items", simple_function("items", { "object" }, [](const std::shared_ptr<Context> &, Value & args) {
  2306. auto items = Value::array();
  2307. if (args.contains("object")) {
  2308. auto & obj = args.at("object");
  2309. if (obj.is_string()) {
  2310. auto json_obj = json::parse(obj.get<std::string>());
  2311. for (const auto & kv : json_obj.items()) {
  2312. items.push_back(Value::array({kv.key(), kv.value()}));
  2313. }
  2314. } else if (!obj.is_null()) {
  2315. for (auto & key : obj.keys()) {
  2316. items.push_back(Value::array({key, obj.at(key)}));
  2317. }
  2318. }
  2319. }
  2320. return items;
  2321. }));
  2322. globals.set("last", simple_function("last", { "items" }, [](const std::shared_ptr<Context> &, Value & args) {
  2323. auto items = args.at("items");
  2324. if (!items.is_array()) throw std::runtime_error("object is not a list");
  2325. if (items.size() == 0) return Value();
  2326. return items.at(items.size() - 1);
  2327. }));
  2328. globals.set("trim", simple_function("trim", { "text" }, [](const std::shared_ptr<Context> &, Value & args) {
  2329. auto & text = args.at("text");
  2330. return text.is_null() ? text : Value(strip(text.get<std::string>()));
  2331. }));
  2332. globals.set("lower", simple_function("lower", { "text" }, [](const std::shared_ptr<Context> &, Value & args) {
  2333. auto text = args.at("text");
  2334. if (text.is_null()) return text;
  2335. std::string res;
  2336. auto str = text.get<std::string>();
  2337. std::transform(str.begin(), str.end(), std::back_inserter(res), ::tolower);
  2338. return Value(res);
  2339. }));
  2340. globals.set("default", Value::callable([=](const std::shared_ptr<Context> &, ArgumentsValue & args) {
  2341. args.expectArgs("default", {2, 3}, {0, 1});
  2342. auto & value = args.args[0];
  2343. auto & default_value = args.args[1];
  2344. bool boolean = false;
  2345. if (args.args.size() == 3) {
  2346. boolean = args.args[2].get<bool>();
  2347. } else {
  2348. Value bv = args.get_named("boolean");
  2349. if (!bv.is_null()) {
  2350. boolean = bv.get<bool>();
  2351. }
  2352. }
  2353. return boolean ? (value.to_bool() ? value : default_value) : value.is_null() ? default_value : value;
  2354. }));
  2355. auto escape = simple_function("escape", { "text" }, [](const std::shared_ptr<Context> &, Value & args) {
  2356. return Value(html_escape(args.at("text").get<std::string>()));
  2357. });
  2358. globals.set("e", escape);
  2359. globals.set("escape", escape);
  2360. globals.set("joiner", simple_function("joiner", { "sep" }, [](const std::shared_ptr<Context> &, Value & args) {
  2361. auto sep = args.get<std::string>("sep", "");
  2362. auto first = std::make_shared<bool>(true);
  2363. return simple_function("", {}, [sep, first](const std::shared_ptr<Context> &, const Value &) -> Value {
  2364. if (*first) {
  2365. *first = false;
  2366. return "";
  2367. }
  2368. return sep;
  2369. });
  2370. return Value(html_escape(args.at("text").get<std::string>()));
  2371. }));
  2372. globals.set("count", simple_function("count", { "items" }, [](const std::shared_ptr<Context> &, Value & args) {
  2373. return Value((int64_t) args.at("items").size());
  2374. }));
  2375. globals.set("dictsort", simple_function("dictsort", { "value" }, [](const std::shared_ptr<Context> &, Value & args) {
  2376. if (args.size() != 1) throw std::runtime_error("dictsort expects exactly 1 argument (TODO: fix implementation)");
  2377. auto & value = args.at("value");
  2378. auto keys = value.keys();
  2379. std::sort(keys.begin(), keys.end());
  2380. auto res = Value::array();
  2381. for (auto & key : keys) {
  2382. res.push_back(Value::array({key, value.at(key)}));
  2383. }
  2384. return res;
  2385. }));
  2386. globals.set("join", simple_function("join", { "items", "d" }, [](const std::shared_ptr<Context> &, Value & args) {
  2387. auto do_join = [](Value & items, const std::string & sep) {
  2388. if (!items.is_array()) throw std::runtime_error("object is not iterable: " + items.dump());
  2389. std::ostringstream oss;
  2390. auto first = true;
  2391. for (size_t i = 0, n = items.size(); i < n; ++i) {
  2392. if (first) first = false;
  2393. else oss << sep;
  2394. oss << items.at(i).to_str();
  2395. }
  2396. return Value(oss.str());
  2397. };
  2398. auto sep = args.get<std::string>("d", "");
  2399. if (args.contains("items")) {
  2400. auto & items = args.at("items");
  2401. return do_join(items, sep);
  2402. } else {
  2403. return simple_function("", {"items"}, [sep, do_join](const std::shared_ptr<Context> &, Value & args) {
  2404. auto & items = args.at("items");
  2405. if (!items.to_bool() || !items.is_array()) throw std::runtime_error("join expects an array for items, got: " + items.dump());
  2406. return do_join(items, sep);
  2407. });
  2408. }
  2409. }));
  2410. globals.set("namespace", Value::callable([=](const std::shared_ptr<Context> &, ArgumentsValue & args) {
  2411. auto ns = Value::object();
  2412. args.expectArgs("namespace", {0, 0}, {0, (std::numeric_limits<size_t>::max)()});
  2413. for (auto & [name, value] : args.kwargs) {
  2414. ns.set(name, value);
  2415. }
  2416. return ns;
  2417. }));
  2418. auto equalto = simple_function("equalto", { "expected", "actual" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2419. return args.at("actual") == args.at("expected");
  2420. });
  2421. globals.set("equalto", equalto);
  2422. globals.set("==", equalto);
  2423. globals.set("length", simple_function("length", { "items" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2424. auto & items = args.at("items");
  2425. return (int64_t) items.size();
  2426. }));
  2427. globals.set("safe", simple_function("safe", { "value" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2428. return args.at("value").to_str();
  2429. }));
  2430. globals.set("string", simple_function("string", { "value" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2431. return args.at("value").to_str();
  2432. }));
  2433. globals.set("int", simple_function("int", { "value" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2434. return args.at("value").to_int();
  2435. }));
  2436. globals.set("list", simple_function("list", { "items" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2437. auto & items = args.at("items");
  2438. if (!items.is_array()) throw std::runtime_error("object is not iterable");
  2439. return items;
  2440. }));
  2441. globals.set("unique", simple_function("unique", { "items" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2442. auto & items = args.at("items");
  2443. if (!items.is_array()) throw std::runtime_error("object is not iterable");
  2444. std::unordered_set<Value> seen;
  2445. auto result = Value::array();
  2446. for (size_t i = 0, n = items.size(); i < n; i++) {
  2447. auto pair = seen.insert(items.at(i));
  2448. if (pair.second) {
  2449. result.push_back(items.at(i));
  2450. }
  2451. }
  2452. return result;
  2453. }));
  2454. auto make_filter = [](const Value & filter, Value & extra_args) -> Value {
  2455. return simple_function("", { "value" }, [=](const std::shared_ptr<Context> & context, Value & args) {
  2456. auto & value = args.at("value");
  2457. ArgumentsValue actual_args;
  2458. actual_args.args.emplace_back(value);
  2459. for (size_t i = 0, n = extra_args.size(); i < n; i++) {
  2460. actual_args.args.emplace_back(extra_args.at(i));
  2461. }
  2462. return filter.call(context, actual_args);
  2463. });
  2464. };
  2465. auto select_or_reject = [make_filter](bool is_select) {
  2466. return Value::callable([=](const std::shared_ptr<Context> & context, ArgumentsValue & args) {
  2467. args.expectArgs(is_select ? "select" : "reject", {2, (std::numeric_limits<size_t>::max)()}, {0, 0});
  2468. auto & items = args.args[0];
  2469. if (items.is_null())
  2470. return Value::array();
  2471. if (!items.is_array()) throw std::runtime_error("object is not iterable: " + items.dump());
  2472. auto filter_fn = context->get(args.args[1]);
  2473. if (filter_fn.is_null()) throw std::runtime_error("Undefined filter: " + args.args[1].dump());
  2474. auto filter_args = Value::array();
  2475. for (size_t i = 2, n = args.args.size(); i < n; i++) {
  2476. filter_args.push_back(args.args[i]);
  2477. }
  2478. auto filter = make_filter(filter_fn, filter_args);
  2479. auto res = Value::array();
  2480. for (size_t i = 0, n = items.size(); i < n; i++) {
  2481. auto & item = items.at(i);
  2482. ArgumentsValue filter_args;
  2483. filter_args.args.emplace_back(item);
  2484. auto pred_res = filter.call(context, filter_args);
  2485. if (pred_res.to_bool() == (is_select ? true : false)) {
  2486. res.push_back(item);
  2487. }
  2488. }
  2489. return res;
  2490. });
  2491. };
  2492. globals.set("select", select_or_reject(/* is_select= */ true));
  2493. globals.set("reject", select_or_reject(/* is_select= */ false));
  2494. globals.set("map", Value::callable([=](const std::shared_ptr<Context> & context, ArgumentsValue & args) {
  2495. auto res = Value::array();
  2496. if (args.args.size() == 1 &&
  2497. ((args.has_named("attribute") && args.kwargs.size() == 1) || (args.has_named("default") && args.kwargs.size() == 2))) {
  2498. auto & items = args.args[0];
  2499. auto attr_name = args.get_named("attribute");
  2500. auto default_value = args.get_named("default");
  2501. for (size_t i = 0, n = items.size(); i < n; i++) {
  2502. auto & item = items.at(i);
  2503. auto attr = item.get(attr_name);
  2504. res.push_back(attr.is_null() ? default_value : attr);
  2505. }
  2506. } else if (args.kwargs.empty() && args.args.size() >= 2) {
  2507. auto fn = context->get(args.args[1]);
  2508. if (fn.is_null()) throw std::runtime_error("Undefined filter: " + args.args[1].dump());
  2509. ArgumentsValue filter_args { {Value()}, {} };
  2510. for (size_t i = 2, n = args.args.size(); i < n; i++) {
  2511. filter_args.args.emplace_back(args.args[i]);
  2512. }
  2513. for (size_t i = 0, n = args.args[0].size(); i < n; i++) {
  2514. auto & item = args.args[0].at(i);
  2515. filter_args.args[0] = item;
  2516. res.push_back(fn.call(context, filter_args));
  2517. }
  2518. } else {
  2519. throw std::runtime_error("Invalid or unsupported arguments for map");
  2520. }
  2521. return res;
  2522. }));
  2523. globals.set("indent", simple_function("indent", { "text", "indent", "first" }, [](const std::shared_ptr<Context> &, Value & args) {
  2524. auto text = args.at("text").get<std::string>();
  2525. auto first = args.get<bool>("first", false);
  2526. std::string out;
  2527. std::string indent(args.get<int64_t>("indent", 0), ' ');
  2528. std::istringstream iss(text);
  2529. std::string line;
  2530. auto is_first = true;
  2531. while (std::getline(iss, line, '\n')) {
  2532. auto needs_indent = !is_first || first;
  2533. if (is_first) is_first = false;
  2534. else out += "\n";
  2535. if (needs_indent) out += indent;
  2536. out += line;
  2537. }
  2538. if (!text.empty() && text.back() == '\n') out += "\n";
  2539. return out;
  2540. }));
  2541. auto select_or_reject_attr = [](bool is_select) {
  2542. return Value::callable([=](const std::shared_ptr<Context> & context, ArgumentsValue & args) {
  2543. args.expectArgs(is_select ? "selectattr" : "rejectattr", {2, (std::numeric_limits<size_t>::max)()}, {0, 0});
  2544. auto & items = args.args[0];
  2545. if (items.is_null())
  2546. return Value::array();
  2547. if (!items.is_array()) throw std::runtime_error("object is not iterable: " + items.dump());
  2548. auto attr_name = args.args[1].get<std::string>();
  2549. bool has_test = false;
  2550. Value test_fn;
  2551. ArgumentsValue test_args {{Value()}, {}};
  2552. if (args.args.size() >= 3) {
  2553. has_test = true;
  2554. test_fn = context->get(args.args[2]);
  2555. if (test_fn.is_null()) throw std::runtime_error("Undefined test: " + args.args[2].dump());
  2556. for (size_t i = 3, n = args.args.size(); i < n; i++) {
  2557. test_args.args.emplace_back(args.args[i]);
  2558. }
  2559. test_args.kwargs = args.kwargs;
  2560. }
  2561. auto res = Value::array();
  2562. for (size_t i = 0, n = items.size(); i < n; i++) {
  2563. auto & item = items.at(i);
  2564. auto attr = item.get(attr_name);
  2565. if (has_test) {
  2566. test_args.args[0] = attr;
  2567. if (test_fn.call(context, test_args).to_bool() == (is_select ? true : false)) {
  2568. res.push_back(item);
  2569. }
  2570. } else {
  2571. res.push_back(attr);
  2572. }
  2573. }
  2574. return res;
  2575. });
  2576. };
  2577. globals.set("selectattr", select_or_reject_attr(/* is_select= */ true));
  2578. globals.set("rejectattr", select_or_reject_attr(/* is_select= */ false));
  2579. globals.set("range", Value::callable([=](const std::shared_ptr<Context> &, ArgumentsValue & args) {
  2580. std::vector<int64_t> startEndStep(3);
  2581. std::vector<bool> param_set(3);
  2582. if (args.args.size() == 1) {
  2583. startEndStep[1] = args.args[0].get<int64_t>();
  2584. param_set[1] = true;
  2585. } else {
  2586. for (size_t i = 0; i < args.args.size(); i++) {
  2587. auto & arg = args.args[i];
  2588. auto v = arg.get<int64_t>();
  2589. startEndStep[i] = v;
  2590. param_set[i] = true;
  2591. }
  2592. }
  2593. for (auto & [name, value] : args.kwargs) {
  2594. size_t i;
  2595. if (name == "start") i = 0;
  2596. else if (name == "end") i = 1;
  2597. else if (name == "step") i = 2;
  2598. else throw std::runtime_error("Unknown argument " + name + " for function range");
  2599. if (param_set[i]) {
  2600. throw std::runtime_error("Duplicate argument " + name + " for function range");
  2601. }
  2602. startEndStep[i] = value.get<int64_t>();
  2603. param_set[i] = true;
  2604. }
  2605. if (!param_set[1]) {
  2606. throw std::runtime_error("Missing required argument 'end' for function range");
  2607. }
  2608. int64_t start = param_set[0] ? startEndStep[0] : 0;
  2609. int64_t end = startEndStep[1];
  2610. int64_t step = param_set[2] ? startEndStep[2] : 1;
  2611. auto res = Value::array();
  2612. if (step > 0) {
  2613. for (int64_t i = start; i < end; i += step) {
  2614. res.push_back(Value(i));
  2615. }
  2616. } else {
  2617. for (int64_t i = start; i > end; i += step) {
  2618. res.push_back(Value(i));
  2619. }
  2620. }
  2621. return res;
  2622. }));
  2623. return std::make_shared<Context>(std::move(globals));
  2624. }
  2625. inline std::shared_ptr<Context> Context::make(Value && values, const std::shared_ptr<Context> & parent) {
  2626. return std::make_shared<Context>(values.is_null() ? Value::object() : std::move(values), parent);
  2627. }
  2628. } // namespace minja