nova-driver 0.3.1

The Nova language's compilation pipeline (internal to the nova toolchain)
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
//! Compilation pipeline orchestration for Nova.
//!
//! Drives source → lex → parse → resolve → typecheck → MIR →
//! Cranelift (JIT for `nova run`, object emission + native linking for
//! `nova build`), rendering diagnostics from every stage through
//! `nova-diagnostics`. This is the crate behind `nova run`,
//! `nova build`, and `nova check`.

mod analyze;
mod link;
mod program;
mod runtime_cache;

pub use analyze::{analyze, analyze_program, Analysis, DiskSources, Options, Probe, Sources};
pub use program::{package_of, Program, Root, RootKind, Roots};
pub use runtime_cache::{set_embedded_runtime, EmbeddedRuntime};

use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use nova_codegen_cranelift::CompiledProgram;
use nova_diagnostics::{render, Diagnostic, FileDb, FileId, Severity, Span};
use nova_hir as hir;
use nova_hir::Ty;
use nova_pm::PackageId;
use nova_resolver::{Builtin, Def, DefId, DefKind, Definitions, ModuleId, ModuleSource, TestFn};
use program::Loaded;

/// Outcome of a pipeline invocation that may fail with user errors.
pub enum Outcome<T> {
    /// The pipeline succeeded.
    Ok(T),
    /// User-facing errors were reported (already rendered to stderr).
    Failed {
        /// Number of error-severity diagnostics.
        errors: usize,
    },
}

/// Type-check a file, printing diagnostics. `Outcome::Ok(())` means the
/// program is well-formed and would compile.
///
/// This also runs monomorphization (MIR lowering), since some checks —
/// notably trait-bound satisfaction — are performed there per
/// `12-TYPESYSTEM.md` §5.4. Without it `nova check` would call a program
/// "well-formed" that `nova run` / `nova build` then reject.
pub fn check_file(path: &Path) -> Result<Outcome<()>> {
    check_program(Program::for_file(path))
}

/// What [`check_program_counted`] rendered.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Checked {
    pub errors: usize,
    /// The warnings shown. A registry package's are not (spec 3.3b §5.4).
    pub warnings: usize,
}

/// [`check_file`] on `program` (spec 3.3a §5.1). MIR runs only when the
/// program runs: its entry is `src/main.nova`, or a loose file.
pub fn check_program(program: Program) -> Result<Outcome<()>> {
    let checked = check_program_counted(program)?;
    if checked.errors > 0 {
        Ok(Outcome::Failed {
            errors: checked.errors,
        })
    } else {
        Ok(Outcome::Ok(()))
    }
}

/// [`check_program`], counting the errors and warnings it rendered.
/// Publishing's verification fails on either (spec 3.3b §6.6).
pub fn check_program_counted(program: Program) -> Result<Checked> {
    let runs = program.runs;
    let mut ctx = FrontendContext::new(program)?;
    if let Some((module, _tests, _fresh_def_id)) = ctx.check(false)? {
        if runs {
            if let Err(diags) = nova_mir::lower_module(&module) {
                ctx.render(&diags);
            }
        }
    }
    Ok(Checked {
        errors: ctx.errors,
        warnings: ctx.warnings,
    })
}

/// Compile a file to native code via the Cranelift JIT.
pub fn compile_file(path: &Path) -> Result<Outcome<CompiledProgram>> {
    compile_program(Program::for_file(path))
}

/// [`compile_file`] on `program`.
pub fn compile_program(program: Program) -> Result<Outcome<CompiledProgram>> {
    let mir = match lower_to_mir(program)? {
        Outcome::Ok(mir) => mir,
        Outcome::Failed { errors } => return Ok(Outcome::Failed { errors }),
    };
    match nova_codegen_cranelift::compile_jit(&mir) {
        Ok(program) => Ok(Outcome::Ok(program)),
        Err(e) => {
            // An unresolvable `extern` symbol is a user error (the symbol isn't
            // in the C runtime / any loaded library), not a compiler bug — the
            // JIT can only discover it at finalize time. Report it as a clean
            // diagnostic, mirroring the `nova build` linker-error path.
            if let Some(sym) = e.downcast_ref::<nova_codegen_cranelift::UnresolvedExternSymbol>() {
                let diag = Diagnostic::error(
                    "E0902",
                    format!(
                        "{sym} at run time; an `extern` function must be provided by the \
                         C runtime or an already-loaded library (a `nova build` executable \
                         resolves it at link time instead)"
                    ),
                );
                render::emit_all(&FileDb::new(), &[diag]);
                return Ok(Outcome::Failed { errors: 1 });
            }
            Err(e).context("internal codegen error (this is a compiler bug)")
        }
    }
}

/// Compile a file to a standalone native executable (`nova build`).
///
/// Emits a Cranelift object file next to `output`, links it with the
/// `nova-runtime` static library through the platform linker, and removes
/// the intermediate object on success.
pub fn build_file(path: &Path, output: &Path) -> Result<Outcome<PathBuf>> {
    build_program(Program::for_file(path), output)
}

/// [`build_file`] on `program`.
pub fn build_program(program: Program, output: &Path) -> Result<Outcome<PathBuf>> {
    let mir = match lower_to_mir(program)? {
        Outcome::Ok(mir) => mir,
        Outcome::Failed { errors } => return Ok(Outcome::Failed { errors }),
    };
    let bytes = nova_codegen_cranelift::compile_object(&mir)
        .context("internal codegen error (this is a compiler bug)")?;

    let obj_ext = if cfg!(windows) { "obj" } else { "o" };
    let obj_path = intermediate(output, obj_ext);
    std::fs::write(&obj_path, bytes)
        .with_context(|| format!("failed to write {}", obj_path.display()))?;

    let linked = link::link_executable(&obj_path, output);
    let _ = std::fs::remove_file(&obj_path);
    linked?;
    Ok(Outcome::Ok(output.to_path_buf()))
}

/// An intermediate-file path derived from `output` that can never alias it:
/// the full output file name plus `.nova.<ext>` (so even `-o out.ll` /
/// `-o out.obj` yield a distinct `out.ll.nova.ll` / `out.obj.nova.obj` and the
/// final binary is never overwritten or deleted as an intermediate).
fn intermediate(output: &Path, ext: &str) -> PathBuf {
    let mut name = output
        .file_name()
        .map(|n| n.to_os_string())
        .unwrap_or_else(|| std::ffi::OsString::from("out"));
    name.push(".nova.");
    name.push(ext);
    output.with_file_name(name)
}

/// Compile a file to an optimized standalone executable via the LLVM backend
/// (`nova build --release`).
///
/// Emits textual LLVM IR next to `output`, compiles it to an object file with
/// a discovered LLVM toolchain (`clang`/`llc`, `-O2`), then links it with the
/// `nova-runtime` static library through the same platform linker as the debug
/// build. If no LLVM toolchain is found the generated `.ll` is left in place
/// and a helpful error is returned.
pub fn build_file_release(path: &Path, output: &Path) -> Result<Outcome<PathBuf>> {
    build_program_release(Program::for_file(path), output)
}

/// [`build_file_release`] on `program`.
pub fn build_program_release(program: Program, output: &Path) -> Result<Outcome<PathBuf>> {
    let mir = match lower_to_mir(program)? {
        Outcome::Ok(mir) => mir,
        Outcome::Failed { errors } => return Ok(Outcome::Failed { errors }),
    };
    let ir = nova_codegen_llvm::compile_ir(&mir)
        .context("internal LLVM IR generation error (this is a compiler bug)")?;

    let ll_path = intermediate(output, "ll");
    std::fs::write(&ll_path, ir.as_bytes())
        .with_context(|| format!("failed to write {}", ll_path.display()))?;

    let obj_ext = if cfg!(windows) { "obj" } else { "o" };
    let obj_path = intermediate(output, obj_ext);

    // Compile IR → object, then link. Keep the `.ll` on failure (for the LLVM
    // toolchain to be pointed at or for inspection); remove it on success.
    let result = link::compile_ir_to_object(&ll_path, &obj_path)
        .and_then(|()| link::link_executable(&obj_path, output));
    let _ = std::fs::remove_file(&obj_path);
    match result {
        Ok(()) => {
            let _ = std::fs::remove_file(&ll_path);
            Ok(Outcome::Ok(output.to_path_buf()))
        }
        Err(e) => Err(e.context(format!(
            "release build failed; generated LLVM IR left at {}",
            ll_path.display()
        ))),
    }
}

