run-rs 0.6.25

Run a subset of Rust as an interpreted script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
//! Lowers the `syn` AST into register bytecode once per program. The VM never does a name lookup.

use std::collections::{HashMap, HashSet};
use std::mem::take;
use std::sync::Arc;

use anyhow::Result;
use syn::{Block, Expr, FnArg, Pat};

use super::bytecode::{
    BuiltinId, CapSource, Chunk, Const, DefaultIr, EnumVariant, FmtSpec, Member, MethodName,
    NO_ATOM, Op, PatInfo, PathRef, Reg, ScalarTy, StructLit,
};
use super::enum_def::EnumDef;
use super::resolver::{Res, Resolver};
use super::typeir::{CastIr, TypeIr, lower_cast, lower_type};

/// `moved[i]` is the new index of the op that was at `i`, one entry past the end included.
fn retarget_jumps(code: &mut [Op], moved: &[u32]) {
    for op in code {
        match op {
            Op::Jump { to: t }
            | Op::JumpIfFalse { to: t, .. }
            | Op::JumpIfTrue { to: t, .. }
            | Op::CmpJump { to: t, .. }
            | Op::CmpJumpImm { to: t, .. }
            | Op::CmpJumpInt { to: t, .. }
            | Op::CmpJumpIntImm { to: t, .. }
            | Op::ForNext { to: t, .. }
            | Op::TryJump { to: t, .. } => *t = moved[*t as usize],
            _ => {}
        }
    }
}

/// Filled before any body is compiled.
pub struct Ctx<'r> {
    pub resolver: &'r Resolver,
    /// paths resolve against it
    pub module: usize,
    /// carried into every chunk for error traces
    pub file: std::sync::Arc<str>,
    /// lets `.await`, `tokio::spawn` and `join!` compile
    pub async_mode: bool,
    pub impl_type: Option<&'r str>,
    /// every script function by name, for the inference pass. A name defined twice is absent.
    pub fn_signatures: &'r HashMap<String, syn::Signature>,
    /// `&mut self` method names. A call compiles its receiver as a place split from sharing.
    pub mut_methods: &'r HashSet<String>,
    /// Includes impls on bridge types like `impl From<Point> for String`, a path call on one is a
    /// user call even when the bridge knows the name.
    pub impl_methods: &'r HashSet<(String, String)>,
    /// atoms of the impl method names no bridge knows
    pub method_atoms: &'r HashMap<String, u32>,
    /// every impl method by type and name, for the inference pass
    pub impl_sigs: &'r HashMap<(String, String), syn::Signature>,
    /// the declared type of every const and static, for the inference pass
    pub const_types: &'r HashMap<String, syn::Type>,
    /// false skips all scope drop bookkeeping
    pub has_drop: bool,
}

/// A stack of these supports nested closures.
struct FnState {
    code: Vec<Op>,
    lines: Vec<u32>,
    cols: Vec<u32>,
    consts: Vec<Const>,
    members: Vec<Member>,
    pats: Vec<PatInfo>,
    fmts: Vec<FmtSpec>,
    struct_lits: Vec<StructLit>,
    enum_variants: Vec<EnumVariant>,
    casts: Vec<CastIr>,
    defaults: Vec<DefaultIr>,
    try_targets: Vec<Arc<str>>,
    /// the target a `?` converts into through `From`
    ret_error: Option<Arc<str>>,
    coerces: Vec<TypeIr>,
    paths: Vec<PathRef>,
    names: Vec<MethodName>,
    children: Vec<Arc<Chunk>>,
    child_caps: Vec<Vec<CapSource>>,
    /// filled by the liveness pass, see `liveness.rs`
    child_moves: Vec<Arc<[bool]>>,
    upvalues: Vec<(String, CapSource)>,
    mutable_locals: HashSet<Reg>,
    /// Whether a register needs a capture cell is only known once the frame is compiled, so
    /// `into_chunk` turns these into `DropCell` ops later.
    binding_sites: Vec<(usize, Reg)>,
    /// Reference parameters. They forward the caller's handle, so they are never moved, copied
    /// or dropped here.
    borrow_params: HashSet<Reg>,
    /// `let r = &place` bindings, shared like a borrow parameter
    ref_locals: HashSet<Reg>,
    /// Bindings that hold a borrowed handle, so scope end must not drop them.
    drop_exempt: HashSet<Reg>,
    /// `let r = &mut v` aliases, access compiles as access to `v` itself
    aliases: HashMap<String, String>,
    /// `const` and `static` items declared in a block. They are locals like a `let`, but a
    /// pattern that names one tests against its value.
    block_consts: HashSet<String>,
    scopes: Vec<HashMap<String, Reg>>,
    /// for scope end `Drop` runs
    scope_order: Vec<Vec<Reg>>,
    drop_lists: Vec<std::sync::Arc<[Reg]>>,
    /// `borrow` results not yet released, see `release_guard_temps`
    guard_temps: Vec<Reg>,
    /// named bindings that hold a `RefCell` guard, released at scope end even without `Drop` impls
    guard_regs: HashSet<Reg>,
    has_guards: bool,
    reg_top: Reg,
    max_reg: Reg,
    num_params: usize,
    param_types: Vec<Option<String>>,
    name: String,
    generics: Vec<Arc<str>>,
    call_type_args: Vec<Arc<[TypeIr]>>,
    /// Retagging on the way out keeps the declared width without a cast at every call site.
    ret_cast: Option<u16>,
}

