moostache 0.6.0

Mustache template engine
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
// moostache readme rendered on docs.rs
#![doc = include_str!("./lib.md")]
#![deny(missing_docs)]
#![warn(clippy::pedantic)]
// ignored lints
#![allow(
    clippy::needless_pass_by_value,
    clippy::enum_glob_use,
    clippy::enum_variant_names,
)]

use fnv::FnvBuildHasher;
use lru::LruCache;
use serde::Serialize;
use serde_json::json;
use winnow::{
    ascii::multispace0,
    combinator::{alt, cut_err, delimited, repeat, separated},
    error::{AddContext, ErrMode, ErrorKind, ParserError as WParserError},
    stream::{FindSlice, Stream},
    token::{literal, take_while},
    PResult,
    Parser,
    Stateful,
};
use yoke::{Yoke, Yokeable};
use std::{
    borrow::{Borrow, Cow},
    cell::RefCell,
    collections::HashMap,
    fmt::{Debug, Display},
    fs,
    hash::{BuildHasher, BuildHasherDefault, Hash},
    io::{self, Write},
    num::NonZeroUsize,
    ops::Deref,
    path::{Path, PathBuf, MAIN_SEPARATOR_STR},
    rc::Rc,
    str,
};
use walkdir::WalkDir;

#[cfg(test)]
mod tests;

/////////////
// PARSING //
/////////////

// Source strings are parsed into template fragments.
// A "compiled" template is just a list of fragments
// and list of "section skips". See SectionSkip.
#[derive(PartialEq, Debug)]
enum Fragment<'src> {
    Literal(&'src str),
    EscapedVariable(&'src str),
    UnescapedVariable(&'src str),
    Section(&'src str),
    InvertedSection(&'src str),
    Partial(&'src str),
}

// We have a stateful parser, and that state
// is maintained in this struct.
#[derive(Debug)]
struct State<'src, 'skips> {
    fragment_index: usize,
    section_index: usize,
    section_starts: Vec<SectionMeta<'src>>,
    section_skips: &'skips mut Vec<SectionSkip>,
}

// Things our stateful parser needs to keep track of.
// Mostly this is for checking that all sections which
// are opened are correctly closed, and also for calculating
// section skips.
impl<'src, 'skips> State<'src, 'skips> {
    fn visited_fragment(&mut self) {
        self.fragment_index += 1;
    }
    fn visited_section_start(&mut self, name: &'src str) {
        self.section_starts.push(SectionMeta {
            name,
            section_index: self.section_index,
            fragment_index: self.fragment_index,
        });
        self.section_skips.push(SectionSkip {
            nested_sections: 0,
            nested_fragments: 0,
        });
        self.fragment_index += 1;
        self.section_index += 1;
    }
    fn visited_section_end(&mut self, name: &'src str) -> Result<(), ()> {
        let start = self.section_starts
            .pop()
            .ok_or(())?;
        if start.name != name {
            return Err(());
        }
        let skip = &mut self.section_skips[start.section_index];
        skip.nested_sections = u16::try_from((self.section_index - 1) - start.section_index)
            .expect("can't have more than 65k sections within a section");
        skip.nested_fragments = u16::try_from((self.fragment_index - 1) - start.fragment_index)
            .expect("can't have more than 65k fragments within a section");
        Ok(())
    }
    fn still_expecting_section_ends(&self) -> bool {
        !self.section_starts.is_empty()
    }
}

// Just data we keep track of in our parser state.
// Helps calculate section skips.
#[derive(Debug)]
struct SectionMeta<'src> {
    name: &'src str,
    section_index: usize,
    fragment_index: usize,
}

// As you may have noticed in Fragment, there's a
// Section and InvertedSection variant but there's
// no SectionEnd variant, so how do we know where
// sections end? Section ends are maintained in a list
// of SectionSkips. The first section in the list
// correponds to the first section that appears in the
// source template, and so is the same for the second,
// third, and so on. A "section skip" basically tells us
// how many nested sections and fragments are in a given
// section, so if the section value is falsy and we need
// to skip over it during render, we can do so quickly
// and efficiently since we know exactly where it ends
// in the fragment list.
#[derive(Debug, PartialEq)]
struct SectionSkip {
    nested_sections: u16,
    nested_fragments: u16,
}

type Input<'src, 'skips> = Stateful<&'src str, State<'src, 'skips>>;

// We can't do "impl Input { fn new()" because Input is a type
// alias and not a newtype.
#[inline]
fn new_input<'src, 'skips>(template: &'src str, skips: &'skips mut Vec<SectionSkip>) -> Input<'src, 'skips> {
    Input {
        input: template,
        state: State {
            fragment_index: 0,
            section_index: 0,
            section_starts: Vec::new(),
            section_skips: skips,
        },
    }
}

// parses a source string into a compiled Template
fn parse<S: Into<Cow<'static, str>>>(source: S) -> Result<Template, InternalError> {
    let source = match source.into() {
        Cow::Owned(s) => Yoke::attach_to_cart(s, |s| &s[..]).wrap_cart_in_option(),
        Cow::Borrowed(s) => Yoke::new_owned(s),
    };
    let mut skips = Vec::new();

    let fragments = source.try_map_project(|source, _| {
        let input = new_input(source, &mut skips);
        match _parse.parse(input) {
            Ok(frags) => Ok(Fragments(frags)),
            Err(err) => Err(err.into_inner()),
        }
    })?;

    Ok(Template { fragments, skips })
}

// parses a source string into a compiled Template
#[inline]
fn _parse<'src>(
    input: &mut Input<'src, '_>,
) -> PResult<Vec<Fragment<'src>>, InternalError> {
    if input.input.is_empty() {
        return Err(ErrMode::Cut(InternalError::ParseErrorNoContent));
    }

    let frags = repeat(1.., alt((
        parse_literal.map(Some),
        parse_section_end.map(|()| None),
        parse_section_start.map(Some),
        parse_inverted_section_start.map(Some),
        parse_unescaped_variable.map(Some),
        parse_comment.map(|()| None),
        parse_partial.map(Some),
        parse_escaped_variable.map(Some),
    )))
        .fold(Vec::new, |mut acc, item: Option<Fragment>| {
            if let Some(item) = item {
                acc.push(item);
            }
            acc
        })
        .parse_next(input)?;

    // means we had unclosed sections
    if input.state.still_expecting_section_ends() {
        return Err(ErrMode::Cut(InternalError::ParseErrorUnclosedSectionTags));
    }

    Ok(frags)
}

// parses a fragment literal, i.e. anything that doesn't begin with
// {{, until it reaches a {{ or EOF
fn parse_literal<'src>(
    input: &mut Input<'src, '_>,
) -> PResult<Fragment<'src>, InternalError> {
    if input.is_empty() {
        return Err(ErrMode::Backtrack(InternalError::ParseErrorGeneric));
    }

    if let Some(range) = input.input.find_slice("{{") {
        if range.start == 0 {
            return Err(ErrMode::Backtrack(InternalError::ParseErrorGeneric));
        }
        let literal = &input.input[..range.start];
        let frag = Fragment::Literal(literal);
        input.input = &input.input[range.start..];
        input.state.visited_fragment();
        Ok(frag)
    } else {
        let frag = Fragment::Literal(input);
        input.input = &input.input[input.input.len()..];
        input.state.visited_fragment();
        Ok(frag)
    }
}

