cljrs-runtime 0.1.247

clojurust runtime: environment, builtins, tree-walking interpreter, and tiered evaluation
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
1845
//! Tier 1 IR interpreter: executes [`IrFunction`] over a VarId→Value register file.
//!
//! This replaces tree-walking of `Form` ASTs with interpretation of the
//! ANF IR.  Benefits:
//! - Escape analysis results are available (region allocation)
//! - Same IR feeds both interpretation and JIT compilation
//! - Optimization passes (constant folding, etc.) apply uniformly
//!
//! The interpreter maintains a dense register file (`Vec<Option<Value>>`)
//! indexed by `VarId`.  Control flow follows the block graph via
//! `Terminator`s.

use std::sync::Arc;

use cljrs_gc::GcPtr;
use cljrs_ir::{
    BlockId, ClosureTemplate, Const, Inst, IrFunction, KnownFn, RegionAllocKind, Terminator, VarId,
};
use cljrs_value::value::{MapValue, SetValue};
use cljrs_value::{
    CljxCons, CljxFn, NativeFn, PersistentHashSet, PersistentList, PersistentVector, Value,
};

use crate::env::apply::apply_value;
use crate::env::env::{Env, GlobalEnv};
use crate::env::error::{EvalError, EvalResult};
use crate::tiered::jit_state::{OsrPoll, OsrSlot};

// ── Register file ───────────────────────────────────────────────────────────

/// Dense register file indexed by `VarId`.
///
/// Uses `Box<[Option<Value>]>` rather than `Vec` so the heap address of the
/// slice data is stable after construction.  This lets us register the slice as
/// a GC root via `root_option_values` without worrying about reallocation
/// invalidating the stored raw pointer.
struct Registers {
    values: Box<[Option<Value>]>,
}

impl Registers {
    fn new(capacity: u32) -> Self {
        Self {
            values: vec![None; capacity as usize].into_boxed_slice(),
        }
    }

    fn get(&self, id: VarId) -> &Value {
        self.values[id.0 as usize]
            .as_ref()
            .unwrap_or_else(|| panic!("IR interpreter: uninitialized register {id}"))
    }

    fn set(&mut self, id: VarId, val: Value) {
        // Bounds check: VarIds are allocated sequentially up to ir_func.next_var,
        // so any out-of-range access indicates malformed IR.
        self.values[id.0 as usize] = Some(val);
    }

    fn get_cloned(&self, id: VarId) -> Value {
        self.get(id).clone()
    }
}

// ── Region state ────────────────────────────────────────────────────────────

/// A region entry in the interpreter's local region stack.
struct RegionEntry {
    /// `Some` until closed; taken by `Drop`.  The region is also pushed onto
    /// the cljrs_gc thread-local REGION_STACK via `push_region_raw`.
    region: Option<Box<cljrs_gc::region::Region>>,
}

impl Drop for RegionEntry {
    fn drop(&mut self) {
        if let Some(region) = self.region.take() {
            // Pops the thread-local stack entry, then resets the region — or
            // retires it if a publish barrier poisoned it (Phase 10.5
            // heap-promotion fallback).
            cljrs_gc::region::close_region(region);
        }
    }
}

/// Per-execution region state: the owned scope stack plus the handle map
/// binding region `VarId`s to their concrete regions.
///
/// The handle map is what makes `RegionAlloc(dst, region, …)` allocate into
/// the *named* region rather than blindly into the innermost open scope —
/// essential once a region-parameterised callee opens scopes of its own: an
/// alloc naming the inherited `RegionParam` must go into the caller's region
/// even while an inner scope is on top of the stack.  (Compiled code gets the
/// same semantics by passing the `*mut Region` handle to `rt_region_alloc_*`.)
#[derive(Default)]
struct RegionFrame {
    stack: Vec<RegionEntry>,
    /// `region VarId → live region` for every `RegionStart`/`RegionParam` in
    /// this frame.  Functions have at most a handful of region vars.
    handles: Vec<(VarId, *mut cljrs_gc::region::Region)>,
    /// The caller's region, when this frame is a region-parameterised callee
    /// entered via `CallWithRegion`.
    inherited: Option<*mut cljrs_gc::region::Region>,
}

impl RegionFrame {
    fn bind(&mut self, var: VarId, region: *mut cljrs_gc::region::Region) {
        self.handles.push((var, region));
    }

    fn lookup(&self, var: VarId) -> Option<*mut cljrs_gc::region::Region> {
        self.handles
            .iter()
            .rev()
            .find(|(v, _)| *v == var)
            .map(|&(_, r)| r)
    }
}

/// Allocate `val` into `target` when given, falling back to the innermost
/// thread-local region (then the GC heap).
fn region_alloc_val<T: cljrs_gc::Trace + 'static>(
    target: Option<*mut cljrs_gc::region::Region>,
    val: T,
) -> cljrs_gc::GcPtr<T> {
    match target {
        // SAFETY: handles are only bound to regions owned by a live
        // `RegionEntry` of this or a caller's frame.
        Some(region) => unsafe { (*region).alloc(val) },
        None => {
            if cljrs_gc::region::region_is_active() {
                unsafe { cljrs_gc::region::try_alloc_in_region(val).unwrap() }
            } else {
                GcPtr::new(val)
            }
        }
    }
}

// ── OSR (on-stack replacement) bookkeeping ──────────────────────────────────

/// Per-execution OSR state — Phase 10.4.
///
/// Allocated lazily on the first loop back-edge of an OSR-eligible execution
/// (a top-level arity dispatched through `execute_ir`), so straight-line
/// functions pay nothing.  Back-edge counts are local to one execution on
/// purpose: a loop that is hot *within a single call* is exactly the case
/// invocation-count tiering cannot promote; loops spread over many short
/// calls are already covered by the invocation counter.
struct OsrLocal {
    arity_id: u64,
    threshold: u32,
    /// Back-edge count per loop header (`BlockId.0`).
    counts: std::collections::HashMap<u32, u32>,
    /// Header we are waiting on: compilation requested (or already published),
    /// checked at each loop-header entry.
    polling: Option<BlockId>,
    /// Headers that must not be polled or re-requested in this execution
    /// (compilation failed, or a transfer was declined).
    dead: std::collections::HashSet<u32>,
}

/// Record one loop back-edge to `target`.  Crossing the threshold requests OSR
/// compilation (idempotent across executions via the global table).
fn record_back_edge(
    osr: &mut Option<Box<OsrLocal>>,
    arity_id: u64,
    target: BlockId,
    ir_func: &IrFunction,
    globals: &GlobalEnv,
) {
    let ol = osr.get_or_insert_with(|| {
        Box::new(OsrLocal {
            arity_id,
            threshold: crate::tiered::jit_state::osr_threshold().max(1),
            counts: std::collections::HashMap::new(),
            polling: None,
            dead: std::collections::HashSet::new(),
        })
    });
    if ol.polling == Some(target) || ol.dead.contains(&target.0) {
        return;
    }
    let count = {
        let c = ol.counts.entry(target.0).or_insert(0);
        *c += 1;
        *c
    };
    if count == 1 {
        // A previous execution may already have requested (or finished)
        // compilation of this loop — start polling right away.
        match globals.jit().osr_poll(arity_id, target.0) {
            OsrPoll::Ready(_) | OsrPoll::Pending => {
                ol.polling = Some(target);
                return;
            }
            OsrPoll::Failed => {
                ol.dead.insert(target.0);
                return;
            }
            OsrPoll::NotRequested => {}
        }
    }
    if count >= ol.threshold {
        globals.jit().osr_request(arity_id, target.0, ir_func);
        ol.polling = Some(target);
    }
}

/// Transfer this execution into compiled OSR-entry code: snapshot the live-in
/// registers, call the native entry, and hand back its result as the result of
/// the whole call.
///
/// Returns `None` (caller keeps interpreting) if any live-in register is not
/// yet initialized — a conservatively declined transfer, not an error.
fn try_osr_enter(slot: &OsrSlot, regs: &Registers, env: &mut Env) -> Option<EvalResult> {
    let mut call_args: Vec<Value> = Vec::with_capacity(slot.live_ins.len());
    for var in slot.live_ins.iter() {
        let v = regs.values.get(var.0 as usize).and_then(|v| v.as_ref())?;
        call_args.push(v.clone());
    }
    tracing::debug!(
        target: "jit",
        "osr entering native code ({} live-ins, epoch={})",
        call_args.len(),
        slot.epoch
    );

    // Same protocol as `call_jit_native` (apply.rs): keep the backing module
    // alive for the duration of the frame, root the caller env and the
    // snapshot, and track allocations made inside the native frame.
    let _jit_frame = crate::tiered::jit_state::push_jit_frame(slot.epoch);
    let _caller_root = crate::env::gc_roots::push_env_root(env);
    let _arg_roots = crate::env::gc_roots::root_values(&call_args);
    let _alloc_frame = cljrs_gc::push_alloc_frame();

    let arg_ptrs: Vec<*const Value> = call_args.iter().map(|v| v as *const Value).collect();
    // SAFETY: fn_ptr was produced by Cranelift JIT with the C ABI and exactly
    // `live_ins.len()` `*const Value` params (`build_osr_function` caps this at
    // the dispatch limit); all arg pointers are live for the call.
    let result_ptr = unsafe { crate::tiered::jit_state::dispatch_jit_call(slot.fn_ptr, &arg_ptrs) };
    // SAFETY: result_ptr points to a live Value in ALLOC_ROOTS; clone it
    // before the alloc frame drops.
    let result = unsafe { (*result_ptr).clone() };

    // Same as `call_jit_native`: an uncaught `(throw …)` inside native code
    // stashes the thrown value and returns the nil sentinel — surface it as an
    // error while the alloc frame still roots it.
    if let Some(thrown) = env.globals.jit().take_pending_exception() {
        return Some(Err(crate::env::error::EvalError::Thrown(thrown)));
    }
    Some(Ok(result))
}

