rant 4.0.0-alpha.22

The Rant procedural templating language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
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
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
#![allow(dead_code)]
#![allow(clippy::ptr_arg)]

use super::{reader::RantTokenReader, lexer::RantToken, message::*, Problem, Reporter};
use crate::{InternalString, RantProgramInfo, lang::*};
use fnv::FnvBuildHasher;
use line_col::LineColLookup;
use quickscope::ScopeMap;
use std::{collections::{HashMap, HashSet}, ops::Range, rc::Rc};

type ParseResult<T> = Result<T, ()>;

const MAIN_PROGRAM_SCOPE_NAME: &str = "main scope";

const KW_RETURN: &str = "return";
const KW_BREAK: &str = "break";
const KW_CONTINUE: &str = "continue";
const KW_WEIGHT: &str = "weight";
const KW_TRUE: &str = "true";
const KW_FALSE: &str = "false";

/// Provides context to the sequence parser; determines valid terminating tokens among other context-sensitive features.
#[derive(Copy, Clone, PartialEq)]
enum SequenceParseMode {
  /// Parse a sequence like a top-level program.
  ///
  /// Breaks on EOF.
  TopLevel,
  /// Parse a sequence like a block element.
  ///
  /// Breaks on `Pipe`, `Colon`, and `RightBrace`.
  BlockElement,
  /// Parse a sequence like a function argument.
  ///
  /// Breaks on `Semi`, `Compose`, and `RightBracket`.
  FunctionArg,
  /// Parse a sequence like a function body.
  ///
  /// Breaks on `RightBrace`.
  FunctionBodyBlock,
  /// Parse a sequence like a dynamic key expression.
  ///
  /// Breaks on `RightBrace`.
  DynamicKey,
  /// Parse a sequence like an anonymous function expression.
  ///
  /// Breaks on `Colon` and `RightBracket`.
  AnonFunctionExpr,
  /// Parse a sequence like a variable assignment value.
  ///
  /// Breaks on `RightAngle` and `Semi`.
  VariableAssignment,
  /// Parse a sequence like an accessor fallback value.
  ///
  /// Breaks on `RightAngle` and `Semi`.
  AccessorFallbackValue,
  /// Parses a sequence like a parameter default value.
  ///
  /// Breaks on `RightBracket` and `Semi`.
  ParamDefaultValue,
  /// Parse a sequence like a collection initializer element.
  ///
  /// Breaks on `Semi` and `RightParen`.
  CollectionInit,
  /// Parses a single item only.
  ///
  /// Breaks automatically or on EOF.
  SingleItem,
}

/// What type of collection initializer to parse?
enum CollectionInitKind {
  /// Parse a list
  List,
  /// Parse a map
  Map
}

/// Indicates what kind of token terminated a sequence read.
enum SequenceEndType {
  /// Top-level program sequence was terminated by end-of-file.
  ProgramEnd,
  /// Block element sequence is key and was terminated by `Colon`.
  BlockAssocDelim,
  /// Block element sequence was terminated by `Pipe`.
  BlockDelim,
  /// Block element sequence was terminated by `RightBrace`.
  BlockEnd,
  /// Function argument sequence was terminated by `Semi`.
  FunctionArgEndNext,
  /// Function argument sequence was terminated by `RightBracket`.
  FunctionArgEndBreak,
  /// Function argument sequence was terminated by `Compose`.
  FunctionArgEndToCompose,
  /// Function body sequence was terminated by `RightBrace`.
  FunctionBodyEnd,
  /// Dynamic key sequencce was terminated by `RightBrace`.
  DynamicKeyEnd,
  /// Anonymous function expression was terminated by `Colon`.
  AnonFunctionExprToArgs,
  /// Anonymous function expression was terminated by `RightBracket` and does not expect arguments.
  AnonFunctionExprNoArgs,
  /// Anonymous function expression was terminated by `Compose`.
  AnonFunctionExprToCompose,
  /// Variable accessor was terminated by `RightAngle`.
  VariableAccessEnd,
  /// Variable assignment expression was terminated by `Semi`. 
  VariableAssignDelim,
  /// Accessor fallback value was termianted by `RightAngle`.
  AccessorFallbackValueToEnd,
  /// Accessor fallback value was terminated by `Semi`.
  AccessorFallbackValueToDelim,
  /// Collection initializer was terminated by `RightParen`.
  CollectionInitEnd,
  /// Collection initializer was termianted by `Semi`.
  CollectionInitDelim,
  /// A single item was parsed using `SingleItem` mode.
  SingleItemEnd,
  /// Parameter default value was terminated by `Semi`, indicating another parameter follows.
  ParamDefaultValueSeparator,
  /// Parameter default value was terminated by `RightBracket`, indicating the end of the signature was reached..
  ParamDefaultValueSignatureEnd,
}

/// Used to track variable usages during compilation.
struct VarStats {
  def_span: Range<usize>,
  writes: usize,
  reads: usize,
  has_fallible_read: bool,
  is_const: bool,
  role: VarRole,
}

impl VarStats {
  #[inline]
  fn add_write(&mut self) {
    self.writes += 1;
  }

  #[inline]
  fn add_read(&mut self, is_fallible_read: bool) {
    if matches!(self.role, VarRole::FallibleOptionalArgument) && is_fallible_read {
      self.has_fallible_read = true;
    }
    self.reads += 1;
  }
}

#[derive(Copy, Clone, PartialEq)]
enum VarRole {
  Normal,
  Function,
  Argument,
  FallibleOptionalArgument,
  ComposeValue,
}

/// Returns a range that encompasses both input ranges.
#[inline]
fn super_range(a: &Range<usize>, b: &Range<usize>) -> Range<usize> {
  a.start.min(b.start)..a.end.max(b.end)
}

#[derive(Debug)]
enum ParsedSequenceExtras {
  WeightedBlockElement {
    weight_expr: Rc<Sequence>
  }
}

/// Contains information about a successfully parsed sequence and its context.
struct ParsedSequence {
  sequence: Sequence,
  end_type: SequenceEndType,
  is_printing: bool,
  extras: Option<ParsedSequenceExtras>,
}

/// A parser that turns Rant code into an RST (Rant Syntax Tree).
pub struct RantParser<'source, 'report, R: Reporter> {
  /// A string slice containing the source code being parsed.
  source: &'source str,
  /// Flag set if there are compiler errors.
  has_errors: bool,
  /// The token stream used by the parser.
  reader: RantTokenReader<'source>,
  /// The line/col lookup for error reporting.
  lookup: LineColLookup<'source>,
  /// The error reporter.
  reporter: &'report mut R,
  /// Enables additional debug information.
  debug_enabled: bool,
  /// A string describing the origin (containing program) of a program element.
  info: Rc<RantProgramInfo>,
  /// Keeps track of active variables in each scope while parsing.
  var_stack: ScopeMap<Identifier, VarStats>,
  /// Keeps track of active variable capture frames.
  capture_stack: Vec<(usize, HashSet<Identifier, FnvBuildHasher>)>,
}

impl<'source, 'report, R: Reporter> RantParser<'source, 'report, R> {
  pub fn new(source: &'source str, reporter: &'report mut R, debug_enabled: bool, info: &Rc<RantProgramInfo>) -> Self {
    Self {
      source,
      has_errors: false,
      reader: RantTokenReader::new(source),
      lookup: LineColLookup::new(source),
      reporter,
      debug_enabled,
      info: Rc::clone(info),
      var_stack: Default::default(),
      capture_stack: Default::default(),
    }
  }
}

impl<'source, 'report, R: Reporter> RantParser<'source, 'report, R> {
  /// Top-level parsing function invoked by the compiler.
  pub fn parse(&mut self) -> Result<Rc<Sequence>, ()> {
    let result = self.parse_sequence(SequenceParseMode::TopLevel);
    match result {
      // Err if parsing "succeeded" but there are soft syntax errors
      Ok(..) if self.has_errors => Err(()),
      // Ok if parsing succeeded and there are no syntax errors
      Ok(ParsedSequence { sequence, .. }) => Ok(Rc::new(sequence)),
      // Err on hard syntax error
      Err(()) => Err(())
    }
  }
  
  /// Reports a syntax error, allowing parsing to continue but causing the final compilation to fail. 
  fn report_error(&mut self, problem: Problem, span: &Range<usize>) {
    let (line, col) = self.lookup.get(span.start);
    self.has_errors = true;
    self.reporter.report(CompilerMessage::new(problem, Severity::Error, Some(Position::new(line, col, span.clone()))));
  }

  /// Reports a warning, but allows compiling to succeed.
  fn report_warning(&mut self, problem: Problem, span: &Range<usize>) {
    let (line, col) = self.lookup.get(span.start);
    self.reporter.report(CompilerMessage::new(problem, Severity::Warning, Some(Position::new(line, col, span.clone()))));
  }
  
  /// Emits an "unexpected token" error for the most recently read token.
  #[inline]
  fn unexpected_last_token_error(&mut self) {
    self.report_error(Problem::UnexpectedToken(self.reader.last_token_string().to_string()), &self.reader.last_token_span())
  }

  /// Parses a sequence of items. Items are individual elements of a Rant program (fragments, blocks, function calls, etc.)
  #[inline]
  fn parse_sequence(&mut self, mode: SequenceParseMode) -> ParseResult<ParsedSequence> {
    self.var_stack.push_layer();
    let parse_result = self.parse_sequence_inner(mode);
    self.analyze_top_vars();
    self.var_stack.pop_layer();
    parse_result
  }
  