// valid variable names can only contain alphanumeric,
// dash, or underscore chars
fn is_variable_name(c: char) -> bool {
    matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_')
}

// valid variable names must be at least 1 char long, and
// must only contain valid variable chars
fn parse_variable_name<'src>(
    input: &mut Input<'src, '_>,
) -> PResult<&'src str, InternalError> {
    take_while(1.., is_variable_name)
        .parse_next(input)
}

// a variable "path" can potentially be several variable names
// delimited by dots, e.g. some.variable.path
fn parse_variable_path<'src>(
    input: &mut Input<'src, '_>,
) -> PResult<&'src str, InternalError> {
    delimited(
        multispace0,
        alt((
            separated(
                1..,
                parse_variable_name, 
                '.'
            ).map(|()| ()).take(),
            literal("."),
        )),
        multispace0,
    )
        .parse_next(input)
}

// parses an escaped variable, e.g. {{ some.variable }}
fn parse_escaped_variable<'src>(
    input: &mut Input<'src, '_>,
) -> PResult<Fragment<'src>, InternalError> {
    let result = delimited(
        literal("{{"),
        cut_err(parse_variable_path),
        cut_err(literal("}}"))
    )
        .context(InternalError::ParseErrorInvalidEscapedVariableTag)
        .parse_next(input)
        .map(Fragment::EscapedVariable);
    if result.is_ok() {
        input.state.visited_fragment();
    }
    result
}

// parses an unescaped variable, e.g. {{{ some.variable }}}
fn parse_unescaped_variable<'src>(
    input: &mut Input<'src, '_>,
) -> PResult<Fragment<'src>, InternalError> {
    let result = delimited(
        literal("{{{"),
        cut_err(parse_variable_path),
        cut_err(literal("}}}"))
    )
        .context(InternalError::ParseErrorInvalidUnescapedVariableTag)
        .parse_next(input)
        .map(Fragment::UnescapedVariable);
    if result.is_ok() {
        input.state.visited_fragment();
    }
    result
}

// parses a comment, e.g. {{! comment }}
fn parse_comment(
    input: &mut Input<'_, '_>
) -> PResult<(), InternalError> {
    if input.input.starts_with("{{!") {
        if let Some(range) = input.input.find_slice("}}") {
            input.input = &input.input[range.end..];
            return Ok(());
        }
        return Err(ErrMode::Cut(InternalError::ParseErrorInvalidCommentTag));
    }
    Err(ErrMode::Backtrack(InternalError::ParseErrorGeneric))
}

// parses a section start, e.g. {{# section.start }}
fn parse_section_start<'src>(
    input: &mut Input<'src, '_>
) -> PResult<Fragment<'src>, InternalError> {
    let variable = delimited(
        literal("{{#"),
        cut_err(parse_variable_path),
        cut_err(literal("}}")),
    )
        .context(InternalError::ParseErrorInvalidSectionStartTag)
        .parse_next(input)?;

    input.state.visited_section_start(variable);

    Ok(Fragment::Section(variable))
}

// parses an inverted section start, e.g. {{^ inverted.section.start }}
fn parse_inverted_section_start<'src>(
    input: &mut Input<'src, '_>,
) -> PResult<Fragment<'src>, InternalError> {
    let variable = delimited(
        literal("{{^"),
        cut_err(parse_variable_path),
        cut_err(literal("}}")),
    )
        .context(InternalError::ParseErrorInvalidInvertedSectionStartTag)
        .parse_next(input)?;

    input.state.visited_section_start(variable);

    Ok(Fragment::InvertedSection(variable))
}

// parses a section end, e.g. {{/ section.end }}
fn parse_section_end(
    input: &mut Input<'_, '_>,
) -> PResult<(), InternalError> {
    let variable = delimited(
        literal("{{/"),
        cut_err(parse_variable_path),
        cut_err(literal("}}")),
    )
        .context(InternalError::ParseErrorInvalidSectionEndTag)
        .parse_next(input)?;

    if input.state.visited_section_end(variable).is_err() {
        return Err(ErrMode::Cut(InternalError::ParseErrorMismatchedSectionEndTag));
    }

    Ok(())
}

// there's way more valid file name chars than
// variable chars, so we calculate a bitfield
// at compile time of all of the chars that
// can appear in a file name
const fn valid_file_chars() -> u128 {
    let mut bitfield = 0u128;

    let mut b = b'0';
    while b <= b'9' {
        bitfield |= 1u128 << b;
        b += 1;
    }

    b = b'a';
    while b <= b'z' {
        bitfield |= 1u128 << b;
        b += 1;
    }

    b = b'A';
    while b <= b'Z' {
        bitfield |= 1u128 << b;
        b += 1;
    }

    let bytes = b"_-.,!@#$%^&()+=[]~";
    let mut i = 0;
    while i < bytes.len() {
        b = bytes[i];
        bitfield |= 1u128 << b;
        i += 1;
    }

    bitfield
}

// store bitfield in const
const VALID_FILE_CHARS: u128 = valid_file_chars();

// checks if char is a valid file name char
#[inline]
fn is_file_name(c: char) -> bool {
    c.is_ascii() && (VALID_FILE_CHARS & (1u128 << c as u32)) != 0
}

// parses a file name, must be at least 1 char long, and
// can contain any valid file name char, with these notable
// exceptions: "{" (used for mustache tags), "}" (used for
// mustache tags), " " (whitespace, used as a delimiter)
fn parse_file_name<'src>(
    input: &mut Input<'src, '_>
) -> PResult<&'src str, InternalError> {
    take_while(1.., is_file_name)
        .parse_next(input)
}

// parses a file path, i.e. a list of file names delimited
// by slashes, e.g. some/file/path
fn parse_file_path<'src>(
    input: &mut Input<'src, '_>,
) -> PResult<&'src str, InternalError> {
    delimited(
        multispace0,
        separated(
            1..,
            parse_file_name, 
            '/'
        ).map(|()| ()).take(),
        multispace0,
    )
        .parse_next(input)
}

// parses a partial, e.g. {{> some/file/path }}
fn parse_partial<'src>(
    input: &mut Input<'src, '_>,
) -> PResult<Fragment<'src>, InternalError> {
    let result = delimited(
        literal("{{>"),
        cut_err(parse_file_path),
        cut_err(literal("}}")),
    )
        .context(InternalError::ParseErrorInvalidPartialTag)
        .parse_next(input)
        .map(Fragment::Partial);
    if result.is_ok() {
        input.state.visited_fragment();
    }
    result
}

