Use region references across std and kernel

9879b929ab8861eb6046ed85c6b912cc6ab9a5cdbdda8517d6a7536a536c605b
Formatting functions returned an offset into the caller buffer, and
callers sliced the buffer again. Several lookups copied their result or
returned a raw pointer because a function could not return a borrow.

Use region references for results that borrow from one parameter.
Formatters return the written bytes. Memory helpers provide prefix,
suffix and ASCII trimming operations. IL lookups borrow from the
function, and module lookups return an entry reference. Pass large AST
records to lowering by reference.

Add allocation and allocationMut to check the generation of a backing
reference and return its allocation record. Use these getters in backing
operations. Check the domain first in expose, where either failed check
returns BadHandle.

Assisted-by: Claude:opus-5.5
Assisted-by: Codex:gpt-6
Alexis Sellier committed ago 1 parent 1ca0eb6b
compiler/radiance.rad +33 -29
294 294
    throws (Error)
295 295
{
296 296
    return try resolver::nodeDataStorage(arena, count) catch failure {
297 297
        let mut required: [u8; fmt::U64_STR_LEN] = undefined;
298 298
        let mut available: [u8; fmt::U32_STR_LEN] = undefined;
299 -
        let requiredStart = fmt::formatU64(failure.required, &mut required[..]);
300 -
        let availableStart = fmt::formatU32(failure.available, &mut available[..]);
299 +
        let requiredText = fmt::formatU64(failure.required, &mut required[..]);
300 +
        let availableText = fmt::formatU32(failure.available, &mut available[..]);
301 301
        io::printError("radiance: fatal: resolver metadata arena exhausted; ");
302 302
        io::printError("required ");
303 -
        io::printError(&required[requiredStart ..]);
303 +
        io::printError(requiredText);
304 304
        io::printError(" bytes; available ");
305 -
        io::printError(&available[availableStart ..]);
305 +
        io::printError(availableText);
306 306
        io::printError(" bytes\n");
307 307
        throw Error::Other;
308 308
    };
309 309
}
310 310
397 397
    } else {
398 398
        set moduleId = try package::registerModule(
399 399
            pkg, graph, &mut frontend.pool, path
400 400
        ) catch failure {
401 401
            if let rootId = pkg.rootModuleId; failure == module::ModuleError::InvalidPath {
402 -
                let root = module::entryCopy(graph, rootId)
402 +
                let root = module::entry(graph, rootId)
403 403
                    else panic "processModule: package root is missing";
404 404
                let prefix = module::trimExtension(root.filePath)
405 405
                    else panic "processModule: root extension is invalid";
406 406
                throw error(
407 407
                    &[
851 851
) throws (Error) {
852 852
    let entryPkg = try getEntryPackage(ctx);
853 853
    let rootId = entryPkg.rootModuleId else {
854 854
        throw error(&["no root module found"]);
855 855
    };
856 -
    let rootEntry = module::entryCopy(graph, rootId) else {
857 -
        throw error(&["root module entry not found"]);
858 -
    };
859 -
    let rootAst = rootEntry.ast else {
860 -
        throw error(&["root module has no AST"]);
861 -
    };
862 -
    // Collect test functions from the entry package's modules. The list is
863 -
    // permanent storage in `driverArena`. The graph is still mutable here, so
864 -
    // entries are read through copies.
856 +
    let mut rootAst: *ast::Node = undefined;
865 857
    let mut tests: *mut [testgen::TestDesc] = &mut [];
866 -
    for modIdx in 0 .. graph.entriesLen {
867 -
        if let entry = module::entryCopy(graph, modIdx as u16) {
868 -
            if entry.packageId == entryPkg.id {
869 -
                try testgen::collect(&entry, &mut tests, driverArena) catch {
870 -
                    throw error(
871 -
                        &[
872 -
                            "fatal: test discovery arena exhausted:",
873 -
                            entry.filePath,
874 -
                        ]
875 -
                    );
876 -
                };
858 +
    let g: &'r module::ModuleGraph = &*graph {
859 +
        let rootEntry = module::entry(g, rootId) else {
860 +
            throw error(&["root module entry not found"]);
861 +
        };
862 +
        let ast = rootEntry.ast else {
863 +
            throw error(&["root module has no AST"]);
864 +
        };
865 +
        set rootAst = ast;
866 +
        // Collect test functions from the entry package's modules. The list is
867 +
        // permanent storage in `driverArena`. Each entry is borrowed while its
868 +
        // test declarations are read.
869 +
        for modIdx in 0 .. g.entriesLen {
870 +
            if let entry = module::entry(g, modIdx as u16) {
871 +
                if entry.packageId == entryPkg.id {
872 +
                    try testgen::collect(entry, &mut tests, driverArena) catch {
873 +
                        throw error(
874 +
                            &[
875 +
                                "fatal: test discovery arena exhausted:",
876 +
                                entry.filePath,
877 +
                            ]
878 +
                        );
879 +
                    };
880 +
                }
877 881
            }
878 882
        }
879 883
    }
880 884
    let testCount = tests.len;
881 885
    if testCount == 0 {
882 886
        throw error(&["fatal:", "no test functions found"]);
883 887
    }
884 888
    let mut countBuf: [u8; fmt::U32_STR_LEN] = undefined;
885 -
    let start = fmt::formatU32(testCount, &mut countBuf[..]);
889 +
    let text = fmt::formatU32(testCount, &mut countBuf[..]);
886 890
    io::printError("radiance: ");
887 891
    io::printError(entryPkg.name);
888 892
    io::printError(": found ");
889 -
    io::printError(&countBuf[start ..]);
893 +
    io::printError(text);
890 894
    io::printError(" test(s)\n");
891 895
892 896
    // Synthesize the `@default` function and append to the root module.
893 897
    let fnDecl = synthTestMainFn(&mut ctx.parser.arena, &mut ctx.parser.pool, &tests[..]);
894 898
1118 1122
        throw Error::Other;
1119 1123
    };
1120 1124
    if not resolver::success(&diags) {
1121 1125
        resolver::printer::printDiagnostics(&diags, &res);
1122 1126
        let mut countBuf: [u8; fmt::U32_STR_LEN] = undefined;
1123 -
        let start = fmt::formatU32(diags.errors.len, &mut countBuf[..]);
1127 +
        let text = fmt::formatU32(diags.errors.len, &mut countBuf[..]);
1124 1128
        io::printError("radiance: failed: ");
1125 -
        io::printError(&countBuf[start ..]);
1129 +
        io::printError(text);
1126 1130
        io::printError(" errors\n");
1127 1131
        throw Error::Other;
1128 1132
    }
1129 1133
    return res;
1130 1134
}
kernel/kernel/backing.rad +36 -21
105 105
    set store.records[object.index].accessed = false;
106 106
    exposePut(&mut store.records[object.index].exposures[..], origin.index);
107 107
    return try! slots::commit(&mut store.slots[..], reservation);
108 108
}
109 109
110 -
/// Require a live generation-bearing backing reference.
111 -
fn require(store: &Store, object: abi::Ref) throws (abi::Error) {
110 +
/// The allocation of a live generation-bearing backing reference.
111 +
fn allocation(store: &'r Store, object: abi::Ref) -> &'r Allocation throws (abi::Error) {
112 112
    if not slots::matches(&store.slots[..], object, slots::State::Live) {
113 113
        throw abi::Error::BadHandle;
114 114
    }
115 +
    return &store.records[object.index];
116 +
}
117 +
118 +
/// The allocation of a live generation-bearing backing reference, for update.
119 +
fn allocationMut(store: &'r mut Store, object: abi::Ref) -> &'r mut Allocation
120 +
    throws (abi::Error)
121 +
{
122 +
    if not slots::matches(&store.slots[..], object, slots::State::Live) {
123 +
        throw abi::Error::BadHandle;
124 +
    }
125 +
    return &mut store.records[object.index];
115 126
}
116 127
117 128
/// Record that the allocation was reached through `page.slice`.
118 129
export fn markAccessed(store: &mut Store, object: abi::Ref) throws (abi::Error) {
119 -
    try require(store, object);
120 -
    set store.records[object.index].accessed = true;
130 +
    let a = try allocationMut(store, object);
131 +
    set a.accessed = true;
121 132
}
122 133
123 134
/// Whether the allocation was ever reached through `page.slice`.
124 135
export fn accessed(store: &Store, object: abi::Ref) -> bool throws (abi::Error) {
125 -
    try require(store, object);
126 -
    return store.records[object.index].accessed;
136 +
    return (try allocation(store, object)).accessed;
127 137
}
128 138
129 139
/// Whether the allocation has exactly one page object, so that no split sibling exists.
130 140
export fn sole(store: &Store, object: abi::Ref) -> bool throws (abi::Error) {
131 -
    try require(store, object);
132 -
    return store.records[object.index].pages == 1;
141 +
    return (try allocation(store, object)).pages == 1;
133 142
}
134 143
135 144
/// Add one split page to the allocation's lifetime count.
136 145
export fn retainPage(store: &mut Store, object: abi::Ref) throws (abi::Error) {
137 -
    try require(store, object);
138 -
    if store.records[object.index].pages == 0 {
146 +
    let a = try allocationMut(store, object);
147 +
    if a.pages == 0 {
139 148
        throw abi::Error::BadHandle;
140 149
    }
141 -
    if store.records[object.index].pages == mem::U32_MAX {
150 +
    if a.pages == mem::U32_MAX {
142 151
        throw abi::Error::Exhausted;
143 152
    }
144 -
    set store.records[object.index].pages += 1;
153 +
    set a.pages += 1;
145 154
}
146 155
147 156
/// Record access for a domain for the rest of that domain generation's lifetime.
148 157
export fn expose(store: &mut Store, object: abi::Ref, domain: abi::Ref) throws (abi::Error) {
149 -
    try require(store, object);
150 -
    if store.records[object.index].pages == 0 or not domainLive(store, domain) {
158 +
    // Both failures are `BadHandle`, so the domain check can come first.
159 +
    if not domainLive(store, domain) {
160 +
        throw abi::Error::BadHandle;
161 +
    }
162 +
    let a = try allocationMut(store, object);
163 +
    if a.pages == 0 {
151 164
        throw abi::Error::BadHandle;
152 165
    }
153 -
    if exposeContains(&store.records[object.index].exposures[..], domain.index) {
166 +
    if exposeContains(&a.exposures[..], domain.index) {
154 167
        return;
155 168
    }
156 -
    exposePut(&mut store.records[object.index].exposures[..], domain.index);
157 -
    set store.records[object.index].exposed += 1;
169 +
    exposePut(&mut a.exposures[..], domain.index);
170 +
    set a.exposed += 1;
158 171
}
159 172
160 173
/// Reclaim only when no page object and no domain exposure remains.
161 174
fn reclaim(
162 175
    store: &mut Store,
171 184
    try! slots::release(&mut store.slots[..], object);
172 185
}
173 186
174 187
/// Release one page object after its final handle disappears.
175 188
export fn releasePage(store: &mut Store, object: abi::Ref) throws (abi::Error) {
176 -
    try require(store, object);
177 -
    if store.records[object.index].pages == 0 {
178 -
        throw abi::Error::BadHandle;
189 +
    {
190 +
        let a = try allocationMut(store, object);
191 +
        if a.pages == 0 {
192 +
            throw abi::Error::BadHandle;
193 +
        }
194 +
        set a.pages -= 1;
179 195
    }
180 -
    set store.records[object.index].pages -= 1;
181 196
    reclaim(store, object, frames::release);
182 197
}
183 198
184 199
/// End all exposure while the caller has exclusive access to metadata.
185 200
export fn endDomain(store: &mut Store, domain: abi::Ref) throws (abi::Error) {
kernel/kernel/plic.rad +1 -1
129 129
    let number = registers::read32(device.registers, claim);
130 130
    if number == 0 {
131 131
        return;
132 132
    }
133 133
    assert number <= device.count;
134 -
    let retained = interrupts::claim(irqs, number);
134 +
    interrupts::claim(irqs, number);
135 135
    registers::write32(device.registers, claim, number);
136 136
    enable(device, number, false);
137 137
}
138 138
139 139
/// Deliver retained notifications, rearm consumed sources, and report runnable harts.
lib/std/arch/rv64/asm.rad +2 -4
117 117
                set column += 1;
118 118
            }
119 119
        }
120 120
        let mut buffer: [u8; fmt::U32_STR_LEN] = undefined;
121 121
        io::printError(":");
122 -
        let lineStart = fmt::formatU32(line, &mut buffer[..]);
123 -
        io::printError(&buffer[lineStart ..]);
122 +
        io::printError(fmt::formatU32(line, &mut buffer[..]));
124 123
        io::printError(":");
125 -
        let columnStart = fmt::formatU32(column, &mut buffer[..]);
126 -
        io::printError(&buffer[columnStart ..]);
124 +
        io::printError(fmt::formatU32(column, &mut buffer[..]));
127 125
    }
128 126
    io::printError(": error: ");
129 127
    match error {
130 128
        case Error::Invalid { message, .. } => io::printError(message),
131 129
        case Error::Capacity                => io::printError("assembler storage exhausted"),
lib/std/char.rad +5 -0
1 1
//! ASCII character classification helpers shared across the standard library.
2 2
3 3
@test mod tests;
4 4
5 +
/// Return `true` for ASCII space, tab, line feed, form feed, or carriage return.
6 +
export fn isWhitespace(ch: u8) -> bool {
7 +
    return ch == ' ' or ch == '\t' or ch == '\n' or ch == 0x0c or ch == '\r';
8 +
}
9 +
5 10
/// Return `true` when `ch` is an ASCII digit.
6 11
export fn isDigit(ch: u8) -> bool {
7 12
    return ch >= '0' and ch <= '9';
8 13
}
9 14
lib/std/fmt.rad +31 -32
49 49
    magnitude: u64,
50 50
    /// Radix used by the literal.
51 51
    radix: Radix,
52 52
}
53 53
54 -
/// Write a u32 at the end of the buffer and return its start offset.
55 -
export fn formatU32(val: u32, buffer: &mut [u8]) -> u32 {
54 +
/// Write a u32 at the end of the buffer and return the written bytes.
55 +
export fn formatU32(val: u32, buffer: &'r mut [u8]) -> &'r [u8] {
56 56
    assert buffer.len >= U32_STR_LEN;
57 57
58 58
    let mut x: u32 = val;
59 59
    let mut i: u32 = buffer.len;
60 60
68 68
            set i -= 1;
69 69
            set buffer[i] = '0' + (x % 10) as u8;
70 70
            set x /= 10;
71 71
        }
72 72
    }
73 -
    // Return the offset of the first written byte.
74 -
    return i;
73 +
    // Return the written bytes.
74 +
    return &buffer[i ..];
75 75
}
76 76
77 -
/// Write a i32 at the end of the buffer and return its start offset.
78 -
export fn formatI32(val: i32, buffer: &mut [u8]) -> u32 {
77 +
/// Write a i32 at the end of the buffer and return the written bytes.
78 +
export fn formatI32(val: i32, buffer: &'r mut [u8]) -> &'r [u8] {
79 79
    assert buffer.len >= I32_STR_LEN;
80 80
81 81
    let neg: bool = val < 0;
82 82
    let mut x: u32 = -val as u32 if neg else val as u32;
83 83
    let mut i: u32 = buffer.len;
96 96
        if neg {
97 97
            set i -= 1;
98 98
            set buffer[i] = '-';
99 99
        }
100 100
    }
101 -
    return i;
101 +
    return &buffer[i ..];
102 102
}
103 103
104 -
/// Write a u64 at the end of the buffer and return its start offset.
105 -
export fn formatU64(val: u64, buffer: &mut [u8]) -> u32 {
104 +
/// Write a u64 at the end of the buffer and return the written bytes.
105 +
export fn formatU64(val: u64, buffer: &'r mut [u8]) -> &'r [u8] {
106 106
    assert buffer.len >= U64_STR_LEN;
107 107
108 108
    let mut x: u64 = val;
109 109
    let mut i: u32 = buffer.len;
110 110
116 116
            set i -= 1;
117 117
            set buffer[i] = '0' + (x % 10) as u8;
118 118
            set x /= 10;
119 119
        }
120 120
    }
121 -
    return i;
121 +
    return &buffer[i ..];
122 122
}
123 123
124 -
/// Write a i64 at the end of the buffer and return its start offset.
125 -
export fn formatI64(val: i64, buffer: &mut [u8]) -> u32 {
124 +
/// Write a i64 at the end of the buffer and return the written bytes.
125 +
export fn formatI64(val: i64, buffer: &'r mut [u8]) -> &'r [u8] {
126 126
    assert buffer.len >= I64_STR_LEN;
127 127
128 128
    let neg: bool = val < 0;
129 129
    let mut x: u64 = -val as u64 if neg else val as u64;
130 130
    let mut i: u32 = buffer.len;
140 140
        if neg {
141 141
            set i -= 1;
142 142
            set buffer[i] = '-';
143 143
        }
144 144
    }
145 -
    return i;
145 +
    return &buffer[i ..];
146 146
}
147 147
148 -
/// Write a i8 at the end of the buffer and return its start offset.
149 -
export fn formatI8(val: i8, buffer: &mut [u8]) -> u32 {
148 +
/// Write a i8 at the end of the buffer and return the written bytes.
149 +
export fn formatI8(val: i8, buffer: &'r mut [u8]) -> &'r [u8] {
150 150
    return formatI32(val as i32, buffer);
151 151
}
152 152
153 -
/// Write a i16 at the end of the buffer and return its start offset.
154 -
export fn formatI16(val: i16, buffer: &mut [u8]) -> u32 {
153 +
/// Write a i16 at the end of the buffer and return the written bytes.
154 +
export fn formatI16(val: i16, buffer: &'r mut [u8]) -> &'r [u8] {
155 155
    return formatI32(val as i32, buffer);
156 156
}
157 157
158 -
/// Write a u8 at the end of the buffer and return its start offset.
159 -
export fn formatU8(val: u8, buffer: &mut [u8]) -> u32 {
158 +
/// Write a u8 at the end of the buffer and return the written bytes.
159 +
export fn formatU8(val: u8, buffer: &'r mut [u8]) -> &'r [u8] {
160 160
    return formatU32(val as u32, buffer);
161 161
}
162 162
163 -
/// Write a u16 at the end of the buffer and return its start offset.
164 -
export fn formatU16(val: u16, buffer: &mut [u8]) -> u32 {
163 +
/// Write a u16 at the end of the buffer and return the written bytes.
164 +
export fn formatU16(val: u16, buffer: &'r mut [u8]) -> &'r [u8] {
165 165
    return formatU32(val as u32, buffer);
166 166
}
167 167
168 -
/// Write a bool at the end of the buffer and return its start offset.
169 -
export fn formatBool(val: bool, buffer: &mut [u8]) -> u32 {
168 +
/// Write a bool at the end of the buffer and return the written bytes.
169 +
export fn formatBool(val: bool, buffer: &'r mut [u8]) -> &'r [u8] {
170 170
    assert buffer.len >= BOOL_STR_LEN;
171 171
    if val {
172 172
        let start = buffer.len - 4;
173 173
        try! mem::copy(&mut buffer[start ..], "true");
174 -
        return start;
175 -
    } else {
176 -
        let start = buffer.len - 5;
177 -
        try! mem::copy(&mut buffer[start ..], "false");
178 -
        return start;
174 +
        return &buffer[start ..];
179 175
    }
176 +
    let start = buffer.len - 5;
177 +
    try! mem::copy(&mut buffer[start ..], "false");
178 +
    return &buffer[start ..];
180 179
}
181 180
182 181
/// Convert a single ASCII digit into its numeric value for the given radix.
183 182
export fn digitFromAscii(ch: u8, radix: u32) -> ?u32 {
184 183
    assert radix >= 2 and radix <= MAX_RADIX;
257 256
    }
258 257
    return IntLiteral { text, magnitude: value, radix: radixType };
259 258
}
260 259
261 260
/// Process escape sequences in a raw string, writing the result into `dst`.
262 -
/// Returns the number of bytes written.
263 -
export fn unescapeString(raw: *[u8], dst: &mut [u8]) -> u32 {
261 +
/// Return the written bytes. The destination must have space for the result.
262 +
export fn unescapeString(raw: &[u8], dst: &'r mut [u8]) -> &'r [u8] {
264 263
    let mut i: u32 = 0;
265 264
    let mut j: u32 = 0;
266 265
267 266
    while i < raw.len {
268 267
        if raw[i] == '\\' and i + 1 < raw.len {
272 271
            set dst[j] = raw[i];
273 272
            set i += 1;
274 273
        }
275 274
        set j += 1;
276 275
    }
277 -
    return j;
276 +
    return &dst[.. j];
278 277
}
279 278
280 279
/// Decode escape sequences in `raw` and append the decoded bytes to `out`.
281 280
///
282 281
/// Decoding matches [`unescapeString`]. Returns the grown slice. The decoded
286 285
{
287 286
    let start = out.len;
288 287
    let mut dst = out;
289 288
    // Grow to the raw length, decode in place, then keep only the decoded bytes.
290 289
    try dst.resize(start + raw.len, 0, a);
291 -
    let n = unescapeString(raw, &mut dst[start ..]);
290 +
    let n = unescapeString(raw, &mut dst[start ..]).len;
292 291
    try dst.resize(start + n, 0, a);
293 292
    return dst;
294 293
}
295 294
296 295
/// Parse a single-byte character literal, including the single quotes.
lib/std/io.rad +3 -6
19 19
}
20 20
21 21
/// Write a signed decimal integer to standard output.
22 22
export fn printI32(val: i32) {
23 23
    let mut buffer: [u8; fmt::I32_STR_LEN] = [0; fmt::I32_STR_LEN];
24 -
    let start = fmt::formatI32(val, &mut buffer[..]);
25 -
    print(&buffer[start ..]);
24 +
    print(fmt::formatI32(val, &mut buffer[..]));
26 25
}
27 26
28 27
/// Write an unsigned decimal integer to standard output.
29 28
export fn printU32(val: u32) {
30 29
    let mut buffer: [u8; fmt::U32_STR_LEN] = [0; fmt::U32_STR_LEN];
31 -
    let start = fmt::formatU32(val, &mut buffer[..]);
32 -
    print(&buffer[start ..]);
30 +
    print(fmt::formatU32(val, &mut buffer[..]));
33 31
}
34 32
35 33
/// Write a Boolean value to standard output.
36 34
export fn printBool(val: bool) {
37 35
    let mut buffer: [u8; fmt::BOOL_STR_LEN] = [0; fmt::BOOL_STR_LEN];
38 -
    let start = fmt::formatBool(val, &mut buffer[..]);
39 -
    print(&buffer[start ..]);
36 +
    print(fmt::formatBool(val, &mut buffer[..]));
40 37
}
41 38
42 39
/// Read standard input into the buffer and return the number of bytes read.
43 40
/// Returns zero at end of input or on failure.
44 41
export fn read(buf: &mut [u8]) -> u32 {
lib/std/lang/ast/printer.rad +6 -6
51 51
                set ret = toExpr(a, rt);
52 52
            }
53 53
            let head = "unsafe-fn" if isUnsafe else "fn";
54 54
            let params = nodeListToExprs(a, sig.params);
55 55
            return sexpr::list(a, head, &[
56 -
                sexpr::list(a, "params", params), ret, throwsToExpr(a, sig)
56 +
                sexpr::list(a, "params", params), ret, throwsToExpr(a, &sig)
57 57
            ]);
58 58
        }
59 59
        case super::TypeSig::TraitObject { class, traitName, mutable } => {
60 60
            let head = pointerClassHead(class, "obj", "obj-ref", "unsafe-obj");
61 61
            return sexpr::list(a, head, &[sexpr::sym("mut"), toExpr(a, traitName)])
110 110
    }
111 111
    return sexpr::list(a, "attrs", exprs);
112 112
}
113 113
114 114
/// Convert a throw list to a `throws` expression.
115 -
fn throwsToExpr(a: &heap::Heap, sig: super::FnSig) -> sexpr::Expr {
115 +
fn throwsToExpr(a: &heap::Heap, sig: &super::FnSig) -> sexpr::Expr {
116 116
    return sexpr::list(a, "throws", nodeListToExprs(a, sig.throwList));
117 117
}
118 118
119 119
/// Convert the kind of a pattern match to an expression, or `Null` for the
120 120
/// binding kind.
184 184
        }
185 185
        case super::ProngArm::Else => {
186 186
            return sexpr::block(a, "else", &[guardExpr(a, p.guard)], &[toExpr(a, p.body)]);
187 187
        }
188 188
        case super::ProngArm::Binding(pat) => {
189 -
            if let g = p.guard {
189 +
            if p.guard <> nil {
190 190
                return sexpr::block(a, "let", &[toExpr(a, pat), guardExpr(a, p.guard)], &[
191 191
                    toExpr(a, p.body)
192 192
                ]);
193 193
            }
194 194
            return sexpr::block(a, "bind", &[toExpr(a, pat)], &[toExpr(a, p.body)]);
523 523
        }
524 524
        case super::NodeValue::FnDecl(f) => {
525 525
            let params = sexpr::list(a, "params", nodeListToExprs(a, f.sig.params));
526 526
            let ret = toExprOrNull(a, f.sig.returnType);
527 527
            let attrs = attributesToExpr(a, f.attrs);
528 -
            let thrown = throwsToExpr(a, f.sig);
528 +
            let thrown = throwsToExpr(a, &f.sig);
529 529
            let name = toExpr(a, f.name);
530 530
            if let body = f.body {
531 531
                return sexpr::block(a, "fn", &[name, params, ret, attrs, thrown], &[
532 532
                    toExpr(a, body)
533 533
                ]);
606 606
            return sexpr::list(
607 607
                a,
608 608
                "methodSig",
609 609
                &[
610 610
                    attributes, toExpr(a, receiver), toExpr(a, name), params,
611 -
                    ret, throwsToExpr(a,  sig),
611 +
                    ret, throwsToExpr(a,  &sig),
612 612
                ]
613 613
            );
614 614
        }
615 615
        case super::NodeValue::InstanceDecl { traitName, targetType, methods } => {
616 616
            let children = nodeListToExprs(a, methods);
632 632
                    toExpr(a, receiverType),
633 633
                    toExpr(a, receiverName),
634 634
                    toExpr(a, name),
635 635
                    params,
636 636
                    ret,
637 -
                    throwsToExpr(a, sig),
637 +
                    throwsToExpr(a, &sig),
638 638
                ],
639 639
                &[toExpr(a, body)]
640 640
            );
641 641
        }
642 642
        case super::NodeValue::Align { value } =>
lib/std/lang/il.rad +3 -3
1041 1041
        else => return false,
1042 1042
    }
1043 1043
}
1044 1044
1045 1045
/// Get the argument values of an instruction or switch case of `func`.
1046 -
export fn argVals(func: &Fn, r: ArgRange) -> *[Val] {
1046 +
export fn argVals(func: &'r Fn, r: ArgRange) -> &'r [Val] {
1047 1047
    if r.len == 0 {
1048 -
        return &[];
1048 +
        return &func.vals[.. 0];
1049 1049
    }
1050 1050
    return &func.vals[r.start .. r.start + r.len];
1051 1051
}
1052 1052
1053 1053
/// Get the switch cases of a switch instruction of `func`.
1054 -
export fn switchCases(func: &Fn, r: CaseRange) -> *[SwitchCase] {
1054 +
export fn switchCases(func: &'r Fn, r: CaseRange) -> &'r [SwitchCase] {
1055 1055
    return &func.cases[r.start .. r.start + r.len];
1056 1056
}
1057 1057
1058 1058
/// Number of successors of block `b` of `func`, counting each branch edge. A block that does
1059 1059
/// not end with a jump, branch or switch has none.
lib/std/lang/il/binary/collect.rad +1 -1
99 99
        else                        => {}
100 100
    }
101 101
}
102 102
103 103
/// Collect names from an instruction's variable-length operand sequence.
104 -
fn values(names: &mut Names, owner: *[u8], items: *[il::Val], a: &heap::Heap)
104 +
fn values(names: &mut Names, owner: *[u8], items: &[il::Val], a: &heap::Heap)
105 105
    throws (binary::Error)
106 106
{
107 107
    for item in items {
108 108
        try value(names, owner, item, a);
109 109
    }
lib/std/lang/il/printer.rad +4 -6
156 156
    }
157 157
}
158 158
159 159
/// Write a register as `%n`.
160 160
fn writeReg(out: &mut opaque sexpr::Output, reg: super::Reg) {
161 -
    let mut buffer: [u8; fmt::I32_STR_LEN] = undefined;
162 -
    let start = fmt::formatU32(reg.n, &mut buffer[1 ..]);
163 -
    set buffer[start] = '%';
164 -
    out.write(&buffer[start ..]);
161 +
    let mut buffer: [u8; fmt::U32_STR_LEN] = undefined;
162 +
    out.write("%");
163 +
    out.write(fmt::formatU32(reg.n, &mut buffer[..]));
165 164
}
166 165
167 166
/// Write ` borrows N` for a result that borrows from parameter `N`.
168 167
fn writeBorrow(out: &mut opaque sexpr::Output, borrow: ?u32) {
169 168
    if let index = borrow {
175 174
/// Write a block label: the base followed by the decimal suffix, if any.
176 175
export fn writeLabel(out: &mut opaque sexpr::Output, label: super::BlockLabel) {
177 176
    out.write(label.base);
178 177
    if let n = label.suffix {
179 178
        let mut digits: [u8; fmt::U32_STR_LEN] = undefined;
180 -
        let start = fmt::formatU32(n, &mut digits[..]);
181 -
        out.write(&digits[start ..]);
179 +
        out.write(fmt::formatU32(n, &mut digits[..]));
182 180
    }
183 181
}
184 182
185 183
/// Write a comma-separated argument list in parentheses.
186 184
fn writeArgs(out: &mut opaque sexpr::Output, func: &super::Fn, args: super::ArgRange) {
lib/std/lang/il/verify.rad +12 -6
981 981
    }
982 982
    let erased = SigRef::Table(m.sig);
983 983
    if receiver <> m.receiver or not typeEq(retTy, sigRet(&v.ctx, erased)) {
984 984
        throw fail(v, Rule::Call);
985 985
    }
986 -
    let values = il::argVals(v.func, args);
986 +
    let func = v.func;
987 +
    let values = il::argVals(func, args);
987 988
    if values.len <> sigLen(&v.ctx, erased) + 1 {
988 989
        throw fail(v, Rule::Arity);
989 990
    }
990 991
    for k in 0 .. values.len {
991 992
        if k == receiver {
1154 1155
        throw fail(v, Rule::Null);
1155 1156
    }
1156 1157
    if not typeEq(retTy, sigRet(&v.ctx, f.sig)) {
1157 1158
        throw fail(v, Rule::Call);
1158 1159
    }
1159 -
    let values = il::argVals(v.func, args);
1160 +
    let func = v.func;
1161 +
    let values = il::argVals(func, args);
1160 1162
    if values.len <> sigLen(&v.ctx, f.sig) {
1161 1163
        throw fail(v, Rule::Arity);
1162 1164
    }
1163 1165
    for k in 0 .. values.len {
1164 1166
        try assign(v, values[k], sigParam(&v.ctx, f.sig, k));
1182 1184
1183 1185
/// Check the arguments that a branch passes to block `target`. A comparison with zero
1184 1186
/// can prove that `present` is non-null on this edge.
1185 1187
fn checkEdge(v: &Verifier, target: u32, args: il::ArgRange, present: ?il::Reg) throws (Error) {
1186 1188
    let params = v.func.blocks[target].params;
1187 -
    let values = il::argVals(v.func, args);
1189 +
    let func = v.func;
1190 +
    let values = il::argVals(func, args);
1188 1191
    if values.len <> params.len {
1189 1192
        throw fail(v, Rule::Arity);
1190 1193
    }
1191 1194
    for k in 0 .. values.len {
1192 1195
        let mut s = try operand(v, values[k]);
1445 1448
            try checkEdge(v, elseTarget, elseArgs, elseNonNull);
1446 1449
        }
1447 1450
        case il::Instr::Switch { val, defaultTarget, defaultArgs, cases } => {
1448 1451
            try operand(v, val);
1449 1452
            try checkEdge(v, defaultTarget, defaultArgs, nil);
1450 -
            for branch in il::switchCases(v.func, cases) {
1453 +
            let func = v.func;
1454 +
            for branch in il::switchCases(func, cases) {
1451 1455
                try checkEdge(v, branch.target, branch.args, nil);
1452 1456
            }
1453 1457
        }
1454 1458
        case il::Instr::Ecall { dst, num, a0, a1, a2, a3, buf } => {
1455 1459
            try operand(v, num);
1607 1611
1608 1612
/// Mark the parameters of block `target` that receive foreign arguments.
1609 1613
fn flowEdge(v: &mut Verifier, target: u32, args: il::ArgRange) -> bool {
1610 1614
    let params = v.func.blocks[target].params;
1611 1615
    let mut changed = false;
1612 -
    for val, k in il::argVals(v.func, args) {
1616 +
    let func = v.func;
1617 +
    for val, k in il::argVals(func, args) {
1613 1618
        if flowForeign(v, params[k].value, val) {
1614 1619
            set changed = true;
1615 1620
        }
1616 1621
    }
1617 1622
    return changed;
1671 1676
            let b = flowEdge(v, elseTarget, elseArgs);
1672 1677
            return a or b;
1673 1678
        }
1674 1679
        case il::Instr::Switch { defaultTarget, defaultArgs, cases, .. } => {
1675 1680
            let mut changed = flowEdge(v, defaultTarget, defaultArgs);
1676 -
            for branch in il::switchCases(v.func, cases) {
1681 +
            let func = v.func;
1682 +
            for branch in il::switchCases(func, cases) {
1677 1683
                if flowEdge(v, branch.target, branch.args) {
1678 1684
                    set changed = true;
1679 1685
                }
1680 1686
            }
1681 1687
            return changed;
lib/std/lang/lower.rad +78 -92
664 664
            set state = hashTypeName(self, state, *item);
665 665
            return hashBytes(state, "]");
666 666
        }
667 667
        case resolver::Type::Array(array) => {
668 668
            let mut digits: [u8; U32_DECIMAL_DIGITS] = undefined;
669 -
            let count = fmt::formatU32(array.length, &mut digits[..]);
669 +
            let text = fmt::formatU32(array.length, &mut digits[..]);
670 670
            set state = hashBytes(state, "[");
671 671
            set state = hashTypeName(self, state, *array.item);
672 672
            set state = hashBytes(state, "; ");
673 -
            set state = hashBytes(state, &digits[.. count]);
673 +
            set state = hashBytes(state, text);
674 674
            return hashBytes(state, "]");
675 675
        }
676 676
        case resolver::Type::Optional(inner) => {
677 677
            set state = hashBytes(state, "?");
678 678
            return hashTypeName(self, state, *inner);
1310 1310
                try lowerInstanceDecl(low, node, traitName, targetType, methods, sink);
1311 1311
            }
1312 1312
            case ast::NodeValue::MethodDecl {
1313 1313
                name, receiverName, receiverType, sig, body, attrs
1314 1314
            } => {
1315 -
                if let f = try lowerMethodDecl(low, node, name, receiverName, sig, body) {
1315 +
                if let f = try lowerMethodDecl(low, node, name, receiverName, &sig, body) {
1316 1316
                    try emitFunction(low, f, FnRole::Normal, declLinkage(attrs), sink);
1317 1317
                }
1318 1318
            }
1319 1319
            else => {}
1320 1320
        }
1562 1562
        return nil;
1563 1563
    }
1564 1564
    let case ast::NodeValue::Ident(name) = decl.name.value else {
1565 1565
        throw LowerError::ExpectedIdentifier;
1566 1566
    };
1567 -
    let data = resolver::nodeData(&self.resolver, node);
1568 -
    let case resolver::Type::Fn(fnType) = data.ty else {
1567 +
    let case resolver::Type::Fn(fnType) = resolver::nodeData(&self.resolver, node).ty else {
1569 1568
        throw LowerError::ExpectedFunction;
1570 1569
    };
1571 1570
    let isExtern = checkAttr(decl.attrs, ast::Attribute::Extern);
1572 1571
1573 1572
    // Build qualified function name for multi-module compilation.
1574 1573
    let qualName = qualifyName(self, nil, name);
1575 1574
1576 1575
    // Register function symbol for cross-package call resolution.
1577 -
    if let sym = data.sym {
1576 +
    if let sym = resolver::symbolFor(&self.resolver, node) {
1578 1577
        try registerFnSym(self, sym, qualName);
1579 1578
    }
1580 1579
    try beginFn(self, node, fnType, qualName);
1581 1580
1582 1581
    // If the function returns an aggregate or is throwing, prepend a hidden
1583 1582
    // return parameter. The caller allocates the buffer and passes it
1584 1583
    // as the first argument; the callee writes the return value into it.
1585 1584
    if requiresReturnParam(&self.resolver, fnType) and not isExtern {
1586 1585
        set self.returnReg = nextReg(self);
1587 1586
    }
1588 -
    let lowParams = try lowerParams(self, *fnType, decl.sig.params, nil) catch e {
1587 +
    let lowParams = try lowerParams(self, fnType, decl.sig.params, nil) catch e {
1589 1588
        endFn(self);
1590 1589
        throw e;
1591 1590
    };
1592 1591
    let returnType = try returnTypeOf(self, fnType) catch e {
1593 1592
        endFn(self);
2007 2006
2008 2007
        let case ast::NodeValue::Ident(mName) = name.value else {
2009 2008
            throw LowerError::ExpectedIdentifier;
2010 2009
        };
2011 2010
        let qualName = try instanceMethodName(self, nil, typeName, mName);
2012 -
        let func = try lowerMethod(self, methodNode, qualName, receiverName, sig, body)
2011 +
        let func = try lowerMethod(self, methodNode, qualName, receiverName, &sig, body)
2013 2012
            else continue;
2014 2013
        try emitFunction(self, func, FnRole::Normal, Linkage::Local, sink);
2015 2014
2016 2015
        let method = resolver::findTraitMethod(&self.resolver, traitInfo, mName)
2017 2016
            else panic "lowerInstanceDecl: method not found in trait";
2142 2141
fn lowerMethod(
2143 2142
    self: &mut Lowerer,
2144 2143
    node: *ast::Node,
2145 2144
    qualName: *[u8],
2146 2145
    receiverName: *ast::Node,
2147 -
    sig: ast::FnSig,
2146 +
    sig: &ast::FnSig,
2148 2147
    body: *ast::Node
2149 2148
) -> ?*il::Fn throws (LowerError) {
2150 -
    let data = resolver::nodeData(&self.resolver, node);
2151 -
    let case resolver::Type::Fn(fnType) = data.ty else {
2149 +
    let case resolver::Type::Fn(fnType) = resolver::nodeData(&self.resolver, node).ty else {
2152 2150
        throw LowerError::ExpectedFunction;
2153 2151
    };
2154 -
    let sym = data.sym else throw LowerError::MissingSymbol(node);
2152 +
    let sym = try symOf(self, node);
2155 2153
    try registerFnSym(self, sym, qualName);
2156 2154
2157 2155
    try beginFn(self, node, fnType, qualName);
2158 2156
    if requiresReturnParam(&self.resolver, fnType) {
2159 2157
        set self.returnReg = nextReg(self);
2160 2158
    }
2161 -
    let lowParams = try lowerParams(self, *fnType, sig.params, receiverName) catch e {
2159 +
    let lowParams = try lowerParams(self, fnType, sig.params, receiverName) catch e {
2162 2160
        endFn(self);
2163 2161
        throw e;
2164 2162
    };
2165 2163
    let returnType = try returnTypeOf(self, fnType) catch e {
2166 2164
        endFn(self);
2174 2172
fn lowerMethodDecl(
2175 2173
    self: &mut Lowerer,
2176 2174
    node: *ast::Node,
2177 2175
    name: *ast::Node,
2178 2176
    receiverName: *ast::Node,
2179 -
    sig: ast::FnSig,
2177 +
    sig: &ast::FnSig,
2180 2178
    body: *ast::Node
2181 2179
) -> ?*il::Fn throws (LowerError) {
2182 2180
    let sym = resolver::symbolFor(&self.resolver, node) else throw LowerError::MissingSymbol(node);
2183 2181
    let case ast::NodeValue::Ident(mName) = name.value else throw LowerError::ExpectedIdentifier;
2184 2182
    let meId = resolver::findMethodBySymbol(&self.resolver, sym)
2302 2300
    node: *ast::Node,
2303 2301
    value: *ast::Node,
2304 2302
    readOnly: bool,
2305 2303
    linkage: Linkage
2306 2304
) throws (LowerError) {
2307 -
    let data = resolver::nodeData(&self.resolver, node);
2308 -
    let sym = data.sym else {
2309 -
        throw LowerError::MissingSymbol(node);
2310 -
    };
2311 -
    if data.ty == resolver::Type::Unknown {
2312 -
        throw LowerError::MissingType(node);
2313 -
    }
2314 -
    let layout = resolver::getTypeLayout(&self.resolver, data.ty);
2305 +
    let sym = try symOf(self, node);
2306 +
    let ty = try typeOf(self, node);
2307 +
    let layout = resolver::getTypeLayout(&self.resolver, ty);
2315 2308
    let symName = self.resolver.symbols[*sym].name;
2316 2309
    let qualName = qualifyName(self, nil, symName);
2317 2310
    // The region of a heap: zero-filled bytes that only `slice.grow` carves up. The binary
2318 2311
    // form takes the size of data from its layout. The backend aligns the pool.
2319 2312
    if let case resolver::NodeExtra::StaticHeap(size) =
2320 2313
        resolver::nodeData(&self.resolver, value).extra
2321 2314
    {
2322 -
        let kind = resolver::heapKindOfType(&self.resolver, data.ty) else {
2315 +
        let kind = resolver::heapKindOfType(&self.resolver, ty) else {
2323 2316
            throw LowerError::MissingType(node);
2324 2317
        };
2325 2318
        try addData(
2326 2319
            self,
2327 2320
            il::Data {
2337 2330
            linkage
2338 2331
        );
2339 2332
        return;
2340 2333
    }
2341 2334
    let mut b = dataBuilder();
2342 -
    try lowerConstDataInto(self, value, data.ty, layout.size, qualName, &mut b);
2335 +
    try lowerConstDataInto(self, value, ty, layout.size, qualName, &mut b);
2343 2336
    let result = dataBuilderFinish(b);
2344 2337
2345 2338
    try addData(
2346 2339
        self,
2347 2340
        il::Data {
2348 2341
            name: qualName,
2349 2342
            size: layout.size,
2350 2343
            alignment: layout.alignment,
2351 -
            layout: try layoutOf(self, data.ty),
2344 +
            layout: try layoutOf(self, ty),
2352 2345
            readOnly,
2353 2346
            heap: nil,
2354 2347
            isZeroInit: not readOnly and result.zeroInit,
2355 2348
            values: result.values,
2356 2349
        },
2843 2836
    prefix: *[u8],
2844 2837
    count: u32,
2845 2838
    namespace: *[u8]
2846 2839
) -> *[u8] throws (LowerError) {
2847 2840
    let mut digits: [u8; fmt::U32_STR_LEN] = undefined;
2848 -
    let start = fmt::formatU32(count, &mut digits[..]);
2841 +
    let text = fmt::formatU32(count, &mut digits[..]);
2849 2842
    let mut suffix: *mut [u8] = &mut [];
2850 -
    try suffix.reserve(digits.len - start, self.resolver.arena) catch {
2843 +
    try suffix.extend(text, self.resolver.arena) catch {
2851 2844
        throw LowerError::AllocationFailed;
2852 2845
    };
2853 -
    for c in &digits[start ..] {
2854 -
        try suffix.append(c, self.resolver.arena) catch {
2855 -
            throw LowerError::AllocationFailed;
2856 -
        };
2857 -
    }
2858 2846
    let segments = [prefix, namespace, suffix];
2859 2847
2860 2848
    return try buildSegmentedName(self, &segments[..]);
2861 2849
}
2862 2850
2915 2903
2916 2904
/// Compare two data items for structural equality.
2917 2905
/// Unlike raw byte comparison, this correctly ignores padding bytes in unions.
2918 2906
fn dataItemEq(a: il::DataItem, b: il::DataItem) -> bool {
2919 2907
    match a {
2920 -
        case il::DataItem::Val { typ: aTyp, val: aVal } =>
2908 +
        case il::DataItem::Val { typ: aTyp, val: aVal } => {
2921 2909
            if let case il::DataItem::Val { typ: bTyp, val: bVal } = b {
2922 2910
                return aTyp == bTyp and aVal == bVal;
2923 -
            } else {
2924 -
                return false;
2925 -
            },
2926 -
        case il::DataItem::Sym(aPtr) =>
2911 +
            }
2912 +
        }
2913 +
        case il::DataItem::Sym(aPtr) => {
2927 2914
            if let case il::DataItem::Sym(bPtr) = b {
2928 2915
                return mem::eq(aPtr, bPtr);
2929 -
            } else {
2930 -
                return false;
2931 -
            },
2932 -
        case il::DataItem::Fn(aName) =>
2916 +
            }
2917 +
        }
2918 +
        case il::DataItem::Fn(aName) => {
2933 2919
            if let case il::DataItem::Fn(bName) = b {
2934 2920
                return mem::eq(aName, bName);
2935 -
            } else {
2936 -
                return false;
2937 -
            },
2938 -
        case il::DataItem::Str(aStr) =>
2921 +
            }
2922 +
        }
2923 +
        case il::DataItem::Str(aStr) => {
2939 2924
            if let case il::DataItem::Str(bStr) = b {
2940 2925
                return mem::eq(aStr, bStr);
2941 -
            } else {
2942 -
                return false;
2943 -
            },
2944 -
        case il::DataItem::Undef =>
2926 +
            }
2927 +
        }
2928 +
        case il::DataItem::Undef => {
2945 2929
            if let case il::DataItem::Undef = b {
2946 2930
                return true;
2947 -
            } else {
2948 -
                return false;
2949 -
            },
2931 +
            }
2932 +
        }
2950 2933
    }
2934 +
    return false;
2951 2935
}
2952 2936
2953 2937
/// Compare two data value slices for structural equality.
2954 2938
fn dataValuesEq(a: &[il::DataValue], b: &[il::DataValue]) -> bool {
2955 2939
    if a.len <> b.len {
4620 4604
4621 4605
/// Lower function parameters. Declares variables for each parameter.
4622 4606
/// When a receiver name is passed, we're handling a trait method.
4623 4607
fn lowerParams(
4624 4608
    self: &mut Lowerer,
4625 -
    fnType: resolver::FnType,
4609 +
    fnType: &resolver::FnType,
4626 4610
    astParams: *[*ast::Node],
4627 4611
    receiverName: ?*ast::Node
4628 4612
) -> *[il::Param] throws (LowerError) {
4629 4613
    let offset: u32 = 1 if self.returnReg <> nil else 0;
4630 4614
    let totalLen = fnType.paramTypes.len as u32 + offset;
5024 5008
            }
5025 5009
        }
5026 5010
        match pattern.value {
5027 5011
            // Compound variant patterns like `Variant { a, b }`.
5028 5012
            case ast::NodeValue::RecordLit(lit) =>
5029 -
                try bindRecordPatternFields(self, subject, pattern, lit, failBlock),
5013 +
                try bindRecordPatternFields(self, subject, pattern, &lit, failBlock),
5030 5014
            // Positional record patterns like `S(x, y)`. Union variant calls
5031 5015
            // have a union subject and were bound above.
5032 5016
            case ast::NodeValue::Call(call) => {
5033 5017
                if let recInfo = resolver::getRecord(&self.resolver, subject.type) {
5034 5018
                    if subject.by == resolver::MatchBy::Value and isScalarRecord(
5089 5073
/// Bind fields from a record pattern.
5090 5074
fn bindRecordPatternFields(
5091 5075
    self: &mut Lowerer,
5092 5076
    subject: &MatchSubject,
5093 5077
    pattern: *ast::Node,
5094 -
    lit: ast::RecordLit,
5078 +
    lit: &ast::RecordLit,
5095 5079
    failBlock: ?BlockId
5096 5080
) throws (LowerError) {
5097 5081
    // No fields to bind (e.g., `{ .. }`).
5098 5082
    if lit.fields.len == 0 {
5099 5083
        return;
5109 5093
                );
5110 5094
            }
5111 5095
            return;
5112 5096
        }
5113 5097
        let base = try emitValToReg(self, subject.val);
5114 -
        try bindNestedRecordFields(self, base, lit, recInfo, subject.by, failBlock, nil);
5098 +
        try bindNestedRecordFields(self, base, lit, &recInfo, subject.by, failBlock, nil);
5115 5099
        return;
5116 5100
    }
5117 5101
    // Get the union type info from the subject.
5118 5102
    let case MatchSubjectKind::Union(unionInfo) = subject.kind
5119 5103
        else panic "bindRecordPatternFields: expected union subject";
5130 5114
5131 5115
    // Get the payload base pointer which points to the record within the tagged union.
5132 5116
    let base = try emitValToReg(self, subject.val);
5133 5117
    if not unionInfo.mixed {
5134 5118
        let payloadBase = try emitPtrOffset(self, base, unionInfo.valOffset as i32);
5135 -
        try bindNestedRecordFields(self, payloadBase, lit, recInfo, subject.by, failBlock, nil);
5119 +
        try bindNestedRecordFields(self, payloadBase, lit, &recInfo, subject.by, failBlock, nil);
5136 5120
        return;
5137 5121
    }
5138 5122
    let read = VariantRead { info: unionInfo, tag: variantTag };
5139 -
    try bindNestedRecordFields(self, base, lit, recInfo, subject.by, failBlock, read);
5123 +
    try bindNestedRecordFields(self, base, lit, &recInfo, subject.by, failBlock, read);
5140 5124
}
5141 5125
5142 5126
/// Bind a single record field to a pattern variable, with support for nested
5143 5127
/// pattern tests that branch to `failBlock` on mismatch.
5144 5128
fn bindFieldVariable(
5185 5169
                set derefType = *target;
5186 5170
            }
5187 5171
            let recInfo = resolver::getRecord(&self.resolver, derefType)
5188 5172
                else throw LowerError::ExpectedRecord;
5189 5173
5190 -
            try bindNestedRecordFields(self, nestedBase, lit, recInfo, matchBy, failBlock, nil);
5174 +
            try bindNestedRecordFields(self, nestedBase, &lit, &recInfo, matchBy, failBlock, nil);
5191 5175
        }
5192 5176
        else => {
5193 5177
            // Nested pattern requiring a test (union variant scope access, literal, etc).
5194 5178
            try emitNestedFieldTest(self, binding, base, fieldInfo, matchBy, failBlock);
5195 5179
        }
5340 5324
/// Bind variables from a nested record literal pattern. The record is the payload of the variant
5341 5325
/// `read` of the union at `base` when there is one, and then field offsets are from the payload.
5342 5326
fn bindNestedRecordFields(
5343 5327
    self: &mut Lowerer,
5344 5328
    base: il::Reg,
5345 -
    lit: ast::RecordLit,
5346 -
    recInfo: resolver::RecordType,
5329 +
    lit: &ast::RecordLit,
5330 +
    recInfo: &resolver::RecordType,
5347 5331
    matchBy: resolver::MatchBy,
5348 5332
    failBlock: ?BlockId,
5349 5333
    read: ?VariantRead
5350 5334
) throws (LowerError) {
5351 5335
    for fieldNode in lit.fields {
7096 7080
/// Lower a record literal expression. Handles both plain records and union variant
7097 7081
/// record literals like `Union::Variant { field: value }`.
7098 7082
fn lowerRecordLit(
7099 7083
    self: &mut Lowerer,
7100 7084
    node: *ast::Node,
7101 -
    lit: ast::RecordLit
7085 +
    lit: &ast::RecordLit
7102 7086
) -> il::Val throws (LowerError) {
7103 7087
    let typ = try typeOf(self, node);
7104 7088
    if let recInfo = recordInfoFromType(&self.resolver, typ) {
7105 7089
        if isScalarRecord(&self.resolver, typ) {
7106 7090
            // A scalar record is lowered as its only field. A missing or
7442 7426
    }
7443 7427
}
7444 7428
7445 7429
/// Lower a union constructor call like `Union::Variant(...)`.
7446 7430
fn lowerUnionCtor(
7447 -
    self: &mut Lowerer, node: *ast::Node, sym: resolver::SymbolId, call: ast::Call
7431 +
    self: &mut Lowerer, node: *ast::Node, sym: resolver::SymbolId, call: &ast::Call
7448 7432
) -> il::Val throws (LowerError) {
7449 7433
    let unionTy = try typeOf(self, node);
7450 7434
    let case resolver::SymbolData::Variant { type: payloadType, index, .. } =
7451 7435
        self.resolver.symbols[*sym].data else {
7452 7436
        throw LowerError::ExpectedVariant;
9225 9209
    // A discarded result uses `Void`.
9226 9210
    // Check for trait method dispatch or standalone method call.
9227 9211
    let mut resVal: il::Val = undefined;
9228 9212
    let callNodeExtra = resolver::extraFor(&self.resolver, t.expr);
9229 9213
    if let case resolver::NodeExtra::SliceAppend { elemType } = callNodeExtra {
9230 -
        set resVal = try lowerSliceAppend(self, callExpr, elemType);
9214 +
        set resVal = try lowerSliceAppend(self, &callExpr, elemType);
9231 9215
    } else if let case resolver::NodeExtra::SliceReserve { elemType } = callNodeExtra {
9232 -
        set resVal = try lowerSliceReserve(self, callExpr, elemType);
9216 +
        set resVal = try lowerSliceReserve(self, &callExpr, elemType);
9233 9217
    } else if let case resolver::NodeExtra::SliceResize { elemType } = callNodeExtra {
9234 -
        set resVal = try lowerSliceResize(self, callExpr, elemType);
9218 +
        set resVal = try lowerSliceResize(self, &callExpr, elemType);
9235 9219
    } else if let case resolver::NodeExtra::SliceExtend { elemType } = callNodeExtra {
9236 -
        set resVal = try lowerSliceExtend(self, callExpr, elemType);
9220 +
        set resVal = try lowerSliceExtend(self, &callExpr, elemType);
9237 9221
    } else if let case resolver::NodeExtra::AllocNew { elemType } = callNodeExtra {
9238 -
        set resVal = try lowerAllocNew(self, callExpr, elemType);
9222 +
        set resVal = try lowerAllocNew(self, &callExpr, elemType);
9239 9223
    } else if let case resolver::NodeExtra::TraitMethodCall {
9240 9224
        traitInfo, methodIndex
9241 9225
    } =
9242 9226
        callNodeExtra
9243 9227
    {
9244 -
        set resVal = try lowerTraitMethodCall(self, t.expr, callExpr, traitInfo, methodIndex);
9228 +
        set resVal = try lowerTraitMethodCall(self, t.expr, &callExpr, traitInfo, methodIndex);
9245 9229
    } else if let case resolver::NodeExtra::MethodCall { method } = callNodeExtra {
9246 -
        set resVal = try lowerMethodCall(self, t.expr, callExpr, method);
9230 +
        set resVal = try lowerMethodCall(self, t.expr, &callExpr, method);
9247 9231
    } else {
9248 -
        set resVal = try lowerCall(self, t.expr, callExpr);
9232 +
        set resVal = try lowerCall(self, t.expr, &callExpr);
9249 9233
    }
9250 9234
    let base = try emitValToReg(self, resVal); // The result value.
9251 9235
    let tagReg = try resultTagReg(self, base); // The result tag.
9252 9236
9253 9237
    let okBlock = try createBlock(self, "ok");   // Block if success.
9638 9622
///
9639 9623
/// The slice header changes only after allocation succeeds. The allocator is a heap handle.
9640 9624
/// Zero-sized elements need no allocation.
9641 9625
fn lowerSliceAppend(
9642 9626
    self: &mut Lowerer,
9643 -
    call: ast::Call,
9627 +
    call: &ast::Call,
9644 9628
    elemType: *resolver::Type
9645 9629
) -> il::Val throws (LowerError) {
9646 9630
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
9647 9631
        else throw LowerError::MissingMetadata;
9648 9632
    let case resolver::Type::Fn(info) = try typeOf(self, call.callee)
9749 9733
/// exactly `len + count` elements, copies the existing elements, and changes
9750 9734
/// the slice header only after the allocation succeeds.
9751 9735
/// Zero-sized elements need no allocation.
9752 9736
fn lowerSliceReserve(
9753 9737
    self: &mut Lowerer,
9754 -
    call: ast::Call,
9738 +
    call: &ast::Call,
9755 9739
    elemType: *resolver::Type
9756 9740
) -> il::Val throws (LowerError) {
9757 9741
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
9758 9742
        else throw LowerError::MissingMetadata;
9759 9743
    let case resolver::Type::Fn(info) = try typeOf(self, call.callee)
9904 9888
///     @shrink:
9905 9889
///       store newLen
9906 9890
///     return success result
9907 9891
fn lowerSliceResize(
9908 9892
    self: &mut Lowerer,
9909 -
    call: ast::Call,
9893 +
    call: &ast::Call,
9910 9894
    elemType: *resolver::Type
9911 9895
) -> il::Val throws (LowerError) {
9912 9896
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
9913 9897
        else throw LowerError::MissingMetadata;
9914 9898
    let case resolver::Type::Fn(info) = try typeOf(self, call.callee)
10011 9995
///       store newLen
10012 9996
///       slice.copy the snapshot to slice[len..newLen]
10013 9997
///     return success result
10014 9998
fn lowerSliceExtend(
10015 9999
    self: &mut Lowerer,
10016 -
    call: ast::Call,
10000 +
    call: &ast::Call,
10017 10001
    elemType: *resolver::Type
10018 10002
) -> il::Val throws (LowerError) {
10019 10003
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
10020 10004
        else throw LowerError::MissingMetadata;
10021 10005
    let case resolver::Type::Fn(info) = try typeOf(self, call.callee)
10136 10120
        else try lowerPlaceAddress(self, parent);
10137 10121
    return try emitValToReg(self, handle);
10138 10122
}
10139 10123
10140 10124
/// Lower `scratch.reset()`.
10141 -
fn lowerScratchReset(self: &mut Lowerer, call: ast::Call) -> il::Val throws (LowerError) {
10125 +
fn lowerScratchReset(self: &mut Lowerer, call: &ast::Call) -> il::Val throws (LowerError) {
10142 10126
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
10143 10127
        else throw LowerError::MissingMetadata;
10144 10128
    let handle = try lowerHeapReceiver(self, access.parent);
10145 10129
    try emit(self, il::Instr::HeapReset { heap: il::Val::Reg(handle) });
10146 10130
    return il::Val::Undef;
10157 10141
///     if the heap is exhausted: return the allocation error
10158 10142
///     store the value
10159 10143
///     return pointer to the element
10160 10144
fn lowerAllocNew(
10161 10145
    self: &mut Lowerer,
10162 -
    call: ast::Call,
10146 +
    call: &ast::Call,
10163 10147
    elemType: *resolver::Type
10164 10148
) -> il::Val throws (LowerError) {
10165 10149
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
10166 10150
        else throw LowerError::MissingMetadata;
10167 10151
    let case resolver::Type::Fn(info) = try typeOf(self, call.callee)
10207 10191
///
10208 10192
/// Each element moves with a copy of its layout between two checked element addresses,
10209 10193
/// and the shorter slice is a subslice of the slice, so slot elements stay typed.
10210 10194
fn lowerSliceDelete(
10211 10195
    self: &mut Lowerer,
10212 -
    call: ast::Call,
10196 +
    call: &ast::Call,
10213 10197
    elemType: *resolver::Type
10214 10198
) throws (LowerError) {
10215 10199
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
10216 10200
        else throw LowerError::MissingMetadata;
10217 10201
10264 10248
/// The header is copied to new stack storage before the place is overwritten.
10265 10249
/// The place then stores the empty slice, which is the same value as `&mut []`:
10266 10250
/// the empty slice pointer, length 0, and capacity 0. No loop or allocation is needed.
10267 10251
fn lowerSliceTake(
10268 10252
    self: &mut Lowerer,
10269 -
    call: ast::Call,
10253 +
    call: &ast::Call,
10270 10254
    elemType: *resolver::Type
10271 10255
) -> il::Val throws (LowerError) {
10272 10256
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
10273 10257
        else throw LowerError::MissingMetadata;
10274 10258
10301 10285
10302 10286
/// Lower a call expression, which may be a function call or type constructor.
10303 10287
fn lowerCallOrCtor(
10304 10288
    self: &mut Lowerer,
10305 10289
    node: *ast::Node,
10306 -
    call: ast::Call
10290 +
    call: &ast::Call
10307 10291
) -> il::Val throws (LowerError) {
10308 10292
    let nodeData = resolver::extraFor(&self.resolver, node);
10309 10293
10310 10294
    // Check for slice method dispatch.
10311 10295
    if let case resolver::NodeExtra::SliceAppend { elemType } = nodeData {
10365 10349
///     call <retTy> %ret %fn(%data, args...)
10366 10350
///
10367 10351
fn lowerTraitMethodCall(
10368 10352
    self: &mut Lowerer,
10369 10353
    node: *ast::Node,
10370 -
    call: ast::Call,
10354 +
    call: &ast::Call,
10371 10355
    traitInfo: resolver::TraitId,
10372 10356
    methodIndex: u32
10373 10357
) -> il::Val throws (LowerError) {
10374 10358
    // Method calls look like field accesses.
10375 10359
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
10615 10599
///     call <retTy> %ret @Type::method(&obj, args...)
10616 10600
///
10617 10601
fn lowerMethodCall(
10618 10602
    self: &mut Lowerer,
10619 10603
    node: *ast::Node,
10620 -
    call: ast::Call,
10604 +
    call: &ast::Call,
10621 10605
    methodId: resolver::MethodId
10622 10606
) -> il::Val throws (LowerError) {
10623 10607
    let method = self.resolver.methods[*methodId];
10624 10608
    let case ast::NodeValue::FieldAccess(access) = call.callee.value
10625 10609
        else throw LowerError::MissingMetadata;
10645 10629
    }
10646 10630
    return try emitCallValue(self, CallTarget::Fn(il::Val::FnAddr(qualName)), fnInfo, args);
10647 10631
}
10648 10632
10649 10633
/// Check if a call is to a compiler intrinsic and lower it directly.
10650 -
fn lowerIntrinsicCall(self: &mut Lowerer, call: ast::Call) -> ?il::Val throws (LowerError) {
10634 +
fn lowerIntrinsicCall(self: &mut Lowerer, call: &ast::Call) -> ?il::Val throws (LowerError) {
10651 10635
    // Get the callee symbol and check if it's marked as an intrinsic.
10652 10636
    let sym = resolver::symbolFor(&self.resolver, call.callee) else {
10653 10637
        // Expressions or function pointers may not have an associated symbol.
10654 10638
        return nil;
10655 10639
    };
10690 10674
}
10691 10675
10692 10676
/// Lower an ecall intrinsic: `ecall(num, a0, a1, a2, a3) -> i64`. An intrinsic whose name
10693 10677
/// starts with `ecall` can take a sixth argument, a pointer to the buffer that the kernel
10694 10678
/// writes. The size of the buffer is the size of the type that the pointer addresses.
10695 -
fn lowerEcall(self: &mut Lowerer, call: ast::Call) -> il::Val throws (LowerError) {
10679 +
fn lowerEcall(self: &mut Lowerer, call: &ast::Call) -> il::Val throws (LowerError) {
10696 10680
    if call.args.len <> 5 and call.args.len <> 6 {
10697 10681
        throw LowerError::InvalidArgCount;
10698 10682
    }
10699 10683
    let num = try lowerExpr(self, call.args[0]);
10700 10684
    let a0 = try lowerExpr(self, call.args[1]);
10715 10699
    return il::Val::Reg(dst);
10716 10700
}
10717 10701
10718 10702
/// Lower a page slice intrinsic: `pageSlice(handle, write, out) -> i64`, where `write` is a
10719 10703
/// constant and `out` points to the slice that receives the memory of the handle.
10720 -
fn lowerPageSlice(self: &mut Lowerer, call: ast::Call) -> il::Val throws (LowerError) {
10704 +
fn lowerPageSlice(self: &mut Lowerer, call: &ast::Call) -> il::Val throws (LowerError) {
10721 10705
    if call.args.len <> 3 {
10722 10706
        throw LowerError::InvalidArgCount;
10723 10707
    }
10724 10708
    let handle = try lowerExpr(self, call.args[0]);
10725 10709
    let flag = resolver::constValueEntry(&self.resolver, call.args[1])
10738 10722
    return il::Val::Reg(err);
10739 10723
}
10740 10724
10741 10725
/// Lower a page heap intrinsic: `pageHeap(handle, out) -> i64`, where `out` points to the
10742 10726
/// heap reference that receives the heap of the Page.
10743 -
fn lowerPageHeap(self: &mut Lowerer, call: ast::Call) -> il::Val throws (LowerError) {
10727 +
fn lowerPageHeap(self: &mut Lowerer, call: &ast::Call) -> il::Val throws (LowerError) {
10744 10728
    if call.args.len <> 2 {
10745 10729
        throw LowerError::InvalidArgCount;
10746 10730
    }
10747 10731
    // The slot holds a heap, so the argument points to a heap or an optional one.
10748 10732
    let outType = try effectiveType(self, call.args[1]);
10763 10747
10764 10748
    return il::Val::Reg(err);
10765 10749
}
10766 10750
10767 10751
/// Lower an ebreak intrinsic: `ebreak()`.
10768 -
fn lowerEbreak(self: &mut Lowerer, call: ast::Call) -> il::Val throws (LowerError) {
10752 +
fn lowerEbreak(self: &mut Lowerer, call: &ast::Call) -> il::Val throws (LowerError) {
10769 10753
    if call.args.len <> 0 {
10770 10754
        throw LowerError::InvalidArgCount;
10771 10755
    }
10772 10756
    try emit(self, il::Instr::Ebreak);
10773 10757
10774 10758
    return il::Val::Undef;
10775 10759
}
10776 10760
10777 10761
/// Lower `memoryFence()`.
10778 -
fn lowerMemoryFence(self: &mut Lowerer, call: ast::Call) -> il::Val throws (LowerError) {
10762 +
fn lowerMemoryFence(self: &mut Lowerer, call: &ast::Call) -> il::Val throws (LowerError) {
10779 10763
    if call.args.len <> 0 {
10780 10764
        throw LowerError::InvalidArgCount;
10781 10765
    }
10782 10766
    try emit(self, il::Instr::MemoryFence);
10783 10767
    return il::Val::Undef;
10806 10790
    }
10807 10791
    return try lowerExpr(self, callee);
10808 10792
}
10809 10793
10810 10794
/// Lower a function call expression.
10811 -
fn lowerCall(self: &mut Lowerer, node: *ast::Node, call: ast::Call) -> il::Val throws (LowerError) {
10795 +
fn lowerCall(self: &mut Lowerer, node: *ast::Node, call: &ast::Call) -> il::Val
10796 +
    throws (LowerError)
10797 +
{
10812 10798
    // Check for intrinsic calls before normal call lowering.
10813 10799
    if let intrinsicVal = try lowerIntrinsicCall(self, call) {
10814 10800
        return intrinsicVal;
10815 10801
    }
10816 10802
    let calleeTy = try typeOf(self, call.callee);
11042 11028
            } else {
11043 11029
                throw LowerError::NilInNonOptional;
11044 11030
            }
11045 11031
        }
11046 11032
        case ast::NodeValue::RecordLit(lit) => {
11047 -
            set val = try lowerRecordLit(self, node, lit);
11033 +
            set val = try lowerRecordLit(self, node, &lit);
11048 11034
        }
11049 11035
        case ast::NodeValue::AddressOf(addr) => {
11050 11036
            set val = try lowerAddressOf(self, node, addr);
11051 11037
        }
11052 11038
        case ast::NodeValue::Deref(target) => {
11063 11049
        }
11064 11050
        case ast::NodeValue::BuiltinCall { kind, args } => {
11065 11051
            set val = try lowerBuiltinCall(self, node, kind, args);
11066 11052
        }
11067 11053
        case ast::NodeValue::Call(call) => {
11068 -
            set val = try lowerCallOrCtor(self, node, call);
11054 +
            set val = try lowerCallOrCtor(self, node, &call);
11069 11055
        }
11070 11056
        case ast::NodeValue::Try(t) => {
11071 11057
            set val = try lowerTry(self, t, try typeOf(self, node));
11072 11058
        }
11073 11059
        case ast::NodeValue::FieldAccess(access) => {
12029 12015
        else                        => panic "ilType: type cannot be lowered",
12030 12016
    }
12031 12017
}
12032 12018
12033 12019
/// Lower one fixed-width MMIO operation without exposing a pointer value.
12034 -
fn lowerDevice(self: &mut Lowerer, call: ast::Call, typ: il::Type, writing: bool) -> il::Val
12020 +
fn lowerDevice(self: &mut Lowerer, call: &ast::Call, typ: il::Type, writing: bool) -> il::Val
12035 12021
    throws (LowerError)
12036 12022
{
12037 12023
    let mut count: u32 = 2;
12038 12024
    if writing {
12039 12025
        set count = 3;
lib/std/lang/lower/tests.rad +24 -0
153 153
    try testing::expect(word == referenceHash("u32"));
154 154
    try testing::expect(first <> second);
155 155
    try testing::expect(again == first);
156 156
}
157 157
158 +
/// Array type hashes include the decimal length in the canonical spelling.
159 +
@test unsafe fn testArrayTypeNameHash() throws (testing::TestError) {
160 +
    let res = tests::testResolver();
161 +
    let mut low = super::lowerer(
162 +
        res,
163 +
        module::ModuleTable { entries: &[] },
164 +
        "test",
165 +
        heap::over(&mut FN_STORAGE[..]),
166 +
        super::LowerOptions {
167 +
            debug: false, buildTest: false, tableScope: super::TableScope::Program
168 +
        }
169 +
    );
170 +
    let byte = resolver::allocType(&mut low.resolver, resolver::Type::U8);
171 +
    let lengths: [u32; 4] = [0, 1, 10, 4294967295];
172 +
    let names: [*[u8]; 4] = ["[u8; 0]", "[u8; 1]", "[u8; 10]", "[u8; 4294967295]"];
173 +
    for length, i in lengths {
174 +
        let ty = resolver::Type::Array(resolver::ArrayType { item: byte, length });
175 +
        let tag = try super::getOrAssignErrorTag(&mut low, ty) catch {
176 +
            throw testing::TestError::Failed;
177 +
        };
178 +
        assert tag == referenceHash(names[i]);
179 +
    }
180 +
}
181 +
158 182
/// A mixed union case copies the pointer field without a second copy of the union.
159 183
@test unsafe fn testMixedUnionFieldSnapshot() throws (testing::TestError) {
160 184
    let mut res = tests::testResolver();
161 185
    let result = try tests::resolveProgramStr(
162 186
        &mut res,
lib/std/lang/module.rad +41 -45
112 112
/// The table shares storage with the consumed graph.
113 113
export fn freeze(graph: ModuleGraph) -> ModuleTable {
114 114
    return ModuleTable { entries: &graph.entries[.. graph.entriesLen] };
115 115
}
116 116
117 -
/// Return a copy of the entry registered under `id`, or `nil` if none is.
118 -
/// Pre-freeze code reads entries through copies. A pointer into the graph
119 -
/// storage would alias later registrations.
120 -
export fn entryCopy(graph: &ModuleGraph, id: u16) -> ?ModuleEntry {
117 +
/// Borrow the entry registered under `id`, or return `nil` if none exists.
118 +
/// The graph remains borrowed while the result is in use.
119 +
export fn entry(graph: &'r ModuleGraph, id: u16) -> ?&'r ModuleEntry {
121 120
    if not isValidId(graph, id) {
122 121
        return nil;
123 122
    }
124 -
    return graph.entries[id as u32];
123 +
    return &graph.entries[id as u32];
125 124
}
126 125
127 126
/// Register a root module residing at `path` for a package.
128 127
export fn registerRoot(
129 128
    graph: &mut ModuleGraph, pool: &mut strings::Pool, packageId: u16, filePath: *[u8]
337 336
    graph: &mut ModuleGraph, pool: &mut strings::Pool, packageId: u16, rootId: ?u16, filePath: *[u8]
338 337
) -> u16 throws (ModuleError) {
339 338
    let root = rootId else {
340 339
        return try registerRoot(graph, pool, packageId, filePath);
341 340
    };
342 -
    let rootEntry = entryCopy(graph, root) else {
343 -
        panic "registerFromPath: root is missing from storage";
344 -
    };
345 -
    // Strip the base directory from the file path.
346 -
    let baseDir = &rootEntry.filePath[.. rootEntry.dirLen];
347 -
    let pathSuffix = mem::stripPrefix(baseDir, filePath) else {
348 -
        throw ModuleError::InvalidPath;
349 -
    };
350 -
    // Parse the stripped path into components.
351 -
    let mut parts: [*[u8]; MAX_MODULE_PATH_DEPTH] = [""; MAX_MODULE_PATH_DEPTH];
352 -
    let partsLen = parsePath(pathSuffix, &mut parts[..]) else {
353 -
        throw ModuleError::InvalidPath;
354 -
    };
355 -
    if partsLen == 0 {
356 -
        throw ModuleError::InvalidPath;
357 -
    }
358 -
    // Strip the directory named after the root file from the parsed components. The
359 -
    // root module may carry another name, such as its package name.
360 -
    let rootStem = try basenameSlice(rootEntry.filePath);
361 -
    let prefixLen = stripPathPrefix(&[rootStem], &parts[.. partsLen]) else {
362 -
        throw ModuleError::InvalidPath;
363 -
    };
364 -
    if prefixLen == partsLen {
365 -
        throw ModuleError::InvalidPath;
366 -
    }
367 -
    let childName = parts[partsLen - 1];
368 -
369 -
    // Navigate through all but the last segment to find the parent.
341 +
    let mut childName: *[u8] = &[];
370 342
    let mut parentId = root;
371 -
    for part in &parts[prefixLen .. partsLen - 1] {
372 -
        let childId = findChildIn(&graph.entries[.. graph.entriesLen], parentId, part) else {
373 -
            throw ModuleError::MissingParent;
343 +
    let g: &'r ModuleGraph = &*graph {
344 +
        let rootEntry = entry(g, root) else {
345 +
            panic "registerFromPath: root is missing from storage";
374 346
        };
375 -
        set parentId = childId;
347 +
        // Strip the base directory from the file path.
348 +
        let baseDir = &rootEntry.filePath[.. rootEntry.dirLen];
349 +
        if not mem::startsWith(filePath, baseDir) {
350 +
            throw ModuleError::InvalidPath;
351 +
        }
352 +
        // Parse the stripped path into components.
353 +
        let mut parts: [*[u8]; MAX_MODULE_PATH_DEPTH] = [""; MAX_MODULE_PATH_DEPTH];
354 +
        let partsLen = parsePath(&filePath[baseDir.len ..], &mut parts[..]) else {
355 +
            throw ModuleError::InvalidPath;
356 +
        };
357 +
        if partsLen == 0 {
358 +
            throw ModuleError::InvalidPath;
359 +
        }
360 +
        // Strip the directory named after the root file from the parsed components. The
361 +
        // root module may carry another name, such as its package name.
362 +
        let rootStem = try basenameSlice(rootEntry.filePath);
363 +
        let prefixLen = stripPathPrefix(&[rootStem], &parts[.. partsLen]) else {
364 +
            throw ModuleError::InvalidPath;
365 +
        };
366 +
        if prefixLen == partsLen {
367 +
            throw ModuleError::InvalidPath;
368 +
        }
369 +
        set childName = parts[partsLen - 1];
370 +
371 +
        // Navigate through all but the last segment to find the parent.
372 +
        for part in &parts[prefixLen .. partsLen - 1] {
373 +
            let childId = findChildIn(&g.entries[.. g.entriesLen], parentId, part) else {
374 +
                throw ModuleError::MissingParent;
375 +
            };
376 +
            set parentId = childId;
377 +
        }
376 378
    }
377 379
    return try registerChild(graph, pool, parentId, childName, filePath);
378 380
}
379 381
380 382
/// Allocate a fresh entry in the graph and return its identifier.
453 455
}
454 456
455 457
/// Trim the `.rad` extension from `path` if present.
456 458
/// Returns the path slice without the extension.
457 459
export fn trimExtension(path: *[u8]) -> ?*[u8] {
458 -
    if path.len < SOURCE_EXT.len {
460 +
    if not mem::endsWith(path, SOURCE_EXT) {
459 461
        return nil;
460 462
    }
461 -
    let extStart = path.len - SOURCE_EXT.len;
462 -
    for ext, i in SOURCE_EXT {
463 -
        if path[extStart + i] <> ext {
464 -
            return nil;
465 -
        }
466 -
    }
467 -
    return &path[.. extStart];
463 +
    return &path[.. path.len - SOURCE_EXT.len];
468 464
}
469 465
470 466
/// Check a path prefix and return its segment count.
471 467
fn stripPathPrefix(prefix: &[*[u8]], path: &[*[u8]]) -> ?u32 {
472 468
    if prefix.len == 0 {
lib/std/lang/module/printer.rad +3 -3
5 5
use std::lang::sexpr;
6 6
use std::mem::heap;
7 7
8 8
/// Format a u32 as a string allocated from `a`. Returns "?" if `a` is full.
9 9
fn formatId(a: &heap::Heap, id: u32) -> *[u8] {
10 +
    let mut buffer: [u8; fmt::U32_STR_LEN] = undefined;
10 11
    let mut digits: *mut [u8] = &mut [];
11 -
    try digits.resize(fmt::U32_STR_LEN, 0, a) catch {
12 +
    try digits.extend(fmt::formatU32(id, &mut buffer[..]), a) catch {
12 13
        return "?";
13 14
    };
14 -
    let start = fmt::formatU32(id, &mut digits[..]);
15 -
    return &digits[start ..];
15 +
    return &digits[..];
16 16
}
17 17
18 18
/// Convert a module state into an S-expression symbol.
19 19
fn stateToExpr(state: super::ModuleState) -> sexpr::Expr {
20 20
    match state {
lib/std/lang/module/tests.rad +57 -52
37 37
    let rootId = try super::registerFromPath(
38 38
        &mut graph, &mut STRING_POOL, 0, nil, "src/root.rad"
39 39
    ) catch {
40 40
        throw testing::TestError::Failed;
41 41
    };
42 -
    let root = super::entryCopy(&graph, rootId) else {
43 -
        throw testing::TestError::Failed;
44 -
    };
45 -
    try expectPathSegments(&root, &["root"]);
46 -
42 +
    {
43 +
        let root = super::entry(&graph, rootId) else {
44 +
            throw testing::TestError::Failed;
45 +
        };
46 +
        try expectPathSegments(root, &["root"]);
47 +
    }
47 48
    // First child.
48 49
    let firstId = try super::registerFromPath(
49 50
        &mut graph, &mut STRING_POOL, 0, rootId, "src/root/first.rad"
50 51
    ) catch {
51 52
        throw testing::TestError::Failed;
52 53
    };
53 -
    let first = super::entryCopy(&graph, firstId) else {
54 -
        throw testing::TestError::Failed;
55 -
    };
56 -
    try expectSliceEq(first.filePath, "src/root/first.rad");
57 -
    try expectSliceEq(first.name, "first");
58 -
    try expectPathSegments(&first, &["root", "first"]);
59 -
54 +
    {
55 +
        let first = super::entry(&graph, firstId) else {
56 +
            throw testing::TestError::Failed;
57 +
        };
58 +
        try expectSliceEq(first.filePath, "src/root/first.rad");
59 +
        try expectSliceEq(first.name, "first");
60 +
        try expectPathSegments(first, &["root", "first"]);
61 +
    }
60 62
    // Second child.
61 63
    let secondId = try super::registerFromPath(
62 64
        &mut graph, &mut STRING_POOL, 0, rootId, "src/root/second.rad"
63 65
    ) catch {
64 66
        throw testing::TestError::Failed;
65 67
    };
66 -
    let second = super::entryCopy(&graph, secondId) else {
68 +
    let second = super::entry(&graph, secondId) else {
67 69
        throw testing::TestError::Failed;
68 70
    };
69 71
    try expectSliceEq(second.filePath, "src/root/second.rad");
70 72
    try expectSliceEq(second.name, "second");
71 -
    try expectPathSegments(&second, &["root", "second"]);
73 +
    try expectPathSegments(second, &["root", "second"]);
72 74
73 -
    let parent = super::entryCopy(&graph, rootId) else {
75 +
    let parent = super::entry(&graph, rootId) else {
74 76
        throw testing::TestError::Failed;
75 77
    };
76 78
    try testing::expect(graph.entriesLen == 3);
77 79
    try testing::expect(parent.childrenLen == 2);
78 -
    try testing::expect(super::childAt(&parent, 0) == firstId);
79 -
    try testing::expect(super::childAt(&parent, 1) == secondId);
80 +
    try testing::expect(super::childAt(parent, 0) == firstId);
81 +
    try testing::expect(super::childAt(parent, 1) == secondId);
80 82
}
81 83
82 84
@test unsafe fn testRegisterChildReusesExisting() throws (testing::TestError) {
83 85
    set STRING_POOL = strings::pool(&mut STRING_TABLE[..]);
84 86
    unsafe static storage: [super::ModuleEntry; 4] = undefined;
99 101
    ) catch {
100 102
        throw testing::TestError::Failed;
101 103
    };
102 104
    try testing::expect(firstId == secondId);
103 105
104 -
    let parent = super::entryCopy(&graph, rootId) else {
106 +
    let parent = super::entry(&graph, rootId) else {
105 107
        throw testing::TestError::Failed;
106 108
    };
107 109
    try testing::expect(graph.entriesLen == 2);
108 110
    try testing::expect(parent.childrenLen == 1);
109 111
}
164 166
    let stdId = try super::registerFromPath(
165 167
        &mut graph, &mut STRING_POOL, 0, nil, "lib/std.rad"
166 168
    ) catch {
167 169
        throw testing::TestError::Failed;
168 170
    };
169 -
    let std = super::entryCopy(&graph, stdId) else {
170 -
        throw testing::TestError::Failed;
171 -
    };
172 -
    try expectSliceEq(std.filePath, "lib/std.rad");
173 -
    try expectSliceEq(&std.filePath[.. std.dirLen], "lib/");
174 -
    try expectPathSegments(&std, &["std"]);
175 -
171 +
    {
172 +
        let std = super::entry(&graph, stdId) else {
173 +
            throw testing::TestError::Failed;
174 +
        };
175 +
        try expectSliceEq(std.filePath, "lib/std.rad");
176 +
        try expectSliceEq(&std.filePath[.. std.dirLen], "lib/");
177 +
        try expectPathSegments(std, &["std"]);
178 +
    }
176 179
    // Register child of root.
177 180
    let langId = try super::registerFromPath(
178 181
        &mut graph, &mut STRING_POOL, 0, stdId, "lib/std/lang.rad"
179 182
    ) catch {
180 183
        throw testing::TestError::Failed;
181 184
    };
182 -
    let lang = super::entryCopy(&graph, langId) else {
183 -
        throw testing::TestError::Failed;
184 -
    };
185 -
    try expectSliceEq(lang.filePath, "lib/std/lang.rad");
186 -
    try expectSliceEq(lang.name, "lang");
187 -
    try expectSliceEq(&lang.filePath[.. lang.dirLen], "lib/std/");
188 -
    try expectPathSegments(&lang, &["std", "lang"]);
189 -
185 +
    {
186 +
        let lang = super::entry(&graph, langId) else {
187 +
            throw testing::TestError::Failed;
188 +
        };
189 +
        try expectSliceEq(lang.filePath, "lib/std/lang.rad");
190 +
        try expectSliceEq(lang.name, "lang");
191 +
        try expectSliceEq(&lang.filePath[.. lang.dirLen], "lib/std/");
192 +
        try expectPathSegments(lang, &["std", "lang"]);
193 +
    }
190 194
    // Register grandchild.
191 195
    let parserId = try super::registerFromPath(
192 196
        &mut graph, &mut STRING_POOL, 0, stdId, "lib/std/lang/parser.rad"
193 197
    ) catch {
194 198
        throw testing::TestError::Failed;
195 199
    };
196 -
    let parser = super::entryCopy(&graph, parserId) else {
200 +
    let parser = super::entry(&graph, parserId) else {
197 201
        throw testing::TestError::Failed;
198 202
    };
199 203
    try expectSliceEq(parser.filePath, "lib/std/lang/parser.rad");
200 204
    try expectSliceEq(parser.name, "parser");
201 205
    try expectSliceEq(&parser.filePath[.. parser.dirLen], "lib/std/lang/");
202 -
    try expectPathSegments(&parser, &["std", "lang", "parser"]);
206 +
    try expectPathSegments(parser, &["std", "lang", "parser"]);
203 207
204 208
    // Verify parent-child relationships on the final graph state.
205 -
    let stdEnd = super::entryCopy(&graph, stdId) else {
209 +
    let stdEnd = super::entry(&graph, stdId) else {
206 210
        throw testing::TestError::Failed;
207 211
    };
208 -
    let langEnd = super::entryCopy(&graph, langId) else {
212 +
    let langEnd = super::entry(&graph, langId) else {
209 213
        throw testing::TestError::Failed;
210 214
    };
211 -
    let parserEnd = super::entryCopy(&graph, parserId) else {
215 +
    let parserEnd = super::entry(&graph, parserId) else {
212 216
        throw testing::TestError::Failed;
213 217
    };
214 218
    try testing::expect(graph.entriesLen == 3);
215 219
    try testing::expect(stdEnd.childrenLen == 1);
216 -
    try testing::expect(super::childAt(&stdEnd, 0) == langId);
220 +
    try testing::expect(super::childAt(stdEnd, 0) == langId);
217 221
    try testing::expect(langEnd.childrenLen == 1);
218 -
    try testing::expect(super::childAt(&langEnd, 0) == parserId);
222 +
    try testing::expect(super::childAt(langEnd, 0) == parserId);
219 223
    try testing::expect(parserEnd.childrenLen == 0);
220 224
}
221 225
222 226
@test unsafe fn testRegisterFromPathMissingParent() throws (testing::TestError) {
223 227
    set STRING_POOL = strings::pool(&mut STRING_TABLE[..]);
266 270
        throw testing::TestError::Failed;
267 271
    };
268 272
    // Verify root module was registered with correct ID.
269 273
    try testing::expect(rootId == 0);
270 274
271 -
    let root = super::entryCopy(&graph, rootId) else {
275 +
    let root = super::entry(&graph, rootId) else {
272 276
        throw testing::TestError::Failed;
273 277
    };
274 278
    try expectSliceEq(root.name, "std");
275 279
    try expectSliceEq(root.filePath, "lib/std.rad");
276 -
    try expectPathSegments(&root, &["std"]);
280 +
    try expectPathSegments(root, &["std"]);
277 281
}
278 282
279 283
@test unsafe fn testRegisterFromPathIgnoresLeadingDirectories() throws (testing::TestError) {
280 284
    set STRING_POOL = strings::pool(&mut STRING_TABLE[..]);
281 285
    unsafe static storage: [super::ModuleEntry; 8] = undefined;
292 296
    let langId = try super::registerFromPath(
293 297
        &mut graph, &mut STRING_POOL, 0, rootId, "src/pkg/root/lang.rad"
294 298
    ) catch {
295 299
        throw testing::TestError::Failed;
296 300
    };
297 -
    let lang = super::entryCopy(&graph, langId) else {
298 -
        throw testing::TestError::Failed;
299 -
    };
300 -
    try expectSliceEq(lang.name, "lang");
301 -
    try expectPathSegments(&lang, &["root", "lang"]);
302 -
301 +
    {
302 +
        let lang = super::entry(&graph, langId) else {
303 +
            throw testing::TestError::Failed;
304 +
        };
305 +
        try expectSliceEq(lang.name, "lang");
306 +
        try expectPathSegments(lang, &["root", "lang"]);
307 +
    }
303 308
    let parserId = try super::registerFromPath(
304 309
        &mut graph, &mut STRING_POOL, 0, rootId, "src/pkg/root/lang/parser.rad"
305 310
    ) catch {
306 311
        throw testing::TestError::Failed;
307 312
    };
308 -
    let parser = super::entryCopy(&graph, parserId) else {
313 +
    let parser = super::entry(&graph, parserId) else {
309 314
        throw testing::TestError::Failed;
310 315
    };
311 316
    try expectSliceEq(parser.name, "parser");
312 -
    try expectPathSegments(&parser, &["root", "lang", "parser"]);
317 +
    try expectPathSegments(parser, &["root", "lang", "parser"]);
313 318
}
314 319
315 320
/// A graph with no registered modules freezes into an empty table.
316 321
@test unsafe fn testFreezeEmptyGraph() throws (testing::TestError) {
317 322
    unsafe static storage: [super::ModuleEntry; 2] = undefined;
366 371
        &mut graph, &mut STRING_POOL, root, "shared", "elsewhere/source.rad"
367 372
    );
368 373
    let nested = try! super::registerAtPath(
369 374
        &mut graph, &mut STRING_POOL, root, "shared/nested_1", "other/value.rad"
370 375
    );
371 -
    let entry = super::entryCopy(&graph, nested) else panic;
376 +
    let entry = super::entry(&graph, nested) else panic;
372 377
    assert entry.parent == shared;
373 378
    assert mem::eq(entry.filePath, "other/value.rad");
374 379
    assert mem::eq(entry.name, "nested_1");
375 -
    try expectPathSegments(&entry, &["root", "shared", "nested_1"]);
380 +
    try expectPathSegments(entry, &["root", "shared", "nested_1"]);
376 381
}
377 382
378 383
/// Invalid and duplicate mappings fail without registering a module.
379 384
@test unsafe fn testInvalidMappedPaths() throws (testing::TestError) {
380 385
    set STRING_POOL = strings::pool(&mut STRING_TABLE[..]);
lib/std/lang/parser.rad +1 -4
1126 1126
1127 1127
/// Parse a statement block with the specified unsafe permission.
1128 1128
fn parseBlockBody(p: &mut Parser, isUnsafe: bool) -> *ast::Node
1129 1129
    throws (ParseError)
1130 1130
{
1131 -
    let start = p.current;
1132 -
1133 1131
    if not consume(p, scanner::TokenKind::LBrace) {
1134 1132
        throw failParsing(p, "expected `{`");
1135 1133
    }
1136 1134
    let statements = try parseStmtsUntil(
1137 1135
        p, scanner::TokenKind::RBrace, INITIAL_STATEMENTS
1211 1209
}
1212 1210
1213 1211
/// Write a decimal integer to standard error.
1214 1212
fn printU32Error(val: u32) {
1215 1213
    let mut buffer: [u8; fmt::U32_STR_LEN] = [0; fmt::U32_STR_LEN];
1216 -
    let start = fmt::formatU32(val, &mut buffer[..]);
1217 -
    io::printError(&buffer[start ..]);
1214 +
    io::printError(fmt::formatU32(val, &mut buffer[..]));
1218 1215
}
1219 1216
1220 1217
/// Print all errors that have been collected during parsing to standard error.
1221 1218
export fn printErrors(p: &Parser) {
1222 1219
    for i in 0 .. p.errors.count {
lib/std/lang/pretty.rad +13 -13
1591 1591
/// Format the result of a function type: `-> T` and `throws (E)`.
1592 1592
fn signatureTail(
1593 1593
    a: &heap::Heap,
1594 1594
    p: &mut Printer,
1595 1595
    kids: &mut *mut [layout::Child],
1596 -
    sig: ast::FnSig,
1596 +
    sig: &ast::FnSig,
1597 1597
    forced: bool
1598 1598
) throws (alloc::AllocError) {
1599 1599
    if let returnType = sig.returnType {
1600 1600
        try operator(a, kids, SPACE, "->");
1601 1601
        try put(a, p, kids, SPACE, returnType, Ctx::Normal);
1672 1672
                try softList(
1673 1673
                    a, p, parens(node), fnSig.params, Ctx::Normal, expr
1674 1674
                )
1675 1675
            );
1676 1676
            let thrown = marked(p, node, ast::BrokenSite::Throws);
1677 -
            try signatureTail(a, p, &mut kids, fnSig, thrown);
1677 +
            try signatureTail(a, p, &mut kids, &fnSig, thrown);
1678 1678
        }
1679 1679
        case ast::TypeSig::TraitObject { class, traitName, mutable } => {
1680 1680
            try operator(a, &mut kids, NONE, pointerPrefix(class, mutable));
1681 1681
            try keyword(a, &mut kids, NONE, "opaque");
1682 1682
            try put(a, p, &mut kids, SPACE, traitName, Ctx::Normal);
1822 1822
            }
1823 1823
            try assigned(a, p, &mut kids, node, "=", l.value);
1824 1824
        }
1825 1825
        case ast::NodeValue::LetElse(l) => {
1826 1826
            let mut head: *mut [layout::Child] = &mut [];
1827 -
            try patternMatch(a, p, &mut head, l.pattern, GuardStyle::If);
1827 +
            try patternMatch(a, p, &mut head, &l.pattern, GuardStyle::If);
1828 1828
            try add(a, &mut kids, NONE, try group(a, nil, head));
1829 1829
            if let case ast::NodeValue::Block(b) = l.elseBranch.value; not b.isUnsafe {
1830 1830
                try keyword(a, &mut kids, SPACE, "else");
1831 1831
                try blockBody(a, p, &mut kids, l.elseBranch, SPACE);
1832 1832
            } else {
2077 2077
    return SOFT_SPACE;
2078 2078
}
2079 2079
2080 2080
/// Placement of the brace after the pattern match of a header. A guard breaks
2081 2081
/// the header before it, so the brace then goes on its own line.
2082 -
fn patternBrace(pm: ast::PatternMatch) -> layout::Placement {
2082 +
fn patternBrace(pm: &ast::PatternMatch) -> layout::Placement {
2083 2083
    if pm.guard <> nil {
2084 2084
        return SOFT_SPACE;
2085 2085
    }
2086 2086
    return bracePlacement(pm.scrutinee);
2087 2087
}
2089 2089
/// Append `let`, a pattern, `=`, and a value, as in `if let` and `let-else`.
2090 2090
fn patternMatch(
2091 2091
    a: &heap::Heap,
2092 2092
    p: &mut Printer,
2093 2093
    kids: &mut *mut [layout::Child],
2094 -
    pm: ast::PatternMatch,
2094 +
    pm: &ast::PatternMatch,
2095 2095
    style: GuardStyle
2096 2096
) throws (alloc::AllocError) {
2097 2097
    try spaced(a, kids, "let", layout::Role::Keyword);
2098 2098
    let mut ctx = Ctx::Condition;
2099 2099
    match pm.kind {
2176 2176
                set thenBranch = i.thenBranch;
2177 2177
                set elseBranch = i.elseBranch;
2178 2178
            }
2179 2179
            case ast::NodeValue::IfLet(i) => {
2180 2180
                try patternMatch(
2181 -
                    a, p, &mut head, i.pattern, GuardStyle::Semicolon
2181 +
                    a, p, &mut head, &i.pattern, GuardStyle::Semicolon
2182 2182
                );
2183 -
                set at = patternBrace(i.pattern);
2183 +
                set at = patternBrace(&i.pattern);
2184 2184
                set thenBranch = i.thenBranch;
2185 2185
                set elseBranch = i.elseBranch;
2186 2186
            }
2187 2187
            else => panic "ifStmt: if expected",
2188 2188
        }
2235 2235
            set loopBody = w.body;
2236 2236
            set elseBranch = w.elseBranch;
2237 2237
        }
2238 2238
        case ast::NodeValue::WhileLet(w) => {
2239 2239
            try spaced(a, &mut head, "while", layout::Role::Keyword);
2240 -
            try patternMatch(a, p, &mut head, w.pattern, GuardStyle::Semicolon);
2241 -
            set at = patternBrace(w.pattern);
2240 +
            try patternMatch(a, p, &mut head, &w.pattern, GuardStyle::Semicolon);
2241 +
            set at = patternBrace(&w.pattern);
2242 2242
            set loopBody = w.body;
2243 2243
            set elseBranch = w.elseBranch;
2244 2244
        }
2245 2245
        case ast::NodeValue::For(f) => {
2246 2246
            try spaced(a, &mut head, "for", layout::Role::Keyword);
2455 2455
        &mut head,
2456 2456
        NONE,
2457 2457
        try softList(a, p, parens(node), sig.params, Ctx::Normal, paramItem)
2458 2458
    );
2459 2459
    let mut tail: *mut [layout::Child] = &mut [];
2460 -
    try signatureTail(a, p, &mut tail, sig, marked(
2460 +
    try signatureTail(a, p, &mut tail, &sig, marked(
2461 2461
        p, node, ast::BrokenSite::Throws
2462 2462
    ));
2463 2463
    let stacked = isStacked(p, node);
2464 2464
    let forced = marked(p, node, ast::BrokenSite::List);
2465 2465
    let mut kids: *mut [layout::Child] = &mut [];
2471 2471
        let mut at = SPACE;
2472 2472
        if sig.throwList.len > 0 {
2473 2473
            set at = SOFT_SPACE;
2474 2474
        }
2475 2475
        try punct(a, &mut tail, at, brace(p, blk.statements.len, b));
2476 -
        let text = try signature(a, sig, stacked, forced, head, tail);
2476 +
        let text = try signature(a, &sig, stacked, forced, head, tail);
2477 2477
        try add(a, &mut kids, NONE, text);
2478 2478
        set p.fnDepth += 1;
2479 2479
        try body(a, p, &mut kids, blk.statements, b, stmt);
2480 2480
        set p.fnDepth -= 1;
2481 2481
    } else {
2482 2482
        try punct(a, &mut tail, NONE, ";");
2483 -
        let text = try signature(a, sig, stacked, forced, head, tail);
2483 +
        let text = try signature(a, &sig, stacked, forced, head, tail);
2484 2484
        try add(a, &mut kids, NONE, text);
2485 2485
    }
2486 2486
    return try group(a, node, kids);
2487 2487
}
2488 2488
2505 2505
/// source has that form, and the signature prefers it. Otherwise it prefers
2506 2506
/// one line, then the stacked form. The parameters break only when neither
2507 2507
/// first line fits, or when `forced`: the source broke them.
2508 2508
fn signature(
2509 2509
    a: &heap::Heap,
2510 -
    sig: ast::FnSig,
2510 +
    sig: &ast::FnSig,
2511 2511
    stacked: bool,
2512 2512
    forced: bool,
2513 2513
    head: *[layout::Child],
2514 2514
    tail: *[layout::Child]
2515 2515
) -> *layout::Layout throws (alloc::AllocError) {
lib/std/lang/resolver.rad +50 -50
1262 1262
1263 1263
    return &mut entries[0];
1264 1264
}
1265 1265
1266 1266
/// Returns an error, if any, associated with the given node.
1267 -
fn errorForNode(self: &Resolver, node: *ast::Node) -> ?Error {
1267 +
fn errorForNode(self: &'r Resolver, node: *ast::Node) -> ?&'r Error {
1268 1268
    for i in 0 .. self.errors.len {
1269 -
        let err = self.errors.entries[i];
1269 +
        let err = &self.errors.entries[i];
1270 1270
        if err.node == node {
1271 1271
            return err;
1272 1272
        }
1273 1273
    }
1274 1274
    return nil;
1420 1420
export fn success(diag: &Diagnostics) -> bool {
1421 1421
    return diag.errors.len == 0;
1422 1422
}
1423 1423
1424 1424
/// Retrieve an error diagnostic by index, if present.
1425 -
export fn errorAt(errs: &[Error], index: u32) -> ?Error {
1425 +
export fn errorAt(errs: &'r [Error], index: u32) -> ?&'r Error {
1426 1426
    if index >= errs.len {
1427 1427
        return nil;
1428 1428
    }
1429 -
    return errs[index];
1429 +
    return &errs[index];
1430 1430
}
1431 1431
1432 1432
/// Record an error diagnostic and return an error sentinel suitable for throwing.
1433 1433
fn emitError(self: &mut Resolver, node: ?*ast::Node, kind: ErrorKind) -> ResolveError {
1434 1434
    // If our error list is full, just return an error without recording it.
1602 1602
    return name;
1603 1603
}
1604 1604
1605 1605
/// Associate a resolved symbol with an AST node.
1606 1606
fn setNodeSymbol(self: &mut Resolver, node: *ast::Node, symbol: SymbolId) {
1607 -
    if let existingSym = self.nodeData.entries[node.id].sym {
1607 +
    if self.nodeData.entries[node.id].sym <> nil {
1608 1608
        panic "setNodeSymbol: a symbol is already associated with this node";
1609 1609
    }
1610 1610
    set self.nodeData.entries[node.id].sym = symbol;
1611 1611
}
1612 1612
1729 1729
    }
1730 1730
    return false;
1731 1731
}
1732 1732
1733 1733
/// Get the resolver metadata for a node.
1734 -
export fn nodeData(self: &Resolver, node: *ast::Node) -> NodeData {
1735 -
    return self.nodeData.entries[node.id];
1734 +
export fn nodeData(self: &'r Resolver, node: *ast::Node) -> &'r NodeData {
1735 +
    return &self.nodeData.entries[node.id];
1736 1736
}
1737 1737
1738 1738
/// Get the type for a node, or `nil` if unknown.
1739 1739
export fn typeFor(self: &Resolver, node: *ast::Node) -> ?Type {
1740 1740
    let ty = self.nodeData.entries[node.id].ty;
3406 3406
        }
3407 3407
        case ast::NodeValue::InstanceDecl { methods, .. } => {
3408 3408
            try resolveInstanceMethodBodies(self, methods);
3409 3409
        }
3410 3410
        case ast::NodeValue::MethodDecl { receiverName, receiverType, sig, body, .. } => {
3411 -
            try resolveMethodBody(self, node, receiverName, receiverType, sig, body);
3411 +
            try resolveMethodBody(self, node, receiverName, receiverType, &sig, body);
3412 3412
        }
3413 3413
        else => {
3414 3414
            // FIXME: This allows module-level statements that should
3415 3415
            // normally only be valid inside function bodies. We currently
3416 3416
            // need this because of how tests are written, but it should
3513 3513
                case SymbolData::Pending { .. }, SymbolData::Region =>
3514 3514
                    panic "visit: unresolved declaration",
3515 3515
            }
3516 3516
        }
3517 3517
        case ast::NodeValue::Call(call) =>
3518 -
            return try resolveCall(self, node, call, CallCtx::Normal),
3518 +
            return try resolveCall(self, node, &call, CallCtx::Normal),
3519 3519
        case ast::NodeValue::FieldAccess(access) =>
3520 3520
            return try resolveFieldAccess(self, node, access),
3521 3521
        case ast::NodeValue::BinOp(binop) => return try resolveBinOp(self, node, binop),
3522 3522
        case ast::NodeValue::Block(block) => return try resolveBlock(self, node, block),
3523 3523
        case ast::NodeValue::Let(decl)    => return try resolveLet(self, node, decl),
3554 3554
        case ast::NodeValue::MatchProng(_)    => panic "visit: `MatchProng` not handled here",
3555 3555
        case ast::NodeValue::LetElse(letElse) => return try resolveLetElse(self, node, letElse),
3556 3556
        case ast::NodeValue::BuiltinCall { kind, args } =>
3557 3557
            return try resolveBuiltinCall(self, node, kind, args),
3558 3558
        case ast::NodeValue::Assign(assign)  => return try resolveAssign(self, node, assign),
3559 -
        case ast::NodeValue::RecordLit(lit)  => return try resolveRecordLit(self, node, lit, hint),
3559 +
        case ast::NodeValue::RecordLit(lit)  => return try resolveRecordLit(self, node, &lit, hint),
3560 3560
        case ast::NodeValue::ArrayLit(items) => return try resolveArrayLit(self, node, items, hint),
3561 3561
        case ast::NodeValue::ArrayRepeatLit(lit) =>
3562 3562
            return try resolveArrayRepeat(self, node, lit, hint),
3563 3563
        case ast::NodeValue::Subscript { container, index } =>
3564 3564
            return try resolveSubscript(self, node, container, index),
4094 4094
/// Check that constructor arguments match record fields.
4095 4095
///
4096 4096
/// Verifies argument count matches field count, and that each argument is
4097 4097
/// assignable to its corresponding field type.
4098 4098
fn checkRecordConstructorArgs(
4099 -
    self: &mut Resolver, node: *ast::Node, args: *[*ast::Node], recInfo: RecordType
4099 +
    self: &mut Resolver, node: *ast::Node, args: *[*ast::Node], recInfo: &RecordType
4100 4100
)
4101 4101
    throws (ResolveError)
4102 4102
{
4103 4103
    try checkRecordArity(self, args, recInfo, node);
4104 4104
    for arg, i in args {
4107 4107
    }
4108 4108
}
4109 4109
4110 4110
/// Check that the argument count of a constructor pattern or call matches the record field count.
4111 4111
fn checkRecordArity(
4112 -
    self: &mut Resolver, args: *[*ast::Node], recInfo: RecordType, pattern: *ast::Node
4112 +
    self: &mut Resolver, args: *[*ast::Node], recInfo: &RecordType, pattern: *ast::Node
4113 4113
) throws (ResolveError) {
4114 4114
    if args.len <> recInfo.fields.len {
4115 4115
        throw emitError(self, pattern, ErrorKind::RecordFieldCountMismatch(CountMismatch {
4116 4116
            expected: recInfo.fields.len as u32,
4117 4117
            actual: args.len,
4729 4729
        borrow: nil,
4730 4730
    };
4731 4731
    // The body reuses the function scope, so the regions and parameters of
4732 4732
    // the signature stay in scope there.
4733 4733
    enterFn(self, node, &fnType);
4734 -
    try resolveFnSig(self, node, decl.sig, &mut fnType) catch e {
4734 +
    try resolveFnSig(self, node, &decl.sig, &mut fnType) catch e {
4735 4735
        exitFn(self);
4736 4736
        throw e;
4737 4737
    };
4738 4738
    exitFn(self);
4739 4739
4759 4759
    } else {
4760 4760
        try ensureNoHeapValue(self, node, *fnType.returnType);
4761 4761
    }
4762 4762
    // Bind the function name.
4763 4763
    let ty = Type::Fn(allocFnType(self, fnType));
4764 -
    let sym = try bindValueIdent(self, decl.name, node, ty, false, 0, attrMask)
4764 +
    let _ = try bindValueIdent(self, decl.name, node, ty, false, 0, attrMask)
4765 4765
        else throw emitError(self, node, ErrorKind::ExpectedIdentifier);
4766 4766
4767 4767
    return ty;
4768 4768
}
4769 4769
4770 4770
/// Resolve the signature of a function in its scope: declare parameter regions,
4771 4771
/// bind its parameters, and fill in `fnType`.
4772 4772
fn resolveFnSig(
4773 4773
    self: &mut Resolver,
4774 4774
    node: *ast::Node,
4775 -
    sig: ast::FnSig,
4775 +
    sig: &ast::FnSig,
4776 4776
    fnType: &mut FnType
4777 4777
) throws (ResolveError) {
4778 4778
    try declareParamRegions(self, nil, sig.params);
4779 4779
    if let retNode = sig.returnType {
4780 4780
        let retTy = try infer(self, retNode);
4880 4880
        // Bind the receiver parameter.
4881 4881
        let receiverTy = *fnType.paramTypes[0];
4882 4882
        try bindValueIdent(self, receiver, receiver, receiverTy, false, 0, 0);
4883 4883
        // Bind the remaining parameters from the signature.
4884 4884
        for paramNode in params {
4885 -
            let paramTy = try infer(self, paramNode);
4885 +
            try infer(self, paramNode);
4886 4886
        }
4887 4887
    }
4888 4888
    // Resolve the body.
4889 4889
    let retTy = *fnType.returnType;
4890 4890
    let bodyTy = try checkAssignable(self, body, Type::Void);
5576 5576
        } =
5577 5577
            methodNode.value else continue;
5578 5578
5579 5579
        // Symbol may be absent if [`resolveInstanceDecl`] reported an error
5580 5580
        // for this method (eg. unknown method name). Skip gracefully.
5581 -
        let sym = symbolFor(self, methodNode) else continue;
5581 +
        let _ = symbolFor(self, methodNode) else continue;
5582 5582
5583 -
        try resolveMethodBody(self, methodNode, receiverName, receiverType, sig, body);
5583 +
        try resolveMethodBody(self, methodNode, receiverName, receiverType, &sig, body);
5584 5584
    }
5585 5585
}
5586 5586
5587 5587
/// Resolve a method body shared by instance methods and standalone methods.
5588 5588
/// Binds the receiver and parameters, then type-checks the body.
5589 5589
fn resolveMethodBody(
5590 5590
    self: &mut Resolver,
5591 5591
    node: *ast::Node,
5592 5592
    receiverName: *ast::Node,
5593 5593
    receiverType: *ast::Node,
5594 -
    sig: ast::FnSig,
5594 +
    sig: &ast::FnSig,
5595 5595
    body: *ast::Node
5596 5596
) throws (ResolveError) {
5597 5597
    let sym = symbolFor(self, node) else throw emitError(self, node, ErrorKind::Internal);
5598 5598
    let case SymbolData::Value { type: Type::Fn(fnType), .. } = self.symbols[*sym].data
5599 5599
        else panic "resolveMethodBody: expected value symbol";
5629 5629
    attrs: ?ast::Attributes
5630 5630
) throws (ResolveError) {
5631 5631
    // The body reuses the method scope, so the region of the receiver stays
5632 5632
    // in scope there.
5633 5633
    enterScope(self, node);
5634 -
    try declareMethod(self, node, name, receiverType, sig, attrs) catch e {
5634 +
    try declareMethod(self, node, name, receiverType, &sig, attrs) catch e {
5635 5635
        exitScope(self);
5636 5636
        throw e;
5637 5637
    };
5638 5638
    exitScope(self);
5639 5639
}
5644 5644
fn declareMethod(
5645 5645
    self: &mut Resolver,
5646 5646
    node: *ast::Node,
5647 5647
    name: *ast::Node,
5648 5648
    receiverType: *ast::Node,
5649 -
    sig: ast::FnSig,
5649 +
    sig: &ast::FnSig,
5650 5650
    attrs: ?ast::Attributes
5651 5651
) throws (ResolveError) {
5652 5652
    try declareParamRegions(self, receiverType, sig.params);
5653 5653
    // Resolve the receiver type: must be `*Type` or `*mut Type` pointing to a
5654 5654
    // nominal type.
6177 6177
                    // variant of another union, or another record, would bind
6178 6178
                    // against this record's fields.
6179 6179
                    match pattern.value {
6180 6180
                        case ast::NodeValue::Call(call) => {
6181 6181
                            try checkEqual(self, call.callee, scrutineeTy);
6182 -
                            try bindRecordPatternFields(self, pattern, recInfo, matchBy);
6182 +
                            try bindRecordPatternFields(self, pattern, &recInfo, matchBy);
6183 6183
                            return;
6184 6184
                        }
6185 6185
                        case ast::NodeValue::RecordLit(lit) => {
6186 6186
                            if let typeName = lit.typeName {
6187 6187
                                try checkEqual(self, typeName, scrutineeTy);
6188 6188
                            }
6189 -
                            try bindRecordPatternFields(self, pattern, recInfo, matchBy);
6189 +
                            try bindRecordPatternFields(self, pattern, &recInfo, matchBy);
6190 6190
                            return;
6191 6191
                        }
6192 6192
                        else => {}
6193 6193
                    }
6194 6194
                }
6955 6955
6956 6956
/// Validate and bind a union constructor call used as a `match` pattern.
6957 6957
fn resolveUnionCallPattern(
6958 6958
    self: &mut Resolver,
6959 6959
    pattern: *ast::Node,
6960 -
    call: ast::Call,
6960 +
    call: &ast::Call,
6961 6961
    subjectTy: Type,
6962 6962
    unionType: UnionType,
6963 6963
    matchBy: MatchBy
6964 6964
) throws (ResolveError) {
6965 -
    let calleeTy = try checkEqual(self, call.callee, subjectTy);
6965 +
    try checkEqual(self, call.callee, subjectTy);
6966 6966
    let case NodeExtra::UnionVariant { ordinal: index, tag } =
6967 6967
        self.nodeData.entries[call.callee.id].extra else {
6968 6968
        throw emitError(self, call.callee, ErrorKind::Internal);
6969 6969
    };
6970 6970
    let variant = &unionType.variants[index];
6980 6980
6981 6981
/// Bind the payload introduced by a union constructor pattern.
6982 6982
fn bindUnionPatternPayload(
6983 6983
    self: &mut Resolver,
6984 6984
    pattern: *ast::Node,
6985 -
    call: ast::Call,
6985 +
    call: &ast::Call,
6986 6986
    variantName: *[u8],
6987 6987
    payloadTy: Type,
6988 6988
    matchBy: MatchBy
6989 6989
) throws (ResolveError) {
6990 6990
    if call.args.len == 0 {
6994 6994
    }
6995 6995
    // All variant payloads are records.
6996 6996
    let recInfo = getRecord(self, payloadTy)
6997 6997
        else panic "bindUnionPatternPayload: payload is not a record";
6998 6998
6999 -
    try bindRecordPatternFields(self, pattern, recInfo, matchBy);
6999 +
    try bindRecordPatternFields(self, pattern, &recInfo, matchBy);
7000 7000
}
7001 7001
7002 7002
/// Bind a pattern variable. For ref matches, wraps the type in a pointer.
7003 7003
fn bindPatternVar(self: &mut Resolver, binding: *ast::Node, ty: Type, matchBy: MatchBy)
7004 7004
    throws (ResolveError)
7035 7035
}
7036 7036
7037 7037
/// Require access to a record's representation. An opaque record's fields can
7038 7038
/// only be read, written, borrowed, constructed, or destructured by its
7039 7039
/// defining module, in safe and unsafe code alike.
7040 -
fn requireRecordAccess(self: &mut Resolver, node: *ast::Node, recInfo: RecordType)
7040 +
fn requireRecordAccess(self: &mut Resolver, node: *ast::Node, recInfo: &RecordType)
7041 7041
    throws (ResolveError)
7042 7042
{
7043 7043
    if let owner = recInfo.privateModule; owner <> self.currentMod {
7044 7044
        throw emitError(self, node, ErrorKind::OpaqueRecordAccess);
7045 7045
    }
7047 7047
7048 7048
/// Bind record pattern fields to variables in the current scope.
7049 7049
fn bindRecordPatternFields(
7050 7050
    self: &mut Resolver,
7051 7051
    pattern: *ast::Node,
7052 -
    recInfo: RecordType,
7052 +
    recInfo: &RecordType,
7053 7053
    matchBy: MatchBy
7054 7054
) throws (ResolveError) {
7055 7055
    try requireRecordAccess(self, pattern, recInfo);
7056 7056
    match pattern.value {
7057 7057
        case ast::NodeValue::Call(call) => {
7121 7121
        throw emitError(self, pattern, ErrorKind::UnionVariantPayloadUnexpected(variant.name));
7122 7122
    }
7123 7123
    let recInfo = getRecord(self, variant.valueType)
7124 7124
        else panic "resolveUnionRecordPattern: payload is not a record";
7125 7125
7126 -
    try bindRecordPatternFields(self, pattern, recInfo, matchBy);
7126 +
    try bindRecordPatternFields(self, pattern, &recInfo, matchBy);
7127 7127
}
7128 7128
7129 7129
/// Analyze a pattern appearing in a union case.
7130 7130
fn resolveUnionPattern(
7131 7131
    self: &mut Resolver,
7143 7143
    }
7144 7144
    match pattern.value {
7145 7145
        case ast::NodeValue::ScopeAccess(access) =>
7146 7146
            try resolveUnionScopePattern(self, pattern, access, subjectTy, unionType),
7147 7147
        case ast::NodeValue::Call(call) =>
7148 -
            try resolveUnionCallPattern(self, pattern, call, subjectTy, unionType, matchBy),
7148 +
            try resolveUnionCallPattern(self, pattern, &call, subjectTy, unionType, matchBy),
7149 7149
        case ast::NodeValue::RecordLit(lit) =>
7150 7150
            try resolveUnionRecordPattern(self, pattern, lit, subjectTy, unionType, matchBy),
7151 7151
        else => {
7152 7152
            let patternTy = try visit(self, pattern, subjectTy);
7153 7153
            throw emitTypeMismatch(self, pattern, TypeMismatch {
7306 7306
}
7307 7307
7308 7308
/// Validate call arguments against a function type: check argument count,
7309 7309
/// type-check each argument, and verify that throwing functions use `try`.
7310 7310
fn checkCallArgs(
7311 -
    self: &mut Resolver, node: *ast::Node, call: ast::Call, info: *FnType, ctx: CallCtx
7311 +
    self: &mut Resolver, node: *ast::Node, call: &ast::Call, info: *FnType, ctx: CallCtx
7312 7312
)
7313 7313
    throws (ResolveError)
7314 7314
{
7315 7315
    if ctx == CallCtx::Normal and info.throwList.len > 0 {
7316 7316
        throw emitError(self, node, ErrorKind::MissingTry);
7337 7337
        }
7338 7338
    }
7339 7339
}
7340 7340
7341 7341
/// Analyze a function call expression.
7342 -
fn resolveCall(self: &mut Resolver, node: *ast::Node, call: ast::Call, ctx: CallCtx) -> Type
7342 +
fn resolveCall(self: &mut Resolver, node: *ast::Node, call: &ast::Call, ctx: CallCtx) -> Type
7343 7343
    throws (ResolveError)
7344 7344
{
7345 7345
    // Intercept method calls on slices before inferring the callee.
7346 7346
    if let case ast::NodeValue::FieldAccess(access) = call.callee.value {
7347 7347
        let parentTy = try infer(self, access.parent);
7739 7739
/// a heap: `&Heap`, or `&Allocator` or `&Scratch` for plain elements. The method throws
7740 7740
/// `AllocError` and must be called with `try`, because the heap can run out.
7741 7741
fn resolveSliceAllocMethod(
7742 7742
    self: &mut Resolver,
7743 7743
    node: *ast::Node,
7744 -
    call: ast::Call,
7744 +
    call: &ast::Call,
7745 7745
    valueTypes: &[Type],
7746 7746
    returnTy: Type,
7747 7747
    extra: NodeExtra,
7748 7748
    ctx: CallCtx
7749 7749
) -> Type throws (ResolveError) {
7802 7802
/// The receiver is a heap handle or a heap place that is borrowed for the call.
7803 7803
/// The object has the type of `value`. Use `try`, because the heap can run out.
7804 7804
fn resolveAllocNew(
7805 7805
    self: &mut Resolver,
7806 7806
    node: *ast::Node,
7807 -
    call: ast::Call,
7807 +
    call: &ast::Call,
7808 7808
    access: ast::Access,
7809 7809
    parentTy: Type,
7810 7810
    ctx: CallCtx
7811 7811
) -> ?Type throws (ResolveError) {
7812 7812
    let methodName = try nodeName(self, access.child);
7858 7858
/// pointers and slices stay in bounds and reach only plain bytes, but they alias new allocations,
7859 7859
/// so a `*T` no longer lives for the whole program and a `*mut T` is no longer exclusive.
7860 7860
fn resolveScratchReset(
7861 7861
    self: &mut Resolver,
7862 7862
    node: *ast::Node,
7863 -
    call: ast::Call,
7863 +
    call: &ast::Call,
7864 7864
    access: ast::Access,
7865 7865
    parentTy: Type
7866 7866
) -> ?Type throws (ResolveError) {
7867 7867
    let methodName = try nodeName(self, access.child);
7868 7868
    if not (methodName == "reset") {
8158 8158
    return nil;
8159 8159
}
8160 8160
8161 8161
/// Analyze a union constructor call with payload.
8162 8162
fn resolveUnionConstructorCall(
8163 -
    self: &mut Resolver, node: *ast::Node, call: ast::Call, unionNominal: NominalId
8163 +
    self: &mut Resolver, node: *ast::Node, call: &ast::Call, unionNominal: NominalId
8164 8164
) -> Type
8165 8165
    throws (ResolveError)
8166 8166
{
8167 8167
    // Get the union nominal type.
8168 8168
    let case NominalType::Union(unionType) = self.nominals[*unionNominal]
8181 8181
    // Check if this variant expects a payload.
8182 8182
    let payloadType = variant.valueType;
8183 8183
    if payloadType <> Type::Void {
8184 8184
        let recInfo = getRecord(self, payloadType)
8185 8185
            else panic "resolveUnionConstructorCall: payload is not a record";
8186 -
        try checkRecordConstructorArgs(self, node, call.args, recInfo);
8186 +
        try checkRecordConstructorArgs(self, node, call.args, &recInfo);
8187 8187
    } else if call.args.len > 0 {
8188 8188
        throw emitError(self, node, ErrorKind::UnionVariantPayloadUnexpected(variant.name));
8189 8189
    }
8190 8190
    return setNodeType(self, node, Type::Nominal(unionNominal));
8191 8191
}
8194 8194
///
8195 8195
/// Handles the syntax `R(a, b)` for unlabeled records, checking that the
8196 8196
/// number of arguments matches the record's field count and that each argument
8197 8197
/// is assignable to its corresponding field type.
8198 8198
fn resolveRecordConstructorCall(
8199 -
    self: &mut Resolver, node: *ast::Node, call: ast::Call, recordType: NominalId
8199 +
    self: &mut Resolver, node: *ast::Node, call: &ast::Call, recordType: NominalId
8200 8200
) -> Type
8201 8201
    throws (ResolveError)
8202 8202
{
8203 8203
    let case NominalType::Record(recInfo) = self.nominals[*recordType]
8204 8204
        else panic "resolveRecordConstructorCall: not a record type";
8205 8205
8206 -
    try requireRecordAccess(self, node, recInfo);
8207 -
    try checkRecordConstructorArgs(self, node, call.args, recInfo);
8206 +
    try requireRecordAccess(self, node, &recInfo);
8207 +
    try checkRecordConstructorArgs(self, node, call.args, &recInfo);
8208 8208
    return setNodeType(self, node, Type::Nominal(recordType));
8209 8209
}
8210 8210
8211 8211
/// Resolve the type name of a record literal, handling both record types and
8212 8212
/// union variant payloads like `Union::Variant { ... }`.
8255 8255
        resultType: Type::Nominal(tyInfo),
8256 8256
    };
8257 8257
}
8258 8258
8259 8259
/// Analyze a record literal expression.
8260 -
fn resolveRecordLit(self: &mut Resolver, node: *ast::Node, lit: ast::RecordLit, hint: Type) -> Type
8260 +
fn resolveRecordLit(self: &mut Resolver, node: *ast::Node, lit: &ast::RecordLit, hint: Type) -> Type
8261 8261
    throws (ResolveError)
8262 8262
{
8263 8263
    // If no type name, infer an anonymous tuple type.
8264 8264
    let typeIdent = lit.typeName else {
8265 8265
        return try resolveAnonRecordLit(self, node, lit, hint);
8273 8273
    try ensureNominalResolved(self, tyInfo, typeIdent);
8274 8274
    let case NominalType::Record(recordType) = self.nominals[*tyInfo]
8275 8275
        else throw emitError(self, node, ErrorKind::ExpectedRecord);
8276 8276
8277 8277
    try ensureNoHeapValue(self, node, Type::Nominal(tyInfo));
8278 -
    try requireRecordAccess(self, node, recordType);
8278 +
    try requireRecordAccess(self, node, &recordType);
8279 8279
    // Unlabeled records must use constructor call syntax `R(...)`, not brace syntax.
8280 8280
    if not recordType.labeled {
8281 8281
        throw emitError(self, node, ErrorKind::RecordFieldStyleMismatch);
8282 8282
    }
8283 8283
    // Check field count. With `{ .. }` syntax, fewer fields are allowed.
8316 8316
    return setNodeType(self, node, resultType);
8317 8317
}
8318 8318
8319 8319
/// Analyze an anonymous record literal, checking fields against the hint type.
8320 8320
fn resolveAnonRecordLit(
8321 -
    self: &mut Resolver, node: *ast::Node, lit: ast::RecordLit, hint: Type
8321 +
    self: &mut Resolver, node: *ast::Node, lit: &ast::RecordLit, hint: Type
8322 8322
) -> Type throws (ResolveError) {
8323 8323
    // Unwrap optional hint to get the inner record type.
8324 8324
    let mut innerHint = hint;
8325 8325
    if let case Type::Optional(inner) = hint {
8326 8326
        set innerHint = *inner;
8333 8333
        }
8334 8334
    }
8335 8335
    let targetInfo = hintInfo else {
8336 8336
        throw emitError(self, node, ErrorKind::CannotInferType);
8337 8337
    };
8338 -
    try requireRecordAccess(self, node, targetInfo);
8338 +
    try requireRecordAccess(self, node, &targetInfo);
8339 8339
    // Check field count.
8340 8340
    if lit.fields.len <> targetInfo.fields.len {
8341 8341
        if lit.fields.len < targetInfo.fields.len {
8342 8342
            let missingName = targetInfo.fields[lit.fields.len].name else panic;
8343 8343
            throw emitError(self, node, ErrorKind::RecordFieldMissing(missingName));
8567 8567
        case Type::Nominal(id) => {
8568 8568
            let fieldNode = access.child;
8569 8569
            let fieldName = try nodeName(self, fieldNode);
8570 8570
            if let case NominalType::Record(recordType) = self.nominals[*id] {
8571 8571
                if let fieldIndex = findRecordField(&recordType.fields[..], fieldName) {
8572 -
                    try requireRecordAccess(self, node, recordType);
8572 +
                    try requireRecordAccess(self, node, &recordType);
8573 8573
                    let fieldTy = recordType.fields[fieldIndex].fieldType;
8574 8574
                    setRecordFieldIndex(self, fieldNode, fieldIndex);
8575 8575
                    return setNodeType(self, node, fieldTy);
8576 8576
                }
8577 8577
                // Not a field: check for a standalone method.
9165 9165
            throw emitError(self, targetNode, ErrorKind::DerefLabeledRecord);
9166 9166
        }
9167 9167
        if recInfo.fields.len <> 1 {
9168 9168
            throw emitError(self, targetNode, ErrorKind::DerefRecordFieldCount);
9169 9169
        }
9170 -
        try requireRecordAccess(self, node, recInfo);
9170 +
        try requireRecordAccess(self, node, &recInfo);
9171 9171
        let fieldTy = recInfo.fields[0].fieldType;
9172 9172
        setRecordFieldIndex(self, node, 0);
9173 9173
        return setNodeType(self, node, fieldTy);
9174 9174
    }
9175 9175
    throw emitError(self, targetNode, ErrorKind::ExpectedPointer);
9388 9388
    throws (ResolveError)
9389 9389
{
9390 9390
    let call = tryExpr.expr;
9391 9391
    let case ast::NodeValue::Call(callExpr) = call.value
9392 9392
        else throw emitError(self, call, ErrorKind::TryNonThrowing);
9393 -
    let resultTy = try resolveCall(self, call, callExpr, CallCtx::Try);
9393 +
    let resultTy = try resolveCall(self, call, &callExpr, CallCtx::Try);
9394 9394
9395 9395
    // TODO: It's annoying that we need to re-fetch the function type after
9396 9396
    // analyzing the call.
9397 9397
    let calleeTy = typeFor(self, callExpr.callee) else return setNodeType(self, node, resultTy);
9398 9398
    let case Type::Fn(calleeInfo) = calleeTy
11108 11108
fn checkLinearCall(
11109 11109
    self: &mut Resolver,
11110 11110
    checker: &mut LinearChecker,
11111 11111
    env: &mut LinearEnv,
11112 11112
    node: *ast::Node,
11113 -
    call: ast::Call
11113 +
    call: &ast::Call
11114 11114
) throws (ResolveError) {
11115 11115
    let localStart = checker.localLen;
11116 11116
    // Receiver of a slice mutation, which an exclusive argument must not overlap.
11117 11117
    let mut sliceReceiver: ?*ast::Node = nil;
11118 11118
    match self.nodeData.entries[node.id].extra {
11447 11447
                set env.available |= 1 as u64 << index as u64;
11448 11448
                set env.movedFields[index] = 0;
11449 11449
                set env.uninit &= ~(1 as u64 << index as u64);
11450 11450
            }
11451 11451
        }
11452 -
        case ast::NodeValue::Call(call) => try checkLinearCall(self, checker, env, node, call),
11452 +
        case ast::NodeValue::Call(call) => try checkLinearCall(self, checker, env, node, &call),
11453 11453
        case ast::NodeValue::AddressOf(addr) => {
11454 11454
            // A value is held in a temporary that nothing consumes.
11455 11455
            if let root = temporaryRoot(self, addr.target) {
11456 11456
                if let ty = typeFor(self, root); isLinear(self, ty) {
11457 11457
                    throw emitError(self, addr.target, ErrorKind::LinearDiscard);
lib/std/lang/resolver/tests.rad +1 -1
241 241
242 242
/// Extract the first error from a test result, failing if none exists.
243 243
export fn expectError(result: &TestResult) -> super::Error throws (testing::TestError) {
244 244
    let err = super::errorAt(&result.diagnostics.errors[..], 0)
245 245
        else throw testing::TestError::Failed;
246 -
    return err;
246 +
    return *err;
247 247
}
248 248
249 249
/// Check if two error kinds match.
250 250
export fn errorKindMatches(actual: &super::ErrorKind, expected: super::ErrorKind) -> bool {
251 251
    if let case super::ErrorKind::DuplicateBinding(expectedName) = expected {
lib/std/lang/sexpr.rad +1 -2
119 119
}
120 120
121 121
/// Write an `i64` in decimal.
122 122
export fn writeI64(out: &mut opaque Output, val: i64) {
123 123
    let mut digits: [u8; fmt::I64_STR_LEN] = [0; fmt::I64_STR_LEN];
124 -
    let start = fmt::formatI64(val, &mut digits[..]);
125 -
    out.write(&digits[start ..]);
124 +
    out.write(fmt::formatI64(val, &mut digits[..]));
126 125
}
127 126
128 127
/// Emit indentation to the output.
129 128
fn indentTo(out: &mut opaque Output, depth: u32) {
130 129
    for _ in 0 .. depth {
lib/std/mem.rad +42 -9
1 1
//! Memory operations and alignment helpers.
2 2
export mod heap;
3 3
4 +
use std::char;
5 +
4 6
/// Largest unsigned 64-bit integer.
5 7
export constant U64_MAX: u64 = 0xffffffffffffffff;
6 8
/// Largest unsigned 32-bit integer.
7 9
export constant U32_MAX: u32 = 0xffffffff;
8 10
26 28
    return from.len;
27 29
}
28 30
29 31
/// Strip a byte-level prefix from the input, and return the suffix.
30 32
/// Returns `nil` if the prefix wasn't found.
31 -
export fn stripPrefix(prefix: &[u8], input: *[u8]) -> ?*[u8] {
32 -
    if prefix.len == 0 {
33 -
        return input;
33 +
export fn stripPrefix(prefix: &[u8], input: &'r [u8]) -> ?&'r [u8] {
34 +
    if not startsWith(input, prefix) {
35 +
        return nil;
34 36
    }
35 -
    if prefix.len > input.len {
37 +
    return &input[prefix.len ..];
38 +
}
39 +
40 +
/// Strip a byte suffix from `input`, or return `nil` if it does not match.
41 +
export fn stripSuffix(suffix: &[u8], input: &'r [u8]) -> ?&'r [u8] {
42 +
    if not endsWith(input, suffix) {
36 43
        return nil;
37 44
    }
38 -
    for i in 0 .. prefix.len {
39 -
        if prefix[i] <> input[i] {
40 -
            return nil;
41 -
        }
45 +
    return &input[.. input.len - suffix.len];
46 +
}
47 +
48 +
/// Return `input` without leading ASCII whitespace.
49 +
/// Whitespace is space, tab, line feed, form feed, or carriage return.
50 +
export fn trimAsciiStart(input: &'r [u8]) -> &'r [u8] {
51 +
    let mut start: u32 = 0;
52 +
    while start < input.len and char::isWhitespace(input[start]) {
53 +
        set start += 1;
42 54
    }
43 -
    return &input[prefix.len ..];
55 +
    return &input[start ..];
56 +
}
57 +
58 +
/// Return `input` without trailing ASCII whitespace.
59 +
/// Whitespace is space, tab, line feed, form feed, or carriage return.
60 +
export fn trimAsciiEnd(input: &'r [u8]) -> &'r [u8] {
61 +
    let mut end = input.len;
62 +
    while end > 0 and char::isWhitespace(input[end - 1]) {
63 +
        set end -= 1;
64 +
    }
65 +
    return &input[.. end];
66 +
}
67 +
68 +
/// Return `input` without leading or trailing ASCII whitespace.
69 +
/// Whitespace is space, tab, line feed, form feed, or carriage return.
70 +
export fn trimAscii(input: &'r [u8]) -> &'r [u8] {
71 +
    return trimAsciiEnd(trimAsciiStart(input));
44 72
}
45 73
46 74
/// Return the offset of the first occurrence of `needle` in `text`, or `nil`.
47 75
export fn find(text: &[u8], needle: &[u8]) -> ?u32 {
48 76
    if needle.len > text.len {
59 87
/// Check whether `text` ends with `suffix`.
60 88
export fn endsWith(text: &[u8], suffix: &[u8]) -> bool {
61 89
    return suffix.len <= text.len and eq(&text[text.len - suffix.len ..], suffix);
62 90
}
63 91
92 +
/// Check whether `text` starts with `prefix`.
93 +
export fn startsWith(text: &[u8], prefix: &[u8]) -> bool {
94 +
    return prefix.len <= text.len and eq(&text[.. prefix.len], prefix);
95 +
}
96 +
64 97
/// Iterator over the parts of a byte string between separator bytes. A final
65 98
/// part needs no separator, and a separator at the very end adds no part.
66 99
export record Split: Copy {
67 100
    /// The whole byte string.
68 101
    text: *[u8],
lib/std/tests.rad +89 -48
86 86
87 87
// fmt /////////////////////////////////////////////////////////////////////////
88 88
89 89
@test fn testFormatU32Zero() throws (testing::TestError) {
90 90
    let mut buffer: [u8; 11] = [0; 11];
91 -
    let start = fmt::formatU32(0, &mut buffer[..]);
92 -
    try testing::expect(buffer.len - start == 1);
93 -
    try testing::expectBytesEq(&buffer[start ..], "0");
91 +
    let text = fmt::formatU32(0, &mut buffer[..]);
92 +
    try testing::expect(text.len == 1);
93 +
    try testing::expectBytesEq(text, "0");
94 94
}
95 95
96 96
@test fn testFormatU32Basic() throws (testing::TestError) {
97 97
    let mut buffer: [u8; 11] = [0; 11];
98 -
    let start = fmt::formatU32(123, &mut buffer[..]);
99 -
    try testing::expect(buffer.len - start == 3);
100 -
    try testing::expectBytesEq(&buffer[start ..], "123");
98 +
    let text = fmt::formatU32(123, &mut buffer[..]);
99 +
    try testing::expect(text.len == 3);
100 +
    try testing::expectBytesEq(text, "123");
101 101
}
102 102
103 103
@test fn testFormatU32Large() throws (testing::TestError) {
104 104
    let mut buffer: [u8; 11] = [0; 11];
105 -
    let start = fmt::formatU32(90000, &mut buffer[..]);
106 -
    try testing::expect(buffer.len - start == 5);
107 -
    try testing::expectBytesEq(&buffer[start ..], "90000");
105 +
    let text = fmt::formatU32(90000, &mut buffer[..]);
106 +
    try testing::expect(text.len == 5);
107 +
    try testing::expectBytesEq(text, "90000");
108 108
}
109 109
110 110
@test fn testFormatU32Max() throws (testing::TestError) {
111 111
    let mut buffer: [u8; 11] = [0; 11];
112 -
    let start = fmt::formatU32(4294967295, &mut buffer[..]);
113 -
    try testing::expect(buffer.len - start == 10);
114 -
    try testing::expectBytesEq(&buffer[start ..], "4294967295");
112 +
    let text = fmt::formatU32(4294967295, &mut buffer[..]);
113 +
    try testing::expect(text.len == 10);
114 +
    try testing::expectBytesEq(text, "4294967295");
115 115
}
116 116
117 117
@test fn testFormatI32Positive() throws (testing::TestError) {
118 118
    let mut buffer: [u8; 11] = [0; 11];
119 -
    let start = fmt::formatI32(456, &mut buffer[..]);
120 -
    try testing::expect(buffer.len - start == 3);
121 -
    try testing::expectBytesEq(&buffer[start ..], "456");
119 +
    let text = fmt::formatI32(456, &mut buffer[..]);
120 +
    try testing::expect(text.len == 3);
121 +
    try testing::expectBytesEq(text, "456");
122 122
}
123 123
124 124
@test fn testFormatI32Negative() throws (testing::TestError) {
125 125
    let mut buffer: [u8; 11] = [0; 11];
126 -
    let start = fmt::formatI32(-789, &mut buffer[..]);
127 -
    try testing::expect(buffer.len - start == 4);
128 -
    try testing::expectBytesEq(&buffer[start ..], "-789");
126 +
    let text = fmt::formatI32(-789, &mut buffer[..]);
127 +
    try testing::expect(text.len == 4);
128 +
    try testing::expectBytesEq(text, "-789");
129 129
}
130 130
131 131
@test fn testFormatI32Zero() throws (testing::TestError) {
132 132
    let mut buffer: [u8; 11] = [0; 11];
133 -
    let start = fmt::formatI32(0, &mut buffer[..]);
134 -
    try testing::expect(buffer.len - start == 1);
135 -
    try testing::expectBytesEq(&buffer[start ..], "0");
133 +
    let text = fmt::formatI32(0, &mut buffer[..]);
134 +
    try testing::expect(text.len == 1);
135 +
    try testing::expectBytesEq(text, "0");
136 136
}
137 137
138 138
@test fn testFormatI32Max() throws (testing::TestError) {
139 139
    let mut buffer: [u8; 11] = [0; 11];
140 -
    let start = fmt::formatI32(2147483647, &mut buffer[..]);
141 -
    try testing::expect(buffer.len - start == 10);
142 -
    try testing::expectBytesEq(&buffer[start ..], "2147483647");
140 +
    let text = fmt::formatI32(2147483647, &mut buffer[..]);
141 +
    try testing::expect(text.len == 10);
142 +
    try testing::expectBytesEq(text, "2147483647");
143 143
}
144 144
145 145
@test fn testFormatI32Min() throws (testing::TestError) {
146 146
    let mut buffer: [u8; 11] = [0; 11];
147 -
    let start = fmt::formatI32(-2147483648, &mut buffer[..]);
148 -
    try testing::expect(buffer.len - start == 11);
149 -
    try testing::expectBytesEq(&buffer[start ..], "-2147483648");
147 +
    let text = fmt::formatI32(-2147483648, &mut buffer[..]);
148 +
    try testing::expect(text.len == 11);
149 +
    try testing::expectBytesEq(text, "-2147483648");
150 150
}
151 151
152 152
@test fn testFormatU64Zero() throws (testing::TestError) {
153 153
    let mut buffer: [u8; 20] = [0; 20];
154 -
    let start = fmt::formatU64(0, &mut buffer[..]);
155 -
    try testing::expect(buffer.len - start == 1);
156 -
    try testing::expectBytesEq(&buffer[start ..], "0");
154 +
    let text = fmt::formatU64(0, &mut buffer[..]);
155 +
    try testing::expect(text.len == 1);
156 +
    try testing::expectBytesEq(text, "0");
157 157
}
158 158
159 159
@test fn testFormatU64Max() throws (testing::TestError) {
160 160
    let mut buffer: [u8; 20] = [0; 20];
161 -
    let start = fmt::formatU64(18446744073709551615, &mut buffer[..]);
162 -
    try testing::expect(buffer.len - start == 20);
163 -
    try testing::expectBytesEq(&buffer[start ..], "18446744073709551615");
161 +
    let text = fmt::formatU64(18446744073709551615, &mut buffer[..]);
162 +
    try testing::expect(text.len == 20);
163 +
    try testing::expectBytesEq(text, "18446744073709551615");
164 164
}
165 165
166 166
@test fn testFormatI64Negative() throws (testing::TestError) {
167 167
    let mut buffer: [u8; 20] = [0; 20];
168 -
    let start = fmt::formatI64(-9876543210, &mut buffer[..]);
169 -
    try testing::expect(buffer.len - start == 11);
170 -
    try testing::expectBytesEq(&buffer[start ..], "-9876543210");
168 +
    let text = fmt::formatI64(-9876543210, &mut buffer[..]);
169 +
    try testing::expect(text.len == 11);
170 +
    try testing::expectBytesEq(text, "-9876543210");
171 171
}
172 172
173 173
@test fn testFormatI64Min() throws (testing::TestError) {
174 174
    let mut buffer: [u8; 20] = [0; 20];
175 -
    let start = fmt::formatI64(-9223372036854775808, &mut buffer[..]);
176 -
    try testing::expect(buffer.len - start == 20);
177 -
    try testing::expectBytesEq(&buffer[start ..], "-9223372036854775808");
175 +
    let text = fmt::formatI64(-9223372036854775808, &mut buffer[..]);
176 +
    try testing::expect(text.len == 20);
177 +
    try testing::expectBytesEq(text, "-9223372036854775808");
178 +
}
179 +
180 +
/// Scalar formatters return only the bytes written into a reusable buffer.
181 +
@test fn testFormatBorrowedScalars() throws (testing::TestError) {
182 +
    let mut buffer: [u8; fmt::I64_STR_LEN] = [0; fmt::I64_STR_LEN];
183 +
    assert mem::eq(fmt::formatU8(255, &mut buffer[..]), "255");
184 +
    assert mem::eq(fmt::formatU16(65535, &mut buffer[..]), "65535");
185 +
    assert mem::eq(fmt::formatI8(-128, &mut buffer[..]), "-128");
186 +
    assert mem::eq(fmt::formatI16(-32768, &mut buffer[..]), "-32768");
187 +
    assert mem::eq(fmt::formatI64(0, &mut buffer[..]), "0");
188 +
    assert mem::eq(fmt::formatBool(true, &mut buffer[..]), "true");
189 +
    assert mem::eq(fmt::formatBool(false, &mut buffer[..]), "false");
190 +
    assert fmt::unescapeString("", &mut buffer[..]).len == 0;
191 +
    assert mem::eq(fmt::unescapeString("tail\\", &mut buffer[..]), "tail\\");
178 192
}
179 193
180 194
@test fn testParseIntLiteralText() throws (testing::TestError) {
181 195
    let dec = try fmt::parseInt("123") catch {
182 196
        throw testing::TestError::Failed;
269 283
    throw testing::TestError::Failed;
270 284
}
271 285
272 286
@test fn testUnescapeString() throws (testing::TestError) {
273 287
    let mut buffer: [u8; 8] = [0; 8];
274 -
    let len = fmt::unescapeString("a\\n\\0", &mut buffer[..]);
288 +
    let text = fmt::unescapeString("a\\n\\0", &mut buffer[..]);
275 289
276 -
    try testing::expect(len == 3);
277 -
    try testing::expect(buffer[0] == 'a');
278 -
    try testing::expect(buffer[1] == '\n');
279 -
    try testing::expect(buffer[2] == 0);
290 +
    assert text.len == 3;
291 +
    assert text[0] == 'a';
292 +
    assert text[1] == '\n';
293 +
    assert text[2] == 0;
280 294
}
281 295
282 296
/// Unescaping through an allocator decodes like `unescapeString` and reserves the raw length.
283 297
@test unsafe fn testUnescapeAppend() throws (testing::TestError) {
284 298
    static STORAGE: [u8; 64] = [0; 64];
366 380
367 381
@test fn testStripPrefixNoMatch() throws (testing::TestError) {
368 382
    let input: *[u8] = "hello world";
369 383
    let prefix: *[u8] = "goodbye";
370 384
371 -
    let result = mem::stripPrefix(prefix, input);
372 -
    try testing::expect(result == nil);
385 +
    assert mem::stripPrefix(prefix, input) == nil;
373 386
}
374 387
375 388
@test fn testStripPrefixEmpty() throws (testing::TestError) {
376 389
    let input: *[u8] = "hello";
377 390
    let prefix: *[u8] = "";
384 397
385 398
@test fn testStripPrefixTooLong() throws (testing::TestError) {
386 399
    let input: *[u8] = "hi";
387 400
    let prefix: *[u8] = "hello";
388 401
389 -
    let result = mem::stripPrefix(prefix, input);
390 -
    try testing::expect(result == nil);
402 +
    assert mem::stripPrefix(prefix, input) == nil;
403 +
}
404 +
405 +
/// Byte views borrow stack storage and preserve non-whitespace bytes.
406 +
@test fn testBorrowedBytes() throws (testing::TestError) {
407 +
    let bytes: [u8; 7] = [' ', '\t', 'a', 0x80, '\r', '\n', ' '];
408 +
    let text = &bytes[..];
409 +
    assert mem::eq(mem::trimAscii(text), &bytes[2 .. 4]);
410 +
    assert mem::eq(mem::trimAsciiStart(text), &bytes[2 ..]);
411 +
    assert mem::eq(mem::trimAsciiEnd(text), &bytes[.. 4]);
412 +
    assert mem::trimAscii("").len == 0;
413 +
    let whitespace: [u8; 5] = [' ', '\t', '\r', '\n', 0x0c];
414 +
    let verticalTabs: [u8; 3] = [0x0b, 'a', 0x0b];
415 +
    assert mem::trimAscii(&whitespace[..]).len == 0;
416 +
    assert mem::eq(mem::trimAscii(&verticalTabs[..]), &verticalTabs[..]);
417 +
    let suffix = mem::stripPrefix(" \t", text) else panic;
418 +
    assert mem::eq(suffix, &bytes[2 ..]);
419 +
    let prefix = mem::stripSuffix("\r\n ", suffix) else panic;
420 +
    assert mem::eq(prefix, &bytes[2 .. 4]);
421 +
    assert mem::stripSuffix("long", "hi") == nil;
422 +
    assert mem::stripSuffix("x", "hi") == nil;
423 +
    let unchanged = mem::stripSuffix("", text) else panic;
424 +
    let empty = mem::stripSuffix("hi", "hi") else panic;
425 +
    assert mem::eq(unchanged, text);
426 +
    assert empty.len == 0;
391 427
}
392 428
393 429
@test fn testFindAndEndsWith() throws (testing::TestError) {
430 +
    assert mem::startsWith("main.rad", "main");
431 +
    assert mem::startsWith("main", "main");
432 +
    assert mem::startsWith("main", "");
433 +
    assert not mem::startsWith("main", "main.rad");
434 +
    assert not mem::startsWith("main", "rain");
394 435
    try testing::expect(mem::find("hello", "llo") == 2);
395 436
    try testing::expect(mem::find("hello", "") == 0);
396 437
    try testing::expect(mem::find("hello", "world") == nil);
397 438
    try testing::expect(mem::find("lo", "hello") == nil);
398 439
    try testing::expect(mem::endsWith("main.rad", ".rad"));
test/compiler/discovery.rad +2 -1
35 35
    );
36 36
    let mut graph = module::moduleGraph(&mut ENTRIES[..]);
37 37
    let id = try! module::registerRoot(
38 38
        &mut graph, &mut frontend.pool, 0, "fixture.rad"
39 39
    );
40 -
    let mut entry = module::entryCopy(&graph, id) else panic;
40 +
    let original = module::entry(&graph, id) else panic;
41 +
    let mut entry = *original;
41 42
    set entry.ast = empty;
42 43
    let mut pathBytes: u32 = 0;
43 44
    {
44 45
        let arena = heap::over(&mut STORAGE[..]);
45 46
        let mut found: *mut [testgen::TestDesc] = &mut [];
test/integration/fixtures.rad +4 -1
218 218
    let output = h.text(c.diagnostics);
219 219
    let mut reason: ?*[u8] = nil;
220 220
    let mut want: u32 = 0;
221 221
    let mut lines = mem::split(c.content, '\n');
222 222
    while let line = lines.next() {
223 -
        let rest = mem::stripPrefix(REJECTS, line) else continue;
223 +
        if not mem::startsWith(line, REJECTS) {
224 +
            continue;
225 +
        }
226 +
        let rest = &line[REJECTS.len ..];
224 227
        let mut start: u32 = 0;
225 228
        while start < rest.len and rest[start] == ' ' {
226 229
            set start += 1;
227 230
        }
228 231
        let spec = &rest[start ..];
test/integration/format.rad +3 -2
109 109
fn fixtures(h: &mut Harness) throws (sys::Error) {
110 110
    let out = h.path(&["fixture.out"]);
111 111
    let err = h.path(&["fixture.err"]);
112 112
    let prefix = h.join(&[FIXTURE_INPUT, "/"]);
113 113
    for input in try h.listFiles(FIXTURE_INPUT, ".rad") {
114 -
        let name = mem::stripPrefix(prefix, input) else {
114 +
        if not mem::startsWith(input, prefix) {
115 115
            panic "fixtures: unexpected path";
116 -
        };
116 +
        }
117 +
        let name = &input[prefix.len ..];
117 118
        let what = h.join(&["fmt fixture: ", name]);
118 119
        format(h, what, &["-fmt", "-fmt.wrap", FIXTURE_WIDTH, input], 0, out, err);
119 120
        h.expect(what, out, Expect::Same(h.join(&[FIXTURE_OUTPUT, "/", name])));
120 121
    }
121 122
}
test/integration/harness.rad +3 -3
138 138
}
139 139
140 140
/// Format a number in decimal into a string allocated from the arena.
141 141
export fn (h: &mut Harness) num(value: u32) -> *[u8] {
142 142
    let mut digits: [u8; fmt::U32_STR_LEN] = [0; fmt::U32_STR_LEN];
143 -
    let start = fmt::formatU32(value, &mut digits[..]);
144 143
    let mut text: *mut [u8] = &mut [];
145 -
    try! text.extend(&digits[start ..], h.arena);
144 +
    try! text.extend(fmt::formatU32(value, &mut digits[..]), h.arena);
146 145
    return &text[..];
147 146
}
148 147
149 148
/// Return the path in the work directory of the file whose name is the
150 149
/// concatenation of `parts`.
308 307
/// Return the rest of the first line of `content` that starts with `prefix`,
309 308
/// without the spaces that follow it, or `nil` when no line does.
310 309
export fn marker(content: *[u8], prefix: *[u8]) -> ?*[u8] {
311 310
    let mut lines = mem::split(content, '\n');
312 311
    while let line = lines.next() {
313 -
        if let rest = mem::stripPrefix(prefix, line) {
312 +
        if mem::startsWith(line, prefix) {
313 +
            let rest = &line[prefix.len ..];
314 314
            let mut start: u32 = 0;
315 315
            while start < rest.len and rest[start] == ' ' {
316 316
                set start += 1;
317 317
            }
318 318
            return &rest[start ..];