/// A name no Nova source can ever produce for a top-level function: the
/// lexer's identifier grammar is `[a-zA-Z_][a-zA-Z0-9_]*` (`nova-lexer/src/
/// lib.rs`'s `RawToken::Ident` regex), which cannot lex a `.` inside one
/// `Ident` token — the same "impossible in surface syntax" property
/// `nova_mir::mangle` already relies on (its symbols are `name.<def_id>`).
/// `build_test_binary` uses this to rename a user's own `main`, if the
/// source declares one, so it cannot be mistaken for the synthesized one.
const SHADOWED_USER_MAIN_NAME: &str = "main.shadowed_by_nova_test";

/// What every function called `main` outside the entry module is renamed
/// to (spec
/// `docs/superpowers/specs/2026-10-08-phase-3-3a-local-packages-design.md`
/// §4.6): a name the lexer cannot produce, like
/// [`SHADOWED_USER_MAIN_NAME`].
const NOT_THE_ENTRY_MAIN: &str = "main.not_the_entry";

/// The test function each doc test module adds (spec
/// `docs/superpowers/specs/2026-10-11-phase-3-5b-doc-tests-design.md`
/// §5.2): in a program of doc tests, the only `@test` function collected.
/// Each module is its own namespace, so each can use this name.
pub const DOC_TEST_FUNCTION: &str = "nova_doctest";

/// Rename every `main` declared outside the entry module, `ModuleId(0)`,
/// so that `nova_mir::lower_module`'s search by name finds the entry's own
/// `main`, or reports E0601 (spec 3.3a §4.6). A call reaches its function
/// by `DefId`, so the rename breaks no call.
fn keep_the_entry_main(module: &mut hir::Module, definitions: &Definitions) {
    for function in &mut module.functions {
        if function.name != "main" {
            continue;
        }
        let def = definitions.defs().get(function.def_id.0 as usize);
        if let Some(Def {
            kind: DefKind::Fn { item_index },
            ..
        }) = def
        {
            if definitions.module_of(*item_index) != ModuleId(0) {
                function.name = NOT_THE_ENTRY_MAIN.to_string();
            }
        }
    }
}

/// Name each test of a `tests/` file `<file stem>::<function>` (spec 3.3a
/// §4.6). The synthesized `main` prints these names as its inventory, so
/// `nova test` and the binary agree on them.
fn name_tests(tests: &mut [TestFn], definitions: &Definitions, modules: &[Loaded]) {
    for test in tests {
        let def = definitions.defs().get(test.def_id.0 as usize);
        let Some(Def {
            kind: DefKind::Fn { item_index },
            ..
        }) = def
        else {
            continue;
        };
        let module = definitions.module_of(*item_index).0 as usize;
        if let Some(module) = modules.get(module).filter(|m| m.test_file) {
            test.name = format!(
                "{}::{}",
                FrontendContext::module_name(&module.path),
                test.name
            );
        }
    }
}

/// Compile `path` as a test binary (`nova test`, Task 5): `main` is
/// synthesized to dispatch to exactly one collected `@test` by index
/// (`Builtin::TestSelector`) rather than to the file's own `main` — a test
/// file need not define one, since a missing `main` is enforced only at MIR
/// lowering (`E0601` in `nova_mir::lower_module`), which the synthesized
/// function supplies before that check ever runs.
///
/// If the source *does* declare its own `main`, that function is renamed
/// (never removed — something else in the module may still call it by
/// `DefId`) before the synthesized dispatcher is pushed, so the dispatcher
/// is the only function left named `"main"`. This matters because
/// `nova-mir/src/mono.rs`'s entry-point search is
/// `module.functions.iter().find(|f| f.name == "main")` — the *first*
/// match — while pushing onto `module.functions` puts the dispatcher
/// *last*: without the rename, a source file with both `@test` functions
/// and its own `main` would silently run the user's `main` instead of any
/// test, compiling and linking cleanly with no diagnostic anywhere.
///
/// Returns the built executable's path and the collected tests in source
/// order, so a caller can run the binary once per test with `NOVA_TEST_INDEX`
/// set without recompiling or re-deriving either the path or the inventory
/// from the source again.
pub fn build_test_binary(path: &Path) -> Result<(PathBuf, Vec<TestFn>)> {
    build_test_program(Program::for_file(path))
}

/// Rewrites a diagnostic before it is counted and rendered, with the
/// program's files at hand (spec
/// `docs/superpowers/specs/2026-10-11-phase-3-5b-doc-tests-design.md` §7):
/// it may move the diagnostic's labels into other files of the database,
/// adding them. `false` hides a warning; an error is always shown.
pub type MapDiagnostic<'a> = dyn Fn(&mut FileDb, &mut Diagnostic) -> bool + 'a;

/// The text of the std module a program's `FileDb` names `name`, such as
/// `<std/time>`, or `None` for any other name. The build adds std's modules
/// to the database only after loading, so a [`MapDiagnostic`] that shows a
/// diagnostic in one, as a std doc test's does (spec 3.5b §7), reads its
/// text here.
pub fn std_source(name: &str) -> Option<&'static str> {
    let short = name.strip_prefix("<std/")?.strip_suffix('>')?;
    nova_resolver::STD_MODULES
        .iter()
        .chain(std::iter::once(&nova_resolver::STD_TEST_MODULE))
        .find(|(module, _)| module.strip_prefix("$std.") == Some(short))
        .map(|&(_, text)| text)
}

/// [`build_test_binary`] on `program`: the test binary of its roots.
pub fn build_test_program(program: Program) -> Result<(PathBuf, Vec<TestFn>)> {
    build_test_program_with(program, &DiskSources, None)
}

/// [`build_test_program`], reading every module through `sources`, and
/// passing each diagnostic through `map` before it is counted and rendered
/// (spec 3.5b §7, §11.2). Doc tests are modules no file holds.
pub fn build_test_program_with(
    program: Program,
    sources: &dyn Sources,
    map: Option<&MapDiagnostic>,
) -> Result<(PathBuf, Vec<TestFn>)> {
    let entry = program
        .roots
        .first()
        .map(|root| root.path.clone())
        .unwrap_or_default();
    let mut ctx = FrontendContext::with(program, sources, map)?;
    let Some((mut module, tests, fresh_def_id)) = ctx.check(true)? else {
        anyhow::bail!(
            "could not compile due to {} previous error{}",
            ctx.errors,
            if ctx.errors == 1 { "" } else { "s" }
        );
    };
    for f in &mut module.functions {
        if f.name == "main" {
            f.name = SHADOWED_USER_MAIN_NAME.to_string();
        }
    }
    module
        .functions
        .push(synthesize_test_main(fresh_def_id, &tests));

    let mir = match nova_mir::lower_module(&module) {
        Ok(mir) => mir,
        Err(diags) => {
            ctx.render(&diags);
            anyhow::bail!(
                "could not compile due to {} previous error{}",
                ctx.errors,
                if ctx.errors == 1 { "" } else { "s" }
            );
        }
    };
    let bytes = nova_codegen_cranelift::compile_object(&mir)
        .context("internal codegen error (this is a compiler bug)")?;

    // A caller-distinguishing directory, keyed on the *canonicalized* input
    // path rather than its file stem: fixtures overwhelmingly share the
    // name `main.nova` (50 occurrences in this workspace's own
    // `nova-cli/tests/run_tests.rs` alone), so two different source files in
    // two different directories must not resolve to the same output path —
    // a real race under `cargo test`'s default parallelism (a locked-file
    // link error on Windows; a binary overwritten mid-execution on Unix).
    let dir = std::env::temp_dir()
        .join("nova-test-bin")
        .join(path_fingerprint(&entry));
    std::fs::create_dir_all(&dir).with_context(|| format!("failed to create {}", dir.display()))?;
    let output = dir.join(format!(
        "{}{}",
        FrontendContext::module_name(&entry),
        std::env::consts::EXE_SUFFIX
    ));

    let obj_ext = if cfg!(windows) { "obj" } else { "o" };
    let obj_path = intermediate(&output, obj_ext);
    std::fs::write(&obj_path, bytes)
        .with_context(|| format!("failed to write {}", obj_path.display()))?;

    let linked = link::link_executable(&obj_path, &output);
    let _ = std::fs::remove_file(&obj_path);
    linked?;
    Ok((output, tests))
}

/// A short, deterministic fingerprint of `path`'s canonicalized form, for
/// `build_test_binary`'s output directory. Canonicalizing first means two
/// different relative spellings of the same file collide on purpose, while
/// two files that merely share a name in different directories do not. A
/// path no file holds, such as a doc test's (spec 3.5b §11.2), is joined
/// onto the current directory instead, so two packages' relative
/// `<doc tests>/doc0.nova` do not share a binary.
fn path_fingerprint(path: &Path) -> String {
    let canon = path.canonicalize().unwrap_or_else(|_| {
        std::env::current_dir()
            .map(|dir| dir.join(path))
            .unwrap_or_else(|_| path.to_path_buf())
    });
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    canon.hash(&mut hasher);
    format!("{:016x}", hasher.finish())
}

