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
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
//! The `hair` crate provides text templates, not unlike mustache and handlebars (and the earlier ctemplate original), but a bit different.
//! All errors are treated as hard errors and are reported.
//! So missing values are not silently ignored.
//! Also, the templates support evaluation: `{{=expression}}`.
//! The supported expressions are from the [`expry`] crate, which provided executing expression on binary encoded JSON-like values.
//!
//! # Syntax
//! In short the features and syntax:
//! - Variables can be declared at top of an input file with `type key: expry` pairs (JSON is a valid expry). `type` can be either `inline` (value is replaced during compilation of the template) or `default` (which is a default value that is added to the evaluation time value). The first non-parsable line signals the end of the variables.
//! - Values can be outputted with `{{=value}}` (supports expressions, see below). Escape mode can
//! be specified with `{{=value:escape_mode}}`. Values are processed by a user-definable escaper
//! that can take the escape mode into account. Normally only strings and numbers are displayed,
//! and the `null` value is considered a nop. Other values are considered an error, except when the
//! `sjs` (script-js) or `js` escape mode is used.
//! - Conditionals with `{{if value}}contents{{end}}`. Contents is displayed if value evaluates to `true`.
//! - Iterators with `{{for variable in name}}content{{end}}`, which can be used to iterate over (arrays of) any type. The contents of the array is available in the loop body under key `variable`;
//! - Template definition with `{{define name}}content{{end}}`. Templates can have optional default values (in an object) with `{{define name defaults object}}content{{end}}`. Defaults are resolved at template compile time, using the global context given to the compile function;
//! - Template instantiation with `{{call name}}` or `{{call name with value}}`. `name` can be an expression. If the name starts with a `*`, name can be an expression that resolves to a string (which is treated as a template name). If the name starts with `**`, name should be an expression that resolves to a binary form template code (as produced by the compile functions). If the `with` syntax is used, only the data specified in `value` is passed along (so the current context is not automatically transfered/merged, to do that use for value `{...this, key: value}`). This is done to avoid errors.
//! - Error handling is different from normal Mustache: missing fields is always considered an error. Errors can be suppressed with the `expr ??? alternative` try syntax (on error in `expr`, `alternative` will be executed). Shorthand for `expr ??? null` is `expr ???` (which can be used in loops with `{{for i in someField???}}`, which ignores errors if the field is not found).
//!
//! Some other template systems have the ability to iterate without variables, in effect making 
//! the object fields available in the current context. Although this is at first appealing,
//! this makes these templates error-prone. Types can differ, depending on the presence of fields
//! in the object iterated over (which can change for each iteration). One of the design goals of hair
//! is error handling. To fall back to the value in the global context on error such as field not
//! found, the following expression can be used: `{{iteration_variable.foo???foo}}`. This makes the
//! whole expression explicit in its intent.
//!
//! ## Escaping
//!
//! Normally, all strings that are dynamically outputted (using an evaluating `{{=..}}`
//! statement) are automatically 'escaped' using the escaper as given to an argument to the
//! `hairy_eval` function. However, often you will want different escape modes depending on the
//! input context. For example in HTML, output may not normally contain `<` or `>`, but output
//! inside attributes in HTML tags are normally escaped like URLs. Although users can specify for
//! every output the escape mode by appending a `:html` or `:url` escaping mode to an expression,
//! this is error-prone. Auto escaping is therefore a safer alternative, by automatically deciding
//! the escape mode from the input. The general advise is to escape defensively. `hair` functions
//! support an argument that is used to look up the escaping mode for a certain position in the input.
//!
//! # Easy interface
//! The 'easy' interface if you just want to quickly use an HTML template, with auto escaping of the
//! input, and returning a nicely formatted error that can be presented to the user. To evaluate, use [`hairy_eval_html`], so the proper escaper is used.
//!
//! Note that although [`hairy_compile_html`] and [`hairy_eval_html]` are easier to use, they are
//! somewhat slower. For top performance please use the [`hairy_compile`] and the [`hairy_eval`]
//! functions.
//!
//! # Example using the simple interface
//!
//! ```
//! use hairy::*;
//! use expry::*;
//! use std::io::Write;
//! let template = r#"foobar = {{=foovar .. barvar}}"#;
//! let result = hairy_compile_html(template, "test.tpl", None, 0);
//! match result {
//!   Ok(parsed) => {
//!     let value = value!({
//!       "foovar": "foo",
//!       "barvar": "bar",
//!     }).to_vec(false);
//!     match hairy_eval_html(parsed.to_ref(), value.to_ref()) {
//!       Ok(output) => { std::io::stdout().write_all(&output); },
//!       Err(err) => { eprintln!("{}", err); },
//!     }
//!   },
//!   Err(err) => {
//!     eprintln!("{}", err);
//!     assert!(false); // to check this example
//!   }
//! }
//! ```
//!
//! # Enclosing other template files
//!
//! The value can contain other template compiled with `hairy_compile_html`. So if value `body`
//! contains the bytecode of such a template, that template can be invoked from the 'main' template
//! by using the template expression `{{call **body with argument}}`.
//!
//! ```
//! use hairy::*;
//! use expry::*;
//! use std::io::Write;
//! let main_template = r#"<html><title>{{=title}}</title><body>{{call **body with {title,foobarvar}}}</body></html>"#;
//! let main = hairy_compile_html(main_template, "main.tpl", None, 0).unwrap();
//! let child_template = r#"<p>title of this page = {{=title}}</p><p>foobar = {{=foobarvar}}"#;
//! let child = hairy_compile_html(child_template, "child.tpl", None, 0).unwrap();
//! let value = value!({
//!   "body": child,
//!   "foobarvar": "foobar",
//!   "title": "my title",
//! }).to_vec(false);
//! match hairy_eval_html(main.to_ref(), value.to_ref()) {
//!   Ok(output) => { std::io::stderr().write_all(&output).unwrap(); },
//!   Err(err) => {
//!     eprintln!("{}", err);
//!     assert!(false); // to check this example
//!   },
//! }
//! ```
#![allow(dead_code)]

extern crate alloc;
use alloc::format;
use alloc::vec;
use alloc::vec::Vec;
use alloc::string::String;

use core::fmt;
use core::fmt::Write;

pub use expry::{BytecodeVec,BytecodeRef,ValueVec,ValueRef,NoCustomFuncs};
use expry::*;

const EMPTY_EXPRY_OBJECT: &[u8] = b"\x06";

/// Internal error of the Hair lexer. Contains the source code line number.
#[derive(Debug, Copy, Clone)]
pub struct HairLexerError {
    line_nr: u32,
}

/// The errors that can occur during Hair template parsing. It can either be a lexer error (so a part of
/// the input can not be translated to a token), or a parser error (a different token expected).
/// As Hair templates can contain expressions, these expressions can also trigger errors. These
/// can either be in the parsing of the expressions, or during optimizing (which causes
/// EvalErrors). Other errors are reporting using `Other`.
#[derive(Copy, Clone)]
pub enum HairParserError<'a> {
    Lexer(HairLexerError),
    Parser(&'a str),
    Expr(CompileErrorDescription<'a>),
    Eval(EvalError<'a>),
    Other(&'a str),
}

#[derive(Clone, Debug)]
pub struct HairCompileError<'a> {
    error: HairParserError<'a>,
    start: usize, // counted from the back of the input string
    end: usize, // counted from the back of the input string
    extra: Option<(usize, usize)>,
    line_context: LineContext,
}

impl<'a> core::fmt::Display for HairCompileError<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} [{}-{}]", self.error, self.start, self.end)
    }
}

impl<'a> From<EncodingError> for HairParserError<'a> {
    fn from(_: EncodingError) -> Self {
        HairParserError::Other("internal encoding error")
    }
}
impl<'a> fmt::Debug for HairParserError<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self)
    }
}
impl<'a> core::fmt::Display for HairParserError<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HairParserError::Lexer(err) => write!(f, "{:?} (in lexer)", err),
            HairParserError::Expr(err) => write!(f, "{} (during parsing of the expression)", err),
            HairParserError::Parser(s) => write!(f, "{}", s),
            HairParserError::Other(s) => write!(f, "{}", s),
            HairParserError::Eval(s) => write!(f, "{}", s),
        }
    }
}

type Expr<'a> = &'a str;
type Text<'a> = &'a str;
type Name<'a> = &'a str;
type Bytes<'a> = &'a [u8];

