run-rs 0.2.22

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
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
//! Calls, closures, assignment, struct literals, and patterns. Split from the compiler.

use std::rc::Rc;

use anyhow::{Result, bail};
use syn::{Expr, Lit, Pat, UnOp};

use crate::interpreter::bytecode::{
    BinKind, CapSource, DISCARD, Member, Op, PLit, PPat, PatInfo, Reg, ScalarTy, StructLit,
};
use crate::interpreter::json_bridge::serde_rename;
use crate::interpreter::value::StructShape;

use super::*;

impl Compiler<'_> {
    /// Compile arguments into a fresh contiguous register window and return its
    /// base. The window is reserved first so an argument's own temporaries,
    /// allocated above it, cannot break the packing.
    pub(super) fn compile_args<'e>(&mut self, args: impl Iterator<Item = &'e Expr>) -> Result<Reg> {
        let list: Vec<&Expr> = args.collect();
        let base = self.cur().reg_top;
        for _ in 0..list.len() {
            self.alloc();
        }
        for (i, a) in list.iter().enumerate() {
            self.compile_into(base + i as Reg, a)?;
        }
        Ok(base)
    }

    /// Record the turbofish type args on a call path, e.g. the `AppList` in
    /// `get_json::<AppList>(..)`, returning an index into the current chunk's
    /// `call_type_args` table, or `u32::MAX` when there are none.
    fn record_call_type_args(&mut self, path: &syn::Path) -> u32 {
        let Some(seg) = path.segments.last() else {
            return u32::MAX;
        };
        let syn::PathArguments::AngleBracketed(ab) = &seg.arguments else {
            return u32::MAX;
        };
        let mut types = Vec::new();
        for a in &ab.args {
            if let syn::GenericArgument::Type(t) = a {
                types.push(self.lower_ir(t));
            }
        }
        if types.is_empty() {
            return u32::MAX;
        }
        let table = &mut self.cur().call_type_args;
        table.push(Arc::from(types.into_boxed_slice()));
        (table.len() - 1) as u32
    }

    pub(super) fn compile_call(&mut self, dst: Reg, c: &syn::ExprCall) -> Result<()> {
        let Expr::Path(path_expr) = &*c.func else {
            let callee = self.compile_expr(&c.func)?;
            let base = self.compile_args(c.args.iter())?;
            self.emit(Op::CallValue {
                dst,
                callee,
                base,
                argc: c.args.len() as u16,
            });
            self.emit_mut_arg_writebacks(c.args.iter(), base)?;
            return Ok(());
        };
        let path = &path_expr.path;
        // tokio::spawn(async { .. }) lowers to a Spawn op carrying the async
        // block as a child chunk, so the task runs on its own worker thread.
        if self.ctx.async_mode && is_tokio_spawn(path) {
            match c.args.first() {
                Some(Expr::Async(block)) if c.args.len() == 1 => {
                    return self.compile_spawn(dst, &block.block);
                }
                _ => bail!("tokio::spawn needs an async block in this interpreter"),
            }
        }
        let coerce = path
            .segments
            .last()
            .and_then(first_generic_type)
            .map(|t| self.lower_ir(t));
        // A pending `let` annotation attaches to exactly this call, see
        // `Compiler::json_let`. Failing that, the enclosing signature may name
        // the target because the function hands this parse back, see
        // `Compiler::json_tails`.
        let coerce = match coerce {
            Some(ty) => Some(ty),
            None => match &self.json_let {
                Some((ptr, ty)) if std::ptr::eq(*ptr, c) => {
                    let ty = ty.clone();
                    self.json_let = None;
                    Some(ty)
                }
                _ => self.json_tails.get(&std::ptr::from_ref(c)).cloned(),
            },
        };
        let argc = c.args.len() as u16;

        if path.segments.len() == 1 {
            let name = path.segments[0].ident.to_string();
            // A local or captured closure value called directly.
            let callee = match self.resolve(&name) {
                NameLoc::Local(reg) => Some(reg),
                NameLoc::Cell(cell) => {
                    let reg = self.alloc();
                    self.emit(Op::LoadCell { dst: reg, cell });
                    Some(reg)
                }
                NameLoc::Upvalue(idx) => {
                    let reg = self.alloc();
                    self.emit(Op::LoadUpvalue { dst: reg, idx });
                    Some(reg)
                }
                NameLoc::None => None,
            };
            if let Some(callee) = callee {
                let base = self.compile_args(c.args.iter())?;
                self.emit(Op::CallValue {
                    dst,
                    callee,
                    base,
                    argc,
                });
                self.emit_mut_arg_writebacks(c.args.iter(), base)?;
                return Ok(());
            }
        }
        let segs: Vec<String> = path.segments.iter().map(|s| s.ident.to_string()).collect();
        let resolved = match self.resolve_path_res(&segs) {
            Ok(r) => r,
            Err(_) => Res::External(segs.clone()),
        };
        let path_segs = match resolved {
            // A known function, called directly by id. Turbofish type args are
            // recorded so the callee can bind them to its generic parameters.
            Res::Fn(idx) => {
                let targ = self.record_call_type_args(path);
                let base = self.compile_args(c.args.iter())?;
                self.emit(Op::CallFn {
                    dst,
                    func: idx,
                    base,
                    argc,
                    targ,
                });
                self.emit_mut_arg_writebacks(c.args.iter(), base)?;
                return Ok(());
            }
            // A tuple struct constructor.
            Res::Struct(canon) => vec![canon.to_string()],
            // An associated function, UFCS method, or tuple enum variant.
            Res::TypeMember(canon, rest) => {
                if let Some(variant) = self.enum_variant(&canon, &rest, |fields| {
                    matches!(fields, syn::Fields::Unnamed(fields) if fields.unnamed.len() == argc as usize)
                }) {
                    let base = self.compile_args(c.args.iter())?;
                    let info = self.add_enum_variant(variant);
                    self.emit(Op::MakeEnum {
                        dst,
                        info,
                        base,
                        count: argc,
                    });
                    return Ok(());
                }
                let mut segs = vec![canon.to_string()];
                segs.extend(rest);
                segs
            }
            // A tuple struct built through a type alias, `type P = Point; P(..)`.
            Res::Alias(m, target) => {
                let aliased = match &*target {
                    syn::Type::Path(p) => self.ctx.resolver.resolve_struct_key(m, &p.path),
                    _ => None,
                };
                match aliased {
                    Some(canon) => vec![canon.to_string()],
                    None => bail!("cannot call `{}`", segs.join("::")),
                }
            }
            Res::Enum(_) | Res::Module | Res::Const(_) => {
                bail!("cannot call `{}`", segs.join("::"))
            }
            // Everything else, resolved by the VM through the bridge dispatch.
            Res::External(segs) => {
                if is_transparent_new(&segs) && c.args.len() == 1 {
                    return self.compile_into(dst, &c.args[0]);
                }
                segs
            }
        };
        let p = self.add_path(path_segs, coerce);
        let base = self.compile_args(c.args.iter())?;
        self.emit(Op::CallPath {
            dst,
            path: p,
            base,
            argc,
        });
        Ok(())
    }

    pub(super) fn compile_method(&mut self, dst: Reg, m: &syn::ExprMethodCall) -> Result<()> {
        // `v[a..b].copy_from_slice(src)` must write through to `v`. Indexing
        // with a range builds a copied temporary, so the call is compiled
        // against the base vec with the bounds as leading arguments instead.
        // An open end becomes the max sentinel the bridge clamps to the len.
        if m.method == "copy_from_slice" {
            let Expr::Index(ix) = &*m.receiver else {
                bail!("copy_from_slice is only supported on a `v[a..b]` receiver");
            };
            let Expr::Range(r) = &*ix.index else {
                bail!("copy_from_slice is only supported on a `v[a..b]` receiver");
            };
            let Some(src) = m.args.first() else {
                bail!("copy_from_slice takes the source slice");
            };
            let recv = self.compile_expr(&ix.expr)?;
            let base = self.cur().reg_top;
            for _ in 0..3 {
                self.alloc();
            }
            match &r.start {
                Some(e) => self.compile_into(base, e)?,
                None => self.emit(Op::LoadInt { dst: base, v: 0 }),
            }
            match &r.end {
                Some(e) => {
                    self.compile_into(base + 1, e)?;
                    if matches!(r.limits, syn::RangeLimits::Closed(_)) {
                        self.emit(Op::BinImm {
                            dst: base + 1,
                            a: base + 1,
                            imm: 1,
                            op: BinKind::Add,
                        });
                    }
                }
                None => self.emit(Op::LoadInt {
                    dst: base + 1,
                    v: i64::MAX,
                }),
            }
            self.compile_into(base + 2, src)?;
            let name = self.add_name("copy_from_slice".to_string());
            self.set_line(m.method.span());
            self.emit(Op::Method {
                dst,
                recv,
                name,
                base,
                argc: 3,
            });
            return Ok(());
        }
        // Fuse `x.get(k).copied().unwrap_or(d)` into one op. The chain builds
        // and tears down an Option per call, which dominates counting loops.
        if dst != DISCARD
            && m.method == "unwrap_or"
            && m.args.len() == 1
            && let Expr::MethodCall(c) = &*m.receiver
            && (c.method == "copied" || c.method == "cloned")
            && c.args.is_empty()
            && let Expr::MethodCall(g) = &*c.receiver
            && g.method == "get"
            && g.args.len() == 1
        {
            let recv = self.compile_expr(&g.receiver)?;
            let key = self.compile_expr(&g.args[0])?;
            let default = self.compile_expr(&m.args[0])?;
            self.emit(Op::GetOrDefault {
                dst,
                recv,
                key,
                default,
            });
            return Ok(());
        }
        // An `unwrap_or_default` whose own result is unwrapped again must have
        // produced an `Option`, so its default is `None`. That is a fact about
        // the shape of the chain, not a guess about the type, and it is the
        // only thing that can type the inner call of
        // `x.unwrap_or_default().unwrap_or_default()`.
        let outer_option_hint = self.option_result.take();
        if m.method == "unwrap_or_default"
            && let Expr::MethodCall(inner) = &*m.receiver
            && inner.method == "unwrap_or_default"
        {
            self.option_result = Some(std::ptr::from_ref(inner));
        }
        let recv = self.compile_expr(&m.receiver)?;
        self.option_result = outer_option_hint;
        let base = self.compile_args(m.args.iter())?;
        // `collect` is type driven in real Rust. The interpreter has no types,
        // so the three places the target is knowable lower to their own method
        // here: a turbofish asking for a String, a pending `let s: String`
        // annotation attached to exactly this call, and a `-> String` signature
        // on the function whose returned value this call produces. See
        // `Compiler::string_let` and `Compiler::string_tails`.
        let mut method = m.method.to_string();
        if method == "collect" {
            let turbofish_string = m.turbofish.as_ref().is_some_and(names_string);
            let let_string = matches!(self.string_let, Some(ptr) if std::ptr::eq(ptr, m));
            let tail_string = self.string_tails.contains(&std::ptr::from_ref(m));
            if turbofish_string || let_string || tail_string {
                self.string_let = None;
                method = "collect_string".to_string();
            }
        }
        // An explicit turbofish is the only place a method's result type is
        // written down, so it rides on the name for the methods that need it.
        let mut scalar = turbofish_scalar(m.turbofish.as_ref());
        // `unwrap_or_default` carries no turbofish of its own, its type is the
        // payload of the Option it is called on. Wherever the source states
        // that payload, as `None::<u64>` or `then_some(1u8)` do, the receiver
        // is where it appears, and without it the default fell back to an
        // empty string whatever the real type was.
        if scalar.is_none() && m.method == "unwrap_or_default" {
            scalar = option_payload(&m.receiver, &self.option_locals);
        }
        // A pending `let x: T = ...unwrap_or_default()` annotation names the
        // payload of the outermost call in the chain.
        if scalar.is_none()
            && let Some((ptr, ty)) = &self.default_let
            && std::ptr::eq(*ptr, m)
        {
            scalar = Some(ty.clone());
            self.default_let = None;
        }
        // Failing all of that, this call's own result is unwrapped again, so
        // whatever it holds, it produced an Option and defaults to None.
        if matches!(self.option_result, Some(ptr) if std::ptr::eq(ptr, m)) {
            self.option_result = None;
            scalar = scalar.or(Some(ScalarTy::Opt(Box::new(ScalarTy::Other))));
        }
        let name = self.add_name_with(method, scalar);
        // A multiline chain compiles its receiver and args first, so restamp
        // with the method's own line before the op lands, the line rustc
        // would name for this call.
        self.set_line(m.method.span());
        self.emit(Op::Method {
            dst,
            recv,
            name,
            base,
            argc: m.args.len() as u16,
        });
        // Methods that fill a `&mut` argument, like read_line, write the new
        // value into the arg window. The window slot is only a copy of the
        // variable, so move the result back into the variable register.
        self.emit_mut_arg_writebacks(m.args.iter(), base)?;
        Ok(())
    }

    /// Emit a writeback for every `&mut variable` argument of a finished call.
    /// The callee worked on the arg window copy, and the VM hands the final
    /// values back into that window on return, so a move from the window slot
    /// lands the mutation in the caller's variable. Only calls whose window
    /// survives the call may use this, a `CallPath` consumes its args instead.
    fn emit_mut_arg_writebacks<'e>(
        &mut self,
        args: impl Iterator<Item = &'e Expr>,
        base: Reg,
    ) -> Result<()> {
        for (i, arg) in args.enumerate() {
            if let Expr::Reference(r) = arg
                && r.mutability.is_some()
                && let Expr::Path(p) = &*r.expr
                && p.path.segments.len() == 1
                && p.qself.is_none()
            {
                let name = p.path.segments[0].ident.to_string();
                let location = self.resolve_for_write(&name);
                self.emit_name_store(location, base + i as u16, &name)?;
            }
        }
        Ok(())
    }

    /// Compile an `async { .. }` block from `tokio::spawn` into a zero argument
    /// child chunk and emit a Spawn op. Captures work like a closure's.
    fn compile_spawn(&mut self, dst: Reg, block: &syn::Block) -> Result<()> {
        self.frames.push(FnState::new("<task>".to_string()));
        self.cur().num_params = 0;
        let ret = self.alloc();
        self.compile_block(block, ret)?;
        self.emit(Op::Ret { src: ret });
        let child = self.frames.pop().unwrap();
        let caps: Vec<CapSource> = child.upvalues.iter().map(|(_, s)| *s).collect();
        let mut chunk = child.into_chunk(self.ctx.file.clone());
        chunk.module = self.ctx.module as u16;
        let parent = self.cur();
        let child_idx = parent.children.len() as u16;
        parent.children.push(Rc::new(chunk));
        parent.child_caps.push(caps);
        self.emit(Op::Spawn {
            dst,
            child: child_idx,
        });
        Ok(())
    }

    pub(super) fn compile_closure(&mut self, dst: Reg, c: &syn::ExprClosure) -> Result<()> {
        self.frames.push(FnState::new("<closure>".to_string()));
        let params: Vec<&Pat> = c.inputs.iter().collect();
        self.cur().num_params = params.len();
        for p in &params {
            let reg = self.alloc();
            match p {
                Pat::Ident(id) if id.subpat.is_none() => self.define(&id.ident.to_string(), reg),
                _ => self.bind_pattern_irrefutable(p, reg)?,
            }
        }
        let ret = self.alloc();
        self.compile_into(ret, &c.body)?;
        self.emit(Op::Ret { src: ret });
        let child = self.frames.pop().unwrap();
        let caps: Vec<CapSource> = child.upvalues.iter().map(|(_, s)| *s).collect();
        let mut chunk = child.into_chunk(self.ctx.file.clone());
        chunk.module = self.ctx.module as u16;
        let chunk = Rc::new(chunk);
        let parent = self.cur();
        let child_idx = parent.children.len() as u16;
        parent.children.push(chunk);
        parent.child_caps.push(caps);
        self.emit(Op::MakeClosure {
            dst,
            child: child_idx,
        });
        Ok(())
    }

    // -- assignment --------------------------------------------------------

    pub(super) fn compile_assign(&mut self, target: &Expr, value: &Expr) -> Result<()> {
        match target {
            Expr::Path(p) if p.path.segments.len() == 1 => {
                let name = p.path.segments[0].ident.to_string();
                let location = self.resolve_for_write(&name);
                let value = self.compile_expr(value)?;
                self.emit_name_store(location, value, &name)?;
            }
            Expr::Index(idx) => {
                let base = self.compile_expr(&idx.expr)?;
                let key = self.compile_expr(&idx.index)?;
                let val = self.compile_expr(value)?;
                self.emit(Op::SetIndex { base, key, val });
            }
            Expr::Field(f) => {
                let base = self.compile_expr(&f.base)?;
                let member = self.member_of(&f.member);
                let val = self.compile_expr(value)?;
                self.emit(Op::SetField { base, member, val });
            }
            Expr::Unary(u) if matches!(u.op, UnOp::Deref(_)) => {
                let target = self.compile_expr(&u.expr)?;
                let val = self.compile_expr(value)?;
                self.emit(Op::SetDeref { target, val });
            }
            Expr::Paren(p) => self.compile_assign(&p.expr, value)?,
            _ => bail!("invalid assignment target"),
        }
        Ok(())
    }

    pub(super) fn compile_compound_assign(
        &mut self,
        target: &Expr,
        op: BinKind,
        rhs: &Expr,
    ) -> Result<()> {
        // `a op= b` becomes `a = a op b`.
        match target {
            Expr::Path(p) if p.path.segments.len() == 1 => {
                let name = p.path.segments[0].ident.to_string();
                let location = self.resolve_for_write(&name);
                let current = self.load_name_location(location, &name)?;
                let result = self.alloc();
                if let Some(imm) = int_literal(rhs) {
                    self.emit(Op::BinImm {
                        dst: result,
                        a: current,
                        imm,
                        op,
                    });
                } else {
                    let b = self.compile_expr(rhs)?;
                    self.emit(Op::Bin {
                        dst: result,
                        a: current,
                        b,
                        op,
                    });
                }
                self.emit_name_store(location, result, &name)?;
            }
            Expr::Index(idx) => {
                let base = self.compile_expr(&idx.expr)?;
                let key = self.compile_expr(&idx.index)?;
                let cur = self.alloc();
                self.emit(Op::Index {
                    dst: cur,
                    base,
                    key,
                });
                let b = self.compile_expr(rhs)?;
                let res = self.alloc();
                self.emit(Op::Bin {
                    dst: res,
                    a: cur,
                    b,
                    op,
                });
                self.emit(Op::SetIndex {
                    base,
                    key,
                    val: res,
                });
            }
            Expr::Field(f) => {
                let base = self.compile_expr(&f.base)?;
                let member = self.member_of(&f.member);
                let cur = self.alloc();
                self.emit(Op::GetField {
                    dst: cur,
                    base,
                    member,
                });
                let b = self.compile_expr(rhs)?;
                let res = self.alloc();
                self.emit(Op::Bin {
                    dst: res,
                    a: cur,
                    b,
                    op,
                });
                self.emit(Op::SetField {
                    base,
                    member,
                    val: res,
                });
            }
            Expr::Unary(u) if matches!(u.op, UnOp::Deref(_)) => {
                let target = self.compile_expr(&u.expr)?;
                let current = self.alloc();
                self.emit(Op::Deref {
                    dst: current,
                    src: target,
                });
                let b = self.compile_expr(rhs)?;
                let result = self.alloc();
                self.emit(Op::Bin {
                    dst: result,
                    a: current,
                    b,
                    op,
                });
                self.emit(Op::SetDeref {
                    target,
                    val: result,
                });
            }
            _ => bail!("invalid compound assignment target"),
        }
        Ok(())
    }

    fn load_name_location(&mut self, location: NameLoc, name: &str) -> Result<Reg> {
        match location {
            NameLoc::Local(reg) => Ok(reg),
            NameLoc::Cell(cell) => {
                let reg = self.alloc();
                self.emit(Op::LoadCell { dst: reg, cell });
                Ok(reg)
            }
            NameLoc::Upvalue(idx) => {
                let reg = self.alloc();
                self.emit(Op::LoadUpvalue { dst: reg, idx });
                Ok(reg)
            }
            NameLoc::None => bail!("assignment to unknown variable `{name}`"),
        }
    }

    fn emit_name_store(&mut self, location: NameLoc, src: Reg, name: &str) -> Result<()> {
        match location {
            NameLoc::Local(dst) if dst != src => self.emit(Op::Move { dst, src }),
            NameLoc::Local(_) => {}
            NameLoc::Cell(cell) => self.emit(Op::StoreCell { cell, src }),
            NameLoc::Upvalue(idx) => self.emit(Op::StoreUpvalue { idx, src }),
            NameLoc::None => bail!("assignment to unknown variable `{name}`"),
        }
        Ok(())
    }

    pub(super) fn member_of(&mut self, member: &syn::Member) -> u16 {
        match member {
            syn::Member::Named(n) => self.add_member(Member::Named(n.to_string().into())),
            syn::Member::Unnamed(i) => self.add_member(Member::Indexed(i.index as usize)),
        }
    }

    pub(super) fn compile_struct_literal(&mut self, dst: Reg, s: &syn::ExprStruct) -> Result<()> {
        // A user struct resolves to its canonical name, which keys shapes,
        // methods, and coercions. Anything else, an enum struct variant for
        // example, keeps the bare last segment.
        let self_type = (s.path.segments.len() == 1 && s.path.segments[0].ident == "Self")
            .then_some(self.ctx.impl_type)
            .flatten();
        let resolved = self_type.map(Rc::<str>::from).or_else(|| {
            self.ctx
                .resolver
                .resolve_struct_key(self.ctx.module, &s.path)
        });
        let (name, def) = match resolved {
            Some(canon) => {
                let def = self.ctx.resolver.structs.get(&canon).map(|d| d.ast.clone());
                (canon.to_string(), def)
            }
            None => {
                let bare = s
                    .path
                    .segments
                    .last()
                    .map(|seg| seg.ident.to_string())
                    .unwrap_or_default();
                (bare, None)
            }
        };
        // Written fields keyed by name.
        let mut written: Vec<(String, &Expr)> = Vec::new();
        for f in &s.fields {
            let key = match &f.member {
                syn::Member::Named(n) => n.to_string(),
                syn::Member::Unnamed(i) => i.index.to_string(),
            };
            written.push((key, &f.expr));
        }
        // Field order follows the declaration when the struct is known.
        // Written fields in declaration order, then any extras. A trailing
        // `..rest` fills whatever was not written.
        let (order, renames): (Vec<String>, Vec<Option<Rc<str>>>) = match def {
            Some(def) => {
                let mut ordered: Vec<String> = def
                    .fields
                    .iter()
                    .filter_map(|f| f.ident.as_ref().map(|i| i.to_string()))
                    .filter(|k| written.iter().any(|(w, _)| w == k))
                    .collect();
                for (k, _) in &written {
                    if !ordered.contains(k) {
                        ordered.push(k.clone());
                    }
                }
                // One rename slot per ordered field, read from the struct def so
                // a serialized literal uses the same json keys as deserialize.
                let renames = ordered
                    .iter()
                    .map(|k| {
                        def.fields
                            .iter()
                            .find(|f| f.ident.as_ref().is_some_and(|i| i == k))
                            .and_then(serde_rename)
                            .map(Rc::<str>::from)
                    })
                    .collect();
                (ordered, renames)
            }
            None => (written.iter().map(|(k, _)| k.clone()).collect(), Vec::new()),
        };
        // Reserve a packed window, then fill it, so field temporaries do not
        // break the packing.
        let has_rest = s.rest.is_some();
        let slots = order.len() + usize::from(has_rest);
        let base = self.cur().reg_top;
        for _ in 0..slots {
            self.alloc();
        }
        for (i, fname) in order.iter().enumerate() {
            let dstf = base + i as Reg;
            match written.iter().find(|(k, _)| k == fname) {
                Some((_, e)) => self.compile_into(dstf, e)?,
                None => self.emit(Op::LoadUnit { dst: dstf }),
            }
        }
        if let Some(rest) = &s.rest {
            self.compile_into(base + order.len() as Reg, rest)?;
        }
        let info = {
            let shape = StructShape::with_renames(
                name,
                order.into_iter().map(Into::into).collect(),
                renames,
            );
            let f = self.cur();
            f.struct_lits.push(StructLit { shape, has_rest });
            (f.struct_lits.len() - 1) as u16
        };
        self.emit(Op::MakeStruct { dst, info, base });
        Ok(())
    }

    // -- patterns ----------------------------------------------------------

    /// Register a pattern and the slot each bound name uses.
    pub(super) fn pattern_info(&mut self, pat: &Pat) -> Result<u16> {
        let mut names = Vec::new();
        collect_pattern_names(pat, &mut names);
        let mut binds = Vec::new();
        for n in names {
            let reg = self.alloc();
            self.define(&n, reg);
            binds.push((n, reg));
        }
        let f = self.cur();
        f.pats.push(PatInfo {
            pat: lower_pattern(pat),
            binds,
        });
        Ok((f.pats.len() - 1) as u16)
    }

    /// Bind an irrefutable pattern whose value already sits in `reg`.
    pub(super) fn bind_pattern_irrefutable(&mut self, pat: &Pat, reg: Reg) -> Result<()> {
        match pat {
            Pat::Ident(id) if id.subpat.is_none() => {
                self.define(&id.ident.to_string(), reg);
                Ok(())
            }
            Pat::Wild(_) => Ok(()),
            Pat::Type(t) => self.bind_pattern_irrefutable(&t.pat, reg),
            Pat::Paren(p) => self.bind_pattern_irrefutable(&p.pat, reg),
            Pat::Reference(r) => self.bind_pattern_irrefutable(&r.pat, reg),
            _ => {
                // Tuple or struct destructuring, use a test-and-bind that always
                // matches for these irrefutable shapes.
                let matched = self.alloc();
                let pidx = self.pattern_info(pat)?;
                self.emit(Op::TestBind {
                    val: reg,
                    pat: pidx,
                    dst: matched,
                });
                Ok(())
            }
        }
    }

    // -- macros ------------------------------------------------------------
}

