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 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 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))
}
#[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> {
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);
}
}