aver-lang 0.18.0

VM and transpiler for Aver, a statically-typed language designed for AI-assisted development
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
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
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
use super::builtins;
use super::emit_ctx::{EmitCtx, expr_can_move, expr_skip_clone, should_borrow_param};
use super::pattern::emit_pattern;
use crate::ast::*;
use crate::codegen::CodegenContext;
use crate::codegen::common::{
    expr_to_dotted_name, is_user_type, module_prefix_to_rust_path, resolve_module_call,
};
use crate::ir::vars::pattern_bindings;
use crate::ir::{
    BodyExprPlan, BodyPlan, BoolCompareOp, BoolSubjectPlan, CallLowerCtx, CallPlan,
    DispatchArmPlan, DispatchBindingPlan, DispatchDefaultPlan, DispatchLiteral, DispatchTableShape,
    ForwardArg, ForwardCallPlan, LeafOp, ListMatchShape, MatchDispatchPlan, SemanticConstructor,
    SemanticDispatchPattern, TailCallPlan, ThinBodyCtx, ThinBodyPlan, WrapperKind,
    classify_body_expr_plan, classify_body_plan, classify_bool_subject_plan, classify_call_plan,
    classify_constructor_name, classify_leaf_op, classify_list_match_shape,
    classify_match_dispatch_plan, classify_tail_call_plan, classify_thin_fn_def,
    is_builtin_namespace,
};
use crate::types::{self, Type};
/// Aver expressions → Rust expression strings.
use std::collections::HashSet;

pub use super::syntax::{aver_name_to_rust, emit_stmt};
pub(super) use super::syntax::{has_list_patterns, has_string_literal_patterns};

struct RustCallCtx<'a, 'b> {
    ctx: &'a CodegenContext,
    ectx: &'b EmitCtx,
}

impl CallLowerCtx for RustCallCtx<'_, '_> {
    fn is_local_value(&self, name: &str) -> bool {
        self.ectx.local_types.contains_key(name)
    }

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

    fn resolve_module_call<'a>(&self, dotted: &'a str) -> Option<(&'a str, &'a str)> {
        let mut best = None;
        for (dot_idx, _) in dotted.match_indices('.') {
            let prefix = &dotted[..dot_idx];
            let suffix = &dotted[dot_idx + 1..];
            if self.ctx.module_prefixes.contains(prefix)
                && best.is_none_or(|existing: (&str, &str)| prefix.len() > existing.0.len())
            {
                best = Some((prefix, suffix));
            }
        }
        best
    }
}

impl ThinBodyCtx for RustCallCtx<'_, '_> {
    fn find_fn_def<'a>(&'a self, name: &str) -> Option<&'a FnDef> {
        if let Some((prefix, bare)) = resolve_module_call(name, self.ctx) {
            return self
                .ctx
                .modules
                .iter()
                .find(|module| module.prefix == prefix)
                .and_then(|module| module.fn_defs.iter().find(|fd| fd.name == bare));
        }

        self.ctx.fn_defs.iter().find(|fd| fd.name == name)
    }
}

pub(super) fn classify_dispatch_plan_for_rust(
    arms: &[MatchArm],
    ctx: &CodegenContext,
    ectx: &EmitCtx,
) -> Option<MatchDispatchPlan> {
    let lower_ctx = RustCallCtx { ctx, ectx };
    classify_match_dispatch_plan(arms, &lower_ctx)
}

pub(super) fn classify_body_plan_for_rust<'a>(
    body: &'a FnBody,
    ctx: &CodegenContext,
    ectx: &EmitCtx,
) -> Option<BodyPlan<'a>> {
    let lower_ctx = RustCallCtx { ctx, ectx };
    classify_body_plan(body, &lower_ctx)
}

pub(super) fn classify_body_expr_plan_for_rust<'a>(
    expr: &'a Expr,
    ctx: &CodegenContext,
    ectx: &EmitCtx,
) -> BodyExprPlan<'a> {
    let lower_ctx = RustCallCtx { ctx, ectx };
    classify_body_expr_plan(expr, &lower_ctx)
}

pub(super) fn classify_thin_fn_def_for_rust<'a>(
    fd: &'a FnDef,
    ctx: &'a CodegenContext,
    ectx: &'a EmitCtx,
) -> Option<ThinBodyPlan<'a>> {
    let lower_ctx = RustCallCtx { ctx, ectx };
    classify_thin_fn_def(fd, &lower_ctx)
}

/// Emit a Rust expression from an Aver Expr.
pub fn emit_expr(expr: &Expr, ctx: &CodegenContext, ectx: &EmitCtx) -> String {
    emit_expr_with_options(expr, ctx, ectx, true)
}

fn emit_tuple_from_vars(prefix: &str, count: usize) -> String {
    match count {
        0 => "()".to_string(),
        1 => format!("({prefix}0,)"),
        _ => format!(
            "({})",
            (0..count)
                .map(|i| format!("{prefix}{i}"))
                .collect::<Vec<_>>()
                .join(", ")
        ),
    }
}

fn emit_result_tuple_unwrap(result_prefix: &str, value_prefix: &str, count: usize) -> String {
    let matched_results = emit_tuple_from_vars(result_prefix, count);
    let ok_pattern = match count {
        0 => "()".to_string(),
        1 => format!("(Ok({value_prefix}0),)"),
        _ => format!(
            "({})",
            (0..count)
                .map(|i| format!("Ok({value_prefix}{i})"))
                .collect::<Vec<_>>()
                .join(", ")
        ),
    };
    let ok_tuple = emit_tuple_from_vars(value_prefix, count);

    let mut out = format!(
        "match {} {{ {} => Ok({}), {} => {{ ",
        matched_results, ok_pattern, ok_tuple, matched_results
    );
    for i in 0..count {
        out.push_str(&format!(
            "if let Err(__err) = {result_prefix}{i} {{ Err(__err) }} else "
        ));
    }
    out.push_str("{ unreachable!(\"independent product unwrap requires Result branches\") } } }");
    out
}

fn emit_parallel_result_tuple_unwrap(
    branch_prefix: &str,
    result_prefix: &str,
    value_prefix: &str,
    count: usize,
) -> String {
    let matched_branches = emit_tuple_from_vars(branch_prefix, count);
    let completed_pattern = match count {
        0 => "()".to_string(),
        1 => format!("(crate::ParallelBranch::Completed({result_prefix}0),)"),
        _ => format!(
            "({})",
            (0..count)
                .map(|i| format!("crate::ParallelBranch::Completed({result_prefix}{i})"))
                .collect::<Vec<_>>()
                .join(", ")
        ),
    };

    let mut out = format!(
        "match {} {{ {} => {}, {} => {{ ",
        matched_branches,
        completed_pattern,
        emit_result_tuple_unwrap(result_prefix, value_prefix, count),
        matched_branches
    );
    for i in 0..count {
        out.push_str(&format!(
            "if let crate::ParallelBranch::Completed(Err(__err)) = {branch_prefix}{i} {{ Err(__err) }} else "
        ));
    }
    out.push_str("{ panic!(\"independent product branch cancelled by sibling branch\") } } }");
    out
}