// ── Public entry point ──────────────────────────────────────────────────────

/// Execute an IR function with the given arguments.
///
/// This is the Tier 1 execution path, called from `call_cljrs_fn` when
/// a cached `IrFunction` is available.
///
/// # Arguments
/// * `ir_func` — the IR function to execute
/// * `args` — argument values (positional, already matched to the arity)
/// * `globals` — the shared global environment
/// * `ns` — the namespace context for global lookups
/// * `env` — caller's Env (for calling back into `apply_value`)
pub fn interpret_ir(
    ir_func: &IrFunction,
    args: Vec<Value>,
    globals: &Arc<GlobalEnv>,
    ns: &Arc<str>,
    env: &mut Env,
) -> EvalResult {
    interpret_ir_with_osr(ir_func, args, globals, ns, env, None)
}

/// Like [`interpret_ir`], with OSR enabled when `osr_arity_id` is given.
///
/// `osr_arity_id` is the `ir_arity_id` under which loop back-edges are counted
/// and OSR-compiled entries are published.  Pass `None` (or use
/// [`interpret_ir`]) for executions that have no stable arity identity, e.g.
/// IR closures and region-parameterised subfunction calls.
pub fn interpret_ir_with_osr(
    ir_func: &IrFunction,
    args: Vec<Value>,
    globals: &Arc<GlobalEnv>,
    ns: &Arc<str>,
    env: &mut Env,
    osr_arity_id: Option<u64>,
) -> EvalResult {
    interpret_ir_inner(ir_func, args, globals, ns, env, osr_arity_id, None)
}

#[allow(clippy::too_many_arguments)]
fn interpret_ir_inner(
    ir_func: &IrFunction,
    args: Vec<Value>,
    globals: &Arc<GlobalEnv>,
    ns: &Arc<str>,
    env: &mut Env,
    osr_arity_id: Option<u64>,
    inherited_region: Option<*mut cljrs_gc::region::Region>,
) -> EvalResult {
    // GC safepoint at function entry.
    crate::env::gc_roots::gc_safepoint(env);

    let mut regs = Registers::new(ir_func.next_var);
    // Keep all values in the register file alive across GC safepoints.
    // The Box<[Option<Value>]> slice address is stable; this guard pops the
    // root entry when interpret_ir returns (or unwinds).
    let _regs_root = crate::env::gc_roots::root_option_values(&regs.values);
    let mut region_frame = RegionFrame {
        inherited: inherited_region,
        ..RegionFrame::default()
    };

    // Bind parameters to registers.
    for (i, (_name, var_id)) in ir_func.params.iter().enumerate() {
        if i < args.len() {
            regs.set(*var_id, args[i].clone());
        } else {
            regs.set(*var_id, Value::Nil);
        }
    }

    // Build a block index for O(1) lookup.
    // In the common case (dense sequential IDs), this is None and we use
    // block_id.0 directly as the index — no allocation at all.
    let block_index = ir_func.block_index();

    // Closure to resolve BlockId → index in ir_func.blocks.
    let resolve = |bid: &BlockId| -> usize {
        match &block_index {
            Some(table) => table[bid.0 as usize],
            None => bid.0 as usize,
        }
    };

    // Start at block 0.
    let mut current_block_idx: usize = 0;
    let mut prev_block_id = BlockId(u32::MAX); // sentinel

    // Lazily allocated OSR back-edge state (only for OSR-eligible executions
    // that actually take a loop back-edge).
    let mut osr: Option<Box<OsrLocal>> = None;

    loop {
        let block = &ir_func.blocks[current_block_idx];

        // Charge one weighted checkpoint per basic block.  Using the number
        // of IR operations keeps Tier 1 and generated native code on the same
        // approximate scale without putting a branch around every operation.
        let block_cost = (block.phis.len() + block.insts.len() + 1) as u64;
        if !crate::env::gas::charge(block_cost) {
            return Err(EvalError::GasExhausted);
        }

        // Resolve phi nodes based on predecessor.
        for phi in &block.phis {
            if let Inst::Phi(dst, entries) = phi {
                for (from_block, var_id) in entries {
                    if *from_block == prev_block_id {
                        regs.set(*dst, regs.get_cloned(*var_id));
                        break;
                    }
                }
            }
        }

        // OSR transfer: once a hot loop header's compilation has been
        // requested, check for published native code each time we re-enter the
        // header (i.e. after its phis — the loop variables — are resolved).
        if let Some(ol) = osr.as_deref_mut()
            && ol.polling == Some(block.id)
        {
            match globals.jit().osr_poll(ol.arity_id, block.id.0) {
                OsrPoll::Ready(slot) => {
                    // Regions opened before the loop stay open across the
                    // transfer (the OSR variant drops their RegionEnds) and
                    // are closed as usual when `region_stack` unwinds after
                    // the native call returns.
                    if let Some(result) = try_osr_enter(&slot, &regs, env) {
                        return result;
                    }
                    ol.polling = None;
                    ol.dead.insert(block.id.0);
                }
                OsrPoll::Failed => {
                    ol.polling = None;
                    ol.dead.insert(block.id.0);
                }
                _ => {}
            }
        }

        // Execute instructions.
        for inst in &block.insts {
            execute_inst(
                inst,
                &mut regs,
                &mut region_frame,
                ir_func,
                globals,
                ns,
                env,
            )?;
        }

        // Execute terminator.
        match &block.terminator {
            Terminator::Return(var_id) => {
                return Ok(regs.get_cloned(*var_id));
            }
            Terminator::Jump(target) => {
                prev_block_id = block.id;
                current_block_idx = resolve(target);
            }
            Terminator::Branch {
                cond,
                then_block,
                else_block,
            } => {
                prev_block_id = block.id;
                let cond_val = regs.get(*cond);
                let truthy = is_truthy(cond_val);
                let target = if truthy { then_block } else { else_block };
                current_block_idx = resolve(target);
            }
            Terminator::RecurJump { target, args: _ } => {
                // GC safepoint at loop back-edge.
                crate::env::gc_roots::gc_safepoint(env);

                // Loop back-edge counter: a hot header triggers background OSR
                // compilation; the transfer happens at the header entry above.
                if let Some(arity_id) = osr_arity_id {
                    record_back_edge(&mut osr, arity_id, *target, ir_func, globals);
                }

                // Jump to the target (loop header) block.
                // Phi nodes at the target block entry will resolve the new
                // loop variable values based on this block as predecessor.
                prev_block_id = block.id;
                current_block_idx = resolve(target);
            }
            Terminator::Unreachable => {
                return Err(EvalError::Runtime(
                    "IR interpreter: reached unreachable".to_string(),
                ));
            }
        }
    }
}

// ── Truthiness ──────────────────────────────────────────────────────────────

/// Clojure truthiness: everything is truthy except `nil` and `false`.
fn is_truthy(val: &Value) -> bool {
    !matches!(val, Value::Nil | Value::Bool(false))
}

// ── Instruction execution ───────────────────────────────────────────────────

