verif 0.1.1

In-code formal verification for Rust: an embedded bit-blasting SMT decision procedure, a symbolic DSL, contracts and a machine-checked proof kernel. SPARK-inspired, no_std, no external dependencies.
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
//! The end-to-end driver: source in, verdicts out.
//!
//! This is the layer that ties the three stages together and owns the two
//! things the other modules cannot know about: how to get MIR out of `rustc`,
//! and how to decide *which* functions to verify. It is also where the honesty
//! of the whole frontend is enforced, in one rule:
//!
//! > A function is reported verified only when every obligation was proved
//! > *and* every path was explored. A cutoff is reported as a cutoff.
//!
//! That rule is why [`FnOutcome`] has a distinct `Incomplete` state instead of
//! folding cutoffs into `Verified`.

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::mir::exec;
use crate::mir::parse::{self, MirFn, MirProgram, Ty, USIZE_WIDTH};

// The report types are part of the public verdict surface -- `FnOutcome`
// carries a `MirReport` -- so they are re-exported here rather than leaving a
// crate-internal type in a public signature.
pub use crate::mir::exec::{MirReport, Obligation, ObligationKind};
use crate::mir::spec::{self, SpecError, Specs};
use crate::smt::{self, Verdict};

/// The Rust edition a file is compiled under.
///
/// The frontend has to compile *the program the user ships*, and that program's
/// edition lives in its `Cargo.toml`. Pinning one edition unconditionally is the
/// mistake this type exists to fix: `--edition=2024` refuses a valid 2021 crate
/// (`extern "C" { … }` must be `unsafe` there) and lowers some code differently
/// from the edition that ships, so a verdict could be about a program nobody
/// built. The edition is therefore *resolved* (see [`resolve_edition`]), never
/// assumed, and it is recorded on every report.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Edition {
    /// Rust 2015, `rustc`'s own default.
    Rust2015,
    /// Rust 2018.
    Rust2018,
    /// Rust 2021.
    Rust2021,
    /// Rust 2024, the crate's own edition.
    Rust2024,
}

impl Edition {
    /// The spelling `rustc --edition=` takes.
    pub fn as_str(self) -> &'static str {
        match self {
            Edition::Rust2015 => "2015",
            Edition::Rust2018 => "2018",
            Edition::Rust2021 => "2021",
            Edition::Rust2024 => "2024",
        }
    }

    /// Parse a manifest or override spelling.
    ///
    /// Only the four numeric forms are accepted, so a typo is an error rather
    /// than a silent fallback to an edition the program does not use.
    pub fn parse(s: &str) -> Option<Edition> {
        match s.trim() {
            "2015" => Some(Edition::Rust2015),
            "2018" => Some(Edition::Rust2018),
            "2021" => Some(Edition::Rust2021),
            "2024" => Some(Edition::Rust2024),
            _ => None,
        }
    }
}

impl std::fmt::Display for Edition {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "edition {}", self.as_str())
    }
}

/// Options that shape a frontend run.
#[derive(Clone, Debug, Default)]
pub struct MirOptions {
    /// The Rust edition to compile under.
    ///
    /// `None` resolves it: from the nearest `Cargo.toml`'s `package.edition`
    /// first, then `VERIF_EDITION`. A file with neither is an *error*, never a
    /// silent default -- see [`resolve_edition`].
    pub edition: Option<Edition>,
}

/// Resolve the edition to compile `file` under: explicit first, then
/// `VERIF_EDITION`, then the nearest `Cargo.toml`.
///
/// There is deliberately no silent default for a *loose* file -- a `.rs` with no
/// manifest above it has no crate edition to infer, and compiling it under an
/// edition the program does not use is the exact mismatch this resolution removes.
/// A real package, however, *does* have a default: Cargo assigns edition 2015 to a
/// `[package]` that omits `edition`, so a manifest that declares a package without
/// the key resolves to 2015 rather than to an error. The two are different
/// questions -- "what edition is this crate?" and "what edition is this file?" --
/// and only the second has no answer.
pub fn resolve_edition(file: &Path, explicit: Option<Edition>) -> Result<Edition, String> {
    if let Some(e) = explicit {
        return Ok(e);
    }
    if let Ok(v) = std::env::var("VERIF_EDITION") {
        if !v.is_empty() {
            return Edition::parse(&v).ok_or_else(|| {
                format!(
                    "VERIF_EDITION is `{v}`, which is not an edition; use 2015, 2018, 2021 or 2024"
                )
            });
        }
    }
    if let Some(e) = edition_from_manifest(file) {
        return Ok(e);
    }
    Err(format!(
        "no Rust edition for {}: it has no `Cargo.toml` and `VERIF_EDITION` is unset. The \
         edition is what the program is compiled under, so it is never guessed -- set \
         `VERIF_EDITION` to 2015, 2018, 2021 or 2024",
        file.display()
    ))
}

/// The edition a file's crate declares, read from the nearest `Cargo.toml`.
///
/// `package.edition` is read directly; `edition.workspace = true` (or
/// `edition = { workspace = true }`) is resolved against the workspace root's
/// `[workspace.package]`. A `[package]` that *omits* `edition` resolves to 2015,
/// which is Cargo's default for a package that does not state one -- so a valid
/// 2015 package is verified, not refused. A manifest the reader cannot parse
/// yields `None`, so the caller reports "no edition" rather than a wrong one.
///
/// Public because it is the manifest half of [`resolve_edition`]: a caller may
/// want to ask what a manifest declares without the environment fallbacks.
pub fn edition_from_manifest(file: &Path) -> Option<Edition> {
    let manifest = nearest_manifest(file)?;
    let text = std::fs::read_to_string(&manifest).ok()?;
    match manifest_value(&text, "package", "edition") {
        // `edition.workspace = true` / `edition = { workspace = true }`: the value
        // lives in the workspace root.
        Some(v) if v == "workspace" => {
            let root = workspace_root(&manifest, &text)?;
            let root_text = std::fs::read_to_string(&root).ok()?;
            Edition::parse(&manifest_value(&root_text, "workspace.package", "edition")?)
        }
        Some(v) => Edition::parse(&v),
        // No `edition` key. Cargo defaults a `[package]` to edition 2015, so a
        // real package resolves to 2015; a manifest with no `[package]` at all
        // (a pure virtual workspace) declares no crate, so it yields `None` and
        // the caller reports "no edition" as before.
        None => declares_package(&text).then_some(Edition::Rust2015),
    }
}

/// Whether a manifest declares a `[package]` table.
///
/// This is the tell between "a package that omitted `edition`" (Cargo's 2015
/// default applies) and "a manifest with no package" (nothing to default).
fn declares_package(text: &str) -> bool {
    text.lines().any(|raw| {
        let line = strip_toml_comment(raw).trim();
        line.strip_prefix('[')
            .and_then(|l| l.strip_suffix(']'))
            .map(|inner| inner.trim() == "package")
            .unwrap_or(false)
    })
}

/// The nearest `Cargo.toml` at or above `file`, if any.
fn nearest_manifest(file: &Path) -> Option<PathBuf> {
    let abs = std::fs::canonicalize(file).unwrap_or_else(|_| file.to_path_buf());
    let mut dir: Option<&Path> = abs.parent();
    while let Some(d) = dir {
        let candidate = d.join("Cargo.toml");
        if candidate.is_file() {
            return Some(candidate);
        }
        dir = d.parent();
    }
    None
}

/// The workspace root for a member manifest.
///
/// Cargo's `package.workspace` key names the root explicitly, and it may point
/// *outside* the member's ancestor chain (`workspace = "../ws"`), so it is
/// resolved first: searching ancestors only would fail a valid workspace member
/// whose root is not above it. When the key is absent, the root is the nearest
/// ancestor manifest that declares `[workspace]`.
fn workspace_root(manifest: &Path, text: &str) -> Option<PathBuf> {
    if let Some(rel) = manifest_value(text, "package", "workspace") {
        if rel != "workspace" {
            let dir = manifest.parent()?;
            let candidate = dir.join(rel).join("Cargo.toml");
            if candidate.is_file() {
                return Some(candidate);
            }
        }
    }
    let mut dir = manifest.parent()?;
    loop {
        let candidate = dir.join("Cargo.toml");
        if candidate.is_file() {
            let text = std::fs::read_to_string(&candidate).ok()?;
            if text.lines().any(|l| l.trim().starts_with("[workspace")) {
                return Some(candidate);
            }
        }
        dir = dir.parent()?;
    }
}