fn emit_expr_with_options(
    expr: &Expr,
    ctx: &CodegenContext,
    ectx: &EmitCtx,
    allow_callsite_inlining: bool,
) -> String {
    let lower_ctx = RustCallCtx { ctx, ectx };
    if let Some(leaf) = classify_leaf_op(expr, &lower_ctx) {
        return emit_leaf_op_with_options(&leaf, ctx, ectx, allow_callsite_inlining);
    }

    match expr {
        Expr::Literal(lit) => emit_literal(lit),
        Expr::Ident(name) | Expr::Resolved { name, .. } => aver_name_to_rust(name),
        Expr::Attr(_, _) => unreachable!(
            "Expr::Attr must be lowered through classify_leaf_op (field access, None, \
             variant constructor, or static ref); reaching this arm means \
             classify_field_access returned None for an Attr shape — a bug in ir::leaf"
        ),
        Expr::FnCall(fn_expr, args) => {
            let bare_args: Vec<Expr> = args.iter().map(|a| a.node.clone()).collect();
            emit_fn_call_with_options(
                &fn_expr.node,
                &bare_args,
                ctx,
                ectx,
                allow_callsite_inlining,
            )
        }
        Expr::BinOp(op, left, right) => {
            // Unary minus: `- expr` is parsed as `BinOp(Sub, Literal(Int(0)), expr)`.
            // Emit as `-expr` instead of `(0i64 - expr)` to avoid type mismatch
            // when the operand is Float.
            if matches!(op, BinOp::Sub) && matches!(&left.node, Expr::Literal(Literal::Int(0))) {
                let r = emit_expr(&right.node, ctx, ectx);
                return format!("(-{})", r);
            }
            // BinOp: left and right use parent ectx (last_use on Resolved handles liveness)
            let l = emit_expr(&left.node, ctx, ectx);
            let r = emit_expr(&right.node, ctx, ectx);
            match op {
                BinOp::Add => {
                    if expr_is_numeric(&left.node, ectx) || expr_is_numeric(&right.node, ectx) {
                        // Both sides are numeric (Int/Float) — plain value add.
                        format!("({} + {})", l, r)
                    } else {
                        // Might be AverStr concatenation: Add<&AverStr>.
                        let l = maybe_clone(l, &left.node, ectx);
                        format!("({} + &{})", l, r)
                    }
                }
                _ => {
                    let op_str = match op {
                        BinOp::Add => unreachable!(),
                        BinOp::Sub => "-",
                        BinOp::Mul => "*",
                        BinOp::Div => "/",
                        BinOp::Eq => "==",
                        BinOp::Neq => "!=",
                        BinOp::Lt => "<",
                        BinOp::Gt => ">",
                        BinOp::Lte => "<=",
                        BinOp::Gte => ">=",
                    };
                    // For Eq/Neq with a string literal on either side, deref AverStr (Rc<str>)
                    // to &str for comparison since Rc<str> doesn't impl PartialEq<&str>.
                    if matches!(op, BinOp::Eq | BinOp::Neq) {
                        if let Expr::Literal(Literal::Str(s)) = &right.node {
                            return format!("(&*{} {} {:?})", l, op_str, s);
                        }
                        if let Expr::Literal(Literal::Str(s)) = &left.node {
                            return format!("({:?} {} &*{})", s, op_str, r);
                        }
                    }
                    format!("({} {} {})", l, op_str, r)
                }
            }
        }
        Expr::Match { subject, arms, .. } => emit_match(&subject.node, arms, ctx, ectx),
        Expr::Constructor(name, arg) => {
            let bare_arg = arg.as_ref().map(|a| Box::new(a.node.clone()));
            emit_constructor(name, &bare_arg, ctx, ectx)
        }
        Expr::ErrorProp(inner) => {
            let inner_str = emit_expr(&inner.node, ctx, ectx);
            format!("{}?", inner_str)
        }
        // Pipeline contract: `interp_lower` always runs before Rust codegen
        // — it rewrites `Expr::InterpolatedStr` to `__buf_*` + `__to_str`
        // intrinsic chains that the runtime backends share. Reaching this
        // arm means the pipeline was misconfigured (interp_lower disabled
        // for a path that emits Rust); bug in the caller.
        Expr::InterpolatedStr(_) => unreachable!(
            "InterpolatedStr should have been lowered by ir::interp_lower; \
             Rust codegen runs only on lowered IR (see ir::pipeline contract)"
        ),
        Expr::List(elements) => {
            if elements.is_empty() {
                "aver_rt::AverList::empty()".to_string()
            } else {
                let bare_elems: Vec<Expr> = elements.iter().map(|e| e.node.clone()).collect();
                let parts: Vec<String> =
                    bare_elems.iter().map(|e| clone_arg(e, ctx, ectx)).collect();
                format!("aver_rt::AverList::from_vec(vec![{}])", parts.join(", "))
            }
        }
        Expr::Tuple(items) => {
            let bare_items: Vec<Expr> = items.iter().map(|e| e.node.clone()).collect();
            let parts: Vec<String> = bare_items.iter().map(|e| clone_arg(e, ctx, ectx)).collect();
            format!("({})", parts.join(", "))
        }
        Expr::IndependentProduct(items, unwrap) => {
            let bare_items: Vec<Expr> = items.iter().map(|e| e.node.clone()).collect();
            let parts: Vec<String> = bare_items.iter().map(|e| clone_arg(e, ctx, ectx)).collect();

            let n = parts.len();
            let has_replay = ctx.emit_replay_runtime;

            let mut code = String::new();
            if has_replay {
                // Runtime branch: if recording/replaying, execute sequentially
                // with replay groups (thread_local state stays on one thread).
                code.push_str("if crate::aver_replay::is_effect_tracking_active() { ");
                code.push_str("crate::aver_replay::enter_effect_group(); ");
                for (i, part) in parts.iter().enumerate() {
                    code.push_str(&format!(
                        "crate::aver_replay::set_effect_branch({i}); let _r{i} = {part}; "
                    ));
                }
                code.push_str("crate::aver_replay::exit_effect_group(); ");
                if *unwrap {
                    code.push_str(&emit_result_tuple_unwrap("_r", "__v", n));
                    code.push('?');
                } else {
                    code.push_str(&emit_tuple_from_vars("_r", n));
                }
                code.push_str(" } else { ");
            }

            if *unwrap {
                code.push_str("{ ");
                if has_replay {
                    code.push_str(
                        "let __parallel_scope = crate::aver_replay::capture_parallel_scope_context(); ",
                    );
                }
                code.push_str(
                    "let __cancel_flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); ",
                );
                code.push_str("std::thread::scope(|_s| { ");
                for (i, part) in parts.iter().enumerate() {
                    if has_replay {
                        code.push_str(&format!(
                            "let __parallel_scope{i} = __parallel_scope.clone(); "
                        ));
                    }
                    code.push_str(&format!("let __cancel_flag{i} = __cancel_flag.clone(); "));
                    code.push_str(&format!("let _h{i} = _s.spawn(move || "));
                    if has_replay {
                        code.push_str(&format!(
                            "crate::aver_replay::with_parallel_scope_context(__parallel_scope{i}.clone(), move || "
                        ));
                    }
                    code.push_str("{ crate::run_cancelable_branch(__cancel_flag");
                    code.push_str(&i.to_string());
                    code.push_str(".clone(), move || { let __result = ");
                    code.push_str(part);
                    code.push_str("; if let Err(_) = &__result { __cancel_flag");
                    code.push_str(&i.to_string());
                    code.push_str(
                        ".store(true, std::sync::atomic::Ordering::Relaxed); } __result }) }",
                    );
                    if has_replay {
                        code.push(')');
                    }
                    code.push_str("); ");
                }
                for i in 0..n {
                    code.push_str(&format!("let _b{i} = _h{i}.join().unwrap(); "));
                }
                code.push_str(&emit_parallel_result_tuple_unwrap("_b", "_r", "__v", n));
                code.push_str(" })? }");
            } else {
                if has_replay {
                    code.push_str(
                        "let __parallel_scope = crate::aver_replay::capture_parallel_scope_context(); ",
                    );
                }
                code.push_str("std::thread::scope(|_s| { ");
                for (i, part) in parts.iter().enumerate() {
                    if has_replay {
                        code.push_str(&format!(
                            "let __parallel_scope{i} = __parallel_scope.clone(); "
                        ));
                        code.push_str(&format!(
                            "let _h{i} = _s.spawn(move || crate::aver_replay::with_parallel_scope_context(__parallel_scope{i}.clone(), move || {part})); "
                        ));
                    } else {
                        code.push_str(&format!("let _h{i} = _s.spawn(move || {part}); "));
                    }
                }
                for i in 0..n {
                    code.push_str(&format!("let _r{i} = _h{i}.join().unwrap(); "));
                }
                code.push_str(&emit_tuple_from_vars("_r", n));
                code.push_str(" }) ");
            }

            if has_replay {
                code.push('}');
            }
            code
        }
        Expr::MapLiteral(entries) => {
            if entries.is_empty() {
                "HashMap::new()".to_string()
            } else {
                let mut parts = Vec::new();
                for (k, v) in entries.iter() {
                    parts.push(format!(
                        "({}, {})",
                        clone_arg(&k.node, ctx, ectx),
                        clone_arg(&v.node, ctx, ectx)
                    ));
                }
                format!(
                    "vec![{}].into_iter().collect::<HashMap<_, _>>()",
                    parts.join(", ")
                )
            }
        }
        Expr::RecordCreate { type_name, fields } => {
            let rust_type = if type_name == "Tcp.Connection" {
                "Tcp_Connection"
            } else {
                type_name
            };
            let parts: Vec<String> = fields
                .iter()
                .map(|(name, expr)| {
                    format!(
                        "{}: {}",
                        aver_name_to_rust(name),
                        clone_arg(&expr.node, ctx, ectx)
                    )
                })
                .collect();
            format!("{} {{ {} }}", rust_type, parts.join(", "))
        }
        Expr::RecordUpdate {
            type_name,
            base,
            updates,
        } => {
            let rust_type = if type_name == "Tcp.Connection" {
                "Tcp_Connection"
            } else {
                type_name
            };
            let base_str = clone_arg(&base.node, ctx, ectx);
            let parts: Vec<String> = updates
                .iter()
                .map(|(name, expr)| {
                    format!(
                        "{}: {}",
                        aver_name_to_rust(name),
                        clone_arg(&expr.node, ctx, ectx)
                    )
                })
                .collect();
            format!("{} {{ {}, ..{} }}", rust_type, parts.join(", "), base_str)
        }
        Expr::TailCall(boxed) => {
            // TailCall outside of a TCO loop → emit as regular function call
            let TailCallData { target, args, .. } = boxed.as_ref();
            let bare_args: Vec<Expr> = args.iter().map(|a| a.node.clone()).collect();
            let call_ctx = RustCallCtx { ctx, ectx };
            match classify_tail_call_plan(target, "", &call_ctx) {
                TailCallPlan::SelfCall | TailCallPlan::KnownFunction(_) => {
                    emit_named_function_call(target, &bare_args, ctx, ectx)
                }
                TailCallPlan::Unknown(name) => emit_codegen_error_expr(format!(
                    "Rust codegen: unknown tail call target {}",
                    name
                )),
            }
        }
    }
}

