minja.hpp 123 KB

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