/// The value of a scalar key in a table of a TOML-ish manifest.
///
/// This is a focused reader, not a TOML parser: it handles the spellings a
/// `Cargo.toml` uses for an edition (`edition = "2024"`, `edition.workspace =
/// true`, `edition = { workspace = true }`) and returns `Some("workspace")` for
/// the two inherited forms. Anything else it might read is something it could read
/// *wrongly*, so it reads nothing else.
fn manifest_value(text: &str, table: &str, key: &str) -> Option<String> {
    let mut current = String::new();
    for raw in text.lines() {
        let line = strip_toml_comment(raw).trim();
        if line.is_empty() {
            continue;
        }
        if let Some(inner) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
            current = inner.trim().to_string();
            continue;
        }
        if current != table {
            continue;
        }
        let Some((lhs, rhs)) = line.split_once('=') else { continue };
        // TOML permits a *quoted* key (`"edition" = "2024"`), which Cargo accepts
        // and treats exactly as the bare spelling. Comparing the raw left-hand side
        // missed it, so a quoted edition key read as *no* edition and the 2015
        // default was applied -- verification then compiled a different edition
        // from Cargo. A dotted key (`edition.workspace`) is not quoted as a whole,
        // so only the bare key is unquoted here.
        let lhs = unquote_toml_key(lhs.trim());
        let rhs = rhs.trim();
        if lhs == format!("{key}.workspace") {
            return Some(if rhs == "true" { "workspace".into() } else { rhs.into() });
        }
        if lhs == key {
            // `edition = { workspace = true }`
            if rhs.starts_with('{') {
                return Some(if rhs.contains("workspace") && rhs.contains("true") {
                    "workspace".into()
                } else {
                    rhs.into()
                });
            }
            return Some(rhs.trim_matches('"').to_string());
        }
    }
    None
}

/// Strip surrounding double quotes from a TOML key, if present.
///
/// A TOML key may be quoted (`"edition" = "2024"`); Cargo reads it identically to
/// the bare spelling. The reader compares keys as strings, so it has to normalise
/// the spelling or a quoted key silently reads as absent.
fn unquote_toml_key(k: &str) -> &str {
    k.strip_prefix('"').and_then(|s| s.strip_suffix('"')).unwrap_or(k)
}

/// Drop a trailing `#` comment, respecting string literals so a `#` inside one is
/// not mistaken for a comment.
fn strip_toml_comment(line: &str) -> &str {
    let mut in_str = false;
    let mut prev = '\0';
    for (i, c) in line.char_indices() {
        match c {
            '"' if prev != '\\' => in_str = !in_str,
            '#' if !in_str => return &line[..i],
            _ => {}
        }
        prev = c;
    }
    line
}

/// Where the MIR text came from, so failures can say so.
#[derive(Clone, Debug)]
pub enum MirSource {
    /// `rustc --emit=mir` on this file.
    Emitted {
        /// The Rust source the MIR was emitted from.
        file: PathBuf,
        /// The MIR text `rustc` printed.
        mir: String,
    },
    /// A pre-generated dump, which lets a build without nightly reuse one.
    File(PathBuf),
    /// Dump text supplied directly, for tests.
    Inline(String),
}

/// The extra environment for `rustc` when the source declares a crate-level
/// `#![feature(…)]`.
///
/// A modelled shape may name a library method that is *stable* on the toolchain the
/// crate is built with but *unstable* on the MSRV floor -- the C6 corpus's
/// `cast_unsigned`/`cast_signed` (`integer_sign_cast`), `is_multiple_of`
/// (`unsigned_is_multiple_of`) and signed `midpoint` (`num_midpoint_signed`) are
/// stable from 1.87 and gated on 1.85. The corpus must compile on the floor (gate 14
/// runs the frontend's own suite against it), so it carries a `#![feature(…)]`
/// header, and `rustc` refuses a feature gate on a stable channel unless
/// `RUSTC_BOOTSTRAP` is set.
///
/// The bootstrap is scoped to a source that *declares* a feature, never set
/// globally: a file with no gate is compiled exactly as before, so this cannot
/// change the lowering of ordinary code. It is inert on current stable too, where
/// the features are already stable and the gate is a no-op warning.
fn bootstrap_env(file: &Path) -> Vec<(&'static str, &'static str)> {
    let declares_feature = std::fs::read_to_string(file)
        .map(|s| s.lines().any(|l| l.trim_start().starts_with("#![feature(")))
        .unwrap_or(false);
    if declares_feature {
        vec![("RUSTC_BOOTSTRAP", "1")]
    } else {
        Vec::new()
    }
}

/// Get MIR text for a Rust file, or explain why not.
///
/// `rustc --emit=mir` is a *stable* flag -- `-Zunpretty=mir` is the nightly-only
/// spelling, and this frontend deliberately does not use it, so the frontend runs
/// on the same stable compiler that builds the crate (checked down to the MSRV,
/// 1.85). The error is returned rather than papered over, because "the frontend
/// could not run" and "the code is wrong" must never be reported the same way.
///
/// The edition is *resolved*, never assumed: `VERIF_EDITION` first, then the
/// nearest `Cargo.toml`'s `package.edition`. A file with neither is an error,
/// because the edition changes the lowering -- `panic!("literal")` is one
/// diverging call under 2015 but an `Arguments` chain plus `std::rt::panic_fmt`
/// under 2024, and `extern "C" { … }` must be `unsafe` only from 2024 -- so a
/// verdict under the wrong edition would be about a program nobody built. See
/// [`resolve_edition`].
///
/// The compiler is taken from `VERIF_RUSTC` when set, and otherwise from
/// `rustc` on `PATH`. The dedicated variable exists so that pointing this tool at
/// a *different* compiler -- a nightly, or the rustc_public oracle's toolchain --
/// does not disturb the `rustc` that cargo is using to build the test suite;
/// setting `RUSTC` would do exactly that.
pub fn emit_mir(file: &Path) -> Result<String, String> {
    emit_mir_opts(file, &MirOptions::default()).map(|(text, _edition)| text)
}

/// [`emit_mir`] with the compiler named explicitly.
///
/// This exists so a test can point at a *specific* toolchain -- the MSRV, say, or
/// a nightly -- without mutating the process environment, which is a race when
/// tests run in parallel.
pub fn emit_mir_with(rustc: &str, file: &Path) -> Result<String, String> {
    emit_mir_with_opts(rustc, file, &MirOptions::default()).map(|(text, _edition)| text)
}

/// [`emit_mir`] with the run's options, returning the resolved edition too.
pub fn emit_mir_opts(
    file: &Path,
    opts: &MirOptions,
) -> Result<(String, Edition), String> {
    let rustc = std::env::var("VERIF_RUSTC").unwrap_or_else(|_| "rustc".into());
    emit_mir_with_opts(&rustc, file, opts)
}