pub(super) fn emit_body_plan_for_rust(
    plan: &BodyPlan<'_>,
    ctx: &CodegenContext,
    ectx: &EmitCtx,
) -> String {
    emit_body_plan_for_rust_with_options(plan, ctx, ectx, true)
}

fn emit_body_plan_for_rust_with_options(
    plan: &BodyPlan<'_>,
    ctx: &CodegenContext,
    ectx: &EmitCtx,
    allow_callsite_inlining: bool,
) -> String {
    match plan {
        BodyPlan::SingleExpr(body_expr) => {
            emit_body_expr_plan_with_options(body_expr, ctx, ectx, allow_callsite_inlining)
        }
        BodyPlan::Block {
            stmts: _,
            bindings,
            tail,
        } => {
            let mut lines = Vec::with_capacity(bindings.len() + 1);
            for binding in bindings.iter() {
                lines.push(format!(
                    "let {} = {};",
                    aver_name_to_rust(binding.name),
                    emit_body_expr_plan_with_options(
                        &binding.expr,
                        ctx,
                        ectx,
                        allow_callsite_inlining,
                    )
                ));
            }
            lines.push(emit_body_expr_plan_with_options(
                tail,
                ctx,
                ectx,
                allow_callsite_inlining,
            ));
            lines.join("\n    ")
        }
    }
}

fn emit_body_expr_plan_with_options(
    plan: &BodyExprPlan<'_>,
    ctx: &CodegenContext,
    ectx: &EmitCtx,
    allow_callsite_inlining: bool,
) -> String {
    match plan {
        BodyExprPlan::Expr(expr) => {
            let code = emit_expr_with_options(expr, ctx, ectx, allow_callsite_inlining);
            // Field access on a borrowed param in return position needs .clone()
            // to produce an owned value (emit_expr produces `obj.field` without clone).
            if let Expr::Attr(obj, _) = expr
                && let Expr::Ident(name) | Expr::Resolved { name, .. } = &obj.node
                && ectx.is_borrowed_param(name)
            {
                return format!("{}.clone()", code);
            }
            code
        }
        BodyExprPlan::Leaf(leaf) => {
            let code = emit_leaf_op_with_options(leaf, ctx, ectx, allow_callsite_inlining);
            // Field access on a borrowed param in return position needs .clone()
            // to produce an owned value.
            if let LeafOp::FieldAccess { object, .. } = leaf
                && let Expr::Ident(name) | Expr::Resolved { name, .. } = &object.node
                && ectx.is_borrowed_param(name)
            {
                return format!("{}.clone()", code);
            }
            code
        }
        BodyExprPlan::Call { target, args } => {
            let bare_args: Vec<Expr> = args.iter().map(|a| a.node.clone()).collect();
            emit_call_plan_with_args_with_options(
                target,
                &bare_args,
                ctx,
                ectx,
                allow_callsite_inlining,
            )
        }
        BodyExprPlan::ForwardCall(plan) => {
            emit_forward_call_plan_with_options(plan, ctx, ectx, allow_callsite_inlining)
        }
    }
}

fn emit_literal(lit: &Literal) -> String {
    match lit {
        Literal::Int(i) => format!("{}i64", i),
        Literal::Float(f) => {
            let s = f.to_string();
            if s.contains('.') || s.contains('e') || s.contains('E') {
                format!("{}f64", s)
            } else {
                format!("{}.0f64", s)
            }
        }
        Literal::Str(s) => format!("AverStr::from({:?})", s),
        Literal::Bool(b) => if *b { "true" } else { "false" }.to_string(),
        Literal::Unit => "()".to_string(),
    }
}

fn emit_codegen_error_expr(message: String) -> String {
    let message_lit = format!("{:?}", message);
    format!(
        "{{ compile_error!({}); unreachable!(\"unreachable after compile_error\") }}",
        message_lit
    )
}

fn emit_fn_call_with_options(
    fn_expr: &Expr,
    args: &[Expr],
    ctx: &CodegenContext,
    ectx: &EmitCtx,
    allow_callsite_inlining: bool,
) -> String {
    let call_ctx = RustCallCtx { ctx, ectx };
    let plan = classify_call_plan(fn_expr, &call_ctx);
    match plan {
        CallPlan::Dynamic => {
            let func = emit_expr_with_options(fn_expr, ctx, ectx, allow_callsite_inlining);
            let arg_strs: Vec<String> = args.iter().map(|a| clone_arg(a, ctx, ectx)).collect();
            format!("{}({})", func, arg_strs.join(", "))
        }
        _ => emit_call_plan_with_args_with_options(&plan, args, ctx, ectx, allow_callsite_inlining),
    }
}

fn emit_call_plan_with_args_with_options(
    plan: &CallPlan,
    args: &[Expr],
    ctx: &CodegenContext,
    ectx: &EmitCtx,
    _allow_callsite_inlining: bool,
) -> String {
    match plan {
        CallPlan::Builtin(name) => builtins::emit_builtin_call(name, args, ctx, ectx)
            .unwrap_or_else(|| {
                emit_codegen_error_expr(format!(
                    "Rust codegen: unhandled builtin call lowering for {}",
                    name
                ))
            }),
        CallPlan::Wrapper(kind) => {
            let wrapper_name = match kind {
                WrapperKind::ResultOk => "Result.Ok",
                WrapperKind::ResultErr => "Result.Err",
                WrapperKind::OptionSome => "Option.Some",
            };
            builtins::emit_builtin_call(wrapper_name, args, ctx, ectx).unwrap_or_else(|| {
                emit_codegen_error_expr(format!(
                    "Rust codegen: missing wrapper lowering for {}",
                    wrapper_name
                ))
            })
        }
        CallPlan::NoneValue => {
            if args.is_empty() {
                "None".to_string()
            } else {
                emit_codegen_error_expr(
                    "Rust codegen: Option.None cannot be called with arguments".to_string(),
                )
            }
        }
        CallPlan::TypeConstructor {
            qualified_type_name,
            variant_name,
        } => emit_type_constructor_call(qualified_type_name, variant_name, args, ctx, ectx),
        CallPlan::Function(name) => emit_named_function_call(name, args, ctx, ectx),
        CallPlan::Dynamic => emit_codegen_error_expr(
            "Rust codegen: dynamic call passed to direct call emitter".to_string(),
        ),
    }
}

fn emit_forward_call_plan_with_options(
    plan: &ForwardCallPlan,
    ctx: &CodegenContext,
    ectx: &EmitCtx,
    allow_callsite_inlining: bool,
) -> String {
    let args: Vec<_> = plan.args.iter().map(forward_arg_to_expr).collect();
    emit_call_plan_with_args_with_options(&plan.target, &args, ctx, ectx, allow_callsite_inlining)
}

fn forward_arg_to_expr(arg: &ForwardArg) -> Expr {
    let ForwardArg::Local(name) = arg;
    Expr::Ident(name.clone())
}

