aver-lang 0.15.0

VM and transpiler for Aver, a statically-typed language designed for AI-assisted development
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
use super::{CallTarget, CompileError, FnCompiler};
use crate::ast::{Expr, Literal, Spanned};
use crate::ir::{
    CallLowerCtx, CallPlan, ForwardArg, LeafOp, SemanticConstructor, TailCallPlan, WrapperKind,
    classify_call_plan, classify_constructor_name, classify_forward_call_parts, classify_leaf_op,
    classify_tail_call_plan,
};
use crate::nan_value::NanValue;
use crate::vm::builtin::VmBuiltin;
use crate::vm::opcode::*;
use crate::vm::symbol::VmSymbolTable;

/// Map a synthesized deforestation intrinsic name to its VM opcode.
/// Returns `None` for anything that isn't one of the four `__buf_*`
/// intrinsics or whose arity doesn't match. Arity is checked here so
/// a stray user-level identifier collision (very unlikely given the
/// `__` prefix) doesn't accidentally lower to a buffer op.
fn buffer_intrinsic_opcode(name: &str, argc: usize) -> Option<u8> {
    match (name, argc) {
        ("__buf_new", 1) => Some(BUFFER_NEW),
        ("__buf_append", 2) => Some(BUFFER_APPEND_STR),
        ("__buf_append_sep_unless_first", 2) => Some(BUFFER_APPEND_SEP_UNLESS_FIRST),
        ("__buf_finalize", 1) => Some(BUFFER_FINALIZE),
        _ => None,
    }
}

struct VmCallCtx<'compiler, 'a> {
    compiler: &'compiler FnCompiler<'a>,
}

impl CallLowerCtx for VmCallCtx<'_, '_> {
    fn is_local_value(&self, name: &str) -> bool {
        self.compiler.local_slots.contains_key(name)
    }

    fn is_user_type(&self, name: &str) -> bool {
        self.compiler.resolve_type_id(name).is_some()
    }

    fn resolve_module_call<'a>(&self, dotted: &'a str) -> Option<(&'a str, &'a str)> {
        let mut best = None;

        for (dot_idx, _) in dotted.match_indices('.') {
            let prefix = &dotted[..dot_idx];
            let suffix = &dotted[dot_idx + 1..];
            if suffix.is_empty()
                || self
                    .compiler
                    .symbols
                    .resolve_namespace_path(prefix)
                    .is_none()
            {
                continue;
            }

            let is_module_function = self.compiler.resolve_fn_id(dotted).is_some();
            let is_module_ctor = suffix.rsplit_once('.').is_some_and(|(type_name, _)| {
                self.compiler.resolve_type_id(type_name).is_some()
                    || self
                        .compiler
                        .resolve_type_id(&format!("{prefix}.{type_name}"))
                        .is_some()
            });

            if is_module_function || is_module_ctor {
                best = Some((prefix, suffix));
            }
        }

        best
    }
}

impl<'a> FnCompiler<'a> {
    pub(super) fn try_compile_leaf_expr(&mut self, expr: &Expr) -> Result<bool, CompileError> {
        let leaf = {
            let call_ctx = VmCallCtx { compiler: self };
            classify_leaf_op(expr, &call_ctx)
        };

        match leaf {
            Some(leaf) => {
                self.compile_leaf_op(leaf)?;
                Ok(true)
            }
            None => Ok(false),
        }
    }

    pub(super) fn classify_constructor_semantics(&self, name: &str) -> SemanticConstructor {
        let call_ctx = VmCallCtx { compiler: self };
        classify_constructor_name(name, &call_ctx)
    }

    fn resolve_builtin_target(&self, name: &str) -> Option<CallTarget> {
        let symbol_id = self.symbols.find(name)?;
        self.symbols
            .resolve_builtin(symbol_id)
            .map(CallTarget::Builtin)
    }

    fn flatten_path(&self, expr: &Spanned<Expr>) -> Option<String> {
        match &expr.node {
            Expr::Ident(name) => Some(name.clone()),
            Expr::Attr(inner, field) => Some(format!("{}.{}", self.flatten_path(inner)?, field)),
            _ => Option::None,
        }
    }

    pub(super) fn resolve_type_id(&self, name: &str) -> Option<u32> {
        self.arena.find_type_id(name)
    }