#[derive(PartialEq, Copy, Clone, Debug)]
enum HairToken<'a> {
    EndOfInput(),
    Text(Text<'a>),
    Loop(Expr<'a>, usize, Name<'a>, Name<'a>), // expr, offset of expr variable, index variable, contents variable
    Conditional(Expr<'a>, usize), // expr
    Else(),
    BlockEnd(Name<'a>),
    Eval(Expr<'a>, usize, Bytes<'a>), // .1: offset of expression (for error messages)
    CallTemplate(Name<'a>, usize, Expr<'a>, usize), // .1, .3: offset of name/expression (for error messages)
    TemplateDef(Name<'a>, Expr<'a>, usize),  // name, defaults, offset_defaults
}

/// This spanner will try to recognize the content of a Hair template (`{{..}}`). It counts the number of
/// nested `{` and `}`. It does have support for recognizing embedded strings, so `{{foo != "}"}}` will work. Raw strings or the like are not supported, instead you can use `{foo != r#" \" "#}`. Stops at first `}` encountered that is not started inside the expression.
pub struct TemplateTagContentSpanner {
    prev_was_escape: bool,
    string: bool,
    nested: u32,
}

impl Spanner for TemplateTagContentSpanner {
    fn next(&mut self, b: char) -> bool {
        if !self.prev_was_escape && !self.string && b == '{' {
            self.nested += 1;
        }
        if !self.prev_was_escape && !self.string && b == '}' {
            if self.nested == 0 {
                return false;
            }
            self.nested -= 1;
        }
        if !self.prev_was_escape && b == '"' {
            self.string = !self.string;
        }
        self.prev_was_escape = !self.prev_was_escape && b == '\\';
        true
    }
    fn valid(&mut self) -> bool {
        self.nested == 0 && !self.string && !self.prev_was_escape
    }
}
impl TemplateTagContentSpanner {
    pub fn new() -> Self {
        Self {
            prev_was_escape: false,
            string: false,
            nested: 0,
        }
    }
}

impl Default for TemplateTagContentSpanner {
    fn default() -> Self {
        Self::new()
    }
}

/// Recognizes expressions by counting the `{`, `}`, `[`, `]`, and `"`. Does not support advanced
/// string literals such as raw strings (e.g. `r##" " "##`). Stops at first `]` or `}` encountered
/// that is not started inside the expression.
pub struct ExprySpanner {
    prev_was_escape: bool,
    string: bool,
    nested: u32,
}

impl Spanner for ExprySpanner {
    fn next(&mut self, b: char) -> bool {
        if !self.prev_was_escape && !self.string && (b == '{' || b == '[') {
            self.nested += 1;
        }
        if !self.prev_was_escape && !self.string && (b == '}' || b == ']') {
            if self.nested == 0 {
                return false;
            }
            self.nested -= 1;
        }
        if !self.prev_was_escape && b == '"' {
            self.string = !self.string;
        }
        self.prev_was_escape = !self.prev_was_escape && b == '\\';
        true
    }

    fn valid(&mut self) -> bool {
        self.nested == 0 && !self.string && !self.prev_was_escape
    }
}

impl ExprySpanner {
    pub fn new() -> Self {
        Self {
            prev_was_escape: false,
            string: false,
            nested: 0,
        }
    }
}

impl Default for ExprySpanner {
    fn default() -> Self {
        Self::new()
    }
}

fn find_subsequence<T>(haystack: &[T], needle: &[T]) -> Option<usize> where for<'a> &'a [T]: PartialEq {
    haystack.windows(needle.len()).position(|window| window == needle)
}

fn hairy_tokenize<'a,'b,'c>(
    reader: &mut &'b str,
    context: &mut ParserContext<'a,'b,'c>,
) -> Result<(HairToken<'b>,usize), (HairParserError<'b>,usize,usize)> {
    const EXPECT_HAIRY_CLOSE : HairParserError = HairParserError::Parser("expecting closing `}}` after a non empty expression");
    fn read_enters(reader: &mut &str) -> usize {
        let mut retval = 0;
        if reader.accept("\r") {
            retval += 1;
        }
        if reader.accept("\n") {
            retval += 1;
        }
        retval
    }
    while reader.accept("{{!") {
        let mut embedded_spanner = TemplateTagContentSpanner::new();
        embedded_spanner.span(reader);
        if !reader.accept("}}") {
            return Err((EXPECT_HAIRY_CLOSE, reader.len(), reader.len()));
        }
        read_enters(reader);
    }
    let remaining = reader.len();
    if reader.is_empty() {
        return Ok((HairToken::EndOfInput(), remaining));
    }
    //let err_pos = *pos;
    if reader.accept("{{for ") {
        let mut embedded_spanner = TemplateTagContentSpanner::new();
        let expr = embedded_spanner.span(reader).map_or("", |x| x);
        if expr.is_empty() || !reader.accept("}}") {
            return Err((EXPECT_HAIRY_CLOSE, reader.len(), reader.len()));
        }
        let content_end = reader.len() + 2;
        let content_end_offset = 2 + read_enters(reader);
        const IN_LEN : usize = 4;
        if let Some((variable, expr)) = expr.split_once(" in ") {
            let mut variable = variable.trim_start();
            let mut index_variable = "";
            let mut content_variable = "";
            let matcher = |c: char| c == '$' || c == '_' || c == '\\' || c.is_ascii_alphanumeric();
            if strparse(variable).accept('(').span(is_space, 0).span(matcher, 1).matched(&mut index_variable).span(is_space, 0).accept(",").span(is_space, 0).span(matcher, 1).matched(&mut content_variable).span(is_space, 0).accept(')').valid(&mut variable) {
                return Ok((HairToken::Loop(expr, content_end_offset, index_variable, content_variable), remaining));
            }
            if variable.trim().contains(|x| !matcher(x)) {
                const EXPECT_HAIRY_VARIABLE : HairParserError = HairParserError::Parser("variable name may only consists of alphanumeric chars, and `$` and `_`");
                return Err((EXPECT_HAIRY_VARIABLE, variable.len() + IN_LEN + expr.len() + content_end, IN_LEN + expr.len() + content_end));
            }
            return Ok((HairToken::Loop(expr, content_end_offset, "", variable), remaining));
        } else {
            const EXPECT_HAIRY_VARIABLE : HairParserError = HairParserError::Parser("expected variable name (indicated with `{{for variable in expr}}`)");
            return Err((EXPECT_HAIRY_VARIABLE, expr.len() + content_end, content_end));
        }
    }
    if reader.accept("{{if ") {
        let mut embedded_spanner = TemplateTagContentSpanner::new();
        let expr = embedded_spanner.span(reader).map_or("", |x| x);
        if expr.is_empty() || !reader.accept("}}") {
            return Err((EXPECT_HAIRY_CLOSE, reader.len(), reader.len()));
        }
        let content_end_offset = 2 + read_enters(reader);
        return Ok((HairToken::Conditional(expr, content_end_offset),remaining));
    }
    if reader.accept("{{else}}") {
        read_enters(reader);
        return Ok((HairToken::Else(),remaining));
    }
    if reader.accept("{{end") {
        let mut embedded_spanner = TemplateTagContentSpanner::new();
        let expr = embedded_spanner.span(reader).map_or("", |x| x);
        if !reader.accept("}}") {
            return Err((EXPECT_HAIRY_CLOSE, reader.len(), reader.len()));
        }
        read_enters(reader);
        return Ok((HairToken::BlockEnd(expr),remaining));
    }
    if reader.accept("{{define ") {
        let mut embedded_spanner = TemplateTagContentSpanner::new();
        let expr = embedded_spanner.span(reader).map_or("", |x| x);
        if expr.is_empty() || !reader.accept("}}") {
            return Err((EXPECT_HAIRY_CLOSE, reader.len(), reader.len()));
        }
        let content_end = reader.len() + 2;
        let content_end_offset = 2 + read_enters(reader);
        const DEFAULTS_LEN : usize = 10;
        let check = |name: &str, extra_len: usize| -> Result<(),(HairParserError, usize, usize)> {
            let matcher = |c: char| c == '$' || c == '_' || c == '\\' || c.is_ascii_alphanumeric();
            if name.trim().contains(|x| !matcher(x)) {
                const HAIRY_ERROR : HairParserError = HairParserError::Parser("template name may only consists of alphanumeric chars, and `$` and `_`");
                return Err((HAIRY_ERROR, name.len() + extra_len + content_end, extra_len + content_end));
            }
            Ok(())
        };
        if let Some((name, defaults)) = expr.split_once(" defaults ") {
            check(name, DEFAULTS_LEN + defaults.len())?;
            return Ok((HairToken::TemplateDef(name.trim(), defaults, content_end_offset),remaining));
        }
        check(expr, 0)?;
        return Ok((HairToken::TemplateDef(expr.trim(), "", content_end_offset),remaining));
    }
    if reader.accept("{{call ") {
        // FIXME: switch to different spanner, to handle {{call **(" with ") with 1}}
        // likewise for different commands
        let mut embedded_spanner = TemplateTagContentSpanner::new();
        let expr = embedded_spanner.span(reader).map_or("", |x| x);
        if expr.is_empty() || !reader.accept("}}") {
            return Err((EXPECT_HAIRY_CLOSE, reader.len(), reader.len()));
        }
        let content_end = reader.len() + 2;
        let content_end_offset = 2 + read_enters(reader);
        const WITH_LEN : usize = 6;
        let check = |name: &str, extra_len: usize| -> Result<(),(HairParserError, usize, usize)> {
            let matcher = |c: char| c == '$' || c == '_' || c == '\\' || c.is_ascii_alphanumeric();
            if !name.starts_with('*') && name.trim().contains(|x| !matcher(x)) {
                const HAIRY_ERROR : HairParserError = HairParserError::Parser("template name may only consists of alphanumeric chars, and `$` and `_` (and start with `*` or `**`)");
                return Err((HAIRY_ERROR, name.len() + extra_len + content_end, extra_len + content_end));
            }
            Ok(())
        };
        if let Some((name, expr)) = expr.split_once(" with ") {
            //println!("call to template '{}' with expr '{}'", String::from_utf8_lossy(name), String::from_utf8_lossy(expr));
            check(name, WITH_LEN + expr.len())?;
            return Ok((HairToken::CallTemplate(name.trim(), WITH_LEN + expr.len() + content_end_offset, expr, content_end_offset),remaining));
        }
        check(expr, 0)?;
        return Ok((HairToken::CallTemplate(expr, content_end_offset, "", content_end_offset), remaining));
    }
    if reader.accept("{{=") {
        let mut embedded_spanner = TemplateTagContentSpanner::new();
        let expr = embedded_spanner.span(reader).map_or("", |x| x);
        if expr.is_empty() || !reader.accept("}}") {
            return Err((EXPECT_HAIRY_CLOSE, reader.len(), reader.len()));
        }
        let content_end_offset = 2;
        const ESCAPE_MODE_LEN : usize = 1;
        if let Some((expr, escape_mode)) = expr.rsplit_once(':') {
            if escape_mode.chars().all(|c| c.is_ascii_alphanumeric()) {
                return Ok((HairToken::Eval(expr, escape_mode.len()+ESCAPE_MODE_LEN+content_end_offset, escape_mode.as_bytes()),remaining));
            }
        }
        return Ok((HairToken::Eval(expr, content_end_offset, b""),remaining));
    }
    if reader.accept("{{") {
        const EXPECT_HAIRY_COMMAND : HairParserError = HairParserError::Parser("expected a command after hair tag: if, else, end, for, call, define, =");
        return Err((EXPECT_HAIRY_COMMAND, remaining, reader.len()));
    }

    let mut retval = ScopedStringBuilder::new(context.allocator);
    loop {
        // searching with reader.find("{{") is slower (?!?)
        let mut start = 0;
        let mut found;
        loop {
            found = reader[start..].find('{').map(|x| x+start);
            if let Some(pos) = found {
                if pos >= reader.len()-1 || &reader[pos..pos+2] != "{{" {
                    start = pos+1;
                    continue;
                }
            }
            break;
        }
        match found {
            None => {
                let extra = &reader[..];
                if !extra.is_empty() {
                    retval.write_str(extra).ok();
                }
                *reader = &reader[0..0];
                return Ok((HairToken::Text(retval.build()),remaining));
            },
            Some(n) => {
                let extra = &reader[0..n];
                *reader = &reader[n..];
                if !extra.ends_with('\\') {
                    if !extra.is_empty() {
                        retval.write_str(extra).ok();
                    }
                    return Ok((HairToken::Text(retval.build()),remaining));
                }
                let extra = &extra[..extra.len()-1];
                if !extra.is_empty() {
                    retval.write_str(extra).ok();
                }
                let reader_saved = *reader;
                *reader = &reader[2..]; // skip "{{"
                let mut embedded_spanner = ExprySpanner::new();
                if let Some(expr) = embedded_spanner.span(reader) {
                    let expr = &reader_saved[0..expr.len()+4]; // include the "{{" before and the "}}" after
                    retval.write_str(expr).ok();
                }
                if !reader.accept("}}") {
                    return Err((EXPECT_HAIRY_CLOSE, reader.len(), reader.len()));
                }
            },
        }
    }
}

#[allow(clippy::upper_case_acronyms)]
type AST<'a> = Vec<HairCommand<'a>>;
type LineNo = u32;
type ColumnNo = u32;

type SourceContext = (LineNo, ColumnNo);

#[derive(PartialEq, Clone)]
enum ResolveTemplate<'a> {
    Static(Name<'a>),
    DynamicName(BytecodeRef<'a>),
    DynamicBody(BytecodeRef<'a>),
}

#[derive(PartialEq, Clone)]
enum HairCommand<'a> {
    Text(Text<'a>),
    Loop(BytecodeRef<'a>, Name<'a>, Name<'a>, AST<'a>, SourceContext),
    Conditional(BytecodeRef<'a>, AST<'a>, AST<'a>, SourceContext),
    Eval(BytecodeRef<'a>, Bytes<'a>, SourceContext), // name is the escape mode
    CallTemplate(ResolveTemplate<'a>, BytecodeRef<'a>, SourceContext),
}

impl<'a> fmt::Debug for ResolveTemplate<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ResolveTemplate::Static(name) => write!(f, "{}", name),
            ResolveTemplate::DynamicName(_) => write!(f, "<dynamic-name>"),
            ResolveTemplate::DynamicBody(_) => write!(f, "<dynamic-body>"),
        }
    }
}
impl<'a> fmt::Debug for HairCommand<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HairCommand::Text(s) => write!(f, "\"{}\"", s),
            HairCommand::Eval(expr, mode, _) => write!(f, "{{{{{:?}:{:?}}}}}", expr, mode),
            HairCommand::Conditional(tag, body, else_body, _) => {
                write!(f, "{{{{if {:?}}}}}", tag)?;
                write!(f, "{:?}", body)?;
                write!(f, "{{{{else}}}}")?;
                write!(f, "{:?}", else_body)?;
                write!(f, "{{{{end}}}}")
            },
            HairCommand::Loop(tag, index_variable, content_variable, body, _) => {
                write!(f, "{{{{for ({:?},{:?}) in {:?}}}}}", index_variable, content_variable, tag)?;
                write!(f, "{:?}", body)?;
                write!(f, "{{{{end}}}}")
            },
            HairCommand::CallTemplate(name, defaults, _) => {
                write!(f, "{{{{{:?} <- {:?}}}}}", name, defaults)
            },
        }
    }
}