fn emit_leaf_op_with_options(
    leaf: &LeafOp<'_>,
    ctx: &CodegenContext,
    ectx: &EmitCtx,
    allow_callsite_inlining: bool,
) -> String {
    match leaf {
        LeafOp::FieldAccess { object, field_name } => {
            let object = emit_expr_with_options(&object.node, ctx, ectx, allow_callsite_inlining);
            format!("{}.{}", object, aver_name_to_rust(field_name))
        }
        LeafOp::MapGet { map, key } => emit_leaf_builtin_call_with_options(
            "Map.get",
            &[&map.node, &key.node],
            ctx,
            ectx,
            allow_callsite_inlining,
        ),
        LeafOp::MapSet { map, key, value } => emit_leaf_builtin_call_with_options(
            "Map.set",
            &[&map.node, &key.node, &value.node],
            ctx,
            ectx,
            allow_callsite_inlining,
        ),
        LeafOp::VectorNew { size, fill } => emit_leaf_builtin_call_with_options(
            "Vector.new",
            &[&size.node, &fill.node],
            ctx,
            ectx,
            allow_callsite_inlining,
        ),
        LeafOp::VectorSetOrDefaultSameVector {
            vector,
            index,
            value,
        } => {
            let vector = clone_arg_with_options(&vector.node, ctx, ectx, allow_callsite_inlining);
            let index = emit_expr_with_options(&index.node, ctx, ectx, allow_callsite_inlining);
            let value = clone_arg_with_options(&value.node, ctx, ectx, allow_callsite_inlining);
            format!(
                "{{ let __vec = {}; let __idx = {} as usize; if __idx < __vec.len() {{ __vec.set_unchecked(__idx, {}) }} else {{ __vec }} }}",
                vector, index, value
            )
        }
        LeafOp::VectorGetOrDefaultLiteral {
            vector,
            index,
            default_literal,
        } => {
            let vector = emit_expr_with_options(&vector.node, ctx, ectx, allow_callsite_inlining);
            let index = emit_expr_with_options(&index.node, ctx, ectx, allow_callsite_inlining);
            let default = emit_literal(default_literal);
            format!(
                "{}.get({} as usize).cloned().unwrap_or({})",
                vector, index, default
            )
        }
        LeafOp::IntModOrDefaultLiteral {
            a,
            b,
            default_literal,
        } => {
            // When divisor is a known non-zero literal, skip the zero check entirely.
            if let Expr::Literal(Literal::Int(n)) = &b.node
                && *n != 0
            {
                let a = emit_expr_with_options(&a.node, ctx, ectx, allow_callsite_inlining);
                let b_str = emit_literal(&Literal::Int(*n));
                format!("({}).rem_euclid({})", a, b_str)
            } else {
                let a = emit_expr_with_options(&a.node, ctx, ectx, allow_callsite_inlining);
                let b = emit_expr_with_options(&b.node, ctx, ectx, allow_callsite_inlining);
                let default = emit_literal(default_literal);
                format!(
                    "{{ let __b = {}; if __b == 0i64 {{ {} }} else {{ ({}).rem_euclid(__b) }} }}",
                    b, default, a
                )
            }
        }
        LeafOp::ListIndexGet { list, index } => {
            let list = emit_expr_with_options(&list.node, ctx, ectx, allow_callsite_inlining);
            let index = emit_expr_with_options(&index.node, ctx, ectx, allow_callsite_inlining);
            format!("{}.to_vec().get({} as usize).cloned()", list, index)
        }
        LeafOp::NoneValue => "None".to_string(),
        LeafOp::VariantConstructor {
            qualified_type_name,
            variant_name,
        } => {
            if let Some((prefix, _)) = resolve_module_call(qualified_type_name, ctx) {
                let module_path = module_prefix_to_rust_path(prefix);
                let bare_type = qualified_type_name
                    .rsplit_once('.')
                    .map(|(_, t)| t)
                    .unwrap_or(qualified_type_name);
                format!("{}::{}::{}", module_path, bare_type, variant_name)
            } else {
                format!("{}::{}", qualified_type_name, variant_name)
            }
        }
        LeafOp::StaticRef(name) => {
            if let Some((prefix, bare)) = resolve_module_call(name, ctx) {
                let module_path = module_prefix_to_rust_path(prefix);
                format!("{}::{}", module_path, aver_name_to_rust(bare))
            } else {
                aver_name_to_rust(name)
            }
        }
    }
}

fn emit_leaf_builtin_call_with_options(
    name: &str,
    args: &[&Expr],
    ctx: &CodegenContext,
    ectx: &EmitCtx,
    _allow_callsite_inlining: bool,
) -> String {
    let owned_args = args.iter().map(|expr| (*expr).clone()).collect::<Vec<_>>();
    builtins::emit_builtin_call(name, &owned_args, ctx, ectx).unwrap_or_else(|| {
        emit_codegen_error_expr(format!(
            "Rust codegen: missing leaf builtin lowering for {}",
            name
        ))
    })
}

/// Check if a FnDef has self-tailcall (TCO) in its body.
/// Returns true only if the function has self-recursive tail calls and NO mutual tail calls.
/// Mutual-TCO functions get wrapper functions with `&T` params, so they should use borrow.
#[allow(dead_code)]
fn fn_def_has_only_self_tco(fd: &FnDef) -> bool {
    let has_self = fn_def_has_tco(fd);
    if !has_self {
        return false;
    }
    // Check if there are tail calls to OTHER functions (mutual TCO)
    !fn_def_has_mutual_tco(fd)
}

#[allow(dead_code)]
fn fn_def_has_mutual_tco(fd: &FnDef) -> bool {
    fn expr_has_other_tailcall(expr: &Expr, fn_name: &str) -> bool {
        match expr {
            Expr::TailCall(boxed) => boxed.target != fn_name,
            Expr::Match { arms, .. } => arms
                .iter()
                .any(|arm| expr_has_other_tailcall(&arm.body.node, fn_name)),
            _ => false,
        }
    }
    fd.body.stmts().iter().any(|s| match s {
        Stmt::Expr(e) => expr_has_other_tailcall(&e.node, &fd.name),
        Stmt::Binding(_, _, e) => expr_has_other_tailcall(&e.node, &fd.name),
    })
}

#[allow(dead_code)]
fn fn_def_has_tco(fd: &FnDef) -> bool {
    fn expr_has_self_tailcall(expr: &Expr, fn_name: &str) -> bool {
        match expr {
            Expr::TailCall(boxed) => boxed.target == fn_name,
            Expr::Match { arms, .. } => arms
                .iter()
                .any(|arm| expr_has_self_tailcall(&arm.body.node, fn_name)),
            _ => false,
        }
    }
    fd.body.stmts().iter().any(|s| match s {
        Stmt::Expr(e) => expr_has_self_tailcall(&e.node, &fd.name),
        Stmt::Binding(_, _, e) => expr_has_self_tailcall(&e.node, &fd.name),
    })
}

/// Compute borrow mask from a FnDef, checking for TCO.
/// Must mirror actual emitted signature:
/// - Mutual-TCO SCC members → wrapper with borrow-by-default (`&T`)
/// - Self-TCO only (not in SCC) → loop with `mut T`, all-false mask
/// - Non-TCO → borrow-by-default
fn borrow_mask_from_fn_def(fd: &FnDef, arg_count: usize, ctx: &CodegenContext) -> Vec<bool> {
    // Mutual-TCO members are emitted as wrappers with borrow-by-default,
    // even if they also have self-TailCalls. Don't skip borrow for them.
    // Memo functions always use borrow-by-default (memo wrapper takes &T),
    // even if the body has self-tail-calls.
    let is_memo = ctx.memo_fns.contains(&fd.name);
    if !is_memo
        && !ctx.mutual_tco_members.contains(&fd.name)
        && super::toplevel::body_has_self_tailcall(&fd.body, &fd.name)
    {
        return vec![false; arg_count];
    }
    fd.params
        .iter()
        .take(arg_count)
        .map(|(_, type_ann)| {
            let ty = crate::types::parse_type_str(type_ann);
            should_borrow_param(&ty)
        })
        .collect()
}

