minja.hpp 120 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915
  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, const 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, Break, Continue };
  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. case Type::Break: return "break";
  659. case Type::Continue: return "continue";
  660. }
  661. return "Unknown";
  662. }
  663. TemplateToken(Type type, const Location & location, SpaceHandling pre, SpaceHandling post) : type(type), location(location), pre_space(pre), post_space(post) {}
  664. virtual ~TemplateToken() = default;
  665. Type type;
  666. Location location;
  667. SpaceHandling pre_space = SpaceHandling::Keep;
  668. SpaceHandling post_space = SpaceHandling::Keep;
  669. };
  670. struct TextTemplateToken : public TemplateToken {
  671. std::string text;
  672. TextTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, const std::string& t) : TemplateToken(Type::Text, location, pre, post), text(t) {}
  673. };
  674. struct ExpressionTemplateToken : public TemplateToken {
  675. std::shared_ptr<Expression> expr;
  676. ExpressionTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, std::shared_ptr<Expression> && e) : TemplateToken(Type::Expression, location, pre, post), expr(std::move(e)) {}
  677. };
  678. struct IfTemplateToken : public TemplateToken {
  679. std::shared_ptr<Expression> condition;
  680. IfTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, std::shared_ptr<Expression> && c) : TemplateToken(Type::If, location, pre, post), condition(std::move(c)) {}
  681. };
  682. struct ElifTemplateToken : public TemplateToken {
  683. std::shared_ptr<Expression> condition;
  684. ElifTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, std::shared_ptr<Expression> && c) : TemplateToken(Type::Elif, location, pre, post), condition(std::move(c)) {}
  685. };
  686. struct ElseTemplateToken : public TemplateToken {
  687. ElseTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::Else, location, pre, post) {}
  688. };
  689. struct EndIfTemplateToken : public TemplateToken {
  690. EndIfTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::EndIf, location, pre, post) {}
  691. };
  692. struct MacroTemplateToken : public TemplateToken {
  693. std::shared_ptr<VariableExpr> name;
  694. Expression::Parameters params;
  695. MacroTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, std::shared_ptr<VariableExpr> && n, Expression::Parameters && p)
  696. : TemplateToken(Type::Macro, location, pre, post), name(std::move(n)), params(std::move(p)) {}
  697. };
  698. struct EndMacroTemplateToken : public TemplateToken {
  699. EndMacroTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::EndMacro, location, pre, post) {}
  700. };
  701. struct FilterTemplateToken : public TemplateToken {
  702. std::shared_ptr<Expression> filter;
  703. FilterTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, std::shared_ptr<Expression> && filter)
  704. : TemplateToken(Type::Filter, location, pre, post), filter(std::move(filter)) {}
  705. };
  706. struct EndFilterTemplateToken : public TemplateToken {
  707. EndFilterTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::EndFilter, location, pre, post) {}
  708. };
  709. struct ForTemplateToken : public TemplateToken {
  710. std::vector<std::string> var_names;
  711. std::shared_ptr<Expression> iterable;
  712. std::shared_ptr<Expression> condition;
  713. bool recursive;
  714. ForTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, const std::vector<std::string> & vns, std::shared_ptr<Expression> && iter,
  715. std::shared_ptr<Expression> && c, bool r)
  716. : TemplateToken(Type::For, location, pre, post), var_names(vns), iterable(std::move(iter)), condition(std::move(c)), recursive(r) {}
  717. };
  718. struct EndForTemplateToken : public TemplateToken {
  719. EndForTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::EndFor, location, pre, post) {}
  720. };
  721. struct GenerationTemplateToken : public TemplateToken {
  722. GenerationTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::Generation, location, pre, post) {}
  723. };
  724. struct EndGenerationTemplateToken : public TemplateToken {
  725. EndGenerationTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::EndGeneration, location, pre, post) {}
  726. };
  727. struct SetTemplateToken : public TemplateToken {
  728. std::string ns;
  729. std::vector<std::string> var_names;
  730. std::shared_ptr<Expression> value;
  731. SetTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, const std::string & ns, const std::vector<std::string> & vns, std::shared_ptr<Expression> && v)
  732. : TemplateToken(Type::Set, location, pre, post), ns(ns), var_names(vns), value(std::move(v)) {}
  733. };
  734. struct EndSetTemplateToken : public TemplateToken {
  735. EndSetTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::EndSet, location, pre, post) {}
  736. };
  737. struct CommentTemplateToken : public TemplateToken {
  738. std::string text;
  739. CommentTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, const std::string& t) : TemplateToken(Type::Comment, location, pre, post), text(t) {}
  740. };
  741. enum class LoopControlType { Break, Continue };
  742. class LoopControlException : public std::runtime_error {
  743. public:
  744. LoopControlType control_type;
  745. LoopControlException(const std::string & message, LoopControlType control_type) : std::runtime_error(message), control_type(control_type) {}
  746. LoopControlException(LoopControlType control_type)
  747. : std::runtime_error((control_type == LoopControlType::Continue ? "continue" : "break") + std::string(" outside of a loop")),
  748. control_type(control_type) {}
  749. };
  750. struct LoopControlTemplateToken : public TemplateToken {
  751. LoopControlType control_type;
  752. LoopControlTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, LoopControlType control_type) : TemplateToken(Type::Break, location, pre, post), control_type(control_type) {}
  753. };
  754. class TemplateNode {
  755. Location location_;
  756. protected:
  757. virtual void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const = 0;
  758. public:
  759. TemplateNode(const Location & location) : location_(location) {}
  760. void render(std::ostringstream & out, const std::shared_ptr<Context> & context) const {
  761. try {
  762. do_render(out, context);
  763. } catch (const LoopControlException & e) {
  764. // TODO: make stack creation lazy. Only needed if it was thrown outside of a loop.
  765. std::ostringstream err;
  766. err << e.what();
  767. if (location_.source) err << error_location_suffix(*location_.source, location_.pos);
  768. throw LoopControlException(err.str(), e.control_type);
  769. } catch (const std::exception & e) {
  770. std::ostringstream err;
  771. err << e.what();
  772. if (location_.source) err << error_location_suffix(*location_.source, location_.pos);
  773. throw std::runtime_error(err.str());
  774. }
  775. }
  776. const Location & location() const { return location_; }
  777. virtual ~TemplateNode() = default;
  778. std::string render(const std::shared_ptr<Context> & context) const {
  779. std::ostringstream out;
  780. render(out, context);
  781. return out.str();
  782. }
  783. };
  784. class SequenceNode : public TemplateNode {
  785. std::vector<std::shared_ptr<TemplateNode>> children;
  786. public:
  787. SequenceNode(const Location & location, std::vector<std::shared_ptr<TemplateNode>> && c)
  788. : TemplateNode(location), children(std::move(c)) {}
  789. void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const override {
  790. for (const auto& child : children) child->render(out, context);
  791. }
  792. };
  793. class TextNode : public TemplateNode {
  794. std::string text;
  795. public:
  796. TextNode(const Location & location, const std::string& t) : TemplateNode(location), text(t) {}
  797. void do_render(std::ostringstream & out, const std::shared_ptr<Context> &) const override {
  798. out << text;
  799. }
  800. };
  801. class ExpressionNode : public TemplateNode {
  802. std::shared_ptr<Expression> expr;
  803. public:
  804. ExpressionNode(const Location & location, std::shared_ptr<Expression> && e) : TemplateNode(location), expr(std::move(e)) {}
  805. void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const override {
  806. if (!expr) throw std::runtime_error("ExpressionNode.expr is null");
  807. auto result = expr->evaluate(context);
  808. if (result.is_string()) {
  809. out << result.get<std::string>();
  810. } else if (result.is_boolean()) {
  811. out << (result.get<bool>() ? "True" : "False");
  812. } else if (!result.is_null()) {
  813. out << result.dump();
  814. }
  815. }
  816. };
  817. class IfNode : public TemplateNode {
  818. std::vector<std::pair<std::shared_ptr<Expression>, std::shared_ptr<TemplateNode>>> cascade;
  819. public:
  820. IfNode(const Location & location, std::vector<std::pair<std::shared_ptr<Expression>, std::shared_ptr<TemplateNode>>> && c)
  821. : TemplateNode(location), cascade(std::move(c)) {}
  822. void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const override {
  823. for (const auto& branch : cascade) {
  824. auto enter_branch = true;
  825. if (branch.first) {
  826. enter_branch = branch.first->evaluate(context).to_bool();
  827. }
  828. if (enter_branch) {
  829. if (!branch.second) throw std::runtime_error("IfNode.cascade.second is null");
  830. branch.second->render(out, context);
  831. return;
  832. }
  833. }
  834. }
  835. };
  836. class LoopControlNode : public TemplateNode {
  837. LoopControlType control_type_;
  838. public:
  839. LoopControlNode(const Location & location, LoopControlType control_type) : TemplateNode(location), control_type_(control_type) {}
  840. void do_render(std::ostringstream &, const std::shared_ptr<Context> &) const override {
  841. throw LoopControlException(control_type_);
  842. }
  843. };
  844. class ForNode : public TemplateNode {
  845. std::vector<std::string> var_names;
  846. std::shared_ptr<Expression> iterable;
  847. std::shared_ptr<Expression> condition;
  848. std::shared_ptr<TemplateNode> body;
  849. bool recursive;
  850. std::shared_ptr<TemplateNode> else_body;
  851. public:
  852. ForNode(const Location & location, std::vector<std::string> && var_names, std::shared_ptr<Expression> && iterable,
  853. std::shared_ptr<Expression> && condition, std::shared_ptr<TemplateNode> && body, bool recursive, std::shared_ptr<TemplateNode> && else_body)
  854. : 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)) {}
  855. void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const override {
  856. // https://jinja.palletsprojects.com/en/3.0.x/templates/#for
  857. if (!iterable) throw std::runtime_error("ForNode.iterable is null");
  858. if (!body) throw std::runtime_error("ForNode.body is null");
  859. auto iterable_value = iterable->evaluate(context);
  860. Value::CallableType loop_function;
  861. std::function<void(Value&)> visit = [&](Value& iter) {
  862. auto filtered_items = Value::array();
  863. if (!iter.is_null()) {
  864. if (!iterable_value.is_iterable()) {
  865. throw std::runtime_error("For loop iterable must be iterable: " + iterable_value.dump());
  866. }
  867. iterable_value.for_each([&](Value & item) {
  868. destructuring_assign(var_names, context, item);
  869. if (!condition || condition->evaluate(context).to_bool()) {
  870. filtered_items.push_back(item);
  871. }
  872. });
  873. }
  874. if (filtered_items.empty()) {
  875. if (else_body) {
  876. else_body->render(out, context);
  877. }
  878. } else {
  879. auto loop = recursive ? Value::callable(loop_function) : Value::object();
  880. loop.set("length", (int64_t) filtered_items.size());
  881. size_t cycle_index = 0;
  882. loop.set("cycle", Value::callable([&](const std::shared_ptr<Context> &, ArgumentsValue & args) {
  883. if (args.args.empty() || !args.kwargs.empty()) {
  884. throw std::runtime_error("cycle() expects at least 1 positional argument and no named arg");
  885. }
  886. auto item = args.args[cycle_index];
  887. cycle_index = (cycle_index + 1) % args.args.size();
  888. return item;
  889. }));
  890. auto loop_context = Context::make(Value::object(), context);
  891. loop_context->set("loop", loop);
  892. for (size_t i = 0, n = filtered_items.size(); i < n; ++i) {
  893. auto & item = filtered_items.at(i);
  894. destructuring_assign(var_names, loop_context, item);
  895. loop.set("index", (int64_t) i + 1);
  896. loop.set("index0", (int64_t) i);
  897. loop.set("revindex", (int64_t) (n - i));
  898. loop.set("revindex0", (int64_t) (n - i - 1));
  899. loop.set("length", (int64_t) n);
  900. loop.set("first", i == 0);
  901. loop.set("last", i == (n - 1));
  902. loop.set("previtem", i > 0 ? filtered_items.at(i - 1) : Value());
  903. loop.set("nextitem", i < n - 1 ? filtered_items.at(i + 1) : Value());
  904. try {
  905. body->render(out, loop_context);
  906. } catch (const LoopControlException & e) {
  907. if (e.control_type == LoopControlType::Break) break;
  908. if (e.control_type == LoopControlType::Continue) continue;
  909. }
  910. }
  911. }
  912. };
  913. if (recursive) {
  914. loop_function = [&](const std::shared_ptr<Context> &, ArgumentsValue & args) {
  915. if (args.args.size() != 1 || !args.kwargs.empty() || !args.args[0].is_array()) {
  916. throw std::runtime_error("loop() expects exactly 1 positional iterable argument");
  917. }
  918. auto & items = args.args[0];
  919. visit(items);
  920. return Value();
  921. };
  922. }
  923. visit(iterable_value);
  924. }
  925. };
  926. class MacroNode : public TemplateNode {
  927. std::shared_ptr<VariableExpr> name;
  928. Expression::Parameters params;
  929. std::shared_ptr<TemplateNode> body;
  930. std::unordered_map<std::string, size_t> named_param_positions;
  931. public:
  932. MacroNode(const Location & location, std::shared_ptr<VariableExpr> && n, Expression::Parameters && p, std::shared_ptr<TemplateNode> && b)
  933. : TemplateNode(location), name(std::move(n)), params(std::move(p)), body(std::move(b)) {
  934. for (size_t i = 0; i < params.size(); ++i) {
  935. const auto & name = params[i].first;
  936. if (!name.empty()) {
  937. named_param_positions[name] = i;
  938. }
  939. }
  940. }
  941. void do_render(std::ostringstream &, const std::shared_ptr<Context> & macro_context) const override {
  942. if (!name) throw std::runtime_error("MacroNode.name is null");
  943. if (!body) throw std::runtime_error("MacroNode.body is null");
  944. auto callable = Value::callable([&](const std::shared_ptr<Context> & context, ArgumentsValue & args) {
  945. auto call_context = macro_context;
  946. std::vector<bool> param_set(params.size(), false);
  947. for (size_t i = 0, n = args.args.size(); i < n; i++) {
  948. auto & arg = args.args[i];
  949. if (i >= params.size()) throw std::runtime_error("Too many positional arguments for macro " + name->get_name());
  950. param_set[i] = true;
  951. auto & param_name = params[i].first;
  952. call_context->set(param_name, arg);
  953. }
  954. for (auto & [arg_name, value] : args.kwargs) {
  955. auto it = named_param_positions.find(arg_name);
  956. if (it == named_param_positions.end()) throw std::runtime_error("Unknown parameter name for macro " + name->get_name() + ": " + arg_name);
  957. call_context->set(arg_name, value);
  958. param_set[it->second] = true;
  959. }
  960. // Set default values for parameters that were not passed
  961. for (size_t i = 0, n = params.size(); i < n; i++) {
  962. if (!param_set[i] && params[i].second != nullptr) {
  963. auto val = params[i].second->evaluate(context);
  964. call_context->set(params[i].first, val);
  965. }
  966. }
  967. return body->render(call_context);
  968. });
  969. macro_context->set(name->get_name(), callable);
  970. }
  971. };
  972. class FilterNode : public TemplateNode {
  973. std::shared_ptr<Expression> filter;
  974. std::shared_ptr<TemplateNode> body;
  975. public:
  976. FilterNode(const Location & location, std::shared_ptr<Expression> && f, std::shared_ptr<TemplateNode> && b)
  977. : TemplateNode(location), filter(std::move(f)), body(std::move(b)) {}
  978. void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const override {
  979. if (!filter) throw std::runtime_error("FilterNode.filter is null");
  980. if (!body) throw std::runtime_error("FilterNode.body is null");
  981. auto filter_value = filter->evaluate(context);
  982. if (!filter_value.is_callable()) {
  983. throw std::runtime_error("Filter must be a callable: " + filter_value.dump());
  984. }
  985. std::string rendered_body = body->render(context);
  986. ArgumentsValue filter_args = {{Value(rendered_body)}, {}};
  987. auto result = filter_value.call(context, filter_args);
  988. out << result.to_str();
  989. }
  990. };
  991. class SetNode : public TemplateNode {
  992. std::string ns;
  993. std::vector<std::string> var_names;
  994. std::shared_ptr<Expression> value;
  995. public:
  996. SetNode(const Location & location, const std::string & ns, const std::vector<std::string> & vns, std::shared_ptr<Expression> && v)
  997. : TemplateNode(location), ns(ns), var_names(vns), value(std::move(v)) {}
  998. void do_render(std::ostringstream &, const std::shared_ptr<Context> & context) const override {
  999. if (!value) throw std::runtime_error("SetNode.value is null");
  1000. if (!ns.empty()) {
  1001. if (var_names.size() != 1) {
  1002. throw std::runtime_error("Namespaced set only supports a single variable name");
  1003. }
  1004. auto & name = var_names[0];
  1005. auto ns_value = context->get(ns);
  1006. if (!ns_value.is_object()) throw std::runtime_error("Namespace '" + ns + "' is not an object");
  1007. ns_value.set(name, this->value->evaluate(context));
  1008. } else {
  1009. auto val = value->evaluate(context);
  1010. destructuring_assign(var_names, context, val);
  1011. }
  1012. }
  1013. };
  1014. class SetTemplateNode : public TemplateNode {
  1015. std::string name;
  1016. std::shared_ptr<TemplateNode> template_value;
  1017. public:
  1018. SetTemplateNode(const Location & location, const std::string & name, std::shared_ptr<TemplateNode> && tv)
  1019. : TemplateNode(location), name(name), template_value(std::move(tv)) {}
  1020. void do_render(std::ostringstream &, const std::shared_ptr<Context> & context) const override {
  1021. if (!template_value) throw std::runtime_error("SetTemplateNode.template_value is null");
  1022. Value value { template_value->render(context) };
  1023. context->set(name, value);
  1024. }
  1025. };
  1026. class IfExpr : public Expression {
  1027. std::shared_ptr<Expression> condition;
  1028. std::shared_ptr<Expression> then_expr;
  1029. std::shared_ptr<Expression> else_expr;
  1030. public:
  1031. IfExpr(const Location & location, std::shared_ptr<Expression> && c, std::shared_ptr<Expression> && t, std::shared_ptr<Expression> && e)
  1032. : Expression(location), condition(std::move(c)), then_expr(std::move(t)), else_expr(std::move(e)) {}
  1033. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1034. if (!condition) throw std::runtime_error("IfExpr.condition is null");
  1035. if (!then_expr) throw std::runtime_error("IfExpr.then_expr is null");
  1036. if (condition->evaluate(context).to_bool()) {
  1037. return then_expr->evaluate(context);
  1038. }
  1039. if (else_expr) {
  1040. return else_expr->evaluate(context);
  1041. }
  1042. return nullptr;
  1043. }
  1044. };
  1045. class LiteralExpr : public Expression {
  1046. Value value;
  1047. public:
  1048. LiteralExpr(const Location & location, const Value& v)
  1049. : Expression(location), value(v) {}
  1050. Value do_evaluate(const std::shared_ptr<Context> &) const override { return value; }
  1051. };
  1052. class ArrayExpr : public Expression {
  1053. std::vector<std::shared_ptr<Expression>> elements;
  1054. public:
  1055. ArrayExpr(const Location & location, std::vector<std::shared_ptr<Expression>> && e)
  1056. : Expression(location), elements(std::move(e)) {}
  1057. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1058. auto result = Value::array();
  1059. for (const auto& e : elements) {
  1060. if (!e) throw std::runtime_error("Array element is null");
  1061. result.push_back(e->evaluate(context));
  1062. }
  1063. return result;
  1064. }
  1065. };
  1066. class DictExpr : public Expression {
  1067. std::vector<std::pair<std::shared_ptr<Expression>, std::shared_ptr<Expression>>> elements;
  1068. public:
  1069. DictExpr(const Location & location, std::vector<std::pair<std::shared_ptr<Expression>, std::shared_ptr<Expression>>> && e)
  1070. : Expression(location), elements(std::move(e)) {}
  1071. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1072. auto result = Value::object();
  1073. for (const auto& [key, value] : elements) {
  1074. if (!key) throw std::runtime_error("Dict key is null");
  1075. if (!value) throw std::runtime_error("Dict value is null");
  1076. result.set(key->evaluate(context), value->evaluate(context));
  1077. }
  1078. return result;
  1079. }
  1080. };
  1081. class SliceExpr : public Expression {
  1082. public:
  1083. std::shared_ptr<Expression> start, end;
  1084. SliceExpr(const Location & location, std::shared_ptr<Expression> && s, std::shared_ptr<Expression> && e)
  1085. : Expression(location), start(std::move(s)), end(std::move(e)) {}
  1086. Value do_evaluate(const std::shared_ptr<Context> &) const override {
  1087. throw std::runtime_error("SliceExpr not implemented");
  1088. }
  1089. };
  1090. class SubscriptExpr : public Expression {
  1091. std::shared_ptr<Expression> base;
  1092. std::shared_ptr<Expression> index;
  1093. public:
  1094. SubscriptExpr(const Location & location, std::shared_ptr<Expression> && b, std::shared_ptr<Expression> && i)
  1095. : Expression(location), base(std::move(b)), index(std::move(i)) {}
  1096. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1097. if (!base) throw std::runtime_error("SubscriptExpr.base is null");
  1098. if (!index) throw std::runtime_error("SubscriptExpr.index is null");
  1099. auto target_value = base->evaluate(context);
  1100. if (auto slice = dynamic_cast<SliceExpr*>(index.get())) {
  1101. auto start = slice->start ? slice->start->evaluate(context).get<int64_t>() : 0;
  1102. auto end = slice->end ? slice->end->evaluate(context).get<int64_t>() : (int64_t) target_value.size();
  1103. if (target_value.is_string()) {
  1104. std::string s = target_value.get<std::string>();
  1105. if (start < 0) start = s.size() + start;
  1106. if (end < 0) end = s.size() + end;
  1107. return s.substr(start, end - start);
  1108. } else if (target_value.is_array()) {
  1109. if (start < 0) start = target_value.size() + start;
  1110. if (end < 0) end = target_value.size() + end;
  1111. auto result = Value::array();
  1112. for (auto i = start; i < end; ++i) {
  1113. result.push_back(target_value.at(i));
  1114. }
  1115. return result;
  1116. } else {
  1117. throw std::runtime_error(target_value.is_null() ? "Cannot subscript null" : "Subscripting only supported on arrays and strings");
  1118. }
  1119. } else {
  1120. auto index_value = index->evaluate(context);
  1121. if (target_value.is_null()) {
  1122. if (auto t = dynamic_cast<VariableExpr*>(base.get())) {
  1123. throw std::runtime_error("'" + t->get_name() + "' is " + (context->contains(t->get_name()) ? "null" : "not defined"));
  1124. }
  1125. throw std::runtime_error("Trying to access property '" + index_value.dump() + "' on null!");
  1126. }
  1127. return target_value.get(index_value);
  1128. }
  1129. }
  1130. };
  1131. class UnaryOpExpr : public Expression {
  1132. public:
  1133. enum class Op { Plus, Minus, LogicalNot, Expansion, ExpansionDict };
  1134. std::shared_ptr<Expression> expr;
  1135. Op op;
  1136. UnaryOpExpr(const Location & location, std::shared_ptr<Expression> && e, Op o)
  1137. : Expression(location), expr(std::move(e)), op(o) {}
  1138. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1139. if (!expr) throw std::runtime_error("UnaryOpExpr.expr is null");
  1140. auto e = expr->evaluate(context);
  1141. switch (op) {
  1142. case Op::Plus: return e;
  1143. case Op::Minus: return -e;
  1144. case Op::LogicalNot: return !e.to_bool();
  1145. case Op::Expansion:
  1146. case Op::ExpansionDict:
  1147. throw std::runtime_error("Expansion operator is only supported in function calls and collections");
  1148. }
  1149. throw std::runtime_error("Unknown unary operator");
  1150. }
  1151. };
  1152. class BinaryOpExpr : public Expression {
  1153. public:
  1154. enum class Op { StrConcat, Add, Sub, Mul, MulMul, Div, DivDiv, Mod, Eq, Ne, Lt, Gt, Le, Ge, And, Or, In, NotIn, Is, IsNot };
  1155. private:
  1156. std::shared_ptr<Expression> left;
  1157. std::shared_ptr<Expression> right;
  1158. Op op;
  1159. public:
  1160. BinaryOpExpr(const Location & location, std::shared_ptr<Expression> && l, std::shared_ptr<Expression> && r, Op o)
  1161. : Expression(location), left(std::move(l)), right(std::move(r)), op(o) {}
  1162. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1163. if (!left) throw std::runtime_error("BinaryOpExpr.left is null");
  1164. if (!right) throw std::runtime_error("BinaryOpExpr.right is null");
  1165. auto l = left->evaluate(context);
  1166. auto do_eval = [&](const Value & l) -> Value {
  1167. if (op == Op::Is || op == Op::IsNot) {
  1168. auto t = dynamic_cast<VariableExpr*>(right.get());
  1169. if (!t) throw std::runtime_error("Right side of 'is' operator must be a variable");
  1170. auto eval = [&]() {
  1171. const auto & name = t->get_name();
  1172. if (name == "none") return l.is_null();
  1173. if (name == "boolean") return l.is_boolean();
  1174. if (name == "integer") return l.is_number_integer();
  1175. if (name == "float") return l.is_number_float();
  1176. if (name == "number") return l.is_number();
  1177. if (name == "string") return l.is_string();
  1178. if (name == "mapping") return l.is_object();
  1179. if (name == "iterable") return l.is_iterable();
  1180. if (name == "sequence") return l.is_array();
  1181. if (name == "defined") return !l.is_null();
  1182. throw std::runtime_error("Unknown type for 'is' operator: " + name);
  1183. };
  1184. auto value = eval();
  1185. return Value(op == Op::Is ? value : !value);
  1186. }
  1187. if (op == Op::And) {
  1188. if (!l.to_bool()) return Value(false);
  1189. return right->evaluate(context).to_bool();
  1190. } else if (op == Op::Or) {
  1191. if (l.to_bool()) return l;
  1192. return right->evaluate(context);
  1193. }
  1194. auto r = right->evaluate(context);
  1195. switch (op) {
  1196. case Op::StrConcat: return l.to_str() + r.to_str();
  1197. case Op::Add: return l + r;
  1198. case Op::Sub: return l - r;
  1199. case Op::Mul: return l * r;
  1200. case Op::Div: return l / r;
  1201. case Op::MulMul: return std::pow(l.get<double>(), r.get<double>());
  1202. case Op::DivDiv: return l.get<int64_t>() / r.get<int64_t>();
  1203. case Op::Mod: return l.get<int64_t>() % r.get<int64_t>();
  1204. case Op::Eq: return l == r;
  1205. case Op::Ne: return l != r;
  1206. case Op::Lt: return l < r;
  1207. case Op::Gt: return l > r;
  1208. case Op::Le: return l <= r;
  1209. case Op::Ge: return l >= r;
  1210. case Op::In: return (r.is_array() || r.is_object()) && r.contains(l);
  1211. case Op::NotIn: return !(r.is_array() && r.contains(l));
  1212. default: break;
  1213. }
  1214. throw std::runtime_error("Unknown binary operator");
  1215. };
  1216. if (l.is_callable()) {
  1217. return Value::callable([l, do_eval](const std::shared_ptr<Context> & context, ArgumentsValue & args) {
  1218. auto ll = l.call(context, args);
  1219. return do_eval(ll); //args[0].second);
  1220. });
  1221. } else {
  1222. return do_eval(l);
  1223. }
  1224. }
  1225. };
  1226. struct ArgumentsExpression {
  1227. std::vector<std::shared_ptr<Expression>> args;
  1228. std::vector<std::pair<std::string, std::shared_ptr<Expression>>> kwargs;
  1229. ArgumentsValue evaluate(const std::shared_ptr<Context> & context) const {
  1230. ArgumentsValue vargs;
  1231. for (const auto& arg : this->args) {
  1232. if (auto un_expr = std::dynamic_pointer_cast<UnaryOpExpr>(arg)) {
  1233. if (un_expr->op == UnaryOpExpr::Op::Expansion) {
  1234. auto array = un_expr->expr->evaluate(context);
  1235. if (!array.is_array()) {
  1236. throw std::runtime_error("Expansion operator only supported on arrays");
  1237. }
  1238. array.for_each([&](Value & value) {
  1239. vargs.args.push_back(value);
  1240. });
  1241. continue;
  1242. } else if (un_expr->op == UnaryOpExpr::Op::ExpansionDict) {
  1243. auto dict = un_expr->expr->evaluate(context);
  1244. if (!dict.is_object()) {
  1245. throw std::runtime_error("ExpansionDict operator only supported on objects");
  1246. }
  1247. dict.for_each([&](const Value & key) {
  1248. vargs.kwargs.push_back({key.get<std::string>(), dict.at(key)});
  1249. });
  1250. continue;
  1251. }
  1252. }
  1253. vargs.args.push_back(arg->evaluate(context));
  1254. }
  1255. for (const auto& [name, value] : this->kwargs) {
  1256. vargs.kwargs.push_back({name, value->evaluate(context)});
  1257. }
  1258. return vargs;
  1259. }
  1260. };
  1261. static std::string strip(const std::string & s, const std::string & chars = "", bool left = true, bool right = true) {
  1262. auto charset = chars.empty() ? " \t\n\r" : chars;
  1263. auto start = left ? s.find_first_not_of(charset) : 0;
  1264. if (start == std::string::npos) return "";
  1265. auto end = right ? s.find_last_not_of(charset) : s.size() - 1;
  1266. return s.substr(start, end - start + 1);
  1267. }
  1268. static std::vector<std::string> split(const std::string & s, const std::string & sep) {
  1269. std::vector<std::string> result;
  1270. size_t start = 0;
  1271. size_t end = s.find(sep);
  1272. while (end != std::string::npos) {
  1273. result.push_back(s.substr(start, end - start));
  1274. start = end + sep.length();
  1275. end = s.find(sep, start);
  1276. }
  1277. result.push_back(s.substr(start));
  1278. return result;
  1279. }
  1280. static std::string capitalize(const std::string & s) {
  1281. if (s.empty()) return s;
  1282. auto result = s;
  1283. result[0] = std::toupper(result[0]);
  1284. return result;
  1285. }
  1286. static std::string html_escape(const std::string & s) {
  1287. std::string result;
  1288. result.reserve(s.size());
  1289. for (const auto & c : s) {
  1290. switch (c) {
  1291. case '&': result += "&amp;"; break;
  1292. case '<': result += "&lt;"; break;
  1293. case '>': result += "&gt;"; break;
  1294. case '"': result += "&#34;"; break;
  1295. case '\'': result += "&apos;"; break;
  1296. default: result += c; break;
  1297. }
  1298. }
  1299. return result;
  1300. }
  1301. class MethodCallExpr : public Expression {
  1302. std::shared_ptr<Expression> object;
  1303. std::shared_ptr<VariableExpr> method;
  1304. ArgumentsExpression args;
  1305. public:
  1306. MethodCallExpr(const Location & location, std::shared_ptr<Expression> && obj, std::shared_ptr<VariableExpr> && m, ArgumentsExpression && a)
  1307. : Expression(location), object(std::move(obj)), method(std::move(m)), args(std::move(a)) {}
  1308. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1309. if (!object) throw std::runtime_error("MethodCallExpr.object is null");
  1310. if (!method) throw std::runtime_error("MethodCallExpr.method is null");
  1311. auto obj = object->evaluate(context);
  1312. auto vargs = args.evaluate(context);
  1313. if (obj.is_null()) {
  1314. throw std::runtime_error("Trying to call method '" + method->get_name() + "' on null");
  1315. }
  1316. if (obj.is_array()) {
  1317. if (method->get_name() == "append") {
  1318. vargs.expectArgs("append method", {1, 1}, {0, 0});
  1319. obj.push_back(vargs.args[0]);
  1320. return Value();
  1321. } else if (method->get_name() == "pop") {
  1322. vargs.expectArgs("pop method", {0, 1}, {0, 0});
  1323. return obj.pop(vargs.args.empty() ? Value() : vargs.args[0]);
  1324. } else if (method->get_name() == "insert") {
  1325. vargs.expectArgs("insert method", {2, 2}, {0, 0});
  1326. auto index = vargs.args[0].get<int64_t>();
  1327. if (index < 0 || index > (int64_t) obj.size()) throw std::runtime_error("Index out of range for insert method");
  1328. obj.insert(index, vargs.args[1]);
  1329. return Value();
  1330. }
  1331. } else if (obj.is_object()) {
  1332. if (method->get_name() == "items") {
  1333. vargs.expectArgs("items method", {0, 0}, {0, 0});
  1334. auto result = Value::array();
  1335. for (const auto& key : obj.keys()) {
  1336. result.push_back(Value::array({key, obj.at(key)}));
  1337. }
  1338. return result;
  1339. } else if (method->get_name() == "pop") {
  1340. vargs.expectArgs("pop method", {1, 1}, {0, 0});
  1341. return obj.pop(vargs.args[0]);
  1342. } else if (method->get_name() == "get") {
  1343. vargs.expectArgs("get method", {1, 2}, {0, 0});
  1344. auto key = vargs.args[0];
  1345. if (vargs.args.size() == 1) {
  1346. return obj.contains(key) ? obj.at(key) : Value();
  1347. } else {
  1348. return obj.contains(key) ? obj.at(key) : vargs.args[1];
  1349. }
  1350. } else if (obj.contains(method->get_name())) {
  1351. auto callable = obj.at(method->get_name());
  1352. if (!callable.is_callable()) {
  1353. throw std::runtime_error("Property '" + method->get_name() + "' is not callable");
  1354. }
  1355. return callable.call(context, vargs);
  1356. }
  1357. } else if (obj.is_string()) {
  1358. auto str = obj.get<std::string>();
  1359. if (method->get_name() == "strip") {
  1360. vargs.expectArgs("strip method", {0, 1}, {0, 0});
  1361. auto chars = vargs.args.empty() ? "" : vargs.args[0].get<std::string>();
  1362. return Value(strip(str, chars));
  1363. } else if (method->get_name() == "lstrip") {
  1364. vargs.expectArgs("lstrip method", {0, 1}, {0, 0});
  1365. auto chars = vargs.args.empty() ? "" : vargs.args[0].get<std::string>();
  1366. return Value(strip(str, chars, /* left= */ true, /* right= */ false));
  1367. } else if (method->get_name() == "rstrip") {
  1368. vargs.expectArgs("rstrip method", {0, 1}, {0, 0});
  1369. auto chars = vargs.args.empty() ? "" : vargs.args[0].get<std::string>();
  1370. return Value(strip(str, chars, /* left= */ false, /* right= */ true));
  1371. } else if (method->get_name() == "split") {
  1372. vargs.expectArgs("split method", {1, 1}, {0, 0});
  1373. auto sep = vargs.args[0].get<std::string>();
  1374. auto parts = split(str, sep);
  1375. Value result = Value::array();
  1376. for (const auto& part : parts) {
  1377. result.push_back(Value(part));
  1378. }
  1379. return result;
  1380. } else if (method->get_name() == "capitalize") {
  1381. vargs.expectArgs("capitalize method", {0, 0}, {0, 0});
  1382. return Value(capitalize(str));
  1383. } else if (method->get_name() == "endswith") {
  1384. vargs.expectArgs("endswith method", {1, 1}, {0, 0});
  1385. auto suffix = vargs.args[0].get<std::string>();
  1386. return suffix.length() <= str.length() && std::equal(suffix.rbegin(), suffix.rend(), str.rbegin());
  1387. } else if (method->get_name() == "title") {
  1388. vargs.expectArgs("title method", {0, 0}, {0, 0});
  1389. auto res = str;
  1390. for (size_t i = 0, n = res.size(); i < n; ++i) {
  1391. if (i == 0 || std::isspace(res[i - 1])) res[i] = std::toupper(res[i]);
  1392. else res[i] = std::tolower(res[i]);
  1393. }
  1394. return res;
  1395. }
  1396. }
  1397. throw std::runtime_error("Unknown method: " + method->get_name());
  1398. }
  1399. };
  1400. class CallExpr : public Expression {
  1401. public:
  1402. std::shared_ptr<Expression> object;
  1403. ArgumentsExpression args;
  1404. CallExpr(const Location & location, std::shared_ptr<Expression> && obj, ArgumentsExpression && a)
  1405. : Expression(location), object(std::move(obj)), args(std::move(a)) {}
  1406. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1407. if (!object) throw std::runtime_error("CallExpr.object is null");
  1408. auto obj = object->evaluate(context);
  1409. if (!obj.is_callable()) {
  1410. throw std::runtime_error("Object is not callable: " + obj.dump(2));
  1411. }
  1412. auto vargs = args.evaluate(context);
  1413. return obj.call(context, vargs);
  1414. }
  1415. };
  1416. class FilterExpr : public Expression {
  1417. std::vector<std::shared_ptr<Expression>> parts;
  1418. public:
  1419. FilterExpr(const Location & location, std::vector<std::shared_ptr<Expression>> && p)
  1420. : Expression(location), parts(std::move(p)) {}
  1421. Value do_evaluate(const std::shared_ptr<Context> & context) const override {
  1422. Value result;
  1423. bool first = true;
  1424. for (const auto& part : parts) {
  1425. if (!part) throw std::runtime_error("FilterExpr.part is null");
  1426. if (first) {
  1427. first = false;
  1428. result = part->evaluate(context);
  1429. } else {
  1430. if (auto ce = dynamic_cast<CallExpr*>(part.get())) {
  1431. auto target = ce->object->evaluate(context);
  1432. ArgumentsValue args = ce->args.evaluate(context);
  1433. args.args.insert(args.args.begin(), result);
  1434. result = target.call(context, args);
  1435. } else {
  1436. auto callable = part->evaluate(context);
  1437. ArgumentsValue args;
  1438. args.args.insert(args.args.begin(), result);
  1439. result = callable.call(context, args);
  1440. }
  1441. }
  1442. }
  1443. return result;
  1444. }
  1445. void prepend(std::shared_ptr<Expression> && e) {
  1446. parts.insert(parts.begin(), std::move(e));
  1447. }
  1448. };
  1449. class Parser {
  1450. private:
  1451. using CharIterator = std::string::const_iterator;
  1452. std::shared_ptr<std::string> template_str;
  1453. CharIterator start, end, it;
  1454. Options options;
  1455. Parser(const std::shared_ptr<std::string>& template_str, const Options & options) : template_str(template_str), options(options) {
  1456. if (!template_str) throw std::runtime_error("Template string is null");
  1457. start = it = this->template_str->begin();
  1458. end = this->template_str->end();
  1459. }
  1460. bool consumeSpaces(SpaceHandling space_handling = SpaceHandling::Strip) {
  1461. if (space_handling == SpaceHandling::Strip) {
  1462. while (it != end && std::isspace(*it)) ++it;
  1463. }
  1464. return true;
  1465. }
  1466. std::unique_ptr<std::string> parseString() {
  1467. auto doParse = [&](char quote) -> std::unique_ptr<std::string> {
  1468. if (it == end || *it != quote) return nullptr;
  1469. std::string result;
  1470. bool escape = false;
  1471. for (++it; it != end; ++it) {
  1472. if (escape) {
  1473. escape = false;
  1474. switch (*it) {
  1475. case 'n': result += '\n'; break;
  1476. case 'r': result += '\r'; break;
  1477. case 't': result += '\t'; break;
  1478. case 'b': result += '\b'; break;
  1479. case 'f': result += '\f'; break;
  1480. case '\\': result += '\\'; break;
  1481. default:
  1482. if (*it == quote) {
  1483. result += quote;
  1484. } else {
  1485. result += *it;
  1486. }
  1487. break;
  1488. }
  1489. } else if (*it == '\\') {
  1490. escape = true;
  1491. } else if (*it == quote) {
  1492. ++it;
  1493. return std::make_unique<std::string>(std::move(result));
  1494. } else {
  1495. result += *it;
  1496. }
  1497. }
  1498. return nullptr;
  1499. };
  1500. consumeSpaces();
  1501. if (it == end) return nullptr;
  1502. if (*it == '"') return doParse('"');
  1503. if (*it == '\'') return doParse('\'');
  1504. return nullptr;
  1505. }
  1506. json parseNumber(CharIterator& it, const CharIterator& end) {
  1507. auto before = it;
  1508. consumeSpaces();
  1509. auto start = it;
  1510. bool hasDecimal = false;
  1511. bool hasExponent = false;
  1512. if (it != end && (*it == '-' || *it == '+')) ++it;
  1513. while (it != end) {
  1514. if (std::isdigit(*it)) {
  1515. ++it;
  1516. } else if (*it == '.') {
  1517. if (hasDecimal) throw std::runtime_error("Multiple decimal points");
  1518. hasDecimal = true;
  1519. ++it;
  1520. } else if (it != start && (*it == 'e' || *it == 'E')) {
  1521. if (hasExponent) throw std::runtime_error("Multiple exponents");
  1522. hasExponent = true;
  1523. ++it;
  1524. } else {
  1525. break;
  1526. }
  1527. }
  1528. if (start == it) {
  1529. it = before;
  1530. return json(); // No valid characters found
  1531. }
  1532. std::string str(start, it);
  1533. try {
  1534. return json::parse(str);
  1535. } catch (json::parse_error& e) {
  1536. throw std::runtime_error("Failed to parse number: '" + str + "' (" + std::string(e.what()) + ")");
  1537. return json();
  1538. }
  1539. }
  1540. /** integer, float, bool, string */
  1541. std::shared_ptr<Value> parseConstant() {
  1542. auto start = it;
  1543. consumeSpaces();
  1544. if (it == end) return nullptr;
  1545. if (*it == '"' || *it == '\'') {
  1546. auto str = parseString();
  1547. if (str) return std::make_shared<Value>(*str);
  1548. }
  1549. static std::regex prim_tok(R"(true\b|True\b|false\b|False\b|None\b)");
  1550. auto token = consumeToken(prim_tok);
  1551. if (!token.empty()) {
  1552. if (token == "true" || token == "True") return std::make_shared<Value>(true);
  1553. if (token == "false" || token == "False") return std::make_shared<Value>(false);
  1554. if (token == "None") return std::make_shared<Value>(nullptr);
  1555. throw std::runtime_error("Unknown constant token: " + token);
  1556. }
  1557. auto number = parseNumber(it, end);
  1558. if (!number.is_null()) return std::make_shared<Value>(number);
  1559. it = start;
  1560. return nullptr;
  1561. }
  1562. class expression_parsing_error : public std::runtime_error {
  1563. const CharIterator it;
  1564. public:
  1565. expression_parsing_error(const std::string & message, const CharIterator & it)
  1566. : std::runtime_error(message), it(it) {}
  1567. size_t get_pos(const CharIterator & begin) const {
  1568. return std::distance(begin, it);
  1569. }
  1570. };
  1571. bool peekSymbols(const std::vector<std::string> & symbols) const {
  1572. for (const auto & symbol : symbols) {
  1573. if (std::distance(it, end) >= (int64_t) symbol.size() && std::string(it, it + symbol.size()) == symbol) {
  1574. return true;
  1575. }
  1576. }
  1577. return false;
  1578. }
  1579. std::vector<std::string> consumeTokenGroups(const std::regex & regex, SpaceHandling space_handling = SpaceHandling::Strip) {
  1580. auto start = it;
  1581. consumeSpaces(space_handling);
  1582. std::smatch match;
  1583. if (std::regex_search(it, end, match, regex) && match.position() == 0) {
  1584. it += match[0].length();
  1585. std::vector<std::string> ret;
  1586. for (size_t i = 0, n = match.size(); i < n; ++i) {
  1587. ret.push_back(match[i].str());
  1588. }
  1589. return ret;
  1590. }
  1591. it = start;
  1592. return {};
  1593. }
  1594. std::string consumeToken(const std::regex & regex, SpaceHandling space_handling = SpaceHandling::Strip) {
  1595. auto start = it;
  1596. consumeSpaces(space_handling);
  1597. std::smatch match;
  1598. if (std::regex_search(it, end, match, regex) && match.position() == 0) {
  1599. it += match[0].length();
  1600. return match[0].str();
  1601. }
  1602. it = start;
  1603. return "";
  1604. }
  1605. std::string consumeToken(const std::string & token, SpaceHandling space_handling = SpaceHandling::Strip) {
  1606. auto start = it;
  1607. consumeSpaces(space_handling);
  1608. if (std::distance(it, end) >= (int64_t) token.size() && std::string(it, it + token.size()) == token) {
  1609. it += token.size();
  1610. return token;
  1611. }
  1612. it = start;
  1613. return "";
  1614. }
  1615. std::shared_ptr<Expression> parseExpression(bool allow_if_expr = true) {
  1616. auto left = parseLogicalOr();
  1617. if (it == end) return left;
  1618. if (!allow_if_expr) return left;
  1619. static std::regex if_tok(R"(if\b)");
  1620. if (consumeToken(if_tok).empty()) {
  1621. return left;
  1622. }
  1623. auto location = get_location();
  1624. auto [condition, else_expr] = parseIfExpression();
  1625. return std::make_shared<IfExpr>(location, std::move(condition), std::move(left), std::move(else_expr));
  1626. }
  1627. Location get_location() const {
  1628. return {template_str, (size_t) std::distance(start, it)};
  1629. }
  1630. std::pair<std::shared_ptr<Expression>, std::shared_ptr<Expression>> parseIfExpression() {
  1631. auto condition = parseLogicalOr();
  1632. if (!condition) throw std::runtime_error("Expected condition expression");
  1633. static std::regex else_tok(R"(else\b)");
  1634. std::shared_ptr<Expression> else_expr;
  1635. if (!consumeToken(else_tok).empty()) {
  1636. else_expr = parseExpression();
  1637. if (!else_expr) throw std::runtime_error("Expected 'else' expression");
  1638. }
  1639. return std::pair(std::move(condition), std::move(else_expr));
  1640. }
  1641. std::shared_ptr<Expression> parseLogicalOr() {
  1642. auto left = parseLogicalAnd();
  1643. if (!left) throw std::runtime_error("Expected left side of 'logical or' expression");
  1644. static std::regex or_tok(R"(or\b)");
  1645. auto location = get_location();
  1646. while (!consumeToken(or_tok).empty()) {
  1647. auto right = parseLogicalAnd();
  1648. if (!right) throw std::runtime_error("Expected right side of 'or' expression");
  1649. left = std::make_shared<BinaryOpExpr>(location, std::move(left), std::move(right), BinaryOpExpr::Op::Or);
  1650. }
  1651. return left;
  1652. }
  1653. std::shared_ptr<Expression> parseLogicalNot() {
  1654. static std::regex not_tok(R"(not\b)");
  1655. auto location = get_location();
  1656. if (!consumeToken(not_tok).empty()) {
  1657. auto sub = parseLogicalNot();
  1658. if (!sub) throw std::runtime_error("Expected expression after 'not' keyword");
  1659. return std::make_shared<UnaryOpExpr>(location, std::move(sub), UnaryOpExpr::Op::LogicalNot);
  1660. }
  1661. return parseLogicalCompare();
  1662. }
  1663. std::shared_ptr<Expression> parseLogicalAnd() {
  1664. auto left = parseLogicalNot();
  1665. if (!left) throw std::runtime_error("Expected left side of 'logical and' expression");
  1666. static std::regex and_tok(R"(and\b)");
  1667. auto location = get_location();
  1668. while (!consumeToken(and_tok).empty()) {
  1669. auto right = parseLogicalNot();
  1670. if (!right) throw std::runtime_error("Expected right side of 'and' expression");
  1671. left = std::make_shared<BinaryOpExpr>(location, std::move(left), std::move(right), BinaryOpExpr::Op::And);
  1672. }
  1673. return left;
  1674. }
  1675. std::shared_ptr<Expression> parseLogicalCompare() {
  1676. auto left = parseStringConcat();
  1677. if (!left) throw std::runtime_error("Expected left side of 'logical compare' expression");
  1678. static std::regex compare_tok(R"(==|!=|<=?|>=?|in\b|is\b|not\s+in\b)");
  1679. static std::regex not_tok(R"(not\b)");
  1680. std::string op_str;
  1681. while (!(op_str = consumeToken(compare_tok)).empty()) {
  1682. auto location = get_location();
  1683. if (op_str == "is") {
  1684. auto negated = !consumeToken(not_tok).empty();
  1685. auto identifier = parseIdentifier();
  1686. if (!identifier) throw std::runtime_error("Expected identifier after 'is' keyword");
  1687. return std::make_shared<BinaryOpExpr>(
  1688. left->location,
  1689. std::move(left), std::move(identifier),
  1690. negated ? BinaryOpExpr::Op::IsNot : BinaryOpExpr::Op::Is);
  1691. }
  1692. auto right = parseStringConcat();
  1693. if (!right) throw std::runtime_error("Expected right side of 'logical compare' expression");
  1694. BinaryOpExpr::Op op;
  1695. if (op_str == "==") op = BinaryOpExpr::Op::Eq;
  1696. else if (op_str == "!=") op = BinaryOpExpr::Op::Ne;
  1697. else if (op_str == "<") op = BinaryOpExpr::Op::Lt;
  1698. else if (op_str == ">") op = BinaryOpExpr::Op::Gt;
  1699. else if (op_str == "<=") op = BinaryOpExpr::Op::Le;
  1700. else if (op_str == ">=") op = BinaryOpExpr::Op::Ge;
  1701. else if (op_str == "in") op = BinaryOpExpr::Op::In;
  1702. else if (op_str.substr(0, 3) == "not") op = BinaryOpExpr::Op::NotIn;
  1703. else throw std::runtime_error("Unknown comparison operator: " + op_str);
  1704. left = std::make_shared<BinaryOpExpr>(get_location(), std::move(left), std::move(right), op);
  1705. }
  1706. return left;
  1707. }
  1708. Expression::Parameters parseParameters() {
  1709. consumeSpaces();
  1710. if (consumeToken("(").empty()) throw std::runtime_error("Expected opening parenthesis in param list");
  1711. Expression::Parameters result;
  1712. while (it != end) {
  1713. if (!consumeToken(")").empty()) {
  1714. return result;
  1715. }
  1716. auto expr = parseExpression();
  1717. if (!expr) throw std::runtime_error("Expected expression in call args");
  1718. if (auto ident = dynamic_cast<VariableExpr*>(expr.get())) {
  1719. if (!consumeToken("=").empty()) {
  1720. auto value = parseExpression();
  1721. if (!value) throw std::runtime_error("Expected expression in for named arg");
  1722. result.emplace_back(ident->get_name(), std::move(value));
  1723. } else {
  1724. result.emplace_back(ident->get_name(), nullptr);
  1725. }
  1726. } else {
  1727. result.emplace_back(std::string(), std::move(expr));
  1728. }
  1729. if (consumeToken(",").empty()) {
  1730. if (consumeToken(")").empty()) {
  1731. throw std::runtime_error("Expected closing parenthesis in call args");
  1732. }
  1733. return result;
  1734. }
  1735. }
  1736. throw std::runtime_error("Expected closing parenthesis in call args");
  1737. }
  1738. ArgumentsExpression parseCallArgs() {
  1739. consumeSpaces();
  1740. if (consumeToken("(").empty()) throw std::runtime_error("Expected opening parenthesis in call args");
  1741. ArgumentsExpression result;
  1742. while (it != end) {
  1743. if (!consumeToken(")").empty()) {
  1744. return result;
  1745. }
  1746. auto expr = parseExpression();
  1747. if (!expr) throw std::runtime_error("Expected expression in call args");
  1748. if (auto ident = dynamic_cast<VariableExpr*>(expr.get())) {
  1749. if (!consumeToken("=").empty()) {
  1750. auto value = parseExpression();
  1751. if (!value) throw std::runtime_error("Expected expression in for named arg");
  1752. result.kwargs.emplace_back(ident->get_name(), std::move(value));
  1753. } else {
  1754. result.args.emplace_back(std::move(expr));
  1755. }
  1756. } else {
  1757. result.args.emplace_back(std::move(expr));
  1758. }
  1759. if (consumeToken(",").empty()) {
  1760. if (consumeToken(")").empty()) {
  1761. throw std::runtime_error("Expected closing parenthesis in call args");
  1762. }
  1763. return result;
  1764. }
  1765. }
  1766. throw std::runtime_error("Expected closing parenthesis in call args");
  1767. }
  1768. std::shared_ptr<VariableExpr> parseIdentifier() {
  1769. static std::regex ident_regex(R"((?!(?:not|is|and|or|del)\b)[a-zA-Z_]\w*)");
  1770. auto location = get_location();
  1771. auto ident = consumeToken(ident_regex);
  1772. if (ident.empty())
  1773. return nullptr;
  1774. return std::make_shared<VariableExpr>(location, ident);
  1775. }
  1776. std::shared_ptr<Expression> parseStringConcat() {
  1777. auto left = parseMathPow();
  1778. if (!left) throw std::runtime_error("Expected left side of 'string concat' expression");
  1779. static std::regex concat_tok(R"(~(?!\}))");
  1780. if (!consumeToken(concat_tok).empty()) {
  1781. auto right = parseLogicalAnd();
  1782. if (!right) throw std::runtime_error("Expected right side of 'string concat' expression");
  1783. left = std::make_shared<BinaryOpExpr>(get_location(), std::move(left), std::move(right), BinaryOpExpr::Op::StrConcat);
  1784. }
  1785. return left;
  1786. }
  1787. std::shared_ptr<Expression> parseMathPow() {
  1788. auto left = parseMathPlusMinus();
  1789. if (!left) throw std::runtime_error("Expected left side of 'math pow' expression");
  1790. while (!consumeToken("**").empty()) {
  1791. auto right = parseMathPlusMinus();
  1792. if (!right) throw std::runtime_error("Expected right side of 'math pow' expression");
  1793. left = std::make_shared<BinaryOpExpr>(get_location(), std::move(left), std::move(right), BinaryOpExpr::Op::MulMul);
  1794. }
  1795. return left;
  1796. }
  1797. std::shared_ptr<Expression> parseMathPlusMinus() {
  1798. static std::regex plus_minus_tok(R"(\+|-(?![}%#]\}))");
  1799. auto left = parseMathMulDiv();
  1800. if (!left) throw std::runtime_error("Expected left side of 'math plus/minus' expression");
  1801. std::string op_str;
  1802. while (!(op_str = consumeToken(plus_minus_tok)).empty()) {
  1803. auto right = parseMathMulDiv();
  1804. if (!right) throw std::runtime_error("Expected right side of 'math plus/minus' expression");
  1805. auto op = op_str == "+" ? BinaryOpExpr::Op::Add : BinaryOpExpr::Op::Sub;
  1806. left = std::make_shared<BinaryOpExpr>(get_location(), std::move(left), std::move(right), op);
  1807. }
  1808. return left;
  1809. }
  1810. std::shared_ptr<Expression> parseMathMulDiv() {
  1811. auto left = parseMathUnaryPlusMinus();
  1812. if (!left) throw std::runtime_error("Expected left side of 'math mul/div' expression");
  1813. static std::regex mul_div_tok(R"(\*\*?|//?|%(?!\}))");
  1814. std::string op_str;
  1815. while (!(op_str = consumeToken(mul_div_tok)).empty()) {
  1816. auto right = parseMathUnaryPlusMinus();
  1817. if (!right) throw std::runtime_error("Expected right side of 'math mul/div' expression");
  1818. auto op = op_str == "*" ? BinaryOpExpr::Op::Mul
  1819. : op_str == "**" ? BinaryOpExpr::Op::MulMul
  1820. : op_str == "/" ? BinaryOpExpr::Op::Div
  1821. : op_str == "//" ? BinaryOpExpr::Op::DivDiv
  1822. : BinaryOpExpr::Op::Mod;
  1823. left = std::make_shared<BinaryOpExpr>(get_location(), std::move(left), std::move(right), op);
  1824. }
  1825. if (!consumeToken("|").empty()) {
  1826. auto expr = parseMathMulDiv();
  1827. if (auto filter = dynamic_cast<FilterExpr*>(expr.get())) {
  1828. filter->prepend(std::move(left));
  1829. return expr;
  1830. } else {
  1831. std::vector<std::shared_ptr<Expression>> parts;
  1832. parts.emplace_back(std::move(left));
  1833. parts.emplace_back(std::move(expr));
  1834. return std::make_shared<FilterExpr>(get_location(), std::move(parts));
  1835. }
  1836. }
  1837. return left;
  1838. }
  1839. std::shared_ptr<Expression> call_func(const std::string & name, ArgumentsExpression && args) const {
  1840. return std::make_shared<CallExpr>(get_location(), std::make_shared<VariableExpr>(get_location(), name), std::move(args));
  1841. }
  1842. std::shared_ptr<Expression> parseMathUnaryPlusMinus() {
  1843. static std::regex unary_plus_minus_tok(R"(\+|-(?![}%#]\}))");
  1844. auto op_str = consumeToken(unary_plus_minus_tok);
  1845. auto expr = parseExpansion();
  1846. if (!expr) throw std::runtime_error("Expected expr of 'unary plus/minus/expansion' expression");
  1847. if (!op_str.empty()) {
  1848. auto op = op_str == "+" ? UnaryOpExpr::Op::Plus : UnaryOpExpr::Op::Minus;
  1849. return std::make_shared<UnaryOpExpr>(get_location(), std::move(expr), op);
  1850. }
  1851. return expr;
  1852. }
  1853. std::shared_ptr<Expression> parseExpansion() {
  1854. static std::regex expansion_tok(R"(\*\*?)");
  1855. auto op_str = consumeToken(expansion_tok);
  1856. auto expr = parseValueExpression();
  1857. if (op_str.empty()) return expr;
  1858. if (!expr) throw std::runtime_error("Expected expr of 'expansion' expression");
  1859. return std::make_shared<UnaryOpExpr>(get_location(), std::move(expr), op_str == "*" ? UnaryOpExpr::Op::Expansion : UnaryOpExpr::Op::ExpansionDict);
  1860. }
  1861. std::shared_ptr<Expression> parseValueExpression() {
  1862. auto parseValue = [&]() -> std::shared_ptr<Expression> {
  1863. auto location = get_location();
  1864. auto constant = parseConstant();
  1865. if (constant) return std::make_shared<LiteralExpr>(location, *constant);
  1866. static std::regex null_regex(R"(null\b)");
  1867. if (!consumeToken(null_regex).empty()) return std::make_shared<LiteralExpr>(location, Value());
  1868. auto identifier = parseIdentifier();
  1869. if (identifier) return identifier;
  1870. auto braced = parseBracedExpressionOrArray();
  1871. if (braced) return braced;
  1872. auto array = parseArray();
  1873. if (array) return array;
  1874. auto dictionary = parseDictionary();
  1875. if (dictionary) return dictionary;
  1876. throw std::runtime_error("Expected value expression");
  1877. };
  1878. auto value = parseValue();
  1879. while (it != end && consumeSpaces() && peekSymbols({ "[", "." })) {
  1880. if (!consumeToken("[").empty()) {
  1881. std::shared_ptr<Expression> index;
  1882. if (!consumeToken(":").empty()) {
  1883. auto slice_end = parseExpression();
  1884. index = std::make_shared<SliceExpr>(slice_end->location, nullptr, std::move(slice_end));
  1885. } else {
  1886. auto slice_start = parseExpression();
  1887. if (!consumeToken(":").empty()) {
  1888. consumeSpaces();
  1889. if (peekSymbols({ "]" })) {
  1890. index = std::make_shared<SliceExpr>(slice_start->location, std::move(slice_start), nullptr);
  1891. } else {
  1892. auto slice_end = parseExpression();
  1893. index = std::make_shared<SliceExpr>(slice_start->location, std::move(slice_start), std::move(slice_end));
  1894. }
  1895. } else {
  1896. index = std::move(slice_start);
  1897. }
  1898. }
  1899. if (!index) throw std::runtime_error("Empty index in subscript");
  1900. if (consumeToken("]").empty()) throw std::runtime_error("Expected closing bracket in subscript");
  1901. value = std::make_shared<SubscriptExpr>(value->location, std::move(value), std::move(index));
  1902. } else if (!consumeToken(".").empty()) {
  1903. auto identifier = parseIdentifier();
  1904. if (!identifier) throw std::runtime_error("Expected identifier in subscript");
  1905. consumeSpaces();
  1906. if (peekSymbols({ "(" })) {
  1907. auto callParams = parseCallArgs();
  1908. value = std::make_shared<MethodCallExpr>(identifier->location, std::move(value), std::move(identifier), std::move(callParams));
  1909. } else {
  1910. auto key = std::make_shared<LiteralExpr>(identifier->location, Value(identifier->get_name()));
  1911. value = std::make_shared<SubscriptExpr>(identifier->location, std::move(value), std::move(key));
  1912. }
  1913. }
  1914. consumeSpaces();
  1915. }
  1916. if (peekSymbols({ "(" })) {
  1917. auto location = get_location();
  1918. auto callParams = parseCallArgs();
  1919. value = std::make_shared<CallExpr>(location, std::move(value), std::move(callParams));
  1920. }
  1921. return value;
  1922. }
  1923. std::shared_ptr<Expression> parseBracedExpressionOrArray() {
  1924. if (consumeToken("(").empty()) return nullptr;
  1925. auto expr = parseExpression();
  1926. if (!expr) throw std::runtime_error("Expected expression in braced expression");
  1927. if (!consumeToken(")").empty()) {
  1928. return expr; // Drop the parentheses
  1929. }
  1930. std::vector<std::shared_ptr<Expression>> tuple;
  1931. tuple.emplace_back(std::move(expr));
  1932. while (it != end) {
  1933. if (consumeToken(",").empty()) throw std::runtime_error("Expected comma in tuple");
  1934. auto next = parseExpression();
  1935. if (!next) throw std::runtime_error("Expected expression in tuple");
  1936. tuple.push_back(std::move(next));
  1937. if (!consumeToken(")").empty()) {
  1938. return std::make_shared<ArrayExpr>(get_location(), std::move(tuple));
  1939. }
  1940. }
  1941. throw std::runtime_error("Expected closing parenthesis");
  1942. }
  1943. std::shared_ptr<Expression> parseArray() {
  1944. if (consumeToken("[").empty()) return nullptr;
  1945. std::vector<std::shared_ptr<Expression>> elements;
  1946. if (!consumeToken("]").empty()) {
  1947. return std::make_shared<ArrayExpr>(get_location(), std::move(elements));
  1948. }
  1949. auto first_expr = parseExpression();
  1950. if (!first_expr) throw std::runtime_error("Expected first expression in array");
  1951. elements.push_back(std::move(first_expr));
  1952. while (it != end) {
  1953. if (!consumeToken(",").empty()) {
  1954. auto expr = parseExpression();
  1955. if (!expr) throw std::runtime_error("Expected expression in array");
  1956. elements.push_back(std::move(expr));
  1957. } else if (!consumeToken("]").empty()) {
  1958. return std::make_shared<ArrayExpr>(get_location(), std::move(elements));
  1959. } else {
  1960. throw std::runtime_error("Expected comma or closing bracket in array");
  1961. }
  1962. }
  1963. throw std::runtime_error("Expected closing bracket");
  1964. }
  1965. std::shared_ptr<Expression> parseDictionary() {
  1966. if (consumeToken("{").empty()) return nullptr;
  1967. std::vector<std::pair<std::shared_ptr<Expression>, std::shared_ptr<Expression>>> elements;
  1968. if (!consumeToken("}").empty()) {
  1969. return std::make_shared<DictExpr>(get_location(), std::move(elements));
  1970. }
  1971. auto parseKeyValuePair = [&]() {
  1972. auto key = parseExpression();
  1973. if (!key) throw std::runtime_error("Expected key in dictionary");
  1974. if (consumeToken(":").empty()) throw std::runtime_error("Expected colon betweek key & value in dictionary");
  1975. auto value = parseExpression();
  1976. if (!value) throw std::runtime_error("Expected value in dictionary");
  1977. elements.emplace_back(std::pair(std::move(key), std::move(value)));
  1978. };
  1979. parseKeyValuePair();
  1980. while (it != end) {
  1981. if (!consumeToken(",").empty()) {
  1982. parseKeyValuePair();
  1983. } else if (!consumeToken("}").empty()) {
  1984. return std::make_shared<DictExpr>(get_location(), std::move(elements));
  1985. } else {
  1986. throw std::runtime_error("Expected comma or closing brace in dictionary");
  1987. }
  1988. }
  1989. throw std::runtime_error("Expected closing brace");
  1990. }
  1991. SpaceHandling parsePreSpace(const std::string& s) const {
  1992. if (s == "-")
  1993. return SpaceHandling::Strip;
  1994. return SpaceHandling::Keep;
  1995. }
  1996. SpaceHandling parsePostSpace(const std::string& s) const {
  1997. if (s == "-") return SpaceHandling::Strip;
  1998. return SpaceHandling::Keep;
  1999. }
  2000. using TemplateTokenVector = std::vector<std::unique_ptr<TemplateToken>>;
  2001. using TemplateTokenIterator = TemplateTokenVector::const_iterator;
  2002. std::vector<std::string> parseVarNames() {
  2003. static std::regex varnames_regex(R"(((?:\w+)(?:\s*,\s*(?:\w+))*)\s*)");
  2004. std::vector<std::string> group;
  2005. if ((group = consumeTokenGroups(varnames_regex)).empty()) throw std::runtime_error("Expected variable names");
  2006. std::vector<std::string> varnames;
  2007. std::istringstream iss(group[1]);
  2008. std::string varname;
  2009. while (std::getline(iss, varname, ',')) {
  2010. varnames.push_back(strip(varname));
  2011. }
  2012. return varnames;
  2013. }
  2014. std::runtime_error unexpected(const TemplateToken & token) const {
  2015. return std::runtime_error("Unexpected " + TemplateToken::typeToString(token.type)
  2016. + error_location_suffix(*template_str, token.location.pos));
  2017. }
  2018. std::runtime_error unterminated(const TemplateToken & token) const {
  2019. return std::runtime_error("Unterminated " + TemplateToken::typeToString(token.type)
  2020. + error_location_suffix(*template_str, token.location.pos));
  2021. }
  2022. TemplateTokenVector tokenize() {
  2023. static std::regex comment_tok(R"(\{#([-~]?)([\s\S]*?)([-~]?)#\})");
  2024. static std::regex expr_open_regex(R"(\{\{([-~])?)");
  2025. static std::regex block_open_regex(R"(^\{%([-~])?\s*)");
  2026. static std::regex block_keyword_tok(R"((if|else|elif|endif|for|endfor|generation|endgeneration|set|endset|block|endblock|macro|endmacro|filter|endfilter|break|continue)\b)");
  2027. static std::regex non_text_open_regex(R"(\{\{|\{%|\{#)");
  2028. static std::regex expr_close_regex(R"(\s*([-~])?\}\})");
  2029. static std::regex block_close_regex(R"(\s*([-~])?%\})");
  2030. TemplateTokenVector tokens;
  2031. std::vector<std::string> group;
  2032. std::string text;
  2033. std::smatch match;
  2034. try {
  2035. while (it != end) {
  2036. auto location = get_location();
  2037. if (!(group = consumeTokenGroups(comment_tok, SpaceHandling::Keep)).empty()) {
  2038. auto pre_space = parsePreSpace(group[1]);
  2039. auto content = group[2];
  2040. auto post_space = parsePostSpace(group[3]);
  2041. tokens.push_back(std::make_unique<CommentTemplateToken>(location, pre_space, post_space, content));
  2042. } else if (!(group = consumeTokenGroups(expr_open_regex, SpaceHandling::Keep)).empty()) {
  2043. auto pre_space = parsePreSpace(group[1]);
  2044. auto expr = parseExpression();
  2045. if ((group = consumeTokenGroups(expr_close_regex)).empty()) {
  2046. throw std::runtime_error("Expected closing expression tag");
  2047. }
  2048. auto post_space = parsePostSpace(group[1]);
  2049. tokens.push_back(std::make_unique<ExpressionTemplateToken>(location, pre_space, post_space, std::move(expr)));
  2050. } else if (!(group = consumeTokenGroups(block_open_regex, SpaceHandling::Keep)).empty()) {
  2051. auto pre_space = parsePreSpace(group[1]);
  2052. std::string keyword;
  2053. auto parseBlockClose = [&]() -> SpaceHandling {
  2054. if ((group = consumeTokenGroups(block_close_regex)).empty()) throw std::runtime_error("Expected closing block tag");
  2055. return parsePostSpace(group[1]);
  2056. };
  2057. if ((keyword = consumeToken(block_keyword_tok)).empty()) throw std::runtime_error("Expected block keyword");
  2058. if (keyword == "if") {
  2059. auto condition = parseExpression();
  2060. if (!condition) throw std::runtime_error("Expected condition in if block");
  2061. auto post_space = parseBlockClose();
  2062. tokens.push_back(std::make_unique<IfTemplateToken>(location, pre_space, post_space, std::move(condition)));
  2063. } else if (keyword == "elif") {
  2064. auto condition = parseExpression();
  2065. if (!condition) throw std::runtime_error("Expected condition in elif block");
  2066. auto post_space = parseBlockClose();
  2067. tokens.push_back(std::make_unique<ElifTemplateToken>(location, pre_space, post_space, std::move(condition)));
  2068. } else if (keyword == "else") {
  2069. auto post_space = parseBlockClose();
  2070. tokens.push_back(std::make_unique<ElseTemplateToken>(location, pre_space, post_space));
  2071. } else if (keyword == "endif") {
  2072. auto post_space = parseBlockClose();
  2073. tokens.push_back(std::make_unique<EndIfTemplateToken>(location, pre_space, post_space));
  2074. } else if (keyword == "for") {
  2075. static std::regex recursive_tok(R"(recursive\b)");
  2076. static std::regex if_tok(R"(if\b)");
  2077. auto varnames = parseVarNames();
  2078. static std::regex in_tok(R"(in\b)");
  2079. if (consumeToken(in_tok).empty()) throw std::runtime_error("Expected 'in' keyword in for block");
  2080. auto iterable = parseExpression(/* allow_if_expr = */ false);
  2081. if (!iterable) throw std::runtime_error("Expected iterable in for block");
  2082. std::shared_ptr<Expression> condition;
  2083. if (!consumeToken(if_tok).empty()) {
  2084. condition = parseExpression();
  2085. }
  2086. auto recursive = !consumeToken(recursive_tok).empty();
  2087. auto post_space = parseBlockClose();
  2088. tokens.push_back(std::make_unique<ForTemplateToken>(location, pre_space, post_space, std::move(varnames), std::move(iterable), std::move(condition), recursive));
  2089. } else if (keyword == "endfor") {
  2090. auto post_space = parseBlockClose();
  2091. tokens.push_back(std::make_unique<EndForTemplateToken>(location, pre_space, post_space));
  2092. } else if (keyword == "generation") {
  2093. auto post_space = parseBlockClose();
  2094. tokens.push_back(std::make_unique<GenerationTemplateToken>(location, pre_space, post_space));
  2095. } else if (keyword == "endgeneration") {
  2096. auto post_space = parseBlockClose();
  2097. tokens.push_back(std::make_unique<EndGenerationTemplateToken>(location, pre_space, post_space));
  2098. } else if (keyword == "set") {
  2099. static std::regex namespaced_var_regex(R"((\w+)\s*\.\s*(\w+))");
  2100. std::string ns;
  2101. std::vector<std::string> var_names;
  2102. std::shared_ptr<Expression> value;
  2103. if (!(group = consumeTokenGroups(namespaced_var_regex)).empty()) {
  2104. ns = group[1];
  2105. var_names.push_back(group[2]);
  2106. if (consumeToken("=").empty()) throw std::runtime_error("Expected equals sign in set block");
  2107. value = parseExpression();
  2108. if (!value) throw std::runtime_error("Expected value in set block");
  2109. } else {
  2110. var_names = parseVarNames();
  2111. if (!consumeToken("=").empty()) {
  2112. value = parseExpression();
  2113. if (!value) throw std::runtime_error("Expected value in set block");
  2114. }
  2115. }
  2116. auto post_space = parseBlockClose();
  2117. tokens.push_back(std::make_unique<SetTemplateToken>(location, pre_space, post_space, ns, var_names, std::move(value)));
  2118. } else if (keyword == "endset") {
  2119. auto post_space = parseBlockClose();
  2120. tokens.push_back(std::make_unique<EndSetTemplateToken>(location, pre_space, post_space));
  2121. } else if (keyword == "macro") {
  2122. auto macroname = parseIdentifier();
  2123. if (!macroname) throw std::runtime_error("Expected macro name in macro block");
  2124. auto params = parseParameters();
  2125. auto post_space = parseBlockClose();
  2126. tokens.push_back(std::make_unique<MacroTemplateToken>(location, pre_space, post_space, std::move(macroname), std::move(params)));
  2127. } else if (keyword == "endmacro") {
  2128. auto post_space = parseBlockClose();
  2129. tokens.push_back(std::make_unique<EndMacroTemplateToken>(location, pre_space, post_space));
  2130. } else if (keyword == "filter") {
  2131. auto filter = parseExpression();
  2132. if (!filter) throw std::runtime_error("Expected expression in filter block");
  2133. auto post_space = parseBlockClose();
  2134. tokens.push_back(std::make_unique<FilterTemplateToken>(location, pre_space, post_space, std::move(filter)));
  2135. } else if (keyword == "endfilter") {
  2136. auto post_space = parseBlockClose();
  2137. tokens.push_back(std::make_unique<EndFilterTemplateToken>(location, pre_space, post_space));
  2138. } else if (keyword == "break" || keyword == "continue") {
  2139. auto post_space = parseBlockClose();
  2140. tokens.push_back(std::make_unique<LoopControlTemplateToken>(location, pre_space, post_space, keyword == "break" ? LoopControlType::Break : LoopControlType::Continue));
  2141. } else {
  2142. throw std::runtime_error("Unexpected block: " + keyword);
  2143. }
  2144. } else if (std::regex_search(it, end, match, non_text_open_regex)) {
  2145. if (!match.position()) {
  2146. if (match[0] != "{#")
  2147. throw std::runtime_error("Internal error: Expected a comment");
  2148. throw std::runtime_error("Missing end of comment tag");
  2149. }
  2150. auto text_end = it + match.position();
  2151. text = std::string(it, text_end);
  2152. it = text_end;
  2153. tokens.push_back(std::make_unique<TextTemplateToken>(location, SpaceHandling::Keep, SpaceHandling::Keep, text));
  2154. } else {
  2155. text = std::string(it, end);
  2156. it = end;
  2157. tokens.push_back(std::make_unique<TextTemplateToken>(location, SpaceHandling::Keep, SpaceHandling::Keep, text));
  2158. }
  2159. }
  2160. return tokens;
  2161. } catch (const std::exception & e) {
  2162. throw std::runtime_error(e.what() + error_location_suffix(*template_str, std::distance(start, it)));
  2163. }
  2164. }
  2165. std::shared_ptr<TemplateNode> parseTemplate(
  2166. const TemplateTokenIterator & begin,
  2167. TemplateTokenIterator & it,
  2168. const TemplateTokenIterator & end,
  2169. bool fully = false) const {
  2170. std::vector<std::shared_ptr<TemplateNode>> children;
  2171. while (it != end) {
  2172. const auto start = it;
  2173. const auto & token = *(it++);
  2174. if (auto if_token = dynamic_cast<IfTemplateToken*>(token.get())) {
  2175. std::vector<std::pair<std::shared_ptr<Expression>, std::shared_ptr<TemplateNode>>> cascade;
  2176. cascade.emplace_back(std::move(if_token->condition), parseTemplate(begin, it, end));
  2177. while (it != end && (*it)->type == TemplateToken::Type::Elif) {
  2178. auto elif_token = dynamic_cast<ElifTemplateToken*>((*(it++)).get());
  2179. cascade.emplace_back(std::move(elif_token->condition), parseTemplate(begin, it, end));
  2180. }
  2181. if (it != end && (*it)->type == TemplateToken::Type::Else) {
  2182. cascade.emplace_back(nullptr, parseTemplate(begin, ++it, end));
  2183. }
  2184. if (it == end || (*(it++))->type != TemplateToken::Type::EndIf) {
  2185. throw unterminated(**start);
  2186. }
  2187. children.emplace_back(std::make_shared<IfNode>(token->location, std::move(cascade)));
  2188. } else if (auto for_token = dynamic_cast<ForTemplateToken*>(token.get())) {
  2189. auto body = parseTemplate(begin, it, end);
  2190. auto else_body = std::shared_ptr<TemplateNode>();
  2191. if (it != end && (*it)->type == TemplateToken::Type::Else) {
  2192. else_body = parseTemplate(begin, ++it, end);
  2193. }
  2194. if (it == end || (*(it++))->type != TemplateToken::Type::EndFor) {
  2195. throw unterminated(**start);
  2196. }
  2197. 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)));
  2198. } else if (dynamic_cast<GenerationTemplateToken*>(token.get())) {
  2199. auto body = parseTemplate(begin, it, end);
  2200. if (it == end || (*(it++))->type != TemplateToken::Type::EndGeneration) {
  2201. throw unterminated(**start);
  2202. }
  2203. // Treat as a no-op, as our scope is templates for inference, not training (`{% generation %}` wraps generated tokens for masking).
  2204. children.emplace_back(std::move(body));
  2205. } else if (auto text_token = dynamic_cast<TextTemplateToken*>(token.get())) {
  2206. SpaceHandling pre_space = (it - 1) != begin ? (*(it - 2))->post_space : SpaceHandling::Keep;
  2207. SpaceHandling post_space = it != end ? (*it)->pre_space : SpaceHandling::Keep;
  2208. auto text = text_token->text;
  2209. if (post_space == SpaceHandling::Strip) {
  2210. static std::regex trailing_space_regex(R"(\s+$)");
  2211. text = std::regex_replace(text, trailing_space_regex, "");
  2212. } else if (options.lstrip_blocks && it != end) {
  2213. auto i = text.size();
  2214. while (i > 0 && (text[i - 1] == ' ' || text[i - 1] == '\t')) i--;
  2215. if ((i == 0 && (it - 1) == begin) || (i > 0 && text[i - 1] == '\n')) {
  2216. text.resize(i);
  2217. }
  2218. }
  2219. if (pre_space == SpaceHandling::Strip) {
  2220. static std::regex leading_space_regex(R"(^\s+)");
  2221. text = std::regex_replace(text, leading_space_regex, "");
  2222. } else if (options.trim_blocks && (it - 1) != begin && !dynamic_cast<ExpressionTemplateToken*>((*(it - 2)).get())) {
  2223. if (text.length() > 0 && text[0] == '\n') {
  2224. text.erase(0, 1);
  2225. }
  2226. }
  2227. if (it == end && !options.keep_trailing_newline) {
  2228. auto i = text.size();
  2229. if (i > 0 && text[i - 1] == '\n') {
  2230. i--;
  2231. if (i > 0 && text[i - 1] == '\r') i--;
  2232. text.resize(i);
  2233. }
  2234. }
  2235. children.emplace_back(std::make_shared<TextNode>(token->location, text));
  2236. } else if (auto expr_token = dynamic_cast<ExpressionTemplateToken*>(token.get())) {
  2237. children.emplace_back(std::make_shared<ExpressionNode>(token->location, std::move(expr_token->expr)));
  2238. } else if (auto set_token = dynamic_cast<SetTemplateToken*>(token.get())) {
  2239. if (set_token->value) {
  2240. children.emplace_back(std::make_shared<SetNode>(token->location, set_token->ns, set_token->var_names, std::move(set_token->value)));
  2241. } else {
  2242. auto value_template = parseTemplate(begin, it, end);
  2243. if (it == end || (*(it++))->type != TemplateToken::Type::EndSet) {
  2244. throw unterminated(**start);
  2245. }
  2246. if (!set_token->ns.empty()) throw std::runtime_error("Namespaced set not supported in set with template value");
  2247. if (set_token->var_names.size() != 1) throw std::runtime_error("Structural assignment not supported in set with template value");
  2248. auto & name = set_token->var_names[0];
  2249. children.emplace_back(std::make_shared<SetTemplateNode>(token->location, name, std::move(value_template)));
  2250. }
  2251. } else if (auto macro_token = dynamic_cast<MacroTemplateToken*>(token.get())) {
  2252. auto body = parseTemplate(begin, it, end);
  2253. if (it == end || (*(it++))->type != TemplateToken::Type::EndMacro) {
  2254. throw unterminated(**start);
  2255. }
  2256. children.emplace_back(std::make_shared<MacroNode>(token->location, std::move(macro_token->name), std::move(macro_token->params), std::move(body)));
  2257. } else if (auto filter_token = dynamic_cast<FilterTemplateToken*>(token.get())) {
  2258. auto body = parseTemplate(begin, it, end);
  2259. if (it == end || (*(it++))->type != TemplateToken::Type::EndFilter) {
  2260. throw unterminated(**start);
  2261. }
  2262. children.emplace_back(std::make_shared<FilterNode>(token->location, std::move(filter_token->filter), std::move(body)));
  2263. } else if (dynamic_cast<CommentTemplateToken*>(token.get())) {
  2264. // Ignore comments
  2265. } else if (auto ctrl_token = dynamic_cast<LoopControlTemplateToken*>(token.get())) {
  2266. children.emplace_back(std::make_shared<LoopControlNode>(token->location, ctrl_token->control_type));
  2267. } else if (dynamic_cast<EndForTemplateToken*>(token.get())
  2268. || dynamic_cast<EndSetTemplateToken*>(token.get())
  2269. || dynamic_cast<EndMacroTemplateToken*>(token.get())
  2270. || dynamic_cast<EndFilterTemplateToken*>(token.get())
  2271. || dynamic_cast<EndIfTemplateToken*>(token.get())
  2272. || dynamic_cast<ElseTemplateToken*>(token.get())
  2273. || dynamic_cast<EndGenerationTemplateToken*>(token.get())
  2274. || dynamic_cast<ElifTemplateToken*>(token.get())) {
  2275. it--; // unconsume the token
  2276. break; // exit the loop
  2277. } else {
  2278. throw unexpected(**(it-1));
  2279. }
  2280. }
  2281. if (fully && it != end) {
  2282. throw unexpected(**it);
  2283. }
  2284. if (children.empty()) {
  2285. return std::make_shared<TextNode>(Location { template_str, 0 }, std::string());
  2286. } else if (children.size() == 1) {
  2287. return std::move(children[0]);
  2288. } else {
  2289. return std::make_shared<SequenceNode>(children[0]->location(), std::move(children));
  2290. }
  2291. }
  2292. public:
  2293. static std::shared_ptr<TemplateNode> parse(const std::string& template_str, const Options & options) {
  2294. Parser parser(std::make_shared<std::string>(normalize_newlines(template_str)), options);
  2295. auto tokens = parser.tokenize();
  2296. TemplateTokenIterator begin = tokens.begin();
  2297. auto it = begin;
  2298. TemplateTokenIterator end = tokens.end();
  2299. return parser.parseTemplate(begin, it, end, /* full= */ true);
  2300. }
  2301. };
  2302. 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) {
  2303. std::map<std::string, size_t> named_positions;
  2304. for (size_t i = 0, n = params.size(); i < n; i++) named_positions[params[i]] = i;
  2305. return Value::callable([=](const std::shared_ptr<Context> & context, ArgumentsValue & args) -> Value {
  2306. auto args_obj = Value::object();
  2307. std::vector<bool> provided_args(params.size());
  2308. for (size_t i = 0, n = args.args.size(); i < n; i++) {
  2309. auto & arg = args.args[i];
  2310. if (i < params.size()) {
  2311. args_obj.set(params[i], arg);
  2312. provided_args[i] = true;
  2313. } else {
  2314. throw std::runtime_error("Too many positional params for " + fn_name);
  2315. }
  2316. }
  2317. for (auto & [name, value] : args.kwargs) {
  2318. auto named_pos_it = named_positions.find(name);
  2319. if (named_pos_it == named_positions.end()) {
  2320. throw std::runtime_error("Unknown argument " + name + " for function " + fn_name);
  2321. }
  2322. provided_args[named_pos_it->second] = true;
  2323. args_obj.set(name, value);
  2324. }
  2325. return fn(context, args_obj);
  2326. });
  2327. }
  2328. inline std::shared_ptr<Context> Context::builtins() {
  2329. auto globals = Value::object();
  2330. globals.set("raise_exception", simple_function("raise_exception", { "message" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2331. throw std::runtime_error(args.at("message").get<std::string>());
  2332. }));
  2333. globals.set("tojson", simple_function("tojson", { "value", "indent" }, [](const std::shared_ptr<Context> &, Value & args) {
  2334. return Value(args.at("value").dump(args.get<int64_t>("indent", -1), /* tojson= */ true));
  2335. }));
  2336. globals.set("items", simple_function("items", { "object" }, [](const std::shared_ptr<Context> &, Value & args) {
  2337. auto items = Value::array();
  2338. if (args.contains("object")) {
  2339. auto & obj = args.at("object");
  2340. if (obj.is_string()) {
  2341. auto json_obj = json::parse(obj.get<std::string>());
  2342. for (const auto & kv : json_obj.items()) {
  2343. items.push_back(Value::array({kv.key(), kv.value()}));
  2344. }
  2345. } else if (!obj.is_null()) {
  2346. for (auto & key : obj.keys()) {
  2347. items.push_back(Value::array({key, obj.at(key)}));
  2348. }
  2349. }
  2350. }
  2351. return items;
  2352. }));
  2353. globals.set("last", simple_function("last", { "items" }, [](const std::shared_ptr<Context> &, Value & args) {
  2354. auto items = args.at("items");
  2355. if (!items.is_array()) throw std::runtime_error("object is not a list");
  2356. if (items.size() == 0) return Value();
  2357. return items.at(items.size() - 1);
  2358. }));
  2359. globals.set("trim", simple_function("trim", { "text" }, [](const std::shared_ptr<Context> &, Value & args) {
  2360. auto & text = args.at("text");
  2361. return text.is_null() ? text : Value(strip(text.get<std::string>()));
  2362. }));
  2363. globals.set("lower", simple_function("lower", { "text" }, [](const std::shared_ptr<Context> &, Value & args) {
  2364. auto text = args.at("text");
  2365. if (text.is_null()) return text;
  2366. std::string res;
  2367. auto str = text.get<std::string>();
  2368. std::transform(str.begin(), str.end(), std::back_inserter(res), ::tolower);
  2369. return Value(res);
  2370. }));
  2371. globals.set("default", Value::callable([=](const std::shared_ptr<Context> &, ArgumentsValue & args) {
  2372. args.expectArgs("default", {2, 3}, {0, 1});
  2373. auto & value = args.args[0];
  2374. auto & default_value = args.args[1];
  2375. bool boolean = false;
  2376. if (args.args.size() == 3) {
  2377. boolean = args.args[2].get<bool>();
  2378. } else {
  2379. Value bv = args.get_named("boolean");
  2380. if (!bv.is_null()) {
  2381. boolean = bv.get<bool>();
  2382. }
  2383. }
  2384. return boolean ? (value.to_bool() ? value : default_value) : value.is_null() ? default_value : value;
  2385. }));
  2386. auto escape = simple_function("escape", { "text" }, [](const std::shared_ptr<Context> &, Value & args) {
  2387. return Value(html_escape(args.at("text").get<std::string>()));
  2388. });
  2389. globals.set("e", escape);
  2390. globals.set("escape", escape);
  2391. globals.set("joiner", simple_function("joiner", { "sep" }, [](const std::shared_ptr<Context> &, Value & args) {
  2392. auto sep = args.get<std::string>("sep", "");
  2393. auto first = std::make_shared<bool>(true);
  2394. return simple_function("", {}, [sep, first](const std::shared_ptr<Context> &, const Value &) -> Value {
  2395. if (*first) {
  2396. *first = false;
  2397. return "";
  2398. }
  2399. return sep;
  2400. });
  2401. return Value(html_escape(args.at("text").get<std::string>()));
  2402. }));
  2403. globals.set("count", simple_function("count", { "items" }, [](const std::shared_ptr<Context> &, Value & args) {
  2404. return Value((int64_t) args.at("items").size());
  2405. }));
  2406. globals.set("dictsort", simple_function("dictsort", { "value" }, [](const std::shared_ptr<Context> &, Value & args) {
  2407. if (args.size() != 1) throw std::runtime_error("dictsort expects exactly 1 argument (TODO: fix implementation)");
  2408. auto & value = args.at("value");
  2409. auto keys = value.keys();
  2410. std::sort(keys.begin(), keys.end());
  2411. auto res = Value::array();
  2412. for (auto & key : keys) {
  2413. res.push_back(Value::array({key, value.at(key)}));
  2414. }
  2415. return res;
  2416. }));
  2417. globals.set("join", simple_function("join", { "items", "d" }, [](const std::shared_ptr<Context> &, Value & args) {
  2418. auto do_join = [](Value & items, const std::string & sep) {
  2419. if (!items.is_array()) throw std::runtime_error("object is not iterable: " + items.dump());
  2420. std::ostringstream oss;
  2421. auto first = true;
  2422. for (size_t i = 0, n = items.size(); i < n; ++i) {
  2423. if (first) first = false;
  2424. else oss << sep;
  2425. oss << items.at(i).to_str();
  2426. }
  2427. return Value(oss.str());
  2428. };
  2429. auto sep = args.get<std::string>("d", "");
  2430. if (args.contains("items")) {
  2431. auto & items = args.at("items");
  2432. return do_join(items, sep);
  2433. } else {
  2434. return simple_function("", {"items"}, [sep, do_join](const std::shared_ptr<Context> &, Value & args) {
  2435. auto & items = args.at("items");
  2436. if (!items.to_bool() || !items.is_array()) throw std::runtime_error("join expects an array for items, got: " + items.dump());
  2437. return do_join(items, sep);
  2438. });
  2439. }
  2440. }));
  2441. globals.set("namespace", Value::callable([=](const std::shared_ptr<Context> &, ArgumentsValue & args) {
  2442. auto ns = Value::object();
  2443. args.expectArgs("namespace", {0, 0}, {0, (std::numeric_limits<size_t>::max)()});
  2444. for (auto & [name, value] : args.kwargs) {
  2445. ns.set(name, value);
  2446. }
  2447. return ns;
  2448. }));
  2449. auto equalto = simple_function("equalto", { "expected", "actual" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2450. return args.at("actual") == args.at("expected");
  2451. });
  2452. globals.set("equalto", equalto);
  2453. globals.set("==", equalto);
  2454. globals.set("length", simple_function("length", { "items" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2455. auto & items = args.at("items");
  2456. return (int64_t) items.size();
  2457. }));
  2458. globals.set("safe", simple_function("safe", { "value" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2459. return args.at("value").to_str();
  2460. }));
  2461. globals.set("string", simple_function("string", { "value" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2462. return args.at("value").to_str();
  2463. }));
  2464. globals.set("int", simple_function("int", { "value" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2465. return args.at("value").to_int();
  2466. }));
  2467. globals.set("list", simple_function("list", { "items" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2468. auto & items = args.at("items");
  2469. if (!items.is_array()) throw std::runtime_error("object is not iterable");
  2470. return items;
  2471. }));
  2472. globals.set("unique", simple_function("unique", { "items" }, [](const std::shared_ptr<Context> &, Value & args) -> Value {
  2473. auto & items = args.at("items");
  2474. if (!items.is_array()) throw std::runtime_error("object is not iterable");
  2475. std::unordered_set<Value> seen;
  2476. auto result = Value::array();
  2477. for (size_t i = 0, n = items.size(); i < n; i++) {
  2478. auto pair = seen.insert(items.at(i));
  2479. if (pair.second) {
  2480. result.push_back(items.at(i));
  2481. }
  2482. }
  2483. return result;
  2484. }));
  2485. auto make_filter = [](const Value & filter, Value & extra_args) -> Value {
  2486. return simple_function("", { "value" }, [=](const std::shared_ptr<Context> & context, Value & args) {
  2487. auto & value = args.at("value");
  2488. ArgumentsValue actual_args;
  2489. actual_args.args.emplace_back(value);
  2490. for (size_t i = 0, n = extra_args.size(); i < n; i++) {
  2491. actual_args.args.emplace_back(extra_args.at(i));
  2492. }
  2493. return filter.call(context, actual_args);
  2494. });
  2495. };
  2496. auto select_or_reject = [make_filter](bool is_select) {
  2497. return Value::callable([=](const std::shared_ptr<Context> & context, ArgumentsValue & args) {
  2498. args.expectArgs(is_select ? "select" : "reject", {2, (std::numeric_limits<size_t>::max)()}, {0, 0});
  2499. auto & items = args.args[0];
  2500. if (items.is_null())
  2501. return Value::array();
  2502. if (!items.is_array()) throw std::runtime_error("object is not iterable: " + items.dump());
  2503. auto filter_fn = context->get(args.args[1]);
  2504. if (filter_fn.is_null()) throw std::runtime_error("Undefined filter: " + args.args[1].dump());
  2505. auto filter_args = Value::array();
  2506. for (size_t i = 2, n = args.args.size(); i < n; i++) {
  2507. filter_args.push_back(args.args[i]);
  2508. }
  2509. auto filter = make_filter(filter_fn, filter_args);
  2510. auto res = Value::array();
  2511. for (size_t i = 0, n = items.size(); i < n; i++) {
  2512. auto & item = items.at(i);
  2513. ArgumentsValue filter_args;
  2514. filter_args.args.emplace_back(item);
  2515. auto pred_res = filter.call(context, filter_args);
  2516. if (pred_res.to_bool() == (is_select ? true : false)) {
  2517. res.push_back(item);
  2518. }
  2519. }
  2520. return res;
  2521. });
  2522. };
  2523. globals.set("select", select_or_reject(/* is_select= */ true));
  2524. globals.set("reject", select_or_reject(/* is_select= */ false));
  2525. globals.set("map", Value::callable([=](const std::shared_ptr<Context> & context, ArgumentsValue & args) {
  2526. auto res = Value::array();
  2527. if (args.args.size() == 1 &&
  2528. ((args.has_named("attribute") && args.kwargs.size() == 1) || (args.has_named("default") && args.kwargs.size() == 2))) {
  2529. auto & items = args.args[0];
  2530. auto attr_name = args.get_named("attribute");
  2531. auto default_value = args.get_named("default");
  2532. for (size_t i = 0, n = items.size(); i < n; i++) {
  2533. auto & item = items.at(i);
  2534. auto attr = item.get(attr_name);
  2535. res.push_back(attr.is_null() ? default_value : attr);
  2536. }
  2537. } else if (args.kwargs.empty() && args.args.size() >= 2) {
  2538. auto fn = context->get(args.args[1]);
  2539. if (fn.is_null()) throw std::runtime_error("Undefined filter: " + args.args[1].dump());
  2540. ArgumentsValue filter_args { {Value()}, {} };
  2541. for (size_t i = 2, n = args.args.size(); i < n; i++) {
  2542. filter_args.args.emplace_back(args.args[i]);
  2543. }
  2544. for (size_t i = 0, n = args.args[0].size(); i < n; i++) {
  2545. auto & item = args.args[0].at(i);
  2546. filter_args.args[0] = item;
  2547. res.push_back(fn.call(context, filter_args));
  2548. }
  2549. } else {
  2550. throw std::runtime_error("Invalid or unsupported arguments for map");
  2551. }
  2552. return res;
  2553. }));
  2554. globals.set("indent", simple_function("indent", { "text", "indent", "first" }, [](const std::shared_ptr<Context> &, Value & args) {
  2555. auto text = args.at("text").get<std::string>();
  2556. auto first = args.get<bool>("first", false);
  2557. std::string out;
  2558. std::string indent(args.get<int64_t>("indent", 0), ' ');
  2559. std::istringstream iss(text);
  2560. std::string line;
  2561. auto is_first = true;
  2562. while (std::getline(iss, line, '\n')) {
  2563. auto needs_indent = !is_first || first;
  2564. if (is_first) is_first = false;
  2565. else out += "\n";
  2566. if (needs_indent) out += indent;
  2567. out += line;
  2568. }
  2569. if (!text.empty() && text.back() == '\n') out += "\n";
  2570. return out;
  2571. }));
  2572. auto select_or_reject_attr = [](bool is_select) {
  2573. return Value::callable([=](const std::shared_ptr<Context> & context, ArgumentsValue & args) {
  2574. args.expectArgs(is_select ? "selectattr" : "rejectattr", {2, (std::numeric_limits<size_t>::max)()}, {0, 0});
  2575. auto & items = args.args[0];
  2576. if (items.is_null())
  2577. return Value::array();
  2578. if (!items.is_array()) throw std::runtime_error("object is not iterable: " + items.dump());
  2579. auto attr_name = args.args[1].get<std::string>();
  2580. bool has_test = false;
  2581. Value test_fn;
  2582. ArgumentsValue test_args {{Value()}, {}};
  2583. if (args.args.size() >= 3) {
  2584. has_test = true;
  2585. test_fn = context->get(args.args[2]);
  2586. if (test_fn.is_null()) throw std::runtime_error("Undefined test: " + args.args[2].dump());
  2587. for (size_t i = 3, n = args.args.size(); i < n; i++) {
  2588. test_args.args.emplace_back(args.args[i]);
  2589. }
  2590. test_args.kwargs = args.kwargs;
  2591. }
  2592. auto res = Value::array();
  2593. for (size_t i = 0, n = items.size(); i < n; i++) {
  2594. auto & item = items.at(i);
  2595. auto attr = item.get(attr_name);
  2596. if (has_test) {
  2597. test_args.args[0] = attr;
  2598. if (test_fn.call(context, test_args).to_bool() == (is_select ? true : false)) {
  2599. res.push_back(item);
  2600. }
  2601. } else {
  2602. res.push_back(attr);
  2603. }
  2604. }
  2605. return res;
  2606. });
  2607. };
  2608. globals.set("selectattr", select_or_reject_attr(/* is_select= */ true));
  2609. globals.set("rejectattr", select_or_reject_attr(/* is_select= */ false));
  2610. globals.set("range", Value::callable([=](const std::shared_ptr<Context> &, ArgumentsValue & args) {
  2611. std::vector<int64_t> startEndStep(3);
  2612. std::vector<bool> param_set(3);
  2613. if (args.args.size() == 1) {
  2614. startEndStep[1] = args.args[0].get<int64_t>();
  2615. param_set[1] = true;
  2616. } else {
  2617. for (size_t i = 0; i < args.args.size(); i++) {
  2618. auto & arg = args.args[i];
  2619. auto v = arg.get<int64_t>();
  2620. startEndStep[i] = v;
  2621. param_set[i] = true;
  2622. }
  2623. }
  2624. for (auto & [name, value] : args.kwargs) {
  2625. size_t i;
  2626. if (name == "start") i = 0;
  2627. else if (name == "end") i = 1;
  2628. else if (name == "step") i = 2;
  2629. else throw std::runtime_error("Unknown argument " + name + " for function range");
  2630. if (param_set[i]) {
  2631. throw std::runtime_error("Duplicate argument " + name + " for function range");
  2632. }
  2633. startEndStep[i] = value.get<int64_t>();
  2634. param_set[i] = true;
  2635. }
  2636. if (!param_set[1]) {
  2637. throw std::runtime_error("Missing required argument 'end' for function range");
  2638. }
  2639. int64_t start = param_set[0] ? startEndStep[0] : 0;
  2640. int64_t end = startEndStep[1];
  2641. int64_t step = param_set[2] ? startEndStep[2] : 1;
  2642. auto res = Value::array();
  2643. if (step > 0) {
  2644. for (int64_t i = start; i < end; i += step) {
  2645. res.push_back(Value(i));
  2646. }
  2647. } else {
  2648. for (int64_t i = start; i > end; i += step) {
  2649. res.push_back(Value(i));
  2650. }
  2651. }
  2652. return res;
  2653. }));
  2654. return std::make_shared<Context>(std::move(globals));
  2655. }
  2656. inline std::shared_ptr<Context> Context::make(Value && values, const std::shared_ptr<Context> & parent) {
  2657. return std::make_shared<Context>(values.is_null() ? Value::object() : std::move(values), parent);
  2658. }
  2659. } // namespace minja