struct ParserContext<'a,'b,'c> where 'c: 'b {
    line_context: LineContext,
    allocator: &'a mut MemoryScope<'c>,
    templates: Vec<(&'b str, &'b str, ValueRef<'b>, AST<'b>)>,
    inlines: Option<&'a DecodedValue<'b>>,
    filename: &'b str,
    custom: &'a mut dyn CustomFuncs,
    input_len: usize,
    escaping: Option<&'a [(usize, &'b [u8])]>,
}
type HairParserState<'a,'b,'c> = ParserState<'b,HairToken<'b>, HairParserError<'b>, ParserContext<'a,'b,'c>>;
type HairParserResult<'b,T> = ParserResult<T, HairParserError<'b>>;

fn hairy_expr<'b,'c>(parser: &'_ mut HairParserState<'_,'b,'c>) -> HairParserResult<'b,AST<'b>> where 'c: 'b {
    let mut retval: AST = Vec::new();
    parser.repeat(|parser: &mut _| {
        let to_source_context = |pos, parser: &mut HairParserState| { let (a,b,_,_) = parser.context().line_context.remaining_to_line_info(pos as u32); (a,b) };
        match parser.get()? {
            (HairToken::Text(text), _) => {
                retval.push(HairCommand::Text(text));
                Ok(true)
            }
            (HairToken::Eval(expr, expr_offset, mut escape_mode), info) => {
                let bytecode = expry_compile(expr, parser.context().inlines, parser.context().allocator).map_err(|e| parser.error_other(&info.bound(e.error_start()+expr_offset, e.error_end()+expr_offset), HairParserError::Expr(e.error())))?;

                let source_context = to_source_context(info.start_to_end_of_input(), parser);
                if escape_mode.is_empty() {
                    if let Some(escaping) = parser.context().escaping {
                        escape_mode = lookup_escape_mode(escaping, parser.context().input_len - info.start_to_end_of_input());
                    }
                }
                retval.push(HairCommand::Eval(bytecode, escape_mode, source_context));
                Ok(true)
            }
            (HairToken::CallTemplate(name, offset_name, expr, offset_expr), info) => {
                let expr_bytecode = if expr.is_empty() { BytecodeRef::new() } else { expry_compile(expr, parser.context().inlines, parser.context().allocator).map_err(|e| parser.error_other(&info.bound(e.error_start()+offset_expr, e.error_end()+offset_expr), HairParserError::Expr(e.error())))? };

                let source_context = to_source_context(info.start_to_end_of_input(), parser);
                let name = name.trim_start_matches(is_space);
                if let Some(name) = name.strip_prefix("**") {
                    let name_bytecode = expry_compile(name, parser.context().inlines, parser.context().allocator).map_err(|e| parser.error_other(&info.bound(e.error_start()+offset_name, e.error_end()+offset_name), HairParserError::Expr(e.error())))?;
                    retval.push(HairCommand::CallTemplate(ResolveTemplate::DynamicBody(name_bytecode), expr_bytecode, source_context));
                } else if let Some(name) = name.strip_prefix('*') {
                    let name_bytecode = expry_compile(name, parser.context().inlines, parser.context().allocator).map_err(|e| parser.error_other(&info.bound(e.error_start()+offset_name, e.error_end()+offset_name), HairParserError::Expr(e.error())))?;
                    retval.push(HairCommand::CallTemplate(ResolveTemplate::DynamicName(name_bytecode), expr_bytecode, source_context));
                } else {
                    retval.push(HairCommand::CallTemplate(ResolveTemplate::Static(name), expr_bytecode, source_context));
                }
                Ok(true)
            }
            (HairToken::Conditional(expr, offset_expr), info) => {
                let expr_bytecode = expry_compile(expr, parser.context().inlines, parser.context().allocator).map_err(|e| parser.error_other(&info.bound(e.error_start()+offset_expr, e.error_end()+offset_expr), HairParserError::Expr(e.error())))?;

                let source_context = to_source_context(info.start_to_end_of_input(), parser);
                let body = hairy_expr(parser)?;
                match parser.get()? {
                    (HairToken::Else(), _info) => {
                        let else_body = hairy_expr(parser)?;
                        match parser.get()? {
                            (HairToken::BlockEnd(end_tag), info) => {
                                if !end_tag.is_empty() && "if" != end_tag.trim() {
                                    let err_msg = write!(parser.context().allocator, "start (if) and end ({}) tag should be the same", end_tag.trim());
                                    return Err(parser.error_other(&info, HairParserError::Parser(err_msg)))
                                }
                                retval.push(HairCommand::Conditional(expr_bytecode, body, else_body, source_context));
                                Ok(true)
                            }
                            (token, info) => Err(parser.error_token(token, info, |_| {
                                HairParserError::Parser("expected 'end' of conditional")
                            })),
                        }
                    }
                    (HairToken::BlockEnd(end_tag), info) => {
                        if !end_tag.is_empty() && "if" != end_tag.trim() {
                            let err_msg = write!(parser.context().allocator, "start (if) and end ({}) tag should be the same", end_tag.trim());
                            return Err(parser.error_other(&info, HairParserError::Parser(err_msg)))
                        }
                        retval.push(HairCommand::Conditional(expr_bytecode, body, Vec::new(), source_context));
                        Ok(true)
                    }
                    (token, info) => Err(parser.error_token(token, info, |_| {
                        HairParserError::Parser("expected 'end' of conditional")
                    })),
                }
            }
            (HairToken::Loop(expr, expr_offset, index_variable, content_variable), info) => {
                let expr_bytecode = expry_compile(expr, parser.context().inlines, parser.context().allocator).map_err(|e| parser.error_other(&info.bound(e.error_start()+expr_offset, e.error_end()+expr_offset), HairParserError::Expr(e.error())))?;

                let source_context = to_source_context(info.start_to_end_of_input(), parser);
                let body = hairy_expr(parser)?;
                match parser.get()? {
                    (HairToken::BlockEnd(end_tag), info) => {
                        if !end_tag.is_empty() && "for" != end_tag.trim() {
                            let err_msg = write!(parser.context().allocator, "start (for) and end ({}) tag should be the same", end_tag.trim());
                            return Err(parser.error_other(&info, HairParserError::Parser(err_msg)))
                        }
                        retval.push(HairCommand::Loop(expr_bytecode, index_variable, content_variable, body, source_context));
                        Ok(true)
                    }
                    (token, info) => Err(parser.error_token(token, info, |_| {
                        HairParserError::Parser("expected 'end' of loop")
                    })),
                }
            }
            (HairToken::TemplateDef(name, defaults, offset_defaults), info) => {
                let defaults_bytecode = if defaults.is_empty() {
                    ValueRef(b"")
                } else {
                    let bytecode = expry_compile(defaults, parser.context().inlines, parser.context().allocator).map_err(|e| parser.error_other(&info.bound(e.error_start()+offset_defaults, e.error_end()+offset_defaults), HairParserError::Expr(e.error())))?;
                    let context = parser.context();
                    expry_slice_func(bytecode, ValueRef(b""), context.allocator, context.custom).map_err(|err| parser.error_other(&info, HairParserError::Eval(err)))?
                };
                let body = hairy_expr(parser)?;
                match parser.get()? {
                    (HairToken::BlockEnd(end_tag), info) => {
                        if !end_tag.is_empty() && "define" != end_tag {
                            let err_msg = write!(parser.context().allocator, "start (define) and end ({}) tag should be the same", end_tag);
                            return Err(parser.error_other(&info, HairParserError::Parser(err_msg)))
                        }
                        let filename = parser.context().filename;
                        // check that we don't override a template
                        if parser.context().templates.iter().any(|(x,_,_,_)| *x == name) {
                            let err_msg = write!(parser.context().allocator, "template '{}' already defined", name);
                            return Err(parser.error_other(&info, HairParserError::Parser(err_msg)));
                        }

                        parser.context().templates.push((name, filename, defaults_bytecode, body));
                        Ok(true)
                    }
                    (token, info) => Err(parser.error_token(token, info, |_| {
                        HairParserError::Parser("expected 'end' of template definition")
                    })),
                }
            }
            (token, info) => Err(parser.error_token(token, info, |_| HairParserError::Parser(""))),
        }
    })?;
    Ok(retval)
}
fn hairy_top_level<'b,'c>(parser: &'_ mut HairParserState<'_,'b,'c>) -> HairParserResult<'b,AST<'b>> where 'c: 'b {
    let retval = hairy_expr(parser)?;
    parser.accept(HairToken::EndOfInput(), None, || HairParserError::Parser("expected end of input"))?;
    Ok(retval)
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum EscapeMode {
    Normal,
    InsideTag,
    InsideAttribute,
    InsideScript,
    InsideStyle,
    InsideComment,
}
fn mode_to_bytes(mode: EscapeMode) -> &'static [u8] {
    // see https://wonko.com/post/html-escaping/ for explanation
    match mode {
        EscapeMode::Normal => b"", // "html" is the default, so we don't need to store it
        EscapeMode::InsideTag => b"sjs",
        EscapeMode::InsideAttribute => b"", // we can use simple 'html' escaping here, because we force all attributes to have double quotes (") around the value.
        EscapeMode::InsideScript => b"sjs", // script js
        EscapeMode::InsideStyle => b"css",
        EscapeMode::InsideComment => b"",
    }
}
fn parse_html<'a,'b, 'c>(input: &'b str, scope: &mut MemoryScope<'c>) -> Result<&'a [(usize,&'static [u8])], HairCompileError<'b>> where 'c: 'a {
    let mut retval = ScopedArrayBuilder::new(scope);
    let mut inside = 0;
    let mut inside_string = false;

    let mut mode = EscapeMode::Normal;
    let mut last = mode;
    retval.push((0, mode_to_bytes(mode)));
    for (i,c) in input.char_indices() {
        // skip any chars inside hair templates, because otherwise {{foo <- args}} triggers the
        // HTML open.
        if inside_string {
            inside_string = c != '"';
            continue;
        }
        match c {
            '{' => inside += 1,
            '}' => inside -= 1,
            '"' if inside > 0 => inside_string = true,
            _ => {},
        }
        if inside > 0 {
            continue;
        }
        match mode {
            EscapeMode::Normal => {
                if c == '<' {
                    if input[i..].starts_with("<script") {
                        mode = EscapeMode::InsideScript;
                    } else if input[i..].starts_with("<style") {
                        mode = EscapeMode::InsideStyle;
                    } else if input[i..].starts_with("<!--") {
                        mode = EscapeMode::InsideComment;
                    } else if let Some(prefix) = input[i+1..].strip_prefix(|x: char| x.is_ascii_alphanumeric()) {
                        if !prefix.is_empty() {
                            mode = EscapeMode::InsideTag;
                        }
                    }
                }
            },
            EscapeMode::InsideTag => {
                match c {
                    '=' => {
                        if !input[i..].starts_with("=\"") {
                            return Err(HairCompileError{error: HairParserError::Parser("for auto escaping to work, attributes of HTML should have quotes around the values"), start: input.len()-i, end: input.len()-i, extra: None, line_context: LineContext::new(input), });

                        }
                    }
                    '"' => {
                        mode = EscapeMode::InsideAttribute;
                    },
                    '>' => {
                        mode = EscapeMode::Normal;
                    },
                    '<' => {
                        return Err(HairCompileError{error: HairParserError::Parser("unexpected character encounted inside tag, likely to break auto escaping."), start: input.len()-i, end: input.len()-i, extra: None, line_context: LineContext::new(input), });
                    }
                    _ => {},
                };
            },
            EscapeMode::InsideAttribute => {
                if c == '"' {
                    mode = EscapeMode::InsideTag;
                } else if c == '<' || c == '>' {
                    return Err(HairCompileError{error: HairParserError::Parser("unexpected character encounted inside attribute, likely to break auto escaping."), start: input.len()-i, end: input.len()-i, extra: None, line_context: LineContext::new(input), });
                }
            },
            EscapeMode::InsideScript => {
                if c == '<' {
                    if input[i..].starts_with("</script") {
                        mode = EscapeMode::InsideTag;
                    } else {
                        // valid inside script tag:
                        // document.innerHTML = '<button>Open in App</button>';
                    }
                }
            },
            EscapeMode::InsideStyle => {
                if c == '<' {
                    if input[i..].starts_with("</style") {
                        mode = EscapeMode::InsideTag;
                    } else {
                        return Err(HairCompileError{error: HairParserError::Parser("expected end of style tag"), start: input.len()-i, end: input.len()-i, extra: None, line_context: LineContext::new(input), });
                    }
                }
            },
            EscapeMode::InsideComment => {
                if input[i..].starts_with("-->") {
                    mode = EscapeMode::Normal;
                }
            }
        }
        if mode != last {
            if mode_to_bytes(mode) != mode_to_bytes(last) {
                retval.push((i+1, mode_to_bytes(mode)));
            }
            last = mode;
        }
    }
    if mode != EscapeMode::Normal {
        // FIXME: remember when the last tag/attribute was opened, that is probably a more useful error
        // location for this error
        let message = match mode {
            EscapeMode::Normal => "",
            EscapeMode::InsideTag => "expected to end with correctly closed tag, now 'inside tag' mode",
            EscapeMode::InsideAttribute => "expected to end with correctly closed tag, now 'inside attribute' mode",
            EscapeMode::InsideScript => "expected to end with correctly closed tag, now 'inside script' mode",
            EscapeMode::InsideStyle => "expected to end with correctly closed tag, now 'inside style' mode",
            EscapeMode::InsideComment => "expected to end with correctly closed HTML comment, now 'inside HTML comment' mode",
        };
        return Err(HairCompileError{error: HairParserError::Parser(message), start: 0, end: 0, extra: None, line_context: LineContext::new(input), });
    }
    Ok(retval.build())
}

fn lookup_escape_mode<'a>(escaping: &'_ [(usize, &'a [u8])], pos: usize) -> &'a [u8] {
    let pp = escaping.partition_point(|x| x.0 <= pos);
    if pp > 0 {
        return escaping[pp-1].1;
    }
    b""
}

/// Converts a Hair template (in `reader`) to bytecode that can be evaluation later. To help debugging during later evaluation, a
/// `filename` can be added to the bytecode. A MemoryScope is used to reduce the number of
/// allocated strings. The result stays valid as long as the MemoryScope is in the scope (forced by
/// the lifetime system of Rust). The globals and custom functions are used when evaluation the
/// defaults (for template calls and such).
///
/// For an easy to version of this function, see the [`hairy_compile_html`] function (which provide
/// auto escaping automatically).
///
/// ## Escaping
///
/// Normally, all strings that are dynamically outputted (between an evaluating `{{..}}`
/// statement) are automatically 'escaped' using the escaper as given to an argument to the
/// `hairy_eval` function. However, often you will want different escape modes depending on the
/// input context. For example in HTML, output may not normally contain `<` or `>`, but output
/// inside attributes in HTML tags are normally escaped using url-escaping. Although users can specify for
/// every output the escape mode by appending a `:html` or `:url` escaping mode to an expression,
/// this is error prone. Auto escaping is therefore a safer alternative, by automatically dedcing
/// the escape mode from the input. That is where the `escaping` argument comes in to play. That
/// argument is used to lookup the escaping mode for a certain position in the input.
///
/// # Example
///
/// ```
/// use hairy::*;
/// use expry::memorypool::MemoryPool;
/// use std::io::Write;
/// let mut allocator = MemoryPool::new();
/// let mut scope = allocator.rewind();
/// let template = r#"foo {{bar}}"#;
/// let result = hairy_compile(template, "test.tpl", None, ValueRef::new(), &mut scope, None, None);
/// match result {
///   Ok(parsed) => {
///     let value = ValueRef(b"");
///     let output = hairy_eval(parsed.to_ref(), value, &mut scope, None, &[], None);
///     if let Ok(output) = output {
///       std::io::stdout().write_all(&output.concat());
///       // OR, more efficient (avoiding allocations):
///       for v in output {
///         std::io::stdout().write_all(v);
///       }
///     }
///   },
///   Err(err) => {
///     eprintln!("{}", hairy_compile_error_format(template, &err, 0));
///   }
/// }
/// ```
pub fn hairy_compile<'a,'b,'c>(reader: &'b str, filename: &'b str, inlines: Option<&'a DecodedValue<'b>>, defaults: ValueRef<'b>, scope: &mut MemoryScope<'c>, mut option_custom: Option<&mut dyn CustomFuncs>, escaping: Option<&'_ [(usize, &'b [u8])]>) -> Result<BytecodeVec,HairCompileError<'b>> where 'c: 'b, 'b: 'a {
    let mut custom : &mut dyn CustomFuncs = &mut NoCustomFuncs{};
    if let Some(f) = &mut option_custom {
        custom = *f;
    }
    if reader.len() >= u32::MAX as usize {
        return Err(HairCompileError{error: HairParserError::Other("input too large to parse (max 4 GiB)"), start: reader.len(), end: 0usize, extra: None, line_context: LineContext::empty()});
    }
    let context = ParserContext {
        allocator: scope,
        line_context: LineContext::new(reader),
        templates: Vec::new(),
        inlines,
        filename,
        custom,
        escaping,
        input_len: reader.len(),
    };
    let mut parser = HairParserState::new_with(reader, hairy_tokenize, context);
    let ast = match parser.parse(hairy_top_level, HairParserError::Parser("unexpected token"), HairParserError::Parser("max recursion depth of parser reached")) {
        Ok(ast) => ast,
        Err((e,start,end,extra)) => return Err(HairCompileError{error: e, start, end, extra, line_context: parser.context.line_context}),
    };
    //println!("{:?}", ast);

    (|| {
        let bytecode_length = ast_to_binary_size(&ast);
        let templates_length = templates_to_binary_size(&parser.context().templates);
        let total_length = 4 // from the magic code 'hair'
            + size_of_var_bytes(filename.as_bytes())
            + size_of_var_u64(bytecode_length as u64) + bytecode_length
            + size_of_var_u64(templates_length as u64) + templates_length
            + size_of_var_bytes(defaults.get());
        let mut bytecode: Vec<u8> = vec![0; total_length];
        let mut writer = RawWriter::with(&mut bytecode);
        writer.write_bytes(b"hair")?;
        writer.write_var_bytes(filename.as_bytes())?;
        writer.write_var_u64(bytecode_length as u64)?;
        ast_to_binary(&ast, &mut writer).map_err(|err| { println!("{:?}", err); HairParserError::Other("error generating bytecode")})?;
        writer.write_var_u64(templates_length as u64)?;
        templates_to_binary(&parser.context().templates, &mut writer).map_err(|err| { println!("{:?}", err); HairParserError::Other("error generating bytecode")})?;
        writer.write_var_bytes(defaults.get())?;
        Ok(BytecodeVec(bytecode))
    })().map_err(|x| HairCompileError{error: x, start:0, end:0, extra: None, line_context: parser.context.line_context})
}

pub fn hairy_extract_subtemplates<'a>(template_bytecode: BytecodeRef<'a>) -> Result<&'a [u8],HairError> {
    let (_template_name, _template_bytecode, new_templates, _defaults) = decode_hair(template_bytecode.get())?;
    Ok(new_templates)
}

pub fn hairy_compile_error_format(expr: &str, e: &HairCompileError, extra_line_no: u32) -> String {
    let mut retval = String::new();
    let (line_no, prefix, error_msg) = e.line_context.format_error_context(expr, e.start, e.end, extra_line_no).map_or((0u32, String::new(), String::new()), |x| x);
    if line_no > 0 {
        write!(retval, "{}{}error at line {}:{} {}\n{}", prefix, TERM_BRIGHT_RED, line_no+extra_line_no, TERM_RESET, e.error, error_msg).ok();
    } else {
        write!(retval, "unknown error, error during hairy_compile_error_format").ok();
    }
    if let Some((start, end)) = e.extra {
        let (line_no, prefix, error_msg) = e.line_context.format_error_context(expr, start, end, extra_line_no).map_or((0u32, String::new(), String::new()), |x| x);
        if line_no > 0 {
            write!(retval, "{}{}related at line {}:{} expected it here (or earlier)\n{}", prefix, TERM_DIM_CYAN, line_no+extra_line_no, TERM_RESET, error_msg).ok();
        }
    }
    retval
}

/// The 'easy' interface if you just want to quickly use a HTML template, with auto escaping of the
/// input, and returning a nicely formatted error that can be presented to the user. For more
/// options, see the [`hairy_compile`] function.
///
/// To evaluate, use [`hairy_eval_html`], so the proper escaper is used.
///
/// Note that although `hairy_compile_html` and `hairy_eval_html` are easier to use, they are
/// somewhat slower. For top performance please use other functions.
///
/// The `inline_overrides` argument overrides the inline key-value pairs that can be specified on the top
/// of a template. These keys can contain alphanumeric characters, `_`, and `$`. The values should be
/// valid expry expressions (JSON is a valid expry). These values are compiled using the
/// `inline_overrides` as value, so the inlines and defaults can depend on a (sub)value of `compiled` (so derived inlines and defaults can be generated).
///
/// # Example
///
/// ```
/// use hairy::*;
/// use expry::*;
/// use std::io::Write;
/// let template = r#"foobar = {{=foovar .. barvar}}"#;
/// let result = hairy_compile_html(template, "test.tpl", None, 0);
/// match result {
///   Ok(parsed) => {
///     let value = value!({
///       "foovar": "foo",
///       "barvar": "bar",
///     }).to_vec(false);
///     match hairy_eval_html(parsed.to_ref(), value.to_ref()) {
///       Ok(output) => { std::io::stdout().write_all(&output); },
///       Err(err) => { eprintln!("{}", err); },
///     }
///   },
///   Err(err) => {
///     eprintln!("{}", err);
///   }
/// }
/// ```
pub fn hairy_compile_html<'b>(reader: &'b str, filename: &'b str, inline_overrides: Option<&DecodedValue<'b>>, mut extra_line_no: u32) -> Result<BytecodeVec,String> {
    let mut allocator = MemoryPool::new();
    let mut scope = allocator.rewind();
    let mut custom = NoCustomFuncs{};

    let mut defaults = DecodedObject::new();
    let mut inlines = DecodedObject::new();
    if let Some(DecodedValue::Object(object)) = inline_overrides {
        inlines = object.clone();
    }

    let mut key = "";
    let mut value = "";
    let mut current = reader;
    let mut type_of = "";
    loop {
        if StringParser::new(current).accepts(&["default ", "inline "]).matched(&mut type_of).span(|c: char| -> bool { char::is_ascii_alphanumeric(&c) || c == '$' || c == '_' }, 1).matched(&mut key).accept(':').split(&mut value, '\n').valid(&mut current) {
            extra_line_no += 1;
            let inlines_clone = DecodedValue::Object(inlines.clone());
            let container = if type_of == "default " { &mut defaults } else { &mut inlines };
            let key = key_str(key);
            if container.contains_key(&key) {
                continue;
            }
            let bytecode = expry_compile(value, Some(&inlines_clone), &mut scope);
            match bytecode {
                Ok(bytecode) => {
                    let result = expry_eval(bytecode, ValueRef::new(), &mut scope);
                    match result {
                        Ok(value) => { container.insert(key, value); },
                        Err(error) => {
                            return Err(hairy_compile_error_format(reader, &HairCompileError{
                                error: HairParserError::Eval(error),
                                start: current.len() + 1,
                                end: current.len() + 1,
                                extra: None,
                                line_context: LineContext::new(reader),
                            }, 0));
                        },
                    }
                },
                Err(error) => {
                    return Err(hairy_compile_error_format(reader, &HairCompileError{
                        error: HairParserError::Expr(error.error),
                        start: current.len() + 1 + error.start,
                        end: current.len() + 1 + error.end,
                        extra: error.extra.map(|(start,end)| (current.len() + 1 + start, current.len() + 1 + end)),
                        line_context: LineContext::new(reader),
                    }, 0));
                },
            }
        } else if strparse(current).accept('#').split(&mut value, '\n').valid(&mut current) {
            extra_line_no += 1;
        } else {
            break;
        }
    }
    let inlines = DecodedValue::Object(inlines);
    let defaults = if defaults.is_empty() { ValueRef::new() } else { DecodedValue::Object(defaults).to_scope(&mut scope, false) };
    let escaping = parse_html(current, &mut scope).map_err(|err| hairy_compile_error_format(current, &err, extra_line_no))?;
    hairy_compile(current, filename, Some(&inlines), defaults, &mut scope, Some(&mut custom), Some(escaping)).map_err(|err| hairy_compile_error_format(current, &err, extra_line_no))
}

fn templates_to_binary<E, Out: RawOutput<E>>(templates: &[(&str, &str, ValueRef, Vec<HairCommand>)], writer: &mut Out) -> Result<(), E> {
    for (name, filename, defaults, body) in templates {
        writer.write_var_bytes(name.as_bytes())?;
        writer.write_var_bytes(filename.as_bytes())?;
        writer.write_var_bytes(defaults.get())?;
        write_with_header(writer, |writer,body_length| {
            writer.write_var_u64(body_length as u64)
        }, |writer| {
            ast_to_binary(body, writer)
        })?;
    }
    Ok(())
}

fn templates_to_binary_size(templates: &[(&str, &str, ValueRef, Vec<HairCommand>)]) -> usize {
    let mut length_collector = RawWriterLength::new();
    templates_to_binary(templates, &mut length_collector).unwrap_infallible();
    length_collector.length()
}

fn ast_to_binary_size(ast: &[HairCommand]) -> usize {
    let mut length_collector = RawWriterLength::new();
    ast_to_binary(ast, &mut length_collector).unwrap_infallible();
    length_collector.length()
}

enum HairBytecode {
    Return = 0,
    Text = 1,
    Evaluate = 2,
    Loop = 4,
    Conditional = 5,
    CallStatic = 6,
    CallDynamicName = 7,
    CallDynamicBody = 8,
}

fn ast_to_binary<E, Out: RawOutput<E>>(ast: &[HairCommand], writer: &mut Out) -> Result<(), E> {
    for cmd in ast {
        match cmd {
            HairCommand::Text(text) => {
                writer.write_u8(HairBytecode::Text as u8)?;
                writer.write_var_bytes(text.as_bytes())?;
            },
            HairCommand::Conditional(expr, body, else_body, source_context) => {
                writer.write_u8(HairBytecode::Conditional as u8)?;
                writer.write_var_u64(source_context.0 as u64)?;
                writer.write_var_u64(source_context.1 as u64)?;
                writer.write_var_bytes(expr.get())?;
                write_with_header(writer, |writer,length| writer.write_var_u64(length), |writer| ast_to_binary(body, writer))?;
                write_with_header(writer, |writer,length| writer.write_var_u64(length), |writer| ast_to_binary(else_body, writer))?;
            },
            HairCommand::Loop(expr, index_variable, content_variable, body, source_context) => {
                writer.write_u8(HairBytecode::Loop as u8)?;
                writer.write_var_u64(source_context.0 as u64)?;
                writer.write_var_u64(source_context.1 as u64)?;
                writer.write_var_bytes(expr.get())?;
                writer.write_var_bytes(index_variable.as_bytes())?;
                writer.write_var_bytes(content_variable.as_bytes())?;
                write_with_header(writer, |writer,length| writer.write_var_u64(length), |writer| ast_to_binary(body, writer))?;
            },
            HairCommand::Eval(expr, escape_mode, source_context) => {
                writer.write_u8(HairBytecode::Evaluate as u8)?;
                writer.write_var_u64(source_context.0 as u64)?;
                writer.write_var_u64(source_context.1 as u64)?;
                writer.write_var_bytes(expr.get())?;
                writer.write_var_bytes(escape_mode)?;
            },
            HairCommand::CallTemplate(name, expr, source_context) => {
                match name {
                    ResolveTemplate::Static(_) => writer.write_u8(HairBytecode::CallStatic as u8)?,
                    ResolveTemplate::DynamicName(_) => writer.write_u8(HairBytecode::CallDynamicName as u8)?,
                    ResolveTemplate::DynamicBody(_) => writer.write_u8(HairBytecode::CallDynamicBody as u8)?,
                }
                writer.write_var_u64(source_context.0 as u64)?;
                writer.write_var_u64(source_context.1 as u64)?;
                match name {
                    ResolveTemplate::Static(name) => writer.write_var_bytes(name.as_bytes())?,
                    ResolveTemplate::DynamicName(expr) => writer.write_var_bytes(expr.get())?,
                    ResolveTemplate::DynamicBody(expr) => writer.write_var_bytes(expr.get())?,
                }
                writer.write_var_bytes(expr.get())?;
            },
        }
    }
    Ok(())
}

#[derive(Debug)]
pub enum HairEvalError<'a> {
    Bytecode(&'a str),
    Evaluate(&'a str),
    Error(&'a str),
    EvalTooLong(), // takes too long, probably recusion depth hit
    TemplateNotFound(&'a [u8]),
}

impl<'a> From<EncodingError> for HairEvalError<'a> {
    fn from(_: EncodingError) -> Self {
        HairEvalError::Error("hair template bytecode error")
    }
}
struct Context<'a,'b> {
    custom: &'a mut dyn CustomFuncs,
    templates: Vec<RawReader<'b>>,
    template_name: &'b [u8],
    escaper: &'a mut dyn Escaper<'b>,
}

pub trait Escaper<'e> {
    #[allow(clippy::ptr_arg)]
    fn append_to_output<'b,'c,'d>(&mut self, value: DecodedValue<'b>, escape_mode: &'b [u8], allocator: &mut MemoryScope<'c>, output: &mut Vec<&'d [u8]>) -> Result<(),HairEvalError<'d>> where 'c: 'd, 'b: 'd, 'e: 'b;
}

/// Default escaper. Defaults to escaping in `html` mode. Currently supports `html`, `url`, and `none`
/// (throws error on other escape modes).
pub struct DefaultEscaper<'e> {
    default_escape_mode: &'e [u8],
}

impl<'e> DefaultEscaper<'e> {
    pub fn new(default_escape_mode: &'e [u8]) -> Self { Self { default_escape_mode } }

    pub fn default() -> Self { Self { default_escape_mode: b"",  } }
}

impl<'e> Escaper<'e> for DefaultEscaper<'e> {
    fn append_to_output<'b,'c,'d>(&mut self, value: DecodedValue<'b>, mut escape_mode: &'b [u8], allocator: &mut MemoryScope<'c>, output: &mut Vec<&'d [u8]>) -> Result<(),HairEvalError<'d>> where 'c: 'd, 'b: 'd, 'e: 'b {
        if escape_mode.is_empty() {
            escape_mode = self.default_escape_mode;
        }
        if escape_mode == b"js" {
            if !value.is_valid_json() {
                return Err(HairEvalError::Error("UTF-8 problem in js mode: maybe non-text is outputted in a key or a string?"));
            }
            output.push(write!(allocator, "{}", value).as_bytes());
            return Ok(());
        }
        if escape_mode == b"sjs" {
            if !value.is_valid_json() {
                return Err(HairEvalError::Error("UTF-8 problem in js mode: maybe non-text is outputted in a key or a string?"));
            }
            let json = write!(allocator, "{}", value).as_bytes();
            output.push(allocator.copy_with_replacement(json, html_escape_script_u8)?);
            return Ok(());
        }
        match value {
            DecodedValue::Null() => Ok(()),
            DecodedValue::Int(i) => {
                output.push(write!(allocator, "{}", i).as_bytes());
                Ok(())
            },
            DecodedValue::Float(f) => {
                // The output is improved for humans. It forces to convert 0.99999998f to 1.0
                let mut out = if escape_mode == b"unrounded" { write!(allocator, "{}", f) } else { write!(allocator, "{:.6}", f) };
                // strip of zero's of the end
                out = &out[0..out.rfind(|x| x != '0').map_or(out.len(), |x| if out.as_bytes()[x] == b'.' { x+2 } else { x+1 })];
                output.push(out.as_bytes());
                Ok(())
            },
            DecodedValue::Double(d) => {
                // The output is improved for humans. It forces to convert 0.999999999999996 to 1.0
                let mut out = if escape_mode == b"unrounded" { write!(allocator, "{}", d) } else { write!(allocator, "{:.14}", d) };
                // strip of zero's of the end
                out = &out[0..out.rfind(|x| x != '0').map_or(out.len(), |x| if out.as_bytes()[x] == b'.' { x+2 } else { x+1 })];
                output.push(out.as_bytes());
                Ok(())
            },
            DecodedValue::String(s) => {
                if escape_mode == b"html" {
                    output.push(allocator.copy_with_replacement(s, html_escape_u8)?);
                } else if escape_mode == b"url" {
                    output.push(allocator.copy_with_dynamic_replacement(s, url_escape_u8)?);
                } else if escape_mode == b"none" {
                    output.push(s);
                } else {
                    return Err(HairEvalError::Evaluate(write!(allocator, "unsupported escape mode: {}", String::from_utf8_lossy(escape_mode))));
                }
                Ok(())
            },
            _ => Err(HairEvalError::Evaluate("only numbers and strings can be outputted (in regular escape modes)")),
        }
    }
}

fn resolve_template<'a,'b>(name: &'_ [u8], context: &'_ Context<'a,'b>) -> Result<Option<(&'b [u8], BytecodeRef<'b>, ValueRef<'b>)>,EncodingError> {
    //eprintln!("resolve template: {} ({})", String::from_utf8_lossy(name), context.templates.len());
    for reader in context.templates.iter().rev() {
        let mut reader : RawReader = *reader;
        //eprintln!("template {}: {} bytes", i, reader.len());
        while !reader.is_empty() {
            let key = reader.read_var_string()?;
            //eprintln!("key: {}", String::from_utf8_lossy(key));
            let filename = reader.read_var_string()?;
            let default_values = ValueRef(reader.read_var_string()?);
            let bytecode = BytecodeRef(reader.read_var_string()?);
            if key == name {
                return Ok(Some((filename, bytecode, default_values)));
            }
        }
    }
    Ok(None)
}

/// Used for stack traces, to make distinction between call sites.
#[derive(Debug)]
pub enum HairLocationType {
    Conditional,
    Loop,
    Call,
    Eval,
}

/// Used for stack traces, contains the details of a call site.
#[derive(Debug)]
pub struct HairStackEntry<'a> {
  location_type: HairLocationType,
  filename: &'a [u8],
  line_no: u64,
  column_no: u64,
}

/// Hair errors, including a stack trace so debugging is easier.
pub struct HairError<'a> {
    error: HairEvalError<'a>,
    stack: Vec<HairStackEntry<'a>>,
}

impl core::fmt::Display for HairLocationType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HairLocationType::Conditional => write!(f, "cond"),
            HairLocationType::Loop => write!(f, "loop"),
            HairLocationType::Call => write!(f, "call"),
            HairLocationType::Eval => write!(f, "eval"),
        }
    }
}
impl<'a> core::fmt::Display for HairError<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "Hair error: {:?}", self.error)?;
        for loc in &self.stack {
            writeln!(f, "  during {} in {} on line {}:{}", loc.location_type, String::from_utf8_lossy(loc.filename), loc.line_no, loc.column_no+1)?;
        }
        Ok(())
    }
}
impl<'a> fmt::Debug for HairError<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self)
    }
}

