rustyfi-lang 0.1.2

Abstract syntax tree, elaboration, evaluator, and primitives for SATySFi
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
//! A closure-compiling ("JIT-style") evaluator that lowers an [`Ast`] into a
//! tree of Rust closures once, so that repeated evaluation chases compiled
//! closures instead of re-matching `Ast` nodes on every visit. This is the
//! only evaluator: [`crate::eval::Interp::eval`] is a thin shim over it.
//!
//! # Design
//!
//! * **Structure-only closures.** Each `Ast` node compiles to a
//!   [`CompiledExpr`] capturing its already-compiled children, so evaluation
//!   is pointer-chasing closures rather than `match ast { … }` dispatch +
//!   recursion.
//! * **Compile-time name resolution.** A scope pass classifies each
//!   [`Ast::Var`]: a name bound by some enclosing `let`/`lambda`/`match`/… is
//!   a *local*, resolved to a `(depth, index)` pair into the runtime frame
//!   chain ([`Env`]); a TOP-LEVEL spine binding gets a `Globals` slot instead
//!   (see that type); and a name bound by no enclosing local frame — and
//!   therefore provably unshadowed all the way down to the base environment —
//!   is a *global* whose `Value` is fetched once, at compile time, so the
//!   compiled node just clones the captured value. That last case eliminates
//!   the lookup entirely for primitives (`+`, `<`, `==`, …), which is where a
//!   compute-heavy workload like `fib` spends much of its time.

use crate::ast::{Ast, Pattern};
use crate::eval::{available_fields, eval_error, match_pattern, EvalError, Interp};
use crate::quoted;
use crate::value::{BaseEnv, Env, Value};
use rustyfi_syntax::RustyfiVersion;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::rc::Rc;

/// A compiled expression: a reference-counted closure taking the runtime
/// environment and the interpreter and yielding a [`Value`] (or an
/// [`EvalError`]). Cloning is a cheap `Rc` bump.
///
/// Crate-internal: it is the opaque body of the public
/// [`Value::CompiledClosure`] variant, with no public constructor and only
/// a `pub(crate)` method (see the `allow(private_interfaces)` note on
/// `Value`).
#[derive(Clone)]
pub(crate) struct CompiledExpr(Rc<dyn Fn(&Env, &mut Interp<'_>) -> Result<Value, EvalError>>);

impl CompiledExpr {
    fn new(
        f: impl Fn(&Env, &mut Interp<'_>) -> Result<Value, EvalError> + 'static,
    ) -> CompiledExpr {
        CompiledExpr(Rc::new(f))
    }

    pub(crate) fn run(&self, env: &Env, interp: &mut Interp<'_>) -> Result<Value, EvalError> {
        (self.0)(env, interp)
    }
}

impl std::fmt::Debug for CompiledExpr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("<compiled>")
    }
}

/// The flat table of TOP-LEVEL ("spine") binding values.
///
/// Every top-level binding is folded into one `LetIn`/`LetRecIn` **spine**
/// around the document body (`elaborate::nest`). Giving each its own
/// `env.child()` frame costs 13-90 frame walks per compiled variable
/// lookup (109M-208M probes on a corpus document) — the single largest
/// evaluator cost — so a spine binding instead gets a **slot index**,
/// assigned at compile time; it builds no frame at all.
///
/// Slots are written before they can be read (the spine executes
/// unconditionally and in order), so nothing needs clearing between
/// fixpoint trials — each trial just overwrites every slot as the spine
/// re-executes.
#[derive(Clone, Default)]
struct Globals(Rc<RefCell<Vec<Value>>>);

impl Globals {
    #[inline]
    fn get(&self, slot: usize) -> Value {
        self.0.borrow()[slot].clone()
    }

    #[inline]
    fn set(&self, slot: usize, v: Value) {
        self.0.borrow_mut()[slot] = v;
    }

    /// Size the table once compilation has assigned every slot. Compiled
    /// closures share this `Rc`, so they see the resize.
    fn finish(&self, len: usize) {
        self.0.borrow_mut().resize(len, Value::Unit);
    }
}

/// One entry of the compiler's lexical stack.
enum Scope {
    /// A real runtime frame, its names in slot order. Contributes one level
    /// of `depth` to every reference resolved past it.
    Frame(Vec<String>),
    /// A top-level (spine) binding and the [`Globals`] slot it was assigned.
    /// Contributes NO depth — spine bindings build no frame.
    Global(String, usize),
}

/// What [`Compiler::resolve`] found for a name.
enum Binding {
    /// A local: `(depth, index)` into the runtime frame chain.
    Local(u16, u16),
    /// A top-level binding: an index into the [`Globals`] table.
    Global(usize),
}

/// The lowering pass. Carries the compile-time lexical scope and, optionally,
/// the base environment used for the constant-folding fast path.
struct Compiler<'b> {
    /// ONE lexical stack, innermost last, holding both kinds of binding the
    /// compiler can resolve — see [`Scope`]. It has to be one stack: a
    /// top-level (spine) binding and a local frame can shadow each other in
    /// either direction (the cross-version deco coercion splices a
    /// top-level `let` that shadows a `let rec` group's frame fallback), so
    /// resolving locals before globals or vice versa gets that shadowing
    /// backwards — only walking one stack innermost-first reproduces the
    /// order a name-keyed environment gave for free.
    scopes: Vec<Scope>,
    /// Slots assigned so far; also the table's final length.
    n_globals: usize,
    /// The table those slots index into, shared with every compiled node that
    /// reads or writes one.
    globals: Globals,
    /// The `V0_1`-slot base environment, when unshadowed names may be
    /// constant-folded. For a PURE (non-cross-version) compile this is
    /// simply *the* base environment regardless of generation —
    /// [`Compiler::new`] always parks it here, leaving
    /// `globals_v006`/`current_version` at their defaults.
    globals_v01: Option<&'b BaseEnv>,
    /// The `V0_0`-slot base environment — `Some` only for a cross-version
    /// splice compile ([`Compiler::new_xver`]), used only while
    /// `current_version` is `V0_0` (inside an `Ast::VersionScope(V0_0, _)`
    /// subtree). `None` on every pure path, which is fine since no
    /// `VersionScope` node is ever emitted there.
    globals_v006: Option<&'b BaseEnv>,
    /// Which of the two envs above is active for the primitive fold —
    /// `V0_1` outside any `VersionScope`, else the tag of the innermost
    /// enclosing one. Only moves off its initial value during a
    /// cross-version splice compile.
    current_version: RustyfiVersion,
}

impl<'b> Compiler<'b> {
    /// The ordinary constructor: one base environment to constant-fold
    /// against. `current_version` never moves off its initial `V0_1` slot
    /// (no `VersionScope` node exists on this path).
    fn new(globals: Option<&'b BaseEnv>) -> Compiler<'b> {
        Compiler {
            scopes: Vec::new(),
            n_globals: 0,
            globals: Globals::default(),
            globals_v01: globals,
            globals_v006: None,
            current_version: RustyfiVersion::V0_1,
        }
    }

    /// The cross-version-splice constructor: `env_v01` folds
    /// every `Ast::Var` OUTSIDE a `VersionScope`; `env_v006` folds every one
    /// INSIDE an `Ast::VersionScope(V0_0, _)` subtree (see the
    /// `Ast::VersionScope` compile arm below). The program body always
    /// starts un-wrapped (`V0_1`), so `current_version` starts there too.
    fn new_xver(env_v01: &'b BaseEnv, env_v006: &'b BaseEnv) -> Compiler<'b> {
        Compiler {
            scopes: Vec::new(),
            n_globals: 0,
            globals: Globals::default(),
            globals_v01: Some(env_v01),
            globals_v006: Some(env_v006),
            current_version: RustyfiVersion::V0_1,
        }
    }