impl FnState {
    fn new(name: String) -> FnState {
        FnState {
            code: Vec::new(),
            lines: Vec::new(),
            cols: Vec::new(),
            consts: Vec::new(),
            members: Vec::new(),
            pats: Vec::new(),
            fmts: Vec::new(),
            struct_lits: Vec::new(),
            defaults: Vec::new(),
            try_targets: Vec::new(),
            ret_error: None,
            enum_variants: Vec::new(),
            casts: Vec::new(),
            coerces: Vec::new(),
            paths: Vec::new(),
            names: Vec::new(),
            children: Vec::new(),
            child_caps: Vec::new(),
            child_moves: Vec::new(),
            upvalues: Vec::new(),
            mutable_locals: HashSet::new(),
            binding_sites: Vec::new(),
            borrow_params: HashSet::new(),
            ref_locals: HashSet::new(),
            drop_exempt: HashSet::new(),
            aliases: HashMap::default(),
            block_consts: HashSet::new(),
            scopes: vec![HashMap::default()],
            scope_order: vec![Vec::new()],
            drop_lists: Vec::new(),
            reg_top: 0,
            max_reg: 0,
            num_params: 0,
            param_types: Vec::new(),
            name,
            generics: Vec::new(),
            call_type_args: Vec::new(),
            ret_cast: None,
            guard_temps: Vec::new(),
            guard_regs: HashSet::new(),
            has_guards: false,
        }
    }

    fn local_reg(&self, name: &str) -> Option<Reg> {
        self.scopes.iter().rev().find_map(|s| s.get(name).copied())
    }

    fn upvalue_index(&self, name: &str) -> Option<u16> {
        self.upvalues.iter().position(|(n, _)| n == name).map(idx16)
    }

    /// Inserted rather than reserved, because the binding compiles long before the closure that makes
    /// the capture mutable. Jump targets past an insertion shift with it and never point at the
    /// inserted op.
    fn insert_cell_drops(&mut self) -> Result<()> {
        let mut sites: Vec<(usize, Reg)> = self
            .binding_sites
            .iter()
            .copied()
            .filter(|(_, reg)| self.mutable_locals.contains(reg))
            .collect();
        if sites.is_empty() {
            return Ok(());
        }
        sites.sort_unstable();
        let mut code = Vec::with_capacity(self.code.len() + sites.len());
        let mut lines = Vec::with_capacity(self.lines.len() + sites.len());
        let mut cols = Vec::with_capacity(self.cols.len() + sites.len());
        // 1 entry longer than the code so a jump to the end remaps too
        let mut moved = Vec::with_capacity(self.code.len() + 1);
        let mut next = 0;
        for (at, op) in take(&mut self.code).into_iter().enumerate() {
            while sites.get(next).is_some_and(|(site, _)| *site == at) {
                code.push(Op::DropCell {
                    cell: sites[next].1,
                });
                lines.push(self.lines[at]);
                cols.push(self.cols[at]);
                next += 1;
            }
            moved.push(u32::try_from(code.len())?);
            code.push(op);
            lines.push(self.lines[at]);
            cols.push(self.cols[at]);
        }
        moved.push(u32::try_from(code.len())?);
        retarget_jumps(&mut code, &moved);
        self.code = code;
        self.lines = lines;
        self.cols = cols;
        Ok(())
    }