fn execute_inst(
    inst: &Inst,
    regs: &mut Registers,
    regions: &mut RegionFrame,
    ir_func: &IrFunction,
    globals: &Arc<GlobalEnv>,
    ns: &Arc<str>,
    env: &mut Env,
) -> EvalResult<()> {
    match inst {
        Inst::Const(dst, c) => {
            regs.set(*dst, const_to_value(c));
        }

        Inst::LoadLocal(dst, name) => {
            // Look up in the caller's environment (captures, locals).
            let val = env
                .lookup(name)
                .ok_or_else(|| {
                    EvalError::Runtime(format!("IR interpreter: unbound local '{name}'"))
                })?
                .clone();
            regs.set(*dst, val);
        }

        Inst::LoadGlobal(dst, gns, name) => {
            let val = load_global_value(globals, gns, name, ns)?;
            regs.set(*dst, val);
        }

        Inst::LoadVar(dst, gns, name) => {
            let resolved_ns = globals
                .resolve_alias(ns, gns)
                .unwrap_or_else(|| Arc::from(&**gns));
            let var = globals
                .lookup_var_in_ns(&resolved_ns, name)
                .ok_or_else(|| {
                    EvalError::Runtime(format!(
                        "IR interpreter: var not found {resolved_ns}/{name}"
                    ))
                })?;
            regs.set(*dst, Value::Var(var));
        }

        Inst::AllocVector(dst, elems) => {
            let items: Vec<Value> = elems.iter().map(|v| regs.get_cloned(*v)).collect();
            let pv = PersistentVector::from_iter(items);
            regs.set(*dst, Value::Vector(GcPtr::new(pv)));
        }

        Inst::AllocMap(dst, pairs) => {
            let kv: Vec<(Value, Value)> = pairs
                .iter()
                .map(|(k, v)| (regs.get_cloned(*k), regs.get_cloned(*v)))
                .collect();
            regs.set(*dst, Value::Map(MapValue::from_pairs(kv)));
        }

        Inst::AllocSet(dst, elems) => {
            let items: Vec<Value> = elems.iter().map(|v| regs.get_cloned(*v)).collect();
            let set = PersistentHashSet::from_iter(items);
            regs.set(*dst, Value::Set(SetValue::Hash(GcPtr::new(set))));
        }

        Inst::AllocList(dst, elems) => {
            let items: Vec<Value> = elems.iter().map(|v| regs.get_cloned(*v)).collect();
            regs.set(
                *dst,
                Value::List(GcPtr::new(PersistentList::from_iter(items))),
            );
        }

        Inst::AllocCons(dst, head, tail) => {
            let h = regs.get_cloned(*head);
            let t = regs.get_cloned(*tail);
            regs.set(*dst, Value::Cons(GcPtr::new(CljxCons { head: h, tail: t })));
        }

        Inst::AllocClosure(dst, template, captures) => {
            let val = alloc_closure(template, captures, regs, ir_func, globals, ns)?;
            regs.set(*dst, val);
        }

        Inst::CallKnown(dst, known_fn, args) => {
            // GC safepoint before call.
            crate::env::gc_roots::gc_safepoint(env);
            let arg_vals: Vec<Value> = args.iter().map(|v| regs.get_cloned(*v)).collect();
            let result = dispatch_known_fn(known_fn, arg_vals, env)?;
            regs.set(*dst, result);
        }

        Inst::Call(dst, callee, args) => {
            crate::env::gc_roots::gc_safepoint(env);
            let callee_val = regs.get_cloned(*callee);
            let arg_vals: Vec<Value> = args.iter().map(|v| regs.get_cloned(*v)).collect();
            let result = dispatch_or_sentinel(callee_val, arg_vals, globals, ns, env)?;
            regs.set(*dst, result);
        }

        Inst::CallDirect(dst, name, args) => {
            crate::env::gc_roots::gc_safepoint(env);
            let arg_vals: Vec<Value> = args.iter().map(|v| regs.get_cloned(*v)).collect();
            let result = dispatch_sentinel_by_name(name, arg_vals, globals, ns, env)?;
            regs.set(*dst, result);
        }

        Inst::Deref(dst, src) => {
            let val = regs.get_cloned(*src);
            let derefed = crate::interp::eval::deref_value(val)?;
            regs.set(*dst, derefed);
        }

        Inst::DefVar(dst, def_ns, name, val_var) => {
            // Always create a fresh, call-local Var (not registered in globals).
            // The ANF compiler uses DefVar as a mutable cell for letfn / named-fn
            // self-recursion; the cell is accessed only via the register returned
            // here, never via LoadGlobal, so name collisions with real globals are
            // harmless and we never need to touch the global namespace.
            let val = regs.get_cloned(*val_var);
            let fresh = cljrs_value::Var::new(def_ns.clone(), name.clone());
            fresh.bind(val);
            regs.set(*dst, Value::Var(GcPtr::new(fresh)));
        }

        Inst::SetBang(var_id, val_id) => {
            let var_val = regs.get(*var_id);
            let new_val = regs.get_cloned(*val_id);
            if let Value::Var(var) = var_val {
                // Try dynamic binding first, then root.
                if !crate::env::dynamics::set_thread_local(var, new_val.clone()) {
                    var.get().bind(new_val);
                }
            } else {
                return Err(EvalError::Runtime("set! target is not a Var".to_string()));
            }
        }

        Inst::Throw(val_id) => {
            let val = regs.get_cloned(*val_id);
            return Err(EvalError::Thrown(val));
        }

        Inst::Phi(..) => {
            // Phis are resolved at block entry, not here.
        }

        Inst::Recur(args) => {
            let vals: Vec<Value> = args.iter().map(|v| regs.get_cloned(*v)).collect();
            return Err(EvalError::Recur(vals));
        }

        Inst::SourceLoc(_span) => {
            // No-op — could update a "current span" for error reporting.
        }

        // ── Region allocation ───────────────────────────────────────────
        Inst::RegionStart(dst) => {
            let mut region = Box::new(cljrs_gc::region::Region::new());
            let region_ptr: *mut cljrs_gc::region::Region = &mut *region;
            unsafe { cljrs_gc::region::push_region_raw(region_ptr) };
            regions.stack.push(RegionEntry {
                region: Some(region),
            });
            regions.bind(*dst, region_ptr);
            regs.set(*dst, Value::Nil);
        }

        Inst::RegionAlloc(dst, region, kind, operands) => {
            let val = alloc_in_region(*kind, operands, regs, regions.lookup(*region))?;
            regs.set(*dst, val);
        }

        Inst::RegionEnd(_region) => {
            // Pop and drop the region entry (Drop impl handles cleanup).
            regions.stack.pop();
        }

        Inst::RegionParam(dst) => {
            // Bind the caller's region (threaded through `CallWithRegion`) so
            // `RegionAlloc`s naming this handle allocate into it even when
            // this frame opens scopes of its own.  The register itself holds
            // nil — region handles are not first-class values here.
            if let Some(region) = regions.inherited {
                regions.bind(*dst, region);
            }
            regs.set(*dst, Value::Nil);
        }

        Inst::CallWithRegion(dst, name, args, region) => {
            crate::env::gc_roots::gc_safepoint(env);
            let target = ir_func
                .subfunctions
                .iter()
                .find(|sf| sf.name.as_deref() == Some(name.as_ref()))
                .ok_or_else(|| {
                    EvalError::Runtime(format!(
                        "IR interpreter: CallWithRegion target {name} not found in subfunctions"
                    ))
                })?;
            let arg_vals: Vec<Value> = args.iter().map(|v| regs.get_cloned(*v)).collect();
            // Thread our region handle into the callee so its inherited
            // `RegionParam` allocations land in *this* region — by name, not
            // by stack position (the callee may open scopes of its own).
            let result = interpret_ir_inner(
                target,
                arg_vals,
                globals,
                ns,
                env,
                None,
                regions.lookup(*region),
            )?;
            regs.set(*dst, result);
        }

        // ── Async instructions ───────────────────────────────────────────
        //
        // Async IR functions are routed to tree-walking eval_async (via the
        // `try_ir_path` bypass in apply.rs), so these arms are rarely reached
        // in practice.  They provide a graceful sync-context fallback for the
        // cases where they are reached (e.g. in tests or non-async callers).
        Inst::Await { src, dst } => {
            // Sync fallback: block the OS thread until the future/promise resolves.
            let val = regs.get_cloned(*src);
            let resolved = crate::interp::eval::deref_value(val)?;
            regs.set(*dst, resolved);
        }

        Inst::Spawn { fn_reg, args, dst } => {
            // Dispatch through the async runtime hook if available; otherwise error.
            let callee = regs.get_cloned(*fn_reg);
            let arg_vals: Vec<Value> = args.iter().map(|v| regs.get_cloned(*v)).collect();
            let result = if let Some(rt) = globals.async_runtime() {
                // Build a minimal env carrying globals; run_async_fn will construct
                // the closure env from the callee's captured bindings.
                let spawn_env = Env::new(globals.clone(), ns);
                rt.spawn_async_call(callee, arg_vals, spawn_env)
            } else {
                return Err(EvalError::Runtime(
                    "IR interpreter: Spawn instruction requires async runtime (cljrs-async)".into(),
                ));
            };
            regs.set(*dst, result);
        }

        Inst::ChanTake { chan, dst } => {
            let chan_val = regs.get_cloned(*chan);
            let result = if let Some(rt) = globals.async_runtime() {
                rt.chan_take_blocking(chan_val)?
            } else {
                return Err(EvalError::Runtime(
                    "IR interpreter: ChanTake requires async runtime (cljrs-async)".into(),
                ));
            };
            regs.set(*dst, result);
        }

        Inst::ChanPut { chan, val } => {
            let chan_val = regs.get_cloned(*chan);
            let put_val = regs.get_cloned(*val);
            if let Some(rt) = globals.async_runtime() {
                rt.chan_put_blocking(chan_val, put_val)?;
            } else {
                return Err(EvalError::Runtime(
                    "IR interpreter: ChanPut requires async runtime (cljrs-async)".into(),
                ));
            }
        }

        // State-machine instructions only ever appear in a compiled poll
        // function (`is_async_poll_fn`); the Tier-1 interpreter never runs one
        // (async arities are dispatched through `eval_async` or the compiled
        // state machine, never lowered to a poll-fn for interpretation).
        Inst::StateStore { .. }
        | Inst::StateLoad { .. }
        | Inst::AsyncSuspend { .. }
        | Inst::AsyncResume { .. } => {
            return Err(EvalError::Runtime(
                "IR interpreter: async state-machine instructions are compile-only".into(),
            ));
        }
    }

    Ok(())
}