/// A zero-width span at the dummy file: there is no source location for a
/// hand-built `hir::Function`, so every node `synthesize_test_main` builds
/// uses the same sentinel `FileId::DUMMY` documents itself for.
fn dummy_span() -> Span {
    Span::point(0, FileId::DUMMY)
}

fn expr(kind: hir::ExprKind, ty: Ty) -> hir::Expr {
    hir::Expr {
        kind,
        ty,
        span: dummy_span(),
    }
}

/// Build the dispatching `main` that `build_test_binary` adds to the module.
///
/// Constructed directly as an `hir::Function` — mirroring the synthetic
/// `main` `nova-mir/src/mono.rs`'s own unit tests build, field for field —
/// rather than as generated Nova source. Generated source is how `std`
/// reaches a program, but it would route through the resolver, which
/// enforces `pub`, and `@test` functions are deliberately not `pub`;
/// constructing the HIR directly sidesteps visibility rather than fighting
/// it. Because `nova-mir/src/mono.rs`'s monomorphizer locates the entry point
/// by the name `"main"`, not by `def_id`, nothing downstream needs to know
/// this particular `main` was synthesized rather than parsed.
///
/// Body: bind `test_selector()` to local 0 (`sel`), then one
/// `if sel == i { test_i() }` per collected test in source order, then
/// (reached only when `sel` matched none of them — including whenever
/// `sel < 0`, the documented sentinel) print the inventory: a count line,
/// then one name per line.
fn synthesize_test_main(main_id: DefId, tests: &[TestFn]) -> hir::Function {
    let sel = hir::LocalId(0);

    let mut stmts = vec![expr(
        hir::ExprKind::Let {
            local: sel,
            init: Box::new(expr(
                hir::ExprKind::Call {
                    func: hir::Callee::Builtin(Builtin::TestSelector),
                    type_args: Vec::new(),
                    args: Vec::new(),
                },
                Ty::Int,
            )),
        },
        Ty::Unit,
    )];

    for (i, t) in tests.iter().enumerate() {
        let cond = expr(
            hir::ExprKind::Binary {
                op: hir::BinOp::Eq,
                lhs: Box::new(expr(hir::ExprKind::Local(sel), Ty::Int)),
                rhs: Box::new(expr(hir::ExprKind::IntLit(i as i64), Ty::Int)),
            },
            Ty::Bool,
        );
        let call = expr(
            hir::ExprKind::Call {
                func: hir::Callee::Def(t.def_id),
                type_args: Vec::new(),
                args: Vec::new(),
            },
            // `nova-resolver`'s `test_shape_violations` rejects a `@test`
            // function that is `async` or returns non-`Unit` (E0084), so every
            // callee here is an ordinary `Unit`-typed function. Both halves are
            // load-bearing: the direct call below neither awaits nor polls, so
            // an `async` callee would be the future-building wrapper and this
            // `if` would allocate a state object and discard it, running none
            // of the test's body.
            Ty::Unit,
        );
        stmts.push(expr(
            hir::ExprKind::If {
                cond: Box::new(cond),
                then: Box::new(call),
                else_: None,
            },
            Ty::Unit,
        ));
    }

    let println = |s: String| {
        expr(
            hir::ExprKind::Call {
                func: hir::Callee::Builtin(Builtin::Println),
                type_args: Vec::new(),
                args: vec![expr(hir::ExprKind::StrLit(s), Ty::String)],
            },
            Ty::Unit,
        )
    };
    let mut inventory = vec![println(tests.len().to_string())];
    inventory.extend(tests.iter().map(|t| println(t.name.clone())));
    let sel_is_negative = expr(
        hir::ExprKind::Binary {
            op: hir::BinOp::Lt,
            lhs: Box::new(expr(hir::ExprKind::Local(sel), Ty::Int)),
            rhs: Box::new(expr(hir::ExprKind::IntLit(0), Ty::Int)),
        },
        Ty::Bool,
    );
    stmts.push(expr(
        hir::ExprKind::If {
            cond: Box::new(sel_is_negative),
            then: Box::new(expr(
                hir::ExprKind::Block {
                    stmts: inventory,
                    trailing: None,
                },
                Ty::Unit,
            )),
            else_: None,
        },
        Ty::Unit,
    ));

    hir::Function {
        def_id: main_id,
        name: "main".to_string(),
        generics: 0,
        bounds: Vec::new(),
        takes_env: false,
        capture_count: 0,
        params: 0,
        locals: vec![hir::Local {
            name: "sel".to_string(),
            ty: Ty::Int,
            is_mut: false,
            span: dummy_span(),
        }],
        ret_ty: Ty::Unit,
        // The synthesized `@test` harness entry point is plain generated
        // dispatch code (a chain of `if sel == i { test_i() }`), never a
        // user-written `async fn` — so it is never async.
        is_async: false,
        body: expr(
            hir::ExprKind::Block {
                stmts,
                trailing: None,
            },
            Ty::Unit,
        ),
        span: dummy_span(),
    }
}

/// Run the front end and MIR lowering, rendering any diagnostics.
fn lower_to_mir(program: Program) -> Result<Outcome<nova_mir::Module>> {
    let mut ctx = FrontendContext::new(program)?;
    let Some((module, _tests, _fresh_def_id)) = ctx.check(false)? else {
        return Ok(Outcome::Failed { errors: ctx.errors });
    };
    match nova_mir::lower_module(&module) {
        Ok(mir) => Ok(Outcome::Ok(mir)),
        Err(diags) => {
            ctx.render(&diags);
            Ok(Outcome::Failed { errors: ctx.errors })
        }
    }
}

/// Compile and immediately execute a file (`nova run`), with `args` as the
/// program's arguments: `std/process`'s `args()` returns exactly this list.
pub fn run_file(path: &Path, args: Vec<String>) -> Result<Outcome<()>> {
    run_program(Program::for_file(path), args)
}

/// [`run_file`] on `program`.
pub fn run_program(program: Program, args: Vec<String>) -> Result<Outcome<()>> {
    match compile_program(program)? {
        Outcome::Ok(program) => {
            program.run_with_args(args);
            Ok(Outcome::Ok(()))
        }
        Outcome::Failed { errors } => Ok(Outcome::Failed { errors }),
    }
}

/// Shared front-end state: what to load, the file database, and error
/// accounting.
struct FrontendContext<'a> {
    db: FileDb,
    graph: Option<nova_pm::Graph>,
    roots: Vec<Root>,
    errors: usize,
    warnings: usize,
    /// The registry packages' modules, once loaded: a warning only about
    /// them is not shown.
    registry_files: HashSet<FileId>,
    /// Where every module is read (spec 3.5b §11.2).
    sources: &'a dyn Sources,
    /// Called on each diagnostic before it is counted and rendered (spec
    /// 3.5b §7).
    map: Option<&'a MapDiagnostic<'a>>,
}

impl<'a> FrontendContext<'a> {
    /// Take `program`, rendering its graph's diagnostics. When they hold
    /// no error, the entry must exist: imported modules are read lazily.
    fn new(program: Program) -> Result<Self> {
        FrontendContext::with(program, &DiskSources, None)
    }

    /// [`FrontendContext::new`], reading every module through `sources`
    /// and passing each diagnostic through `map`.
    fn with(
        program: Program,
        sources: &'a dyn Sources,
        map: Option<&'a MapDiagnostic<'a>>,
    ) -> Result<Self> {
        let Program {
            db,
            graph,
            roots,
            diagnostics,
            ..
        } = program;
        let mut ctx = FrontendContext {
            db,
            graph,
            roots,
            errors: 0,
            warnings: 0,
            registry_files: HashSet::new(),
            sources,
            map,
        };
        ctx.render(&diagnostics);
        if ctx.errors == 0 {
            let entry = ctx
                .entry()
                .context("nothing to compile: the package has no source file for this")?;
            ctx.sources
                .read(entry)
                .with_context(|| format!("failed to open {}", entry.display()))?;
        }
        Ok(ctx)
    }

    /// The first root.
    fn entry(&self) -> Option<&Path> {
        self.roots.first().map(|root| root.path.as_path())
    }

    fn render(&mut self, diagnostics: &[Diagnostic]) {
        let mut shown: Vec<Diagnostic> = diagnostics
            .iter()
            .filter(|d| !program::a_dependencys_warning(d, &self.registry_files))
            .cloned()
            .collect();
        if let Some(map) = self.map {
            let db = &mut self.db;
            shown.retain_mut(|d| map(db, d) || d.severity == Severity::Error);
        }
        self.errors += shown
            .iter()
            .filter(|d| d.severity == Severity::Error)
            .count();
        self.warnings += shown
            .iter()
            .filter(|d| d.severity == Severity::Warning)
            .count();
        if !shown.is_empty() {
            render::emit_all(&self.db, &shown);
        }
    }

