run-rs 0.2.30

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
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
//! Expressions and control flow. Split from the compiler.

use anyhow::{Result, anyhow, bail};
use syn::spanned::Spanned;
use syn::{BinOp, Block, Expr, Lit, Pat, Stmt, UnOp};

use std::sync::Arc;

use crate::interpreter::bytecode::{BinKind, Const, DISCARD, Op, Reg, UnKind};
use crate::interpreter::numeric::{IntWidth, truncate};

use super::*;

/// Flatten a left-nested `&&` chain into its terms, in source order. A cond
/// that is not an `&&` is returned as a single term. Used to compile let-chains
/// in `if let A = x && cond && let B = y`.
fn flatten_and(cond: &Expr) -> Vec<&Expr> {
    fn walk<'a>(e: &'a Expr, out: &mut Vec<&'a Expr>) {
        if let Expr::Binary(b) = e
            && matches!(b.op, BinOp::And(_))
        {
            walk(&b.left, out);
            walk(&b.right, out);
        } else {
            out.push(e);
        }
    }
    let mut out = Vec::new();
    walk(cond, &mut out);
    out
}

/// The `from_str` call at the root of a `let` init chain, looking through
/// `?`, `unwrap`, and `expect`. Only a call without its own turbofish counts.
fn from_str_root(e: &Expr) -> Option<&syn::ExprCall> {
    from_str_chain(e, false)
}

/// Methods that rewrite only the error of a Result and hand the parsed value
/// through untouched, so the annotation still names what the parse must build.
fn maps_only_the_error(method: &syn::Ident) -> bool {
    method == "map_err" || method == "context" || method == "with_context"
}

/// `unwrapped` says whether a `?`, `unwrap` or `expect` sits above this point
/// in the chain. The error mapping methods are only followed under one, because
/// without it the annotation names a `Result` rather than the parsed payload,
/// and handing that to the planner would parse into the wrong shape.
fn from_str_chain(e: &Expr, unwrapped: bool) -> Option<&syn::ExprCall> {
    match e {
        Expr::Call(c) => {
            let Expr::Path(p) = &*c.func else { return None };
            let seg = p.path.segments.last()?;
            if seg.ident != "from_str" || first_generic_type(seg).is_some() {
                return None;
            }
            Some(c)
        }
        Expr::Try(t) => from_str_chain(&t.expr, true),
        Expr::Paren(p) => from_str_chain(&p.expr, unwrapped),
        Expr::Group(g) => from_str_chain(&g.expr, unwrapped),
        Expr::MethodCall(m) if m.method == "unwrap" || m.method == "expect" => {
            from_str_chain(&m.receiver, true)
        }
        Expr::MethodCall(m) if unwrapped && maps_only_the_error(&m.method) => {
            from_str_chain(&m.receiver, unwrapped)
        }
        _ => None,
    }
}

/// The `collect` call at the root of a `let` init chain. Only a call without
/// its own turbofish counts, a turbofish already names the target itself.
fn collect_root(e: &Expr) -> Option<&syn::ExprMethodCall> {
    match e {
        Expr::MethodCall(m) if m.method == "collect" && m.turbofish.is_none() => Some(m),
        Expr::Paren(p) => collect_root(&p.expr),
        Expr::Group(g) => collect_root(&g.expr),
        _ => None,
    }
}

/// Whether an annotated type is a plain `String`.
fn is_string_type(ty: &syn::Type) -> bool {
    matches!(ty, syn::Type::Path(p)
        if p.path.segments.last().is_some_and(|s| s.ident == "String"))
}

/// Whether a signature returns a plain `String`, so the return type names the
/// target of a `collect` whose value the function hands back.
pub(super) fn returns_string(output: &syn::ReturnType) -> bool {
    matches!(output, syn::ReturnType::Type(_, ty) if is_string_type(ty))
}

/// The payload a signature hands back, looking inside a `Result`. That is the
/// type a `from_str` in tail position has to parse into, the fourth place the
/// target is knowable after a turbofish, an annotated `let`, and a `-> String`.
pub(super) fn returned_json_type(output: &syn::ReturnType) -> Option<&syn::Type> {
    let syn::ReturnType::Type(_, ty) = output else {
        return None;
    };
    Some(result_ok_type(ty).unwrap_or(ty))
}

/// The `T` of a `Result<T, E>` annotation.
fn result_ok_type(ty: &syn::Type) -> Option<&syn::Type> {
    let syn::Type::Path(p) = ty else { return None };
    let seg = p.path.segments.last()?;
    if seg.ident != "Result" {
        return None;
    }
    first_generic_type(seg)
}

/// Expressions in tail position, so the value the expression produces is the
/// value of one of them. Walks only the shapes whose own value is a
/// sub-expression's value: parens, a block's trailing expression, both branches
/// of an `if`, and every arm of a `match`.
fn tail_exprs<'a>(e: &'a Expr, out: &mut Vec<&'a Expr>) {
    match e {
        Expr::Paren(p) => tail_exprs(&p.expr, out),
        Expr::Group(g) => tail_exprs(&g.expr, out),
        Expr::Block(b) => tail_block_exprs(&b.block, out),
        Expr::If(i) => {
            tail_block_exprs(&i.then_branch, out);
            if let Some((_, alt)) = &i.else_branch {
                tail_exprs(alt, out);
            }
        }
        Expr::Match(m) => {
            for arm in &m.arms {
                tail_exprs(&arm.body, out);
            }
        }
        other => out.push(other),
    }
}