fn is_transparent_new(segments: &[String]) -> bool {
    let Some((prefix, [receiver, method])) = segments.split_last_chunk::<2>() else {
        return false;
    };
    (prefix.is_empty() || matches!(prefix.first().map(String::as_str), Some("std" | "alloc")))
        && method == "new"
        && matches!(receiver.as_str(), "Box" | "Rc" | "Arc" | "RefCell" | "Cell")
}

// A bare identifier pattern that names a unit variant, not a new binding. Real Rust tells the two
// apart by name resolution, which we do not have, so we lean on the naming rule these scripts
// follow. Bindings are snake_case and variants are UpperCamel. So an uppercase-initial ident with no
// ref, mut, or subpattern is a unit-variant pattern like None, not a binding. Without this a bare
// None arm lowers to an always-true catch-all and matches a Some value.
pub(super) fn is_unit_variant_ident(id: &syn::PatIdent) -> bool {
    id.by_ref.is_none()
        && id.mutability.is_none()
        && id.subpat.is_none()
        && id
            .ident
            .to_string()
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_uppercase())
}

fn lower_pattern(pattern: &Pat) -> PPat {
    match pattern {
        Pat::Wild(_) => PPat::Wild,
        Pat::Rest(_) => PPat::Rest,
        Pat::Ident(ident) if is_unit_variant_ident(ident) => PPat::Path {
            name: Some(ident.ident.to_string()),
        },
        Pat::Ident(ident) => PPat::Ident {
            name: ident.ident.to_string(),
            sub: ident
                .subpat
                .as_ref()
                .map(|subpattern| Box::new(lower_pattern(&subpattern.1))),
        },
        Pat::Lit(literal) => lower_literal(&literal.lit),
        Pat::Paren(paren) => lower_pattern(&paren.pat),
        Pat::Reference(reference) => lower_pattern(&reference.pat),
        Pat::Type(typed) => lower_pattern(&typed.pat),
        Pat::Tuple(tuple) => PPat::Tuple(tuple.elems.iter().map(lower_pattern).collect()),
        Pat::TupleStruct(tuple) => PPat::TupleStruct {
            name: tuple
                .path
                .segments
                .last()
                .map(|segment| segment.ident.to_string()),
            elems: tuple.elems.iter().map(lower_pattern).collect(),
        },
        Pat::Path(path) => PPat::Path {
            name: path
                .path
                .segments
                .last()
                .map(|segment| segment.ident.to_string()),
        },
        Pat::Struct(structure) => PPat::Struct {
            name: structure
                .path
                .segments
                .last()
                .map(|segment| segment.ident.to_string()),
            fields: structure
                .fields
                .iter()
                .map(|field| {
                    let name = match &field.member {
                        syn::Member::Named(name) => name.to_string(),
                        syn::Member::Unnamed(index) => index.index.to_string(),
                    };
                    (name, lower_pattern(&field.pat))
                })
                .collect(),
        },
        Pat::Or(or) => PPat::Or(or.cases.iter().map(lower_pattern).collect()),
        Pat::Slice(slice) => PPat::Slice(slice.elems.iter().map(lower_pattern).collect()),
        Pat::Range(range) => lower_range(range),
        _ => PPat::Unsupported,
    }
}