    fn resolve_fn_id(&self, name: &str) -> Option<u32> {
        self.module_scope
            .get(name)
            .copied()
            .or_else(|| self.code_store.find(name))
    }

    pub(super) fn resolve_call_target(&self, expr: &Expr) -> Option<CallTarget> {
        let call_ctx = VmCallCtx { compiler: self };
        self.call_plan_to_target(classify_call_plan(expr, &call_ctx))
    }

    fn call_plan_to_target(&self, plan: CallPlan) -> Option<CallTarget> {
        match plan {
            CallPlan::Dynamic => None,
            CallPlan::Function(name) => {
                self.resolve_fn_id(&name)
                    .map(CallTarget::KnownFn)
                    .or_else(|| {
                        if name.contains('.') {
                            Some(CallTarget::UnknownQualified(name))
                        } else {
                            None
                        }
                    })
            }
            CallPlan::Builtin(name) => self
                .resolve_builtin_target(&name)
                .or(Some(CallTarget::UnknownQualified(name))),
            CallPlan::Wrapper(kind) => {
                let wrap_kind = match kind {
                    WrapperKind::ResultOk => 0,
                    WrapperKind::ResultErr => 1,
                    WrapperKind::OptionSome => 2,
                };
                Some(CallTarget::Wrapper(wrap_kind))
            }
            CallPlan::NoneValue => Some(CallTarget::None_),
            CallPlan::TypeConstructor {
                qualified_type_name,
                variant_name,
            } => {
                let type_id = self.resolve_type_id(&qualified_type_name)?;
                if let Some(variant_id) = self.arena.find_variant_id(type_id, &variant_name) {
                    Some(CallTarget::Variant(type_id, variant_id))
                } else {
                    Some(CallTarget::UnknownQualified(format!(
                        "{}.{}",
                        qualified_type_name, variant_name
                    )))
                }
            }
        }
    }

    fn compile_forward_arg(&mut self, arg: ForwardArg) -> Result<(), CompileError> {
        let ForwardArg::Local(name) = arg;
        let Some(&slot) = self.local_slots.get(&name) else {
            return Err(CompileError {
                msg: format!("forwarded local '{}' is not a known slot", name),
            });
        };
        self.emit_op(LOAD_LOCAL);
        self.emit_u8(slot as u8);
        Ok(())
    }

    pub(super) fn compile_call(
        &mut self,
        fn_expr: &Spanned<Expr>,
        args: &[Spanned<Expr>],
    ) -> Result<(), CompileError> {
        // 0.15 Traversal: deforestation buffer intrinsics. The synth
        // pass replaces canonical `String.join(<fn>(args, []), sep)`
        // shapes with `__buf_finalize(<fn>__buffered(args.., __buf_new(...), sep))`,
        // and `<fn>__buffered`'s body is built from `__buf_append` /
        // `__buf_append_sep_unless_first`. None of these are user-visible —
        // they only ever appear synthesized — so we recognise them
        // before regular builtin resolution and emit dedicated opcodes
        // backed by `vm.buffer_pool` (a host-side `Vec<Option<String>>`).
        if let Expr::Ident(name) = &fn_expr.node {
            if let Some(opcode) = buffer_intrinsic_opcode(name, args.len()) {
                for arg in args {
                    self.compile_expr(arg)?;
                }
                self.emit_op(opcode);
                return Ok(());
            }

            // `__to_str(x)`: coerce any value to its string repr. Used by
            // the interpolation lowering pass to produce a string before
            // a `__buf_append`. Reuses the existing CONCAT-against-empty
            // trick — CONCAT calls `NanValue::repr` on both sides, so any
            // value lowers to its display string.
            if name == "__to_str" && args.len() == 1 {
                self.compile_expr(&args[0])?;
                let empty_nv = NanValue::new_string_value("", self.arena);
                let empty_const = self.add_constant(empty_nv);
                self.emit_op(LOAD_CONST);
                self.emit_u16(empty_const);
                self.emit_op(CONCAT);
                return Ok(());
            }
        }

        let call_ctx = VmCallCtx { compiler: self };
        if let Some(plan) = classify_forward_call_parts(&fn_expr.node, args, &call_ctx) {
            let Some(target) = self.call_plan_to_target(plan.target.clone()) else {
                return Err(CompileError {
                    msg: "dynamic call cannot lower through ForwardCallPlan".to_string(),
                });
            };
            for arg in plan.args {
                self.compile_forward_arg(arg)?;
            }
            return self.emit_resolved_call_after_loaded_args(target, args.len(), 0);
        }

        if let Some(target) = self.resolve_call_target(&fn_expr.node) {
            return self.compile_resolved_call(target, args);
        }
        self.compile_expr(fn_expr)?;
        for arg in args {
            self.compile_expr(arg)?;
        }
        self.emit_op(CALL_VALUE);
        self.emit_u8(args.len() as u8);
        Ok(())
    }