/// The trailing expression of a block, which is the block's own value.
fn tail_block_exprs<'a>(block: &'a Block, out: &mut Vec<&'a Expr>) {
    if let Some(Stmt::Expr(e, None)) = block.stmts.last() {
        tail_exprs(e, out);
    }
}

/// Every expression whose value this function body hands back, from its
/// trailing expression and from a `return`. A closure body is skipped, because
/// its `return` leaves the closure rather than this function, so the function's
/// return type says nothing about it.
fn returned_exprs(block: &Block) -> Vec<&Expr> {
    let mut found = Vec::new();
    tail_block_exprs(block, &mut found);
    walk_returns(block, &mut found);
    found
}

/// Every bare `collect` whose value this function body hands back.
pub(super) fn returned_collects(block: &Block) -> Vec<*const syn::ExprMethodCall> {
    returned_exprs(block)
        .into_iter()
        .filter_map(|e| match e {
            Expr::MethodCall(m) if m.method == "collect" && m.turbofish.is_none() => {
                Some(std::ptr::from_ref(m))
            }
            _ => None,
        })
        .collect()
}

/// Every `from_str` whose parsed value this function body hands back. The
/// chain is walked as already unwrapped, because the signature's payload type
/// is read from inside its `Result`, so a plain `.map_err(..)` tail names the
/// parse target just as much as a `?` does.
pub(super) fn returned_from_strs(block: &Block) -> Vec<*const syn::ExprCall> {
    returned_exprs(block)
        .into_iter()
        .filter_map(|e| from_str_chain(e, true).map(std::ptr::from_ref))
        .collect()
}

/// Statement level `return`s, following the constructs that carry a block.
fn walk_returns<'a>(block: &'a Block, out: &mut Vec<&'a Expr>) {
    for stmt in &block.stmts {
        match stmt {
            Stmt::Expr(e, _) => walk_returns_expr(e, out),
            // The only expression a `let` carries that is not part of its value
            // is the `else` block of a let-else, which commonly returns.
            Stmt::Local(local) => {
                if let Some(init) = &local.init
                    && let Some(diverge) = &init.diverge
                {
                    walk_returns_expr(&diverge.1, out);
                }
            }
            _ => {}
        }
    }
}

fn walk_returns_expr<'a>(e: &'a Expr, out: &mut Vec<&'a Expr>) {
    match e {
        Expr::Return(r) => {
            if let Some(value) = &r.expr {
                tail_exprs(value, out);
            }
        }
        Expr::Block(b) => walk_returns(&b.block, out),
        Expr::Unsafe(u) => walk_returns(&u.block, out),
        Expr::If(i) => {
            walk_returns(&i.then_branch, out);
            if let Some((_, alt)) = &i.else_branch {
                walk_returns_expr(alt, out);
            }
        }
        Expr::Match(m) => {
            for arm in &m.arms {
                walk_returns_expr(&arm.body, out);
            }
        }
        Expr::ForLoop(f) => walk_returns(&f.body, out),
        Expr::While(w) => walk_returns(&w.body, out),
        Expr::Loop(l) => walk_returns(&l.body, out),
        _ => {}
    }
}

