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
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
// Copyright 2020-2023 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::collections::HashMap;

use itertools::Itertools as _;
use jj_lib::backend::{Signature, Timestamp};
use jj_lib::dsl_util::AliasExpandError as _;

use crate::template_parser::{
    self, BinaryOp, ExpressionKind, ExpressionNode, FunctionCallNode, TemplateAliasesMap,
    TemplateParseError, TemplateParseErrorKind, TemplateParseResult, UnaryOp,
};
use crate::templater::{
    CoalesceTemplate, ConcatTemplate, ConditionalTemplate, LabelTemplate, ListPropertyTemplate,
    ListTemplate, Literal, PlainTextFormattedProperty, PropertyPlaceholder, ReformatTemplate,
    SeparateTemplate, SizeHint, Template, TemplateProperty, TemplatePropertyError,
    TemplatePropertyExt as _, TemplateRenderer, TimestampRange,
};
use crate::{text_util, time_util};

/// Callbacks to build language-specific evaluation objects from AST nodes.
pub trait TemplateLanguage<'a> {
    type Property: IntoTemplateProperty<'a>;

    fn wrap_string(property: impl TemplateProperty<Output = String> + 'a) -> Self::Property;
    fn wrap_string_list(
        property: impl TemplateProperty<Output = Vec<String>> + 'a,
    ) -> Self::Property;
    fn wrap_boolean(property: impl TemplateProperty<Output = bool> + 'a) -> Self::Property;
    fn wrap_integer(property: impl TemplateProperty<Output = i64> + 'a) -> Self::Property;
    fn wrap_integer_opt(
        property: impl TemplateProperty<Output = Option<i64>> + 'a,
    ) -> Self::Property;
    fn wrap_signature(property: impl TemplateProperty<Output = Signature> + 'a) -> Self::Property;
    fn wrap_size_hint(property: impl TemplateProperty<Output = SizeHint> + 'a) -> Self::Property;
    fn wrap_timestamp(property: impl TemplateProperty<Output = Timestamp> + 'a) -> Self::Property;
    fn wrap_timestamp_range(
        property: impl TemplateProperty<Output = TimestampRange> + 'a,
    ) -> Self::Property;

    fn wrap_template(template: Box<dyn Template + 'a>) -> Self::Property;
    fn wrap_list_template(template: Box<dyn ListTemplate + 'a>) -> Self::Property;

    /// Translates the given global `function` call to a property.
    ///
    /// This should be delegated to
    /// `CoreTemplateBuildFnTable::build_function()`.
    fn build_function(
        &self,
        build_ctx: &BuildContext<Self::Property>,
        function: &FunctionCallNode,
    ) -> TemplateParseResult<Self::Property>;

    fn build_method(
        &self,
        build_ctx: &BuildContext<Self::Property>,
        property: Self::Property,
        function: &FunctionCallNode,
    ) -> TemplateParseResult<Self::Property>;
}

/// Implements `TemplateLanguage::wrap_<type>()` functions.
///
/// - `impl_core_wrap_property_fns('a)` for `CoreTemplatePropertyKind`,
/// - `impl_core_wrap_property_fns('a, MyKind::Core)` for `MyKind::Core(..)`.
macro_rules! impl_core_wrap_property_fns {
    ($a:lifetime) => {
        $crate::template_builder::impl_core_wrap_property_fns!($a, std::convert::identity);
    };
    ($a:lifetime, $outer:path) => {
        $crate::template_builder::impl_wrap_property_fns!(
            $a, $crate::template_builder::CoreTemplatePropertyKind, $outer, {
                wrap_string(String) => String,
                wrap_string_list(Vec<String>) => StringList,
                wrap_boolean(bool) => Boolean,
                wrap_integer(i64) => Integer,
                wrap_integer_opt(Option<i64>) => IntegerOpt,
                wrap_signature(jj_lib::backend::Signature) => Signature,
                wrap_size_hint($crate::templater::SizeHint) => SizeHint,
                wrap_timestamp(jj_lib::backend::Timestamp) => Timestamp,
                wrap_timestamp_range($crate::templater::TimestampRange) => TimestampRange,
            }
        );
        fn wrap_template(
            template: Box<dyn $crate::templater::Template + $a>,
        ) -> Self::Property {
            use $crate::template_builder::CoreTemplatePropertyKind as Kind;
            $outer(Kind::Template(template))
        }
        fn wrap_list_template(
            template: Box<dyn $crate::templater::ListTemplate + $a>,
        ) -> Self::Property {
            use $crate::template_builder::CoreTemplatePropertyKind as Kind;
            $outer(Kind::ListTemplate(template))
        }
    };
}

macro_rules! impl_wrap_property_fns {
    ($a:lifetime, $kind:path, $outer:path, { $( $func:ident($ty:ty) => $var:ident, )+ }) => {
        $(
            fn $func(
                property: impl $crate::templater::TemplateProperty<Output = $ty> + $a,
            ) -> Self::Property {
                use $kind as Kind; // https://github.com/rust-lang/rust/issues/48067
                $outer(Kind::$var(Box::new(property)))
            }
        )+
    };
}

pub(crate) use {impl_core_wrap_property_fns, impl_wrap_property_fns};

/// Provides access to basic template property types.
pub trait IntoTemplateProperty<'a> {
    /// Type name of the property output.
    fn type_name(&self) -> &'static str;

    fn try_into_boolean(self) -> Option<Box<dyn TemplateProperty<Output = bool> + 'a>>;
    fn try_into_integer(self) -> Option<Box<dyn TemplateProperty<Output = i64> + 'a>>;

    fn try_into_plain_text(self) -> Option<Box<dyn TemplateProperty<Output = String> + 'a>>;
    fn try_into_template(self) -> Option<Box<dyn Template + 'a>>;
}

pub enum CoreTemplatePropertyKind<'a> {
    String(Box<dyn TemplateProperty<Output = String> + 'a>),
    StringList(Box<dyn TemplateProperty<Output = Vec<String>> + 'a>),
    Boolean(Box<dyn TemplateProperty<Output = bool> + 'a>),
    Integer(Box<dyn TemplateProperty<Output = i64> + 'a>),
    IntegerOpt(Box<dyn TemplateProperty<Output = Option<i64>> + 'a>),
    Signature(Box<dyn TemplateProperty<Output = Signature> + 'a>),
    SizeHint(Box<dyn TemplateProperty<Output = SizeHint> + 'a>),
    Timestamp(Box<dyn TemplateProperty<Output = Timestamp> + 'a>),
    TimestampRange(Box<dyn TemplateProperty<Output = TimestampRange> + 'a>),

    // Both TemplateProperty and Template can represent a value to be evaluated
    // dynamically, which suggests that `Box<dyn Template + 'a>` could be
    // composed as `Box<dyn TemplateProperty<Output = Box<dyn Template ..`.
    // However, there's a subtle difference: TemplateProperty is strict on
    // error, whereas Template is usually lax and prints an error inline. If
    // `concat(x, y)` were a property returning Template, and if `y` failed to
    // evaluate, the whole expression would fail. In this example, a partial
    // evaluation output is more useful. That's one reason why Template isn't
    // wrapped in a TemplateProperty. Another reason is that the outermost
    // caller expects a Template, not a TemplateProperty of Template output.
    Template(Box<dyn Template + 'a>),
    ListTemplate(Box<dyn ListTemplate + 'a>),
}

impl<'a> IntoTemplateProperty<'a> for CoreTemplatePropertyKind<'a> {
    fn type_name(&self) -> &'static str {
        match self {
            CoreTemplatePropertyKind::String(_) => "String",
            CoreTemplatePropertyKind::StringList(_) => "List<String>",
            CoreTemplatePropertyKind::Boolean(_) => "Boolean",
            CoreTemplatePropertyKind::Integer(_) => "Integer",
            CoreTemplatePropertyKind::IntegerOpt(_) => "Option<Integer>",
            CoreTemplatePropertyKind::Signature(_) => "Signature",
            CoreTemplatePropertyKind::SizeHint(_) => "SizeHint",
            CoreTemplatePropertyKind::Timestamp(_) => "Timestamp",
            CoreTemplatePropertyKind::TimestampRange(_) => "TimestampRange",
            CoreTemplatePropertyKind::Template(_) => "Template",
            CoreTemplatePropertyKind::ListTemplate(_) => "ListTemplate",
        }
    }

    fn try_into_boolean(self) -> Option<Box<dyn TemplateProperty<Output = bool> + 'a>> {
        match self {
            CoreTemplatePropertyKind::String(property) => {
                Some(Box::new(property.map(|s| !s.is_empty())))
            }
            CoreTemplatePropertyKind::StringList(property) => {
                Some(Box::new(property.map(|l| !l.is_empty())))
            }
            CoreTemplatePropertyKind::Boolean(property) => Some(property),
            CoreTemplatePropertyKind::Integer(_) => None,
            CoreTemplatePropertyKind::IntegerOpt(property) => {
                Some(Box::new(property.map(|opt| opt.is_some())))
            }
            CoreTemplatePropertyKind::Signature(_) => None,
            CoreTemplatePropertyKind::SizeHint(_) => None,
            CoreTemplatePropertyKind::Timestamp(_) => None,
            CoreTemplatePropertyKind::TimestampRange(_) => None,
            // Template types could also be evaluated to boolean, but it's less likely
            // to apply label() or .map() and use the result as conditional. It's also
            // unclear whether ListTemplate should behave as a "list" or a "template".
            CoreTemplatePropertyKind::Template(_) => None,
            CoreTemplatePropertyKind::ListTemplate(_) => None,
        }
    }

    fn try_into_integer(self) -> Option<Box<dyn TemplateProperty<Output = i64> + 'a>> {
        match self {
            CoreTemplatePropertyKind::Integer(property) => Some(property),
            CoreTemplatePropertyKind::IntegerOpt(property) => {
                Some(Box::new(property.try_unwrap("Integer")))
            }
            _ => None,
        }
    }

    fn try_into_plain_text(self) -> Option<Box<dyn TemplateProperty<Output = String> + 'a>> {
        match self {
            CoreTemplatePropertyKind::String(property) => Some(property),
            _ => {
                let template = self.try_into_template()?;
                Some(Box::new(PlainTextFormattedProperty::new(template)))
            }
        }
    }

    fn try_into_template(self) -> Option<Box<dyn Template + 'a>> {
        match self {
            CoreTemplatePropertyKind::String(property) => Some(property.into_template()),
            CoreTemplatePropertyKind::StringList(property) => Some(property.into_template()),
            CoreTemplatePropertyKind::Boolean(property) => Some(property.into_template()),
            CoreTemplatePropertyKind::Integer(property) => Some(property.into_template()),
            CoreTemplatePropertyKind::IntegerOpt(property) => Some(property.into_template()),
            CoreTemplatePropertyKind::Signature(property) => Some(property.into_template()),
            CoreTemplatePropertyKind::SizeHint(_) => None,
            CoreTemplatePropertyKind::Timestamp(property) => Some(property.into_template()),
            CoreTemplatePropertyKind::TimestampRange(property) => Some(property.into_template()),
            CoreTemplatePropertyKind::Template(template) => Some(template),
            CoreTemplatePropertyKind::ListTemplate(template) => Some(template.into_template()),
        }
    }
}

/// Function that translates global function call node.
// The lifetime parameter 'a could be replaced with for<'a> to keep the method
// table away from a certain lifetime. That's technically more correct, but I
// couldn't find an easy way to expand that to the core template methods, which
// are defined for L: TemplateLanguage<'a>. That's why the build fn table is
// bound to a named lifetime, and therefore can't be cached statically.
pub type TemplateBuildFunctionFn<'a, L> =
    fn(
        &L,
        &BuildContext<<L as TemplateLanguage<'a>>::Property>,
        &FunctionCallNode,
    ) -> TemplateParseResult<<L as TemplateLanguage<'a>>::Property>;

/// Function that translates method call node of self type `T`.
pub type TemplateBuildMethodFn<'a, L, T> =
    fn(
        &L,
        &BuildContext<<L as TemplateLanguage<'a>>::Property>,
        Box<dyn TemplateProperty<Output = T> + 'a>,
        &FunctionCallNode,
    ) -> TemplateParseResult<<L as TemplateLanguage<'a>>::Property>;

/// Table of functions that translate global function call node.
pub type TemplateBuildFunctionFnMap<'a, L> = HashMap<&'static str, TemplateBuildFunctionFn<'a, L>>;

/// Table of functions that translate method call node of self type `T`.
pub type TemplateBuildMethodFnMap<'a, L, T> =
    HashMap<&'static str, TemplateBuildMethodFn<'a, L, T>>;

/// Symbol table of functions and methods available in the core template.
pub struct CoreTemplateBuildFnTable<'a, L: TemplateLanguage<'a> + ?Sized> {
    pub functions: TemplateBuildFunctionFnMap<'a, L>,
    pub string_methods: TemplateBuildMethodFnMap<'a, L, String>,
    pub boolean_methods: TemplateBuildMethodFnMap<'a, L, bool>,
    pub integer_methods: TemplateBuildMethodFnMap<'a, L, i64>,
    pub signature_methods: TemplateBuildMethodFnMap<'a, L, Signature>,
    pub size_hint_methods: TemplateBuildMethodFnMap<'a, L, SizeHint>,
    pub timestamp_methods: TemplateBuildMethodFnMap<'a, L, Timestamp>,
    pub timestamp_range_methods: TemplateBuildMethodFnMap<'a, L, TimestampRange>,
}

pub fn merge_fn_map<'s, F>(base: &mut HashMap<&'s str, F>, extension: HashMap<&'s str, F>) {
    for (name, function) in extension {
        if base.insert(name, function).is_some() {
            panic!("Conflicting template definitions for '{name}' function");
        }
    }
}

impl<'a, L: TemplateLanguage<'a> + ?Sized> CoreTemplateBuildFnTable<'a, L> {
    /// Creates new symbol table containing the builtin functions and methods.
    pub fn builtin() -> Self {
        CoreTemplateBuildFnTable {
            functions: builtin_functions(),
            string_methods: builtin_string_methods(),
            boolean_methods: HashMap::new(),
            integer_methods: HashMap::new(),
            signature_methods: builtin_signature_methods(),
            size_hint_methods: builtin_size_hint_methods(),
            timestamp_methods: builtin_timestamp_methods(),
            timestamp_range_methods: builtin_timestamp_range_methods(),
        }
    }

    pub fn empty() -> Self {
        CoreTemplateBuildFnTable {
            functions: HashMap::new(),
            string_methods: HashMap::new(),
            boolean_methods: HashMap::new(),
            integer_methods: HashMap::new(),
            signature_methods: HashMap::new(),
            size_hint_methods: HashMap::new(),
            timestamp_methods: HashMap::new(),
            timestamp_range_methods: HashMap::new(),
        }
    }

    pub fn merge(&mut self, extension: CoreTemplateBuildFnTable<'a, L>) {
        let CoreTemplateBuildFnTable {
            functions,
            string_methods,
            boolean_methods,
            integer_methods,
            signature_methods,
            size_hint_methods,
            timestamp_methods,
            timestamp_range_methods,
        } = extension;

        merge_fn_map(&mut self.functions, functions);
        merge_fn_map(&mut self.string_methods, string_methods);
        merge_fn_map(&mut self.boolean_methods, boolean_methods);
        merge_fn_map(&mut self.integer_methods, integer_methods);
        merge_fn_map(&mut self.signature_methods, signature_methods);
        merge_fn_map(&mut self.size_hint_methods, size_hint_methods);
        merge_fn_map(&mut self.timestamp_methods, timestamp_methods);
        merge_fn_map(&mut self.timestamp_range_methods, timestamp_range_methods);
    }

    /// Translates the function call node `function` by using this symbol table.
    pub fn build_function(
        &self,
        language: &L,
        build_ctx: &BuildContext<L::Property>,
        function: &FunctionCallNode,
    ) -> TemplateParseResult<L::Property> {
        let table = &self.functions;
        let build = template_parser::lookup_function(table, function)?;
        build(language, build_ctx, function)
    }

    /// Applies the method call node `function` to the given `property` by using
    /// this symbol table.
    pub fn build_method(
        &self,
        language: &L,
        build_ctx: &BuildContext<L::Property>,
        property: CoreTemplatePropertyKind<'a>,
        function: &FunctionCallNode,
    ) -> TemplateParseResult<L::Property> {
        let type_name = property.type_name();
        match property {
            CoreTemplatePropertyKind::String(property) => {
                let table = &self.string_methods;
                let build = template_parser::lookup_method(type_name, table, function)?;
                build(language, build_ctx, property, function)
            }
            CoreTemplatePropertyKind::StringList(property) => {
                // TODO: migrate to table?
                build_formattable_list_method(language, build_ctx, property, function, |item| {
                    L::wrap_string(item)
                })
            }
            CoreTemplatePropertyKind::Boolean(property) => {
                let table = &self.boolean_methods;
                let build = template_parser::lookup_method(type_name, table, function)?;
                build(language, build_ctx, property, function)
            }
            CoreTemplatePropertyKind::Integer(property) => {
                let table = &self.integer_methods;
                let build = template_parser::lookup_method(type_name, table, function)?;
                build(language, build_ctx, property, function)
            }
            CoreTemplatePropertyKind::IntegerOpt(property) => {
                let type_name = "Integer";
                let table = &self.integer_methods;
                let build = template_parser::lookup_method(type_name, table, function)?;
                let inner_property = property.try_unwrap(type_name);
                build(language, build_ctx, Box::new(inner_property), function)
            }
            CoreTemplatePropertyKind::Signature(property) => {
                let table = &self.signature_methods;
                let build = template_parser::lookup_method(type_name, table, function)?;
                build(language, build_ctx, property, function)
            }
            CoreTemplatePropertyKind::SizeHint(property) => {
                let table = &self.size_hint_methods;
                let build = template_parser::lookup_method(type_name, table, function)?;
                build(language, build_ctx, property, function)
            }
            CoreTemplatePropertyKind::Timestamp(property) => {
                let table = &self.timestamp_methods;
                let build = template_parser::lookup_method(type_name, table, function)?;
                build(language, build_ctx, property, function)
            }
            CoreTemplatePropertyKind::TimestampRange(property) => {
                let table = &self.timestamp_range_methods;
                let build = template_parser::lookup_method(type_name, table, function)?;
                build(language, build_ctx, property, function)
            }
            CoreTemplatePropertyKind::Template(_) => {
                // TODO: migrate to table?
                Err(TemplateParseError::no_such_method(type_name, function))
            }
            CoreTemplatePropertyKind::ListTemplate(template) => {
                // TODO: migrate to table?
                build_list_template_method(language, build_ctx, template, function)
            }
        }
    }
}

/// Opaque struct that represents a template value.
pub struct Expression<P> {
    property: P,
    labels: Vec<String>,
}

impl<P> Expression<P> {
    fn unlabeled(property: P) -> Self {
        let labels = vec![];
        Expression { property, labels }
    }

    fn with_label(property: P, label: impl Into<String>) -> Self {
        let labels = vec![label.into()];
        Expression { property, labels }
    }
}

impl<'a, P: IntoTemplateProperty<'a>> Expression<P> {
    pub fn type_name(&self) -> &'static str {
        self.property.type_name()
    }

    pub fn try_into_boolean(self) -> Option<Box<dyn TemplateProperty<Output = bool> + 'a>> {
        self.property.try_into_boolean()
    }

    pub fn try_into_integer(self) -> Option<Box<dyn TemplateProperty<Output = i64> + 'a>> {
        self.property.try_into_integer()
    }

    pub fn try_into_plain_text(self) -> Option<Box<dyn TemplateProperty<Output = String> + 'a>> {
        self.property.try_into_plain_text()
    }

    pub fn try_into_template(self) -> Option<Box<dyn Template + 'a>> {
        let template = self.property.try_into_template()?;
        if self.labels.is_empty() {
            Some(template)
        } else {
            Some(Box::new(LabelTemplate::new(template, Literal(self.labels))))
        }
    }
}

pub struct BuildContext<'i, P> {
    /// Map of functions to create `L::Property`.
    local_variables: HashMap<&'i str, &'i (dyn Fn() -> P)>,
    /// Function to create `L::Property` representing `self`.
    ///
    /// This could be `local_variables["self"]`, but keyword lookup shouldn't be
    /// overridden by a user-defined `self` variable.
    self_variable: &'i (dyn Fn() -> P),
}

fn build_keyword<'a, L: TemplateLanguage<'a> + ?Sized>(
    language: &L,
    build_ctx: &BuildContext<L::Property>,
    name: &str,
    name_span: pest::Span<'_>,
) -> TemplateParseResult<L::Property> {
    // Keyword is a 0-ary method on the "self" property
    let self_property = (build_ctx.self_variable)();
    let function = FunctionCallNode {
        name,
        name_span,
        args: vec![],
        keyword_args: vec![],
        args_span: name_span.end_pos().span(&name_span.end_pos()),
    };
    language
        .build_method(build_ctx, self_property, &function)
        .map_err(|err| match err.kind() {
            TemplateParseErrorKind::NoSuchMethod { candidates, .. } => {
                let kind = TemplateParseErrorKind::NoSuchKeyword {
                    name: name.to_owned(),
                    // TODO: filter methods by arity?
                    candidates: candidates.clone(),
                };
                TemplateParseError::with_span(kind, name_span)
            }
            // Since keyword is a 0-ary method, any argument errors mean there's
            // no such keyword.
            TemplateParseErrorKind::InvalidArguments { .. } => {
                let kind = TemplateParseErrorKind::NoSuchKeyword {
                    name: name.to_owned(),
                    // TODO: might be better to phrase the error differently
                    candidates: vec![format!("self.{name}(..)")],
                };
                TemplateParseError::with_span(kind, name_span)
            }
            // The keyword function may fail with the other reasons.
            _ => err,
        })
}

fn build_unary_operation<'a, L: TemplateLanguage<'a> + ?Sized>(
    language: &L,
    build_ctx: &BuildContext<L::Property>,
    op: UnaryOp,
    arg_node: &ExpressionNode,
) -> TemplateParseResult<L::Property> {
    match op {
        UnaryOp::LogicalNot => {
            let arg = expect_boolean_expression(language, build_ctx, arg_node)?;
            Ok(L::wrap_boolean(arg.map(|v| !v)))
        }
        UnaryOp::Negate => {
            let arg = expect_integer_expression(language, build_ctx, arg_node)?;
            Ok(L::wrap_integer(arg.and_then(|v| {
                v.checked_neg()
                    .ok_or_else(|| TemplatePropertyError("Attempt to negate with overflow".into()))
            })))
        }
    }
}

fn build_binary_operation<'a, L: TemplateLanguage<'a> + ?Sized>(
    language: &L,
    build_ctx: &BuildContext<L::Property>,
    op: BinaryOp,
    lhs_node: &ExpressionNode,
    rhs_node: &ExpressionNode,
) -> TemplateParseResult<L::Property> {
    match op {
        BinaryOp::LogicalOr => {
            let lhs = expect_boolean_expression(language, build_ctx, lhs_node)?;
            let rhs = expect_boolean_expression(language, build_ctx, rhs_node)?;
            let out = lhs.and_then(move |l| Ok(l || rhs.extract()?));
            Ok(L::wrap_boolean(out))
        }
        BinaryOp::LogicalAnd => {
            let lhs = expect_boolean_expression(language, build_ctx, lhs_node)?;
            let rhs = expect_boolean_expression(language, build_ctx, rhs_node)?;
            let out = lhs.and_then(move |l| Ok(l && rhs.extract()?));
            Ok(L::wrap_boolean(out))
        }
    }
}

fn builtin_string_methods<'a, L: TemplateLanguage<'a> + ?Sized>(
) -> TemplateBuildMethodFnMap<'a, L, String> {
    // Not using maplit::hashmap!{} or custom declarative macro here because
    // code completion inside macro is quite restricted.
    let mut map = TemplateBuildMethodFnMap::<L, String>::new();
    map.insert("len", |_language, _build_ctx, self_property, function| {
        function.expect_no_arguments()?;
        let out_property = self_property.and_then(|s| Ok(s.len().try_into()?));
        Ok(L::wrap_integer(out_property))
    });
    map.insert(
        "contains",
        |language, build_ctx, self_property, function| {
            let [needle_node] = function.expect_exact_arguments()?;
            // TODO: or .try_into_string() to disable implicit type cast?
            let needle_property = expect_plain_text_expression(language, build_ctx, needle_node)?;
            let out_property = (self_property, needle_property)
                .map(|(haystack, needle)| haystack.contains(&needle));
            Ok(L::wrap_boolean(out_property))
        },
    );
    map.insert(
        "starts_with",
        |language, build_ctx, self_property, function| {
            let [needle_node] = function.expect_exact_arguments()?;
            let needle_property = expect_plain_text_expression(language, build_ctx, needle_node)?;
            let out_property = (self_property, needle_property)
                .map(|(haystack, needle)| haystack.starts_with(&needle));
            Ok(L::wrap_boolean(out_property))
        },
    );
    map.insert(
        "ends_with",
        |language, build_ctx, self_property, function| {
            let [needle_node] = function.expect_exact_arguments()?;
            let needle_property = expect_plain_text_expression(language, build_ctx, needle_node)?;
            let out_property = (self_property, needle_property)
                .map(|(haystack, needle)| haystack.ends_with(&needle));
            Ok(L::wrap_boolean(out_property))
        },
    );
    map.insert(
        "remove_prefix",
        |language, build_ctx, self_property, function| {
            let [needle_node] = function.expect_exact_arguments()?;
            let needle_property = expect_plain_text_expression(language, build_ctx, needle_node)?;
            let out_property = (self_property, needle_property).map(|(haystack, needle)| {
                haystack
                    .strip_prefix(&needle)
                    .map(ToOwned::to_owned)
                    .unwrap_or(haystack)
            });
            Ok(L::wrap_string(out_property))
        },
    );
    map.insert(
        "remove_suffix",
        |language, build_ctx, self_property, function| {
            let [needle_node] = function.expect_exact_arguments()?;
            let needle_property = expect_plain_text_expression(language, build_ctx, needle_node)?;
            let out_property = (self_property, needle_property).map(|(haystack, needle)| {
                haystack
                    .strip_suffix(&needle)
                    .map(ToOwned::to_owned)
                    .unwrap_or(haystack)
            });
            Ok(L::wrap_string(out_property))
        },
    );
    map.insert("substr", |language, build_ctx, self_property, function| {
        let [start_idx, end_idx] = function.expect_exact_arguments()?;
        let start_idx_property = expect_isize_expression(language, build_ctx, start_idx)?;
        let end_idx_property = expect_isize_expression(language, build_ctx, end_idx)?;
        let out_property =
            (self_property, start_idx_property, end_idx_property).map(|(s, start_idx, end_idx)| {
                let start_idx = string_index_to_char_boundary(&s, start_idx);
                let end_idx = string_index_to_char_boundary(&s, end_idx);
                s.get(start_idx..end_idx).unwrap_or_default().to_owned()
            });
        Ok(L::wrap_string(out_property))
    });
    map.insert(
        "first_line",
        |_language, _build_ctx, self_property, function| {
            function.expect_no_arguments()?;
            let out_property =
                self_property.map(|s| s.lines().next().unwrap_or_default().to_string());
            Ok(L::wrap_string(out_property))
        },
    );
    map.insert("lines", |_language, _build_ctx, self_property, function| {
        function.expect_no_arguments()?;
        let out_property = self_property.map(|s| s.lines().map(|l| l.to_owned()).collect());
        Ok(L::wrap_string_list(out_property))
    });
    map.insert("upper", |_language, _build_ctx, self_property, function| {
        function.expect_no_arguments()?;
        let out_property = self_property.map(|s| s.to_uppercase());
        Ok(L::wrap_string(out_property))
    });
    map.insert("lower", |_language, _build_ctx, self_property, function| {
        function.expect_no_arguments()?;
        let out_property = self_property.map(|s| s.to_lowercase());
        Ok(L::wrap_string(out_property))
    });
    map
}

/// Clamps and aligns the given index `i` to char boundary.
///
/// Negative index counts from the end. If the index isn't at a char boundary,
/// it will be rounded towards 0 (left or right depending on the sign.)
fn string_index_to_char_boundary(s: &str, i: isize) -> usize {
    // TODO: use floor/ceil_char_boundary() if get stabilized
    let magnitude = i.unsigned_abs();
    if i < 0 {
        let p = s.len().saturating_sub(magnitude);
        (p..=s.len()).find(|&p| s.is_char_boundary(p)).unwrap()
    } else {
        let p = magnitude.min(s.len());
        (0..=p).rev().find(|&p| s.is_char_boundary(p)).unwrap()
    }
}

fn builtin_signature_methods<'a, L: TemplateLanguage<'a> + ?Sized>(
) -> TemplateBuildMethodFnMap<'a, L, Signature> {
    // Not using maplit::hashmap!{} or custom declarative macro here because
    // code completion inside macro is quite restricted.
    let mut map = TemplateBuildMethodFnMap::<L, Signature>::new();
    map.insert("name", |_language, _build_ctx, self_property, function| {
        function.expect_no_arguments()?;
        let out_property = self_property.map(|signature| signature.name);
        Ok(L::wrap_string(out_property))
    });
    map.insert("email", |_language, _build_ctx, self_property, function| {
        function.expect_no_arguments()?;
        let out_property = self_property.map(|signature| signature.email);
        Ok(L::wrap_string(out_property))
    });
    map.insert(
        "username",
        |_language, _build_ctx, self_property, function| {
            function.expect_no_arguments()?;
            let out_property = self_property.map(|signature| {
                let (username, _) = text_util::split_email(&signature.email);
                username.to_owned()
            });
            Ok(L::wrap_string(out_property))
        },
    );
    map.insert(
        "timestamp",
        |_language, _build_ctx, self_property, function| {
            function.expect_no_arguments()?;
            let out_property = self_property.map(|signature| signature.timestamp);
            Ok(L::wrap_timestamp(out_property))
        },
    );
    map
}

