minja.hpp 122 KB

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