/// [`emit_mir_with`] with the run's options, returning the resolved edition too.
///
/// The edition is resolved before `rustc` is invoked, so a file whose edition
/// cannot be determined fails with "no edition" rather than with a compiler error
/// about a program compiled under the wrong one.
pub fn emit_mir_with_opts(
    rustc: &str,
    file: &Path,
    opts: &MirOptions,
) -> Result<(String, Edition), String> {
    let edition = resolve_edition(file, opts.edition)?;
    // `rustc` writes its intermediate artifacts next to the output path, so the
    // output goes to a temp file rather than to `/dev/stdout` -- pointing it at
    // `/dev` makes rustc try to create a temp directory there and fail.
    // The name must be unique per *call*, not just per process: tests run in
    // parallel threads of one process, and a shared name means one test deletes
    // the file another is about to read.
    static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let out_path = std::env::temp_dir().join(format!(
        "verif-mir-{}-{}-{}.mir",
        std::process::id(),
        seq,
        file.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default()
    ));
    let out = Command::new(rustc)
        .arg(format!("--edition={}", edition.as_str()))
        .arg("--crate-type=lib")
        .arg("--emit=mir")
        .arg("-o")
        .arg(&out_path)
        .arg(file)
        .envs(bootstrap_env(file))
        .output()
        .map_err(|e| format!("could not run rustc: {e}"))?;
    if !out.status.success() {
        return Err(format!(
            "rustc failed on {} under {}: {}",
            file.display(),
            edition,
            String::from_utf8_lossy(&out.stderr).trim()
        ));
    }
    let text = std::fs::read_to_string(&out_path).map_err(|e| {
        format!(
            "rustc produced no MIR for {} under {} ({e}); `--emit=mir` is stable, so this is a \
             missing output file rather than a toolchain problem",
            file.display(),
            edition
        )
    })?;
    let _ = std::fs::remove_file(&out_path);
    if text.trim().is_empty() {
        return Err(format!(
            "rustc produced empty MIR for {} under {}; `--emit=mir` is stable, so check the \
             file's crate type and that it defines an item with a body",
            file.display(),
            edition
        ));
    }
    Ok((text, edition))
}

/// What happened to one function.
#[derive(Clone, Debug)]
pub enum FnOutcome {
    /// Every obligation proved and every path explored.
    Verified {
        /// How many obligations were discharged.
        obligations: usize,
        /// How many of those were rustc-emitted panic conditions.
        panics_ruled_out: usize,
    },
    /// A definite failure, with the obligation that failed.
    Failed {
        /// Which obligation failed, e.g. `panic: attempt to compute ...`.
        kind: String,
        /// The counterexample, as variable assignments.
        detail: String,
    },
    /// Not decided: a budget, an unmodelled construct, or an open obligation.
    /// This is *not* a pass.
    Incomplete {
        /// The obligations that were discharged before the path was cut short.
        report: Box<MirReport>,
        /// Why the verification is incomplete: budgets, unmodelled constructs,
        /// or obligations the engine could not decide.
        reasons: Vec<String>,
    },
    /// The function was skipped, with the reason.
    Skipped {
        /// Why the function was not verified at all.
        reason: String,
    },
}

impl FnOutcome {
    /// True only for [`FnOutcome::Verified`]. `Incomplete` is not a pass.
    pub fn is_verified(&self) -> bool {
        matches!(self, FnOutcome::Verified { .. })
    }
}

impl std::fmt::Display for FnOutcome {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FnOutcome::Verified { obligations, panics_ruled_out } => write!(
                f,
                "verified ({obligations} obligation(s), {panics_ruled_out} panic(s) ruled out)"
            ),
            FnOutcome::Failed { kind, detail } => write!(f, "FAILED: {kind} — {detail}"),
            FnOutcome::Incomplete { reasons, .. } => {
                write!(f, "incomplete ({} reason(s))", reasons.len())?;
                for r in reasons.iter().take(3) {
                    write!(f, "\n      - {r}")?;
                }
                Ok(())
            }
            FnOutcome::Skipped { reason } => write!(f, "skipped: {reason}"),
        }
    }
}