// ── Constant conversion ─────────────────────────────────────────────────────

fn const_to_value(c: &Const) -> Value {
    match c {
        Const::Nil => Value::Nil,
        Const::Bool(b) => Value::Bool(*b),
        Const::Long(n) => Value::Long(*n),
        Const::Double(d) => Value::Double(*d),
        Const::Str(s) => Value::Str(GcPtr::new(s.to_string())),
        Const::Keyword(k) => Value::Keyword(GcPtr::new(cljrs_value::keyword::Keyword::parse(k))),
        Const::Symbol(s) => Value::symbol(cljrs_value::Symbol::simple(s.clone())),
        Const::Char(c) => Value::Char(*c),
    }
}

// ── Global value lookup ─────────────────────────────────────────────────────

fn load_global_value(
    globals: &Arc<GlobalEnv>,
    ns: &str,
    name: &str,
    defining_ns: &str,
) -> EvalResult {
    // Versioned reference (`name@hash`): resolve through the shared service,
    // which lazily loads the immutable `ns@hash` namespace and looks up the
    // base name in it (with the native HEAD fallback).
    #[cfg(not(target_arch = "wasm32"))]
    if let (base_name, Some(commit)) = cljrs_value::symbol::split_version(name) {
        return crate::env::versioned::resolve_versioned_value(
            globals,
            defining_ns,
            Some(ns),
            base_name,
            commit,
        );
    }

    // Try direct namespace lookup first, then resolve as alias.
    let resolved_ns = globals
        .resolve_alias(defining_ns, ns)
        .unwrap_or_else(|| Arc::from(ns));

    if let Some(var) = globals.lookup_var_in_ns(&resolved_ns, name) {
        if let Some(val) = crate::env::dynamics::deref_var(&var) {
            return Ok(val);
        }
        return Err(EvalError::Runtime(format!(
            "IR interpreter: unbound var {resolved_ns}/{name}"
        )));
    }

    // Reference into a versioned namespace (`lib@hash`/name) that has not
    // been loaded this session: load it lazily and retry the lookup.
    #[cfg(not(target_arch = "wasm32"))]
    if let (base, Some(commit)) = cljrs_value::symbol::split_version(&resolved_ns)
        && !globals.is_loaded(&resolved_ns)
    {
        crate::env::versioned::ensure_versioned_ns_loaded(globals, base, commit)?;
        if let Some(var) = globals.lookup_var_in_ns(&resolved_ns, name)
            && let Some(val) = crate::env::dynamics::deref_var(&var)
        {
            return Ok(val);
        }
    }

    // Slash-named builtins (`Math/abs`, `Math/PI`, …) are registered in
    // clojure.core under their full `Class/member` name; the lowerer's
    // split_sym split them into (ns="Math", name="abs").  Mirror
    // eval_symbol's whole-symbol lookup (which reaches clojure.core through
    // the namespace's refers) before giving up.
    if let Some(val) = globals.lookup_in_ns(defining_ns, &format!("{ns}/{name}")) {
        return Ok(val);
    }

    // JVM class names resolve to themselves as symbols, mirroring eval_symbol.
    if crate::interp::eval::is_jvm_class_name(name) {
        return Ok(Value::symbol(cljrs_value::Symbol::simple(name)));
    }
    Err(EvalError::Runtime(format!(
        "IR interpreter: var not found {resolved_ns}/{name}"
    )))
}

// ── Region-aware allocation ─────────────────────────────────────────────────

fn alloc_in_region(
    kind: RegionAllocKind,
    operands: &[VarId],
    regs: &Registers,
    target: Option<*mut cljrs_gc::region::Region>,
) -> EvalResult {
    match kind {
        RegionAllocKind::Vector => {
            let items: Vec<Value> = operands.iter().map(|v| regs.get_cloned(*v)).collect();
            let pv = PersistentVector::from_iter(items);
            Ok(Value::Vector(region_alloc_val(target, pv)))
        }
        RegionAllocKind::Map => {
            // Operands are flattened [k, v, k, v, ...].
            let kv: Vec<(Value, Value)> = operands
                .chunks(2)
                .map(|pair| (regs.get_cloned(pair[0]), regs.get_cloned(pair[1])))
                .collect();
            Ok(Value::Map(MapValue::from_pairs(kv)))
        }
        RegionAllocKind::Set => {
            let items: Vec<Value> = operands.iter().map(|v| regs.get_cloned(*v)).collect();
            let set = PersistentHashSet::from_iter(items);
            Ok(Value::Set(SetValue::Hash(GcPtr::new(set))))
        }
        RegionAllocKind::List => {
            let items: Vec<Value> = operands.iter().map(|v| regs.get_cloned(*v)).collect();
            let list = PersistentList::from_iter(items);
            Ok(Value::List(region_alloc_val(target, list)))
        }
        RegionAllocKind::Cons => {
            if operands.len() == 2 {
                let h = regs.get_cloned(operands[0]);
                let t = regs.get_cloned(operands[1]);
                let cons = CljxCons { head: h, tail: t };
                Ok(Value::Cons(region_alloc_val(target, cons)))
            } else {
                Ok(Value::Nil)
            }
        }
    }
}

// ── Closure construction ────────────────────────────────────────────────────

fn alloc_closure(
    template: &ClosureTemplate,
    capture_vars: &[VarId],
    regs: &Registers,
    ir_func: &IrFunction,
    globals: &Arc<GlobalEnv>,
    ns: &Arc<str>,
) -> EvalResult {
    let captured_values: Vec<Value> = capture_vars.iter().map(|v| regs.get_cloned(*v)).collect();

    // Build a CljxFn-like wrapper using NativeFunction.
    // Each arity maps to a named subfunction in ir_func.subfunctions.
    // We use arity_fn_names (when present) to match each arity slot to its
    // correct subfunction by name, rather than relying on positional indexing.
    // Positional indexing is wrong when the parent function has more
    // subfunctions than arities (e.g. fnil has two inner lambdas but the
    // returned closure is only the second one).
    let subfuncs: Vec<Arc<IrFunction>> = if !template.arity_fn_names.is_empty() {
        template
            .arity_fn_names
            .iter()
            .map(|fn_name| {
                let sf = ir_func
                    .subfunctions
                    .iter()
                    .find(|sf| sf.name.as_deref() == Some(fn_name.as_ref()))
                    .unwrap_or_else(|| {
                        ir_func.subfunctions.first().unwrap_or_else(|| {
                            panic!("IR closure: no subfunctions for '{fn_name}'")
                        })
                    });
                Arc::new(clone_ir_function(sf))
            })
            .collect()
    } else {
        ir_func
            .subfunctions
            .iter()
            .map(clone_ir_function)
            .map(Arc::new)
            .collect()
    };

    let param_counts = template.param_counts.clone();
    let is_variadic = template.is_variadic.clone();
    let fn_name = template.name.clone();
    let closure_ns = ns.clone();
    let closure_globals = globals.clone();

    // Create a native function that dispatches to the IR interpreter.
    let nf = NativeFn {
        name: fn_name.as_deref().unwrap_or("<ir-closure>").into(),
        arity: if param_counts.len() == 1 && !is_variadic[0] {
            cljrs_value::Arity::Fixed(param_counts[0])
        } else {
            cljrs_value::Arity::Variadic {
                min: param_counts.iter().copied().min().unwrap_or(0),
            }
        },
        func: Arc::new({
            let captured_values = captured_values.clone();
            let subfuncs = subfuncs.clone();
            let param_counts = param_counts.clone();
            let is_variadic = is_variadic.clone();
            let closure_globals = closure_globals.clone();
            let closure_ns = closure_ns.clone();
            move |call_args: &[Value]| {
                // Select the right arity.
                let nargs = call_args.len();
                let mut best_idx = None;
                for (i, &pc) in param_counts.iter().enumerate() {
                    if is_variadic[i] && nargs >= pc {
                        // Variadic: accept pc or more.
                        match best_idx {
                            None => best_idx = Some(i),
                            Some(prev) => {
                                if pc > param_counts[prev] {
                                    best_idx = Some(i);
                                }
                            }
                        }
                    } else if !is_variadic[i] && nargs == pc {
                        best_idx = Some(i);
                        break;
                    }
                }

                let idx = best_idx.ok_or_else(|| {
                    cljrs_value::ValueError::Other(format!(
                        "Wrong number of args ({nargs}) passed to IR closure"
                    ))
                })?;

                let subfunc = &subfuncs[idx];

                // Build full args: captures + call_args (+ rest list for variadic).
                let mut full_args = captured_values.clone();
                if is_variadic[idx] {
                    let pc = param_counts[idx];
                    // Fixed params.
                    for a in call_args[..pc.min(nargs)].iter() {
                        full_args.push(a.clone());
                    }
                    // Rest as a list.
                    let rest: Vec<Value> = if nargs > pc {
                        call_args[pc..].to_vec()
                    } else {
                        Vec::new()
                    };
                    full_args.push(Value::List(GcPtr::new(PersistentList::from_iter(rest))));
                } else {
                    full_args.extend_from_slice(call_args);
                }

                // Call back into the interpreter via callback::invoke infrastructure.
                // We need an Env, which we get from the callback context.
                let result = crate::env::callback::with_eval_context(|env| {
                    interpret_ir(subfunc, full_args, &closure_globals, &closure_ns, env)
                });
                match result {
                    Ok(v) => Ok(v),
                    Err(EvalError::Runtime(msg)) => Err(cljrs_value::ValueError::Other(msg)),
                    Err(EvalError::Thrown(v)) => Err(cljrs_value::ValueError::Thrown(v)),
                    Err(EvalError::Recur(vals)) => Err(cljrs_value::ValueError::Other(format!(
                        "recur from non-tail position ({} values)",
                        vals.len()
                    ))),
                    Err(other) => Err(cljrs_value::ValueError::Other(format!("{other}"))),
                }
            }
        }),
    };

    Ok(Value::NativeFunction(GcPtr::new(nf)))
}