fn builtin_size_hint_methods<'a, L: TemplateLanguage<'a> + ?Sized>(
) -> TemplateBuildMethodFnMap<'a, L, SizeHint> {
    // Not using maplit::hashmap!{} or custom declarative macro here because
    // code completion inside macro is quite restricted.
    let mut map = TemplateBuildMethodFnMap::<L, SizeHint>::new();
    map.insert("lower", |_language, _build_ctx, self_property, function| {
        function.expect_no_arguments()?;
        let out_property = self_property.and_then(|(lower, _)| Ok(i64::try_from(lower)?));
        Ok(L::wrap_integer(out_property))
    });
    map.insert("upper", |_language, _build_ctx, self_property, function| {
        function.expect_no_arguments()?;
        let out_property =
            self_property.and_then(|(_, upper)| Ok(upper.map(i64::try_from).transpose()?));
        Ok(L::wrap_integer_opt(out_property))
    });
    map.insert("exact", |_language, _build_ctx, self_property, function| {
        function.expect_no_arguments()?;
        let out_property = self_property.and_then(|(lower, upper)| {
            let exact = (Some(lower) == upper).then_some(lower);
            Ok(exact.map(i64::try_from).transpose()?)
        });
        Ok(L::wrap_integer_opt(out_property))
    });
    map.insert("zero", |_language, _build_ctx, self_property, function| {
        function.expect_no_arguments()?;
        let out_property = self_property.map(|(_, upper)| upper == Some(0));
        Ok(L::wrap_boolean(out_property))
    });
    map
}