    fn emit_resolved_call_after_loaded_args(
        &mut self,
        target: CallTarget,
        argc: usize,
        owned_mask: u8,
    ) -> Result<(), CompileError> {
        match target {
            CallTarget::KnownFn(fn_id) => {
                self.emit_op(CALL_KNOWN);
                self.emit_u16(fn_id as u16);
                self.emit_u8(argc as u8);
            }
            CallTarget::Wrapper(kind) => {
                if argc == 0 {
                    self.emit_op(LOAD_UNIT);
                }
                self.emit_op(WRAP);
                self.emit_u8(kind);
            }
            CallTarget::None_ => {
                let idx = self.add_constant(NanValue::NONE);
                self.emit_op(LOAD_CONST);
                self.emit_u16(idx);
            }
            CallTarget::Variant(type_id, variant_id) => {
                self.emit_op(VARIANT_NEW);
                self.emit_u16(type_id as u16);
                self.emit_u16(variant_id);
                self.emit_u8(argc as u8);
            }
            CallTarget::Builtin(builtin) => self.emit_builtin_after_args(builtin, argc, owned_mask),
            CallTarget::UnknownQualified(qualified) => {
                return Err(CompileError {
                    msg: format!("unknown builtin or namespace member: {}", qualified),
                });
            }
        }
        Ok(())
    }

    fn compile_resolved_call(
        &mut self,
        target: CallTarget,
        args: &[Spanned<Expr>],
    ) -> Result<(), CompileError> {
        // Compute owned mask before compiling args (we need the AST).
        let arg_refs: Vec<&Spanned<Expr>> = args.iter().collect();
        let owned_mask = Self::compute_builtin_owned_mask(&arg_refs);
        for arg in args {
            self.compile_expr(arg)?;
        }
        self.emit_resolved_call_after_loaded_args(target, args.len(), owned_mask)
    }

    pub(super) fn compile_tail_call(
        &mut self,
        target: &str,
        args: &[Spanned<Expr>],
    ) -> Result<(), CompileError> {
        for arg in args {
            self.compile_expr(arg)?;
        }

        // Derive owned mask from last_use annotations on the tail call args.
        // Bit i set = arg i contains a last-use reference to param i.
        let owned_mask: u8 = args.iter().enumerate().take(8).fold(0u8, |mask, (i, arg)| {
            if contains_last_use_slot(&arg.node, i as u16) {
                mask | (1 << i)
            } else {
                mask
            }
        });

        let call_ctx = VmCallCtx { compiler: self };
        match classify_tail_call_plan(target, &self.name, &call_ctx) {
            TailCallPlan::SelfCall => {
                self.emit_op(TAIL_CALL_SELF);
                self.emit_u8(args.len() as u8);
                self.emit_u8(owned_mask);
            }
            TailCallPlan::KnownFunction(name) => {
                if let Some(fn_id) = self.resolve_fn_id(&name) {
                    self.emit_op(TAIL_CALL_KNOWN);
                    self.emit_u16(fn_id as u16);
                    self.emit_u8(args.len() as u8);
                    self.emit_u8(owned_mask);
                } else {
                    return Err(CompileError {
                        msg: format!("unknown tail call target: {}", name),
                    });
                }
            }
            TailCallPlan::Unknown(name) => {
                return Err(CompileError {
                    msg: format!("unknown tail call target: {}", name),
                });
            }
        }
        Ok(())
    }