/// Deep clone an IrFunction (it doesn't implement Clone due to Debug derive).
fn clone_ir_function(f: &IrFunction) -> IrFunction {
    IrFunction {
        name: f.name.clone(),
        params: f.params.clone(),
        blocks: f.blocks.clone(),
        next_var: f.next_var,
        next_block: f.next_block,
        span: f.span.clone(),
        subfunctions: f.subfunctions.iter().map(clone_ir_function).collect(),
        is_async: f.is_async,
        is_async_poll_fn: f.is_async_poll_fn,
        async_resume_blocks: f.async_resume_blocks.clone(),
        seed_reprs: f.seed_reprs.clone(),
        local_seed_reprs: f.local_seed_reprs.clone(),
    }
}

// ── Sentinel-aware call dispatch ────────────────────────────────────────────

/// Dispatch a generic callee value, intercepting sentinel `NativeFunction`s.
///
/// Several clojure.core entries (volatile!, vswap!, make-delay, etc.) are
/// sentinel stubs that unconditionally error when called normally — the real
/// work happens in `eval_call`'s special-form dispatch, which the IR
/// interpreter bypasses.  We intercept those by name here so that IR code
/// calling them works correctly.
fn dispatch_or_sentinel(
    callee: Value,
    args: Vec<Value>,
    globals: &Arc<GlobalEnv>,
    ns: &Arc<str>,
    env: &mut Env,
) -> EvalResult {
    if let Value::NativeFunction(nf) = &callee
        && is_sentinel(nf.get().name.as_ref())
    {
        return dispatch_sentinel_by_name(nf.get().name.as_ref(), args, globals, ns, env);
    }
    apply_value(&callee, args, env)
}

/// Dispatch a call to a sentinel operation by name, or fall through to a
/// global lookup + `apply_value` for non-sentinel names.
fn dispatch_sentinel_by_name(
    name: &str,
    args: Vec<Value>,
    globals: &Arc<GlobalEnv>,
    ns: &Arc<str>,
    env: &mut Env,
) -> EvalResult {
    // `(.method target args…)` interop: the lowerer emits these as
    // `CallDirect` with the dot-prefixed method name (see `lower_list` in
    // cljrs-ir).  Route to the tree-walker's method dispatch — args[0] is
    // the target object.
    if let Some(method) = name.strip_prefix('.')
        && !method.is_empty()
    {
        let Some((target, rest)) = args.split_first() else {
            return Err(EvalError::Runtime(format!(
                ".{method} requires a target object"
            )));
        };
        return crate::interp::apply::dispatch_method(method, target, rest);
    }
    match name {
        "volatile!" => crate::interp::apply::eval_volatile(args),
        "reset!" => crate::interp::apply::eval_reset_bang(args, env),
        "vreset!" => crate::interp::apply::eval_vreset_bang(args),
        "vswap!" => crate::interp::apply::eval_vswap_bang(args, env),
        "make-delay" => {
            let f = args.into_iter().next().ok_or_else(|| EvalError::Arity {
                name: "make-delay".into(),
                expected: "1".into(),
                got: 0,
            })?;
            crate::interp::apply::make_delay_from_fn(&f, globals.clone(), ns.clone())
        }
        "alter-var-root" => crate::interp::apply::eval_alter_var_root(args, env),
        "vary-meta" => crate::interp::apply::eval_vary_meta(args, env),
        "with-bindings*" => crate::interp::apply::eval_with_bindings_star(args, env),
        "send" | "send-off" => crate::interp::apply::eval_send_to_agent(args, env),
        _ => {
            let callee = load_global_value(globals, ns, name, ns)?;
            apply_value(&callee, args, env)
        }
    }
}

fn is_sentinel(name: &str) -> bool {
    matches!(
        name,
        "volatile!"
            | "reset!"
            | "vreset!"
            | "vswap!"
            | "make-delay"
            | "alter-var-root"
            | "vary-meta"
            | "with-bindings*"
            | "send"
            | "send-off"
    )
}

// ── KnownFn dispatch ────────────────────────────────────────────────────────