/// Look up whether the callee's i-th parameter is borrowed (`&T`).
/// Returns a Vec of booleans, one per parameter, indicating borrow status.
/// Uses fn_sigs first, falls back to FnDef type annotations from the AST.
/// TCO functions (self or mutual) never use borrow-by-default.
fn callee_borrow_mask(name: &str, arg_count: usize, ctx: &CodegenContext) -> Vec<bool> {
    // First, try to find the FnDef to check for TCO (which overrides everything)
    let fd = find_fn_def_by_name(name, ctx);
    if let Some(fd) = fd {
        return borrow_mask_from_fn_def(fd, arg_count, ctx);
    }

    // No FnDef found, try fn_sigs (type-checker resolved types)
    let lookup_name = if let Some((prefix, bare)) = resolve_module_call(name, ctx) {
        crate::visibility::qualified_name(prefix, bare)
    } else {
        name.to_string()
    };

    if let Some((param_types, _, _)) = ctx
        .fn_sigs
        .get(&lookup_name)
        .or_else(|| ctx.fn_sigs.get(name))
    {
        // Without FnDef we can't check TCO status, but self-TCO functions
        // always resolve via find_fn_def_by_name above, so this path is safe
        // for borrow-by-default on all non-scalar types including Named.
        return param_types
            .iter()
            .take(arg_count)
            .map(should_borrow_param)
            .collect();
    }

    // Unknown function -- don't borrow (conservative)
    vec![false; arg_count]
}

/// Find a FnDef by name, checking top-level, modules (qualified), and all modules (unqualified).
fn find_fn_def_by_name<'a>(name: &str, ctx: &'a CodegenContext) -> Option<&'a FnDef> {
    // Check top-level fn_defs
    if let Some(fd) = ctx.fn_defs.iter().find(|fd| fd.name == name) {
        return Some(fd);
    }

    // Check extra fn_defs (current module being emitted)
    if let Some(fd) = ctx.extra_fn_defs.iter().find(|fd| fd.name == name) {
        return Some(fd);
    }

    // Check module fn_defs for qualified calls
    if let Some((prefix, bare)) = resolve_module_call(name, ctx) {
        for module in &ctx.modules {
            if module.prefix == prefix
                && let Some(fd) = module.fn_defs.iter().find(|fd| fd.name == bare)
            {
                return Some(fd);
            }
        }
    }

    None
}

fn emit_named_function_call(
    name: &str,
    args: &[Expr],
    ctx: &CodegenContext,
    ectx: &EmitCtx,
) -> String {
    let borrow_mask = callee_borrow_mask(name, args.len(), ctx);
    let arg_strs: Vec<String> = args
        .iter()
        .enumerate()
        .map(|(i, a)| {
            if borrow_mask.get(i).copied().unwrap_or(false) {
                borrow_arg(a, ctx, ectx)
            } else {
                clone_arg(a, ctx, ectx)
            }
        })
        .collect();

    if let Some((prefix, bare)) = resolve_module_call(name, ctx) {
        let module_path = module_prefix_to_rust_path(prefix);
        format!(
            "{}::{}({})",
            module_path,
            aver_name_to_rust(bare),
            arg_strs.join(", ")
        )
    } else {
        format!("{}({})", aver_name_to_rust(name), arg_strs.join(", "))
    }
}

fn emit_type_constructor_call(
    qualified_type_name: &str,
    variant_name: &str,
    args: &[Expr],
    ctx: &CodegenContext,
    ectx: &EmitCtx,
) -> String {
    let ctor_name = format!("{}.{}", qualified_type_name, variant_name);
    let boxed_positions = constructor_boxed_positions(&ctor_name, ctx);
    let arg_strs: Vec<String> = args
        .iter()
        .enumerate()
        .map(|(idx, a)| {
            let arg = clone_arg(a, ctx, ectx);
            if boxed_positions.contains(&idx) {
                format!("std::sync::Arc::new({})", arg)
            } else {
                arg
            }
        })
        .collect();

    if let Some((prefix, bare_type_name)) = resolve_module_call(qualified_type_name, ctx) {
        let module_path = module_prefix_to_rust_path(prefix);
        format!(
            "{}::{}::{}({})",
            module_path,
            bare_type_name,
            variant_name,
            arg_strs.join(", ")
        )
    } else {
        format!(
            "{}::{}({})",
            qualified_type_name,
            variant_name,
            arg_strs.join(", ")
        )
    }
}

/// Clone a value if it's a variable reference (to avoid move issues in generated Rust).
/// Literals and complex expressions don't need cloning.
///
/// For borrowed params (`&T` from borrow-by-default), the default behavior is to
/// produce an owned clone. Call sites for user functions override this via `borrow_arg`.
pub(super) fn maybe_clone(code: String, expr: &Expr, ectx: &EmitCtx) -> String {
    match expr {
        Expr::Ident(name) | Expr::Resolved { name, .. } => {
            if expr_skip_clone(expr, ectx) {
                code
            } else if ectx.is_rc_wrapped(name) {
                // Pass-through param (Rc<T> in self-TCO, &T in mutual-TCO trampoline).
                // For Rc<T>: `(*param).clone()` derefs Rc then clones inner T.
                // For &T: `(*param).clone()` derefs borrow then clones inner T.
                // Both produce owned T at the call site.
                format!("(*{}).clone()", code)
            } else if ectx.is_borrowed_param(name) {
                // Borrowed param: clone to produce owned T (e.g. for return position,
                // constructors, wrappers). User function calls use `borrow_arg` instead.
                format!("{}.clone()", code)
            } else {
                format!("{}.clone()", code)
            }
        }
        // Field access on records: emit_expr produces `obj.field` without clone.
        // Clone here when ownership is needed (constructors, return, etc.).
        // When passed to a function expecting `&T`, `borrow_arg` handles it.
        Expr::Attr(obj, _field) => {
            // Builtin namespace access (e.g. Int.abs) → no clone needed
            if matches!(&obj.node, Expr::Ident(name) if is_builtin_namespace(name)) {
                code
            } else {
                format!("{}.clone()", code)
            }
        }
        _ => code,
    }
}

/// Is this expression known to produce a numeric (Int/Float) value?
/// Used to decide whether `+` needs `&` on the RHS (only strings do).
fn expr_is_numeric(expr: &Expr, ectx: &EmitCtx) -> bool {
    match expr {
        Expr::Literal(Literal::Int(_) | Literal::Float(_)) => true,
        Expr::Ident(name) | Expr::Resolved { name, .. } => {
            matches!(
                ectx.local_types.get(name.as_str()),
                Some(Type::Int | Type::Float)
            )
        }
        // Sub/Mul/Div always produce numeric results.
        Expr::BinOp(op, _, _) => !matches!(op, BinOp::Add),
        Expr::FnCall(fn_expr, _) => {
            if let Some(dotted) = expr_to_dotted_name(&fn_expr.node) {
                matches!(
                    dotted.as_str(),
                    "Int.abs"
                        | "Int.min"
                        | "Int.max"
                        | "Float.abs"
                        | "Float.floor"
                        | "Float.ceil"
                        | "Float.round"
                        | "Float.min"
                        | "Float.max"
                        | "Float.sqrt"
                        | "Float.pow"
                        | "Float.sin"
                        | "Float.cos"
                        | "Float.atan2"
                        | "Float.fromInt"
                        | "List.len"
                        | "Vector.len"
                        | "Map.len"
                        | "String.len"
                        | "String.byteLength"
                        | "Char.toCode"
                )
            } else {
                false
            }
        }
        _ => false,
    }
}

/// Is a record field access known to return a Copy type?
/// Looks up the record definition in the context to find the field's type.
fn attr_result_is_copy(obj: &Expr, field: &str, ctx: &CodegenContext, ectx: &EmitCtx) -> bool {
    let obj_type = match obj {
        Expr::Ident(name) | Expr::Resolved { name, .. } => ectx.local_types.get(name),
        _ => None,
    };
    let record_name = match obj_type {
        Some(Type::Named(name)) => name.as_str(),
        _ => return false,
    };
    // Find record definition and look up field type.
    for td in ctx
        .type_defs
        .iter()
        .chain(ctx.modules.iter().flat_map(|m| m.type_defs.iter()))
    {
        if let TypeDef::Product { name, fields, .. } = td
            && name == record_name
            && let Some((_, type_ann)) = fields.iter().find(|(n, _)| n == field)
        {
            let ty = types::parse_type_str(type_ann);
            return super::emit_ctx::is_copy_type(&ty);
        }
    }
    false
}

