lang: Fix parser and resolver failures

9839c5be6a23ebced65cee008904bf4df719eb6d9b56e2b156bd0858d103904e
Report AST allocation failure through parser and driver diagnostics.
Check instances after all module type bodies, so that parent and sibling
trait methods are available. Report excess record fields as a source
error at the first field beyond the limit.

Share module traversal and use empty slices for empty parser lists.
Avoid repeated token-consumption results, span updates and empty trivia
work. Cover arena exhaustion, field limits and cross-module instances.

Assisted-by: Codex:gpt-6
Change-Id: Id3d4d5ef4879788109a00465ecd19d872ced4282
Alexis Sellier committed ago 1 parent 25cdb5b3
compiler/radiance.rad +57 -48
1 1
//! Radiance compiler front-end.
2 2
mod codegen;
3 3
mod testgen;
4 4
5 5
use std::mem;
6 +
use std::lang::alloc::AllocError;
6 7
use std::fmt;
7 8
use std::io;
8 9
use std::mem::heap;
9 10
use std::lang::ast;
10 11
use std::lang::layout;
763 764
}
764 765
765 766
/// Build a scope access chain: a::b::c from a slice of identifiers.
766 767
fn synthScopeAccess(
767 768
    arena: &mut ast::NodeArena, pool: &mut strings::Pool, path: &[*[u8]]
768 -
) -> *ast::Node {
769 -
    let mut result = ast::synthNode(
769 +
) -> *ast::Node throws (AllocError) {
770 +
    let mut result = try ast::synthNode(
770 771
        arena,
771 772
        ast::NodeValue::Ident(strings::intern(pool, path[0]))
772 773
    );
773 774
    for i in 1 .. path.len {
774 -
        let child = ast::synthNode(
775 +
        let child = try ast::synthNode(
775 776
            arena,
776 777
            ast::NodeValue::Ident(strings::intern(pool, path[i]))
777 778
        );
778 -
        set result = ast::synthNode(arena, ast::NodeValue::ScopeAccess(ast::Access {
779 +
        set result = try ast::synthNode(arena, ast::NodeValue::ScopeAccess(ast::Access {
779 780
            parent: result, child
780 781
        }));
781 782
    }
782 783
    return result;
783 784
}
786 787
fn synthRecordLitField(
787 788
    arena: &mut ast::NodeArena,
788 789
    pool: &mut strings::Pool,
789 790
    label: *[u8],
790 791
    value: *ast::Node
791 -
) -> *ast::Node {
792 -
    let labelNode = ast::synthNode(arena, ast::NodeValue::Ident(strings::intern(pool, label)));
793 -
    return ast::synthNode(arena, ast::NodeValue::RecordLitField(ast::Arg {
792 +
) -> *ast::Node throws (AllocError) {
793 +
    let labelNode = try ast::synthNode(arena, ast::NodeValue::Ident(strings::intern(pool, label)));
794 +
    return try ast::synthNode(arena, ast::NodeValue::RecordLitField(ast::Arg {
794 795
        label: labelNode, value
795 796
    }));
796 797
}
797 798
798 799
/// Synthesize a `testing::TestInfo { module, name, func }` literal for one test.
799 800
/// All fields are constants, so a list of these literals is emitted as data.
800 801
fn synthTestInfo(
801 802
    arena: &mut ast::NodeArena, pool: &mut strings::Pool, desc: &testgen::TestDesc
802 -
) -> *ast::Node {
803 -
    let typeName = synthScopeAccess(arena, pool, &["testing", "TestInfo"]);
804 -
    let modStr = il::formatQualifiedName(
803 +
) -> *ast::Node throws (AllocError) {
804 +
    let typeName = try synthScopeAccess(arena, pool, &["testing", "TestInfo"]);
805 +
    let modStr = try il::formatQualifiedName(
805 806
        arena.heap,
806 807
        &desc.modPath[.. desc.modPath.len - 1],
807 808
        desc.modPath[desc.modPath.len - 1]
808 809
    );
809 -
    let modArg = ast::synthNode(arena, ast::NodeValue::String(modStr));
810 -
    let nameArg = ast::synthNode(arena, ast::NodeValue::String(desc.fnName));
810 +
    let modArg = try ast::synthNode(arena, ast::NodeValue::String(modStr));
811 +
    let nameArg = try ast::synthNode(arena, ast::NodeValue::String(desc.fnName));
811 812
812 813
    // Intra-package path: skip the package name prefix.
813 814
    let mut funcPath: [*[u8]; module::MAX_MODULE_PATH_DEPTH] =
814 815
        [""; module::MAX_MODULE_PATH_DEPTH];
815 816
    for j in 1 .. desc.modPath.len {
816 817
        set funcPath[j - 1] = desc.modPath[j];
817 818
    }
818 819
    set funcPath[desc.modPath.len - 1] = desc.fnName;
819 -
    let funcArg = synthScopeAccess(arena, pool, &funcPath[.. desc.modPath.len]);
820 +
    let funcArg = try synthScopeAccess(arena, pool, &funcPath[.. desc.modPath.len]);
820 821
821 -
    let mut fields = ast::nodeSlice(arena, 3);
822 -
    try! fields.append(synthRecordLitField(arena, pool, "module", modArg), arena.heap);
823 -
    try! fields.append(synthRecordLitField(arena, pool, "name", nameArg), arena.heap);
824 -
    try! fields.append(synthRecordLitField(arena, pool, "func", funcArg), arena.heap);
822 +
    let mut fields = try ast::nodeSlice(arena, 3);
823 +
    try fields.append(try synthRecordLitField(arena, pool, "module", modArg), arena.heap);
824 +
    try fields.append(try synthRecordLitField(arena, pool, "name", nameArg), arena.heap);
825 +
    try fields.append(try synthRecordLitField(arena, pool, "func", funcArg), arena.heap);
825 826
826 -
    return ast::synthNode(arena, ast::NodeValue::RecordLit(ast::RecordLit {
827 +
    return try ast::synthNode(arena, ast::NodeValue::RecordLit(ast::RecordLit {
827 828
        typeName, fields, ignoreRest: false
828 829
    }));
829 830
}
830 831
831 832
/// Inject a test runner into the entry package's root module.
891 892
    io::printError(": found ");
892 893
    io::printError(text);
893 894
    io::printError(" test(s)\n");
894 895
895 896
    // Synthesize the `@default` function and append to the root module.
896 -
    let fnDecl = synthTestMainFn(&mut ctx.parser.arena, &mut ctx.parser.pool, &tests[..]);
897 -
898 -
    let updatedRoot = injectIntoBlock(rootAst, &mut ctx.parser.arena, fnDecl);
897 +
    let fnDecl = try synthTestMainFn(
898 +
        &mut ctx.parser.arena, &mut ctx.parser.pool, &tests[..]
899 +
    ) catch {
900 +
        throw error(&["fatal: syntax tree arena is full"]);
901 +
    };
902 +
    let updatedRoot = try injectIntoBlock(rootAst, &mut ctx.parser.arena, fnDecl) catch {
903 +
        throw error(&["fatal: syntax tree arena is full"]);
904 +
    };
899 905
    try module::setAst(graph, rootId, updatedRoot) catch {
900 906
        throw error(&["failed to set test runner AST"]);
901 907
    };
902 908
}
903 909
904 910
/// Synthesize the test entry point.
905 911
fn synthTestMainFn(
906 912
    arena: &mut ast::NodeArena, pool: &mut strings::Pool, tests: &[testgen::TestDesc]
907 -
) -> *ast::Node {
913 +
) -> *ast::Node throws (AllocError) {
908 914
    // Build array literal: `[testing::TestInfo { ... }, ...]`. Every element is a
909 915
    // constant, so the array is emitted as data and the size of the generated
910 916
    // function does not depend on the number of tests.
911 -
    let mut elements = ast::nodeSlice(arena, tests.len as u32);
917 +
    let mut elements = try ast::nodeSlice(arena, tests.len as u32);
912 918
    for i in 0 .. tests.len {
913 -
        try! elements.append(synthTestInfo(arena, pool, &tests[i]), arena.heap);
919 +
        try elements.append(try synthTestInfo(arena, pool, &tests[i]), arena.heap);
914 920
    }
915 -
    let arrayLit = ast::synthNode(arena, ast::NodeValue::ArrayLit(elements));
921 +
    let arrayLit = try ast::synthNode(arena, ast::NodeValue::ArrayLit(elements));
916 922
917 923
    // Build: `&[...]`.
918 -
    let testsRef = ast::synthNode(arena, ast::NodeValue::AddressOf(ast::AddressOf {
924 +
    let testsRef = try ast::synthNode(arena, ast::NodeValue::AddressOf(ast::AddressOf {
919 925
        target: arrayLit, mutable: false
920 926
    }));
921 927
922 928
    // Build: `testing::runAllTests(&[...])`.
923 -
    let runFn = synthScopeAccess(arena, pool, &["testing", "runAllTests"]);
924 -
    let callArgs = try! ast::nodeSlice(arena, 1).append(testsRef, arena.heap);
925 -
    let callExpr = ast::synthNode(arena, ast::NodeValue::Call(ast::Call {
929 +
    let runFn = try synthScopeAccess(arena, pool, &["testing", "runAllTests"]);
930 +
    let mut callArgs = try ast::nodeSlice(arena, 1);
931 +
    try callArgs.append(testsRef, arena.heap);
932 +
    let callExpr = try ast::synthNode(arena, ast::NodeValue::Call(ast::Call {
926 933
        callee: runFn, args: callArgs
927 934
    }));
928 935
929 936
    // Build: `return testing::runAllTests(&[...]);`
930 -
    let retStmt = ast::synthNode(arena, ast::NodeValue::Return { value: callExpr });
931 -
    let bodyStmts = try! ast::nodeSlice(arena, 1).append(retStmt, arena.heap);
932 -
    let fnBody = ast::synthNode(arena, ast::NodeValue::Block(
937 +
    let retStmt = try ast::synthNode(arena, ast::NodeValue::Return { value: callExpr });
938 +
    let mut bodyStmts = try ast::nodeSlice(arena, 1);
939 +
    try bodyStmts.append(retStmt, arena.heap);
940 +
    let fnBody = try ast::synthNode(arena, ast::NodeValue::Block(
933 941
        ast::Block { statements: bodyStmts, isUnsafe: false }
934 942
    ));
935 943
936 944
    // Build: `unsafe fn #testMain() -> i32`
937 -
    let fnName = ast::synthNode(arena, ast::NodeValue::Ident(strings::intern(pool, "#testMain")));
938 -
    let returnType = ast::synthNode(arena, ast::NodeValue::TypeSig(ast::TypeSig::Integer {
945 +
    let fnName = try ast::synthNode(arena, ast::NodeValue::Ident(
946 +
        strings::intern(pool, "#testMain")
947 +
    ));
948 +
    let returnType = try ast::synthNode(arena, ast::NodeValue::TypeSig(ast::TypeSig::Integer {
939 949
        width: 4, sign: ast::Signedness::Signed
940 950
    }));
941 951
    let fnSig = ast::FnSig {
942 -
        params: ast::nodeSlice(arena, 0),
952 +
        params: &[],
943 953
        returnType,
944 -
        throwList: ast::nodeSlice(arena, 0),
954 +
        throwList: &[],
945 955
    };
946 956
947 957
    // Entry and function safety attributes.
948 -
    let attrNode = ast::synthNode(arena, ast::NodeValue::Attribute(ast::Attribute::Default));
949 -
    let unsafeAttr = ast::synthNode(arena, ast::NodeValue::Attribute(ast::Attribute::Unsafe));
950 -
    let mut attrList = try! ast::nodeSlice(arena, 2).append(attrNode, arena.heap);
951 -
    try! attrList.append(unsafeAttr, arena.heap);
958 +
    let attrNode = try ast::synthNode(arena, ast::NodeValue::Attribute(ast::Attribute::Default));
959 +
    let unsafeAttr = try ast::synthNode(arena, ast::NodeValue::Attribute(ast::Attribute::Unsafe));
960 +
    let mut attrList = try ast::nodeSlice(arena, 2);
961 +
    try attrList.append(attrNode, arena.heap);
962 +
    try attrList.append(unsafeAttr, arena.heap);
952 963
    let fnAttrs = ast::Attributes { list: attrList };
953 964
954 -
    return ast::synthNode(arena, ast::NodeValue::FnDecl(ast::FnDecl {
965 +
    return try ast::synthNode(arena, ast::NodeValue::FnDecl(ast::FnDecl {
955 966
        name: fnName, sig: fnSig, body: fnBody, attrs: fnAttrs
956 967
    }));
957 968
}
958 969
959 970
/// Build a block node with a declaration appended to its statement list.
960 971
fn injectIntoBlock(
961 972
    blockNode: *ast::Node,
962 973
    arena: &mut ast::NodeArena,
963 974
    decl: *ast::Node
964 -
) -> *ast::Node {
975 +
) -> *ast::Node throws (AllocError) {
965 976
    let case ast::NodeValue::Block(block) = blockNode.value else {
966 977
        panic "injectIntoBlock: expected Block node";
967 978
    };
968 -
    let mut stmts = ast::nodeSlice(arena, block.statements.len + 1);
969 -
    for stmt in block.statements {
970 -
        try! stmts.append(stmt, arena.heap);
971 -
    }
972 -
    try! stmts.append(decl, arena.heap);
973 -
    return ast::allocNode(arena, blockNode.span, ast::NodeValue::Block(
979 +
    let mut stmts = try ast::nodeSlice(arena, block.statements.len + 1);
980 +
    try stmts.extend(block.statements, arena.heap);
981 +
    try stmts.append(decl, arena.heap);
982 +
    return try ast::allocNode(arena, blockNode.span, ast::NodeValue::Block(
974 983
        ast::Block { statements: stmts, isUnsafe: block.isUnsafe }
975 984
    ));
976 985
}
977 986
978 987
/// Write a hosted RV64 image: the native header for `layout`, then the code,
lib/std/lang/ast.rad +23 -18
1 1
//! Radiance AST modules.
2 2
export mod printer;
3 3
4 -
use std::io;
5 4
use std::fmt;
6 -
use std::mem::heap;
5 +
use std::io;
6 +
use std::lang::alloc::AllocError;
7 7
use std::lang::types;
8 +
use std::mem::heap;
8 9
9 10
/// Maximum number of trait methods.
10 11
export constant MAX_TRAIT_METHODS: u32 = 8;
11 12
12 13
/// Arena for all parser allocations.
28 29
}
29 30
30 31
/// Create an empty `*mut [*Node]` slice with exactly `capacity` reserved elements.
31 32
///
32 33
/// The returned slice has length zero and keeps the reserved capacity. A zero
33 -
/// capacity allocates nothing.
34 -
export fn nodeSlice(arena: &mut NodeArena, capacity: u32) -> *mut [*Node] {
34 +
/// capacity allocates nothing. Throws `AllocError` if the arena is full.
35 +
export fn nodeSlice(arena: &mut NodeArena, capacity: u32) -> *mut [*Node] throws (AllocError) {
35 36
    let mut nodes: *mut [*Node] = &mut [];
36 -
    try! nodes.reserve(capacity, arena.heap);
37 -
    return &mut nodes[.. 0];
37 +
    try nodes.reserve(capacity, arena.heap);
38 +
    return nodes;
38 39
}
39 40
40 41
/// Declaration attribute or modifier.
41 42
export union Attribute: Copy {
42 43
    /// Public visibility attribute.
1054 1055
}
1055 1056
1056 1057
/// Allocate a new AST node from the arena with the given span and value.
1057 1058
///
1058 1059
/// The node stays valid for the rest of compilation, because the AST arena is
1059 -
/// never reset or restored.
1060 -
export fn allocNode(arena: &mut NodeArena, span: Span, value: NodeValue) -> *mut Node {
1060 +
/// never reset or restored. Throws `AllocError` if the arena is full.
1061 +
export fn allocNode(arena: &mut NodeArena, span: Span, value: NodeValue) -> *mut Node
1062 +
    throws (AllocError)
1063 +
{
1061 1064
    let nodeId = arena.nextId;
1062 -
    set arena.nextId = nodeId + 1;
1063 1065
1064 1066
    let mut nodes: *mut [Node] = &mut [];
1065 -
    try! nodes.append(Node { id: nodeId, span, value }, arena.heap);
1067 +
    try nodes.append(Node { id: nodeId, span, value }, arena.heap);
1066 1068
1069 +
    set arena.nextId = nodeId + 1;
1067 1070
    return &mut nodes[0];
1068 1071
}
1069 1072
1070 1073
/// Allocate a synthetic AST node with a zero-length span.
1071 -
export fn synthNode(arena: &mut NodeArena, value: NodeValue) -> *mut Node {
1072 -
    return allocNode(arena, Span { offset: 0, length: 0 }, value);
1074 +
/// Throws `AllocError` if the arena is full.
1075 +
export fn synthNode(arena: &mut NodeArena, value: NodeValue) -> *mut Node throws (AllocError) {
1076 +
    return try allocNode(arena, Span { offset: 0, length: 0 }, value);
1073 1077
}
1074 1078
1075 1079
/// Synthetic module with a single function in it.
1076 1080
record SynthFnMod: Copy {
1077 1081
    /// The module block.
1079 1083
    /// The function block.
1080 1084
    fnBody: *Node,
1081 1085
}
1082 1086
1083 1087
/// Synthesize a module with a function in it with the given name and statements.
1088 +
/// Throws `AllocError` if the arena is full.
1084 1089
export fn synthFnModule(
1085 1090
    arena: &mut NodeArena, name: *[u8], bodyStmts: *[*Node]
1086 -
) -> SynthFnMod {
1087 -
    let fnName = synthNode(arena, NodeValue::Ident(name));
1091 +
) -> SynthFnMod throws (AllocError) {
1092 +
    let fnName = try synthNode(arena, NodeValue::Ident(name));
1088 1093
    let params: *[*Node] = &[];
1089 1094
    let throwList: *[*Node] = &[];
1090 1095
    let fnSig = FnSig { params, returnType: nil, throwList };
1091 -
    let fnBody: *Node = synthNode(arena, NodeValue::Block(
1096 +
    let fnBody: *Node = try synthNode(arena, NodeValue::Block(
1092 1097
        Block { statements: bodyStmts, isUnsafe: false }
1093 1098
    ));
1094 -
    let fnDecl = synthNode(arena, NodeValue::FnDecl(FnDecl {
1099 +
    let fnDecl = try synthNode(arena, NodeValue::FnDecl(FnDecl {
1095 1100
        name: fnName, sig: fnSig, body: fnBody, attrs: nil
1096 1101
    }));
1097 1102
    let mut rootStmts: *mut [*Node] = &mut [];
1098 -
    try! rootStmts.append(fnDecl, arena.heap);
1099 -
    let modBody = synthNode(arena, NodeValue::Block(
1103 +
    try rootStmts.append(fnDecl, arena.heap);
1104 +
    let modBody = try synthNode(arena, NodeValue::Block(
1100 1105
        Block { statements: rootStmts, isUnsafe: false }
1101 1106
    ));
1102 1107
1103 1108
    return SynthFnMod { modBody, fnBody };
1104 1109
}
lib/std/lang/il.rad +7 -6
76 76
export mod printer;
77 77
export mod binary;
78 78
export mod verify;
79 79
80 80
use std::mem::heap;
81 +
use std::lang::alloc::AllocError;
81 82
82 83
/// DeviceAccess flag bits that contain the byte width.
83 84
export constant DEVICE_WIDTH_MASK: u64 = 0xff;
84 85
/// DeviceAccess flag that selects a register write.
85 86
export constant DEVICE_WRITE: u64 = 0x100;
113 114
export constant PATH_SEPARATOR: *[u8] = "::";
114 115
115 116
/// Format a qualified symbol name: `pkg::mod::path::name`.
116 117
///
117 118
/// The name is allocated from `a`, so it stays valid as long as the storage
118 -
/// behind `a` does.
119 +
/// behind `a` does. Throws `AllocError` if the heap is full.
119 120
export fn formatQualifiedName(
120 121
    a: &heap::Heap, path: &[*[u8]], name: *[u8]
121 -
) -> *[u8] {
122 +
) -> *[u8] throws (AllocError) {
122 123
    let mut totalLen: u32 = name.len;
123 124
    for segment in path {
124 125
        set totalLen += segment.len + PATH_SEPARATOR.len;
125 126
    }
126 127
    let mut buf: *mut [u8] = &mut [];
127 -
    try! buf.reserve(totalLen, a);
128 +
    try buf.reserve(totalLen, a);
128 129
129 130
    for segment in path {
130 -
        try! buf.extend(segment, a);
131 -
        try! buf.extend(PATH_SEPARATOR, a);
131 +
        try buf.extend(segment, a);
132 +
        try buf.extend(PATH_SEPARATOR, a);
132 133
    }
133 -
    try! buf.extend(name, a);
134 +
    try buf.extend(name, a);
134 135
    return &buf[..];
135 136
}
136 137
137 138
///////////
138 139
// Types //
lib/std/lang/lower.rad +12 -10
1356 1356
    return module::moduleQualifiedPath(entry);
1357 1357
}
1358 1358
1359 1359
/// Build a qualified name string for a symbol.
1360 1360
/// If `modId` is nil, uses current module.
1361 -
fn qualifyName(self: &mut Lowerer, modId: ?u16, name: *[u8]) -> *[u8] {
1361 +
fn qualifyName(self: &mut Lowerer, modId: ?u16, name: *[u8]) -> *[u8] throws (LowerError) {
1362 1362
    let path = getModulePath(self, modId);
1363 1363
    if path.len == 0 {
1364 1364
        return name;
1365 1365
    }
1366 -
    return il::formatQualifiedName(self.resolver.arena, path, name);
1366 +
    return try il::formatQualifiedName(self.resolver.arena, path, name) catch {
1367 +
        throw LowerError::AllocationFailed;
1368 +
    };
1367 1369
}
1368 1370
1369 1371
/// Register a function symbol with its qualified name.
1370 1372
/// Called when lowering function declarations, so cross-package calls can find
1371 1373
/// the function by name.
1570 1572
        throw LowerError::ExpectedFunction;
1571 1573
    };
1572 1574
    let isExtern = checkAttr(decl.attrs, ast::Attribute::Extern);
1573 1575
1574 1576
    // Build qualified function name for multi-module compilation.
1575 -
    let qualName = qualifyName(self, nil, name);
1577 +
    let qualName = try qualifyName(self, nil, name);
1576 1578
1577 1579
    // Register function symbol for cross-package call resolution.
1578 1580
    if let sym = resolver::symbolFor(&self.resolver, node) {
1579 1581
        try registerFnSym(self, sym, qualName);
1580 1582
    }
1948 1950
            methodName,
1949 1951
        ]
1950 1952
    ) catch {
1951 1953
        throw LowerError::AllocationFailed;
1952 1954
    };
1953 -
    return qualifyName(self, modId, &buf[..]);
1955 +
    return try qualifyName(self, modId, &buf[..]);
1954 1956
}
1955 1957
1956 1958
/// Build a v-table data name of the form "vtable::Type::Trait".
1957 1959
fn vtableName(
1958 1960
    self: &mut Lowerer,
1967 1969
            traitName,
1968 1970
        ]
1969 1971
    ) catch {
1970 1972
        throw LowerError::AllocationFailed;
1971 1973
    };
1972 -
    return qualifyName(self, modId, &buf[..]);
1974 +
    return try qualifyName(self, modId, &buf[..]);
1973 1975
}
1974 1976
1975 1977
/// Lower an instance declaration (`instance Trait for Type { ... }`).
1976 1978
///
1977 1979
/// Each method in the instance block is lowered as a standalone function
2312 2314
) throws (LowerError) {
2313 2315
    let sym = try symOf(self, node);
2314 2316
    let ty = try typeOf(self, node);
2315 2317
    let layout = resolver::getTypeLayout(&self.resolver, ty);
2316 2318
    let symName = self.resolver.symbols[*sym].name;
2317 -
    let qualName = qualifyName(self, nil, symName);
2319 +
    let qualName = try qualifyName(self, nil, symName);
2318 2320
    // The region of a heap: zero-filled bytes that only `slice.grow` carves up. The binary
2319 2321
    // form takes the size of data from its layout. The backend aligns the pool.
2320 2322
    if let case resolver::NodeExtra::StaticHeap(size) =
2321 2323
        resolver::nodeData(&self.resolver, value).extra
2322 2324
    {
2479 2481
    if let case resolver::Type::Fn(_) = ty {
2480 2482
        let sym = resolver::symbolFor(&self.resolver, node)
2481 2483
            else throw LowerError::MissingSymbol(node);
2482 2484
        let modId = resolver::moduleIdForSymbol(&self.resolver, sym);
2483 2485
        let symName = self.resolver.symbols[*sym].name;
2484 -
        let qualName = qualifyName(self, modId, symName);
2486 +
        let qualName = try qualifyName(self, modId, symName);
2485 2487
        try dataBuilderPush(
2486 2488
            b,
2487 2489
            il::DataValue {
2488 2490
                item: il::DataItem::Fn(qualName), count: 1
2489 2491
            },
3626 3628
/// Emit a copy instruction that loads a data symbol's address into a register.
3627 3629
fn emitDataAddr(self: &mut Lowerer, sym: resolver::SymbolId) -> il::Reg throws (LowerError) {
3628 3630
    let dst = nextReg(self);
3629 3631
    let modId = resolver::moduleIdForSymbol(&self.resolver, sym);
3630 3632
    let symName = self.resolver.symbols[*sym].name;
3631 -
    let qualName = qualifyName(self, modId, symName);
3633 +
    let qualName = try qualifyName(self, modId, symName);
3632 3634
3633 3635
    try emit(self, il::Instr::Copy { dst, val: il::Val::DataSym(qualName) });
3634 3636
3635 3637
    return dst;
3636 3638
}
3638 3640
/// Emit a copy instruction that loads a function's address into a register.
3639 3641
fn emitFnAddr(self: &mut Lowerer, sym: resolver::SymbolId) -> il::Reg throws (LowerError) {
3640 3642
    let dst = nextReg(self);
3641 3643
    let modId = resolver::moduleIdForSymbol(&self.resolver, sym);
3642 3644
    let symName = self.resolver.symbols[*sym].name;
3643 -
    let qualName = qualifyName(self, modId, symName);
3645 +
    let qualName = try qualifyName(self, modId, symName);
3644 3646
3645 3647
    try emit(self, il::Instr::Copy { dst, val: il::Val::FnAddr(qualName) });
3646 3648
3647 3649
    return dst;
3648 3650
}
10828 10830
            // This works for functions in the current package.
10829 10831
            let modId = resolver::moduleIdForSymbol(&self.resolver, sym) else {
10830 10832
                throw LowerError::MissingMetadata;
10831 10833
            };
10832 10834
            let symName = self.resolver.symbols[*sym].name;
10833 -
            return il::Val::FnAddr(qualifyName(self, modId, symName));
10835 +
            return il::Val::FnAddr(try qualifyName(self, modId, symName));
10834 10836
        }
10835 10837
    }
10836 10838
    return try lowerExpr(self, callee);
10837 10839
}
10838 10840
lib/std/lang/lower/tests.rad +7 -5
16 16
/// Test that each lowering error has a message and that no two messages are equal.
17 17
@test unsafe fn testErrorMessagesAreSpecific() throws (testing::TestError) {
18 18
    let mut arena = ast::nodeArena(&mut NODE_STORAGE[..]);
19 19
    let errors: [super::LowerError; 28] = [
20 20
        super::LowerError::OutputFailed,
21 -
        super::LowerError::MissingSymbol(ast::synthNode(&mut arena, ast::NodeValue::Nil)),
22 -
        super::LowerError::MissingType(ast::synthNode(&mut arena, ast::NodeValue::Nil)),
23 -
        super::LowerError::MissingConst(ast::synthNode(&mut arena, ast::NodeValue::Nil)),
21 +
        super::LowerError::MissingSymbol(try! ast::synthNode(&mut arena, ast::NodeValue::Nil)),
22 +
        super::LowerError::MissingType(try! ast::synthNode(&mut arena, ast::NodeValue::Nil)),
23 +
        super::LowerError::MissingConst(try! ast::synthNode(&mut arena, ast::NodeValue::Nil)),
24 24
        super::LowerError::ExpectedOptional,
25 25
        super::LowerError::ExpectedRecord,
26 26
        super::LowerError::ExpectedArray,
27 -
        super::LowerError::ExpectedBlock(ast::synthNode(&mut arena, ast::NodeValue::Nil)),
27 +
        super::LowerError::ExpectedBlock(try! ast::synthNode(&mut arena, ast::NodeValue::Nil)),
28 28
        super::LowerError::ExpectedIdentifier,
29 29
        super::LowerError::ExpectedFunctionParam,
30 30
        super::LowerError::ExpectedFunction,
31 31
        super::LowerError::OutsideOfLoop,
32 32
        super::LowerError::InvalidUse,
33 -
        super::LowerError::UnexpectedNodeValue(ast::synthNode(&mut arena, ast::NodeValue::Nil)),
33 +
        super::LowerError::UnexpectedNodeValue(try! ast::synthNode(
34 +
            &mut arena, ast::NodeValue::Nil
35 +
        )),
34 36
        super::LowerError::UnexpectedType(resolver::Type::Void),
35 37
        super::LowerError::MissingTarget,
36 38
        super::LowerError::MissingMetadata,
37 39
        super::LowerError::ExpectedSliceOrArray,
38 40
        super::LowerError::ExpectedVariant,
lib/std/lang/parser.rad +569 -552
1 1
//! Recursive descent parser for the Radiance programming language.
2 2
@test export mod tests;
3 3
4 4
use std::mem;
5 +
use std::lang::alloc::AllocError;
5 6
use std::io;
6 7
use std::fmt;
7 8
use std::lang::types;
8 9
use std::lang::ast;
9 10
use std::lang::strings;
40 41
41 42
/// Parser error type.
42 43
export union ParseError: Copy {
43 44
    /// Encountered a token that was not expected in the current context.
44 45
    UnexpectedToken,
46 +
    /// The syntax tree arena has no space for the module.
47 +
    AllocationFailed,
45 48
}
46 49
47 50
/// Represents a parsed name-type-value triple.
48 51
///
49 52
/// Used for record field declarations, variable declarations,
236 239
        closing: &mut [],
237 240
    };
238 241
}
239 242
240 243
/// Emit a `true` or `false` literal node.
241 -
fn nodeBool(p: &mut Parser, value: bool) -> *ast::Node {
242 -
    return node(p, ast::NodeValue::Bool(value));
244 +
fn nodeBool(p: &mut Parser, value: bool) -> *ast::Node throws (AllocError) {
245 +
    return try node(p, ast::NodeValue::Bool(value));
243 246
}
244 247
245 248
/// Parse an integer literal while mapping shared errors into parser diagnostics.
246 249
fn parseIntLiteral(p: &mut Parser, text: *[u8]) -> fmt::IntLiteral
247 250
    throws (ParseError)
258 261
    };
259 262
    return literal;
260 263
}
261 264
262 265
/// Emit an integer type node.
263 -
fn nodeTypeInt(p: &mut Parser, width: u8, sign: ast::Signedness) -> *ast::Node {
264 -
    return node(p, ast::NodeValue::TypeSig(
266 +
fn nodeTypeInt(p: &mut Parser, width: u8, sign: ast::Signedness) -> *ast::Node throws (AllocError) {
267 +
    return try node(p, ast::NodeValue::TypeSig(
265 268
        ast::TypeSig::Integer { width, sign }
266 269
    ));
267 270
}
268 271
269 272
/// Emit a number literal node with the provided literal metadata.
270 -
fn nodeNumber(p: &mut Parser, literal: fmt::IntLiteral) -> *ast::Node {
271 -
    return node(p, ast::NodeValue::Number(literal));
273 +
fn nodeNumber(p: &mut Parser, literal: fmt::IntLiteral) -> *ast::Node throws (AllocError) {
274 +
    return try node(p, ast::NodeValue::Number(literal));
272 275
}
273 276
274 277
/// Emit a `super` node.
275 -
fn nodeSuper(p: &mut Parser) -> *ast::Node {
276 -
    return node(p, ast::NodeValue::Super);
278 +
fn nodeSuper(p: &mut Parser) -> *ast::Node throws (AllocError) {
279 +
    return try node(p, ast::NodeValue::Super);
277 280
}
278 281
279 282
/// Emit a single attribute node.
280 -
fn nodeAttribute(p: &mut Parser, attr: ast::Attribute) -> *ast::Node {
281 -
    return node(p, ast::NodeValue::Attribute(attr));
283 +
fn nodeAttribute(p: &mut Parser, attr: ast::Attribute) -> *ast::Node throws (AllocError) {
284 +
    return try node(p, ast::NodeValue::Attribute(attr));
282 285
}
283 286
284 287
/// Emit a unary operator node.
285 -
fn nodeUnary(p: &mut Parser, op: ast::UnaryOp, value: *ast::Node) -> *ast::Node {
286 -
    return node(p, ast::NodeValue::UnOp({ op, value }));
288 +
fn nodeUnary(p: &mut Parser, op: ast::UnaryOp, value: *ast::Node) -> *ast::Node
289 +
    throws (AllocError)
290 +
{
291 +
    return try node(p, ast::NodeValue::UnOp({ op, value }));
287 292
}
288 293
289 294
/// Parse one expression without inheriting a surrounding condition or pattern context.
290 -
fn parseNormalExpr(p: &mut Parser) -> *ast::Node throws (ParseError) {
295 +
fn parseNormalExpr(p: &mut Parser) -> *ast::Node throws (ParseError, AllocError) {
291 296
    let saved = p.context;
292 297
    set p.context = Context::Normal;
293 298
    let expr = try parseExpr(p);
294 299
    set p.context = saved;
295 300
    return expr;
296 301
}
297 302
298 303
/// Parse a parenthesized expression without applying postfix operators.
299 304
fn parseParenthesized(p: &mut Parser) -> *ast::Node
300 -
    throws (ParseError)
305 +
    throws (ParseError, AllocError)
301 306
{
302 307
    try expect(p, scanner::TokenKind::LParen, "expected `(`");
303 308
304 309
    let expr = try parseNormalExpr(p);
305 310
308 313
    return expr;
309 314
}
310 315
311 316
/// Parse an array literal: `[a, b, c]` or `[item; count]`.
312 317
fn parseArrayLiteral(p: &mut Parser) -> *ast::Node
313 -
    throws (ParseError)
318 +
    throws (ParseError, AllocError)
314 319
{
315 320
    try expect(p, scanner::TokenKind::LBracket, "expected `[`");
316 321
    let mut outer = openList(p);
317 322
    if check(p, scanner::TokenKind::RBracket) {
318 323
        // Empty array: `[]`.
319 324
        let empty: *mut [*ast::Node] = &mut [];
320 -
        closeList(p, outer, &[]);
321 -
        advance(p);
322 -
        let lit: *ast::Node = node(p, ast::NodeValue::ArrayLit(empty));
323 -
        attachClosing(p, lit);
325 +
        try closeList(p, outer, &[]);
326 +
        try advance(p);
327 +
        let lit: *ast::Node = try node(p, ast::NodeValue::ArrayLit(empty));
328 +
        try attachClosing(p, lit);
324 329
325 330
        return lit;
326 331
    }
327 -
    let firstLeading = takePending(p, &[]);
332 +
    let firstLeading = try takePending(p, &[]);
328 333
    noteItem(p, &mut outer);
329 334
    let firstExpr = try parseNormalExpr(p);
330 -
    attachLeading(p, firstExpr, firstLeading);
335 +
    try attachLeading(p, firstExpr, firstLeading);
331 336
332 -
    if consume(p, scanner::TokenKind::Semicolon) {
337 +
    if try consume(p, scanner::TokenKind::Semicolon) {
333 338
        // Array repeat literal: `[item; count]`. It has no list of items, so
334 339
        // its trivia stays with the enclosing item.
335 340
        set p.base = outer.base;
336 341
        let count = try parseNormalExpr(p);
337 342
        let broken = spansLines(p, outer);
338 343
        try expect(p, scanner::TokenKind::RBracket, "expected `]` after array repeat count");
339 -
        let repeat: *ast::Node = node(p, ast::NodeValue::ArrayRepeatLit(
344 +
        let repeat: *ast::Node = try node(p, ast::NodeValue::ArrayRepeatLit(
340 345
            ast::ArrayRepeatLit { item: firstExpr, count }
341 346
        ));
342 -
        markBroken(p, repeat, broken, ast::BrokenSite::List);
347 +
        try markBroken(p, repeat, broken, ast::BrokenSite::List);
343 348
344 349
        return repeat;
345 350
    }
346 351
    // Regular array literal: `[a, b, ...]`.
347 -
    let mut items = try! ast::nodeSlice(
352 +
    let mut items = try ast::nodeSlice(
348 353
        &mut p.arena, INITIAL_ITEMS
349 -
    ).append(firstExpr, p.arena.heap);
354 +
    );
355 +
    try items.append(firstExpr, p.arena.heap);
350 356
351 -
    while consume(p, scanner::TokenKind::Comma) and not check(p, scanner::TokenKind::RBracket) {
352 -
        let leading = takePending(p, &items[..]);
357 +
    while try consume(p, scanner::TokenKind::Comma) and not check(p, scanner::TokenKind::RBracket) {
358 +
        let leading = try takePending(p, &items[..]);
353 359
        let itemLine = startsLine(p) and p.triviaMode == TriviaMode::Keep;
354 360
        noteItem(p, &mut outer);
355 361
        let elem = try parseNormalExpr(p);
356 -
        attachLeading(p, elem, leading);
362 +
        try attachLeading(p, elem, leading);
357 363
        if itemLine {
358 -
            attachOne(p, elem, ast::TriviaPlacement::Leading, ast::TriviaKind::Broken(
364 +
            try attachOne(p, elem, ast::TriviaPlacement::Leading, ast::TriviaKind::Broken(
359 365
                ast::BrokenSite::ItemLine
360 366
            ));
361 367
        }
362 -
        try! items.append(elem, p.arena.heap);
368 +
        try items.append(elem, p.arena.heap);
363 369
    }
364 -
    closeSoftList(p, outer, &items[..]);
370 +
    try closeSoftList(p, outer, &items[..]);
365 371
    try expect(p, scanner::TokenKind::RBracket, "expected `]` after array elements");
366 -
    let lit: *ast::Node = node(p, ast::NodeValue::ArrayLit(items));
367 -
    attachClosing(p, lit);
372 +
    let lit: *ast::Node = try node(p, ast::NodeValue::ArrayLit(items));
373 +
    try attachClosing(p, lit);
368 374
369 375
    return lit;
370 376
}
371 377
372 378
/// Parse a function call expression.
373 379
fn parseCall(p: &mut Parser, callee: *ast::Node) -> *ast::Node
374 -
    throws (ParseError)
380 +
    throws (ParseError, AllocError)
375 381
{
376 382
    try expect(p, scanner::TokenKind::LParen, "expected `(`");
377 383
    let mut outer = openList(p);
378 384
    let args = try parseItems(
379 385
        p, scanner::TokenKind::RParen, parseNormalExpr, &mut outer
380 386
    );
381 -
    closeSoftList(p, outer, &args[..]);
387 +
    try closeSoftList(p, outer, &args[..]);
382 388
    try expect(p, scanner::TokenKind::RParen, "expected `)`");
383 -
    let call: *ast::Node = node(p, ast::NodeValue::Call(
389 +
    let call: *ast::Node = try node(p, ast::NodeValue::Call(
384 390
        ast::Call { callee, args }
385 391
    ));
386 -
    attachClosing(p, call);
392 +
    try attachClosing(p, call);
387 393
388 394
    return call;
389 395
}
390 396
391 397
/// Parse zero or more trailing `as` casts applied to `expr`.
392 398
fn parseAsCast(p: &mut Parser, expr: *ast::Node) -> *ast::Node
393 -
    throws (ParseError)
399 +
    throws (ParseError, AllocError)
394 400
{
395 401
    let mut result = expr;
396 402
397 -
    while consume(p, scanner::TokenKind::As) {
403 +
    while try consume(p, scanner::TokenKind::As) {
398 404
        let target = try parseType(p);
399 405
400 -
        set result = node(p, ast::NodeValue::As(
406 +
        set result = try node(p, ast::NodeValue::As(
401 407
            ast::As { value: result, type: target }
402 408
        ));
403 409
    }
404 410
    return result;
405 411
}
408 414
///
409 415
///   `<thenExpr> if <condition> else <elseExpr>`
410 416
///
411 417
/// If no `if` keyword follows, returns the input expression unchanged.
412 418
fn parseCondExpr(p: &mut Parser, thenExpr: *ast::Node) -> *ast::Node
413 -
    throws (ParseError)
419 +
    throws (ParseError, AllocError)
414 420
{
415 421
    // Only parse conditional expressions in normal context.
416 422
    // In conditional context, `if` is used for guards.
417 423
    if p.context <> Context::Normal {
418 424
        return thenExpr;
419 425
    }
420 426
    let beforeIf = startsLine(p);
421 -
    if not consume(p, scanner::TokenKind::If) {
427 +
    if not try consume(p, scanner::TokenKind::If) {
422 428
        return thenExpr;
423 429
    }
424 430
    let condition = try parseCond(p);
425 431
    let beforeElse = startsLine(p);
426 432
    try expect(p, scanner::TokenKind::Else, "expected `else` in conditional expression");
427 433
    let elseExpr = try parseExpr(p);
428 -
    let cond: *ast::Node = node(p, ast::NodeValue::CondExpr(
434 +
    let cond: *ast::Node = try node(p, ast::NodeValue::CondExpr(
429 435
        ast::CondExpr { condition, thenExpr, elseExpr }
430 436
    ));
431 -
    markBroken(p, cond, beforeIf or beforeElse, ast::BrokenSite::Chain);
437 +
    try markBroken(p, cond, beforeIf or beforeElse, ast::BrokenSite::Chain);
432 438
433 439
    return cond;
434 440
}
435 441
436 442
/// Parse array subscript or slice expression after `[`.
437 443
fn parseSubscriptOrSlice(p: &mut Parser, container: *ast::Node) -> *ast::Node
438 -
    throws (ParseError)
444 +
    throws (ParseError, AllocError)
439 445
{
440 446
    try expect(p, scanner::TokenKind::LBracket, "expected `[`");
441 447
442 448
    let mut index: *ast::Node = undefined;
443 449
444 -
    if consume(p, scanner::TokenKind::DotDot) {
450 +
    if try consume(p, scanner::TokenKind::DotDot) {
445 451
        // Either `..` or `..end`.
446 452
        let mut endExpr: ?*ast::Node = nil;
447 453
        if not check(p, scanner::TokenKind::RBracket) {
448 454
            set endExpr = try parseNormalExpr(p);
449 455
        }
450 -
        set index = node(p, ast::NodeValue::Range(
456 +
        set index = try node(p, ast::NodeValue::Range(
451 457
            ast::Range { start: nil, end: endExpr }
452 458
        ));
453 459
    } else {
454 460
        // Either `n`, `n..` or `n..end`.
455 461
        let startExpr = try parseNormalExpr(p);
456 462
457 -
        if consume(p, scanner::TokenKind::DotDot) {
463 +
        if try consume(p, scanner::TokenKind::DotDot) {
458 464
            // Either `n..` or `n..end`.
459 465
            let mut endExpr: ?*ast::Node = nil;
460 466
            if not check(p, scanner::TokenKind::RBracket) {
461 467
                set endExpr = try parseNormalExpr(p);
462 468
            }
463 -
            set index = node(p, ast::NodeValue::Range(
469 +
            set index = try node(p, ast::NodeValue::Range(
464 470
                ast::Range { start: startExpr, end: endExpr }
465 471
            ));
466 472
        } else {
467 473
            // Just `n` - regular indexing.
468 474
            set index = startExpr;
469 475
        }
470 476
    }
471 477
    try expect(p, scanner::TokenKind::RBracket, "expected `]` after array index");
472 478
473 -
    return node(p, ast::NodeValue::Subscript { container, index });
479 +
    return try node(p, ast::NodeValue::Subscript { container, index });
474 480
}
475 481
476 482
/// Parse postfix operators (eg. field access, function call etc.)
477 483
fn parsePostfix(p: &mut Parser, expr: *ast::Node) -> *ast::Node
478 -
    throws (ParseError)
484 +
    throws (ParseError, AllocError)
479 485
{
480 486
    let mut result = expr;
481 487
482 488
    loop {
483 489
        match p.current.kind {
484 490
            case scanner::TokenKind::Dot => {
485 -
                advance(p);
491 +
                try advance(p);
486 492
487 493
                let field = try parseIdent(p, "expected field name after `.`");
488 -
                set result = node(p, ast::NodeValue::FieldAccess(
494 +
                set result = try node(p, ast::NodeValue::FieldAccess(
489 495
                    ast::Access { parent: result, child: field }
490 496
                ));
491 497
            }
492 498
            case scanner::TokenKind::ColonColon => {
493 -
                advance(p);
499 +
                try advance(p);
494 500
495 501
                let ident = try parseIdent(p, "expected identifier after `::`");
496 -
                set result = node(p, ast::NodeValue::ScopeAccess(
502 +
                set result = try node(p, ast::NodeValue::ScopeAccess(
497 503
                    ast::Access { parent: result, child: ident }
498 504
                ));
499 505
            }
500 506
            case scanner::TokenKind::LBracket => {
501 507
                set result = try parseSubscriptOrSlice(p, result);
513 519
    }
514 520
    return result;
515 521
}
516 522
517 523
/// Parse a conditional expression.
518 -
export fn parseCond(p: &mut Parser) -> *ast::Node throws (ParseError) {
524 +
export fn parseCond(p: &mut Parser) -> *ast::Node throws (ParseError, AllocError) {
519 525
    let saved = p.context;
520 526
    set p.context = Context::Condition;
521 527
    let expr = try parseExpr(p);
522 528
    set p.context = saved;
523 529
524 530
    return expr;
525 531
}
526 532
527 533
/// Parse unary expression followed by optional `as` cast.
528 534
/// `as` has higher precedence than binary ops but lower than unary.
529 -
fn parseUnary(p: &mut Parser) -> *ast::Node throws (ParseError) {
535 +
fn parseUnary(p: &mut Parser) -> *ast::Node throws (ParseError, AllocError) {
530 536
    let unary = try parseUnaryExpr(p);
531 537
    return try parseAsCast(p, unary);
532 538
}
533 539
534 540
/// Parse prefix unary expressions and defer to primary expressions otherwise.
535 541
fn parseUnaryExpr(p: &mut Parser) -> *ast::Node
536 -
    throws (ParseError)
542 +
    throws (ParseError, AllocError)
537 543
{
538 544
    match p.current.kind {
539 545
        case scanner::TokenKind::Not => {
540 -
            advance(p);
546 +
            try advance(p);
541 547
            let value = try parseUnaryExpr(p);
542 -
            return nodeUnary(p, ast::UnaryOp::Not, value);
548 +
            return try nodeUnary(p, ast::UnaryOp::Not, value);
543 549
        }
544 550
        case scanner::TokenKind::Minus => {
545 -
            advance(p);
551 +
            try advance(p);
546 552
            let value = try parseUnaryExpr(p);
547 -
            return nodeUnary(p, ast::UnaryOp::Neg, value);
553 +
            return try nodeUnary(p, ast::UnaryOp::Neg, value);
548 554
        }
549 555
        case scanner::TokenKind::Tilde => {
550 -
            advance(p);
556 +
            try advance(p);
551 557
            let value = try parseUnaryExpr(p);
552 -
            return nodeUnary(p, ast::UnaryOp::BitNot, value);
558 +
            return try nodeUnary(p, ast::UnaryOp::BitNot, value);
553 559
        }
554 560
        case scanner::TokenKind::Star => {
555 -
            advance(p);
561 +
            try advance(p);
556 562
            let value = try parseUnaryExpr(p);
557 -
            return node(p, ast::NodeValue::Deref(value));
563 +
            return try node(p, ast::NodeValue::Deref(value));
558 564
        }
559 565
        case scanner::TokenKind::Amp => {
560 -
            advance(p);
561 -
            let mutable = consume(p, scanner::TokenKind::Mut);
566 +
            try advance(p);
567 +
            let mutable = try consume(p, scanner::TokenKind::Mut);
562 568
            let target = try parseUnaryExpr(p);
563 -
            return node(p, ast::NodeValue::AddressOf({ target: target, mutable: mutable }));
569 +
            return try node(p, ast::NodeValue::AddressOf({ target: target, mutable: mutable }));
564 570
        }
565 571
        else => {
566 -
            return try parsePrimary(p);
572 +
            // Parse a primary expression (leaf nodes followed by postfix operators).
573 +
            let leaf = try parseLeaf(p);
574 +
            return try parsePostfix(p, leaf);
567 575
        }
568 576
    }
569 577
}
570 578
571 579
/// Find the operator info for a token if it has precedence greater than the
600 608
    }
601 609
}
602 610
603 611
/// Build a range expression node with an optional start and end expression.
604 612
fn parseRangeExpr(p: &mut Parser, start: ?*ast::Node) -> *ast::Node
605 -
    throws (ParseError)
613 +
    throws (ParseError, AllocError)
606 614
{
607 615
    let mut endExpr: ?*ast::Node = nil;
608 616
609 617
    if not isRangeTerminator(p.current.kind) {
610 618
        let right = try parseUnary(p);
611 619
        set endExpr = try parseBinary(p, right, -1);
612 620
    }
613 -
    return node(p, ast::NodeValue::Range(
621 +
    return try node(p, ast::NodeValue::Range(
614 622
        ast::Range { start, end: endExpr }
615 623
    ));
616 624
}
617 625
618 626
/// Parse binary expressions using precedence climbing.
619 627
fn parseBinary(p: &mut Parser, left: *ast::Node, minPrec: i32) -> *ast::Node
620 -
    throws (ParseError)
628 +
    throws (ParseError, AllocError)
621 629
{
622 630
    let mut result = left;
623 631
624 632
    loop {
625 633
        if p.current.kind == scanner::TokenKind::DotDot {
626 634
            if minPrec >= 0 {
627 635
                break;
628 636
            }
629 -
            advance(p);
637 +
            try advance(p);
630 638
            set result = try parseRangeExpr(p, result);
631 639
        } else {
632 640
            let opInfo = findNextOp(p.current.kind, minPrec) else break;
633 641
            let beforeOp = startsLine(p);
634 -
            advance(p);
642 +
            try advance(p);
635 643
            let afterOp = startsLine(p);
636 644
637 645
            let mut right = try parseUnary(p);
638 646
639 647
            while let _ = findNextOp(p.current.kind, opInfo.prec) {
640 648
                set right = try parseBinary(p, right, opInfo.prec);
641 649
            }
642 -
            set result = node(p, ast::NodeValue::BinOp(ast::BinOp {
650 +
            set result = try node(p, ast::NodeValue::BinOp(ast::BinOp {
643 651
                op: opInfo.op, left: result, right
644 652
            }));
645 -
            markBroken(p, result, beforeOp or afterOp, ast::BrokenSite::Chain);
653 +
            try markBroken(p, result, beforeOp or afterOp, ast::BrokenSite::Chain);
646 654
        }
647 655
    }
648 656
    return result;
649 657
}
650 658
666 674
    }
667 675
}
668 676
669 677
/// Parse a primary leaf expression without postfix operators.
670 678
fn parseLeaf(p: &mut Parser) -> *ast::Node
671 -
    throws (ParseError)
679 +
    throws (ParseError, AllocError)
672 680
{
673 681
    match p.current.kind {
674 682
        case scanner::TokenKind::True => {
675 -
            advance(p);
676 -
            return nodeBool(p, true);
683 +
            try advance(p);
684 +
            return try nodeBool(p, true);
677 685
        }
678 686
        case scanner::TokenKind::False => {
679 -
            advance(p);
680 -
            return nodeBool(p, false);
687 +
            try advance(p);
688 +
            return try nodeBool(p, false);
681 689
        }
682 690
        case scanner::TokenKind::Ident => {
683 -
            advance(p);
684 -
            return node(p, ast::NodeValue::Ident(p.previous.source));
691 +
            try advance(p);
692 +
            return try node(p, ast::NodeValue::Ident(p.previous.source));
685 693
        }
686 694
        case scanner::TokenKind::Super => {
687 -
            advance(p);
688 -
            return nodeSuper(p);
695 +
            try advance(p);
696 +
            return try nodeSuper(p);
689 697
        }
690 698
        case scanner::TokenKind::Number => {
691 -
            advance(p);
699 +
            try advance(p);
692 700
            let source = p.previous.source;
693 701
            let literal = try parseIntLiteral(p, source);
694 -
            return nodeNumber(p, literal);
702 +
            return try nodeNumber(p, literal);
695 703
        }
696 704
        case scanner::TokenKind::LParen => {
697 705
            return try parseParenthesized(p);
698 706
        }
699 707
        case scanner::TokenKind::Try => {
700 708
            return try parseTryExpr(p);
701 709
        }
702 710
        case scanner::TokenKind::Nil => {
703 -
            advance(p);
704 -
            return node(p, ast::NodeValue::Nil);
711 +
            try advance(p);
712 +
            return try node(p, ast::NodeValue::Nil);
705 713
        }
706 714
        case scanner::TokenKind::Undefined => {
707 -
            advance(p);
708 -
            return node(p, ast::NodeValue::Undef);
715 +
            try advance(p);
716 +
            return try node(p, ast::NodeValue::Undef);
709 717
        }
710 718
        case scanner::TokenKind::Char => {
711 -
            advance(p);
719 +
            try advance(p);
712 720
            let ch = try fmt::parseChar(p.previous.source) catch {
713 721
                throw failParsing(p, "invalid char literal");
714 722
            };
715 -
            return node(p, ast::NodeValue::Char(ch));
723 +
            return try node(p, ast::NodeValue::Char(ch));
716 724
        }
717 725
        case scanner::TokenKind::String => {
718 -
            advance(p);
726 +
            try advance(p);
719 727
            let src = p.previous.source;
720 728
            let raw = &src[1 .. src.len - 1]; // Strip quotes.
721 729
722 730
            let mut buf: *mut [u8] = &mut [];
723 -
            set buf = try! fmt::unescapeAppend(buf, raw, p.arena.heap);
724 -
            return node(p, ast::NodeValue::String(buf));
731 +
            set buf = try fmt::unescapeAppend(buf, raw, p.arena.heap);
732 +
            return try node(p, ast::NodeValue::String(buf));
725 733
        }
726 734
        case scanner::TokenKind::Underscore => {
727 -
            advance(p);
728 -
            return node(p, ast::NodeValue::Placeholder);
735 +
            try advance(p);
736 +
            return try node(p, ast::NodeValue::Placeholder);
729 737
        }
730 738
        case scanner::TokenKind::LBracket => {
731 739
            return try parseArrayLiteral(p);
732 740
        }
733 741
        case scanner::TokenKind::AtIdent => {
734 742
            return try parseBuiltin(p);
735 743
        }
736 744
        case scanner::TokenKind::DotDot => {
737 -
            advance(p);
745 +
            try advance(p);
738 746
            return try parseRangeExpr(p, nil);
739 747
        }
740 748
        case scanner::TokenKind::LBrace => {
741 749
            // Anonymous record literal: { x: 1, y: 2 }.
742 750
            // Only allowed in normal context, not in conditions.
749 757
            throw failParsing(p, "expected expression");
750 758
        }
751 759
    }
752 760
}
753 761
754 -
/// Parse a primary expression (leaf nodes followed by postfix operators).
755 -
fn parsePrimary(p: &mut Parser) -> *ast::Node
756 -
    throws (ParseError)
757 -
{
758 -
    let leaf = try parseLeaf(p);
759 -
    return try parsePostfix(p, leaf);
760 -
}
761 -
762 762
/// Parse a builtin function call like `@sizeOf(T)` or `@alignOf(T)`.
763 763
fn parseBuiltin(p: &mut Parser) -> *ast::Node
764 -
    throws (ParseError)
764 +
    throws (ParseError, AllocError)
765 765
{
766 766
    // Skip the '@' to get the name.
767 767
    let ident = p.current.source;
768 -
    advance(p);
768 +
    try advance(p);
769 769
770 770
    let mut kind: ast::Builtin = undefined;
771 771
    // TODO: Use `match`.
772 772
    if ident == "@sizeOf" {
773 773
        set kind = ast::Builtin::SizeOf;
780 780
    }
781 781
    try expect(p, scanner::TokenKind::LParen, "expected `(` after builtin name");
782 782
783 783
    // Parse arguments into a list. Use capacity 4 to handle any valid argument count
784 784
    // plus some extra for error recovery.
785 -
    let mut args = ast::nodeSlice(&mut p.arena, 4);
785 +
    let mut args = try ast::nodeSlice(&mut p.arena, 4);
786 786
787 787
    if kind == ast::Builtin::SliceOf {
788 788
        // Parse comma-separated expressions until closing paren.
789 789
        // Argument count validation is done in semantic analysis.
790 790
        let mut outer = openList(p);
791 791
        while not check(p, scanner::TokenKind::RParen) {
792 -
            let leading = takePending(p, &args[..]);
792 +
            let leading = try takePending(p, &args[..]);
793 793
            noteItem(p, &mut outer);
794 794
            let arg = try parseExpr(p);
795 -
            attachLeading(p, arg, leading);
796 -
            try! args.append(arg, p.arena.heap);
797 -
            if not consume(p, scanner::TokenKind::Comma) {
795 +
            try attachLeading(p, arg, leading);
796 +
            try args.append(arg, p.arena.heap);
797 +
            if not try consume(p, scanner::TokenKind::Comma) {
798 798
                break;
799 799
            }
800 800
        }
801 -
        closeSoftList(p, outer, &args[..]);
801 +
        try closeSoftList(p, outer, &args[..]);
802 802
    } else {
803 -
        try! args.append(try parseType(p), p.arena.heap);
803 +
        try args.append(try parseType(p), p.arena.heap);
804 804
    }
805 805
    try expect(p, scanner::TokenKind::RParen, "expected `)` after builtin argument");
806 -
    let call: *ast::Node = node(p, ast::NodeValue::BuiltinCall { kind, args });
807 -
    attachClosing(p, call);
806 +
    let call: *ast::Node = try node(p, ast::NodeValue::BuiltinCall { kind, args });
807 +
    try attachClosing(p, call);
808 808
809 809
    return call;
810 810
}
811 811
812 812
/// Parse a single expression.
813 813
///
814 814
/// Parses unary and binary operators using precedence climbing.
815 815
/// Conditional expressions (`x if cond else y`) have lowest precedence.
816 816
export fn parseExpr(p: &mut Parser) -> *ast::Node
817 -
    throws (ParseError)
817 +
    throws (ParseError, AllocError)
818 818
{
819 819
    let left = try parseUnary(p);
820 820
    let expr = try parseBinary(p, left, -1);
821 821
    return try parseCondExpr(p, expr);
822 822
}
823 823
824 824
/// Try to consume a compound assignment operator and return its binary op.
825 -
fn tryCompoundAssignOp(p: &mut Parser) -> ?ast::BinaryOp {
825 +
fn tryCompoundAssignOp(p: &mut Parser) -> ?ast::BinaryOp throws (AllocError) {
826 826
    match p.current.kind {
827 827
        case scanner::TokenKind::PlusEqual => {
828 -
            advance(p);
828 +
            try advance(p);
829 829
            return ast::BinaryOp::Add;
830 830
        }
831 831
        case scanner::TokenKind::MinusEqual => {
832 -
            advance(p);
832 +
            try advance(p);
833 833
            return ast::BinaryOp::Sub;
834 834
        }
835 835
        case scanner::TokenKind::StarEqual => {
836 -
            advance(p);
836 +
            try advance(p);
837 837
            return ast::BinaryOp::Mul;
838 838
        }
839 839
        case scanner::TokenKind::SlashEqual => {
840 -
            advance(p);
840 +
            try advance(p);
841 841
            return ast::BinaryOp::Div;
842 842
        }
843 843
        case scanner::TokenKind::PercentEqual => {
844 -
            advance(p);
844 +
            try advance(p);
845 845
            return ast::BinaryOp::Mod;
846 846
        }
847 847
        case scanner::TokenKind::AmpEqual => {
848 -
            advance(p);
848 +
            try advance(p);
849 849
            return ast::BinaryOp::BitAnd;
850 850
        }
851 851
        case scanner::TokenKind::PipeEqual => {
852 -
            advance(p);
852 +
            try advance(p);
853 853
            return ast::BinaryOp::BitOr;
854 854
        }
855 855
        case scanner::TokenKind::CaretEqual => {
856 -
            advance(p);
856 +
            try advance(p);
857 857
            return ast::BinaryOp::BitXor;
858 858
        }
859 859
        case scanner::TokenKind::LtLtEqual => {
860 -
            advance(p);
860 +
            try advance(p);
861 861
            return ast::BinaryOp::Shl;
862 862
        }
863 863
        case scanner::TokenKind::GtGtEqual => {
864 -
            advance(p);
864 +
            try advance(p);
865 865
            return ast::BinaryOp::Shr;
866 866
        }
867 867
        else => return nil,
868 868
    }
869 869
}
870 870
871 871
/// Parse an expression statement.
872 872
export fn parseExprStmt(p: &mut Parser) -> *ast::Node
873 -
    throws (ParseError)
873 +
    throws (ParseError, AllocError)
874 874
{
875 875
    let expr = try parseExpr(p);
876 -
    return node(p, ast::NodeValue::ExprStmt(expr));
876 +
    return try node(p, ast::NodeValue::ExprStmt(expr));
877 877
}
878 878
879 879
/// Parse a `set` statement assignment.
880 880
fn parseSetStmt(p: &mut Parser) -> *ast::Node
881 -
    throws (ParseError)
881 +
    throws (ParseError, AllocError)
882 882
{
883 883
    let target = try parseUnary(p);
884 884
    if not ast::isPlaceExpr(target) {
885 885
        throw failParsing(p, "invalid assignment target");
886 886
    }
887 -
    if consume(p, scanner::TokenKind::Equal) {
887 +
    if try consume(p, scanner::TokenKind::Equal) {
888 888
        let broken = startsLine(p);
889 889
        let value = try parseExpr(p);
890 -
        let stmt: *ast::Node = node(p, ast::NodeValue::Assign(
890 +
        let stmt: *ast::Node = try node(p, ast::NodeValue::Assign(
891 891
            ast::Assign { left: target, right: value }
892 892
        ));
893 -
        markBroken(p, stmt, broken, ast::BrokenSite::Value);
893 +
        try markBroken(p, stmt, broken, ast::BrokenSite::Value);
894 894
895 895
        return stmt;
896 896
    }
897 897
    // Compound assignment: desugar `set x <op>= y` into `set x = x <op> y`.
898 898
    // The target node is shared with the binary operand.
899 -
    if let op = tryCompoundAssignOp(p) {
899 +
    if let op = try tryCompoundAssignOp(p) {
900 900
        let broken = startsLine(p);
901 901
        let rhs = try parseExpr(p);
902 -
        let binop = node(p, ast::NodeValue::BinOp(
902 +
        let binop = try node(p, ast::NodeValue::BinOp(
903 903
            ast::BinOp { op, left: target, right: rhs }
904 904
        ));
905 -
        let stmt: *ast::Node = node(p, ast::NodeValue::Assign(
905 +
        let stmt: *ast::Node = try node(p, ast::NodeValue::Assign(
906 906
            ast::Assign { left: target, right: binop }
907 907
        ));
908 -
        markBroken(p, stmt, broken, ast::BrokenSite::Value);
908 +
        try markBroken(p, stmt, broken, ast::BrokenSite::Value);
909 909
910 910
        return stmt;
911 911
    }
912 912
    throw failParsing(p, "expected assignment after `set`");
913 913
}
914 914
915 915
/// Parse leading attributes and declaration modifiers.
916 -
fn parseAttributes(p: &mut Parser) -> ?ast::Attributes {
917 -
    let mut attrs = ast::nodeSlice(&mut p.arena, 4);
916 +
fn parseAttributes(p: &mut Parser) -> ?ast::Attributes throws (AllocError) {
917 +
    match p.current.kind {
918 +
        case
919 +
            scanner::TokenKind::AtIdent,
920 +
            scanner::TokenKind::Export,
921 +
            scanner::TokenKind::Unsafe =>
922 +
        {}
923 +
        else => return nil,
924 +
    }
925 +
    let mut attrs: *mut [*ast::Node] = &mut [];
918 926
919 -
    if let attr = tryParseAnnotation(p) {
920 -
        try! attrs.append(attr, p.arena.heap);
927 +
    if let attr = try tryParseAnnotation(p) {
928 +
        try attrs.append(attr, p.arena.heap);
921 929
    }
922 -
    if consume(p, scanner::TokenKind::Export) {
923 -
        try! attrs.append(nodeAttribute(p, ast::Attribute::Export), p.arena.heap);
930 +
    if try consume(p, scanner::TokenKind::Export) {
931 +
        try attrs.append(try nodeAttribute(p, ast::Attribute::Export), p.arena.heap);
924 932
    }
925 -
    if consume(p, scanner::TokenKind::Unsafe) {
926 -
        try! attrs.append(nodeAttribute(p, ast::Attribute::Unsafe), p.arena.heap);
933 +
    if try consume(p, scanner::TokenKind::Unsafe) {
934 +
        try attrs.append(try nodeAttribute(p, ast::Attribute::Unsafe), p.arena.heap);
927 935
    }
928 936
    if attrs.len > 0 {
929 937
        return ast::Attributes { list: attrs };
930 938
    }
931 939
    return nil;
933 941
934 942
/// Try to parse an annotation like `@default`.
935 943
///
936 944
/// Returns `nil` if not a known annotation (e.g. `@sizeOf` or `@alignOf` which are builtins).
937 945
/// Only consumes tokens if a valid annotation is found.
938 -
fn tryParseAnnotation(p: &mut Parser) -> ?*ast::Node {
946 +
fn tryParseAnnotation(p: &mut Parser) -> ?*ast::Node throws (AllocError) {
939 947
    if not check(p, scanner::TokenKind::AtIdent) {
940 948
        return nil;
941 949
    }
942 950
    // Token is @identifier, skip the '@' to get the name.
943 951
    let ident = p.current.source;
944 952
    if ident == "@default" {
945 -
        advance(p); // Consume `@default`.
946 -
        return nodeAttribute(p, ast::Attribute::Default);
953 +
        try advance(p); // Consume `@default`.
954 +
        return try nodeAttribute(p, ast::Attribute::Default);
947 955
    }
948 956
    if ident == "@test" {
949 -
        advance(p); // Consume `@test`.
950 -
        return nodeAttribute(p, ast::Attribute::Test);
957 +
        try advance(p); // Consume `@test`.
958 +
        return try nodeAttribute(p, ast::Attribute::Test);
951 959
    }
952 960
    if ident == "@intrinsic" {
953 -
        advance(p); // Consume `@intrinsic`.
954 -
        return nodeAttribute(p, ast::Attribute::Intrinsic);
961 +
        try advance(p); // Consume `@intrinsic`.
962 +
        return try nodeAttribute(p, ast::Attribute::Intrinsic);
955 963
    }
956 964
    if ident == "@language" {
957 -
        advance(p); // Consume `@language`.
958 -
        return nodeAttribute(p, ast::Attribute::Language);
965 +
        try advance(p); // Consume `@language`.
966 +
        return try nodeAttribute(p, ast::Attribute::Language);
959 967
    }
960 968
    return nil;
961 969
}
962 970
963 971
/// Parse a single statement.
964 972
///
965 973
/// Dispatches to the appropriate statement parser based on the current token.
966 974
export fn parseStmt(p: &mut Parser) -> *ast::Node
967 -
    throws (ParseError)
975 +
    throws (ParseError, AllocError)
968 976
{
969 977
    // TODO: Why is `parseStmt` checking for attributes?
970 978
    // We should have a `parseDecl` which is top-level, and `parseStmt` which
971 979
    // is inside functions.
972 -
    let attrs = parseAttributes(p);
980 +
    let attrs = try parseAttributes(p);
973 981
    if let list = attrs {
974 982
        if ast::attributesContains(&list, ast::Attribute::Unsafe)
975 983
            and p.current.kind == scanner::TokenKind::LBrace
976 984
        {
977 985
            if list.list.len <> 1 {
1028 1036
        }
1029 1037
        case scanner::TokenKind::Assert => {
1030 1038
            return try parseAssert(p);
1031 1039
        }
1032 1040
        case scanner::TokenKind::Break => {
1033 -
            advance(p);
1034 -
            return node(p, ast::NodeValue::Break);
1041 +
            try advance(p);
1042 +
            return try node(p, ast::NodeValue::Break);
1035 1043
        }
1036 1044
        case scanner::TokenKind::Continue => {
1037 -
            advance(p);
1038 -
            return node(p, ast::NodeValue::Continue);
1045 +
            try advance(p);
1046 +
            return try node(p, ast::NodeValue::Continue);
1039 1047
        }
1040 1048
        case scanner::TokenKind::Match => {
1041 1049
            return try parseMatch(p);
1042 1050
        }
1043 1051
        case scanner::TokenKind::Let => {
1044 -
            advance(p);
1045 -
            if consume(p, scanner::TokenKind::Case) {
1052 +
            try advance(p);
1053 +
            if try consume(p, scanner::TokenKind::Case) {
1046 1054
                return try parseLetCase(p);
1047 1055
            }
1048 -
            if consume(p, scanner::TokenKind::Mut) {
1056 +
            if try consume(p, scanner::TokenKind::Mut) {
1049 1057
                return try parseLet(p, true);
1050 1058
            }
1051 1059
            return try parseLet(p, false);
1052 1060
        }
1053 1061
        case scanner::TokenKind::Set => {
1054 -
            advance(p);
1062 +
            try advance(p);
1055 1063
            return try parseSetStmt(p);
1056 1064
        }
1057 1065
        case scanner::TokenKind::Constant => {
1058 1066
            return try parseConst(p, attrs);
1059 1067
        }
1090 1098
/// Parse statements until the specified ending token is encountered.
1091 1099
///
1092 1100
/// Returns the completed immutable statement list. The trivia before `end` is
1093 1101
/// left for the block that owns the statements.
1094 1102
export fn parseStmtsUntil(p: &mut Parser, end: scanner::TokenKind, capacity: u32) -> *[*ast::Node]
1095 -
    throws (ParseError)
1103 +
    throws (ParseError, AllocError)
1096 1104
{
1097 1105
    let outer = openList(p);
1098 -
    let mut statements = ast::nodeSlice(&mut p.arena, capacity);
1099 -
    while not check(p, end) {
1100 -
        let leading = takePending(p, &statements[..]);
1106 +
    let mut statements = try ast::nodeSlice(&mut p.arena, capacity);
1107 +
    while p.current.kind <> end {
1108 +
        let leading = try takePending(p, &statements[..]);
1101 1109
        let stmt = try parseStmt(p);
1102 -
        attachLeading(p, stmt, leading);
1103 -
        try! statements.append(stmt, p.arena.heap);
1110 +
        try attachLeading(p, stmt, leading);
1111 +
        try statements.append(stmt, p.arena.heap);
1104 1112
1105 -
        if check(p, end) or check(p, scanner::TokenKind::Eof) {
1113 +
        if p.current.kind == end or p.current.kind == scanner::TokenKind::Eof {
1106 1114
            break;
1107 1115
        }
1108 -
        if not consume(p, scanner::TokenKind::Semicolon) {
1109 -
            // Only require semicolon if the statement needs one.
1110 -
            if ast::needsSemicolon(stmt) {
1111 -
                throw failParsing(p, "expected `;` after statement");
1112 -
            }
1116 +
        // Only require semicolon if the statement needs one.
1117 +
        if p.current.kind == scanner::TokenKind::Semicolon {
1118 +
            try advance(p);
1119 +
        } else if ast::needsSemicolon(stmt) {
1120 +
            throw failParsing(p, "expected `;` after statement");
1113 1121
        }
1114 1122
    }
1115 -
    closeList(p, outer, &statements[..]);
1123 +
    try closeList(p, outer, &statements[..]);
1116 1124
1117 1125
    return statements;
1118 1126
}
1119 1127
1120 1128
/// Parse a block of statements enclosed in curly braces.
1121 1129
export fn parseBlock(p: &mut Parser) -> *ast::Node
1122 -
    throws (ParseError)
1130 +
    throws (ParseError, AllocError)
1123 1131
{
1124 1132
    return try parseBlockBody(p, false);
1125 1133
}
1126 1134
1127 1135
/// Parse a statement block with the specified unsafe permission.
1128 1136
fn parseBlockBody(p: &mut Parser, isUnsafe: bool) -> *ast::Node
1129 -
    throws (ParseError)
1137 +
    throws (ParseError, AllocError)
1130 1138
{
1131 -
    if not consume(p, scanner::TokenKind::LBrace) {
1139 +
    if not try consume(p, scanner::TokenKind::LBrace) {
1132 1140
        throw failParsing(p, "expected `{`");
1133 1141
    }
1134 1142
    let statements = try parseStmtsUntil(
1135 1143
        p, scanner::TokenKind::RBrace, INITIAL_STATEMENTS
1136 1144
    );
1137 1145
    let blk = ast::Block { statements, isUnsafe };
1138 1146
    try expect(p, scanner::TokenKind::RBrace, "expected `}`");
1139 -
    let block: *ast::Node = node(p, ast::NodeValue::Block(blk));
1140 -
    attachClosing(p, block);
1147 +
    let block: *ast::Node = try node(p, ast::NodeValue::Block(blk));
1148 +
    try attachClosing(p, block);
1141 1149
1142 1150
    return block;
1143 1151
}
1144 1152
1145 1153
/// Create a block containing a single statement node.
1146 -
fn mkBlockWith(p: &mut Parser, node: *ast::Node) -> ast::Block {
1147 -
    let stmts = try! ast::nodeSlice(&mut p.arena, 1).append(node, p.arena.heap);
1154 +
fn mkBlockWith(p: &mut Parser, node: *ast::Node) -> ast::Block throws (AllocError) {
1155 +
    let mut stmts = try ast::nodeSlice(&mut p.arena, 1);
1156 +
    try stmts.append(node, p.arena.heap);
1148 1157
    return ast::Block { statements: stmts, isUnsafe: false };
1149 1158
}
1150 1159
1151 1160
/// Parse the branch that follows `else` in let-else style constructs.
1152 1161
///
1153 1162
/// Allows either a block, a single statement like `return`,
1154 1163
/// or a standalone expression which is returned directly.
1155 1164
fn parseLetElseBranch(p: &mut Parser) -> *ast::Node
1156 -
    throws (ParseError)
1165 +
    throws (ParseError, AllocError)
1157 1166
{
1158 1167
    if check(p, scanner::TokenKind::LBrace) {
1159 1168
        return try parseBlock(p);
1160 1169
    }
1161 1170
    let branch = try parseStmt(p);
1165 1174
    }
1166 1175
    return branch;
1167 1176
}
1168 1177
1169 1178
/// Allocate a new node from the parser's arena.
1170 -
fn node(p: &mut Parser, value: ast::NodeValue) -> *mut ast::Node {
1179 +
/// Use the most recently consumed token for the node's span.
1180 +
fn node(p: &mut Parser, value: ast::NodeValue) -> *mut ast::Node throws (AllocError) {
1171 1181
    let span = ast::Span {
1172 1182
        offset: p.previous.offset,
1173 1183
        length: p.previous.source.len,
1174 1184
    };
1175 -
    let n = ast::allocNode(&mut p.arena, span, value);
1176 -
    finishSpan(p, n);
1177 -
1178 -
    return n;
1179 -
}
1180 -
1181 -
/// Update the span of `node` using the most recently consumed token.
1182 -
fn finishSpan(p: &mut Parser, node: &mut ast::Node) {
1183 -
    let start: u32 = node.span.offset;
1184 -
    let mut end: u32 = p.previous.offset + p.previous.source.len;
1185 -
1186 -
    if end >= start {
1187 -
        set node.span.length = end - start;
1188 -
    } else {
1189 -
        set node.span.length = 0;
1190 -
    }
1185 +
    return try ast::allocNode(&mut p.arena, span, value);
1191 1186
}
1192 1187
1193 1188
/// Report a parser error.
1194 1189
fn reportError(p: &mut Parser, token: scanner::Token, message: *[u8]) {
1195 1190
    assert message.len > 0;
1249 1244
export fn check(p: &Parser, kind: scanner::TokenKind) -> bool {
1250 1245
    return p.current.kind == kind;
1251 1246
}
1252 1247
1253 1248
/// Advance the parser by one token.
1254 -
export fn advance(p: &mut Parser) {
1249 +
export fn advance(p: &mut Parser) throws (AllocError) {
1255 1250
    set p.previous = p.current;
1256 1251
    if p.triviaMode == TriviaMode::Discard {
1257 1252
        set p.current = scanner::next(&mut p.scanner, &mut p.pool);
1258 1253
        return;
1259 1254
    }
1260 1255
    let gapStart = p.scanner.cursor;
1261 1256
    set p.current = scanner::next(&mut p.scanner, &mut p.pool);
1262 1257
    let gapEnd = p.scanner.token;
1263 -
    scanGap(p, gapStart, gapEnd);
1258 +
    try scanGap(p, gapStart, gapEnd);
1264 1259
}
1265 1260
1266 1261
/// Record the comments and blank lines in the source between two tokens.
1267 1262
///
1268 1263
/// Consecutive blank lines count as one.
1269 -
fn scanGap(p: &mut Parser, start: u32, end: u32) {
1264 +
fn scanGap(p: &mut Parser, start: u32, end: u32) throws (AllocError) {
1270 1265
    let source = p.scanner.source;
1271 1266
    let mut i = start;
1272 1267
    let mut newlines: u32 = 0;
1273 1268
    let mut blank = true; // Only whitespace since the last line break.
1274 1269
    let mut afterBlank = false;
1275 1270
1276 1271
    while i < end {
1277 1272
        let c = source[i];
1278 1273
        if c == '\n' {
1279 1274
            if newlines > 0 and blank and not afterBlank {
1280 -
                appendPending(
1275 +
                try appendPending(
1281 1276
                    p, ast::TriviaKind::BlankLine, PendingLine::NewLine, i
1282 1277
                );
1283 1278
                set afterBlank = true;
1284 1279
            }
1285 1280
            set newlines += 1;
1295 1290
                set stop += 1;
1296 1291
            }
1297 1292
            let line = PendingLine::SameLine
1298 1293
                if newlines == 0
1299 1294
                else PendingLine::NewLine;
1300 -
            appendPending(
1295 +
            try appendPending(
1301 1296
                p, ast::TriviaKind::Comment(&source[i .. last]), line, i
1302 1297
            );
1303 1298
            set blank = false;
1304 1299
            set afterBlank = false;
1305 1300
            set i = stop;
1310 1305
}
1311 1306
1312 1307
/// Add a scanned comment or blank line at `offset` to the pending trivia.
1313 1308
fn appendPending(
1314 1309
    p: &mut Parser, kind: ast::TriviaKind, line: PendingLine, offset: u32
1315 -
) {
1316 -
    try! p.pending.append(Pending { kind, line, offset }, p.arena.heap);
1310 +
) throws (AllocError) {
1311 +
    try p.pending.append(Pending { kind, line, offset }, p.arena.heap);
1317 1312
}
1318 1313
1319 1314
/// An open list: where the trivia of the enclosing list starts, and where the
1320 1315
/// opening delimiter is.
1321 1316
record Open: Copy {
1343 1338
    return Open { base: outer, offset: p.previous.offset, alone: true };
1344 1339
}
1345 1340
1346 1341
/// Attach the pending comments on the line where the last of `items` ends to
1347 1342
/// it as trailing trivia. Other pending trivia of the list stays pending.
1348 -
fn trailPending(p: &mut Parser, items: &[*ast::Node]) {
1349 -
    if items.len == 0 {
1343 +
fn trailPending(p: &mut Parser, items: &[*ast::Node]) throws (AllocError) {
1344 +
    if items.len == 0 or p.pending.len == p.base {
1350 1345
        return;
1351 1346
    }
1352 1347
    let last = items[items.len - 1];
1353 1348
    let mut list = p.pending.take();
1354 1349
    let mut kept = p.base;
1355 1350
    for i in p.base .. list.len {
1356 1351
        let t = list[i];
1357 1352
        if t.line == PendingLine::SameLine {
1358 -
            attachOne(p, last, ast::TriviaPlacement::Trailing, t.kind);
1353 +
            try attachOne(p, last, ast::TriviaPlacement::Trailing, t.kind);
1359 1354
        } else {
1360 1355
            set list[kept] = t;
1361 1356
            set kept += 1;
1362 1357
        }
1363 1358
    }
1368 1363
/// the list.
1369 1364
///
1370 1365
/// A comment on the line where the last of `items` ends is attached to it as
1371 1366
/// trailing trivia. The rest of the list's trivia is returned. Trivia of the
1372 1367
/// enclosing constructs stays pending.
1373 -
fn takePending(p: &mut Parser, items: &[*ast::Node]) -> *mut [Pending] {
1374 -
    trailPending(p, items);
1368 +
fn takePending(p: &mut Parser, items: &[*ast::Node]) -> *mut [Pending] throws (AllocError) {
1369 +
    if p.pending.len == p.base {
1370 +
        return &mut [];
1371 +
    }
1372 +
    try trailPending(p, items);
1375 1373
    let mut list = p.pending.take();
1376 1374
    let mut taken: *mut [Pending] = &mut [];
1377 1375
    for i in p.base .. list.len {
1378 -
        try! taken.append(list[i], p.arena.heap);
1376 +
        try taken.append(list[i], p.arena.heap);
1379 1377
    }
1380 1378
    set p.pending = &mut list[.. p.base];
1381 1379
1382 1380
    return taken;
1383 1381
}
1384 1382
1385 1383
/// Set aside the trivia before the closing delimiter of a list, and return to
1386 1384
/// the enclosing list whose trivia started at `outer`.
1387 1385
///
1388 1386
/// The node that owns the list claims it with [`attachClosing`] once created.
1389 -
fn closeList(p: &mut Parser, outer: Open, items: &[*ast::Node]) {
1387 +
fn closeList(p: &mut Parser, outer: Open, items: &[*ast::Node]) throws (AllocError) {
1390 1388
    assert p.closing.len == 0, "closeList: unclaimed closing trivia";
1391 -
    set p.closing = takePending(p, items);
1389 +
    set p.closing = try takePending(p, items);
1392 1390
    set p.base = outer.base;
1393 1391
}
1394 1392
1395 1393
/// Close a list that a printer may break or keep on one line, with the
1396 1394
/// closing delimiter as the current token.
1397 1395
///
1398 1396
/// Like [`closeList`], and the closing trivia also holds a mark when the source
1399 1397
/// breaks the list across lines. Only a parser that keeps trivia marks.
1400 -
fn closeSoftList(p: &mut Parser, outer: Open, items: &[*ast::Node]) {
1401 -
    closeList(p, outer, items);
1398 +
fn closeSoftList(p: &mut Parser, outer: Open, items: &[*ast::Node]) throws (AllocError) {
1399 +
    try closeList(p, outer, items);
1402 1400
    if spansLines(p, outer) {
1403 -
        appendMark(p, ast::BrokenSite::List);
1401 +
        try appendMark(p, ast::BrokenSite::List);
1404 1402
        if outer.alone and items.len > 1 {
1405 -
            appendMark(p, ast::BrokenSite::Items);
1403 +
            try appendMark(p, ast::BrokenSite::Items);
1406 1404
        }
1407 1405
    }
1408 1406
}
1409 1407
1410 1408
/// Add a mark of a broken list to the closing trivia that [`closeList`] set
1411 1409
/// aside.
1412 -
fn appendMark(p: &mut Parser, site: ast::BrokenSite) {
1410 +
fn appendMark(p: &mut Parser, site: ast::BrokenSite) throws (AllocError) {
1413 1411
    let kind = ast::TriviaKind::Broken(site);
1414 1412
    let offset = p.current.offset;
1415 -
    try! p.closing.append(
1413 +
    try p.closing.append(
1416 1414
        Pending { kind, line: PendingLine::NewLine, offset }, p.arena.heap
1417 1415
    );
1418 1416
}
1419 1417
1420 1418
/// Note the item of a list that starts at the current token. The list stays
1442 1440
/// End a list that has no owner node, and return to the enclosing list whose
1443 1441
/// trivia started at `outer`.
1444 1442
///
1445 1443
/// A comment on the line where the last of `items` ends is attached to it.
1446 1444
/// The remaining trivia of the list joins the enclosing item.
1447 -
fn endList(p: &mut Parser, outer: Open, items: &[*ast::Node]) {
1448 -
    trailPending(p, items);
1445 +
fn endList(p: &mut Parser, outer: Open, items: &[*ast::Node]) throws (AllocError) {
1446 +
    try trailPending(p, items);
1449 1447
    set p.base = outer.base;
1450 1448
}
1451 1449
1452 1450
/// Attach one comment or blank line to the most recently created node.
1453 1451
fn attachOne(
1454 1452
    p: &mut Parser,
1455 1453
    target: *ast::Node,
1456 1454
    placement: ast::TriviaPlacement,
1457 1455
    kind: ast::TriviaKind
1458 -
) {
1456 +
) throws (AllocError) {
1459 1457
    if p.trivia.len > 0 {
1460 1458
        assert p.trivia[p.trivia.len - 1].node.id <= target.id,
1461 1459
            "attachOne: trivia not ordered by node";
1462 1460
    }
1463 1461
    let trivia = ast::Trivia { node: target, placement, kind };
1464 -
    try! p.trivia.append(trivia, p.arena.heap);
1462 +
    try p.trivia.append(trivia, p.arena.heap);
1465 1463
}
1466 1464
1467 1465
/// Attach pending trivia to the most recently created node.
1468 1466
fn attachTrivia(
1469 1467
    p: &mut Parser,
1470 1468
    target: *ast::Node,
1471 1469
    placement: ast::TriviaPlacement,
1472 1470
    list: *[Pending]
1473 -
) {
1471 +
) throws (AllocError) {
1474 1472
    for t in list {
1475 -
        attachOne(p, target, placement, t.kind);
1473 +
        try attachOne(p, target, placement, t.kind);
1476 1474
    }
1477 1475
}
1478 1476
1479 1477
/// Attach the trivia before an item of a list to it as leading trivia.
1480 1478
///
1481 1479
/// Comments of the list that start before the end of the last token of the
1482 1480
/// item follow. No list inside the item claimed them, so they are a part of
1483 1481
/// the item, such as a comment inside an expression. Blank lines among them
1484 1482
/// are dropped.
1485 -
fn attachLeading(p: &mut Parser, item: *ast::Node, leading: *[Pending]) {
1486 -
    attachTrivia(p, item, ast::TriviaPlacement::Leading, leading);
1483 +
fn attachLeading(p: &mut Parser, item: *ast::Node, leading: *[Pending]) throws (AllocError) {
1484 +
    if leading.len == 0 and p.pending.len == p.base {
1485 +
        return;
1486 +
    }
1487 +
    try attachTrivia(p, item, ast::TriviaPlacement::Leading, leading);
1487 1488
    let end = p.previous.offset + p.previous.source.len;
1488 1489
    let mut list = p.pending.take();
1489 1490
    let mut inside = p.base;
1490 1491
    while inside < list.len and list[inside].offset < end {
1491 1492
        let t = list[inside];
1492 1493
        if let case ast::TriviaKind::Comment(_) = t.kind {
1493 -
            attachOne(p, item, ast::TriviaPlacement::Leading, t.kind);
1494 +
            try attachOne(p, item, ast::TriviaPlacement::Leading, t.kind);
1494 1495
        }
1495 1496
        set inside += 1;
1496 1497
    }
1497 1498
    let mut kept = p.base;
1498 1499
    for i in inside .. list.len {
1502 1503
    set p.pending = &mut list[.. kept];
1503 1504
}
1504 1505
1505 1506
/// Attach the trivia set aside by [`closeList`] to `container` as closing
1506 1507
/// trivia.
1507 -
fn attachClosing(p: &mut Parser, container: *ast::Node) {
1508 +
fn attachClosing(p: &mut Parser, container: *ast::Node) throws (AllocError) {
1509 +
    if p.closing.len == 0 {
1510 +
        return;
1511 +
    }
1508 1512
    let closing = p.closing.take();
1509 -
    attachTrivia(p, container, ast::TriviaPlacement::Closing, closing);
1513 +
    try attachTrivia(p, container, ast::TriviaPlacement::Closing, closing);
1510 1514
}
1511 1515
1512 1516
/// Parse an `if let` pattern matching statement.
1513 1517
///
1514 1518
/// Syntax: `if let binding = scrutinee { ... }`
1515 1519
/// Syntax: `if let mut binding = scrutinee { ... }`
1516 -
fn parseIfLet(p: &mut Parser) -> *ast::Node throws (ParseError) {
1520 +
fn parseIfLet(p: &mut Parser) -> *ast::Node throws (ParseError, AllocError) {
1517 1521
    try expect(p, scanner::TokenKind::Let, "expected `let`");
1518 1522
1519 1523
    // Parse pattern: either `case <pattern>`, `mut <ident>`, or simple `<ident>`.
1520 1524
    let mut pattern: *ast::Node = undefined;
1521 1525
    let mut kind = ast::PatternKind::Binding;
1522 1526
    let mut mutable = false;
1523 1527
1524 -
    if consume(p, scanner::TokenKind::Case) {
1528 +
    if try consume(p, scanner::TokenKind::Case) {
1525 1529
        set pattern = try parseMatchPattern(p);
1526 1530
        set kind = ast::PatternKind::Case;
1527 1531
    } else {
1528 -
        set mutable = consume(p, scanner::TokenKind::Mut);
1532 +
        set mutable = try consume(p, scanner::TokenKind::Mut);
1529 1533
        set pattern = try parseIdentOrPlaceholder(
1530 1534
            p, "expected `case`, `mut`, or identifier after `let`"
1531 1535
        );
1532 1536
    }
1533 1537
    try expect(p, scanner::TokenKind::Equal, "expected `=` after pattern");
1534 1538
1535 1539
    let scrutinee = try parseCond(p);
1536 1540
    let mut guard: ?*ast::Node = nil;
1537 1541
1538 -
    if consume(p, scanner::TokenKind::Semicolon) {
1542 +
    if try consume(p, scanner::TokenKind::Semicolon) {
1539 1543
        set guard = try parseCond(p);
1540 1544
    }
1541 1545
    let thenBranch = try parseBlock(p);
1542 1546
    let mut elseBranch: ?*ast::Node = nil;
1543 1547
1544 -
    if consume(p, scanner::TokenKind::Else) {
1548 +
    if try consume(p, scanner::TokenKind::Else) {
1545 1549
        if check(p, scanner::TokenKind::If) {
1546 -
            set elseBranch = node(p, ast::NodeValue::Block(
1547 -
                mkBlockWith(p, try parseIf(p))
1550 +
            set elseBranch = try node(p, ast::NodeValue::Block(
1551 +
                try mkBlockWith(p, try parseIf(p))
1548 1552
            ));
1549 1553
        } else {
1550 1554
            set elseBranch = try parseBlock(p);
1551 1555
        }
1552 1556
    }
1553 -
    return node(p, ast::NodeValue::IfLet(ast::IfLet {
1557 +
    return try node(p, ast::NodeValue::IfLet(ast::IfLet {
1554 1558
        pattern: ast::PatternMatch { pattern, scrutinee, guard, kind, mutable },
1555 1559
        thenBranch,
1556 1560
        elseBranch,
1557 1561
    }));
1558 1562
}
1559 1563
1560 1564
/// Parse a `while let` statement.
1561 1565
fn parseWhileLet(p: &mut Parser) -> *ast::Node
1562 -
    throws (ParseError)
1566 +
    throws (ParseError, AllocError)
1563 1567
{
1564 1568
    try expect(p, scanner::TokenKind::Let, "expected `let`");
1565 1569
1566 1570
    // Parse pattern: either `case <pattern>`, `mut <ident>`, or simple `<ident>`.
1567 1571
    let mut pattern: *ast::Node = undefined;
1568 1572
    let mut kind = ast::PatternKind::Binding;
1569 1573
    let mut mutable = false;
1570 -
    if consume(p, scanner::TokenKind::Case) {
1574 +
    if try consume(p, scanner::TokenKind::Case) {
1571 1575
        set pattern = try parseMatchPattern(p);
1572 1576
        set kind = ast::PatternKind::Case;
1573 1577
    } else {
1574 -
        set mutable = consume(p, scanner::TokenKind::Mut);
1578 +
        set mutable = try consume(p, scanner::TokenKind::Mut);
1575 1579
        set pattern = try parseIdentOrPlaceholder(
1576 1580
            p, "expected `case`, `mut`, or identifier after `let`"
1577 1581
        );
1578 1582
    }
1579 1583
    try expect(p, scanner::TokenKind::Equal, "expected `=` after pattern");
1580 1584
1581 1585
    let scrutinee = try parseCond(p);
1582 1586
    let mut guard: ?*ast::Node = nil;
1583 1587
1584 -
    if consume(p, scanner::TokenKind::Semicolon) {
1588 +
    if try consume(p, scanner::TokenKind::Semicolon) {
1585 1589
        set guard = try parseCond(p);
1586 1590
    }
1587 1591
    let body = try parseBlock(p);
1588 1592
    let mut elseBranch: ?*ast::Node = nil;
1589 1593
1590 -
    if consume(p, scanner::TokenKind::Else) {
1594 +
    if try consume(p, scanner::TokenKind::Else) {
1591 1595
        set elseBranch = try parseBlock(p);
1592 1596
    }
1593 -
    return node(p, ast::NodeValue::WhileLet(ast::WhileLet {
1597 +
    return try node(p, ast::NodeValue::WhileLet(ast::WhileLet {
1594 1598
        pattern: ast::PatternMatch { pattern, scrutinee, guard, kind, mutable },
1595 1599
        body,
1596 1600
        elseBranch,
1597 1601
    }));
1598 1602
}
1599 1603
1600 1604
/// Parse a `while` statement.
1601 1605
fn parseWhile(p: &mut Parser) -> *ast::Node
1602 -
    throws (ParseError)
1606 +
    throws (ParseError, AllocError)
1603 1607
{
1604 1608
    try expect(p, scanner::TokenKind::While, "expected `while`");
1605 1609
1606 1610
    // Check for `while let` or `while let case` syntax.
1607 1611
    if check(p, scanner::TokenKind::Let) {
1609 1613
    }
1610 1614
    let condition = try parseCond(p);
1611 1615
    let body = try parseBlock(p);
1612 1616
    let mut elseBranch: ?*ast::Node = nil;
1613 1617
1614 -
    if consume(p, scanner::TokenKind::Else) {
1618 +
    if try consume(p, scanner::TokenKind::Else) {
1615 1619
        set elseBranch = try parseBlock(p);
1616 1620
    }
1617 -
    return node(p, ast::NodeValue::While(ast::While {
1621 +
    return try node(p, ast::NodeValue::While(ast::While {
1618 1622
        condition, body, elseBranch
1619 1623
    }));
1620 1624
}
1621 1625
1622 1626
/// Parse a `loop` statement.
1623 1627
fn parseLoop(p: &mut Parser) -> *ast::Node
1624 -
    throws (ParseError)
1628 +
    throws (ParseError, AllocError)
1625 1629
{
1626 1630
    try expect(p, scanner::TokenKind::Loop, "expected `loop`");
1627 1631
    let body = try parseBlock(p);
1628 1632
1629 -
    return node(p, ast::NodeValue::Loop { body });
1633 +
    return try node(p, ast::NodeValue::Loop { body });
1630 1634
}
1631 1635
1632 1636
/// Parse a `for` statement.
1633 1637
fn parseFor(p: &mut Parser) -> *ast::Node
1634 -
    throws (ParseError)
1638 +
    throws (ParseError, AllocError)
1635 1639
{
1636 1640
    try expect(p, scanner::TokenKind::For, "expected `for`");
1637 1641
1638 1642
    let binding = try parseIdentOrPlaceholder(p, "expected identifier or `_`");
1639 1643
    let mut index: ?*ast::Node = nil;
1640 1644
1641 -
    if consume(p, scanner::TokenKind::Comma) {
1645 +
    if try consume(p, scanner::TokenKind::Comma) {
1642 1646
        set index = try parseIdentOrPlaceholder(p, "expected index identifier or `_` after `,`");
1643 1647
    }
1644 1648
    try expect(p, scanner::TokenKind::In, "expected `in`");
1645 1649
1646 1650
    let iterable = try parseCond(p);
1647 1651
    let body = try parseBlock(p);
1648 1652
    let mut elseBranch: ?*ast::Node = nil;
1649 1653
1650 -
    if consume(p, scanner::TokenKind::Else) {
1654 +
    if try consume(p, scanner::TokenKind::Else) {
1651 1655
        set elseBranch = try parseBlock(p);
1652 1656
    }
1653 -
    return node(p, ast::NodeValue::For(ast::For {
1657 +
    return try node(p, ast::NodeValue::For(ast::For {
1654 1658
        binding, index, iterable, body, elseBranch
1655 1659
    }));
1656 1660
}
1657 1661
1658 1662
/// Return whether a token ends an optional statement value.
1673 1677
    }
1674 1678
}
1675 1679
1676 1680
/// Parse a `return` statement.
1677 1681
fn parseReturn(p: &mut Parser) -> *ast::Node
1678 -
    throws (ParseError)
1682 +
    throws (ParseError, AllocError)
1679 1683
{
1680 1684
    try expect(p, scanner::TokenKind::Return, "expected `return`");
1681 1685
1682 1686
    let mut value: ?*ast::Node = nil;
1683 1687
    if not endsOptionalValue(p.current.kind) {
1684 1688
        set value = try parseExpr(p);
1685 1689
    }
1686 -
    return node(p, ast::NodeValue::Return { value });
1690 +
    return try node(p, ast::NodeValue::Return { value });
1687 1691
}
1688 1692
1689 1693
/// Parse a `throw` statement.
1690 1694
fn parseThrow(p: &mut Parser) -> *ast::Node
1691 -
    throws (ParseError)
1695 +
    throws (ParseError, AllocError)
1692 1696
{
1693 1697
    try expect(p, scanner::TokenKind::Throw, "expected `throw`");
1694 1698
    let expr = try parseExpr(p);
1695 1699
1696 -
    return node(p, ast::NodeValue::Throw { expr });
1700 +
    return try node(p, ast::NodeValue::Throw { expr });
1697 1701
}
1698 1702
1699 1703
/// Parse a `panic` statement.
1700 1704
fn parsePanic(p: &mut Parser) -> *ast::Node
1701 -
    throws (ParseError)
1705 +
    throws (ParseError, AllocError)
1702 1706
{
1703 1707
    try expect(p, scanner::TokenKind::Panic, "expected `panic`");
1704 1708
1705 1709
    // `panic { expr }`.
1706 -
    if consume(p, scanner::TokenKind::LBrace) {
1710 +
    if try consume(p, scanner::TokenKind::LBrace) {
1707 1711
        let message: ?*ast::Node = try parseExpr(p);
1708 1712
        try expect(p, scanner::TokenKind::RBrace, "expected closing `}` after expression");
1709 -
        return node(p, ast::NodeValue::Panic { message });
1713 +
        return try node(p, ast::NodeValue::Panic { message });
1710 1714
    }
1711 1715
    // `panic` or `panic "message"`.
1712 1716
    let mut message: ?*ast::Node = nil;
1713 1717
    if not endsOptionalValue(p.current.kind) {
1714 1718
        set message = try parseExpr(p);
1715 1719
    }
1716 -
    return node(p, ast::NodeValue::Panic { message });
1720 +
    return try node(p, ast::NodeValue::Panic { message });
1717 1721
}
1718 1722
1719 1723
/// Parse an `assert` statement.
1720 1724
///
1721 1725
/// Forms:
1722 1726
///   `assert <expr>`
1723 1727
///   `assert <expr>, "message"`
1724 1728
///   `assert { <expr> }, "message"`
1725 1729
fn parseAssert(p: &mut Parser) -> *ast::Node
1726 -
    throws (ParseError)
1730 +
    throws (ParseError, AllocError)
1727 1731
{
1728 1732
    try expect(p, scanner::TokenKind::Assert, "expected `assert`");
1729 1733
1730 1734
    // `assert { expr }` block form or `assert <expr>`.
1731 1735
    let mut condition: *ast::Node = undefined;
1732 -
    if consume(p, scanner::TokenKind::LBrace) {
1736 +
    if try consume(p, scanner::TokenKind::LBrace) {
1733 1737
        set condition = try parseExpr(p);
1734 1738
        try expect(p, scanner::TokenKind::RBrace, "expected closing `}` after expression");
1735 1739
    } else {
1736 1740
        set condition = try parseExpr(p);
1737 1741
    }
1738 1742
    let mut message: ?*ast::Node = nil;
1739 -
    if consume(p, scanner::TokenKind::Comma) {
1743 +
    if try consume(p, scanner::TokenKind::Comma) {
1740 1744
        set message = try parseExpr(p);
1741 1745
    }
1742 -
    return node(p, ast::NodeValue::Assert { condition, message });
1746 +
    return try node(p, ast::NodeValue::Assert { condition, message });
1743 1747
}
1744 1748
1745 1749
/// Parse a `try` expression with optional `catch` clause(s).
1746 1750
fn parseTryExpr(p: &mut Parser) -> *ast::Node
1747 -
    throws (ParseError)
1751 +
    throws (ParseError, AllocError)
1748 1752
{
1749 1753
    try expect(p, scanner::TokenKind::Try, "expected `try`");
1750 1754
1751 -
    let shouldPanic = consume(p, scanner::TokenKind::Bang);
1752 -
    let returnsOptional = consume(p, scanner::TokenKind::Question);
1755 +
    let shouldPanic = try consume(p, scanner::TokenKind::Bang);
1756 +
    let returnsOptional = try consume(p, scanner::TokenKind::Question);
1753 1757
    let expr = try parseUnaryExpr(p);
1754 -
    let mut catches = ast::nodeSlice(&mut p.arena, 4);
1758 +
    let mut catches = try ast::nodeSlice(&mut p.arena, 4);
1755 1759
1756 -
    while consume(p, scanner::TokenKind::Catch) {
1760 +
    while try consume(p, scanner::TokenKind::Catch) {
1757 1761
        let mut binding: ?*ast::Node = nil;
1758 1762
        let mut typeNode: ?*ast::Node = nil;
1759 1763
1760 1764
        // Check for optional error binding: `catch ident { ... }` or
1761 1765
        // `catch ident as Type { ... }`.
1762 1766
        if check(p, scanner::TokenKind::Ident) {
1763 1767
            set binding = try parseIdent(p, "expected identifier after `catch`");
1764 -
            if consume(p, scanner::TokenKind::As) {
1768 +
            if try consume(p, scanner::TokenKind::As) {
1765 1769
                set typeNode = try parseType(p);
1766 1770
            }
1767 1771
        }
1768 1772
        if not check(p, scanner::TokenKind::LBrace) {
1769 1773
            throw failParsing(p, "expected `{` after `catch`");
1770 1774
        }
1771 1775
        let body = try parseBlock(p);
1772 -
        let clause = node(p, ast::NodeValue::CatchClause(
1776 +
        let clause = try node(p, ast::NodeValue::CatchClause(
1773 1777
            ast::CatchClause { binding, typeNode, body }
1774 1778
        ));
1775 -
        try! catches.append(clause, p.arena.heap);
1779 +
        try catches.append(clause, p.arena.heap);
1776 1780
    }
1777 -
    return node(p, ast::NodeValue::Try(
1781 +
    return try node(p, ast::NodeValue::Try(
1778 1782
        ast::Try { expr, catches, shouldPanic, returnsOptional }
1779 1783
    ));
1780 1784
}
1781 1785
1782 1786
/// Parse an `if` expression, with optional `else` or `else if` clauses.
1814 1818
///               d
1815 1819
///           }
1816 1820
///       }
1817 1821
///   }
1818 1822
///
1819 -
fn parseIf(p: &mut Parser) -> *ast::Node throws (ParseError) {
1823 +
fn parseIf(p: &mut Parser) -> *ast::Node throws (ParseError, AllocError) {
1820 1824
    try expect(p, scanner::TokenKind::If, "expected `if`");
1821 1825
1822 1826
    // Check for `if let` or `if let case` syntax.
1823 1827
    if check(p, scanner::TokenKind::Let) {
1824 1828
        return try parseIfLet(p);
1826 1830
    // Regular if statement.
1827 1831
    let cond = try parseCond(p);
1828 1832
    let thenBranch = try parseBlock(p);
1829 1833
    let mut elseBranch: ?*ast::Node = nil;
1830 1834
1831 -
    if consume(p, scanner::TokenKind::Else) {
1835 +
    if try consume(p, scanner::TokenKind::Else) {
1832 1836
        // Check for `else if` construct.
1833 1837
        if check(p, scanner::TokenKind::If) {
1834 1838
            // Set the else branch to a block containing the nested if.
1835 -
            set elseBranch = node(p, ast::NodeValue::Block(
1836 -
                mkBlockWith(p, try parseIf(p))
1839 +
            set elseBranch = try node(p, ast::NodeValue::Block(
1840 +
                try mkBlockWith(p, try parseIf(p))
1837 1841
            ));
1838 1842
        } else {
1839 1843
            // Regular else clause.
1840 1844
            set elseBranch = try parseBlock(p);
1841 1845
        }
1842 1846
    }
1843 -
    return node(p, ast::NodeValue::If(ast::If {
1847 +
    return try node(p, ast::NodeValue::If(ast::If {
1844 1848
        condition: cond, thenBranch, elseBranch
1845 1849
    }));
1846 1850
}
1847 1851
1848 1852
/// Parse a `match` statement.
1849 1853
fn parseMatch(p: &mut Parser) -> *ast::Node
1850 -
    throws (ParseError)
1854 +
    throws (ParseError, AllocError)
1851 1855
{
1852 1856
    try expect(p, scanner::TokenKind::Match, "expected `match`");
1853 1857
1854 1858
    let subject = try parseCond(p);
1855 1859
    try expect(p, scanner::TokenKind::LBrace, "expected `{` before match prongs");
1856 1860
1857 1861
    let outer = openList(p);
1858 -
    let mut prongs = ast::nodeSlice(&mut p.arena, INITIAL_PRONGS);
1862 +
    let mut prongs = try ast::nodeSlice(&mut p.arena, INITIAL_PRONGS);
1859 1863
    // TODO: We shouldn't have to manually check for EOF.
1860 1864
    while not check(p, scanner::TokenKind::RBrace)
1861 1865
        and not check(p, scanner::TokenKind::Eof)
1862 1866
    {
1863 -
        let leading = takePending(p, &prongs[..]);
1867 +
        let leading = try takePending(p, &prongs[..]);
1864 1868
        let prongNode = try parseMatchProng(p);
1865 -
        attachLeading(p, prongNode, leading);
1866 -
        try! prongs.append(prongNode, p.arena.heap);
1867 -
        consume(p, scanner::TokenKind::Comma);
1869 +
        try attachLeading(p, prongNode, leading);
1870 +
        try prongs.append(prongNode, p.arena.heap);
1871 +
        try consume(p, scanner::TokenKind::Comma);
1868 1872
    }
1869 -
    closeList(p, outer, &prongs[..]);
1873 +
    try closeList(p, outer, &prongs[..]);
1870 1874
    try expect(p, scanner::TokenKind::RBrace, "expected `}` after match prongs");
1871 -
    let matchNode: *ast::Node = node(p, ast::NodeValue::Match(
1875 +
    let matchNode: *ast::Node = try node(p, ast::NodeValue::Match(
1872 1876
        ast::Match { subject, prongs }
1873 1877
    ));
1874 -
    attachClosing(p, matchNode);
1878 +
    try attachClosing(p, matchNode);
1875 1879
1876 1880
    return matchNode;
1877 1881
}
1878 1882
1879 1883
/// Parse a single `match` prong.
1880 1884
fn parseMatchProng(p: &mut Parser) -> *ast::Node
1881 -
    throws (ParseError)
1885 +
    throws (ParseError, AllocError)
1882 1886
{
1883 1887
    let mut guard: ?*ast::Node = nil;
1884 1888
1885 1889
    // Case prong: `case <pattern>, ... if <guard> => <body>`.
1886 -
    if consume(p, scanner::TokenKind::Case) {
1887 -
        let mut patterns = ast::nodeSlice(&mut p.arena, INITIAL_PATTERNS);
1890 +
    if try consume(p, scanner::TokenKind::Case) {
1891 +
        let mut patterns = try ast::nodeSlice(&mut p.arena, INITIAL_PATTERNS);
1888 1892
        loop {
1889 1893
            let pattern = try parseMatchPattern(p);
1890 -
            try! patterns.append(pattern, p.arena.heap);
1894 +
            try patterns.append(pattern, p.arena.heap);
1891 1895
1892 -
            if not consume(p, scanner::TokenKind::Comma) {
1896 +
            if not try consume(p, scanner::TokenKind::Comma) {
1893 1897
                break;
1894 1898
            }
1895 1899
            // After a comma, check for tokens that start a new prong.
1896 1900
            // This catches mistakes like `case A, case B`.
1897 1901
            if check(p, scanner::TokenKind::Case) or check(p, scanner::TokenKind::Else) {
1898 1902
                throw failParsing(p, "unexpected keyword after `,` in case pattern list");
1899 1903
            }
1900 1904
        }
1901 -
        if consume(p, scanner::TokenKind::If) {
1905 +
        if try consume(p, scanner::TokenKind::If) {
1902 1906
            set guard = try parseCond(p);
1903 1907
        }
1904 1908
        try expect(p, scanner::TokenKind::FatArrow, "expected `=>` after case pattern");
1905 1909
        let broken = startsLine(p);
1906 1910
        let body = try parseStmt(p);
1907 -
        let prong: *ast::Node = node(p, ast::NodeValue::MatchProng(
1911 +
        let prong: *ast::Node = try node(p, ast::NodeValue::MatchProng(
1908 1912
            ast::MatchProng { arm: ast::ProngArm::Case(patterns), guard, body }
1909 1913
        ));
1910 -
        markBroken(p, prong, broken, ast::BrokenSite::Value);
1914 +
        try markBroken(p, prong, broken, ast::BrokenSite::Value);
1911 1915
1912 1916
        return prong;
1913 1917
    }
1914 1918
    // Else prong: `else if <guard> => <body>`.
1915 -
    if consume(p, scanner::TokenKind::Else) {
1916 -
        if consume(p, scanner::TokenKind::If) {
1919 +
    if try consume(p, scanner::TokenKind::Else) {
1920 +
        if try consume(p, scanner::TokenKind::If) {
1917 1921
            set guard = try parseCond(p);
1918 1922
        }
1919 1923
        try expect(p, scanner::TokenKind::FatArrow, "expected `=>` after else");
1920 1924
        let broken = startsLine(p);
1921 1925
        let body = try parseStmt(p);
1922 -
        let prong: *ast::Node = node(p, ast::NodeValue::MatchProng(
1926 +
        let prong: *ast::Node = try node(p, ast::NodeValue::MatchProng(
1923 1927
            ast::MatchProng { arm: ast::ProngArm::Else, guard, body }
1924 1928
        ));
1925 -
        markBroken(p, prong, broken, ast::BrokenSite::Value);
1929 +
        try markBroken(p, prong, broken, ast::BrokenSite::Value);
1926 1930
1927 1931
        return prong;
1928 1932
    }
1929 1933
    // Binding prong: `<ident> if <guard> => <body>` or `_ if <guard> => <body>`.
1930 1934
    let binding = try parseIdentOrPlaceholder(p, "expected `case`, `else`, or identifier");
1931 1935
1932 -
    if consume(p, scanner::TokenKind::If) {
1936 +
    if try consume(p, scanner::TokenKind::If) {
1933 1937
        set guard = try parseCond(p);
1934 1938
    }
1935 1939
    try expect(p, scanner::TokenKind::FatArrow, "expected `=>` after binding");
1936 1940
    let broken = startsLine(p);
1937 1941
    let body = try parseStmt(p);
1938 -
    let prong: *ast::Node = node(p, ast::NodeValue::MatchProng(
1942 +
    let prong: *ast::Node = try node(p, ast::NodeValue::MatchProng(
1939 1943
        ast::MatchProng { arm: ast::ProngArm::Binding(binding), guard, body }
1940 1944
    ));
1941 -
    markBroken(p, prong, broken, ast::BrokenSite::Value);
1945 +
    try markBroken(p, prong, broken, ast::BrokenSite::Value);
1942 1946
1943 1947
    return prong;
1944 1948
}
1945 1949
1946 1950
/// Parse a pattern expression used by `case` constructs.
1947 1951
/// Uses `Pattern` context to allow record literals but not conditional expressions.
1948 1952
fn parseMatchPattern(p: &mut Parser) -> *ast::Node
1949 -
    throws (ParseError)
1953 +
    throws (ParseError, AllocError)
1950 1954
{
1951 1955
    let saved = p.context;
1952 1956
    set p.context = Context::Pattern;
1953 1957
    let pattern = try parseExpr(p);
1954 1958
    set p.context = saved;
1956 1960
    return pattern;
1957 1961
}
1958 1962
1959 1963
/// Parse an identifier.
1960 1964
fn parseIdent(p: &mut Parser, err: *[u8]) -> *ast::Node
1961 -
    throws (ParseError)
1965 +
    throws (ParseError, AllocError)
1962 1966
{
1963 -
    if consume(p, scanner::TokenKind::Ident) {
1967 +
    if p.current.kind == scanner::TokenKind::Ident {
1968 +
        try advance(p);
1964 1969
        let source = p.previous.source;
1965 -
        return node(p, ast::NodeValue::Ident(source));
1970 +
        return try node(p, ast::NodeValue::Ident(source));
1966 1971
    }
1967 1972
    if scanner::isKeyword(p.current.kind) {
1968 1973
        throw failParsing(p, "reserved keyword cannot be used as an identifier");
1969 1974
    }
1970 1975
    throw failParsing(p, err);
1971 1976
}
1972 1977
1973 1978
/// Parse a list of region names, eg. `['r, 's]`, from the current `[`.
1974 -
fn parseRegions(p: &mut Parser) -> *[*ast::Node] throws (ParseError) {
1975 -
    advance(p);
1976 -
    let mut regions = ast::nodeSlice(&mut p.arena, 0);
1979 +
fn parseRegions(p: &mut Parser) -> *[*ast::Node] throws (ParseError, AllocError) {
1980 +
    try advance(p);
1981 +
    let mut regions: *mut [*ast::Node] = &mut [];
1977 1982
    while check(p, scanner::TokenKind::Region) {
1978 -
        try! regions.append(parseRegion(p), p.arena.heap);
1983 +
        try regions.append(try parseRegion(p), p.arena.heap);
1979 1984
1980 -
        if not consume(p, scanner::TokenKind::Comma) {
1985 +
        if not try consume(p, scanner::TokenKind::Comma) {
1981 1986
            break;
1982 1987
        }
1983 1988
    }
1984 1989
    if regions.len == 0 {
1985 1990
        throw failParsing(p, "expected region name");
1989 1994
    return regions;
1990 1995
}
1991 1996
1992 1997
/// Parse the current region token, eg. `'r`, into an identifier node
1993 1998
/// holding its name with the quote, which keeps it apart from value names.
1994 -
fn parseRegion(p: &mut Parser) -> *ast::Node {
1995 -
    advance(p);
1999 +
fn parseRegion(p: &mut Parser) -> *ast::Node throws (AllocError) {
2000 +
    try advance(p);
1996 2001
    let name = strings::intern(&mut p.pool, p.previous.source);
1997 -
    return node(p, ast::NodeValue::Ident(name));
2002 +
    return try node(p, ast::NodeValue::Ident(name));
1998 2003
}
1999 2004
2000 2005
/// Parse either an identifier or a placeholder (`_`).
2001 2006
fn parseIdentOrPlaceholder(p: &mut Parser, err: *[u8]) -> *ast::Node
2002 -
    throws (ParseError)
2007 +
    throws (ParseError, AllocError)
2003 2008
{
2004 -
    if consume(p, scanner::TokenKind::Underscore) {
2005 -
        return node(p, ast::NodeValue::Placeholder);
2009 +
    if p.current.kind == scanner::TokenKind::Underscore {
2010 +
        try advance(p);
2011 +
        return try node(p, ast::NodeValue::Placeholder);
2006 2012
    }
2007 2013
    return try parseIdent(p, err);
2008 2014
}
2009 2015
2010 2016
/// Parse an alignment specifier.
2011 2017
///
2012 2018
/// Syntax: `align(N)` where N is a power of 2.
2013 2019
fn parseAlign(p: &mut Parser) -> *ast::Node
2014 -
    throws (ParseError)
2020 +
    throws (ParseError, AllocError)
2015 2021
{
2016 2022
    try expect(p, scanner::TokenKind::Align, "expected `align`");
2017 2023
    let value = try parseParenthesized(p);
2018 -
    return node(p, ast::NodeValue::Align { value });
2024 +
    return try node(p, ast::NodeValue::Align { value });
2019 2025
}
2020 2026
2021 2027
/// Parse a comma-separated list of record fields.
2022 2028
/// The opening delimiter should already be consumed. The trivia before the
2023 2029
/// closing delimiter is left for the node that owns the fields.
2025 2031
/// For unlabeled fields: `(T, T, ...)`.
2026 2032
fn parseRecordFields(
2027 2033
    p: &mut Parser,
2028 2034
    mode: RecordFieldMode
2029 2035
) -> *mut [*ast::Node]
2030 -
    throws (ParseError)
2036 +
    throws (ParseError, AllocError)
2031 2037
{
2032 2038
    let terminator = scanner::TokenKind::RBrace
2033 2039
        if mode == RecordFieldMode::Labeled
2034 2040
        else scanner::TokenKind::RParen;
2035 2041
    let mut outer = openList(p);
2036 -
    let mut fields = ast::nodeSlice(&mut p.arena, MAX_RECORD_FIELDS);
2042 +
    let mut fields = try ast::nodeSlice(&mut p.arena, MAX_RECORD_FIELDS);
2037 2043
    while not check(p, terminator) {
2038 -
        let leading = takePending(p, &fields[..]);
2044 +
        let leading = try takePending(p, &fields[..]);
2039 2045
        noteItem(p, &mut outer);
2040 2046
        let mut recordField: ast::NodeValue = undefined;
2041 2047
        match mode {
2042 2048
            case RecordFieldMode::Labeled => {
2043 2049
                // Allow optional `let` keyword before field name.
2044 -
                consume(p, scanner::TokenKind::Let);
2050 +
                try consume(p, scanner::TokenKind::Let);
2045 2051
2046 2052
                let field = try parseNameTypeValue(p);
2047 2053
                let type = field.type else {
2048 2054
                    throw failParsing(p, "expected type annotation in record field");
2049 2055
                };
2062 2068
                set recordField = ast::NodeValue::RecordField {
2063 2069
                    field: nil, type, value: nil
2064 2070
                };
2065 2071
            }
2066 2072
        }
2067 -
        let fieldNode: *ast::Node = node(p, recordField);
2068 -
        attachLeading(p, fieldNode, leading);
2069 -
        try! fields.append(fieldNode, p.arena.heap);
2073 +
        let fieldNode: *ast::Node = try node(p, recordField);
2074 +
        try attachLeading(p, fieldNode, leading);
2075 +
        try fields.append(fieldNode, p.arena.heap);
2070 2076
2071 -
        if not consume(p, scanner::TokenKind::Comma) {
2077 +
        if not try consume(p, scanner::TokenKind::Comma) {
2072 2078
            break;
2073 2079
        }
2074 2080
    }
2075 -
    closeSoftList(p, outer, &fields[..]);
2081 +
    try closeSoftList(p, outer, &fields[..]);
2076 2082
    try expect(p, terminator, "expected closing delimiter after record fields");
2077 2083
2078 2084
    return fields;
2079 2085
}
2080 2086
2081 2087
/// Parse an optional derives list (`: Trait + Trait`).
2082 -
fn parseDerives(p: &mut Parser) -> *mut [*ast::Node] throws (ParseError) {
2083 -
    let mut derives = ast::nodeSlice(&mut p.arena, 4);
2088 +
fn parseDerives(p: &mut Parser) -> *mut [*ast::Node] throws (ParseError, AllocError) {
2089 +
    let mut derives = try ast::nodeSlice(&mut p.arena, 4);
2084 2090
2085 -
    if not consume(p, scanner::TokenKind::Colon) {
2091 +
    if not try consume(p, scanner::TokenKind::Colon) {
2086 2092
        return derives;
2087 2093
    }
2088 2094
    loop {
2089 2095
        let t = try parseIdent(p, "expected trait name in derive list");
2090 -
        try! derives.append(t, p.arena.heap);
2096 +
        try derives.append(t, p.arena.heap);
2091 2097
2092 -
        if not consume(p, scanner::TokenKind::Plus) {
2098 +
        if not try consume(p, scanner::TokenKind::Plus) {
2093 2099
            break;
2094 2100
        }
2095 2101
    }
2096 2102
    return derives;
2097 2103
}
2098 2104
2099 2105
/// Parse a single record literal field.
2100 2106
/// Can be either labeled, or shorthand.
2101 2107
fn parseRecordLitField(p: &mut Parser) -> *ast::Node
2102 -
    throws (ParseError)
2108 +
    throws (ParseError, AllocError)
2103 2109
{
2104 2110
    let name = try parseIdent(p, "expected field name");
2105 -
    if consume(p, scanner::TokenKind::Colon) {
2111 +
    if try consume(p, scanner::TokenKind::Colon) {
2106 2112
        // Labeled field: `name: value`.
2107 2113
        let value = try parseExpr(p);
2108 -
        return node(p, ast::NodeValue::RecordLitField(
2114 +
        return try node(p, ast::NodeValue::RecordLitField(
2109 2115
            ast::Arg { label: name, value }
2110 2116
        ));
2111 2117
    }
2112 2118
    // Shorthand syntax: `{ x }` is equivalent to `{ x: x }`.
2113 -
    return node(p, ast::NodeValue::RecordLitField(
2119 +
    return try node(p, ast::NodeValue::RecordLitField(
2114 2120
        ast::Arg { label: name, value: name }
2115 2121
    ));
2116 2122
}
2117 2123
2118 2124
/// Parse a record literal body.
2119 2125
/// Eg. `{ x: 1, y: 2 }`
2120 2126
/// Eg. `{ x: 1, .. }`
2121 2127
fn parseRecordLit(p: &mut Parser, typeName: ?*ast::Node) -> *ast::Node
2122 -
    throws (ParseError)
2128 +
    throws (ParseError, AllocError)
2123 2129
{
2124 -
    let mut fields = ast::nodeSlice(&mut p.arena, MAX_RECORD_FIELDS);
2130 +
    let mut fields = try ast::nodeSlice(&mut p.arena, MAX_RECORD_FIELDS);
2125 2131
    let mut ignoreRest = false;
2126 2132
    try expect(p, scanner::TokenKind::LBrace, "expected `{` to begin record literal");
2127 2133
    let mut outer = openList(p);
2128 2134
2129 2135
    while not check(p, scanner::TokenKind::RBrace) {
2130 2136
        // Check for `..` to ignore remaining fields.
2131 -
        if consume(p, scanner::TokenKind::DotDot) {
2137 +
        if try consume(p, scanner::TokenKind::DotDot) {
2132 2138
            set ignoreRest = true;
2133 2139
            break;
2134 2140
        }
2135 -
        let leading = takePending(p, &fields[..]);
2141 +
        let leading = try takePending(p, &fields[..]);
2136 2142
        noteItem(p, &mut outer);
2137 2143
        let field = try parseRecordLitField(p);
2138 -
        attachLeading(p, field, leading);
2139 -
        try! fields.append(field, p.arena.heap);
2144 +
        try attachLeading(p, field, leading);
2145 +
        try fields.append(field, p.arena.heap);
2140 2146
2141 -
        if not consume(p, scanner::TokenKind::Comma) {
2147 +
        if not try consume(p, scanner::TokenKind::Comma) {
2142 2148
            break;
2143 2149
        }
2144 2150
    }
2145 -
    closeSoftList(p, outer, &fields[..]);
2151 +
    try closeSoftList(p, outer, &fields[..]);
2146 2152
    try expect(p, scanner::TokenKind::RBrace, "expected `}` to end record literal");
2147 -
    let lit: *ast::Node = node(p, ast::NodeValue::RecordLit(
2153 +
    let lit: *ast::Node = try node(p, ast::NodeValue::RecordLit(
2148 2154
        ast::RecordLit { typeName, fields, ignoreRest }
2149 2155
    ));
2150 -
    attachClosing(p, lit);
2156 +
    try attachClosing(p, lit);
2151 2157
2152 2158
    return lit;
2153 2159
}
2154 2160
2155 2161
/// Parse a named record declaration.
2157 2163
/// Derives follow the positional fields: `record ScopeId(u32): Copy;`.
2158 2164
/// Labeled records put derives before the body: `record Point: Eq { x: i32 }`.
2159 2165
/// An `opaque` prefix, written after `export`, keeps the representation private
2160 2166
/// to the defining module: `export opaque record Handle(u32): Copy;`.
2161 2167
fn parseRecordDecl(p: &mut Parser, attrs: ?ast::Attributes) -> *ast::Node
2162 -
    throws (ParseError)
2168 +
    throws (ParseError, AllocError)
2163 2169
{
2164 2170
    let mut recordAttrs = attrs;
2165 -
    if consume(p, scanner::TokenKind::Opaque) {
2166 -
        let mut list = ast::nodeSlice(&mut p.arena, 4);
2171 +
    if try consume(p, scanner::TokenKind::Opaque) {
2172 +
        let mut list = try ast::nodeSlice(&mut p.arena, 4);
2167 2173
        if let a = attrs {
2168 2174
            for attr in a.list {
2169 -
                try! list.append(attr, p.arena.heap);
2175 +
                try list.append(attr, p.arena.heap);
2170 2176
            }
2171 2177
        }
2172 -
        try! list.append(nodeAttribute(p, ast::Attribute::Opaque), p.arena.heap);
2178 +
        try list.append(try nodeAttribute(p, ast::Attribute::Opaque), p.arena.heap);
2173 2179
        set recordAttrs = ast::Attributes { list };
2174 2180
    }
2175 2181
    try expect(p, scanner::TokenKind::Record, "expected `record`");
2176 2182
2177 2183
    let name = try parseIdent(p, "expected record name");
2178 2184
    let mut regions: *[*ast::Node] = &[];
2179 2185
    if check(p, scanner::TokenKind::LBracket) {
2180 2186
        set regions = try parseRegions(p);
2181 2187
    }
2182 -
    if consume(p, scanner::TokenKind::LParen) {
2188 +
    if try consume(p, scanner::TokenKind::LParen) {
2183 2189
        let fields = try parseRecordFields(p, RecordFieldMode::Unlabeled);
2184 2190
        let derives = try parseDerives(p);
2185 2191
        try expect(p, scanner::TokenKind::Semicolon, "expected `;` after record");
2186 -
        let decl: *ast::Node = node(p, ast::NodeValue::RecordDecl(
2192 +
        let decl: *ast::Node = try node(p, ast::NodeValue::RecordDecl(
2187 2193
            ast::RecordDecl { name, regions, fields, attrs: recordAttrs, derives, labeled: false }
2188 2194
        ));
2189 -
        attachClosing(p, decl);
2195 +
        try attachClosing(p, decl);
2190 2196
2191 2197
        return decl;
2192 2198
    }
2193 2199
    let derives = try parseDerives(p);
2194 2200
    try expect(p, scanner::TokenKind::LBrace, "expected `{` before record body");
2195 2201
    let fields = try parseRecordFields(p, RecordFieldMode::Labeled);
2196 -
    let decl: *ast::Node = node(p, ast::NodeValue::RecordDecl(
2202 +
    let decl: *ast::Node = try node(p, ast::NodeValue::RecordDecl(
2197 2203
        ast::RecordDecl { name, regions, fields, attrs: recordAttrs, derives, labeled: true }
2198 2204
    ));
2199 -
    attachClosing(p, decl);
2205 +
    try attachClosing(p, decl);
2200 2206
2201 2207
    return decl;
2202 2208
}
2203 2209
2204 2210
/// Parse a union declaration.
2205 2211
/// Example: `union Color { Red, Green, Blue = 5 }`
2206 2212
fn parseUnionDecl(p: &mut Parser, attrs: ?ast::Attributes) -> *ast::Node
2207 -
    throws (ParseError)
2213 +
    throws (ParseError, AllocError)
2208 2214
{
2209 2215
    try expect(p, scanner::TokenKind::Union, "expected `union`");
2210 2216
2211 2217
    let name = try parseIdent(p, "expected union name");
2212 2218
    let mut regions: *[*ast::Node] = &[];
2216 2222
    let derives = try parseDerives(p);
2217 2223
2218 2224
    try expect(p, scanner::TokenKind::LBrace, "expected `{` before union body");
2219 2225
    let outer = openList(p);
2220 2226
2221 -
    let mut variants = ast::nodeSlice(&mut p.arena, INITIAL_VARIANTS);
2227 +
    let mut variants = try ast::nodeSlice(&mut p.arena, INITIAL_VARIANTS);
2222 2228
    while not check(p, scanner::TokenKind::RBrace) {
2223 -
        let leading = takePending(p, &variants[..]);
2229 +
        let leading = try takePending(p, &variants[..]);
2224 2230
        let joined = variants.len > 0 and sharesLine(p);
2225 2231
2226 2232
        // Allow optional `case` keyword before variant name.
2227 -
        consume(p, scanner::TokenKind::Case);
2233 +
        try consume(p, scanner::TokenKind::Case);
2228 2234
2229 2235
        let variantName = try parseIdent(p, "expected variant name");
2230 2236
        let mut payloadType: ?*ast::Node = nil;
2231 2237
        let mut explicitValue: ?*ast::Node = nil;
2232 2238
2233 -
        if consume(p, scanner::TokenKind::LParen) {
2239 +
        if try consume(p, scanner::TokenKind::LParen) {
2234 2240
            // `Variant(T, U)`.
2235 2241
            let fields = try parseRecordFields(p, RecordFieldMode::Unlabeled);
2236 -
            let payload: *ast::Node = node(p, ast::NodeValue::TypeSig(
2242 +
            let payload: *ast::Node = try node(p, ast::NodeValue::TypeSig(
2237 2243
                ast::TypeSig::Record { fields, labeled: false }
2238 2244
            ));
2239 -
            attachClosing(p, payload);
2245 +
            try attachClosing(p, payload);
2240 2246
            set payloadType = payload;
2241 -
        } else if consume(p, scanner::TokenKind::LBrace) {
2247 +
        } else if try consume(p, scanner::TokenKind::LBrace) {
2242 2248
            // `Variant { x: T, y: T }`.
2243 2249
            let fields = try parseRecordFields(p, RecordFieldMode::Labeled);
2244 -
            let payload: *ast::Node = node(p, ast::NodeValue::TypeSig(
2250 +
            let payload: *ast::Node = try node(p, ast::NodeValue::TypeSig(
2245 2251
                ast::TypeSig::Record { fields, labeled: true }
2246 2252
            ));
2247 -
            attachClosing(p, payload);
2253 +
            try attachClosing(p, payload);
2248 2254
            set payloadType = payload;
2249 -
        } else if consume(p, scanner::TokenKind::Equal) {
2255 +
        } else if try consume(p, scanner::TokenKind::Equal) {
2250 2256
            // TODO: Support constant expressions.
2251 2257
            try expect(p, scanner::TokenKind::Number, "expected integer literal after `=`");
2252 2258
            let source = p.previous.source;
2253 2259
            let literal = try parseIntLiteral(p, source);
2254 -
            set explicitValue = nodeNumber(p, literal);
2255 -
        }
2256 -
        let variant: *ast::Node = node(p, ast::NodeValue::UnionDeclVariant(ast::UnionDeclVariant {
2257 -
            name: variantName, index: variants.len as u32, value: explicitValue, type: payloadType
2258 -
        }));
2259 -
        attachLeading(p, variant, leading);
2260 -
        markBroken(p, variant, joined, ast::BrokenSite::Joined);
2261 -
        try! variants.append(variant, p.arena.heap);
2260 +
            set explicitValue = try nodeNumber(p, literal);
2261 +
        }
2262 +
        let variant: *ast::Node = try node(p, ast::NodeValue::UnionDeclVariant(
2263 +
            ast::UnionDeclVariant {
2264 +
                name: variantName,
2265 +
                index: variants.len as u32,
2266 +
                value: explicitValue,
2267 +
                type: payloadType,
2268 +
            }
2269 +
        ));
2270 +
        try attachLeading(p, variant, leading);
2271 +
        try markBroken(p, variant, joined, ast::BrokenSite::Joined);
2272 +
        try variants.append(variant, p.arena.heap);
2262 2273
2263 -
        if not consume(p, scanner::TokenKind::Comma) {
2274 +
        if not try consume(p, scanner::TokenKind::Comma) {
2264 2275
            break;
2265 2276
        }
2266 2277
    }
2267 -
    closeList(p, outer, &variants[..]);
2278 +
    try closeList(p, outer, &variants[..]);
2268 2279
    try expect(p, scanner::TokenKind::RBrace, "expected `}`");
2269 -
    let decl: *ast::Node = node(p, ast::NodeValue::UnionDecl(
2280 +
    let decl: *ast::Node = try node(p, ast::NodeValue::UnionDecl(
2270 2281
        ast::UnionDecl { name, regions, variants, attrs, derives }
2271 2282
    ));
2272 -
    attachClosing(p, decl);
2283 +
    try attachClosing(p, decl);
2273 2284
2274 2285
    return decl;
2275 2286
}
2276 2287
2277 2288
/// Parse a function parameter.
2278 2289
fn parseFnParam(p: &mut Parser) -> *ast::Node
2279 -
    throws (ParseError)
2290 +
    throws (ParseError, AllocError)
2280 2291
{
2281 2292
    let ntv = try parseNameTypeValue(p);
2282 2293
    let type = ntv.type else throw failParsing(p, "missing type in function parameter");
2283 2294
2284 -
    return node(p, ast::NodeValue::FnParam(
2295 +
    return try node(p, ast::NodeValue::FnParam(
2285 2296
        ast::FnParam { name: ntv.name, type }
2286 2297
    ));
2287 2298
}
2288 2299
2289 2300
/// Parse an optional `throws` clause and return the collected type list.
2290 2301
///
2291 2302
/// Sets `broken` to whether the closing parenthesis of the list is on a later
2292 2303
/// line than the opening one. It stays false when trivia is discarded.
2293 2304
fn parseThrowList(p: &mut Parser, broken: &mut bool) -> *mut [*ast::Node]
2294 -
    throws (ParseError)
2305 +
    throws (ParseError, AllocError)
2295 2306
{
2296 -
    if not consume(p, scanner::TokenKind::Throws) {
2297 -
        return ast::nodeSlice(&mut p.arena, 0);
2307 +
    if not try consume(p, scanner::TokenKind::Throws) {
2308 +
        return &mut [];
2298 2309
    }
2299 2310
    try expect(p, scanner::TokenKind::LParen, "expected `(`");
2300 2311
    let mut outer = openList(p);
2301 2312
    let list = try parseItems(
2302 2313
        p, scanner::TokenKind::RParen, parseType, &mut outer
2303 2314
    );
2304 -
    endList(p, outer, &list[..]);
2315 +
    try endList(p, outer, &list[..]);
2305 2316
    set *broken = spansLines(p, outer);
2306 2317
    try expect(p, scanner::TokenKind::RParen, "expected `)`");
2307 2318
2308 2319
    return list;
2309 2320
}
2310 2321
2311 2322
/// Parse a function type signature.
2312 2323
fn parseFnType(p: &mut Parser) -> *ast::Node
2313 -
    throws (ParseError)
2324 +
    throws (ParseError, AllocError)
2314 2325
{
2315 -
    let isUnsafe = consume(p, scanner::TokenKind::Unsafe);
2326 +
    let isUnsafe = try consume(p, scanner::TokenKind::Unsafe);
2316 2327
    try expect(p, scanner::TokenKind::Fn, "expected `fn`");
2317 2328
    try expect(p, scanner::TokenKind::LParen, "expected `(`");
2318 2329
    let mut outer = openList(p);
2319 2330
    let params = try parseItems(
2320 2331
        p, scanner::TokenKind::RParen, parseType, &mut outer
2321 2332
    );
2322 -
    closeSoftList(p, outer, &params[..]);
2333 +
    try closeSoftList(p, outer, &params[..]);
2323 2334
    let closing = p.closing.take();
2324 2335
    try expect(p, scanner::TokenKind::RParen, "expected `)`");
2325 2336
2326 2337
    let mut returnType: ?*ast::Node = nil;
2327 -
    if consume(p, scanner::TokenKind::Arrow) {
2338 +
    if try consume(p, scanner::TokenKind::Arrow) {
2328 2339
        set returnType = try parseReturnType(p);
2329 2340
    }
2330 2341
    let mut brokenThrows = false;
2331 2342
    let throwList = try parseThrowList(p, &mut brokenThrows);
2332 2343
    let sig = ast::FnSig { params, returnType, throwList };
2333 -
    let type: *ast::Node = node(p, ast::NodeValue::TypeSig(
2344 +
    let type: *ast::Node = try node(p, ast::NodeValue::TypeSig(
2334 2345
        ast::TypeSig::Fn { sig, isUnsafe }
2335 2346
    ));
2336 -
    attachTrivia(p, type, ast::TriviaPlacement::Closing, closing);
2337 -
    markBroken(p, type, brokenThrows, ast::BrokenSite::Throws);
2347 +
    try attachTrivia(p, type, ast::TriviaPlacement::Closing, closing);
2348 +
    try markBroken(p, type, brokenThrows, ast::BrokenSite::Throws);
2338 2349
2339 2350
    return type;
2340 2351
}
2341 2352
2342 2353
/// Parse a function signature following the function name.
2343 2354
fn parseFnTypeSig(p: &mut Parser) -> ParsedSig
2344 -
    throws (ParseError)
2355 +
    throws (ParseError, AllocError)
2345 2356
{
2346 2357
    try expect(p, scanner::TokenKind::LParen, "expected `(` after function name");
2347 2358
    let mut outer = openList(p);
2348 -
    let mut params = ast::nodeSlice(&mut p.arena, 8);
2359 +
    let mut params = try ast::nodeSlice(&mut p.arena, 8);
2349 2360
2350 2361
    while not check(p, scanner::TokenKind::RParen) {
2351 -
        let leading = takePending(p, &params[..]);
2362 +
        let leading = try takePending(p, &params[..]);
2352 2363
        noteItem(p, &mut outer);
2353 2364
        let param = try parseFnParam(p);
2354 -
        attachLeading(p, param, leading);
2355 -
        try! params.append(param, p.arena.heap);
2365 +
        try attachLeading(p, param, leading);
2366 +
        try params.append(param, p.arena.heap);
2356 2367
2357 -
        if not consume(p, scanner::TokenKind::Comma) {
2368 +
        if not try consume(p, scanner::TokenKind::Comma) {
2358 2369
            break;
2359 2370
        }
2360 2371
    }
2361 -
    closeSoftList(p, outer, &params[..]);
2372 +
    try closeSoftList(p, outer, &params[..]);
2362 2373
    let closing: *[Pending] = p.closing.take();
2363 2374
    try expect(p, scanner::TokenKind::RParen, "expected `)` after function parameters");
2364 2375
2365 2376
    let mut returnType: ?*ast::Node = nil;
2366 -
    if consume(p, scanner::TokenKind::Arrow) {
2377 +
    if try consume(p, scanner::TokenKind::Arrow) {
2367 2378
        set returnType = try parseReturnType(p);
2368 2379
    }
2369 2380
    let stacked = check(p, scanner::TokenKind::Throws) and startsLine(p);
2370 2381
    let mut brokenThrows = false;
2371 2382
    let throwList = try parseThrowList(p, &mut brokenThrows);
2401 2412
2402 2413
/// Attach the trivia of a parsed signature to the node that owns it: the
2403 2414
/// comments before the `)` of the parameters and the mark of broken
2404 2415
/// parameters, then the stacked `throws` mark and the mark of a broken
2405 2416
/// `throws` list.
2406 -
fn attachSig(p: &mut Parser, owner: *ast::Node, parsed: ParsedSig) {
2407 -
    attachTrivia(p, owner, ast::TriviaPlacement::Closing, parsed.closing);
2417 +
fn attachSig(p: &mut Parser, owner: *ast::Node, parsed: ParsedSig) throws (AllocError) {
2418 +
    try attachTrivia(p, owner, ast::TriviaPlacement::Closing, parsed.closing);
2408 2419
    if parsed.stacked {
2409 2420
        let mark = ast::TriviaKind::StackedThrows;
2410 -
        attachOne(p, owner, ast::TriviaPlacement::Closing, mark);
2421 +
        try attachOne(p, owner, ast::TriviaPlacement::Closing, mark);
2411 2422
    }
2412 -
    markBroken(p, owner, parsed.brokenThrows, ast::BrokenSite::Throws);
2423 +
    try markBroken(p, owner, parsed.brokenThrows, ast::BrokenSite::Throws);
2413 2424
}
2414 2425
2415 2426
/// Attach to `owner` the mark that the source breaks a construct of it across
2416 2427
/// lines at `site`, if `broken`.
2417 2428
fn markBroken(
2418 2429
    p: &mut Parser, owner: *ast::Node, broken: bool, site: ast::BrokenSite
2419 -
) {
2430 +
) throws (AllocError) {
2420 2431
    if broken {
2421 2432
        let mark = ast::TriviaKind::Broken(site);
2422 -
        attachOne(p, owner, ast::TriviaPlacement::Closing, mark);
2433 +
        try attachOne(p, owner, ast::TriviaPlacement::Closing, mark);
2423 2434
    }
2424 2435
}
2425 2436
2426 2437
/// Parse a function return type, including the uninhabited type.
2427 -
fn parseReturnType(p: &mut Parser) -> *ast::Node throws (ParseError) {
2428 -
    if consume(p, scanner::TokenKind::Bang) {
2429 -
        return node(p, ast::NodeValue::TypeSig(ast::TypeSig::Never));
2438 +
fn parseReturnType(p: &mut Parser) -> *ast::Node throws (ParseError, AllocError) {
2439 +
    if try consume(p, scanner::TokenKind::Bang) {
2440 +
        return try node(p, ast::NodeValue::TypeSig(ast::TypeSig::Never));
2430 2441
    }
2431 2442
    return try parseType(p);
2432 2443
}
2433 2444
2434 2445
/// Parse a function declaration.
2435 2446
fn parseFnDecl(p: &mut Parser, attrs: ?ast::Attributes) -> *ast::Node
2436 -
    throws (ParseError)
2447 +
    throws (ParseError, AllocError)
2437 2448
{
2438 2449
    try expect(p, scanner::TokenKind::Fn, "expected `fn`");
2439 2450
2440 2451
    // Method syntax: `fn (recv: *Type) name(params) { body }`.
2441 2452
    if check(p, scanner::TokenKind::LParen) {
2447 2458
    let name = try parseIdent(p, "expected function name");
2448 2459
    let parsed = try parseFnTypeSig(p);
2449 2460
    let mut body: ?*ast::Node = nil;
2450 2461
    let mut fnAttrs = attrs;
2451 2462
2452 -
    if consume(p, scanner::TokenKind::Semicolon) {
2463 +
    if try consume(p, scanner::TokenKind::Semicolon) {
2453 2464
        if let a = attrs; ast::attributesContains(&a, ast::Attribute::Extern) {
2454 2465
            // Keep existing attributes unchanged.
2455 2466
        } else {
2456 -
            let mut list = ast::nodeSlice(&mut p.arena, 4);
2467 +
            let mut list = try ast::nodeSlice(&mut p.arena, 4);
2457 2468
            if let a = attrs {
2458 2469
                for i in 0 .. a.list.len {
2459 -
                    try! list.append(a.list[i], p.arena.heap);
2470 +
                    try list.append(a.list[i], p.arena.heap);
2460 2471
                }
2461 2472
            }
2462 -
            let attrNode = nodeAttribute(p, ast::Attribute::Extern);
2463 -
            try! list.append(attrNode, p.arena.heap);
2473 +
            let attrNode = try nodeAttribute(p, ast::Attribute::Extern);
2474 +
            try list.append(attrNode, p.arena.heap);
2464 2475
            set fnAttrs = ast::Attributes { list };
2465 2476
        }
2466 2477
    } else {
2467 2478
        set body = try parseBlock(p);
2468 2479
    }
2469 -
    let decl: *ast::Node = node(p, ast::NodeValue::FnDecl(
2480 +
    let decl: *ast::Node = try node(p, ast::NodeValue::FnDecl(
2470 2481
        ast::FnDecl { name, sig: parsed.sig, body, attrs: fnAttrs }
2471 2482
    ));
2472 -
    attachSig(p, decl, parsed);
2483 +
    try attachSig(p, decl, parsed);
2473 2484
2474 2485
    return decl;
2475 2486
}
2476 2487
2477 2488
/// Parse a pointer-like type after its ownership prefix: a pointer, slice,
2478 2489
/// pointer to an array, or trait object.
2479 2490
fn parsePointerLikeType(
2480 2491
    p: &mut Parser,
2481 2492
    class: types::PointerClass
2482 -
) -> *ast::Node throws (ParseError) {
2493 +
) -> *ast::Node throws (ParseError, AllocError) {
2483 2494
    let mut region: ?*ast::Node = nil;
2484 2495
    if class == types::PointerClass::Ref and p.current.kind == scanner::TokenKind::Region {
2485 -
        set region = parseRegion(p);
2496 +
        set region = try parseRegion(p);
2486 2497
    }
2487 -
    let mutable = consume(p, scanner::TokenKind::Mut);
2498 +
    let mutable = try consume(p, scanner::TokenKind::Mut);
2488 2499
2489 -
    if consume(p, scanner::TokenKind::LBracket) {
2500 +
    if try consume(p, scanner::TokenKind::LBracket) {
2490 2501
        let itemType = try parseType(p);
2491 2502
2492 2503
        // `[T; N]` after a prefix is a pointer to an array, `[T]` a slice.
2493 -
        if consume(p, scanner::TokenKind::Semicolon) {
2504 +
        if try consume(p, scanner::TokenKind::Semicolon) {
2494 2505
            let length = try parseExpr(p);
2495 2506
            try expect(p, scanner::TokenKind::RBracket, "expected `]` after array length");
2496 2507
2497 -
            let valueType = node(p, ast::NodeValue::TypeSig(
2508 +
            let valueType = try node(p, ast::NodeValue::TypeSig(
2498 2509
                ast::TypeSig::Array { itemType, length }
2499 2510
            ));
2500 -
            return node(p, ast::NodeValue::TypeSig(
2511 +
            return try node(p, ast::NodeValue::TypeSig(
2501 2512
                ast::TypeSig::Pointer { class, valueType, mutable, region }
2502 2513
            ));
2503 2514
        }
2504 2515
        try expect(p, scanner::TokenKind::RBracket, "expected `]` after slice element type");
2505 2516
2506 -
        return node(p, ast::NodeValue::TypeSig(
2517 +
        return try node(p, ast::NodeValue::TypeSig(
2507 2518
            ast::TypeSig::Slice { class, itemType, mutable, region }
2508 2519
        ));
2509 2520
    }
2510 2521
    // Check for an opaque trait object.
2511 -
    if consume(p, scanner::TokenKind::Opaque) {
2522 +
    if try consume(p, scanner::TokenKind::Opaque) {
2512 2523
        if check(p, scanner::TokenKind::Ident) or check(p, scanner::TokenKind::Super) {
2513 2524
            if region <> nil {
2514 2525
                throw failParsing(p, "trait object references cannot name a region");
2515 2526
            }
2516 2527
            let traitName = try parseTypePath(p);
2517 -
            return node(p, ast::NodeValue::TypeSig(
2528 +
            return try node(p, ast::NodeValue::TypeSig(
2518 2529
                ast::TypeSig::TraitObject { class, traitName, mutable }
2519 2530
            ));
2520 2531
        }
2521 2532
        // Plain opaque target.
2522 -
        let valueType = node(p, ast::NodeValue::TypeSig(ast::TypeSig::Opaque));
2523 -
        return node(p, ast::NodeValue::TypeSig(
2533 +
        let valueType = try node(p, ast::NodeValue::TypeSig(ast::TypeSig::Opaque));
2534 +
        return try node(p, ast::NodeValue::TypeSig(
2524 2535
            ast::TypeSig::Pointer { class, valueType, mutable, region }
2525 2536
        ));
2526 2537
    }
2527 2538
    let valueType = try parseType(p);
2528 2539
2529 -
    return node(p, ast::NodeValue::TypeSig(
2540 +
    return try node(p, ast::NodeValue::TypeSig(
2530 2541
        ast::TypeSig::Pointer { class, valueType, mutable, region }
2531 2542
    ));
2532 2543
}
2533 2544
2534 2545
/// Parse an array type.
2535 2546
fn parseArrayType(p: &mut Parser) -> *ast::Node
2536 -
    throws (ParseError)
2547 +
    throws (ParseError, AllocError)
2537 2548
{
2538 2549
    try expect(p, scanner::TokenKind::LBracket, "expected `[`");
2539 2550
    let itemType = try parseType(p);
2540 2551
2541 2552
    try expect(p, scanner::TokenKind::Semicolon, "expected `;` in array type");
2542 2553
    let length = try parseExpr(p);
2543 2554
2544 2555
    try expect(p, scanner::TokenKind::RBracket, "expected `]` after array length");
2545 -
    return node(p, ast::NodeValue::TypeSig(
2556 +
    return try node(p, ast::NodeValue::TypeSig(
2546 2557
        ast::TypeSig::Array { itemType, length }
2547 2558
    ));
2548 2559
}
2549 2560
2550 2561
/// Parse a type path: an identifier optionally followed by `::` scope access.
2551 2562
/// Returns an identifier node or a scope access chain.
2552 2563
fn parseTypePath(p: &mut Parser) -> *ast::Node
2553 -
    throws (ParseError)
2564 +
    throws (ParseError, AllocError)
2554 2565
{
2555 2566
    let mut path: *ast::Node = undefined;
2556 2567
    if p.current.kind == scanner::TokenKind::Super {
2557 -
        advance(p);
2558 -
        set path = nodeSuper(p);
2568 +
        try advance(p);
2569 +
        set path = try nodeSuper(p);
2559 2570
    } else {
2560 2571
        set path = try parseIdent(p, "expected type identifier");
2561 2572
    }
2562 -
    while consume(p, scanner::TokenKind::ColonColon) {
2573 +
    while try consume(p, scanner::TokenKind::ColonColon) {
2563 2574
        let part = try parseIdent(p, "expected identifier after `::`");
2564 -
        set path = node(p, ast::NodeValue::ScopeAccess(
2575 +
        set path = try node(p, ast::NodeValue::ScopeAccess(
2565 2576
            ast::Access { parent: path, child: part }
2566 2577
        ));
2567 2578
    }
2568 2579
    return path;
2569 2580
}
2570 2581
2571 2582
/// Parse a type annotation.
2572 2583
export fn parseType(p: &mut Parser) -> *ast::Node
2573 -
    throws (ParseError)
2584 +
    throws (ParseError, AllocError)
2574 2585
{
2575 2586
    match p.current.kind {
2576 2587
        case scanner::TokenKind::Question => {
2577 -
            advance(p);
2588 +
            try advance(p);
2578 2589
            let valueType = try parseType(p);
2579 2590
2580 -
            return node(p, ast::NodeValue::TypeSig(
2591 +
            return try node(p, ast::NodeValue::TypeSig(
2581 2592
                ast::TypeSig::Optional { valueType }
2582 2593
            ));
2583 2594
        }
2584 2595
        case scanner::TokenKind::Star => {
2585 -
            advance(p);
2596 +
            try advance(p);
2586 2597
            let class = types::PointerClass::Unsafe
2587 -
                if consume(p, scanner::TokenKind::Unsafe)
2598 +
                if try consume(p, scanner::TokenKind::Unsafe)
2588 2599
                else types::PointerClass::Owned;
2589 2600
            return try parsePointerLikeType(p, class);
2590 2601
        }
2591 2602
        case scanner::TokenKind::Amp => {
2592 -
            advance(p);
2603 +
            try advance(p);
2593 2604
            return try parsePointerLikeType(p, types::PointerClass::Ref);
2594 2605
        }
2595 2606
        case scanner::TokenKind::LBracket => {
2596 2607
            return try parseArrayType(p);
2597 2608
        }
2599 2610
            let path = try parseTypePath(p);
2600 2611
            let mut regions: *[*ast::Node] = &[];
2601 2612
            if check(p, scanner::TokenKind::LBracket) {
2602 2613
                set regions = try parseRegions(p);
2603 2614
            }
2604 -
            return node(p, ast::NodeValue::TypeSig(
2615 +
            return try node(p, ast::NodeValue::TypeSig(
2605 2616
                ast::TypeSig::Nominal { path, regions }
2606 2617
            ));
2607 2618
        }
2608 2619
        case scanner::TokenKind::U8 => {
2609 -
            advance(p);
2610 -
            return nodeTypeInt(p, 1, ast::Signedness::Unsigned);
2620 +
            try advance(p);
2621 +
            return try nodeTypeInt(p, 1, ast::Signedness::Unsigned);
2611 2622
        }
2612 2623
        case scanner::TokenKind::U16 => {
2613 -
            advance(p);
2614 -
            return nodeTypeInt(p, 2, ast::Signedness::Unsigned);
2624 +
            try advance(p);
2625 +
            return try nodeTypeInt(p, 2, ast::Signedness::Unsigned);
2615 2626
        }
2616 2627
        case scanner::TokenKind::U32 => {
2617 -
            advance(p);
2618 -
            return nodeTypeInt(p, 4, ast::Signedness::Unsigned);
2628 +
            try advance(p);
2629 +
            return try nodeTypeInt(p, 4, ast::Signedness::Unsigned);
2619 2630
        }
2620 2631
        case scanner::TokenKind::U64 => {
2621 -
            advance(p);
2622 -
            return nodeTypeInt(p, 8, ast::Signedness::Unsigned);
2632 +
            try advance(p);
2633 +
            return try nodeTypeInt(p, 8, ast::Signedness::Unsigned);
2623 2634
        }
2624 2635
        case scanner::TokenKind::I8 => {
2625 -
            advance(p);
2626 -
            return nodeTypeInt(p, 1, ast::Signedness::Signed);
2636 +
            try advance(p);
2637 +
            return try nodeTypeInt(p, 1, ast::Signedness::Signed);
2627 2638
        }
2628 2639
        case scanner::TokenKind::I16 => {
2629 -
            advance(p);
2630 -
            return nodeTypeInt(p, 2, ast::Signedness::Signed);
2640 +
            try advance(p);
2641 +
            return try nodeTypeInt(p, 2, ast::Signedness::Signed);
2631 2642
        }
2632 2643
        case scanner::TokenKind::I32 => {
2633 -
            advance(p);
2634 -
            return nodeTypeInt(p, 4, ast::Signedness::Signed);
2644 +
            try advance(p);
2645 +
            return try nodeTypeInt(p, 4, ast::Signedness::Signed);
2635 2646
        }
2636 2647
        case scanner::TokenKind::I64 => {
2637 -
            advance(p);
2638 -
            return nodeTypeInt(p, 8, ast::Signedness::Signed);
2648 +
            try advance(p);
2649 +
            return try nodeTypeInt(p, 8, ast::Signedness::Signed);
2639 2650
        }
2640 2651
        case scanner::TokenKind::Bool => {
2641 -
            advance(p);
2642 -
            return node(p, ast::NodeValue::TypeSig(ast::TypeSig::Bool));
2652 +
            try advance(p);
2653 +
            return try node(p, ast::NodeValue::TypeSig(ast::TypeSig::Bool));
2643 2654
        }
2644 2655
        case scanner::TokenKind::Opaque => {
2645 -
            advance(p);
2646 -
            return node(p, ast::NodeValue::TypeSig(ast::TypeSig::Opaque));
2656 +
            try advance(p);
2657 +
            return try node(p, ast::NodeValue::TypeSig(ast::TypeSig::Opaque));
2647 2658
        }
2648 2659
        case scanner::TokenKind::Fn, scanner::TokenKind::Unsafe => {
2649 2660
            return try parseFnType(p);
2650 2661
        }
2651 2662
        else => {
2657 2668
/// Parse a name, optional type, and optional value.
2658 2669
///
2659 2670
/// Used for record field declarations, variable declarations,
2660 2671
/// and record field initializations.
2661 2672
fn parseNameTypeValue(p: &mut Parser) -> NameTypeValue
2662 -
    throws (ParseError)
2673 +
    throws (ParseError, AllocError)
2663 2674
{
2664 2675
    let name = try parseIdentOrPlaceholder(p, "expected identifier or `_`");
2665 2676
    let mut type: ?*ast::Node = nil;
2666 2677
    let mut alignment: ?*ast::Node = nil;
2667 2678
    let mut value: ?*ast::Node = nil;
2668 2679
    // Only a reference type can name a region.
2669 2680
    let mut reference = false;
2670 2681
2671 -
    if consume(p, scanner::TokenKind::Colon) {
2682 +
    if try consume(p, scanner::TokenKind::Colon) {
2672 2683
        set reference = p.current.kind == scanner::TokenKind::Amp;
2673 2684
        set type = try parseType(p);
2674 2685
2675 2686
        if check(p, scanner::TokenKind::Align) {
2676 2687
            set alignment = try parseAlign(p);
2677 2688
        }
2678 2689
    }
2679 2690
    let mut valueBroken = false;
2680 -
    if consume(p, scanner::TokenKind::Equal) {
2691 +
    if try consume(p, scanner::TokenKind::Equal) {
2681 2692
        set valueBroken = startsLine(p);
2682 2693
        // A `{` after the value of a region reference begins a borrow block.
2683 2694
        if let t = type; reference and ast::regionOf(t) <> nil {
2684 2695
            set value = try parseCond(p);
2685 2696
        } else {
2689 2700
    return NameTypeValue { name, type, value, alignment, valueBroken };
2690 2701
}
2691 2702
2692 2703
/// Parse a constant declaration.
2693 2704
fn parseConst(p: &mut Parser, attrs: ?ast::Attributes) -> *ast::Node
2694 -
    throws (ParseError)
2705 +
    throws (ParseError, AllocError)
2695 2706
{
2696 2707
    try expect(p, scanner::TokenKind::Constant, "expected `constant`");
2697 2708
    if check(p, scanner::TokenKind::Fn) {
2698 -
        let mut list = ast::nodeSlice(&mut p.arena, 4);
2709 +
        let mut list = try ast::nodeSlice(&mut p.arena, 4);
2699 2710
        if let attrs = attrs {
2700 2711
            for attr in attrs.list {
2701 -
                try! list.append(attr, p.arena.heap);
2712 +
                try list.append(attr, p.arena.heap);
2702 2713
            }
2703 2714
        }
2704 -
        try! list.append(nodeAttribute(p, ast::Attribute::Constant), p.arena.heap);
2715 +
        try list.append(try nodeAttribute(p, ast::Attribute::Constant), p.arena.heap);
2705 2716
        return try parseFnDecl(p, ast::Attributes { list });
2706 2717
    }
2707 2718
    if let attrs = attrs; ast::attributesContains(&attrs, ast::Attribute::Unsafe) {
2708 2719
        throw failParsing(p, "`unsafe` requires a function, block, or static");
2709 2720
    }
2713 2724
    let type = try parseType(p);
2714 2725
    try expect(p, scanner::TokenKind::Equal, "expected `=` in constant declaration");
2715 2726
2716 2727
    let broken = startsLine(p);
2717 2728
    let value = try parseExpr(p);
2718 -
    let decl: *ast::Node = node(p, ast::NodeValue::ConstDecl(
2729 +
    let decl: *ast::Node = try node(p, ast::NodeValue::ConstDecl(
2719 2730
        ast::ConstDecl { ident, type, value, attrs }
2720 2731
    ));
2721 -
    markBroken(p, decl, broken, ast::BrokenSite::Value);
2732 +
    try markBroken(p, decl, broken, ast::BrokenSite::Value);
2722 2733
2723 2734
    return decl;
2724 2735
}
2725 2736
2726 2737
/// Parse a static declaration.
2727 2738
fn parseStatic(p: &mut Parser, attrs: ?ast::Attributes) -> *ast::Node
2728 -
    throws (ParseError)
2739 +
    throws (ParseError, AllocError)
2729 2740
{
2730 2741
    try expect(p, scanner::TokenKind::Static, "expected `static`");
2731 2742
2732 2743
    let ident = try parseIdent(p, "expected identifier in static declaration");
2733 2744
    try expect(p, scanner::TokenKind::Colon, "expected `:` after identifier");
2735 2746
    let type = try parseType(p);
2736 2747
    try expect(p, scanner::TokenKind::Equal, "expected `=` in static declaration");
2737 2748
2738 2749
    let broken = startsLine(p);
2739 2750
    let value = try parseExpr(p);
2740 -
    let decl: *ast::Node = node(p, ast::NodeValue::StaticDecl(
2751 +
    let decl: *ast::Node = try node(p, ast::NodeValue::StaticDecl(
2741 2752
        ast::StaticDecl { ident, type, value, attrs }
2742 2753
    ));
2743 -
    markBroken(p, decl, broken, ast::BrokenSite::Value);
2754 +
    try markBroken(p, decl, broken, ast::BrokenSite::Value);
2744 2755
2745 2756
    return decl;
2746 2757
}
2747 2758
2748 2759
/// Parse a `use` declaration.
2749 2760
fn parseUse(p: &mut Parser, attrs: ?ast::Attributes) -> *ast::Node
2750 -
    throws (ParseError)
2761 +
    throws (ParseError, AllocError)
2751 2762
{
2752 2763
    try expect(p, scanner::TokenKind::Use, "expected `use`");
2753 2764
2754 2765
    // Allow `super` or identifier as the first part of the path.
2755 2766
    let mut path: *ast::Node = undefined;
2756 -
    if consume(p, scanner::TokenKind::Super) {
2757 -
        set path = nodeSuper(p);
2767 +
    if try consume(p, scanner::TokenKind::Super) {
2768 +
        set path = try nodeSuper(p);
2758 2769
    } else {
2759 2770
        set path = try parseIdent(p, "expected module name or `super` after `use`");
2760 2771
    }
2761 -
    while consume(p, scanner::TokenKind::ColonColon) {
2772 +
    while try consume(p, scanner::TokenKind::ColonColon) {
2762 2773
        // Check for wildcard import (e.g., `use parser::*`)
2763 -
        if consume(p, scanner::TokenKind::Star) {
2764 -
            return node(p, ast::NodeValue::Use(
2774 +
        if try consume(p, scanner::TokenKind::Star) {
2775 +
            return try node(p, ast::NodeValue::Use(
2765 2776
                ast::Use { path, wildcard: true, attrs }
2766 2777
            ));
2767 2778
        }
2768 2779
        let part = try parseIdent(p, "expected identifier or `*` after `::`");
2769 -
        set path = node(p, ast::NodeValue::ScopeAccess(
2780 +
        set path = try node(p, ast::NodeValue::ScopeAccess(
2770 2781
            ast::Access { parent: path, child: part }
2771 2782
        ));
2772 2783
    }
2773 -
    return node(p, ast::NodeValue::Use(
2784 +
    return try node(p, ast::NodeValue::Use(
2774 2785
        ast::Use { path, wildcard: false, attrs }
2775 2786
    ));
2776 2787
}
2777 2788
2778 2789
/// Parse a `mod` declaration.
2779 2790
fn parseMod(p: &mut Parser, attrs: ?ast::Attributes) -> *ast::Node
2780 -
    throws (ParseError)
2791 +
    throws (ParseError, AllocError)
2781 2792
{
2782 2793
    try expect(p, scanner::TokenKind::Mod, "expected `mod`");
2783 2794
    let name = try parseIdent(p, "expected module name after `mod`");
2784 2795
2785 -
    return node(p, ast::NodeValue::Mod(
2796 +
    return try node(p, ast::NodeValue::Mod(
2786 2797
        ast::Mod { name, attrs }
2787 2798
    ));
2788 2799
}
2789 2800
2790 2801
/// Parse a `let case` guard statement.
2791 2802
///
2792 2803
/// Eg. `let case <pattern> = <expr> else { ... };`
2793 2804
/// Eg. `let case <pattern> = <expr> if <guard> else { ... };`
2794 2805
///
2795 2806
/// Expects `let case` tokens to have already been consumed.
2796 -
fn parseLetCase(p: &mut Parser) -> *ast::Node throws (ParseError) {
2807 +
fn parseLetCase(p: &mut Parser) -> *ast::Node throws (ParseError, AllocError) {
2797 2808
    let pattern = try parseMatchPattern(p);
2798 2809
2799 2810
    try expect(p, scanner::TokenKind::Equal, "expected `=` after pattern");
2800 2811
    let expr = try parseCond(p);
2801 2812
2802 2813
    let mut guard: ?*ast::Node = nil;
2803 -
    if consume(p, scanner::TokenKind::If) {
2814 +
    if try consume(p, scanner::TokenKind::If) {
2804 2815
        set guard = try parseCond(p);
2805 2816
    }
2806 2817
    try expect(p, scanner::TokenKind::Else, "expected `else` after pattern");
2807 2818
    let elseBranch = try parseLetElseBranch(p);
2808 2819
2809 -
    return node(p, ast::NodeValue::LetElse(ast::LetElse {
2820 +
    return try node(p, ast::NodeValue::LetElse(ast::LetElse {
2810 2821
        pattern: ast::PatternMatch {
2811 2822
            pattern, scrutinee: expr, guard, kind: ast::PatternKind::Case, mutable: false
2812 2823
        },
2813 2824
        elseBranch,
2814 2825
    }));
2822 2833
/// Eg. `let <ident> = <expr> if <guard> else { ... };`
2823 2834
/// Eg. `let <ident>: &'r <type> = <expr> { ... }`
2824 2835
/// Eg. `mut <ident> = <expr>;`
2825 2836
///
2826 2837
/// Expects `let` or `mut` token to have already been consumed.
2827 -
fn parseLet(p: &mut Parser, mutable: bool) -> *ast::Node throws (ParseError) {
2838 +
fn parseLet(p: &mut Parser, mutable: bool) -> *ast::Node throws (ParseError, AllocError) {
2828 2839
    let binding = try parseNameTypeValue(p);
2829 2840
    let value = binding.value else throw failParsing(p, "expected value initializer");
2830 2841
2831 2842
    // Check for optional `else` clause (let-else).
2832 -
    if consume(p, scanner::TokenKind::Else) {
2843 +
    if try consume(p, scanner::TokenKind::Else) {
2833 2844
        let elseBranch = try parseLetElseBranch(p);
2834 2845
2835 -
        return node(p, ast::NodeValue::LetElse(ast::LetElse {
2846 +
        return try node(p, ast::NodeValue::LetElse(ast::LetElse {
2836 2847
            pattern: ast::PatternMatch {
2837 2848
                pattern: binding.name,
2838 2849
                scrutinee: value,
2839 2850
                guard: nil,
2840 2851
                kind: ast::PatternKind::Binding,
2845 2856
    }
2846 2857
    let mut borrow = false;
2847 2858
    if let t = binding.type {
2848 2859
        set borrow = p.current.kind == scanner::TokenKind::LBrace and ast::regionOf(t) <> nil;
2849 2860
    }
2850 -
    let stmt: *ast::Node = node(p, ast::NodeValue::Let(ast::Let {
2861 +
    let stmt: *ast::Node = try node(p, ast::NodeValue::Let(ast::Let {
2851 2862
        ident: binding.name,
2852 2863
        type: binding.type,
2853 2864
        value,
2854 2865
        alignment: binding.alignment,
2855 2866
        mutable,
2856 2867
        borrow,
2857 2868
    }));
2858 -
    markBroken(p, stmt, binding.valueBroken, ast::BrokenSite::Value);
2869 +
    try markBroken(p, stmt, binding.valueBroken, ast::BrokenSite::Value);
2859 2870
    if not borrow {
2860 2871
        return stmt;
2861 2872
    }
2862 2873
    // A borrow block is a block of the binding and its body.
2863 2874
    let body = try parseBlock(p);
2864 -
    let mut statements = ast::nodeSlice(&mut p.arena, 2);
2865 -
    try! statements.append(stmt, p.arena.heap);
2866 -
    try! statements.append(body, p.arena.heap);
2875 +
    let mut statements = try ast::nodeSlice(&mut p.arena, 2);
2876 +
    try statements.append(stmt, p.arena.heap);
2877 +
    try statements.append(body, p.arena.heap);
2867 2878
2868 -
    return node(p, ast::NodeValue::Block(ast::Block { statements, isUnsafe: false }));
2879 +
    return try node(p, ast::NodeValue::Block(ast::Block { statements, isUnsafe: false }));
2869 2880
}
2870 2881
2871 2882
/// Parse one module from source text into a block of top-level statements.
2872 2883
///
2873 2884
/// Scanner, token, and error state are reset for the module. Nodes and strings
2875 2886
export fn parseModule(p: &mut Parser, sourceLoc: scanner::SourceLoc, input: *[u8]) -> *ast::Node
2876 2887
    throws (ParseError)
2877 2888
{
2878 2889
    beginModule(p, sourceLoc, input);
2879 2890
2880 -
    return try parseTopLevel(p) catch {
2891 +
    return try parseTopLevel(p) catch err as AllocError {
2892 +
        let token = p.current;
2893 +
        reportError(p, token, "syntax tree arena is full");
2881 2894
        printErrors(p);
2882 -
        throw ParseError::UnexpectedToken;
2895 +
        throw ParseError::AllocationFailed;
2896 +
    } catch err as ParseError {
2897 +
        printErrors(p);
2898 +
        throw err;
2883 2899
    };
2884 2900
}
2885 2901
2886 2902
/// Reset the scanner, token, and error state to read `input` as a new module.
2887 2903
///
2899 2915
    set p.closing = &mut [];
2900 2916
}
2901 2917
2902 2918
/// Parse the current module's tokens into a block of top-level statements.
2903 2919
fn parseTopLevel(p: &mut Parser) -> *ast::Node
2904 -
    throws (ParseError)
2920 +
    throws (ParseError, AllocError)
2905 2921
{
2906 -
    advance(p); // Set the parser up with a first token.
2922 +
    try advance(p); // Set the parser up with a first token.
2907 2923
2908 2924
    let statements = try parseStmtsUntil(
2909 2925
        p, scanner::TokenKind::Eof, INITIAL_MODULE_STATEMENTS
2910 2926
    );
2911 2927
    let blk = ast::Block { statements, isUnsafe: false };
2912 -
    consume(p, scanner::TokenKind::Eof);
2913 -
    let block: *ast::Node = node(p, ast::NodeValue::Block(blk));
2914 -
    attachClosing(p, block);
2928 +
    try consume(p, scanner::TokenKind::Eof);
2929 +
    let block: *ast::Node = try node(p, ast::NodeValue::Block(blk));
2930 +
    try attachClosing(p, block);
2915 2931
2916 2932
    return block;
2917 2933
}
2918 2934
2919 2935
/// Consume a token of the given kind if present.
2920 -
export fn consume(p: &mut Parser, kind: scanner::TokenKind) -> bool {
2921 -
    if check(p, kind) {
2922 -
        advance(p);
2936 +
export fn consume(p: &mut Parser, kind: scanner::TokenKind) -> bool throws (AllocError) {
2937 +
    if p.current.kind == kind {
2938 +
        try advance(p);
2923 2939
        return true;
2924 2940
    }
2925 2941
    return false;
2926 2942
}
2927 2943
2928 2944
/// Expect a token of the given kind or report an error.
2929 2945
export fn expect(p: &mut Parser, kind: scanner::TokenKind, message: *[u8]) -> *[u8]
2930 -
    throws (ParseError)
2946 +
    throws (ParseError, AllocError)
2931 2947
{
2932 -
    if not consume(p, kind) {
2948 +
    if p.current.kind <> kind {
2933 2949
        let token = p.current;
2934 2950
        reportError(p, token, message);
2935 2951
        throw ParseError::UnexpectedToken;
2936 2952
    }
2953 +
    try advance(p);
2937 2954
    return p.previous.source;
2938 2955
}
2939 2956
2940 2957
/// Parse a trait declaration.
2941 2958
/// Syntax: `trait Name { fn (*Trait) method(...) -> T; ... }`
2942 2959
fn parseTraitDecl(p: &mut Parser, attrs: ?ast::Attributes) -> *ast::Node
2943 -
    throws (ParseError)
2960 +
    throws (ParseError, AllocError)
2944 2961
{
2945 2962
    try expect(p, scanner::TokenKind::Trait, "expected `trait`");
2946 2963
    let name = try parseIdent(p, "expected trait name");
2947 2964
    let supertraits = try parseDerives(p);
2948 2965
    try expect(p, scanner::TokenKind::LBrace, "expected `{` after trait name");
2949 2966
    let outer = openList(p);
2950 2967
2951 -
    let mut methods = ast::nodeSlice(&mut p.arena, ast::MAX_TRAIT_METHODS);
2968 +
    let mut methods = try ast::nodeSlice(&mut p.arena, ast::MAX_TRAIT_METHODS);
2952 2969
    while not check(p, scanner::TokenKind::RBrace)
2953 2970
        and not check(p, scanner::TokenKind::Eof)
2954 2971
    {
2955 -
        let leading = takePending(p, &methods[..]);
2972 +
        let leading = try takePending(p, &methods[..]);
2956 2973
        let method = try parseTraitMethodSig(p);
2957 -
        attachLeading(p, method, leading);
2958 -
        try! methods.append(method, p.arena.heap);
2974 +
        try attachLeading(p, method, leading);
2975 +
        try methods.append(method, p.arena.heap);
2959 2976
    }
2960 -
    closeList(p, outer, &methods[..]);
2977 +
    try closeList(p, outer, &methods[..]);
2961 2978
    try expect(p, scanner::TokenKind::RBrace, "expected `}` after trait methods");
2962 -
    let decl: *ast::Node = node(p, ast::NodeValue::TraitDecl {
2979 +
    let decl: *ast::Node = try node(p, ast::NodeValue::TraitDecl {
2963 2980
        name, supertraits, methods, attrs
2964 2981
    });
2965 -
    attachClosing(p, decl);
2982 +
    try attachClosing(p, decl);
2966 2983
2967 2984
    return decl;
2968 2985
}
2969 2986
2970 2987
/// Parse a trait method signature.
2971 2988
/// Syntax: `fn (*Trait) fnord(<params>) -> ReturnType;`
2972 2989
fn parseTraitMethodSig(p: &mut Parser) -> *ast::Node
2973 -
    throws (ParseError)
2990 +
    throws (ParseError, AllocError)
2974 2991
{
2975 -
    let attrs = parseAttributes(p);
2992 +
    let attrs = try parseAttributes(p);
2976 2993
    try expect(p, scanner::TokenKind::Fn, "expected `fn`");
2977 2994
    try expect(p, scanner::TokenKind::LParen, "expected `(` before receiver");
2978 2995
2979 2996
    let receiver = try parseType(p);
2980 2997
2981 2998
    try expect(p, scanner::TokenKind::RParen, "expected `)` after receiver");
2982 2999
2983 3000
    let name = try parseIdent(p, "expected method name");
2984 3001
    let parsed = try parseFnTypeSig(p);
2985 3002
    try expect(p, scanner::TokenKind::Semicolon, "expected `;` after method signature");
2986 -
    let method: *ast::Node = node(p, ast::NodeValue::TraitMethodSig {
3003 +
    let method: *ast::Node = try node(p, ast::NodeValue::TraitMethodSig {
2987 3004
        name, receiver, sig: parsed.sig, attrs
2988 3005
    });
2989 -
    attachSig(p, method, parsed);
3006 +
    try attachSig(p, method, parsed);
2990 3007
2991 3008
    return method;
2992 3009
}
2993 3010
2994 3011
/// Parse an instance block.
2995 3012
/// Syntax: `instance Trait for Type { fn (t: *mut Type) fnord(..) {..} }`
2996 3013
///
2997 3014
/// Instance declarations do not accept attributes (e.g. `export`).
2998 3015
/// Visibility is determined by the trait declaration itself.
2999 3016
fn parseInstanceDecl(p: &mut Parser) -> *ast::Node
3000 -
    throws (ParseError)
3017 +
    throws (ParseError, AllocError)
3001 3018
{
3002 3019
    try expect(p, scanner::TokenKind::Instance, "expected `instance`");
3003 3020
    let traitName = try parseTypePath(p);
3004 3021
    try expect(p, scanner::TokenKind::For, "expected `for` after trait name");
3005 3022
    let targetType = try parseTypePath(p);
3006 3023
    try expect(p, scanner::TokenKind::LBrace, "expected `{` after target type");
3007 3024
    let outer = openList(p);
3008 3025
3009 -
    let mut methods = ast::nodeSlice(&mut p.arena, ast::MAX_TRAIT_METHODS);
3026 +
    let mut methods = try ast::nodeSlice(&mut p.arena, ast::MAX_TRAIT_METHODS);
3010 3027
3011 3028
    while not check(p, scanner::TokenKind::RBrace)
3012 3029
        and not check(p, scanner::TokenKind::Eof)
3013 3030
    {
3014 -
        let leading = takePending(p, &methods[..]);
3015 -
        let attrs = parseAttributes(p);
3031 +
        let leading = try takePending(p, &methods[..]);
3032 +
        let attrs = try parseAttributes(p);
3016 3033
        try expect(p, scanner::TokenKind::Fn, "expected `fn`");
3017 3034
        let method = try parseMethodDecl(p, attrs);
3018 3035
3019 -
        attachLeading(p, method, leading);
3020 -
        try! methods.append(method, p.arena.heap);
3036 +
        try attachLeading(p, method, leading);
3037 +
        try methods.append(method, p.arena.heap);
3021 3038
    }
3022 -
    closeList(p, outer, &methods[..]);
3039 +
    try closeList(p, outer, &methods[..]);
3023 3040
    try expect(p, scanner::TokenKind::RBrace, "expected `}` after instance methods");
3024 -
    let decl: *ast::Node = node(p, ast::NodeValue::InstanceDecl {
3041 +
    let decl: *ast::Node = try node(p, ast::NodeValue::InstanceDecl {
3025 3042
        traitName, targetType, methods
3026 3043
    });
3027 -
    attachClosing(p, decl);
3044 +
    try attachClosing(p, decl);
3028 3045
3029 3046
    return decl;
3030 3047
}
3031 3048
3032 3049
/// Parse a method declaration with a receiver.
3033 3050
/// Syntax: `fn (t: *mut Type) fnord(<params>) -> ReturnType { body }`
3034 3051
///
3035 3052
/// Used both inside `instance` blocks and as standalone methods at the top level.
3036 3053
/// Expects the `fn` token to have already been consumed.
3037 3054
fn parseMethodDecl(p: &mut Parser, attrs: ?ast::Attributes) -> *ast::Node
3038 -
    throws (ParseError)
3055 +
    throws (ParseError, AllocError)
3039 3056
{
3040 3057
    try expect(p, scanner::TokenKind::LParen, "expected `(` before receiver");
3041 3058
3042 3059
    let receiverName = try parseIdent(p, "expected receiver name");
3043 3060
    try expect(p, scanner::TokenKind::Colon, "expected `:` after receiver name");
3046 3063
    try expect(p, scanner::TokenKind::RParen, "expected `)` after receiver type");
3047 3064
3048 3065
    let name = try parseIdent(p, "expected method name");
3049 3066
    let parsed = try parseFnTypeSig(p);
3050 3067
    let body = try parseBlock(p);
3051 -
    let method: *ast::Node = node(p, ast::NodeValue::MethodDecl {
3068 +
    let method: *ast::Node = try node(p, ast::NodeValue::MethodDecl {
3052 3069
        name, receiverName, receiverType, sig: parsed.sig, body, attrs
3053 3070
    });
3054 -
    attachSig(p, method, parsed);
3071 +
    try attachSig(p, method, parsed);
3055 3072
3056 3073
    return method;
3057 3074
}
3058 3075
3059 3076
/// Parse comma-separated items up to, not including, the `close` token.
3061 3078
/// The opening delimiter should already be consumed and the list opened with
3062 3079
/// [`openList`], whose result is `outer`. The caller ends the list.
3063 3080
fn parseItems(
3064 3081
    p: &mut Parser,
3065 3082
    close: scanner::TokenKind,
3066 -
    parseItem: fn(&mut Parser) -> *ast::Node throws (ParseError),
3083 +
    parseItem: fn(&mut Parser) -> *ast::Node throws (ParseError, AllocError),
3067 3084
    outer: &mut Open
3068 -
) -> *mut [*ast::Node] throws (ParseError) {
3069 -
    let mut items = ast::nodeSlice(&mut p.arena, 8);
3085 +
) -> *mut [*ast::Node] throws (ParseError, AllocError) {
3086 +
    let mut items = try ast::nodeSlice(&mut p.arena, 8);
3070 3087
3071 3088
    while not check(p, close) {
3072 -
        let leading = takePending(p, &items[..]);
3089 +
        let leading = try takePending(p, &items[..]);
3073 3090
        noteItem(p, outer);
3074 3091
        let item = try parseItem(p);
3075 -
        attachLeading(p, item, leading);
3076 -
        try! items.append(item, p.arena.heap);
3092 +
        try attachLeading(p, item, leading);
3093 +
        try items.append(item, p.arena.heap);
3077 3094
3078 -
        if not consume(p, scanner::TokenKind::Comma) {
3095 +
        if not try consume(p, scanner::TokenKind::Comma) {
3079 3096
            break;
3080 3097
        }
3081 3098
    }
3082 3099
    return items;
3083 3100
}
lib/std/lang/parser/tests.rad +100 -21
1 1
//! Parser tests.
2 2
3 -
use std::mem;
4 3
use std::fmt;
5 -
use std::testing;
4 +
use std::lang::alloc::AllocError;
6 5
use std::lang::ast;
7 -
use std::lang::types;
8 -
use std::mem::heap;
9 -
use std::lang::sexpr;
10 6
use std::lang::ast::printer;
11 7
use std::lang::scanner;
8 +
use std::lang::sexpr;
12 9
use std::lang::strings;
10 +
use std::lang::types;
11 +
use std::mem;
12 +
use std::mem::heap;
13 +
use std::testing;
13 14
14 15
/// Unified arena size.
15 16
constant ARENA_SIZE: u32 = 2097152;
16 17
/// Unified arena storage for all AST allocations.
17 18
static ARENA_STORAGE: [u8; ARENA_SIZE] = [0; ARENA_SIZE];
112 113
    return root;
113 114
}
114 115
115 116
/// Parse a single type from a string.
116 117
unsafe fn parseTypeStr(input: *[u8]) -> *ast::Node
117 -
    throws (super::ParseError)
118 +
    throws (super::ParseError, AllocError)
118 119
{
119 120
    let mut parser = mkParser(input);
120 -
    super::advance(&mut parser);
121 +
    try super::advance(&mut parser);
121 122
    let root = try super::parseType(&mut parser);
122 123
    try super::expect(&mut parser, scanner::TokenKind::Eof, "expected end of type");
123 124
    keepNodes(&parser);
124 125
125 126
    return root;
126 127
}
127 128
128 129
/// Parse a single expression from a string.
129 130
export unsafe fn parseExprStr(input: *[u8]) -> *ast::Node
130 -
    throws (super::ParseError)
131 +
    throws (super::ParseError, AllocError)
131 132
{
132 133
    let mut parser = mkParser(input);
133 -
    super::advance(&mut parser);
134 +
    try super::advance(&mut parser);
134 135
    let root = try super::parseExpr(&mut parser);
135 136
    keepNodes(&parser);
136 137
137 138
    return root;
138 139
}
139 140
140 141
/// Parse a single statement from a string.
141 142
unsafe fn parseStmtStr(input: *[u8]) -> *ast::Node
142 -
    throws (super::ParseError)
143 +
    throws (super::ParseError, AllocError)
143 144
{
144 145
    let mut parser = mkParser(input);
145 -
    super::advance(&mut parser);
146 +
    try super::advance(&mut parser);
146 147
    let root = try super::parseStmt(&mut parser);
147 -
    while super::consume(&mut parser, scanner::TokenKind::Semicolon) {}
148 +
    while try super::consume(&mut parser, scanner::TokenKind::Semicolon) {}
148 149
    try super::expect(&mut parser, scanner::TokenKind::Eof, "expected end of statement");
149 150
    keepNodes(&parser);
150 151
151 152
    return root;
152 153
}
154 155
/// Parse an expression expected to be a number literal and return its payload.
155 156
unsafe fn parseNumberLiteral(text: *[u8]) -> fmt::IntLiteral
156 157
    throws (testing::TestError)
157 158
{
158 159
    let mut parser = mkParser(text);
159 -
    super::advance(&mut parser);
160 +
    try! super::advance(&mut parser);
160 161
161 162
    let node = try! super::parseExpr(&mut parser);
162 163
163 164
    if not super::check(&parser, scanner::TokenKind::Eof) {
164 165
        throw testing::TestError::Failed;
171 172
/// Ensure that parsing the supplied literal source fails.
172 173
unsafe fn expectNumberLiteralFail(text: *[u8])
173 174
    throws (testing::TestError)
174 175
{
175 176
    let mut parser = mkParser(text);
176 -
    super::advance(&mut parser);
177 +
    try! super::advance(&mut parser);
177 178
178 179
    try super::parseExpr(&mut parser) catch {
179 180
        return;
180 181
    };
181 182
    if not super::check(&parser, scanner::TokenKind::Eof) {
1228 1229
}
1229 1230
1230 1231
/// Test scanning source-level `void` produces an identifier, not a type keyword.
1231 1232
@test unsafe fn testParseTypeVoidRejected() throws (testing::TestError) {
1232 1233
    let mut parser = mkParser("void");
1233 -
    super::advance(&mut parser);
1234 +
    try! super::advance(&mut parser);
1234 1235
    try testing::expect(super::check(&parser, scanner::TokenKind::Ident));
1235 1236
}
1236 1237
1237 1238
/// Test parsing the unsafe function modifier.
1238 1239
@test unsafe fn testParseUnsafeFnDecl() throws (testing::TestError) {
1720 1721
1721 1722
/// Test that AST nodes keep their ids and values as the arena grows.
1722 1723
@test unsafe fn testAllocNodeStable() throws (testing::TestError) {
1723 1724
    let mut arena = ast::nodeArena(&mut ARENA_STORAGE[..]);
1724 1725
    let span = ast::Span { offset: 0, length: 0 };
1725 -
    let first = ast::allocNode(&mut arena, span, ast::NodeValue::Bool(true));
1726 -
    let second = ast::synthNode(&mut arena, ast::NodeValue::Bool(false));
1727 -
    let third = ast::synthNode(&mut arena, ast::NodeValue::Nil);
1726 +
    let first = try! ast::allocNode(&mut arena, span, ast::NodeValue::Bool(true));
1727 +
    let second = try! ast::synthNode(&mut arena, ast::NodeValue::Bool(false));
1728 +
    let third = try! ast::synthNode(&mut arena, ast::NodeValue::Nil);
1728 1729
1729 1730
    try testing::expect(first.id == 0 and second.id == 1 and third.id == 2);
1730 1731
    try testing::expect(arena.nextId == 3);
1731 1732
    try testing::expect(heap::used(arena.heap) == 3 * @sizeOf(ast::Node));
1732 1733
3049 3050
/// `nodeSlice` reserves exactly the requested capacity, and appends within it do not grow it.
3050 3051
@test unsafe fn testNodeSliceCapacity() throws (testing::TestError) {
3051 3052
    static STORAGE: [u8; 4096] = [0; 4096];
3052 3053
    let mut arena = ast::nodeArena(&mut STORAGE[..]);
3053 3054
3054 -
    let empty = ast::nodeSlice(&mut arena, 0);
3055 +
    let empty = try! ast::nodeSlice(&mut arena, 0);
3055 3056
    assert empty.len == 0;
3056 3057
    assert empty.cap == 0;
3057 3058
3058 -
    let mut nodes = ast::nodeSlice(&mut arena, 3);
3059 +
    let mut nodes = try! ast::nodeSlice(&mut arena, 3);
3059 3060
    assert nodes.len == 0;
3060 3061
    assert nodes.cap == 3;
3061 3062
    for _ in 0 .. 3 {
3062 -
        let node = ast::synthNode(&mut arena, ast::NodeValue::Placeholder);
3063 +
        let node = try! ast::synthNode(&mut arena, ast::NodeValue::Placeholder);
3063 3064
        try! nodes.append(node, arena.heap);
3064 3065
    }
3065 3066
    assert nodes.len == 3;
3066 3067
    assert nodes.cap == 3;
3067 3068
}
3725 3726
    let regions = ast::nominalRegions(type);
3726 3727
    assert regions.len == 2;
3727 3728
    try expectIdent(regions[0], "'b");
3728 3729
    try expectIdent(regions[1], "'a");
3729 3730
}
3731 +
3732 +
/// A full AST arena returns a parse failure with a diagnostic.
3733 +
@test unsafe fn arenaExhaustion() throws (testing::TestError) {
3734 +
    let mut parser = mkParser("");
3735 +
    static STORAGE: [u8; 64] = [0; 64];
3736 +
    set parser.arena = ast::NodeArena {
3737 +
        heap: heap::withCapacity(&mut STORAGE[..], 0), nextId: 0
3738 +
    };
3739 +
    let mut failed = false;
3740 +
    try super::parseModule(&mut parser, scanner::SourceLoc::String, "true;") catch {
3741 +
        set failed = true;
3742 +
    };
3743 +
    assert failed;
3744 +
    assert parser.errors.count == 1;
3745 +
    assert mem::eq(parser.errors.list[0].message, "syntax tree arena is full");
3746 +
}
3747 +
3748 +
/// AST allocation failure preserves node IDs and reaches synthesis callers.
3749 +
@test unsafe fn arenaAllocationErrors() throws (testing::TestError) {
3750 +
    static STORAGE: [u8; 4096] = [0; 4096];
3751 +
    let mut arena = ast::NodeArena {
3752 +
        heap: heap::withCapacity(&mut STORAGE[..], 0), nextId: 0
3753 +
    };
3754 +
    let empty = try! ast::nodeSlice(&mut arena, 0);
3755 +
    assert empty.len == 0 and empty.cap == 0;
3756 +
    let mut failures: u32 = 0;
3757 +
    try ast::nodeSlice(&mut arena, 1) catch {
3758 +
        set failures += 1;
3759 +
    };
3760 +
    try ast::synthNode(&mut arena, ast::NodeValue::Nil) catch {
3761 +
        set failures += 1;
3762 +
    };
3763 +
    assert failures == 2 and arena.nextId == 0;
3764 +
3765 +
    let mut capacity: u32 = 0;
3766 +
    loop {
3767 +
        let mut arena = ast::NodeArena {
3768 +
            heap: heap::withCapacity(&mut STORAGE[..], capacity), nextId: 0
3769 +
        };
3770 +
        let result = try ast::synthFnModule(&mut arena, "f", &[]) catch {
3771 +
            set capacity += 8;
3772 +
            assert capacity < 4096 - 48;
3773 +
            continue;
3774 +
        };
3775 +
        assert arena.nextId == 4;
3776 +
        assert result.modBody.id == 3 and result.fnBody.id == 1;
3777 +
        break;
3778 +
    }
3779 +
}
3780 +
3781 +
/// Expression and trivia allocation failures reach the parser's callers.
3782 +
@test unsafe fn parserAllocationErrors() throws (testing::TestError) {
3783 +
    static STORAGE: [u8; 4096] = [0; 4096];
3784 +
    for source in ["true", "[true, false]", "\"a\\nb\"", "// note\ntrue"] {
3785 +
        let mut capacity: u32 = 0;
3786 +
        loop {
3787 +
            let mut parser = mkParser(source);
3788 +
            set parser.arena = ast::NodeArena {
3789 +
                heap: heap::withCapacity(&mut STORAGE[..], capacity), nextId: 0
3790 +
            };
3791 +
            set parser.triviaMode = super::TriviaMode::Keep;
3792 +
            try super::advance(&mut parser) catch {
3793 +
                set capacity += 8;
3794 +
                assert capacity < 4096 - 48;
3795 +
                continue;
3796 +
            };
3797 +
            let result = try super::parseExpr(&mut parser) catch err as AllocError {
3798 +
                set capacity += 8;
3799 +
                assert capacity < 4096 - 48;
3800 +
                continue;
3801 +
            } catch err as super::ParseError {
3802 +
                throw testing::TestError::Failed;
3803 +
            };
3804 +
            assert result.span.length > 0;
3805 +
            break;
3806 +
        }
3807 +
    }
3808 +
}
lib/std/lang/resolver.rad +42 -33
675 675
    ReceiverNotOwned,
676 676
    /// Expected a compile-time constant expression.
677 677
    ConstExprRequired,
678 678
    /// Symbol arena exhausted while binding identifiers.
679 679
    SymbolOverflow,
680 -
    /// Union declares more than [`MAX_UNION_VARIANTS`] variants.
681 -
    UnionVariantOverflow,
680 +
    /// A declaration exceeds a compiler limit, with a source diagnostic.
681 +
    LimitExceeded(*[u8]),
682 682
    /// Expression has the wrong type.
683 683
    TypeMismatch(TypeMismatch),
684 684
    /// Numeric literal does not fit within the required range.
685 685
    NumericLiteralOverflow,
686 686
    /// Array length exceeds [`types::MAX_LENGTH`].
5160 5160
    let mut maxAlignment: u32 = 1;
5161 5161
    // Whether the record or union whose fields are resolved declares a region.
5162 5162
    let borrowedDecl = self.declRegions.len > 0;
5163 5163
5164 5164
    if fields.len > parser::MAX_RECORD_FIELDS {
5165 -
        throw emitError(self, node, ErrorKind::Internal);
5165 +
        throw emitError(self, fields[parser::MAX_RECORD_FIELDS], ErrorKind::LimitExceeded(
5166 +
            "too many fields in one record"
5167 +
        ));
5166 5168
    }
5167 5169
    // TODO: Add cycle detection to catch invalid recursive types like `record A { a: A }`.
5168 5170
    for field in fields {
5169 5171
        let case ast::NodeValue::RecordField {
5170 5172
            field: fieldNode,
6162 6164
        borrowed: decl.regions.len > 0,
6163 6165
        regions: decl.regions,
6164 6166
    });
6165 6167
6166 6168
    if decl.variants.len > MAX_UNION_VARIANTS {
6167 -
        throw emitError(self, decl.variants[MAX_UNION_VARIANTS], ErrorKind::UnionVariantOverflow);
6169 +
        throw emitError(self, decl.variants[MAX_UNION_VARIANTS], ErrorKind::LimitExceeded(
6170 +
            "too many variants in one union"
6171 +
        ));
6168 6172
    }
6169 6173
    let mut iota: u32 = 0;
6170 6174
    let mut tags: [bool; 256] = [false; 256];
6171 6175
    for variantNode, i in decl.variants {
6172 6176
        let case ast::NodeValue::UnionDeclVariant(variantDecl) = variantNode.value
10515 10519
}
10516 10520
10517 10521
/// Analyze a standalone expression by wrapping it in a synthetic function.
10518 10522
export fn resolveExpr(
10519 10523
    self: &mut Resolver, expr: *ast::Node, arena: &mut ast::NodeArena
10520 -
) -> Diagnostics throws (ResolveError) {
10521 -
    let exprStmt = ast::synthNode(arena, ast::NodeValue::ExprStmt(expr));
10522 -
    let bodyStmts = try! ast::nodeSlice(arena, 1).append(exprStmt, arena.heap);
10523 -
    let module = ast::synthFnModule(arena, ANALYZE_EXPR_FN_NAME, bodyStmts);
10524 +
) -> Diagnostics throws (ResolveError, super::alloc::AllocError) {
10525 +
    let exprStmt = try ast::synthNode(arena, ast::NodeValue::ExprStmt(expr));
10526 +
    let mut bodyStmts = try ast::nodeSlice(arena, 1);
10527 +
    try bodyStmts.append(exprStmt, arena.heap);
10528 +
    let module = try ast::synthFnModule(arena, ANALYZE_EXPR_FN_NAME, bodyStmts);
10524 10529
10525 10530
    let case ast::NodeValue::Block(block) = module.modBody.value
10526 10531
        else panic "resolveExpr: expected block for module body";
10527 10532
    enterScope(self, module.modBody);
10528 10533
    try resolveModuleDecls(self, &block) catch {
10755 10760
        }
10756 10761
    }
10757 10762
}
10758 10763
10759 10764
/// Analyze a module tree's declarations, then resolve its type bodies.
10765 +
/// This includes the type bodies of each module and its sub-modules.
10766 +
/// Type bodies run after every module's declarations are processed, so that
10767 +
/// on-demand resolution in another module sees that module's imports.
10760 10768
fn resolveModuleDecls(res: &mut Resolver, block: &ast::Block) throws (ResolveError) {
10761 10769
    try declareModule(res, block);
10762 -
    try resolveModuleTypes(res, block);
10770 +
    // Resolve type bodies (record fields, union variants).
10771 +
    try resolveModuleTree(res, block, resolveTypeBodies);
10772 +
    try resolveModuleTree(res, block, resolveModuleMembers);
10763 10773
}
10764 10774
10765 -
/// Resolve the type bodies of a sub-module.
10766 -
fn resolveModTypes(self: &mut Resolver, node: *ast::Node, decl: ast::Mod) throws (ResolveError) {
10767 -
    if not shouldAnalyzeModule(self, decl.attrs) {
10768 -
        return;
10769 -
    }
10770 -
    let modName = try nodeName(self, decl.name);
10771 -
    let submod = try enterSubModule(self, modName, node);
10772 -
    let case ast::NodeValue::Block(block) = submod.root.value
10773 -
        else panic "resolveModTypes: expected block for module root";
10774 -
    try resolveModuleTypes(self, &block) catch e {
10775 -
        exitModuleScope(self, submod);
10776 -
        throw e;
10777 -
    };
10778 -
    exitModuleScope(self, submod);
10779 -
}
10780 -
10781 -
/// Resolve type bodies of a module and its sub-modules.
10782 -
/// This runs after every module's declarations are processed, so that a type body
10783 -
/// resolved on demand in another module sees that module's imports.
10784 -
fn resolveModuleTypes(res: &mut Resolver, block: &ast::Block) throws (ResolveError) {
10775 +
/// Apply `resolveBody` to child modules before their parent.
10776 +
fn resolveModuleTree(
10777 +
    res: &mut Resolver,
10778 +
    block: &ast::Block,
10779 +
    resolveBody: fn(&mut Resolver, &ast::Block) throws (ResolveError)
10780 +
) throws (ResolveError) {
10785 10781
    for node in block.statements {
10786 10782
        if let case ast::NodeValue::Mod(decl) = node.value {
10787 -
            try resolveModTypes(res, node, decl);
10783 +
            if not shouldAnalyzeModule(res, decl.attrs) {
10784 +
                continue;
10785 +
            }
10786 +
            let name = try nodeName(res, decl.name);
10787 +
            let submod = try enterSubModule(res, name, node);
10788 +
            let case ast::NodeValue::Block(child) = submod.root.value
10789 +
                else panic "resolveModuleTree: expected module block";
10790 +
            try resolveModuleTree(res, &child, resolveBody) catch err {
10791 +
                exitModuleScope(res, submod);
10792 +
                throw err;
10793 +
            };
10794 +
            exitModuleScope(res, submod);
10788 10795
        }
10789 10796
    }
10790 -
    // Resolve type bodies (record fields, union variants), then the remaining
10791 -
    // declarations (constant checks, instances, methods).
10792 -
    try resolveTypeBodies(res, block);
10797 +
    try resolveBody(res, block);
10798 +
}
10799 +
10800 +
/// Resolve constants, instances and methods after all module types are complete.
10801 +
fn resolveModuleMembers(res: &mut Resolver, block: &ast::Block) throws (ResolveError) {
10793 10802
    for stmt in block.statements {
10794 10803
        try visitDecl(res, stmt);
10795 10804
    }
10796 10805
}
10797 10806
lib/std/lang/resolver/printer.rad +4 -4
1 1
//! Resolver scope printer.
2 2
use std::io;
3 3
use std::lang::ast;
4 -
use std::lang::types;
5 -
use std::lang::scanner;
6 4
use std::lang::module;
5 +
use std::lang::scanner;
6 +
use std::lang::types;
7 7
8 8
/// Print a span in `@offset:length` form.
9 9
fn printSpan(span: ast::Span) {
10 10
    io::print("@");
11 11
    io::printU32(span.offset);
428 428
            io::print("expected compile-time constant expression");
429 429
        }
430 430
        case super::ErrorKind::SymbolOverflow => {
431 431
            io::print("too many symbols in one scope");
432 432
        }
433 -
        case super::ErrorKind::UnionVariantOverflow => {
434 -
            io::print("too many variants in one union");
433 +
        case super::ErrorKind::LimitExceeded(message) => {
434 +
            io::print(message);
435 435
        }
436 436
        case super::ErrorKind::NumericLiteralOverflow => {
437 437
            io::print("numeric literal overflow");
438 438
        }
439 439
        case super::ErrorKind::ArrayTooLong => {
lib/std/lang/resolver/tests.rad +7 -7
6 6
@test mod structure;
7 7
@test mod safety;
8 8
@test mod opacity;
9 9
@test mod regions;
10 10
11 -
use std::mem;
12 -
use std::testing;
13 -
use std::mem::heap;
14 -
use std::lang::ast;
15 11
use std::lang::alloc;
12 +
use std::lang::ast;
13 +
use std::lang::module;
16 14
use std::lang::parser;
17 15
use std::lang::scanner;
18 -
use std::lang::module;
19 16
use std::lang::strings;
17 +
use std::mem;
18 +
use std::mem::heap;
19 +
use std::testing;
20 20
21 21
/// Synthetic file path used for resolver tests.
22 22
export constant MODULE_PATH: *[u8] = "/dev/test.rad";
23 23
24 24
/// Joined test programs and the source spans kept by their ASTs.
108 108
109 109
/// Resolve a block of statements by wrapping them in a synthetic function.
110 110
export unsafe fn resolveStatements(
111 111
    self: &mut super::Resolver, block: ast::Block, arena: &mut ast::NodeArena
112 112
) -> TestResult throws (super::ResolveError) {
113 -
    let module = ast::synthFnModule(arena, super::ANALYZE_BLOCK_FN_NAME, block.statements);
113 +
    let module = try! ast::synthFnModule(arena, super::ANALYZE_BLOCK_FN_NAME, block.statements);
114 114
    let diagnostics = try super::resolveModuleRoot(self, module.modBody) catch {
115 115
        return TestResult { diagnostics: super::diagnostics(self), root: module.modBody };
116 116
    };
117 117
    return TestResult { diagnostics, root: module.fnBody };
118 118
}
120 120
/// Parse and analyze an expression string for testing.
121 121
export unsafe fn resolveExprStr(self: &mut super::Resolver, stmt: *[u8]) -> TestResult
122 122
    throws (testing::TestError)
123 123
{
124 124
    parser::beginModule(&mut TEST_FRONTEND, scanner::SourceLoc::String, stmt);
125 -
    parser::advance(&mut TEST_FRONTEND);
125 +
    try! parser::advance(&mut TEST_FRONTEND);
126 126
127 127
    let expr = try parser::parseExpr(&mut TEST_FRONTEND) catch {
128 128
        panic "resolveExprStr: parsing failed";
129 129
    };
130 130
    let diagnostics = try super::resolveExpr(self, expr, &mut TEST_FRONTEND.arena) catch {
lib/std/lang/resolver/tests/structure.rad +59 -4
1 1
//! Resolver tests: union and module declarations, imports, opaque pointers, match patterns, and
2 2
//! slice builtins.
3 3
4 -
use std::mem;
5 -
use std::testing;
6 -
use std::lang::resolver;
7 4
use std::lang::ast;
8 -
use std::lang::types;
5 +
use std::lang::resolver;
9 6
use std::lang::resolver::tests::*;
7 +
use std::lang::types;
8 +
use std::mem;
9 +
use std::testing;
10 10
11 11
// Union tests /////////////////////////////////////////////////////////////////
12 12
13 13
@test unsafe fn testResolveUnionVariantWithoutPayload() throws (testing::TestError) {
14 14
    let mut a = testResolver();
3920 3920
    let error = try expectError(&result);
3921 3921
    let case resolver::ErrorKind::TypeMismatch(_) = error.kind else {
3922 3922
        throw testing::TestError::Failed;
3923 3923
    };
3924 3924
}
3925 +
3926 +
/// Record field limits produce a source diagnostic at the boundary.
3927 +
@test unsafe fn recordFieldLimit() throws (testing::TestError) {
3928 +
    let mut a = testResolver();
3929 +
    let valid = try resolveProgramStr(
3930 +
        &mut a,
3931 +
        "record R { a0: u8, a1: u8, a2: u8, a3: u8, a4: u8, a5: u8, a6: u8, a7: u8, a8: u8, a9: u8, a10: u8, a11: u8, a12: u8, a13: u8, a14: u8, a15: u8, a16: u8, a17: u8, a18: u8, a19: u8, a20: u8, a21: u8, a22: u8, a23: u8, a24: u8, a25: u8, a26: u8, a27: u8, a28: u8, a29: u8, a30: u8, a31: u8 }"
3932 +
    );
3933 +
    try expectNoErrors(&valid);
3934 +
    let mut b = testResolver();
3935 +
    let invalid = try resolveProgramStr(
3936 +
        &mut b,
3937 +
        "record R { a0: u8, a1: u8, a2: u8, a3: u8, a4: u8, a5: u8, a6: u8, a7: u8, a8: u8, a9: u8, a10: u8, a11: u8, a12: u8, a13: u8, a14: u8, a15: u8, a16: u8, a17: u8, a18: u8, a19: u8, a20: u8, a21: u8, a22: u8, a23: u8, a24: u8, a25: u8, a26: u8, a27: u8, a28: u8, a29: u8, a30: u8, a31: u8, a32: u8 }"
3938 +
    );
3939 +
    assert invalid.diagnostics.errors.len == 1;
3940 +
    assert invalid.diagnostics.errors[0].kind
3941 +
        == resolver::ErrorKind::LimitExceeded("too many fields in one record");
3942 +
    for source in [
3943 +
        "record R(u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8);",
3944 +
        "union U { V(u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8, u8) }",
3945 +
    ] {
3946 +
        let mut a = testResolver();
3947 +
        let result = try resolveProgramStr(&mut a, source);
3948 +
        let error = try expectError(&result);
3949 +
        assert error.kind == resolver::ErrorKind::LimitExceeded(
3950 +
            "too many fields in one record"
3951 +
        );
3952 +
    }
3953 +
}
3954 +
3955 +
/// Instances can use traits declared in a parent or a later sibling module.
3956 +
@test unsafe fn instanceTraitModuleOrder() throws (testing::TestError) {
3957 +
    let mut a = testResolver();
3958 +
    let root = try registerModule(
3959 +
        &mut super::MODULE_GRAPH,
3960 +
        nil,
3961 +
        "root",
3962 +
        "mod child; export mod sibling; export trait Visit { fn (&mut Visit) visit(value: u32); }"
3963 +
    );
3964 +
    try registerModule(
3965 +
        &mut super::MODULE_GRAPH,
3966 +
        root,
3967 +
        "child",
3968 +
        "use super::Visit; use super::sibling::Other; record State { value: u32 } instance Visit for State { fn (self: &mut State) visit(value: u32) { set self.value = value; } } instance Other for State { fn (self: &State) value() -> u32 { return self.value; } }"
3969 +
    );
3970 +
    try registerModule(
3971 +
        &mut super::MODULE_GRAPH,
3972 +
        root,
3973 +
        "sibling",
3974 +
        "export trait Other { fn (&Other) value() -> u32; }"
3975 +
    );
3976 +
    let result = try resolveModuleTree(&mut a, root);
3977 +
    try expectNoErrors(&result);
3978 +
    assert a.instances.len == 2;
3979 +
}