    /// Drops the ops flagged in `dead` and retargets every jump.
    fn remove_ops(&mut self, dead: &[bool]) -> Result<()> {
        if !dead.iter().any(|d| *d) {
            return Ok(());
        }
        let mut code = Vec::with_capacity(self.code.len());
        let mut lines = Vec::with_capacity(self.lines.len());
        let mut cols = Vec::with_capacity(self.cols.len());
        let mut moved = Vec::with_capacity(self.code.len() + 1);
        for (at, op) in take(&mut self.code).into_iter().enumerate() {
            // a jump to a removed op lands on the op after it
            moved.push(u32::try_from(code.len())?);
            if dead[at] {
                continue;
            }
            code.push(op);
            lines.push(self.lines[at]);
            cols.push(self.cols[at]);
        }
        moved.push(u32::try_from(code.len())?);
        retarget_jumps(&mut code, &moved);
        self.code = code;
        self.lines = lines;
        self.cols = cols;
        Ok(())
    }

    /// A borrow parameter or a reference local forwards a handle, never a value of its own.
    fn shares_only(&self, reg: Reg) -> bool {
        self.borrow_params.contains(&reg) || self.ref_locals.contains(&reg)
    }

    fn into_chunk(mut self, file: std::sync::Arc<str>) -> Result<Chunk> {
        self.insert_cell_drops()?;
        self.child_moves = self
            .children
            .iter()
            .map(|_| Arc::from(Vec::new()))
            .collect();
        self.resolve_owns();
        let dead = self.dead_unit_loads();
        self.remove_ops(&dead)?;
        let dead = self.dead_jumps();
        self.remove_ops(&dead)?;
        let mut droppable: Vec<Reg> = self
            .drop_lists
            .iter()
            .flat_map(|list| list.iter().copied())
            .collect();
        droppable.sort_unstable_by(|a, b| b.cmp(a));
        droppable.dedup();
        Ok(Chunk {
            code: self.code,
            lines: self.lines,
            cols: self.cols,
            file,
            num_regs: self.max_reg as usize,
            num_params: self.num_params,
            param_types: self.param_types,
            name: self.name,
            module: 0,
            moves: false,
            consts: self.consts,
            members: self.members,
            pats: self.pats,
            fmts: self.fmts,
            struct_lits: self.struct_lits,
            enum_variants: self.enum_variants,
            casts: self.casts,
            defaults: self.defaults,
            try_targets: self.try_targets,
            coerces: self.coerces,
            paths: self.paths,
            names: self.names,
            children: self.children,
            child_caps: self.child_caps,
            child_moves: self.child_moves,
            generics: self.generics,
            drop_lists: self.drop_lists,
            droppable: droppable.into(),
            call_type_args: self.call_type_args,
            path_forwarder: false,
            clears_frame: self.has_guards,
        })
    }
}

struct LoopCtx {
    /// patched to the end
    breaks: Vec<usize>,
    /// `None` for a labeled block, which only `break` can leave
    continue_to: Option<usize>,
    /// for `loop { break v }`
    result: Reg,
    /// a `break` or `continue` ends every scope deeper than this first
    scope_depth: usize,
    /// `'name` on the loop
    label: Option<String>,
}

/// Where the source states a `collect` target, the call is renamed to a target specific method.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum CollectTarget {
    Str,
    Map,
    Set,
}

impl CollectTarget {
    pub(super) fn method_name(self) -> &'static str {
        match self {
            Self::Str => "collect_string",
            Self::Map => "collect_map",
            Self::Set => "collect_set",
        }
    }

    pub(super) fn of_type(ty: &syn::Type) -> Option<Self> {
        let syn::Type::Path(p) = ty else { return None };
        match p.path.segments.last()?.ident.to_string().as_str() {
            "String" => Some(Self::Str),
            "HashMap" | "BTreeMap" => Some(Self::Map),
            "HashSet" | "BTreeSet" => Some(Self::Set),
            _ => None,
        }
    }
}