/// A compiled moostache template.
/// 
/// ### Examples
/// 
/// ```rust
/// use moostache::Template;
/// use serde_json::json;
/// 
/// let template = Template::parse("hello {{name}}!").unwrap();
/// let data = json!({"name": "John"});
/// let rendered = template.render_no_partials_to_string(&data).unwrap();
/// assert_eq!(rendered, "hello John!");
/// ```
pub struct Template {
    // parsed template fragments
    fragments: Yoke<Fragments<'static>, Option<String>>,
    // parsed section skips, i.e. tell us where sections end
    skips: Vec<SectionSkip>,
}
#[derive(Yokeable)]
struct Fragments<'src>(Vec<Fragment<'src>>);

impl Debug for Template {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Template")
            .field("fragments", &self.fragments.get().0)
            .field("skips", &self.skips)
            .finish()
    }
}
impl PartialEq for Template {
    fn eq(&self, other: &Self) -> bool {
        self.fragments.get().0 == other.fragments.get().0 && self.skips == other.skips
    }
}

impl Template {
    /// Parse a [`&'static str`](std::str) or [`String`] into a compiled
    /// moostache template.
    /// 
    /// ### Errors
    /// 
    /// Returns a [`MoostacheError`] parse error enum variant
    /// if parsing fails for whatever reason.
    #[inline]
    pub fn parse<S: Into<Cow<'static, str>>>(source: S) -> Result<Template, MoostacheError> {
        match parse(source) {
            Err(err) => {
                Err(MoostacheError::from_internal(err, String::new()))
            },
            Ok(template) => Ok(template),
        }
    }

    /// Render this template.
    /// 
    /// ### Errors
    /// 
    /// If using [`HashMapLoader`] or [`FileLoader`] this function
    /// can return any enum variant of [`MoostacheError`].
    #[inline]
    pub fn render<K: Borrow<str> + Eq + Hash, T: TemplateLoader<K> + ?Sized, W: Write>(
        &self,
        loader: &T,
        value: &serde_json::Value,
        writer: &mut W,
    ) -> Result<(), T::Error> {
        let mut scopes = Vec::new();
        scopes.push(value);
        _render(
            &self.fragments.get().0,
            &self.skips,
            loader,
            &mut scopes,
            writer
        )
    }

    /// Render this template given a type that impls
    /// [`serde::Serialize`].
    /// 
    /// ### Errors
    /// 
    /// If using [`HashMapLoader`] or [`FileLoader`] this function
    /// can return any enum variant of [`MoostacheError`].
    #[inline]
    pub fn render_serializable<K: Borrow<str> + Eq + Hash, T: TemplateLoader<K> + ?Sized, W: Write, S: Serialize>(
        &self,
        loader: &T,
        serializeable: &S,
        writer: &mut W,
    ) -> Result<(), T::Error> {
        let value = serde_json::to_value(serializeable)
            .map_err(|_| MoostacheError::SerializationError)?;
        self.render(
            loader,
            &value,
            writer
        )
    }

    /// Render this template, assuming it has no partial tags.
    /// 
    /// ### Errors
    /// 
    /// Returns a [`MoostacheError`] if the template contains a
    /// partial, or serializing data during render fails for
    /// whatever reason.
    #[inline]
    pub fn render_no_partials<W: Write>(
        &self,
        value: &serde_json::Value,
        writer: &mut W,
    ) -> Result<(), MoostacheError> {
        self.render(
            &(),
            value,
            writer
        )
    }

    /// Render this template using a type which impls
    /// [`serde::Serialize`] and assuming it has no partials.
    /// 
    /// ### Errors
    /// 
    /// Returns a [`MoostacheError`] if the template contains a
    /// partial, or serializing data during render fails for
    /// whatever reason.
    #[inline]
    pub fn render_serializable_no_partials<S: Serialize, W: Write>(
        &self,
        serializeable: &S,
        writer: &mut W,
    ) -> Result<(), MoostacheError> {
        self.render_serializable(
            &(),
            serializeable,
            writer
        )
    }

    /// Render this template to a [`String`].
    /// 
    /// ### Errors
    /// 
    /// If using [`HashMapLoader`] or [`FileLoader`] this function
    /// can return any enum variant of [`MoostacheError`].
    #[inline]
    pub fn render_to_string<K: Borrow<str> + Eq + Hash, T: TemplateLoader<K> + ?Sized>(
        &self,
        loader: &T,
        value: &serde_json::Value,
    ) -> Result<String, T::Error> {
        let mut writer = Vec::<u8>::new();
        self.render(
            loader,
            value,
            &mut writer
        )?;
        let rendered = unsafe {
            // SAFETY: templates are utf8 and value
            // is utf8 so we know templates + value
            // will also be utf8
            debug_assert!(str::from_utf8(&writer).is_ok());
            String::from_utf8_unchecked(writer)
        };
        Ok(rendered)
    }

    /// Render this template assuming it has no partial tags
    /// and return the result as a [`String`].
    /// 
    /// ### Errors
    /// 
    /// Returns a [`MoostacheError`] if the template contains a
    /// partial, or serializing data during render fails for
    /// whatever reason.
    #[inline]
    pub fn render_no_partials_to_string(
        &self,
        value: &serde_json::Value,
    ) -> Result<String, MoostacheError> {
        self.render_to_string(
            &(),
            value,
        )
    }

    /// Render this template given a type which impls
    /// [`serde::Serialize`] and return result as a [`String`].
    /// 
    /// ### Errors
    /// 
    /// If using [`HashMapLoader`] or [`FileLoader`] this function
    /// can return any enum variant of [`MoostacheError`].
    #[inline]
    pub fn render_serializable_to_string<K: Borrow<str> + Eq + Hash, T: TemplateLoader<K> + ?Sized, S: Serialize>(
        &self,
        loader: &T,
        serializable: &S,
    ) -> Result<String, T::Error> {
        let value = serde_json::to_value(serializable)
            .map_err(|_| MoostacheError::SerializationError)?;
        self.render_to_string(
            loader,
            &value,
        )
    }

    /// Render this template given a type which impls
    /// [`serde::Serialize`], assume it has no partials,
    /// and return result as a [`String`].
    /// 
    /// ### Errors
    /// 
    /// Returns a [`MoostacheError`] if the template contains a
    /// partial, or serializing data during render fails for
    /// whatever reason.
    #[inline]
    pub fn render_serializable_no_partials_to_string<S: Serialize>(
        &self,
        serializable: &S,
    ) -> Result<String, MoostacheError> {
        let value = serde_json::to_value(serializable)
            .map_err(|_| MoostacheError::SerializationError)?;
        self.render_to_string(
            &(),
            &value,
        )
    }
}

