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};
pub use crate::mir::exec::{MirReport, Obligation, ObligationKind};
use crate::mir::spec::{self, SpecError, Specs};
use crate::smt::{self, Verdict};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Edition {
Rust2015,
Rust2018,
Rust2021,
Rust2024,
}
impl Edition {
pub fn as_str(self) -> &'static str {
match self {
Edition::Rust2015 => "2015",
Edition::Rust2018 => "2018",
Edition::Rust2021 => "2021",
Edition::Rust2024 => "2024",
}
}
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())
}
}
#[derive(Clone, Debug, Default)]
pub struct MirOptions {
pub edition: Option<Edition>,
pub externs: Vec<(String, PathBuf)>,
pub search_paths: Vec<PathBuf>,
pub probed_with: Option<String>,
}
#[cfg(feature = "std")]
pub fn extern_options(name: &str) -> Option<MirOptions> {
let rustc = std::env::var("VERIF_RUSTC").unwrap_or_else(|_| "rustc".into());
extern_options_with(&rustc, name)
}
#[cfg(feature = "std")]
pub fn extern_options_with(rustc: &str, name: &str) -> Option<MirOptions> {
let roots = build_script_roots()?;
let prefix = format!("lib{}-", name.replace('-', "_"));
let mut found: Vec<PathBuf> = Vec::new();
for root in &roots {
let Ok(entries) = std::fs::read_dir(root) else {
continue;
};
for e in entries.flatten() {
let p = e.path();
let Some(f) = p.file_name().and_then(|s| s.to_str()) else {
continue;
};
if f.starts_with(&prefix) && f.ends_with(".rlib") {
found.push(p);
}
}
}
found.sort();
found.dedup();
found.sort_by_key(|p| {
std::cmp::Reverse(
std::fs::metadata(p).and_then(|m| m.modified()).ok(),
)
});
let search: Vec<PathBuf> = roots;
let probed_with = Some(canonical_compiler(rustc));
for cand in found {
let mut opts = MirOptions {
externs: vec![(name.to_string(), cand.clone())],
search_paths: search.clone(),
probed_with: probed_with.clone(),
..MirOptions::default()
};
opts.search_paths.retain(|r| r.is_dir());
if extern_compiles(rustc, &opts) {
return Some(opts);
}
}
None
}
fn canonical_compiler(p: &str) -> String {
commit_identity(p).unwrap_or_else(|| {
std::fs::canonicalize(p)
.map(|c| c.to_string_lossy().into_owned())
.unwrap_or_else(|_| p.to_string())
})
}
fn commit_identity(p: &str) -> Option<String> {
let out = Command::new(p).arg("-vV").output().ok()?;
if !out.status.success() {
return None;
}
let text = String::from_utf8(out.stdout).ok()?;
let mut commit = None;
let mut host = None;
for line in text.lines() {
if let Some(v) = line.strip_prefix("commit-hash: ") {
commit = Some(v.trim());
} else if let Some(v) = line.strip_prefix("host: ") {
host = Some(v.trim());
}
}
Some(format!("{}/{}", commit?, host?))
}
fn check_probe_compiler(rustc: &str, opts: &MirOptions) -> Result<(), String> {
let Some(probed) = opts.probed_with.as_deref() else {
return Ok(());
};
let emitting = canonical_compiler(rustc);
if emitting == probed {
return Ok(());
}
Err(format!(
"the externs were probed with `{probed}` but MIR would be emitted with `{emitting}`: \
an rlib's metadata is compiler-specific, so probe and emit must name one compiler \
-- pass the same `rustc` to `extern_options_with` and `verify_file_with_opts`"
))
}
#[cfg(feature = "std")]
fn extern_compiles(rustc: &str, opts: &MirOptions) -> bool {
let Some((name, _)) = opts.externs.first() else {
return false;
};
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("verif-extern-probe-{}-{seq}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
let src = dir.join("probe.rs");
let body = format!("#![allow(unused_extern_crates)]\nextern crate {name};\n");
if std::fs::write(&src, body).is_err() {
return false;
}
let mut cmd = Command::new(rustc);
cmd.arg("--edition=2021")
.arg("--crate-type=lib")
.arg("--emit=metadata")
.arg("-o")
.arg(dir.join("probe.rmeta"));
for (n, p) in &opts.externs {
cmd.arg("--extern").arg(format!("{}={}", n, p.display()));
}
for d in &opts.search_paths {
cmd.arg("-L").arg(format!("dependency={}", d.display()));
}
let ok = cmd.arg(&src).output().map(|o| o.status.success()).unwrap_or(false);
let _ = std::fs::remove_dir_all(&dir);
ok
}
#[cfg(feature = "std")]
fn build_script_roots() -> Option<Vec<PathBuf>> {
let out = PathBuf::from(std::env::var("OUT_DIR").ok()?);
let host = std::env::var("HOST").ok();
let target = std::env::var("TARGET").ok();
build_script_roots_from(&out, host.as_deref(), target.as_deref())
}
fn build_script_roots_from(
out: &std::path::Path,
host: Option<&str>,
target: Option<&str>,
) -> Option<Vec<PathBuf>> {
let build_dir = out.ancestors().find(|a| a.file_name().is_some_and(|n| n == "build"))?;
let profile = build_dir.parent()?;
let mut roots = vec![profile.join("deps")];
collect_outs(build_dir, &mut roots);
if let (Some(h), Some(t)) = (host, target) {
if h != t {
if let (Some(triple_dir), Some(root)) =
(profile.parent(), profile.parent().and_then(|p| p.parent()))
{
if triple_dir.file_name().is_some_and(|n| n == t) {
if let Some(name) = profile.file_name() {
let host_profile = root.join(name);
roots.push(host_profile.join("deps"));
collect_outs(&host_profile.join("build"), &mut roots);
}
}
}
}
}
roots.retain(|r| r.is_dir());
if roots.is_empty() {
None
} else {
Some(roots)
}
}
fn collect_outs(build_dir: &std::path::Path, roots: &mut Vec<PathBuf>) {
if let Ok(entries) = std::fs::read_dir(build_dir) {
for e in entries.flatten() {
if let Ok(inner) = std::fs::read_dir(e.path()) {
for i in inner.flatten() {
roots.push(i.path().join("out"));
}
}
}
}
}
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()
))
}
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") {
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),
None => declares_package(&text).then_some(Edition::Rust2015),
}
}
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)
})
}
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
}
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()?;
}
}
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 };
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 {
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
}
fn unquote_toml_key(k: &str) -> &str {
k.strip_prefix('"').and_then(|s| s.strip_suffix('"')).unwrap_or(k)
}
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
}
#[derive(Clone, Debug)]
pub enum MirSource {
Emitted {
file: PathBuf,
mir: String,
},
File(PathBuf),
Inline(String),
}
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()
}
}
pub fn emit_mir(file: &Path) -> Result<String, String> {
emit_mir_opts(file, &MirOptions::default()).map(|(text, _edition)| text)
}
pub fn emit_mir_with(rustc: &str, file: &Path) -> Result<String, String> {
emit_mir_with_opts(rustc, file, &MirOptions::default()).map(|(text, _edition)| text)
}
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)
}
pub fn emit_mir_with_opts(
rustc: &str,
file: &Path,
opts: &MirOptions,
) -> Result<(String, Edition), String> {
let edition = resolve_edition(file, opts.edition)?;
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 mut cmd = Command::new(rustc);
cmd.arg(format!("--edition={}", edition.as_str()))
.arg("--crate-type=lib")
.arg("--emit=mir")
.arg("-o")
.arg(&out_path);
for (name, path) in &opts.externs {
cmd.arg("--extern").arg(format!("{}={}", name, path.display()));
}
for dir in &opts.search_paths {
cmd.arg("-L").arg(format!("dependency={}", dir.display()));
}
let out = cmd
.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))
}
#[derive(Clone, Debug)]
pub enum FnOutcome {
Verified {
obligations: usize,
panics_ruled_out: usize,
},
Failed {
kind: String,
detail: String,
},
Incomplete {
report: Box<MirReport>,
reasons: Vec<String>,
},
Skipped {
reason: String,
},
}
impl FnOutcome {
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}"),
}
}
}
pub fn verify_function(prog: &MirProgram, f: &MirFn, specs: &Specs) -> FnOutcome {
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"
),
};
}
let (contract, rename) = match specs.contract_for_fn(f) {
Ok(x) => x,
Err(reason) => return FnOutcome::Skipped { reason },
};
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"
),
};
}
}
if let Some(reason) = specs.contract_conflict(&f.name) {
return FnOutcome::Skipped { reason };
}
let arg_vars = spec::arg_vars_named(f, rename.as_ref());
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());
let mut fields = spec::field_env_named(f, rename.as_ref(), &specs.structs, &specs.enums);
fields.consts = prog.consts.clone();
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();
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(),
}
}
},
};
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)
}
},
};
let unwind: Option<u32> = contract.and_then(|c| c.unwind);
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}"),
}
}
}
}
}
for (idx, bound) in fields.index_guards() {
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;
}
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"
),
};
}
let ensures: Vec<String> = contract.map(|c| c.ensures.clone()).unwrap_or_default();
if !ensures.is_empty() {
let probe_ret = f.ret_ty.width().map(|w| smt::var_named(0, w.clamp(1, 64)));
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"
),
};
}
}
}
}
let probe_absent =
if probe_ret.is_some() { spec::RET_IS_UNKNOWN } else { spec::RET_IS_AGGREGATE };
if spec::ret_enum_def(&f.ret_ty, &specs.enums).is_some() {
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);
}
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();
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();
let ret_components: Vec<Ty> = match &f.ret_ty {
Ty::Tuple(ts) => ts.clone(),
_ => Vec::new(),
};
let ret_absent = if f.ret_ty.width().is_some() {
spec::RET_IS_UNKNOWN
} else {
spec::RET_IS_AGGREGATE
};
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)]| {
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);
}
}
let mut fields = fields_for_post.clone();
for (i, ty) in ret_components.iter().enumerate() {
let i = i as u32;
if let Some((_, v)) = projs.iter().find(|(k, _)| *k == i) {
fields.bind_ret(i, ty, *v);
}
}
if let Some(tag) = ret {
if let Some((ok, err)) = enum_ret {
fields.bind_ret_enum(tag, ok, err);
}
spec::bind_ret_payloads(
&mut fields,
&f.ret_ty,
&specs.enums,
tag,
ret_payloads,
&ensures,
);
}
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)))
})
};
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();
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,
);
if let Some(ob) = report.first_failure() {
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(),
}
}
#[derive(Clone, Debug, Default)]
pub struct FileReport {
pub source: PathBuf,
pub edition: Option<Edition>,
pub outcomes: Vec<(String, FnOutcome)>,
pub missing: Vec<String>,
}
impl FileReport {
pub fn verified(&self) -> usize {
self.outcomes.iter().filter(|(_, o)| o.is_verified()).count()
}
pub fn failed(&self) -> usize {
self.outcomes.iter().filter(|(_, o)| matches!(o, FnOutcome::Failed { .. })).count()
}
pub fn incomplete(&self) -> usize {
self.outcomes.iter().filter(|(_, o)| matches!(o, FnOutcome::Incomplete { .. })).count()
}
pub fn skipped(&self) -> usize {
self.outcomes.iter().filter(|(_, o)| matches!(o, FnOutcome::Skipped { .. })).count()
}
pub fn is_clean(&self) -> bool {
self.failed() == 0
&& self.incomplete() == 0
&& self.skipped() == 0
&& self.missing.is_empty()
}
}
pub fn verify_file(source: &Path, only: &[String]) -> Result<FileReport, String> {
verify_file_opts(source, only, &MirOptions::default())
}
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)
}
pub fn verify_file_with(
rustc: &str,
source: &Path,
only: &[String],
) -> Result<FileReport, String> {
verify_file_with_opts(rustc, source, only, &MirOptions::default())
}
pub fn verify_file_with_opts(
rustc: &str,
source: &Path,
only: &[String],
opts: &MirOptions,
) -> Result<FileReport, String> {
check_probe_compiler(rustc, opts)?;
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)
}
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()
}
fn resolve_targets<'a>(
prog: &'a MirProgram,
specs: &Specs,
) -> (Vec<(String, &'a MirFn)>, Vec<String>) {
let method_targets = trait_method_targets(specs);
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();
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);
}
}
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])),
None if specs.bodyless.contains(*key) => {}
None => missing.push((*key).clone()),
}
}
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()),
}
}
let mut enforced: BTreeSet<String> = BTreeSet::new();
for (line, col, method) in method_targets {
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));
}
}
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)
}
fn trait_method_targets(specs: &Specs) -> Vec<(usize, usize, String)> {
let mut out = Vec::new();
for ((line, col), tr) in &specs.impl_traits {
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
}
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 {
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
}
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)
}
pub fn function_names(mir: &str) -> Vec<String> {
parse::parse_program(mir).fns.iter().map(|f| f.name.clone()).collect()
}
pub fn functions(mir: &str) -> BTreeMap<String, MirFn> {
parse::parse_program(mir)
.fns
.into_iter()
.map(|f| (f.name.clone(), f))
.collect()
}
pub fn decide(p: crate::smt::Pred) -> Verdict {
smt::with_fresh(|| smt::prove(p))
}
pub type ContractError = SpecError;
#[cfg(test)]
mod edition_tests {
use super::*;
use std::path::PathBuf;
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
}
#[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"
);
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"
);
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();
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);
}
#[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));
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"
);
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);
}
#[test]
fn extern_options_refuses_when_the_artifact_is_absent() {
assert!(
extern_options("a-crate-that-no-build-ever-produced").is_none(),
"an absent artifact must be refused, never guessed"
);
}
#[test]
fn a_cross_build_searches_the_host_profile_directory() {
let root = std::env::temp_dir().join(format!("verif-cross-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let triple = "thumbv7em-none-eabihf";
let out = root.join(triple).join("debug").join("build").join("pkg").join("hash").join("out");
std::fs::create_dir_all(&out).unwrap();
let host_deps = root.join("debug").join("deps");
std::fs::create_dir_all(&host_deps).unwrap();
let target_deps = root.join(triple).join("debug").join("deps");
std::fs::create_dir_all(&target_deps).unwrap();
let roots = build_script_roots_from(&out, Some("x86_64-unknown-linux-gnu"), Some(triple))
.expect("a build directory exists");
let _ = std::fs::remove_dir_all(&root);
assert!(
roots.contains(&host_deps),
"the host profile's deps directory must be searched under cross-compilation: {roots:?}"
);
assert!(
roots.contains(&target_deps),
"the target profile directory is still searched (a non-cross build uses it): {roots:?}"
);
}
#[test]
fn a_host_build_searches_only_its_own_profile_directory() {
let root = std::env::temp_dir().join(format!("verif-host-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let out = root.join("debug").join("build").join("pkg").join("hash").join("out");
std::fs::create_dir_all(&out).unwrap();
let deps = root.join("debug").join("deps");
std::fs::create_dir_all(&deps).unwrap();
let roots = build_script_roots_from(&out, Some("x86_64-unknown-linux-gnu"), Some("x86_64-unknown-linux-gnu"))
.expect("a build directory exists");
let _ = std::fs::remove_dir_all(&root);
let deps_roots: Vec<_> = roots.iter().filter(|r| r.ends_with("deps")).collect();
assert_eq!(
deps_roots,
vec![&deps],
"a host build searches exactly one deps directory -- its own: {roots:?}"
);
}
#[test]
fn an_unresolvable_import_names_the_missing_extern() {
let dir = std::env::temp_dir().join(format!("verif-extern-{}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
let src = dir.join("m.rs");
std::fs::write(
&src,
"use some_crate_nobody_linked::thing;\npub fn f() -> u8 { thing() }\n",
)
.unwrap();
let opts = MirOptions { edition: Some(Edition::Rust2021), ..MirOptions::default() };
let err = emit_mir_with_opts("rustc", &src, &opts).expect_err("an unknown crate cannot resolve");
assert!(
err.contains("E0432") || err.contains("unresolved import"),
"the refusal must name the unresolved import, got: {err}"
);
let _ = std::fs::remove_dir_all(&dir);
}
}
#[cfg(all(test, feature = "std"))]
mod extern_probe_tests {
use super::*;
fn have(toolchain: &str) -> Option<(String, String)> {
let out = Command::new("rustup")
.args(["which", "--toolchain", toolchain, "rustc"])
.output()
.ok()?;
if !out.status.success() {
return None;
}
let path = String::from_utf8(out.stdout).ok()?.trim().to_string();
if path.is_empty() {
return None;
}
let id = canonical_compiler(&path);
Some((path, id))
}
fn active() -> Option<(String, String)> {
let out = Command::new("rustup").args(["which", "rustc"]).output().ok()?;
if !out.status.success() {
return None;
}
let path = String::from_utf8(out.stdout).ok()?.trim().to_string();
if path.is_empty() {
return None;
}
let id = canonical_compiler(&path);
Some((path, id))
}
#[test]
fn the_probe_answers_for_the_compiler_that_will_read_the_rlib() {
let producer_path = std::env::var("RUSTC")
.ok()
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "rustc".into());
let producer = canonical_compiler(&producer_path);
let other = ["1.85", "nightly", "stable"]
.into_iter()
.filter_map(have)
.find(|(_, id)| *id != producer);
let Some((other_path, other_id)) = other else {
eprintln!(
"skipped: no second toolchain installed, so there is no cross-compiler \
case to test (producer identity {producer})"
);
return;
};
let dir = std::env::temp_dir().join(format!(
"verif-extern-cross-{}",
std::process::id()
));
let _ = std::fs::create_dir_all(&dir);
let src = dir.join("lib.rs");
std::fs::write(&src, "pub fn seven() -> u8 { 7 }\n").unwrap();
let rlib = dir.join("libprobe_crate.rlib");
let built = Command::new(&producer_path)
.args(["--crate-type=lib", "--crate-name", "probe_crate", "-o"])
.arg(&rlib)
.arg(&src)
.output()
.map(|o| o.status.success())
.unwrap_or(false);
if !built {
let _ = std::fs::remove_dir_all(&dir);
panic!(
"the producing compiler ({producer_path}, identity {producer}) must be able \
to build a trivial rlib; without it there is nothing to probe"
);
}
let opts = MirOptions {
externs: vec![("probe_crate".into(), rlib.clone())],
..MirOptions::default()
};
assert!(
extern_compiles(&producer_path, &opts),
"the compiler that built the rlib must accept it ({producer_path}, {producer})"
);
assert_ne!(producer, other_id, "the cross toolchain must be a different build");
assert!(
!extern_compiles(&other_path, &opts),
"a different toolchain ({other_path}, {other_id}) must not accept an rlib \
built by {producer_path} ({producer})"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_probed_extern_set_is_refused_by_a_different_compiler() {
let dir = std::env::temp_dir().join(format!("verif-probe-guard-{}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
let src = dir.join("lib.rs");
std::fs::write(&src, "pub fn one() -> u8 { 1 }\n").unwrap();
let hand_built = MirOptions { edition: Some(Edition::Rust2021), ..MirOptions::default() };
assert!(
check_probe_compiler("rustc", &hand_built).is_ok(),
"a hand-built option set names its own rlib and must not be refused"
);
let probed = MirOptions {
edition: Some(Edition::Rust2021),
probed_with: Some(canonical_compiler("rustc")),
..MirOptions::default()
};
assert!(
check_probe_compiler("rustc", &probed).is_ok(),
"the probing compiler must be accepted"
);
let active_id = canonical_compiler("rustc");
if let Some((other_path, other_id)) = ["1.85", "nightly", "stable"]
.into_iter()
.filter_map(have)
.find(|(_, id)| *id != active_id)
{
let err = check_probe_compiler(&other_path, &probed)
.expect_err("a different compiler must be refused");
assert!(
err.contains(&other_id),
"the error must name the emitting compiler's identity {other_id}: {err}"
);
assert_ne!(active_id, other_id, "the two must be different builds");
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_bare_compiler_name_and_its_absolute_path_are_one_identity() {
let Some((abs, abs_id)) = active() else {
eprintln!("skipped: no rustup, so there is no shim/path pair to compare");
return;
};
let bare = canonical_compiler("rustc");
assert_eq!(
bare, abs_id,
"a bare `rustc` (the rustup shim) and `rustup which`'s path ({abs}) name one \
compiler and must canonicalise to one identity; got {bare:?} vs {abs_id:?}"
);
let probed = MirOptions {
probed_with: Some(canonical_compiler(&abs)),
..MirOptions::default()
};
assert!(
check_probe_compiler("rustc", &probed).is_ok(),
"a bare name naming the probed compiler must not be refused"
);
}
#[test]
fn two_toolchains_are_two_identities() {
let (Some((a_path, a)), Some((b_path, b))) = (have("stable"), have("1.85")) else {
eprintln!("skipped: stable and 1.85 must both be installed to compare them");
return;
};
assert_ne!(
a, b,
"stable ({a_path}) and 1.85 ({b_path}) are different builds and must not \
share an identity"
);
}
}