fn builtin_timestamp_methods<'a, L: TemplateLanguage<'a> + ?Sized>(
) -> TemplateBuildMethodFnMap<'a, L, Timestamp> {
    // Not using maplit::hashmap!{} or custom declarative macro here because
    // code completion inside macro is quite restricted.
    let mut map = TemplateBuildMethodFnMap::<L, Timestamp>::new();
    map.insert("ago", |_language, _build_ctx, self_property, function| {
        function.expect_no_arguments()?;
        let now = Timestamp::now();
        let format = timeago::Formatter::new();
        let out_property = self_property
            .and_then(move |timestamp| Ok(time_util::format_duration(&timestamp, &now, &format)?));
        Ok(L::wrap_string(out_property))
    });
    map.insert(
        "format",
        |_language, _build_ctx, self_property, function| {
            // No dynamic string is allowed as the templater has no runtime error type.
            let [format_node] = function.expect_exact_arguments()?;
            let format =
                template_parser::expect_string_literal_with(format_node, |format, span| {
                    time_util::FormattingItems::parse(format)
                        .ok_or_else(|| TemplateParseError::expression("Invalid time format", span))
                })?
                .into_owned();
            let out_property = self_property.and_then(move |timestamp| {
                Ok(time_util::format_absolute_timestamp_with(
                    &timestamp, &format,
                )?)
            });
            Ok(L::wrap_string(out_property))
        },
    );
    map.insert("utc", |_language, _build_ctx, self_property, function| {
        function.expect_no_arguments()?;
        let out_property = self_property.map(|mut timestamp| {
            timestamp.tz_offset = 0;
            timestamp
        });
        Ok(L::wrap_timestamp(out_property))
    });
    map.insert("local", |_language, _build_ctx, self_property, function| {
        function.expect_no_arguments()?;
        let tz_offset = std::env::var("JJ_TZ_OFFSET_MINS")
            .ok()
            .and_then(|tz_string| tz_string.parse::<i32>().ok())
            .unwrap_or_else(|| chrono::Local::now().offset().local_minus_utc() / 60);
        let out_property = self_property.map(move |mut timestamp| {
            timestamp.tz_offset = tz_offset;
            timestamp
        });
        Ok(L::wrap_timestamp(out_property))
    });
    map
}

fn builtin_timestamp_range_methods<'a, L: TemplateLanguage<'a> + ?Sized>(
) -> TemplateBuildMethodFnMap<'a, L, TimestampRange> {
    // Not using maplit::hashmap!{} or custom declarative macro here because
    // code completion inside macro is quite restricted.
    let mut map = TemplateBuildMethodFnMap::<L, TimestampRange>::new();
    map.insert("start", |_language, _build_ctx, self_property, function| {
        function.expect_no_arguments()?;
        let out_property = self_property.map(|time_range| time_range.start);
        Ok(L::wrap_timestamp(out_property))
    });
    map.insert("end", |_language, _build_ctx, self_property, function| {
        function.expect_no_arguments()?;
        let out_property = self_property.map(|time_range| time_range.end);
        Ok(L::wrap_timestamp(out_property))
    });
    map.insert(
        "duration",
        |_language, _build_ctx, self_property, function| {
            function.expect_no_arguments()?;
            let out_property = self_property.and_then(|time_range| Ok(time_range.duration()?));
            Ok(L::wrap_string(out_property))
        },
    );
    map
}