    pub(super) fn compile_constructor(
        &mut self,
        name: &str,
        arg: Option<&Spanned<Expr>>,
    ) -> Result<(), CompileError> {
        let normalized_name = match name {
            "Ok" => "Result.Ok",
            "Err" => "Result.Err",
            "Some" => "Option.Some",
            "None" => "Option.None",
            other => other,
        };

        match self.classify_constructor_semantics(normalized_name) {
            SemanticConstructor::Wrapper(kind) => {
                self.compile_constructor_arg(arg)?;
                self.emit_op(WRAP);
                self.emit_u8(match kind {
                    WrapperKind::ResultOk => 0,
                    WrapperKind::ResultErr => 1,
                    WrapperKind::OptionSome => 2,
                });
            }
            SemanticConstructor::NoneValue => {
                let idx = self.add_constant(NanValue::NONE);
                self.emit_op(LOAD_CONST);
                self.emit_u16(idx);
            }
            SemanticConstructor::TypeConstructor {
                qualified_type_name,
                variant_name,
            } => {
                if let Some(type_id) = self.resolve_type_id(&qualified_type_name)
                    && let Some(variant_id) = self.arena.find_variant_id(type_id, &variant_name)
                {
                    let field_count = if let Some(a) = arg {
                        self.compile_expr(a)?;
                        1u8
                    } else {
                        0u8
                    };
                    self.emit_op(VARIANT_NEW);
                    self.emit_u16(type_id as u16);
                    self.emit_u16(variant_id);
                    self.emit_u8(field_count);
                    return Ok(());
                }
                return Err(CompileError {
                    msg: format!("unknown constructor: {}", name),
                });
            }
            SemanticConstructor::Unknown(_) => {
                return Err(CompileError {
                    msg: format!("unknown constructor: {}", name),
                });
            }
        }
        Ok(())
    }

    fn compile_constructor_arg(&mut self, arg: Option<&Spanned<Expr>>) -> Result<(), CompileError> {
        if let Some(a) = arg {
            self.compile_expr(a)
        } else {
            self.emit_op(LOAD_UNIT);
            Ok(())
        }
    }

    fn compile_leaf_op(&mut self, leaf: LeafOp<'_>) -> Result<(), CompileError> {
        match leaf {
            LeafOp::FieldAccess { object, field_name } => self.compile_attr(object, field_name),
            LeafOp::MapGet { map, key } => {
                self.compile_expr(map)?;
                self.compile_expr(key)?;
                self.emit_builtin_after_args(VmBuiltin::MapGet, 2, 0);
                Ok(())
            }
            LeafOp::MapSet { map, key, value } => {
                let owned_mask = Self::compute_builtin_owned_mask(&[map, key, value]);
                self.compile_expr(map)?;
                self.compile_expr(key)?;
                self.compile_expr(value)?;
                self.emit_builtin_after_args(VmBuiltin::MapSet, 3, owned_mask);
                Ok(())
            }
            LeafOp::VectorNew { size, fill } => {
                self.compile_expr(size)?;
                self.compile_expr(fill)?;
                self.emit_builtin_after_args(VmBuiltin::VectorNew, 2, 0);
                Ok(())
            }
            LeafOp::VectorGetOrDefaultLiteral {
                vector,
                index,
                default_literal,
            } => {
                self.compile_expr(vector)?;
                self.compile_expr(index)?;
                let default_value = self.nan_literal(default_literal);
                let const_idx = self.add_constant(default_value);
                self.emit_op(VECTOR_GET_OR);
                self.emit_u16(const_idx);
                Ok(())
            }
            LeafOp::VectorSetOrDefaultSameVector {
                vector,
                index,
                value,
            } => {
                // In the fused VECTOR_SET_OR_KEEP opcode, the default is
                // implicitly the same vector — it's not loaded separately.
                // So we can always take ownership: the vector appears twice
                // in the AST (set arg + default) but only once on the stack.
                self.compile_expr(vector)?;
                self.compile_expr(index)?;
                self.compile_expr(value)?;
                self.emit_op(VECTOR_SET_OR_KEEP);
                self.emit_u8(1); // always owned — fused op consumes the only ref
                Ok(())
            }
            LeafOp::ListIndexGet { list, index } => {
                // Decompose: Vector.fromList(list) then Vector.get(_, index)
                self.compile_expr(list)?;
                self.emit_builtin_after_args(VmBuiltin::VectorFromList, 1, 0);
                self.compile_expr(index)?;
                self.emit_op(VECTOR_GET);
                Ok(())
            }
            LeafOp::IntModOrDefaultLiteral {
                a,
                b,
                default_literal,
            } => {
                self.compile_expr(a)?;
                self.compile_expr(b)?;
                self.emit_builtin_after_args(VmBuiltin::IntMod, 2, 0);
                let default_value = self.nan_literal(default_literal);
                let const_idx = self.add_constant(default_value);
                self.emit_op(LOAD_CONST);
                self.emit_u16(const_idx);
                self.emit_op(UNWRAP_RESULT_OR);
                Ok(())
            }
            LeafOp::NoneValue => {
                let idx = self.add_constant(NanValue::NONE);
                self.emit_op(LOAD_CONST);
                self.emit_u16(idx);
                Ok(())
            }
            LeafOp::VariantConstructor {
                ref qualified_type_name,
                ref variant_name,
            } => {
                if let Some(type_id) = self.resolve_type_id(qualified_type_name)
                    && let Some(variant_id) = self.arena.find_variant_id(type_id, variant_name)
                {
                    self.emit_op(VARIANT_NEW);
                    self.emit_u16(type_id as u16);
                    self.emit_u16(variant_id);
                    self.emit_u8(0); // nullary — zero fields
                    Ok(())
                } else {
                    Err(CompileError {
                        msg: format!(
                            "unknown variant constructor: {}.{}",
                            qualified_type_name, variant_name
                        ),
                    })
                }
            }
            LeafOp::StaticRef(ref name) => {
                // Static function/builtin reference in value position.
                // Resolve via namespace path lookup (same as compile_attr).
                if let Some(dot) = name.rfind('.') {
                    let ns_path = &name[..dot];
                    let member = &name[dot + 1..];
                    if let Some(symbol_id) = self.symbols.resolve_namespace_path(ns_path) {
                        let idx = self.add_constant(VmSymbolTable::symbol_ref(symbol_id));
                        self.emit_op(LOAD_CONST);
                        self.emit_u16(idx);
                        let field_symbol_id = self.symbols.intern_name(member);
                        self.emit_op(RECORD_GET_NAMED);
                        self.emit_u32(field_symbol_id);
                        return Ok(());
                    }
                }
                Err(CompileError {
                    msg: format!("unresolved static reference: {}", name),
                })
            }
        }
    }