/// Emit an expression as a borrow for passing to a user function that takes `&T`.
/// For borrowed params: pass directly (already `&T`).
/// For owned locals: pass `&x`.
/// For Copy types: pass by value (no borrow needed).
/// For AverStr: pass by value (cheap clone).
pub(super) fn borrow_arg(expr: &Expr, ctx: &CodegenContext, ectx: &EmitCtx) -> String {
    let code = emit_expr(expr, ctx, ectx);
    match expr {
        Expr::Ident(name) => {
            if ectx.is_copy(name) {
                // Copy type: pass by value
                code
            } else if ectx
                .local_types
                .get(name)
                .is_some_and(|ty| matches!(ty, Type::Str))
            {
                // AverStr (Rc<str>): pass by value (cheap clone if needed)
                // Ident (globals) are always moveable
                if ectx.is_rc_wrapped(name) {
                    format!("(*{}).clone()", code)
                } else {
                    code
                }
            } else if ectx.is_borrowed_param(name) {
                // Already `&T` — pass directly
                code
            } else if ectx.is_rc_wrapped(name) {
                // Pass-through TCO param (Rc<T> or &T): deref to get &T
                format!("&*{}", code)
            } else {
                // Owned local: borrow it
                format!("&{}", code)
            }
        }
        Expr::Resolved { name, .. } => {
            if ectx.is_copy(name) {
                code
            } else if ectx
                .local_types
                .get(name)
                .is_some_and(|ty| matches!(ty, Type::Str))
            {
                // AverStr: check last_use for move eligibility
                if expr_can_move(expr) {
                    code
                } else if ectx.is_rc_wrapped(name) {
                    format!("(*{}).clone()", code)
                } else {
                    format!("{}.clone()", code)
                }
            } else if ectx.is_borrowed_param(name) {
                code
            } else if ectx.is_rc_wrapped(name) {
                format!("&*{}", code)
            } else if expr_can_move(expr) {
                // Last use: can move, borrow the owned value
                format!("&{}", code)
            } else {
                // Not last use: clone then borrow
                format!("&{}", code)
            }
        }
        _ => {
            // Complex expression: emit and borrow the result.
            // Check if the expression type needs borrowing by looking at what
            // the callee expects. For complex expressions, we produce a temporary
            // and borrow it.
            format!("&{}", code)
        }
    }
}

/// Emit an expression as a function argument, cloning variables to prevent move errors.
pub(super) fn clone_arg(expr: &Expr, ctx: &CodegenContext, ectx: &EmitCtx) -> String {
    clone_arg_with_options(expr, ctx, ectx, true)
}

fn clone_arg_with_options(
    expr: &Expr,
    ctx: &CodegenContext,
    ectx: &EmitCtx,
    allow_callsite_inlining: bool,
) -> String {
    let code = emit_expr_with_options(expr, ctx, ectx, allow_callsite_inlining);
    // Field access on record: check if the field type is Copy before cloning.
    if let Expr::Attr(obj, field) = expr
        && attr_result_is_copy(&obj.node, field, ctx, ectx)
    {
        return code;
    }
    maybe_clone(code, expr, ectx)
}

fn emit_constructor(
    name: &str,
    arg: &Option<Box<Expr>>,
    ctx: &CodegenContext,
    ectx: &EmitCtx,
) -> String {
    let normalized_name = match name {
        "Ok" => "Result.Ok",
        "Err" => "Result.Err",
        "Some" => "Option.Some",
        "None" => "Option.None",
        other => other,
    };
    let args: &[Expr] = match arg {
        Some(inner) => std::slice::from_ref(inner.as_ref()),
        None => &[],
    };
    let lower_ctx = RustCallCtx { ctx, ectx };

    match classify_constructor_name(normalized_name, &lower_ctx) {
        SemanticConstructor::Wrapper(kind) => {
            let wrapper_name = match kind {
                WrapperKind::ResultOk => "Result.Ok",
                WrapperKind::ResultErr => "Result.Err",
                WrapperKind::OptionSome => "Option.Some",
            };
            builtins::emit_builtin_call(wrapper_name, args, ctx, ectx).unwrap_or_else(|| {
                emit_codegen_error_expr(format!(
                    "Rust codegen: missing constructor wrapper lowering for {}",
                    wrapper_name
                ))
            })
        }
        SemanticConstructor::NoneValue => "None".to_string(),
        SemanticConstructor::TypeConstructor {
            qualified_type_name,
            variant_name,
        } => emit_type_constructor_call(&qualified_type_name, &variant_name, args, ctx, ectx),
        SemanticConstructor::Unknown(_) => {
            let inner = arg
                .as_ref()
                .map(|a| clone_arg(a, ctx, ectx))
                .unwrap_or_else(|| "()".to_string());
            format!("{}({})", name, inner)
        }
    }
}

fn is_irrefutable_pattern(pat: &Pattern) -> bool {
    match pat {
        Pattern::Wildcard | Pattern::Ident(_) => true,
        Pattern::Tuple(pats) => pats.iter().all(is_irrefutable_pattern),
        _ => false,
    }
}

fn emit_match(subject: &Expr, arms: &[MatchArm], ctx: &CodegenContext, ectx: &EmitCtx) -> String {
    // Single-arm irrefutable match → `let` destructuring instead of `match`.
    // e.g. `match x: (a, b) -> expr` → `{ let (a, b) = x; expr }`
    if arms.len() == 1 && is_irrefutable_pattern(&arms[0].pattern) {
        let arm = &arms[0];
        let subj = clone_arg(subject, ctx, ectx);
        let pat = emit_pattern(&arm.pattern, false, ctx);
        let body = maybe_clone(emit_expr(&arm.body.node, ctx, ectx), &arm.body.node, ectx);
        return match &arm.pattern {
            Pattern::Wildcard => body,
            Pattern::Ident(name) => {
                let name = aver_name_to_rust(name);
                format!("{{ let {} = {}; {} }}", name, subj, body)
            }
            _ => format!("{{ let {} = {}; {} }}", pat, subj, body),
        };
    }

    // For borrowed params, match on the reference directly instead of cloning,
    // but only when no arms have pattern bindings (destructuring produces &T refs
    // that would need clone rebindings across all match emission paths).
    let no_bindings = arms
        .iter()
        .all(|arm| pattern_bindings(&arm.pattern).is_empty());
    let match_on_ref = no_bindings
        && matches!(
            subject,
            Expr::Ident(name) | Expr::Resolved { name, .. } if ectx.is_borrowed_param(name)
        );
    let subj = if match_on_ref {
        emit_expr(subject, ctx, ectx)
    } else {
        clone_arg(subject, ctx, ectx)
    };
    let dispatch_plan = classify_dispatch_plan_for_rust(arms, ctx, ectx);

    // Bool match → if/else: match expr { true => A, false => B } → if expr { A } else { B }
    // Always applied (not just optimized) since it generates strictly better code.
    if let Some(MatchDispatchPlan::Bool(shape)) = dispatch_plan.as_ref()
        && let Some(code) = try_emit_bool_if_else(subject, &subj, arms, *shape, ctx, ectx, ectx)
    {
        return code;
    }

    // Determine if subject needs special treatment
    let needs_as_str = subject_might_be_string(subject, ctx);
    let _needs_as_slice = subject_might_be_list(subject, arms, ctx);

    if has_list_patterns(arms) {
        let list_shape = match dispatch_plan.as_ref() {
            Some(MatchDispatchPlan::List(shape)) => Some(*shape),
            _ => None,
        };
        return emit_list_match(subj, arms, list_shape, true, ctx, |arm| {
            maybe_clone(emit_expr(&arm.body.node, ctx, ectx), &arm.body.node, ectx)
        });
    }

    if let Some(MatchDispatchPlan::Table(shape)) = dispatch_plan.as_ref() {
        return emit_dispatch_table_match(subj, arms, shape, |arm| {
            maybe_clone(emit_expr(&arm.body.node, ctx, ectx), &arm.body.node, ectx)
        });
    }

    let match_expr = if needs_as_str && has_string_literal_patterns(arms) {
        format!("&*{}", subj)
    } else {
        subj
    };

    let mut arm_strs = Vec::new();
    for arm in arms {
        let pat = emit_pattern(&arm.pattern, needs_as_str, ctx);
        // Each arm body is independent — use parent's used_after
        // Clone the result if it's a bare ident that's still needed after the match
        let body = maybe_clone(emit_expr(&arm.body.node, ctx, ectx), &arm.body.node, ectx);
        let mut rebindings = emit_pattern_rebindings(&arm.pattern, ctx);
        // When matching on a reference (borrowed param), bindings are &T.
        // Clone them to produce owned values expected by arm bodies.
        if match_on_ref {
            let ref_rebinds = emit_ref_match_rebindings(&arm.pattern);
            if !ref_rebinds.is_empty() {
                rebindings = format!("{}{}", ref_rebinds, rebindings);
            }
        }
        arm_strs.push(format!(
            "        {} => {{\n            {}{}\n        }}",
            pat, rebindings, body
        ));
    }

    format!("match {} {{\n{}\n    }}", match_expr, arm_strs.join(",\n"))
}