    /// The module name for a source path — its file stem.
    fn module_name(path: &Path) -> String {
        path.file_stem()
            .map(|s| s.to_string_lossy().into_owned())
            .unwrap_or_else(|| "main".to_string())
    }

    /// Load, lex and parse every module the roots reach, through
    /// `sources`, rendering the lex, parse and import diagnostics. The
    /// loading itself is [`program::load_program`], which the language
    /// server shares.
    fn load_modules(&mut self) -> Result<Vec<Loaded>> {
        let entry = self.entry().map(Path::to_path_buf).unwrap_or_default();
        let load =
            program::load_program(self.graph.as_ref(), &self.roots, self.sources, &mut self.db)
                .with_context(|| format!("failed to read {}", entry.display()))?;
        self.registry_files = program::registry_files(self.graph.as_ref(), &load.modules);
        self.render(&load.diagnostics);
        Ok(load.modules)
    }

    /// Run load → lex → parse → resolve → typecheck across all modules.
    /// Returns the merged typed module, the `@test` functions collected along
    /// the way (source order, per `nova_resolver::TestFn`'s doc comment), and
    /// a `DefId` that no definition and no function of the module holds — or
    /// `None` if any stage reported errors.
    ///
    /// `with_test_module` seeds `std/test` (`assert`/`assert_eq`/`assert_ne`)
    /// alongside every `STD_MODULES` entry, so it is glob-imported the same way — but
    /// only when `true`. `build_test_binary` is the only caller that passes
    /// `true`; `check_file` and `lower_to_mir` (behind `check_file`,
    /// `compile_file`, `build_file`, `build_file_release`) pass `false`, so
    /// those names never resolve in an ordinary compile.
    ///
    /// The fresh `DefId` is past both kinds of id the module holds.
    /// `Definitions` documents `defs` as one global counter shared by every
    /// definition kind (functions, sums, records, traits, methods, externs,
    /// associated types), allocated by `push_def` in strict `Vec::len()`
    /// order, so every id resolution handed out is `< defs().len()`. The type
    /// checker then numbers the functions it lifts for closures and for named
    /// functions used as values from `defs().len()` on, so the fresh id is
    /// also past every function's. `build_test_binary` uses it to name a
    /// synthesized `main` that cannot alias an id a `@test` function or a
    /// lifted closure already owns.
    fn check(
        &mut self,
        with_test_module: bool,
    ) -> Result<Option<(nova_hir::Module, Vec<TestFn>, DefId)>> {
        // The graph's errors were rendered by `new`.
        if self.errors > 0 {
            return Ok(None);
        }
        let mut modules = self.load_modules()?;
        if self.errors > 0 {
            return Ok(None);
        }
        // Whole-branch review, finding 1 (Critical): a `@test` function's
        // body is written assuming `std/test`'s `assert`/`assert_eq`/
        // `assert_ne` are in scope, which — per the doc comment above — is
        // true only when `with_test_module` is `true`. Left in the
        // compilation unit under `nova run`/`build`/`check`, such a body's
        // calls to them fail to resolve (`E0001`), which means a program
        // could never both `nova build` and `nova test` cleanly, and `nova
        // check` (the editor path) reported spurious errors on every test in
        // the project. Stripping the items here — before any of them reaches
        // `nova_resolver::resolve_program` — removes the problem instead of
        // working around it: a stripped function gets no `DefId`, no scope
        // entry, and its body is never visited by anything downstream, the
        // same "does not exist in this build" semantics as Rust's
        // `#[cfg(test)]`. See `strip_test_functions`'s own doc comment for
        // why this must happen *before* resolution rather than after.
        //
        // Phase 3.3a: under `nova test` the root package's tests are
        // kept and a dependency's stripped (spec
        // docs/superpowers/specs/2026-10-08-phase-3-3a-local-packages-design.md
        // §4.6). Phase 3.5b: a program of doc tests keeps only the test
        // each doc test adds (spec 3.5b §5.2).
        strip_test_functions(&mut modules, with_test_module);
        // Register each embedded std module's source in the `FileDb` so a
        // syntax error inside one (a compiler bug, since they ship with the
        // compiler) is reported against a real, named file instead of
        // `FileId::DUMMY`. One id per `nova_resolver::STD_MODULES` entry, in
        // order — e.g. `$std.core` names `<std/core>`.
        let std_files: Vec<FileId> = nova_resolver::STD_MODULES
            .iter()
            .map(|&(name, src)| {
                let short = name.strip_prefix("$std.").unwrap_or(name);
                self.db.add(format!("<std/{short}>"), src)
            })
            .collect();
        // `std/test`, registered the same way but only under `nova test`
        // (`with_test_module`): one more `FileId` allocated *conditionally*,
        // which is fine precisely because it rides alongside `STD_MODULES`
        // rather than being folded into it — nothing computes an index from
        // `STD_MODULES.len()` expecting it to already include this entry.
        let extra_std = with_test_module.then(|| {
            let (name, src) = nova_resolver::STD_TEST_MODULE;
            let short = name.strip_prefix("$std.").unwrap_or(name);
            let file_id = self.db.add(format!("<std/{short}>"), src);
            (nova_resolver::STD_TEST_MODULE, file_id)
        });
        let sources: Vec<ModuleSource> = modules
            .iter()
            .map(|m| ModuleSource {
                name: m.name.clone(),
                file: &m.ast,
                imports: m.imports.clone(),
                text: self.db.get_source(m.file),
                package: m.package.map(|p| p.0),
                importable: m.importable.clone(),
            })
            .collect();
        let resolved = nova_resolver::resolve_program(&sources, &std_files, extra_std);
        self.render(&resolved.diagnostics);
        if self.errors > 0 {
            return Ok(None);
        }
        let mut tests = resolved.tests;
        name_tests(&mut tests, &resolved.definitions, &modules);

        let checked = nova_typeck::check_with(
            &resolved.file,
            &resolved.definitions,
            &nova_typeck::CheckOptions {
                sources: Some(&self.db),
                ..Default::default()
            },
        );
        self.render(&checked.diagnostics);
        if self.errors > 0 {
            return Ok(None);
        }
        let mut module = checked.module;
        keep_the_entry_main(&mut module, &resolved.definitions);
        let fresh_def_id = DefId(
            module
                .functions
                .iter()
                .map(|f| f.def_id.0 + 1)
                .fold(resolved.definitions.defs().len() as u32, u32::max),
        );
        Ok(Some((module, tests, fresh_def_id)))
    }
}