// note: can't do impl<S: Into<ImmutableStr> TryFrom<S> below
// because compiler complains that generic impl overlaps
// with another generic impl in the std lib, so we do separate
// impls for &'static str and String

impl TryFrom<&'static str> for Template {
    type Error = MoostacheError;
    fn try_from(source: &'static str) -> Result<Self, Self::Error> {
        Self::parse(source)
    }
}

impl TryFrom<String> for Template {
    type Error = MoostacheError;
    fn try_from(source: String) -> Result<Self, Self::Error> {
        Self::parse(source)
    }
}

//////////////////////
// TEMPLATE LOADERS //
//////////////////////

/// Loads templates and renders them.
pub trait TemplateLoader<K: Borrow<str> + Eq + Hash = String> {
    /// Output type of the [`get`](TemplateLoader::get) method.
    type Output<'a>: Deref<Target = Template> + 'a where Self: 'a;
    /// Error type of the [`get`](TemplateLoader::get) and render methods.
    type Error: From<MoostacheError>;
    
    /// Get a template by name.
    /// 
    /// ### Errors
    /// 
    /// Returns an [`Error`](TemplateLoader::Error) if getting
    /// the template fails for whatever reason. In [`HashMapLoader`]
    /// this would only ever return
    /// [`MoostacheError::LoaderErrorTemplateNotFound`] since it
    /// either has the template or it doesn't. In [`FileLoader`] it
    /// can return almost any enum variant of [`MoostacheError`]
    /// since it lazily loads and compiles templates on-demand.
    fn get<'a>(&'a self, name: &str) -> Result<Self::Output<'a>, Self::Error>;

    /// Insert a template by name.
    fn insert(&mut self, name: K, value: Template) -> Option<Template>;

    /// Remove a template by name.
    fn remove(&mut self, name: &str) -> Option<Template>;
    
    /// Render a template by name, using a [`serde_json::Value`]
    /// as data and writing output to a [`&mut impl Write`](std::io::Write).
    /// 
    /// ### Errors
    /// 
    /// If using [`HashMapLoader`] or [`FileLoader`] this function
    /// can return any enum variant of [`MoostacheError`].
    #[inline]
    fn render<W: Write>(
        &self,
        name: &str,
        value: &serde_json::Value,
        writer: &mut W,
    ) -> Result<(), Self::Error> {
        let template = self.get(name)?;
        template.render(self, value, writer)
    }

    /// Render a template by name, using a type which impls
    /// [`serde::Serialize`] as data and writing output to a
    /// [`&mut impl Write`](std::io::Write).
    /// 
    /// ### Errors
    /// 
    /// If using [`HashMapLoader`] or [`FileLoader`] this function
    /// can return any enum variant of [`MoostacheError`].
    #[inline]
    fn render_serializable<W: Write, S: Serialize>(
        &self,
        name: &str,
        serializeable: &S,
        writer: &mut W,
    ) -> Result<(), Self::Error> {
        let value = serde_json::to_value(serializeable)
            .map_err(|_| MoostacheError::SerializationError)?;
        self.render(
            name,
            &value,
            writer
        )
    }

    /// Renders a template by name, using a [`serde_json::Value`]
    /// as data and returning the output as a [`String`].
    /// 
    /// ### Errors
    /// 
    /// If using [`HashMapLoader`] or [`FileLoader`] this function
    /// can return any enum variant of [`MoostacheError`].
    #[inline]
    fn render_to_string(
        &self,
        name: &str,
        value: &serde_json::Value,
    ) -> Result<String, Self::Error> {
        let mut writer = Vec::<u8>::new();
        self.render(
            name,
            value,
            &mut writer
        )?;
        let rendered = unsafe {
            // SAFETY: templates are utf8 and value
            // is utf8 so we know templates + value
            // will also be utf8
            debug_assert!(str::from_utf8(&writer).is_ok());
            String::from_utf8_unchecked(writer)
        };
        Ok(rendered)
    }

    /// Renders a template by name, using a type which impls
    /// [`serde::Serialize`] as data and returning the output
    /// as a [`String`].
    /// 
    /// ### Errors
    /// 
    /// If using [`HashMapLoader`] or [`FileLoader`] this function
    /// can return any enum variant of [`MoostacheError`].
    #[inline]
    fn render_serializable_to_string<S: Serialize>(
        &self,
        name: &str,
        serializable: &S,
    ) -> Result<String, Self::Error> {
        let value = serde_json::to_value(serializable)
            .map_err(|_| MoostacheError::SerializationError)?;
        self.render_to_string(
            name,
            &value,
        )
    }
}

/// Useful struct for creating [`HashMapLoader`]s or
/// [`FileLoader`]s.
/// 
/// ### Examples
/// 
/// Creating a [`HashMapLoader`]:
/// 
/// ```rust
/// use moostache::{LoaderConfig, HashMapLoader};
/// 
/// let loader = HashMapLoader::try_from(LoaderConfig::default()).unwrap();
/// ```
/// 
/// Creating a [`FileLoader`]:
/// 
/// ```rust
/// use moostache::{LoaderConfig, FileLoader};
/// 
/// let loader = FileLoader::try_from(LoaderConfig::default()).unwrap();
/// ```
/// 
/// [`LoaderConfig`] default values:
/// 
/// ```rust
/// use moostache::LoaderConfig;
/// 
/// assert_eq!(
///     LoaderConfig::default(),
///     LoaderConfig {
///         templates_directory: "./templates/",
///         templates_extension: ".html",
///         cache_size: 200,
///     },
/// );
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct LoaderConfig<'a> {
    /// Directory to load templates from.
    pub templates_directory: &'a str,
    /// File extension of template files.
    pub templates_extension: &'a str,
    /// Max number of compiled templates to cache in memory.
    pub cache_size: usize,
}

#[cfg(windows)]
const DEFAULT_TEMPLATES_DIRECTORY: &str = ".\\templates\\";

#[cfg(not(windows))]
const DEFAULT_TEMPLATES_DIRECTORY: &str = "./templates/";

impl Default for LoaderConfig<'_> {
    fn default() -> Self {
        Self {
            templates_directory: DEFAULT_TEMPLATES_DIRECTORY,
            templates_extension: ".html",
            cache_size: 200,
        }
    }
}