fn lower_range(range: &syn::PatRange) -> PPat {
    // Outer None means a present endpoint that is not a supported literal,
    // inner None means that side of the range is unbounded.
    let endpoint = |e: &Option<Box<Expr>>| match e {
        Some(e) => endpoint_lit(e).map(Some),
        None => Some(None),
    };
    let (Some(lo), Some(hi)) = (endpoint(&range.start), endpoint(&range.end)) else {
        return PPat::Unsupported;
    };
    PPat::Range {
        lo,
        hi,
        inclusive: matches!(range.limits, syn::RangeLimits::Closed(_)),
    }
}

/// A literal range endpoint, including a negated number, seen through parens.
fn endpoint_lit(e: &Expr) -> Option<PLit> {
    match e {
        Expr::Lit(l) => match &l.lit {
            Lit::Int(value) => value.base10_parse().ok().map(PLit::Int),
            Lit::Float(value) => value.base10_parse().ok().map(PLit::Float),
            Lit::Char(value) => Some(PLit::Char(value.value())),
            Lit::Byte(value) => Some(PLit::Int(i64::from(value.value()))),
            _ => None,
        },
        Expr::Unary(u) if matches!(u.op, syn::UnOp::Neg(_)) => match endpoint_lit(&u.expr) {
            Some(PLit::Int(n)) => Some(PLit::Int(-n)),
            Some(PLit::Float(f)) => Some(PLit::Float(-f)),
            _ => None,
        },
        Expr::Paren(p) => endpoint_lit(&p.expr),
        Expr::Group(g) => endpoint_lit(&g.expr),
        Expr::Path(p) if p.path.segments.len() == 2 => {
            let ty = p.path.segments[0].ident.to_string();
            let which = p.path.segments[1].ident.to_string();
            int_type_bound(&ty, &which).map(PLit::Int)
        }
        _ => None,
    }
}