/// Dispatch a call to a known built-in function.
///
/// This maps each `KnownFn` variant to the corresponding Rust builtin
/// from `builtins.rs`, or falls back to `apply_value` for complex cases.
fn dispatch_known_fn(known_fn: &KnownFn, args: Vec<Value>, env: &mut Env) -> EvalResult {
    match known_fn {
        // ── Arithmetic ──────────────────────────────────────────────────
        KnownFn::Add => builtin_arith(&args, "+"),
        KnownFn::Sub => builtin_arith(&args, "-"),
        KnownFn::Mul => builtin_arith(&args, "*"),
        KnownFn::Div => builtin_arith(&args, "/"),
        KnownFn::Rem => builtin_arith(&args, "rem"),
        KnownFn::UncheckedAdd => builtin_arith(&args, "unchecked-add"),
        KnownFn::UncheckedSub => builtin_arith(&args, "unchecked-subtract"),
        KnownFn::UncheckedMul => builtin_arith(&args, "unchecked-multiply"),

        // ── Comparison ──────────────────────────────────────────────────
        KnownFn::Eq => Ok(Value::Bool(args.len() == 2 && args[0] == args[1])),
        KnownFn::CaseEq => {
            if args.len() != 2 {
                return Ok(Value::Bool(false));
            }
            let a = args[0].unwrap_meta();
            let b = args[1].unwrap_meta();
            let result = match (a, b) {
                (Value::Long(_) | Value::BigInt(_), Value::Long(_) | Value::BigInt(_)) => {
                    args[0] == args[1]
                }
                (Value::Double(_), Value::Double(_)) => args[0] == args[1],
                (Value::BigDecimal(_), Value::BigDecimal(_)) => args[0] == args[1],
                (Value::Ratio(_), Value::Ratio(_)) => args[0] == args[1],
                (
                    Value::Long(_)
                    | Value::BigInt(_)
                    | Value::Double(_)
                    | Value::BigDecimal(_)
                    | Value::Ratio(_),
                    Value::Long(_)
                    | Value::BigInt(_)
                    | Value::Double(_)
                    | Value::BigDecimal(_)
                    | Value::Ratio(_),
                ) => false,
                _ => args[0] == args[1],
            };
            Ok(Value::Bool(result))
        }
        KnownFn::Lt | KnownFn::Gt | KnownFn::Lte | KnownFn::Gte => builtin_compare(known_fn, &args),
        KnownFn::Identical => Ok(Value::Bool(
            args.len() == 2 && std::ptr::eq(&args[0] as *const _, &args[1] as *const _),
        )),

        // ── Type predicates ─────────────────────────────────────────────
        KnownFn::IsNil => Ok(Value::Bool(matches!(args.first(), Some(Value::Nil)))),
        KnownFn::IsSeq => Ok(Value::Bool(matches!(
            args.first(),
            Some(Value::List(_) | Value::Cons(_) | Value::LazySeq(_))
        ))),
        KnownFn::IsVector => Ok(Value::Bool(matches!(
            args.first().map(Value::unwrap_meta),
            Some(Value::Vector(_))
        ))),
        KnownFn::IsMap => Ok(Value::Bool(matches!(
            args.first().map(Value::unwrap_meta),
            Some(Value::Map(_))
        ))),
        KnownFn::IsNumber => Ok(Value::Bool(matches!(
            args.first(),
            Some(
                Value::Long(_)
                    | Value::Double(_)
                    | Value::BigInt(_)
                    | Value::Ratio(_)
                    | Value::BigDecimal(_)
            )
        ))),
        KnownFn::IsString => Ok(Value::Bool(matches!(args.first(), Some(Value::Str(_))))),
        KnownFn::IsKeyword => Ok(Value::Bool(matches!(args.first(), Some(Value::Keyword(_))))),
        KnownFn::IsSymbol => Ok(Value::Bool(matches!(args.first(), Some(Value::Symbol(_))))),
        KnownFn::IsBool => Ok(Value::Bool(matches!(args.first(), Some(Value::Bool(_))))),
        KnownFn::IsInt => Ok(Value::Bool(matches!(args.first(), Some(Value::Long(_))))),

        // ── String ──────────────────────────────────────────────────────
        KnownFn::Str => {
            let s: String = args
                .iter()
                .map(|v| match v {
                    Value::Nil => String::new(),
                    Value::Str(s) => s.get().to_string(),
                    Value::Char(c) => c.to_string(),
                    other => format!("{}", cljrs_value::value::PrintValue(other)),
                })
                .collect();
            Ok(Value::Str(GcPtr::new(s)))
        }

        // ── Collection construction ─────────────────────────────────────
        KnownFn::Vector => Ok(Value::Vector(GcPtr::new(PersistentVector::from_iter(args)))),
        KnownFn::HashMap => {
            let pairs: Vec<(Value, Value)> = args
                .chunks(2)
                .map(|c| (c[0].clone(), c.get(1).cloned().unwrap_or(Value::Nil)))
                .collect();
            Ok(Value::Map(MapValue::from_pairs(pairs)))
        }
        KnownFn::HashSet => Ok(Value::Set(SetValue::Hash(GcPtr::new(
            PersistentHashSet::from_iter(args),
        )))),
        KnownFn::List => Ok(Value::List(GcPtr::new(PersistentList::from_iter(args)))),

        // ── Collection operations ───────────────────────────────────────
        KnownFn::Get => {
            let result = builtin_call_native("get", &args)?;
            Ok(result)
        }
        KnownFn::Nth => builtin_call_native("nth", &args),
        KnownFn::NthLenient => {
            // Destructuring nth: out-of-bounds yields nil, never throws.  The
            // 3-arg `nth` returns its default (nil here) for a short collection.
            let mut args = args;
            args.push(Value::Nil);
            builtin_call_native("nth", &args)
        }
        KnownFn::Aget => builtin_call_native("aget", &args),
        KnownFn::Aset => builtin_call_native("aset", &args),
        KnownFn::Alength => builtin_call_native("alength", &args),
        KnownFn::Count => builtin_call_native("count", &args),
        KnownFn::CountFilter => {
            // Synthesized fused op == (count (filter pred coll)).
            let filter_fn = load_builtin(env, "filter")?;
            let seq = apply_value(&filter_fn, args, env)?;
            builtin_call_native("count", &[seq])
        }
        KnownFn::IntoFilter | KnownFn::IntoMapcat | KnownFn::IntoMap => {
            // Synthesized fused ops == (into to (filter|mapcat|map f coll)).
            let hof = match known_fn {
                KnownFn::IntoFilter => "filter",
                KnownFn::IntoMapcat => "mapcat",
                _ => "map",
            };
            let mut args = args;
            let to = args.remove(0);
            let hof_fn = load_builtin(env, hof)?;
            let seq = apply_value(&hof_fn, args, env)?;
            let into_fn = load_builtin(env, "into")?;
            apply_value(&into_fn, vec![to, seq], env)
        }
        KnownFn::Contains => builtin_call_native("contains?", &args),
        KnownFn::Assoc => builtin_call_native("assoc", &args),
        KnownFn::Dissoc => builtin_call_native("dissoc", &args),
        KnownFn::Conj => builtin_call_native("conj", &args),
        KnownFn::Disj => builtin_call_native("disj", &args),
        KnownFn::First => builtin_call_native("first", &args),
        KnownFn::Rest => builtin_call_native("rest", &args),
        KnownFn::Next => builtin_call_native("next", &args),
        KnownFn::Cons => builtin_call_native("cons", &args),
        KnownFn::Seq => builtin_call_native("seq", &args),
        KnownFn::Keys => builtin_call_native("keys", &args),
        KnownFn::Vals => builtin_call_native("vals", &args),
        KnownFn::Merge => builtin_call_native("merge", &args),
        KnownFn::Update => builtin_call_native("update", &args),
        KnownFn::GetIn => builtin_call_native("get-in", &args),
        KnownFn::AssocIn => builtin_call_native("assoc-in", &args),
        KnownFn::Concat => builtin_call_native("concat", &args),
        KnownFn::Reverse => builtin_call_native("reverse", &args),
        KnownFn::Frequencies => builtin_call_native("frequencies", &args),
        KnownFn::Zipmap => builtin_call_native("zipmap", &args),

        // ── Transient operations ────────────────────────────────────────
        KnownFn::Transient => builtin_call_native("transient", &args),
        KnownFn::AssocBang => builtin_call_native("assoc!", &args),
        KnownFn::ConjBang => builtin_call_native("conj!", &args),
        KnownFn::PersistentBang => builtin_call_native("persistent!", &args),

        // ── Sequence operations ─────────────────────────────────────────
        KnownFn::Take => builtin_call_native("take", &args),
        KnownFn::Drop => builtin_call_native("drop", &args),
        KnownFn::Range1 | KnownFn::Range2 | KnownFn::Range3 => builtin_call_native("range", &args),
        KnownFn::LazySeq => {
            // `(lazy-seq f)` wraps a zero-arg Clojure fn in a LazySeq.  The
            // builtin `make-lazy-seq` registered in clojure.core is a
            // sentinel that intentionally errors (it's only callable
            // through eval_call's special dispatch); from the IR
            // interpreter we need to construct the LazySeq directly.
            if let Some(f) = args.first() {
                crate::env::callback::with_eval_context(|env| {
                    crate::interp::apply::make_lazy_seq_from_fn(
                        f,
                        env.globals.clone(),
                        env.current_ns.clone(),
                    )
                })
            } else {
                Ok(Value::Nil)
            }
        }

        // ── Atom operations ─────────────────────────────────────────────
        KnownFn::Atom => builtin_call_native("atom", &args),
        KnownFn::Deref | KnownFn::AtomDeref => {
            if let Some(v) = args.into_iter().next() {
                crate::interp::eval::deref_value(v)
            } else {
                Ok(Value::Nil)
            }
        }
        KnownFn::AtomReset => crate::interp::apply::eval_reset_bang(args, env),
        KnownFn::AtomSwap => crate::interp::apply::eval_swap_bang(args, env),

        // ── I/O ─────────────────────────────────────────────────────────
        KnownFn::Println => builtin_call_native("println", &args),
        KnownFn::Pr => builtin_call_native("pr", &args),
        KnownFn::Prn => builtin_call_native("prn", &args),
        KnownFn::Print => builtin_call_native("print", &args),

        // ── HOFs (need env for callbacks) ───────────────────────────────
        KnownFn::Map
        | KnownFn::Filter
        | KnownFn::Mapv
        | KnownFn::Filterv
        | KnownFn::Reduce2
        | KnownFn::Reduce3
        | KnownFn::Some
        | KnownFn::Every
        | KnownFn::Into
        | KnownFn::Into3
        | KnownFn::Sort
        | KnownFn::SortBy
        | KnownFn::GroupBy
        | KnownFn::Partition2
        | KnownFn::Partition3
        | KnownFn::Partition4
        | KnownFn::Keep
        | KnownFn::Remove
        | KnownFn::MapIndexed
        | KnownFn::Juxt
        | KnownFn::Comp
        | KnownFn::Partial
        | KnownFn::Complement => {
            let fn_name = known_fn_to_name(known_fn);
            let callee = load_builtin(env, fn_name)?;
            apply_value(&callee, args, env)
        }

        KnownFn::Apply => {
            if args.len() < 2 {
                return Err(EvalError::Arity {
                    name: "apply".into(),
                    expected: "2+".into(),
                    got: args.len(),
                });
            }
            let mut args = args;
            let f = args.remove(0);
            let last = args.pop().unwrap();
            let spread = crate::interp::destructure::value_to_seq_vec(&last);
            args.extend(spread);
            apply_value(&f, args, env)
        }

        // ── Dynamic binding / exception handling ────────────────────────
        KnownFn::SetBangVar => builtin_call_native("set!", &args),
        KnownFn::WithBindings => eval_ir_with_bindings(args, env),
        KnownFn::TryCatchFinally => eval_ir_try_catch_finally(args, env),
        // `(with-out-str body…)` — the lowerer wraps the body in a zero-arg
        // thunk.  Capture output around the call, exactly like the
        // tree-walker's eval_with_out_str and the compiled tier's
        // rt_with_out_str.  (clojure.core's `with-out-str` var is a nil stub
        // — the tree-walker intercepts the form before the var is ever
        // called — so dispatching to it by name silently returned nil.)
        KnownFn::WithOutStr => {
            let body = args.into_iter().next().unwrap_or(Value::Nil);
            crate::builtins::builtins::push_output_capture();
            let result = apply_value(&body, vec![], env);
            let captured = crate::builtins::builtins::pop_output_capture().unwrap_or_default();
            // Propagate errors, but only after the capture frame is popped.
            result?;
            Ok(Value::Str(GcPtr::new(captured)))
        }
        // Analysis-only KnownFns: variants the analyzer cares about but
        // the interpreter has no specialised path for.  Fall back to a
        // dynamic lookup of the builtin by name.
        KnownFn::IsEmpty
        | KnownFn::Peek
        | KnownFn::Pop
        | KnownFn::Vec
        | KnownFn::Mapcat
        | KnownFn::Repeatedly => {
            let fn_name = known_fn_to_name(known_fn);
            let callee = load_builtin(env, fn_name)?;
            apply_value(&callee, args, env)
        }
    }
}