/// If match has exactly two arms with `true` and `false` bool literal patterns,
/// emit `if subject { true_body } else { false_body }` instead of a match.
fn try_emit_bool_if_else(
    subject: &Expr,
    subj: &str,
    arms: &[MatchArm],
    shape: crate::ir::BoolMatchShape,
    ctx: &CodegenContext,
    subj_ectx: &EmitCtx,
    ectx: &EmitCtx,
) -> Option<String> {
    let (true_body, false_body, cond) = match classify_bool_subject_plan(subject) {
        BoolSubjectPlan::Expr(_) => (
            &arms[shape.true_arm_index].body,
            &arms[shape.false_arm_index].body,
            subj.to_string(),
        ),
        BoolSubjectPlan::Compare {
            lhs,
            rhs,
            op,
            invert,
        } => {
            let lhs_code = emit_expr(&lhs.node, ctx, subj_ectx);
            let rhs_code = emit_expr(&rhs.node, ctx, subj_ectx);
            let op_code = match op {
                BoolCompareOp::Eq => "==",
                BoolCompareOp::Lt => "<",
                BoolCompareOp::Gt => ">",
            };
            let cond = format!("({lhs_code} {op_code} {rhs_code})");
            if invert {
                (
                    &arms[shape.false_arm_index].body,
                    &arms[shape.true_arm_index].body,
                    cond,
                )
            } else {
                (
                    &arms[shape.true_arm_index].body,
                    &arms[shape.false_arm_index].body,
                    cond,
                )
            }
        }
    };
    let t = maybe_clone(emit_expr(&true_body.node, ctx, ectx), &true_body.node, ectx);
    let f = maybe_clone(
        emit_expr(&false_body.node, ctx, ectx),
        &false_body.node,
        ectx,
    );
    Some(format!("if {} {{ {} }} else {{ {} }}", cond, t, f))
}

fn subject_might_be_string(_subject: &Expr, _ctx: &CodegenContext) -> bool {
    // Heuristic: if subject is an ident, we can't tell at codegen time
    // We'll rely on the patterns to decide
    true
}

fn subject_might_be_list(_subject: &Expr, _arms: &[MatchArm], _ctx: &CodegenContext) -> bool {
    true
}

pub(super) fn emit_dispatch_table_match<F>(
    subject: String,
    arms: &[MatchArm],
    shape: &DispatchTableShape,
    body_for_arm: F,
) -> String
where
    F: Fn(&MatchArm) -> String,
{
    // Fast path: if all entries are wrapper tags (Result/Option), emit a Rust `match`
    // with move bindings instead of if-chain + clone.  This is both shorter and faster
    // because it avoids cloning the inner value.
    if let Some(code) = try_emit_wrapper_match(&subject, arms, shape, &body_for_arm) {
        return code;
    }

    let subject_name = "__dispatch_subject";
    let fallback = match &shape.default_arm {
        Some(default_arm) => emit_default_dispatch_arm(
            subject_name,
            &arms[default_arm.arm_index],
            default_arm,
            &body_for_arm,
        ),
        None => "panic!(\"Aver Rust codegen: non-exhaustive dispatch match\")".to_string(),
    };

    let body = shape
        .entries
        .iter()
        .rev()
        .fold(fallback, |else_branch, entry| {
            let arm = &arms[entry.arm_index];
            let cond = emit_dispatch_condition(subject_name, &entry.pattern);
            let body = emit_dispatch_arm_body(subject_name, arm, entry, &body_for_arm);
            format!("if {} {{ {} }} else {{ {} }}", cond, body, else_branch)
        });

    format!("{{ let {} = {}; {} }}", subject_name, subject, body)
}

/// Emit `match subject { Ok(v) => ..., Err(e) => ... }` when ALL dispatch entries are
/// wrapper tags (Result.Ok/Err, Option.Some/None).  Bindings are by move (no clone).
fn try_emit_wrapper_match<F>(
    subject: &str,
    arms: &[MatchArm],
    shape: &DispatchTableShape,
    body_for_arm: &F,
) -> Option<String>
where
    F: Fn(&MatchArm) -> String,
{
    // All entries must be wrapper tags with payload bindings
    let all_wrappers = shape.entries.iter().all(|e| {
        matches!(
            e.pattern,
            SemanticDispatchPattern::WrapperTag(_) | SemanticDispatchPattern::NoneValue
        )
    });
    if !all_wrappers {
        return None;
    }

    let mut match_arms = Vec::new();
    for entry in &shape.entries {
        let arm = &arms[entry.arm_index];
        let body = body_for_arm(arm);
        match (&entry.pattern, &entry.binding) {
            (
                SemanticDispatchPattern::WrapperTag(kind),
                DispatchBindingPlan::WrapperPayload(name),
            ) => {
                let binding = aver_name_to_rust(name);
                let extractor = match kind {
                    WrapperKind::ResultOk => "Ok",
                    WrapperKind::ResultErr => "Err",
                    WrapperKind::OptionSome => "Some",
                };
                match_arms.push(format!("{extractor}({binding}) => {{ {body} }}"));
            }
            (SemanticDispatchPattern::WrapperTag(kind), DispatchBindingPlan::None) => {
                let pattern = match kind {
                    WrapperKind::ResultOk => "Ok(_)",
                    WrapperKind::ResultErr => "Err(_)",
                    WrapperKind::OptionSome => "Some(_)",
                };
                match_arms.push(format!("{pattern} => {{ {body} }}"));
            }
            (SemanticDispatchPattern::NoneValue, _) => {
                match_arms.push(format!("None => {{ {body} }}"));
            }
            _ => return None,
        }
    }

    // Default arm (wildcard)
    if let Some(default_arm) = &shape.default_arm {
        let arm = &arms[default_arm.arm_index];
        let body = body_for_arm(arm);
        if let Some(name) = &default_arm.binding_name {
            let binding = aver_name_to_rust(name);
            match_arms.push(format!("{binding} => {{ {body} }}"));
        } else {
            match_arms.push(format!("_ => {{ {body} }}"));
        }
    }

    Some(format!("match {} {{ {} }}", subject, match_arms.join(", ")))
}

fn emit_dispatch_condition(subject_name: &str, pattern: &SemanticDispatchPattern) -> String {
    match pattern {
        SemanticDispatchPattern::Literal(lit) => match lit {
            DispatchLiteral::Int(i) => format!("{subject_name} == {i}i64"),
            DispatchLiteral::Float(f) => format!("{subject_name} == {f}f64"),
            DispatchLiteral::Bool(b) => format!("{subject_name} == {b}"),
            DispatchLiteral::Str(s) => format!("&*{subject_name} == {:?}", s),
            DispatchLiteral::Unit => format!("{subject_name} == ()"),
        },
        SemanticDispatchPattern::EmptyList => format!("{subject_name}.is_empty()"),
        SemanticDispatchPattern::NoneValue => format!("{subject_name}.is_none()"),
        SemanticDispatchPattern::WrapperTag(kind) => match kind {
            WrapperKind::ResultOk => format!("{subject_name}.is_ok()"),
            WrapperKind::ResultErr => format!("{subject_name}.is_err()"),
            WrapperKind::OptionSome => format!("{subject_name}.is_some()"),
        },
    }
}

fn emit_dispatch_arm_body(
    subject_name: &str,
    arm: &MatchArm,
    entry: &DispatchArmPlan,
    body_for_arm: &impl Fn(&MatchArm) -> String,
) -> String {
    let body = body_for_arm(arm);
    match (&entry.pattern, &entry.binding) {
        (
            SemanticDispatchPattern::WrapperTag(kind),
            DispatchBindingPlan::WrapperPayload(binding_name),
        ) => {
            let binding = aver_name_to_rust(binding_name);
            let extractor = match kind {
                WrapperKind::ResultOk => "Ok",
                WrapperKind::ResultErr => "Err",
                WrapperKind::OptionSome => "Some",
            };
            format!(
                "{{ let {binding} = if let {extractor}({binding}) = &{subject_name} {{ {binding}.clone() }} else {{ unreachable!(\"Aver Rust codegen: dispatch tag mismatch\") }}; {body} }}"
            )
        }
        _ => body,
    }
}