/// Verify one function from a parsed program plus its source contracts.
pub fn verify_function(prog: &MirProgram, f: &MirFn, specs: &Specs) -> FnOutcome {
    // A 128-bit type is wider than the engine, whose every width-taking
    // constructor asserts `1..=64`. Refusing here, before any of them runs, is
    // what keeps the refusal whole: the argument seeding, the loop havoc and the
    // contract bindings all consult a type's width, and a 128-bit local would be a
    // panic in whichever came first. A panic is not a refusal -- it takes the run
    // down and reports nothing -- so this guard must precede them all.
    if let Some(ty) = f.first_unrepresentable_type() {
        return FnOutcome::Skipped {
            reason: format!(
                "`{ty:?}` is wider than the engine's 64-bit words, so the function is not modelled"
            ),
        };
    }
    // Resolved by tail as well as exactly: the dump names an inherent method
    // `<impl at …>::f` while the contract is keyed by the source's `f`. An
    // unresolved contract is not "no contract" here -- it is the false-proof
    // case, where the body would be checked against `true` and no `ensures`.
    //
    // An *inherited* trait contract comes with a rename, because the declaration
    // and the implementation may name their parameters differently and the
    // contract means the declaration's names. Binding it by the implementation's
    // own names would attach `ret == a` to the wrong argument -- a false proof.
    let (contract, rename) = match specs.contract_for_fn(f) {
        Ok(x) => x,
        Err(reason) => return FnOutcome::Skipped { reason },
    };
    // A clause the frontend does not take is refused rather than ignored. This
    // is the silent-loss direction: `/// ensuers: ret == 99` was dropped, so the
    // function had no postcondition, was checked against `true`, and came back
    // `Verified` with zero obligations -- a green report for a claim nobody read.
    // A `variant:` is the same shape from the other side: the reader wrote a
    // termination measure and the tool ignored it, so a total-correctness claim
    // would rest on nothing. Refusing names the line and the keyword it looks
    // like, which is what a typo needs, and it is the same discipline as an
    // unreadable `requires`.
    if let Some(c) = contract {
        if let Some((line, text)) = c.unknown.first() {
            return FnOutcome::Skipped {
                reason: format!(
                    "line {line}: `{text}` is not a clause this frontend takes; refusing \
                     rather than verifying the function without it"
                ),
            };
        }
    }
    // Two contracts for one function: the impl's own and the trait's it inherits.
    // `resolve` can only return one, so the other would be dropped without a word.
    // Refused, naming both, because a claim the source wrote must not vanish.
    if let Some(reason) = specs.contract_conflict(&f.name) {
        return FnOutcome::Skipped { reason };
    }
    let arg_vars = spec::arg_vars_named(f, rename.as_ref());
    // The *entry* value of each reference argument, keyed by the contract's name
    // for it, for `old(c)` in a postcondition. A bare `c` in an `ensures` is the
    // value at *return* (see the `post` closure), so this is the only route back to
    // the input. Built once, from the same bindings `arg_vars` uses, so a name and
    // its entry value cannot disagree.
    let old_args_for_post: BTreeMap<String, smt::Var> = f
        .arg_locals
        .iter()
        .filter_map(|&l| {
            if !matches!(f.ty_of(l), Some(Ty::Ref(_))) {
                return None;
            }
            let name = spec::arg_name_of(f, rename.as_ref(), l)?;
            let v = *arg_vars.get(&name)?;
            Some((name, v))
        })
        .collect();
    let signed = spec::signed_args_named(f, rename.as_ref());
    // Fields of struct-typed arguments, bound to their own symbolic inputs. The
    // same bindings are handed to the executor as seeds, so `c.lo` in a contract
    // and `((*_1).0)` in the body name one variable.
    let mut fields = spec::field_env_named(f, rename.as_ref(), &specs.structs, &specs.enums);
    // Named `const` items the contract may name, from the program's own table --
    // the same one the executor folds a body's `const LIMIT` from, so a contract's
    // `LIMIT` and the body's `LIMIT` are one value. The executor's `Env` carries
    // this table for the invariant path already; this is the contract path's copy.
    fields.consts = prog.consts.clone();
    // Slice element references a contract names, bound before the rewrite runs so
    // each `xs[k]` has a binding to rewrite to. Done here, once, rather than on
    // demand, because the postcondition is evaluated inside a closure that cannot
    // hold a `&mut`.
    if let Some(c) = contract {
        for text in c.requires.iter().chain(c.ensures.iter()).chain(c.invariants.iter()) {
            fields.bind_index_refs(text, &arg_vars);
        }
    }
    let ret_signed = f.ret_ty.is_signed();

    // A loop invariant. The clause carries no loop label, so it can only be
    // attached when there is exactly one to attach it to. A function with
    // several `invariant:` lines is refused rather than guessed at: pairing the
    // wrong text with the wrong loop would check a preservation obligation that
    // does not mean what the source says, which is the one failure this crate
    // exists to avoid.
    let invariant: Option<&str> = match contract {
        None => None,
        Some(c) => match c.invariants.len() {
            0 => None,
            1 => Some(c.invariants[0].as_str()),
            _ => {
                return FnOutcome::Skipped {
                    reason: "several `invariant:` clauses, and there is no way to say which \
                             loop each belongs to"
                        .to_string(),
                }
            }
        },
    };

    // The loop termination measure, if the contract carries one. A `variant:`
    // without an `invariant:` is refused rather than ignored: the measure has no
    // loop head to be evaluated at (the invariant is what locates the loop), so
    // taking it would mean guessing which loop it is about. Ignoring it silently
    // would be worse still -- the reader wrote a termination claim and the tool
    // would report partial correctness as if it were total.
    let variant: Option<&str> = match contract {
        None => None,
        Some(c) => match c.variant.as_deref() {
            None => None,
            Some(v) => {
                if c.invariants.is_empty() {
                    return FnOutcome::Skipped {
                        reason: "a `variant:` was declared with no `invariant:`; the measure \
                                 needs the loop the invariant locates"
                            .to_string(),
                    };
                }
                Some(v)
            }
        },
    };

    // The loop-unwinding bound, if the contract carries one. It applies to a
    // function's loops whether or not it also has an `invariant:`: an invariant
    // decides a loop by induction (no unwinding), but a *second* loop with no
    // invariant is still unwound, and the bound governs it. It is not tied to the
    // invariant the way `variant:` is, so a lone `unwind:` is honoured rather than
    // refused.
    let unwind: Option<u32> = contract.and_then(|c| c.unwind);

    // Build the precondition. No contract means `true`, which is the right
    // default: a function with no `requires` is checked for panic freedom on
    // every input.
    let mut pre = None;
    if let Some(c) = contract {
        for r in &c.requires {
            match spec::eval_requires(r, &arg_vars, &signed, &fields) {
                Ok(p) => pre = Some(match pre {
                    None => p,
                    Some(prev) => smt::and(prev, p),
                }),
                Err(e) => {
                    return FnOutcome::Skipped {
                        reason: format!("unreadable `requires`: {e}"),
                    }
                }
            }
        }
    }

    // A symbolic subscript is modelled as an ite chain, which is an honest model
    // of the element only where the index is in range. The chain cannot make that
    // true on its own, so the *precondition* has to establish it: if `requires`
    // does not imply the bound, the subscript is refused rather than checked
    // against a chain that quietly returned the wrong element for an
    // out-of-range index.
    //
    // Conjoining the bound into the precondition instead would be unsound in the
    // direction that matters: it would strengthen what the source asked to be
    // checked, so a contract proved under `i < 4` would claim to hold without it.
    //
    // A slice needs *two* facts. `i < len` says the named index is in range, and
    // `len <= MAX_INDEX_CHAIN` says the enumeration covers the whole slice -- so
    // a read at some *other* index the body uses is also covered rather than
    // falling through the chain to a wrong value. The second is a fact about the
    // length, not the index, which is why bounding the index alone is not enough.
    for (idx, bound) in fields.index_guards() {
        // Two facts, checked separately so the refusal names the one that is
        // missing. A combined message would leave a user who wrote one of the two
        // bounds unable to tell which one the checker wanted.
        let (cond, what) = match bound {
            spec::IndexBound::Const(n) => (smt::ult_const(idx, n), format!("`i < {n}`")),
            spec::IndexBound::Len(len) => (
                smt::and(smt::ult(idx, len), smt::ule_const(len, spec::MAX_INDEX_CHAIN)),
                format!("`i < xs.len()` and `xs.len() <= {}`", spec::MAX_INDEX_CHAIN),
            ),
        };
        let established = match pre {
            Some(p) => smt::prove(smt::implies(p, cond)) == smt::Verdict::Valid,
            None => false,
        };
        if established {
            continue;
        }
        // Which half is missing, for a slice. An array has only the one fact, so
        // it keeps the plain message.
        let detail = match bound {
            spec::IndexBound::Const(_) => String::new(),
            spec::IndexBound::Len(len) => {
                let in_range = match pre {
                    Some(p) => smt::prove(smt::implies(p, smt::ult(idx, len)))
                        == smt::Verdict::Valid,
                    None => false,
                };
                let bounded = match pre {
                    Some(p) => {
                        smt::prove(smt::implies(p, smt::ule_const(len, spec::MAX_INDEX_CHAIN)))
                            == smt::Verdict::Valid
                    }
                    None => false,
                };
                match (in_range, bounded) {
                    (false, false) => " (neither `i < xs.len()` nor `xs.len() <= 64` holds)",
                    (false, true) => " (`i < xs.len()` does not hold)",
                    (true, false) => {
                        " (`xs.len() <= 64` does not hold: the slice may be longer than the \
                         enumeration covers)"
                    }
                    (true, true) => "",
                }
                .to_string()
            }
        };
        return FnOutcome::Skipped {
            reason: format!(
                "a symbolic index is not known to be in range: the precondition does not \
                 imply {what}{detail}, and the subscript is only modelled there"
            ),
        };
    }

    // Build the postcondition as a closure over the return value.
    //
    // An unreadable `ensures` must not be quietly dropped: folding it into `true`
    // would verify the function with no postcondition checked. The closure
    // returns a `Result` for that reason, and `exec` turns an error into an
    // unmodelled path. The parse is also checked *here*, up front, so that a
    // function with no reachable `return` cannot leave the error unmentioned.
    //
    // The check reuses `arg_vars` and the return local's own index and width, so
    // it declares exactly the handles the run itself will declare. It must not
    // reset the arena to get "throwaway" variables: `pre` and `arg_vars` are
    // already live handles in this context, and a reset would invalidate them,
    // which would drop the precondition from every path and make the whole run
    // unsound in the other direction.
    let ensures: Vec<String> = contract.map(|c| c.ensures.clone()).unwrap_or_default();
    if !ensures.is_empty() {
        // Local `_0` is the return place; `Ty::width` is `Some` for a scalar
        // return, which is the only case where a bare `ret` can be read. For an
        // aggregate there is no single word, so the probe must pass `None` here
        // exactly as the run does -- a fabricated one-bit word would let a bare
        // `ret` in an aggregate contract parse against it, and the width then
        // comes out as 1, so `ret <= 5` is refused with a message about a
        // "1-bit width" that has nothing to do with the function.
        let probe_ret = f.ret_ty.width().map(|w| smt::var_named(0, w.clamp(1, 64)));
        // The probe must resolve exactly what the real postcondition will, so
        // `ret.N` is bound here too. Leaving it out would make the probe fail on a
        // contract the run could have handled, and the function would be skipped
        // for a reason that is not true of it.
        //
        // Only the components a contract *names* are probed. Binding every
        // declared component made a `(u8, &u8)` return unprobeable -- component 1
        // is a reference with no bit-vector width -- so a contract about `ret.0`
        // alone skipped the whole function. A component the contract does name and
        // that has no width is still refused, because then the name really cannot
        // be resolved.
        let mut probe_fields = fields.clone();
        let named_components = spec::named_ret_components(&ensures);
        if let Ty::Tuple(ts) = &f.ret_ty {
            for i in &named_components {
                match ts.get(*i as usize) {
                    Some(ty) if probe_fields.probe_ret_slot(*i, ty).is_some() => {}
                    _ => {
                        return FnOutcome::Skipped {
                            reason: format!(
                                "cannot bind `ret.{i}`: the component's type has no bit-vector width"
                            ),
                        };
                    }
                }
            }
        }
        // The probe's `ret` is `None` exactly when the return type has no single
        // word, so the aggregate message is the honest one here.
        let probe_absent =
            if probe_ret.is_some() { spec::RET_IS_UNKNOWN } else { spec::RET_IS_AGGREGATE };
        // An enum return: bind the discriminant so `ret.is_ok()` and friends parse
        // in the probe exactly as they will in the run. The tag is a `usize`-wide
        // word (the enum's discriminant type), which is the width the run passes.
        // The probe discards its result, so a throwaway variable is enough; it must
        // only be the right *width* for `eq_const` to be well-formed.
        //
        // The *payload* bindings (`ret.Ok`, `ret.Run`) are probed too, and they are
        // gated on the enum layout rather than on the success/failure pair: a user
        // enum with neither `Ok` nor `Some` has no `is_ok`, but its payloads are
        // still meaningful.
        if spec::ret_enum_def(&f.ret_ty, &specs.enums).is_some() {
            // A throwaway tag, above every slot the run will use so it cannot
            // collide with a live variable (see `probe_ret_enum_slot`). The probe
            // discards its result; it only has to be the right *width* for
            // `eq_const` to be well-formed.
            if let Some(tag) = probe_fields.probe_ret_enum_slot(USIZE_WIDTH) {
                if let Some((ok, err)) = spec::enum_ret_discriminants(&f.ret_ty, &specs.enums) {
                    probe_fields.bind_ret_enum(tag, ok, err);
                }
                // A contract naming a payload (`ret.Ok`, `ret.Some`, `ret.Err`,
                // `ret.None`, `ret.Run`) binds a variable of the payload's own width
                // and sign, guarded on the discriminant. The payload type comes from
                // the enum's layout (`Result<u8, u8>` gives `Ok: u8`, `Err: u8`),
                // which is the same table the run reads.
                probe_fields.probe_ret_payloads(&f.ret_ty, &specs.enums, tag, &ensures);
            }
        }
        if let Some(err) = ensures.iter().find_map(|e| {
            spec::eval_ensures(
                e,
                &arg_vars,
                probe_ret,
                probe_absent,
                &signed,
                ret_signed,
                &probe_fields,
                &old_args_for_post,
            )
            .err()
        }) {
            return FnOutcome::Skipped { reason: format!("unreadable `ensures`: {err}") };
        }
    }
    let args_for_post = arg_vars.clone();
    let fields_for_post = fields.clone();
    // The names bound to a reference-to-scalar argument. A bare one in an `ensures`
    // means its value at *return*, so the `post` closure must rebind it to the final
    // value -- and, when the final value is not known on this path, *remove* it, so
    // the name is refused rather than silently read as the entry value. Falling back
    // to the entry value is the false proof this shape closed.
    let ref_arg_names: Vec<String> = f
        .arg_locals
        .iter()
        .filter(|&&l| matches!(f.ty_of(l), Some(Ty::Ref(_))))
        .filter_map(|&l| spec::arg_name_of(f, rename.as_ref(), l))
        .collect();
    // The return type's components, for a postcondition that names `ret.N`. The
    // type comes from the MIR (`-> (u8, u8)`), so the binding is to the declared
    // shape rather than to whichever elements a particular path happened to
    // write: a path that leaves `_0.1` unwritten must make `ret.1` a refusal, not
    // a silently dropped conjunct.
    let ret_components: Vec<Ty> = match &f.ret_ty {
        Ty::Tuple(ts) => ts.clone(),
        _ => Vec::new(),
    };
    // Which refusal to give when a bare `ret` is unbound. It is decided from the
    // return *type*: a scalar return can only be unbound because its value is
    // unknown on this path, while an aggregate has no single word to bind at all.
    let ret_absent = if f.ret_ty.width().is_some() {
        spec::RET_IS_UNKNOWN
    } else {
        spec::RET_IS_AGGREGATE
    };
    // The recursion contract: when the function declares a `decreases:` measure,
    // a self-call is answered by the contract instead of being inlined. The
    // measure is required -- without it there is no induction principle and the
    // assumption would be circular -- so its absence leaves `rec` as `None` and
    // the call falls back to inlining. See `exec::Recursion`. Built here, before
    // `signed` is moved into the `post` closure below.
    let rec = match contract {
        Some(c) if !c.decreases.is_empty() => {
            if c.decreases.len() > 1 {
                return FnOutcome::Skipped {
                    reason: "several `decreases:` clauses, and there is no way to say which \
                             measure the recursion counts down"
                        .to_string(),
                };
            }
            Some(exec::Recursion {
                requires: c.requires.clone(),
                ensures: c.ensures.clone(),
                decreases: c.decreases[0].clone(),
                signed: signed.clone(),
                consts: prog.consts.clone(),
                ret_signed,
            })
        }
        _ => None,
    };

    let post = if ensures.is_empty() {
        None
    } else {
        let enum_ret = spec::enum_ret_discriminants(&f.ret_ty, &specs.enums);
        Some(move |ret: Option<smt::Var>,
                   projs: &[(u32, smt::Var)],
                   ret_payloads: &[(u64, smt::Var)],
                   ref_final: &[(u32, smt::Var)]| {
            // A reference argument's name denotes the value the body left at the
            // target, so a bare `c` in the postcondition is bound to the *final*
            // value. Binding it to the entry value instead (which `arg_vars` holds)
            // was a false proof: `ensures: c == 0` on `*c = 5` verified, because
            // `c` still named the input. The entry value stays reachable through
            // `old(c)`, which is why the two maps are handed over separately.
            //
            // A reference argument whose final value is not known on this path is
            // *removed* from the map rather than left at its entry value: a bare
            // name that could not be read at return must be refused, never quietly
            // resolved to the input. `old(name)` still works -- the entry value is
            // known regardless of what the body did.
            let mut args = args_for_post.clone();
            for name in &ref_arg_names {
                args.remove(name);
            }
            for (l, v) in ref_final {
                if let Some(name) = spec::arg_name_of(f, rename.as_ref(), *l) {
                    args.insert(name, *v);
                }
            }
            // Bind each declared component that this path actually produced.
            let mut fields = fields_for_post.clone();
            for (i, ty) in ret_components.iter().enumerate() {
                let i = i as u32;
                // Declared but unwritten on this path: binding a *fresh*
                // unconstrained variable would be wrong, because a postcondition
                // about `ret.1` would then pass vacuously. Leaving it unbound makes
                // the parser refuse the name instead.
                if let Some((_, v)) = projs.iter().find(|(k, _)| *k == i) {
                    fields.bind_ret(i, ty, *v);
                }
            }
            // An enum return: bind the discriminant, so `ret.is_ok()` and friends
            // read the tag the body produced. `ret` here is the tag variable the
            // executor passed (the return word for an enum-returning function), and
            // the discriminants are the same ones the body's `switchInt` compares.
            if let Some(tag) = ret {
                // `ret.is_ok()`/`is_some()` need a success/failure pair, which only
                // `Result`/`Option` and a user enum with `Ok`/`Some` have. A user
                // enum with neither is refused those methods, but its *payloads*
                // (`ret.Run`) are still bound below: a payload is meaningful
                // whenever the layout names the variant, regardless of the
                // success/failure reading.
                if let Some((ok, err)) = enum_ret {
                    fields.bind_ret_enum(tag, ok, err);
                }
                // The payloads a contract names (`ret.Ok`, `ret.Some`, `ret.Run`),
                // each bound to the variable the executor holds for it and guarded
                // on the discriminant. The payload values come from `ret_payloads`,
                // keyed by the payload's *discriminant* -- the executor writes a
                // downcast payload under the variant's own number, so the two agree
                // by construction.
                spec::bind_ret_payloads(
                    &mut fields,
                    &f.ret_ty,
                    &specs.enums,
                    tag,
                    ret_payloads,
                    &ensures,
                );
            }
            // `ret` is `None` when the return value is an aggregate: there is no
            // single word to stand for it, and the parser refuses a bare `ret`
            // rather than checking it against a fabricated value. Components are
            // still reachable as `ret.0`, `ret.1` through `fields`.
            let mut acc: Option<crate::smt::Pred> = None;
            for e in &ensures {
                let p = spec::eval_ensures(
                    e,
                    &args,
                    ret,
                    ret_absent,
                    &signed,
                    ret_signed,
                    &fields,
                    &old_args_for_post,
                )
                .map_err(|err| err.to_string())?;
                acc = Some(match acc {
                    None => p,
                    Some(prev) => smt::and(prev, p),
                });
            }
            Ok(acc.unwrap_or_else(|| smt::truth(true)))
        })
    };

    // Arguments the precondition pins to a constant. The executor seeds those
    // arguments with their literal, which is sound -- every model of `pre` has the
    // argument equal to it -- and is what makes a body whose operand is pinned build
    // its operations on a literal, where the constant folds collapse them. Without
    // it a pinned 64-bit divider is built symbolically and the query is refused for
    // the size of its own diagram even though the precondition leaves one input.
    let mut pin_buf = [(0u32, 0u64); smt::MAX_PINS];
    let n_pins = match pre {
        Some(p) => smt::pinned_vars(p, &mut pin_buf),
        None => 0,
    };
    let pins: Vec<(u32, u64)> = pin_buf[..n_pins].to_vec();

    // The callees a call may be answered from a contract rather than a body. A
    // name the dump already contains is not in here: its body is inlined, which
    // is strictly more precise than assuming what it promised.
    let callees = exec::CalleeEnv::new(prog, specs);
    let report = exec::verify_fn(
        prog,
        f,
        pre,
        post,
        exec::LoopSpec { invariant, variant, unwind },
        &callees,
        &exec::Seeds {
            fields: fields.seeds.clone(),
            nested: fields.nested_seeds.clone(),
            lens: fields.len_seeds.clone(),
            array_lens: fields.array_lens.clone(),
            slice_steps: fields.slice_chain_steps(),
            elems: fields.elem_seeds.clone(),
            path_elems: fields.path_elem_seeds.clone(),
            tags: fields.tag_seeds.clone(),
            payload_seeds: fields.payload_seeds.clone(),
            pins,
        },
        rec,
    );

    // A definite failure outranks incompleteness: a counterexample is a result.
    // The polarity is per-kind, so this cannot just look for `Counterexample`:
    // a postcondition fails on a `Counterexample` or an `Unsat`, and a panic
    // fails on a `Counterexample` or a `Valid` (a panic that happens on *every*
    // input, which has no witness to show).
    if let Some(ob) = report.first_failure() {
        // The diagnosis is per-kind: an `Unsat` postcondition holds for *no*
        // input, while a `Valid` panic fires on *every* input. Both leave no
        // witness, so the detail cannot be one shared string.
        //
        // The witness is rendered with the source names the `debug` bindings
        // recorded, so a report says `x = 224` rather than `v1:u8 = 224`. A
        // variable with no source name -- a temporary, a promoted constant --
        // keeps its `v{index}:u{width}` spelling, so the fallback is exactly the
        // old rendering.
        let names: Vec<(&str, u32)> =
            f.local_names.iter().map(|(&l, n)| (n.as_str(), l)).collect();
        return FnOutcome::Failed {
            kind: ob.kind.to_string(),
            detail: ob.failure_detail_named(&names),
        };
    }
    if report.undecided() > 0 {
        let mut reasons = report.unknown_paths.clone();
        reasons.push(format!("{} obligation(s) the engine could not decide", report.undecided()));
        return FnOutcome::Incomplete { report: Box::new(report), reasons };
    }
    if !report.unknown_paths.is_empty() {
        return FnOutcome::Incomplete {
            reasons: report.unknown_paths.clone(),
            report: Box::new(report),
        };
    }
    FnOutcome::Verified {
        obligations: report.obligations.len(),
        panics_ruled_out: report.panics_ruled_out(),
    }
}