    /// The base environment currently active for the primitive fold —
    /// `V0_1`'s slot outside any `VersionScope`, `V0_0`'s slot inside one
    /// (only ever populated by [`Compiler::new_xver`]).
    fn globals_for(&self, version: RustyfiVersion) -> Option<&'b BaseEnv> {
        match version {
            RustyfiVersion::V0_1 => self.globals_v01,
            RustyfiVersion::V0_0 => self.globals_v006,
            // `RustyfiVersion` is `#[non_exhaustive]`; this crate only ever
            // constructs the two variants matched above, so there is no
            // third slot to resolve to.
            _ => None,
        }
    }

    /// Where the program binds `name`, walking the lexical stack
    /// innermost-first so the most recent binding wins. Within one frame,
    /// names are scanned LAST-first, so a name bound twice resolves to the
    /// later slot — matching a name-keyed environment, where a second
    /// `define` simply overwrites the first (reachable for a repeated
    /// pattern-bound name, or a `let rec` group that repeats one).
    fn resolve(&self, name: &str) -> Option<Binding> {
        let mut depth = 0u16;
        for entry in self.scopes.iter().rev() {
            match entry {
                Scope::Frame(names) => {
                    if let Some(index) = names.iter().rposition(|n| n == name) {
                        return Some(Binding::Local(depth, index as u16));
                    }
                    depth += 1;
                }
                Scope::Global(n, slot) => {
                    if n == name {
                        return Some(Binding::Global(*slot));
                    }
                }
            }
        }
        None
    }

    /// Is `name` bound by the program at all? This, not "is it a local", is
    /// what guards the base-environment constant fold: a top-level binding
    /// that shadows a primitive name must win.
    fn is_bound(&self, name: &str) -> bool {
        self.resolve(name).is_some()
    }

    fn alloc_global(&mut self, name: &str) -> usize {
        let slot = self.n_globals;
        self.n_globals += 1;
        self.scopes.push(Scope::Global(name.to_string(), slot));
        slot
    }

    /// Push a frame binding `names` (in slot order), compile `body` inside
    /// it, then pop. Must stay 1:1 with where the emitted code calls
    /// `env.child(..)` — that correspondence is what makes `(depth, index)`
    /// mean the same thing at compile time and at run time.
    fn in_frame<R>(
        &mut self,
        names: impl IntoIterator<Item = String>,
        body: impl FnOnce(&mut Compiler<'b>) -> R,
    ) -> R {
        // Truncate rather than pop: `body` may push its own `Scope::Global`
        // entries (the spine continuing inside a `let rec` group's fallback
        // frame), which belong to this region too.
        let mark = self.scopes.len();
        self.scopes.push(Scope::Frame(names.into_iter().collect()));
        let r = body(self);
        self.scopes.truncate(mark);
        r
    }

    /// If `ast` is a fully-applied call to an unshadowed base-environment
    /// primitive — `op a1 … aN` with `op` a *global* (not local) resolving
    /// to a zero-args-applied [`Value::Prim`] of arity exactly `N` — compile
    /// it to a direct primitive-body invocation, skipping the per-argument
    /// `Value::Prim` clone + `applied`-vector churn of currying one
    /// argument at a time.
    ///
    /// The argument vector handed to `def.run` is in the same left-to-right
    /// order currying would produce, so the primitive body and any error it
    /// raises are unchanged. Under/over-application or a shadowed/local
    /// `op` return `None` and fall back to ordinary nested application.
    fn try_saturated_prim(&mut self, ast: &Ast) -> Option<CompiledExpr> {
        let (head, args) = unfold_spine(ast);
        let Ast::Var(name, _) = head else {
            return None;
        };
        if self.is_bound(name) {
            return None;
        }
        let Value::Prim { def, applied } = self
            .globals_for(self.current_version)
            .and_then(|g| g.lookup(name))?
        else {
            return None;
        };
        if !applied.is_empty() || def.arity != args.len() {
            return None;
        }
        let run = def.run;
        let cargs: Vec<CompiledExpr> = args.iter().map(|a| self.compile(a)).collect();
        Some(CompiledExpr::new(move |env, interp| {
            let mut vals = Vec::with_capacity(cargs.len());
            for c in &cargs {
                vals.push(c.run(env, interp)?);
            }
            run(interp, vals)
        }))
    }

    fn compile(&mut self, ast: &Ast) -> CompiledExpr {
        match ast {
            Ast::Unit => CompiledExpr::new(|_, _| Ok(Value::Unit)),
            Ast::Bool(b) => {
                let b = *b;
                CompiledExpr::new(move |_, _| Ok(Value::Bool(b)))
            }
            Ast::Int(n) => {
                let n = *n;
                CompiledExpr::new(move |_, _| Ok(Value::Int(n)))
            }
            Ast::Float(x) => {
                let x = *x;
                CompiledExpr::new(move |_, _| Ok(Value::Float(x)))
            }
            Ast::Length(l) => {
                let l = *l;
                CompiledExpr::new(move |_, _| Ok(Value::Length(l)))
            }
            Ast::Str(s) => {
                let s = s.clone();
                CompiledExpr::new(move |_, _| Ok(Value::Str(s.clone())))
            }
            Ast::Var(name, span) => self.compile_var_read(name, *span, "variable"),
            Ast::Apply(f, arg) => {
                if let Some(special) = self.try_saturated_prim(ast) {
                    special
                } else {
                    let cf = self.compile(f);
                    let ca = self.compile(arg);
                    CompiledExpr::new(move |env, interp| {
                        let func = cf.run(env, interp)?;
                        let arg = ca.run(env, interp)?;
                        interp.apply(func, arg)
                    })
                }
            }
            Ast::Lambda(param, body) => {
                // The parameter is slot 0 of the frame `apply` pushes; its
                // name is needed only to compile the body.
                let cbody = self.in_frame([param.clone()], |c| c.compile(body));
                CompiledExpr::new(move |env, _| {
                    Ok(Value::CompiledClosure {
                        opt_labels: Vec::new(),
                        body: cbody.clone(),
                        env: env.clone(),
                    })
                })
            }
            // `fun ?(l = x, …) p -> body` (SATySFi 0.1): optional binders in
            // declaration order, then the positional param — the slot order
            // `in_frame` records here and `apply_with_opts` fills.
            Ast::LambdaOpt { opts, param, body } => {
                let binders: Vec<String> = opts
                    .iter()
                    .map(|(_, b)| b.clone())
                    .chain(std::iter::once(param.clone()))
                    .collect();
                let cbody = self.in_frame(binders, |c| c.compile(body));
                let opt_labels: Vec<String> = opts.iter().map(|(l, _)| l.clone()).collect();
                CompiledExpr::new(move |env, _| {
                    Ok(Value::CompiledClosure {
                        opt_labels: opt_labels.clone(),
                        body: cbody.clone(),
                        env: env.clone(),
                    })
                })
            }
            // `f ?(l = e, …) arg` (SATySFi 0.1) — mirror `Ast::Apply` minus
            // the saturated-prim fast path (prims reject optionals anyway).
            Ast::ApplyOpt { func, opts, arg } => {
                let cf = self.compile(func);
                let copts: Vec<(String, CompiledExpr)> = opts
                    .iter()
                    .map(|(l, e)| (l.clone(), self.compile(e)))
                    .collect();
                let ca = self.compile(arg);
                CompiledExpr::new(move |env, interp| {
                    let func = cf.run(env, interp)?;
                    let mut opt_vals = Vec::with_capacity(copts.len());
                    for (l, ce) in &copts {
                        opt_vals.push((l.clone(), ce.run(env, interp)?));
                    }
                    let arg = ca.run(env, interp)?;
                    interp.apply_with_opts(func, opt_vals, arg)
                })
            }
            Ast::LetIn(name, value, rest) => {
                let cvalue = self.compile(value);
                let crest = self.in_frame([name.clone()], |c| c.compile(rest));
                CompiledExpr::new(move |env, interp| {
                    let v = cvalue.run(env, interp)?;
                    crest.run(&env.child(vec![v]), interp)
                })
            }
            // Same run-time shape as `LetIn` (see `ast.rs`'s doc comment).
            Ast::LetMathIn(name, value, rest) => {
                let cvalue = self.compile(value);
                let crest = self.in_frame([name.clone()], |c| c.compile(rest));
                CompiledExpr::new(move |env, interp| {
                    let v = cvalue.run(env, interp)?;
                    crest.run(&env.child(vec![v]), interp)
                })
            }
            Ast::LetRecIn(bindings, body) => {
                let names: Vec<String> = bindings.iter().map(|(n, _)| n.clone()).collect();
                let (cbindings, cbody) = self.in_frame(names.clone(), |c| {
                    let cbindings: Vec<(std::rc::Rc<str>, CompiledExpr)> = bindings
                        .iter()
                        .map(|(n, value_ast)| (n.as_str().into(), c.compile(value_ast)))
                        .collect();
                    let cbody = c.compile(body);
                    (cbindings, cbody)
                });
                let_rec_frame(cbindings, cbody)
            }
            Ast::IfThenElse(cond, then_e, else_e) => {
                let ccond = self.compile(cond);
                let cthen = self.compile(then_e);
                let celse = self.compile(else_e);
                CompiledExpr::new(move |env, interp| match ccond.run(env, interp)? {
                    Value::Bool(true) => cthen.run(env, interp),
                    Value::Bool(false) => celse.run(env, interp),
                    other => eval_error(format!(
                        "if-then-else condition must be bool, got {}",
                        other.type_name()
                    )),
                })
            }
            Ast::Record(fields) => {
                let cfields: Vec<(String, CompiledExpr)> = fields
                    .iter()
                    .map(|(name, e)| (name.clone(), self.compile(e)))
                    .collect();
                CompiledExpr::new(move |env, interp| {
                    let mut map = BTreeMap::new();
                    for (name, ce) in &cfields {
                        map.insert(name.clone(), ce.run(env, interp)?);
                    }
                    Ok(Value::Record(map))
                })
            }
            Ast::List(items) => {
                let citems: Vec<CompiledExpr> = items.iter().map(|e| self.compile(e)).collect();
                CompiledExpr::new(move |env, interp| {
                    let mut out = Vec::with_capacity(citems.len());
                    for ce in &citems {
                        out.push(ce.run(env, interp)?);
                    }
                    Ok(Value::List(out))
                })
            }
            Ast::Tuple(items) => {
                let citems: Vec<CompiledExpr> = items.iter().map(|e| self.compile(e)).collect();
                CompiledExpr::new(move |env, interp| {
                    let mut out = Vec::with_capacity(citems.len());
                    for ce in &citems {
                        out.push(ce.run(env, interp)?);
                    }
                    Ok(Value::Tuple(out))
                })
            }
            Ast::Ctor(name, arg) => {
                let name = name.clone();
                let carg = arg.as_ref().map(|a| self.compile(a));
                CompiledExpr::new(move |env, interp| {
                    let payload = match &carg {
                        Some(ce) => Some(Box::new(ce.run(env, interp)?)),
                        None => None,
                    };
                    Ok(Value::Ctor(name.clone(), payload))
                })
            }
            // Quoted text is compiled EAGERLY, here, in the lexical scope of
            // the quote site (`crate::quoted`): command names and
            // embedded expressions are resolved now rather than by string
            // against the captured environment at layout time.
            Ast::InlineText(elems) => {
                let elems = Rc::new(elems.iter().map(|e| self.compile_itext(e)).collect());
                CompiledExpr::new(move |env, _| {
                    Ok(Value::InlineText {
                        elems: Rc::clone(&elems),
                        env: env.clone(),
                    })
                })
            }
            Ast::BlockText(elems) => {
                let elems = Rc::new(elems.iter().map(|e| self.compile_btext(e)).collect());
                CompiledExpr::new(move |env, _| {
                    Ok(Value::BlockText {
                        elems: Rc::clone(&elems),
                        env: env.clone(),
                    })
                })
            }
            Ast::MathText(elems) => {
                let elems = Rc::new(elems.iter().map(|e| self.compile_melem(e)).collect());
                CompiledExpr::new(move |env, _| {
                    Ok(Value::MathText {
                        elems: Rc::clone(&elems),
                        env: env.clone(),
                    })
                })
            }
            Ast::LetMutableIn(name, init, body) => {
                let cinit = self.compile(init);
                let cbody = self.in_frame([name.clone()], |c| c.compile(body));
                CompiledExpr::new(move |env, interp| {
                    let v = cinit.run(env, interp)?;
                    let cell = Value::Ref(Rc::new(RefCell::new(v)));
                    cbody.run(&env.child(vec![cell]), interp)
                })
            }
            Ast::Overwrite(name, span, value) => {
                // `let-mutable` binds a `Value::Ref` cell; overwriting it is a
                // read of that binding (local slot, top-level slot, or — for
                // an unresolvable name — the same error as before) followed by
                // a write THROUGH the shared cell, so no frame is mutated.
                let cell_of = self.compile_var_read(name, *span, "mutable variable");
                let name = name.clone();
                let span = *span;
                let cvalue = self.compile(value);
                CompiledExpr::new(move |env, interp| {
                    let cell = cell_of.run(env, interp)?;
                    match cell {
                        Value::Ref(cell) => {
                            let v = cvalue.run(env, interp)?;
                            *cell.borrow_mut() = v;
                            Ok(Value::Unit)
                        }
                        other => Err(EvalError {
                            span: Some(span),
                            msg: format!(
                                "cannot overwrite an immutable variable '{name}' (got a value of type {})",
                                other.type_name()
                            ),
                        }),
                    }
                })
            }
            Ast::WhileDo(cond, body) => {
                let ccond = self.compile(cond);
                let cbody = self.compile(body);
                CompiledExpr::new(move |env, interp| loop {
                    match ccond.run(env, interp)? {
                        Value::Bool(true) => {
                            cbody.run(env, interp)?;
                        }
                        Value::Bool(false) => break Ok(Value::Unit),
                        other => {
                            return eval_error(format!(
                                "while-do condition must be bool, got {}",
                                other.type_name()
                            ))
                        }
                    }
                })
            }
            Ast::Sequential(e1, e2) => {
                let ce1 = self.compile(e1);
                let ce2 = self.compile(e2);
                CompiledExpr::new(move |env, interp| {
                    ce1.run(env, interp)?;
                    ce2.run(env, interp)
                })
            }
            Ast::AccessField(e, label, span) => {
                let ce = self.compile(e);
                let label = label.clone();
                let span = *span;
                CompiledExpr::new(move |env, interp| {
                    let v = ce.run(env, interp)?;
                    match v {
                        Value::Record(map) => map.get(&label).cloned().ok_or_else(|| EvalError {
                            span: Some(span),
                            msg: format!(
                                "record has no field '{label}' (available fields: {})",
                                available_fields(&map)
                            ),
                        }),
                        other => Err(EvalError {
                            span: Some(span),
                            msg: format!(
                                "cannot access field '{label}' of a non-record value (got {})",
                                other.type_name()
                            ),
                        }),
                    }
                })
            }
            Ast::UpdateField(e, label, value) => {
                let ce = self.compile(e);
                let label = label.clone();
                let cvalue = self.compile(value);
                CompiledExpr::new(move |env, interp| {
                    let v = ce.run(env, interp)?;
                    let new_v = cvalue.run(env, interp)?;
                    match v {
                        Value::Record(mut map) => {
                            if !map.contains_key(&label) {
                                return eval_error(format!(
                                    "cannot update field '{label}': record has no such field \
                                     (available fields: {})",
                                    available_fields(&map)
                                ));
                            }
                            map.insert(label.clone(), new_v);
                            Ok(Value::Record(map))
                        }
                        other => eval_error(format!(
                            "cannot update field '{label}' of a non-record value (got {})",
                            other.type_name()
                        )),
                    }
                })
            }
            Ast::Match(scrutinee, arms) => {
                let cscrut = self.compile(scrutinee);
                let carms: Vec<CompiledArm> = arms
                    .iter()
                    .map(|arm| {
                        let mut vars = Vec::new();
                        pattern_vars(&arm.pat, &mut vars);
                        self.in_frame(vars, |c| CompiledArm {
                            pat: arm.pat.clone(),
                            guard: arm.guard.as_ref().map(|g| c.compile(g)),
                            body: c.compile(&arm.body),
                        })
                    })
                    .collect();
                CompiledExpr::new(move |env, interp| {
                    let v = cscrut.run(env, interp)?;
                    for arm in &carms {
                        // `match_pattern` pushes bindings in exactly the order
                        // `pattern_vars` collected the names above, so position
                        // i in this vector IS slot i of the arm's frame.
                        let mut bindings = Vec::new();
                        if !match_pattern(&arm.pat, &v, &mut bindings) {
                            continue;
                        }
                        let inner = env.child(bindings);
                        if let Some(guard) = &arm.guard {
                            match guard.run(&inner, interp)? {
                                Value::Bool(true) => {}
                                Value::Bool(false) => continue,
                                other => {
                                    return eval_error(format!(
                                        "match guard must be bool, got {}",
                                        other.type_name()
                                    ))
                                }
                            }
                        }
                        return arm.body.run(&inner, interp);
                    }
                    eval_error(format!(
                        "non-exhaustive match: no arm matched a value of type {}",
                        v.type_name()
                    ))
                })
            }
            // Push the tag, compile `body`
            // recursively (every nested `Var`/saturated-prim fold under it —
            // including inside a nested `Lambda`'s body, since `compile`
            // recurses eagerly at COMPILE time — sees `current_version ==
            // v`), pop. This is the whole mechanism: a version-forked
            // primitive name folds to `v`'s `PrimDef` here and nowhere else.
            // A local binding of the same name still shadows this
            // regardless of the cursor. Never reached on a pure
            // single-version compile: no `VersionScope` node is ever
            // produced there (`elaborate_program_with_versions`'s empty
            // `v006_indices`).
            Ast::VersionScope(v, body) => {
                let prev = std::mem::replace(&mut self.current_version, *v);
                let c = self.compile(body);
                self.current_version = prev;
                c
            }
            // Ctor-scoping marker — transparent to compilation (typecheck
            // runs on the uncompiled body).
            Ast::ModuleScope(_, body) => self.compile(body),

            // Stages are a typing-time discipline; evaluation of the body is
            // unaffected by which stage it was written at.
            Ast::StageScope(_, body) => self.compile(body),

            // `&e` -- quote. The body is compiled here, in the scope it was
            // written in, and NOT run: the value is that compiled body paired
            // with the environment reaching it, which is what makes the
            // fragment mean the same thing wherever it is later spliced.
            Ast::Next(inner) => {
                let body = self.compile(inner);
                CompiledExpr::new(move |env, _| {
                    Ok(Value::Code {
                        body: body.clone(),
                        env: env.clone(),
                    })
                })
            }

            // `~e` -- splice: run `e` to get a code value, then run that code
            // in the environment it was quoted in.
            //
            // Deviation from upstream worth stating: upstream runs every
            // splice during a separate preprocessing pass, before any
            // stage-1 code runs, so all splices happen first and in file
            // order. Here a splice runs where it stands. The VALUE is the
            // same for the pure code-building that staging is used for; the
            // difference is observable only through side effects ordered
            // between a splice and its surrounding stage-1 code.
            Ast::Prev(inner) => {
                let inner = self.compile(inner);
                CompiledExpr::new(move |env, interp| {
                    match inner.run(env, interp)? {
                        Value::Code { body, env: quoted_env } => body.run(&quoted_env, interp),
                        other => eval_error(format!(
                            "`~` expects a code value (from `&`), got {}",
                            other.type_name()
                        )),
                    }
                })
            }
        }
    }

    /// Resolve a NAME REFERENCE to the expression that yields its value —
    /// the compiler's single three-way classification, shared by `Ast::Var`,
    /// `Ast::Overwrite`'s cell lookup, and quoted text's command names:
    ///
    /// 1. the program binds it — a local frame -> a static `(depth, index)`
    ///    slot read, a top-level (spine) binding -> its [`Globals`] slot,
    ///    whichever [`Compiler::resolve`] reaches first;
    /// 2. an unshadowed base-environment name -> constant-folded to its value,
    ///    against `current_version`'s slot so a version-forked primitive
    ///    referenced inside an `Ast::VersionScope` freezes to THAT version's
    ///    `PrimDef`;
    /// 3. otherwise nothing can be resolved — elaboration rejects unbound
    ///    names long before here, so this is unreachable for a well-formed
    ///    program; raise "unbound {what} '…' at run time".
    ///
    /// `what` only shapes that last error: "variable", "mutable variable",
    /// "inline command", …
    fn compile_var_read(
        &mut self,
        name: &str,
        span: rustyfi_syntax::Span,
        what: &'static str,
    ) -> CompiledExpr {
        match self.resolve(name) {
            Some(Binding::Local(depth, index)) => {
                return CompiledExpr::new(move |env: &Env, _| Ok(env.slot(depth, index)))
            }
            Some(Binding::Global(slot)) => {
                let globals = self.globals.clone();
                return CompiledExpr::new(move |_, _| Ok(globals.get(slot)));
            }
            None => {}
        }
        if let Some(v) = self
            .globals_for(self.current_version)
            .and_then(|g| g.lookup(name))
        {
            return CompiledExpr::new(move |_, _| Ok(v.clone()));
        }
        let name = name.to_string();
        CompiledExpr::new(move |_, _| {
            Err(EvalError {
                span: Some(span),
                msg: format!("unbound {what} '{name}' at run time"),
            })
        })
    }

    fn compile_cmd_name(
        &mut self,
        name: &str,
        span: rustyfi_syntax::Span,
        kind: &'static str,
    ) -> CompiledExpr {
        self.compile_var_read(name, span, kind)
    }

    fn compile_cmd_arg(&mut self, a: &crate::ast::CmdArg) -> quoted::CmdArg {
        quoted::CmdArg {
            opts: a
                .opts
                .iter()
                .map(|(l, e)| (l.clone(), self.compile(e)))
                .collect(),
            arg: self.compile(&a.arg),
        }
    }

    fn compile_itext(&mut self, e: &crate::ast::IText) -> quoted::IText {
        use crate::ast::IText as A;
        match e {
            A::Text(s) => quoted::IText::Text(s.clone()),
            A::CodeText(s) => quoted::IText::CodeText(s.clone()),
            A::Cmd { name, span, args } => quoted::IText::Cmd {
                cmd: self.compile_cmd_name(name, *span, "inline command"),
                args: args.iter().map(|a| self.compile_cmd_arg(a)).collect(),
            },
            A::Embed { expr, span } => quoted::IText::Embed {
                expr: self.compile(expr),
                span: *span,
            },
            A::EmbedMath { elems, span } => quoted::IText::EmbedMath {
                elems: Rc::new(elems.iter().map(|m| self.compile_melem(m)).collect()),
                span: *span,
            },
        }
    }

    fn compile_btext(&mut self, e: &crate::ast::BText) -> quoted::BText {
        use crate::ast::BText as A;
        match e {
            A::Cmd { name, span, args } => quoted::BText::Cmd {
                cmd: self.compile_cmd_name(name, *span, "block command"),
                args: args.iter().map(|a| self.compile_cmd_arg(a)).collect(),
            },
            A::Embed { expr, span } => quoted::BText::Embed {
                expr: self.compile(expr),
                span: *span,
            },
        }
    }

    fn compile_melem(&mut self, e: &crate::ast::MathElem) -> quoted::MathElem {
        use crate::ast::MathElem as A;
        match e {
            A::Chars(s) => quoted::MathElem::Chars(s.clone()),
            A::Group(es) => {
                quoted::MathElem::Group(es.iter().map(|x| self.compile_melem(x)).collect())
            }
            A::Sub(b, s) => quoted::MathElem::Sub(
                Box::new(self.compile_melem(b)),
                s.iter().map(|x| self.compile_melem(x)).collect(),
            ),
            A::Sup(b, s) => quoted::MathElem::Sup(
                Box::new(self.compile_melem(b)),
                s.iter().map(|x| self.compile_melem(x)).collect(),
            ),
            A::Primes(b, n) => quoted::MathElem::Primes(Box::new(self.compile_melem(b)), *n),
            A::Cmd { name, span, args } => quoted::MathElem::Cmd {
                cmd: self.compile_cmd_name(name, *span, "math command"),
                name: name.as_str().into(),
                span: *span,
                args: args.iter().map(|a| self.compile_cmd_arg(a)).collect(),
            },
            A::Embed { expr, span } => quoted::MathElem::Embed {
                expr: self.compile(expr),
                span: *span,
            },
        }
    }

    /// Compile the top-level **spine** — the unbroken chain of Let-shaped
    /// nodes `elaborate::nest` wraps around the document body, one per
    /// top-level/`@require`d binding — giving each a [`Globals`] slot
    /// instead of a frame-chain walk. Each arm evaluates its
    /// right-hand side in the same order and raises the same errors as its
    /// [`Compiler::compile`] counterpart, but writes to a slot and builds
    /// no frame. The first non-Let-shaped node is the document body; it
    /// compiles normally.
    fn compile_spine(&mut self, ast: &Ast) -> CompiledExpr {
        match ast {
            Ast::LetIn(name, value, rest) => self.spine_let(name, value, rest, false),
            Ast::LetMathIn(name, value, rest) => self.spine_let(name, value, rest, false),
            Ast::LetMutableIn(name, init, body) => self.spine_let(name, init, body, true),
            Ast::LetRecIn(bindings, body) => self.spine_let_rec(bindings, body),
            other => self.compile(other),
        }
    }

    /// The shared `LetIn`/`LetMathIn`/`LetMutableIn` spine arm. `mutable`
    /// selects the `let-mutable` form, whose bound value is a fresh `Ref`
    /// cell.
    ///
    /// `value` is compiled BEFORE the slot is allocated, so a reference to
    /// `name` inside its own right-hand side resolves to whatever `name`
    /// meant before this binding — matching the runtime, which evaluates
    /// `value` in the outer env before creating the frame.
    fn spine_let(&mut self, name: &str, value: &Ast, rest: &Ast, mutable: bool) -> CompiledExpr {
        let cvalue = self.compile(value);
        let slot = self.alloc_global(name);
        let crest = self.compile_spine(rest);
        let globals = self.globals.clone();
        CompiledExpr::new(move |env, interp| {
            let v = cvalue.run(env, interp)?;
            globals.set(
                slot,
                if mutable {
                    Value::Ref(Rc::new(RefCell::new(v)))
                } else {
                    v
                },
            );
            crest.run(env, interp)
        })
    }

    /// The `LetRecIn` spine arm.
    ///
    /// Slots for the whole group are allocated BEFORE its values are
    /// compiled, which is only sound if no value can *read* a sibling
    /// while the group is still being filled — a slot read would see the
    /// previous trial's value, where a frame read falls through to the
    /// outer scope instead. A syntactic `fun`/`fun ?(..)` right-hand side
    /// can't read anything at definition time (evaluating a lambda never
    /// runs its body), and the runtime rejects any non-function `let-rec`
    /// binding anyway. When some value is *not* syntactically a lambda,
    /// this falls back to an ordinary local frame for the group instead.
    fn spine_let_rec(&mut self, bindings: &[(String, Rc<Ast>)], body: &Ast) -> CompiledExpr {
        let all_lambda = bindings
            .iter()
            .all(|(_, v)| matches!(**v, Ast::Lambda(..) | Ast::LambdaOpt { .. }));
        if !all_lambda {
            let names: Vec<String> = bindings.iter().map(|(n, _)| n.clone()).collect();
            let (cbindings, cbody) = self.in_frame(names, |c| {
                let cbindings: Vec<(Rc<str>, CompiledExpr)> = bindings
                    .iter()
                    .map(|(n, value_ast)| (n.as_str().into(), c.compile(value_ast)))
                    .collect();
                let cbody = c.compile_spine(body);
                (cbindings, cbody)
            });
            return let_rec_frame(cbindings, cbody);
        }
        let slots: Vec<usize> = bindings.iter().map(|(n, _)| self.alloc_global(n)).collect();
        let cbindings: Vec<(Rc<str>, CompiledExpr)> = bindings
            .iter()
            .map(|(n, value_ast)| (n.as_str().into(), self.compile(value_ast)))
            .collect();
        let cbody = self.compile_spine(body);
        let globals = self.globals.clone();
        CompiledExpr::new(move |env, interp| {
            for ((name, cval), slot) in cbindings.iter().zip(slots.iter()) {
                let v = cval.run(env, interp)?;
                if !matches!(v, Value::CompiledClosure { .. }) {
                    return eval_error(format!(
                        "let-rec binding '{name}' must be a function, got {}",
                        v.type_name()
                    ));
                }
                globals.set(*slot, v);
            }
            cbody.run(env, interp)
        })
    }
}

