lang: Mark copyable compiler types with Copy

0ed90d386c830fbe48271cde60adf00392d1210085d5817fffe515e721eeff50
Declare `Copy` on the records and unions of the compiler and the
standard library that are duplicated by value.

Assisted-by: Claude:opus-5.5
Alexis Sellier committed ago 1 parent f83d9d59
compiler/radiance.rad +9 -9
97 97
/// Usage string.
98 98
constant USAGE: *[u8] =
99 99
    "usage: radiance -pkg <name> [-start <input.ras>] -mod <input>.. [-pkg <name> -mod <input>..] -entry <pkg> -o <output>\n";
100 100
101 101
/// Compiler error.
102 -
union Error {
102 +
union Error: Copy {
103 103
    Other,
104 104
}
105 105
106 106
/// What to dump during compilation.
107 -
union Dump {
107 +
union Dump: Copy {
108 108
    /// Don't dump anything.
109 109
    None,
110 110
    /// Dump the parsed AST before semantic analysis.
111 111
    Ast,
112 112
    /// Dump the module graph.
116 116
    /// Dump the generated assembly.
117 117
    Asm,
118 118
}
119 119
120 120
/// A discovered test function.
121 -
record TestDesc {
121 +
record TestDesc: Copy {
122 122
    /// Full module qualified path segments (eg. ["std", "tests"]).
123 123
    modPath: *[*[u8]],
124 124
    /// Test function name (eg. "testFoo").
125 125
    fnName: *[u8],
126 126
}
127 127
128 128
/// Source inputs belonging to one command-line package.
129 -
record PackageInput {
129 +
record PackageInput: Copy {
130 130
    /// Package name from the `-pkg` argument.
131 131
    name: *[u8],
132 132
    /// Optional startup assembly emitted before generated text.
133 133
    startupPath: ?*[u8],
134 134
    /// Radiance source paths for this package.
140 140
    /// Number of assembly source paths.
141 141
    asmPathCount: u32,
142 142
}
143 143
144 144
/// Compilation context.
145 -
record CompileContext {
145 +
record CompileContext: Copy {
146 146
    /// Array of packages to compile.
147 147
    packages: [package::Package; MAX_PACKAGES],
148 148
    /// Driver inputs for each package slot.
149 149
    inputs: [PackageInput; MAX_PACKAGES],
150 150
    /// Number of packages.
162 162
    /// Whether to emit debug info (.debug file).
163 163
    debug: bool,
164 164
}
165 165
166 166
/// Root module info for a package.
167 -
record RootModule {
167 +
record RootModule: Copy {
168 168
    entry: *module::ModuleEntry,
169 169
    ast: *mut ast::Node,
170 170
}
171 171
172 172
/// State carried by the streaming lowerer/codegen callback.
173 -
record CodegenSinkContext {
173 +
record CodegenSinkContext: Copy {
174 174
    /// RV64 generator receiving lowered functions.
175 175
    generator: *mut rv64::Generator,
176 176
    /// Arena holding the current function's lowered IL.
177 177
    fnArena: *mut alloc::Arena,
178 178
}
179 179
180 180
/// Entry handling for streamed code generation.
181 -
union CodegenEntryMode {
181 +
union CodegenEntryMode: Copy {
182 182
    /// Do not reserve an entry jump.
183 183
    None,
184 184
    /// Reserve and patch an entry jump to the `@default` function.
185 185
    DefaultEntry,
186 186
}
187 187
188 188
/// Options controlling streamed lowering and code generation.
189 -
record CodegenOptions {
189 +
record CodegenOptions: Copy {
190 190
    /// Optional output path used for progress logging.
191 191
    logPath: ?*[u8],
192 192
    /// Whether to emit debug source locations.
193 193
    debug: bool,
194 194
    /// How the generated program should handle entry.
lib/std/arch/rv64.rad +5 -5
159 159
export fn imageHeader(codeBytes: u32, roDataBytes: u32, rwDataBytes: u32) -> [u32; 5] {
160 160
    return [IMAGE_MAGIC, IMAGE_VERSION, codeBytes, roDataBytes, rwDataBytes];
161 161
}
162 162
163 163
/// Storage buffers passed from driver for code generation.
164 -
export record Storage {
164 +
export record Storage: Copy {
165 165
    /// Buffer for data symbols.
166 166
    dataSyms: *mut [data::DataSym],
167 167
    /// Hash table entries for data symbol lookup.
168 168
    dataSymEntries: *mut [dict::Entry],
169 169
}
170 170
171 171
/// Result of code generation.
172 -
export record Program {
172 +
export record Program: Copy {
173 173
    /// Slice of emitted code.
174 174
    code: *[u32],
175 175
    /// Slice of function addresses (name + start index).
176 176
    funcs: *[types::FuncAddr],
177 177
    /// Number of read-only data bytes emitted.
181 181
    /// Debug entries mapping PCs to source locations. Empty when debug is off.
182 182
    debugEntries: *[types::DebugEntry],
183 183
}
184 184
185 185
/// Entry jump patching requested for the generated program.
186 -
export union EntryPatch {
186 +
export union EntryPatch: Copy {
187 187
    /// No entry jump is emitted.
188 188
    None,
189 189
    /// Reserve code slot zero for a jump to the default function.
190 190
    Reserved(?*[u8]),
191 191
}
192 192
193 193
/// Options controlling incremental RV64 program generation.
194 -
export record ProgramOptions {
194 +
export record ProgramOptions: Copy {
195 195
    /// Entry jump patching mode.
196 196
    entryPatch: EntryPatch,
197 197
    /// Whether to emit debug source locations.
198 198
    debug: bool,
199 199
}
201 201
/// State for incremental RV64 program generation.
202 202
///
203 203
/// The generator owns global codegen state that must survive across function
204 204
/// emission. Function-local scratch stays outside this record so callers can
205 205
/// reclaim it after each function.
206 -
export record Generator {
206 +
export record Generator: Copy {
207 207
    /// Binary emitter and relocation state.
208 208
    e: emit::Emitter,
209 209
    /// Entry jump patching state.
210 210
    entryPatch: EntryPatch,
211 211
}
lib/std/arch/rv64/asm.rad +15 -15
71 71
/// consumes the program, [`rv64::addAssembly`] appends the text words to the
72 72
/// generated text stream and registers text labels at their relocated offsets.
73 73
/// The driver copies `data` into the final read-only data prefix; the data
74 74
/// base supplied to [`assemble`] lets the assembler resolve data addresses as
75 75
/// they will appear in that final layout.
76 -
export record Program {
76 +
export record Program: Copy {
77 77
    /// Encoded instructions in the text section.
78 78
    text: *[u32],
79 79
    /// Raw bytes in the data section.
80 80
    data: *[u8],
81 81
    /// Symbols defined by the source.
83 83
    /// Text references resolved by the whole-program emitter.
84 84
    externalFixups: *[Fixup],
85 85
}
86 86
87 87
/// Errors reported while assembling source text.
88 -
export union Error {
88 +
export union Error: Copy {
89 89
    /// Invalid syntax or operand form at a source offset.
90 90
    Invalid { offset: u32, message: *[u8] },
91 91
    /// The source emitted more text words than the caller-provided buffer holds.
92 92
    TextOverflow,
93 93
    /// The source emitted more data bytes than the caller-provided buffer holds.
94 94
    DataOverflow,
95 95
}
96 96
97 97
/// Active output section.
98 -
export union Section {
98 +
export union Section: Copy {
99 99
    /// Instruction section.
100 100
    Text,
101 101
    /// Data byte section.
102 102
    Data,
103 103
}
104 104
105 105
/// Branch opcode that needs fixup.
106 -
export union BranchOp {
106 +
export union BranchOp: Copy {
107 107
    /// Branch if equal.
108 108
    Beq,
109 109
    /// Branch if not equal.
110 110
    Bne,
111 111
    /// Branch if less than, signed.
121 121
    /// Branch if greater than, signed pseudo-instruction.
122 122
    Bgt,
123 123
}
124 124
125 125
/// Parser and encoder behavior for one instruction mnemonic.
126 -
export union InstructionEncoder {
126 +
export union InstructionEncoder: Copy {
127 127
    /// No-operand instruction encoded by a fixed encoder.
128 128
    NoOperand { enc: fn() -> u32 },
129 129
    /// Load-immediate pseudo-instruction.
130 130
    Li,
131 131
    /// Load-address pseudo-instruction.
163 163
    /// Upper-immediate operand form.
164 164
    Upper { enc: fn(gen::Reg, i32) -> u32 },
165 165
}
166 166
167 167
/// Classified directive name.
168 -
export union DirectiveKind {
168 +
export union DirectiveKind: Copy {
169 169
    /// `.align` directive.
170 170
    Align,
171 171
    /// `.ascii` directive.
172 172
    Ascii,
173 173
    /// `.byte` directive.
187 187
    /// `.word` directive.
188 188
    Word,
189 189
}
190 190
191 191
/// Instruction descriptor table row.
192 -
record InstructionEntry {
192 +
record InstructionEntry: Copy {
193 193
    /// Assembly mnemonic text.
194 194
    name: *[u8],
195 195
    /// Operand parser and encoder behavior.
196 196
    encoder: InstructionEncoder,
197 197
}
198 198
199 199
/// Directive descriptor table row.
200 -
record DirectiveEntry {
200 +
record DirectiveEntry: Copy {
201 201
    /// Directive name without the leading `.`.
202 202
    name: *[u8],
203 203
    /// Parser behavior for the directive.
204 204
    kind: DirectiveKind,
205 205
}
206 206
207 207
/// Register descriptor table row.
208 -
record RegisterEntry {
208 +
record RegisterEntry: Copy {
209 209
    /// Register alias text without the leading `%`.
210 210
    name: *[u8],
211 211
    /// Numeric register selected by the alias.
212 212
    reg: gen::Reg,
213 213
}
214 214
215 215
/// CSR descriptor table row.
216 -
record CsrEntry {
216 +
record CsrEntry: Copy {
217 217
    /// CSR name text.
218 218
    name: *[u8],
219 219
    /// Numeric CSR address.
220 220
    csr: u32,
221 221
}
222 222
223 223
/// Width of an integer data directive.
224 -
export union DataWidth {
224 +
export union DataWidth: Copy {
225 225
    /// 32-bit data value.
226 226
    Word,
227 227
    /// 64-bit data value.
228 228
    Dword,
229 229
}
416 416
    { name: "mtval",    csr: 0x343 },
417 417
    { name: "mtvec",    csr: 0x305 },
418 418
];
419 419
420 420
/// Recorded symbol definition.
421 -
export record Symbol {
421 +
export record Symbol: Copy {
422 422
    /// Symbol name.
423 423
    name: *[u8],
424 424
    /// Section the symbol belongs to.
425 425
    section: Section,
426 426
    /// Byte offset within the section.
428 428
    /// Whether `.export` exported this symbol outside its assembly fragment.
429 429
    isExported: bool,
430 430
}
431 431
432 432
/// Information needed to resolve a pending symbol reference.
433 -
export union FixupInfo {
433 +
export union FixupInfo: Copy {
434 434
    /// Branch to a text label.
435 435
    Branch { op: BranchOp, rs1: gen::Reg, rs2: gen::Reg, index: u32 },
436 436
    /// JAL-like jump to a text label.
437 437
    Jal { rd: gen::Reg, index: u32 },
438 438
    /// Absolute address materialization into a register.
442 442
    /// A 64-bit data word referring to a symbol offset.
443 443
    Dword { offset: u32 },
444 444
}
445 445
446 446
/// Pending symbol reference.
447 -
export record Fixup {
447 +
export record Fixup: Copy {
448 448
    /// Referenced symbol.
449 449
    symbol: *[u8],
450 450
    /// Fixup payload.
451 451
    info: FixupInfo,
452 452
}
453 453
454 454
/// Parser and emission state.
455 -
export record Assembler {
455 +
export record Assembler: Copy {
456 456
    /// Allocation arena for temporary assembler state.
457 457
    arena: *mut alloc::Arena,
458 458
    /// Assembler lexical scanner.
459 459
    scan: scanner::Scanner,
460 460
    /// Output text buffer.
lib/std/arch/rv64/asm/parser.rad +1 -1
11 11
12 12
use super::emit;
13 13
use super::scanner;
14 14
15 15
/// Parsed memory operand with base register and signed byte offset.
16 -
record MemOperand {
16 +
record MemOperand: Copy {
17 17
    /// Base register inside the memory operand parentheses.
18 18
    base: gen::Reg,
19 19
    /// Signed byte offset preceding the base register.
20 20
    offset: i32,
21 21
}
lib/std/arch/rv64/asm/scanner.rad +4 -4
3 3
4 4
use std::char;
5 5
use std::lang::strings;
6 6
7 7
/// Token kinds recognized by the assembler scanner.
8 -
export union TokenKind {
8 +
export union TokenKind: Copy {
9 9
    /// Special end-of-file token generated when the input is exhausted.
10 10
    Eof,
11 11
    /// Special invalid token carrying an error message in [`Token::source`].
12 12
    Invalid,
13 13
40 40
    /// Integer literal token.
41 41
    Number,
42 42
}
43 43
44 44
/// Describes where assembler source originated from.
45 -
export union SourceKind {
45 +
export union SourceKind: Copy {
46 46
    /// Source loaded from a file at the given path.
47 47
    File { path: *[u8] },
48 48
    /// Source provided as an inline string.
49 49
    String,
50 50
}
51 51
52 52
/// Lexical scanner state for assembler source.
53 -
export record Scanner {
53 +
export record Scanner: Copy {
54 54
    /// Origin of the source being scanned.
55 55
    sourceKind: SourceKind,
56 56
    /// Source buffer.
57 57
    source: *[u8],
58 58
    /// Offset of the current token in `source`.
66 66
    /// Intern pool for identifier-shaped token text.
67 67
    pool: *mut strings::Pool,
68 68
}
69 69
70 70
/// Individual token with kind, source text, and byte offset.
71 -
export record Token {
71 +
export record Token: Copy {
72 72
    /// Token kind.
73 73
    kind: TokenKind,
74 74
    /// Token source text.
75 75
    source: *[u8],
76 76
    /// Byte offset of `source` in the input buffer.
lib/std/arch/rv64/decode.rad +1 -1
101 101
/////////////////////////
102 102
// Decoded Instruction //
103 103
/////////////////////////
104 104
105 105
/// Decoded RV64 instruction.
106 -
export union Instr {
106 +
export union Instr: Copy {
107 107
    // R-type ALU.
108 108
    Add  { rd: gen::Reg, rs1: gen::Reg, rs2: gen::Reg },
109 109
    Sub  { rd: gen::Reg, rs1: gen::Reg, rs2: gen::Reg },
110 110
    Sll  { rd: gen::Reg, rs1: gen::Reg, rs2: gen::Reg },
111 111
    Slt  { rd: gen::Reg, rs1: gen::Reg, rs2: gen::Reg },
lib/std/arch/rv64/emit.rad +10 -10
29 29
//////////////////////
30 30
// Emission Context //
31 31
//////////////////////
32 32
33 33
/// Branch/jump that needs offset patching after all blocks are emitted.
34 -
export record PendingBranch {
34 +
export record PendingBranch: Copy {
35 35
    /// Index into code buffer where the branch instruction is.
36 36
    index: u32,
37 37
    /// Target block index.
38 38
    target: u32,
39 39
    /// Type of branch for re-encoding.
40 40
    kind: BranchKind,
41 41
}
42 42
43 43
/// Type of branch instruction.
44 -
export union BranchKind {
44 +
export union BranchKind: Copy {
45 45
    /// Conditional branch (B-type encoding).
46 46
    Cond { op: il::CmpOp, rs1: gen::Reg, rs2: gen::Reg },
47 47
    /// Inverted conditional branch (B-type encoding with negated condition).
48 48
    InvertedCond { op: il::CmpOp, rs1: gen::Reg, rs2: gen::Reg },
49 49
    /// Unconditional jump (J-type encoding).
50 50
    Jump,
51 51
}
52 52
53 53
/// Function call that needs offset patching.
54 -
export record PendingCall {
54 +
export record PendingCall: Copy {
55 55
    /// Index in code buffer where the call was emitted.
56 56
    index: u32,
57 57
    /// Target function name.
58 58
    target: *[u8],
59 59
}
60 60
61 61
/// Assembly jump that needs offset patching after all text is emitted.
62 -
export record PendingJump {
62 +
export record PendingJump: Copy {
63 63
    /// Index in code buffer where the jump was emitted.
64 64
    index: u32,
65 65
    /// Target function name.
66 66
    target: *[u8],
67 67
    /// Destination register.
68 68
    rd: gen::Reg,
69 69
}
70 70
71 71
/// Address load that needs patching after layout is known.
72 -
export record PendingAddrLoad {
72 +
export record PendingAddrLoad: Copy {
73 73
    /// Index in code buffer where the load was emitted.
74 74
    index: u32,
75 75
    /// Target function or data symbol name.
76 76
    target: *[u8],
77 77
    /// Destination register.
79 79
    /// Whether this is an absolute data symbol address.
80 80
    isData: bool,
81 81
}
82 82
83 83
/// Adjusted base register and offset for addressing.
84 -
export record AdjustedOffset {
84 +
export record AdjustedOffset: Copy {
85 85
    /// Base register.
86 86
    base: gen::Reg,
87 87
    /// Byte offset from register.
88 88
    offset: i32,
89 89
}
90 90
91 91
/// Callee-saved register with its stack offset.
92 -
export record SavedReg {
92 +
export record SavedReg: Copy {
93 93
    /// Register to save/restore.
94 94
    reg: gen::Reg,
95 95
    /// Offset from SP.
96 96
    offset: i32,
97 97
}
98 98
99 99
/// Emission context. Tracks state during code generation.
100 -
export record Emitter {
100 +
export record Emitter: Copy {
101 101
    /// Allocator for growing append-backed emitter lists.
102 102
    allocator: alloc::Allocator,
103 103
    /// Emitted instructions storage.
104 104
    code: *mut [u32],
105 105
    /// Current number of emitted instructions.
121 121
    /// Number of debug entries recorded.
122 122
    debugEntriesLen: u32,
123 123
}
124 124
125 125
/// Computed stack frame layout for a function.
126 -
export record Frame {
126 +
export record Frame: Copy {
127 127
    /// Total frame size in bytes (aligned).
128 128
    totalSize: i32,
129 129
    /// Callee-saved registers and their offsets.
130 130
    // TODO: Use constant length when language supports it.
131 131
    savedRegs: [SavedReg; super::NUM_SAVED_REGISTERS],
453 453
/////////////////////////
454 454
// Immediate Handling  //
455 455
/////////////////////////
456 456
457 457
/// Split immediate into `hi` and `lo` bits.
458 -
export record SplitImm {
458 +
export record SplitImm: Copy {
459 459
    /// Upper 20 bits.
460 460
    hi: i32,
461 461
    /// Lower 12 bits.
462 462
    lo: i32,
463 463
}
lib/std/arch/rv64/isel.rad +6 -6
63 63
constant U8_MAX: i64 = 255;
64 64
constant U16_MAX: i64 = 65535;
65 65
constant U32_MAX: i64 = 4294967295;
66 66
67 67
/// Binary operation.
68 -
union BinOp { Add, And, Or, Xor }
68 +
union BinOp: Copy { Add, And, Or, Xor }
69 69
/// Shift operation.
70 -
union ShiftOp { Sll, Srl, Sra }
70 +
union ShiftOp: Copy { Sll, Srl, Sra }
71 71
/// Compare operation.
72 -
union CmpOp { Slt, Ult }
72 +
union CmpOp: Copy { Slt, Ult }
73 73
74 74
/// A pending spill store to be flushed after instruction selection.
75 -
record PendingSpill {
75 +
record PendingSpill: Copy {
76 76
    /// The SSA register that was spilled.
77 77
    ssa: il::Reg,
78 78
    /// The physical register holding the value to store.
79 79
    rd: gen::Reg,
80 80
}
82 82
////////////////////
83 83
// Selector State //
84 84
////////////////////
85 85
86 86
/// Instruction selector state.
87 -
export record Selector {
87 +
export record Selector: Copy {
88 88
    /// Emitter for outputting instructions.
89 89
    e: *mut emit::Emitter,
90 90
    /// Register allocation result.
91 91
    ralloc: *regalloc::AllocResult,
92 92
    /// Total stack frame size.
263 263
////////////////////////
264 264
// Instruction Select //
265 265
////////////////////////
266 266
267 267
/// Pre-scan result for reserve analysis.
268 -
record ReserveInfo {
268 +
record ReserveInfo: Copy {
269 269
    /// Total size needed for constant-sized reserves.
270 270
    size: i32,
271 271
    /// Whether any dynamic-sized reserves exist.
272 272
    isDynamic: bool,
273 273
}
lib/std/collections/dict.rad +2 -2
4 4
//! of two and is provided by the caller via arena-allocated storage.
5 5
6 6
use std::mem;
7 7
8 8
/// Hash map entry.
9 -
export record Entry {
9 +
export record Entry: Copy {
10 10
    /// Key.
11 11
    key: *[u8],
12 12
    /// Associated value.
13 13
    value: i32,
14 14
}
15 15
16 16
/// Open-addressed hash map with caller-provided storage.
17 -
export record Dict {
17 +
export record Dict: Copy {
18 18
    /// Hash table entries.
19 19
    entries: *mut [Entry],
20 20
    /// Number of occupied entries.
21 21
    count: u32,
22 22
}
lib/std/fmt.rad +3 -3
13 13
export constant I64_STR_LEN: u32 = 20;
14 14
/// Maximum string length for a formatted bool (eg. "false").
15 15
export constant BOOL_STR_LEN: u32 = 5;
16 16
17 17
/// Radix/base of a parsed integer literal.
18 -
export union Radix {
18 +
export union Radix: Copy {
19 19
    /// Binary literal (0b...).
20 20
    Binary,
21 21
    /// Decimal literal.
22 22
    Decimal,
23 23
    /// Hexadecimal literal (0x...).
24 24
    Hex,
25 25
}
26 26
27 27
/// Errors reported while parsing literal text.
28 -
export union ParseError {
28 +
export union ParseError: Copy {
29 29
    /// Literal text was empty or missing required digits.
30 30
    Invalid,
31 31
    /// Literal contained an invalid digit for its radix.
32 32
    InvalidDigit,
33 33
    /// Literal value exceeded the supported range.
34 34
    Overflow,
35 35
}
36 36
37 37
/// Parsed integer literal metadata.
38 -
export record IntLiteral {
38 +
export record IntLiteral: Copy {
39 39
    /// Raw characters that comprised the literal.
40 40
    text: *[u8],
41 41
    /// Magnitude parsed from the literal.
42 42
    magnitude: u64,
43 43
    /// Radix used by the literal.
lib/std/lang/alloc.rad +3 -3
7 7
@test mod tests;
8 8
9 9
use std::mem;
10 10
11 11
/// Error thrown by allocator.
12 -
export union AllocError {
12 +
export union AllocError: Copy {
13 13
    /// Allocator is out of memory.
14 14
    OutOfMemory,
15 15
}
16 16
17 17
/// Bump allocator backed by a byte slice.
18 18
///
19 19
/// Allocations are made by advancing an offset pointer. Individual allocations
20 20
/// cannot be freed; instead, the entire arena is reset at once via [`reset`].
21 -
export record Arena {
21 +
export record Arena: Copy {
22 22
    /// Backing storage.
23 23
    data: *mut [u8],
24 24
    /// Current allocation offset in bytes.
25 25
    offset: u32,
26 26
}
109 109
/// Bundles an allocation function with an opaque context pointer so that
110 110
/// any allocation strategy (arena, free-list, mmap, pool) can be used
111 111
/// through a uniform interface. The `func` field is called with the context
112 112
/// pointer, a byte size and an alignment, and must return a pointer to
113 113
/// the allocated memory or panic on failure.
114 -
export record Allocator {
114 +
export record Allocator: Copy {
115 115
    /// Allocation function. Returns a pointer to `size` bytes
116 116
    /// aligned to `alignment`, or panics on failure.
117 117
    func: fn(*mut opaque, u32, u32) -> *mut opaque,
118 118
    /// Opaque context pointer passed to `func`.
119 119
    ctx: *mut opaque,
lib/std/lang/ast.rad +49 -49
10 10
export constant MAX_TRAIT_METHODS: u32 = 8;
11 11
12 12
/// Arena for all parser allocations.
13 13
///
14 14
/// Uses a bump allocator for both AST nodes and node pointer arrays.
15 -
export record NodeArena {
15 +
export record NodeArena: Copy {
16 16
    /// Bump allocator for all allocations.
17 17
    arena: alloc::Arena,
18 18
    /// Next node ID to assign. Incremented on each node allocation.
19 19
    nextId: u32,
20 20
}
36 36
37 37
    return @sliceOf(ptr.ptr as *mut *Node, 0, capacity);
38 38
}
39 39
40 40
/// Attribute bit set applied to declarations or fields.
41 -
export union Attribute {
41 +
export union Attribute: Copy {
42 42
    /// Public visibility attribute.
43 43
    Export = 0b1,
44 44
    /// Default implementation attribute.
45 45
    Default = 0b10,
46 46
    /// Extern linkage attribute.
52 52
    /// Declaration may perform unsafe pointer operations.
53 53
    Unsafe = 0b100000,
54 54
}
55 55
56 56
/// Ordered collection of attribute nodes applied to a declaration.
57 -
export record Attributes {
57 +
export record Attributes: Copy {
58 58
    list: *mut [*Node],
59 59
}
60 60
61 61
/// Check if an attributes list contains an attribute.
62 62
export fn attributesContains(self: *Attributes, attr: Attribute) -> bool {
72 72
export fn hasAttribute(attrs: u32, attr: Attribute) -> bool {
73 73
    return (attrs & (attr as u32)) <> 0;
74 74
}
75 75
76 76
/// Signedness of an integer type.
77 -
export union Signedness {
77 +
export union Signedness: Copy {
78 78
    /// Signed, eg. `i8`.
79 79
    Signed,
80 80
    /// Unsigned, eg. `u32`.
81 81
    Unsigned,
82 82
}
83 83
84 84
/// Binary operator kinds used in numeric expressions.
85 -
export union BinaryOp {
85 +
export union BinaryOp: Copy {
86 86
    /// Addition (`+`).
87 87
    Add,
88 88
    /// Subtraction (`-`).
89 89
    Sub,
90 90
    /// Multiplication (`*`).
124 124
    /// Logical exclusive disjunction (`xor`).
125 125
    Xor,
126 126
}
127 127
128 128
/// Unary operator kinds used in expressions.
129 -
export union UnaryOp {
129 +
export union UnaryOp: Copy {
130 130
    /// Logical negation (`not`).
131 131
    Not,
132 132
    /// Arithmetic negation (`-`).
133 133
    Neg,
134 134
    /// Bitwise NOT (`~`).
135 135
    BitNot,
136 136
}
137 137
138 138
/// Builtin function kind.
139 -
export union Builtin {
139 +
export union Builtin: Copy {
140 140
    /// Size of type in bytes (`@sizeOf`).
141 141
    SizeOf,
142 142
    /// Alignment requirement of type (`@alignOf`).
143 143
    AlignOf,
144 144
    /// Construct a slice from pointer, length, and optional capacity (`@sliceOf`).
145 145
    SliceOf,
146 146
}
147 147
148 148
/// Source extent for a node measured in bytes.
149 -
export record Span {
149 +
export record Span: Copy {
150 150
    /// Byte offset from the start of the source file.
151 151
    offset: u32,
152 152
    /// Length of the node in bytes.
153 153
    length: u32,
154 154
}
155 155
156 156
/// Type signature node.
157 -
export union TypeSig {
157 +
export union TypeSig: Copy {
158 158
    /// Absence of type.
159 159
    Void,
160 160
    /// Opaque type.
161 161
    Opaque,
162 162
    /// Boolean type.
220 220
        mutable: bool,
221 221
    },
222 222
}
223 223
224 224
/// Function signature.
225 -
export record FnSig {
225 +
export record FnSig: Copy {
226 226
    /// Parameter type nodes in declaration order.
227 227
    params: *mut [*Node],
228 228
    /// Optional return type node.
229 229
    returnType: ?*Node,
230 230
    /// Throwable type nodes declared in the signature.
231 231
    throwList: *mut [*Node],
232 232
}
233 233
234 234
/// Address-of expression metadata.
235 -
export record AddressOf {
235 +
export record AddressOf: Copy {
236 236
    /// Target expression being referenced.
237 237
    target: *Node,
238 238
    /// Indicates whether the reference is mutable.
239 239
    mutable: bool,
240 240
}
241 241
242 242
/// Compound statement block with optional dedicated scope.
243 -
export record Block {
243 +
export record Block: Copy {
244 244
    /// Statements that belong to this block.
245 245
    statements: *mut [*Node],
246 246
}
247 247
248 248
/// Function call expression.
249 -
export record Call {
249 +
export record Call: Copy {
250 250
    /// Callee expression.
251 251
    callee: *Node,
252 252
    /// Argument expressions in source order.
253 253
    args: *mut [*Node],
254 254
}
255 255
256 256
/// Single argument to a function or record literal, optionally labeled.
257 -
export record Arg {
257 +
export record Arg: Copy {
258 258
    /// Optional label applied to the argument.
259 259
    label: ?*Node,
260 260
    /// Expression supplying the argument value.
261 261
    value: *Node,
262 262
}
263 263
264 264
/// Assignment expression connecting a target and value.
265 -
export record Assign {
265 +
export record Assign: Copy {
266 266
    /// Expression representing the assignment target.
267 267
    left: *Node,
268 268
    /// Expression providing the value being assigned.
269 269
    right: *Node,
270 270
}
271 271
272 272
/// While loop with an optional alternate branch.
273 -
export record While {
273 +
export record While: Copy {
274 274
    /// Condition evaluated before each iteration.
275 275
    condition: *Node,
276 276
    /// Loop body executed while `condition` is true.
277 277
    body: *Node,
278 278
    /// Optional branch executed when the condition is false at entry.
279 279
    elseBranch: ?*Node,
280 280
}
281 281
282 282
/// `while let` loop binding metadata.
283 -
export record WhileLet {
283 +
export record WhileLet: Copy {
284 284
    /// Pattern matching structure.
285 285
    pattern: PatternMatch,
286 286
    /// Loop body executed when the pattern matches.
287 287
    body: *Node,
288 288
    /// Optional branch executed when the match fails immediately.
289 289
    elseBranch: ?*Node,
290 290
}
291 291
292 292
/// Try expression metadata.
293 -
export record Try {
293 +
export record Try: Copy {
294 294
    /// Expression evaluated with implicit error propagation.
295 295
    expr: *Node,
296 296
    /// Catch clauses. Empty for propagation (`try`), `try!`, or `try?`.
297 297
    catches: *mut [*Node],
298 298
    /// Whether the try should panic instead of returning an error.
300 300
    /// Whether the try should return an optional instead of propagating error.
301 301
    returnsOptional: bool,
302 302
}
303 303
304 304
/// A single catch clause in a `try ... catch` expression.
305 -
export record CatchClause {
305 +
export record CatchClause: Copy {
306 306
    /// Optional identifier binding for the error value (eg. `e`).
307 307
    binding: ?*Node,
308 308
    /// Optional type annotation after `as` (eg. `IoError`).
309 309
    typeNode: ?*Node,
310 310
    /// Block body executed when this clause matches.
311 311
    body: *Node,
312 312
}
313 313
314 314
/// `for` loop metadata.
315 -
export record For {
315 +
export record For: Copy {
316 316
    /// Loop variable binding.
317 317
    binding: *Node,
318 318
    /// Optional index binding for enumeration loops.
319 319
    index: ?*Node,
320 320
    /// Expression producing the iterable value.
324 324
    /// Optional branch executed when the loop body never runs.
325 325
    elseBranch: ?*Node,
326 326
}
327 327
328 328
/// Conditional `if` statement metadata.
329 -
export record If {
329 +
export record If: Copy {
330 330
    /// Condition controlling the branch.
331 331
    condition: *Node,
332 332
    /// Branch executed when `condition` is true.
333 333
    thenBranch: *Node,
334 334
    /// Optional branch executed when `condition` is false.
335 335
    elseBranch: ?*Node,
336 336
}
337 337
338 338
/// Conditional expression (`<true> if <condition> else <false>`).
339 -
export record CondExpr {
339 +
export record CondExpr: Copy {
340 340
    /// Condition controlling which branch is evaluated.
341 341
    condition: *Node,
342 342
    /// Expression evaluated when `condition` is true.
343 343
    thenExpr: *Node,
344 344
    /// Expression evaluated when `condition` is false.
345 345
    elseExpr: *Node,
346 346
}
347 347
348 348
/// Classification of pattern matches (if-let, while-let, let-else).
349 -
export union PatternKind {
349 +
export union PatternKind: Copy {
350 350
    /// Case pattern match.
351 351
    Case,
352 352
    /// Binding pattern match.
353 353
    Binding,
354 354
}
355 355
356 356
/// Prong arm.
357 -
export union ProngArm {
357 +
export union ProngArm: Copy {
358 358
    /// Case arm with pattern list.
359 359
    Case(*mut [*Node]),
360 360
    /// Binding arm with single identifier or placeholder.
361 361
    Binding(*Node),
362 362
    /// Else arm.
363 363
    Else,
364 364
}
365 365
366 366
/// Common pattern matching structure used by `if let`, `while let`, and `let-else`.
367 -
export record PatternMatch {
367 +
export record PatternMatch: Copy {
368 368
    /// Pattern or binding to match against.
369 369
    pattern: *Node,
370 370
    /// Scrutinee expression to match against.
371 371
    scrutinee: *Node,
372 372
    /// Optional guard that must evaluate to `true`.
376 376
    /// Whether the binding is mutable.
377 377
    mutable: bool,
378 378
}
379 379
380 380
/// `if let` conditional binding metadata.
381 -
export record IfLet {
381 +
export record IfLet: Copy {
382 382
    /// Pattern matching structure.
383 383
    pattern: PatternMatch,
384 384
    /// Branch executed when the pattern matches.
385 385
    thenBranch: *Node,
386 386
    /// Optional branch executed when the match fails.
387 387
    elseBranch: ?*Node,
388 388
}
389 389
390 390
/// `let-else` statement metadata.
391 -
export record LetElse {
391 +
export record LetElse: Copy {
392 392
    /// Pattern matching structure.
393 393
    pattern: PatternMatch,
394 394
    /// Else branch executed if match fails (must diverge).
395 395
    elseBranch: *Node,
396 396
}
397 397
398 398
/// `match` statement metadata.
399 -
export record Match {
399 +
export record Match: Copy {
400 400
    /// Expression whose value controls the match.
401 401
    subject: *Node,
402 402
    /// Prong nodes evaluated in order.
403 403
    prongs: *mut [*Node],
404 404
}
405 405
406 406
/// `match` prong metadata.
407 -
export record MatchProng {
407 +
export record MatchProng: Copy {
408 408
    /// Prong arm.
409 409
    arm: ProngArm,
410 410
    /// Optional guard that must evaluate to `true`.
411 411
    guard: ?*Node,
412 412
    /// Body executed when patterns match and guard passes.
413 413
    body: *Node,
414 414
}
415 415
416 416
/// `let` binding.
417 -
export record Let {
417 +
export record Let: Copy {
418 418
    /// Identifier bound by the declaration.
419 419
    ident: *Node,
420 420
    /// Declared type annotation.
421 421
    type: ?*Node,
422 422
    /// Initializer expression.
426 426
    /// Whether the variable is mutable.
427 427
    mutable: bool,
428 428
}
429 429
430 430
/// Constant declaration.
431 -
export record ConstDecl {
431 +
export record ConstDecl: Copy {
432 432
    /// Identifier bound by the declaration.
433 433
    ident: *Node,
434 434
    /// Declared type annotation.
435 435
    type: *Node,
436 436
    /// Constant initializer expression.
438 438
    /// Optional attribute list applied to the constant.
439 439
    attrs: ?Attributes,
440 440
}
441 441
442 442
/// Static storage declaration.
443 -
export record StaticDecl {
443 +
export record StaticDecl: Copy {
444 444
    /// Identifier bound by the declaration.
445 445
    ident: *Node,
446 446
    /// Declared storage type.
447 447
    type: *Node,
448 448
    /// Initialization expression.
450 450
    /// Optional attribute list applied to the static.
451 451
    attrs: ?Attributes,
452 452
}
453 453
454 454
/// Function parameter declaration.
455 -
export record FnParam {
455 +
export record FnParam: Copy {
456 456
    /// Parameter identifier.
457 457
    name: *Node,
458 458
    /// Parameter type annotation.
459 459
    type: *Node,
460 460
}
461 461
462 462
/// Record literal expression metadata.
463 -
export record RecordLit {
463 +
export record RecordLit: Copy {
464 464
    /// Type name associated with the literal.
465 465
    /// If `nil`, it's an anonymous record literal.
466 466
    typeName: ?*Node,
467 467
    /// Field initializer nodes.
468 468
    fields: *mut [*Node],
469 469
    /// When true, remaining fields are discarded (`{ x, .. }`).
470 470
    ignoreRest: bool,
471 471
}
472 472
473 473
/// Record declaration.
474 -
export record RecordDecl {
474 +
export record RecordDecl: Copy {
475 475
    /// Identifier naming the record.
476 476
    name: *Node,
477 477
    /// Field declaration nodes.
478 478
    fields: *mut [*Node],
479 479
    /// Optional attribute list applied to the record.
483 483
    /// Whether this record has labeled fields.
484 484
    labeled: bool,
485 485
}
486 486
487 487
/// Union declarations.
488 -
export record UnionDecl {
488 +
export record UnionDecl: Copy {
489 489
    /// Identifier naming the union.
490 490
    name: *Node,
491 491
    /// Variant nodes making up the union.
492 492
    variants: *mut [*Node],
493 493
    /// Optional attribute list applied to the union.
495 495
    /// Trait derivations attached to the union.
496 496
    derives: *mut [*Node],
497 497
}
498 498
499 499
/// Union variant declaration.
500 -
export record UnionDeclVariant {
500 +
export record UnionDeclVariant: Copy {
501 501
    /// Identifier naming the variant.
502 502
    name: *Node,
503 503
    /// Variant index.
504 504
    index: u32,
505 505
    /// Explicit discriminant value, if provided.
507 507
    /// Optional payload type.
508 508
    type: ?*Node,
509 509
}
510 510
511 511
/// Function declaration.
512 -
export record FnDecl {
512 +
export record FnDecl: Copy {
513 513
    /// Identifier naming the function.
514 514
    name: *Node,
515 515
    /// Function type signature.
516 516
    sig: FnSig,
517 517
    /// Optional function body (`nil` for extern functions).
519 519
    /// Optional attribute list applied to the function.
520 520
    attrs: ?Attributes,
521 521
}
522 522
523 523
/// Array repeat literal metadata.
524 -
export record ArrayRepeatLit {
524 +
export record ArrayRepeatLit: Copy {
525 525
    /// Expression providing the repeated value.
526 526
    item: *Node,
527 527
    /// Expression providing the repetition count.
528 528
    count: *Node,
529 529
}
530 530
531 531
/// Module declaration.
532 -
export record Mod {
532 +
export record Mod: Copy {
533 533
    /// Identifier naming the module.
534 534
    name: *Node,
535 535
    /// Optional attribute list applied to the module.
536 536
    attrs: ?Attributes,
537 537
}
538 538
539 539
/// Use declaration for importing modules.
540 -
export record Use {
540 +
export record Use: Copy {
541 541
    /// Access node identifying the imported module.
542 542
    path: *Node,
543 543
    /// Whether this is a wildcard import (e.g. `use ast::*`).
544 544
    wildcard: bool,
545 545
    /// Optional attribute list applied to the use declaration.
546 546
    attrs: ?Attributes,
547 547
}
548 548
549 549
/// Access expression used for field, scope, and index lookups.
550 -
export record Access {
550 +
export record Access: Copy {
551 551
    /// Expression providing the container or namespace.
552 552
    parent: *Node,
553 553
    /// Expression identifying the member, scope element, or index.
554 554
    child: *Node,
555 555
}
556 556
557 557
/// `as` cast expression metadata.
558 -
export record As {
558 +
export record As: Copy {
559 559
    /// Expression being coerced.
560 560
    value: *Node,
561 561
    /// Target type annotation.
562 562
    type: *Node,
563 563
}
564 564
565 565
/// Range expression metadata.
566 -
export record Range {
566 +
export record Range: Copy {
567 567
    /// Optional inclusive start expression.
568 568
    start: ?*Node,
569 569
    /// Optional exclusive end expression.
570 570
    end: ?*Node,
571 571
}
572 572
573 573
/// Binary operation expression, eg. `x * y`.
574 -
export record BinOp {
574 +
export record BinOp: Copy {
575 575
    /// Operator applied to the operands.
576 576
    op: BinaryOp,
577 577
    /// Left-hand operand.
578 578
    left: *Node,
579 579
    /// Right-hand operand.
580 580
    right: *Node,
581 581
}
582 582
583 583
/// Unary operation expression, eg. `-x`.
584 -
export record UnOp {
584 +
export record UnOp: Copy {
585 585
    /// Operator applied to the operand.
586 586
    op: UnaryOp,
587 587
    /// Operand expression.
588 588
    value: *Node,
589 589
}
590 590
591 591
/// Tagged union describing every possible AST node payload.
592 -
export union NodeValue {
592 +
export union NodeValue: Copy {
593 593
    /// Placeholder `_` expression.
594 594
    Placeholder,
595 595
    /// Nil literal (`nil`).
596 596
    Nil,
597 597
    /// Undefined literal (`undefined`).
793 793
        attrs: ?Attributes,
794 794
    },
795 795
}
796 796
797 797
/// Full AST node with shared metadata and variant-specific payload.
798 -
export record Node {
798 +
export record Node: Copy {
799 799
    /// Unique identifier for this node.
800 800
    id: u32,
801 801
    /// Source span describing where the node originated.
802 802
    span: Span,
803 803
    /// Variant-specific payload for the node.
835 835
export fn synthNode(arena: *mut NodeArena, value: NodeValue) -> *mut Node {
836 836
    return allocNode(arena, Span { offset: 0, length: 0 }, value);
837 837
}
838 838
839 839
/// Synthetic module with a single function in it.
840 -
record SynthFnMod {
840 +
record SynthFnMod: Copy {
841 841
    /// The module block.
842 842
    modBody: *Node,
843 843
    /// The function block.
844 844
    fnBody: *Node
845 845
}
lib/std/lang/gen.rad +1 -1
13 13
/// Physical register.
14 14
///
15 15
/// Lightweight wrapper around a register number. Used both in the
16 16
/// target-independent register allocator and in architecture-specific
17 17
/// backends.
18 -
export record Reg(u8);
18 +
export record Reg: Copy(u8);
lib/std/lang/gen/bitset.rad +2 -2
18 18
export fn wordsFor(n: u32) -> u32 {
19 19
    return (n + 31) / 32;
20 20
}
21 21
22 22
/// A fixed-size bitset backed by an array of 32-bit words.
23 -
export record Bitset {
23 +
export record Bitset: Copy {
24 24
    /// Backing storage for bits, organized as 32-bit words.
25 25
    bits: *mut [u32],
26 26
    /// Number of bits this bitset can hold.
27 27
    len: u32,
28 28
}
172 172
        set bs.bits[i] = 0;
173 173
    }
174 174
}
175 175
176 176
/// Iterator state for iterating set bits.
177 -
export record BitIter {
177 +
export record BitIter: Copy {
178 178
    /// Bitset being iterated.
179 179
    bs: *Bitset,
180 180
    /// Current word index.
181 181
    wordIdx: u32,
182 182
    /// Remaining bits in the current word (visited bits cleared).
lib/std/lang/gen/data.rad +2 -2
14 14
/// Size of the data symbol hash table. Must be a power of two
15 15
/// and at least twice the size of [`MAX_DATA_SYMS`].
16 16
export constant DATA_SYM_TABLE_SIZE: u32 = MAX_DATA_SYMS * 2;
17 17
18 18
/// Data symbol entry mapping name to address.
19 -
export record DataSym {
19 +
export record DataSym: Copy {
20 20
    /// Symbol name.
21 21
    name: *[u8],
22 22
    /// Absolute address, including data base address.
23 23
    addr: u32,
24 24
}
25 25
26 26
/// Hash-indexed data symbol map.
27 -
export record DataSymMap {
27 +
export record DataSymMap: Copy {
28 28
    /// Underlying hash table.
29 29
    dict: dict::Dict,
30 30
    /// Fallback linear array for edge cases.
31 31
    syms: *[DataSym],
32 32
}
lib/std/lang/gen/labels.rad +1 -1
10 10
export constant MAX_FUNCS: u32 = 8192;
11 11
/// Size of the function hash table. Must be a power of two.
12 12
export constant FUNC_TABLE_SIZE: u32 = MAX_FUNCS * 2;
13 13
14 14
/// Label tracking for code emission.
15 -
export record Labels {
15 +
export record Labels: Copy {
16 16
    /// Block offsets indexed by block index.
17 17
    /// Per-function, reset each function.
18 18
    blockOffsets: *mut [i32],
19 19
    /// Number of blocks recorded in current function.
20 20
    blockCount: u32,
lib/std/lang/gen/regalloc.rad +2 -2
20 20
21 21
use std::lang::il;
22 22
use std::lang::alloc;
23 23
24 24
/// Target configuration for register allocation.
25 -
export record TargetConfig {
25 +
export record TargetConfig: Copy {
26 26
    /// List of allocatable physical registers.
27 27
    /// Order determines allocation preference.
28 28
    allocatable: *[super::Reg],
29 29
    /// Function argument registers.
30 30
    argRegs: *[super::Reg],
33 33
    /// Size of a spill slot in bytes.
34 34
    slotSize: u32,
35 35
}
36 36
37 37
/// Complete register allocation result.
38 -
export record AllocResult {
38 +
export record AllocResult: Copy {
39 39
    /// SSA register to physical register mapping.
40 40
    assignments: *[?super::Reg],
41 41
    /// Spill slot information.
42 42
    spill: spill::SpillInfo,
43 43
    /// Bitmask of used callee-saved registers.
lib/std/lang/gen/regalloc/assign.rad +3 -3
16 16
/// Maximum number of active register mappings.
17 17
constant MAX_ACTIVE: u32 = 64;
18 18
19 19
/// Register mapping at a program point.
20 20
/// Maps SSA registers to physical registers.
21 -
export record RegMap {
21 +
export record RegMap: Copy {
22 22
    /// SSA (virtual) registers that have mappings.
23 23
    virtRegs: *mut [u32],
24 24
    /// Physical register for each virtual register.
25 25
    physRegs: *mut [gen::Reg],
26 26
    /// Number of active mappings.
27 27
    n: u32,
28 28
}
29 29
30 30
/// Register assignment result, per function.
31 -
export record AssignInfo {
31 +
export record AssignInfo: Copy {
32 32
    /// SSA register -> physical register mapping.
33 33
    assignments: *mut [?gen::Reg],
34 34
    /// Bitmask of used callee-saved registers.
35 35
    usedCalleeSaved: u32,
36 36
}
37 37
38 38
/// Per-instruction context for freeing and allocating register uses.
39 -
record InstrCtx {
39 +
record InstrCtx: Copy {
40 40
    current: *mut RegMap,
41 41
    usedRegs: *mut bitset::Bitset,
42 42
    func: *il::Fn,
43 43
    live: *liveness::LiveInfo,
44 44
    blockIdx: u32,
lib/std/lang/gen/regalloc/liveness.rad +3 -3
30 30
31 31
/// Maximum number of SSA registers supported.
32 32
export constant MAX_SSA_REGS: u32 = 8192;
33 33
34 34
/// Liveness information for a function.
35 -
export record LiveInfo {
35 +
export record LiveInfo: Copy {
36 36
    /// Per-block live-in sets (indexed by block index).
37 37
    liveIn: *mut [bitset::Bitset],
38 38
    /// Per-block live-out sets (indexed by block index).
39 39
    liveOut: *mut [bitset::Bitset],
40 40
    /// Per-block defs sets (registers defined in block).
46 46
    /// Maximum register number used.
47 47
    maxReg: u32,
48 48
}
49 49
50 50
/// Context for collecting defs and uses during block analysis.
51 -
record DefsUses {
51 +
record DefsUses: Copy {
52 52
    defs: *bitset::Bitset,
53 53
    uses: *mut bitset::Bitset,
54 54
}
55 55
56 56
/// Context for searching for a specific register in an instruction.
57 -
record FindCtx {
57 +
record FindCtx: Copy {
58 58
    target: u32,
59 59
    found: bool,
60 60
}
61 61
62 62
/// Compute liveness information for a function.
lib/std/lang/gen/regalloc/spill.rad +5 -5
39 39
constant MAX_CANDIDATES: u32 = 256;
40 40
/// Maximum loop depth for cost weighting (2^10 = 1024).
41 41
constant MAX_LOOP_WEIGHT: u32 = 10;
42 42
43 43
/// Spill cost for a single SSA register.
44 -
record SpillCost {
44 +
record SpillCost: Copy {
45 45
    /// Number of definitions (weighted by loop depth).
46 46
    defs: u32,
47 47
    /// Number of uses (weighted by loop depth).
48 48
    uses: u32,
49 49
}
50 50
51 51
/// Spill decision for a function.
52 -
export record SpillInfo {
52 +
export record SpillInfo: Copy {
53 53
    /// SSA register mapped to stack slot offset. `-1` means not spilled.
54 54
    slots: *mut [i32],
55 55
    /// Total spill frame size needed in bytes.
56 56
    frameSize: i32,
57 57
    /// Values that must be allocated in callee-saved registers.
59 59
    /// Maximum SSA register number.
60 60
    maxReg: u32,
61 61
}
62 62
63 63
/// Candidate buffer for spill decisions.
64 -
record Candidates {
64 +
record Candidates: Copy {
65 65
    entries: [CostEntry; 256],
66 66
    n: u32,
67 67
}
68 68
69 69
/// Entry for cost sorting.
70 -
record CostEntry {
70 +
record CostEntry: Copy {
71 71
    reg: u32,
72 72
    cost: u32,
73 73
}
74 74
75 75
/// Context for counting register uses.
76 -
record CountCtx {
76 +
record CountCtx: Copy {
77 77
    costs: *mut [SpillCost],
78 78
    weight: u32,
79 79
}
80 80
81 81
/// Analyze a function and determine which values need spill slots.
lib/std/lang/gen/types.rad +2 -2
1 1
//! Target-independent code generation types.
2 2
//!
3 3
//! Defines common records used by all code generation backends.
4 4
5 5
/// Function address entry for printing.
6 -
export record FuncAddr {
6 +
export record FuncAddr: Copy {
7 7
    /// Function name.
8 8
    name: *[u8],
9 9
    /// Instruction index where this function starts.
10 10
    index: u32,
11 11
}
12 12
13 13
/// Debug entry mapping an instruction to a source location.
14 -
export record DebugEntry {
14 +
export record DebugEntry: Copy {
15 15
    /// Byte offset of the instruction from the start of the program.
16 16
    pc: u32,
17 17
    /// Module identifier.
18 18
    moduleId: u16,
19 19
    /// Byte offset into the module's source file.
lib/std/lang/il.rad +16 -16
65 65
66 66
/// Source location for debug info.
67 67
///
68 68
/// Associates an IL instruction with its originating source module and
69 69
/// byte offset.
70 -
export record SrcLoc {
70 +
export record SrcLoc: Copy {
71 71
    /// Module identifier.
72 72
    moduleId: u16,
73 73
    /// Byte offset into the module's source file.
74 74
    offset: u32,
75 75
}
102 102
///////////
103 103
// Types //
104 104
///////////
105 105
106 106
/// IL type representation. Integer signedness is encoded in operations, not types.
107 -
export union Type {
107 +
export union Type: Copy {
108 108
    /// 8-bit value.
109 109
    W8,
110 110
    /// 16-bit value.
111 111
    W16,
112 112
    /// 32-bit value.
124 124
        case Type::W64 => return 8,
125 125
    }
126 126
}
127 127
128 128
/// SSA register reference.
129 -
export record Reg { n: u32 }
129 +
export record Reg: Copy { n: u32 }
130 130
131 131
/// Instruction value.
132 -
export union Val {
132 +
export union Val: Copy {
133 133
    /// Register reference.
134 134
    Reg(Reg),
135 135
    /// Immediate integer value.
136 136
    Imm(i64),
137 137
    /// Data symbol address (globals, constants, string literals).
143 143
    /// eg. in void returns.
144 144
    Undef,
145 145
}
146 146
147 147
/// Comparison operation for compare-and-branch.
148 -
export union CmpOp { Eq, Ne, Slt, Ult }
148 +
export union CmpOp: Copy { Eq, Ne, Slt, Ult }
149 149
150 150
/// Binary ALU operation kind.
151 -
export union BinOp {
151 +
export union BinOp: Copy {
152 152
    // Arithmetic.
153 153
    Add, Sub, Mul, Sdiv, Udiv, Srem, Urem,
154 154
    // Comparison.
155 155
    Eq, Ne, Slt, Sge, Ult, Uge,
156 156
    // Bitwise.
157 157
    And, Or, Xor, Shl, Sshr, Ushr,
158 158
}
159 159
160 160
/// Unary ALU operation kind.
161 -
export union UnOp {
161 +
export union UnOp: Copy {
162 162
    Neg, Not,
163 163
}
164 164
165 165
//////////////////
166 166
// Instructions //
167 167
//////////////////
168 168
169 169
/// Block parameter.
170 -
export record Param {
170 +
export record Param: Copy {
171 171
    /// SSA register.
172 172
    value: Reg,
173 173
    /// Parameter type.
174 174
    type: Type,
175 175
}
176 176
177 177
/// Switch case mapping a constant value to a branch target.
178 -
export record SwitchCase {
178 +
export record SwitchCase: Copy {
179 179
    /// The constant value to match against.
180 180
    value: i64,
181 181
    /// The target block index.
182 182
    target: u32,
183 183
    /// Arguments to pass to the target block.
184 184
    args: *mut [Val],
185 185
}
186 186
187 187
/// IL instruction.
188 188
/// SSA registers are represented as `Reg`, values as `Val`.
189 -
export union Instr {
189 +
export union Instr: Copy {
190 190
    ///////////////////////
191 191
    // Memory operations //
192 192
    ///////////////////////
193 193
194 194
    /// Allocate space on the stack: `reserve %dst <size> <alignment>;`
307 307
///
308 308
/// Basic blocks are instruction sequences with a single entry point and no branch
309 309
/// instruction, except possibly at the end of the sequence, where a terminator
310 310
/// may be found, ie. an instruction that terminates the sequence by jumping
311 311
/// to another sequence.
312 -
export record Block {
312 +
export record Block: Copy {
313 313
    /// Block label.
314 314
    label: *[u8],
315 315
    /// Block parameters.
316 316
    params: *[Param],
317 317
    /// Instructions in the block. The last instruction must be a terminator.
325 325
    /// Used for spill cost weighting in register allocation.
326 326
    loopDepth: u32,
327 327
}
328 328
329 329
/// An IL function.
330 -
export record Fn {
330 +
export record Fn: Copy {
331 331
    /// Qualified function name (e.g. `$mod$path$func`).
332 332
    name: *[u8],
333 333
    /// Function parameters.
334 334
    params: *[Param],
335 335
    /// Return type.
345 345
/////////////
346 346
// Program //
347 347
/////////////
348 348
349 349
/// Data initializer item.
350 -
export union DataItem {
350 +
export union DataItem: Copy {
351 351
    /// Typed value: `w32 42;` or `w8 255;`
352 352
    Val { typ: Type, val: i64 },
353 353
    /// Symbol reference: `$symbol`
354 354
    Sym(*[u8]),
355 355
    /// Function reference: `$fnName`
359 359
    /// Undefined value. Used for padding and `void` returns.
360 360
    Undef,
361 361
}
362 362
363 363
/// Data initializer value with optional repeat count.
364 -
export record DataValue {
364 +
export record DataValue: Copy {
365 365
    /// The item contained in the value.
366 366
    item: DataItem,
367 367
    /// The number of times the item should be repeated.
368 368
    count: u32,
369 369
}
370 370
371 371
/// Global data definition.
372 -
export record Data {
372 +
export record Data: Copy {
373 373
    /// Data name.
374 374
    name: *[u8],
375 375
    /// Size in bytes.
376 376
    size: u32,
377 377
    /// Alignment requirement.
386 386
    /// Initializer values.
387 387
    values: *[DataValue],
388 388
}
389 389
390 390
/// An IL program (compilation unit).
391 -
export record Program {
391 +
export record Program: Copy {
392 392
    /// Global data.
393 393
    data: *[Data],
394 394
    /// Functions.
395 395
    fns: *[*Fn],
396 396
}
lib/std/lang/lower.rad +25 -25
107 107
// Error Handling //
108 108
////////////////////
109 109
110 110
/// Lowering errors are typically unrecoverable since they indicate bugs in
111 111
/// the resolver or malformed AST that should have been caught earlier.
112 -
export union LowerError {
112 +
export union LowerError: Copy {
113 113
    /// A node's symbol was not set before lowering.
114 114
    MissingSymbol(*ast::Node),
115 115
    /// A node's type was not set before lowering.
116 116
    MissingType(*ast::Node),
117 117
    /// A node's constant value was not set before lowering.
247 247
//////////////////////////
248 248
// Core Data Structures //
249 249
//////////////////////////
250 250
251 251
/// Options controlling the lowering pass.
252 -
export record LowerOptions {
252 +
export record LowerOptions: Copy {
253 253
    /// Whether to emit source location info.
254 254
    debug: bool,
255 255
    /// Whether to lower `@test` functions.
256 256
    buildTest: bool,
257 257
}
258 258
259 259
/// Role of a lowered function in the final program.
260 -
export union FnRole {
260 +
export union FnRole: Copy {
261 261
    /// Regular function.
262 262
    Normal,
263 263
    /// Program entry function marked with `@default`.
264 264
    Default,
265 265
}
266 266
267 267
/// Function sink used by lowerers that consume functions as they are produced.
268 -
export record FnSink {
268 +
export record FnSink: Copy {
269 269
    /// Opaque context passed to the sink callback.
270 270
    ctx: *mut opaque,
271 271
    /// Callback invoked for each lowered function.
272 272
    emitFn: fn(*mut opaque, *il::Fn, FnRole),
273 273
}
274 274
275 275
/// Destination for functions produced by the lowerer.
276 -
export union FnOutput {
276 +
export union FnOutput: Copy {
277 277
    /// Store lowered functions in the provided slice.
278 278
    Accumulate(*mut [*il::Fn]),
279 279
    /// Send lowered functions to an external consumer immediately.
280 280
    Stream(FnSink),
281 281
}
282 282
283 283
/// Module-level lowering context. Shared across all function lowerings.
284 284
/// Holds global state like the data section (strings, constants) and provides
285 285
/// access to the resolver for type queries.
286 -
export record Lowerer {
286 +
export record Lowerer: Copy {
287 287
    /// Arena for persistent lowering state, including data and symbol names.
288 288
    arena: *mut alloc::Arena,
289 289
    /// Arena for allocations owned by the function currently being lowered.
290 290
    fnArena: *mut alloc::Arena,
291 291
    /// Allocator backed by the arena.
313 313
    /// Lowering options.
314 314
    options: LowerOptions,
315 315
}
316 316
317 317
/// Entry mapping a function symbol to its qualified name.
318 -
record FnSymEntry {
318 +
record FnSymEntry: Copy {
319 319
    sym: *resolver::Symbol,
320 320
    qualName: *[u8],
321 321
}
322 322
323 323
/// Entry in the global error tag table.
324 -
record ErrTagEntry {
324 +
record ErrTagEntry: Copy {
325 325
    /// The type of this error, identified by its interned pointer.
326 326
    ty: resolver::Type,
327 327
    /// The globally unique tag assigned to this error type (non-zero).
328 328
    tag: u32,
329 329
}
377 377
    }
378 378
    return FnRole::Normal;
379 379
}
380 380
381 381
/// Builder for accumulating data values during constant lowering.
382 -
record DataValueBuilder {
382 +
record DataValueBuilder: Copy {
383 383
    allocator: alloc::Allocator,
384 384
    values: *mut [il::DataValue],
385 385
    /// Whether all pushed values can be represented by zero-filled memory.
386 386
    zeroInit: bool,
387 387
}
388 388
389 389
/// Result of lowering constant data.
390 -
record ConstDataResult {
390 +
record ConstDataResult: Copy {
391 391
    values: *[il::DataValue],
392 392
    zeroInit: bool,
393 393
}
394 394
395 395
/// Create a new builder.
442 442
// a mapping from [`Var`] to current SSA value. When control flow merges,
443 443
// block parameters are inserted to merge values from different control flow paths.
444 444
445 445
/// A variable handle. Represents a source-level variable during lowering.
446 446
/// The same [`Var`] can have different SSA values in different blocks.
447 -
export record Var(u32);
447 +
export record Var: Copy(u32);
448 448
449 449
/// Metadata for a source-level variable, stored once per function.
450 450
///
451 451
/// Each variable declaration in the source creates one [`VarData`] entry in the
452 452
/// function's `variables` array, indexed by `id`. This contains static
454 454
///
455 455
/// Per-block SSA values are tracked separately in [`BlockData::vars`] as [`?il::Val`],
456 456
/// where `nil` means "not yet assigned in this block". Together they implement
457 457
/// SSA construction.
458 458
///
459 -
record VarData {
459 +
record VarData: Copy {
460 460
    /// Variable name, used by [`lookupVarByName`] to resolve identifiers.
461 461
    /// Nil for anonymous variables (e.g., internal loop counters).
462 462
    name: ?*[u8],
463 463
    /// IL type of this variable. Set at declaration time and used when
464 464
    /// generating loads, stores, and type-checking assignments.
472 472
    addressTaken: bool,
473 473
}
474 474
475 475
/// Links a function parameter to its corresponding variable for the entry block.
476 476
/// After creating the entry block, we iterate through these to define initial values.
477 -
record FnParamBinding {
477 +
record FnParamBinding: Copy {
478 478
    /// The variable that receives this parameter's value.
479 479
    var: Var,
480 480
    /// SSA register containing the parameter value from the caller.
481 481
    reg: il::Reg,
482 482
}
489 489
// instructions until terminated by a jump, branch, return, or unreachable.
490 490
// Blocks can be created before they're filled (forward references for jumps).
491 491
492 492
/// A handle to a basic block within the current function.
493 493
/// Block handles are stable, they don't change as more blocks are added.
494 -
export record BlockId(u32);
494 +
export record BlockId: Copy(u32);
495 495
496 496
/// Internal block state during construction.
497 497
///
498 498
/// The key invariants:
499 499
///
500 500
/// - A block is "open" if it has no terminator; instructions can be added.
501 501
/// - A block is "sealed" when all predecessor edges are known.
502 502
/// - Sealing is required before SSA construction can insert block parameters.
503 503
///
504 504
/// This differs from the final [`il::Block`] which is immutable and fully formed.
505 -
record BlockData {
505 +
record BlockData: Copy {
506 506
    /// Block label for debugging and IL printing.
507 507
    label: *[u8],
508 508
    /// Block parameters for merging values at control flow joins. These
509 509
    /// receive values from predecessor edges when control flow merges.
510 510
    params: *mut [il::Param],
535 535
///
536 536
/// A block is "unsealed" while its predecessors are still being discovered.
537 537
/// During this time, variables used before being defined locally are tracked.
538 538
/// Once all predecessors are known, the block is sealed and those variables
539 539
/// are resolved via [`resolveBlockArgs`].
540 -
union Sealed {
540 +
union Sealed: Copy {
541 541
    /// Block is unsealed; predecessors may still be added.
542 542
    No { incompleteVars: *mut [u32] },
543 543
    /// Block is sealed; all predecessors are known.
544 544
    Yes,
545 545
}
548 548
// Loop and Control Flow Context //
549 549
///////////////////////////////////
550 550
551 551
/// Context for break/continue statements within a loop.
552 552
/// Each nested loop pushes a new context onto the loop stack.
553 -
export record LoopCtx {
553 +
export record LoopCtx: Copy {
554 554
    /// Where `break` should transfer control (the loop's exit block).
555 555
    breakTarget: BlockId,
556 556
    /// Where `continue` should transfer control.
557 557
    continueTarget: ?BlockId,
558 558
}
559 559
560 560
/// Logical operator.
561 -
union LogicalOp { And, Or }
561 +
union LogicalOp: Copy { And, Or }
562 562
563 563
/// Iterator state for for-loop lowering.
564 -
union ForIter {
564 +
union ForIter: Copy {
565 565
    /// Range iterator: `for i in 0..n`.
566 566
    Range {
567 567
        valVar: Var,
568 568
        indexVar: ?Var,
569 569
        endVal: il::Val,
592 592
// - Optional aggregates: tag checked then payload extracted.
593 593
// - Unions: tag compared against variant indices.
594 594
595 595
/// Cached information about a match subject. Computed once and reused across
596 596
/// all arms to avoid redundant lowering and type queries.
597 -
record MatchSubject {
597 +
record MatchSubject: Copy {
598 598
    /// The lowered subject value.
599 599
    val: il::Val,
600 600
    /// Source-level type from the resolver.
601 601
    type: resolver::Type,
602 602
    /// IL-level type for code generation.
609 609
    /// How bindings are created: by value, or by reference.
610 610
    by: resolver::MatchBy,
611 611
}
612 612
613 613
/// Classifies a match subject by how it should be compared and destructured.
614 -
union MatchSubjectKind {
614 +
union MatchSubjectKind: Copy {
615 615
    /// Regular value: direct equality comparison.
616 616
    Regular,
617 617
    /// Optional with null pointer optimization: `?*T`, `?*[T]`.
618 618
    OptionalPtr,
619 619
    /// Optional aggregate `?T`: tagged union with payload.
639 639
//////////////////////////
640 640
// Field Access Support //
641 641
//////////////////////////
642 642
643 643
/// Result of resolving a place expression to a memory location.
644 -
record FieldRef {
644 +
record FieldRef: Copy {
645 645
    /// Base pointer register (points to the container).
646 646
    base: il::Reg,
647 647
    /// Byte offset of the value within the container.
648 648
    offset: i32,
649 649
    /// Type of the value held at that location.
651 651
}
652 652
653 653
/// Result of computing an element pointer for array/slice subscript operations.
654 654
/// Used by [`lowerElemPtr`] to return both the element address register and
655 655
/// the element type for subsequent load or address-of operations.
656 -
record ElemPtrResult {
656 +
record ElemPtrResult: Copy {
657 657
    /// Register holding the computed element address.
658 658
    elemReg: il::Reg,
659 659
    /// Source-level type of the element.
660 660
    elemType: resolver::Type,
661 661
}
662 662
663 663
/// Result of resolving a slice range to a data pointer and element count.
664 -
record SliceRangeResult {
664 +
record SliceRangeResult: Copy {
665 665
    dataReg: il::Reg,
666 666
    count: il::Val,
667 667
}
668 668
669 669
/////////////////////////////
670 670
// Function Lowering State //
671 671
/////////////////////////////
672 672
673 673
/// Per-function lowering state. Created fresh for each function and contains
674 674
/// all the mutable state needed during function body lowering.
675 -
record FnLowerer {
675 +
record FnLowerer: Copy {
676 676
    /// Reference to the module-level lowerer.
677 677
    low: *mut Lowerer,
678 678
    /// Allocator for IL allocations.
679 679
    allocator: alloc::Allocator,
680 680
    /// Type signature of the function being lowered.
lib/std/lang/module.rad +4 -4
23 23
constant PATH_SEP: u8 = '/';
24 24
/// Source file extension handled by the loader.
25 25
constant SOURCE_EXT: *[u8] = ".rad";
26 26
27 27
/// Lifecycle state for modules in the dependency graph.
28 -
export union ModuleState {
28 +
export union ModuleState: Copy {
29 29
    /// Slot unused or yet to be initialized.
30 30
    Vacant,
31 31
    /// Module registered with a known path but not parsed yet.
32 32
    Registered,
33 33
    /// Module is currently being parsed (used for cycle detection).
39 39
    /// Module finished semantic analysis and is ready for codegen.
40 40
    Ready,
41 41
}
42 42
43 43
/// Error categories that can be produced by the module graph.
44 -
export union ModuleError {
44 +
export union ModuleError: Copy {
45 45
    /// Module not found.
46 46
    NotFound(u16),
47 47
    /// Adding the module would exceed the fixed storage.
48 48
    CapacityExceeded,
49 49
    /// Provided path is missing the required `.rad` extension or otherwise invalid.
53 53
    /// Attempt to register a module before its parent.
54 54
    MissingParent,
55 55
}
56 56
57 57
/// Module metadata recorded inside the dependency graph.
58 -
export record ModuleEntry {
58 +
export record ModuleEntry: Copy {
59 59
    /// Numeric identifier for the slot (index in the graph array).
60 60
    id: u16,
61 61
    /// Package identifier this module belongs to.
62 62
    packageId: u16,
63 63
    /// Parent module identifier, or `nil` for root modules.
83 83
    /// Source text for this module (for error reporting).
84 84
    source: ?*[u8],
85 85
}
86 86
87 87
/// Dense storage for all modules referenced by the compilation unit.
88 -
export record ModuleGraph {
88 +
export record ModuleGraph: Copy {
89 89
    entries: *mut [ModuleEntry],
90 90
    entriesLen: u32,
91 91
    pool: *mut strings::Pool,
92 92
    /// Arena used for all AST node allocations.
93 93
    arena: ?*ast::NodeArena,
lib/std/lang/package.rad +1 -1
7 7
8 8
/// Maximum number of packages processed in a single invocation.
9 9
export constant MAX_PACKAGES: u32 = 4;
10 10
11 11
/// A compilation unit.
12 -
export record Package {
12 +
export record Package: Copy {
13 13
    /// Package identifier (index in the package array).
14 14
    id: u16,
15 15
    /// Package name.
16 16
    name: *[u8],
17 17
    /// Root module identifier for this package, or `nil` if not yet registered.
lib/std/lang/parser.rad +9 -9
25 25
26 26
/// Maximum number of parser errors before aborting.
27 27
constant MAX_ERRORS: u32 = 8;
28 28
29 29
/// Parser error type.
30 -
export union ParseError {
30 +
export union ParseError: Copy {
31 31
    /// Encountered a token that was not expected in the current context.
32 32
    UnexpectedToken,
33 33
}
34 34
35 35
/// Represents a parsed name-type-value triple.
36 36
///
37 37
/// Used for record field declarations, variable declarations,
38 38
/// and record field initializations.
39 -
record NameTypeValue {
39 +
record NameTypeValue: Copy {
40 40
    /// The identifier name.
41 41
    name: *ast::Node,
42 42
    /// The optional type annotation.
43 43
    type: ?*ast::Node,
44 44
    /// The optional initialization value.
46 46
    /// The optional alignment specifier.
47 47
    alignment: ?*ast::Node,
48 48
}
49 49
50 50
/// Behavioural differences when parsing record field lists.
51 -
union RecordFieldMode {
51 +
union RecordFieldMode: Copy {
52 52
    /// Labeled fields, allows for default values.
53 53
    Labeled,
54 54
    /// Unlabeled fields.
55 55
    Unlabeled,
56 56
}
57 57
58 58
/// Parser context differentiates between regular expressions and
59 59
/// conditional contexts where `{` begins a block.
60 -
union Context {
60 +
union Context: Copy {
61 61
    /// Normal expression context where `{` may start a record literal
62 62
    /// and `if` may start a conditional expression.
63 63
    Normal,
64 64
    /// Pattern context where `{` may start a record literal
65 65
    /// but `if` is reserved for guards.
68 68
    /// and `if` is reserved for guards.
69 69
    Condition,
70 70
}
71 71
72 72
/// A single parser error with location information.
73 -
export record Error {
73 +
export record Error: Copy {
74 74
    /// Human-readable error message.
75 75
    message: *[u8],
76 76
    /// The token where the error occurred.
77 77
    token: scanner::Token,
78 78
}
79 79
80 80
/// List of parser errors encountered during parsing.
81 -
record ErrorList {
81 +
record ErrorList: Copy {
82 82
    /// Fixed-size array of error records.
83 83
    list: [Error; MAX_ERRORS],
84 84
    /// Number of errors currently in the list.
85 85
    count: u32,
86 86
}
87 87
88 88
/// Snapshot of parser state for speculative parsing.
89 -
record SavedState {
89 +
record SavedState: Copy {
90 90
    parser: Parser,
91 91
    arena: u32,
92 92
    nextId: u32,
93 93
}
94 94
95 95
/// Operator metadata for precedence climbing.
96 -
record OpInfo {
96 +
record OpInfo: Copy {
97 97
    op: ast::BinaryOp,
98 98
    prec: i32,
99 99
}
100 100
101 101
/// Get operator info for a token kind using match-based dispatch.
142 142
            return nil,
143 143
    }
144 144
}
145 145
146 146
/// Parser state.
147 -
export record Parser {
147 +
export record Parser: Copy {
148 148
    /// The scanner that provides tokens.
149 149
    scanner: scanner::Scanner,
150 150
    /// The current token being examined.
151 151
    current: scanner::Token,
152 152
    /// The most recently consumed token.
lib/std/lang/resolver.rad +52 -52
51 51
constant MAX_LINEAR_BINDINGS: u32 = 32;
52 52
/// Maximum nesting depth tracked for loops.
53 53
constant MAX_LINEAR_LOOP_DEPTH: u32 = 16;
54 54
55 55
/// Trait definition stored in the resolver.
56 -
export record TraitType {
56 +
export record TraitType: Copy {
57 57
    /// Trait name.
58 58
    name: *[u8],
59 59
    /// Method signatures, including from supertraits.
60 60
    methods: *mut [TraitMethod],
61 61
    /// Supertraits that must also be implemented.
62 62
    supertraits: *mut [*TraitType],
63 63
}
64 64
65 65
/// A single method signature within a trait.
66 -
export record TraitMethod {
66 +
export record TraitMethod: Copy {
67 67
    /// Method name.
68 68
    name: *[u8],
69 69
    /// Function type for the method, excluding the receiver.
70 70
    fnType: *FnType,
71 71
    /// Whether the receiver is mutable.
75 75
    /// V-table slot index.
76 76
    index: u32,
77 77
}
78 78
79 79
/// An entry in the trait instance registry.
80 -
export record InstanceEntry {
80 +
export record InstanceEntry: Copy {
81 81
    /// Trait type descriptor.
82 82
    traitType: *TraitType,
83 83
    /// Concrete type that implements the trait.
84 84
    concreteType: Type,
85 85
    /// Name of the concrete type.
89 89
    /// Method symbols for each trait method, in declaration order.
90 90
    methods: *mut [*mut Symbol],
91 91
}
92 92
93 93
/// An entry in the method registry.
94 -
export record MethodEntry {
94 +
export record MethodEntry: Copy {
95 95
    /// Concrete type that owns the method.
96 96
    concreteType: Type,
97 97
    /// Name of the concrete type.
98 98
    concreteTypeName: *[u8],
99 99
    /// Method name.
140 140
141 141
/// Size of a pointer in bytes.
142 142
export constant PTR_SIZE: u32 = 8;
143 143
144 144
/// Information about a record or tuple field.
145 -
export record RecordField {
145 +
export record RecordField: Copy {
146 146
    /// Field name, `nil` for positional fields.
147 147
    name: ?*[u8],
148 148
    /// Field type.
149 149
    fieldType: Type,
150 150
    /// Byte offset from the start of the record.
151 151
    offset: i32,
152 152
}
153 153
154 154
/// Information about a union variant.
155 -
record UnionVariant {
155 +
record UnionVariant: Copy {
156 156
    name: *[u8],
157 157
    valueType: Type,
158 158
    symbol: *mut Symbol,
159 159
}
160 160
161 161
/// Array type payload.
162 -
export record ArrayType {
162 +
export record ArrayType: Copy {
163 163
    item: *Type,
164 164
    length: u32,
165 165
}
166 166
167 167
/// Record nominal type.
168 -
export record RecordType {
168 +
export record RecordType: Copy {
169 169
    fields: *[RecordField],
170 170
    labeled: bool,
171 171
    /// Cached layout.
172 172
    layout: Layout,
173 173
    /// Whether the declaration explicitly carries the `Linear` marker.
175 175
    /// Whether the declaration explicitly carries the `Copy` marker.
176 176
    declaredCopy: bool,
177 177
}
178 178
179 179
/// Union nominal type.
180 -
export record UnionType {
180 +
export record UnionType: Copy {
181 181
    variants: *[UnionVariant],
182 182
    /// Cached layout.
183 183
    layout: Layout,
184 184
    /// Cached payload offset within the union aggregate.
185 185
    valOffset: u32,
190 190
    /// Whether the declaration explicitly carries the `Copy` marker.
191 191
    declaredCopy: bool,
192 192
}
193 193
194 194
/// Metadata for user-defined types.
195 -
export union NominalType {
195 +
export union NominalType: Copy {
196 196
    /// Placeholder for a type that hasn't been fully resolved yet.
197 197
    /// Stores the declaration node for lazy resolution.
198 198
    Placeholder(*ast::Node),
199 199
    Record(RecordType),
200 200
    Union(UnionType),
201 201
}
202 202
203 203
/// Coercion plan, when coercion from one type to another.
204 -
export union Coercion {
204 +
export union Coercion: Copy {
205 205
    /// No coercion, eg. `T -> T`.
206 206
    Identity,
207 207
    /// Eg. `u8 -> i32`. Stores both source and target types for lowering.
208 208
    NumericCast { from: Type, to: Type },
209 209
    /// Eg. `T -> ?T`. Stores the inner value type.
218 218
        inst: *InstanceEntry,
219 219
    },
220 220
}
221 221
222 222
/// Result of resolving a module path.
223 -
record ResolvedModule {
223 +
record ResolvedModule: Copy {
224 224
    /// Module entry in the graph.
225 225
    entry: *module::ModuleEntry,
226 226
    /// Scope containing the module's declarations.
227 227
    scope: *mut Scope,
228 228
}
229 229
230 230
/// Type layout.
231 -
export record Layout {
231 +
export record Layout: Copy {
232 232
    /// Size in bytes.
233 233
    size: u32,
234 234
    /// Alignment in bytes.
235 235
    alignment: u32,
236 236
}
237 237
238 238
/// Computed union layout parameters.
239 -
record UnionLayoutInfo {
239 +
record UnionLayoutInfo: Copy {
240 240
    layout: Layout,
241 241
    valOffset: u32,
242 242
    isAllVoid: bool,
243 243
}
244 244
245 245
/// Pre-computed metadata for slice range expressions.
246 246
/// Used by the lowerer.
247 -
export record SliceRangeInfo {
247 +
export record SliceRangeInfo: Copy {
248 248
    /// Element type of the resulting slice.
249 249
    itemType: *Type,
250 250
    /// Whether the resulting slice is mutable.
251 251
    mutable: bool,
252 252
    /// Static capacity if container is an array.
253 253
    capacity: ?u32,
254 254
}
255 255
256 256
/// Pre-computed metadata for `for` loop iteration.
257 257
/// Used by the lowerer to avoid re-analyzing the iterable type.
258 -
export union ForLoopInfo {
258 +
export union ForLoopInfo: Copy {
259 259
    /// Iterating over a range expression (e.g., `for i in 0..n`).
260 260
    Range {
261 261
        valType: *Type,
262 262
        range: ast::Range,
263 263
        bindingName: ?*[u8],
271 271
        indexName: ?*[u8]
272 272
    },
273 273
}
274 274
275 275
/// Resolved function signature details.
276 -
export record FnType {
276 +
export record FnType: Copy {
277 277
    paramTypes: *[*Type],
278 278
    returnType: *Type,
279 279
    throwList: *[*Type],
280 280
    /// Whether calling this function requires an unsafe context.
281 281
    isUnsafe: bool,
282 282
    localCount: u32,
283 283
}
284 284
285 285
/// Describes a type computed during semantic analysis.
286 -
export union Type {
286 +
export union Type: Copy {
287 287
    /// A type that couldn't be decided.
288 288
    Unknown,
289 289
    /// Types only used during inference.
290 290
    Nil, Undefined, Int,
291 291
    /// Primitive types.
327 327
        mutable: bool,
328 328
    },
329 329
}
330 330
331 331
/// Structured diagnostic payload for type mismatches.
332 -
export record TypeMismatch {
332 +
export record TypeMismatch: Copy {
333 333
    expected: Type,
334 334
    actual: Type,
335 335
}
336 336
337 337
/// Structured diagnostic payload for invalid `as` casts.
338 -
export record InvalidAsCast {
338 +
export record InvalidAsCast: Copy {
339 339
    from: Type,
340 340
    to: Type,
341 341
}
342 342
343 343
/// Diagnostic payload for argument count mismatches.
344 -
export record CountMismatch {
344 +
export record CountMismatch: Copy {
345 345
    expected: u32,
346 346
    actual: u32,
347 347
}
348 348
349 349
/// Detailed payload attached to a symbol, specialized per symbol kind.
350 -
export union SymbolData {
350 +
export union SymbolData: Copy {
351 351
    /// Payload describing mutable bindings like variables or functions.
352 352
    Value {
353 353
        /// Whether the binding permits mutation.
354 354
        mutable: bool,
355 355
        /// Custom alignment requirement, or 0 for default.
390 390
    /// Trait symbol.
391 391
    Trait(*mut TraitType),
392 392
}
393 393
394 394
/// Resolved symbol allocated during semantic analysis.
395 -
export record Symbol {
395 +
export record Symbol: Copy {
396 396
    /// Symbol name in source code.
397 397
    name: *[u8],
398 398
    /// Data associated with the symbol.
399 399
    data: SymbolData,
400 400
    /// Bitset of attributes applied to the declaration.
404 404
    /// Module ID this symbol belongs to. Only for module-level symbols.
405 405
    moduleId: ?u16,
406 406
}
407 407
408 408
/// Integer constant payload.
409 -
export record ConstInt {
409 +
export record ConstInt: Copy {
410 410
    /// Absolute magnitude of the value.
411 411
    magnitude: u64,
412 412
    /// Bit width of the integer.
413 413
    bits: u8,
414 414
    /// Whether the integer is signed.
416 416
    /// Whether the value is negative (only valid when `signed` is true).
417 417
    negative: bool,
418 418
}
419 419
420 420
/// Constant value recorded for literal nodes.
421 -
export union ConstValue {
421 +
export union ConstValue: Copy {
422 422
    Bool(bool),
423 423
    Char(u8),
424 424
    String(*[u8]),
425 425
    Int(ConstInt),
426 426
}
427 427
428 428
/// Integer range metadata for primitive integer types.
429 -
union IntegerRange {
429 +
union IntegerRange: Copy {
430 430
    Signed {
431 431
        bits: u8,
432 432
        min: i64,
433 433
        max: i64,
434 434
        lim: u64,
438 438
        max: u64,
439 439
    },
440 440
}
441 441
442 442
/// Diagnostic emitted by the analyzer.
443 -
export record Error {
443 +
export record Error: Copy {
444 444
    /// Error category.
445 445
    kind: ErrorKind,
446 446
    /// Node associated with the error, if known.
447 447
    node: ?*ast::Node,
448 448
    /// Module ID where this error occurred.
449 449
    moduleId: u16,
450 450
}
451 451
452 452
/// High-level classification for semantic diagnostics.
453 -
export union ErrorKind {
453 +
export union ErrorKind: Copy {
454 454
    /// Identifier declared more than once in the same scope.
455 455
    DuplicateBinding(*[u8]),
456 456
    /// Identifier referenced before it was declared.
457 457
    UnresolvedSymbol(*[u8]),
458 458
    /// Attempted to assign to an immutable binding.
634 634
    /// Internal error.
635 635
    Internal,
636 636
}
637 637
638 638
/// Diagnostics returned by the analyzer.
639 -
export record Diagnostics {
639 +
export record Diagnostics: Copy {
640 640
    errors: *mut [Error],
641 641
}
642 642
643 643
/// Call context.
644 -
union CallCtx {
644 +
union CallCtx: Copy {
645 645
    /// Normal function call.
646 646
    Normal,
647 647
    /// Fallible function call, ie. `try f()`.
648 648
    Try,
649 649
}
650 650
651 651
/// Result of resolving a record literal's type name.
652 -
record ResolvedRecordLitType {
652 +
record ResolvedRecordLitType: Copy {
653 653
    /// The record nominal type to use for field checking.
654 654
    recordType: *NominalType,
655 655
    /// The result type of the literal (record type or union type for variants).
656 656
    resultType: Type,
657 657
}
658 658
659 659
/// Result of checking for a `super` path prefix.
660 -
record SuperAccessResult {
660 +
record SuperAccessResult: Copy {
661 661
    scope: *mut Scope,
662 662
    child: *ast::Node,
663 663
}
664 664
665 665
/// Node-specific resolver metadata.
666 -
export union NodeExtra {
666 +
export union NodeExtra: Copy {
667 667
    /// No extra data for this node.
668 668
    None,
669 669
    /// Resolved field index for record literal fields.
670 670
    RecordField { index: u32 },
671 671
    /// Slice range metadata for subscript expressions with ranges.
692 692
    /// Slice `.delete(index)` method call.
693 693
    SliceDelete { elemType: *Type },
694 694
}
695 695
696 696
/// Combined resolver metadata for a single AST node.
697 -
export record NodeData {
697 +
export record NodeData: Copy {
698 698
    /// Resolved type for this node.
699 699
    ty: Type,
700 700
    /// Coercion plan applied to this node.
701 701
    coercion: Coercion,
702 702
    /// Symbol associated with this node.
708 708
    /// Node-specific extra data.
709 709
    extra: NodeExtra,
710 710
}
711 711
712 712
/// Table storing all resolver metadata indexed by node ID.
713 -
record NodeDataTable {
713 +
record NodeDataTable: Copy {
714 714
    entries: *mut [NodeData],
715 715
}
716 716
717 717
/// Lexical scope.
718 -
export record Scope {
718 +
export record Scope: Copy {
719 719
    /// Owning AST node, or `nil` for the root scope.
720 720
    owner: ?*ast::Node,
721 721
    /// Parent/enclosing scope.
722 722
    parent: ?*mut Scope,
723 723
    /// Module ID if this is a module scope.
727 727
    /// Number of live symbols.
728 728
    symbolsLen: u32,
729 729
}
730 730
731 731
/// An object used by the enter and exit functions for module scopes.
732 -
record ModuleScope {
732 +
record ModuleScope: Copy {
733 733
    /// Module root node.
734 734
    root: *ast::Node,
735 735
    /// Module entry in graph.
736 736
    entry: *module::ModuleEntry,
737 737
    /// The newly entered scope.
741 741
    /// The previous module.
742 742
    prevMod: u16,
743 743
}
744 744
745 745
/// Loop context for tracking control flow within loops.
746 -
record LoopCtx {
746 +
record LoopCtx: Copy {
747 747
    /// Whether a reachable break was encountered in this loop.
748 748
    /// This is used to determine whether a loop diverges.
749 749
    hasBreak: bool,
750 750
}
751 751
752 752
/// Configuration for semantic analysis.
753 -
export record Config {
753 +
export record Config: Copy {
754 754
    /// Whether we're building in test mode.
755 755
    buildTest: bool,
756 756
}
757 757
758 758
/// How pattern bindings are created during match.
759 -
export union MatchBy {
759 +
export union MatchBy: Copy {
760 760
    /// Match by value.
761 761
    Value,
762 762
    /// Match by immutable reference.
763 763
    Ref,
764 764
    /// Match by mutable reference.
765 765
    MutRef,
766 766
}
767 767
768 768
/// State of a match statement being resolved.
769 769
// TODO: This is only used because of the maximum function param limitation.
770 -
record MatchState {
770 +
record MatchState: Copy {
771 771
    /// Is the match catch-all?
772 772
    catchAll: bool,
773 773
    /// Is the match constant?
774 774
    isConst: bool
775 775
}
776 776
777 777
/// Result of unwrapping a type for pattern matching.
778 -
export record MatchSubject {
778 +
export record MatchSubject: Copy {
779 779
    /// The effective type to match against.
780 780
    effectiveTy: Type,
781 781
    /// How bindings should be created.
782 782
    by: MatchBy,
783 783
}
784 784
785 785
/// How an expression uses a linear result.
786 -
union LinearUse {
786 +
union LinearUse: Copy {
787 787
    /// Consume the value and end its availability.
788 788
    Consume,
789 789
    /// Read the value without consuming it.
790 790
    Observe,
791 791
    /// Borrow the value through a reference.
795 795
    /// Use the value as an assignment target.
796 796
    Place,
797 797
}
798 798
799 799
/// Per-control-flow-path ownership state.
800 -
record LinearEnv {
800 +
record LinearEnv: Copy {
801 801
    /// Symbols tracked on this control-flow path.
802 802
    symbols: [?*mut Symbol; MAX_LINEAR_BINDINGS],
803 803
    /// Bit set for each binding that remains available.
804 804
    available: u64,
805 805
    /// Number of entries in `symbols`.
807 807
    /// Whether this control-flow path has terminated.
808 808
    terminated: bool,
809 809
}
810 810
811 811
/// Function-local exact-use checker state.
812 -
record LinearChecker {
812 +
record LinearChecker: Copy {
813 813
    /// Resolver that owns the symbols and diagnostics.
814 814
    resolver: *mut Resolver,
815 815
    /// Binding count at entry to each active loop.
816 816
    loopMarks: [u32; MAX_LINEAR_LOOP_DEPTH],
817 817
    /// Available bindings at entry to each active loop.
834 834
    }
835 835
    return MatchSubject { effectiveTy: ty, by: MatchBy::Value };
836 836
}
837 837
838 838
/// Global resolver state.
839 -
export record Resolver {
839 +
export record Resolver: Copy {
840 840
    /// Current scope.
841 841
    scope: *mut Scope,
842 842
    /// Package scope containing package roots and top-level symbols.
843 843
    pkgScope: *mut Scope,
844 844
    /// Stack of loop contexts for nested loops.
874 874
    /// Number of registered standalone methods.
875 875
    methodsLen: u32,
876 876
}
877 877
878 878
/// Internal error sentinel thrown when analysis cannot proceed.
879 -
export union ResolveError {
879 +
export union ResolveError: Copy {
880 880
    Failure,
881 881
}
882 882
883 883
/// Node in the type interning linked list.
884 -
record TypeNode {
884 +
record TypeNode: Copy {
885 885
    ty: Type,
886 886
    next: ?*TypeNode,
887 887
}
888 888
889 889
/// Allocate and intern a type in the arena, returning a pointer for deduplication.
942 942
    }
943 943
    return nil;
944 944
}
945 945
946 946
/// Storage buffers used by the analyzer.
947 -
export record ResolverStorage {
947 +
export record ResolverStorage: Copy {
948 948
    /// Unified arena for symbols, scopes, and nominal type.
949 949
    arena: alloc::Arena,
950 950
    /// Node semantic metadata indexed by node ID.
951 951
    nodeData: *mut [NodeData],
952 952
    /// Package scope.
954 954
    /// Error storage.
955 955
    errors: *mut [Error],
956 956
}
957 957
958 958
/// Input for resolving a single package.
959 -
export record Pkg {
959 +
export record Pkg: Copy {
960 960
    /// Root module entry.
961 961
    rootEntry: *module::ModuleEntry,
962 962
    /// Root AST node.
963 963
    rootAst: *ast::Node,
964 964
}
3450 3450
3451 3451
    return ty;
3452 3452
}
3453 3453
3454 3454
/// Compiler-known ownership markers carried by a composite declaration.
3455 -
record OwnershipMarkers {
3455 +
record OwnershipMarkers: Copy {
3456 3456
    /// The declaration requires exact consumption.
3457 3457
    linear: bool,
3458 3458
    /// The declaration permits implicit copies.
3459 3459
    copy: bool,
3460 3460
}
4466 4466
4467 4467
    return setNodeType(self, node, unifyBranches(thenTy, elseTy));
4468 4468
}
4469 4469
4470 4470
/// Controls how bare identifiers are handled in case patterns.
4471 -
union IdentMode {
4471 +
union IdentMode: Copy {
4472 4472
    /// Identifier is a value to compare against.
4473 4473
    Compare,
4474 4474
    /// Identifier introduces a new binding.
4475 4475
    Bind,
4476 4476
}
lib/std/lang/scanner.rad +6 -6
10 10
11 11
/// Token kinds representing all lexical elements in Radiance.
12 12
///
13 13
/// This enum covers operators, keywords, literals, and structural
14 14
/// elements used by the parser to build the AST.
15 -
export union TokenKind {
15 +
export union TokenKind: Copy {
16 16
    /// Special end of file token generated when the input is exhausted.
17 17
    Eof,
18 18
    /// Special invalid token.
19 19
    Invalid,
20 20
107 107
    I8, I16, I32, I64, U8, U16, U32, U64,
108 108
    Opaque, Fn, Bool, Union, Record, As, Unsafe
109 109
}
110 110
111 111
/// A reserved keyword.
112 -
record Keyword {
112 +
record Keyword: Copy {
113 113
    /// Keyword string.
114 114
    name: *[u8],
115 115
    /// Corresponding token.
116 116
    tok: TokenKind,
117 117
}
171 171
    { name: "use", tok: TokenKind::Use },
172 172
    { name: "while", tok: TokenKind::While },
173 173
];
174 174
175 175
/// Describes where source code originated from.
176 -
export union SourceLoc {
176 +
export union SourceLoc: Copy {
177 177
    /// Source loaded from a file at the given path.
178 178
    File(*[u8]),
179 179
    /// Source provided as an inline string (no file path).
180 180
    String,
181 181
}
182 182
183 183
/// Lexical scanner state for tokenizing Radiance source code.
184 184
///
185 185
/// Maintains position information and source buffer reference.
186 -
export record Scanner {
186 +
export record Scanner: Copy {
187 187
    /// Origin of the source being scanned.
188 188
    sourceLoc: SourceLoc,
189 189
    /// Source buffer.
190 190
    source: *[u8],
191 191
    /// Offset of current token into buffer.
198 198
199 199
/// Individual token with kind, source text, and position.
200 200
///
201 201
/// Represents a single lexical element extracted from source,
202 202
/// including its original text and byte offset for error reporting.
203 -
export record Token {
203 +
export record Token: Copy {
204 204
    /// Token kind.
205 205
    kind: TokenKind,
206 206
    /// Token source string.
207 207
    source: *[u8],
208 208
    /// Byte offset of `source` in input buffer.
210 210
}
211 211
212 212
/// Source code location with line/column information.
213 213
///
214 214
/// Used for error reporting and debugging.
215 -
export record Location {
215 +
export record Location: Copy {
216 216
    /// Origin of the source.
217 217
    source: SourceLoc,
218 218
    /// Line number.
219 219
    line: u16,
220 220
    /// Column number.
lib/std/lang/sexpr.rad +2 -2
5 5
6 6
use std::io;
7 7
use std::lang::alloc;
8 8
9 9
/// Output target for S-expression printing.
10 -
export union Output {
10 +
export union Output: Copy {
11 11
    /// Print to stdout.
12 12
    Stdout,
13 13
    /// Write to a buffer, tracking position.
14 14
    Buffer { buf: *mut [u8], pos: *mut u32 },
15 15
}
16 16
17 17
/// An S-expression element.
18 -
export union Expr {
18 +
export union Expr: Copy {
19 19
    /// An empty expression.
20 20
    Null,
21 21
    /// A symbol/identifier.
22 22
    Sym(*[u8]),
23 23
    /// A quoted string literal.
lib/std/lang/strings.rad +2 -2
14 14
15 15
/// String interning pool using open-addressed hash table.
16 16
///
17 17
/// Each unique string content is stored only once, allowing pointer equality
18 18
/// to be used instead of content comparison for symbol lookups and module names.
19 -
export record Pool {
19 +
export record Pool: Copy {
20 20
    /// Hash table slots.
21 21
    table: [*[u8]; TABLE_SIZE],
22 22
    /// Number of strings currently in the pool.
23 23
    count: u32,
24 24
}
25 25
26 26
/// Lookup result.
27 -
union Lookup {
27 +
union Lookup: Copy {
28 28
    /// Found.
29 29
    Found(*[u8]),
30 30
    /// Not found, contains empty slot index.
31 31
    Empty(u32),
32 32
}
lib/std/lang/types.rad +1 -1
1 1
//! Shared Radiance language types.
2 2
3 3
/// Ownership and safety class for pointer-like types.
4 -
export union PointerClass {
4 +
export union PointerClass: Copy {
5 5
    /// Owned pointer, eg. `*T`.
6 6
    Owned,
7 7
    /// Reference, borrowed pointer, eg. `&T`.
8 8
    Ref,
9 9
    /// Unsafe, raw pointer, eg. `*unsafe T`.
lib/std/mem.rad +1 -1
1 1
/// Memory error.
2 -
union MemoryError {
2 +
union MemoryError: Copy {
3 3
    /// Buffer is too small.
4 4
    BufferTooSmall,
5 5
}
6 6
7 7
/// Copy bytes between two slices. Returns the number of bytes copied.
lib/std/sys.rad +1 -1
1 1
//! System utilities.
2 2
export mod unix;
3 3
4 4
/// Process environment passed to the program entry point.
5 -
export record Env {
5 +
export record Env: Copy {
6 6
    /// Command-line arguments.
7 7
    args: *[*[u8]],
8 8
}
lib/std/sys/unix.rad +1 -1
1 1
//! Unix-specific system calls and utilities.
2 2
use std::intrinsics;
3 3
4 4
/// File access modes.
5 -
export record OpenFlags(i64);
5 +
export record OpenFlags: Copy(i64);
6 6
7 7
/// Open file for reading only.
8 8
export constant O_RDONLY: OpenFlags = OpenFlags(0);
9 9
10 10
/// Open file for writing only.
lib/std/vec.rad +1 -1
5 5
//! to the element type's requirements.
6 6
7 7
/// Raw vector metadata structure.
8 8
///
9 9
/// Does not own storage, points to user-provided arena.
10 -
export record RawVec {
10 +
export record RawVec: Copy {
11 11
    /// Pointer to user-provided byte arena.
12 12
    data: *mut [u8],
13 13
    /// Current number of elements stored.
14 14
    len: u32,
15 15
    /// Size of each element in bytes (stride between elements).