/// The result for a whole file.
#[derive(Clone, Debug, Default)]
pub struct FileReport {
    /// The file these results are about.
    pub source: PathBuf,
    /// The edition the file was compiled under.
    ///
    /// A `verified` that does not say which edition it holds under is only half a
    /// claim: the edition changes the lowering, so the verdict is about *this*
    /// edition's program. It is `None` only for a run whose MIR text was supplied
    /// directly (tests), where no edition was involved.
    pub edition: Option<Edition>,
    /// One outcome per verified function, in contract order.
    pub outcomes: Vec<(String, FnOutcome)>,
    /// Functions that carried a contract but were not found in the MIR. A
    /// non-empty list means the run covered less than the contracts asked for.
    pub missing: Vec<String>,
}

impl FileReport {
    /// How many functions were fully verified.
    pub fn verified(&self) -> usize {
        self.outcomes.iter().filter(|(_, o)| o.is_verified()).count()
    }

    /// How many functions had a definite counterexample.
    pub fn failed(&self) -> usize {
        self.outcomes.iter().filter(|(_, o)| matches!(o, FnOutcome::Failed { .. })).count()
    }

    /// How many functions were left undecided.
    pub fn incomplete(&self) -> usize {
        self.outcomes.iter().filter(|(_, o)| matches!(o, FnOutcome::Incomplete { .. })).count()
    }