/// The ordinary (non-spine) `let-rec` runtime shape, shared by
/// [`Compiler::compile`]'s arm and [`Compiler::spine_let_rec`]'s fallback.
fn let_rec_frame(cbindings: Vec<(Rc<str>, CompiledExpr)>, cbody: CompiledExpr) -> CompiledExpr {
    CompiledExpr::new(move |env, interp| {
        // Pre-sized with placeholders and back-patched in order: a closure
        // built by an earlier binding captures this frame and sees the
        // later fills, making the group mutually recursive. Names survive
        // only for the "must be a function" message.
        //
        // A value that EAGERLY reads a not-yet-filled sibling sees the
        // `Unit` placeholder, where a name-keyed chain would fall through
        // to an outer binding instead — only reachable in a program the
        // next line rejects anyway (a non-function `let rec` binding), and
        // arguably the more faithful answer: the sibling IS the binding in
        // scope there.
        let inner = env.child(vec![Value::Unit; cbindings.len()]);
        for (i, (name, cval)) in cbindings.iter().enumerate() {
            let v = cval.run(&inner, interp)?;
            if !matches!(v, Value::CompiledClosure { .. }) {
                return eval_error(format!(
                    "let-rec binding '{name}' must be a function, got {}",
                    v.type_name()
                ));
            }
            inner.set_slot(0, i as u16, v);
        }
        cbody.run(&inner, interp)
    })
}

