Files @ 97b87404ffa5
Branch filter:

Location: CSY/reowolf/src/protocol/parser/pass_definitions.rs

97b87404ffa5 80.3 KiB application/rls-services+xml Show Annotation Show as Raw Download as Raw
mh
WIP on performance fixes
   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
use crate::protocol::ast::*;
use super::symbol_table::*;
use super::{Module, ModuleCompilationPhase, PassCtx};
use super::tokens::*;
use super::token_parsing::*;
use super::pass_definitions_types::*;

use crate::protocol::input_source::{InputSource, InputPosition, InputSpan, ParseError};
use crate::collections::*;

/// Parses all the tokenized definitions into actual AST nodes.
pub(crate) struct PassDefinitions {
    // State associated with the definition currently being processed
    cur_definition: DefinitionId,
    // Itty bitty parsing machines
    type_parser: ParserTypeParser,
    // Temporary buffers of various kinds
    buffer: String,
    struct_fields: ScopedBuffer<StructFieldDefinition>,
    enum_variants: ScopedBuffer<EnumVariantDefinition>,
    union_variants: ScopedBuffer<UnionVariantDefinition>,
    variables: ScopedBuffer<VariableId>,
    expressions: ScopedBuffer<ExpressionId>,
    statements: ScopedBuffer<StatementId>,
    parser_types: ScopedBuffer<ParserType>,
}

impl PassDefinitions {
    pub(crate) fn new() -> Self {
        Self{
            cur_definition: DefinitionId::new_invalid(),
            type_parser: ParserTypeParser::new(),
            buffer: String::with_capacity(128),
            struct_fields: ScopedBuffer::with_capacity(128),
            enum_variants: ScopedBuffer::with_capacity(128),
            union_variants: ScopedBuffer::with_capacity(128),
            variables: ScopedBuffer::with_capacity(128),
            expressions: ScopedBuffer::with_capacity(128),
            statements: ScopedBuffer::with_capacity(128),
            parser_types: ScopedBuffer::with_capacity(128),
        }
    }

    pub(crate) fn parse(&mut self, modules: &mut [Module], module_idx: usize, ctx: &mut PassCtx) -> Result<(), ParseError> {
        let module = &modules[module_idx];
        let module_range = &module.tokens.ranges[0];
        debug_assert_eq!(module.phase, ModuleCompilationPhase::ImportsResolved);
        debug_assert_eq!(module_range.range_kind, TokenRangeKind::Module);

        // Although we only need to parse the definitions, we want to go through
        // code ranges as well such that we can throw errors if we get
        // unexpected tokens at the module level of the source.
        let mut range_idx = module_range.first_child_idx;
        loop {
            let range_idx_usize = range_idx as usize;
            let cur_range = &module.tokens.ranges[range_idx_usize];

            match cur_range.range_kind {
                TokenRangeKind::Module => unreachable!(), // should not be reachable
                TokenRangeKind::Pragma | TokenRangeKind::Import => {
                    // Already fully parsed, fall through and go to next range
                },
                TokenRangeKind::Definition | TokenRangeKind::Code => {
                    // Visit range even if it is a "code" range to provide
                    // proper error messages.
                    self.visit_range(modules, module_idx, ctx, range_idx_usize)?;
                },
            }

            if cur_range.next_sibling_idx == NO_SIBLING {
                break;
            } else {
                range_idx = cur_range.next_sibling_idx;
            }
        }

        modules[module_idx].phase = ModuleCompilationPhase::DefinitionsParsed;

        Ok(())
    }

    fn visit_range(
        &mut self, modules: &[Module], module_idx: usize, ctx: &mut PassCtx, range_idx: usize
    ) -> Result<(), ParseError> {
        let module = &modules[module_idx];
        let cur_range = &module.tokens.ranges[range_idx];
        debug_assert!(cur_range.range_kind == TokenRangeKind::Definition || cur_range.range_kind == TokenRangeKind::Code);

        // Detect which definition we're parsing
        let mut iter = module.tokens.iter_range(cur_range);
        loop {
            let next = iter.next();
            if next.is_none() {
                return Ok(())
            }

            // Token was not None, so peek_ident returns None if not an ident
            let ident = peek_ident(&module.source, &mut iter);
            match ident {
                Some(KW_STRUCT) => self.visit_struct_definition(module, &mut iter, ctx)?,
                Some(KW_ENUM) => self.visit_enum_definition(module, &mut iter, ctx)?,
                Some(KW_UNION) => self.visit_union_definition(module, &mut iter, ctx)?,
                Some(KW_FUNCTION) => self.visit_function_definition(module, &mut iter, ctx)?,
                Some(KW_PRIMITIVE) | Some(KW_COMPOSITE) => self.visit_component_definition(module, &mut iter, ctx)?,
                _ => return Err(ParseError::new_error_str_at_pos(
                    &module.source, iter.last_valid_pos(),
                    "unexpected symbol, expected a keyword marking the start of a definition"
                )),
            }
        }
    }