// ── Helpers for KnownFn dispatch ────────────────────────────────────────────

/// Handle `KnownFn::WithBindings` emitted by `lower-binding`.
///
/// The ANF lowerer emits flat args `[var0, val0, var1, val1, ..., body-fn]`.
/// This is different from the `with-bindings*` public API which takes a map,
/// so we assemble the frame here rather than delegating to eval_with_bindings_star.
fn eval_ir_with_bindings(args: Vec<Value>, env: &mut Env) -> EvalResult {
    use std::collections::HashMap;
    if args.is_empty() {
        return Err(EvalError::Arity {
            name: "with-bindings".into(),
            expected: "1+".into(),
            got: 0,
        });
    }
    // Last arg is the body thunk; preceding args are (Var, value) pairs.
    let body = args.last().unwrap().clone();
    let pairs = &args[..args.len() - 1];
    if !pairs.len().is_multiple_of(2) {
        return Err(EvalError::Runtime(
            "with-bindings: odd number of var/val pairs".into(),
        ));
    }
    let mut frame: HashMap<usize, Value> = HashMap::new();
    for chunk in pairs.chunks(2) {
        if let Value::Var(vp) = &chunk[0] {
            frame.insert(crate::env::dynamics::var_key_of(vp), chunk[1].clone());
        } else {
            return Err(EvalError::Runtime(format!(
                "with-bindings: binding key must be a Var, got {}",
                chunk[0].type_name()
            )));
        }
    }
    let _guard = crate::env::dynamics::push_frame(frame);
    crate::env::apply::apply_value(&body, vec![], env)
}

/// Handle `KnownFn::TryCatchFinally` emitted by `lower_try`.
///
/// Args are `[body-fn, catch-fn-or-nil, finally-fn-or-nil]`.  The body thunk
/// is called with no arguments.  On a thrown exception the catch thunk (if not
/// nil) is called with the exception value as its sole argument.  The finally
/// thunk (if not nil) is always called with no arguments before returning.
fn eval_ir_try_catch_finally(args: Vec<Value>, env: &mut Env) -> EvalResult {
    let body = args.first().cloned().unwrap_or(Value::Nil);
    let catch_fn = args.get(1).cloned().unwrap_or(Value::Nil);
    let finally_fn = args.get(2).cloned().unwrap_or(Value::Nil);

    let body_result = apply_value(&body, vec![], env);

    let ret = match body_result {
        Ok(val) => Ok(val),
        Err(EvalError::Thrown(thrown_val)) => {
            if matches!(catch_fn, Value::Nil) {
                Err(EvalError::Thrown(thrown_val))
            } else {
                apply_value(&catch_fn, vec![thrown_val], env)
            }
        }
        err => err,
    };

    if !matches!(finally_fn, Value::Nil) {
        let _ = apply_value(&finally_fn, vec![], env);
    }

    ret
}

/// Call a native builtin by name from the global environment.
fn builtin_call_native(name: &str, args: &[Value]) -> EvalResult {
    // Use the callback infrastructure to get an eval context.
    crate::env::callback::with_eval_context(|env| {
        let callee = load_builtin(env, name)?;
        if let Value::NativeFunction(nf) = &callee {
            (nf.get().func)(args).map_err(|e| EvalError::Runtime(e.to_string()))
        } else {
            apply_value(&callee, args.to_vec(), env)
        }
    })
}

/// Look up a builtin function by name in the global environment.
fn load_builtin(env: &Env, name: &str) -> EvalResult {
    env.globals
        .lookup_in_ns("clojure.core", name)
        .ok_or_else(|| EvalError::Runtime(format!("IR interpreter: builtin not found: {name}")))
}

/// Map KnownFn variants to their Clojure function names.
fn known_fn_to_name(kf: &KnownFn) -> &'static str {
    match kf {
        KnownFn::Map => "map",
        KnownFn::Filter => "filter",
        KnownFn::Mapv => "mapv",
        KnownFn::Filterv => "filterv",
        KnownFn::Reduce2 | KnownFn::Reduce3 => "reduce",
        KnownFn::Some => "some",
        KnownFn::Every => "every?",
        KnownFn::Into | KnownFn::Into3 => "into",
        KnownFn::Sort => "sort",
        KnownFn::SortBy => "sort-by",
        KnownFn::GroupBy => "group-by",
        KnownFn::Partition2 | KnownFn::Partition3 | KnownFn::Partition4 => "partition",
        KnownFn::Keep => "keep",
        KnownFn::Remove => "remove",
        KnownFn::MapIndexed => "map-indexed",
        KnownFn::Juxt => "juxt",
        KnownFn::Comp => "comp",
        KnownFn::Partial => "partial",
        KnownFn::Complement => "complement",
        KnownFn::Apply => "apply",
        KnownFn::WithBindings => "with-bindings*",
        KnownFn::WithOutStr => "with-out-str",
        KnownFn::TryCatchFinally => "try",
        KnownFn::SetBangVar => "set!",
        KnownFn::CaseEq => "case=",
        KnownFn::IsEmpty => "empty?",
        KnownFn::Peek => "peek",
        KnownFn::Pop => "pop",
        KnownFn::Vec => "vec",
        KnownFn::Mapcat => "mapcat",
        KnownFn::Repeatedly => "repeatedly",
        _ => "unknown",
    }
}

/// Arithmetic dispatch for +, -, *, /, rem.
fn builtin_arith(args: &[Value], op: &str) -> EvalResult {
    if args.len() != 2 {
        return builtin_call_native(op, args);
    }
    let (a, b) = (&args[0], &args[1]);
    match (a, b) {
        (Value::Long(x), Value::Long(y)) => match op {
            // Checked: primitive long arithmetic throws on overflow (matches
            // the compiled tier).  The wrapping variants are `unchecked-*`.
            "+" => x
                .checked_add(*y)
                .map(Value::Long)
                .ok_or_else(|| EvalError::Runtime("integer overflow".to_string())),
            "-" => x
                .checked_sub(*y)
                .map(Value::Long)
                .ok_or_else(|| EvalError::Runtime("integer overflow".to_string())),
            "*" => x
                .checked_mul(*y)
                .map(Value::Long)
                .ok_or_else(|| EvalError::Runtime("integer overflow".to_string())),
            "unchecked-add" => Ok(Value::Long(x.wrapping_add(*y))),
            "unchecked-subtract" => Ok(Value::Long(x.wrapping_sub(*y))),
            "unchecked-multiply" => Ok(Value::Long(x.wrapping_mul(*y))),
            "/" => {
                if *y == 0 {
                    Err(EvalError::Runtime("Divide by zero".to_string()))
                } else {
                    Ok(Value::Long(x / y))
                }
            }
            "rem" => {
                if *y == 0 {
                    Err(EvalError::Runtime("Divide by zero".to_string()))
                } else {
                    Ok(Value::Long(x % y))
                }
            }
            _ => builtin_call_native(op, args),
        },
        (Value::Double(x), Value::Double(y)) => match op {
            "+" | "unchecked-add" => Ok(Value::Double(x + y)),
            "-" | "unchecked-subtract" => Ok(Value::Double(x - y)),
            "*" | "unchecked-multiply" => Ok(Value::Double(x * y)),
            "/" => Ok(Value::Double(x / y)),
            "rem" => Ok(Value::Double(x % y)),
            _ => builtin_call_native(op, args),
        },
        (Value::Long(x), Value::Double(y)) => {
            let x = *x as f64;
            match op {
                "+" | "unchecked-add" => Ok(Value::Double(x + y)),
                "-" | "unchecked-subtract" => Ok(Value::Double(x - y)),
                "*" | "unchecked-multiply" => Ok(Value::Double(x * y)),
                "/" => Ok(Value::Double(x / y)),
                "rem" => Ok(Value::Double(x % y)),
                _ => builtin_call_native(op, args),
            }
        }
        (Value::Double(x), Value::Long(y)) => {
            let y = *y as f64;
            match op {
                "+" | "unchecked-add" => Ok(Value::Double(*x + y)),
                "-" | "unchecked-subtract" => Ok(Value::Double(*x - y)),
                "*" | "unchecked-multiply" => Ok(Value::Double(*x * y)),
                "/" => Ok(Value::Double(*x / y)),
                "rem" => Ok(Value::Double(*x % y)),
                _ => builtin_call_native(op, args),
            }
        }
        _ => builtin_call_native(op, args),
    }
}