fn build_list_template_method<'a, L: TemplateLanguage<'a> + ?Sized>(
    language: &L,
    build_ctx: &BuildContext<L::Property>,
    self_template: Box<dyn ListTemplate + 'a>,
    function: &FunctionCallNode,
) -> TemplateParseResult<L::Property> {
    let property = match function.name {
        "join" => {
            let [separator_node] = function.expect_exact_arguments()?;
            let separator = expect_template_expression(language, build_ctx, separator_node)?;
            L::wrap_template(self_template.join(separator))
        }
        _ => return Err(TemplateParseError::no_such_method("ListTemplate", function)),
    };
    Ok(property)
}

/// Builds method call expression for printable list property.
pub fn build_formattable_list_method<'a, L, O>(
    language: &L,
    build_ctx: &BuildContext<L::Property>,
    self_property: impl TemplateProperty<Output = Vec<O>> + 'a,
    function: &FunctionCallNode,
    // TODO: Generic L: WrapProperty<O> trait might be needed to support more
    // list operations such as first()/slice(). For .map(), a simple callback works.
    wrap_item: impl Fn(PropertyPlaceholder<O>) -> L::Property,
) -> TemplateParseResult<L::Property>
where
    L: TemplateLanguage<'a> + ?Sized,
    O: Template + Clone + 'a,
{
    let property = match function.name {
        "len" => {
            function.expect_no_arguments()?;
            let out_property = self_property.and_then(|items| Ok(items.len().try_into()?));
            L::wrap_integer(out_property)
        }
        "join" => {
            let [separator_node] = function.expect_exact_arguments()?;
            let separator = expect_template_expression(language, build_ctx, separator_node)?;
            let template =
                ListPropertyTemplate::new(self_property, separator, |formatter, item| {
                    item.format(formatter)
                });
            L::wrap_template(Box::new(template))
        }
        "map" => build_map_operation(language, build_ctx, self_property, function, wrap_item)?,
        _ => return Err(TemplateParseError::no_such_method("List", function)),
    };
    Ok(property)
}

pub fn build_unformattable_list_method<'a, L, O>(
    language: &L,
    build_ctx: &BuildContext<L::Property>,
    self_property: impl TemplateProperty<Output = Vec<O>> + 'a,
    function: &FunctionCallNode,
    wrap_item: impl Fn(PropertyPlaceholder<O>) -> L::Property,
) -> TemplateParseResult<L::Property>
where
    L: TemplateLanguage<'a> + ?Sized,
    O: Clone + 'a,
{
    let property = match function.name {
        "len" => {
            function.expect_no_arguments()?;
            let out_property = self_property.and_then(|items| Ok(items.len().try_into()?));
            L::wrap_integer(out_property)
        }
        // No "join"
        "map" => build_map_operation(language, build_ctx, self_property, function, wrap_item)?,
        _ => return Err(TemplateParseError::no_such_method("List", function)),
    };
    Ok(property)
}

/// Builds expression that extracts iterable property and applies template to
/// each item.
///
/// `wrap_item()` is the function to wrap a list item of type `O` as a property.
fn build_map_operation<'a, L, O, P>(
    language: &L,
    build_ctx: &BuildContext<L::Property>,
    self_property: P,
    function: &FunctionCallNode,
    wrap_item: impl Fn(PropertyPlaceholder<O>) -> L::Property,
) -> TemplateParseResult<L::Property>
where
    L: TemplateLanguage<'a> + ?Sized,
    P: TemplateProperty + 'a,
    P::Output: IntoIterator<Item = O>,
    O: Clone + 'a,
{
    // Build an item template with placeholder property, then evaluate it
    // for each item.
    let [lambda_node] = function.expect_exact_arguments()?;
    let item_placeholder = PropertyPlaceholder::new();
    let item_template = template_parser::expect_lambda_with(lambda_node, |lambda, _span| {
        let item_fn = || wrap_item(item_placeholder.clone());
        let mut local_variables = build_ctx.local_variables.clone();
        if let [name] = lambda.params.as_slice() {
            local_variables.insert(name, &item_fn);
        } else {
            return Err(TemplateParseError::expression(
                "Expected 1 lambda parameters",
                lambda.params_span,
            ));
        }
        let inner_build_ctx = BuildContext {
            local_variables,
            self_variable: build_ctx.self_variable,
        };
        expect_template_expression(language, &inner_build_ctx, &lambda.body)
    })?;
    let list_template = ListPropertyTemplate::new(
        self_property,
        Literal(" "), // separator
        move |formatter, item| {
            item_placeholder.with_value(item, || item_template.format(formatter))
        },
    );
    Ok(L::wrap_list_template(Box::new(list_template)))
}

fn builtin_functions<'a, L: TemplateLanguage<'a> + ?Sized>() -> TemplateBuildFunctionFnMap<'a, L> {
    // Not using maplit::hashmap!{} or custom declarative macro here because
    // code completion inside macro is quite restricted.
    let mut map = TemplateBuildFunctionFnMap::<L>::new();
    map.insert("fill", |language, build_ctx, function| {
        let [width_node, content_node] = function.expect_exact_arguments()?;
        let width = expect_usize_expression(language, build_ctx, width_node)?;
        let content = expect_template_expression(language, build_ctx, content_node)?;
        let template =
            ReformatTemplate::new(content, move |formatter, recorded| match width.extract() {
                Ok(width) => text_util::write_wrapped(formatter.as_mut(), recorded, width),
                Err(err) => formatter.handle_error(err),
            });
        Ok(L::wrap_template(Box::new(template)))
    });
    map.insert("indent", |language, build_ctx, function| {
        let [prefix_node, content_node] = function.expect_exact_arguments()?;
        let prefix = expect_template_expression(language, build_ctx, prefix_node)?;
        let content = expect_template_expression(language, build_ctx, content_node)?;
        let template = ReformatTemplate::new(content, move |formatter, recorded| {
            let rewrap = formatter.rewrap_fn();
            text_util::write_indented(formatter.as_mut(), recorded, |formatter| {
                prefix.format(&mut rewrap(formatter))
            })
        });
        Ok(L::wrap_template(Box::new(template)))
    });
    map.insert("label", |language, build_ctx, function| {
        let [label_node, content_node] = function.expect_exact_arguments()?;
        let label_property = expect_plain_text_expression(language, build_ctx, label_node)?;
        let content = expect_template_expression(language, build_ctx, content_node)?;
        let labels =
            label_property.map(|s| s.split_whitespace().map(ToString::to_string).collect());
        Ok(L::wrap_template(Box::new(LabelTemplate::new(
            content, labels,
        ))))
    });
    map.insert("if", |language, build_ctx, function| {
        let ([condition_node, true_node], [false_node]) = function.expect_arguments()?;
        let condition = expect_boolean_expression(language, build_ctx, condition_node)?;
        let true_template = expect_template_expression(language, build_ctx, true_node)?;
        let false_template = false_node
            .map(|node| expect_template_expression(language, build_ctx, node))
            .transpose()?;
        let template = ConditionalTemplate::new(condition, true_template, false_template);
        Ok(L::wrap_template(Box::new(template)))
    });
    map.insert("coalesce", |language, build_ctx, function| {
        let contents = function
            .args
            .iter()
            .map(|node| expect_template_expression(language, build_ctx, node))
            .try_collect()?;
        Ok(L::wrap_template(Box::new(CoalesceTemplate(contents))))
    });
    map.insert("concat", |language, build_ctx, function| {
        let contents = function
            .args
            .iter()
            .map(|node| expect_template_expression(language, build_ctx, node))
            .try_collect()?;
        Ok(L::wrap_template(Box::new(ConcatTemplate(contents))))
    });
    map.insert("separate", |language, build_ctx, function| {
        let ([separator_node], content_nodes) = function.expect_some_arguments()?;
        let separator = expect_template_expression(language, build_ctx, separator_node)?;
        let contents = content_nodes
            .iter()
            .map(|node| expect_template_expression(language, build_ctx, node))
            .try_collect()?;
        Ok(L::wrap_template(Box::new(SeparateTemplate::new(
            separator, contents,
        ))))
    });
    map.insert("surround", |language, build_ctx, function| {
        let [prefix_node, suffix_node, content_node] = function.expect_exact_arguments()?;
        let prefix = expect_template_expression(language, build_ctx, prefix_node)?;
        let suffix = expect_template_expression(language, build_ctx, suffix_node)?;
        let content = expect_template_expression(language, build_ctx, content_node)?;
        let template = ReformatTemplate::new(content, move |formatter, recorded| {
            if recorded.data().is_empty() {
                return Ok(());
            }
            prefix.format(formatter)?;
            recorded.replay(formatter.as_mut())?;
            suffix.format(formatter)?;
            Ok(())
        });
        Ok(L::wrap_template(Box::new(template)))
    });
    map
}

/// Builds intermediate expression tree from AST nodes.
pub fn build_expression<'a, L: TemplateLanguage<'a> + ?Sized>(
    language: &L,
    build_ctx: &BuildContext<L::Property>,
    node: &ExpressionNode,
) -> TemplateParseResult<Expression<L::Property>> {
    match &node.kind {
        ExpressionKind::Identifier(name) => {
            if let Some(make) = build_ctx.local_variables.get(name) {
                // Don't label a local variable with its name
                Ok(Expression::unlabeled(make()))
            } else if *name == "self" {
                // "self" is a special variable, so don't label it
                let make = build_ctx.self_variable;
                Ok(Expression::unlabeled(make()))
            } else {
                let property =
                    build_keyword(language, build_ctx, name, node.span).map_err(|err| {
                        err.extend_keyword_candidates(itertools::chain(
                            build_ctx.local_variables.keys().copied(),
                            ["self"],
                        ))
                    })?;
                Ok(Expression::with_label(property, *name))
            }
        }
        ExpressionKind::Boolean(value) => {
            let property = L::wrap_boolean(Literal(*value));
            Ok(Expression::unlabeled(property))
        }
        ExpressionKind::Integer(value) => {
            let property = L::wrap_integer(Literal(*value));
            Ok(Expression::unlabeled(property))
        }
        ExpressionKind::String(value) => {
            let property = L::wrap_string(Literal(value.clone()));
            Ok(Expression::unlabeled(property))
        }
        ExpressionKind::Unary(op, arg_node) => {
            let property = build_unary_operation(language, build_ctx, *op, arg_node)?;
            Ok(Expression::unlabeled(property))
        }
        ExpressionKind::Binary(op, lhs_node, rhs_node) => {
            let property = build_binary_operation(language, build_ctx, *op, lhs_node, rhs_node)?;
            Ok(Expression::unlabeled(property))
        }
        ExpressionKind::Concat(nodes) => {
            let templates = nodes
                .iter()
                .map(|node| expect_template_expression(language, build_ctx, node))
                .try_collect()?;
            let property = L::wrap_template(Box::new(ConcatTemplate(templates)));
            Ok(Expression::unlabeled(property))
        }
        ExpressionKind::FunctionCall(function) => {
            let property = language.build_function(build_ctx, function)?;
            Ok(Expression::unlabeled(property))
        }
        ExpressionKind::MethodCall(method) => {
            let mut expression = build_expression(language, build_ctx, &method.object)?;
            expression.property =
                language.build_method(build_ctx, expression.property, &method.function)?;
            expression.labels.push(method.function.name.to_owned());
            Ok(expression)
        }
        ExpressionKind::Lambda(_) => Err(TemplateParseError::expression(
            "Lambda cannot be defined here",
            node.span,
        )),
        ExpressionKind::AliasExpanded(id, subst) => build_expression(language, build_ctx, subst)
            .map_err(|e| e.within_alias_expansion(*id, node.span)),
    }
}