impl TryFrom<LoaderConfig<'_>> for HashMapLoader {
    type Error = MoostacheError;
    fn try_from(config: LoaderConfig<'_>) -> Result<Self, MoostacheError> {
        let mut dir: String = config.templates_directory.into();
        if !dir.ends_with(MAIN_SEPARATOR_STR) {
            dir.push_str(MAIN_SEPARATOR_STR);
        }
        let dir_path: &Path = dir.as_ref();
        let mut ext: String = config.templates_extension.into();
        if !ext.starts_with('.') {
            ext.insert(0, '.');
        }
        let max_size = NonZeroUsize::new(config.cache_size)
            .ok_or(MoostacheError::ConfigErrorNonPositiveCacheSize)?;
        let max_size: usize = max_size.into();

        if !dir_path.is_dir() {
            return Err(MoostacheError::ConfigErrorInvalidTemplatesDirectory(dir_path.into()));
        }

        let mut current_size = 0usize;
        let mut templates: HashMap<String, Template, FnvBuildHasher> = HashMap::with_hasher(BuildHasherDefault::default());
        for entry in WalkDir::new(dir_path).into_iter().filter_map(Result::ok) {
            if entry.file_type().is_file() {
                let entry_path = entry.path();
                let entry_path_str = entry_path
                    .to_str()
                    .ok_or_else(|| MoostacheError::LoaderErrorNonUtf8FilePath(entry_path.into()))?;
                if entry_path_str.ends_with(&ext) {
                    let name = entry_path_str
                        .strip_prefix(&dir)
                        .and_then(|path| path.strip_suffix(&ext))
                        .unwrap()
                        .to_string();
                    let source = fs::read_to_string(entry_path)
                        .map_err(|err| MoostacheError::from_io(err, name.clone()))?;
                    let template = Template::parse(source)
                        .map_err(|err| err.set_name(&name))?;
                    templates.insert(name, template);
                    current_size += 1;
                    if current_size > max_size {
                        return Err(MoostacheError::ConfigErrorTooManyTemplates);
                    }
                }
            }
        }

        Ok(HashMapLoader {
            templates
        })
    }
}

/// Stores all templates in memory.
/// 
/// ### Examples
/// 
/// Creating a [`HashMapLoader`] from a hashmap:
/// 
/// ```rust
/// use moostache::HashMapLoader;
/// use maplit::hashmap;
/// 
/// let loader = HashMapLoader::try_from(hashmap! {
///    "greet" => "hello {{name}}!",
/// }).unwrap();
/// ```
/// 
/// Creating a [`HashMapLoader`] from a [`LoaderConfig`]:
/// 
/// ```rust
/// use moostache::{LoaderConfig, HashMapLoader};
/// 
/// let loader = HashMapLoader::try_from(LoaderConfig::default()).unwrap();
/// ```
#[derive(Debug)]
pub struct HashMapLoader<K: Borrow<str> + Eq + Hash = String, H: BuildHasher + Default = FnvBuildHasher> {
    templates: HashMap<K, Template, H>,
}

impl<K: Borrow<str> + Eq + Hash, H: BuildHasher + Default> TemplateLoader<K> for HashMapLoader<K, H> {
    type Output<'a> = &'a Template where K: 'a, H: 'a;
    type Error = MoostacheError;
    fn get(&self, name: &str) -> Result<&Template, MoostacheError> {
        self.templates.get(name)
            .ok_or_else(|| MoostacheError::LoaderErrorTemplateNotFound(name.into()))
    }
    fn insert(&mut self, name: K, value: Template) -> Option<Template> {
        self.templates.insert(name, value)
    }
    fn remove(&mut self, name: &str) -> Option<Template> {
        self.templates.remove(name)
    }
}

/// Lazily loads templates on-demand during render. Caches
/// some compiled templates in memory.
/// 
/// ### Examples
/// 
/// Creating a [`FileLoader`] from a [`LoaderConfig`]:
/// 
/// ```rust
/// use moostache::{LoaderConfig, FileLoader};
/// 
/// let loader = FileLoader::try_from(LoaderConfig::default()).unwrap();
/// ```
#[derive(Debug)]
pub struct FileLoader<H: BuildHasher + Default = FnvBuildHasher> {
    templates_directory: String,
    templates_extension: String,
    path_buf: RefCell<String>,
    templates: RefCell<LruCache<String, Rc<Template>, H>>,
}

impl TemplateLoader for FileLoader {
    type Output<'a> = Rc<Template>;
    type Error = MoostacheError;
    fn get(&self, name: &str) -> Result<Rc<Template>, MoostacheError> {
        let mut templates = self.templates.borrow_mut();
        let template = templates.get(name);
        if let Some(template) = template {
            return Ok(Rc::clone(template));
        }
        let mut path_buf = self.path_buf.borrow_mut();
        path_buf.clear();
        path_buf.push_str(&self.templates_directory);
        path_buf.push_str(name);
        path_buf.push_str(&self.templates_extension);
        let source = fs::read_to_string::<&Path>(path_buf.as_ref())
            .map_err(|err| MoostacheError::from_io(err, name.into()))?;
        let template = Template::parse(source)
            .map_err(|err| err.set_name(name))?;
        let template = Rc::new(template);
        templates.put(name.into(), Rc::clone(&template));
        Ok(template)
    }
    fn insert(&mut self, name: String, value: Template) -> Option<Template> {
        let option = self.templates
            .borrow_mut()
            .put(name, Rc::new(value));
        match option {
            Some(template) => {
                Rc::into_inner(template)
            },
            None => None,
        }
    }
    fn remove(&mut self, name: &str) -> Option<Template> {
        let option = self.templates
            .borrow_mut()
            .pop(name);
        match option {
            Some(template) => {
                Rc::into_inner(template)
            },
            None => None,
        }
    }
}

impl TryFrom<LoaderConfig<'_>> for FileLoader {
    type Error = MoostacheError;
    fn try_from(config: LoaderConfig<'_>) -> Result<Self, MoostacheError> {
        let mut dir: String = config.templates_directory.into();
        if !dir.ends_with(MAIN_SEPARATOR_STR) {
            dir.push_str(MAIN_SEPARATOR_STR);
        }
        let dir_path: &Path = dir.as_ref();
        let mut ext: String = config.templates_extension.into();
        if !ext.starts_with('.') {
            ext.insert(0, '.');
        }
        let max_size = NonZeroUsize::new(config.cache_size)
            .ok_or(MoostacheError::ConfigErrorNonPositiveCacheSize)?;

        if !dir_path.is_dir() {
            return Err(MoostacheError::ConfigErrorInvalidTemplatesDirectory(dir_path.into()));
        }

        let templates = RefCell::new(LruCache::with_hasher(max_size, BuildHasherDefault::default()));

        Ok(FileLoader {
            templates_directory: dir,
            templates_extension: ext,
            path_buf: RefCell::new(String::new()),
            templates,
        })
    }
}

impl<K: Borrow<str> + Eq + Hash, V: Into<Cow<'static, str>>> TryFrom<HashMap<K, V>> for HashMapLoader<K> {
    type Error = MoostacheError;
    fn try_from(map: HashMap<K, V>) -> Result<Self, Self::Error> {
        let templates = map
            .into_iter()
            .map(|(key, value)| {
                match parse(value) {
                    Ok(template) => Ok((key, template)),
                    Err(err) => Err(MoostacheError::from_internal(err, key.borrow().to_owned())),
                }
            })
            .collect::<Result<_, _>>();
        templates.map(|templates| HashMapLoader {
            templates,
        })
    }
}