pub struct Compiler<'a> {
    ctx: &'a Ctx<'a>,
    /// the type of every expression of the body being compiled, see `infer`
    types: infer::Types,
    frames: Vec<FnState>,
    loops: Vec<LoopCtx>,
    /// stamped onto every emitted op
    cur_line: u32,
    cur_col: u32,
    /// 1 shape per layout, so shape identity means layout identity. The member slot cache of the
    /// scalar plan keys on it.
    pub(super) shapes: Vec<std::sync::Arc<crate::interpreter::bytecode::StructShape>>,
}

#[derive(Clone, Copy)]
enum NameLoc {
    Local(Reg),
    Cell(Reg),
    Upvalue(u16),
    /// not a variable
    None,
}

impl<'a> Compiler<'a> {
    pub fn new(ctx: &'a Ctx<'a>) -> Compiler<'a> {
        Compiler {
            ctx,
            types: infer::Types::empty(),
            frames: Vec::new(),
            loops: Vec::new(),
            cur_line: 0,
            cur_col: 0,
            shapes: Vec::new(),
        }
    }

    pub(super) fn set_line(&mut self, span: proc_macro2::Span) {
        let start = span.start();
        self.cur_line = u32::try_from(start.line).unwrap_or(u32::MAX);
        self.cur_col = u32::try_from(start.column + 1).unwrap_or(u32::MAX);
    }

    pub(super) fn resolve_path_res(&self, segs: &[String]) -> Result<Res> {
        self.ctx.resolver.resolve(self.ctx.module, segs)
    }

    pub fn compile_fn(&mut self, sig: &syn::Signature, block: &Block) -> Result<Chunk> {
        self.types = infer::infer_fn(self.ctx, sig, block);
        self.frames.push(FnState::new(sig.ident.to_string()));
        // so a caller's turbofish type args can be bound, `from_str::<T>`
        let generics: Vec<Arc<str>> = sig
            .generics
            .type_params()
            .map(|p| Arc::from(p.ident.to_string().as_str()))
            .collect();
        self.cur().generics = generics;
        // parameters occupy the first registers
        let mut params: Vec<Option<&Pat>> = Vec::new();
        let mut types: Vec<Option<String>> = Vec::new();
        let mut annotations: Vec<Option<&syn::Type>> = Vec::new();
        // a mutable access through a borrow must reach the caller's storage, so it never splits
        let mut borrows: Vec<bool> = Vec::new();
        for input in &sig.inputs {
            match input {
                FnArg::Receiver(r) => {
                    params.push(None);
                    types.push(None);
                    annotations.push(None);
                    borrows.push(matches!(r.kind, syn::ReceiverKind::Reference(..)));
                }
                FnArg::Typed(t) => {
                    params.push(Some(&t.pat));
                    types.push(type_head(&t.ty));
                    annotations.push(Some(&t.ty));
                    borrows.push(matches!(&*t.ty, syn::Type::Reference(_)));
                }
            }
        }
        self.cur().num_params = params.len();
        self.cur().param_types = types;
        self.bind_params(sig, &params, &annotations, &borrows)?;
        // the return type retags the tail and every early `return`
        if let syn::ReturnType::Type(_, ty) = &sig.output
            && numeric_annotation(ty).is_some()
        {
            let idx = self.add_cast(ty);
            self.cur().ret_cast = Some(idx);
        }
        self.install_return_error(&sig.output);
        let ret = self.alloc();
        self.compile_block(block, ret)?;
        if let Some(idx) = self.cur().ret_cast {
            self.emit(Op::Cast {
                dst: ret,
                src: ret,
                ty: idx,
            });
        }
        // by value parameters drop before the frame returns
        self.emit_scope_drops(1);
        self.emit(Op::Ret { src: ret });
        self.finish_chunk()
    }

    /// Parameters occupy the first registers, in order.
    fn bind_params(
        &mut self,
        sig: &syn::Signature,
        params: &[Option<&Pat>],
        annotations: &[Option<&syn::Type>],
        borrows: &[bool],
    ) -> Result<()> {
        // a pattern param binds more registers, so every param slot is claimed before any binding
        let regs: Vec<Reg> = params.iter().map(|_| self.alloc()).collect();
        for (i, (p, reg)) in params.iter().zip(regs).enumerate() {
            debug_assert_eq!(reg as usize, i);
            if borrows[i] {
                self.cur().borrow_params.insert(reg);
            }
            match p {
                None => self.define("self", reg),
                Some(Pat::Ident(id)) if id.subpat.is_none() => {
                    self.define(&id.ident.to_string(), reg);
                }
                Some(pat) => self.bind_pattern_irrefutable(pat, reg)?,
            }
            // A `mut` by value parameter may be a `Copy` of a caller value that stays live, so it
            // owns a copy unless its type rules `Copy` out.
            let mutable = match (p, &sig.inputs[i]) {
                (None, FnArg::Receiver(r)) => {
                    matches!(r.kind, syn::ReceiverKind::Value)
                        && r.mutability.is_some()
                        && self
                            .ctx
                            .impl_type
                            .is_none_or(|ty| !self.is_non_copy_name(ty))
                }
                (Some(Pat::Ident(id)), _) => {
                    id.mutability.is_some()
                        && !borrows[i]
                        && !self.is_non_copy_annotation(annotations[i])
                }
                _ => false,
            };
            if mutable {
                self.emit(Op::Copy { dst: reg, src: reg });
            }
            // a numeric param retags the value, so u8 arithmetic in the body panics at the u8 bound
            if let Some(ty) = annotations[i]
                && numeric_annotation(ty).is_some()
            {
                let idx = self.add_cast(ty);
                self.emit(Op::Cast {
                    dst: reg,
                    src: reg,
                    ty: idx,
                });
            }
        }
        Ok(())
    }

    pub fn compile_const(&mut self, expr: &Expr, ty: &syn::Type) -> Result<Chunk> {
        self.types = infer::infer_const(self.ctx, expr, Some(ty));
        self.frames.push(FnState::new("<const>".to_string()));
        let ret = self.alloc();
        self.compile_into(ret, expr)?;
        self.emit(Op::Ret { src: ret });
        self.finish_chunk()
    }

    fn finish_chunk(&mut self) -> Result<Chunk> {
        let mut chunk = self
            .frames
            .pop()
            .unwrap()
            .into_chunk(self.ctx.file.clone())?;
        chunk.module = idx16(self.ctx.module);
        Ok(chunk)
    }

    // frame helpers

    fn cur(&mut self) -> &mut FnState {
        self.frames.last_mut().unwrap()
    }

    fn emit(&mut self, op: Op) {
        let line = self.cur_line;
        let col = self.cur_col;
        let f = self.cur();
        if let Op::Method { dst, name, .. } = &op
            && f.names[usize::from(*name)].id.is_borrow()
        {
            f.guard_temps.push(*dst);
            f.has_guards = true;
        }
        f.code.push(op);
        f.lines.push(line);
        f.cols.push(col);
    }

    fn here(&mut self) -> usize {
        self.cur().code.len()
    }

    /// Errors when a function grows past what u32 targets can address.
    fn mark(&mut self) -> Result<u32> {
        Ok(u32::try_from(self.here())?)
    }

    fn alloc(&mut self) -> Reg {
        let f = self.cur();
        let r = f.reg_top;
        f.reg_top += 1;
        if f.reg_top > f.max_reg {
            f.max_reg = f.reg_top;
        }
        r
    }

    fn push_scope(&mut self) {
        let f = self.cur();
        f.scopes.push(HashMap::default());
        f.scope_order.push(Vec::new());
    }

    fn pop_scope(&mut self) {
        let f = self.cur();
        f.scopes.pop();
        f.scope_order.pop();
    }

    fn define(&mut self, name: &str, reg: Reg) {
        let f = self.cur();
        f.aliases.remove(name);
        f.scopes.last_mut().unwrap().insert(name.to_string(), reg);
        f.scope_order.last_mut().unwrap().push(reg);
        f.binding_sites.push((f.code.len(), reg));
    }

    fn define_block_const(&mut self, name: &str, reg: Reg) {
        self.define(name, reg);
        self.cur().block_consts.insert(name.to_string());
    }

    /// A closure body sees the constants of the function that holds it.
    pub(super) fn block_const(&self, name: &str) -> bool {
        self.frames.iter().any(|f| f.block_consts.contains(name))
    }

    /// `depth` 1 is the current scope alone, a `return` uses every open scope. Scopes are not popped.
    /// Without `Drop` impls only `RefCell` guard bindings drop, everything else can stay.
    fn emit_scope_drops(&mut self, depth: usize) {
        let has_drop = self.ctx.has_drop;
        if !has_drop && self.cur().guard_regs.is_empty() {
            return;
        }
        let f = self.cur();
        let total = f.scope_order.len();
        let lists: Vec<Vec<Reg>> = f
            .scope_order
            .iter()
            .skip(total.saturating_sub(depth))
            .rev()
            .cloned()
            .collect();
        for regs in lists {
            let regs: Vec<Reg> = regs
                .into_iter()
                .filter(|r| {
                    let f = self.cur();
                    !f.borrow_params.contains(r)
                        && (f.guard_regs.contains(r) || (has_drop && !f.drop_exempt.contains(r)))
                })
                .collect();
            if regs.is_empty() {
                continue;
            }
            let f = self.cur();
            f.drop_lists.push(regs.into());
            let list = idx16(f.drop_lists.len() - 1);
            self.emit(Op::DropScope { list });
        }
    }

    fn add_const(&mut self, c: Const) -> u16 {
        let f = self.cur();
        f.consts.push(c);
        idx16(f.consts.len() - 1)
    }

    fn add_member(&mut self, m: Member) -> u16 {
        let f = self.cur();
        f.members.push(m);
        idx16(f.members.len() - 1)
    }

    fn add_cast(&mut self, ty: &syn::Type) -> u16 {
        let f = self.cur();
        f.casts.push(lower_cast(ty));
        idx16(f.casts.len() - 1)
    }

    /// A closure body has no generics of its own.
    pub(super) fn lower_ir(&self, ty: &syn::Type) -> TypeIr {
        let generics = &self.frames.last().unwrap().generics;
        lower_type(ty, self.ctx.resolver, self.ctx.module, generics)
    }

    fn add_coerce(&mut self, ir: TypeIr) -> u16 {
        let f = self.cur();
        f.coerces.push(ir);
        idx16(f.coerces.len() - 1)
    }

    fn add_name(&mut self, name: String) -> u16 {
        self.add_name_with(name, None)
    }

    fn add_name_with(&mut self, name: String, scalar: Option<ScalarTy>) -> u16 {
        self.add_name_full(name, scalar, None, false)
    }

    fn add_name_full(
        &mut self,
        name: String,
        scalar: Option<ScalarTy>,
        default: Option<DefaultIr>,
        place: bool,
    ) -> u16 {
        let bare = name.strip_prefix("r#").unwrap_or(&name);
        let id = BuiltinId::resolve(bare);
        let atom = self.ctx.method_atoms.get(bare).copied().unwrap_or(NO_ATOM);
        let f = self.cur();
        f.names.push(MethodName {
            id,
            atom,
            text: name,
            scalar,
            default: default.map(Arc::new),
            place,
        });
        idx16(f.names.len() - 1)
    }

    /// `String::from` after `impl From<Point> for String` stays a user call.
    pub(super) fn external_path(&self, segs: Vec<String>, coerce: Option<TypeIr>) -> PathRef {
        if let [.., ty, name] = segs.as_slice()
            && self.ctx.impl_methods.contains(&(ty.clone(), name.clone()))
        {
            return PathRef::user(segs, coerce);
        }
        PathRef::new(segs, coerce)
    }

    fn add_path(&mut self, path: PathRef) -> u16 {
        let f = self.cur();
        f.paths.push(path);
        idx16(f.paths.len() - 1)
    }

    fn add_enum_variant(&mut self, variant: EnumVariant) -> u16 {
        let variants = &mut self.cur().enum_variants;
        if let Some(index) = variants.iter().position(|known| {
            EnumDef::same(&known.def, &variant.def) && known.variant == variant.variant
        }) {
            return idx16(index);
        }
        variants.push(variant);
        idx16(variants.len() - 1)
    }

    fn enum_variant(
        &self,
        enum_name: &Arc<str>,
        rest: &[String],
        fields: impl Fn(&syn::Fields) -> bool,
    ) -> Option<EnumVariant> {
        let variant_name = rest.first().filter(|_| rest.len() == 1)?;
        let definition = self.ctx.resolver.enums.get(enum_name)?;
        definition
            .variants
            .iter()
            .find(|variant| variant.ident == variant_name && fields(&variant.fields))?;
        let def = self.ctx.resolver.enum_defs.get(enum_name)?;
        Some(EnumVariant {
            def: def.clone(),
            variant: def.variant_index(variant_name)?,
        })
    }

    // name resolution

    pub(super) fn patch_jump(&mut self, at: usize, to: u32) {
        match &mut self.cur().code[at] {
            Op::Jump { to: t }
            | Op::JumpIfFalse { to: t, .. }
            | Op::JumpIfTrue { to: t, .. }
            | Op::CmpJump { to: t, .. }
            | Op::CmpJumpImm { to: t, .. }
            | Op::CmpJumpInt { to: t, .. }
            | Op::CmpJumpIntImm { to: t, .. }
            | Op::ForNext { to: t, .. }
            | Op::TryJump { to: t, .. } => *t = to,
            _ => panic!("patch target is not a jump"),
        }
    }
}