/// One compiled match arm: the (uncompiled) pattern is kept for the runtime
/// [`match_pattern`] structural test; the guard and body are compiled in a
/// scope extended with the pattern's bound variables.
struct CompiledArm {
    pat: Pattern,
    guard: Option<CompiledExpr>,
    body: CompiledExpr,
}

/// Unfold a left-nested application spine `((h a1) a2) … aN` into its head
/// `h` and the argument list `[a1, a2, …, aN]` in left-to-right (source)
/// order.
fn unfold_spine(ast: &Ast) -> (&Ast, Vec<&Ast>) {
    let mut args = Vec::new();
    let mut head = ast;
    while let Ast::Apply(f, a) = head {
        args.push(a.as_ref());
        head = f.as_ref();
    }
    args.reverse();
    (head, args)
}

/// Collect the variable names a pattern binds (order irrelevant — this only
/// feeds the compile-time scope's membership test, so that pattern-bound
/// names are treated as locals rather than constant-folded globals).
fn pattern_vars(pat: &Pattern, out: &mut Vec<String>) {
    match pat {
        Pattern::Wild
        | Pattern::Unit
        | Pattern::Bool(_)
        | Pattern::Int(_)
        | Pattern::Str(_)
        | Pattern::EmptyList => {}
        Pattern::Var(name) => out.push(name.clone()),
        Pattern::As(inner, name) => {
            pattern_vars(inner, out);
            out.push(name.clone());
        }
        Pattern::Tuple(ps) => {
            for p in ps {
                pattern_vars(p, out);
            }
        }
        Pattern::Cons(h, t) => {
            pattern_vars(h, out);
            pattern_vars(t, out);
        }
        Pattern::Ctor(_, Some(p)) => pattern_vars(p, out),
        Pattern::Ctor(_, None) => {}
    }
}