impl TemplateLoader<&'static str> for () {
    type Output<'a> = &'a Template;
    type Error = MoostacheError;
    fn get(&self, name: &str) -> Result<&Template, MoostacheError> {
        Err(MoostacheError::LoaderErrorTemplateNotFound(name.into()))
    }
    fn insert(&mut self, _: &'static str, _: Template) -> Option<Template> {
        None
    }
    fn remove(&mut self, _: &str) -> Option<Template> {
        None
    }
}

///////////////
// RENDERING //
///////////////

// checks if serde_json::Value is truthy
fn is_truthy(value: &serde_json::Value) -> bool {
    use serde_json::Value;
    match value {
        Value::Null => false,
        Value::Bool(b) => *b,
        Value::Number(_) => value != &json!(0),
        Value::String(string) => !string.is_empty(),
        Value::Array(array) => !array.is_empty(),
        Value::Object(object) => !object.is_empty(),
    }
}

// wraps a Write type and escapes HTML chars
// before writing to the inner Write
struct EscapeHtml<'a, W: Write>(&'a mut W);

// as recommended by OWASP the chars "&", "<",
// ">", "\"", and "'" are escaped
impl<W: Write> Write for EscapeHtml<'_, W> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let written = buf.len();
        self.write_all(buf)
            .map(|()| written)
    }
    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
        let mut start = 0;
        let mut end = 0;
        for byte in buf {
            match byte {
                b'&' => {
                    if start < end {
                        self.0.write_all(&buf[start..end])?;
                    }
                    end += 1;
                    start = end;
                    self.0.write_all(b"&amp;")?;
                },
                b'<' => {
                    if start < end {
                        self.0.write_all(&buf[start..end])?;
                    }
                    end += 1;
                    start = end;
                    self.0.write_all(b"&lt;")?;
                },
                b'>' => {
                    if start < end {
                        self.0.write_all(&buf[start..end])?;
                    }
                    end += 1;
                    start = end;
                    self.0.write_all(b"&gt;")?;
                },
                b'"' => {
                    if start < end {
                        self.0.write_all(&buf[start..end])?;
                    }
                    end += 1;
                    start = end;
                    self.0.write_all(b"&quot;")?;
                },
                b'\'' => {
                    if start < end {
                        self.0.write_all(&buf[start..end])?;
                    }
                    end += 1;
                    start = end;
                    self.0.write_all(b"&#x27;")?;
                },
                _ => {
                    end += 1;
                },
            }
        }
        if start < end {
            self.0.write_all(&buf[start..end])?;
        }
        Ok(())
    }
    fn flush(&mut self) -> io::Result<()> {
        self.0.flush()
    }
}

// serializes a serde_json::Value
fn write_value<W: Write>(
    value: &serde_json::Value,
    writer: &mut W,
) -> Result<(), MoostacheError> {
    use serde_json::Value;
    match value {
        Value::Null => {
            // serde_json serializes null as
            // "null" but we want this to be
            // an empty string instead
        },
        Value::String(string) => {
            // serde_json serializes strings
            // wrapped with quotes, but we
            // want to write them without quotes
            writer.write_all(string.as_bytes())
                .map_err(|err| MoostacheError::from_io(err, String::new()))?;
        },
        // let serde_json handle the rest
        _ => {
            let mut serializer = serde_json::Serializer::new(writer);
            value.serialize(&mut serializer)
                .map_err(|_| MoostacheError::SerializationError)?;
        },
    }
    Ok(())
}

// given a variable path, e.g. variable.path, and a list of scopes,
// e.g. serde_json::Values, it resolves the path to the specific
// serde_json::Value it points to, or returns serde_json::Value::Null
// if it cannot be found
fn resolve_value<'a>(path: &str, scopes: &[&'a serde_json::Value]) -> &'a serde_json::Value {
    use serde_json::Value;
    if path == "." {
        return scopes[scopes.len() - 1];
    }
    let mut resolved_value = &Value::Null;
    'parent: for value in scopes.iter().rev() {
        resolved_value = *value;
        for (idx, key) in path.split('.').enumerate() {
            match resolved_value {
                Value::Array(array) => {
                    // if we're in this branch assume
                    // the key is an integer index
                    let parsed_index = key.parse::<usize>();
                    if let Ok(index) = parsed_index {
                        let get_option = array.get(index);
                        match get_option {
                            Some(get) => {
                                resolved_value = get;
                            },
                            None => {
                                return &Value::Null;
                            },
                        }
                    } else {
                        // key doesn't exist in this scope
                        if idx == 0 {
                            // go to parent scope
                            continue 'parent;
                        }
                        return &Value::Null;
                    }
                },
                Value::Object(object) => {
                    let get_option = object.get(key);
                    if let Some(get) = get_option {
                        resolved_value = get;
                    } else {
                        // key doesn't exist in this scope
                        if idx == 0 {
                            // go to parent scope
                            continue 'parent;
                        }
                        return &Value::Null;
                    }
                },
                // we got a null, string, or number
                // none of which are keyed, return null
                _ => {
                    // key doesn't exist in this scope
                    if idx == 0 {
                        // go to parent scope
                        continue 'parent;
                    }
                    return &Value::Null;
                }
            }
        }
        return resolved_value;
    }
    resolved_value
}