impl<'a> HairError<'a> {
    fn wrap(error: HairEvalError<'a>, location_type: HairLocationType, filename: &'a [u8], line_no: u64, column_no: u64) -> Self { Self { error, stack: vec![HairStackEntry {
        location_type,
        filename,
        line_no,
        column_no,
    }]} }

    fn add_location(mut self, location: HairLocationType, filename: &'a [u8], line_no: u64, column_no: u64) -> Self {
        self.stack.push(HairStackEntry{ location_type: location, filename, line_no, column_no });
        self
    }
}
impl<'a> From<EncodingError> for HairError<'a> {
    fn from(e: EncodingError) -> Self {
        Self {
            error: e.into(),
            stack: Vec::new(),
        }
    }
}
impl<'a> From<HairEvalError<'a>> for HairError<'a> {
    fn from(e: HairEvalError<'a>) -> Self {
        Self {
            error: e,
            stack: Vec::new(),
        }
    }
}

fn evaluate_to<'a,'b,'c>(expression: &mut RawReader<'b>, value: ValueRef<'b>, context: &'_ mut Context<'a,'b>, allocator: &mut MemoryScope<'c>, output: &mut Vec<&'b [u8]>, depth: usize) -> Result<(),HairError<'b>> where 'c: 'b, 'b: 'a {
    if depth == 0 {
        return Err(HairEvalError::EvalTooLong().into());
    }
    while !expression.is_empty() {
        let opcode = expression.read_u8().map_err(|_| HairEvalError::Bytecode("Expected more bytes in expression"))?;
        if opcode == HairBytecode::Text as u8 {
            let err = |_| HairEvalError::Bytecode("corrupted TEXT");
            let text_length = expression.read_var_u64().map_err(err)?;
            let text = expression.read_bytes(text_length as usize).map_err(err)?;
            output.push(text);
            continue;
        }
        if opcode == HairBytecode::Evaluate as u8 {
            let err = |_| HairEvalError::Bytecode("corrupted EXPR");
            let line_no = expression.read_var_u64().map_err(err)?;
            let column_no = expression.read_var_u64().map_err(err)?;
            let expr = BytecodeRef(expression.read_var_string().map_err(err)?);
            let escape_mode = expression.read_var_string().map_err(err)?;
            let object = expry_eval_func(expr, value, allocator, context.custom).map_err(|err| HairError::wrap(HairEvalError::Evaluate(write!(allocator, "{}", err)), HairLocationType::Eval, context.template_name, line_no, column_no))?;
            context.escaper.append_to_output(object, escape_mode, allocator, output).map_err(|err| HairError::wrap(err, HairLocationType::Eval, context.template_name, line_no, column_no))?;
            continue;
        }
        if opcode == HairBytecode::Conditional as u8 {
            let err = |_| HairEvalError::Bytecode("corrupted CONDITIONAL");
            let line_no = expression.read_var_u64().map_err(err)?;
            let column_no = expression.read_var_u64().map_err(err)?;
            let expr = BytecodeRef(expression.read_var_string().map_err(err)?);
            let body = expression.read_var_string().map_err(err)?;
            let else_body = expression.read_var_string().map_err(err)?;
            let retval = expry_eval_func(expr, value, allocator, context.custom).map_err(|err| HairError::wrap(HairEvalError::Evaluate(write!(allocator, "{}", err)),HairLocationType::Loop, context.template_name, line_no, column_no))?;
            if let DecodedValue::Bool(true) = retval {
                evaluate_to(&mut RawReader::with(body), value, context, allocator, output, depth-1).map_err(|err| err.add_location(HairLocationType::Loop, context.template_name, line_no, column_no))?;
                continue;
            }
            // `expr???` indicates ignore on error (which produces a null value), so we
            // continue on null.
            if matches!(retval, DecodedValue::Bool(_) | DecodedValue::Null()) {
                if !else_body.is_empty() {
                    evaluate_to(&mut RawReader::with(else_body), value, context, allocator, output, depth-1).map_err(|err| err.add_location(HairLocationType::Loop, context.template_name, line_no, column_no))?;
                }
                continue;
            }
            return Err(HairError::wrap(HairEvalError::Error(write!(allocator, "expression in conditional should result in a bool or null, not {}", retval.type_string())), HairLocationType::Conditional, context.template_name, line_no, column_no));
        }
        if opcode == HairBytecode::Loop as u8 {
            let err = |_| HairEvalError::Bytecode("corrupted LOOP");
            let line_no = expression.read_var_u64().map_err(err)?;
            let column_no = expression.read_var_u64().map_err(err)?;
            let expr = BytecodeRef(expression.read_var_string().map_err(err)?);
            let index_key = expression.read_var_string().map_err(err)?;
            let variable = expression.read_var_string().map_err(err)?;
            let body = expression.read_var_string().map_err(err)?;
            let retval = expry_slice_func(expr, value, allocator, context.custom).map_err(|err| HairError::wrap(HairEvalError::Evaluate(write!(allocator, "{}", err)),HairLocationType::Loop, context.template_name, line_no, column_no))?;
            let parsed = LazyDecodedValue::parse(&mut RawReader::with(retval.get()))?;
            if let LazyDecodedValue::Array(mut array) = parsed {
                let mut index : i64 = 0;
                let index_key = key_u8(index_key);
                while !array.is_empty() {
                    // make a state with the current state with one variable replaced.
                    let iteration_value = array.get_raw()?;

                    //let value_with_variable = expry_object_with_single_field(variable, iteration_value.get())?;
                    let index_value = DecodedValue::Int(index).to_scope(allocator, false);
                    let contents : &mut [(Key<'b>, &'b [u8])];
                    if !index_key.1.is_empty() {
                        contents = allocator.alloc(2);
                        contents[0] = (key_u8(variable), iteration_value.get());
                        contents[1] = (index_key, index_value.get());
                        if contents[0].0.cmp(&contents[1].0) == std::cmp::Ordering::Greater {
                            contents.swap(0, 1);
                        }
                    } else {
                        contents = allocator.alloc(1);
                        contents[0] = (key_u8(variable), iteration_value.get());
                    }
                    let value_with_variable = expry_object_raw(allocator, contents)?;
                    let value_with_variable = ValueRef(value_with_variable);

                    let merged = merge_objects(value_with_variable, value, allocator).map_err(|x| HairError::wrap(x.into(), HairLocationType::Loop, context.template_name, line_no, column_no))?;
                    evaluate_to(&mut RawReader::with(body), merged, context, allocator, output, depth-1).map_err(|err| err.add_location(HairLocationType::Loop, context.template_name, line_no, column_no))?;

                    index += 1;
                }
                continue;
            }
            // added so that `expr???` indicates ignore on error
            if let LazyDecodedValue::Null() = parsed {
                continue;
            }
            return Err(HairError::wrap(HairEvalError::Error(write!(allocator, "expression in loop should result in an array (with any value) or null, not {}", parsed.type_string())), HairLocationType::Loop, context.template_name, line_no, column_no));
        }
        if opcode == HairBytecode::CallDynamicName as u8 || opcode == HairBytecode::CallDynamicBody as u8 || opcode == HairBytecode::CallStatic as u8 {
            let err = |_| HairEvalError::Bytecode("corrupted LOOP");
            let line_no = expression.read_var_u64().map_err(err)?;
            let column_no = expression.read_var_u64().map_err(err)?;
            let mut name = expression.read_var_string().map_err(err)?;
            let expr = BytecodeRef(expression.read_var_string().map_err(err)?);
            let (template_name, template_bytecode, template_defaults);
            let mut templates = context.templates.clone();
            if opcode == HairBytecode::CallDynamicName as u8 {
                let name_value = expry_eval_func(BytecodeRef(name), value, allocator, context.custom).map_err(|err| HairError::wrap(HairEvalError::Evaluate(write!(allocator, "{}", err)), HairLocationType::Call, context.template_name, line_no, column_no))?;
                if let DecodedValue::String(name_string) = name_value {
                    name = name_string;
                } else if let DecodedValue::Null() = name_value {
                    return Ok(());
                } else {
                    return Err(HairError::wrap(HairEvalError::Error(write!(allocator, "expression in dynamic name template call should resolve to a string (or null), not {}", name_value.type_string())), HairLocationType::Call, context.template_name, line_no, column_no));
                }
                let result = match resolve_template(name, context)? {
                    None => {
                        return Err(HairError::wrap(HairEvalError::TemplateNotFound(name),HairLocationType::Call, context.template_name, line_no, column_no));
                    },
                    Some(values) => values,
                };
                template_name = result.0;
                template_bytecode = result.1;
                template_defaults = result.2;
                //eprintln!("call dynamic template {} with {} bytes", String::from_utf8_lossy(name), template_bytecode.0.len());
            } else if opcode == HairBytecode::CallDynamicBody as u8 {
                let hairy_template;
                let value = expry_eval_func(BytecodeRef(name), value, allocator, context.custom).map_err(|err| HairError::wrap(HairEvalError::Evaluate(write!(allocator, "{}", err)), HairLocationType::Call, context.template_name, line_no, column_no))?;
                if let DecodedValue::String(contents) = value {
                    hairy_template = contents;
                } else if let DecodedValue::Null() = value {
                    return Ok(());
                } else {
                    return Err(HairError::wrap(HairEvalError::Error(write!(allocator, "expression in dynamic body template call should resolve to a string (or null), not {}", value.type_string())), HairLocationType::Call, context.template_name, line_no, column_no));
                }
                let result = decode_hair(hairy_template)?;
                template_name = result.0;
                template_bytecode = result.1;
                let template_templates = result.2;
                template_defaults = result.3;
                templates.push(RawReader::with(template_templates));
                //eprintln!("call dynamic bytecode with {} bytes and defaults of {} bytes", template_bytecode.0.len(), template_defaults.0.len());
            } else if opcode == HairBytecode::CallStatic as u8 {
                let result = match resolve_template(name, context)? {
                    None => {
                        return Err(HairError::wrap(HairEvalError::TemplateNotFound(name),HairLocationType::Call, context.template_name, line_no, column_no));
                    },
                    Some(values) => values,
                };
                template_name = result.0;
                template_bytecode = result.1;
                template_defaults = result.2;
                //eprintln!("call static template '{}' (of '{}'), with template defaults of {} bytes, and body of {} bytes", String::from_utf8_lossy(name), String::from_utf8_lossy(template_name), template_defaults.0.len(), template_bytecode.0.len());
            } else {
                return Err(HairError::wrap(HairEvalError::Error("unrecognized opcode in template bytecode"),HairLocationType::Call, context.template_name, line_no, column_no));
            }
            if !expr.is_empty() {
                let mut retval = expry_slice_func(expr, value, allocator, context.custom).map_err(|err| HairError::wrap(HairEvalError::Evaluate(write!(allocator, "{}", err)), HairLocationType::Call, context.template_name, line_no, column_no))?;
                let type_and_length = RawReader::with(retval.get()).read_var_u64()?;
                if DecodedValue::type_of_binary(type_and_length) == ValueType::Null as u8 {
                    continue;
                }
                if DecodedValue::type_of_binary(type_and_length) != ValueType::Object as u8 {
                    return Err(HairError::wrap(HairEvalError::Bytecode(write!(allocator, "Hair: calling template '{}' should be with an object (or null to skip, type={})", String::from_utf8_lossy(name), DecodedValue::decoded_type_of(type_and_length).map_or("unknown", |x| x.type_string()))), HairLocationType::Call, context.template_name, line_no, column_no));
                }
                if !template_defaults.is_empty() {
                    retval = merge_objects(retval, template_defaults, allocator)?;
                }
                let mut context2 = Context { templates, template_name, custom: context.custom, escaper: context.escaper, };
                evaluate_to(&mut RawReader::with(template_bytecode.get()), retval, &mut context2, allocator, output, depth-1).map_err(|err| err.add_location(HairLocationType::Call, context.template_name, line_no, column_no))?;
                //eprintln!("end call template {} with {} bytes", String::from_utf8_lossy(template_name), template_bytecode.0.len());
                continue;
            } else {
                let merged = if !template_defaults.is_empty() {
                    merge_objects(value, template_defaults, allocator)?
                } else {
                    value
                };
                let mut context2 = Context { templates, template_name, custom: context.custom, escaper: context.escaper, };
                evaluate_to(&mut RawReader::with(template_bytecode.get()), merged, &mut context2, allocator, output, depth-1).map_err(|err| err.add_location(HairLocationType::Call, context.template_name, line_no, column_no))?;
                //eprintln!("end call template {} with {} bytes", String::from_utf8_lossy(template_name), template_bytecode.0.len());
                continue;
            }
        }
        return Err(HairEvalError::Bytecode(write!(allocator, "unrecognized opcode {}", opcode)).into());
    }
    Ok(())
}