/// Remove top-level `@test` functions from `modules`, in place, before
/// resolution:
/// - without `keep_root_tests` (`nova run`, `build` and `check`), every one;
/// - with it (`nova test`, and the language server's `tests` option), a
///   dependency's, whose tests never run in its dependent's binary (spec
///   3.3a §4.6), keeping the root package's and a loose program's;
/// - with it, in a program of doc tests (spec
///   `docs/superpowers/specs/2026-10-11-phase-3-5b-doc-tests-design.md`
///   §5.2, §6.2), every one but the [`DOC_TEST_FUNCTION`] each doc test
///   module adds: the library's tests run in the unit tests' binary, and a
///   `@test` function a block declares is not collected.
///
/// What follows was written when this ran only for `nova run`, `build`
/// and `check`, and every module was the program's own; why a test is
/// removed before resolution still holds for every one it removes.
///
/// A `@test` function is ordinary Nova source with no special compilation
/// unit of its own — before this fix, `nova_resolver::resolve_program` collected it,
/// gave it a `DefId`, and `nova_typeck::check` type-checked its body exactly
/// like any other function, regardless of `with_test_module`. That body is
/// written assuming `std/test`'s `assert`/`assert_eq`/`assert_ne` are in
/// scope; they are seeded only under `nova test` (this file's own doc
/// comment on `check`), so under every other compilation mode those calls
/// failed to resolve (`E0001`) — a program containing so much as one test
/// could not be built or checked at all, and `nova check` (the editor path)
/// reported spurious errors on every test in the project on every keystroke.
///
/// **Removed here, before `resolve_program` ever runs**, rather than kept
/// through resolution and typeck and discarded afterward. Two designs were
/// available and only one is actually correct:
///
/// - *Strip before resolution* (this one): the function never gets a
///   `DefId`, never enters its module's scope, and its body is never visited
///   by anything — the same "does not exist in this build" semantics as
///   Rust's `#[cfg(test)]`. Anything that still tries to call it by name
///   (unusual, but not forbidden by anything in the language) gets the
///   ordinary, well-tested "cannot find function" `E0001`, exactly as if the
///   function had never been written.
/// - *Strip after resolution* (e.g. filter `nova_typeck::check`'s per-`DefId`
///   iteration instead): resolution would still assign the function a real
///   `DefId` and scope entry, and `collect_signatures` runs before any
///   per-function body pass, so *other*, kept, functions could still
///   type-check a call to it successfully against a signature that then has
///   no corresponding `hir::Function` body in the compiled module — a
///   dangling `DefId` reference that MIR lowering has no defined behavior
///   for. This is strictly worse than the bug being fixed: today's failure
///   is a clean compile error; that failure mode would be a compiler panic
///   or a silently broken binary, and only in the one case where non-test
///   code happens to reference a test function by name.
///
/// Deliberately done in `nova-driver`, not `nova_resolver`, and keyed off
/// this driver's own `with_test_module` rather than any new parameter on
/// `nova_resolver::resolve_program`: `nova_resolver::resolve`/`resolve_program`
/// are also called directly, with no notion of "compiling for `nova test`",
/// by a large fraction of `nova-resolver`'s and `nova-typeck`'s own unit
/// tests — including the very tests that pin `E0082`-`E0085` and `TestFn`
/// collection on `@test` functions (`nova-typeck/src/check.rs`'s
/// `an_unknown_attribute_is_e0082_and_names_it` and neighbors). Teaching
/// `resolve_program` to drop `@test` items itself, gated on whether it was
/// given `extra_std`, would silently empty out every one of those functions'
/// subject items before validation ever ran, breaking them. Confining the
/// strip to this driver function leaves `nova_resolver`'s validation and
/// collection behavior — and every test that exercises it directly —
/// completely unchanged.
///
/// As a consequence, `nova_resolver::validate_test_function`'s attribute-
/// shape diagnostics (`E0082`-`E0085`) do not fire for a stripped function
/// — matching `#[cfg(test)]`, where an invalid test signature is likewise
/// uncaught outside `cargo test`. `nova test` validates the shape of every
/// `@test` function it keeps.
fn strip_test_functions(modules: &mut [Loaded], keep_root_tests: bool) {
    let doc_tests = modules.iter().any(|m| m.doc);
    for module in modules.iter_mut() {
        let root = matches!(module.package, None | Some(PackageId(0)));
        let doc = module.doc;
        module.ast.items.retain(|item| match &item.value {
            nova_ast::Item::Function(f) if f.attrs.iter().any(|a| a.name.value == "test") => {
                keep_root_tests
                    && if doc_tests {
                        doc && f.name.value == DOC_TEST_FUNCTION
                    } else {
                        root
                    }
            }
            _ => true,
        });
    }
}

/// What doc tests need of a build (spec
/// `docs/superpowers/specs/2026-10-11-phase-3-5b-doc-tests-design.md`
/// §7, §11.2), where only this crate can see it.
#[cfg(test)]
mod doc_test_builds {
    use super::*;

    /// Every path holds an empty program.
    struct Memory;

    impl Sources for Memory {
        fn read(&self, _: &Path) -> std::io::Result<String> {
            Ok("fn main() {}\n".to_string())
        }
    }

    #[test]
    fn a_map_hides_the_warnings_it_rejects_and_never_an_error() {
        let map = |_: &mut FileDb, _: &mut Diagnostic| false;
        let program = Program::loose(Path::new("<nova driver: memory>/main.nova"));
        let mut ctx = FrontendContext::with(program, &Memory, Some(&map)).expect("the entry reads");
        ctx.render(&[
            Diagnostic::warning("W0000", "a warning"),
            Diagnostic::error("E0000", "an error"),
        ]);
        assert_eq!((ctx.errors, ctx.warnings), (1, 0));
    }

    #[test]
    fn a_path_no_file_holds_is_fingerprinted_from_the_current_directory() {
        // Two packages' relative `<doc tests>/doc0.nova` must not share a
        // test binary.
        let relative = Path::new("<nova driver: no such dir>").join("doc0.nova");
        let absolute = std::env::current_dir()
            .expect("a current directory")
            .join(&relative);
        assert_eq!(path_fingerprint(&relative), path_fingerprint(&absolute));
    }

    #[test]
    fn std_source_gives_a_std_modules_text_by_its_name_in_the_database() {
        assert_eq!(
            std_source("<std/core>"),
            Some(nova_resolver::STD_MODULES[0].1)
        );
        assert_eq!(
            std_source("<std/time>"),
            Some(nova_resolver::STD_MODULES[10].1)
        );
        assert_eq!(
            std_source("<std/test>"),
            Some(nova_resolver::STD_TEST_MODULE.1)
        );
        assert_eq!(std_source("<std/nope>"), None);
        assert_eq!(std_source("std/time/lib.nova"), None);
        assert_eq!(std_source("src/lib.nova"), None);
    }
}

/// End-to-end proof that a generated `async fn` actually *runs*: the future
/// this compiler builds, JIT-compiled, driven by the real `nova-runtime`
/// executor, with the value read back out of the state object's output slot.
///
/// This lives here rather than in `nova-codegen-cranelift` (which owns the
/// MIR → native seam) or `nova-cli` (which owns `nova run`) because it needs
/// both halves at once: the whole front end, to get real MIR out of real
/// source, and an in-process runtime, to poll the resulting future and inspect
/// the answer. `nova-driver` is the only crate that already has the front end
/// and the JIT; `nova-runtime` is a dev-dependency for the executor entry
/// points.
///
/// **Why `main` is synthesized in MIR instead of written in Nova.** Nothing in
/// the language can reach `block_on` yet. Not because a future cannot be
/// *named* — `Future` is a nameable type, handled by `nova-typeck`'s
/// `convert_ty` ahead of its primitive table, so `fn take(f: Future<Int>)`
/// type-checks — but because nothing in source can *drive* one: there is no
/// poll or await outside an `async fn`, and an `extern` signature accepts only
/// `Int`, `Float` and `Bool`, so no foreign function can be handed one either.
/// Task 7's `std/task` is what closes that. Until then the only way to
/// *execute* a generated poll function is to
/// build the calling code at the level where futures do exist — MIR — which is
/// exactly the level `nova-cli`'s `nova run` tests cannot reach. So those tests
/// assert that such a program compiles and runs; these assert that it computes
/// the right value.
#[cfg(test)]
mod async_end_to_end {
    use nova_diagnostics::FileId;
    use nova_mir::{Function, MirTy, Module, RtFunc, Stmt, Temp, Terminator};

    /// One probe per test, because the executor's task table is a
    /// `thread_local!` and libtest gives each `#[test]` its own thread: the
    /// probe's own task is therefore always id 0. A second probe on the same
    /// thread would shift the ids and make `output_bits(0)` quietly return the
    /// first probe's answer, so that is refused rather than reasoned about.
    const PROBE_TASK_ID: i64 = 0;

    thread_local! {
        static PROBED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    }

    /// An argument to pass to the async function under test.
    enum Arg {
        Int(i64),
        Float(f64),
    }

    /// Compile `src`, call its `async fn <name>` with `args`, drive the
    /// resulting future to completion through the real executor, and return
    /// the raw 64 bits of its output slot.
    ///
    /// Raw bits, not a typed value: `STATE_SLOT_OUTPUT` is one 8-byte slot that
    /// the poll function stores through with the output's own machine class, and
    /// the executor copies out as an `i64` because it cannot tell a `Float` from
    /// an `Int` from a pointer. Comparing against `f64::to_bits` is therefore
    /// the strongest available check on a `Float` output — it fails if the store
    /// or the load used the wrong class, the wrong offset, or the wrong width.
    fn run_async_fn(src: &str, name: &str, args: &[Arg]) -> i64 {
        run_async_fn_with(src, name, args, &|_| {})
    }