  /// Inner logic of `parse_sequence()`. Intended to be wrapped in other specialized sequence-parsing functions.
  #[inline(always)]
  fn parse_sequence_inner(&mut self, mode: SequenceParseMode) -> ParseResult<ParsedSequence> {    
    let mut sequence = Sequence::empty(&self.info);
    let mut next_print_flag = PrintFlag::None;
    let mut last_print_flag_span: Option<Range<usize>> = None;
    let mut is_seq_printing = false;
    let mut pending_whitespace = None;
    let debug = self.debug_enabled;

    macro_rules! check_dangling_printflags {
      () => {
        // Make sure there are no dangling printflags
        match next_print_flag {
          PrintFlag::None => {},
          PrintFlag::Hint => {
            if let Some(flag_span) = last_print_flag_span.take() {
              self.report_error(Problem::InvalidHint, &flag_span);
            }
          },
          PrintFlag::Sink => {
            if let Some(flag_span) = last_print_flag_span.take() {
              self.report_error(Problem::InvalidSink, &flag_span);
            }
          }
        }
      }
    }
    
    while let Some((token, span)) = self.reader.next() {
      let _debug_inject_toggle = true;

      macro_rules! no_debug {
        ($e:expr) => {{
          let _debug_inject_toggle = false;
          $e
        }}
      }

      macro_rules! inject_debug_info {
        () => {
          if debug && _debug_inject_toggle {
            let (line, col) = self.lookup.get(span.start);
            sequence.push(Rc::new(Rst::DebugCursor(DebugInfo::Location { line, col })));
          }
        }
      }
      
      // Macro for prohibiting hints/sinks before certain tokens
      macro_rules! no_flags {
        (on $b:block) => {{
          let elem = $b;
          if !matches!(next_print_flag, PrintFlag::None) {
            if let Some(flag_span) = last_print_flag_span.take() {
              self.report_error(match next_print_flag {
                PrintFlag::Hint => Problem::InvalidHintOn(elem.display_name()),
                PrintFlag::Sink => Problem::InvalidSinkOn(elem.display_name()),
                PrintFlag::None => unreachable!()
              }, &flag_span)
            }
          }
          inject_debug_info!();
          sequence.push(Rc::new(elem));
        }};
        ($b:block) => {
          if matches!(next_print_flag, PrintFlag::None) {
            $b
          } else if let Some(flag_span) = last_print_flag_span.take() {
            self.report_error(match next_print_flag {
              PrintFlag::Hint => Problem::InvalidHint,
              PrintFlag::Sink => Problem::InvalidSink,
              PrintFlag::None => unreachable!()
            }, &flag_span)
          }
        };
      }

      macro_rules! emit {
        ($elem:expr) => {{
          inject_debug_info!();
          sequence.push(Rc::new($elem));
        }}
      }

      macro_rules! emit_last_string {
        () => {{
          inject_debug_info!();
          sequence.push(Rc::new(Rst::Fragment(InternalString::from(self.reader.last_token_string()))));
        }}
      }
      
      // Shortcut macro for "unexpected token" error
      macro_rules! unexpected_token_error {
        () => {
          self.report_error(Problem::UnexpectedToken(self.reader.last_token_string().to_string()), &span)
        };
      }
      
      macro_rules! whitespace {
        (allow) => {
          if is_seq_printing {
            if let Some(ws) = pending_whitespace.take() {
              emit!(Rst::Whitespace(ws));
            }
          } else {
            pending_whitespace = None;
          }
        };
        (queue next) => {{
          if let Some((RantToken::Whitespace, ..)) = self.reader.take_where(|tt| matches!(tt, Some((RantToken::Whitespace, ..)))) {
            pending_whitespace = Some(self.reader.last_token_string());
          }
        }};
        (queue $ws:expr) => {
          pending_whitespace = Some($ws);
        };
        (ignore prev) => {{
          #![allow(unused_assignments)]
          pending_whitespace = None;
        }};
        (ignore next) => {
          self.reader.skip_ws();
        };
        (ignore both) => {{
          whitespace!(ignore prev);
          whitespace!(ignore next);
        }};
      }

      /// Eats as many fragments / escape sequences as possible and combines their string representations into the input `String`.
      macro_rules! consume_fragments {
        ($s:ident) => {
          while let Some((token, _)) = self.reader.take_where(|t| matches!(t, Some((RantToken::Escape(..), ..)) | Some((RantToken::Fragment, ..)))) {
            match token {
              RantToken::Escape(ch) => $s.push(ch),
              _ => $s.push_str(&self.reader.last_token_string()),
            }
          }
        }
      }
      
      // Parse next sequence item
      match token {
        
        // Hint
        RantToken::Hint => no_flags!({
          whitespace!(allow);
          is_seq_printing = true;
          next_print_flag = PrintFlag::Hint;
          last_print_flag_span = Some(span.clone());
          continue
        }),
        
        // Sink
        RantToken::Sink => no_flags!({
          // Ignore pending whitespace
          whitespace!(ignore prev);
          next_print_flag = PrintFlag::Sink;
          last_print_flag_span = Some(span.clone());
          continue
        }),

        RantToken::Keyword(kw) => {
          let kwstr = kw.as_str();
          match kwstr {
            // Boolean constants
            KW_TRUE => no_debug!(no_flags!(on {
              whitespace!(ignore both);
              is_seq_printing = true;
              Rst::Boolean(true)
            })),
            KW_FALSE => no_debug!(no_flags!(on {
              whitespace!(ignore both);
              is_seq_printing = true;
              Rst::Boolean(false)
            })),
            // Charms
            KW_RETURN | KW_CONTINUE | KW_BREAK | KW_WEIGHT => {
              whitespace!(ignore both);
              let ParsedSequence {
                sequence: charm_sequence,
                end_type: charm_end_type,
                is_printing: is_charm_printing,
                extras: mut charm_extras
              } = self.parse_sequence(mode)?;
              let charm_sequence_name = charm_sequence.name.clone();
              let charm_sequence = (!charm_sequence.is_empty()).then(|| Rc::new(charm_sequence));
              match kw.as_str() {
                KW_RETURN => emit!(Rst::Return(charm_sequence)),
                KW_CONTINUE => emit!(Rst::Continue(charm_sequence)),
                KW_BREAK => emit!(Rst::Break(charm_sequence)),
                KW_WEIGHT => {
                  if mode == SequenceParseMode::BlockElement {
                    charm_extras = Some(ParsedSequenceExtras::WeightedBlockElement {
                      weight_expr: charm_sequence.unwrap_or_else(|| Rc::new(Sequence::empty(&self.info)))
                    });
                  } else {
                    self.report_error(Problem::WeightNotAllowed, &span);
                  }
                },
                _ => unreachable!()
              };
              check_dangling_printflags!();
              return Ok(ParsedSequence {
                sequence: if let Some(charm_sequence_name) = charm_sequence_name {
                  sequence.with_name(charm_sequence_name)
                } else {
                  sequence
                },
                end_type: charm_end_type,
                is_printing: is_charm_printing || is_seq_printing,
                extras: charm_extras,
              })
            },
            other => self.report_error(Problem::InvalidKeyword(other.to_string()), &span),
          }          
        },
        
        // Defer operator
        RantToken::Defer => {
          self.reader.skip_ws();
          let block = self.parse_block(true, next_print_flag)?;
          
          // Decide what to do with surrounding whitespace
          match next_print_flag {                        
            // If hinted, allow pending whitespace
            PrintFlag::Hint => {
              whitespace!(allow);
              is_seq_printing = true;
            },
            
            // If sinked, remove surrounding whitespace
            PrintFlag::Sink => whitespace!(ignore both),
            
            // If no flag, take a hint
            PrintFlag::None => {
              // Inherit hints from inner blocks
              if let Block { flag: PrintFlag::Hint, ..} = block {
                whitespace!(allow);
                is_seq_printing = true;
              }
            }
          }
          
          emit!(Rst::BlockValue(Rc::new(block)));
        },
        
        // Block start
        RantToken::LeftBrace => {
          // Read in the entire block
          let block = self.parse_block(false, next_print_flag)?;

          // Decide what to do with previous whitespace
          match next_print_flag {                        
            // If hinted, allow pending whitespace
            PrintFlag::Hint => {
              whitespace!(allow);
              is_seq_printing = true;
            },
            
            // If sinked, delete pending whitespace
            PrintFlag::Sink => whitespace!(ignore both),
            
            // If no flag, infer from block contents
            PrintFlag::None => {
              // Inherit hints from inner blocks
              if let Block { flag: PrintFlag::Hint, ..} = block {
                whitespace!(allow);
                is_seq_printing = true;
              }
            }
          }
          
          emit!(Rst::Block(Rc::new(block)));
        },

        // Compose operator
        RantToken::Compose => no_flags!({
          // Ignore pending whitespace
          whitespace!(ignore prev);
          match mode {
            SequenceParseMode::FunctionArg => {
              return Ok(ParsedSequence {
                sequence: sequence.with_name_str("argument"),
                end_type: SequenceEndType::FunctionArgEndToCompose,
                is_printing: is_seq_printing,
                extras: None,
              })
            },
            SequenceParseMode::AnonFunctionExpr => {
              return Ok(ParsedSequence {
                sequence: sequence.with_name_str("anonymous function expression"),
                end_type: SequenceEndType::AnonFunctionExprToCompose,
                is_printing: is_seq_printing,
                extras: None,
              })
            },
            _ => unexpected_token_error!()
          }
        }),

        // Compose value
        RantToken::ComposeValue => no_flags!({
          if let Some(compval) = self.var_stack.get_mut(COMPOSE_VALUE_NAME) {
            emit!(Rst::ComposeValue);
            compval.add_read(false);
          } else {
            self.report_error(Problem::NothingToCompose, &span);
          }
        }),
        
        // Block element delimiter (when in block parsing mode)
        RantToken::Pipe => no_flags!({
          // Ignore pending whitespace
          whitespace!(ignore prev);
          match mode {
            SequenceParseMode::BlockElement => {
              return Ok(ParsedSequence {
                sequence: sequence.with_name_str("block element"),
                end_type: SequenceEndType::BlockDelim,
                is_printing: is_seq_printing,
                extras: None,
              })
            },
            SequenceParseMode::DynamicKey => {
              self.report_error(Problem::DynamicKeyBlockMultiElement, &span);
            },
            SequenceParseMode::FunctionBodyBlock => {
              self.report_error(Problem::FunctionBodyBlockMultiElement, &span);
            },
            _ => unexpected_token_error!()
          }
        }),
        
        // Block/func body/dynamic key end
        RantToken::RightBrace => no_flags!({
          // Ignore pending whitespace
          whitespace!(ignore prev);
          match mode {
            SequenceParseMode::BlockElement => {
              return Ok(ParsedSequence {
                sequence: sequence.with_name_str("block element"),
                end_type: SequenceEndType::BlockEnd,
                is_printing: true,
                extras: None,
              })
            },
            SequenceParseMode::FunctionBodyBlock => {
              return Ok(ParsedSequence {
                sequence: sequence.with_name_str("function body"),
                end_type: SequenceEndType::FunctionBodyEnd,
                is_printing: true,
                extras: None,
              })
            },
            SequenceParseMode::DynamicKey => {
              return Ok(ParsedSequence {
                sequence: sequence.with_name_str("dynamic key"),
                end_type: SequenceEndType::DynamicKeyEnd,
                is_printing: true,
                extras: None,
              })
            }
            _ => unexpected_token_error!()
          }
        }),
        
        // Map initializer
        RantToken::At => no_flags!(on {
          match self.reader.next_solid() {
            Some((RantToken::LeftParen, _)) => {
              self.parse_collection_initializer(CollectionInitKind::Map, &span)?
            },
            _ => {
              self.report_error(Problem::ExpectedToken("(".to_owned()), &self.reader.last_token_span());
              Rst::EmptyVal
            },
          }
        }),
        
        // List initializer
        RantToken::LeftParen => no_flags!(on {
          self.parse_collection_initializer(CollectionInitKind::List, &span)?
        }),
        
        // Collection init termination
        RantToken::RightParen => no_flags!({
          match mode {
            SequenceParseMode::CollectionInit => {
              return Ok(ParsedSequence {
                sequence,
                end_type: SequenceEndType::CollectionInitEnd,
                is_printing: true,
                extras: None,
              })
            },
            _ => unexpected_token_error!()
          }
        }),
        
        // Function creation or call
        RantToken::LeftBracket => {
          let func_access = self.parse_func_access(next_print_flag)?;
          
          // Handle hint/sink behavior
          match func_access {
            Rst::FuncCall(FunctionCall { flag, ..}) => {
              // If the call is not sinked, allow whitespace around it
              match flag {
                PrintFlag::Hint => {
                  is_seq_printing = true;
                  whitespace!(allow);
                },
                _ => whitespace!(ignore both)
              }
            },
            // Definitions are implicitly sinked and ignore surrounding whitespace
            Rst::FuncDef(_) => {
              whitespace!(ignore both);
            },
            // Do nothing if it's an unsupported node type, e.g. NOP
            _ => {}
          }
          
          emit!(func_access);
        },
        
        // Can be terminator for function args and anonymous function expressions
        RantToken::RightBracket => no_flags!({
          match mode {
            SequenceParseMode::AnonFunctionExpr => return Ok(ParsedSequence {
              sequence: sequence.with_name_str("anonymous function expression"),
              end_type: SequenceEndType::AnonFunctionExprNoArgs,
              is_printing: true,
              extras: None,
            }),
            SequenceParseMode::FunctionArg => return Ok(ParsedSequence {
              sequence: sequence.with_name_str("argument"),
              end_type: SequenceEndType::FunctionArgEndBreak,
              is_printing: true,
              extras: None,
            }),
            SequenceParseMode::ParamDefaultValue => return Ok(ParsedSequence {
              sequence: sequence.with_name_str("default value"),
              end_type: SequenceEndType::ParamDefaultValueSignatureEnd,
              is_printing: true,
              extras: None,
            }),
            _ => unexpected_token_error!()
          }
        }),
        
        // Variable access start
        RantToken::LeftAngle => no_flags!({
          let accessors = self.parse_accessor()?;
          for accessor in accessors {
            match accessor {
              Rst::VarGet(..) | Rst::VarDepth(..) => {
                is_seq_printing = true;
                whitespace!(allow);
              },
              Rst::VarSet(..) | Rst::VarDef(..) | Rst::ConstDef(..) => {
                // whitespace!(ignore both);
              },
              _ => unreachable!()
            }
            emit!(accessor);
          }
        }),
        
        // Variable access end
        RantToken::RightAngle => no_flags!({
          match mode {
            SequenceParseMode::VariableAssignment => return Ok(ParsedSequence {
              sequence: sequence.with_name_str("setter value"),
              end_type: SequenceEndType::VariableAccessEnd,
              is_printing: true,
              extras: None,
            }),
            SequenceParseMode::AccessorFallbackValue => return Ok(ParsedSequence {
              sequence: sequence.with_name_str("fallback value"),
              end_type: SequenceEndType::AccessorFallbackValueToEnd,
              is_printing: true,
              extras: None,
            }),
            _ => unexpected_token_error!()
          }
        }),
        
        // These symbols are only used in special contexts and can be safely printed
        RantToken::Bang | RantToken::Question | RantToken::Slash | RantToken::Plus | RantToken::Dollar | RantToken::Equals | RantToken::Percent
        => no_flags!(on {
          whitespace!(allow);
          is_seq_printing = true;
          let frag = self.reader.last_token_string();
          Rst::Fragment(frag)
        }),
        
        // Fragment
        RantToken::Fragment => no_flags!(on {
          whitespace!(allow);
          is_seq_printing = true;
          let mut frag = self.reader.last_token_string();
          consume_fragments!(frag);
          Rst::Fragment(frag)
        }),
        
        // Whitespace (only if sequence isn't empty)
        RantToken::Whitespace => no_flags!({
          // Don't set is_printing here; whitespace tokens always appear with other printing tokens
          if is_seq_printing {
            let ws = self.reader.last_token_string();
            whitespace!(queue ws);
          }
        }),
        
        // Escape sequences
        RantToken::Escape(ch) => no_flags!(on {
          whitespace!(allow);
          is_seq_printing = true;
          let mut frag = InternalString::new();
          frag.push(ch);
          consume_fragments!(frag);
          Rst::Fragment(frag)
        }),
        
        // Integers
        RantToken::Integer(n) => no_flags!(on {
          whitespace!(allow);
          is_seq_printing = true;
          Rst::Integer(n)
        }),
        
        // Floats
        RantToken::Float(n) => no_flags!(on {
          whitespace!(allow);
          is_seq_printing = true;
          Rst::Float(n)
        }),
        
        // Empty
        RantToken::EmptyValue => no_flags!(on {
          Rst::EmptyVal
        }),
        
        // Verbatim string literals
        RantToken::StringLiteral(s) => no_flags!(on {
          whitespace!(allow);
          is_seq_printing = true;
          Rst::Fragment(s)
        }),
        
        // Colon can be either fragment or argument separator.
        RantToken::Colon => no_flags!({
          match mode {
            SequenceParseMode::AnonFunctionExpr => return Ok(ParsedSequence {
              sequence: sequence.with_name_str("anonymous function expression"),
              end_type: SequenceEndType::AnonFunctionExprToArgs,
              is_printing: true,
              extras: None,
            }),
            _ => emit_last_string!(),
          }
        }),
        
        // Semicolon can be a fragment, collection element separator, or argument separator.
        RantToken::Semi => no_flags!({
          match mode {
            SequenceParseMode::FunctionArg => return Ok(ParsedSequence {
              sequence: sequence.with_name_str("argument"),
              end_type: SequenceEndType::FunctionArgEndNext,
              is_printing: true,
              extras: None,
            }),
            SequenceParseMode::CollectionInit => return Ok(ParsedSequence {
              sequence: sequence.with_name_str("collection item"),
              end_type: SequenceEndType::CollectionInitDelim,
              is_printing: true,
              extras: None,
            }),
            SequenceParseMode::VariableAssignment => return Ok(ParsedSequence {
              sequence: sequence.with_name_str("variable assignment"),
              end_type: SequenceEndType::VariableAssignDelim,
              is_printing: true,
              extras: None,
            }),
            SequenceParseMode::AccessorFallbackValue => return Ok(ParsedSequence {
              sequence: sequence.with_name_str("fallback"),
              end_type: SequenceEndType::AccessorFallbackValueToDelim,
              is_printing: true,
              extras: None,
            }),
            SequenceParseMode::ParamDefaultValue => return Ok(ParsedSequence {
              sequence: sequence.with_name_str("default value"),
              end_type: SequenceEndType::ParamDefaultValueSeparator,
              is_printing: true,
              extras: None,
            }),
            // If we're anywhere else, just print the semicolon like normal text
            _ => emit_last_string!(),
          }
        }),
        
        // Handle unclosed string literals as hard errors
        RantToken::UnterminatedStringLiteral => {
          self.report_error(Problem::UnclosedStringLiteral, &span); 
          return Err(())
        },
        _ => unexpected_token_error!(),
      }

      // If in Single Item mode, return the sequence immediately without looping
      if mode == SequenceParseMode::SingleItem {
        return Ok(ParsedSequence {
          sequence,
          end_type: SequenceEndType::SingleItemEnd,
          is_printing: is_seq_printing,
          extras: None,
        })
      }
      
      // Clear flag
      next_print_flag = PrintFlag::None;
    }
    
    // Reached when the whole program has been read
    // This should only get hit for top-level sequences
    
    check_dangling_printflags!();
    
    // Return the top-level sequence
    Ok(ParsedSequence {
      sequence: sequence.with_name_str(MAIN_PROGRAM_SCOPE_NAME),
      end_type: SequenceEndType::ProgramEnd,
      is_printing: is_seq_printing,
      extras: None,
    })
  }
  