/// Evaluate Hair bytecode to generate output, using a `value` encoded as a [`expry`] object.
pub fn hairy_eval<'a,'b,'c>(template_bytecode: BytecodeRef<'b>, mut value: ValueRef<'b>, allocator: &'b mut MemoryScope<'c>, mut option_custom: Option<&mut dyn CustomFuncs>, given_templates: &[RawReader<'b>], mut option_escaper: Option<&mut dyn Escaper<'b>>) -> Result<Vec<&'b [u8]>, HairError<'b>> where 'c: 'b, 'b: 'a {
    let mut escaper : &mut dyn Escaper<'b> = &mut DefaultEscaper::new(b"html");
    if let Some(f) = &mut option_escaper {
        escaper = *f;
    }
    let mut custom : &mut dyn CustomFuncs = &mut NoCustomFuncs{};
    if let Some(f) = &mut option_custom {
        custom = *f;
    }
    // start with empty object if no value is given
    if value.is_empty() {
        value = ValueRef(EMPTY_EXPRY_OBJECT);
    }
    let (template_name, template_bytecode, new_templates, defaults) = decode_hair(template_bytecode.get())?;

    let mut templates = Vec::with_capacity(given_templates.len() + 1);
    templates.extend_from_slice(given_templates);
    templates.push(RawReader::with(new_templates));

    let merged = merge_objects(value, defaults, allocator)?;
    let mut output : Vec<&'b [u8]> = Vec::with_capacity(128);
    let mut context = Context { templates, template_name, custom, escaper };
    let mut bytecode_reader = RawReader::with(template_bytecode.get());
    evaluate_to(&mut bytecode_reader, merged, &mut context, allocator, &mut output, 255)?;
    Ok(output)
}

