-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathHandlebars.cpp
More file actions
7026 lines (6576 loc) · 211 KB
/
Copy pathHandlebars.cpp
File metadata and controls
7026 lines (6576 loc) · 211 KB
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
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
// Copyright (c) 2023 Alan de Freitas (alandefreitas@gmail.com)
//
// Official repository: https://github.com/cppalliance/mrdocs
//
#include <mrdocs/Support/Handlebars.hpp>
#include <mrdocs/Support/Path.hpp>
#include <algorithm>
#include <array>
#include <charconv>
#include <chrono>
#include <filesystem>
#include <format>
#include <print>
#include <ranges>
#include <unordered_set>
#include <utility>
namespace mrdocs {
// ==============================================================
// Output
// ==============================================================
OutputRef&
OutputRef::
write_impl( std::string_view sv )
{
// ==========================================
// No indent
// ==========================================
if (indent_ == 0)
{
fptr_( out_, sv );
return *this;
}
std::size_t pos = sv.find('\n');
if (pos == std::string_view::npos)
{
fptr_( out_, sv );
return *this;
}
// ==========================================
// Indented
// ==========================================
fptr_( out_, sv.substr(0, pos + 1) );
++pos;
while (pos < sv.size())
{
for (std::size_t i = 0; i < indent_; ++i)
{
fptr_( out_, std::string_view(" ") );
}
std::size_t next = sv.find('\n', pos);
if (next == std::string_view::npos)
{
fptr_( out_, sv.substr(pos) );
return *this;
}
fptr_( out_, sv.substr(pos, (next - pos) + 1) );
pos = next + 1;
}
return *this;
}
// ==============================================================
// Utility functions
// ==============================================================
bool
isEmpty(dom::Value const& arg)
{
if (arg.isArray())
{
return arg.getArray().empty();
}
if (arg.isInteger())
{
return false;
}
return !arg.isTruthy();
}
class OverlayObjectImpl : public dom::ObjectImpl
{
std::vector<dom::Object> grandParents_;
dom::Object parent_;
dom::Object child_;
public:
~OverlayObjectImpl() override = default;
OverlayObjectImpl(dom::Object parent)
{
auto* parImpl = parent.impl().get();
auto* parOverlay = dynamic_cast<OverlayObjectImpl*>(parImpl);
if (parOverlay == nullptr)
{
parent_ = std::move(parent);
}
else if (parOverlay->child_.empty())
{
grandParents_ = parOverlay->grandParents_;
parent_ = parOverlay->parent_;
}
else
{
grandParents_.push_back(parOverlay->parent_);
grandParents_.insert(
grandParents_.end(),
parOverlay->grandParents_.begin(),
parOverlay->grandParents_.end());
parent_ = parOverlay->child_;
}
}
OverlayObjectImpl(dom::Object child, dom::Object parent)
: OverlayObjectImpl(std::move(parent))
{
child_ = std::move(child);
auto* childOverlay = dynamic_cast<OverlayObjectImpl*>(child_.impl().get());
if (childOverlay != nullptr)
{
grandParents_.insert(
grandParents_.begin(),
parent_);
grandParents_.insert(
grandParents_.end(),
childOverlay->grandParents_.begin(),
childOverlay->grandParents_.end());
parent_ = childOverlay->parent_;
child_ = childOverlay->child_;
}
}
std::size_t size() const override
{
std::size_t n = parent_.size() + child_.size();
child_.visit([&](dom::String const& key, dom::Value const&)
{
if (parent_.exists(key))
{
--n;
}
else
{
for (auto const& grandParent : grandParents_)
{
if (grandParent.exists(key))
{
--n;
break;
}
}
}
});
return n;
};
dom::Value get(std::string_view key) const override
{
if (child_.exists(key))
{
return child_.get(key);
}
if (parent_.exists(key))
{
return parent_.get(key);
}
for (auto const& grandParent : grandParents_)
{
if (grandParent.exists(key))
{
return grandParent.get(key);
}
}
return dom::Kind::Undefined;
}
void set(dom::String key, dom::Value value) override
{
child_.set(key, std::move(value));
};
bool visit(std::function<bool(dom::String, dom::Value)> fn) const override
{
if (!child_.visit(fn))
{
return false;
}
auto visit_if_not_inchild = [&](
dom::String const& key, dom::Value const& value)
{
if (!child_.exists(key))
{
return fn(key, value);
}
return true;
};
if (!parent_.visit(visit_if_not_inchild))
{
return false;
}
for (std::size_t i = 0; i < grandParents_.size(); ++i)
{
auto visit_if_not_in_prev = [&](
dom::String const& key, dom::Value const& value)
{
if (child_.exists(key))
{
return true;
}
if (parent_.exists(key))
{
return true;
}
for (std::size_t j = 0; j < i; ++j)
{
if (grandParents_[j].exists(key))
{
return true;
}
}
return fn(key, value);
};
if (!grandParents_[i].visit(visit_if_not_in_prev))
{
return false;
}
}
return true;
}
bool exists(std::string_view key) const override
{
if (child_.exists(key))
{
return true;
}
if (parent_.exists(key))
{
return true;
}
return std::ranges::any_of(
grandParents_,
[&](dom::Object const& grandParent)
{
return grandParent.exists(key);
});
}
};
dom::Object
createFrame(dom::Object const& parent)
{
return dom::newObject<OverlayObjectImpl>(parent);
}
dom::Object
createFrame(dom::Object const& child, dom::Object const& parent)
{
return dom::newObject<OverlayObjectImpl>(child, parent);
}
dom::Object
createFrame(dom::Value const& parent)
{
if (parent.isObject())
{
return createFrame(parent.getObject());
}
return {};
}
dom::Value
safeString(std::string_view str)
{
dom::Value w(str);
w.kind_ = dom::Kind::SafeString;
return w;
}
dom::Value
safeString(dom::Value const& str)
{
if (str.isString() || str.isSafeString())
{
return safeString(str.getString().get());
}
return {};
}
void
HTMLEscape(
OutputRef& out,
std::string_view str)
{
// https://github.com/handlebars-lang/handlebars.js/blob/master/lib/handlebars/utils.js
static constexpr std::pair<char, std::string_view>
escapeMap[] = {
{'&', "&"},
{'<', "<"},
{'>', ">"},
{'"', """},
{'\'', "'"},
{'`', "`"},
{'=', "="}
};
static constexpr auto badChars = std::views::keys(escapeMap);
for (auto c : str)
{
if (auto it = std::ranges::find(badChars, c); it != badChars.end())
{
out << it.base()->second;
}
else
{
out << c;
}
}
}
std::string
HTMLEscape(std::string_view str)
{
std::string result;
OutputRef out(result);
HTMLEscape(out, str);
return result;
}
void
escapeExpression(
OutputRef out,
std::string_view str,
HandlebarsOptions const& opt)
{
if (opt.noEscape)
{
out << str;
}
else
{
opt.escapeFunction(out, str);
}
}
static void
format_to(
OutputRef out,
dom::Value const& value,
HandlebarsOptions const& opt)
{
if (value.isString())
{
escapeExpression(out, value.getString(), opt);
}
else if (value.isSafeString())
{
out << value.getString();
}
else if (value.isInteger())
{
out << value.getInteger();
}
else if (value.isBoolean())
{
if (value.getBool())
{
out << "true";
}
else
{
out << "false";
}
}
else if (value.isArray())
{
out << "[";
dom::Array const& array = value.getArray();
if (!array.empty())
{
format_to(out, array.at(0), opt);
dom::Array::size_type const n = array.size();
for (std::size_t i = 1; i < n; ++i) {
out << ",";
format_to(out, array.at(i), opt);
}
}
out << "]";
}
else if (value.isObject())
{
out << "[object Object]";
}
}
static constexpr
std::string_view
trim_delimiters(std::string_view expression, std::string_view delimiters)
{
auto pos = expression.find_first_not_of(delimiters);
if (pos == std::string_view::npos)
{
return "";
}
expression.remove_prefix(pos);
pos = expression.find_last_not_of(delimiters);
if (pos == std::string_view::npos)
{
return "";
}
expression.remove_suffix(expression.size() - pos - 1);
return expression;
}
static constexpr
std::string_view
trim_ldelimiters(std::string_view expression, std::string_view delimiters)
{
auto pos = expression.find_first_not_of(delimiters);
if (pos == std::string_view::npos)
{
return "";
}
expression.remove_prefix(pos);
return expression;
}
static constexpr
std::string_view
trim_rdelimiters(std::string_view expression, std::string_view delimiters)
{
auto pos = expression.find_last_not_of(delimiters);
if (pos == std::string_view::npos)
{
return "";
}
expression.remove_suffix(expression.size() - pos - 1);
return expression;
}
static constexpr
std::string_view
trim_spaces(std::string_view expression)
{
return trim_delimiters(expression, " \t\r\n");
}
static constexpr
std::string_view
trim_lspaces(std::string_view expression)
{
return trim_ldelimiters(expression, " \t\r\n");
}
static constexpr
std::string_view
trim_rspaces(std::string_view expression)
{
return trim_rdelimiters(expression, " \t\r\n");
}
// ==============================================================
// Helper Callback
// ==============================================================
namespace detail {
/* Holds the state information required for rendering templates.
This structure contains various fields that are used to manage the state
during the rendering process of Handlebars templates.
*/
struct RenderState
{
/* The original template text.
As the templateText being rendered changes,
this is used for features that rely on the
context of the template, such as finding
the position of an error or identifying the
context of a tag.
*/
std::string_view rootTemplateText;
/* The current template text being processed.
This range of chars keeps changing as we
render the template. For instance, when
a tag contains ~, the string is updated
the whitespaces around the tag.
*/
std::string_view templateText;
/* A vector of inline partials view maps.
This vector is used to store maps of inline partials
that are defined directly in the templates.
Each map contains the partials defined on that level.
Any partial in any of the maps can be accessed.
When the level is out of scope, its map is removed.
*/
std::vector<detail::partials_view_map> inlinePartials;
/* A vector of partial block contents.
Keeps all partial blocks, so they can be rendered
at deeper levels when needed.
If no partial block content is provided for
any higher level partial, and a partial attempts to
render {{@partial-block}}, we should return an error
"The partial @partial-block could not be found".
What's tricky is if a nested partial renders
{{> @partial-block}}, and this partial block
includes another {{> @partial-block}}, the second
call should render the partial content of the
outer partial and not recursively render the
inner partial block.
This is achieved by keeping all partial blocks
in this vector and the partialBlockLevel index
to indicate the current level of partial blocks.
This level is usually partialBlocks.size(),
and is decreased when we recursively render
partial blocks at deeper levels so that they
can potentially only use partial blocks from
outer levels instead of always taking the
last element of partialBlocks.back().
*/
std::vector<std::string_view> partialBlocks;
/* The current level of partial blocks.
See `partialBlocks` for more information.
*/
std::size_t partialBlockLevel = 0;
/* The original context object used in the template.
This allows us to always access the initial
context via @root.
This assumes the context is always an object
because the state at deeper levels always
use objects.
If the root context is a dom::Value,
it's available from `rootContext`.
*/
dom::Object context;
/* The root context value.
The root context as a value, when applicable.
In this case, {{.}} can be used to access the
root context.
*/
dom::Value rootContext;
/* A stack of data objects.
This stack is used to keep track of the
context as we render the template at deeper
levels.
Elements are always taken from the highest level,
and elements from lower levels can be accessed
via "..".
*/
std::vector<dom::Object> contextStack;
// A stack of parent context values.
std::vector<dom::Value> parentContext;
/* The block values object used in the template.
Block values can also be accessed from a block,
and they take precedence over the usual data
context.
*/
dom::Object blockValues;
// The block value paths object used in the template.
dom::Object blockValuePaths;
};
}
static bool
isCurrentContextSegment(std::string_view path)
{
return path == "." || path == "this";
}
static bool
isIdChar(char c)
{
// Identifiers may be any unicode character except for the following:
// Whitespace ! " # % & ' ( ) * + , . / ; < = > @ [ \ ] ^ ` { | } ~
static constexpr std::array<char, 32> invalidChars = {
' ', '!', '"', '#', '%', '&', '\'', '(', ')', '*', '+', ',', '.', '/',
';', '<', '=', '>', '@', '[', '\\', ']', '^', '`', '{', '|', '}', '~',
'\t', '\r', '\n', '\0'};
return !std::ranges::any_of(invalidChars, [c](char invalid) { return c == invalid; });
}
static std::string_view
popFirstSegment(std::string_view& path0)
{
// ==============================================================
// Skip dot segments
// ==============================================================
std::string_view path = path0;
while (path.starts_with("./") || path.starts_with("[.]/") || path.starts_with("[.]."))
{
path.remove_prefix(path.front() == '.' ? 2 : 4);
}
// ==============================================================
// Single dot segment
// ==============================================================
if (path == "." || path == "[.]")
{
path0 = {};
return {};
}
// ==============================================================
// Literal segment [...]
// ==============================================================
if (path.starts_with('['))
{
auto pos = path.find_first_of(']');
if (pos == std::string_view::npos)
{
// '[' segment was never closed
path0 = {};
return {};
}
std::string_view seg = path.substr(0, pos + 1);
path = path.substr(pos + 1);
if (path.empty())
{
// rest of the path is empty, so this is the last segment
path0 = path;
return seg;
}
if (path.front() != '.' && path.front() != '/')
{
// segment has no valid continuation, so it's invalid
path0 = path;
return {};
}
path0 = path.substr(1);
return seg;
}
// ==============================================================
// Literal number segment
// ==============================================================
// In a literal number segment the dots are part of the segment
if (
std::ranges::all_of(path, [](char c) { return c == '.' || std::isdigit(c) != 0; }) &&
std::ranges::count(path, '.') < 2)
{
// Number segment
path0 = {};
return path;
}
// ==============================================================
// Dotdot segment
// ==============================================================
// If path starts with dotdot segment, the delimiter needs to be a slash
if (path.starts_with("../"))
{
path0 = path.substr(3);
return path.substr(0, 2);
}
if (path == "..")
{
path0 = {};
return path;
}
// ==============================================================
// Regular ID
// ==============================================================
auto it = std::ranges::find_if_not(path, isIdChar);
auto pos = static_cast<std::size_t>(it - path.begin());
bool endsAtDelimiter = it != path.end() && (*it == '.' || *it == '/');
path0 = path.substr(pos + static_cast<std::size_t>(endsAtDelimiter));
return path.substr(0, pos);
}
struct position_in_text
{
std::size_t line = static_cast<std::size_t>(-1);
std::size_t column = static_cast<std::size_t>(-1);
std::size_t pos = static_cast<std::size_t>(-1);
constexpr
operator bool() const
{
return line != static_cast<std::size_t>(-1);
}
};
static constexpr
position_in_text
find_position_in_text(
std::string_view text,
std::string_view substr)
{
position_in_text res;
if ((substr.data() >= text.data()) &&
(substr.data() <= (text.data() + text.size())))
{
res.pos = static_cast<std::size_t>(substr.data() - text.data());
res.line = static_cast<std::size_t>(
std::ranges::count(text.substr(0, res.pos), '\n') + 1);
if (res.line == 1)
{
res.column = res.pos;
}
else
{
res.column = res.pos - text.rfind('\n', res.pos) - 1;
}
}
return res;
}
[[nodiscard]]
static
Expected<void, HandlebarsError>
checkPath(std::string_view path0, detail::RenderState const& state)
{
std::string_view path = path0;
if (path.starts_with('@')) {
path.remove_prefix(1);
}
std::string_view seg = popFirstSegment(path);
bool areDotDots = seg == "..";
seg = popFirstSegment(path);
while (!seg.empty())
{
bool isDotDot = seg == "..";
bool invalidPath =
(!areDotDots && isDotDot) ||
isCurrentContextSegment(seg);
areDotDots = areDotDots && isDotDot;
if (invalidPath)
{
std::string msg =
"Invalid path: " +
std::string(path0.substr(0, seg.data() + seg.size() - path0.data()));
auto res = find_position_in_text(state.rootTemplateText, path0);
if (res)
{
return Unexpected(
HandlebarsError(msg, res.line, res.column, res.pos));
}
return Unexpected(HandlebarsError(msg));
}
seg = popFirstSegment(path);
}
return {};
}
static std::pair<dom::Value, bool>
lookupPropertyImpl(
dom::Object const& context,
std::string_view path,
detail::RenderState const& state,
HandlebarsOptions const& opt)
{
// Get first value from Object
std::string_view segment = popFirstSegment(path);
bool isLiteral = segment.starts_with('[') && segment.ends_with(']');
std::string_view literalSegment = segment.substr(
1 * static_cast<std::size_t>(isLiteral),
segment.size() - (2 * static_cast<std::size_t>(isLiteral)));
dom::Value cur = nullptr;
if (isCurrentContextSegment(segment))
{
cur = context;
}
else if (!context.exists(literalSegment))
{
if (opt.strict || (opt.assumeObjects && !path.empty()))
{
std::string msg = std::format("\"{}\" not defined in {}",
literalSegment, toString(context));
auto res =
find_position_in_text(state.rootTemplateText, literalSegment);
if (res) {
throw HandlebarsError(msg, res.line, res.column, res.pos);
}
throw HandlebarsError(msg);
}
else
{
return {dom::Kind::Undefined, false};
}
}
else
{
cur = context.get(literalSegment);
}
// Recursively get more values from current value
segment = popFirstSegment(path);
isLiteral = segment.starts_with('[') && segment.ends_with(']');
literalSegment = segment.substr(
1 * static_cast<std::size_t>(isLiteral),
segment.size() - (2 * static_cast<std::size_t>(isLiteral)));
while (!literalSegment.empty())
{
// If current value is an Object, get the next value from it
if (cur.isObject())
{
auto obj = cur.getObject();
if (obj.exists(literalSegment))
{
cur = obj.get(literalSegment);
}
else
{
if (opt.strict)
{
std::string msg = std::format("\"{}\" not defined in {}",
literalSegment, toString(cur));
auto res = find_position_in_text(state.rootTemplateText,
literalSegment);
if (res) {
throw HandlebarsError(msg, res.line, res.column, res.pos);
}
throw HandlebarsError(msg);
}
else
{
return {dom::Kind::Undefined, false};
}
}
}
// If current value is an Array, get the next value the stripped index
else if (cur.isArray())
{
size_t index = 0;
std::from_chars_result res = std::from_chars(
literalSegment.data(),
literalSegment.data() + literalSegment.size(),
index);
if (res.ec != std::errc())
{
return {nullptr, false};
}
auto& arr = cur.getArray();
if (index >= arr.size())
{
return {nullptr, false};
}
cur = arr.at(index);
}
else
{
// Current value is not an Object or Array, so we can't get any more
// segments from it
return {dom::Kind::Undefined, false};
}
// Consume more segments to get into the array element
segment = popFirstSegment(path);
isLiteral = segment.starts_with('[') && segment.ends_with(']');
literalSegment = segment.substr(
1 * static_cast<std::size_t>(isLiteral),
segment.size() - (2 * static_cast<std::size_t>(isLiteral)));
}
return {cur, true};
}
[[nodiscard]]
static
Expected<std::pair<dom::Value, bool>, HandlebarsError>
lookupPropertyImpl(
dom::Value const& context,
std::string_view path,
detail::RenderState const& state,
HandlebarsOptions const& opt)
{
using Res = std::pair<dom::Value, bool>;
MRDOCS_TRY(checkPath(path, state));
// ==============================================================
// "." / "this"
// ==============================================================
if (isCurrentContextSegment(path) || path.empty())
{
return Res{context, true};
}
// ==============================================================
// Non-object key
// ==============================================================
if (context.kind() != dom::Kind::Object) {
if (opt.strict || opt.assumeObjects)
{
std::string msg =
std::format("\"{}\" not defined in {}", path, context);
auto res = find_position_in_text(state.rootTemplateText, path);
if (res) {
return Unexpected(
HandlebarsError(msg, res.line, res.column, res.pos));
}
return Unexpected(HandlebarsError(msg));
}
return Res{nullptr, false};
}
// ==============================================================
// Object path
// ==============================================================
return lookupPropertyImpl(context.getObject(), path, state, opt);
}
template <std::convertible_to<std::string_view> S>
static Expected<std::pair<dom::Value, bool>, HandlebarsError>
lookupPropertyImpl(
dom::Value const& data,
S const& path,
detail::RenderState const& state,
HandlebarsOptions const& opt)
{
return lookupPropertyImpl(
data, static_cast<std::string_view>(path), state, opt);
}
[[nodiscard]]
Expected<std::pair<dom::Value, bool>, HandlebarsError>
lookupPropertyImpl(
dom::Value const& context,
dom::Value const& path,
detail::RenderState const& state,
HandlebarsOptions const& opt)
{
using Res = std::pair<dom::Value, bool>;
if (path.isString())
{
return lookupPropertyImpl(context, path.getString(), state, opt);
}
if (path.isInteger())
{
if (context.isArray())
{
auto& arr = context.getArray();
if (path.getInteger() >= static_cast<std::int64_t>(arr.size()))
{
return Res{nullptr, false};
}
return Res{arr.at(static_cast<std::size_t>(path.getInteger())), true};
}
return lookupPropertyImpl(context, std::to_string(path.getInteger()), state, opt);
}
return Res{nullptr, false};
}
// ==============================================================
// Engine
// ==============================================================
struct defaultLogger {
static constexpr std::array<std::string_view, 4> methodMap =
{"debug", "info", "warn", "error"};
std::int64_t level_ = 1;
void
operator()(dom::Array const& args) const {
dom::Value level = lookupLevel(args.at(0));
if (!level.isInteger() || level.getInteger() > level_) {
return;
}
std::string_view method = methodMap[