    fn emit_builtin_after_args(&mut self, builtin: VmBuiltin, argc: usize, owned_mask: u8) {
        match builtin {
            VmBuiltin::ListLen => self.emit_op(LIST_LEN),
            VmBuiltin::ListPrepend => self.emit_op(LIST_PREPEND),
            VmBuiltin::VectorGet => self.emit_op(VECTOR_GET),
            VmBuiltin::VectorSet if owned_mask != 0 => {
                // Owned path: go through CALL_BUILTIN_OWNED for take optimization
                let symbol_id = self.symbols.intern_builtin(builtin);
                self.emit_op(CALL_BUILTIN_OWNED);
                self.emit_u32(symbol_id);
                self.emit_u8(argc as u8);
                self.emit_u8(owned_mask);
            }
            VmBuiltin::VectorSet => self.emit_op(VECTOR_SET),
            VmBuiltin::OptionWithDefault => self.emit_op(UNWRAP_OR),
            VmBuiltin::ResultWithDefault => self.emit_op(UNWRAP_RESULT_OR),
            _ => {
                let symbol_id = self.symbols.intern_builtin(builtin);
                if owned_mask != 0 {
                    self.emit_op(CALL_BUILTIN_OWNED);
                    self.emit_u32(symbol_id);
                    self.emit_u8(argc as u8);
                    self.emit_u8(owned_mask);
                } else {
                    self.emit_op(CALL_BUILTIN);
                    self.emit_u32(symbol_id);
                    self.emit_u8(argc as u8);
                }
            }
        }
    }

    /// Compute owned bitmask for builtin args by checking if any arg
    /// is a last-use local reference (annotated by ir::last_use pass).
    fn compute_builtin_owned_mask(arg_exprs: &[&Spanned<Expr>]) -> u8 {
        let mut mask = 0u8;
        for (i, arg) in arg_exprs.iter().enumerate().take(8) {
            if let Expr::Resolved { last_use, .. } = &arg.node
                && last_use.0
            {
                mask |= 1 << i;
            }
        }
        mask
    }