    fn visit_struct_definition(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<(), ParseError> {
        consume_exact_ident(&module.source, iter, KW_STRUCT)?;
        let (ident_text, _) = consume_ident(&module.source, iter)?;

        // Retrieve preallocated DefinitionId
        let module_scope = SymbolScope::Module(module.root_id);
        let definition_id = ctx.symbols.get_symbol_by_name_defined_in_scope(module_scope, ident_text)
            .unwrap().variant.as_definition().definition_id;
        self.cur_definition = definition_id;

        // Parse struct definition
        consume_polymorphic_vars_spilled(&module.source, iter, ctx)?;

        let mut fields_section = self.struct_fields.start_section();
        consume_comma_separated(
            TokenKind::OpenCurly, TokenKind::CloseCurly, &module.source, iter, ctx,
            |source, iter, ctx| {
                let poly_vars = ctx.heap[definition_id].poly_vars();

                let start_pos = iter.last_valid_pos();
                let parser_type = self.type_parser.consume_parser_type(
                    iter, &ctx.heap, source, &ctx.symbols, poly_vars, definition_id,
                    module_scope, false, None
                )?;
                let field = consume_ident_interned(source, iter, ctx)?;
                Ok(StructFieldDefinition{
                    span: InputSpan::from_positions(start_pos, field.span.end),
                    field, parser_type
                })
            },
            &mut fields_section, "a struct field", "a list of struct fields", None
        )?;

        // Transfer to preallocated definition
        let struct_def = ctx.heap[definition_id].as_struct_mut();
        struct_def.fields = fields_section.into_vec();

        Ok(())
    }

    fn visit_enum_definition(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<(), ParseError> {
        consume_exact_ident(&module.source, iter, KW_ENUM)?;
        let (ident_text, _) = consume_ident(&module.source, iter)?;

        // Retrieve preallocated DefinitionId
        let module_scope = SymbolScope::Module(module.root_id);
        let definition_id = ctx.symbols.get_symbol_by_name_defined_in_scope(module_scope, ident_text)
            .unwrap().variant.as_definition().definition_id;
        self.cur_definition = definition_id;

        // Parse enum definition
        consume_polymorphic_vars_spilled(&module.source, iter, ctx)?;

        let mut enum_section = self.enum_variants.start_section();
        consume_comma_separated(
            TokenKind::OpenCurly, TokenKind::CloseCurly, &module.source, iter, ctx,
            |source, iter, ctx| {
                let identifier = consume_ident_interned(source, iter, ctx)?;
                let value = if iter.next() == Some(TokenKind::Equal) {
                    iter.consume();
                    let (variant_number, _) = consume_integer_literal(source, iter, &mut self.buffer)?;
                    EnumVariantValue::Integer(variant_number as i64) // TODO: @int
                } else {
                    EnumVariantValue::None
                };
                Ok(EnumVariantDefinition{ identifier, value })
            },
            &mut enum_section, "an enum variant", "a list of enum variants", None
        )?;

        // Transfer to definition
        let enum_def = ctx.heap[definition_id].as_enum_mut();
        enum_def.variants = enum_section.into_vec();

        Ok(())
    }

    fn visit_union_definition(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<(), ParseError> {
        consume_exact_ident(&module.source, iter, KW_UNION)?;
        let (ident_text, _) = consume_ident(&module.source, iter)?;

        // Retrieve preallocated DefinitionId
        let module_scope = SymbolScope::Module(module.root_id);
        let definition_id = ctx.symbols.get_symbol_by_name_defined_in_scope(module_scope, ident_text)
            .unwrap().variant.as_definition().definition_id;
        self.cur_definition = definition_id;

        // Parse union definition
        consume_polymorphic_vars_spilled(&module.source, iter, ctx)?;

        let mut variants_section = self.union_variants.start_section();
        consume_comma_separated(
            TokenKind::OpenCurly, TokenKind::CloseCurly, &module.source, iter, ctx,
            |source, iter, ctx| {
                let identifier = consume_ident_interned(source, iter, ctx)?;
                let mut close_pos = identifier.span.end;

                let mut types_section = self.parser_types.start_section();

                let has_embedded = maybe_consume_comma_separated(
                    TokenKind::OpenParen, TokenKind::CloseParen, source, iter, ctx,
                    |source, iter, ctx| {
                        let poly_vars = ctx.heap[definition_id].poly_vars();
                        self.type_parser.consume_parser_type(
                            iter, &ctx.heap, source, &ctx.symbols, poly_vars, definition_id,
                            module_scope, false, None
                        )
                    },
                    &mut types_section, "an embedded type", Some(&mut close_pos)
                )?;
                let value = if has_embedded {
                    types_section.into_vec()
                } else {
                    types_section.forget();
                    Vec::new()
                };

                Ok(UnionVariantDefinition{
                    span: InputSpan::from_positions(identifier.span.begin, close_pos),
                    identifier,
                    value
                })
            },
            &mut variants_section, "a union variant", "a list of union variants", None
        )?;

        // Transfer to AST
        let union_def = ctx.heap[definition_id].as_union_mut();
        union_def.variants = variants_section.into_vec();

        Ok(())
    }

    fn visit_function_definition(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<(), ParseError> {
        // Retrieve function name
        consume_exact_ident(&module.source, iter, KW_FUNCTION)?;
        let (ident_text, _) = consume_ident(&module.source, iter)?;

        // Retrieve preallocated DefinitionId
        let module_scope = SymbolScope::Module(module.root_id);
        let definition_id = ctx.symbols.get_symbol_by_name_defined_in_scope(module_scope, ident_text)
            .unwrap().variant.as_definition().definition_id;
        self.cur_definition = definition_id;

        consume_polymorphic_vars_spilled(&module.source, iter, ctx)?;

        // Parse function's argument list
        let mut parameter_section = self.variables.start_section();
        consume_parameter_list(
            &mut self.type_parser, &module.source, iter, ctx, &mut parameter_section, module_scope, definition_id
        )?;
        let parameters = parameter_section.into_vec();

        // Consume return types
        consume_token(&module.source, iter, TokenKind::ArrowRight)?;
        let mut return_types = self.parser_types.start_section();
        let mut open_curly_pos = iter.last_valid_pos(); // bogus value
        consume_comma_separated_until(
            TokenKind::OpenCurly, &module.source, iter, ctx,
            |source, iter, ctx| {
                let poly_vars = ctx.heap[definition_id].poly_vars();
                self.type_parser.consume_parser_type(
                    iter, &ctx.heap, source, &ctx.symbols, poly_vars, definition_id,
                    module_scope, false, None
                )
            },
            &mut return_types, "a return type", Some(&mut open_curly_pos)
        )?;
        let return_types = return_types.into_vec();

        match return_types.len() {
            0 => return Err(ParseError::new_error_str_at_pos(&module.source, open_curly_pos, "expected a return type")),
            1 => {},
            _ => return Err(ParseError::new_error_str_at_pos(&module.source, open_curly_pos, "multiple return types are not (yet) allowed")),
        }

        // Consume block
        let body = self.consume_block_statement_without_leading_curly(module, iter, ctx, open_curly_pos)?;

        // Assign everything in the preallocated AST node
        let function = ctx.heap[definition_id].as_function_mut();
        function.return_types = return_types;
        function.parameters = parameters;
        function.body = body;

        Ok(())
    }

    fn visit_component_definition(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<(), ParseError> {
        // Consume component variant and name
        let (_variant_text, _) = consume_any_ident(&module.source, iter)?;
        debug_assert!(_variant_text == KW_PRIMITIVE || _variant_text == KW_COMPOSITE);
        let (ident_text, _) = consume_ident(&module.source, iter)?;

        // Retrieve preallocated definition
        let module_scope = SymbolScope::Module(module.root_id);
        let definition_id = ctx.symbols.get_symbol_by_name_defined_in_scope(module_scope, ident_text)
            .unwrap().variant.as_definition().definition_id;
        self.cur_definition = definition_id;

        consume_polymorphic_vars_spilled(&module.source, iter, ctx)?;

        // Parse component's argument list
        let mut parameter_section = self.variables.start_section();
        consume_parameter_list(
            &mut self.type_parser, &module.source, iter, ctx, &mut parameter_section, module_scope, definition_id
        )?;
        let parameters = parameter_section.into_vec();

        // Consume block
        let body = self.consume_block_statement(module, iter, ctx)?;

        // Assign everything in the AST node
        let component = ctx.heap[definition_id].as_component_mut();
        component.parameters = parameters;
        component.body = body;

        Ok(())
    }

    /// Consumes a block statement. If the resulting statement is not a block
    /// (e.g. for a shorthand "if (expr) single_statement") then it will be
    /// wrapped in one
    fn consume_block_or_wrapped_statement(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<BlockStatementId, ParseError> {
        if Some(TokenKind::OpenCurly) == iter.next() {
            // This is a block statement
            self.consume_block_statement(module, iter, ctx)
        } else {
            // Not a block statement, so wrap it in one
            let mut statements = self.statements.start_section();
            let wrap_begin_pos = iter.last_valid_pos();
            self.consume_statement(module, iter, ctx, &mut statements)?;
            let wrap_end_pos = iter.last_valid_pos();

            let statements = statements.into_vec();

            let id = ctx.heap.alloc_block_statement(|this| BlockStatement{
                this,
                is_implicit: true,
                span: InputSpan::from_positions(wrap_begin_pos, wrap_end_pos),
                statements,
                end_block: EndBlockStatementId::new_invalid(),
                scope_node: ScopeNode::new_invalid(),
                first_unique_id_in_scope: -1,
                next_unique_id_in_scope: -1,
                relative_pos_in_parent: 0,
                locals: Vec::new(),
                labels: Vec::new(),
                next: StatementId::new_invalid(),
            });

            let end_block = ctx.heap.alloc_end_block_statement(|this| EndBlockStatement{
                this, start_block: id, next: StatementId::new_invalid()
            });

            let block_stmt = &mut ctx.heap[id];
            block_stmt.end_block = end_block;

            Ok(id)
        }
    }

    /// Consumes a statement and returns a boolean indicating whether it was a
    /// block or not.
    fn consume_statement(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx, section: &mut ScopedSection<StatementId>
    ) -> Result<(), ParseError> {
        let next = iter.next().expect("consume_statement has a next token");

        if next == TokenKind::OpenCurly {
            let id = self.consume_block_statement(module, iter, ctx)?;
            section.push(id.upcast());
        } else if next == TokenKind::Ident {
            let ident = peek_ident(&module.source, iter).unwrap();
            if ident == KW_STMT_IF {
                // Consume if statement and place end-if statement directly
                // after it.
                let id = self.consume_if_statement(module, iter, ctx)?;
                section.push(id.upcast());

                let end_if = ctx.heap.alloc_end_if_statement(|this| EndIfStatement {
                    this,
                    start_if: id,
                    next: StatementId::new_invalid()
                });
                section.push(end_if.upcast());

                let if_stmt = &mut ctx.heap[id];
                if_stmt.end_if = end_if;
            } else if ident == KW_STMT_WHILE {
                let id = self.consume_while_statement(module, iter, ctx)?;
                section.push(id.upcast());

                let end_while = ctx.heap.alloc_end_while_statement(|this| EndWhileStatement {
                    this,
                    start_while: id,
                    next: StatementId::new_invalid()
                });
                section.push(end_while.upcast());

                let while_stmt = &mut ctx.heap[id];
                while_stmt.end_while = end_while;
            } else if ident == KW_STMT_BREAK {
                let id = self.consume_break_statement(module, iter, ctx)?;
                section.push(id.upcast());
            } else if ident == KW_STMT_CONTINUE {
                let id = self.consume_continue_statement(module, iter, ctx)?;
                section.push(id.upcast());
            } else if ident == KW_STMT_SYNC {
                let id = self.consume_synchronous_statement(module, iter, ctx)?;
                section.push(id.upcast());

                let end_sync = ctx.heap.alloc_end_synchronous_statement(|this| EndSynchronousStatement {
                    this,
                    start_sync: id,
                    next: StatementId::new_invalid()
                });
                section.push(end_sync.upcast());

                let sync_stmt = &mut ctx.heap[id];
                sync_stmt.end_sync = end_sync;
            } else if ident == KW_STMT_FORK {
                let id = self.consume_fork_statement(module, iter, ctx)?;
                section.push(id.upcast());

                let end_fork = ctx.heap.alloc_end_fork_statement(|this| EndForkStatement {
                    this,
                    start_fork: id,
                    next: StatementId::new_invalid(),
                });
                section.push(end_fork.upcast());

                let fork_stmt = &mut ctx.heap[id];
                fork_stmt.end_fork = end_fork;
            } else if ident == KW_STMT_RETURN {
                let id = self.consume_return_statement(module, iter, ctx)?;
                section.push(id.upcast());
            } else if ident == KW_STMT_GOTO {
                let id = self.consume_goto_statement(module, iter, ctx)?;
                section.push(id.upcast());
            } else if ident == KW_STMT_NEW {
                let id = self.consume_new_statement(module, iter, ctx)?;
                section.push(id.upcast());
            } else if ident == KW_STMT_CHANNEL {
                let id = self.consume_channel_statement(module, iter, ctx)?;
                section.push(id.upcast().upcast());
            } else if iter.peek() == Some(TokenKind::Colon) {
                self.consume_labeled_statement(module, iter, ctx, section)?;
            } else {
                // Two fallback possibilities: the first one is a memory
                // declaration, the other one is to parse it as a normal
                // expression. This is a bit ugly.
                if let Some((memory_stmt_id, assignment_stmt_id)) = self.maybe_consume_memory_statement(module, iter, ctx)? {
                    section.push(memory_stmt_id.upcast().upcast());
                    section.push(assignment_stmt_id.upcast());
                } else {
                    let id = self.consume_expression_statement(module, iter, ctx)?;
                    section.push(id.upcast());
                }
            }
        } else if next == TokenKind::OpenParen {
            // Same as above: memory statement or normal expression
            if let Some((memory_stmt_id, assignment_stmt_id)) = self.maybe_consume_memory_statement(module, iter, ctx)? {
                section.push(memory_stmt_id.upcast().upcast());
                section.push(assignment_stmt_id.upcast());
            } else {
                let id = self.consume_expression_statement(module, iter, ctx)?;
                section.push(id.upcast());
            }
        } else {
            let id = self.consume_expression_statement(module, iter, ctx)?;
            section.push(id.upcast());
        }

        return Ok(());
    }

    fn consume_block_statement(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<BlockStatementId, ParseError> {
        let open_span = consume_token(&module.source, iter, TokenKind::OpenCurly)?;
        self.consume_block_statement_without_leading_curly(module, iter, ctx, open_span.begin)
    }

    fn consume_block_statement_without_leading_curly(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx, open_curly_pos: InputPosition
    ) -> Result<BlockStatementId, ParseError> {
        let mut stmt_section = self.statements.start_section();
        let mut next = iter.next();
        while next != Some(TokenKind::CloseCurly) {
            if next.is_none() {
                return Err(ParseError::new_error_str_at_pos(
                    &module.source, iter.last_valid_pos(), "expected a statement or '}'"
                ));
            }
            self.consume_statement(module, iter, ctx, &mut stmt_section)?;
            next = iter.next();
        }

        let statements = stmt_section.into_vec();
        let mut block_span = consume_token(&module.source, iter, TokenKind::CloseCurly)?;
        block_span.begin = open_curly_pos;

        let id = ctx.heap.alloc_block_statement(|this| BlockStatement{
            this,
            is_implicit: false,
            span: block_span,
            statements,
            end_block: EndBlockStatementId::new_invalid(),
            scope_node: ScopeNode::new_invalid(),
            first_unique_id_in_scope: -1,
            next_unique_id_in_scope: -1,
            relative_pos_in_parent: 0,
            locals: Vec::new(),
            labels: Vec::new(),
            next: StatementId::new_invalid(),
        });

        let end_block = ctx.heap.alloc_end_block_statement(|this| EndBlockStatement{
            this, start_block: id, next: StatementId::new_invalid()
        });

        let block_stmt = &mut ctx.heap[id];
        block_stmt.end_block = end_block;

        Ok(id)
    }

    fn consume_if_statement(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<IfStatementId, ParseError> {
        let if_span = consume_exact_ident(&module.source, iter, KW_STMT_IF)?;
        consume_token(&module.source, iter, TokenKind::OpenParen)?;
        let test = self.consume_expression(module, iter, ctx)?;
        consume_token(&module.source, iter, TokenKind::CloseParen)?;
        let true_body = self.consume_block_or_wrapped_statement(module, iter, ctx)?;

        let false_body = if has_ident(&module.source, iter, KW_STMT_ELSE) {
            iter.consume();
            let false_body = self.consume_block_or_wrapped_statement(module, iter, ctx)?;
            Some(false_body)
        } else {
            None
        };

        Ok(ctx.heap.alloc_if_statement(|this| IfStatement{
            this,
            span: if_span,
            test,
            true_body,
            false_body,
            end_if: EndIfStatementId::new_invalid(),
        }))
    }

    fn consume_while_statement(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<WhileStatementId, ParseError> {
        let while_span = consume_exact_ident(&module.source, iter, KW_STMT_WHILE)?;
        consume_token(&module.source, iter, TokenKind::OpenParen)?;
        let test = self.consume_expression(module, iter, ctx)?;
        consume_token(&module.source, iter, TokenKind::CloseParen)?;
        let body = self.consume_block_or_wrapped_statement(module, iter, ctx)?;

        Ok(ctx.heap.alloc_while_statement(|this| WhileStatement{
            this,
            span: while_span,
            test,
            body,
            end_while: EndWhileStatementId::new_invalid(),
            in_sync: SynchronousStatementId::new_invalid(),
        }))
    }

    fn consume_break_statement(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<BreakStatementId, ParseError> {
        let break_span = consume_exact_ident(&module.source, iter, KW_STMT_BREAK)?;
        let label = if Some(TokenKind::Ident) == iter.next() {
            let label = consume_ident_interned(&module.source, iter, ctx)?;
            Some(label)
        } else {
            None
        };
        consume_token(&module.source, iter, TokenKind::SemiColon)?;
        Ok(ctx.heap.alloc_break_statement(|this| BreakStatement{
            this,
            span: break_span,
            label,
            target: None,
        }))
    }

    fn consume_continue_statement(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<ContinueStatementId, ParseError> {
        let continue_span = consume_exact_ident(&module.source, iter, KW_STMT_CONTINUE)?;
        let label=  if Some(TokenKind::Ident) == iter.next() {
            let label = consume_ident_interned(&module.source, iter, ctx)?;
            Some(label)
        } else {
            None
        };
        consume_token(&module.source, iter, TokenKind::SemiColon)?;
        Ok(ctx.heap.alloc_continue_statement(|this| ContinueStatement{
            this,
            span: continue_span,
            label,
            target: None
        }))
    }

    fn consume_synchronous_statement(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<SynchronousStatementId, ParseError> {
        let synchronous_span = consume_exact_ident(&module.source, iter, KW_STMT_SYNC)?;
        let body = self.consume_block_or_wrapped_statement(module, iter, ctx)?;

        Ok(ctx.heap.alloc_synchronous_statement(|this| SynchronousStatement{
            this,
            span: synchronous_span,
            body,
            end_sync: EndSynchronousStatementId::new_invalid(),
        }))
    }

    fn consume_fork_statement(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<ForkStatementId, ParseError> {
        let fork_span = consume_exact_ident(&module.source, iter, KW_STMT_FORK)?;
        let left_body = self.consume_block_or_wrapped_statement(module, iter, ctx)?;

        let right_body = if has_ident(&module.source, iter, KW_STMT_OR) {
            iter.consume();
            let right_body = self.consume_block_or_wrapped_statement(module, iter, ctx)?;
            Some(right_body)
        } else {
            None
        };

        Ok(ctx.heap.alloc_fork_statement(|this| ForkStatement{
            this,
            span: fork_span,
            left_body,
            right_body,
            end_fork: EndForkStatementId::new_invalid(),
        }))
    }

    fn consume_return_statement(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<ReturnStatementId, ParseError> {
        let return_span = consume_exact_ident(&module.source, iter, KW_STMT_RETURN)?;
        let mut scoped_section = self.expressions.start_section();

        consume_comma_separated_until(
            TokenKind::SemiColon, &module.source, iter, ctx,
            |_source, iter, ctx| self.consume_expression(module, iter, ctx),
            &mut scoped_section, "an expression", None
        )?;
        let expressions = scoped_section.into_vec();

        if expressions.is_empty() {
            return Err(ParseError::new_error_str_at_span(&module.source, return_span, "expected at least one return value"));
        } else if expressions.len() > 1 {
            return Err(ParseError::new_error_str_at_span(&module.source, return_span, "multiple return values are not (yet) supported"))
        }

        Ok(ctx.heap.alloc_return_statement(|this| ReturnStatement{
            this,
            span: return_span,
            expressions
        }))
    }

    fn consume_goto_statement(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<GotoStatementId, ParseError> {
        let goto_span = consume_exact_ident(&module.source, iter, KW_STMT_GOTO)?;
        let label = consume_ident_interned(&module.source, iter, ctx)?;
        consume_token(&module.source, iter, TokenKind::SemiColon)?;
        Ok(ctx.heap.alloc_goto_statement(|this| GotoStatement{
            this,
            span: goto_span,
            label,
            target: None
        }))
    }

    fn consume_new_statement(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<NewStatementId, ParseError> {
        let new_span = consume_exact_ident(&module.source, iter, KW_STMT_NEW)?;

        let start_pos = iter.last_valid_pos();
        let expression_id = self.consume_primary_expression(module, iter, ctx)?;
        let expression = &ctx.heap[expression_id];
        let mut valid = false;

        let mut call_id = CallExpressionId::new_invalid();
        if let Expression::Call(expression) = expression {
            // Allow both components and functions, as it makes more sense to
            // check their correct use in the validation and linking pass
            if expression.method == Method::UserComponent || expression.method == Method::UserFunction {
                call_id = expression.this;
                valid = true;
            }
        }

        if !valid {
            return Err(ParseError::new_error_str_at_span(
                &module.source, InputSpan::from_positions(start_pos, iter.last_valid_pos()), "expected a call expression"
            ));
        }
        consume_token(&module.source, iter, TokenKind::SemiColon)?;

        debug_assert!(!call_id.is_invalid());
        Ok(ctx.heap.alloc_new_statement(|this| NewStatement{
            this,
            span: new_span,
            expression: call_id,
            next: StatementId::new_invalid(),
        }))
    }

    fn consume_channel_statement(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<ChannelStatementId, ParseError> {
        // Consume channel specification
        let channel_span = consume_exact_ident(&module.source, iter, KW_STMT_CHANNEL)?;
        let (inner_port_type, end_pos) = if Some(TokenKind::OpenAngle) == iter.next() {
            // Retrieve the type of the channel, we're cheating a bit here by
            // consuming the first '<' and setting the initial angle depth to 1
            // such that our final '>' will be consumed as well.
            let angle_start_pos = iter.next_start_position();
            iter.consume();
            let definition_id = self.cur_definition;
            let poly_vars = ctx.heap[definition_id].poly_vars();
            let parser_type = self.type_parser.consume_parser_type(
                iter, &ctx.heap, &module.source, &ctx.symbols, poly_vars,
                definition_id, SymbolScope::Module(module.root_id),
                true, Some(angle_start_pos)
            )?;

            (parser_type.elements, parser_type.full_span.end)
        } else {
            // Assume inferred
            (
                vec![ParserTypeElement{
                    element_span: channel_span,
                    variant: ParserTypeVariant::Inferred
                }],
                channel_span.end
            )
        };

        let from_identifier = consume_ident_interned(&module.source, iter, ctx)?;
        consume_token(&module.source, iter, TokenKind::ArrowRight)?;
        let to_identifier = consume_ident_interned(&module.source, iter, ctx)?;
        consume_token(&module.source, iter, TokenKind::SemiColon)?;

        // Construct ports
        let port_type_span = InputSpan::from_positions(channel_span.begin, end_pos);
        let port_type_len = inner_port_type.len() + 1;
        let mut from_port_type = ParserType{ elements: Vec::with_capacity(port_type_len), full_span: port_type_span };
        from_port_type.elements.push(ParserTypeElement{
            element_span: channel_span,
            variant: ParserTypeVariant::Output,
        });
        from_port_type.elements.extend_from_slice(&inner_port_type);
        let from = ctx.heap.alloc_variable(|this| Variable{
            this,
            kind: VariableKind::Local,
            identifier: from_identifier,
            parser_type: from_port_type,
            relative_pos_in_block: 0,
            unique_id_in_scope: -1,
        });

        let mut to_port_type = ParserType{ elements: Vec::with_capacity(port_type_len), full_span: port_type_span };
        to_port_type.elements.push(ParserTypeElement{
            element_span: channel_span,
            variant: ParserTypeVariant::Input
        });
        to_port_type.elements.extend_from_slice(&inner_port_type);
        let to = ctx.heap.alloc_variable(|this|Variable{
            this,
            kind: VariableKind::Local,
            identifier: to_identifier,
            parser_type: to_port_type,
            relative_pos_in_block: 0,
            unique_id_in_scope: -1,
        });

        // Construct the channel
        Ok(ctx.heap.alloc_channel_statement(|this| ChannelStatement{
            this,
            span: channel_span,
            from, to,
            relative_pos_in_block: 0,
            next: StatementId::new_invalid(),
        }))
    }

    fn consume_labeled_statement(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx, section: &mut ScopedSection<StatementId>
    ) -> Result<(), ParseError> {
        let label = consume_ident_interned(&module.source, iter, ctx)?;
        consume_token(&module.source, iter, TokenKind::Colon)?;

        // Not pretty: consume_statement may produce more than one statement.
        // The values in the section need to be in the correct order if some
        // kind of outer block is consumed, so we take another section, push
        // the expressions in that one, and then allocate the labeled statement.
        let mut inner_section = self.statements.start_section();
        self.consume_statement(module, iter, ctx, &mut inner_section)?;
        debug_assert!(inner_section.len() >= 1);

        let stmt_id = ctx.heap.alloc_labeled_statement(|this| LabeledStatement {
            this,
            label,
            body: inner_section[0],
            relative_pos_in_block: 0,
            in_sync: SynchronousStatementId::new_invalid(),
        });

        if inner_section.len() == 1 {
            // Produce the labeled statement pointing to the first statement.
            // This is by far the most common case.
            inner_section.forget();
            section.push(stmt_id.upcast());
        } else {
            // Produce the labeled statement using the first statement, and push
            // the remaining ones at the end.
            let inner_statements = inner_section.into_vec();
            section.push(stmt_id.upcast());
            for idx in 1..inner_statements.len() {
                section.push(inner_statements[idx])
            }
        }

        Ok(())
    }

    fn maybe_consume_memory_statement(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<Option<(MemoryStatementId, ExpressionStatementId)>, ParseError> {
        // This is a bit ugly. It would be nicer if we could somehow
        // consume the expression with a type hint if we do get a valid
        // type, but we don't get an identifier following it
        let iter_state = iter.save();
        let definition_id = self.cur_definition;
        let poly_vars = ctx.heap[definition_id].poly_vars();

        let parser_type = self.type_parser.consume_parser_type(
            iter, &ctx.heap, &module.source, &ctx.symbols, poly_vars,
            definition_id, SymbolScope::Definition(definition_id), true, None
        );

        if let Ok(parser_type) = parser_type {
            if Some(TokenKind::Ident) == iter.next() {
                // Assume this is a proper memory statement
                let identifier = consume_ident_interned(&module.source, iter, ctx)?;
                let memory_span = InputSpan::from_positions(parser_type.full_span.begin, identifier.span.end);
                let assign_span = consume_token(&module.source, iter, TokenKind::Equal)?;

                let initial_expr_begin_pos = iter.last_valid_pos();
                let initial_expr_id = self.consume_expression(module, iter, ctx)?;
                let initial_expr_end_pos = iter.last_valid_pos();
                consume_token(&module.source, iter, TokenKind::SemiColon)?;

                // Allocate the memory statement with the variable
                let local_id = ctx.heap.alloc_variable(|this| Variable{
                    this,
                    kind: VariableKind::Local,
                    identifier: identifier.clone(),
                    parser_type,
                    relative_pos_in_block: 0,
                    unique_id_in_scope: -1,
                });
                let memory_stmt_id = ctx.heap.alloc_memory_statement(|this| MemoryStatement{
                    this,
                    span: memory_span,
                    variable: local_id,
                    next: StatementId::new_invalid()
                });

                // Allocate the initial assignment
                let variable_expr_id = ctx.heap.alloc_variable_expression(|this| VariableExpression{
                    this,
                    identifier,
                    declaration: None,
                    used_as_binding_target: false,
                    parent: ExpressionParent::None,
                    unique_id_in_definition: -1,
                });
                let assignment_expr_id = ctx.heap.alloc_assignment_expression(|this| AssignmentExpression{
                    this,
                    operator_span: assign_span,
                    full_span: InputSpan::from_positions(memory_span.begin, initial_expr_end_pos),
                    left: variable_expr_id.upcast(),
                    operation: AssignmentOperator::Set,
                    right: initial_expr_id,
                    parent: ExpressionParent::None,
                    unique_id_in_definition: -1,
                });
                let assignment_stmt_id = ctx.heap.alloc_expression_statement(|this| ExpressionStatement{
                    this,
                    span: InputSpan::from_positions(initial_expr_begin_pos, initial_expr_end_pos),
                    expression: assignment_expr_id.upcast(),
                    next: StatementId::new_invalid(),
                });

                return Ok(Some((memory_stmt_id, assignment_stmt_id)))
            }
        }

        // If here then one of the preconditions for a memory statement was not
        // met. So recover the iterator and return
        iter.load(iter_state);
        Ok(None)
    }

    fn consume_expression_statement(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<ExpressionStatementId, ParseError> {
        let start_pos = iter.last_valid_pos();
        let expression = self.consume_expression(module, iter, ctx)?;
        let end_pos = iter.last_valid_pos();
        consume_token(&module.source, iter, TokenKind::SemiColon)?;

        Ok(ctx.heap.alloc_expression_statement(|this| ExpressionStatement{
            this,
            span: InputSpan::from_positions(start_pos, end_pos),
            expression,
            next: StatementId::new_invalid(),
        }))
    }

    //--------------------------------------------------------------------------
    // Expression Parsing
    //--------------------------------------------------------------------------

    // TODO: @Cleanup This is fine for now. But I prefer my stacktraces not to
    //  look like enterprise Java code...
    fn consume_expression(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<ExpressionId, ParseError> {
        self.consume_assignment_expression(module, iter, ctx)
    }

    fn consume_assignment_expression(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<ExpressionId, ParseError> {
        // Utility to convert token into assignment operator
        fn parse_assignment_operator(token: Option<TokenKind>) -> Option<AssignmentOperator> {
            use TokenKind as TK;
            use AssignmentOperator as AO;

            if token.is_none() {
                return None
            }

            match token.unwrap() {
                TK::Equal               => Some(AO::Set),
                TK::AtEquals            => Some(AO::Concatenated),
                TK::StarEquals          => Some(AO::Multiplied),
                TK::SlashEquals         => Some(AO::Divided),
                TK::PercentEquals       => Some(AO::Remained),
                TK::PlusEquals          => Some(AO::Added),
                TK::MinusEquals         => Some(AO::Subtracted),
                TK::ShiftLeftEquals     => Some(AO::ShiftedLeft),
                TK::ShiftRightEquals    => Some(AO::ShiftedRight),
                TK::AndEquals           => Some(AO::BitwiseAnded),
                TK::CaretEquals         => Some(AO::BitwiseXored),
                TK::OrEquals            => Some(AO::BitwiseOred),
                _                       => None
            }
        }

        let expr = self.consume_conditional_expression(module, iter, ctx)?;
        if let Some(operation) = parse_assignment_operator(iter.next()) {
            let operator_span = iter.next_span();
            iter.consume();

            let left = expr;
            let right = self.consume_expression(module, iter, ctx)?;

            let full_span = InputSpan::from_positions(
                ctx.heap[left].full_span().begin,
                ctx.heap[right].full_span().end,
            );

            Ok(ctx.heap.alloc_assignment_expression(|this| AssignmentExpression{
                this, operator_span, full_span, left, operation, right,
                parent: ExpressionParent::None,
                unique_id_in_definition: -1,
            }).upcast())
        } else {
            Ok(expr)
        }
    }

    fn consume_conditional_expression(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<ExpressionId, ParseError> {
        let result = self.consume_concat_expression(module, iter, ctx)?;
        if let Some(TokenKind::Question) = iter.next() {
            let operator_span = iter.next_span();
            iter.consume();

            let test = result;
            let true_expression = self.consume_expression(module, iter, ctx)?;
            consume_token(&module.source, iter, TokenKind::Colon)?;
            let false_expression = self.consume_expression(module, iter, ctx)?;

            let full_span = InputSpan::from_positions(
                ctx.heap[test].full_span().begin,
                ctx.heap[false_expression].full_span().end,
            );

            Ok(ctx.heap.alloc_conditional_expression(|this| ConditionalExpression{
                this, operator_span, full_span, test, true_expression, false_expression,
                parent: ExpressionParent::None,
                unique_id_in_definition: -1,
            }).upcast())
        } else {
            Ok(result)
        }
    }

    fn consume_concat_expression(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<ExpressionId, ParseError> {
        self.consume_generic_binary_expression(
            module, iter, ctx,
            |token| match token {
                Some(TokenKind::At) => Some(BinaryOperator::Concatenate),
                _ => None
            },
            Self::consume_logical_or_expression
        )
    }

    fn consume_logical_or_expression(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<ExpressionId, ParseError> {
        self.consume_generic_binary_expression(
            module, iter, ctx,
            |token| match token {
                Some(TokenKind::OrOr) => Some(BinaryOperator::LogicalOr),
                _ => None
            },
            Self::consume_logical_and_expression
        )
    }

    fn consume_logical_and_expression(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<ExpressionId, ParseError> {
        self.consume_generic_binary_expression(
            module, iter, ctx,
            |token| match token {
                Some(TokenKind::AndAnd) => Some(BinaryOperator::LogicalAnd),
                _ => None
            },
            Self::consume_bitwise_or_expression
        )
    }

    fn consume_bitwise_or_expression(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<ExpressionId, ParseError> {
        self.consume_generic_binary_expression(
            module, iter, ctx,
            |token| match token {
                Some(TokenKind::Or) => Some(BinaryOperator::BitwiseOr),
                _ => None
            },
            Self::consume_bitwise_xor_expression
        )
    }

    fn consume_bitwise_xor_expression(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<ExpressionId, ParseError> {
        self.consume_generic_binary_expression(
            module, iter, ctx,
            |token| match token {
                Some(TokenKind::Caret) => Some(BinaryOperator::BitwiseXor),
                _ => None
            },
            Self::consume_bitwise_and_expression
        )
    }

    fn consume_bitwise_and_expression(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<ExpressionId, ParseError> {
        self.consume_generic_binary_expression(
            module, iter, ctx,
            |token| match token {
                Some(TokenKind::And) => Some(BinaryOperator::BitwiseAnd),
                _ => None
            },
            Self::consume_equality_expression
        )
    }

    fn consume_equality_expression(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<ExpressionId, ParseError> {
        self.consume_generic_binary_expression(
            module, iter, ctx,
            |token| match token {
                Some(TokenKind::EqualEqual) => Some(BinaryOperator::Equality),
                Some(TokenKind::NotEqual) => Some(BinaryOperator::Inequality),
                _ => None
            },
            Self::consume_relational_expression
        )
    }

    fn consume_relational_expression(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<ExpressionId, ParseError> {
        self.consume_generic_binary_expression(
            module, iter, ctx,
            |token| match token {
                Some(TokenKind::OpenAngle) => Some(BinaryOperator::LessThan),
                Some(TokenKind::CloseAngle) => Some(BinaryOperator::GreaterThan),
                Some(TokenKind::LessEquals) => Some(BinaryOperator::LessThanEqual),
                Some(TokenKind::GreaterEquals) => Some(BinaryOperator::GreaterThanEqual),
                _ => None
            },
            Self::consume_shift_expression
        )
    }

    fn consume_shift_expression(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<ExpressionId, ParseError> {
        self.consume_generic_binary_expression(
            module, iter, ctx,
            |token| match token {
                Some(TokenKind::ShiftLeft) => Some(BinaryOperator::ShiftLeft),
                Some(TokenKind::ShiftRight) => Some(BinaryOperator::ShiftRight),
                _ => None
            },
            Self::consume_add_or_subtract_expression
        )
    }

    fn consume_add_or_subtract_expression(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<ExpressionId, ParseError> {
        self.consume_generic_binary_expression(
            module, iter, ctx,
            |token| match token {
                Some(TokenKind::Plus) => Some(BinaryOperator::Add),
                Some(TokenKind::Minus) => Some(BinaryOperator::Subtract),
                _ => None,
            },
            Self::consume_multiply_divide_or_modulus_expression
        )
    }

    fn consume_multiply_divide_or_modulus_expression(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<ExpressionId, ParseError> {
        self.consume_generic_binary_expression(
            module, iter, ctx,
            |token| match token {
                Some(TokenKind::Star) => Some(BinaryOperator::Multiply),
                Some(TokenKind::Slash) => Some(BinaryOperator::Divide),
                Some(TokenKind::Percent) => Some(BinaryOperator::Remainder),
                _ => None
            },
            Self::consume_prefix_expression
        )
    }

    fn consume_prefix_expression(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<ExpressionId, ParseError> {
        fn parse_prefix_token(token: Option<TokenKind>) -> Option<UnaryOperator> {
            use TokenKind as TK;
            use UnaryOperator as UO;
            match token {
                Some(TK::Plus) => Some(UO::Positive),
                Some(TK::Minus) => Some(UO::Negative),
                Some(TK::Tilde) => Some(UO::BitwiseNot),
                Some(TK::Exclamation) => Some(UO::LogicalNot),
                _ => None
            }
        }

        let next = iter.next();
        if let Some(operation) = parse_prefix_token(next) {
            let operator_span = iter.next_span();
            iter.consume();

            let expression = self.consume_prefix_expression(module, iter, ctx)?;
            let full_span = InputSpan::from_positions(
                operator_span.begin, ctx.heap[expression].full_span().end,
            );
            Ok(ctx.heap.alloc_unary_expression(|this| UnaryExpression {
                this, operator_span, full_span, operation, expression,
                parent: ExpressionParent::None,
                unique_id_in_definition: -1,
            }).upcast())
        } else if next == Some(TokenKind::PlusPlus) {
            return Err(ParseError::new_error_str_at_span(
                &module.source, iter.next_span(), "prefix increment is not supported in the language"
            ));
        } else if next == Some(TokenKind::MinusMinus) {
            return Err(ParseError::new_error_str_at_span(
                &module.source, iter.next_span(), "prefix decrement is not supported in this language"
            ));
        } else {
            self.consume_postfix_expression(module, iter, ctx)
        }
    }

    fn consume_postfix_expression(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<ExpressionId, ParseError> {
        fn has_matching_postfix_token(token: Option<TokenKind>) -> bool {
            use TokenKind as TK;

            if token.is_none() { return false; }
            match token.unwrap() {
                TK::PlusPlus | TK::MinusMinus | TK::OpenSquare | TK::Dot => true,
                _ => false
            }
        }

        let mut result = self.consume_primary_expression(module, iter, ctx)?;
        let mut next = iter.next();
        while has_matching_postfix_token(next) {
            let token = next.unwrap();
            let mut operator_span = iter.next_span();
            iter.consume();

            if token == TokenKind::PlusPlus {
                return Err(ParseError::new_error_str_at_span(
                    &module.source, operator_span, "postfix increment is not supported in this language"
                ));
            } else if token == TokenKind::MinusMinus {
                return Err(ParseError::new_error_str_at_span(
                    &module.source, operator_span, "prefix increment is not supported in this language"
                ));
            } else if token == TokenKind::OpenSquare {
                let subject = result;
                let from_index = self.consume_expression(module, iter, ctx)?;

                // Check if we have an indexing or slicing operation
                next = iter.next();
                if Some(TokenKind::DotDot) == next {
                    iter.consume();

                    let to_index = self.consume_expression(module, iter, ctx)?;
                    let end_span = consume_token(&module.source, iter, TokenKind::CloseSquare)?;
                    operator_span.end = end_span.end;
                    let full_span = InputSpan::from_positions(
                        ctx.heap[subject].full_span().begin, operator_span.end
                    );

                    result = ctx.heap.alloc_slicing_expression(|this| SlicingExpression{
                        this,
                        slicing_span: operator_span,
                        full_span, subject, from_index, to_index,
                        parent: ExpressionParent::None,
                        unique_id_in_definition: -1,
                    }).upcast();
                } else if Some(TokenKind::CloseSquare) == next {
                    let end_span = consume_token(&module.source, iter, TokenKind::CloseSquare)?;
                    operator_span.end = end_span.end;

                    let full_span = InputSpan::from_positions(
                        ctx.heap[subject].full_span().begin, operator_span.end
                    );

                    result = ctx.heap.alloc_indexing_expression(|this| IndexingExpression{
                        this, operator_span, full_span, subject,
                        index: from_index,
                        parent: ExpressionParent::None,
                        unique_id_in_definition: -1,
                    }).upcast();
                } else {
                    return Err(ParseError::new_error_str_at_pos(
                        &module.source, iter.last_valid_pos(), "unexpected token: expected ']' or '..'"
                    ));
                }
            } else {
                // Can be a select expression for struct fields, or a select
                // for a tuple element.
                debug_assert_eq!(token, TokenKind::Dot);
                let subject = result;

                let next = iter.next();
                let (select_kind, full_span) = if Some(TokenKind::Integer) == next {
                    // Tuple member
                    let (index, index_span) = consume_integer_literal(&module.source, iter, &mut self.buffer)?;
                    let full_span = InputSpan::from_positions(
                        ctx.heap[subject].full_span().begin, index_span.end
                    );

                    (SelectKind::TupleMember(index), full_span)
                } else if Some(TokenKind::Ident) == next {
                    // Struct field
                    let field_name = consume_ident_interned(&module.source, iter, ctx)?;

                    let full_span = InputSpan::from_positions(
                        ctx.heap[subject].full_span().begin, field_name.span.end
                    );

                    (SelectKind::StructField(field_name), full_span)
                } else {
                    return Err(ParseError::new_error_str_at_pos(
                        &module.source, iter.last_valid_pos(), "unexpected token: expected integer or identifier"
                    ));
                };

                result = ctx.heap.alloc_select_expression(|this| SelectExpression{
                    this, operator_span, full_span, subject,
                    kind: select_kind,
                    parent: ExpressionParent::None,
                    unique_id_in_definition: -1,
                }).upcast();
            }

            next = iter.next();
        }

        Ok(result)
    }

    fn consume_primary_expression(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx
    ) -> Result<ExpressionId, ParseError> {
        let next = iter.next();

        let result = if next == Some(TokenKind::OpenParen) {
            // Something parenthesized. This can mean several things: we have
            // a parenthesized expression or we have a tuple literal. They are
            // ambiguous when the tuple has one member. But like the tuple type
            // parsing we interpret all one-tuples as parenthesized expressions.
            //
            // Practically (to prevent unnecessary `consume_expression` calls)
            // we distinguish the zero-tuple, the parenthesized expression, and
            // the N-tuple (for N > 1).
            let open_paren_pos = iter.next_start_position();
            iter.consume();
            let result = if Some(TokenKind::CloseParen) == iter.next() {
                // Zero-tuple
                let (_, close_paren_pos) = iter.next_positions();
                iter.consume();

                let literal_id = ctx.heap.alloc_literal_expression(|this| LiteralExpression{
                    this,
                    span: InputSpan::from_positions(open_paren_pos, close_paren_pos),
                    value: Literal::Tuple(Vec::new()),
                    parent: ExpressionParent::None,
                    unique_id_in_definition: -1,
                });

                literal_id.upcast()
            } else {
                // Start by consuming one expression, then check for a comma
                let expr_id = self.consume_expression(module, iter, ctx)?;
                if Some(TokenKind::Comma) == iter.next() && Some(TokenKind::CloseParen) != iter.peek() {
                    // Must be an N-tuple
                    iter.consume(); // the comma
                    let mut scoped_section = self.expressions.start_section();
                    scoped_section.push(expr_id);

                    let mut close_paren_pos = open_paren_pos;
                    consume_comma_separated_until(
                        TokenKind::CloseParen, &module.source, iter, ctx,
                        |_source, iter, ctx| self.consume_expression(module, iter, ctx),
                        &mut scoped_section, "an expression", Some(&mut close_paren_pos)
                    )?;
                    debug_assert!(scoped_section.len() > 1); // peeked token wasn't CloseParen, must be expression

                    let literal_id = ctx.heap.alloc_literal_expression(|this| LiteralExpression{
                        this,
                        span: InputSpan::from_positions(open_paren_pos, close_paren_pos),
                        value: Literal::Tuple(scoped_section.into_vec()),
                        parent: ExpressionParent::None,
                        unique_id_in_definition: -1,
                    });

                    literal_id.upcast()
                } else {
                    // Assume we're dealing with a normal expression
                    consume_token(&module.source, iter, TokenKind::CloseParen)?;

                    expr_id
                }
            };

            result
        } else if next == Some(TokenKind::OpenCurly) {
            // Array literal
            let (start_pos, mut end_pos) = iter.next_positions();
            let mut scoped_section = self.expressions.start_section();
            consume_comma_separated(
                TokenKind::OpenCurly, TokenKind::CloseCurly, &module.source, iter, ctx,
                |_source, iter, ctx| self.consume_expression(module, iter, ctx),
                &mut scoped_section, "an expression", "a list of expressions", Some(&mut end_pos)
            )?;

            ctx.heap.alloc_literal_expression(|this| LiteralExpression{
                this,
                span: InputSpan::from_positions(start_pos, end_pos),
                value: Literal::Array(scoped_section.into_vec()),
                parent: ExpressionParent::None,
                unique_id_in_definition: -1,
            }).upcast()
        } else if next == Some(TokenKind::Integer) {
            let (literal, span) = consume_integer_literal(&module.source, iter, &mut self.buffer)?;

            ctx.heap.alloc_literal_expression(|this| LiteralExpression{
                this, span,
                value: Literal::Integer(LiteralInteger{ unsigned_value: literal, negated: false }),
                parent: ExpressionParent::None,
                unique_id_in_definition: -1,
            }).upcast()
        } else if next == Some(TokenKind::String) {
            let span = consume_string_literal(&module.source, iter, &mut self.buffer)?;
            let interned = ctx.pool.intern(self.buffer.as_bytes());

            ctx.heap.alloc_literal_expression(|this| LiteralExpression{
                this, span,
                value: Literal::String(interned),
                parent: ExpressionParent::None,
                unique_id_in_definition: -1,
            }).upcast()
        } else if next == Some(TokenKind::Character) {
            let (character, span) = consume_character_literal(&module.source, iter)?;

            ctx.heap.alloc_literal_expression(|this| LiteralExpression{
                this, span,
                value: Literal::Character(character),
                parent: ExpressionParent::None,
                unique_id_in_definition: -1,
            }).upcast()
        } else if next == Some(TokenKind::Ident) {
            // May be a variable, a type instantiation or a function call. If we
            // have a single identifier that we cannot find in the type table
            // then we're going to assume that we're dealing with a variable.

            let ident_span = iter.next_span();
            let ident_text = module.source.section_at_span(ident_span);
            let symbol = ctx.symbols.get_symbol_by_name(SymbolScope::Module(module.root_id), ident_text);

            if symbol.is_some() {
                // The first bit looked like a symbol, so we're going to follow
                // that all the way through, assume we arrive at some kind of
                // function call or type instantiation
                use ParserTypeVariant as PTV;

                let symbol_scope = SymbolScope::Definition(self.cur_definition);
                let poly_vars = ctx.heap[self.cur_definition].poly_vars();
                let parser_type = self.type_parser.consume_parser_type(
                    iter, &ctx.heap, &module.source, &ctx.symbols, poly_vars, self.cur_definition,
                    symbol_scope, true, None
                )?;
                debug_assert!(!parser_type.elements.is_empty());
                match parser_type.elements[0].variant {
                    PTV::Definition(target_definition_id, _) => {
                        let definition = &ctx.heap[target_definition_id];
                        match definition {
                            Definition::Struct(_) => {
                                // Struct literal
                                let mut last_token = iter.last_valid_pos();
                                let mut struct_fields = Vec::new();
                                consume_comma_separated(
                                    TokenKind::OpenCurly, TokenKind::CloseCurly, &module.source, iter, ctx,
                                    |source, iter, ctx| {
                                        let identifier = consume_ident_interned(source, iter, ctx)?;
                                        consume_token(source, iter, TokenKind::Colon)?;
                                        let value = self.consume_expression(module, iter, ctx)?;
                                        Ok(LiteralStructField{ identifier, value, field_idx: 0 })
                                    },
                                    &mut struct_fields, "a struct field", "a list of struct fields", Some(&mut last_token)
                                )?;

                                ctx.heap.alloc_literal_expression(|this| LiteralExpression{
                                    this,
                                    span: InputSpan::from_positions(ident_span.begin, last_token),
                                    value: Literal::Struct(LiteralStruct{
                                        parser_type,
                                        fields: struct_fields,
                                        definition: target_definition_id,
                                    }),
                                    parent: ExpressionParent::None,
                                    unique_id_in_definition: -1,
                                }).upcast()
                            },
                            Definition::Enum(_) => {
                                // Enum literal: consume the variant
                                consume_token(&module.source, iter, TokenKind::ColonColon)?;
                                let variant = consume_ident_interned(&module.source, iter, ctx)?;

                                ctx.heap.alloc_literal_expression(|this| LiteralExpression{
                                    this,
                                    span: InputSpan::from_positions(ident_span.begin, variant.span.end),
                                    value: Literal::Enum(LiteralEnum{
                                        parser_type,
                                        variant,
                                        definition: target_definition_id,
                                        variant_idx: 0
                                    }),
                                    parent: ExpressionParent::None,
                                    unique_id_in_definition: -1,
                                }).upcast()
                            },
                            Definition::Union(_) => {
                                // Union literal: consume the variant
                                consume_token(&module.source, iter, TokenKind::ColonColon)?;
                                let variant = consume_ident_interned(&module.source, iter, ctx)?;

                                // Consume any possible embedded values
                                let mut end_pos = variant.span.end;
                                let values = if Some(TokenKind::OpenParen) == iter.next() {
                                    self.consume_expression_list(module, iter, ctx, Some(&mut end_pos))?
                                } else {
                                    Vec::new()
                                };

                                ctx.heap.alloc_literal_expression(|this| LiteralExpression{
                                    this,
                                    span: InputSpan::from_positions(ident_span.begin, end_pos),
                                    value: Literal::Union(LiteralUnion{
                                        parser_type, variant, values,
                                        definition: target_definition_id,
                                        variant_idx: 0,
                                    }),
                                    parent: ExpressionParent::None,
                                    unique_id_in_definition: -1,
                                }).upcast()
                            },
                            Definition::Component(_) => {
                                // Component instantiation
                                let func_span = parser_type.full_span;
                                let mut full_span = func_span;
                                let arguments = self.consume_expression_list(
                                    module, iter, ctx, Some(&mut full_span.end)
                                )?;

                                ctx.heap.alloc_call_expression(|this| CallExpression{
                                    this, func_span, full_span,
                                    parser_type,
                                    method: Method::UserComponent,
                                    arguments,
                                    definition: target_definition_id,
                                    parent: ExpressionParent::None,
                                    unique_id_in_definition: -1,
                                }).upcast()
                            },
                            Definition::Function(function_definition) => {
                                // Check whether it is a builtin function
                                let method = if function_definition.builtin {
                                    match function_definition.identifier.value.as_bytes() {
                                        KW_FUNC_GET => Method::Get,
                                        KW_FUNC_PUT => Method::Put,
                                        KW_FUNC_FIRES => Method::Fires,
                                        KW_FUNC_CREATE => Method::Create,
                                        KW_FUNC_LENGTH => Method::Length,
                                        KW_FUNC_ASSERT => Method::Assert,
                                        KW_FUNC_PRINT => Method::Print,
                                        _ => unreachable!(),
                                    }
                                } else {
                                    Method::UserFunction
                                };

                                // Function call: consume the arguments
                                let func_span = parser_type.full_span;
                                let mut full_span = func_span;
                                let arguments = self.consume_expression_list(
                                    module, iter, ctx, Some(&mut full_span.end)
                                )?;

                                ctx.heap.alloc_call_expression(|this| CallExpression{
                                    this, func_span, full_span, parser_type, method, arguments,
                                    definition: target_definition_id,
                                    parent: ExpressionParent::None,
                                    unique_id_in_definition: -1,
                                }).upcast()
                            }
                        }
                    },
                    _ => {
                        return Err(ParseError::new_error_str_at_span(
                            &module.source, parser_type.full_span, "unexpected type in expression"
                        ))
                    }
                }
            } else {
                // Check for builtin keywords or builtin functions
                if ident_text == KW_LIT_NULL || ident_text == KW_LIT_TRUE || ident_text == KW_LIT_FALSE {
                    iter.consume();

                    // Parse builtin literal
                    let value = match ident_text {
                        KW_LIT_NULL => Literal::Null,
                        KW_LIT_TRUE => Literal::True,
                        KW_LIT_FALSE => Literal::False,
                        _ => unreachable!(),
                    };

                    ctx.heap.alloc_literal_expression(|this| LiteralExpression {
                        this,
                        span: ident_span,
                        value,
                        parent: ExpressionParent::None,
                        unique_id_in_definition: -1,
                    }).upcast()
                } else if ident_text == KW_LET {
                    // Binding expression
                    let operator_span = iter.next_span();
                    iter.consume();

                    let bound_to = self.consume_prefix_expression(module, iter, ctx)?;
                    consume_token(&module.source, iter, TokenKind::Equal)?;
                    let bound_from = self.consume_prefix_expression(module, iter, ctx)?;

                    let full_span = InputSpan::from_positions(
                        operator_span.begin, ctx.heap[bound_from].full_span().end,
                    );

                    ctx.heap.alloc_binding_expression(|this| BindingExpression{
                        this, operator_span, full_span, bound_to, bound_from,
                        parent: ExpressionParent::None,
                        unique_id_in_definition: -1,
                    }).upcast()
                } else if ident_text == KW_CAST {
                    // Casting expression
                    iter.consume();
                    let to_type = if Some(TokenKind::OpenAngle) == iter.next() {
                        let angle_start_pos = iter.next_start_position();
                        iter.consume();
                        let definition_id = self.cur_definition;
                        let poly_vars = ctx.heap[definition_id].poly_vars();
                        self.type_parser.consume_parser_type(
                            iter, &ctx.heap, &module.source, &ctx.symbols,
                            poly_vars, definition_id, SymbolScope::Module(module.root_id),
                            true, Some(angle_start_pos)
                        )?
                    } else {
                        // Automatic casting with inferred target type
                        ParserType{
                            elements: vec![ParserTypeElement{
                                element_span: ident_span,
                                variant: ParserTypeVariant::Inferred,
                            }],
                            full_span: ident_span
                        }
                    };

                    consume_token(&module.source, iter, TokenKind::OpenParen)?;
                    let subject = self.consume_expression(module, iter, ctx)?;
                    let mut full_span = iter.next_span();
                    full_span.begin = to_type.full_span.begin;
                    consume_token(&module.source, iter, TokenKind::CloseParen)?;

                    ctx.heap.alloc_cast_expression(|this| CastExpression{
                        this,
                        cast_span: to_type.full_span,
                        full_span, to_type, subject,
                        parent: ExpressionParent::None,
                        unique_id_in_definition: -1,
                    }).upcast()
                } else {
                    // Not a builtin literal, but also not a known type. So we
                    // assume it is a variable expression. Although if we do,
                    // then if a programmer mistyped a struct/function name the
                    // error messages will be rather cryptic. For polymorphic
                    // arguments we can't really do anything at all (because it
                    // uses the '<' token). In the other cases we try to provide
                    // a better error message.
                    iter.consume();
                    let next = iter.next();
                    if Some(TokenKind::ColonColon) == next {
                        return Err(ParseError::new_error_str_at_span(&module.source, ident_span, "unknown identifier"));
                    } else if Some(TokenKind::OpenParen) == next {
                        return Err(ParseError::new_error_str_at_span(
                            &module.source, ident_span,
                            "unknown identifier, did you mistype a union variant's, component's, or function's name?"
                        ));
                    } else if Some(TokenKind::OpenCurly) == next {
                        return Err(ParseError::new_error_str_at_span(
                            &module.source, ident_span,
                            "unknown identifier, did you mistype a struct type's name?"
                        ))
                    }

                    let ident_text = ctx.pool.intern(ident_text);
                    let identifier = Identifier { span: ident_span, value: ident_text };

                    ctx.heap.alloc_variable_expression(|this| VariableExpression {
                        this,
                        identifier,
                        declaration: None,
                        used_as_binding_target: false,
                        parent: ExpressionParent::None,
                        unique_id_in_definition: -1,
                    }).upcast()
                }
            }
        } else {
            return Err(ParseError::new_error_str_at_pos(
                &module.source, iter.last_valid_pos(), "expected an expression"
            ));
        };

        Ok(result)
    }

    //--------------------------------------------------------------------------
    // Expression Utilities
    //--------------------------------------------------------------------------

    #[inline]
    fn consume_generic_binary_expression<
        M: Fn(Option<TokenKind>) -> Option<BinaryOperator>,
        F: Fn(&mut PassDefinitions, &Module, &mut TokenIter, &mut PassCtx) -> Result<ExpressionId, ParseError>
    >(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx, match_fn: M, higher_precedence_fn: F
    ) -> Result<ExpressionId, ParseError> {
        let mut result = higher_precedence_fn(self, module, iter, ctx)?;
        while let Some(operation) = match_fn(iter.next()) {
            let operator_span = iter.next_span();
            iter.consume();

            let left = result;
            let right = higher_precedence_fn(self, module, iter, ctx)?;

            let full_span = InputSpan::from_positions(
                ctx.heap[left].full_span().begin,
                ctx.heap[right].full_span().end,
            );

            result = ctx.heap.alloc_binary_expression(|this| BinaryExpression{
                this, operator_span, full_span, left, operation, right,
                parent: ExpressionParent::None,
                unique_id_in_definition: -1,
            }).upcast();
        }

        Ok(result)
    }

    #[inline]
    fn consume_expression_list(
        &mut self, module: &Module, iter: &mut TokenIter, ctx: &mut PassCtx, end_pos: Option<&mut InputPosition>
    ) -> Result<Vec<ExpressionId>, ParseError> {
        let mut section = self.expressions.start_section();
        consume_comma_separated(
            TokenKind::OpenParen, TokenKind::CloseParen, &module.source, iter, ctx,
            |_source, iter, ctx| self.consume_expression(module, iter, ctx),
            &mut section, "an expression", "a list of expressions", end_pos
        )?;
        Ok(section.into_vec())
    }
}

/// Consumes polymorphic variables and throws them on the floor.
fn consume_polymorphic_vars_spilled(source: &InputSource, iter: &mut TokenIter, _ctx: &mut PassCtx) -> Result<(), ParseError> {
    maybe_consume_comma_separated_spilled(
        TokenKind::OpenAngle, TokenKind::CloseAngle, source, iter, _ctx,
        |source, iter, _ctx| {
            consume_ident(source, iter)?;
            Ok(())
        }, "a polymorphic variable"
    )?;
    Ok(())
}

/// Consumes the parameter list to functions/components
fn consume_parameter_list(
    parser: &mut ParserTypeParser, source: &InputSource, iter: &mut TokenIter,
    ctx: &mut PassCtx, target: &mut ScopedSection<VariableId>,
    scope: SymbolScope, definition_id: DefinitionId
) -> Result<(), ParseError> {
    consume_comma_separated(
        TokenKind::OpenParen, TokenKind::CloseParen, source, iter, ctx,
        |source, iter, ctx| {
            let poly_vars = ctx.heap[definition_id].poly_vars(); // Rust being rust, multiple lookups
            let parser_type = parser.consume_parser_type(
                iter, &ctx.heap, source, &ctx.symbols, poly_vars, definition_id,
                scope, false, None
            )?;
            let identifier = consume_ident_interned(source, iter, ctx)?;
            let parameter_id = ctx.heap.alloc_variable(|this| Variable{
                this,
                kind: VariableKind::Parameter,
                parser_type,
                identifier,
                relative_pos_in_block: 0,
                unique_id_in_scope: -1,
            });
            Ok(parameter_id)
        },
        target, "a parameter", "a parameter list", None
    )
}