    /// How many functions were skipped outright.
    pub fn skipped(&self) -> usize {
        self.outcomes.iter().filter(|(_, o)| matches!(o, FnOutcome::Skipped { .. })).count()
    }

    /// True only when nothing failed, nothing was incomplete, nothing was
    /// skipped, and every contracted function was found. A skipped function is
    /// *not* a pass: it means a contract could not be read, so the function was
    /// never checked, and counting it as clean would turn an unreadable contract
    /// into a green report.
    pub fn is_clean(&self) -> bool {
        self.failed() == 0
            && self.incomplete() == 0
            && self.skipped() == 0
            && self.missing.is_empty()
    }
}

/// Verify every contracted function in one source file.
///
/// `only` restricts the run to the named functions, which is what a per-file
/// contract test wants: verifying the whole file on every call would be slow and
/// would report unrelated functions.
pub fn verify_file(source: &Path, only: &[String]) -> Result<FileReport, String> {
    verify_file_opts(source, only, &MirOptions::default())
}

/// [`verify_file`] with the run's options (currently the edition).
pub fn verify_file_opts(
    source: &Path,
    only: &[String],
    opts: &MirOptions,
) -> Result<FileReport, String> {
    let rustc = std::env::var("VERIF_RUSTC").unwrap_or_else(|_| "rustc".into());
    verify_file_with_opts(&rustc, source, only, opts)
}

/// [`verify_file`] with the compiler named explicitly. See [`emit_mir_with`].
pub fn verify_file_with(
    rustc: &str,
    source: &Path,
    only: &[String],
) -> Result<FileReport, String> {
    verify_file_with_opts(rustc, source, only, &MirOptions::default())
}

/// [`verify_file_with`] with the run's options.
pub fn verify_file_with_opts(
    rustc: &str,
    source: &Path,
    only: &[String],
    opts: &MirOptions,
) -> Result<FileReport, String> {
    let text = std::fs::read_to_string(source)
        .map_err(|e| format!("could not read {}: {e}", source.display()))?;
    let specs = spec::extract(&text);
    let (mir, edition) = emit_mir_with_opts(rustc, source, opts)?;
    let prog =
        parse::parse_program_scoped(&mir, &enum_layouts(&specs), &specs.crate_consts, &specs.const_generics, &specs.impl_owners, &specs.impl_traits, &specs.impl_trait_args, &specs.declared_traits);

    let (targets, missing) = resolve_targets(&prog, &specs);
    let mut report = FileReport {
        source: source.to_path_buf(),
        edition: Some(edition),
        missing,
        ..Default::default()
    };
    for (key, f) in select(&prog, &targets, only) {
        let outcome = smt::with_fresh(|| verify_function(&prog, f, &specs));
        report.outcomes.push((key, outcome));
    }
    Ok(report)
}

/// The executor's view of each enum: names in declaration order, so a
/// `(base as Variant)` downcast resolves to the discriminant the `switchInt`
/// compares against.
///
/// The spec reader carries payload types the parser has no use for, so only the
/// names cross over. Both views are read from the same source in the same pass,
/// which is what keeps a downcast's index and a contract's `Enum::Variant`
/// constant in step by construction rather than by convention.
fn enum_layouts(specs: &Specs) -> BTreeMap<String, parse::EnumLayout> {
    specs
        .enums
        .iter()
        .map(|(name, def)| {
            let variants = def.variants.iter().map(|(v, _, d)| (v.clone(), *d)).collect();
            (name.clone(), parse::EnumLayout { variants })
        })
        .collect()
}