/// The `MIN` or `MAX` associated const of an integer type, as the i64 the
/// interpreter stores every integer in. Bounds outside i64, the u64 and u128
/// maxima, clamp to i64's range, which acts as unbounded for stored values.
fn int_type_bound(ty: &str, which: &str) -> Option<i64> {
    let (lo, hi) = match ty {
        "i8" => (i64::from(i8::MIN), i64::from(i8::MAX)),
        "i16" => (i64::from(i16::MIN), i64::from(i16::MAX)),
        "i32" => (i64::from(i32::MIN), i64::from(i32::MAX)),
        "i64" | "isize" | "i128" => (i64::MIN, i64::MAX),
        "u8" => (0, i64::from(u8::MAX)),
        "u16" => (0, i64::from(u16::MAX)),
        "u32" => (0, i64::from(u32::MAX)),
        "u64" | "usize" | "u128" => (0, i64::MAX),
        _ => return None,
    };
    match which {
        "MIN" => Some(lo),
        "MAX" => Some(hi),
        _ => None,
    }
}

fn lower_literal(literal: &Lit) -> PPat {
    match literal {
        Lit::Int(value) => value
            .base10_parse()
            .map(|value| PPat::Lit(PLit::Int(value)))
            .unwrap_or(PPat::Unsupported),
        Lit::Float(value) => value
            .base10_parse()
            .map(|value| PPat::Lit(PLit::Float(value)))
            .unwrap_or(PPat::Unsupported),
        Lit::Bool(value) => PPat::Lit(PLit::Bool(value.value)),
        Lit::Str(value) => PPat::Lit(PLit::Str(value.value())),
        Lit::Char(value) => PPat::Lit(PLit::Char(value.value())),
        Lit::Byte(value) => PPat::Lit(PLit::Int(i64::from(value.value()))),
        _ => PPat::Unsupported,
    }
}

