-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathminja.hpp
2788 lines (2541 loc) · 113 KB
/
minja.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2024 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
// SPDX-License-Identifier: MIT
#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <memory>
#include <stdexcept>
#include <sstream>
#include <unordered_set>
#include <json.hpp>
using json = nlohmann::ordered_json;
namespace minja {
class Context;
struct Options {
bool trim_blocks; // removes the first newline after a block
bool lstrip_blocks; // removes leading whitespace on the line of the block
bool keep_trailing_newline; // don't remove last newline
};
struct ArgumentsValue;
inline std::string normalize_newlines(const std::string & s) {
#ifdef _WIN32
static const std::regex nl_regex("\r\n");
return std::regex_replace(s, nl_regex, "\n");
#else
return s;
#endif
}
/* Values that behave roughly like in Python. */
class Value : public std::enable_shared_from_this<Value> {
public:
using CallableType = std::function<Value(const std::shared_ptr<Context> &, ArgumentsValue &)>;
using FilterType = std::function<Value(const std::shared_ptr<Context> &, ArgumentsValue &)>;
private:
using ObjectType = nlohmann::ordered_map<json, Value>; // Only contains primitive keys
using ArrayType = std::vector<Value>;
std::shared_ptr<ArrayType> array_;
std::shared_ptr<ObjectType> object_;
std::shared_ptr<CallableType> callable_;
json primitive_;
Value(const std::shared_ptr<ArrayType> & array) : array_(array) {}
Value(const std::shared_ptr<ObjectType> & object) : object_(object) {}
Value(const std::shared_ptr<CallableType> & callable) : object_(std::make_shared<ObjectType>()), callable_(callable) {}
/* Python-style string repr */
static void dump_string(const json & primitive, std::ostringstream & out, char string_quote = '\'') {
if (!primitive.is_string()) throw std::runtime_error("Value is not a string: " + primitive.dump());
auto s = primitive.dump();
if (string_quote == '"' || s.find('\'') != std::string::npos) {
out << s;
return;
}
// Reuse json dump, just changing string quotes
out << string_quote;
for (size_t i = 1, n = s.size() - 1; i < n; ++i) {
if (s[i] == '\\' && s[i + 1] == '"') {
out << '"';
i++;
} else if (s[i] == string_quote) {
out << '\\' << string_quote;
} else {
out << s[i];
}
}
out << string_quote;
}
void dump(std::ostringstream & out, int indent = -1, int level = 0, bool to_json = false) const {
auto print_indent = [&](int level) {
if (indent > 0) {
out << "\n";
for (int i = 0, n = level * indent; i < n; ++i) out << ' ';
}
};
auto print_sub_sep = [&]() {
out << ',';
if (indent < 0) out << ' ';
else print_indent(level + 1);
};
auto string_quote = to_json ? '"' : '\'';
if (is_null()) out << "null";
else if (array_) {
out << "[";
print_indent(level + 1);
for (size_t i = 0; i < array_->size(); ++i) {
if (i) print_sub_sep();
(*array_)[i].dump(out, indent, level + 1, to_json);
}
print_indent(level);
out << "]";
} else if (object_) {
out << "{";
print_indent(level + 1);
for (auto begin = object_->begin(), it = begin; it != object_->end(); ++it) {
if (it != begin) print_sub_sep();
if (it->first.is_string()) {
dump_string(it->first, out, string_quote);
} else {
out << string_quote << it->first.dump() << string_quote;
}
out << ": ";
it->second.dump(out, indent, level + 1, to_json);
}
print_indent(level);
out << "}";
} else if (callable_) {
throw std::runtime_error("Cannot dump callable to JSON");
} else if (is_boolean() && !to_json) {
out << (this->to_bool() ? "True" : "False");
} else if (is_string() && !to_json) {
dump_string(primitive_, out, string_quote);
} else {
out << primitive_.dump();
}
}
public:
Value() {}
Value(const bool& v) : primitive_(v) {}
Value(const int64_t & v) : primitive_(v) {}
Value(const double& v) : primitive_(v) {}
Value(const std::nullptr_t &) {}
Value(const std::string & v) : primitive_(v) {}
Value(const char * v) : primitive_(std::string(v)) {}
Value(const json & v) {
if (v.is_object()) {
auto object = std::make_shared<ObjectType>();
for (auto it = v.begin(); it != v.end(); ++it) {
(*object)[it.key()] = it.value();
}
object_ = std::move(object);
} else if (v.is_array()) {
auto array = std::make_shared<ArrayType>();
for (const auto& item : v) {
array->push_back(Value(item));
}
array_ = array;
} else {
primitive_ = v;
}
}
std::vector<Value> keys() {
if (!object_) throw std::runtime_error("Value is not an object: " + dump());
std::vector<Value> res;
for (const auto& item : *object_) {
res.push_back(item.first);
}
return res;
}
size_t size() const {
if (is_object()) return object_->size();
if (is_array()) return array_->size();
if (is_string()) return primitive_.get<std::string>().length();
throw std::runtime_error("Value is not an array or object: " + dump());
}
static Value array(const std::vector<Value> values = {}) {
auto array = std::make_shared<ArrayType>();
for (const auto& item : values) {
array->push_back(item);
}
return Value(array);
}
static Value object(const std::shared_ptr<ObjectType> object = std::make_shared<ObjectType>()) {
return Value(object);
}
static Value callable(const CallableType & callable) {
return Value(std::make_shared<CallableType>(callable));
}
void insert(size_t index, const Value& v) {
if (!array_)
throw std::runtime_error("Value is not an array: " + dump());
array_->insert(array_->begin() + index, v);
}
void push_back(const Value& v) {
if (!array_)
throw std::runtime_error("Value is not an array: " + dump());
array_->push_back(v);
}
Value pop(const Value& index) {
if (is_array()) {
if (array_->empty())
throw std::runtime_error("pop from empty list");
if (index.is_null()) {
auto ret = array_->back();
array_->pop_back();
return ret;
} else if (!index.is_number_integer()) {
throw std::runtime_error("pop index must be an integer: " + index.dump());
} else {
auto i = index.get<int>();
if (i < 0 || i >= static_cast<int>(array_->size()))
throw std::runtime_error("pop index out of range: " + index.dump());
auto it = array_->begin() + (i < 0 ? array_->size() + i : i);
auto ret = *it;
array_->erase(it);
return ret;
}
} else if (is_object()) {
if (!index.is_hashable())
throw std::runtime_error("Unashable type: " + index.dump());
auto it = object_->find(index.primitive_);
if (it == object_->end())
throw std::runtime_error("Key not found: " + index.dump());
auto ret = it->second;
object_->erase(it);
return ret;
} else {
throw std::runtime_error("Value is not an array or object: " + dump());
}
}
Value get(const Value& key) {
if (array_) {
if (!key.is_number_integer()) {
return Value();
}
auto index = key.get<int>();
return array_->at(index < 0 ? array_->size() + index : index);
} else if (object_) {
if (!key.is_hashable()) throw std::runtime_error("Unashable type: " + dump());
auto it = object_->find(key.primitive_);
if (it == object_->end()) return Value();
return it->second;
}
return Value();
}
void set(const Value& key, const Value& value) {
if (!object_) throw std::runtime_error("Value is not an object: " + dump());
if (!key.is_hashable()) throw std::runtime_error("Unashable type: " + dump());
(*object_)[key.primitive_] = value;
}
Value call(const std::shared_ptr<Context> & context, ArgumentsValue & args) const {
if (!callable_) throw std::runtime_error("Value is not callable: " + dump());
return (*callable_)(context, args);
}
bool is_object() const { return !!object_; }
bool is_array() const { return !!array_; }
bool is_callable() const { return !!callable_; }
bool is_null() const { return !object_ && !array_ && primitive_.is_null() && !callable_; }
bool is_boolean() const { return primitive_.is_boolean(); }
bool is_number_integer() const { return primitive_.is_number_integer(); }
bool is_number_float() const { return primitive_.is_number_float(); }
bool is_number() const { return primitive_.is_number(); }
bool is_string() const { return primitive_.is_string(); }
bool is_iterable() const { return is_array() || is_object() || is_string(); }
bool is_primitive() const { return !array_ && !object_ && !callable_; }
bool is_hashable() const { return is_primitive(); }
bool empty() const {
if (is_null())
throw std::runtime_error("Undefined value or reference");
if (is_string()) return primitive_.empty();
if (is_array()) return array_->empty();
if (is_object()) return object_->empty();
return false;
}
void for_each(const std::function<void(Value &)> & callback) const {
if (is_null())
throw std::runtime_error("Undefined value or reference");
if (array_) {
for (auto& item : *array_) {
callback(item);
}
} else if (object_) {
for (auto & item : *object_) {
Value key(item.first);
callback(key);
}
} else if (is_string()) {
for (char c : primitive_.get<std::string>()) {
auto val = Value(std::string(1, c));
callback(val);
}
} else {
throw std::runtime_error("Value is not iterable: " + dump());
}
}
bool to_bool() const {
if (is_null()) return false;
if (is_boolean()) return get<bool>();
if (is_number()) return get<double>() != 0;
if (is_string()) return !get<std::string>().empty();
if (is_array()) return !empty();
return true;
}
int64_t to_int() const {
if (is_null()) return 0;
if (is_boolean()) return get<bool>() ? 1 : 0;
if (is_number()) return static_cast<int64_t>(get<double>());
if (is_string()) {
try {
return std::stol(get<std::string>());
} catch (const std::exception &) {
return 0;
}
}
return 0;
}
bool operator<(const Value & other) const {
if (is_null())
throw std::runtime_error("Undefined value or reference");
if (is_number() && other.is_number()) return get<double>() < other.get<double>();
if (is_string() && other.is_string()) return get<std::string>() < other.get<std::string>();
throw std::runtime_error("Cannot compare values: " + dump() + " < " + other.dump());
}
bool operator>=(const Value & other) const { return !(*this < other); }
bool operator>(const Value & other) const {
if (is_null())
throw std::runtime_error("Undefined value or reference");
if (is_number() && other.is_number()) return get<double>() > other.get<double>();
if (is_string() && other.is_string()) return get<std::string>() > other.get<std::string>();
throw std::runtime_error("Cannot compare values: " + dump() + " > " + other.dump());
}
bool operator<=(const Value & other) const { return !(*this > other); }
bool operator==(const Value & other) const {
if (callable_ || other.callable_) {
if (callable_.get() != other.callable_.get()) return false;
}
if (array_) {
if (!other.array_) return false;
if (array_->size() != other.array_->size()) return false;
for (size_t i = 0; i < array_->size(); ++i) {
if (!(*array_)[i].to_bool() || !(*other.array_)[i].to_bool() || (*array_)[i] != (*other.array_)[i]) return false;
}
return true;
} else if (object_) {
if (!other.object_) return false;
if (object_->size() != other.object_->size()) return false;
for (const auto& item : *object_) {
if (!item.second.to_bool() || !other.object_->count(item.first) || item.second != other.object_->at(item.first)) return false;
}
return true;
} else {
return primitive_ == other.primitive_;
}
}
bool operator!=(const Value & other) const { return !(*this == other); }
bool contains(const char * key) const { return contains(std::string(key)); }
bool contains(const std::string & key) const {
if (array_) {
return false;
} else if (object_) {
return object_->find(key) != object_->end();
} else {
throw std::runtime_error("contains can only be called on arrays and objects: " + dump());
}
}
bool contains(const Value & value) const {
if (is_null())
throw std::runtime_error("Undefined value or reference");
if (array_) {
for (const auto& item : *array_) {
if (item.to_bool() && item == value) return true;
}
return false;
} else if (object_) {
if (!value.is_hashable()) throw std::runtime_error("Unashable type: " + value.dump());
return object_->find(value.primitive_) != object_->end();
} else {
throw std::runtime_error("contains can only be called on arrays and objects: " + dump());
}
}
void erase(size_t index) {
if (!array_) throw std::runtime_error("Value is not an array: " + dump());
array_->erase(array_->begin() + index);
}
void erase(const std::string & key) {
if (!object_) throw std::runtime_error("Value is not an object: " + dump());
object_->erase(key);
}
const Value& at(const Value & index) const {
return const_cast<Value*>(this)->at(index);
}
Value& at(const Value & index) {
if (!index.is_hashable()) throw std::runtime_error("Unashable type: " + dump());
if (is_array()) return array_->at(index.get<int>());
if (is_object()) return object_->at(index.primitive_);
throw std::runtime_error("Value is not an array or object: " + dump());
}
const Value& at(size_t index) const {
return const_cast<Value*>(this)->at(index);
}
Value& at(size_t index) {
if (is_null())
throw std::runtime_error("Undefined value or reference");
if (is_array()) return array_->at(index);
if (is_object()) return object_->at(index);
throw std::runtime_error("Value is not an array or object: " + dump());
}
template <typename T>
T get(const std::string & key, T default_value) const {
if (!contains(key)) return default_value;
return at(key).get<T>();
}
template <typename T>
T get() const {
if (is_primitive()) return primitive_.get<T>();
throw std::runtime_error("get<T> not defined for this value type: " + dump());
}
std::string dump(int indent=-1, bool to_json=false) const {
std::ostringstream out;
dump(out, indent, 0, to_json);
return out.str();
}
Value operator-() const {
if (is_number_integer())
return -get<int64_t>();
else
return -get<double>();
}
std::string to_str() const {
if (is_string()) return get<std::string>();
if (is_number_integer()) return std::to_string(get<int64_t>());
if (is_number_float()) return std::to_string(get<double>());
if (is_boolean()) return get<bool>() ? "True" : "False";
if (is_null()) return "None";
return dump();
}
Value operator+(const Value& rhs) const {
if (is_string() || rhs.is_string()) {
return to_str() + rhs.to_str();
} else if (is_number_integer() && rhs.is_number_integer()) {
return get<int64_t>() + rhs.get<int64_t>();
} else if (is_array() && rhs.is_array()) {
auto res = Value::array();
for (const auto& item : *array_) res.push_back(item);
for (const auto& item : *rhs.array_) res.push_back(item);
return res;
} else {
return get<double>() + rhs.get<double>();
}
}
Value operator-(const Value& rhs) const {
if (is_number_integer() && rhs.is_number_integer())
return get<int64_t>() - rhs.get<int64_t>();
else
return get<double>() - rhs.get<double>();
}
Value operator*(const Value& rhs) const {
if (is_string() && rhs.is_number_integer()) {
std::ostringstream out;
for (int64_t i = 0, n = rhs.get<int64_t>(); i < n; ++i) {
out << to_str();
}
return out.str();
}
else if (is_number_integer() && rhs.is_number_integer())
return get<int64_t>() * rhs.get<int64_t>();
else
return get<double>() * rhs.get<double>();
}
Value operator/(const Value& rhs) const {
if (is_number_integer() && rhs.is_number_integer())
return get<int64_t>() / rhs.get<int64_t>();
else
return get<double>() / rhs.get<double>();
}
Value operator%(const Value& rhs) const {
return get<int64_t>() % rhs.get<int64_t>();
}
};
struct ArgumentsValue {
std::vector<Value> args;
std::vector<std::pair<std::string, Value>> kwargs;
bool has_named(const std::string & name) {
for (const auto & p : kwargs) {
if (p.first == name) return true;
}
return false;
}
Value get_named(const std::string & name) {
for (const auto & [key, value] : kwargs) {
if (key == name) return value;
}
return Value();
}
bool empty() {
return args.empty() && kwargs.empty();
}
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) {
if (args.size() < pos_count.first || args.size() > pos_count.second || kwargs.size() < kw_count.first || kwargs.size() > kw_count.second) {
std::ostringstream out;
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";
throw std::runtime_error(out.str());
}
}
};
template <>
inline json Value::get<json>() const {
if (is_primitive()) return primitive_;
if (is_null()) return json();
if (array_) {
std::vector<json> res;
for (const auto& item : *array_) {
res.push_back(item.get<json>());
}
return res;
}
if (object_) {
json res = json::object();
for (const auto& [key, value] : *object_) {
if (key.is_string()) {
res[key.get<std::string>()] = value.get<json>();
} else if (key.is_primitive()) {
res[key.dump()] = value.get<json>();
} else {
throw std::runtime_error("Invalid key type for conversion to JSON: " + key.dump());
}
}
if (is_callable()) {
res["__callable__"] = true;
}
return res;
}
throw std::runtime_error("get<json> not defined for this value type: " + dump());
}
} // namespace minja
namespace std {
template <>
struct hash<minja::Value> {
size_t operator()(const minja::Value & v) const {
if (!v.is_hashable())
throw std::runtime_error("Unsupported type for hashing: " + v.dump());
return std::hash<json>()(v.get<json>());
}
};
} // namespace std
namespace minja {
static std::string error_location_suffix(const std::string & source, size_t pos) {
auto get_line = [&](size_t line) {
auto start = source.begin();
for (size_t i = 1; i < line; ++i) {
start = std::find(start, source.end(), '\n') + 1;
}
auto end = std::find(start, source.end(), '\n');
return std::string(start, end);
};
auto start = source.begin();
auto end = source.end();
auto it = start + pos;
auto line = std::count(start, it, '\n') + 1;
auto max_line = std::count(start, end, '\n') + 1;
auto col = pos - std::string(start, it).rfind('\n');
std::ostringstream out;
out << " at row " << line << ", column " << col << ":\n";
if (line > 1) out << get_line(line - 1) << "\n";
out << get_line(line) << "\n";
out << std::string(col - 1, ' ') << "^\n";
if (line < max_line) out << get_line(line + 1) << "\n";
return out.str();
}
class Context : public std::enable_shared_from_this<Context> {
protected:
Value values_;
std::shared_ptr<Context> parent_;
public:
Context(Value && values, const std::shared_ptr<Context> & parent = nullptr) : values_(std::move(values)), parent_(parent) {
if (!values_.is_object()) throw std::runtime_error("Context values must be an object: " + values_.dump());
}
virtual ~Context() {}
static std::shared_ptr<Context> builtins();
static std::shared_ptr<Context> make(Value && values, const std::shared_ptr<Context> & parent = builtins());
std::vector<Value> keys() {
return values_.keys();
}
virtual Value get(const Value & key) {
if (values_.contains(key)) return values_.at(key);
if (parent_) return parent_->get(key);
return Value();
}
virtual Value & at(const Value & key) {
if (values_.contains(key)) return values_.at(key);
if (parent_) return parent_->at(key);
throw std::runtime_error("Undefined variable: " + key.dump());
}
virtual bool contains(const Value & key) {
if (values_.contains(key)) return true;
if (parent_) return parent_->contains(key);
return false;
}
virtual void set(const Value & key, Value & value) {
values_.set(key, value);
}
};
struct Location {
std::shared_ptr<std::string> source;
size_t pos;
};
class Expression {
protected:
virtual Value do_evaluate(const std::shared_ptr<Context> & context) const = 0;
public:
using Parameters = std::vector<std::pair<std::string, std::shared_ptr<Expression>>>;
Location location;
Expression(const Location & location) : location(location) {}
virtual ~Expression() = default;
Value evaluate(const std::shared_ptr<Context> & context) const {
try {
return do_evaluate(context);
} catch (const std::exception & e) {
std::ostringstream out;
out << e.what();
if (location.source) out << error_location_suffix(*location.source, location.pos);
throw std::runtime_error(out.str());
}
}
};
class VariableExpr : public Expression {
std::string name;
public:
VariableExpr(const Location & location, const std::string& n)
: Expression(location), name(n) {}
std::string get_name() const { return name; }
Value do_evaluate(const std::shared_ptr<Context> & context) const override {
if (!context->contains(name)) {
return Value();
}
return context->at(name);
}
};
static void destructuring_assign(const std::vector<std::string> & var_names, const std::shared_ptr<Context> & context, Value& item) {
if (var_names.size() == 1) {
Value name(var_names[0]);
context->set(name, item);
} else {
if (!item.is_array() || item.size() != var_names.size()) {
throw std::runtime_error("Mismatched number of variables and items in destructuring assignment");
}
for (size_t i = 0; i < var_names.size(); ++i) {
context->set(var_names[i], item.at(i));
}
}
}
enum SpaceHandling { Keep, Strip, StripSpaces, StripNewline };
class TemplateToken {
public:
enum class Type { Text, Expression, If, Else, Elif, EndIf, For, EndFor, Set, EndSet, Comment, Macro, EndMacro, Filter, EndFilter };
static std::string typeToString(Type t) {
switch (t) {
case Type::Text: return "text";
case Type::Expression: return "expression";
case Type::If: return "if";
case Type::Else: return "else";
case Type::Elif: return "elif";
case Type::EndIf: return "endif";
case Type::For: return "for";
case Type::EndFor: return "endfor";
case Type::Set: return "set";
case Type::EndSet: return "endset";
case Type::Comment: return "comment";
case Type::Macro: return "macro";
case Type::EndMacro: return "endmacro";
case Type::Filter: return "filter";
case Type::EndFilter: return "endfilter";
}
return "Unknown";
}
TemplateToken(Type type, const Location & location, SpaceHandling pre, SpaceHandling post) : type(type), location(location), pre_space(pre), post_space(post) {}
virtual ~TemplateToken() = default;
Type type;
Location location;
SpaceHandling pre_space = SpaceHandling::Keep;
SpaceHandling post_space = SpaceHandling::Keep;
};
struct TextTemplateToken : public TemplateToken {
std::string text;
TextTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, const std::string& t) : TemplateToken(Type::Text, location, pre, post), text(t) {}
};
struct ExpressionTemplateToken : public TemplateToken {
std::shared_ptr<Expression> expr;
ExpressionTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, std::shared_ptr<Expression> && e) : TemplateToken(Type::Expression, location, pre, post), expr(std::move(e)) {}
};
struct IfTemplateToken : public TemplateToken {
std::shared_ptr<Expression> condition;
IfTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, std::shared_ptr<Expression> && c) : TemplateToken(Type::If, location, pre, post), condition(std::move(c)) {}
};
struct ElifTemplateToken : public TemplateToken {
std::shared_ptr<Expression> condition;
ElifTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, std::shared_ptr<Expression> && c) : TemplateToken(Type::Elif, location, pre, post), condition(std::move(c)) {}
};
struct ElseTemplateToken : public TemplateToken {
ElseTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::Else, location, pre, post) {}
};
struct EndIfTemplateToken : public TemplateToken {
EndIfTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::EndIf, location, pre, post) {}
};
struct MacroTemplateToken : public TemplateToken {
std::shared_ptr<VariableExpr> name;
Expression::Parameters params;
MacroTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, std::shared_ptr<VariableExpr> && n, Expression::Parameters && p)
: TemplateToken(Type::Macro, location, pre, post), name(std::move(n)), params(std::move(p)) {}
};
struct EndMacroTemplateToken : public TemplateToken {
EndMacroTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::EndMacro, location, pre, post) {}
};
struct FilterTemplateToken : public TemplateToken {
std::shared_ptr<Expression> filter;
FilterTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, std::shared_ptr<Expression> && filter)
: TemplateToken(Type::Filter, location, pre, post), filter(std::move(filter)) {}
};
struct EndFilterTemplateToken : public TemplateToken {
EndFilterTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::EndFilter, location, pre, post) {}
};
struct ForTemplateToken : public TemplateToken {
std::vector<std::string> var_names;
std::shared_ptr<Expression> iterable;
std::shared_ptr<Expression> condition;
bool recursive;
ForTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, const std::vector<std::string> & vns, std::shared_ptr<Expression> && iter,
std::shared_ptr<Expression> && c, bool r)
: TemplateToken(Type::For, location, pre, post), var_names(vns), iterable(std::move(iter)), condition(std::move(c)), recursive(r) {}
};
struct EndForTemplateToken : public TemplateToken {
EndForTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::EndFor, location, pre, post) {}
};
struct SetTemplateToken : public TemplateToken {
std::string ns;
std::vector<std::string> var_names;
std::shared_ptr<Expression> value;
SetTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, const std::string & ns, const std::vector<std::string> & vns, std::shared_ptr<Expression> && v)
: TemplateToken(Type::Set, location, pre, post), ns(ns), var_names(vns), value(std::move(v)) {}
};
struct EndSetTemplateToken : public TemplateToken {
EndSetTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post) : TemplateToken(Type::EndSet, location, pre, post) {}
};
struct CommentTemplateToken : public TemplateToken {
std::string text;
CommentTemplateToken(const Location & location, SpaceHandling pre, SpaceHandling post, const std::string& t) : TemplateToken(Type::Comment, location, pre, post), text(t) {}
};
class TemplateNode {
Location location_;
protected:
virtual void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const = 0;
public:
TemplateNode(const Location & location) : location_(location) {}
void render(std::ostringstream & out, const std::shared_ptr<Context> & context) const {
try {
do_render(out, context);
} catch (const std::exception & e) {
std::ostringstream err;
err << e.what();
if (location_.source) err << error_location_suffix(*location_.source, location_.pos);
throw std::runtime_error(err.str());
}
}
const Location & location() const { return location_; }
virtual ~TemplateNode() = default;
std::string render(const std::shared_ptr<Context> & context) const {
std::ostringstream out;
render(out, context);
return out.str();
}
};
class SequenceNode : public TemplateNode {
std::vector<std::shared_ptr<TemplateNode>> children;
public:
SequenceNode(const Location & location, std::vector<std::shared_ptr<TemplateNode>> && c)
: TemplateNode(location), children(std::move(c)) {}
void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const override {
for (const auto& child : children) child->render(out, context);
}
};
class TextNode : public TemplateNode {
std::string text;
public:
TextNode(const Location & location, const std::string& t) : TemplateNode(location), text(t) {}
void do_render(std::ostringstream & out, const std::shared_ptr<Context> &) const override {
out << text;
}
};
class ExpressionNode : public TemplateNode {
std::shared_ptr<Expression> expr;
public:
ExpressionNode(const Location & location, std::shared_ptr<Expression> && e) : TemplateNode(location), expr(std::move(e)) {}
void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const override {
if (!expr) throw std::runtime_error("ExpressionNode.expr is null");
auto result = expr->evaluate(context);
if (result.is_string()) {
out << result.get<std::string>();
} else if (result.is_boolean()) {
out << (result.get<bool>() ? "True" : "False");
} else if (!result.is_null()) {
out << result.dump();
}
}
};
class IfNode : public TemplateNode {
std::vector<std::pair<std::shared_ptr<Expression>, std::shared_ptr<TemplateNode>>> cascade;
public:
IfNode(const Location & location, std::vector<std::pair<std::shared_ptr<Expression>, std::shared_ptr<TemplateNode>>> && c)
: TemplateNode(location), cascade(std::move(c)) {}
void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const override {
for (const auto& branch : cascade) {
auto enter_branch = true;
if (branch.first) {
enter_branch = branch.first->evaluate(context).to_bool();
}
if (enter_branch) {
if (!branch.second) throw std::runtime_error("IfNode.cascade.second is null");
branch.second->render(out, context);
return;
}
}
}
};
class ForNode : public TemplateNode {
std::vector<std::string> var_names;
std::shared_ptr<Expression> iterable;
std::shared_ptr<Expression> condition;
std::shared_ptr<TemplateNode> body;
bool recursive;
std::shared_ptr<TemplateNode> else_body;
public:
ForNode(const Location & location, std::vector<std::string> && var_names, std::shared_ptr<Expression> && iterable,
std::shared_ptr<Expression> && condition, std::shared_ptr<TemplateNode> && body, bool recursive, std::shared_ptr<TemplateNode> && else_body)
: 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)) {}
void do_render(std::ostringstream & out, const std::shared_ptr<Context> & context) const override {
// https://jinja.palletsprojects.com/en/3.0.x/templates/#for
if (!iterable) throw std::runtime_error("ForNode.iterable is null");
if (!body) throw std::runtime_error("ForNode.body is null");
auto iterable_value = iterable->evaluate(context);
Value::CallableType loop_function;
std::function<void(Value&)> visit = [&](Value& iter) {
auto filtered_items = Value::array();
if (!iter.is_null()) {
if (!iterable_value.is_iterable()) {
throw std::runtime_error("For loop iterable must be iterable: " + iterable_value.dump());
}
iterable_value.for_each([&](Value & item) {
destructuring_assign(var_names, context, item);
if (!condition || condition->evaluate(context).to_bool()) {
filtered_items.push_back(item);
}
});
}
if (filtered_items.empty()) {
if (else_body) {
else_body->render(out, context);
}
} else {
auto loop = recursive ? Value::callable(loop_function) : Value::object();
loop.set("length", (int64_t) filtered_items.size());
size_t cycle_index = 0;
loop.set("cycle", Value::callable([&](const std::shared_ptr<Context> &, ArgumentsValue & args) {
if (args.args.empty() || !args.kwargs.empty()) {
throw std::runtime_error("cycle() expects at least 1 positional argument and no named arg");
}
auto item = args.args[cycle_index];
cycle_index = (cycle_index + 1) % args.args.size();
return item;
}));
auto loop_context = Context::make(Value::object(), context);
loop_context->set("loop", loop);
for (size_t i = 0, n = filtered_items.size(); i < n; ++i) {
auto & item = filtered_items.at(i);
destructuring_assign(var_names, loop_context, item);
loop.set("index", (int64_t) i + 1);
loop.set("index0", (int64_t) i);
loop.set("revindex", (int64_t) (n - i));
loop.set("revindex0", (int64_t) (n - i - 1));
loop.set("length", (int64_t) n);
loop.set("first", i == 0);
loop.set("last", i == (n - 1));
loop.set("previtem", i > 0 ? filtered_items.at(i - 1) : Value());
loop.set("nextitem", i < n - 1 ? filtered_items.at(i + 1) : Value());
body->render(out, loop_context);
}
}
};
if (recursive) {
loop_function = [&](const std::shared_ptr<Context> &, ArgumentsValue & args) {
if (args.args.size() != 1 || !args.kwargs.empty() || !args.args[0].is_array()) {
throw std::runtime_error("loop() expects exactly 1 positional iterable argument");
}
auto & items = args.args[0];
visit(items);
return Value();
};
}
visit(iterable_value);
}
};
class MacroNode : public TemplateNode {
std::shared_ptr<VariableExpr> name;
Expression::Parameters params;
std::shared_ptr<TemplateNode> body;
std::unordered_map<std::string, size_t> named_param_positions;
public:
MacroNode(const Location & location, std::shared_ptr<VariableExpr> && n, Expression::Parameters && p, std::shared_ptr<TemplateNode> && b)
: TemplateNode(location), name(std::move(n)), params(std::move(p)), body(std::move(b)) {
for (size_t i = 0; i < params.size(); ++i) {
const auto & name = params[i].first;
if (!name.empty()) {
named_param_positions[name] = i;
}
}
}
void do_render(std::ostringstream &, const std::shared_ptr<Context> & macro_context) const override {
if (!name) throw std::runtime_error("MacroNode.name is null");
if (!body) throw std::runtime_error("MacroNode.body is null");
auto callable = Value::callable([&](const std::shared_ptr<Context> & context, ArgumentsValue & args) {
auto call_context = macro_context;
std::vector<bool> param_set(params.size(), false);
for (size_t i = 0, n = args.args.size(); i < n; i++) {
auto & arg = args.args[i];
if (i >= params.size()) throw std::runtime_error("Too many positional arguments for macro " + name->get_name());
param_set[i] = true;
auto & param_name = params[i].first;
call_context->set(param_name, arg);