    /// As [`run_async_fn`], with `fixup` applied to the lowered module before it
    /// is compiled.
    ///
    /// The hook exists for exactly one thing: substituting a poll function that
    /// actually suspends. Nothing compiled from Nova source can, in this phase —
    /// every future's poll either completes on its first call or stops at an
    /// await, and the awaits bottom out in an `async fn` with none, so the whole
    /// chain reports `POLL_READY` on the first poll. The `POLL_PENDING` path
    /// through a generated poll function is therefore unreachable from source
    /// until a primitive that parks exists, and the only way to execute it now is
    /// to hand the *awaiting* function -- real generated code, unmodified -- an
    /// inner future whose poll pends.
    fn run_async_fn_with(src: &str, name: &str, args: &[Arg], fixup: &dyn Fn(&mut Module)) -> i64 {
        assert!(
            !PROBED.with(|p| p.replace(true)),
            "one probe per test: see PROBE_TASK_ID"
        );

        let (tokens, lex_errors) = nova_lexer::lex(src, FileId::DUMMY);
        assert!(lex_errors.is_empty(), "lex: {lex_errors:?}");
        let (ast, parse_errors) = nova_parser::parse(&tokens, FileId::DUMMY);
        assert!(parse_errors.is_empty(), "parse: {parse_errors:?}");
        let resolved = nova_resolver::resolve(&ast.expect("no AST"));
        assert!(
            resolved.diagnostics.is_empty(),
            "resolve: {:?}",
            resolved.diagnostics
        );
        let checked = nova_typeck::check(&resolved.file, &resolved.definitions);
        assert!(
            checked.diagnostics.is_empty(),
            "typeck: {:?}",
            checked.diagnostics
        );
        let mut mir = nova_mir::lower_module(&checked.module).expect("MIR lowering");

        // The wrapper: the half of the transform that kept the original
        // mangled symbol. Its `$poll` sibling is deliberately NOT called
        // directly -- going through the wrapper is what exercises the state
        // allocation, the parameter seeding and the fat-pointer construction.
        let prefix = format!("{name}.");
        let wrapper = mir
            .functions
            .iter()
            .map(|f| f.name.clone())
            .find(|n| n.starts_with(&prefix) && !n.ends_with("$poll"))
            .unwrap_or_else(|| {
                panic!(
                    "no wrapper for `{name}`; have {:?}",
                    mir.functions.iter().map(|f| &f.name).collect::<Vec<_>>()
                )
            });
        assert!(
            mir.functions
                .iter()
                .any(|f| f.name == format!("{wrapper}$poll")),
            "the transform must also have emitted `{wrapper}$poll`"
        );

        fixup(&mut mir);
        replace_main(&mut mir, &wrapper, args);
        let program = nova_codegen_cranelift::compile_jit(&mir).expect("JIT compile");
        program.run();

        // A poll function returning a status that is neither POLL_PENDING nor
        // POLL_READY does not reach this call at all, and does not present as
        // a test failure either. `poll_one` panics naming the value, and that
        // panic then has to unwind out through the JIT-compiled `main` frame --
        // Cranelift output with no landing pads -- so **the process dies** and
        // the harness reports only that the test exited abnormally. Run the one
        // test with `-- --nocapture` to see the executor's message, which does
        // name the offending status.
        //
        // A task left queued rather than polled -- the other failure shape --
        // is caught by `output_bits` itself: it asserts the task is done
        // before handing back its output, so that case panics here with its
        // own message rather than silently returning the `output: 0`
        // initializer. There is no `nova_rt_task_is_done` pre-check for it any
        // more: that entry point now takes a future, not a task id, and this
        // harness only ever kept `PROBE_TASK_ID`, the id `TaskSpawn` returned
        // to the JIT-compiled `main` -- the future itself was never a value
        // this Rust frame held, so there is nothing to pass it.
        //
        // `output_bits` rather than `nova_rt_task_take_output`: the probe is a
        // *spawned* task, and a spawned task's GC root is released at
        // completion, so its output can no longer be taken. Every probe in
        // this module returns a scalar (`Int`, `Float`, `Bool` or unit),
        // which is what `output_bits` is for -- its bits are read, not
        // dereferenced.
        nova_runtime::task::output_bits(PROBE_TASK_ID)
    }

    /// Overwrite `main` with MIR that builds the future twice: once spawned as
    /// the probe (whose output copy the caller reads with `output_bits`), and
    /// once as `block_on`'s root, whose only job is to drain the queue so the
    /// probe gets polled. Two separate futures, because one future must not be
    /// registered as two tasks sharing a state object.
    fn replace_main(mir: &mut Module, wrapper: &str, args: &[Arg]) {
        let mut temps: Vec<MirTy> = Vec::new();
        let mut stmts: Vec<Stmt> = Vec::new();
        fn push(temps: &mut Vec<MirTy>, ty: MirTy) -> Temp {
            let t = Temp(temps.len() as u32);
            temps.push(ty);
            t
        }

        let mut arg_temps = Vec::new();
        for a in args {
            match a {
                Arg::Int(v) => {
                    let t = push(&mut temps, MirTy::I64);
                    stmts.push(Stmt::ConstInt(t, *v));
                    arg_temps.push(t);
                }
                Arg::Float(v) => {
                    let t = push(&mut temps, MirTy::F64);
                    stmts.push(Stmt::ConstFloat(t, *v));
                    arg_temps.push(t);
                }
            }
        }

        for spawn in [true, false] {
            let fut = push(&mut temps, MirTy::Ptr);
            stmts.push(Stmt::Call {
                dst: Some(fut),
                callee: wrapper.to_string(),
                args: arg_temps.clone(),
            });
            let status = push(&mut temps, MirTy::I64);
            stmts.push(Stmt::CallRuntime {
                dst: Some(status),
                func: if spawn {
                    RtFunc::TaskSpawn
                } else {
                    RtFunc::TaskBlockOn
                },
                args: vec![fut],
            });
        }

        let main = mir
            .functions
            .iter_mut()
            .find(|f| f.name == "main")
            .expect("`main` was lowered");
        *main = Function {
            name: "main".to_string(),
            params: 0,
            takes_env: false,
            capture_count: 0,
            temps,
            ret: MirTy::Unit,
            is_async: false,
            blocks: vec![nova_mir::Block {
                stmts,
                term: Terminator::Return(None),
            }],
        };
    }

    #[test]
    fn an_await_free_async_fn_returning_int_runs_and_produces_its_value() {
        let out = run_async_fn(
            "async fn f() -> Int { 40 + 2 }\nfn main() { let x = f() }",
            "f",
            &[],
        );
        assert_eq!(out, 42);
    }

    /// **The `Float` case, and the one that matters most.** `mir_ty` collapses
    /// `Int`, `Char` and every pointer-like type onto one 64-bit integer class,
    /// so an `Int` probe passes even if the output is stored, loaded or
    /// returned through the wrong one of them. `F64` is the only class that
    /// crosses register banks, and the exact type at which this project already
    /// shipped a reachable ICE: an `async fn f() -> Float { 1.5 }` merely
    /// called from `main` hit a Cranelift verifier error that the `Int` version
    /// silently survived.
    #[test]
    fn an_await_free_async_fn_returning_float_runs_and_produces_its_value() {
        let out = run_async_fn(
            "async fn f() -> Float { 1.5 }\nfn main() { let x = f() }",
            "f",
            &[],
        );
        assert_eq!(
            out as u64,
            1.5f64.to_bits(),
            "the output slot must hold 1.5 as an f64 bit pattern, not an \
             integer 1 or a truncation: got {out:#x}, want {:#x}",
            1.5f64.to_bits()
        );
    }

    /// **`std/core`'s `mix64` and the runtime's `splitmix64_finalize` compute the
    /// same function, and until these two probes nothing asserted it.** The
    /// records have said it for some time -- ADR 0005 describes `mix64` as the
    /// splitmix64 finalizer written in signed Nova with masked shifts, and the
    /// runtime's own doc comment says the constants correspond -- but each side
    /// was only ever pinned against *published* splitmix64 vectors, separately.
    /// Two implementations can both match a published vector at two points and
    /// still disagree elsewhere; nothing compared them to each other.
    ///
    /// The comparison is possible without inverting anything because the seed is
    /// a process-global `OnceLock` in `nova-runtime`, and `nova-driver` takes
    /// that crate as a dev-dependency of the *same instance* -- so
    /// `nova_rt_int_hash_seed()` here returns the very value the JIT-compiled
    /// code XORed in. Whichever side reaches the `OnceLock` first initialises
    /// it; order does not matter.
    ///
    /// One probe per test is the module's rule, so the many-key form has to
    /// arrive as a single `Int`: the Nova body XOR-accumulates `(k).hash()` over
    /// 128 keys spanning both signs, and the assertion recomputes that fold from
    /// `splitmix64_finalize`. A constant or a shift drifting on either side
    /// changes the fold with overwhelming probability -- a mask mutation alters
    /// roughly half of all inputs, so surviving 128 keys is a `2^-128`-order
    /// event rather than a coincidence to worry about.
    ///
    /// Both signs on purpose. Nova's `>>` is arithmetic and `mix64` masks each
    /// shift to emulate a logical one, so a dropped mask is visible only on
    /// inputs whose sign bit is set -- and the seed makes the *hashed* value's
    /// sign unpredictable from the key's, which is why the range is chosen
    /// rather than the mask relied upon.
    ///
    /// **What these two probes cover that nothing else did, counted rather than
    /// reasoned.** Both mutations below were applied and the whole workspace
    /// suite run for each, and the failures enumerated:
    ///
    /// - The runtime's `splitmix64_finalize` first constant, last nibble `9` to
    ///   `b`: **two failures across the suite, and they are these two probes.**
    ///   Nothing else noticed. `nova_rt_str_hash` routes through that function,
    ///   but every test of it asserts a relation -- same key same hash, different
    ///   keys different hashes -- and a relation survives any bijective change.
    /// - Nova's `mix64` first constant, `-4658895280553007687` to
    ///   `...685`: four failures -- `hash_run`, `hash_build_standalone` and these
    ///   two. The golden's `splitmix64 canonical x1/x3` line reads `false`
    ///   `false`, which is the published-vector check doing its job.
    ///
    /// So Nova-side drift already had a witness and Rust-side drift had none.
    /// That asymmetry is the whole reason these exist; the fold's own margin is
    /// secondary.
    ///
    /// `Bool` and `Char` get no probe of their own, deliberately. All three
    /// impls call this one `mix64`, differing only in what they feed it, and
    /// `tests/runtime/hash.stdout`'s `char/int agree` line already pins that
    /// agreement -- so a `Bool` or `Char` probe would cost a full compile and
    /// JIT for nothing this fold does not already establish.
    #[test]
    fn mix64_agrees_with_the_runtime_finalizer_over_keys_of_both_signs() {
        let out = run_async_fn(
            "async fn fold() -> Int {\n\
            \x20 let mut acc = 0\n\
            \x20 let mut k = -64\n\
            \x20 while k < 64 {\n\
            \x20   acc = acc ^ (k).hash()\n\
            \x20   k = k + 1\n\
            \x20 }\n\
            \x20 acc\n\
             }\n\
             fn main() { let x = fold() }",
            "fold",
            &[],
        );
        let seed = nova_runtime::nova_rt_int_hash_seed() as u64;
        let want = (-64i64..64).fold(0i64, |acc, k| {
            acc ^ nova_runtime::splitmix64_finalize((k as u64) ^ seed) as i64
        });
        assert_eq!(
            out, want,
            "Nova's `mix64` and the runtime's `splitmix64_finalize` disagree \
             somewhere in the keys -64..63. Both are the splitmix64 finalizer \
             and the records say so; one of them has drifted. The single-key \
             probe names a specific input."
        );
    }