/// Compile a top-level program body against `base_env`. Names bound by the
/// program's own `let`s become locals as compilation descends; names that
/// remain free are the (unshadowed) base-environment primitives, which are
/// constant-folded to their captured values.
pub(crate) fn compile_program(ast: &Ast, base_env: &BaseEnv) -> CompiledExpr {
    let mut c = Compiler::new(Some(base_env));
    let compiled = c.compile_spine(ast);
    c.globals.finish(c.n_globals);
    compiled
}

/// Compile a top-level program body that may contain `Ast::VersionScope`
/// nodes (a cross-version splice, `lib.rs`'s
/// `compile_document_v1_with_trials`): `base_env` folds every unshadowed
/// `Ast::Var` OUTSIDE a `VersionScope`, `base_env_v006` folds every one
/// INSIDE an `Ast::VersionScope(V0_0, _)` subtree. See
/// [`Compiler::new_xver`].
pub(crate) fn compile_program_xver(
    ast: &Ast,
    base_env: &BaseEnv,
    base_env_v006: &BaseEnv,
) -> CompiledExpr {
    let mut c = Compiler::new_xver(base_env, base_env_v006);
    let compiled = c.compile_spine(ast);
    c.globals.finish(c.n_globals);
    compiled
}

#[cfg(test)]
mod tests {
    //! Determinism checks over a broad set of programs, plus opt-in
    //! (`#[ignore]`) micro-benchmarks.
    //!
    //! The property under test is the one the project's byte-identical-output
    //! constraint depends on: two INDEPENDENT compiles, against two freshly
    //! built base environments, must produce identical output. That is what
    //! catches nondeterminism leaking in from hash iteration order,
    //! allocation addresses, or the shared `Globals` table.
    //!
    //! Run the benchmarks with, e.g.:
    //! `cargo test -p rustyfi-lang --release -- --ignored --nocapture bench_`