  /// Parses a list/map initializer.
  fn parse_collection_initializer(&mut self, kind: CollectionInitKind, start_span: &Range<usize>) -> ParseResult<Rst> {
    match kind {
      CollectionInitKind::List => {
        self.reader.skip_ws();
        
        // Exit early on empty list
        if self.reader.eat_where(|token| matches!(token, Some((RantToken::RightParen, ..)))) {
          return Ok(Rst::ListInit(Rc::new(vec![])))
        }
        
        let mut sequences = vec![];
        
        loop {
          self.reader.skip_ws();
          
          let ParsedSequence { sequence, end_type: seq_end, .. } = self.parse_sequence(SequenceParseMode::CollectionInit)?;
          
          match seq_end {
            SequenceEndType::CollectionInitDelim => {
              sequences.push(Rc::new(sequence));
            },
            SequenceEndType::CollectionInitEnd => {
              sequences.push(Rc::new(sequence));
              break
            },
            SequenceEndType::ProgramEnd => {
              self.report_error(Problem::UnclosedList, &super_range(start_span, &self.reader.last_token_span()));
              return Err(())
            },
            _ => unreachable!()
          }
        }

        // To allow trailing semicolons, remove the last element if its sequence is empty
        if let Some(seq) = sequences.last() {
          if seq.is_empty() {
            sequences.pop();
          }
        }

        Ok(Rst::ListInit(Rc::new(sequences)))
      },
      CollectionInitKind::Map => {
        let mut pairs = vec![];
        
        loop {
          let key_expr = match self.reader.next_solid() {
            // Allow blocks as dynamic keys
            Some((RantToken::LeftBrace, _)) => {
              MapKeyExpr::Dynamic(Rc::new(self.parse_dynamic_expr(false)?))
            },
            // Allow fragments as keys if they are valid identifiers
            Some((RantToken::Fragment, span)) => {
              let key = self.reader.last_token_string();
              if !is_valid_ident(key.as_str()) {
                self.report_error(Problem::InvalidIdentifier(key.to_string()), &span);
              }
              MapKeyExpr::Static(key)
            },
            // Allow string literals as static keys
            Some((RantToken::StringLiteral(s), _)) => {
              MapKeyExpr::Static(s)
            },
            // End of map
            Some((RantToken::RightParen, _)) => break,
            // Soft error on anything weird
            Some(_) => {
              self.unexpected_last_token_error();
              MapKeyExpr::Static(self.reader.last_token_string())
            },
            // Hard error on EOF
            None => {
              self.report_error(Problem::UnclosedMap, &super_range(start_span, &self.reader.last_token_span()));
              return Err(())
            }
          };
          
          self.reader.skip_ws();
          if !self.reader.eat_where(|tok| matches!(tok, Some((RantToken::Equals, ..)))) {
            self.report_error(Problem::ExpectedToken("=".to_owned()), &self.reader.last_token_span());
            return Err(())
          }
          self.reader.skip_ws();
          let ParsedSequence { 
            sequence: value_expr, 
            end_type: value_expr_end, 
            .. 
          } = self.parse_sequence(SequenceParseMode::CollectionInit)?;
          
          match value_expr_end {
            SequenceEndType::CollectionInitDelim => {
              pairs.push((key_expr, Rc::new(value_expr)));
            },
            SequenceEndType::CollectionInitEnd => {
              pairs.push((key_expr, Rc::new(value_expr)));
              break
            },
            SequenceEndType::ProgramEnd => {
              self.report_error(Problem::UnclosedMap, &super_range(start_span, &self.reader.last_token_span()));
              return Err(())
            },
            _ => unreachable!()
          }
        }
        
        Ok(Rst::MapInit(Rc::new(pairs)))
      },
    }
    
  }
  