    /// The same tie at one key, kept for diagnosis rather than for coverage.
    /// When the fold above fails it reports two folded totals, which say nothing
    /// about *where*; this one fails with a concrete input and two concrete
    /// hashes. `-1` is chosen because every one of `mix64`'s three masked shifts
    /// sign-extends on it before the seed is applied, so a dropped mask is most
    /// likely to show here.
    #[test]
    fn mix64_agrees_with_the_runtime_finalizer_at_a_single_key() {
        let out = run_async_fn(
            "async fn one() -> Int { (-1).hash() }\n\
             fn main() { let x = one() }",
            "one",
            &[],
        );
        let seed = nova_runtime::nova_rt_int_hash_seed() as u64;
        let want = nova_runtime::splitmix64_finalize((-1i64 as u64) ^ seed) as i64;
        assert_eq!(
            out, want,
            "`(-1).hash()` in Nova and `splitmix64_finalize(-1 ^ seed)` in the \
             runtime must agree: got {out:#x}, want {want:#x}"
        );
    }

    /// Arguments reach the WRAPPER, not `poll` -- so a wrapper that forgets to
    /// copy them into their state slots leaves the body reading the allocator's
    /// zeroes. At `Float`, which also proves the seeding store and the body's
    /// reload agree on the register class, not merely on the offset.
    #[test]
    fn an_async_fns_parameters_reach_its_body_through_the_state_object() {
        let out = run_async_fn(
            "async fn add(a: Float, b: Float) -> Float { a + b }\n\
             fn main() { let x = add(1.0, 2.0) }",
            "add",
            &[Arg::Float(1.5), Arg::Float(2.25)],
        );
        assert_eq!(
            out as u64,
            3.75f64.to_bits(),
            "1.5 + 2.25 must reach the body; a zeroed parameter slot yields \
             0.0. Commutative, so `parameter_slots_are_seeded_in_order` \
             covers ordering: got {out:#x}"
        );
    }

    /// Ordering, which a commutative operator cannot see: `a - b` distinguishes
    /// parameter slot 0 from slot 1.
    #[test]
    fn parameter_slots_are_seeded_in_order() {
        let out = run_async_fn(
            "async fn sub(a: Float, b: Float) -> Float { a - b }\n\
             fn main() { let x = sub(1.0, 2.0) }",
            "sub",
            &[Arg::Float(10.0), Arg::Float(2.5)],
        );
        assert_eq!(
            out as u64,
            7.5f64.to_bits(),
            "10.0 - 2.5 = 7.5; reversed slots would give -7.5: got {out:#x}"
        );
    }

    /// A value carried across block boundaries entirely through state slots --
    /// the property Task 6 relies on. A `while` loop's accumulator is written
    /// in the body block and read in the header block, so if the spill were
    /// incomplete this returns garbage or zero rather than the sum.
    #[test]
    fn a_loop_accumulator_survives_the_spill_across_blocks() {
        let out = run_async_fn(
            "async fn total(n: Int) -> Int {\n  \
             let mut i = 0\n  \
             let mut t = 0\n  \
             while i < n { t = t + i\n i = i + 1 }\n  \
             t\n\
             }\n\
             fn main() { let x = total(1) }",
            "total",
            &[Arg::Int(10)],
        );
        assert_eq!(out, 45, "0+1+..+9 = 45");
    }

    /// A heap value built INSIDE the poll function, then reduced to a scalar
    /// output. The state object holds the interpolated `String`'s pointer in a
    /// temp slot while `str_len_chars` is called on it, so this covers three
    /// things no other probe here does: `nova_rt_alloc` running from inside a
    /// generated poll function, a `Ptr`-class value round-tripping through a
    /// state slot, and a runtime call in a poll body.
    ///
    /// A `String` OUTPUT is not asserted directly, because nothing public in
    /// `nova-runtime` decodes a `NovaStr` -- the output slot would only be
    /// readable as an opaque non-zero pointer, which a wrong slot could
    /// accidentally satisfy. Comparing the string inside Nova and returning the
    /// `Bool` checks the value instead, and adds the third distinct output class
    /// (`MirTy::I8`, an 8-byte slot holding one byte) to the two above.
    #[test]
    fn a_heap_value_allocated_inside_the_poll_fn_round_trips_through_a_state_slot() {
        let out = run_async_fn(
            "async fn f(n: Int) -> Bool { let s = \"ab${n}cd\"
 s == \"ab7cd\" }
             fn main() { let x = f(1) }",
            "f",
            &[Arg::Int(7)],
        );
        assert_eq!(
            out & 0xff, 1,
            "the interpolated string must equal \"ab7cd\"; a parameter that did              not reach the body would build \"ab0cd\" and give 0: got {out:#x}"
        );
    }

    /// Replace `<name>`'s generated poll function with one that reports
    /// `POLL_PENDING` the first `pends` calls on a given state object and then
    /// completes with `value`.
    ///
    /// Hand-built MIR obeying the same ABI the transform generates against: it
    /// reads the resume tag out of slot `STATE_SLOT_TAG`, advances it, writes its
    /// `Float` result to `STATE_SLOT_OUTPUT` and returns a status. Only the
    /// *awaited* function is substituted; the function under test is the real
    /// generated code, so what the probe exercises is its suspend and its resume.
    ///
    /// One state object per call to `<name>`, since each call allocates its own,
    /// so a stub built with `pends = 1` pends once per await rather than once per
    /// program.
    fn replace_poll_with_a_pending_stub(mir: &mut Module, name: &str, pends: i64, value: f64) {
        let prefix = format!("{name}.");
        let poll = mir
            .functions
            .iter_mut()
            .find(|f| f.name.starts_with(&prefix) && f.name.ends_with("$poll"))
            .unwrap_or_else(|| panic!("no `$poll` for `{name}`"));

        // Temp 0 is the state object (the poll ABI's env), temp 1 is task_ctx.
        let mut temps = vec![MirTy::Ptr, MirTy::Ptr];
        fn push(temps: &mut Vec<MirTy>, ty: MirTy) -> Temp {
            let t = Temp(temps.len() as u32);
            temps.push(ty);
            t
        }
        let state = Temp(0);

        // Block 0 dispatches on the tag: tag k (k < pends) goes to the k-th
        // suspend block, and anything else -- which is tag `pends` -- completes.
        let tag = push(&mut temps, MirTy::I64);
        let dispatch = nova_mir::Block {
            stmts: vec![Stmt::RecordField {
                dst: tag,
                record: state,
                index: nova_mir::STATE_SLOT_TAG,
                ty: MirTy::I64,
            }],
            term: Terminator::Switch {
                disc: tag,
                arms: (0..pends)
                    .map(|k| (k, nova_mir::BlockId(k as u32 + 1)))
                    .collect(),
                default: nova_mir::BlockId(pends as u32 + 1),
            },
        };

        let mut blocks = vec![dispatch];
        for k in 0..pends {
            let next = push(&mut temps, MirTy::I64);
            let pending = push(&mut temps, MirTy::I64);
            blocks.push(nova_mir::Block {
                stmts: vec![
                    Stmt::ConstInt(next, k + 1),
                    Stmt::SetField {
                        record: state,
                        index: nova_mir::STATE_SLOT_TAG,
                        value: next,
                        ty: MirTy::I64,
                    },
                    Stmt::ConstInt(pending, nova_mir::POLL_PENDING),
                ],
                term: Terminator::Return(Some(pending)),
            });
        }
        let out = push(&mut temps, MirTy::F64);
        let ready = push(&mut temps, MirTy::I64);
        blocks.push(nova_mir::Block {
            stmts: vec![
                Stmt::ConstFloat(out, value),
                Stmt::SetField {
                    record: state,
                    index: nova_mir::STATE_SLOT_OUTPUT,
                    value: out,
                    ty: MirTy::F64,
                },
                Stmt::ConstInt(ready, nova_mir::POLL_READY),
            ],
            term: Terminator::Return(Some(ready)),
        });

        *poll = Function {
            name: poll.name.clone(),
            params: 1,
            takes_env: true,
            capture_count: 0,
            temps,
            ret: MirTy::I64,
            is_async: false,
            blocks,
        };
    }