    use super::*;
    use crate::ast::{MatchArm, Pattern};
    use crate::eval::Interp;
    use crate::value::{BaseEnv, Env, Value};
    use rustyfi_backend::{FontKey, FontMetrics, Length};
    use rustyfi_syntax::Span;

    struct Mono;
    impl FontMetrics for Mono {
        fn advance(&self, _f: FontKey, c: char, size: Length) -> Option<Length> {
            if c.is_ascii() {
                Some(size * 0.5)
            } else {
                None
            }
        }
        fn ascender(&self, _f: FontKey, size: Length) -> Length {
            size * 0.75
        }
        fn descender(&self, _f: FontKey, size: Length) -> Length {
            size * 0.25
        }
    }

    // ---- small Ast builders (mirroring the eval_phase2 test helpers) -------

    fn var(name: &str) -> Ast {
        Ast::Var(name.to_string(), Span::default())
    }
    fn app1(f: Ast, a: Ast) -> Ast {
        Ast::Apply(Box::new(f), Box::new(a))
    }
    fn app2(name: &str, a: Ast, b: Ast) -> Ast {
        app1(app1(var(name), a), b)
    }

    /// `let rec fib n = if n < 2 then n else fib (n-1) + fib (n-2) in fib n`.
    fn fib_program(n: i64) -> Ast {
        let body = Ast::IfThenElse(
            Box::new(app2("<", var("n"), Ast::Int(2))),
            Box::new(var("n")),
            Box::new(app2(
                "+",
                app1(var("fib"), app2("-", var("n"), Ast::Int(1))),
                app1(var("fib"), app2("-", var("n"), Ast::Int(2))),
            )),
        );
        let fib_lambda = Rc::new(Ast::Lambda("n".to_string(), Rc::new(body)));
        Ast::LetRecIn(
            vec![("fib".to_string(), fib_lambda)],
            Box::new(app1(var("fib"), Ast::Int(n))),
        )
    }

    /// Compile `ast` against the compile-time environment `base`, then run it
    /// in a fresh (empty) runtime frame chain — the same two-environment split
    /// `lib.rs` uses.
    fn eval_compiled(base: &BaseEnv, ast: &Ast) -> Result<Value, EvalError> {
        let mono = Mono;
        let mut interp = Interp::new(&mono);
        compile_program(ast, base).run(&Env::root(), &mut interp)
    }