// free helpers

mod assign;
mod block;
mod calls;
mod closure;
mod defaults;
mod expr;
mod flow;
mod guards;
mod infer;
mod liveness;
mod macros;
mod method;
mod names;
mod pattern;
mod place;
mod struct_lit;
mod support;
mod typed;
mod walks;

use support::{
    FloatTy, NumericTy, bin_kind, collect_pattern_names, expr_kind, first_generic_type,
    inline_holes, int_literal, is_assign_op, macro_yields_value, numeric_annotation, parse_exprs,
    parse_matches, parse_vec_repeat, type_head,
};

impl Compiler<'_> {
    /// True when the type can not be `Copy`, a `String`, a container, a cell, a user type that
    /// does not derive `Copy`. Unknown types answer false, so they copy to be safe.
    pub(super) fn is_non_copy_annotation(&self, ty: Option<&syn::Type>) -> bool {
        let Some(ty) = ty else { return false };
        match ty {
            syn::Type::Paren(p) => self.is_non_copy_annotation(Some(&p.elem)),
            syn::Type::Group(g) => self.is_non_copy_annotation(Some(&g.elem)),
            syn::Type::Tuple(t) => t
                .elems
                .iter()
                .any(|elem| self.is_non_copy_annotation(Some(elem))),
            syn::Type::Array(a) => self.is_non_copy_annotation(Some(&a.elem)),
            syn::Type::Path(p) => {
                let Some(last) = p.path.segments.last() else {
                    return false;
                };
                let name = last.ident.to_string();
                if matches!(
                    name.as_str(),
                    "String"
                        | "Vec"
                        | "VecDeque"
                        | "HashMap"
                        | "HashSet"
                        | "BTreeMap"
                        | "BTreeSet"
                        | "Box"
                        | "Rc"
                        | "Arc"
                        | "RefCell"
                        | "Cell"
                        | "Mutex"
                        | "PathBuf"
                        | "OsString"
                ) {
                    return true;
                }
                let segs: Vec<String> = p
                    .path
                    .segments
                    .iter()
                    .map(|s| s.ident.to_string())
                    .collect();
                let segs = match (segs.first().map(String::as_str), self.ctx.impl_type) {
                    (Some("Self"), Some(ty)) => vec![ty.to_string()],
                    _ => segs,
                };
                match self.resolve_path_res(&segs) {
                    Ok(Res::Struct(canon)) => self.is_non_copy_name(&canon),
                    Ok(Res::Enum(canon)) => self
                        .ctx
                        .resolver
                        .enums
                        .get(&canon)
                        .is_some_and(|e| !derives_copy(&e.attrs)),
                    _ => false,
                }
            }
            _ => false,
        }
    }

    pub(super) fn is_non_copy_name(&self, canon: &str) -> bool {
        self.ctx
            .resolver
            .structs
            .get(canon)
            .is_some_and(|def| !derives_copy(&def.ast.attrs))
    }
}

pub(super) fn derives_copy(attrs: &[syn::Attribute]) -> bool {
    attrs.iter().any(|attr| {
        if !attr.path().is_ident("derive") {
            return false;
        }
        let mut found = false;
        let parsed = attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("Copy") {
                found = true;
            }
            Ok(())
        });
        parsed.is_ok() && found
    })
}

/// Past u16 is a compiler bug, an abort beats a wrapped index.
pub(super) fn idx16(i: usize) -> u16 {
    u16::try_from(i).expect("bytecode table exceeds u16 indices")
}

pub(super) fn derives_default(attrs: &[syn::Attribute]) -> bool {
    attrs.iter().any(|attr| {
        if !attr.path().is_ident("derive") {
            return false;
        }
        let mut found = false;
        let parsed = attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("Default") {
                found = true;
            }
            Ok(())
        });
        parsed.is_ok() && found
    })
}