  fn parse_func_params(&mut self, start_span: &Range<usize>) -> ParseResult<Vec<(Parameter, Range<usize>)>> {
    // List of parameter names for function
    let mut params = vec![];
    // Separate set of all parameter names to check for duplicates
    let mut params_set = HashSet::new();
    // Most recently used parameter varity in this signature
    let mut last_varity = Varity::Required;
    // Keep track of whether we've encountered any variadic params
    let mut is_sig_variadic = false;
    
    // At this point there should either be ':' or ']'
    match self.reader.next_solid() {
      // ':' means there are params to be read
      Some((RantToken::Colon, _)) => {
        // Read the params
        'read_params: loop {
          match self.reader.next_solid() {
            // Regular parameter
            Some((RantToken::Fragment, span)) => {              
              // We only care about verifying/recording the param if it's in a valid position
              let param_name = Identifier::new(self.reader.last_token_string());
              // Make sure it's a valid identifier
              if !is_valid_ident(param_name.as_str()) {
                self.report_error(Problem::InvalidIdentifier(param_name.to_string()), &span)
              }
              // Check for duplicates
              // I'd much prefer to store references in params_set, but that's way more annoying to deal with
              if !params_set.insert(param_name.clone()) {
                self.report_error(Problem::DuplicateParameter(param_name.to_string()), &span);
              }                
              
              // Get varity of parameter
              self.reader.skip_ws();
              let (varity, full_param_span) = if let Some((varity_token, varity_span)) = 
              self.reader.take_where(|t| matches!(t, 
                Some((RantToken::Question, _)) |
                Some((RantToken::Star, _)) | 
                Some((RantToken::Plus, _)))) 
              {
                (match varity_token {
                  // Optional parameter
                  RantToken::Question => Varity::Optional,
                  // Optional variadic parameter
                  RantToken::Star => Varity::VariadicStar,
                  // Required variadic parameter
                  RantToken::Plus => Varity::VariadicPlus,
                  _ => unreachable!()
                }, super_range(&span, &varity_span))
              } else {
                (Varity::Required, span)
              };
              
              let is_param_variadic = varity.is_variadic();
                
              // Check for varity issues
              if is_sig_variadic && is_param_variadic {
                // Soft error on multiple variadics
                self.report_error(Problem::MultipleVariadicParams, &full_param_span);
              } else if !Varity::is_valid_order(last_varity, varity) {
                // Soft error on bad varity order
                self.report_error(Problem::InvalidParamOrder(last_varity.to_string(), varity.to_string()), &full_param_span);
              }

              last_varity = varity;
              is_sig_variadic |= is_param_variadic;

              // Read default value expr on optional params
              if matches!(varity, Varity::Optional) {
                let ParsedSequence {
                  sequence: default_value_seq,
                  end_type: default_value_end_type,
                  ..
                } = self.parse_sequence(SequenceParseMode::ParamDefaultValue)?;

                let should_continue = match default_value_end_type {
                  SequenceEndType::ParamDefaultValueSeparator => true,
                  SequenceEndType::ParamDefaultValueSignatureEnd => false,
                  SequenceEndType::ProgramEnd => {
                    self.report_error(Problem::UnclosedFunctionSignature, &start_span);
                    return Err(())
                  }
                  _ => unreachable!(),
                };

                let opt_param = Parameter {
                  name: param_name,
                  varity: Varity::Optional,
                  default_value_expr: (!default_value_seq.is_empty()).then(|| Rc::new(default_value_seq))
                };

                // Add parameter to list
                params.push((opt_param, full_param_span.end .. self.reader.last_token_span().start));

                // Keep reading other params if needed
                if should_continue {
                  continue 'read_params
                } else {
                  break 'read_params
                }
              }

              // Handle other varities here...

              let param = Parameter {
                name: param_name,
                varity,
                default_value_expr: None,
              };
              
              // Add parameter to list
              params.push((param, full_param_span));
                
              // Check if there are more params or if the signature is done
              match self.reader.next_solid() {
                // ';' means there are more params
                Some((RantToken::Semi, ..)) => {
                  continue 'read_params
                },
                // ']' means end of signature
                Some((RantToken::RightBracket, ..)) => {
                  break 'read_params
                },
                // Emit a hard error on anything else
                Some((_, span)) => {
                  self.report_error(Problem::UnexpectedToken(self.reader.last_token_string().to_string()), &span);
                  return Err(())
                },
                None => {
                  self.report_error(Problem::UnclosedFunctionSignature, &start_span);
                  return Err(())
                },
              }
            },
            // Error on early close
            Some((RantToken::RightBracket, span)) => {
              self.report_error(Problem::MissingIdentifier, &span);
              break 'read_params
            },
            // Error on anything else
            Some((.., span)) => {
              self.report_error(Problem::InvalidIdentifier(self.reader.last_token_string().to_string()), &span)
            },
            None => {
              self.report_error(Problem::UnclosedFunctionSignature, &start_span);
              return Err(())
            }
          }
        }
      },
      // ']' means there are no params-- fall through to the next step
      Some((RantToken::RightBracket, _)) => {},
      // Something weird is here, emit a hard error
      Some((.., span)) => {
        self.report_error(Problem::UnexpectedToken(self.reader.last_token_string().to_string()), &span);
        return Err(())
      },
      // Nothing is here, emit a hard error
      None => {
        self.report_error(Problem::UnclosedFunctionSignature, &start_span);
        return Err(())
      }
    }
      