/// Builds template evaluation tree from AST nodes, with fresh build context.
///
/// `wrap_self` specifies the type of the top-level property, which should be
/// one of the `L::wrap_*()` functions.
pub fn build<'a, C: Clone + 'a, L: TemplateLanguage<'a> + ?Sized>(
    language: &L,
    node: &ExpressionNode,
    // TODO: Generic L: WrapProperty<C> trait might be better. See the
    // comment in build_formattable_list_method().
    wrap_self: impl Fn(PropertyPlaceholder<C>) -> L::Property,
) -> TemplateParseResult<TemplateRenderer<'a, C>> {
    let self_placeholder = PropertyPlaceholder::new();
    let build_ctx = BuildContext {
        local_variables: HashMap::new(),
        self_variable: &|| wrap_self(self_placeholder.clone()),
    };
    let template = expect_template_expression(language, &build_ctx, node)?;
    Ok(TemplateRenderer::new(template, self_placeholder))
}

/// Parses text, expands aliases, then builds template evaluation tree.
pub fn parse<'a, C: Clone + 'a, L: TemplateLanguage<'a> + ?Sized>(
    language: &L,
    template_text: &str,
    aliases_map: &TemplateAliasesMap,
    wrap_self: impl Fn(PropertyPlaceholder<C>) -> L::Property,
) -> TemplateParseResult<TemplateRenderer<'a, C>> {
    let node = template_parser::parse(template_text, aliases_map)?;
    build(language, &node, wrap_self).map_err(|err| err.extend_alias_candidates(aliases_map))
}

pub fn expect_boolean_expression<'a, L: TemplateLanguage<'a> + ?Sized>(
    language: &L,
    build_ctx: &BuildContext<L::Property>,
    node: &ExpressionNode,
) -> TemplateParseResult<Box<dyn TemplateProperty<Output = bool> + 'a>> {
    expect_expression_of_type(language, build_ctx, node, "Boolean", |expression| {
        expression.try_into_boolean()
    })
}

pub fn expect_integer_expression<'a, L: TemplateLanguage<'a> + ?Sized>(
    language: &L,
    build_ctx: &BuildContext<L::Property>,
    node: &ExpressionNode,
) -> TemplateParseResult<Box<dyn TemplateProperty<Output = i64> + 'a>> {
    expect_expression_of_type(language, build_ctx, node, "Integer", |expression| {
        expression.try_into_integer()
    })
}

/// If the given expression `node` is of `Integer` type, converts it to `isize`.
pub fn expect_isize_expression<'a, L: TemplateLanguage<'a> + ?Sized>(
    language: &L,
    build_ctx: &BuildContext<L::Property>,
    node: &ExpressionNode,
) -> TemplateParseResult<Box<dyn TemplateProperty<Output = isize> + 'a>> {
    let i64_property = expect_integer_expression(language, build_ctx, node)?;
    let isize_property = i64_property.and_then(|v| Ok(isize::try_from(v)?));
    Ok(Box::new(isize_property))
}

/// If the given expression `node` is of `Integer` type, converts it to `usize`.
pub fn expect_usize_expression<'a, L: TemplateLanguage<'a> + ?Sized>(
    language: &L,
    build_ctx: &BuildContext<L::Property>,
    node: &ExpressionNode,
) -> TemplateParseResult<Box<dyn TemplateProperty<Output = usize> + 'a>> {
    let i64_property = expect_integer_expression(language, build_ctx, node)?;
    let usize_property = i64_property.and_then(|v| Ok(usize::try_from(v)?));
    Ok(Box::new(usize_property))
}

pub fn expect_plain_text_expression<'a, L: TemplateLanguage<'a> + ?Sized>(
    language: &L,
    build_ctx: &BuildContext<L::Property>,
    node: &ExpressionNode,
) -> TemplateParseResult<Box<dyn TemplateProperty<Output = String> + 'a>> {
    // Since any formattable type can be converted to a string property,
    // the expected type is not a String, but a Template.
    expect_expression_of_type(language, build_ctx, node, "Template", |expression| {
        expression.try_into_plain_text()
    })
}

pub fn expect_template_expression<'a, L: TemplateLanguage<'a> + ?Sized>(
    language: &L,
    build_ctx: &BuildContext<L::Property>,
    node: &ExpressionNode,
) -> TemplateParseResult<Box<dyn Template + 'a>> {
    expect_expression_of_type(language, build_ctx, node, "Template", |expression| {
        expression.try_into_template()
    })
}

fn expect_expression_of_type<'a, L: TemplateLanguage<'a> + ?Sized, T>(
    language: &L,
    build_ctx: &BuildContext<L::Property>,
    node: &ExpressionNode,
    expected_type: &str,
    f: impl FnOnce(Expression<L::Property>) -> Option<T>,
) -> TemplateParseResult<T> {
    if let ExpressionKind::AliasExpanded(id, subst) = &node.kind {
        expect_expression_of_type(language, build_ctx, subst, expected_type, f)
            .map_err(|e| e.within_alias_expansion(*id, node.span))
    } else {
        let expression = build_expression(language, build_ctx, node)?;
        let actual_type = expression.type_name();
        f(expression)
            .ok_or_else(|| TemplateParseError::expected_type(expected_type, actual_type, node.span))
    }
}

#[cfg(test)]
mod tests {
    use std::iter;

    use jj_lib::backend::MillisSinceEpoch;

    use super::*;
    use crate::formatter::{self, ColorFormatter};
    use crate::generic_templater::GenericTemplateLanguage;

    type L = GenericTemplateLanguage<'static, ()>;
    type TestTemplatePropertyKind = <L as TemplateLanguage<'static>>::Property;

    /// Helper to set up template evaluation environment.
    struct TestTemplateEnv {
        language: L,
        aliases_map: TemplateAliasesMap,
        color_rules: Vec<(Vec<String>, formatter::Style)>,
    }

    impl TestTemplateEnv {
        fn new() -> Self {
            TestTemplateEnv {
                language: L::new(),
                aliases_map: TemplateAliasesMap::new(),
                color_rules: Vec::new(),
            }
        }
    }

    impl TestTemplateEnv {
        fn add_keyword<F>(&mut self, name: &'static str, build: F)
        where
            F: Fn() -> TestTemplatePropertyKind + 'static,
        {
            self.language.add_keyword(name, move |_| Ok(build()));
        }

        fn add_alias(&mut self, decl: impl AsRef<str>, defn: impl Into<String>) {
            self.aliases_map.insert(decl, defn).unwrap();
        }

        fn add_color(&mut self, label: &str, fg_color: crossterm::style::Color) {
            let labels = label.split_whitespace().map(|s| s.to_owned()).collect();
            let style = formatter::Style {
                fg_color: Some(fg_color),
                ..Default::default()
            };
            self.color_rules.push((labels, style));
        }

        fn parse(&self, template: &str) -> TemplateParseResult<TemplateRenderer<'static, ()>> {
            parse(&self.language, template, &self.aliases_map, L::wrap_self)
        }

        fn parse_err(&self, template: &str) -> String {
            let err = self.parse(template).err().unwrap();
            iter::successors(Some(&err), |e| e.origin()).join("\n")
        }

        fn render_ok(&self, template: &str) -> String {
            let template = self.parse(template).unwrap();
            let mut output = Vec::new();
            let mut formatter =
                ColorFormatter::new(&mut output, self.color_rules.clone().into(), false);
            template.format(&(), &mut formatter).unwrap();
            drop(formatter);
            String::from_utf8(output).unwrap()
        }
    }