/// Comparison dispatch for <, >, <=, >=.
fn builtin_compare(known_fn: &KnownFn, args: &[Value]) -> EvalResult {
    if args.len() != 2 {
        return Ok(Value::Bool(false));
    }
    let (a, b) = (&args[0], &args[1]);
    let result = match (a, b) {
        (Value::Long(x), Value::Long(y)) => match known_fn {
            KnownFn::Lt => x < y,
            KnownFn::Gt => x > y,
            KnownFn::Lte => x <= y,
            KnownFn::Gte => x >= y,
            _ => false,
        },
        (Value::Double(x), Value::Double(y)) => match known_fn {
            KnownFn::Lt => x < y,
            KnownFn::Gt => x > y,
            KnownFn::Lte => x <= y,
            KnownFn::Gte => x >= y,
            _ => false,
        },
        (Value::Long(x), Value::Double(y)) => {
            let x = *x as f64;
            match known_fn {
                KnownFn::Lt => x < *y,
                KnownFn::Gt => x > *y,
                KnownFn::Lte => x <= *y,
                KnownFn::Gte => x >= *y,
                _ => false,
            }
        }
        (Value::Double(x), Value::Long(y)) => {
            let y = *y as f64;
            match known_fn {
                KnownFn::Lt => *x < y,
                KnownFn::Gt => *x > y,
                KnownFn::Lte => *x <= y,
                KnownFn::Gte => *x >= y,
                _ => false,
            }
        }
        _ => {
            // Delegate to the native comparison function for all other types
            // (BigInt, Ratio, mixed, etc.) so they compare correctly.
            let op = match known_fn {
                KnownFn::Lt => "<",
                KnownFn::Gt => ">",
                KnownFn::Lte => "<=",
                KnownFn::Gte => ">=",
                _ => return Ok(Value::Bool(false)),
            };
            return builtin_call_native(op, args);
        }
    };
    Ok(Value::Bool(result))
}

// IR lowering

/// Eagerly lower all arities of a function to IR, storing the results
/// in the IR cache.  Failures are silently recorded as `Unsupported`.
///
/// Only lowers once the runtime has left its bootstrap and raised the tier
/// state to [`crate::TierState::Ir`] or above; the gate is applied by
/// `GlobalEnv::on_fn_defined`, which is this function's only caller.
pub(crate) fn eager_lower_fn(f: &CljxFn, env: &mut Env) {
    use crate::tiered::apply::IR_LOWERING_ACTIVE;
    let mut lowered = 0;
    let mut cached = 0;
    let mut failed = 0;

    // Skip if eager lowering is disabled.
    if !crate::tiered::apply::eager_lower_enabled() {
        return;
    }

    tracing::trace!(target: "ir", "eager_lower_fn {:?}", f.name);

    // Don't lower macros (they operate on forms, not values).
    if f.is_macro {
        tracing::debug!(target: "ir", "not lowering macro: {:?}", f.name);
        return;
    }

    // Don't lower closures that capture variables from an enclosing scope.
    // lower-fn-body only knows about the explicit arity params; captured names
    // are invisible to it, so any reference to a capture would be emitted as
    // LoadGlobal(defining-ns, name) — which either resolves to the wrong var or
    // fails at runtime with "var not found".  Top-level defns have no captures,
    // so they are safe to lower.  Inner closures will fall back to tree-walking.
    if !f.closed_over_names.is_empty() {
        return;
    }

    // Don't nest lowering calls.
    if IR_LOWERING_ACTIVE.get() {
        tracing::trace!(target: "ir", "lowering active, not continuing");
        return;
    }

    IR_LOWERING_ACTIVE.set(true);

    // Arities lowered in this call, collected for the cross-defn registry
    // (param_count, is_variadic, ir).
    let mut registered: Vec<(usize, bool, Arc<IrFunction>)> = Vec::new();

    // Hold the tier state by `Arc` rather than borrowing it out of `env`,
    // which the lowering call below needs mutably.
    let tiers = env.globals.tiers().clone();
    let ir_cache = tiers.ir_cache();

    for arity in &f.arities {
        let arity_id = arity.ir_arity_id;
        if !ir_cache.should_attempt(arity_id) {
            cached += 1;
            // Keep already-cached arities in the registration so a partial
            // re-lower doesn't drop them from the cross-defn registry.
            if let Some(ir) = ir_cache.get(arity_id) {
                registered.push((arity.params.len(), arity.rest_param.is_some(), ir));
            }
            continue;
        }

        // Destructured params are expanded into explicit IR-prologue bindings by
        // lower_and_optimize_arity (passing the patterns below), so they no
        // longer force a tree-walk fallback.

        match crate::tiered::lower::lower_and_optimize_arity_tracked(
            f.name.as_deref(),
            &arity.params,
            arity.rest_param.as_ref(),
            &arity.destructure_params,
            arity.destructure_rest.as_ref(),
            &arity.body,
            &f.defining_ns,
            env,
            f.is_async,
        ) {
            Ok((mut ir_func, used_externals)) => {
                // Attach static primitive type-hint seeds so the JIT can skip
                // its profiling warmup and guard/unbox these params directly.
                ir_func.seed_reprs =
                    crate::tiered::lower::seed_reprs_from_hints(&arity.param_hints);
                let ir_func = Arc::new(ir_func);
                ir_cache.store(arity_id, ir_func.clone());
                // The lowering specialized against these defns — invalidate
                // it (and re-lower lazily) if any of them is rebound.
                crate::tiered::defn_registry::record_dependents(arity_id, used_externals);
                registered.push((arity.params.len(), arity.rest_param.is_some(), ir_func));
                lowered += 1;
            }
            Err(_) => {
                ir_cache.store_unsupported(arity_id);
                failed += 1;
            }
        }
    }

    // Publish this defn so later lowerings of *other* functions can
    // region-promote calls into it (stage 4).  Anonymous, async, or capturing
    // fns are not callable cross-defn by name, so skip them.
    if !f.is_async
        && !registered.is_empty()
        && let Some(name) = f.name.as_deref()
    {
        crate::tiered::defn_registry::install_invalidation_hook();
        crate::tiered::defn_registry::register_defn(
            env.globals.id(),
            &f.defining_ns,
            &Arc::from(name),
            registered,
        );
    }

    tracing::debug!(
        target: "ir",
        "ir complete {:?} lowered:{} cached:{} failed:{}",
        f.name,
        lowered,
        cached,
        failed
    );

    IR_LOWERING_ACTIVE.set(false);
}

#[cfg(test)]
mod arith_tests {
    use super::builtin_arith;
    use cljrs_value::Value;

    #[test]
    fn checked_add_overflow_throws() {
        let r = builtin_arith(&[Value::Long(i64::MAX), Value::Long(1)], "+");
        assert!(r.is_err(), "checked + overflow must throw");
    }

    #[test]
    fn checked_mul_overflow_throws() {
        let r = builtin_arith(&[Value::Long(i64::MAX), Value::Long(2)], "*");
        assert!(r.is_err(), "checked * overflow must throw");
    }

    #[test]
    fn checked_add_normal_ok() {
        let r = builtin_arith(&[Value::Long(3), Value::Long(4)], "+").unwrap();
        assert_eq!(r, Value::Long(7));
    }

    #[test]
    fn unchecked_add_wraps() {
        let r = builtin_arith(&[Value::Long(i64::MAX), Value::Long(1)], "unchecked-add").unwrap();
        assert_eq!(r, Value::Long(i64::MIN));
    }

    #[test]
    fn unchecked_multiply_wraps() {
        let r = builtin_arith(
            &[Value::Long(i64::MAX), Value::Long(2)],
            "unchecked-multiply",
        )
        .unwrap();
        assert_eq!(r, Value::Long(-2));
    }
}