/// The 'easy' interface if you just want to quickly use a HTML template, with auto escaping of the
/// input, and returning a nicely formatted error that can be presented to the user. For more
/// options, see the [`hairy_eval`] function.
///
/// To compile, use [`hairy_compile_html`], so the proper escaper is used.
///
/// Note that although `hairy_compile_html` and `hairy_eval_html` are easier to use, they are
/// somewhat slower. For top performance please use other functions.
///
/// Another easy function is [`hairy_eval_html_custom`] to expose custom functions (like translation
/// functions).
pub fn hairy_eval_html(template_bytecode: BytecodeRef<'_>, value: ValueRef<'_>) -> Result<Vec<u8>, String> {
    let mut allocator = MemoryPool::new();
    let mut scope = allocator.rewind();
    let result = hairy_eval(template_bytecode, value, &mut scope, None, &[], Some(&mut DefaultEscaper::new(b"html")));
    match result {
        Ok(result) => Ok(result.concat()),
        Err(err) => Err(format!("{}", err)),
    }
}

/// The 'easy' interface (with custom functions) if you just want to quickly use a HTML template, with auto escaping of the
/// input, and returning a nicely formatted error that can be presented to the user. For more
/// options, see the [`hairy_eval`] function.
///
/// To compile, use [`hairy_compile_html`], so the proper escaper is used.
///
/// Note that although `hairy_compile_html` and `hairy_eval_html` are easier to use, they are
/// somewhat slower. For top performance please use other functions.
pub fn hairy_eval_html_custom<'b>(template_bytecode: BytecodeRef<'b>, value: ValueRef<'b>, custom: &mut dyn CustomFuncs) -> Result<Vec<u8>, String> {
    let mut allocator = MemoryPool::new();
    let mut scope = allocator.rewind();
    let result = hairy_eval(template_bytecode, value, &mut scope, Some(custom), &[], Some(&mut DefaultEscaper::new(b"html")));
    match result {
        Ok(result) => Ok(result.concat()),
        Err(err) => Err(format!("{}", err)),
    }
}