/// Whether a call path names tokio's `spawn`, either `tokio::spawn` or
/// `tokio::task::spawn`.
fn is_tokio_spawn(path: &syn::Path) -> bool {
    let segs: Vec<String> = path.segments.iter().map(|s| s.ident.to_string()).collect();
    segs.last().map(String::as_str) == Some("spawn") && segs.iter().any(|s| s == "tokio")
}

/// Whether a turbofish asks for a `String`, as in `collect::<String>()`.
fn names_string(tf: &syn::AngleBracketedGenericArguments) -> bool {
    tf.args.iter().any(|arg| {
        matches!(arg, syn::GenericArgument::Type(syn::Type::Path(p))
            if p.path.segments.last().is_some_and(|s| s.ident == "String"))
    })
}

/// The payload type of an expression that syntactically builds an `Option`,
/// for the cases where the source states it outright. Only a `Default` is ever
/// built from this, so a container answers with the kind of default it has
/// rather than with its element type.
///
/// This is not type inference. Every arm reads a type the program wrote down,
/// and anything else answers `None` so the caller keeps its old behavior.
fn option_payload(expr: &Expr, locals: &HashMap<String, ScalarTy>) -> Option<ScalarTy> {
    match expr {
        Expr::Paren(inner) => option_payload(&inner.expr, locals),
        Expr::Group(inner) => option_payload(&inner.expr, locals),
        Expr::Path(path) => {
            let segment = path.path.segments.last()?;
            // `None::<T>`, the payload is the turbofish.
            if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
                return turbofish_scalar(Some(args));
            }
            // A bare name the program declared as `let opt: Option<T>`.
            locals.get(&segment.ident.to_string()).cloned()
        }
        // `Some(x)`, the payload is whatever `x` is.
        Expr::Call(call) => {
            let Expr::Path(path) = &*call.func else {
                return None;
            };
            let last = path.path.segments.last()?;
            (last.ident == "Some")
                .then(|| call.args.first().and_then(|a| written_ty(a, locals)))
                .flatten()
        }
        Expr::MethodCall(call) => match call.method.to_string().as_str() {
            // `flag.then_some(x)` is an `Option` of whatever `x` is.
            "then_some" => call.args.first().and_then(|a| written_ty(a, locals)),
            // `a.or(b)` keeps the payload both sides share, so either side
            // that states it answers for both.
            "or" => call
                .args
                .first()
                .and_then(|a| option_payload(a, locals))
                .or_else(|| option_payload(&call.receiver, locals)),
            // These hand the same payload through untouched.
            "cloned" | "copied" | "take" | "as_ref" | "as_mut" => {
                option_payload(&call.receiver, locals)
            }
            // `x.unwrap_or_default()` peels one layer, so its own payload is
            // one layer further in than the receiver's.
            "unwrap_or_default" => option_payload(&call.receiver, locals)?.payload().cloned(),
            _ => None,
        },
        _ => None,
    }
}