    /// **A real suspend and a real resume.** The awaited future pends twice, so
    /// the awaiting function -- ordinary generated code -- returns `POLL_PENDING`
    /// to the executor, is re-queued, and comes back into the same await twice
    /// before the value arrives.
    ///
    /// This is the probe for the same-tag rule. A suspend that stored the tag
    /// *after* its own would resume past this await: the second poll would
    /// dispatch on a tag with no arm and reach the trap block, which aborts the
    /// process rather than failing the assertion -- so a run that gets as far as
    /// comparing a value has already proved the tag came back to the await.
    ///
    /// At `Float`, and with `+ 1.0` after the await, so the awaited value has to
    /// have travelled through the inner state object's output slot as an f64 and
    /// then been used: reading the slot before the inner future wrote it yields
    /// `0.0`, giving `1.0` rather than `3.5`.
    #[test]
    fn an_await_on_a_twice_pending_future_resumes_at_the_same_await() {
        let out = run_async_fn_with(
            "async fn g() -> Float { 0.0 }\n\
             async fn f() -> Float { g().await + 1.0 }\n\
             fn main() { let x = f() }",
            "f",
            &[],
            &|mir| replace_poll_with_a_pending_stub(mir, "g", 2, 2.5),
        );
        assert_eq!(
            out as u64,
            3.5f64.to_bits(),
            "2.5 + 1.0 must come back from the resumed await; an output slot read \
             before the inner future wrote it gives 1.0: got {out:#x}, want {:#x}",
            3.5f64.to_bits()
        );
    }

    /// An await **inside a loop**, suspending on every iteration: one suspend
    /// point resumed at four separate times, with the loop's own accumulator and
    /// counter living in state slots across each suspension.
    ///
    /// Three things only this shape reaches. The loop's back edge has to follow
    /// the renumbering the split introduces, or it lands in the resumable poll
    /// function's trap block on the second iteration. The resume has to re-enter
    /// the await rather than the loop header, or the iteration count is wrong. And
    /// the accumulator has to survive a *suspend*, not merely a block boundary --
    /// the await-free loop probe above already covers the latter, and would pass
    /// with the accumulator living in a register across the whole poll call.
    ///
    /// The result discriminates each: a lost accumulator gives `0.5`, a lost
    /// counter loops forever or once, and a wrong awaited value gives `0.0`.
    #[test]
    fn an_await_inside_a_loop_suspends_and_resumes_on_every_iteration() {
        let out = run_async_fn_with(
            "async fn half() -> Float { 0.0 }\n\
             async fn total(n: Int) -> Float {\n  \
             let mut i = 0\n  \
             let mut t = 0.0\n  \
             while i < n { t = t + half().await\n i = i + 1 }\n  \
             t\n\
             }\n\
             fn main() { let x = total(1) }",
            "total",
            &[Arg::Int(4)],
            &|mir| replace_poll_with_a_pending_stub(mir, "half", 1, 0.5),
        );
        assert_eq!(
            out as u64,
            2.0f64.to_bits(),
            "four iterations of 0.5 must accumulate to 2.0 across four \
             suspensions: got {out:#x}, want {:#x}",
            2.0f64.to_bits()
        );
    }

    /// The ready path, with no stub anywhere: a suspend point whose inner future
    /// completes on its first poll, so the await falls straight through to its
    /// continuation. This is what every `.await` a `.nova` file can write does
    /// today, and it is a different path through the status switch than the two
    /// probes above take.
    #[test]
    fn an_await_on_an_already_ready_future_falls_through_to_its_continuation() {
        let out = run_async_fn(
            "async fn g(x: Float) -> Float { x * 2.0 }\n\
             async fn f(a: Float) -> Float { g(a).await + 0.25 }\n\
             fn main() { let x = f(1.0) }",
            "f",
            &[Arg::Float(1.5)],
        );
        assert_eq!(
            out as u64,
            3.25f64.to_bits(),
            "1.5 * 2.0 + 0.25 = 3.25; the awaited value must be the inner \
             future's own output, not its argument or zero: got {out:#x}, want {:#x}",
            3.25f64.to_bits()
        );
    }

    /// Two awaits in one body, so the resume tags have to be distinct and the
    /// second await's continuation has to be reachable from the first's.
    /// Subtraction, not addition: reversed continuations give `-1.5`.
    #[test]
    fn two_awaits_in_one_body_each_get_their_own_resume_state() {
        let out = run_async_fn(
            "async fn g(x: Float) -> Float { x }\n\
             async fn f() -> Float { g(4.0).await - g(2.5).await }\n\
             fn main() { let x = f() }",
            "f",
            &[],
        );
        assert_eq!(
            out as u64,
            1.5f64.to_bits(),
            "4.0 - 2.5 = 1.5: got {out:#x}, want {:#x}",
            1.5f64.to_bits()
        );
    }

    /// An `.await` inside a `match` arm, executed. The suspend point is in a
    /// block reached through the match's own tag `Switch`, whose arm targets the
    /// split has to renumber -- an arm left naming its pre-split id reaches the
    /// resumable poll function's trap block, which aborts the process rather than
    /// producing a wrong value.
    ///
    /// The scrutinee is built inside the `async fn` rather than passed in, since
    /// a probe argument can only be a scalar.
    #[test]
    fn an_await_inside_a_match_arm_runs_the_arm_it_selected() {
        let out = run_async_fn(
            "type Choice = | Left | Right\n\
             async fn g(x: Float) -> Float { x }\n\
             async fn f(a: Float) -> Float {\n  \
             let c: Choice = Left\n  \
             match c { Left => g(a).await + 1.0, Right => 0.0, }\n\
             }\n\
             fn main() { let x = f(1.0) }",
            "f",
            &[Arg::Float(2.5)],
        );
        assert_eq!(
            out as u64,
            3.5f64.to_bits(),
            "the `Left` arm awaits and adds 1.0, so 2.5 gives 3.5; the `Right` \
             arm would give 0.0: got {out:#x}, want {:#x}",
            3.5f64.to_bits()
        );
    }

    /// A unit-output await: nothing is copied out of the inner future's output
    /// slot, but the inner future still has to be polled and the continuation
    /// still has to run. The `Float` the body returns afterwards is what shows it
    /// did.
    #[test]
    fn a_unit_output_await_still_polls_its_future_and_continues() {
        let out = run_async_fn(
            "async fn g() { }\n\
             async fn f(a: Float) -> Float { g().await\n a + 1.0 }\n\
             fn main() { let x = f(1.0) }",
            "f",
            &[Arg::Float(0.5)],
        );
        assert_eq!(
            out as u64,
            1.5f64.to_bits(),
            "0.5 + 1.0 = 1.5 must run after the unit await: got {out:#x}, want {:#x}",
            1.5f64.to_bits()
        );
    }

    /// A unit-returning `async fn` never touches the output slot itself, yet
    /// the executor reads it on completion regardless. What is asserted here is
    /// that the run completes at all: reaching `output_bits` means the poll
    /// function returned exactly `POLL_READY` and the executor's unconditional
    /// read of `STATE_SLOT_OUTPUT` stayed inside a state object with the
    /// fewest temp slots any body can have -- the `STATE_MIN_SIZE` case.
    #[test]
    fn a_unit_returning_async_fn_completes_and_reads_a_valid_output_slot() {
        let out = run_async_fn("async fn f() { }\nfn main() { let x = f() }", "f", &[]);
        assert_eq!(out, 0, "the explicit zero the transform stores for unit");
    }
}