    /// Compile and run `ast` twice — separate compiles, separate base
    /// environments, separate interpreters — and require the two runs to agree
    /// exactly: identical `Value` (compared by structural `Debug`) on success,
    /// identical error text on failure, and the same success/failure verdict.
    fn assert_deterministic(ast: &Ast) {
        let env_a = crate::primitives::base_env();
        let env_b = crate::primitives::base_env();
        match (eval_compiled(&env_a, ast), eval_compiled(&env_b, ast)) {
            (Ok(a), Ok(b)) => assert_eq!(
                format!("{a:?}"),
                format!("{b:?}"),
                "two independent compiles produced different values"
            ),
            (Err(a), Err(b)) => assert_eq!(
                a.to_string(),
                b.to_string(),
                "two independent compiles produced different errors"
            ),
            (a, b) => panic!("ok/err mismatch between two runs: {a:?} vs {b:?}"),
        }
    }

    /// SATySFi 0.1 labeled-optional lambda/application (`LambdaOpt`/
    /// `ApplyOpt`) `Some`/`None` defaulting: a provided `?(bias = e)` binds
    /// `Some e`, an omitted one (a plain apply of an opt-closure) binds
    /// `None`.
    #[test]
    fn deterministic_labeled_optionals() {
        use std::rc::Rc;
        // `fun ?(bias = b) x -> x + (match b with None -> 0 | Some v -> v end)`
        let body = app2(
            "+",
            var("x"),
            Ast::Match(
                Box::new(var("b")),
                vec![
                    MatchArm {
                        pat: Pattern::Ctor("None".to_string(), None),
                        guard: None,
                        body: Ast::Int(0),
                    },
                    MatchArm {
                        pat: Pattern::Ctor(
                            "Some".to_string(),
                            Some(Box::new(Pattern::Var("v".to_string()))),
                        ),
                        guard: None,
                        body: var("v"),
                    },
                ],
            ),
        );
        let lam = Ast::LambdaOpt {
            opts: vec![("bias".to_string(), "b".to_string())],
            param: "x".to_string(),
            body: Rc::new(body),
        };
        // provided `?(bias = 40) 2` -> 42
        assert_deterministic(&Ast::ApplyOpt {
            func: Box::new(lam.clone()),
            opts: vec![("bias".to_string(), Ast::Int(40))],
            arg: Box::new(Ast::Int(2)),
        });
        // omitted (plain apply of an opt-closure) -> bias defaults None -> 2
        assert_deterministic(&app1(lam, Ast::Int(2)));
    }

    #[test]
    fn deterministic_literals_and_arithmetic() {
        assert_deterministic(&Ast::Int(42));
        assert_deterministic(&Ast::Str("hi".to_string()));
        assert_deterministic(&Ast::Bool(true));
        assert_deterministic(&app2("+", Ast::Int(2), Ast::Int(3)));
        assert_deterministic(&app2("*", Ast::Int(7), Ast::Int(6)));
        assert_deterministic(&app2("<", Ast::Int(2), Ast::Int(3)));
        assert_deterministic(&app2("^", Ast::Str("foo".into()), Ast::Str("bar".into())));
        // division by zero: both must error the same way.
        assert_deterministic(&app2("/", Ast::Int(1), Ast::Int(0)));
    }

    #[test]
    fn deterministic_let_lambda_and_capture() {
        // let id x = x in id 7
        assert_deterministic(&Ast::LetIn(
            "id".into(),
            Box::new(Ast::Lambda("x".into(), Rc::new(var("x")))),
            Box::new(app1(var("id"), Ast::Int(7))),
        ));
        // capture of an outer let through a closure: let a = 5 in (fun x -> a + x) 3
        assert_deterministic(&Ast::LetIn(
            "a".into(),
            Box::new(Ast::Int(5)),
            Box::new(app1(
                Ast::Lambda("x".into(), Rc::new(app2("+", var("a"), var("x")))),
                Ast::Int(3),
            )),
        ));
    }

    #[test]
    fn deterministic_let_rec_fib_and_mutual() {
        assert_deterministic(&fib_program(15));
        // mutual even/odd
        let even_body = Ast::IfThenElse(
            Box::new(app2("==", var("n"), Ast::Int(0))),
            Box::new(Ast::Bool(true)),
            Box::new(app1(var("odd"), app2("-", var("n"), Ast::Int(1)))),
        );
        let odd_body = Ast::IfThenElse(
            Box::new(app2("==", var("n"), Ast::Int(0))),
            Box::new(Ast::Bool(false)),
            Box::new(app1(var("even"), app2("-", var("n"), Ast::Int(1)))),
        );
        let bindings = vec![
            (
                "even".to_string(),
                Rc::new(Ast::Lambda("n".into(), Rc::new(even_body))),
            ),
            (
                "odd".to_string(),
                Rc::new(Ast::Lambda("n".into(), Rc::new(odd_body))),
            ),
        ];
        assert_deterministic(&Ast::LetRecIn(
            bindings,
            Box::new(Ast::Tuple(vec![
                app1(var("even"), Ast::Int(10)),
                app1(var("odd"), Ast::Int(7)),
            ])),
        ));
        // a non-function let-rec binding errors identically in both paths.
        assert_deterministic(&Ast::LetRecIn(
            vec![("x".into(), Rc::new(Ast::Int(1)))],
            Box::new(var("x")),
        ));
    }

    #[test]
    fn deterministic_records_lists_tuples_and_fields() {
        assert_deterministic(&Ast::Record(vec![
            ("a".into(), Ast::Int(1)),
            ("b".into(), Ast::Str("x".into())),
        ]));
        assert_deterministic(&Ast::List(vec![Ast::Int(1), Ast::Int(2), Ast::Int(3)]));
        assert_deterministic(&Ast::Tuple(vec![Ast::Int(1), Ast::Bool(true)]));
        // field access, present and absent (absent => identical error)
        let rec = Ast::Record(vec![("a".into(), Ast::Int(9)), ("b".into(), Ast::Int(8))]);
        assert_deterministic(&Ast::AccessField(
            Box::new(rec.clone()),
            "a".into(),
            Span::default(),
        ));
        assert_deterministic(&Ast::AccessField(
            Box::new(rec.clone()),
            "zzz".into(),
            Span::default(),
        ));
        // functional update, present and absent
        assert_deterministic(&Ast::UpdateField(
            Box::new(rec.clone()),
            "a".into(),
            Box::new(Ast::Int(100)),
        ));
        assert_deterministic(&Ast::UpdateField(
            Box::new(rec),
            "nope".into(),
            Box::new(Ast::Int(1)),
        ));
    }