    Ok(params)
  }
    
  /// Parses a function definition, anonymous function, or function call.
  fn parse_func_access(&mut self, flag: PrintFlag) -> ParseResult<Rst> {
    let start_span = self.reader.last_token_span();
    self.reader.skip_ws();
    // Check if we're defining a function (with [$|% ...]) or creating a closure (with [? ...])
    if let Some((func_access_type_token, func_access_type_span)) 
    = self.reader.take_where(|t| matches!(t, Some((RantToken::Dollar, ..)) | Some((RantToken::Percent, ..)) | Some((RantToken::Question, ..)))) {
      match func_access_type_token {
        // Function definition
        tt @ RantToken::Dollar | tt @ RantToken::Percent => {
          let is_const = matches!(tt, RantToken::Percent);

          // Name of variable function will be stored in
          let (func_path, _func_path_span) = self.parse_access_path(false)?;

          // Warn user if non-variable function definition is marked as a constant
          if is_const && !func_path.is_variable() {
            self.report_warning(Problem::NestedFunctionDefMarkedConstant, &func_access_type_span);
          }
          
          self.reader.skip_ws();

          let ((body, params, end_func_sig_span), captures) = self.capture_pass(|self_| {
            // Function params
            let params = self_.parse_func_params(&start_span)?;
            let end_func_sig_span = self_.reader.last_token_span();
            
            // Read function body
            let body = self_.parse_func_body(&params, false)?;
            
            Ok((body, params, end_func_sig_span))
          })?;

          // Track variable
          if func_path.is_variable() {
            if let Some(id) = &func_path.var_name() {
              let func_def_span = super_range(&start_span, &end_func_sig_span);
              self.track_variable(id, &func_path.kind(), is_const, VarRole::Function, &func_def_span);
            }
          }
          
          Ok(Rst::FuncDef(FunctionDef {
            body: Rc::new(body.with_name_str(format!("[{}]", func_path).as_str())),
            path: Rc::new(func_path),
            params: Rc::new(params.into_iter().map(|(p, _)| p).collect()),
            capture_vars: Rc::new(captures),
            is_const,
          }))
        },
        // Closure
        RantToken::Question => {
          // Closure params
          let params = self.parse_func_params(&start_span)?;
          self.reader.skip_ws();
          // Read function body
          let (body, captures) = self.capture_pass(|self_| self_.parse_func_body(&params, true))?;
          
          Ok(Rst::Closure(ClosureExpr {
            capture_vars: Rc::new(captures),
            body: Rc::new(body.with_name_str("closure")),
            params: Rc::new(params.into_iter().map(|(p, _)| p).collect()),
          }))
        },
        _ => unreachable!()
      }
    } else {
      // Function calls, both composed and otherwise
      
      // List of calls in chain. This will only contain one call if it's non-composed (chain of one).
      let mut calls: Vec<FunctionCall> = vec![];
      // Flag indicating whether call is composed (has multiple chained function calls)
      let mut is_composed = false;
      // Indicates whether the last call in the chain has been parsed
      let mut is_finished = false;
      // Indicates whether the chain has any temporal calls
      let mut is_chain_temporal = false;

      // Read all calls in chain
      while !is_finished {
        self.reader.skip_ws();
        // Argument list for current call
        let mut func_args = vec![];
        // Currently tracked temporal labels
        let mut temporal_index_labels: HashMap<InternalString, usize> = Default::default();
        // Next temporal index to be consumed
        let mut cur_temporal_index: usize = 0;
        // Anonymous call flag
        let is_anonymous = self.reader.eat_where(|t| matches!(t, Some((RantToken::Bang, ..))));
        // Temporal call flag
        let mut is_temporal = false;
        // Do the user-supplied args use the compose value?
        let mut is_compval_used = false;
        
        /// Reads arguments until a terminating / delimiting token is reached.
        macro_rules! parse_args {
          () => {{
            #[allow(unused_assignments)] // added because rustc whines about `spread_mode` being unused; that is a LIE
            loop {
              self.reader.skip_ws();
              let mut spread_mode = ArgumentSpreadMode::NoSpread;

              // Check for spread operators
              match self.reader.take_where(|t| matches!(t, Some((RantToken::Star, ..)) | Some((RantToken::Temporal, ..)) | Some((RantToken::TemporalLabeled(_), ..)))) {
                // Parametric spread
                Some((RantToken::Star, ..)) => {
                  self.reader.skip_ws();
                  spread_mode = ArgumentSpreadMode::Parametric;
                },
                // Unlabeled temporal spread
                Some((RantToken::Temporal, ..)) => {
                  is_temporal = true;
                  self.reader.skip_ws();
                  spread_mode = ArgumentSpreadMode::Temporal { label: cur_temporal_index };
                  cur_temporal_index += 1;
                },
                // Labeled temporal spread
                Some((RantToken::TemporalLabeled(label_str), ..)) => {
                  is_temporal = true;
                  self.reader.skip_ws();
                  let label_index = if let Some(label_index) = temporal_index_labels.get(&label_str) {
                    *label_index
                  } else {
                    let label_index = cur_temporal_index;
                    temporal_index_labels.insert(label_str.clone(), label_index);
                    cur_temporal_index += 1;
                    label_index
                  };
                  spread_mode = ArgumentSpreadMode::Temporal { label: label_index };
                },
                Some(_) => unreachable!(),
                None => {},
              }

              // Parse argument
              let ParsedSequence {
                sequence: arg_seq,
                end_type: arg_end,
                ..
              } = if is_composed {
                self.var_stack.push_layer();
                // Track compose value inside arguement scope
                let compval_stats = VarStats {
                  writes: 1,
                  reads: 0,
                  def_span: Default::default(), // we'll never need this anyway
                  is_const: true,
                  has_fallible_read: false,
                  role: VarRole::ComposeValue,
                };
                self.var_stack.define(Identifier::from(COMPOSE_VALUE_NAME), compval_stats);
                let parsed_arg_expr = self.parse_sequence_inner(SequenceParseMode::FunctionArg)?;
                is_compval_used |= self.var_stack.get(COMPOSE_VALUE_NAME).unwrap().reads > 0;
                self.analyze_top_vars();
                self.var_stack.pop_layer();
                parsed_arg_expr
              } else {
                self.parse_sequence(SequenceParseMode::FunctionArg)?
              };

              let arg = ArgumentExpr {
                expr: Rc::new(arg_seq),
                spread_mode,
              };
              func_args.push(arg);
              match arg_end {
                SequenceEndType::FunctionArgEndNext => continue,
                SequenceEndType::FunctionArgEndBreak => {
                  is_finished = true;
                  break
                },
                SequenceEndType::FunctionArgEndToCompose => {
                  is_composed = true;
                  break
                },
                SequenceEndType::ProgramEnd => {
                  self.report_error(Problem::UnclosedFunctionCall, &self.reader.last_token_span());
                  return Err(())
                },
                _ => unreachable!()
              }
            }
          }}
        }

        /// If the composition value wasn't used, inserts it as the first argument.
        macro_rules! fallback_compose {
          () => {
            if calls.len() > 0 && !is_compval_used {
              let arg = ArgumentExpr {
                expr: Rc::new(Sequence::one(Rst::ComposeValue, &self.info)),
                spread_mode: ArgumentSpreadMode::NoSpread,
              };
              func_args.insert(0, arg);
            }
          }
        }
        
        self.reader.skip_ws();

        // What kind of function call is this?
        if is_anonymous {
          // Anonymous function call
          
          self.var_stack.push_layer();
          // Track compose value inside anonymous function access scope
          let compval_stats = VarStats {
            writes: 1,
            reads: 0,
            def_span: Default::default(), // we'll never need this anyway
            is_const: true,
            has_fallible_read: false,
            role: VarRole::ComposeValue,
          };
          self.var_stack.define(Identifier::from(COMPOSE_VALUE_NAME), compval_stats);
          let ParsedSequence {
            sequence: func_expr,
            end_type: func_expr_end,
            ..
          } = self.parse_sequence_inner(SequenceParseMode::AnonFunctionExpr)?;
          is_compval_used |= self.var_stack.get(COMPOSE_VALUE_NAME).unwrap().reads > 0;
          self.analyze_top_vars();
          self.var_stack.pop_layer();
          
          // Parse arguments if available
          match func_expr_end {
            // No args, fall through
            SequenceEndType::AnonFunctionExprNoArgs => {
              is_finished = true;
            },
            // Parse arguments
            SequenceEndType::AnonFunctionExprToArgs => parse_args!(),
            // Compose without args
            SequenceEndType::AnonFunctionExprToCompose => {
              is_composed = true;
            }
            _ => unreachable!()
          }

          fallback_compose!();
          
          // Create final node for anon function call
          let fcall = FunctionCall {
            target: FunctionCallTarget::Expression(Rc::new(func_expr)),
            arguments: Rc::new(func_args),
            flag,
            is_temporal,
          };

          calls.push(fcall);
        } else {
          // Named function call
          let (func_path, func_path_span) = self.parse_access_path(false)?;
          if let Some((token, _)) = self.reader.next_solid() {
            match token {
              // No args, fall through
              RantToken::RightBracket => {
                is_finished = true;
              },
              // Parse arguments
              RantToken::Colon => parse_args!(),
              // Compose without args
              RantToken::Compose => {
                is_composed = true;
              }
              _ => {
                self.unexpected_last_token_error();
                return Err(())
              }
            }

            fallback_compose!();
            
            // Record access to function
            self.track_variable_access(&func_path, false, false, &func_path_span);
            
            // Create final node for function call
            let fcall = FunctionCall {
              target: FunctionCallTarget::Path(Rc::new(func_path)),
              arguments: Rc::new(func_args),
              flag,
              is_temporal,
            };

            calls.push(fcall);
          } else {
            // Found EOF instead of end of function call, emit hard error
            self.report_error(Problem::UnclosedFunctionCall, &self.reader.last_token_span());
            return Err(())
          }
        }

        is_chain_temporal |= is_temporal;
      }

      // Return the finished node
      Ok(if is_composed {
        Rst::ComposedCall(ComposedFunctionCall {
          flag,
          is_temporal: is_chain_temporal,
          steps: Rc::new(calls),
        })
      } else {
        Rst::FuncCall(calls.drain(..).next().unwrap())
      })
    }
  }
    
  #[inline]
  fn parse_access_path_kind(&mut self) -> AccessPathKind {    
    if let Some((token, _span)) = self.reader.take_where(
      |t| matches!(t, Some((RantToken::Slash, _)) | Some((RantToken::Caret, _))
    )) {
      match token {
        // Accessor is explicit global
        RantToken::Slash => {
          AccessPathKind::ExplicitGlobal
        },
        // Accessor is for parent scope (descope operator)
        RantToken::Caret => {
          let mut descope_count = 1;
          loop {
            if !self.reader.eat_where(|t| matches!(t, Some((RantToken::Caret, _)))) {
              break AccessPathKind::Descope(descope_count)
            }
            descope_count += 1;
          }
        },
        _ => unreachable!()
      }
    } else {
      AccessPathKind::Local
    }
  }
  
  /// Parses an access path.
  #[inline]
  fn parse_access_path(&mut self, allow_anonymous: bool) -> ParseResult<(AccessPath, Range<usize>)> {
    self.reader.skip_ws();
    let mut idparts = vec![];
    let start_span = self.reader.last_token_span();
    let mut access_kind = AccessPathKind::Local;

    if allow_anonymous && self.reader.eat_where(|t| matches!(t, Some((RantToken::Bang, ..)))) {
      self.reader.skip_ws();
      let ParsedSequence {
        sequence: anon_expr,
        end_type: anon_end_type,
        ..
      } = self.parse_sequence(SequenceParseMode::SingleItem)?;
      match anon_end_type {
        SequenceEndType::SingleItemEnd => {
          idparts.push(AccessPathComponent::AnonymousValue(Rc::new(anon_expr)));
        },
        SequenceEndType::ProgramEnd => {
          self.report_error(Problem::UnclosedVariableAccess, &self.reader.last_token_span());
          return Err(())
        },
        _ => unreachable!(),
      }
    } else {
      // Check for global/descope specifiers
      access_kind = self.parse_access_path_kind();
      
      let first_part = self.reader.next_solid();
      
      // Parse the first part of the path
      match first_part {
        // The first part of the path may only be a variable name (for now)
        Some((RantToken::Fragment, span)) => {
          let varname = Identifier::new(self.reader.last_token_string());
          if is_valid_ident(varname.as_str()) {
            idparts.push(AccessPathComponent::Name(varname));
          } else {
            self.report_error(Problem::InvalidIdentifier(varname.to_string()), &span);
          }
        },
        // An expression can also be used to provide the variable
        Some((RantToken::LeftBrace, _)) => {
          let dynamic_key_expr = self.parse_dynamic_expr(false)?;
          idparts.push(AccessPathComponent::DynamicKey(Rc::new(dynamic_key_expr)));
        },
        // TODO: Check for dynamic slices here too!
        // First path part can't be a slice
        Some((RantToken::Colon, span)) => {
          self.reader.take_where(|t| matches!(t, Some((RantToken::Integer(_), ..))));
          self.report_error(Problem::AccessPathStartsWithSlice, &super_range(&span, &self.reader.last_token_span()));
        }
        // Prevent other slice forms
        Some((RantToken::Integer(_), span)) => {
          self.reader.skip_ws();
          if self.reader.eat_where(|t| matches!(t, Some((RantToken::Colon, ..)))) {
            self.report_error(Problem::AccessPathStartsWithSlice, &super_range(&span, &self.reader.last_token_span()));
          } else {
            self.report_error(Problem::AccessPathStartsWithIndex, &span);
          }
        },
        Some((.., span)) => {
          self.report_error(Problem::InvalidIdentifier(self.reader.last_token_string().to_string()), &span);
        },
        None => {
          self.report_error(Problem::MissingIdentifier, &start_span);
          return Err(())
        }
      }
    }
    
    // Parse the rest of the path
    loop {
      // We expect a '/' between each component, so check for that first.
      // If it's anything else, terminate the path and return it.
      self.reader.skip_ws();
      if self.reader.eat_where(|t| matches!(t, Some((RantToken::Slash, ..)))) {
        // From here we expect to see either another key (fragment) or index (integer).
        // If it's anything else, return a syntax error.
        let component = self.reader.next_solid();
        match component {
          // Key
          Some((RantToken::Fragment, span)) => {
            let varname = Identifier::new(self.reader.last_token_string());
            if is_valid_ident(varname.as_str()) {
              idparts.push(AccessPathComponent::Name(varname));
            } else {
              self.report_error(Problem::InvalidIdentifier(varname.to_string()), &span);
            }
          },
          // Index or slice with static from-bound
          Some((RantToken::Integer(i), _)) => {
            self.reader.skip_ws();
            // Look for a colon to see if it's a slice
            if self.reader.eat_where(|t| matches!(t, Some((RantToken::Colon, ..)))) {
              self.reader.skip_ws();
              match self.reader.peek() {
                // Between-slice with static from- + to-bounds
                Some((RantToken::Integer(j), ..)) => {
                  let j = *j;
                  self.reader.skip_one();
                  idparts.push(AccessPathComponent::Slice(SliceExpr::Between(SliceIndex::Static(i), SliceIndex::Static(j))));
                },
                // Between-slice with static from-bound + dynamic to-bound
                Some((RantToken::LeftBrace, ..)) => {
                  let to_expr = Rc::new(self.parse_dynamic_expr(true)?);
                  idparts.push(AccessPathComponent::Slice(SliceExpr::Between(SliceIndex::Static(i), SliceIndex::Dynamic(to_expr))));
                },
                // From-slice with static from-bound
                Some((RantToken::Slash, ..)) | 
                Some((RantToken::RightAngle, ..)) | 
                Some((RantToken::Equals, ..)) | 
                Some((RantToken::Question, ..)) |
                Some((RantToken::Semi, ..)) => {
                  idparts.push(AccessPathComponent::Slice(SliceExpr::From(SliceIndex::Static(i))));
                },
                // Found something weird as the to-bound, emit an error
                Some(_) => {
                  self.reader.next();
                  let token = self.reader.last_token_string().to_string();
                  self.report_error(Problem::InvalidSliceBound(token), &self.reader.last_token_span());
                },
                None => {
                  self.report_error(Problem::UnclosedVariableAccess, &super_range(&start_span, &self.reader.last_token_span()));
                  return Err(())
                }
              }
            } else {
              // No colon, so it's an index
              idparts.push(AccessPathComponent::Index(i));
            }
          },
          // Full- or to-slice
          Some((RantToken::Colon, _)) => {
            self.reader.skip_ws();
            match self.reader.peek() {
              // To-slice with static bound
              Some((RantToken::Integer(to), ..)) => {
                let to = *to;
                self.reader.skip_one();
                idparts.push(AccessPathComponent::Slice(SliceExpr::To(SliceIndex::Static(to))));
              },
              // To-slice with dynamic bound
              Some((RantToken::LeftBrace, ..)) => {
                let to_expr = Rc::new(self.parse_dynamic_expr(true)?);
                idparts.push(AccessPathComponent::Slice(SliceExpr::To(SliceIndex::Dynamic(to_expr))));
              },
              // Full-slice
              Some((RantToken::Slash, ..)) | 
              Some((RantToken::RightAngle, ..)) | 
              Some((RantToken::Equals, ..)) | 
              Some((RantToken::Question, ..)) |
              Some((RantToken::Semi, ..)) => {
                idparts.push(AccessPathComponent::Slice(SliceExpr::Full));
              },
              // Found something weird as the to-bound, emit an error
              Some(_) => {
                self.reader.next();
                let token = self.reader.last_token_string().to_string();
                self.report_error(Problem::InvalidSliceBound(token), &self.reader.last_token_span());
              },
              None => {
                self.report_error(Problem::UnclosedVariableAccess, &super_range(&start_span, &self.reader.last_token_span()));
                return Err(())
              }
            }
          },
          // Dynamic key or slice with dynamic from-bound
          Some((RantToken::LeftBrace, _)) => {
            let expr = Rc::new(self.parse_dynamic_expr(false)?);
            self.reader.skip_ws();
            // Look for a colon to see if it's a slice
            if self.reader.eat_where(|t| matches!(t, Some((RantToken::Colon, ..)))) {
              self.reader.skip_ws();
              match self.reader.peek() {
                // Between-slice with a dynamic from-bound + static to-bound
                Some((RantToken::Integer(to), ..)) => {
                  let to = *to;
                  self.reader.skip_one();
                  idparts.push(AccessPathComponent::Slice(SliceExpr::Between(SliceIndex::Dynamic(expr), SliceIndex::Static(to))));
                },
                // Between-slice with dynamic from- + to-bounds
                Some((RantToken::LeftBrace, ..)) => {
                  let to_expr = Rc::new(self.parse_dynamic_expr(true)?);
                  idparts.push(AccessPathComponent::Slice(SliceExpr::Between(SliceIndex::Dynamic(expr), SliceIndex::Dynamic(to_expr))));
                },
                // From-slice with dynamic bound
                Some((RantToken::Slash, ..)) |
                Some((RantToken::RightAngle, ..)) | 
                Some((RantToken::Equals, ..)) | 
                Some((RantToken::Question, ..)) |
                Some((RantToken::Semi, ..)) => {
                  idparts.push(AccessPathComponent::Slice(SliceExpr::From(SliceIndex::Dynamic(expr))));
                },
                // Found something weird as the to-bound, emit an error
                Some(_) => {
                  self.reader.next();
                  let token = self.reader.last_token_string().to_string();
                  self.report_error(Problem::InvalidSliceBound(token), &self.reader.last_token_span());
                },
                None => {
                  self.report_error(Problem::UnclosedVariableAccess, &super_range(&start_span, &self.reader.last_token_span()));
                  return Err(())
                }
              }
            } else {
              // No colon, so it's an dynamic key
              idparts.push(AccessPathComponent::DynamicKey(expr));
            }
          },
          Some((.., span)) => {
            // error
            self.report_error(Problem::InvalidIdentifier(self.reader.last_token_string().to_string()), &span);
          },
          None => {
            self.report_error(Problem::MissingIdentifier, &self.reader.last_token_span());
            return Err(())
          }
        }
      } else {
        return Ok((AccessPath::new(idparts, access_kind), start_span.start .. self.reader.last_token_span().start))
      }
    }
  }
    
  /// Parses a dynamic expression (a linear block).
  fn parse_dynamic_expr(&mut self, expect_opening_brace: bool) -> ParseResult<Sequence> {
    if expect_opening_brace && !self.reader.eat_where(|t| matches!(t, Some((RantToken::LeftBrace, _)))) {
      self.report_error(Problem::ExpectedToken("{".to_owned()), &self.reader.last_token_span());
      return Err(())
    }
    
    let start_span = self.reader.last_token_span();
    let ParsedSequence { sequence, end_type, .. } = self.parse_sequence(SequenceParseMode::DynamicKey)?;
    
    match end_type {
      SequenceEndType::DynamicKeyEnd => {},
      SequenceEndType::ProgramEnd => {
        // Hard error if block isn't closed
        let err_span = start_span.start .. self.source.len();
        self.report_error(Problem::UnclosedBlock, &err_span);
        return Err(())
      },
      _ => unreachable!()
    }
    
    Ok(sequence)
  }

  /// Parses a function body and DOES NOT capture variables.
  fn parse_func_body(&mut self, params: &Vec<(Parameter, Range<usize>)>, allow_inline: bool) -> ParseResult<Sequence> {
    self.reader.skip_ws();

    let is_block_body = if allow_inline {
      // Determine if the body is a block and eat the opening brace if available
      self.reader.eat_where(|t| matches!(t, Some((RantToken::LeftBrace, _))))
    } else {
      if !self.reader.eat_where(|t| matches!(t, Some((RantToken::LeftBrace, _)))) {
        self.report_error(Problem::ExpectedToken("{".to_owned()), &self.reader.last_token_span());
        return Err(())
      }
      true
    };

    let start_span = self.reader.last_token_span();

    // Define each parameter as a variable in the current var_stack frame so they are not accidentally captured
    for (param, span) in params {
      self.var_stack.define(param.name.clone(), VarStats {
        reads: 0,
        writes: 1,
        def_span: span.clone(),
        is_const: true,
        has_fallible_read: false,
        role: if param.is_optional() && param.default_value_expr.is_none() {
          VarRole::FallibleOptionalArgument
        } else { 
          VarRole::Argument 
        }
      });
    }

    // parse_sequence_inner() is used here so that the new stack frame can be customized before use
    let ParsedSequence { sequence, end_type, .. } = self.parse_sequence_inner(if is_block_body {
      SequenceParseMode::FunctionBodyBlock
    } else {
      SequenceParseMode::SingleItem
    })?;

    match end_type {
      SequenceEndType::FunctionBodyEnd | SequenceEndType::SingleItemEnd => {},
      SequenceEndType::ProgramEnd => {
        let err_span = start_span.start .. self.source.len();
        self.report_error(if is_block_body { 
          Problem::UnclosedFunctionBody 
        } else { 
          Problem::MissingFunctionBody 
        }, &err_span);
        return Err(())
      },
      _ => unreachable!()
    }

    Ok(sequence)
  }
  
  fn capture_pass<T>(&mut self, parse_func: impl FnOnce(&mut Self) -> ParseResult<T>) -> ParseResult<(T, Vec<Identifier>)> {
    // Since we're about to push another var_stack frame, we can use the current depth of var_stack as the index
    let capture_height = self.var_stack.depth();

    // Push a new capture frame
    self.capture_stack.push((capture_height, Default::default()));

    // Push a new variable frame
    self.var_stack.push_layer();

    // Call parse_func
    let parse_out = parse_func(self)?;

    // Run static analysis on variable/param usage
    self.analyze_top_vars();

    self.var_stack.pop_layer();

    // Pop the topmost capture frame and grab the set of captures
    let (_, mut capture_set) = self.capture_stack.pop().unwrap();

    Ok((parse_out, capture_set.drain().collect()))
  }
    
  /// Parses a block.
  fn parse_block(&mut self, expect_opening_brace: bool, flag: PrintFlag) -> ParseResult<Block> {
    if expect_opening_brace && !self.reader.eat_where(|t| matches!(t, Some((RantToken::LeftBrace, _)))) {
      self.report_error(Problem::ExpectedToken("{".to_owned()), &self.reader.last_token_span());
      return Err(())
    }
    
    // Get position of starting brace for error reporting
    let start_pos = self.reader.last_token_pos();
    // Keeps track of inherited hinting
    let mut auto_hint = false;
    // Is the block weighted?
    let mut is_weighted = false;
    // Block content
    let mut elements = vec![];
    
    loop {
      let ParsedSequence { 
        sequence, 
        end_type, 
        is_printing, 
        extras 
      } = self.parse_sequence(SequenceParseMode::BlockElement)?;
      
      auto_hint |= is_printing;

      let element = BlockElement {
        main: Rc::new(sequence),
        weight: if let Some(ParsedSequenceExtras::WeightedBlockElement { weight_expr }) = extras {
          is_weighted = true;
          // Optimize constant weights
          Some(match (weight_expr.len(), weight_expr.first().map(Rc::as_ref)) {
            (1, Some(Rst::Integer(n))) => BlockWeight::Constant(*n as f64),
            (1, Some(Rst::Float(n))) => BlockWeight::Constant(*n),
            _ => BlockWeight::Dynamic(weight_expr)
          })
        } else {
          None
        },
      };
      
      match end_type {
        SequenceEndType::BlockDelim => {
          elements.push(element);
        },
        SequenceEndType::BlockEnd => {
          elements.push(element);
          break
        },
        SequenceEndType::ProgramEnd => {
          // Hard error if block isn't closed
          let err_span = start_pos .. self.source.len();
          self.report_error(Problem::UnclosedBlock, &err_span);
          return Err(())
        },
        _ => unreachable!()
      }
    }
    
    // Figure out the printflag before returning the block
    if auto_hint && flag != PrintFlag::Sink {
      Ok(Block::new(PrintFlag::Hint, is_weighted, elements))
    } else {
      Ok(Block::new(flag, is_weighted, elements))
    }
  }
  
  /// Parses an identifier.
  fn parse_ident(&mut self) -> ParseResult<Identifier> {
    if let Some((token, span)) = self.reader.next_solid() {
      match token {
        RantToken::Fragment => {
          let idstr = self.reader.last_token_string();
          if !is_valid_ident(idstr.as_str()) {
            self.report_error(Problem::InvalidIdentifier(idstr.to_string()), &span);
          }
          Ok(Identifier::new(idstr))
        },
        _ => {
          self.unexpected_last_token_error();
          Err(())
        }
      }
    } else {
      self.report_error(Problem::MissingIdentifier, &self.reader.last_token_span());
      Err(())
    }
  }

  #[inline]
  fn track_variable(&mut self, id: &Identifier, access_kind: &AccessPathKind, is_const: bool, role: VarRole, def_span: &Range<usize>) {
    // Check if there's already a variable with this name
    let (prev_tracker, requested_depth, found_depth) = match access_kind {        
      AccessPathKind::Local => {
        (self.var_stack.get(id), 0, self.var_stack.depth_of(id))
      },
      AccessPathKind::Descope(n) => {
        let (v, d) = self.var_stack
          .get_parent_depth(id, *n)
          .map(|(v, d)| (Some(v), Some(d)))
          .unwrap_or_default();
        (v, *n, d)
      },
      AccessPathKind::ExplicitGlobal => {
        let rd = self.var_stack.depth();
        let (v, d) = self.var_stack
          .get_parent_depth(id, rd)
          .map(|(v, d)| (Some(v), Some(d)))
          .unwrap_or_default();
        (v, rd, d)
      },
    };

    // Check for constant redef
    if let Some(prev_tracker) = prev_tracker {
      if prev_tracker.is_const && found_depth == Some(requested_depth) {
        self.report_error(Problem::ConstantRedefinition(id.to_string()), def_span);
      }
    }

    // Create variable tracking info
    let v = VarStats {
      writes: 0,
      reads: 0,
      def_span: def_span.clone(),
      has_fallible_read: false,
      is_const,
      role,
    };

    // Add to stack
    match access_kind {
      AccessPathKind::Local => {
        self.var_stack.define(id.clone(), v);
      },
      AccessPathKind::Descope(n) => {
        self.var_stack.define_parent(id.clone(), v, *n);
      },
      AccessPathKind::ExplicitGlobal => {
        self.var_stack.define_parent(id.clone(), v, self.var_stack.depth());
      },
    }
  }

  #[inline]
  fn track_variable_access(&mut self, path: &AccessPath, is_write: bool, fallback_hint: bool, span: &Range<usize>) {
    // Handle access stats
    if let Some(id) = &path.var_name() {
      let tracker = match path.kind() {
        AccessPathKind::Local => {
          self.var_stack.get_mut(id)
        },
        AccessPathKind::Descope(n) => {
          self.var_stack.get_parent_mut(id, n)
        },
        AccessPathKind::ExplicitGlobal => {
          self.var_stack.get_parent_mut(id, self.var_stack.depth())
        }
      };

      // Update tracker
      if let Some(tracker) = tracker {
        if is_write {
          tracker.writes += 1;

          if tracker.is_const {
            self.report_error(Problem::ConstantReassignment(id.to_string()), span);
          }
        } else {
          tracker.add_read(!fallback_hint);

          // Warn the user if they're accessing a fallible optional argument without a fallback
          if tracker.has_fallible_read && tracker.role == VarRole::FallibleOptionalArgument {
            self.report_warning(Problem::FallibleOptionalArgAccess(id.to_string()), span);
          }
        }
      }
    }
    
    // Handle captures
    if path.kind().is_local() {
      // At least one capture frame must exist
      if let Some((capture_frame_height, captures)) = self.capture_stack.last_mut() {
        // Must be accessing a variable
        if let Some(id) = path.var_name() {
          // Variable must not exist in the current scope of the active function
          if self.var_stack.height_of(&id).unwrap_or_default() < *capture_frame_height {
            captures.insert(id);
          }
        }
      }
    }
  }

  #[inline]
  fn analyze_top_vars(&mut self) {
    let mut unused_vars: Vec<(String, VarRole, Range<usize>)> = vec![];

    // Can't warn inside the loop due to bOrRoWiNg RuLeS!
    // Have to store the warning contents in a vec first...
    for (id, tracker) in self.var_stack.iter_top() {
      if tracker.reads == 0 {
        unused_vars.push((id.to_string(), tracker.role, tracker.def_span.clone()));
      }
    }

    // Generate warnings
    unused_vars.sort_by(|(.., a_span), (.., b_span)| a_span.start.cmp(&b_span.start));
    for (name, role, span) in unused_vars {
      match role {
        VarRole::Normal => self.report_warning(Problem::UnusedVariable(name), &span),
        VarRole::Argument => self.report_warning(Problem::UnusedParameter(name), &span),
        VarRole::Function => self.report_warning(Problem::UnusedFunction(name), &span),
        // Ignore any other roles
        _ => {},
      }
    }
  }
    
  /// Parses one or more accessors (getter/setter/definition).
  #[inline(always)]
  fn parse_accessor(&mut self) -> ParseResult<Vec<Rst>> {
    let mut accessors = vec![];

    macro_rules! add_accessor {
      ($rst:expr) => {{
        let rst = $rst;
        accessors.push(rst);
      }}
    }
    
    'read: loop {      
      self.reader.skip_ws();

      // Check if the accessor ends here as long as there's at least one component
      if !accessors.is_empty() && self.reader.eat_where(|t| matches!(t, Some((RantToken::RightAngle, ..)))) {
        break
      }
      
      let (is_def, is_const_def) = if let Some((def_token, ..)) 
      = self.reader.take_where(|t| matches!(t, Some((RantToken::Dollar, ..)) | Some((RantToken::Percent, ..)))) {
        match def_token {
          // Variable declaration
          RantToken::Dollar => (true, false),
          // Constant declaration
          RantToken::Percent => (true, true),
          _ => unreachable!()
        }
      } else {
        (false, false)
      };

      let access_start_span = self.reader.last_token_span();

      self.reader.skip_ws();
      
      // Check if it's a definition. If not, it's a getter or setter
      if is_def {
        // Check for accessor modifiers
        let access_kind = self.parse_access_path_kind();
        self.reader.skip_ws();
        // Read name of variable we're defining
        let var_name = self.parse_ident()?;

        let def_span = access_start_span.start .. self.reader.last_token_span().end;
        
        if let Some((token, _token_span)) = self.reader.next_solid() {
          match token {
            // Empty definition
            RantToken::RightAngle => {              
              if is_const_def {
                self.track_variable(&var_name, &access_kind, true, VarRole::Normal, &def_span);
                add_accessor!(Rst::ConstDef(var_name, access_kind, None));
              } else {
                self.track_variable(&var_name, &access_kind, false, VarRole::Normal, &def_span);
                add_accessor!(Rst::VarDef(var_name, access_kind, None));
              }
              break 'read
            },
            // Accessor delimiter
            RantToken::Semi => {
              if is_const_def {
                self.track_variable(&var_name, &access_kind, true, VarRole::Normal, &def_span);
                add_accessor!(Rst::ConstDef(var_name, access_kind, None));
              } else {
                self.track_variable(&var_name, &access_kind, false, VarRole::Normal, &def_span);
                add_accessor!(Rst::VarDef(var_name, access_kind, None));
              }
              continue 'read;
            },
            // Definition and assignment
            RantToken::Equals => {
              self.reader.skip_ws();
              let ParsedSequence { 
                sequence: setter_expr, 
                end_type: setter_end_type, 
                .. 
              } = self.parse_sequence(SequenceParseMode::VariableAssignment)?;

              let def_span = access_start_span.start .. self.reader.last_token_span().start;
              if is_const_def {
                self.track_variable(&var_name, &access_kind, true, VarRole::Normal, &def_span);
                add_accessor!(Rst::ConstDef(var_name, access_kind, Some(Rc::new(setter_expr))));
              } else {
                self.track_variable(&var_name, &access_kind, false, VarRole::Normal, &def_span);
                add_accessor!(Rst::VarDef(var_name, access_kind, Some(Rc::new(setter_expr))));
              }
              
              match setter_end_type {
                SequenceEndType::VariableAssignDelim => {
                  continue 'read
                },
                SequenceEndType::VariableAccessEnd => {
                  break 'read
                },
                SequenceEndType::ProgramEnd => {
                  self.report_error(Problem::UnclosedVariableAccess, &self.reader.last_token_span());
                  return Err(())
                },
                _ => unreachable!()
              }
            },
            // Ran into something we don't support
            _ => {
              self.unexpected_last_token_error();
              return Err(())
            }
          }
        } else {
          self.report_error(Problem::UnclosedVariableAccess, &self.reader.last_token_span());
          return Err(())
        }
      } else {
        // Read the path to what we're accessing
        let mut is_depth_op = false;
        let (var_path, var_path_span) = self.parse_access_path(true)?;
        
        self.reader.skip_ws();

        // Check for depth operator
        if let Some((_, depth_op_range)) = self.reader.take_where(|t| matches!(t, Some((RantToken::And, _)))) {
          if var_path.is_variable() && var_path.var_name().is_some() {
            is_depth_op = true;
          } else if var_path.len() == 1 && matches!(var_path.first(), Some(AccessPathComponent::DynamicKey(..))) {
            self.report_error(Problem::DynamicDepth, &depth_op_range);
          } else {
            self.report_error(Problem::InvalidDepthUsage, &depth_op_range);
          }
        }
        
        if let Some((token, cur_token_span)) = self.reader.next_solid() {
          match token {
            // If we hit a '>', it's a getter
            RantToken::RightAngle => {
              self.track_variable_access(&var_path, false, false, &var_path_span);
              add_accessor!(if is_depth_op {
                Rst::VarDepth(var_path.var_name().unwrap(), var_path.kind(), None)
              } else { 
                Rst::VarGet(Rc::new(var_path), None)
              });
              break 'read;
            },
            // If we hit a ';', it's a getter with another accessor chained after it
            RantToken::Semi => {
              self.track_variable_access(&var_path, false, false, &var_path_span);
              add_accessor!(if is_depth_op {
                Rst::VarDepth(var_path.var_name().unwrap(), var_path.kind(), None)
              } else { 
                Rst::VarGet(Rc::new(var_path), None)
              });
              continue 'read;
            },
            // If we hit a `?`, it's a getter with a fallback
            RantToken::Question => {
              self.reader.skip_ws();
              let ParsedSequence {
                sequence: fallback_expr,
                end_type: fallback_end_type,
                ..
              } = self.parse_sequence(SequenceParseMode::AccessorFallbackValue)?;

              self.track_variable_access(&var_path, false, true, &var_path_span);

              add_accessor!(if is_depth_op {
                Rst::VarDepth(var_path.var_name().unwrap(), var_path.kind(), Some(Rc::new(fallback_expr)))
              } else { 
                Rst::VarGet(Rc::new(var_path), Some(Rc::new(fallback_expr)))
              });

              match fallback_end_type {
                SequenceEndType::AccessorFallbackValueToDelim => continue 'read,
                SequenceEndType::AccessorFallbackValueToEnd => break 'read,
                // Error
                SequenceEndType::ProgramEnd => {
                  self.report_error(Problem::UnclosedVariableAccess, &cur_token_span);
                  return Err(())
                },
                _ => unreachable!()
              }
            },
            // If we hit a '=' here, it's a setter
            RantToken::Equals => {
              self.reader.skip_ws();
              let ParsedSequence {
                sequence: setter_rhs_expr,
                end_type: setter_rhs_end,
                ..
              } = self.parse_sequence(SequenceParseMode::VariableAssignment)?;
              let assign_end_span = self.reader.last_token_span();
              let setter_span = super_range(&access_start_span, &assign_end_span);
              // Don't allow setters directly on anonymous values
              if var_path.is_anonymous() && var_path.len() == 1 {
                self.report_error(Problem::AnonValueAssignment, &setter_span);
              }

              self.track_variable_access(&var_path, true, false, &setter_span);
              add_accessor!(Rst::VarSet(Rc::new(var_path), Rc::new(setter_rhs_expr)));

              // Assignment is not valid if we're using depth operator
              if is_depth_op {
                self.report_error(Problem::DepthAssignment, &(cur_token_span.start .. assign_end_span.start));
              }

              match setter_rhs_end {
                // Accessor was terminated
                SequenceEndType::VariableAccessEnd => {                  
                  break 'read;
                },
                // Expression ended with delimiter
                SequenceEndType::VariableAssignDelim => {
                  continue 'read;
                },
                // Error
                SequenceEndType::ProgramEnd => {
                  self.report_error(Problem::UnclosedVariableAccess, &self.reader.last_token_span());
                  return Err(())
                },
                _ => unreachable!()
              }
            },
            // Anything else is an error
            _ => {
              self.unexpected_last_token_error();
              return Err(())
            }
          }
        } else {
          self.report_error(Problem::UnclosedVariableAccess, &self.reader.last_token_span());
          return Err(())
        }
      }
    }
    
    Ok(accessors)
  }
}