    fn nan_literal(&mut self, lit: &Literal) -> NanValue {
        match lit {
            Literal::Int(i) => NanValue::new_int(*i, self.arena),
            Literal::Float(f) => NanValue::new_float(*f),
            Literal::Bool(true) => NanValue::TRUE,
            Literal::Bool(false) => NanValue::FALSE,
            Literal::Unit => NanValue::UNIT,
            Literal::Str(s) => NanValue::new_string_value(s, self.arena),
        }
    }

    pub(super) fn compile_attr(
        &mut self,
        obj: &Spanned<Expr>,
        field: &str,
    ) -> Result<(), CompileError> {
        if let Some(path) = self.flatten_path(obj)
            && let Some(symbol_id) = self.symbols.resolve_namespace_path(&path)
        {
            let idx = self.add_constant(VmSymbolTable::symbol_ref(symbol_id));
            self.emit_op(LOAD_CONST);
            self.emit_u16(idx);
            let field_symbol_id = self.symbols.intern_name(field);
            self.emit_op(RECORD_GET_NAMED);
            self.emit_u32(field_symbol_id);
            return Ok(());
        }

        if let Some(field_idx) = self
            .infer_record_field_idx(&obj.node, field)
            .or_else(|| self.resolve_record_field_idx(&obj.node, field))
        {
            self.compile_expr(obj)?;
            self.emit_op(RECORD_GET);
            self.emit_u8(field_idx);
            return Ok(());
        }

        self.compile_expr(obj)?;
        let field_symbol_id = self.symbols.intern_name(field);
        self.emit_op(RECORD_GET_NAMED);
        self.emit_u32(field_symbol_id);
        Ok(())
    }

    fn infer_record_field_idx(&self, obj: &Expr, field: &str) -> Option<u8> {
        let type_name = match obj {
            Expr::RecordCreate { type_name, .. } | Expr::RecordUpdate { type_name, .. } => {
                type_name.as_str()
            }
            _ => return None,
        };
        let type_id = self.resolve_type_id(type_name)?;
        let fields = self.arena.get_field_names(type_id);
        fields
            .iter()
            .position(|name| name == field)
            .map(|idx| idx as u8)
    }

    fn resolve_record_field_idx(&self, obj: &Expr, field: &str) -> Option<u8> {
        let field_symbol_id = self.code_store.symbols.find(field)?;
        match obj {
            Expr::Ident(type_name)
                if type_name.chars().next().is_some_and(|c| c.is_uppercase()) =>
            {
                let type_id = self.resolve_type_id(type_name)?;
                self.code_store
                    .record_field_slots
                    .get(&(type_id, field_symbol_id))
                    .copied()
            }
            _ => None,
        }
    }
}

/// Check if an expression tree contains a `Resolved { slot, last_use: true }`
/// for a specific slot. Used to derive tail-call owned_mask from last_use
/// annotations instead of the old `TailCallData.owned` mechanism.
fn contains_last_use_slot(expr: &Expr, target_slot: u16) -> bool {
    match expr {
        Expr::Resolved { slot, last_use, .. } => *slot == target_slot && last_use.0,
        Expr::FnCall(fn_expr, args) => {
            contains_last_use_slot(&fn_expr.node, target_slot)
                || args
                    .iter()
                    .any(|a| contains_last_use_slot(&a.node, target_slot))
        }
        Expr::BinOp(_, left, right) => {
            contains_last_use_slot(&left.node, target_slot)
                || contains_last_use_slot(&right.node, target_slot)
        }
        Expr::Attr(obj, _) => contains_last_use_slot(&obj.node, target_slot),
        Expr::ErrorProp(inner) | Expr::Constructor(_, Some(inner)) => {
            contains_last_use_slot(&inner.node, target_slot)
        }
        Expr::InterpolatedStr(parts) => parts.iter().any(|p| match p {
            crate::ast::StrPart::Parsed(e) => contains_last_use_slot(&e.node, target_slot),
            _ => false,
        }),
        Expr::List(items) | Expr::Tuple(items) | Expr::IndependentProduct(items, _) => items
            .iter()
            .any(|e| contains_last_use_slot(&e.node, target_slot)),
        _ => false,
    }
}