minja.hpp 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974
  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. case Op::NotIn: return !(r.is_array() && r.contains(l));
  1241. default: break;
  1242. }
  1243. throw std::runtime_error("Unknown binary operator");
  1244. };
  1245. if (l.is_callable()) {
  1246. return Value::callable([l, do_eval](const std::shared_ptr<Context> & context, ArgumentsValue & args) {
  1247. auto ll = l.call(context, args);
  1248. return do_eval(ll); //args[0].second);
  1249. });
  1250. } else {
  1251. return do_eval(l);
  1252. }
  1253. }
  1254. };
  1255. struct ArgumentsExpression {
  1256. std::vector<std::shared_ptr<Expression>> args;
  1257. std::vector<std::pair<std::string, std::shared_ptr<Expression>>> kwargs;
  1258. ArgumentsValue evaluate(const std::shared_ptr<Context> & context) const {
  1259. ArgumentsValue vargs;
  1260. for (const auto& arg : this->args) {
  1261. if (auto un_expr = std::dynamic_pointer_cast<UnaryOpExpr>(arg)) {
  1262. if (un_expr->op == UnaryOpExpr::Op::Expansion) {
  1263. auto array = un_expr->expr->evaluate(context);
  1264. if (!array.is_array()) {
  1265. throw std::runtime_error("Expansion operator only supported on arrays");
  1266. }
  1267. array.for_each([&](Value & value) {
  1268. vargs.args.push_back(value);
  1269. });
  1270. continue;
  1271. } else if (un_expr->op == UnaryOpExpr::Op::ExpansionDict) {
  1272. auto dict = un_expr->expr->evaluate(context);
  1273. if (!dict.is_object()) {
  1274. throw std::runtime_error("ExpansionDict operator only supported on objects");
  1275. }
  1276. dict.for_each([&](const Value & key) {
  1277. vargs.kwargs.push_back({key.get<std::string>(), dict.at(key)});
  1278. });
  1279. continue;
  1280. }
  1281. }
  1282. vargs.args.push_back(arg->evaluate(context));
  1283. }
  1284. for (const auto& [name, value] : this->kwargs) {
  1285. vargs.kwargs.push_back({name, value->evaluate(context)});
  1286. }
  1287. return vargs;
  1288. }
  1289. };
  1290. static std::string strip(const std::string & s, const std::string & chars = "", bool left = true, bool right = true) {
  1291. auto charset = chars.empty() ? " \t\n\r" : chars;
  1292. auto start = left ? s.find_first_not_of(charset) : 0;
  1293. if (start == std::string::npos) return "";
  1294. auto end = right ? s.find_last_not_of(charset) : s.size() - 1;
  1295. return s.substr(start, end - start + 1);
  1296. }
  1297. static std::vector<std::string> split(const std::string & s, const std::string & sep) {
  1298. std::vector<std::string> result;
  1299. size_t start = 0;
  1300. size_t end = s.find(sep);
  1301. while (end != std::string::npos) {
  1302. result.push_back(s.substr(start, end - start));
  1303. start = end + sep.length();
  1304. end = s.find(sep, start);
  1305. }
  1306. result.push_back(s.substr(start));
  1307. return result;
  1308. }
  1309. static std::string capitalize(const std::string & s) {
  1310. if (s.empty()) return s;
  1311. auto result = s;
  1312. result[0] = std::toupper(result[0]);
  1313. return result;
  1314. }
  1315. static std::string html_escape(const std::string & s) {
  1316. std::string result;
  1317. result.reserve(s.size());
  1318. for (const auto & c : s) {
  1319. switch (c) {
  1320. case '&': result += "&amp;"; break;
  1321. case '<': result += "&lt;"; break;
  1322. case '>': result += "&gt;"; break;
  1323. case '"': result += "&#34;"; break;
  1324. case '\'': result += "&apos;"; break;
  1325. default: result += c; break;
  1326. }
  1327. }
  1328. return result;
  1329. }
  1330. class MethodCallExpr : public Expression {
  1331. std::shared_ptr<Expression> object;
  1332. std::shared_ptr<VariableExpr> method;
  1333. ArgumentsExpression args;
  1334. public:
  1335. MethodCallExpr(const Location & loc, std::shared_ptr<Expression> && obj, std::shared_ptr<VariableExpr> && m, ArgumentsExpression && a)
  1336. : Expression(loc), object(std::move(obj)), method(std::move(m)), args(std::move(a)) {}
  1337. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1338. if (!object) throw std::runtime_error("MethodCallExpr.object is null");
  1339. if (!method) throw std::runtime_error("MethodCallExpr.method is null");
  1340. auto obj = object->evaluate(context);
  1341. auto vargs = args.evaluate(context);
  1342. if (obj.is_null()) {
  1343. throw std::runtime_error("Trying to call method '" + method->get_name() + "' on null");
  1344. }
  1345. if (obj.is_array()) {
  1346. if (method->get_name() == "append") {
  1347. vargs.expectArgs("append method", {1, 1}, {0, 0});
  1348. obj.push_back(vargs.args[0]);
  1349. return Value();
  1350. } else if (method->get_name() == "pop") {
  1351. vargs.expectArgs("pop method", {0, 1}, {0, 0});
  1352. return obj.pop(vargs.args.empty() ? Value() : vargs.args[0]);
  1353. } else if (method->get_name() == "insert") {
  1354. vargs.expectArgs("insert method", {2, 2}, {0, 0});
  1355. auto index = vargs.args[0].get<int64_t>();
  1356. if (index < 0 || index > (int64_t) obj.size()) throw std::runtime_error("Index out of range for insert method");
  1357. obj.insert(index, vargs.args[1]);
  1358. return Value();
  1359. }
  1360. } else if (obj.is_object()) {
  1361. if (method->get_name() == "items") {
  1362. vargs.expectArgs("items method", {0, 0}, {0, 0});
  1363. auto result = Value::array();
  1364. for (const auto& key : obj.keys()) {
  1365. result.push_back(Value::array({key, obj.at(key)}));
  1366. }
  1367. return result;
  1368. } else if (method->get_name() == "pop") {
  1369. vargs.expectArgs("pop method", {1, 1}, {0, 0});
  1370. return obj.pop(vargs.args[0]);
  1371. } else if (method->get_name() == "get") {
  1372. vargs.expectArgs("get method", {1, 2}, {0, 0});
  1373. auto key = vargs.args[0];
  1374. if (vargs.args.size() == 1) {
  1375. return obj.contains(key) ? obj.at(key) : Value();
  1376. } else {
  1377. return obj.contains(key) ? obj.at(key) : vargs.args[1];
  1378. }
  1379. } else if (obj.contains(method->get_name())) {
  1380. auto callable = obj.at(method->get_name());
  1381. if (!callable.is_callable()) {
  1382. throw std::runtime_error("Property '" + method->get_name() + "' is not callable");
  1383. }
  1384. return callable.call(context, vargs);
  1385. }
  1386. } else if (obj.is_string()) {
  1387. auto str = obj.get<std::string>();
  1388. if (method->get_name() == "strip") {
  1389. vargs.expectArgs("strip method", {0, 1}, {0, 0});
  1390. auto chars = vargs.args.empty() ? "" : vargs.args[0].get<std::string>();
  1391. return Value(strip(str, chars));
  1392. } else if (method->get_name() == "lstrip") {
  1393. vargs.expectArgs("lstrip method", {0, 1}, {0, 0});
  1394. auto chars = vargs.args.empty() ? "" : vargs.args[0].get<std::string>();
  1395. return Value(strip(str, chars, /* left= */ true, /* right= */ false));
  1396. } else if (method->get_name() == "rstrip") {
  1397. vargs.expectArgs("rstrip method", {0, 1}, {0, 0});
  1398. auto chars = vargs.args.empty() ? "" : vargs.args[0].get<std::string>();
  1399. return Value(strip(str, chars, /* left= */ false, /* right= */ true));
  1400. } else if (method->get_name() == "split") {
  1401. vargs.expectArgs("split method", {1, 1}, {0, 0});
  1402. auto sep = vargs.args[0].get<std::string>();
  1403. auto parts = split(str, sep);
  1404. Value result = Value::array();
  1405. for (const auto& part : parts) {
  1406. result.push_back(Value(part));
  1407. }
  1408. return result;
  1409. } else if (method->get_name() == "capitalize") {
  1410. vargs.expectArgs("capitalize method", {0, 0}, {0, 0});
  1411. return Value(capitalize(str));
  1412. } else if (method->get_name() == "endswith") {
  1413. vargs.expectArgs("endswith method", {1, 1}, {0, 0});
  1414. auto suffix = vargs.args[0].get<std::string>();
  1415. return suffix.length() <= str.length() && std::equal(suffix.rbegin(), suffix.rend(), str.rbegin());
  1416. } else if (method->get_name() == "startswith") {
  1417. vargs.expectArgs("startswith method", {1, 1}, {0, 0});
  1418. auto prefix = vargs.args[0].get<std::string>();
  1419. return prefix.length() <= str.length() && std::equal(prefix.begin(), prefix.end(), str.begin());
  1420. } else if (method->get_name() == "title") {
  1421. vargs.expectArgs("title method", {0, 0}, {0, 0});
  1422. auto res = str;
  1423. for (size_t i = 0, n = res.size(); i < n; ++i) {
  1424. if (i == 0 || std::isspace(res[i - 1])) res[i] = std::toupper(res[i]);
  1425. else res[i] = std::tolower(res[i]);
  1426. }
  1427. return res;
  1428. }
  1429. }
  1430. throw std::runtime_error("Unknown method: " + method->get_name());
  1431. }
  1432. };
  1433. class CallExpr : public Expression {
  1434. public:
  1435. std::shared_ptr<Expression> object;
  1436. ArgumentsExpression args;
  1437. CallExpr(const Location & loc, std::shared_ptr<Expression> && obj, ArgumentsExpression && a)
  1438. : Expression(loc), object(std::move(obj)), args(std::move(a)) {}
  1439. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1440. if (!object) throw std::runtime_error("CallExpr.object is null");
  1441. auto obj = object->evaluate(context);
  1442. if (!obj.is_callable()) {
  1443. throw std::runtime_error("Object is not callable: " + obj.dump(2));
  1444. }
  1445. auto vargs = args.evaluate(context);
  1446. return obj.call(context, vargs);
  1447. }
  1448. };
  1449. class FilterExpr : public Expression {
  1450. std::vector<std::shared_ptr<Expression>> parts;
  1451. public:
  1452. FilterExpr(const Location & loc, std::vector<std::shared_ptr<Expression>> && p)
  1453. : Expression(loc), parts(std::move(p)) {}
  1454. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1455. Value result;
  1456. bool first = true;
  1457. for (const auto& part : parts) {
  1458. if (!part) throw std::runtime_error("FilterExpr.part is null");
  1459. if (first) {
  1460. first = false;
  1461. result = part->evaluate(context);
  1462. } else {
  1463. if (auto ce = dynamic_cast<CallExpr*>(part.get())) {
  1464. auto target = ce->object->evaluate(context);
  1465. ArgumentsValue args = ce->args.evaluate(context);
  1466. args.args.insert(args.args.begin(), result);
  1467. result = target.call(context, args);
  1468. } else {
  1469. auto callable = part->evaluate(context);
  1470. ArgumentsValue args;
  1471. args.args.insert(args.args.begin(), result);
  1472. result = callable.call(context, args);
  1473. }
  1474. }
  1475. }
  1476. return result;
  1477. }
  1478. void prepend(std::shared_ptr<Expression> && e) {
  1479. parts.insert(parts.begin(), std::move(e));
  1480. }
  1481. };
  1482. class Parser {
  1483. private:
  1484. using CharIterator = std::string::const_iterator;
  1485. std::shared_ptr<std::string> template_str;
  1486. CharIterator start, end, it;
  1487. Options options;
  1488. Parser(const std::shared_ptr<std::string>& template_str, const Options & options) : template_str(template_str), options(options) {
  1489. if (!template_str) throw std::runtime_error("Template string is null");
  1490. start = it = this->template_str->begin();
  1491. end = this->template_str->end();
  1492. }
  1493. bool consumeSpaces(SpaceHandling space_handling = SpaceHandling::Strip) {
  1494. if (space_handling == SpaceHandling::Strip) {
  1495. while (it != end && std::isspace(*it)) ++it;
  1496. }
  1497. return true;
  1498. }
  1499. std::unique_ptr<std::string> parseString() {
  1500. auto doParse = [&](char quote) -> std::unique_ptr<std::string> {
  1501. if (it == end || *it != quote) return nullptr;
  1502. std::string result;
  1503. bool escape = false;
  1504. for (++it; it != end; ++it) {
  1505. if (escape) {
  1506. escape = false;
  1507. switch (*it) {
  1508. case 'n': result += '\n'; break;
  1509. case 'r': result += '\r'; break;
  1510. case 't': result += '\t'; break;
  1511. case 'b': result += '\b'; break;
  1512. case 'f': result += '\f'; break;
  1513. case '\\': result += '\\'; break;
  1514. default:
  1515. if (*it == quote) {
  1516. result += quote;
  1517. } else {
  1518. result += *it;
  1519. }
  1520. break;
  1521. }
  1522. } else if (*it == '\\') {
  1523. escape = true;
  1524. } else if (*it == quote) {
  1525. ++it;
  1526. return std::make_unique<std::string>(std::move(result));
  1527. } else {
  1528. result += *it;
  1529. }
  1530. }
  1531. return nullptr;
  1532. };
  1533. consumeSpaces();
  1534. if (it == end) return nullptr;
  1535. if (*it == '"') return doParse('"');
  1536. if (*it == '\'') return doParse('\'');
  1537. return nullptr;
  1538. }
  1539. json parseNumber(CharIterator& it, const CharIterator& end) {
  1540. auto before = it;
  1541. consumeSpaces();
  1542. auto start = it;
  1543. bool hasDecimal = false;
  1544. bool hasExponent = false;
  1545. if (it != end && (*it == '-' || *it == '+')) ++it;
  1546. while (it != end) {
  1547. if (std::isdigit(*it)) {
  1548. ++it;
  1549. } else if (*it == '.') {
  1550. if (hasDecimal) throw std::runtime_error("Multiple decimal points");
  1551. hasDecimal = true;
  1552. ++it;
  1553. } else if (it != start && (*it == 'e' || *it == 'E')) {
  1554. if (hasExponent) throw std::runtime_error("Multiple exponents");
  1555. hasExponent = true;
  1556. ++it;
  1557. } else {
  1558. break;
  1559. }
  1560. }
  1561. if (start == it) {
  1562. it = before;
  1563. return json(); // No valid characters found
  1564. }
  1565. std::string str(start, it);
  1566. try {
  1567. return json::parse(str);
  1568. } catch (json::parse_error& e) {
  1569. throw std::runtime_error("Failed to parse number: '" + str + "' (" + std::string(e.what()) + ")");
  1570. return json();
  1571. }
  1572. }
  1573. /** integer, float, bool, string */
  1574. std::shared_ptr<Value> parseConstant() {
  1575. auto start = it;
  1576. consumeSpaces();
  1577. if (it == end) return nullptr;
  1578. if (*it == '"' || *it == '\'') {
  1579. auto str = parseString();
  1580. if (str) return std::make_shared<Value>(*str);
  1581. }
  1582. static std::regex prim_tok(R"(true\b|True\b|false\b|False\b|None\b)");
  1583. auto token = consumeToken(prim_tok);
  1584. if (!token.empty()) {
  1585. if (token == "true" || token == "True") return std::make_shared<Value>(true);
  1586. if (token == "false" || token == "False") return std::make_shared<Value>(false);
  1587. if (token == "None") return std::make_shared<Value>(nullptr);
  1588. throw std::runtime_error("Unknown constant token: " + token);
  1589. }
  1590. auto number = parseNumber(it, end);
  1591. if (!number.is_null()) return std::make_shared<Value>(number);
  1592. it = start;
  1593. return nullptr;
  1594. }
  1595. class expression_parsing_error : public std::runtime_error {
  1596. const CharIterator it;
  1597. public:
  1598. expression_parsing_error(const std::string & message, const CharIterator & it)
  1599. : std::runtime_error(message), it(it) {}
  1600. size_t get_pos(const CharIterator & begin) const {
  1601. return std::distance(begin, it);
  1602. }
  1603. };
  1604. bool peekSymbols(const std::vector<std::string> & symbols) const {
  1605. for (const auto & symbol : symbols) {
  1606. if (std::distance(it, end) >= (int64_t) symbol.size() && std::string(it, it + symbol.size()) == symbol) {
  1607. return true;
  1608. }
  1609. }
  1610. return false;
  1611. }
  1612. std::vector<std::string> consumeTokenGroups(const std::regex & regex, SpaceHandling space_handling = SpaceHandling::Strip) {
  1613. auto start = it;
  1614. consumeSpaces(space_handling);
  1615. std::smatch match;
  1616. if (std::regex_search(it, end, match, regex) && match.position() == 0) {
  1617. it += match[0].length();
  1618. std::vector<std::string> ret;
  1619. for (size_t i = 0, n = match.size(); i < n; ++i) {
  1620. ret.push_back(match[i].str());
  1621. }
  1622. return ret;
  1623. }
  1624. it = start;
  1625. return {};
  1626. }
  1627. std::string consumeToken(const std::regex & regex, SpaceHandling space_handling = SpaceHandling::Strip) {
  1628. auto start = it;
  1629. consumeSpaces(space_handling);
  1630. std::smatch match;
  1631. if (std::regex_search(it, end, match, regex) && match.position() == 0) {
  1632. it += match[0].length();
  1633. return match[0].str();
  1634. }
  1635. it = start;
  1636. return "";
  1637. }
  1638. std::string consumeToken(const std::string & token, SpaceHandling space_handling = SpaceHandling::Strip) {
  1639. auto start = it;
  1640. consumeSpaces(space_handling);
  1641. if (std::distance(it, end) >= (int64_t) token.size() && std::string(it, it + token.size()) == token) {
  1642. it += token.size();
  1643. return token;
  1644. }
  1645. it = start;
  1646. return "";
  1647. }
  1648. std::shared_ptr<Expression> parseExpression(bool allow_if_expr = true) {
  1649. auto left = parseLogicalOr();
  1650. if (it == end) return left;
  1651. if (!allow_if_expr) return left;
  1652. static std::regex if_tok(R"(if\b)");
  1653. if (consumeToken(if_tok).empty()) {
  1654. return left;
  1655. }
  1656. auto location = get_location();
  1657. auto [condition, else_expr] = parseIfExpression();
  1658. return std::make_shared<IfExpr>(location, std::move(condition), std::move(left), std::move(else_expr));
  1659. }
  1660. Location get_location() const {
  1661. return {template_str, (size_t) std::distance(start, it)};
  1662. }
  1663. std::pair<std::shared_ptr<Expression>, std::shared_ptr<Expression>> parseIfExpression() {
  1664. auto condition = parseLogicalOr();
  1665. if (!condition) throw std::runtime_error("Expected condition expression");
  1666. static std::regex else_tok(R"(else\b)");
  1667. std::shared_ptr<Expression> else_expr;
  1668. if (!consumeToken(else_tok).empty()) {
  1669. else_expr = parseExpression();
  1670. if (!else_expr) throw std::runtime_error("Expected 'else' expression");
  1671. }
  1672. return std::pair(std::move(condition), std::move(else_expr));
  1673. }
  1674. std::shared_ptr<Expression> parseLogicalOr() {
  1675. auto left = parseLogicalAnd();
  1676. if (!left) throw std::runtime_error("Expected left side of 'logical or' expression");
  1677. static std::regex or_tok(R"(or\b)");
  1678. auto location = get_location();
  1679. while (!consumeToken(or_tok).empty()) {
  1680. auto right = parseLogicalAnd();
  1681. if (!right) throw std::runtime_error("Expected right side of 'or' expression");
  1682. left = std::make_shared<BinaryOpExpr>(location, std::move(left), std::move(right), BinaryOpExpr::Op::Or);
  1683. }
  1684. return left;
  1685. }
  1686. std::shared_ptr<Expression> parseLogicalNot() {
  1687. static std::regex not_tok(R"(not\b)");
  1688. auto location = get_location();
  1689. if (!consumeToken(not_tok).empty()) {
  1690. auto sub = parseLogicalNot();
  1691. if (!sub) throw std::runtime_error("Expected expression after 'not' keyword");
  1692. return std::make_shared<UnaryOpExpr>(location, std::move(sub), UnaryOpExpr::Op::LogicalNot);
  1693. }
  1694. return parseLogicalCompare();
  1695. }
  1696. std::shared_ptr<Expression> parseLogicalAnd() {
  1697. auto left = parseLogicalNot();
  1698. if (!left) throw std::runtime_error("Expected left side of 'logical and' expression");
  1699. static std::regex and_tok(R"(and\b)");
  1700. auto location = get_location();
  1701. while (!consumeToken(and_tok).empty()) {
  1702. auto right = parseLogicalNot();
  1703. if (!right) throw std::runtime_error("Expected right side of 'and' expression");
  1704. left = std::make_shared<BinaryOpExpr>(location, std::move(left), std::move(right), BinaryOpExpr::Op::And);
  1705. }
  1706. return left;
  1707. }
  1708. std::shared_ptr<Expression> parseLogicalCompare() {
  1709. auto left = parseStringConcat();
  1710. if (!left) throw std::runtime_error("Expected left side of 'logical compare' expression");
  1711. static std::regex compare_tok(R"(==|!=|<=?|>=?|in\b|is\b|not\s+in\b)");
  1712. static std::regex not_tok(R"(not\b)");
  1713. std::string op_str;
  1714. while (!(op_str = consumeToken(compare_tok)).empty()) {
  1715. auto location = get_location();
  1716. if (op_str == "is") {
  1717. auto negated = !consumeToken(not_tok).empty();
  1718. auto identifier = parseIdentifier();
  1719. if (!identifier) throw std::runtime_error("Expected identifier after 'is' keyword");
  1720. return std::make_shared<BinaryOpExpr>(
  1721. left->location,
  1722. std::move(left), std::move(identifier),
  1723. negated ? BinaryOpExpr::Op::IsNot : BinaryOpExpr::Op::Is);
  1724. }
  1725. auto right = parseStringConcat();
  1726. if (!right) throw std::runtime_error("Expected right side of 'logical compare' expression");
  1727. BinaryOpExpr::Op op;
  1728. if (op_str == "==") op = BinaryOpExpr::Op::Eq;
  1729. else if (op_str == "!=") op = BinaryOpExpr::Op::Ne;
  1730. else if (op_str == "<") op = BinaryOpExpr::Op::Lt;
  1731. else if (op_str == ">") op = BinaryOpExpr::Op::Gt;
  1732. else if (op_str == "<=") op = BinaryOpExpr::Op::Le;
  1733. else if (op_str == ">=") op = BinaryOpExpr::Op::Ge;
  1734. else if (op_str == "in") op = BinaryOpExpr::Op::In;
  1735. else if (op_str.substr(0, 3) == "not") op = BinaryOpExpr::Op::NotIn;
  1736. else throw std::runtime_error("Unknown comparison operator: " + op_str);
  1737. left = std::make_shared<BinaryOpExpr>(get_location(), std::move(left), std::move(right), op);
  1738. }
  1739. return left;
  1740. }
  1741. Expression::Parameters parseParameters() {
  1742. consumeSpaces();
  1743. if (consumeToken("(").empty()) throw std::runtime_error("Expected opening parenthesis in param list");
  1744. Expression::Parameters result;
  1745. while (it != end) {
  1746. if (!consumeToken(")").empty()) {
  1747. return result;
  1748. }
  1749. auto expr = parseExpression();
  1750. if (!expr) throw std::runtime_error("Expected expression in call args");
  1751. if (auto ident = dynamic_cast<VariableExpr*>(expr.get())) {
  1752. if (!consumeToken("=").empty()) {
  1753. auto value = parseExpression();
  1754. if (!value) throw std::runtime_error("Expected expression in for named arg");
  1755. result.emplace_back(ident->get_name(), std::move(value));
  1756. } else {
  1757. result.emplace_back(ident->get_name(), nullptr);
  1758. }
  1759. } else {
  1760. result.emplace_back(std::string(), std::move(expr));
  1761. }
  1762. if (consumeToken(",").empty()) {
  1763. if (consumeToken(")").empty()) {
  1764. throw std::runtime_error("Expected closing parenthesis in call args");
  1765. }
  1766. return result;
  1767. }
  1768. }
  1769. throw std::runtime_error("Expected closing parenthesis in call args");
  1770. }
  1771. ArgumentsExpression parseCallArgs() {
  1772. consumeSpaces();
  1773. if (consumeToken("(").empty()) throw std::runtime_error("Expected opening parenthesis in call args");
  1774. ArgumentsExpression result;
  1775. while (it != end) {
  1776. if (!consumeToken(")").empty()) {
  1777. return result;
  1778. }
  1779. auto expr = parseExpression();
  1780. if (!expr) throw std::runtime_error("Expected expression in call args");
  1781. if (auto ident = dynamic_cast<VariableExpr*>(expr.get())) {
  1782. if (!consumeToken("=").empty()) {
  1783. auto value = parseExpression();
  1784. if (!value) throw std::runtime_error("Expected expression in for named arg");
  1785. result.kwargs.emplace_back(ident->get_name(), std::move(value));
  1786. } else {
  1787. result.args.emplace_back(std::move(expr));
  1788. }
  1789. } else {
  1790. result.args.emplace_back(std::move(expr));
  1791. }
  1792. if (consumeToken(",").empty()) {
  1793. if (consumeToken(")").empty()) {
  1794. throw std::runtime_error("Expected closing parenthesis in call args");
  1795. }
  1796. return result;
  1797. }
  1798. }
  1799. throw std::runtime_error("Expected closing parenthesis in call args");
  1800. }
  1801. std::shared_ptr<VariableExpr> parseIdentifier() {
  1802. static std::regex ident_regex(R"((?!(?:not|is|and|or|del)\b)[a-zA-Z_]\w*)");
  1803. auto location = get_location();
  1804. auto ident = consumeToken(ident_regex);
  1805. if (ident.empty())
  1806. return nullptr;
  1807. return std::make_shared<VariableExpr>(location, ident);
  1808. }
  1809. std::shared_ptr<Expression> parseStringConcat() {
  1810. auto left = parseMathPow();
  1811. if (!left) throw std::runtime_error("Expected left side of 'string concat' expression");
  1812. static std::regex concat_tok(R"(~(?!\}))");
  1813. if (!consumeToken(concat_tok).empty()) {
  1814. auto right = parseLogicalAnd();
  1815. if (!right) throw std::runtime_error("Expected right side of 'string concat' expression");
  1816. left = std::make_shared<BinaryOpExpr>(get_location(), std::move(left), std::move(right), BinaryOpExpr::Op::StrConcat);
  1817. }
  1818. return left;
  1819. }
  1820. std::shared_ptr<Expression> parseMathPow() {
  1821. auto left = parseMathPlusMinus();
  1822. if (!left) throw std::runtime_error("Expected left side of 'math pow' expression");
  1823. while (!consumeToken("**").empty()) {
  1824. auto right = parseMathPlusMinus();
  1825. if (!right) throw std::runtime_error("Expected right side of 'math pow' expression");
  1826. left = std::make_shared<BinaryOpExpr>(get_location(), std::move(left), std::move(right), BinaryOpExpr::Op::MulMul);
  1827. }
  1828. return left;
  1829. }
  1830. std::shared_ptr<Expression> parseMathPlusMinus() {
  1831. static std::regex plus_minus_tok(R"(\+|-(?![}%#]\}))");
  1832. auto left = parseMathMulDiv();
  1833. if (!left) throw std::runtime_error("Expected left side of 'math plus/minus' expression");
  1834. std::string op_str;
  1835. while (!(op_str = consumeToken(plus_minus_tok)).empty()) {
  1836. auto right = parseMathMulDiv();
  1837. if (!right) throw std::runtime_error("Expected right side of 'math plus/minus' expression");
  1838. auto op = op_str == "+" ? BinaryOpExpr::Op::Add : BinaryOpExpr::Op::Sub;
  1839. left = std::make_shared<BinaryOpExpr>(get_location(), std::move(left), std::move(right), op);
  1840. }
  1841. return left;
  1842. }
  1843. std::shared_ptr<Expression> parseMathMulDiv() {
  1844. auto left = parseMathUnaryPlusMinus();
  1845. if (!left) throw std::runtime_error("Expected left side of 'math mul/div' expression");
  1846. static std::regex mul_div_tok(R"(\*\*?|//?|%(?!\}))");
  1847. std::string op_str;
  1848. while (!(op_str = consumeToken(mul_div_tok)).empty()) {
  1849. auto right = parseMathUnaryPlusMinus();
  1850. if (!right) throw std::runtime_error("Expected right side of 'math mul/div' expression");
  1851. auto op = op_str == "*" ? BinaryOpExpr::Op::Mul
  1852. : op_str == "**" ? BinaryOpExpr::Op::MulMul
  1853. : op_str == "/" ? BinaryOpExpr::Op::Div
  1854. : op_str == "//" ? BinaryOpExpr::Op::DivDiv
  1855. : BinaryOpExpr::Op::Mod;
  1856. left = std::make_shared<BinaryOpExpr>(get_location(), std::move(left), std::move(right), op);
  1857. }
  1858. if (!consumeToken("|").empty()) {
  1859. auto expr = parseMathMulDiv();
  1860. if (auto filter = dynamic_cast<FilterExpr*>(expr.get())) {
  1861. filter->prepend(std::move(left));
  1862. return expr;
  1863. } else {
  1864. std::vector<std::shared_ptr<Expression>> parts;
  1865. parts.emplace_back(std::move(left));
  1866. parts.emplace_back(std::move(expr));
  1867. return std::make_shared<FilterExpr>(get_location(), std::move(parts));
  1868. }
  1869. }
  1870. return left;
  1871. }
  1872. std::shared_ptr<Expression> call_func(const std::string & name, ArgumentsExpression && args) const {
  1873. return std::make_shared<CallExpr>(get_location(), std::make_shared<VariableExpr>(get_location(), name), std::move(args));
  1874. }
  1875. std::shared_ptr<Expression> parseMathUnaryPlusMinus() {
  1876. static std::regex unary_plus_minus_tok(R"(\+|-(?![}%#]\}))");
  1877. auto op_str = consumeToken(unary_plus_minus_tok);
  1878. auto expr = parseExpansion();
  1879. if (!expr) throw std::runtime_error("Expected expr of 'unary plus/minus/expansion' expression");
  1880. if (!op_str.empty()) {
  1881. auto op = op_str == "+" ? UnaryOpExpr::Op::Plus : UnaryOpExpr::Op::Minus;
  1882. return std::make_shared<UnaryOpExpr>(get_location(), std::move(expr), op);
  1883. }
  1884. return expr;
  1885. }
  1886. std::shared_ptr<Expression> parseExpansion() {
  1887. static std::regex expansion_tok(R"(\*\*?)");
  1888. auto op_str = consumeToken(expansion_tok);
  1889. auto expr = parseValueExpression();
  1890. if (op_str.empty()) return expr;
  1891. if (!expr) throw std::runtime_error("Expected expr of 'expansion' expression");
  1892. return std::make_shared<UnaryOpExpr>(get_location(), std::move(expr), op_str == "*" ? UnaryOpExpr::Op::Expansion : UnaryOpExpr::Op::ExpansionDict);
  1893. }
  1894. std::shared_ptr<Expression> parseValueExpression() {
  1895. auto parseValue = [&]() -> std::shared_ptr<Expression> {
  1896. auto location = get_location();
  1897. auto constant = parseConstant();
  1898. if (constant) return std::make_shared<LiteralExpr>(location, *constant);
  1899. static std::regex null_regex(R"(null\b)");
  1900. if (!consumeToken(null_regex).empty()) return std::make_shared<LiteralExpr>(location, Value());
  1901. auto identifier = parseIdentifier();
  1902. if (identifier) return identifier;
  1903. auto braced = parseBracedExpressionOrArray();
  1904. if (braced) return braced;
  1905. auto array = parseArray();
  1906. if (array) return array;
  1907. auto dictionary = parseDictionary();
  1908. if (dictionary) return dictionary;
  1909. throw std::runtime_error("Expected value expression");
  1910. };
  1911. auto value = parseValue();
  1912. while (it != end && consumeSpaces() && peekSymbols({ "[", "." })) {
  1913. if (!consumeToken("[").empty()) {
  1914. std::shared_ptr<Expression> index;
  1915. auto slice_loc = get_location();
  1916. std::shared_ptr<Expression> start, end, step;
  1917. bool has_first_colon = false, has_second_colon = false;
  1918. if (!peekSymbols({ ":" })) {
  1919. start = parseExpression();
  1920. }
  1921. if (!consumeToken(":").empty()) {
  1922. has_first_colon = true;
  1923. if (!peekSymbols({ ":", "]" })) {
  1924. end = parseExpression();
  1925. }
  1926. if (!consumeToken(":").empty()) {
  1927. has_second_colon = true;
  1928. if (!peekSymbols({ "]" })) {
  1929. step = parseExpression();
  1930. }
  1931. }
  1932. }
  1933. if ((has_first_colon || has_second_colon) && (start || end || step)) {
  1934. index = std::make_shared<SliceExpr>(slice_loc, std::move(start), std::move(end), std::move(step));
  1935. } else {
  1936. index = std::move(start);
  1937. }
  1938. if (!index) throw std::runtime_error("Empty index in subscript");
  1939. if (consumeToken("]").empty()) throw std::runtime_error("Expected closing bracket in subscript");
  1940. value = std::make_shared<SubscriptExpr>(value->location, std::move(value), std::move(index));
  1941. } else if (!consumeToken(".").empty()) {
  1942. auto identifier = parseIdentifier();
  1943. if (!identifier) throw std::runtime_error("Expected identifier in subscript");
  1944. consumeSpaces();
  1945. if (peekSymbols({ "(" })) {
  1946. auto callParams = parseCallArgs();
  1947. value = std::make_shared<MethodCallExpr>(identifier->location, std::move(value), std::move(identifier), std::move(callParams));
  1948. } else {
  1949. auto key = std::make_shared<LiteralExpr>(identifier->location, Value(identifier->get_name()));
  1950. value = std::make_shared<SubscriptExpr>(identifier->location, std::move(value), std::move(key));
  1951. }
  1952. }
  1953. consumeSpaces();
  1954. }
  1955. if (peekSymbols({ "(" })) {
  1956. auto location = get_location();
  1957. auto callParams = parseCallArgs();
  1958. value = std::make_shared<CallExpr>(location, std::move(value), std::move(callParams));
  1959. }
  1960. return value;
  1961. }
  1962. std::shared_ptr<Expression> parseBracedExpressionOrArray() {
  1963. if (consumeToken("(").empty()) return nullptr;
  1964. auto expr = parseExpression();
  1965. if (!expr) throw std::runtime_error("Expected expression in braced expression");
  1966. if (!consumeToken(")").empty()) {
  1967. return expr; // Drop the parentheses
  1968. }
  1969. std::vector<std::shared_ptr<Expression>> tuple;
  1970. tuple.emplace_back(std::move(expr));
  1971. while (it != end) {
  1972. if (consumeToken(",").empty()) throw std::runtime_error("Expected comma in tuple");
  1973. auto next = parseExpression();
  1974. if (!next) throw std::runtime_error("Expected expression in tuple");
  1975. tuple.push_back(std::move(next));
  1976. if (!consumeToken(")").empty()) {
  1977. return std::make_shared<ArrayExpr>(get_location(), std::move(tuple));
  1978. }
  1979. }
  1980. throw std::runtime_error("Expected closing parenthesis");
  1981. }
  1982. std::shared_ptr<Expression> parseArray() {
  1983. if (consumeToken("[").empty()) return nullptr;
  1984. std::vector<std::shared_ptr<Expression>> elements;
  1985. if (!consumeToken("]").empty()) {
  1986. return std::make_shared<ArrayExpr>(get_location(), std::move(elements));
  1987. }
  1988. auto first_expr = parseExpression();
  1989. if (!first_expr) throw std::runtime_error("Expected first expression in array");
  1990. elements.push_back(std::move(first_expr));
  1991. while (it != end) {
  1992. if (!consumeToken(",").empty()) {
  1993. auto expr = parseExpression();
  1994. if (!expr) throw std::runtime_error("Expected expression in array");
  1995. elements.push_back(std::move(expr));
  1996. } else if (!consumeToken("]").empty()) {
  1997. return std::make_shared<ArrayExpr>(get_location(), std::move(elements));
  1998. } else {
  1999. throw std::runtime_error("Expected comma or closing bracket in array");
  2000. }
  2001. }
  2002. throw std::runtime_error("Expected closing bracket");
  2003. }
  2004. std::shared_ptr<Expression> parseDictionary() {
  2005. if (consumeToken("{").empty()) return nullptr;
  2006. std::vector<std::pair<std::shared_ptr<Expression>, std::shared_ptr<Expression>>> elements;
  2007. if (!consumeToken("}").empty()) {
  2008. return std::make_shared<DictExpr>(get_location(), std::move(elements));
  2009. }
  2010. auto parseKeyValuePair = [&]() {
  2011. auto key = parseExpression();
  2012. if (!key) throw std::runtime_error("Expected key in dictionary");
  2013. if (consumeToken(":").empty()) throw std::runtime_error("Expected colon betweek key & value in dictionary");
  2014. auto value = parseExpression();
  2015. if (!value) throw std::runtime_error("Expected value in dictionary");
  2016. elements.emplace_back(std::pair(std::move(key), std::move(value)));
  2017. };
  2018. parseKeyValuePair();
  2019. while (it != end) {
  2020. if (!consumeToken(",").empty()) {
  2021. parseKeyValuePair();
  2022. } else if (!consumeToken("}").empty()) {
  2023. return std::make_shared<DictExpr>(get_location(), std::move(elements));
  2024. } else {
  2025. throw std::runtime_error("Expected comma or closing brace in dictionary");
  2026. }
  2027. }
  2028. throw std::runtime_error("Expected closing brace");
  2029. }
  2030. SpaceHandling parsePreSpace(const std::string& s) const {
  2031. if (s == "-")
  2032. return SpaceHandling::Strip;
  2033. return SpaceHandling::Keep;
  2034. }
  2035. SpaceHandling parsePostSpace(const std::string& s) const {
  2036. if (s == "-") return SpaceHandling::Strip;
  2037. return SpaceHandling::Keep;
  2038. }
  2039. using TemplateTokenVector = std::vector<std::unique_ptr<TemplateToken>>;
  2040. using TemplateTokenIterator = TemplateTokenVector::const_iterator;
  2041. std::vector<std::string> parseVarNames() {
  2042. static std::regex varnames_regex(R"(((?:\w+)(?:\s*,\s*(?:\w+))*)\s*)");
  2043. std::vector<std::string> group;
  2044. if ((group = consumeTokenGroups(varnames_regex)).empty()) throw std::runtime_error("Expected variable names");
  2045. std::vector<std::string> varnames;
  2046. std::istringstream iss(group[1]);
  2047. std::string varname;
  2048. while (std::getline(iss, varname, ',')) {
  2049. varnames.push_back(strip(varname));
  2050. }
  2051. return varnames;
  2052. }
  2053. std::runtime_error unexpected(const TemplateToken & token) const {
  2054. return std::runtime_error("Unexpected " + TemplateToken::typeToString(token.type)
  2055. + error_location_suffix(*template_str, token.location.pos));
  2056. }
  2057. std::runtime_error unterminated(const TemplateToken & token) const {
  2058. return std::runtime_error("Unterminated " + TemplateToken::typeToString(token.type)
  2059. + error_location_suffix(*template_str, token.location.pos));
  2060. }
  2061. TemplateTokenVector tokenize() {
  2062. static std::regex comment_tok(R"(\{#([-~]?)([\s\S]*?)([-~]?)#\})");
  2063. static std::regex expr_open_regex(R"(\{\{([-~])?)");
  2064. static std::regex block_open_regex(R"(^\{%([-~])?\s*)");
  2065. 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)");
  2066. static std::regex non_text_open_regex(R"(\{\{|\{%|\{#)");
  2067. static std::regex expr_close_regex(R"(\s*([-~])?\}\})");
  2068. static std::regex block_close_regex(R"(\s*([-~])?%\})");
  2069. TemplateTokenVector tokens;
  2070. std::vector<std::string> group;
  2071. std::string text;
  2072. std::smatch match;
  2073. try {
  2074. while (it != end) {
  2075. auto location = get_location();
  2076. if (!(group = consumeTokenGroups(comment_tok, SpaceHandling::Keep)).empty()) {
  2077. auto pre_space = parsePreSpace(group[1]);
  2078. auto content = group[2];
  2079. auto post_space = parsePostSpace(group[3]);
  2080. tokens.push_back(std::make_unique<CommentTemplateToken>(location, pre_space, post_space, content));
  2081. } else if (!(group = consumeTokenGroups(expr_open_regex, SpaceHandling::Keep)).empty()) {
  2082. auto pre_space = parsePreSpace(group[1]);
  2083. auto expr = parseExpression();
  2084. if ((group = consumeTokenGroups(expr_close_regex)).empty()) {
  2085. throw std::runtime_error("Expected closing expression tag");
  2086. }
  2087. auto post_space = parsePostSpace(group[1]);
  2088. tokens.push_back(std::make_unique<ExpressionTemplateToken>(location, pre_space, post_space, std::move(expr)));
  2089. } else if (!(group = consumeTokenGroups(block_open_regex, SpaceHandling::Keep)).empty()) {
  2090. auto pre_space = parsePreSpace(group[1]);
  2091. std::string keyword;
  2092. auto parseBlockClose = [&]() -> SpaceHandling {
  2093. if ((group = consumeTokenGroups(block_close_regex)).empty()) throw std::runtime_error("Expected closing block tag");
  2094. return parsePostSpace(group[1]);
  2095. };
  2096. if ((keyword = consumeToken(block_keyword_tok)).empty()) throw std::runtime_error("Expected block keyword");
  2097. if (keyword == "if") {
  2098. auto condition = parseExpression();
  2099. if (!condition) throw std::runtime_error("Expected condition in if block");
  2100. auto post_space = parseBlockClose();
  2101. tokens.push_back(std::make_unique<IfTemplateToken>(location, pre_space, post_space, std::move(condition)));
  2102. } else if (keyword == "elif") {
  2103. auto condition = parseExpression();
  2104. if (!condition) throw std::runtime_error("Expected condition in elif block");
  2105. auto post_space = parseBlockClose();
  2106. tokens.push_back(std::make_unique<ElifTemplateToken>(location, pre_space, post_space, std::move(condition)));
  2107. } else if (keyword == "else") {
  2108. auto post_space = parseBlockClose();
  2109. tokens.push_back(std::make_unique<ElseTemplateToken>(location, pre_space, post_space));
  2110. } else if (keyword == "endif") {
  2111. auto post_space = parseBlockClose();
  2112. tokens.push_back(std::make_unique<EndIfTemplateToken>(location, pre_space, post_space));
  2113. } else if (keyword == "for") {
  2114. static std::regex recursive_tok(R"(recursive\b)");
  2115. static std::regex if_tok(R"(if\b)");
  2116. auto varnames = parseVarNames();
  2117. static std::regex in_tok(R"(in\b)");
  2118. if (consumeToken(in_tok).empty()) throw std::runtime_error("Expected 'in' keyword in for block");
  2119. auto iterable = parseExpression(/* allow_if_expr = */ false);
  2120. if (!iterable) throw std::runtime_error("Expected iterable in for block");
  2121. std::shared_ptr<Expression> condition;
  2122. if (!consumeToken(if_tok).empty()) {
  2123. condition = parseExpression();
  2124. }
  2125. auto recursive = !consumeToken(recursive_tok).empty();
  2126. auto post_space = parseBlockClose();
  2127. tokens.push_back(std::make_unique<ForTemplateToken>(location, pre_space, post_space, std::move(varnames), std::move(iterable), std::move(condition), recursive));
  2128. } else if (keyword == "endfor") {
  2129. auto post_space = parseBlockClose();
  2130. tokens.push_back(std::make_unique<EndForTemplateToken>(location, pre_space, post_space));
  2131. } else if (keyword == "generation") {
  2132. auto post_space = parseBlockClose();
  2133. tokens.push_back(std::make_unique<GenerationTemplateToken>(location, pre_space, post_space));
  2134. } else if (keyword == "endgeneration") {
  2135. auto post_space = parseBlockClose();
  2136. tokens.push_back(std::make_unique<EndGenerationTemplateToken>(location, pre_space, post_space));
  2137. } else if (keyword == "set") {
  2138. static std::regex namespaced_var_regex(R"((\w+)\s*\.\s*(\w+))");
  2139. std::string ns;
  2140. std::vector<std::string> var_names;
  2141. std::shared_ptr<Expression> value;
  2142. if (!(group = consumeTokenGroups(namespaced_var_regex)).empty()) {
  2143. ns = group[1];
  2144. var_names.push_back(group[2]);
  2145. if (consumeToken("=").empty()) throw std::runtime_error("Expected equals sign in set block");
  2146. value = parseExpression();
  2147. if (!value) throw std::runtime_error("Expected value in set block");
  2148. } else {
  2149. var_names = parseVarNames();
  2150. if (!consumeToken("=").empty()) {
  2151. value = parseExpression();
  2152. if (!value) throw std::runtime_error("Expected value in set block");
  2153. }
  2154. }
  2155. auto post_space = parseBlockClose();
  2156. tokens.push_back(std::make_unique<SetTemplateToken>(location, pre_space, post_space, ns, var_names, std::move(value)));
  2157. } else if (keyword == "endset") {
  2158. auto post_space = parseBlockClose();
  2159. tokens.push_back(std::make_unique<EndSetTemplateToken>(location, pre_space, post_space));
  2160. } else if (keyword == "macro") {
  2161. auto macroname = parseIdentifier();
  2162. if (!macroname) throw std::runtime_error("Expected macro name in macro block");
  2163. auto params = parseParameters();
  2164. auto post_space = parseBlockClose();
  2165. tokens.push_back(std::make_unique<MacroTemplateToken>(location, pre_space, post_space, std::move(macroname), std::move(params)));
  2166. } else if (keyword == "endmacro") {
  2167. auto post_space = parseBlockClose();
  2168. tokens.push_back(std::make_unique<EndMacroTemplateToken>(location, pre_space, post_space));
  2169. } else if (keyword == "filter") {
  2170. auto filter = parseExpression();
  2171. if (!filter) throw std::runtime_error("Expected expression in filter block");
  2172. auto post_space = parseBlockClose();
  2173. tokens.push_back(std::make_unique<FilterTemplateToken>(location, pre_space, post_space, std::move(filter)));
  2174. } else if (keyword == "endfilter") {
  2175. auto post_space = parseBlockClose();
  2176. tokens.push_back(std::make_unique<EndFilterTemplateToken>(location, pre_space, post_space));
  2177. } else if (keyword == "break" || keyword == "continue") {
  2178. auto post_space = parseBlockClose();
  2179. tokens.push_back(std::make_unique<LoopControlTemplateToken>(location, pre_space, post_space, keyword == "break" ? LoopControlType::Break : LoopControlType::Continue));
  2180. } else {
  2181. throw std::runtime_error("Unexpected block: " + keyword);
  2182. }
  2183. } else if (std::regex_search(it, end, match, non_text_open_regex)) {
  2184. if (!match.position()) {
  2185. if (match[0] != "{#")
  2186. throw std::runtime_error("Internal error: Expected a comment");
  2187. throw std::runtime_error("Missing end of comment tag");
  2188. }
  2189. auto text_end = it + match.position();
  2190. text = std::string(it, text_end);
  2191. it = text_end;
  2192. tokens.push_back(std::make_unique<TextTemplateToken>(location, SpaceHandling::Keep, SpaceHandling::Keep, text));
  2193. } else {
  2194. text = std::string(it, end);
  2195. it = end;
  2196. tokens.push_back(std::make_unique<TextTemplateToken>(location, SpaceHandling::Keep, SpaceHandling::Keep, text));
  2197. }
  2198. }
  2199. return tokens;
  2200. } catch (const std::exception & e) {
  2201. throw std::runtime_error(e.what() + error_location_suffix(*template_str, std::distance(start, it)));
  2202. }
  2203. }
  2204. std::shared_ptr<TemplateNode> parseTemplate(
  2205. const TemplateTokenIterator & begin,
  2206. TemplateTokenIterator & it,
  2207. const TemplateTokenIterator & end,
  2208. bool fully = false) const {
  2209. std::vector<std::shared_ptr<TemplateNode>> children;
  2210. while (it != end) {
  2211. const auto start = it;
  2212. const auto & token = *(it++);
  2213. if (auto if_token = dynamic_cast<IfTemplateToken*>(token.get())) {
  2214. std::vector<std::pair<std::shared_ptr<Expression>, std::shared_ptr<TemplateNode>>> cascade;
  2215. cascade.emplace_back(std::move(if_token->condition), parseTemplate(begin, it, end));
  2216. while (it != end && (*it)->type == TemplateToken::Type::Elif) {
  2217. auto elif_token = dynamic_cast<ElifTemplateToken*>((*(it++)).get());
  2218. cascade.emplace_back(std::move(elif_token->condition), parseTemplate(begin, it, end));
  2219. }
  2220. if (it != end && (*it)->type == TemplateToken::Type::Else) {
  2221. cascade.emplace_back(nullptr, parseTemplate(begin, ++it, end));
  2222. }
  2223. if (it == end || (*(it++))->type != TemplateToken::Type::EndIf) {
  2224. throw unterminated(**start);
  2225. }
  2226. children.emplace_back(std::make_shared<IfNode>(token->location, std::move(cascade)));
  2227. } else if (auto for_token = dynamic_cast<ForTemplateToken*>(token.get())) {
  2228. auto body = parseTemplate(begin, it, end);
  2229. auto else_body = std::shared_ptr<TemplateNode>();
  2230. if (it != end && (*it)->type == TemplateToken::Type::Else) {
  2231. else_body = parseTemplate(begin, ++it, end);
  2232. }
  2233. if (it == end || (*(it++))->type != TemplateToken::Type::EndFor) {
  2234. throw unterminated(**start);
  2235. }
  2236. 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)));
  2237. } else if (dynamic_cast<GenerationTemplateToken*>(token.get())) {
  2238. auto body = parseTemplate(begin, it, end);
  2239. if (it == end || (*(it++))->type != TemplateToken::Type::EndGeneration) {
  2240. throw unterminated(**start);
  2241. }
  2242. // Treat as a no-op, as our scope is templates for inference, not training (`{% generation %}` wraps generated tokens for masking).
  2243. children.emplace_back(std::move(body));
  2244. } else if (auto text_token = dynamic_cast<TextTemplateToken*>(token.get())) {
  2245. SpaceHandling pre_space = (it - 1) != begin ? (*(it - 2))->post_space : SpaceHandling::Keep;
  2246. SpaceHandling post_space = it != end ? (*it)->pre_space : SpaceHandling::Keep;
  2247. auto text = text_token->text;
  2248. if (post_space == SpaceHandling::Strip) {
  2249. static std::regex trailing_space_regex(R"(\s+$)");
  2250. text = std::regex_replace(text, trailing_space_regex, "");
  2251. } else if (options.lstrip_blocks && it != end) {
  2252. auto i = text.size();
  2253. while (i > 0 && (text[i - 1] == ' ' || text[i - 1] == '\t')) i--;
  2254. if ((i == 0 && (it - 1) == begin) || (i > 0 && text[i - 1] == '\n')) {
  2255. text.resize(i);
  2256. }
  2257. }
  2258. if (pre_space == SpaceHandling::Strip) {
  2259. static std::regex leading_space_regex(R"(^\s+)");
  2260. text = std::regex_replace(text, leading_space_regex, "");
  2261. } else if (options.trim_blocks && (it - 1) != begin && !dynamic_cast<ExpressionTemplateToken*>((*(it - 2)).get())) {
  2262. if (!text.empty() && text[0] == '\n') {
  2263. text.erase(0, 1);
  2264. }
  2265. }
  2266. if (it == end && !options.keep_trailing_newline) {
  2267. auto i = text.size();
  2268. if (i > 0 && text[i - 1] == '\n') {
  2269. i--;
  2270. if (i > 0 && text[i - 1] == '\r') i--;
  2271. text.resize(i);
  2272. }
  2273. }
  2274. children.emplace_back(std::make_shared<TextNode>(token->location, text));
  2275. } else if (auto expr_token = dynamic_cast<ExpressionTemplateToken*>(token.get())) {
  2276. children.emplace_back(std::make_shared<ExpressionNode>(token->location, std::move(expr_token->expr)));
  2277. } else if (auto set_token = dynamic_cast<SetTemplateToken*>(token.get())) {
  2278. if (set_token->value) {
  2279. children.emplace_back(std::make_shared<SetNode>(token->location, set_token->ns, set_token->var_names, std::move(set_token->value)));
  2280. } else {
  2281. auto value_template = parseTemplate(begin, it, end);
  2282. if (it == end || (*(it++))->type != TemplateToken::Type::EndSet) {
  2283. throw unterminated(**start);
  2284. }
  2285. if (!set_token->ns.empty()) throw std::runtime_error("Namespaced set not supported in set with template value");
  2286. if (set_token->var_names.size() != 1) throw std::runtime_error("Structural assignment not supported in set with template value");
  2287. auto & name = set_token->var_names[0];
  2288. children.emplace_back(std::make_shared<SetTemplateNode>(token->location, name, std::move(value_template)));
  2289. }
  2290. } else if (auto macro_token = dynamic_cast<MacroTemplateToken*>(token.get())) {
  2291. auto body = parseTemplate(begin, it, end);
  2292. if (it == end || (*(it++))->type != TemplateToken::Type::EndMacro) {
  2293. throw unterminated(**start);
  2294. }
  2295. children.emplace_back(std::make_shared<MacroNode>(token->location, std::move(macro_token->name), std::move(macro_token->params), std::move(body)));
  2296. } else if (auto filter_token = dynamic_cast<FilterTemplateToken*>(token.get())) {
  2297. auto body = parseTemplate(begin, it, end);
  2298. if (it == end || (*(it++))->type != TemplateToken::Type::EndFilter) {
  2299. throw unterminated(**start);
  2300. }
  2301. children.emplace_back(std::make_shared<FilterNode>(token->location, std::move(filter_token->filter), std::move(body)));
  2302. } else if (dynamic_cast<CommentTemplateToken*>(token.get())) {
  2303. // Ignore comments
  2304. } else if (auto ctrl_token = dynamic_cast<LoopControlTemplateToken*>(token.get())) {
  2305. children.emplace_back(std::make_shared<LoopControlNode>(token->location, ctrl_token->control_type));
  2306. } else if (dynamic_cast<EndForTemplateToken*>(token.get())
  2307. || dynamic_cast<EndSetTemplateToken*>(token.get())
  2308. || dynamic_cast<EndMacroTemplateToken*>(token.get())
  2309. || dynamic_cast<EndFilterTemplateToken*>(token.get())
  2310. || dynamic_cast<EndIfTemplateToken*>(token.get())
  2311. || dynamic_cast<ElseTemplateToken*>(token.get())
  2312. || dynamic_cast<EndGenerationTemplateToken*>(token.get())
  2313. || dynamic_cast<ElifTemplateToken*>(token.get())) {
  2314. it--; // unconsume the token
  2315. break; // exit the loop
  2316. } else {
  2317. throw unexpected(**(it-1));
  2318. }
  2319. }
  2320. if (fully && it != end) {
  2321. throw unexpected(**it);
  2322. }
  2323. if (children.empty()) {
  2324. return std::make_shared<TextNode>(Location { template_str, 0 }, std::string());
  2325. } else if (children.size() == 1) {
  2326. return std::move(children[0]);
  2327. } else {
  2328. return std::make_shared<SequenceNode>(children[0]->location(), std::move(children));
  2329. }
  2330. }
  2331. public:
  2332. static std::shared_ptr<TemplateNode> parse(const std::string& template_str, const Options & options) {
  2333. Parser parser(std::make_shared<std::string>(normalize_newlines(template_str)), options);
  2334. auto tokens = parser.tokenize();
  2335. TemplateTokenIterator begin = tokens.begin();
  2336. auto it = begin;
  2337. TemplateTokenIterator end = tokens.end();
  2338. return parser.parseTemplate(begin, it, end, /* fully= */ true);
  2339. }
  2340. };
  2341. 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) {
  2342. std::map<std::string, size_t> named_positions;
  2343. for (size_t i = 0, n = params.size(); i < n; i++) named_positions[params[i]] = i;
  2344. return Value::callable([=](const std::shared_ptr<Context> & context, ArgumentsValue & args) -> Value {
  2345. auto args_obj = Value::object();
  2346. std::vector<bool> provided_args(params.size());
  2347. for (size_t i = 0, n = args.args.size(); i < n; i++) {
  2348. auto & arg = args.args[i];
  2349. if (i < params.size()) {
  2350. args_obj.set(params[i], arg);
  2351. provided_args[i] = true;
  2352. } else {
  2353. throw std::runtime_error("Too many positional params for " + fn_name);
  2354. }
  2355. }
  2356. for (auto & [name, value] : args.kwargs) {
  2357. auto named_pos_it = named_positions.find(name);
  2358. if (named_pos_it == named_positions.end()) {
  2359. throw std::runtime_error("Unknown argument " + name + " for function " + fn_name);
  2360. }
  2361. provided_args[named_pos_it->second] = true;
  2362. args_obj.set(name, value);
  2363. }
  2364. return fn(context, args_obj);
  2365. });
  2366. }
  2367. inline std::shared_ptr<Context> Context::builtins() {
  2368. auto globals = Value::object();
  2369. globals.set("raise_exception", simple_function("raise_exception", { "message" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2370. throw std::runtime_error(args.at("message").get<std::string>());
  2371. }));
  2372. globals.set("tojson", simple_function("tojson", { "value", "indent" }, [](const std::shared_ptr<Context> &, Value & args) {
  2373. return Value(args.at("value").dump(args.get<int64_t>("indent", -1), /* to_json= */ true));
  2374. }));
  2375. globals.set("items", simple_function("items", { "object" }, [](const std::shared_ptr<Context> &, Value & args) {
  2376. auto items = Value::array();
  2377. if (args.contains("object")) {
  2378. auto & obj = args.at("object");
  2379. if (obj.is_string()) {
  2380. auto json_obj = json::parse(obj.get<std::string>());
  2381. for (const auto & kv : json_obj.items()) {
  2382. items.push_back(Value::array({kv.key(), kv.value()}));
  2383. }
  2384. } else if (!obj.is_null()) {
  2385. for (auto & key : obj.keys()) {
  2386. items.push_back(Value::array({key, obj.at(key)}));
  2387. }
  2388. }
  2389. }
  2390. return items;
  2391. }));
  2392. globals.set("last", simple_function("last", { "items" }, [](const std::shared_ptr<Context> &, Value & args) {
  2393. auto items = args.at("items");
  2394. if (!items.is_array()) throw std::runtime_error("object is not a list");
  2395. if (items.empty()) return Value();
  2396. return items.at(items.size() - 1);
  2397. }));
  2398. globals.set("trim", simple_function("trim", { "text" }, [](const std::shared_ptr<Context> &, Value & args) {
  2399. auto & text = args.at("text");
  2400. return text.is_null() ? text : Value(strip(text.get<std::string>()));
  2401. }));
  2402. auto char_transform_function = [](const std::string & name, const std::function<char(char)> & fn) {
  2403. return simple_function(name, { "text" }, [=](const std::shared_ptr<Context> &, Value & args) {
  2404. auto text = args.at("text");
  2405. if (text.is_null()) return text;
  2406. std::string res;
  2407. auto str = text.get<std::string>();
  2408. std::transform(str.begin(), str.end(), std::back_inserter(res), fn);
  2409. return Value(res);
  2410. });
  2411. };
  2412. globals.set("lower", char_transform_function("lower", ::tolower));
  2413. globals.set("upper", char_transform_function("upper", ::toupper));
  2414. globals.set("default", Value::callable([=](const std::shared_ptr<Context> &, ArgumentsValue & args) {
  2415. args.expectArgs("default", {2, 3}, {0, 1});
  2416. auto & value = args.args[0];
  2417. auto & default_value = args.args[1];
  2418. bool boolean = false;
  2419. if (args.args.size() == 3) {
  2420. boolean = args.args[2].get<bool>();
  2421. } else {
  2422. Value bv = args.get_named("boolean");
  2423. if (!bv.is_null()) {
  2424. boolean = bv.get<bool>();
  2425. }
  2426. }
  2427. return boolean ? (value.to_bool() ? value : default_value) : value.is_null() ? default_value : value;
  2428. }));
  2429. auto escape = simple_function("escape", { "text" }, [](const std::shared_ptr<Context> &, Value & args) {
  2430. return Value(html_escape(args.at("text").get<std::string>()));
  2431. });
  2432. globals.set("e", escape);
  2433. globals.set("escape", escape);
  2434. globals.set("joiner", simple_function("joiner", { "sep" }, [](const std::shared_ptr<Context> &, Value & args) {
  2435. auto sep = args.get<std::string>("sep", "");
  2436. auto first = std::make_shared<bool>(true);
  2437. return simple_function("", {}, [sep, first](const std::shared_ptr<Context> &, const Value &) -> Value {
  2438. if (*first) {
  2439. *first = false;
  2440. return "";
  2441. }
  2442. return sep;
  2443. });
  2444. return Value(html_escape(args.at("text").get<std::string>()));
  2445. }));
  2446. globals.set("count", simple_function("count", { "items" }, [](const std::shared_ptr<Context> &, Value & args) {
  2447. return Value((int64_t) args.at("items").size());
  2448. }));
  2449. globals.set("dictsort", simple_function("dictsort", { "value" }, [](const std::shared_ptr<Context> &, Value & args) {
  2450. if (args.size() != 1) throw std::runtime_error("dictsort expects exactly 1 argument (TODO: fix implementation)");
  2451. auto & value = args.at("value");
  2452. auto keys = value.keys();
  2453. std::sort(keys.begin(), keys.end());
  2454. auto res = Value::array();
  2455. for (auto & key : keys) {
  2456. res.push_back(Value::array({key, value.at(key)}));
  2457. }
  2458. return res;
  2459. }));
  2460. globals.set("join", simple_function("join", { "items", "d" }, [](const std::shared_ptr<Context> &, Value & args) {
  2461. auto do_join = [](Value & items, const std::string & sep) {
  2462. if (!items.is_array()) throw std::runtime_error("object is not iterable: " + items.dump());
  2463. std::ostringstream oss;
  2464. auto first = true;
  2465. for (size_t i = 0, n = items.size(); i < n; ++i) {
  2466. if (first) first = false;
  2467. else oss << sep;
  2468. oss << items.at(i).to_str();
  2469. }
  2470. return Value(oss.str());
  2471. };
  2472. auto sep = args.get<std::string>("d", "");
  2473. if (args.contains("items")) {
  2474. auto & items = args.at("items");
  2475. return do_join(items, sep);
  2476. } else {
  2477. return simple_function("", {"items"}, [sep, do_join](const std::shared_ptr<Context> &, Value & args) {
  2478. auto & items = args.at("items");
  2479. if (!items.to_bool() || !items.is_array()) throw std::runtime_error("join expects an array for items, got: " + items.dump());
  2480. return do_join(items, sep);
  2481. });
  2482. }
  2483. }));
  2484. globals.set("namespace", Value::callable([=](const std::shared_ptr<Context> &, ArgumentsValue & args) {
  2485. auto ns = Value::object();
  2486. args.expectArgs("namespace", {0, 0}, {0, (std::numeric_limits<size_t>::max)()});
  2487. for (auto & [name, value] : args.kwargs) {
  2488. ns.set(name, value);
  2489. }
  2490. return ns;
  2491. }));
  2492. auto equalto = simple_function("equalto", { "expected", "actual" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2493. return args.at("actual") == args.at("expected");
  2494. });
  2495. globals.set("equalto", equalto);
  2496. globals.set("==", equalto);
  2497. globals.set("length", simple_function("length", { "items" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2498. auto & items = args.at("items");
  2499. return (int64_t) items.size();
  2500. }));
  2501. globals.set("safe", simple_function("safe", { "value" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2502. return args.at("value").to_str();
  2503. }));
  2504. globals.set("string", simple_function("string", { "value" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2505. return args.at("value").to_str();
  2506. }));
  2507. globals.set("int", simple_function("int", { "value" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2508. return args.at("value").to_int();
  2509. }));
  2510. globals.set("list", simple_function("list", { "items" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2511. auto & items = args.at("items");
  2512. if (!items.is_array()) throw std::runtime_error("object is not iterable");
  2513. return items;
  2514. }));
  2515. globals.set("unique", simple_function("unique", { "items" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2516. auto & items = args.at("items");
  2517. if (!items.is_array()) throw std::runtime_error("object is not iterable");
  2518. std::unordered_set<Value> seen;
  2519. auto result = Value::array();
  2520. for (size_t i = 0, n = items.size(); i < n; i++) {
  2521. auto pair = seen.insert(items.at(i));
  2522. if (pair.second) {
  2523. result.push_back(items.at(i));
  2524. }
  2525. }
  2526. return result;
  2527. }));
  2528. auto make_filter = [](const Value & filter, Value & extra_args) -> Value {
  2529. return simple_function("", { "value" }, [=](const std::shared_ptr<Context> & context, Value & args) {
  2530. auto & value = args.at("value");
  2531. ArgumentsValue actual_args;
  2532. actual_args.args.emplace_back(value);
  2533. for (size_t i = 0, n = extra_args.size(); i < n; i++) {
  2534. actual_args.args.emplace_back(extra_args.at(i));
  2535. }
  2536. return filter.call(context, actual_args);
  2537. });
  2538. };
  2539. auto select_or_reject = [make_filter](bool is_select) {
  2540. return Value::callable([=](const std::shared_ptr<Context> & context, ArgumentsValue & args) {
  2541. args.expectArgs(is_select ? "select" : "reject", {2, (std::numeric_limits<size_t>::max)()}, {0, 0});
  2542. auto & items = args.args[0];
  2543. if (items.is_null()) {
  2544. return Value::array();
  2545. }
  2546. if (!items.is_array()) {
  2547. throw std::runtime_error("object is not iterable: " + items.dump());
  2548. }
  2549. auto filter_fn = context->get(args.args[1]);
  2550. if (filter_fn.is_null()) {
  2551. throw std::runtime_error("Undefined filter: " + args.args[1].dump());
  2552. }
  2553. auto filter_args = Value::array();
  2554. for (size_t i = 2, n = args.args.size(); i < n; i++) {
  2555. filter_args.push_back(args.args[i]);
  2556. }
  2557. auto filter = make_filter(filter_fn, filter_args);
  2558. auto res = Value::array();
  2559. for (size_t i = 0, n = items.size(); i < n; i++) {
  2560. auto & item = items.at(i);
  2561. ArgumentsValue filter_args;
  2562. filter_args.args.emplace_back(item);
  2563. auto pred_res = filter.call(context, filter_args);
  2564. if (pred_res.to_bool() == (is_select ? true : false)) {
  2565. res.push_back(item);
  2566. }
  2567. }
  2568. return res;
  2569. });
  2570. };
  2571. globals.set("select", select_or_reject(/* is_select= */ true));
  2572. globals.set("reject", select_or_reject(/* is_select= */ false));
  2573. globals.set("map", Value::callable([=](const std::shared_ptr<Context> & context, ArgumentsValue & args) {
  2574. auto res = Value::array();
  2575. if (args.args.size() == 1 &&
  2576. ((args.has_named("attribute") && args.kwargs.size() == 1) || (args.has_named("default") && args.kwargs.size() == 2))) {
  2577. auto & items = args.args[0];
  2578. auto attr_name = args.get_named("attribute");
  2579. auto default_value = args.get_named("default");
  2580. for (size_t i = 0, n = items.size(); i < n; i++) {
  2581. auto & item = items.at(i);
  2582. auto attr = item.get(attr_name);
  2583. res.push_back(attr.is_null() ? default_value : attr);
  2584. }
  2585. } else if (args.kwargs.empty() && args.args.size() >= 2) {
  2586. auto fn = context->get(args.args[1]);
  2587. if (fn.is_null()) throw std::runtime_error("Undefined filter: " + args.args[1].dump());
  2588. ArgumentsValue filter_args { {Value()}, {} };
  2589. for (size_t i = 2, n = args.args.size(); i < n; i++) {
  2590. filter_args.args.emplace_back(args.args[i]);
  2591. }
  2592. for (size_t i = 0, n = args.args[0].size(); i < n; i++) {
  2593. auto & item = args.args[0].at(i);
  2594. filter_args.args[0] = item;
  2595. res.push_back(fn.call(context, filter_args));
  2596. }
  2597. } else {
  2598. throw std::runtime_error("Invalid or unsupported arguments for map");
  2599. }
  2600. return res;
  2601. }));
  2602. globals.set("indent", simple_function("indent", { "text", "indent", "first" }, [](const std::shared_ptr<Context> &, Value & args) {
  2603. auto text = args.at("text").get<std::string>();
  2604. auto first = args.get<bool>("first", false);
  2605. std::string out;
  2606. std::string indent(args.get<int64_t>("indent", 0), ' ');
  2607. std::istringstream iss(text);
  2608. std::string line;
  2609. auto is_first = true;
  2610. while (std::getline(iss, line, '\n')) {
  2611. auto needs_indent = !is_first || first;
  2612. if (is_first) is_first = false;
  2613. else out += "\n";
  2614. if (needs_indent) out += indent;
  2615. out += line;
  2616. }
  2617. if (!text.empty() && text.back() == '\n') out += "\n";
  2618. return out;
  2619. }));
  2620. auto select_or_reject_attr = [](bool is_select) {
  2621. return Value::callable([=](const std::shared_ptr<Context> & context, ArgumentsValue & args) {
  2622. args.expectArgs(is_select ? "selectattr" : "rejectattr", {2, (std::numeric_limits<size_t>::max)()}, {0, 0});
  2623. auto & items = args.args[0];
  2624. if (items.is_null())
  2625. return Value::array();
  2626. if (!items.is_array()) throw std::runtime_error("object is not iterable: " + items.dump());
  2627. auto attr_name = args.args[1].get<std::string>();
  2628. bool has_test = false;
  2629. Value test_fn;
  2630. ArgumentsValue test_args {{Value()}, {}};
  2631. if (args.args.size() >= 3) {
  2632. has_test = true;
  2633. test_fn = context->get(args.args[2]);
  2634. if (test_fn.is_null()) throw std::runtime_error("Undefined test: " + args.args[2].dump());
  2635. for (size_t i = 3, n = args.args.size(); i < n; i++) {
  2636. test_args.args.emplace_back(args.args[i]);
  2637. }
  2638. test_args.kwargs = args.kwargs;
  2639. }
  2640. auto res = Value::array();
  2641. for (size_t i = 0, n = items.size(); i < n; i++) {
  2642. auto & item = items.at(i);
  2643. auto attr = item.get(attr_name);
  2644. if (has_test) {
  2645. test_args.args[0] = attr;
  2646. if (test_fn.call(context, test_args).to_bool() == (is_select ? true : false)) {
  2647. res.push_back(item);
  2648. }
  2649. } else {
  2650. res.push_back(attr);
  2651. }
  2652. }
  2653. return res;
  2654. });
  2655. };
  2656. globals.set("selectattr", select_or_reject_attr(/* is_select= */ true));
  2657. globals.set("rejectattr", select_or_reject_attr(/* is_select= */ false));
  2658. globals.set("range", Value::callable([=](const std::shared_ptr<Context> &, ArgumentsValue & args) {
  2659. std::vector<int64_t> startEndStep(3);
  2660. std::vector<bool> param_set(3);
  2661. if (args.args.size() == 1) {
  2662. startEndStep[1] = args.args[0].get<int64_t>();
  2663. param_set[1] = true;
  2664. } else {
  2665. for (size_t i = 0; i < args.args.size(); i++) {
  2666. auto & arg = args.args[i];
  2667. auto v = arg.get<int64_t>();
  2668. startEndStep[i] = v;
  2669. param_set[i] = true;
  2670. }
  2671. }
  2672. for (auto & [name, value] : args.kwargs) {
  2673. size_t i;
  2674. if (name == "start") {
  2675. i = 0;
  2676. } else if (name == "end") {
  2677. i = 1;
  2678. } else if (name == "step") {
  2679. i = 2;
  2680. } else {
  2681. throw std::runtime_error("Unknown argument " + name + " for function range");
  2682. }
  2683. if (param_set[i]) {
  2684. throw std::runtime_error("Duplicate argument " + name + " for function range");
  2685. }
  2686. startEndStep[i] = value.get<int64_t>();
  2687. param_set[i] = true;
  2688. }
  2689. if (!param_set[1]) {
  2690. throw std::runtime_error("Missing required argument 'end' for function range");
  2691. }
  2692. int64_t start = param_set[0] ? startEndStep[0] : 0;
  2693. int64_t end = startEndStep[1];
  2694. int64_t step = param_set[2] ? startEndStep[2] : 1;
  2695. auto res = Value::array();
  2696. if (step > 0) {
  2697. for (int64_t i = start; i < end; i += step) {
  2698. res.push_back(Value(i));
  2699. }
  2700. } else {
  2701. for (int64_t i = start; i > end; i += step) {
  2702. res.push_back(Value(i));
  2703. }
  2704. }
  2705. return res;
  2706. }));
  2707. return std::make_shared<Context>(std::move(globals));
  2708. }
  2709. inline std::shared_ptr<Context> Context::make(Value && values, const std::shared_ptr<Context> & parent) {
  2710. return std::make_shared<Context>(values.is_null() ? Value::object() : std::move(values), parent);
  2711. }
  2712. } // namespace minja