    fn new_error_property<O>(message: &str) -> impl TemplateProperty<Output = O> + '_ {
        Literal(()).and_then(|()| Err(TemplatePropertyError(message.into())))
    }

    fn new_signature(name: &str, email: &str) -> Signature {
        Signature {
            name: name.to_owned(),
            email: email.to_owned(),
            timestamp: new_timestamp(0, 0),
        }
    }

    fn new_timestamp(msec: i64, tz_offset: i32) -> Timestamp {
        Timestamp {
            timestamp: MillisSinceEpoch(msec),
            tz_offset,
        }
    }

    #[test]
    fn test_parsed_tree() {
        let mut env = TestTemplateEnv::new();
        env.add_keyword("divergent", || L::wrap_boolean(Literal(false)));
        env.add_keyword("empty", || L::wrap_boolean(Literal(true)));
        env.add_keyword("hello", || L::wrap_string(Literal("Hello".to_owned())));

        // Empty
        insta::assert_snapshot!(env.render_ok(r#"  "#), @"");

        // Single term with whitespace
        insta::assert_snapshot!(env.render_ok(r#"  hello.upper()  "#), @"HELLO");

        // Multiple terms
        insta::assert_snapshot!(env.render_ok(r#"  hello.upper()  ++ true "#), @"HELLOtrue");

        // Parenthesized single term
        insta::assert_snapshot!(env.render_ok(r#"(hello.upper())"#), @"HELLO");

        // Parenthesized multiple terms and concatenation
        insta::assert_snapshot!(env.render_ok(r#"(hello.upper() ++ " ") ++ empty"#), @"HELLO true");

        // Parenthesized "if" condition
        insta::assert_snapshot!(env.render_ok(r#"if((divergent), "t", "f")"#), @"f");

        // Parenthesized method chaining
        insta::assert_snapshot!(env.render_ok(r#"(hello).upper()"#), @"HELLO");
    }

    #[test]
    fn test_parse_error() {
        let mut env = TestTemplateEnv::new();
        env.add_keyword("description", || L::wrap_string(Literal("".to_owned())));
        env.add_keyword("empty", || L::wrap_boolean(Literal(true)));

        insta::assert_snapshot!(env.parse_err(r#"description ()"#), @r###"
         --> 1:13
          |
        1 | description ()
          |             ^---
          |
          = expected <EOI>, `++`, `||`, or `&&`
        "###);

        insta::assert_snapshot!(env.parse_err(r#"foo"#), @r###"
         --> 1:1
          |
        1 | foo
          | ^-^
          |
          = Keyword "foo" doesn't exist
        "###);

        insta::assert_snapshot!(env.parse_err(r#"foo()"#), @r###"
         --> 1:1
          |
        1 | foo()
          | ^-^
          |
          = Function "foo" doesn't exist
        "###);
        insta::assert_snapshot!(env.parse_err(r#"false()"#), @r###"
         --> 1:1
          |
        1 | false()
          | ^---^
          |
          = Expected identifier
        "###);

        insta::assert_snapshot!(env.parse_err(r#"!foo"#), @r###"
         --> 1:2
          |
        1 | !foo
          |  ^-^
          |
          = Keyword "foo" doesn't exist
        "###);
        insta::assert_snapshot!(env.parse_err(r#"true && 123"#), @r###"
         --> 1:9
          |
        1 | true && 123
          |         ^-^
          |
          = Expected expression of type "Boolean", but actual type is "Integer"
        "###);

        insta::assert_snapshot!(env.parse_err(r#"description.first_line().foo()"#), @r###"
         --> 1:26
          |
        1 | description.first_line().foo()
          |                          ^-^
          |
          = Method "foo" doesn't exist for type "String"
        "###);

        insta::assert_snapshot!(env.parse_err(r#"10000000000000000000"#), @r###"
         --> 1:1
          |
        1 | 10000000000000000000
          | ^------------------^
          |
          = Invalid integer literal
        "###);
        insta::assert_snapshot!(env.parse_err(r#"42.foo()"#), @r###"
         --> 1:4
          |
        1 | 42.foo()
          |    ^-^
          |
          = Method "foo" doesn't exist for type "Integer"
        "###);
        insta::assert_snapshot!(env.parse_err(r#"(-empty)"#), @r###"
         --> 1:3
          |
        1 | (-empty)
          |   ^---^
          |
          = Expected expression of type "Integer", but actual type is "Boolean"
        "###);

        insta::assert_snapshot!(env.parse_err(r#"("foo" ++ "bar").baz()"#), @r###"
         --> 1:18
          |
        1 | ("foo" ++ "bar").baz()
          |                  ^-^
          |
          = Method "baz" doesn't exist for type "Template"
        "###);

        insta::assert_snapshot!(env.parse_err(r#"description.contains()"#), @r###"
         --> 1:22
          |
        1 | description.contains()
          |                      ^
          |
          = Function "contains": Expected 1 arguments
        "###);

        insta::assert_snapshot!(env.parse_err(r#"description.first_line("foo")"#), @r###"
         --> 1:24
          |
        1 | description.first_line("foo")
          |                        ^---^
          |
          = Function "first_line": Expected 0 arguments
        "###);

        insta::assert_snapshot!(env.parse_err(r#"label()"#), @r###"
         --> 1:7
          |
        1 | label()
          |       ^
          |
          = Function "label": Expected 2 arguments
        "###);
        insta::assert_snapshot!(env.parse_err(r#"label("foo", "bar", "baz")"#), @r###"
         --> 1:7
          |
        1 | label("foo", "bar", "baz")
          |       ^-----------------^
          |
          = Function "label": Expected 2 arguments
        "###);

        insta::assert_snapshot!(env.parse_err(r#"if()"#), @r###"
         --> 1:4
          |
        1 | if()
          |    ^
          |
          = Function "if": Expected 2 to 3 arguments
        "###);
        insta::assert_snapshot!(env.parse_err(r#"if("foo", "bar", "baz", "quux")"#), @r###"
         --> 1:4
          |
        1 | if("foo", "bar", "baz", "quux")
          |    ^-------------------------^
          |
          = Function "if": Expected 2 to 3 arguments
        "###);

        insta::assert_snapshot!(env.parse_err(r#"if(label("foo", "bar"), "baz")"#), @r###"
         --> 1:4
          |
        1 | if(label("foo", "bar"), "baz")
          |    ^-----------------^
          |
          = Expected expression of type "Boolean", but actual type is "Template"
        "###);

        insta::assert_snapshot!(env.parse_err(r#"|x| description"#), @r###"
         --> 1:1
          |
        1 | |x| description
          | ^-------------^
          |
          = Lambda cannot be defined here
        "###);
    }

    #[test]
    fn test_self_keyword() {
        let mut env = TestTemplateEnv::new();
        env.add_keyword("say_hello", || L::wrap_string(Literal("Hello".to_owned())));

        insta::assert_snapshot!(env.render_ok(r#"self.say_hello()"#), @"Hello");
        insta::assert_snapshot!(env.parse_err(r#"self"#), @r###"
         --> 1:1
          |
        1 | self
          | ^--^
          |
          = Expected expression of type "Template", but actual type is "Self"
        "###);
    }

    #[test]
    fn test_boolean_cast() {
        let mut env = TestTemplateEnv::new();

        insta::assert_snapshot!(env.render_ok(r#"if("", true, false)"#), @"false");
        insta::assert_snapshot!(env.render_ok(r#"if("a", true, false)"#), @"true");

        env.add_keyword("sl0", || {
            L::wrap_string_list(Literal::<Vec<String>>(vec![]))
        });
        env.add_keyword("sl1", || L::wrap_string_list(Literal(vec!["".to_owned()])));
        insta::assert_snapshot!(env.render_ok(r#"if(sl0, true, false)"#), @"false");
        insta::assert_snapshot!(env.render_ok(r#"if(sl1, true, false)"#), @"true");

        // No implicit cast of integer
        insta::assert_snapshot!(env.parse_err(r#"if(0, true, false)"#), @r###"
         --> 1:4
          |
        1 | if(0, true, false)
          |    ^
          |
          = Expected expression of type "Boolean", but actual type is "Integer"
        "###);

        // Optional integer can be converted to boolean, and Some(0) is truthy.
        env.add_keyword("none_i64", || L::wrap_integer_opt(Literal(None)));
        env.add_keyword("some_i64", || L::wrap_integer_opt(Literal(Some(0))));
        insta::assert_snapshot!(env.render_ok(r#"if(none_i64, true, false)"#), @"false");
        insta::assert_snapshot!(env.render_ok(r#"if(some_i64, true, false)"#), @"true");

        insta::assert_snapshot!(env.parse_err(r#"if(label("", ""), true, false)"#), @r###"
         --> 1:4
          |
        1 | if(label("", ""), true, false)
          |    ^-----------^
          |
          = Expected expression of type "Boolean", but actual type is "Template"
        "###);
        insta::assert_snapshot!(env.parse_err(r#"if(sl0.map(|x| x), true, false)"#), @r###"
         --> 1:4
          |
        1 | if(sl0.map(|x| x), true, false)
          |    ^------------^
          |
          = Expected expression of type "Boolean", but actual type is "ListTemplate"
        "###);
    }

    #[test]
    fn test_arithmetic_operation() {
        let mut env = TestTemplateEnv::new();
        env.add_keyword("none_i64", || L::wrap_integer_opt(Literal(None)));
        env.add_keyword("some_i64", || L::wrap_integer_opt(Literal(Some(1))));
        env.add_keyword("i64_min", || L::wrap_integer(Literal(i64::MIN)));

        insta::assert_snapshot!(env.render_ok(r#"-1"#), @"-1");
        insta::assert_snapshot!(env.render_ok(r#"--2"#), @"2");
        insta::assert_snapshot!(env.render_ok(r#"-(3)"#), @"-3");

        // Since methods of the contained value can be invoked, it makes sense
        // to apply operators to optional integers as well.
        insta::assert_snapshot!(env.render_ok(r#"-none_i64"#), @"<Error: No Integer available>");
        insta::assert_snapshot!(env.render_ok(r#"-some_i64"#), @"-1");

        // No panic on integer overflow.
        insta::assert_snapshot!(
            env.render_ok(r#"-i64_min"#),
            @"<Error: Attempt to negate with overflow>");
    }

    #[test]
    fn test_logical_operation() {
        let mut env = TestTemplateEnv::new();

        insta::assert_snapshot!(env.render_ok(r#"!false"#), @"true");
        insta::assert_snapshot!(env.render_ok(r#"false || !false"#), @"true");
        insta::assert_snapshot!(env.render_ok(r#"false && true"#), @"false");

        insta::assert_snapshot!(env.render_ok(r#" !"" "#), @"true");
        insta::assert_snapshot!(env.render_ok(r#" "" || "a".lines() "#), @"true");

        // Short-circuiting
        env.add_keyword("bad_bool", || L::wrap_boolean(new_error_property("Bad")));
        insta::assert_snapshot!(env.render_ok(r#"false && bad_bool"#), @"false");
        insta::assert_snapshot!(env.render_ok(r#"true && bad_bool"#), @"<Error: Bad>");
        insta::assert_snapshot!(env.render_ok(r#"false || bad_bool"#), @"<Error: Bad>");
        insta::assert_snapshot!(env.render_ok(r#"true || bad_bool"#), @"true");
    }

    #[test]
    fn test_list_method() {
        let mut env = TestTemplateEnv::new();
        env.add_keyword("empty", || L::wrap_boolean(Literal(true)));
        env.add_keyword("sep", || L::wrap_string(Literal("sep".to_owned())));

        insta::assert_snapshot!(env.render_ok(r#""".lines().len()"#), @"0");
        insta::assert_snapshot!(env.render_ok(r#""a\nb\nc".lines().len()"#), @"3");

        insta::assert_snapshot!(env.render_ok(r#""".lines().join("|")"#), @"");
        insta::assert_snapshot!(env.render_ok(r#""a\nb\nc".lines().join("|")"#), @"a|b|c");
        // Null separator
        insta::assert_snapshot!(env.render_ok(r#""a\nb\nc".lines().join("\0")"#), @"a\0b\0c");
        // Keyword as separator
        insta::assert_snapshot!(
            env.render_ok(r#""a\nb\nc".lines().join(sep.upper())"#),
            @"aSEPbSEPc");

        insta::assert_snapshot!(
            env.render_ok(r#""a\nb\nc".lines().map(|s| s ++ s)"#),
            @"aa bb cc");
        // Global keyword in item template
        insta::assert_snapshot!(
            env.render_ok(r#""a\nb\nc".lines().map(|s| s ++ empty)"#),
            @"atrue btrue ctrue");
        // Global keyword in item template shadowing 'self'
        insta::assert_snapshot!(
            env.render_ok(r#""a\nb\nc".lines().map(|self| self ++ empty)"#),
            @"atrue btrue ctrue");
        // Override global keyword 'empty'
        insta::assert_snapshot!(
            env.render_ok(r#""a\nb\nc".lines().map(|empty| empty)"#),
            @"a b c");
        // Nested map operations
        insta::assert_snapshot!(
            env.render_ok(r#""a\nb\nc".lines().map(|s| "x\ny".lines().map(|t| s ++ t))"#),
            @"ax ay bx by cx cy");
        // Nested map/join operations
        insta::assert_snapshot!(
            env.render_ok(r#""a\nb\nc".lines().map(|s| "x\ny".lines().map(|t| s ++ t).join(",")).join(";")"#),
            @"ax,ay;bx,by;cx,cy");
        // Nested string operations
        insta::assert_snapshot!(
            env.render_ok(r#""!a\n!b\nc\nend".remove_suffix("end").lines().map(|s| s.remove_prefix("!"))"#),
            @"a b c");

        // Lambda expression in alias
        env.add_alias("identity", "|x| x");
        insta::assert_snapshot!(env.render_ok(r#""a\nb\nc".lines().map(identity)"#), @"a b c");

        // Not a lambda expression
        insta::assert_snapshot!(env.parse_err(r#""a".lines().map(empty)"#), @r###"
         --> 1:17
          |
        1 | "a".lines().map(empty)
          |                 ^---^
          |
          = Expected lambda expression
        "###);
        // Bad lambda parameter count
        insta::assert_snapshot!(env.parse_err(r#""a".lines().map(|| "")"#), @r###"
         --> 1:18
          |
        1 | "a".lines().map(|| "")
          |                  ^
          |
          = Expected 1 lambda parameters
        "###);
        insta::assert_snapshot!(env.parse_err(r#""a".lines().map(|a, b| "")"#), @r###"
         --> 1:18
          |
        1 | "a".lines().map(|a, b| "")
          |                  ^--^
          |
          = Expected 1 lambda parameters
        "###);
        // Error in lambda expression
        insta::assert_snapshot!(env.parse_err(r#""a".lines().map(|s| s.unknown())"#), @r###"
         --> 1:23
          |
        1 | "a".lines().map(|s| s.unknown())
          |                       ^-----^
          |
          = Method "unknown" doesn't exist for type "String"
        "###);
        // Error in lambda alias
        env.add_alias("too_many_params", "|x, y| x");
        insta::assert_snapshot!(env.parse_err(r#""a".lines().map(too_many_params)"#), @r###"
         --> 1:17
          |
        1 | "a".lines().map(too_many_params)
          |                 ^-------------^
          |
          = Alias "too_many_params" cannot be expanded
         --> 1:2
          |
        1 | |x, y| x
          |  ^--^
          |
          = Expected 1 lambda parameters
        "###);
    }

    #[test]
    fn test_string_method() {
        let mut env = TestTemplateEnv::new();
        env.add_keyword("description", || {
            L::wrap_string(Literal("description 1".to_owned()))
        });
        env.add_keyword("bad_string", || L::wrap_string(new_error_property("Bad")));

        insta::assert_snapshot!(env.render_ok(r#""".len()"#), @"0");
        insta::assert_snapshot!(env.render_ok(r#""foo".len()"#), @"3");
        insta::assert_snapshot!(env.render_ok(r#""💩".len()"#), @"4");

        insta::assert_snapshot!(env.render_ok(r#""fooo".contains("foo")"#), @"true");
        insta::assert_snapshot!(env.render_ok(r#""foo".contains("fooo")"#), @"false");
        insta::assert_snapshot!(env.render_ok(r#"description.contains("description")"#), @"true");
        insta::assert_snapshot!(
            env.render_ok(r#""description 123".contains(description.first_line())"#),
            @"true");

        // inner template error should propagate
        insta::assert_snapshot!(env.render_ok(r#""foo".contains(bad_string)"#), @"<Error: Bad>");
        insta::assert_snapshot!(
            env.render_ok(r#""foo".contains("f" ++ bad_string) ++ "bar""#), @"<Error: Bad>bar");
        insta::assert_snapshot!(
            env.render_ok(r#""foo".contains(separate("o", "f", bad_string))"#), @"<Error: Bad>");

        insta::assert_snapshot!(env.render_ok(r#""".first_line()"#), @"");
        insta::assert_snapshot!(env.render_ok(r#""foo\nbar".first_line()"#), @"foo");

        insta::assert_snapshot!(env.render_ok(r#""".lines()"#), @"");
        insta::assert_snapshot!(env.render_ok(r#""a\nb\nc\n".lines()"#), @"a b c");

        insta::assert_snapshot!(env.render_ok(r#""".starts_with("")"#), @"true");
        insta::assert_snapshot!(env.render_ok(r#""everything".starts_with("")"#), @"true");
        insta::assert_snapshot!(env.render_ok(r#""".starts_with("foo")"#), @"false");
        insta::assert_snapshot!(env.render_ok(r#""foo".starts_with("foo")"#), @"true");
        insta::assert_snapshot!(env.render_ok(r#""foobar".starts_with("foo")"#), @"true");
        insta::assert_snapshot!(env.render_ok(r#""foobar".starts_with("bar")"#), @"false");

        insta::assert_snapshot!(env.render_ok(r#""".ends_with("")"#), @"true");
        insta::assert_snapshot!(env.render_ok(r#""everything".ends_with("")"#), @"true");
        insta::assert_snapshot!(env.render_ok(r#""".ends_with("foo")"#), @"false");
        insta::assert_snapshot!(env.render_ok(r#""foo".ends_with("foo")"#), @"true");
        insta::assert_snapshot!(env.render_ok(r#""foobar".ends_with("foo")"#), @"false");
        insta::assert_snapshot!(env.render_ok(r#""foobar".ends_with("bar")"#), @"true");

        insta::assert_snapshot!(env.render_ok(r#""".remove_prefix("wip: ")"#), @"");
        insta::assert_snapshot!(
            env.render_ok(r#""wip: testing".remove_prefix("wip: ")"#),
            @"testing");

        insta::assert_snapshot!(
            env.render_ok(r#""bar@my.example.com".remove_suffix("@other.example.com")"#),
            @"bar@my.example.com");
        insta::assert_snapshot!(
            env.render_ok(r#""bar@other.example.com".remove_suffix("@other.example.com")"#),
            @"bar");

        insta::assert_snapshot!(env.render_ok(r#""foo".substr(0, 0)"#), @"");
        insta::assert_snapshot!(env.render_ok(r#""foo".substr(0, 1)"#), @"f");
        insta::assert_snapshot!(env.render_ok(r#""foo".substr(0, 3)"#), @"foo");
        insta::assert_snapshot!(env.render_ok(r#""foo".substr(0, 4)"#), @"foo");
        insta::assert_snapshot!(env.render_ok(r#""abcdef".substr(2, -1)"#), @"cde");
        insta::assert_snapshot!(env.render_ok(r#""abcdef".substr(-3, 99)"#), @"def");
        insta::assert_snapshot!(env.render_ok(r#""abcdef".substr(-6, 99)"#), @"abcdef");
        insta::assert_snapshot!(env.render_ok(r#""abcdef".substr(-7, 1)"#), @"a");

        // non-ascii characters
        insta::assert_snapshot!(env.render_ok(r#""abc💩".substr(2, -1)"#), @"c💩");
        insta::assert_snapshot!(env.render_ok(r#""abc💩".substr(3, -3)"#), @"💩");
        insta::assert_snapshot!(env.render_ok(r#""abc💩".substr(3, -4)"#), @"");
        insta::assert_snapshot!(env.render_ok(r#""abc💩".substr(6, -3)"#), @"💩");
        insta::assert_snapshot!(env.render_ok(r#""abc💩".substr(7, -3)"#), @"");
        insta::assert_snapshot!(env.render_ok(r#""abc💩".substr(3, 4)"#), @"");
        insta::assert_snapshot!(env.render_ok(r#""abc💩".substr(3, 6)"#), @"");
        insta::assert_snapshot!(env.render_ok(r#""abc💩".substr(3, 7)"#), @"💩");
        insta::assert_snapshot!(env.render_ok(r#""abc💩".substr(-1, 7)"#), @"");
        insta::assert_snapshot!(env.render_ok(r#""abc💩".substr(-3, 7)"#), @"");
        insta::assert_snapshot!(env.render_ok(r#""abc💩".substr(-4, 7)"#), @"💩");

        // ranges with end > start are empty
        insta::assert_snapshot!(env.render_ok(r#""abcdef".substr(4, 2)"#), @"");
        insta::assert_snapshot!(env.render_ok(r#""abcdef".substr(-2, -4)"#), @"");
    }

    #[test]
    fn test_signature() {
        let mut env = TestTemplateEnv::new();

        env.add_keyword("author", || {
            L::wrap_signature(Literal(new_signature("Test User", "test.user@example.com")))
        });
        insta::assert_snapshot!(env.render_ok(r#"author"#), @"Test User <test.user@example.com>");
        insta::assert_snapshot!(env.render_ok(r#"author.name()"#), @"Test User");
        insta::assert_snapshot!(env.render_ok(r#"author.email()"#), @"test.user@example.com");
        insta::assert_snapshot!(env.render_ok(r#"author.username()"#), @"test.user");

        env.add_keyword("author", || {
            L::wrap_signature(Literal(new_signature(
                "Another Test User",
                "test.user@example.com",
            )))
        });
        insta::assert_snapshot!(env.render_ok(r#"author"#), @"Another Test User <test.user@example.com>");
        insta::assert_snapshot!(env.render_ok(r#"author.name()"#), @"Another Test User");
        insta::assert_snapshot!(env.render_ok(r#"author.email()"#), @"test.user@example.com");
        insta::assert_snapshot!(env.render_ok(r#"author.username()"#), @"test.user");

        env.add_keyword("author", || {
            L::wrap_signature(Literal(new_signature(
                "Test User",
                "test.user@invalid@example.com",
            )))
        });
        insta::assert_snapshot!(env.render_ok(r#"author"#), @"Test User <test.user@invalid@example.com>");
        insta::assert_snapshot!(env.render_ok(r#"author.name()"#), @"Test User");
        insta::assert_snapshot!(env.render_ok(r#"author.email()"#), @"test.user@invalid@example.com");
        insta::assert_snapshot!(env.render_ok(r#"author.username()"#), @"test.user");

        env.add_keyword("author", || {
            L::wrap_signature(Literal(new_signature("Test User", "test.user")))
        });
        insta::assert_snapshot!(env.render_ok(r#"author"#), @"Test User <test.user>");
        insta::assert_snapshot!(env.render_ok(r#"author.email()"#), @"test.user");
        insta::assert_snapshot!(env.render_ok(r#"author.username()"#), @"test.user");

        env.add_keyword("author", || {
            L::wrap_signature(Literal(new_signature(
                "Test User",
                "test.user+tag@example.com",
            )))
        });
        insta::assert_snapshot!(env.render_ok(r#"author"#), @"Test User <test.user+tag@example.com>");
        insta::assert_snapshot!(env.render_ok(r#"author.email()"#), @"test.user+tag@example.com");
        insta::assert_snapshot!(env.render_ok(r#"author.username()"#), @"test.user+tag");

        env.add_keyword("author", || {
            L::wrap_signature(Literal(new_signature("Test User", "x@y")))
        });
        insta::assert_snapshot!(env.render_ok(r#"author"#), @"Test User <x@y>");
        insta::assert_snapshot!(env.render_ok(r#"author.email()"#), @"x@y");
        insta::assert_snapshot!(env.render_ok(r#"author.username()"#), @"x");

        env.add_keyword("author", || {
            L::wrap_signature(Literal(new_signature("", "test.user@example.com")))
        });
        insta::assert_snapshot!(env.render_ok(r#"author"#), @"<test.user@example.com>");
        insta::assert_snapshot!(env.render_ok(r#"author.name()"#), @"");
        insta::assert_snapshot!(env.render_ok(r#"author.email()"#), @"test.user@example.com");
        insta::assert_snapshot!(env.render_ok(r#"author.username()"#), @"test.user");

        env.add_keyword("author", || {
            L::wrap_signature(Literal(new_signature("Test User", "")))
        });
        insta::assert_snapshot!(env.render_ok(r#"author"#), @"Test User");
        insta::assert_snapshot!(env.render_ok(r#"author.name()"#), @"Test User");
        insta::assert_snapshot!(env.render_ok(r#"author.email()"#), @"");
        insta::assert_snapshot!(env.render_ok(r#"author.username()"#), @"");

        env.add_keyword("author", || {
            L::wrap_signature(Literal(new_signature("", "")))
        });
        insta::assert_snapshot!(env.render_ok(r#"author"#), @"");
        insta::assert_snapshot!(env.render_ok(r#"author.name()"#), @"");
        insta::assert_snapshot!(env.render_ok(r#"author.email()"#), @"");
        insta::assert_snapshot!(env.render_ok(r#"author.username()"#), @"");
    }

    #[test]
    fn test_size_hint_method() {
        let mut env = TestTemplateEnv::new();

        env.add_keyword("unbounded", || L::wrap_size_hint(Literal((5, None))));
        insta::assert_snapshot!(env.render_ok(r#"unbounded.lower()"#), @"5");
        insta::assert_snapshot!(env.render_ok(r#"unbounded.upper()"#), @"");
        insta::assert_snapshot!(env.render_ok(r#"unbounded.exact()"#), @"");
        insta::assert_snapshot!(env.render_ok(r#"unbounded.zero()"#), @"false");

        env.add_keyword("bounded", || L::wrap_size_hint(Literal((0, Some(10)))));
        insta::assert_snapshot!(env.render_ok(r#"bounded.lower()"#), @"0");
        insta::assert_snapshot!(env.render_ok(r#"bounded.upper()"#), @"10");
        insta::assert_snapshot!(env.render_ok(r#"bounded.exact()"#), @"");
        insta::assert_snapshot!(env.render_ok(r#"bounded.zero()"#), @"false");

        env.add_keyword("zero", || L::wrap_size_hint(Literal((0, Some(0)))));
        insta::assert_snapshot!(env.render_ok(r#"zero.lower()"#), @"0");
        insta::assert_snapshot!(env.render_ok(r#"zero.upper()"#), @"0");
        insta::assert_snapshot!(env.render_ok(r#"zero.exact()"#), @"0");
        insta::assert_snapshot!(env.render_ok(r#"zero.zero()"#), @"true");
    }

    #[test]
    fn test_timestamp_method() {
        let mut env = TestTemplateEnv::new();
        env.add_keyword("t0", || L::wrap_timestamp(Literal(new_timestamp(0, 0))));

        insta::assert_snapshot!(
            env.render_ok(r#"t0.format("%Y%m%d %H:%M:%S")"#),
            @"19700101 00:00:00");

        // Invalid format string
        insta::assert_snapshot!(env.parse_err(r#"t0.format("%_")"#), @r###"
         --> 1:11
          |
        1 | t0.format("%_")
          |           ^--^
          |
          = Invalid time format
        "###);

        // Invalid type
        insta::assert_snapshot!(env.parse_err(r#"t0.format(0)"#), @r###"
         --> 1:11
          |
        1 | t0.format(0)
          |           ^
          |
          = Expected string literal
        "###);

        // Dynamic string isn't supported yet
        insta::assert_snapshot!(env.parse_err(r#"t0.format("%Y" ++ "%m")"#), @r###"
         --> 1:11
          |
        1 | t0.format("%Y" ++ "%m")
          |           ^----------^
          |
          = Expected string literal
        "###);

        // Literal alias expansion
        env.add_alias("time_format", r#""%Y-%m-%d""#);
        env.add_alias("bad_time_format", r#""%_""#);
        insta::assert_snapshot!(env.render_ok(r#"t0.format(time_format)"#), @"1970-01-01");
        insta::assert_snapshot!(env.parse_err(r#"t0.format(bad_time_format)"#), @r###"
         --> 1:11
          |
        1 | t0.format(bad_time_format)
          |           ^-------------^
          |
          = Alias "bad_time_format" cannot be expanded
         --> 1:1
          |
        1 | "%_"
          | ^--^
          |
          = Invalid time format
        "###);
    }

    #[test]
    fn test_fill_function() {
        let mut env = TestTemplateEnv::new();
        env.add_color("error", crossterm::style::Color::DarkRed);

        insta::assert_snapshot!(
            env.render_ok(r#"fill(20, "The quick fox jumps over the " ++
                                  label("error", "lazy") ++ " dog\n")"#),
            @r###"
        The quick fox jumps
        over the lazy dog
        "###);

        // A low value will not chop words, but can chop a label by words
        insta::assert_snapshot!(
            env.render_ok(r#"fill(9, "Longlonglongword an some short words " ++
                                  label("error", "longlonglongword and short words") ++
                                  " back out\n")"#),
            @r###"
        Longlonglongword
        an some
        short
        words
        longlonglongword
        and short
        words
        back out
        "###);

        // Filling to 0 means breaking at every word
        insta::assert_snapshot!(
            env.render_ok(r#"fill(0, "The quick fox jumps over the " ++
                                  label("error", "lazy") ++ " dog\n")"#),
            @r###"
        The
        quick
        fox
        jumps
        over
        the
        lazy
        dog
        "###);

        // Filling to -0 is the same as 0
        insta::assert_snapshot!(
            env.render_ok(r#"fill(-0, "The quick fox jumps over the " ++
                                  label("error", "lazy") ++ " dog\n")"#),
            @r###"
        The
        quick
        fox
        jumps
        over
        the
        lazy
        dog
        "###);

        // Filling to negative width is an error
        insta::assert_snapshot!(
            env.render_ok(r#"fill(-10, "The quick fox jumps over the " ++
                                  label("error", "lazy") ++ " dog\n")"#),
            @"<Error: out of range integral type conversion attempted>");

        // Word-wrap, then indent
        insta::assert_snapshot!(
            env.render_ok(r#""START marker to help insta\n" ++
                             indent("    ", fill(20, "The quick fox jumps over the " ++
                                                 label("error", "lazy") ++ " dog\n"))"#),
            @r###"
        START marker to help insta
            The quick fox jumps
            over the lazy dog
        "###);

        // Word-wrap indented (no special handling for leading spaces)
        insta::assert_snapshot!(
            env.render_ok(r#""START marker to help insta\n" ++
                             fill(20, indent("    ", "The quick fox jumps over the " ++
                                             label("error", "lazy") ++ " dog\n"))"#),
            @r###"
        START marker to help insta
            The quick fox
        jumps over the lazy
        dog
        "###);
    }

    #[test]
    fn test_indent_function() {
        let mut env = TestTemplateEnv::new();
        env.add_color("error", crossterm::style::Color::DarkRed);
        env.add_color("warning", crossterm::style::Color::DarkYellow);
        env.add_color("hint", crossterm::style::Color::DarkCyan);

        // Empty line shouldn't be indented. Not using insta here because we test
        // whitespace existence.
        assert_eq!(env.render_ok(r#"indent("__", "")"#), "");
        assert_eq!(env.render_ok(r#"indent("__", "\n")"#), "\n");
        assert_eq!(env.render_ok(r#"indent("__", "a\n\nb")"#), "__a\n\n__b");

        // "\n" at end of labeled text
        insta::assert_snapshot!(
            env.render_ok(r#"indent("__", label("error", "a\n") ++ label("warning", "b\n"))"#),
            @r###"
        __a
        __b
        "###);

        // "\n" in labeled text
        insta::assert_snapshot!(
            env.render_ok(r#"indent("__", label("error", "a") ++ label("warning", "b\nc"))"#),
            @r###"
        __ab
        __c
        "###);

        // Labeled prefix + unlabeled content
        insta::assert_snapshot!(
            env.render_ok(r#"indent(label("error", "XX"), "a\nb\n")"#),
            @r###"
        XXa
        XXb
        "###);

        // Nested indent, silly but works
        insta::assert_snapshot!(
            env.render_ok(r#"indent(label("hint", "A"),
                                    label("warning", indent(label("hint", "B"),
                                                            label("error", "x\n") ++ "y")))"#),
            @r###"
        ABx
        ABy
        "###);
    }

    #[test]
    fn test_label_function() {
        let mut env = TestTemplateEnv::new();
        env.add_keyword("empty", || L::wrap_boolean(Literal(true)));
        env.add_color("error", crossterm::style::Color::DarkRed);
        env.add_color("warning", crossterm::style::Color::DarkYellow);

        // Literal
        insta::assert_snapshot!(
            env.render_ok(r#"label("error", "text")"#),
            @"text");

        // Evaluated property
        insta::assert_snapshot!(
            env.render_ok(r#"label("error".first_line(), "text")"#),
            @"text");

        // Template
        insta::assert_snapshot!(
            env.render_ok(r#"label(if(empty, "error", "warning"), "text")"#),
            @"text");
    }

    #[test]
    fn test_coalesce_function() {
        let mut env = TestTemplateEnv::new();
        env.add_keyword("bad_string", || L::wrap_string(new_error_property("Bad")));
        env.add_keyword("empty_string", || L::wrap_string(Literal("".to_owned())));
        env.add_keyword("non_empty_string", || {
            L::wrap_string(Literal("a".to_owned()))
        });

        insta::assert_snapshot!(env.render_ok(r#"coalesce()"#), @"");
        insta::assert_snapshot!(env.render_ok(r#"coalesce("")"#), @"");
        insta::assert_snapshot!(env.render_ok(r#"coalesce("", "a", "", "b")"#), @"a");
        insta::assert_snapshot!(
            env.render_ok(r#"coalesce(empty_string, "", non_empty_string)"#), @"a");

        // "false" is not empty
        insta::assert_snapshot!(env.render_ok(r#"coalesce(false, true)"#), @"false");

        // Error is not empty
        insta::assert_snapshot!(env.render_ok(r#"coalesce(bad_string, "a")"#), @"<Error: Bad>");
        // but can be short-circuited
        insta::assert_snapshot!(env.render_ok(r#"coalesce("a", bad_string)"#), @"a");
    }

    #[test]
    fn test_concat_function() {
        let mut env = TestTemplateEnv::new();
        env.add_keyword("empty", || L::wrap_boolean(Literal(true)));
        env.add_keyword("hidden", || L::wrap_boolean(Literal(false)));
        env.add_color("empty", crossterm::style::Color::DarkGreen);
        env.add_color("error", crossterm::style::Color::DarkRed);
        env.add_color("warning", crossterm::style::Color::DarkYellow);

        insta::assert_snapshot!(env.render_ok(r#"concat()"#), @"");
        insta::assert_snapshot!(
            env.render_ok(r#"concat(hidden, empty)"#),
            @"falsetrue");
        insta::assert_snapshot!(
            env.render_ok(r#"concat(label("error", ""), label("warning", "a"), "b")"#),
            @"ab");
    }

    #[test]
    fn test_separate_function() {
        let mut env = TestTemplateEnv::new();
        env.add_keyword("description", || L::wrap_string(Literal("".to_owned())));
        env.add_keyword("empty", || L::wrap_boolean(Literal(true)));
        env.add_keyword("hidden", || L::wrap_boolean(Literal(false)));
        env.add_color("empty", crossterm::style::Color::DarkGreen);
        env.add_color("error", crossterm::style::Color::DarkRed);
        env.add_color("warning", crossterm::style::Color::DarkYellow);

        insta::assert_snapshot!(env.render_ok(r#"separate(" ")"#), @"");
        insta::assert_snapshot!(env.render_ok(r#"separate(" ", "")"#), @"");
        insta::assert_snapshot!(env.render_ok(r#"separate(" ", "a")"#), @"a");
        insta::assert_snapshot!(env.render_ok(r#"separate(" ", "a", "b")"#), @"a b");
        insta::assert_snapshot!(env.render_ok(r#"separate(" ", "a", "", "b")"#), @"a b");
        insta::assert_snapshot!(env.render_ok(r#"separate(" ", "a", "b", "")"#), @"a b");
        insta::assert_snapshot!(env.render_ok(r#"separate(" ", "", "a", "b")"#), @"a b");

        // Labeled
        insta::assert_snapshot!(
            env.render_ok(r#"separate(" ", label("error", ""), label("warning", "a"), "b")"#),
            @"a b");

        // List template
        insta::assert_snapshot!(env.render_ok(r#"separate(" ", "a", ("" ++ ""))"#), @"a");
        insta::assert_snapshot!(env.render_ok(r#"separate(" ", "a", ("" ++ "b"))"#), @"a b");

        // Nested separate
        insta::assert_snapshot!(
            env.render_ok(r#"separate(" ", "a", separate("|", "", ""))"#), @"a");
        insta::assert_snapshot!(
            env.render_ok(r#"separate(" ", "a", separate("|", "b", ""))"#), @"a b");
        insta::assert_snapshot!(
            env.render_ok(r#"separate(" ", "a", separate("|", "b", "c"))"#), @"a b|c");

        // Conditional template
        insta::assert_snapshot!(
            env.render_ok(r#"separate(" ", "a", if(true, ""))"#), @"a");
        insta::assert_snapshot!(
            env.render_ok(r#"separate(" ", "a", if(true, "", "f"))"#), @"a");
        insta::assert_snapshot!(
            env.render_ok(r#"separate(" ", "a", if(false, "t", ""))"#), @"a");
        insta::assert_snapshot!(
            env.render_ok(r#"separate(" ", "a", if(true, "t", "f"))"#), @"a t");

        // Separate keywords
        insta::assert_snapshot!(
            env.render_ok(r#"separate(" ", hidden, description, empty)"#),
            @"false true");

        // Keyword as separator
        insta::assert_snapshot!(
            env.render_ok(r#"separate(hidden, "X", "Y", "Z")"#),
            @"XfalseYfalseZ");
    }

    #[test]
    fn test_surround_function() {
        let mut env = TestTemplateEnv::new();
        env.add_keyword("lt", || L::wrap_string(Literal("<".to_owned())));
        env.add_keyword("gt", || L::wrap_string(Literal(">".to_owned())));
        env.add_keyword("content", || L::wrap_string(Literal("content".to_owned())));
        env.add_keyword("empty_content", || L::wrap_string(Literal("".to_owned())));
        env.add_color("error", crossterm::style::Color::DarkRed);
        env.add_color("paren", crossterm::style::Color::Cyan);

        insta::assert_snapshot!(env.render_ok(r#"surround("{", "}", "")"#), @"");
        insta::assert_snapshot!(env.render_ok(r#"surround("{", "}", "a")"#), @"{a}");

        // Labeled
        insta::assert_snapshot!(
            env.render_ok(
                r#"surround(label("paren", "("), label("paren", ")"), label("error", "a"))"#),
            @"(a)");

        // Keyword
        insta::assert_snapshot!(
            env.render_ok(r#"surround(lt, gt, content)"#),
            @"<content>");
        insta::assert_snapshot!(
            env.render_ok(r#"surround(lt, gt, empty_content)"#),
            @"");

        // Conditional template as content
        insta::assert_snapshot!(
            env.render_ok(r#"surround(lt, gt, if(empty_content, "", "empty"))"#),
            @"<empty>");
        insta::assert_snapshot!(
            env.render_ok(r#"surround(lt, gt, if(empty_content, "not empty", ""))"#),
            @"");
    }
}