minja.hpp 115 KB

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