minja.hpp 118 KB

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