    #[test]
    fn deterministic_match_arms_guards_and_ctors() {
        // int literal + wildcard
        assert_deterministic(&Ast::Match(
            Box::new(Ast::Int(3)),
            vec![
                MatchArm {
                    pat: Pattern::Int(1),
                    guard: None,
                    body: Ast::Str("one".into()),
                },
                MatchArm {
                    pat: Pattern::Wild,
                    guard: None,
                    body: Ast::Str("other".into()),
                },
            ],
        ));
        // guard selecting the second arm
        assert_deterministic(&Ast::Match(
            Box::new(Ast::Int(4)),
            vec![
                MatchArm {
                    pat: Pattern::Var("x".into()),
                    guard: Some(app2(">", var("x"), Ast::Int(10))),
                    body: Ast::Str("big".into()),
                },
                MatchArm {
                    pat: Pattern::Var("x".into()),
                    guard: Some(app2(">", var("x"), Ast::Int(0))),
                    body: Ast::Str("small".into()),
                },
                MatchArm {
                    pat: Pattern::Wild,
                    guard: None,
                    body: Ast::Str("np".into()),
                },
            ],
        ));
        // cons/empty-list, `as`, and ctor payload
        assert_deterministic(&Ast::Match(
            Box::new(Ast::List(vec![Ast::Int(1), Ast::Int(2)])),
            vec![
                MatchArm {
                    pat: Pattern::EmptyList,
                    guard: None,
                    body: Ast::Int(-1),
                },
                MatchArm {
                    pat: Pattern::Cons(
                        Box::new(Pattern::Var("h".into())),
                        Box::new(Pattern::Var("t".into())),
                    ),
                    guard: None,
                    body: var("h"),
                },
            ],
        ));
        assert_deterministic(&Ast::Match(
            Box::new(Ast::Ctor("Some".into(), Some(Box::new(Ast::Int(5))))),
            vec![
                MatchArm {
                    pat: Pattern::Ctor("None".into(), None),
                    guard: None,
                    body: Ast::Int(0),
                },
                MatchArm {
                    pat: Pattern::Ctor("Some".into(), Some(Box::new(Pattern::Var("x".into())))),
                    guard: None,
                    body: var("x"),
                },
            ],
        ));
        // non-exhaustive => identical error
        assert_deterministic(&Ast::Match(
            Box::new(Ast::Int(5)),
            vec![MatchArm {
                pat: Pattern::Int(1),
                guard: None,
                body: Ast::Int(0),
            }],
        ));
    }

    #[test]
    fn deterministic_mutable_while_and_sequential() {
        // let-mutable acc <- 0 in
        // let-mutable i <- 0 in
        //   (while i < 5 do (acc <- acc + i before i <- i + 1)) before !acc
        let deref = |n: &str| app1(var("!"), var(n));
        let loop_body = Ast::Sequential(
            Box::new(Ast::Overwrite(
                "acc".into(),
                Span::default(),
                Box::new(app2("+", deref("acc"), deref("i"))),
            )),
            Box::new(Ast::Overwrite(
                "i".into(),
                Span::default(),
                Box::new(app2("+", deref("i"), Ast::Int(1))),
            )),
        );
        let while_loop = Ast::WhileDo(
            Box::new(app2("<", deref("i"), Ast::Int(5))),
            Box::new(loop_body),
        );
        let prog = Ast::LetMutableIn(
            "acc".into(),
            Box::new(Ast::Int(0)),
            Box::new(Ast::LetMutableIn(
                "i".into(),
                Box::new(Ast::Int(0)),
                Box::new(Ast::Sequential(
                    Box::new(while_loop),
                    Box::new(deref("acc")),
                )),
            )),
        );
        assert_deterministic(&prog); // 0+1+2+3+4 = 10
    }

    // ---- document-level cross-check + shared prep for the doc benchmark ----

    /// Merge the `stdja-mini` prelude ahead of `src` (as the loader does),
    /// then elaborate + typecheck, returning `(base_env, elaborated body)`.
    fn prepare_document(src: &str) -> (BaseEnv, Ast) {
        let lib_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../lib-rustyfi/dist/packages/stdja-mini.satyh");
        let lib_src = std::fs::read_to_string(&lib_path).unwrap();
        let lib_file = rustyfi_syntax::parse_file(&lib_src).unwrap();
        let doc_file = rustyfi_syntax::parse_file(src).unwrap();
        let mut prelude = lib_file.prelude;
        prelude.extend(doc_file.prelude);
        let merged = rustyfi_syntax::cst::File {
            headers: Vec::new(),
            prelude,
            in_kw: doc_file.in_kw,
            body: doc_file.body,
            eoi: doc_file.eoi,
        };
        let env = crate::primitives::base_env();
        let store = crate::symbol::SymbolStore::new();
        let scope = crate::elaborate::Scope::new(&store, env.names());
        let program = crate::elaborate::elaborate_program(&merged, &scope).unwrap();
        crate::typecheck::typecheck(&program).unwrap();
        // De-brand before returning: the store is local to this helper, and
        // the tests below drive the runtime, which is `Symbol`-free.
        (env, crate::ast::debrand(&program.body, &store))
    }

    fn many_paragraph_src(n: usize) -> String {
        let mut body = String::new();
        for i in 0..n {
            body.push_str(&format!(
                "+p {{ paragraph number {i} with a few \\emph{{words}} to typeset here }}\n"
            ));
        }
        format!("document (||) '< {body} >")
    }

    #[test]
    fn deterministic_document_many_paragraphs() {
        let (env_a, body_a) = prepare_document(&many_paragraph_src(12));
        let doc_a = eval_compiled(&env_a, &body_a).unwrap();
        let (env_b, body_b) = prepare_document(&many_paragraph_src(12));
        let doc_b = eval_compiled(&env_b, &body_b).unwrap();
        // The whole typeset document (pages/boxes) must come out identical
        // from two independent elaborate -> typecheck -> compile -> run runs.
        assert_eq!(
            format!("{doc_a:?}"),
            format!("{doc_b:?}"),
            "two independent runs produced different documents"
        );
        assert!(matches!(doc_a, Value::Document(_)));
    }

    // ---- benchmarks (opt-in) ----------------------------------------------

    fn bench_ns<F: FnMut()>(iters: u32, mut f: F) -> f64 {
        f();
        let start = std::time::Instant::now();
        for _ in 0..iters {
            f();
        }
        start.elapsed().as_nanos() as f64 / iters as f64
    }

    #[test]
    #[ignore = "benchmark; run with --release -- --ignored --nocapture"]
    fn bench_fib() {
        const N: i64 = 28;
        // fib call count = 2*fib(N+1) - 1
        let calls = {
            let (mut a, mut b) = (0u64, 1u64);
            for _ in 0..=N + 1 {
                let t = a + b;
                a = b;
                b = t;
            }
            2 * a - 1
        };
        let prog = fib_program(N);
        let env = crate::primitives::base_env();

        // Compilation is one-off; time it separately from repeated execution.
        let build = bench_ns(20, || {
            let _ = compile_program(&prog, &env);
        });
        let compiled = compile_program(&prog, &env);
        let mono = Mono;
        let mut interp = Interp::new(&mono);
        let root = Env::root();
        let run = bench_ns(20, || {
            let _ = compiled.run(&root, &mut interp).unwrap();
        });

        println!("\n== fib({N}) : {calls} calls/eval ==");
        println!("  compile   : {build:>9.0} ns  (one-off)");
        println!(
            "  run       : {:>9.0} ns/eval  ({:>5.1} ns/call)",
            run,
            run / calls as f64
        );
    }

    #[test]
    #[ignore = "benchmark; run with --release -- --ignored --nocapture"]
    fn bench_many_paragraph_document() {
        const PARAS: usize = 300;
        let (env, body) = prepare_document(&many_paragraph_src(PARAS));

        let build = bench_ns(20, || {
            let _ = compile_program(&body, &env);
        });
        let compiled = compile_program(&body, &env);
        let mono = Mono;
        let mut interp = Interp::new(&mono);
        let root = Env::root();
        let run = bench_ns(20, || {
            let _ = compiled.run(&root, &mut interp).unwrap();
        });

        println!("\n== document with {PARAS} paragraphs ==");
        println!("  compile   : {build:>10.0} ns  (one-off)");
        println!("  run       : {run:>10.0} ns/doc");
    }
}