minja.hpp 127 KB

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