fn emit_default_dispatch_arm(
    subject_name: &str,
    arm: &MatchArm,
    default_arm: &DispatchDefaultPlan,
    body_for_arm: &impl Fn(&MatchArm) -> String,
) -> String {
    let body = body_for_arm(arm);
    match &default_arm.binding_name {
        None => body,
        Some(name) => {
            let name = aver_name_to_rust(name);
            format!("{{ let {} = {}.clone(); {} }}", name, subject_name, body)
        }
    }
}

pub(super) fn emit_list_match<F>(
    subject: String,
    arms: &[MatchArm],
    list_shape: Option<ListMatchShape>,
    allow_fast_macro: bool,
    ctx: &CodegenContext,
    body_for_arm: F,
) -> String
where
    F: Fn(&MatchArm) -> String,
{
    // Fast path: exactly [] and [h, ..t] → use aver_list_match! macro
    if allow_fast_macro
        && let Some(code) =
            try_emit_list_match_macro(&subject, arms, list_shape, ctx, &body_for_arm)
    {
        return code;
    }
    let subject_name = "__list_subject";
    let arms_code = emit_list_match_arms(subject_name, arms, ctx, &body_for_arm);
    format!("{{ let {} = {}; {} }}", subject_name, subject, arms_code)
}

/// Emit the aver_list_match! macro for the common []/[h,..t] two-arm pattern.
fn try_emit_list_match_macro<F>(
    subject: &str,
    arms: &[MatchArm],
    list_shape: Option<ListMatchShape>,
    ctx: &CodegenContext,
    body_for_arm: &F,
) -> Option<String>
where
    F: Fn(&MatchArm) -> String,
{
    let shape = match list_shape {
        Some(shape) => shape,
        None => classify_list_match_shape(arms)?,
    };
    let empty_arm = &arms[shape.empty_arm_index];
    let cons_arm = &arms[shape.cons_arm_index];
    let Pattern::Cons(head, tail) = &cons_arm.pattern else {
        return None;
    };
    // Both names must be real idents (not _) for the macro binding
    if head == "_" || tail == "_" {
        return None;
    }
    let head_name = aver_name_to_rust(head);
    let tail_name = aver_name_to_rust(tail);
    let empty_body = emit_list_arm_body(empty_arm, ctx, body_for_arm(empty_arm));
    let cons_body = emit_list_arm_body(cons_arm, ctx, body_for_arm(cons_arm));
    // Wrap arm bodies in braces only when they contain statements (return, let, etc.)
    // to avoid Rust's "unnecessary braces" warning on simple expressions.
    let wrap = |body: &str| -> String {
        if body.contains("return ") || body.contains("let ") || body.contains(';') {
            format!("{{ {} }}", body)
        } else {
            body.to_string()
        }
    };
    Some(format!(
        "aver_list_match!({}, [] => {}, [{}, {}] => {})",
        subject,
        wrap(&empty_body),
        head_name,
        tail_name,
        wrap(&cons_body)
    ))
}

fn emit_list_match_arms<F>(
    subject_name: &str,
    arms: &[MatchArm],
    ctx: &CodegenContext,
    body_for_arm: &F,
) -> String
where
    F: Fn(&MatchArm) -> String,
{
    let Some((first, rest)) = arms.split_first() else {
        return "panic!(\"Aver Rust codegen: empty list match\")".to_string();
    };

    let body = emit_list_arm_body(first, ctx, body_for_arm(first));
    let fallback = if rest.is_empty() {
        "panic!(\"Aver Rust codegen: non-exhaustive list match\")".to_string()
    } else {
        emit_list_match_arms(subject_name, rest, ctx, body_for_arm)
    };

    match &first.pattern {
        Pattern::EmptyList => format!(
            "if {}.is_empty() {{ {} }} else {{ {} }}",
            subject_name, body, fallback
        ),
        Pattern::Cons(head, tail) => {
            let head_pat = if head == "_" {
                "_".to_string()
            } else {
                aver_name_to_rust(head)
            };
            let tail_pat = if tail == "_" {
                "_".to_string()
            } else {
                aver_name_to_rust(tail)
            };
            format!(
                "if let Some(({}, {})) = aver_rt::list_uncons_cloned(&{}) {{ {} }} else {{ {} }}",
                head_pat, tail_pat, subject_name, body, fallback
            )
        }
        Pattern::Wildcard => body,
        Pattern::Ident(name) => {
            let name = aver_name_to_rust(name);
            format!("{{ let {} = {}.clone(); {} }}", name, subject_name, body)
        }
        other => {
            let pat = emit_pattern(other, false, ctx);
            format!(
                "match &{} {{ {} => {{ {} }}, _ => {{ {} }} }}",
                subject_name, pat, body, fallback
            )
        }
    }
}

fn emit_list_arm_body(arm: &MatchArm, ctx: &CodegenContext, body: String) -> String {
    let rebindings = emit_pattern_rebindings(&arm.pattern, ctx);
    if rebindings.is_empty() {
        body
    } else {
        format!("{{ {}{} }}", rebindings, body)
    }
}

pub(super) fn constructor_boxed_positions(name: &str, ctx: &CodegenContext) -> HashSet<usize> {
    let sig = ctx.fn_sigs.get(name).or_else(|| {
        // Cross-module constructors: "Type.Variant" may be registered as
        // "Module.Type.Variant" in fn_sigs. Search by suffix.
        let suffix = format!(".{}", name);
        ctx.fn_sigs
            .iter()
            .find(|(k, _)| k.ends_with(&suffix))
            .map(|(_, v)| v)
    });
    let mut out = HashSet::new();
    let Some((params, ret, _)) = sig else {
        return out;
    };
    let Type::Named(ret_name) = ret else {
        return out;
    };
    for (idx, param) in params.iter().enumerate() {
        if let Type::Named(param_name) = param
            && param_name == ret_name
        {
            out.insert(idx);
        }
    }
    out
}

pub(super) fn constructor_boxed_bindings(
    name: &str,
    bindings: &[String],
    ctx: &CodegenContext,
) -> Vec<String> {
    let mut sig_name = None;
    if ctx.fn_sigs.contains_key(name) {
        sig_name = Some(name.to_string());
    } else {
        // Cross-module constructors: bare or dotted name may be registered
        // with a module prefix in fn_sigs. Search by suffix.
        let suffix = format!(".{}", name);
        let mut matches = ctx
            .fn_sigs
            .keys()
            .filter(|k| k.ends_with(&suffix))
            .cloned()
            .collect::<Vec<_>>();
        matches.sort();
        if matches.len() == 1 {
            sig_name = matches.into_iter().next();
        }
    }
    let Some(sig_name) = sig_name else {
        return Vec::new();
    };
    let boxed = constructor_boxed_positions(&sig_name, ctx);
    bindings
        .iter()
        .enumerate()
        .filter_map(|(idx, b)| {
            if b != "_" && boxed.contains(&idx) {
                Some(b.clone())
            } else {
                None
            }
        })
        .collect()
}

/// When matching on a reference (`&T`), pattern bindings are `&Inner`.
/// Emit `let b = b.clone();` for each binding to produce owned values.
fn emit_ref_match_rebindings(pattern: &Pattern) -> String {
    let bindings = pattern_bindings(pattern);
    if bindings.is_empty() {
        return String::new();
    }
    let mut lines = Vec::new();
    for b in &bindings {
        let rb = super::syntax::aver_name_to_rust(b);
        lines.push(format!("let {} = {}.clone();", rb, rb));
    }
    format!("{}\n            ", lines.join("\n            "))
}

fn emit_pattern_rebindings(pattern: &Pattern, ctx: &CodegenContext) -> String {
    let mut lines = Vec::new();
    if let Pattern::Constructor(name, bindings) = pattern {
        // Ok/Err/Some bindings are now moved (not ref), so no clone needed.
        // Only Box-wrapped fields (recursive types) need deref.
        for b in constructor_boxed_bindings(name, bindings, ctx) {
            let b = aver_name_to_rust(&b);
            lines.push(format!("let {} = (*{}).clone();", b, b));
        }
    }
    if lines.is_empty() {
        String::new()
    } else {
        format!("{}\n            ", lines.join("\n            "))
    }
}