impl Compiler<'_> {
    pub(super) fn compile_block(&mut self, block: &Block, dst: Reg) -> Result<()> {
        self.push_scope();
        let res = self.compile_block_inner(block, dst);
        self.pop_scope();
        res
    }

    pub(super) fn compile_block_inner(&mut self, block: &Block, dst: Reg) -> Result<()> {
        if block.stmts.is_empty() {
            self.emit(Op::LoadUnit { dst });
            return Ok(());
        }
        // Block-level consts and statics bind up front, so a use earlier in
        // the block still resolves, the way item hoisting works in real Rust.
        // Their init expressions are const-evaluable, so evaluation order
        // against the other statements is unobservable.
        for stmt in &block.stmts {
            let Stmt::Item(item) = stmt else { continue };
            match item {
                syn::Item::Const(c) => {
                    self.set_line(c.span());
                    let val = self.alloc();
                    self.compile_into(val, &c.expr)?;
                    self.define(&c.ident.to_string(), val);
                }
                syn::Item::Static(s) => {
                    if matches!(s.mutability, syn::StaticMutability::Mut(_)) {
                        bail!("unsupported feature: `static mut`");
                    }
                    self.set_line(s.span());
                    let val = self.alloc();
                    self.compile_into(val, &s.expr)?;
                    self.define(&s.ident.to_string(), val);
                }
                _ => {}
            }
        }
        let last = block.stmts.len() - 1;
        for (i, stmt) in block.stmts.iter().enumerate() {
            let is_last = i == last;
            self.set_line(stmt.span());
            match stmt {
                Stmt::Local(local)
                    if local
                        .init
                        .as_ref()
                        .and_then(|i| i.diverge.as_ref())
                        .is_some() =>
                {
                    // `let PAT = EXPR else { .. }`. Test the refutable pattern,
                    // and run the diverging else block when it does not match.
                    // Bindings land in the current scope, visible afterwards.
                    let init = local.init.as_ref().unwrap();
                    let else_expr = &init.diverge.as_ref().unwrap().1;
                    let val = self.alloc();
                    self.compile_into(val, &init.expr)?;
                    let matched = self.alloc();
                    let pidx = self.pattern_info(&local.pat)?;
                    self.emit(Op::TestBind {
                        val,
                        pat: pidx,
                        dst: matched,
                    });
                    let jmp_ok = self.here();
                    self.emit(Op::JumpIfTrue {
                        cond: matched,
                        to: 0,
                    });
                    let else_dst = self.alloc();
                    self.compile_into(else_dst, else_expr)?;
                    let ok_at = self.here() as u32;
                    self.patch_jump(jmp_ok, ok_at);
                    if is_last {
                        self.emit(Op::LoadUnit { dst });
                    }
                }
                Stmt::Local(local) => {
                    let val = self.alloc();
                    // An annotated `let` whose init chain roots in a
                    // `from_str` call hands its type to that call, so the
                    // parse is typed at the source and no coerce op is
                    // needed afterwards.
                    let mut offered = false;
                    // A let nested in the init chain, say in a closure body,
                    // runs this code again before the outer collect consumes
                    // its hint, so the outer hint is restored, not cleared.
                    let outer_string_let = self.string_let.take();
                    if let Pat::Type(t) = &local.pat
                        && let Some(init) = &local.init
                    {
                        if let Some(call) = from_str_root(&init.expr) {
                            self.json_let = Some((call as *const _, self.lower_ir(&t.ty)));
                            offered = true;
                        } else if is_string_type(&t.ty)
                            && let Some(mc) = collect_root(&init.expr)
                        {
                            self.string_let = Some(mc as *const _);
                        }
                        // `let x: T = ...unwrap_or_default()` is the only place
                        // that names the payload the default is built from,
                        // since the method takes no turbofish of its own.
                        if let Expr::MethodCall(mc) = &*init.expr
                            && mc.method == "unwrap_or_default"
                            && let Some(ty) = ScalarTy::lower(&t.ty)
                        {
                            self.default_let = Some((std::ptr::from_ref(mc), ty));
                        }
                    }
                    // `let opt: Option<T> = ..` and `let v: Vec<T> = ..`
                    // record the declared type, so a later
                    // `opt.unwrap_or_default()` or `v.get(i).cloned()
                    // .unwrap_or_default()` builds the right default from it.
                    if let Pat::Type(t) = &local.pat
                        && let Pat::Ident(ident) = &*t.pat
                        && let Some(declared) = annotation_scalar(&t.ty)
                    {
                        self.typed_locals.insert(ident.ident.to_string(), declared);
                    }
                    // A numeric annotation types a bare literal init at
                    // compile time, so the value never exists at the wrong
                    // width.
                    let mut typed_literal = false;
                    if let Pat::Type(t) = &local.pat
                        && let Some(init) = &local.init
                        && let Some(target) = numeric_annotation(&t.ty)
                    {
                        typed_literal = self.compile_numeric_annotated(val, &init.expr, target)?;
                    }
                    if !typed_literal {
                        match &local.init {
                            Some(init) => self.compile_into(val, &init.expr)?,
                            None => self.emit(Op::LoadUnit { dst: val }),
                        }
                    }
                    let consumed = offered && self.json_let.is_none();
                    self.json_let = None;
                    self.string_let = outer_string_let;
                    // A type annotation coerces a dynamic value into that type.
                    if let Pat::Type(t) = &local.pat {
                        if !consumed && !typed_literal {
                            self.emit_annotation(val, &t.ty);
                        }
                        self.bind_pattern_irrefutable(&t.pat, val)?;
                    } else {
                        self.bind_pattern_irrefutable(&local.pat, val)?;
                    }
                    if is_last {
                        self.emit(Op::LoadUnit { dst });
                    }
                }
                Stmt::Expr(expr, semi) => {
                    if is_last && semi.is_none() {
                        self.compile_into(dst, expr)?;
                    } else {
                        // A statement position method call discards its result,
                        // so the VM can skip building it.
                        if let Expr::MethodCall(m) = expr {
                            self.compile_method(DISCARD, m)?;
                        } else {
                            let tmp = self.alloc();
                            self.compile_into(tmp, expr)?;
                        }
                        if is_last {
                            self.emit(Op::LoadUnit { dst });
                        }
                    }
                }
                Stmt::Item(item) => {
                    if let syn::Item::Fn(_) = item {
                        bail!("unsupported feature: nested functions");
                    }
                    if is_last {
                        self.emit(Op::LoadUnit { dst });
                    }
                }
                Stmt::Macro(m) => {
                    let target = if is_last { dst } else { self.alloc() };
                    self.compile_macro(&m.mac, target)?;
                    if is_last && !macro_yields_value(&m.mac) {
                        self.emit(Op::LoadUnit { dst });
                    }
                }
            }
        }
        Ok(())
    }

    /// Apply a `let` annotation to an already-computed init value. A numeric
    /// primitive retags through a cast, which only ever acts on a bare
    /// literal's value, an init typed by the real checker already has the
    /// annotated type. Everything else goes through the struct coercion.
    fn emit_annotation(&mut self, reg: Reg, ty: &syn::Type) {
        if numeric_annotation(ty).is_some() {
            let idx = self.add_cast(ty);
            self.emit(Op::Cast {
                dst: reg,
                src: reg,
                ty: idx,
            });
            return;
        }
        self.emit_coerce(reg, ty);
    }

    /// Emit a coercion of `reg` into the annotated type when it names a struct,
    /// `Vec<T>`, or `Option<T>`. A type coercion can never change, `f64` or
    /// `HashMap<K, V>`, emits nothing, so annotated lets in hot loops carry no
    /// runtime work at all.
    pub(super) fn emit_coerce(&mut self, reg: Reg, ty: &syn::Type) {
        let ir = self.lower_ir(ty);
        if !ir.is_active() {
            return;
        }
        let idx = self.add_coerce(ir);
        self.emit(Op::Coerce {
            dst: reg,
            src: reg,
            ty: idx,
        });
    }

    // -- expressions -------------------------------------------------------

    /// Compile `expr`, returning the register holding its value. A plain local
    /// returns its own register with no copy.
    pub(super) fn compile_expr(&mut self, expr: &Expr) -> Result<Reg> {
        if let Expr::Path(p) = expr
            && p.path.segments.len() == 1
            && p.qself.is_none()
        {
            let name = p.path.segments[0].ident.to_string();
            if let NameLoc::Local(reg) = self.resolve(&name) {
                return Ok(reg);
            }
        }
        let dst = self.alloc();
        self.compile_into(dst, expr)?;
        Ok(dst)
    }

    pub(super) fn compile_into(&mut self, dst: Reg, expr: &Expr) -> Result<()> {
        self.set_line(expr.span());
        match expr {
            Expr::Lit(lit) => self.compile_lit(dst, &lit.lit)?,
            Expr::Paren(p) => self.compile_into(dst, &p.expr)?,
            Expr::Group(g) => self.compile_into(dst, &g.expr)?,
            Expr::Reference(r) => self.compile_into(dst, &r.expr)?,
            Expr::Unsafe(u) => self.compile_block(&u.block, dst)?,
            Expr::Block(b) => self.compile_block(&b.block, dst)?,
            Expr::Path(p) => self.compile_path(dst, &p.path)?,
            Expr::Unary(u) => self.compile_unary(dst, u)?,
            Expr::Binary(b) => self.compile_binary(dst, b)?,
            Expr::Assign(a) => {
                self.compile_assign(&a.left, &a.right)?;
                self.emit(Op::LoadUnit { dst });
            }
            Expr::If(if_expr) => self.compile_if(dst, if_expr)?,
            Expr::While(w) => self.compile_while(dst, w)?,
            Expr::ForLoop(f) => self.compile_for(dst, f)?,
            Expr::Loop(l) => self.compile_loop(dst, l)?,
            Expr::Match(m) => self.compile_match(dst, m)?,
            Expr::Return(r) => {
                let src = match &r.expr {
                    Some(e) => self.compile_expr(e)?,
                    None => {
                        let u = self.alloc();
                        self.emit(Op::LoadUnit { dst: u });
                        u
                    }
                };
                self.emit(Op::Ret { src });
            }
            Expr::Break(b) => self.compile_break(b)?,
            Expr::Continue(_) => self.compile_continue()?,
            Expr::Call(c) => self.compile_call(dst, c)?,
            Expr::MethodCall(m) => self.compile_method(dst, m)?,
            Expr::Macro(m) => self.compile_macro(&m.mac, dst)?,
            Expr::Tuple(t) => {
                let base = self.compile_args(t.elems.iter())?;
                self.emit(Op::MakeTuple {
                    dst,
                    base,
                    count: t.elems.len() as u16,
                });
            }
            Expr::Array(a) => {
                let base = self.compile_args(a.elems.iter())?;
                self.emit(Op::MakeVec {
                    dst,
                    base,
                    count: a.elems.len() as u16,
                });
            }
            Expr::Repeat(r) => {
                let val = self.compile_expr(&r.expr)?;
                let count = self.compile_expr(&r.len)?;
                self.emit(Op::MakeArrayRepeat { dst, val, count });
            }
            Expr::Index(idx) => {
                let base = self.compile_expr(&idx.expr)?;
                let key = self.compile_expr(&idx.index)?;
                self.emit(Op::Index { dst, base, key });
            }
            Expr::Field(f) => {
                let base = self.compile_expr(&f.base)?;
                let member = self.member_of(&f.member);
                self.emit(Op::GetField { dst, base, member });
            }
            Expr::Struct(s) => self.compile_struct_literal(dst, s)?,
            Expr::Range(r) => self.compile_range(dst, r)?,
            Expr::Try(t) => {
                let src = self.compile_expr(&t.expr)?;
                self.emit(Op::Try { dst, src });
            }
            Expr::Cast(c) => {
                let src = self.compile_expr(&c.expr)?;
                let ty = self.add_cast(&c.ty);
                self.emit(Op::Cast { dst, src, ty });
            }
            Expr::Closure(c) => self.compile_closure(dst, c)?,
            Expr::Await(a) => {
                if !self.ctx.async_mode {
                    bail!("`.await` is only available under #[tokio::main]");
                }
                let src = self.compile_expr(&a.base)?;
                self.emit(Op::Await { dst, src });
            }
            Expr::Async(_) => {
                bail!("an async block is only supported directly inside tokio::spawn")
            }
            other => bail!("unsupported expression: {}", expr_kind(other)),
        }
        Ok(())
    }

    pub(super) fn compile_lit(&mut self, dst: Reg, lit: &Lit) -> Result<()> {
        match lit {
            Lit::Int(i) => self.compile_int_lit(dst, i, false, None)?,
            Lit::Bool(b) => self.emit(Op::LoadBool { dst, v: b.value }),
            Lit::Float(f) => self.compile_float_lit(dst, f, false, None)?,
            Lit::Str(s) => {
                let k = self.add_const(Const::Str(Arc::from(s.value().as_str())));
                self.emit(Op::LoadConst { dst, k });
            }
            Lit::Char(c) => {
                let k = self.add_const(Const::Char(c.value()));
                self.emit(Op::LoadConst { dst, k });
            }
            Lit::Byte(b) => self.emit(Op::LoadInt {
                dst,
                v: b.value() as i64,
            }),
            Lit::ByteStr(bs) => {
                let k = self.add_const(Const::Bytes(Arc::from(bs.value().as_slice())));
                self.emit(Op::LoadConst { dst, k });
            }
            other => bail!("unsupported literal: {other:?}"),
        }
        Ok(())
    }

    /// An integer literal with its real width: from its suffix first, else
    /// from an annotation the caller saw, else untyped. Parses through u128
    /// so a bare literal past i64::MAX, which real Rust types as u64 or
    /// usize, still loads with its full value. The sign of an enclosing
    /// negation comes in as `negated` so `-128i8` and `-9223372036854775808`
    /// type before they could overflow.
    fn compile_int_lit(
        &mut self,
        dst: Reg,
        lit: &syn::LitInt,
        negated: bool,
        annotation: Option<IntWidth>,
    ) -> Result<()> {
        let raw: u128 = lit.base10_parse()?;
        if raw > u128::from(u64::MAX) {
            bail!("integer literal does not fit any supported width");
        }
        let mut value = raw as i128;
        if negated {
            value = -value;
        }
        let width = match lit.suffix() {
            "" | "u128" | "i128" => annotation,
            suffix => Some(
                IntWidth::parse(suffix)
                    .ok_or_else(|| anyhow!("unsupported literal suffix `{suffix}`"))?,
            ),
        };
        let width = width.unwrap_or({
            // Untyped and past i64::MAX can only be u64 or usize in a valid
            // program, and those two share one runtime semantic.
            if value > i128::from(i64::MAX) {
                IntWidth::U64
            } else {
                IntWidth::I64
            }
        });
        match width {
            IntWidth::I64 => self.emit(Op::LoadInt {
                dst,
                v: value as i64,
            }),
            w => self.emit(Op::LoadIntW {
                dst,
                v: w.encode(truncate(value, w)),
                w,
            }),
        }
        Ok(())
    }

    /// A float literal at its real width. An f32 parses from its own digits,
    /// never through f64 rounding.
    fn compile_float_lit(
        &mut self,
        dst: Reg,
        lit: &syn::LitFloat,
        negated: bool,
        annotation: Option<FloatTy>,
    ) -> Result<()> {
        let is_f32 = match lit.suffix() {
            "f32" => true,
            "f64" => false,
            _ => annotation == Some(FloatTy::F32),
        };
        let k = if is_f32 {
            let mut v: f32 = lit.base10_parse()?;
            if negated {
                v = -v;
            }
            self.add_const(Const::F32(v))
        } else {
            let mut v: f64 = lit.base10_parse()?;
            if negated {
                v = -v;
            }
            self.add_const(Const::Float(v))
        };
        self.emit(Op::LoadConst { dst, k });
        Ok(())
    }

    /// Compile an annotated numeric init directly at the annotated type when
    /// it is a plain literal, possibly negated or parenthesized. False means
    /// the init needs a runtime cast after normal compilation.
    fn compile_numeric_annotated(
        &mut self,
        dst: Reg,
        expr: &Expr,
        target: NumericTy,
    ) -> Result<bool> {
        match expr {
            Expr::Paren(p) => self.compile_numeric_annotated(dst, &p.expr, target),
            Expr::Group(g) => self.compile_numeric_annotated(dst, &g.expr, target),
            Expr::Unary(u) if matches!(u.op, UnOp::Neg(_)) => {
                self.compile_numeric_lit(dst, &u.expr, true, target)
            }
            other => self.compile_numeric_lit(dst, other, false, target),
        }
    }

    fn compile_numeric_lit(
        &mut self,
        dst: Reg,
        expr: &Expr,
        negated: bool,
        target: NumericTy,
    ) -> Result<bool> {
        let Expr::Lit(l) = expr else {
            return Ok(false);
        };
        match (&l.lit, target) {
            (Lit::Int(i), NumericTy::Int(width)) => {
                self.compile_int_lit(dst, i, negated, Some(width))?;
                Ok(true)
            }
            (Lit::Float(f), NumericTy::Float(ty)) => {
                self.compile_float_lit(dst, f, negated, Some(ty))?;
                Ok(true)
            }
            _ => Ok(false),
        }
    }

    pub(super) fn compile_path(&mut self, dst: Reg, path: &syn::Path) -> Result<()> {
        if path.segments.len() == 1 {
            let name = path.segments[0].ident.to_string();
            return self.load_name(&name, dst);
        }
        // A multi segment path used as a value, resolved against the module.
        let segs: Vec<String> = path.segments.iter().map(|s| s.ident.to_string()).collect();
        self.compile_resolved_value(dst, &segs)
    }

    pub(super) fn compile_unary(&mut self, dst: Reg, u: &syn::ExprUnary) -> Result<()> {
        if matches!(u.op, UnOp::Deref(_)) {
            let src = self.compile_expr(&u.expr)?;
            self.emit(Op::Deref { dst, src });
            return Ok(());
        }
        // A negated literal types as one token, so `-128i8` and the i64
        // minimum load directly instead of negating an unrepresentable
        // positive value.
        if matches!(u.op, UnOp::Neg(_))
            && let Expr::Lit(l) = &*u.expr
        {
            match &l.lit {
                Lit::Int(i) => return self.compile_int_lit(dst, i, true, None),
                Lit::Float(f) => return self.compile_float_lit(dst, f, true, None),
                _ => {}
            }
        }
        let a = self.compile_expr(&u.expr)?;
        let op = match u.op {
            UnOp::Neg(_) => UnKind::Neg,
            UnOp::Not(_) => UnKind::Not,
            _ => bail!("unsupported unary operator"),
        };
        self.emit(Op::Un { dst, a, op });
        Ok(())
    }

    pub(super) fn compile_binary(&mut self, dst: Reg, b: &syn::ExprBinary) -> Result<()> {
        // Compound assignment, `a += b`, mutates in place and yields unit.
        if is_assign_op(&b.op) {
            let op = bin_kind(&b.op).ok_or_else(|| anyhow!("unsupported operator {:?}", b.op))?;
            self.compile_compound_assign(&b.left, op, &b.right)?;
            self.emit(Op::LoadUnit { dst });
            return Ok(());
        }
        // Short circuiting logical operators.
        match b.op {
            BinOp::And(_) => {
                self.compile_into(dst, &b.left)?;
                let jmp = self.here();
                self.emit(Op::JumpIfFalse { cond: dst, to: 0 });
                self.compile_into(dst, &b.right)?;
                let end = self.here() as u32;
                self.patch_jump(jmp, end);
                return Ok(());
            }
            BinOp::Or(_) => {
                self.compile_into(dst, &b.left)?;
                let jmp = self.here();
                self.emit(Op::JumpIfTrue { cond: dst, to: 0 });
                self.compile_into(dst, &b.right)?;
                let end = self.here() as u32;
                self.patch_jump(jmp, end);
                return Ok(());
            }
            _ => {}
        }
        let op = bin_kind(&b.op).ok_or_else(|| anyhow!("unsupported operator {:?}", b.op))?;
        let a = self.compile_expr(&b.left)?;
        // A literal immediate is width-safe: when the left side carries a
        // width the general path adopts it, exactly like a bare literal.
        if let Some(imm) = int_literal(&b.right) {
            self.emit(Op::BinImm { dst, a, imm, op });
            return Ok(());
        }
        let c = self.compile_expr(&b.right)?;
        self.emit(Op::Bin { dst, a, b: c, op });
        Ok(())
    }

    // -- statements ----------------------------------------------------------

    /// Compile a branch condition and emit the jump taken when it is false,
    /// returning the jump's index for patching. A plain comparison becomes a
    /// fused compare-and-branch instead of a Bin plus JumpIfFalse pair.
    pub(super) fn emit_cond_jump(&mut self, cond: &Expr) -> Result<usize> {
        if let Expr::Binary(b) = cond
            && let Some(op) = bin_kind(&b.op)
            && !is_assign_op(&b.op)
            && matches!(
                op,
                BinKind::Eq | BinKind::Ne | BinKind::Lt | BinKind::Le | BinKind::Gt | BinKind::Ge
            )
        {
            let a = self.compile_expr(&b.left)?;
            if let Some(imm) = int_literal(&b.right) {
                let at = self.here();
                self.emit(Op::CmpJumpImm { a, imm, op, to: 0 });
                return Ok(at);
            }
            let c = self.compile_expr(&b.right)?;
            let at = self.here();
            self.emit(Op::CmpJump { a, b: c, op, to: 0 });
            return Ok(at);
        }
        let c = self.compile_expr(cond)?;
        let at = self.here();
        self.emit(Op::JumpIfFalse { cond: c, to: 0 });
        Ok(at)
    }

    /// An open end becomes an i64::MAX sentinel that every range consumer,
    /// the slicing op and `str::get`, reads as "to the end". One shape for
    /// every position, so `s.get(3..)` works the same as `s[3..]`.
    pub(super) fn compile_range(&mut self, dst: Reg, r: &syn::ExprRange) -> Result<()> {
        let start = match &r.start {
            Some(e) => self.compile_expr(e)?,
            None => {
                let z = self.alloc();
                self.emit(Op::LoadInt { dst: z, v: 0 });
                z
            }
        };
        let end = match &r.end {
            Some(e) => self.compile_expr(e)?,
            None => {
                let z = self.alloc();
                self.emit(Op::LoadInt {
                    dst: z,
                    v: i64::MAX,
                });
                z
            }
        };
        let inclusive = matches!(r.limits, syn::RangeLimits::Closed(_));
        self.emit(Op::MakeRange {
            dst,
            start,
            end,
            inclusive,
        });
        Ok(())
    }

    // -- control flow ------------------------------------------------------

    pub(super) fn compile_if(&mut self, dst: Reg, if_expr: &syn::ExprIf) -> Result<()> {
        // `if let PAT = EXPR { .. }` and let-chains like
        // `if let Some(x) = a && x > 0 && let Ok(y) = b { .. }`. The chain is a
        // left-nested `&&` whose terms may each be a `let` binding or a plain
        // condition. All terms must pass, and earlier bindings are in scope for
        // later terms and the body.
        let terms = flatten_and(&if_expr.cond);
        if terms.iter().any(|t| matches!(t, Expr::Let(_))) {
            self.push_scope();
            let mut else_jumps = Vec::new();
            for term in &terms {
                if let Expr::Let(let_expr) = term {
                    let scrut = self.compile_expr(&let_expr.expr)?;
                    let matched = self.alloc();
                    let pat = self.pattern_info(&let_expr.pat)?;
                    self.emit(Op::TestBind {
                        val: scrut,
                        pat,
                        dst: matched,
                    });
                    else_jumps.push(self.here());
                    self.emit(Op::JumpIfFalse {
                        cond: matched,
                        to: 0,
                    });
                } else {
                    let cond = self.compile_expr(term)?;
                    else_jumps.push(self.here());
                    self.emit(Op::JumpIfFalse { cond, to: 0 });
                }
            }
            self.compile_block_inner(&if_expr.then_branch, dst)?;
            self.pop_scope();
            let jmp_end = self.here();
            self.emit(Op::Jump { to: 0 });
            let else_at = self.here() as u32;
            for j in else_jumps {
                self.patch_jump(j, else_at);
            }
            match &if_expr.else_branch {
                Some((_, e)) => self.compile_into(dst, e)?,
                None => self.emit(Op::LoadUnit { dst }),
            }
            let end = self.here() as u32;
            self.patch_jump(jmp_end, end);
            return Ok(());
        }
        let jmp_else = self.emit_cond_jump(&if_expr.cond)?;
        self.compile_block(&if_expr.then_branch, dst)?;
        let jmp_end = self.here();
        self.emit(Op::Jump { to: 0 });
        let else_at = self.here() as u32;
        self.patch_jump(jmp_else, else_at);
        match &if_expr.else_branch {
            Some((_, e)) => self.compile_into(dst, e)?,
            None => self.emit(Op::LoadUnit { dst }),
        }
        let end = self.here() as u32;
        self.patch_jump(jmp_end, end);
        Ok(())
    }

    pub(super) fn compile_while(&mut self, dst: Reg, w: &syn::ExprWhile) -> Result<()> {
        let head = self.here();
        // `while let PAT = EXPR` support.
        if let Expr::Let(let_expr) = &*w.cond {
            let scrut = self.compile_expr(&let_expr.expr)?;
            self.push_scope();
            let matched = self.alloc();
            let pat = self.pattern_info(&let_expr.pat)?;
            self.emit(Op::TestBind {
                val: scrut,
                pat,
                dst: matched,
            });
            let exit = self.here();
            self.emit(Op::JumpIfFalse {
                cond: matched,
                to: 0,
            });
            self.loops.push(LoopCtx {
                breaks: vec![exit],
                continue_to: head,
                result: dst,
            });
            let body = self.alloc();
            self.compile_block_inner(&w.body, body)?;
            self.pop_scope();
            self.emit(Op::Jump { to: head as u32 });
            let end = self.here() as u32;
            let lc = self.loops.pop().unwrap();
            for b in lc.breaks {
                self.patch_jump(b, end);
            }
            self.emit(Op::LoadUnit { dst });
            return Ok(());
        }
        let exit = self.emit_cond_jump(&w.cond)?;
        self.loops.push(LoopCtx {
            breaks: vec![exit],
            continue_to: head,
            result: dst,
        });
        let body = self.alloc();
        self.compile_block(&w.body, body)?;
        self.emit(Op::Jump { to: head as u32 });
        let end = self.here() as u32;
        let lc = self.loops.pop().unwrap();
        for b in lc.breaks {
            self.patch_jump(b, end);
        }
        self.emit(Op::LoadUnit { dst });
        Ok(())
    }

    pub(super) fn compile_loop(&mut self, dst: Reg, l: &syn::ExprLoop) -> Result<()> {
        self.emit(Op::LoadUnit { dst });
        let head = self.here();
        self.loops.push(LoopCtx {
            breaks: Vec::new(),
            continue_to: head,
            result: dst,
        });
        let body = self.alloc();
        self.compile_block(&l.body, body)?;
        self.emit(Op::Jump { to: head as u32 });
        let end = self.here() as u32;
        let lc = self.loops.pop().unwrap();
        for b in lc.breaks {
            self.patch_jump(b, end);
        }
        Ok(())
    }

    pub(super) fn compile_for(&mut self, dst: Reg, f: &syn::ExprForLoop) -> Result<()> {
        let src = self.compile_expr(&f.expr)?;
        let iter = self.alloc();
        self.emit(Op::IterInit { dst: iter, src });
        let idx = self.alloc();
        self.emit(Op::LoadInt { dst: idx, v: 0 });
        let val = self.alloc();
        let head = self.here();
        let next = self.here();
        self.emit(Op::ForNext {
            iter,
            idx,
            val,
            to: 0,
        });
        self.push_scope();
        self.bind_pattern_irrefutable(&f.pat, val)?;
        self.loops.push(LoopCtx {
            breaks: vec![next],
            continue_to: head,
            result: dst,
        });
        let body = self.alloc();
        self.compile_block_inner(&f.body, body)?;
        self.pop_scope();
        self.emit(Op::Jump { to: head as u32 });
        let end = self.here() as u32;
        let lc = self.loops.pop().unwrap();
        for b in lc.breaks {
            self.patch_jump(b, end);
        }
        self.emit(Op::LoadUnit { dst });
        Ok(())
    }

    pub(super) fn compile_break(&mut self, b: &syn::ExprBreak) -> Result<()> {
        let result = self.loops.last().map(|l| l.result);
        if let Some(result) = result {
            if let Some(e) = &b.expr {
                self.compile_into(result, e)?;
            }
        } else {
            bail!("break outside a loop");
        }
        let jmp = self.here();
        self.emit(Op::Jump { to: 0 });
        self.loops.last_mut().unwrap().breaks.push(jmp);
        Ok(())
    }

    pub(super) fn compile_continue(&mut self) -> Result<()> {
        let to = self
            .loops
            .last()
            .map(|l| l.continue_to)
            .ok_or_else(|| anyhow!("continue outside a loop"))?;
        self.emit(Op::Jump { to: to as u32 });
        Ok(())
    }

    pub(super) fn compile_match(&mut self, dst: Reg, m: &syn::ExprMatch) -> Result<()> {
        let scrut = self.compile_expr(&m.expr)?;
        let mut end_jumps = Vec::new();
        for arm in &m.arms {
            self.push_scope();
            let matched = self.alloc();
            let pat = self.pattern_info(&arm.pat)?;
            self.emit(Op::TestBind {
                val: scrut,
                pat,
                dst: matched,
            });
            let skip = self.here();
            self.emit(Op::JumpIfFalse {
                cond: matched,
                to: 0,
            });
            // Guard.
            let mut guard_skip = None;
            if let Some((_, guard)) = &arm.guard {
                let g = self.compile_expr(guard)?;
                let gs = self.here();
                self.emit(Op::JumpIfFalse { cond: g, to: 0 });
                guard_skip = Some(gs);
            }
            self.compile_into(dst, &arm.body)?;
            let je = self.here();
            self.emit(Op::Jump { to: 0 });
            end_jumps.push(je);
            self.pop_scope();
            let next = self.here() as u32;
            self.patch_jump(skip, next);
            if let Some(gs) = guard_skip {
                self.patch_jump(gs, next);
            }
        }
        // No arm matched, a runtime error mirroring the old behavior.
        let p = self.add_path(vec!["::unreachable_match".to_string()], None);
        self.emit(Op::CallPath {
            dst,
            path: p,
            base: dst,
            argc: 0,
        });
        let end = self.here() as u32;
        for j in end_jumps {
            self.patch_jump(j, end);
        }
        Ok(())
    }

    // -- calls -------------------------------------------------------------
}

/// The payload of an `Option<T>` or `Result<T, _>` annotation, for building a
/// `Default` when the value turns out to be absent.
pub(super) fn annotation_scalar(ty: &syn::Type) -> Option<ScalarTy> {
    let syn::Type::Path(path) = ty else {
        return None;
    };
    let segment = path.path.segments.last()?;
    let container = segment.ident.to_string();
    if !matches!(container.as_str(), "Option" | "Result" | "Vec" | "VecDeque") {
        return None;
    }
    let syn::PathArguments::AngleBracketed(args) = &segment.arguments else {
        return None;
    };
    let inner = args.args.iter().find_map(|arg| match arg {
        syn::GenericArgument::Type(inner) => ScalarTy::lower(inner),
        _ => None,
    })?;
    // A `Result<T, E>` answers its defaults through the same `Opt` shape,
    // since only the payload side ever builds one.
    Some(match container.as_str() {
        "Option" | "Result" => ScalarTy::Opt(Box::new(inner)),
        _ => ScalarTy::List(Box::new(inner)),
    })
}