minja.hpp 120 KB

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