fn decode_hair(template_bytecode: &[u8]) -> Result<(&[u8], BytecodeRef, &[u8], ValueRef), HairError> {
    let mut template_bytecode_reader = RawReader::with(template_bytecode);

    let header = template_bytecode_reader.read_bytes(4)?;
    if header != b"hair" {
        return Err(HairEvalError::Bytecode("expression is missing magic header ('hair')").into());
    }

    let template_name = template_bytecode_reader.read_var_string()?;

    let bytecode = template_bytecode_reader.read_var_string()?;
    let templates = template_bytecode_reader.read_var_string()?;
    let mut defaults = ValueRef(template_bytecode_reader.read_var_string()?);
    if defaults.is_empty() {
        defaults = ValueRef(b"\x06");
    }
    Ok((template_name, BytecodeRef(bytecode), templates, defaults))
}

#[cfg(test)]
mod hair {
    use std::io::Write;

    use crate::*;

    pub struct TestCustomFuncs {
    }

    impl CustomFuncs for TestCustomFuncs {
        fn call<'b,'c>(&'_ mut self, name: &'_ str, _args: &'_ [DecodedValue<'b>], scope: &'_ mut MemoryScope<'c>) -> Result<DecodedValue<'b>,&'b str> where 'c: 'b {
            if "func" == name {
                Ok(DecodedValue::String(scope.copy_u8("dyncustomfoo".as_bytes())))
            } else {
                Err("no custom functions defined except for 'func'")
            }
            //Ok(Binary::String(scope.copy(name.key)))
        }
    }

    #[test]
    fn test_escape() {
        let template = r#"foobar = \{{=foovar .. barvar}}"#;
        let result = hairy_compile_html(template, "test.tpl", None, 0);
        match result {
            Ok(parsed) => {
                let value = value!({
                    "foovar": "foo",
                    "barvar": "bar",
                }).to_vec(false);
                match hairy_eval_html(parsed.to_ref(), value.to_ref()) {
                    Ok(output) => {
                        assert_eq!(br#"foobar = {{=foovar .. barvar}}"#, &output[..]);
                    },
                    Err(err) => { eprintln!("{}", err); },
                }
            },
            Err(err) => {
                eprintln!("{}", err);
            }
        }
    }

    #[test]
    fn example_html_interface() {
        let template = r#"foobar = {{=foovar .. barvar}}"#;
        let result = hairy_compile_html(template, "test.tpl", None, 0);
        match result {
            Ok(parsed) => {
                let value = value!({
                    "foovar": "foo",
                    "barvar": "bar",
                }).to_vec(false);
                match hairy_eval_html(parsed.to_ref(), value.to_ref()) {
                    Ok(output) => {
                        assert_eq!(b"foobar = foobar", &output[..]);
                    },
                    Err(err) => { eprintln!("{}", err); },
                }
            },
            Err(err) => {
                eprintln!("{}", err);
            }
        }
    }

    struct Foo {
        foo: u32,
        bar: bool,
    }


    impl<'a> From<&'a Foo> for DecodedValue<'a> {
        fn from(v: &'a Foo) -> Self {
            value!({
                "foo": v.foo as i64,
                "bar": v.bar,
            })
        }
    }

    #[test]
    fn example_nesting() {
        let arr = [1,2,3];
        let globals = value!({
          "$sitetitle": "foooooobaaaar",
          "$arr": arr,
        });
        let main_template = r#"<html><title>{{=$sitetitle}}: {{=pagetitle}}</title><body>{{call **bodytemplate with {...this, ...body}}}</body></html>"#;
        let main = hairy_compile_html(main_template, "main.tpl", Some(&globals), 0);
        if let Err(main) = &main {
            eprintln!("{}", main);
        }
        let main = main.unwrap();
        let child_template = r#"<p>title of this page = {{=pagetitle}}</p><p>foobar = {{=foobarvar}}"#;
        let child = hairy_compile_html(child_template, "child.tpl", Some(&globals), 0);
        if let Err(err) = &child {
            println!("{}", err);
        }
        let child = child.unwrap();
        let value = value!({
          "bodytemplate": child,
          "body": {"foobarvar": "foobar"},
          "pagetitle": "my page",
          "foo": Foo{foo:1,bar:true},
        }).to_vec(false);
        assert_eq!("<html><title>foooooobaaaar: my page</title><body><p>title of this page = my page</p><p>foobar = foobar</body></html>", String::from_utf8_lossy(&hairy_eval_html(main.to_ref(), value.to_ref()).unwrap()));
    }

    #[test]
    fn basic() {
        //let hair = r####"foo{{"♥" .. "heart"}}bar -> {{1+2+3}}"####.as_bytes();
        let hair = r####"
Basic: {{="a"}},{{=1+2+3}}

Normally html is auto escaped (to prevent cross-site-scripting attacks):
{{="<p><b>Bold</b></p>"}}

But if you don't want that, you can add a different escape mode:
{{="<p><b>Bold</b></p>":none}}

Because these templates are aimed at humans, floats get rounded. All these expressions result in the output "1.0". Floats are rounded to 6 digits after the decimal seperator, doubles are rounded tot 14 digits after the decimal seperator. Other behaviour can be specified by using a different escaper or different escape modes.
float rounding:  {{=0.9999998f}}
float rounding:  {{=0.99999998f}}
double rounding: {{=0.999999999999996}}
double rounding: {{=1.0}}
float not rounded:  {{=0.9999998f:unrounded}}

Conditional:
\{{if true}}
Show text
\{{else}}
Hidden
\{{end}}

Output:
{{if true}}
Show text
{{else}}
Hidden
{{end}}

Output:
{{if (1/0)???}}
Not shown, because condition triggers an error
{{else}}
Shown because condition triggers an error which is catched with the `???` operator.
{{endif}}

Loop over array:
\{{for i in numbers}}
- \{{=i}}
\{{end}}

Output:
{{for i in numbers}}
- {{=i}}
{{end}}

Loop over array with objects, using an index variable (with `\{{for (index,person) in persons}}`):
{{for (index,person) in persons}}
- {{=index}}={{=person.name}}
{{end}}

Call a template, with a specific context specified after the `&lt;-`. See next example how to define one:
{{call card with {name: "Some card", body: "Explanation over some card."}}}

If the template name is prefixed with one `*`, the template name can be an expression that is evaluated to a template name:
{{call *"CARD".lower() with {name: "Some card", body: "Explanation over some card."}}}

If the template name is prefixed with `**`, the template name can be an expression that is evaluated to template binary code. This is useful to embed templates in one each other. See another example for this.

Define a template. The template can optionally have default values, that are specified after `defaults`. These default values are only evaluated once during compile time (so they do not depend on the context a template is evaluted in).
{{define card defaults {dark: false}}}
<div class="card-{{=dark?"dark":"light"}}">
  <h2>{{=name}}</h2>
  <p>{{=body}}</p>
</div>
{{enddefine}}

        "####;
        //let hair = r####"{{define test}}{{foo}}{{end}}{{test <- {foo:32}}}"####.as_bytes();
        let mut allocator = MemoryPool::new();
        let mut scope = allocator.rewind();
        let mut custom = TestCustomFuncs{};
        let defaults = ValueRef::new();
        let inlines = None;
        let maincode = r#"
<html>
    <title extra="{{=title}}">{{=title}}</title>
    <script>{{=title}}</script>
    <script>var foo = {{=persons:js}};</script>
    <body>
    {{call **content}}
    </body>
</html>"#;
        let main = parse_html(maincode, &mut scope);
        if let Err(err) = &main {
            println!("{}", hairy_compile_error_format(maincode, err, 0));
        }
        let main = hairy_compile(maincode, "main.tpl", inlines, defaults, &mut scope, Some(&mut custom), Some(main.unwrap()));
        if let Err(err) = &main {
            println!("{}", hairy_compile_error_format(maincode, err, 0));
        }
        let main = main.unwrap();
        let escaping = parse_html(hair, &mut scope);
        if let Err(err) = &escaping {
            println!("{}", hairy_compile_error_format(hair, err, 0));
        }
        let escaping = escaping.unwrap();
        let test = hairy_compile(hair, "test.tpl", inlines, defaults, &mut scope, Some(&mut custom), Some(escaping));
        if let Err(err) = &test {
            println!("{}", hairy_compile_error_format(hair, err, 0));
        }
        let test = test.unwrap();
        let value = value!({
            "title": "My title<script>",
            "content": test,
            "numbers": [1,2,3,4],
            "persons": [{"name": "Andrew"},{"name": "Bart"},{"name": "Casper"}],
        }).to_scope(&mut scope, false);
        if false {
            for _ in 0..16 {
                let before = std::time::Instant::now();
                let count = 4*16384;
                for _ in 0..count {
                    let mut scope = scope.rewind();
                    let escaping = parse_html(hair, &mut scope);
                    if let Err(err) = &escaping {
                        println!("{}", hairy_compile_error_format(hair, err, 0));
                    }
                    let escaping = escaping.unwrap();
                    let test = hairy_compile(hair, "test.tpl", inlines, defaults, &mut scope, Some(&mut custom), Some(escaping));
                    if let Err(err) = &test {
                        println!("{}", hairy_compile_error_format(hair, err, 0));
                    }
                    let test = test.unwrap();
                    let value = value!({
                        "title": "My title<script>",
                        "content": test,
                        "numbers": [1,2,3,4],
                        "persons": [{"name": "Andrew"},{"name": "Bart"},{"name": "Casper"}],
                    }).to_scope(&mut scope, false);
                    let output = hairy_eval(main.to_ref(), value, &mut scope, Some(&mut custom), &[], Some(&mut DefaultEscaper::new(b"html"))).unwrap();
                    assert!(!output.is_empty());
                }
                let after = std::time::Instant::now();
                let dur = after - before;
                eprintln!("{}x in {} ms", count, dur.as_millis());
            }
        } else {
            let output = hairy_eval(main.to_ref(), value, &mut scope, Some(&mut custom), &[], Some(&mut DefaultEscaper::new(b"html")));
            //let output = HairEvaluator::new().custom_functions(&mut custom).eval(main.to_ref(), value.to_ref(), &mut scope);
            let output = output.unwrap();
            for c in output {
                print!("{}", std::str::from_utf8(c).unwrap());
            }
            println!();
            //assert!(false);
        }
    }
    use expry_macros::*;
    #[test]
    fn compile_time_expr() {
        let compiled = expry!("2+3");
        assert_eq!(compiled.get().len(), 3);
        let mut allocator = MemoryPool::new();
        let mut scope = allocator.rewind();
        let result = expry_eval(compiled, ValueRef::new(), &mut scope);
        let result = result.unwrap();
        assert_eq!(result, value!(5));
    }

    #[test]
    fn embedded() {
        let main_template = r#"<html><title>{{=title}}</title><body>{{call **body with {title,foobarvar}}}</body></html>"#;
        let main = hairy_compile_html(main_template, "main.tpl", None, 0).unwrap();
        let child_template = r#"<p>title of this page = {{=title}}</p><p>foobar = {{=foobarvar}}"#;
        let child = hairy_compile_html(child_template, "child.tpl", None, 0).unwrap();
        let value = value!({
            "body": child,
            "foobarvar": "foobar",
            "title": "my title",
        }).to_vec(false);
        match hairy_eval_html(main.to_ref(), value.to_ref()) {
            Ok(output) => { std::io::stdout().write_all(&output).unwrap(); },
            Err(err) => {
                eprintln!("{}", err);
                assert!(false);
            },
        }
    }

    #[test]
    fn inline_script() {
        let template = r#"inline $sitetitle: true ? "t" : "f"
default foo: 42
inline foo: 43
<html><title>{{=$sitetitle}}: title</title><body><script>
    document.innerHTML = '<button>Open in App</button>';
</script></body></html>
<!-- <foo {{=title}}> -->
<{{=title}}>
{{=foo}}
"#;
        let mut allocator = MemoryPool::new();
        let mut scope = allocator.rewind();
        let parsed = parse_html(template, &mut scope);
        if let Err(msg) = &parsed {
            println!("error: {}", msg);
        }

        let result = hairy_compile_html(template, "test.tpl", None, 0);
        if let Err(msg) = &result {
            println!("error: {}", msg);
        }
        let main = result.unwrap();
        let value = value!({"title": "<b>title</b>", "foo": 123}).to_vec(false);
        println!("{}", String::from_utf8_lossy(&hairy_eval_html(main.to_ref(), value.to_ref()).unwrap()));
    }

    #[test]
    fn inline_script2() {
        let template_works = r#"<html><title>title</title><body>
      {{if true}}
    Show text
    {{else}}

    {{end}}
        </body></html>1"#;
        let result = hairy_compile_html(template_works, "test.tpl", None, 0);
        if let Err(msg) = &result {
            println!("{}", msg);
        }
        result.unwrap();

        let template2 = r#"<html><title>title</title><body>
      {{if true}}
        Show text
        {{else}}
        {{end}}
        </body></html>2"#;
        let result = hairy_compile_html(template2, "test.tpl", None, 0);
        if let Err(msg) = &result {
            println!("{}", msg);
        }
        result.unwrap();

        let template3 = r#"<html><title>title</title><body>
      {{if true}}
        Show text
       {{end}}
        </body></html>3"#;
        let result = hairy_compile_html(template3, "test.tpl", None, 0);
        if let Err(msg) = &result {
            println!("{}", msg);
        }
        result.unwrap();
    }

    pub struct TranslateFuncs {
        map: std::collections::HashMap<String,String>,
    }

    impl CustomFuncs for TranslateFuncs {
        fn call<'b,'c>(&mut self, name: &'_ str, args: &'_ [DecodedValue<'b>], scope: &'_ mut MemoryScope<'c>) -> Result<DecodedValue<'b>,&'b str> where 'c: 'b {
            if name == "tr" {
                if let (Some(DecodedValue::String(key)), Some(DecodedValue::String(default))) = (args.get(0), args.get(1)) {
                    let key = core::str::from_utf8(key);
                    if let Ok(key) = key {
                        if let Some(translated) = self.map.get(key) {
                            Ok(DecodedValue::String(scope.copy_u8(translated.as_bytes())))
                        } else {
                            Ok(DecodedValue::String(default))
                        }
                    } else {
                        Err("tr(key, default) with invalid UTF-8 as key")
                    }
                } else {
                    Err("tr(key, default) expected")
                }
            } else {
                Err("no custom functions defined except for 'func'")
            }
        }
    }

    pub struct FallbackTranslationsFuncs {
    }

    impl CustomFuncs for FallbackTranslationsFuncs {
        fn call<'b,'c>(&mut self, name: &'_ str, args: &'_ [DecodedValue<'b>], _scope: &'_ mut MemoryScope<'c>) -> Result<DecodedValue<'b>,&'b str> where 'c: 'b {
            if name == "tr" {
                if let (_, Some(DecodedValue::String(default))) = (args.get(0), args.get(1)) {
                    Ok(DecodedValue::String(default))
                } else {
                    Err("tr(key, default) expected")
                }
            } else {
                Err("no custom functions defined except for 'func'")
            }
        }
    }

    #[test]
    pub fn translations() {
        let mut map = std::collections::HashMap::new();
        map.insert("hello".to_string(), "Hallo.".to_string());
        map.insert("welcome-text".to_string(), "Welkom op onze site, fijn dat je ons virtueel bezoekt.".to_string());
        let mut translate_to_nl = TranslateFuncs { map, };
        let template = r#"
<h1>{{=tr("hello", "Hello.")}}</h1>
<p>{{=tr("welcome-text", "Welcome to our site. We are glad that you are here.")}}</p>
"#;
        let result = hairy_compile_html(template, "test.tpl", None, 0);
        if let Err(msg) = &result {
            println!("error: {}", msg);
        }
        let main = result.unwrap();
        let value = value!({}).to_vec(false);
        let output = hairy_eval_html_custom(main.to_ref(), value.to_ref(), &mut translate_to_nl);
        if let Err(msg) = &output {
            println!("error: {}", msg);
        }
        let output = output.unwrap();
        //eprintln!("{}", String::from_utf8_lossy(&output));
        assert_eq!(r#"
<h1>Hallo.</h1>
<p>Welkom op onze site, fijn dat je ons virtueel bezoekt.</p>
"#.as_bytes(), output);

        let mut translate_to_defaults = FallbackTranslationsFuncs{};
        let output = hairy_eval_html_custom(main.to_ref(), value.to_ref(), &mut translate_to_defaults);
        if let Err(msg) = &output {
            println!("error: {}", msg);
        }
        let output = output.unwrap();
        //eprintln!("{}", String::from_utf8_lossy(&output));
        assert_eq!(r#"
<h1>Hello.</h1>
<p>Welcome to our site. We are glad that you are here.</p>
"#.as_bytes(), output);
    }
}