/// The `(report key, function)` pairs for every function the source declared a
/// contract for, plus the contracted names the dump did not contain.
///
/// A free function's contract is keyed by its bare name, which is unique in a
/// file. A method's is keyed by the `(line, column)` of its `impl`, so it is
/// matched to the dump function carrying that same location -- never by the
/// method's bare name alone, which two `impl` blocks can share. A method the dump
/// does not contain is reported missing, exactly like a free function, so a
/// contract cannot be silently dropped.
///
/// The report key is the bare method name when no other contracted method shares
/// it, and `Owner::method` when one does: two methods named `value` would
/// otherwise collapse into one `outcomes` entry and only one of them would be
/// visible. The bare name is preferred because it is what a reader looks for, and
/// it is exactly what the MIR dump itself uses as the method's tail.
fn resolve_targets<'a>(
    prog: &'a MirProgram,
    specs: &Specs,
) -> (Vec<(String, &'a MirFn)>, Vec<String>) {
    // Every method that will be a target, from its own contract or from a trait
    // declaration's, so the tail count below sees both kinds. Counting only
    // `by_method` let two impls of one contracted trait both be keyed by the bare
    // tail, and one `outcomes` entry then hid the other -- the same collapse the
    // location key exists to prevent.
    let method_targets = trait_method_targets(specs);
    // Counted over *distinct* functions, not table entries: a method that declares
    // its own contract and also inherits its trait's appears in both, and counting
    // it twice would spell its key `Owner::method` even though it is the only one
    // -- a key the tests and the report do not expect, for a method that is not
    // ambiguous at all.
    let mut distinct: BTreeSet<(usize, usize, String)> = specs.by_method.keys().cloned().collect();
    distinct.extend(method_targets.iter().cloned());
    let mut tail_counts: BTreeMap<&str, usize> = BTreeMap::new();
    for (_, _, method) in &distinct {
        *tail_counts.entry(method.as_str()).or_default() += 1;
    }

    let mut targets: Vec<(String, &MirFn)> = Vec::new();
    let mut missing: Vec<String> = Vec::new();

    // The contract key is the full source path; the MIR definition name is the
    // shortest crate-unique suffix of it. An exact match wins outright (so
    // `a::f` and `b::a::f` stay apart -- rustc prints both in full once they
    // collide); only when there is none does a unique `::`-aligned suffix count.
    //
    // Both directions of ambiguity are refused, not guessed at. A key that
    // suffix-matches several dump functions is refused, and so is a dump function
    // that several keys suffix-match: either pairing would check one body against
    // another's contract. The second case is the one a `#[cfg]`-excluded item
    // creates -- the key still comes from the source, but its body is not in the
    // dump, so its suffix lands on a *different* compiled function, which would
    // otherwise be reported `Verified` against the wrong contract and conceal
    // that the excluded item was never checked at all.
    let keys: Vec<&String> = specs.by_fn.keys().collect();
    let mut chosen: Vec<Option<usize>> = vec![None; keys.len()];
    let mut exact_owner: BTreeMap<usize, usize> = BTreeMap::new();
    for (ki, key) in keys.iter().enumerate() {
        if let Some(fi) = prog.fns.iter().position(|f| f.name == **key) {
            chosen[ki] = Some(fi);
            exact_owner.insert(fi, ki);
        }
    }
    // A key with exactly one suffix candidate proposes it; a candidate a key
    // already claimed exactly, or that more than one key proposes, is refused.
    let mut proposed: BTreeMap<usize, Vec<usize>> = BTreeMap::new();
    for (ki, key) in keys.iter().enumerate() {
        if chosen[ki].is_some() {
            continue;
        }
        let mut cand: Option<usize> = None;
        let mut count = 0usize;
        for (fi, f) in prog.fns.iter().enumerate() {
            if spec::is_path_suffix(key, &f.name) {
                cand = Some(fi);
                count += 1;
            }
        }
        if count == 1 {
            proposed.entry(cand.unwrap()).or_default().push(ki);
        }
    }
    for (fi, kis) in proposed {
        if kis.len() == 1 && !exact_owner.contains_key(&fi) {
            chosen[kis[0]] = Some(fi);
        }
    }
    for (ki, key) in keys.iter().enumerate() {
        match chosen[ki] {
            Some(fi) => targets.push(((*key).clone(), &prog.fns[fi])),
            // A declaration with no body is *assumed* at each call, which is the
            // modular case rather than a contract whose body went missing. It has
            // no MIR by construction, so reporting it `missing` would make every
            // file that calls an external function unclean.
            None if specs.bodyless.contains(*key) => {}
            None => missing.push((*key).clone()),
        }
    }
    // The report key for a method: the bare tail when it is unique, `Owner::method`
    // when two contracted methods share it.
    let method_key = |line: usize, col: usize, method: &str, f: &MirFn| {
        let ambiguous = tail_counts.get(method).copied().unwrap_or(0) > 1
            || specs.by_fn.contains_key(method);
        if ambiguous {
            match prog.impl_owners.get(&(line, col)) {
                Some(owner) => format!("{owner}::{method}"),
                None => f.name.clone(),
            }
        } else {
            method.to_string()
        }
    };
    let mut seen: BTreeSet<(usize, usize, String)> = BTreeSet::new();
    for (line, col, method) in specs.by_method.keys() {
        seen.insert((*line, *col, method.clone()));
        let method = method.as_str();
        match prog.fns.iter().find(|f| f.impl_loc == Some((*line, *col))
            && f.name.rsplit("::").next() == Some(method))
        {
            Some(f) => targets.push((method_key(*line, *col, method, f), f)),
            None => missing.push(method.to_string()),
        }
    }
    // An `impl` that declares no contract of its own but implements a trait that
    // *does*: the implementation is where the promise is kept or broken, so it is a
    // target. Without this the trait's contract was inherited by `resolve` (so a
    // call to it was answered correctly) but never *checked* on any body, and the
    // declaration itself is not in `by_fn` to be reported missing either -- the
    // promise would be silently unenforced, which is the one outcome this frontend
    // treats as worse than a refusal.
    let mut enforced: BTreeSet<String> = BTreeSet::new();
    for (line, col, method) in method_targets {
        // The impl's own contract, if it has one, is already the entry above; the
        // trait's is then a *second* specification of the same function, and
        // `resolve` can only hand back one of them. Reporting it is the only
        // honest answer: silently preferring either would drop a claim the source
        // wrote. See `verify_function`, which refuses on `contract_conflict`.
        let Some(f) = prog.fns.iter().find(|f| f.impl_loc == Some((line, col))
            && f.name.rsplit("::").next() == Some(method.as_str())) else {
            continue;
        };
        enforced.insert(format!("{}::{method}", specs.impl_traits[&(line, col)]));
        if seen.insert((line, col, method.clone())) {
            targets.push((method_key(line, col, &method, f), f));
        }
    }
    // A trait declaration whose contract no implementation in this file carries is
    // a promise with nothing to keep it. It has no MIR, so it can never be a
    // target, and leaving it unmentioned would make the run `is_clean()` while the
    // claim was never checked -- the silent-loss shape this frontend refuses
    // everywhere else. Reported like any other un-found contract, with the reason
    // spelled out so it is not mistaken for a missing body.
    for key in specs.by_trait.keys() {
        if !enforced.contains(key) {
            missing.push(format!("{key} (a trait declaration with no implementation in this file)"));
        }
    }
    (targets, missing)
}

/// Every `(impl line, impl column, method)` whose contract comes from a *trait
/// declaration* rather than from the implementation.
///
/// A declaration has no body and so can never be a target itself; the implementations
/// are where it has to be checked. This is the inverse of
/// [`crate::mir::spec::Specs::trait_contract`]: that one asks "what does this impl
/// inherit for this method", this one enumerates the pairs so they can be checked.
///
/// Only a trait declaration the scanner read is enumerated, so an `impl` of a trait
/// declared elsewhere (an external trait, or one whose declaration is in another
/// file) contributes nothing -- there is no contract text to check it against.
fn trait_method_targets(specs: &Specs) -> Vec<(usize, usize, String)> {
    let mut out = Vec::new();
    for ((line, col), tr) in &specs.impl_traits {
        // Every declaration the trait carries, which is every method of it this
        // scanner read a contract for. A trait with no contracted method
        // contributes nothing, so an impl of it is left as it was: checked for
        // panic freedom, with no postcondition to establish.
        let prefix = format!("{tr}::");
        for key in specs.by_trait.keys() {
            if let Some(method) = key.strip_prefix(&prefix) {
                out.push((*line, *col, method.to_string()));
            }
        }
    }
    out
}

/// The targets to check: all of them when `only` is empty, otherwise those whose
/// report key or bare tail is named in `only`.
///
/// A name in `only` that matches no contracted target is still looked up in the
/// dump, so naming a function that carries no contract keeps checking it for panic
/// freedom rather than silently reporting nothing.
fn select<'a>(
    prog: &'a MirProgram,
    targets: &[(String, &'a MirFn)],
    only: &[String],
) -> Vec<(String, &'a MirFn)> {
    if only.is_empty() {
        return targets.to_vec();
    }
    let mut out: Vec<(String, &'a MirFn)> = Vec::new();
    for want in only {
        let mut found = false;
        for (key, f) in targets {
            // `key` is the report key (a method's `Owner::method`, or a free
            // function's full source path). A request matches the key, the MIR
            // name, or a bare tail of either -- so `f`, `a::f` and `Owner::f` all
            // find their target without over-matching a different owner.
            if want == key
                || f.name == *want
                || key.rsplit("::").next() == Some(want.as_str())
                || f.name.rsplit("::").next() == Some(want.as_str())
            {
                out.push((key.clone(), *f));
                found = true;
            }
        }
        if !found {
            if let Some(f) = prog.get(want) {
                out.push((want.clone(), f));
            }
        }
    }
    out
}

/// Verify a whole MIR dump, using contracts from a companion source file.
pub fn verify_mir_text(
    mir: &str,
    specs: &Specs,
    only: &[String],
) -> Result<FileReport, String> {
    let prog =
        parse::parse_program_scoped(mir, &enum_layouts(specs), &specs.crate_consts, &specs.const_generics, &specs.impl_owners, &specs.impl_traits, &specs.impl_trait_args, &specs.declared_traits);
    let (targets, missing) = resolve_targets(&prog, specs);
    let mut report = FileReport { missing, ..Default::default() };
    for (key, f) in select(&prog, &targets, only) {
        let outcome = smt::with_fresh(|| verify_function(&prog, f, specs));
        report.outcomes.push((key, outcome));
    }
    Ok(report)
}

/// A helper for tests and tools: parse a dump and return function names.
pub fn function_names(mir: &str) -> Vec<String> {
    parse::parse_program(mir).fns.iter().map(|f| f.name.clone()).collect()
}

/// Map from name to parsed function, for callers that want to inspect the IR.
pub fn functions(mir: &str) -> BTreeMap<String, MirFn> {
    parse::parse_program(mir)
        .fns
        .into_iter()
        .map(|f| (f.name.clone(), f))
        .collect()
}

/// The `Verdict` for a predicate, as a convenience for callers that want to ask
/// a one-off question of the engine under the same arena discipline.
pub fn decide(p: crate::smt::Pred) -> Verdict {
    smt::with_fresh(|| smt::prove(p))
}

/// Re-exported so a caller can name the error type without reaching into `spec`.
pub type ContractError = SpecError;

#[cfg(test)]
mod edition_tests {
    use super::*;
    use std::path::PathBuf;

    /// A scratch directory unique per call, so tests can run in parallel.
    fn scratch(tag: &str) -> PathBuf {
        use std::sync::atomic::{AtomicU64, Ordering};
        static SEQ: AtomicU64 = AtomicU64::new(0);
        let seq = SEQ.fetch_add(1, Ordering::Relaxed);
        let dir = std::env::temp_dir()
            .join(format!("verif-edition-unit-{}-{seq}-{tag}", std::process::id()));
        let _ = std::fs::create_dir_all(&dir);
        dir
    }

    /// A `[package]` that omits `edition` is Cargo's 2015 default, not an error.
    ///
    /// Cargo assigns edition 2015 to a package that does not state one, so
    /// refusing it would stop verification of a package that builds. The
    /// distinction is between a real package (a default applies) and a loose file
    /// (nothing to default) -- and the second must still be refused, or the tool
    /// would compile under an edition the program may not use.
    #[test]
    fn a_package_without_an_edition_defaults_to_2015_but_a_loose_file_does_not() {
        let dir = scratch("no-edition");
        let manifest = dir.join("Cargo.toml");
        std::fs::write(&manifest, "[package]\nname = \"demo\"\nversion = \"0.1.0\"\n").unwrap();
        let src = dir.join("probe.rs");
        std::fs::write(&src, "pub fn f() {}\n").unwrap();
        assert_eq!(
            edition_from_manifest(&src),
            Some(Edition::Rust2015),
            "a package that omits `edition` must resolve to Cargo's 2015 default"
        );

        // A manifest with no `[package]` (a pure virtual workspace) declares no
        // crate, so there is nothing to default and the resolution is `None`.
        std::fs::write(&manifest, "[workspace]\nmembers = [\"a\"]\n").unwrap();
        assert_eq!(
            edition_from_manifest(&src),
            None,
            "a manifest with no `[package]` has no crate edition to default"
        );

        // A loose file (no manifest above it) is still refused by `resolve_edition`
        // when nothing else supplies the edition.
        let loose = std::env::temp_dir().join(format!(
            "verif-loose-{}-{}.rs",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::write(&loose, "pub fn f() {}\n").unwrap();
        // Only assert when no override is set, since the env is process-global.
        if std::env::var("VERIF_EDITION").map(|v| v.is_empty()).unwrap_or(true) {
            assert!(
                resolve_edition(&loose, None).is_err(),
                "a loose file with no edition anywhere must be refused, not defaulted"
            );
        }
        let _ = std::fs::remove_dir_all(&dir);
        let _ = std::fs::remove_file(&loose);
    }

    /// An explicit `package.edition` and a workspace-inherited one both resolve.
    #[test]
    fn a_stated_edition_and_a_workspace_inheritance_both_resolve() {
        let dir = scratch("stated");
        let src = dir.join("probe.rs");
        std::fs::write(&src, "pub fn f() {}\n").unwrap();
        let manifest = dir.join("Cargo.toml");
        std::fs::write(&manifest, "[package]\nname = \"d\"\nedition = \"2021\"\n").unwrap();
        assert_eq!(edition_from_manifest(&src), Some(Edition::Rust2021));

        // `edition.workspace = true` reads the value from the workspace root.
        let root = scratch("ws-root");
        std::fs::write(
            root.join("Cargo.toml"),
            "[workspace]\nmembers = [\"member\"]\n[workspace.package]\nedition = \"2018\"\n",
        )
        .unwrap();
        let member = root.join("member");
        let _ = std::fs::create_dir_all(&member);
        let m_src = member.join("probe.rs");
        std::fs::write(&m_src, "pub fn f() {}\n").unwrap();
        std::fs::write(
            member.join("Cargo.toml"),
            "[package]\nname = \"m\"\nedition.workspace = true\n",
        )
        .unwrap();
        assert_eq!(
            edition_from_manifest(&m_src),
            Some(Edition::Rust2018),
            "`edition.workspace = true` must resolve against the workspace root"
        );

        // An unparseable edition is a refusal, not a fallback.
        std::fs::write(&manifest, "[package]\nname = \"d\"\nedition = \"2030\"\n").unwrap();
        assert_eq!(edition_from_manifest(&src), None, "an unknown edition is refused");

        let _ = std::fs::remove_dir_all(&dir);
        let _ = std::fs::remove_dir_all(&root);
    }
}