// this function iterates over a list of fragments and writes
// each one out to the writer, will call itself recursively
// to render sections and partials
fn _render<K: Borrow<str> + Eq + Hash, T: TemplateLoader<K> + ?Sized, W: Write>(
    frags: &[Fragment<'_>],
    skips: &[SectionSkip],
    loader: &T,
    scopes: &mut Vec<&serde_json::Value>,
    writer: &mut W,
) -> Result<(), T::Error> {
    use serde_json::Value;
    let mut frag_idx = 0;
    let mut section_idx = 0;
    while frag_idx < frags.len() {
        let frag = &frags[frag_idx];
        match frag {
            // write literal to writer
            Fragment::Literal(literal) => {
                writer.write_all(literal.as_bytes())
                    .map_err(|err| MoostacheError::from_io(err, String::new()))?;
                frag_idx += 1;
            },
            // write variable value to writer, escape any html chars
            Fragment::EscapedVariable(name) => {
                let resolved_value = resolve_value(name, scopes);
                write_value(resolved_value, &mut EscapeHtml(writer))?;
                frag_idx += 1;
            },
            // write variable value to writer
            Fragment::UnescapedVariable(name) => {
                let resolved_value = resolve_value(name, scopes);
                write_value(resolved_value, writer)?;
                frag_idx += 1;
            },
            // check if section value is truthy, if not skip it,
            // otherwise create an "implicit iterator" over
            // the resolved value and render the section content
            // that many times
            Fragment::Section(name) => {
                let resolved_value = resolve_value(name, scopes);
                let start_frag = frag_idx + 1;
                let end_frag = start_frag + skips[section_idx].nested_fragments as usize;
                let start_section = section_idx + 1;
                let end_section = start_section + skips[section_idx].nested_sections as usize;
                if is_truthy(resolved_value) {
                    if let Value::Array(array) = resolved_value {
                        for value in array {
                            scopes.push(value);
                            _render(
                                &frags[start_frag..end_frag],
                                &skips[start_section..end_section],
                                loader,
                                scopes,
                                writer,
                            )?;
                            scopes.pop();
                        }
                    } else {
                        scopes.push(resolved_value);
                        _render(
                            &frags[start_frag..end_frag],
                            &skips[start_section..end_section],
                            loader,
                            scopes,
                            writer,
                        )?;
                        scopes.pop();
                    }
                }
                frag_idx += 1 + skips[section_idx].nested_fragments as usize;
                section_idx += 1 + skips[section_idx].nested_sections as usize;
            },
            // check if invertedsection value is falsey, if not
            // skip it, otherwise render inner content
            Fragment::InvertedSection(name) => {
                let resolved_value = resolve_value(name, scopes);
                let start_frag = frag_idx + 1;
                let end_frag = start_frag + skips[section_idx].nested_fragments as usize;
                let start_section = section_idx + 1;
                let end_section = start_section + skips[section_idx].nested_sections as usize;
                if !is_truthy(resolved_value) {
                    scopes.push(resolved_value);
                    _render(
                        &frags[start_frag..end_frag],
                        &skips[start_section..end_section],
                        loader,
                        scopes,
                        writer,
                    )?;
                    scopes.pop();
                }
                frag_idx += 1 + skips[section_idx].nested_fragments as usize;
                section_idx += 1 + skips[section_idx].nested_sections as usize;
            },
            // render partial by loading its content via a TemplateLoader
            Fragment::Partial(path) => {
                let template = loader.get(path)?;
                _render(
                    &template.fragments.get().0,
                    &template.skips,
                    loader,
                    scopes,
                    writer,
                )?;
                frag_idx += 1;
            },
        }
    }
    Ok(())
}

////////////
// ERRORS //
////////////

/// Enum of all possible errors that
/// moostache can produce.
/// 
/// The [`String`] in almost every enum variant
/// is the name of the template which produced
/// the error.
#[derive(Debug, Clone, PartialEq)]
pub enum MoostacheError {
    /// Reading from the filesystem, or writing
    /// to a writer, failed for whatever reason.
    IoError(String, std::io::ErrorKind),
    /// Parsing failed for some generic unidentifiable
    /// reason.
    ParseErrorGeneric(String),
    /// Parsing failed because the template was empty.
    ParseErrorNoContent(String),
    /// Not all sections were properly closed
    /// in the template.
    ParseErrorUnclosedSectionTags(String),
    /// Some escaped variable tag, e.g. {{ variable }},
    /// was invalid.
    ParseErrorInvalidEscapedVariableTag(String),
    /// Some unescaped variable tag, e.g. {{{ variable }}},
    /// was invalid.
    ParseErrorInvalidUnescapedVariableTag(String),
    /// Some section end tag, e.g. {{/ section }},
    /// was invalid.
    ParseErrorInvalidSectionEndTag(String),
    /// Some section end tag doesn't match its section
    /// start tag, e.g. {{# section1 }} ... {{/ section2 }}
    ParseErrorMismatchedSectionEndTag(String),
    /// Some comment tag, e.g. {{! comment }}, is invalid.
    ParseErrorInvalidCommentTag(String),
    /// Some section start tag, e.g. {{ section }}, is invalid.
    ParseErrorInvalidSectionStartTag(String),
    /// Some inverted section start tag, e.g. {{^ section }}, is invalid.
    ParseErrorInvalidInvertedSectionStartTag(String),
    /// Some partial tag, e.g. {{> partial }}, is invalid.
    ParseErrorInvalidPartialTag(String),
    /// Loader tried to load a template but couldn't find it by
    /// its name.
    LoaderErrorTemplateNotFound(String),
    /// [`FileLoader`] tried to load a template but its filepath wasn't
    /// valid utf-8.
    LoaderErrorNonUtf8FilePath(PathBuf),
    /// Cache size parameter in [`LoaderConfig`] must be greater than zero.
    ConfigErrorNonPositiveCacheSize,
    /// Templates directory passed to [`LoaderConfig`] is not a directory.
    ConfigErrorInvalidTemplatesDirectory(PathBuf),
    /// Tried creating a [`HashMapLoader`] from a [`LoaderConfig`] but there were
    /// more templates in the directory than the maximum allowed by cache
    /// size so not all templates could be loaded into memory. To fix this
    /// increase your cache size or switch to [`FileLoader`].
    ConfigErrorTooManyTemplates,
    /// moostache uses [`serde_json`] internally, and if [`serde_json`] fails
    /// to serialize anything for any reason this error will be returned.
    SerializationError,
}

impl MoostacheError {
    fn from_internal(internal: InternalError, s: String) -> Self {
        match internal {
            InternalError::ParseErrorGeneric => MoostacheError::ParseErrorGeneric(s),
            InternalError::ParseErrorNoContent => MoostacheError::ParseErrorNoContent(s),
            InternalError::ParseErrorUnclosedSectionTags => MoostacheError::ParseErrorUnclosedSectionTags(s),
            InternalError::ParseErrorInvalidEscapedVariableTag => MoostacheError::ParseErrorInvalidEscapedVariableTag(s),
            InternalError::ParseErrorInvalidUnescapedVariableTag => MoostacheError::ParseErrorInvalidUnescapedVariableTag(s),
            InternalError::ParseErrorInvalidSectionEndTag => MoostacheError::ParseErrorInvalidSectionEndTag(s),
            InternalError::ParseErrorMismatchedSectionEndTag => MoostacheError::ParseErrorMismatchedSectionEndTag(s),
            InternalError::ParseErrorInvalidCommentTag => MoostacheError::ParseErrorInvalidCommentTag(s),
            InternalError::ParseErrorInvalidSectionStartTag => MoostacheError::ParseErrorInvalidSectionStartTag(s),
            InternalError::ParseErrorInvalidInvertedSectionStartTag => MoostacheError::ParseErrorInvalidInvertedSectionStartTag(s),
            InternalError::ParseErrorInvalidPartialTag => MoostacheError::ParseErrorInvalidPartialTag(s),
        }
    }
    fn set_name(mut self, name: &str) -> Self {
        use MoostacheError::*;
        match &mut self {
            ParseErrorGeneric(s) |
            ParseErrorNoContent(s) |
            ParseErrorUnclosedSectionTags(s) |
            ParseErrorInvalidEscapedVariableTag(s) |
            ParseErrorInvalidUnescapedVariableTag(s) |
            ParseErrorInvalidSectionEndTag(s) |
            ParseErrorMismatchedSectionEndTag(s) |
            ParseErrorInvalidCommentTag(s) |
            ParseErrorInvalidSectionStartTag(s) |
            ParseErrorInvalidInvertedSectionStartTag(s) |
            ParseErrorInvalidPartialTag(s) |
            IoError(s, _) |
            LoaderErrorTemplateNotFound(s) => {
                s.clear();
                s.push_str(name);
            },
            _ => unreachable!("trying to set name for parse error"),
        };
        self
    }
    fn from_io(io: std::io::Error, s: String) -> Self {
        let kind = io.kind();
        MoostacheError::IoError(s, kind)
    }
}

impl std::error::Error for MoostacheError {}

impl Display for MoostacheError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use MoostacheError::*;
        fn template_name(name: &str) -> String {
            if name.is_empty() {
                return "anonymous".to_owned();
            }
            format!("\"{name}\"")
        }
        match self {
            ParseErrorGeneric(s) => write!(f, "error parsing {} template", template_name(s)),
            ParseErrorNoContent(s) => write!(f, "error parsing {} template: empty template", template_name(s)),
            ParseErrorUnclosedSectionTags(s) => write!(f, "error parsing {} template: unclosed section tags", template_name(s)),
            ParseErrorInvalidEscapedVariableTag(s) => write!(f, "error parsing {} template: invalid escaped variable tag, expected {{{{ variable }}}}", template_name(s)),
            ParseErrorInvalidUnescapedVariableTag(s) => write!(f, "error parsing {} template: invalid unescaped variable tag, expected {{{{{{ variable }}}}}}", template_name(s)),
            ParseErrorInvalidSectionEndTag(s) => write!(f, "error parsing {} template: invalid section eng tag, expected {{{{/ section }}}}", template_name(s)),
            ParseErrorMismatchedSectionEndTag(s) => write!(f, "error parsing {} template: mismatched section eng tag, expected {{{{# section }}}} ... {{{{/ section }}}}", template_name(s)),
            ParseErrorInvalidCommentTag(s) => write!(f, "error parsing {} template: invalid comment tag, expected {{{{! comment }}}}", template_name(s)),
            ParseErrorInvalidSectionStartTag(s) => write!(f, "error parsing {} template: invalid section start tag, expected {{{{# section }}}}", template_name(s)),
            ParseErrorInvalidInvertedSectionStartTag(s) => write!(f, "error parsing {} template: invalid inverted section start tag, expected {{{{^ section }}}}", template_name(s)),
            ParseErrorInvalidPartialTag(s) => write!(f, "error parsing {} template: invalid partial tag, expected {{{{> partial }}}}", template_name(s)),
            IoError(s, error_kind) => write!(f, "error reading {} template: {}", template_name(s), error_kind),
            LoaderErrorTemplateNotFound(s) => write!(f, "loader error: {} template not found", template_name(s)),
            LoaderErrorNonUtf8FilePath(s) => write!(f, "loader error: can't load non-utf8 file path: {}", s.display()),
            ConfigErrorNonPositiveCacheSize => write!(f, "config error: cache size must be positive"),
            ConfigErrorInvalidTemplatesDirectory(s) => write!(f, "config error: invalid templates directory: {}", s.display()),
            ConfigErrorTooManyTemplates => write!(f, "config error: templates in directory exceeds cache size"),
            SerializationError => write!(f, "serialization error: could not serialize data to serde_json::Value"),
        }
    }
}