/// The type an expression states about itself, for the same narrow purpose.
fn written_ty(expr: &Expr, locals: &HashMap<String, ScalarTy>) -> Option<ScalarTy> {
    match expr {
        Expr::Paren(inner) => written_ty(&inner.expr, locals),
        Expr::Group(inner) => written_ty(&inner.expr, locals),
        // `value as u8` names the type at the cast.
        Expr::Cast(cast) => ScalarTy::lower(&cast.ty),
        Expr::Lit(lit) => match &lit.lit {
            Lit::Str(_) => Some(ScalarTy::Str),
            Lit::Bool(_) => Some(ScalarTy::Bool),
            Lit::Char(_) => Some(ScalarTy::Char),
            Lit::Int(int) => {
                crate::interpreter::numeric::IntWidth::parse(int.suffix()).map(ScalarTy::Int)
            }
            Lit::Float(float) => match float.suffix() {
                "f32" => Some(ScalarTy::F32),
                "f64" => Some(ScalarTy::F64),
                _ => None,
            },
            _ => None,
        },
        // Anything that is itself an `Option` is one layer deeper, keeping
        // what it wraps so a further unwrap can still read it.
        Expr::Call(_) | Expr::Path(_) | Expr::MethodCall(_) => {
            if let Some(payload) = option_payload(expr, locals) {
                Some(ScalarTy::Opt(Box::new(payload)))
            } else if is_none_path(expr) {
                Some(ScalarTy::Opt(Box::new(ScalarTy::Other)))
            } else {
                None
            }
        }
        Expr::Macro(mac) if mac.mac.path.is_ident("vec") => {
            Some(ScalarTy::List(Box::new(ScalarTy::Other)))
        }
        _ => None,
    }
}

/// A bare `None`, with or without a turbofish.
fn is_none_path(expr: &Expr) -> bool {
    matches!(expr, Expr::Path(path)
        if path.path.segments.last().is_some_and(|s| s.ident == "None"))
}

/// The first concrete scalar named by a turbofish argument list.
fn turbofish_scalar(args: Option<&syn::AngleBracketedGenericArguments>) -> Option<ScalarTy> {
    args?
        .args
        .iter()
        .find_map(|arg| match arg {
            syn::GenericArgument::Type(ty) => Some(ty),
            _ => None,
        })
        .and_then(ScalarTy::lower)
}