// The reason why we have this is because our parser is a backtracking
// parser that will try to parse something, and if it fails, will
// backtrack and try another parser. This means that even parsing a
// valid mustache template will generate A LOT of errors, and we don't
// want to heap allocate a String every time the parser has to backtrack
// due to an error, so we have this InternalError type instead for parser
// errors that eventually get converted to MoostacheErrors by the time they
// make it to the user.
#[derive(Debug, Copy, Clone, PartialEq)]
enum InternalError {
    ParseErrorGeneric,
    ParseErrorNoContent,
    ParseErrorUnclosedSectionTags,
    ParseErrorInvalidEscapedVariableTag,
    ParseErrorInvalidUnescapedVariableTag,
    ParseErrorInvalidSectionEndTag,
    ParseErrorMismatchedSectionEndTag,
    ParseErrorInvalidCommentTag,
    ParseErrorInvalidSectionStartTag,
    ParseErrorInvalidInvertedSectionStartTag,
    ParseErrorInvalidPartialTag,
}

impl std::error::Error for InternalError {}

impl Display for InternalError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use InternalError::*;
        match self {
            ParseErrorGeneric => write!(f, "generic parse error"),
            ParseErrorNoContent => write!(f, "parse error: empty moostache template"),
            ParseErrorUnclosedSectionTags => write!(f, "parse error: unclosed section tags"),
            ParseErrorInvalidEscapedVariableTag => write!(f, "parse error: invalid escaped variable tag, expected {{{{ variable }}}}"),
            ParseErrorInvalidUnescapedVariableTag => write!(f, "parse error: invalid unescaped variable tag, expected {{{{{{ variable }}}}}}"),
            ParseErrorInvalidSectionEndTag => write!(f, "parse error: invalid section eng tag, expected {{{{/ section }}}}"),
            ParseErrorMismatchedSectionEndTag => write!(f, "parse error: mismatched section eng tag, expected {{{{# section }}}} ... {{{{/ section }}}}"),
            ParseErrorInvalidCommentTag => write!(f, "parse error: invalid comment tag, expected {{{{! comment }}}}"),
            ParseErrorInvalidSectionStartTag => write!(f, "parse error: invalid section start tag, expected {{{{# section }}}}"),
            ParseErrorInvalidInvertedSectionStartTag => write!(f, "parse error: invalid inverted section start tag, expected {{{{^ section }}}}"),
            ParseErrorInvalidPartialTag => write!(f, "parse error: invalid partial tag, expected {{{{> partial }}}}"),
        }
    }
}

// need to impl this so InternalError plays nice with winnow
impl<I: Stream> WParserError<I> for InternalError {
    #[inline]
    fn from_error_kind(_input: &I, _kind: ErrorKind) -> Self {
        InternalError::ParseErrorGeneric
    }

    #[inline]
    fn append(
        self,
        _input: &I,
        _token_start: &<I as Stream>::Checkpoint,
        _kind: ErrorKind,
    ) -> Self {
        self
    }

    #[inline]
    fn or(self, other: Self) -> Self {
        other
    }
}

// need to impl this so InternalError plays nice with winnow
impl<I: Stream> AddContext<I, Self> for InternalError {
    #[inline]
    fn add_context(
        self,
        _input: &I,
        _token_start: &<I as Stream>::Checkpoint,
        context: Self,
    ) -> Self {
        context
    }
}