use std::collections::{BTreeMap, BTreeSet};
use crate::mir::parse::{split_top_level, Const, Ty, USIZE_WIDTH};
use crate::smt::{self, Pred, Var};
pub const MAX_INDEX_CHAIN: u64 = 64;
#[derive(Clone, Copy, Debug)]
pub enum IndexBound {
Const(u64),
Len(Var),
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FnContract {
pub requires: Vec<String>,
pub ensures: Vec<String>,
pub invariants: Vec<String>,
pub decreases: Vec<String>,
pub variant: Option<String>,
pub unwind: Option<u32>,
pub unknown: Vec<(usize, String)>,
pub line: usize,
pub params: Vec<(String, Ty)>,
pub ret: Option<Ty>,
pub slots: Option<Vec<ParamSlot>>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ParamSlot {
Receiver,
Named(String),
}
#[derive(Clone, Debug, Default)]
pub struct Specs {
pub by_fn: BTreeMap<String, FnContract>,
pub structs: BTreeMap<String, StructDef>,
pub enums: BTreeMap<String, EnumDef>,
pub crate_consts: BTreeSet<String>,
pub const_generics: BTreeSet<String>,
pub impl_owners: BTreeMap<(usize, usize), String>,
pub impl_traits: BTreeMap<(usize, usize), String>,
pub impl_trait_args: BTreeMap<(usize, usize), String>,
pub declared_traits: BTreeSet<String>,
pub by_method: BTreeMap<(usize, usize, String), FnContract>,
pub by_trait: BTreeMap<String, FnContract>,
pub bodyless: BTreeSet<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct EnumDef {
pub variants: Vec<(String, Vec<Ty>, u64)>,
}
impl EnumDef {
pub fn index_of(&self, name: &str) -> Option<u64> {
self.variants.iter().find(|(n, _, _)| n == name).map(|(_, _, d)| *d)
}
pub fn tag_width(&self) -> u8 {
let max = self.variants.iter().map(|(_, _, d)| *d).max().unwrap_or(0);
(64 - max.leading_zeros()).max(1) as u8
}
pub fn tag_bound(&self, tag: Var) -> Pred {
let mut acc: Option<Pred> = None;
for (_, _, d) in &self.variants {
let p = smt::eq_const(tag, *d);
acc = Some(match acc {
None => p,
Some(prev) => smt::or(prev, p),
});
}
acc.unwrap_or_else(|| smt::truth(false))
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct StructDef {
pub fields: Vec<(String, Ty)>,
}
impl StructDef {
pub fn index_of(&self, name: &str) -> Option<u32> {
self.fields.iter().position(|(n, _)| n == name).map(|i| i as u32)
}
}
impl Specs {
pub fn get(&self, name: &str) -> Option<&FnContract> {
self.by_fn.get(name)
}
pub fn resolve(&self, name: &str) -> Option<&FnContract> {
if let Some(c) = self.by_fn.get(name) {
return Some(c);
}
if let Some(loc) = impl_location(name) {
let tail = name.rsplit("::").next()?;
if let Some(c) = self.by_method.get(&(loc.0, loc.1, tail.to_string())) {
return Some(c);
}
return self.trait_contract(loc.0, loc.1, tail);
}
let mut hit: Option<&FnContract> = None;
let mut count = 0usize;
for (key, c) in &self.by_fn {
if is_path_suffix(key, name) {
hit = Some(c);
count += 1;
}
}
if count == 1 {
hit
} else {
None
}
}
pub fn struct_of(&self, name: &str) -> Option<&StructDef> {
struct_lookup(&self.structs, name)
}
pub fn contract_conflict(&self, name: &str) -> Option<String> {
let loc = impl_location(name)?;
let tail = name.rsplit("::").next()?;
if !self.by_method.contains_key(&(loc.0, loc.1, tail.to_string())) {
return None;
}
let tr = self.impl_traits.get(&(loc.0, loc.1))?;
if !self.by_trait.contains_key(&format!("{tr}::{tail}")) {
return None;
}
Some(format!(
"the implementation of `{tail}` declares its own contract and the trait `{tr}` declares one for the same method, so the two would have to agree; the frontend checks one specification per function and refuses rather than dropping either"
))
}
pub fn trait_contract(&self, line: usize, col: usize, tail: &str) -> Option<&FnContract> {
let tr = self.impl_traits.get(&(line, col))?;
self.by_trait.get(&format!("{tr}::{tail}"))
}
pub fn contract_for_fn<'a>(
&'a self,
f: &crate::mir::parse::MirFn,
) -> Result<(Option<&'a FnContract>, Option<ArgRename>), String> {
let Some(loc) = impl_location(&f.name) else {
return Ok((self.resolve(&f.name), None));
};
let Some(tail) = f.name.rsplit("::").next() else {
return Ok((self.resolve(&f.name), None));
};
if let Some(c) = self.by_method.get(&(loc.0, loc.1, tail.to_string())) {
return Ok((Some(c), None));
}
let Some(decl) = self.trait_contract(loc.0, loc.1, tail) else {
return Ok((None, None));
};
let Some(tr) = self.impl_traits.get(&(loc.0, loc.1)) else {
return Ok((Some(decl), None));
};
let rename = self.align_signature(decl, f, tr, tail)?;
Ok((Some(decl), rename))
}
fn align_signature(
&self,
decl: &FnContract,
f: &crate::mir::parse::MirFn,
tr: &str,
tail: &str,
) -> Result<Option<ArgRename>, String> {
let Some(slots) = decl.slots.as_ref() else {
return Err(format!(
"the trait `{tr}` declares a contract for `{tail}`, but its signature could not be read, so the contract's parameters cannot be aligned with the implementation's by position"
));
};
if slots.len() != f.arg_locals.len() {
return Err(format!(
"the trait `{tr}` declares {} parameter slot(s) for `{tail}`, but the implementation has {} argument local(s), so the contract cannot be aligned with the body by position",
slots.len(),
f.arg_locals.len()
));
}
let mut map = BTreeMap::new();
for (slot, &local) in slots.iter().zip(&f.arg_locals) {
if let ParamSlot::Named(name) = slot {
map.insert(local, name.clone());
}
}
Ok(Some(ArgRename(map)))
}
}
pub(crate) fn impl_location(name: &str) -> Option<(usize, usize)> {
let start = name.find("<impl at ")? + "<impl at ".len();
let inner = name[start..].split('>').next()?;
let (head, _end) = inner.rsplit_once(": ")?;
let mut parts = head.rsplit(':');
let col = parts.next()?;
let line = parts.next()?;
Some((line.trim().parse().ok()?, col.trim().parse().ok()?))
}
pub fn const_generic_params(source: &str) -> BTreeSet<String> {
let mut out = BTreeSet::new();
let bytes = source.as_bytes();
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'/') {
while i < bytes.len() && bytes[i] != b'\n' {
i += 1;
}
continue;
}
if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'*') {
i += 2;
while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
i += 1;
}
i += 2;
continue;
}
if bytes[i] == b'"' {
i += 1;
while i < bytes.len() && bytes[i] != b'"' {
if bytes[i] == b'\\' {
i += 1;
}
i += 1;
}
i += 1;
continue;
}
if bytes[i..].starts_with(b"const")
&& !bytes.get(i + 5).is_some_and(|c| c.is_ascii_alphanumeric() || *c == b'_')
{
let before = source[..i].trim_end().as_bytes().last().copied();
if matches!(before, Some(b'<') | Some(b',')) {
let mut j = i + "const".len();
loop {
while j < bytes.len() && bytes[j].is_ascii_whitespace() {
j += 1;
}
if bytes.get(j) == Some(&b'/') && bytes.get(j + 1) == Some(&b'/') {
while j < bytes.len() && bytes[j] != b'\n' {
j += 1;
}
continue;
}
if bytes.get(j) == Some(&b'/') && bytes.get(j + 1) == Some(&b'*') {
j += 2;
while j + 1 < bytes.len() && !(bytes[j] == b'*' && bytes[j + 1] == b'/') {
j += 1;
}
j = (j + 2).min(bytes.len());
continue;
}
break;
}
let after = &source[j..];
let name: String = after
.chars()
.take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
.collect();
let plain =
name.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_');
if plain && after[name.len()..].trim_start().starts_with(':') {
out.insert(name);
}
}
i += "const".len();
continue;
}
i += 1;
}
out
}
pub fn crate_level_consts(source: &str) -> BTreeSet<String> {
let mut out = BTreeSet::new();
let mut depth: i32 = 0;
let mut in_block_comment = false;
let mut prev_last: Option<u8> = None;
for raw in source.lines() {
let mut line = raw;
loop {
if in_block_comment {
match line.find("*/") {
Some(i) => {
in_block_comment = false;
line = &line[i + 2..];
}
None => line = "",
}
} else if let Some(i) = line.find("/*") {
in_block_comment = true;
line = &line[i + 2..];
} else {
break;
}
}
if depth == 0 {
let t = line.trim_start();
let t = t.strip_prefix("pub(crate) ").or_else(|| t.strip_prefix("pub ")).unwrap_or(t);
if let Some(after) = t.strip_prefix("const ") {
let preceded = line[..line.len() - t.len()].trim_end().as_bytes().last().copied();
let before = preceded.or(prev_last);
let name: String = after
.chars()
.take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
.collect();
let plain =
name.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_');
if plain
&& !matches!(before, Some(b'<') | Some(b','))
&& after[name.len()..].trim_start().starts_with(':')
{
out.insert(name);
}
}
}
let bytes = line.as_bytes();
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'/' if bytes.get(i + 1) == Some(&b'/') => break,
b'"' => {
i += 1;
while i < bytes.len() && bytes[i] != b'"' {
if bytes[i] == b'\\' {
i += 1;
}
i += 1;
}
}
b'\'' => {
i += 1;
while i < bytes.len() && bytes[i] != b'\'' {
if bytes[i] == b'\\' {
i += 1;
}
i += 1;
}
}
b'{' => depth += 1,
b'}' => depth -= 1,
_ => {}
}
i += 1;
}
if let Some(c) = line.trim_end().as_bytes().last() {
prev_last = Some(*c);
}
}
out
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct LineScope {
pub impl_loc: Option<(usize, usize)>,
pub trait_path: Vec<String>,
pub path: Vec<String>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum ItemKind {
Impl,
Mod,
Trait,
Fn,
}
struct ScopeFrame {
kind: ItemKind,
name: String,
impl_loc: Option<(usize, usize)>,
body_depth: Option<i32>,
}
pub(crate) fn line_scopes(source: &str) -> Vec<LineScope> {
let lines: Vec<&str> = source.lines().collect();
let mut out: Vec<LineScope> = vec![LineScope::default(); lines.len()];
let mut stack: Vec<ScopeFrame> = Vec::new();
let mut depth: i32 = 0;
let mut in_block_comment = false;
for (idx, raw) in lines.iter().enumerate() {
let mut line = *raw;
loop {
if in_block_comment {
match line.find("*/") {
Some(i) => {
in_block_comment = false;
line = &line[i + 2..];
}
None => line = "",
}
} else if let Some(i) = line.find("/*") {
in_block_comment = true;
line = &line[i + 2..];
} else {
break;
}
}
let impl_loc =
stack.iter().rev().find(|f| f.kind == ItemKind::Impl).and_then(|f| f.impl_loc);
let path: Vec<String> = stack
.iter()
.filter(|f| matches!(f.kind, ItemKind::Mod | ItemKind::Trait | ItemKind::Fn))
.map(|f| f.name.clone())
.collect();
let trait_path: Vec<String> = stack
.iter()
.filter(|f| f.kind == ItemKind::Trait)
.map(|f| f.name.clone())
.collect();
out[idx] = LineScope { impl_loc, path, trait_path };
if let Some(col) = impl_keyword_col(raw) {
stack.push(ScopeFrame {
kind: ItemKind::Impl,
name: String::new(),
impl_loc: Some((idx + 1, col)),
body_depth: None,
});
} else if let Some((kind, name)) = item_head(raw) {
stack.push(ScopeFrame {
kind,
name,
impl_loc: None,
body_depth: None,
});
}
let bytes = line.as_bytes();
let mut body_open_depth: Option<i32> = None;
let mut body_seen = false;
let mut angle = 0i32;
let mut angle_depth: Option<i32> = None;
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'/' if bytes.get(i + 1) == Some(&b'/') => break,
b'"' => {
i += 1;
while i < bytes.len() && bytes[i] != b'"' {
if bytes[i] == b'\\' {
i += 1;
}
i += 1;
}
}
b'\'' => {
let lifetime = matches!(bytes.get(i + 1), Some(c) if c.is_ascii_alphabetic() || *c == b'_')
&& bytes.get(i + 2) != Some(&b'\'');
if !lifetime {
i += 1;
while i < bytes.len() && bytes[i] != b'\'' {
if bytes[i] == b'\\' {
i += 1;
}
i += 1;
}
}
}
b'{' if body_seen || angle == 0 => {
if !body_seen {
body_seen = true;
body_open_depth = Some(depth + 1);
}
depth += 1;
}
b'{' => depth += 1,
b'}' => depth -= 1,
b'<' if !body_seen && angle == 0 => {
angle = 1;
angle_depth = Some(depth);
}
b'<' if !body_seen && angle_depth == Some(depth) => angle += 1,
b'>' if !body_seen && angle > 0 && angle_depth == Some(depth) => angle -= 1,
_ => {}
}
i += 1;
}
if let Some(last) = stack.last_mut() {
if last.body_depth.is_none() {
if let Some(d) = body_open_depth {
last.body_depth = Some(d);
}
}
}
if let Some(last) = stack.last() {
if last.body_depth.is_none() && line.trim_end().ends_with(';') {
stack.pop();
}
}
while let Some(f) = stack.last() {
if let Some(d) = f.body_depth {
if depth < d {
stack.pop();
} else {
break;
}
} else {
break;
}
}
}
out
}
fn item_head(raw: &str) -> Option<(ItemKind, String)> {
let mut rest = raw.trim_start();
loop {
let t = rest.trim_start();
let mut advanced = false;
for p in [
"pub(crate)",
"pub(self)",
"pub(super)",
"pub",
"unsafe",
"async",
"const",
"default",
"extern",
] {
if let Some(r) = t.strip_prefix(p) {
if r.starts_with(|c: char| c.is_whitespace()) {
rest = r;
advanced = true;
break;
}
}
}
if !advanced {
rest = t;
break;
}
}
if let Some(after) = rest.strip_prefix('"') {
if let Some(end) = after.find('"') {
rest = after[end + 1..].trim_start();
}
}
let (kw, kind) = if let Some(r) = rest.strip_prefix("mod ") {
(r, ItemKind::Mod)
} else if let Some(r) = rest.strip_prefix("trait ") {
(r, ItemKind::Trait)
} else if rest.starts_with("fn ") {
return Some((ItemKind::Fn, fn_name(raw)?));
} else {
return None;
};
let name: String = kw.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
if name.is_empty() {
None
} else {
Some((kind, name))
}
}
pub(crate) fn is_path_suffix(path: &str, suffix: &str) -> bool {
if suffix.is_empty() || path.len() <= suffix.len() {
return false;
}
if !path.ends_with(suffix) {
return false;
}
path.as_bytes()[path.len() - suffix.len() - 1] == b':'
}
fn impl_keyword_col(raw: &str) -> Option<usize> {
let trimmed = raw.trim_start();
let offset = raw.len() - trimmed.len();
let (rest, col0) = match trimmed.strip_prefix("unsafe ") {
Some(r) => (r, offset + "unsafe ".len()),
None => (trimmed, offset),
};
let rest = rest.strip_prefix("impl")?;
if rest.chars().next().is_some_and(|c| c.is_ascii_alphanumeric() || c == '_') {
return None;
}
Some(raw[..col0].chars().count() + 1)
}
pub(crate) fn impl_owner(header: &str) -> Option<String> {
let after = header.trim_start().strip_prefix("unsafe ").unwrap_or(header.trim_start());
let rest = after.strip_prefix("impl")?;
let rest = rest.trim_start();
let rest = if let Some(r) = rest.strip_prefix('<') {
let mut depth = 1usize;
let mut end = 0usize;
for (i, c) in r.char_indices() {
match c {
'<' => depth += 1,
'>' => {
depth -= 1;
if depth == 0 {
end = i + 1;
break;
}
}
_ => {}
}
}
&r[end..]
} else {
rest
};
let (before, after_for) = match rest.split_once(" for ") {
Some((b, a)) => (b, Some(a)),
None => (rest, None),
};
let source = after_for.unwrap_or(before);
let name: String = source
.trim_start()
.chars()
.take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
.collect();
if name.is_empty() {
None
} else {
Some(name)
}
}
pub(crate) fn angle_inner(s: &str) -> Option<&str> {
let open = s.find('<')?;
let mut depth = 0usize;
for (i, c) in s[open..].char_indices() {
match c {
'<' => depth += 1,
'>' => {
depth -= 1;
if depth == 0 {
return Some(s[open + 1..open + i].trim());
}
}
_ => {}
}
}
None
}
fn impl_trait_clause(header: &str) -> Option<&str> {
let after = header.trim_start().strip_prefix("unsafe ").unwrap_or(header.trim_start());
let rest = after.strip_prefix("impl")?;
let rest = rest.trim_start();
let rest = if let Some(r) = rest.strip_prefix('<') {
let mut depth = 1usize;
let mut end = 0usize;
for (i, c) in r.char_indices() {
match c {
'<' => depth += 1,
'>' => {
depth -= 1;
if depth == 0 {
end = i + 1;
break;
}
}
_ => {}
}
}
&r[end..]
} else {
rest
};
let (before, _) = rest.split_once(" for ")?;
Some(before)
}
pub(crate) fn impl_trait(header: &str) -> Option<String> {
let before = impl_trait_clause(header)?;
let path: String = before
.trim_start()
.chars()
.take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == ':')
.collect();
let path = path.trim_end_matches(':').to_string();
if path.is_empty() {
None
} else {
Some(path)
}
}
pub(crate) fn impl_trait_args(header: &str) -> Option<String> {
let before = impl_trait_clause(header)?;
let inner = angle_inner(before)?;
(!inner.is_empty()).then(|| inner.to_string())
}
fn is_absolute_trait_path(path: &str) -> bool {
let first = path.split("::").next().unwrap_or(path);
matches!(first, "std" | "core" | "alloc" | "crate" | "self" | "super")
}
pub(crate) fn declared_traits(scopes: &[LineScope], lines: &[&str]) -> BTreeSet<String> {
let mut out = BTreeSet::new();
for (idx, raw) in lines.iter().enumerate() {
let Some((ItemKind::Trait, name)) = item_head(raw) else {
continue;
};
let qualified = if scopes[idx].path.is_empty() {
name
} else {
format!("{}::{}", scopes[idx].path.join("::"), name)
};
out.insert(qualified);
}
out
}
fn qualify_trait(
written: &str,
scope: &[String],
imports: &BTreeMap<String, String>,
) -> String {
if let Some(normalized) = resolve_relative_trait_path(written, scope) {
return normalized;
}
if is_absolute_trait_path(written) {
return written.to_string();
}
let first = written.split("::").next().unwrap_or(written);
if let Some(full) = imports.get(first) {
return format!("{full}{}", &written[first.len()..]);
}
if scope.is_empty() {
written.to_string()
} else {
format!("{}::{}", scope.join("::"), written)
}
}
fn resolve_relative_trait_path(written: &str, scope: &[String]) -> Option<String> {
let mut segments: Vec<&str> = written.split("::").collect();
let mut base: Vec<String> = scope.to_vec();
let mut saw_root = false;
while let Some(first) = segments.first().copied() {
match first {
"crate" => {
base.clear();
segments.remove(0);
saw_root = true;
}
"self" => {
segments.remove(0);
saw_root = true;
}
"super" => {
base.pop()?;
segments.remove(0);
saw_root = true;
}
_ => break,
}
}
if !saw_root {
return None;
}
if segments.is_empty() {
return None;
}
base.extend(segments.into_iter().map(|s| s.to_string()));
Some(base.join("::"))
}
fn impl_header(lines: &[&str], start: usize) -> String {
let mut out = String::new();
let mut angle = 0i32;
let mut seen_angle = false;
for raw in &lines[start..] {
let mut line = *raw;
if let Some(i) = line.find("//") {
line = &line[..i];
}
let mut cut = line.len();
for (i, c) in line.char_indices() {
match c {
'<' if !seen_angle => {
angle += 1;
seen_angle = true;
}
'<' if angle > 0 => angle += 1,
'>' if angle > 0 => angle -= 1,
'{' if angle == 0 => {
cut = i;
break;
}
';' if angle == 0 => {
cut = i;
break;
}
_ => {}
}
}
out.push_str(&line[..cut]);
if cut < line.len() {
break;
}
out.push(' ');
}
out
}
fn module_imports(scopes: &[LineScope], lines: &[&str]) -> Vec<BTreeMap<String, String>> {
let mut per_module: BTreeMap<Vec<String>, BTreeMap<String, (String, bool)>> = BTreeMap::new();
let mut i = 0;
while i < lines.len() {
if !is_use_start(lines[i]) {
i += 1;
continue;
}
let conditional = is_cfg_use(lines, i);
let mut item = String::new();
let mut j = i;
loop {
item.push_str(lines[j]);
item.push(' ');
if lines[j].contains(';') || j + 1 >= lines.len() {
break;
}
j += 1;
}
let map = per_module.entry(scopes[i].path.clone()).or_default();
for (short, full) in parse_use(&item) {
let live_unconditional = map.get(&short).is_some_and(|(_, unconditional)| *unconditional);
if conditional && live_unconditional {
continue;
}
map.insert(short, (full, !conditional));
}
i = j + 1;
}
lines
.iter()
.enumerate()
.map(|(idx, _)| {
per_module
.get(&scopes[idx].path)
.map(|m| m.iter().map(|(k, (v, _))| (k.clone(), v.clone())).collect())
.unwrap_or_default()
})
.collect()
}
fn is_cfg_use(lines: &[&str], i: usize) -> bool {
if split_leading_attrs(lines[i]).1 {
return true;
}
attrs_above_have_cfg(lines, i)
}
fn attrs_above_have_cfg(lines: &[&str], end: usize) -> bool {
let mut top = end;
while top > 0 && !lines[top - 1].trim().is_empty() {
top -= 1;
}
(top..end).any(|start| read_attr_run(lines, start, end) == Some(true))
}
fn raw_string_start(bytes: &[u8], i: usize) -> Option<(usize, usize)> {
let mut j = i;
if matches!(bytes.get(j), Some(b'b') | Some(b'c')) {
j += 1;
}
if bytes.get(j) != Some(&b'r') {
return None;
}
j += 1;
let mut hashes = 0;
while bytes.get(j) == Some(&b'#') {
hashes += 1;
j += 1;
}
if bytes.get(j) != Some(&b'"') {
return None;
}
Some((hashes, j + 1))
}
fn is_char_literal_start_bytes(bytes: &[u8], i: usize) -> bool {
match bytes.get(i + 1) {
Some(b'\\') => true,
Some(_) => bytes.get(i + 2) == Some(&b'\''),
None => false,
}
}
fn skip_string(bytes: &[u8], i: usize) -> usize {
let mut j = i + 1;
while j < bytes.len() {
match bytes[j] {
b'\\' => j += 2,
b'"' => return j + 1,
_ => j += 1,
}
}
bytes.len()
}
fn skip_char(bytes: &[u8], i: usize) -> usize {
let mut j = i + 1;
if bytes.get(j) == Some(&b'\\') {
j += 1;
}
j += 1;
if bytes.get(j) == Some(&b'\'') {
j + 1
} else {
j
}
}
fn skip_raw_string(bytes: &[u8], after_quote: usize, hashes: usize) -> usize {
let mut j = after_quote;
while j < bytes.len() {
if bytes[j] == b'"' {
let mut h = 0;
let mut k = j + 1;
while h < hashes && bytes.get(k) == Some(&b'#') {
h += 1;
k += 1;
}
if h == hashes {
return k;
}
}
j += 1;
}
bytes.len()
}
fn attr_close_offset(text: &str, open: usize) -> Option<usize> {
let bytes = text.as_bytes();
let mut depth = 1i32;
let mut i = open + 1;
while i < bytes.len() {
match bytes[i] {
b'/' if bytes.get(i + 1) == Some(&b'/') => {
while i < bytes.len() && bytes[i] != b'\n' {
i += 1;
}
}
b'/' if bytes.get(i + 1) == Some(&b'*') => {
let mut d = 1u32;
i += 2;
while i < bytes.len() && d > 0 {
if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'*') {
d += 1;
i += 2;
} else if bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/') {
d -= 1;
i += 2;
} else {
i += 1;
}
}
}
b'"' => i = skip_string(bytes, i),
b'\'' if is_char_literal_start_bytes(bytes, i) => i = skip_char(bytes, i),
b'r' | b'b' | b'c' => match raw_string_start(bytes, i) {
Some((hashes, after)) => i = skip_raw_string(bytes, after, hashes),
None => i += 1,
},
b'[' | b'(' => {
depth += 1;
i += 1;
}
b']' | b')' => {
depth -= 1;
if depth == 0 {
return Some(i + 1);
}
i += 1;
}
_ => i += 1,
}
}
None
}
fn read_attr_run(lines: &[&str], start: usize, end: usize) -> Option<bool> {
let mut cfg = false;
let mut k = start;
while k < end {
let trimmed = lines[k].trim_start();
let head = trimmed.strip_prefix("#[")?;
let lead = lines[k].len() - trimmed.len();
let flat = lines[k..end].join("\n");
let close = attr_close_offset(&flat, lead + 1)?;
let spanned = flat[..close].matches('\n').count();
if head.starts_with("cfg") {
cfg = true;
}
k += spanned + 1;
}
Some(cfg)
}
fn split_leading_attrs(line: &str) -> (&str, bool) {
let mut rest = line.trim_start();
let mut cfg = false;
while let Some(after) = rest.strip_prefix("#[") {
if after.starts_with("cfg") {
cfg = true;
}
match attr_close_offset(rest, 1) {
Some(e) => rest = after[e - 2..].trim_start(),
None => break,
}
}
(rest, cfg)
}
fn strip_visibility(line: &str) -> &str {
let s = split_leading_attrs(line).0;
let Some(rest) = s.strip_prefix("pub") else {
return s;
};
match rest.chars().next() {
None => rest,
Some(c) if c.is_whitespace() => rest.trim_start(),
Some('(') => match rest.find(')') {
Some(close) => rest[close + 1..].trim_start(),
None => rest,
},
Some(_) => s,
}
}
fn is_use_start(line: &str) -> bool {
strip_visibility(line).starts_with("use ")
|| strip_visibility(line).trim_end() == "use"
}
fn parse_use(raw: &str) -> Vec<(String, String)> {
let after_vis = strip_visibility(raw);
let rest = match after_vis.strip_prefix("use ") {
Some(r) => r,
None => return Vec::new(),
};
let rest = match rest.find(';') {
Some(i) => &rest[..i],
None => rest,
};
let rest = match rest.find("//") {
Some(i) => &rest[..i],
None => rest,
};
let rest = rest.trim();
if let Some((prefix, group)) = rest.split_once("::{") {
let group = group.strip_suffix('}').unwrap_or(group);
let mut out = Vec::new();
for item in group.split(',') {
let item = item.trim();
if item.is_empty() || item.contains('*') {
continue;
}
let (path, alias) = match item.split_once(" as ") {
Some((p, a)) => (p.trim(), a.trim()),
None => (item, ""),
};
let full = format!("{}::{}", prefix, path);
let short = if alias.is_empty() {
path.rsplit("::").next().unwrap_or(path).to_string()
} else {
alias.to_string()
};
out.push((short, full));
}
return out;
}
if rest.contains('*') {
return Vec::new();
}
let (path, alias) = match rest.split_once(" as ") {
Some((p, a)) => (p.trim(), a.trim()),
None => (rest, ""),
};
let short = if alias.is_empty() {
path.rsplit("::").next().unwrap_or(path).to_string()
} else {
alias.to_string()
};
if short.is_empty() {
Vec::new()
} else {
vec![(short, path.to_string())]
}
}
pub fn extract(source: &str) -> Specs {
let mut specs = Specs::default();
let mut pending = FnContract::default();
let mut in_block_comment = false;
specs.crate_consts = crate_level_consts(source);
specs.const_generics = const_generic_params(source);
let scopes = line_scopes(source);
let enclosing: Vec<Option<(usize, usize)>> =
scopes.iter().map(|s| s.impl_loc).collect();
let scope_path: Vec<Vec<String>> = scopes.iter().map(|s| s.path.clone()).collect();
let lines: Vec<&str> = source.lines().collect();
let imports = module_imports(&scopes, &lines);
for (idx, raw) in lines.iter().enumerate() {
if let Some(col) = impl_keyword_col(raw) {
let header = impl_header(&lines, idx);
if let Some(owner) = impl_owner(&header) {
specs.impl_owners.insert((idx + 1, col), owner);
}
if let Some(tr) = impl_trait(&header) {
let qualified = qualify_trait(&tr, &scope_path[idx], &imports[idx]);
specs.impl_traits.insert((idx + 1, col), qualified);
}
if let Some(args) = impl_trait_args(&header) {
specs.impl_trait_args.insert((idx + 1, col), args);
}
}
}
specs.declared_traits = declared_traits(&scopes, &lines);
let mut cur_struct: Option<(String, StructDef)> = None;
let mut cur_enum: Option<(String, EnumDef)> = None;
let mut struct_paths: BTreeMap<String, String> = BTreeMap::new();
let mut struct_name_counts: BTreeMap<String, u32> = BTreeMap::new();
for (lineno, raw_line) in source.lines().enumerate() {
let line = raw_line.trim();
if in_block_comment {
if line.contains("*/") {
in_block_comment = false;
}
continue;
}
if line.starts_with("/*") {
if !line.contains("*/") {
in_block_comment = true;
}
continue;
}
if cur_enum.is_some() {
if line.starts_with('}') {
let (name, def) = cur_enum.take().unwrap();
specs.enums.insert(name, def);
continue;
}
match enum_variant(line) {
VariantLine::Variant { name: vname, payload, explicit } => {
if let Some((_, def)) = cur_enum.as_mut() {
push_variant(def, vname, payload, explicit);
}
}
VariantLine::NotAVariant => {}
VariantLine::UnreadableDiscriminant => {
cur_enum = None;
}
}
continue;
}
if cur_struct.is_some() {
if line.starts_with('}') {
let (name, def) = cur_struct.take().unwrap();
specs.structs.insert(name, def);
continue;
}
if let Some((fname, fty)) = struct_field(line) {
if let Some((_, def)) = cur_struct.as_mut() {
def.fields.push((fname, Ty::parse(&fty)));
}
}
continue;
}
if let Some(head) = struct_head(line) {
pending = FnContract::default();
let scope = scope_path.get(lineno).cloned().unwrap_or_default();
let key_of = |name: &str| -> String {
if scope.is_empty() {
name.to_string()
} else {
let mut p = scope.clone();
p.push(name.to_string());
p.join("::")
}
};
match head {
StructHead::Tuple { name, fields } => {
let mut def = StructDef::default();
for (fname, fty) in fields {
def.fields.push((fname, Ty::parse(&fty)));
}
let key = key_of(&name);
*struct_name_counts.entry(name.clone()).or_insert(0) += 1;
if key != name {
struct_paths.insert(name, key.clone());
}
specs.structs.insert(key, def);
}
StructHead::Unit { name } => {
let key = key_of(&name);
*struct_name_counts.entry(name.clone()).or_insert(0) += 1;
if key != name {
struct_paths.insert(name, key.clone());
}
specs.structs.insert(key, StructDef::default());
}
StructHead::Named { name, closed_inline } => {
if closed_inline {
let t =
line.trim_start_matches("pub(crate) ").trim_start_matches("pub ").trim();
let mut def = StructDef::default();
if let Some(open) = t.find('{') {
if let Some(close) = t[open + 1..].rfind('}') {
for f in split_top_level(&t[open + 1..open + 1 + close], ',') {
if let Some((fname, fty)) = struct_field(&f) {
def.fields.push((fname, Ty::parse(&fty)));
}
}
}
}
let key = key_of(&name);
*struct_name_counts.entry(name.clone()).or_insert(0) += 1;
if key != name {
struct_paths.insert(name, key.clone());
}
specs.structs.insert(key, def);
} else {
let key = key_of(&name);
*struct_name_counts.entry(name.clone()).or_insert(0) += 1;
if key != name {
struct_paths.insert(name, key.clone());
}
cur_struct = Some((key, StructDef::default()));
}
}
}
continue;
}
if let Some((name, head)) = enum_head(line) {
pending = FnContract::default();
match head {
EnumHead::Inline(variants) => {
specs.enums.insert(name, EnumDef { variants });
}
EnumHead::MultiLine => cur_enum = Some((name, EnumDef::default())),
EnumHead::Refused => {}
}
continue;
}
if line.starts_with("//!") || line.starts_with("//") && !line.starts_with("///") {
continue;
}
if let Some(rest) = line.strip_prefix("///") {
let t = rest.trim();
if let Some(r) = t.strip_prefix("requires:") {
pending.requires.push(r.trim().to_string());
} else if let Some(r) = t.strip_prefix("ensures:") {
pending.ensures.push(r.trim().to_string());
} else if let Some(r) = t.strip_prefix("invariant:") {
pending.invariants.push(r.trim().to_string());
} else if let Some(r) = t.strip_prefix("decreases:") {
pending.decreases.push(r.trim().to_string());
} else if let Some(r) = t.strip_prefix("variant:") {
if pending.variant.is_some() {
pending.unknown.push((
lineno + 1,
format!("{t} — a second `variant:`; the first is the measure"),
));
} else {
pending.variant = Some(r.trim().to_string());
}
} else if let Some(r) = t.strip_prefix("unwind:") {
match r.trim().parse::<u32>() {
Ok(n) if n > 0 => pending.unwind = Some(n),
_ => pending.unknown.push((
lineno + 1,
format!("{t} — `unwind:` needs a positive integer"),
)),
}
} else if let Some(note) = clause_shaped_word(t) {
pending.unknown.push((lineno + 1, format!("{t} — {note}")));
}
continue;
}
if let Some(name) = fn_name(line) {
if !pending.requires.is_empty()
|| !pending.ensures.is_empty()
|| !pending.invariants.is_empty()
|| !pending.decreases.is_empty()
|| pending.variant.is_some()
|| pending.unwind.is_some()
|| !pending.unknown.is_empty()
{
pending.line = lineno + 1;
let (params, ret, slots) = fn_signature_full(line);
pending.params = params;
pending.ret = ret;
pending.slots = slots;
match enclosing.get(lineno).copied().flatten() {
Some(loc) => {
specs.by_method.insert((loc.0, loc.1, name), std::mem::take(&mut pending));
}
None => {
let mut path = scope_path.get(lineno).cloned().unwrap_or_default();
path.push(name);
let key = path.join("::");
let in_trait = !scopes[lineno].trait_path.is_empty();
if in_trait && !fn_has_body(&lines, lineno) {
specs.by_trait.insert(key, std::mem::take(&mut pending));
} else {
if !fn_has_body(&lines, lineno) {
specs.bodyless.insert(key.clone());
}
specs.by_fn.insert(key, std::mem::take(&mut pending));
}
}
}
}
pending = FnContract::default();
continue;
}
if !line.is_empty() && !line.starts_with('#') {
pending = FnContract::default();
}
}
for (bare, count) in &struct_name_counts {
if *count != 1 {
continue;
}
if specs.structs.contains_key(bare) {
continue;
}
if let Some(qualified) = struct_paths.get(bare) {
if let Some(def) = specs.structs.get(qualified).cloned() {
specs.structs.insert(bare.clone(), def);
}
}
}
specs
}
fn clause_shaped_word(t: &str) -> Option<String> {
const KEYWORDS: [&str; 6] =
["requires", "ensures", "invariant", "decreases", "variant", "unwind"];
let word = t.split(':').next()?.trim();
if word.is_empty() || !word.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
return None;
}
KEYWORDS
.into_iter()
.filter(|k| edit_distance_at_most_two(word, k))
.min_by_key(|k| edit_distance(word, k))
.map(|k| format!("did you mean `{k}:`?"))
}
fn edit_distance_at_most_two(a: &str, b: &str) -> bool {
edit_distance(a, b) <= 2
}
fn edit_distance(a: &str, b: &str) -> usize {
let a: Vec<char> = a.chars().collect();
let b: Vec<char> = b.chars().collect();
if a.len().abs_diff(b.len()) > 2 {
return 3;
}
let mut prev: Vec<usize> = (0..=b.len()).collect();
let mut cur = vec![0usize; b.len() + 1];
for (i, ca) in a.iter().enumerate() {
cur[0] = i + 1;
for (j, cb) in b.iter().enumerate() {
let sub = prev[j] + usize::from(ca != cb);
cur[j + 1] = sub.min(prev[j + 1] + 1).min(cur[j] + 1);
}
std::mem::swap(&mut prev, &mut cur);
}
prev[b.len()]
}
fn fn_has_body(lines: &[&str], start: usize) -> bool {
let mut angle = 0i32;
let mut round = 0i32;
let mut square = 0i32;
let mut seen_angle = false;
for raw in &lines[start..] {
let mut line = *raw;
if let Some(i) = line.find("//") {
line = &line[..i];
}
for c in line.chars() {
match c {
'<' if !seen_angle => {
angle += 1;
seen_angle = true;
}
'<' if angle > 0 => angle += 1,
'>' if angle > 0 => angle -= 1,
'(' => round += 1,
')' => round -= 1,
'[' => square += 1,
']' => square -= 1,
'{' if angle == 0 && round <= 0 && square <= 0 => return true,
';' if angle == 0 && round <= 0 && square <= 0 => return false,
_ => {}
}
}
}
false
}
#[cfg(test)]
fn fn_signature(line: &str) -> (Vec<(String, Ty)>, Option<Ty>) {
let (params, ret, _) = fn_signature_full(line);
(params, ret)
}
type SourceSignature = (Vec<(String, Ty)>, Option<Ty>, Option<Vec<ParamSlot>>);
fn fn_signature_full(line: &str) -> SourceSignature {
let Some(open) = line.find('(') else {
return (Vec::new(), None, None);
};
let mut depth = 0usize;
let mut close = None;
for (i, ch) in line[open..].char_indices() {
match ch {
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
close = Some(open + i);
break;
}
}
_ => {}
}
}
let Some(close) = close else {
return (Vec::new(), None, None);
};
let mut params = Vec::new();
let mut slots = Vec::new();
let list = line[open + 1..close].trim();
if !list.is_empty() {
for part in split_top_level(list, ',') {
let part = part.trim();
if part.is_empty() {
continue;
}
if is_receiver(part) {
slots.push(ParamSlot::Receiver);
continue;
}
let Some(colon) = part.find(':') else {
return (Vec::new(), None, None);
};
let before = part[..colon].trim();
let name = before
.strip_prefix("mut ")
.unwrap_or(before)
.trim()
.to_string();
if name.is_empty()
|| name == "_"
|| !name.chars().all(|c| c.is_alphanumeric() || c == '_')
{
return (Vec::new(), None, None);
}
params.push((name.clone(), Ty::parse(part[colon + 1..].trim())));
slots.push(ParamSlot::Named(name));
}
}
let after = &line[close..];
let ret = match after.find("->") {
None => None,
Some(i) => {
let rest = &after[i + 2..];
match rest.find(['{', ';']) {
Some(end) => Some(Ty::parse(rest[..end].trim())),
None => return (Vec::new(), None, None),
}
}
};
(params, ret, Some(slots))
}
fn is_receiver(part: &str) -> bool {
let t = part.trim();
let t = t.strip_prefix("mut ").unwrap_or(t).trim();
if t == "self" {
return true;
}
if let Some(rest) = t.strip_prefix("&mut ") {
return rest.trim() == "self";
}
if let Some(rest) = t.strip_prefix('&') {
return rest.trim() == "self";
}
t.split(':').next().map(|n| n.trim()) == Some("self")
}
fn fn_name(line: &str) -> Option<String> {
let t = line.trim_start_matches("pub(crate) ").trim_start_matches("pub ").trim();
let rest = t.strip_prefix("const ").unwrap_or(t).trim();
let rest = rest.strip_prefix("async ").unwrap_or(rest).trim();
let rest = rest.strip_prefix("unsafe ").unwrap_or(rest).trim();
let rest = rest.strip_prefix("extern \"C\" ").unwrap_or(rest).trim();
let rest = rest.strip_prefix("fn ")?;
let name: String = rest
.chars()
.take_while(|c| c.is_alphanumeric() || *c == '_')
.collect();
if name.is_empty() {
None
} else {
Some(name)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SpecError {
pub text: String,
pub reason: String,
}
impl SpecError {
fn about(self, text: &str) -> Self {
Self { text: text.to_string(), reason: self.reason }
}
}
impl std::fmt::Display for SpecError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "cannot read contract `{}`: {}", self.text, self.reason)
}
}
#[derive(Clone, Debug)]
pub struct PathElem {
pub arg: String,
pub local: u32,
pub chain: Vec<u32>,
pub elem_w: u8,
pub elem_signed: bool,
pub len: u64,
}
#[derive(Clone, Debug, Default)]
pub struct FieldEnv {
pub vars: BTreeMap<String, Var>,
pub signed: BTreeSet<String>,
pub paths: BTreeMap<String, String>,
pub nested_paths: BTreeMap<String, String>,
pub aggregate_args: BTreeSet<String>,
pub known_args: BTreeSet<String>,
base: u32,
next_slot: u32,
next_ret_slot: u32,
pub seeds: Vec<(u32, u32, Var, bool)>,
pub nested_seeds: Vec<(u32, Vec<u32>, Var, bool)>,
pub array_lens: Vec<(u32, u64)>,
pub len_seeds: Vec<(u32, Var, u8, bool)>,
pub elem_seeds: Vec<(u32, u64, Var, bool)>,
pub path_elem_seeds: Vec<(u32, Vec<u32>, u64, Var, bool)>,
pub path_elem_types: BTreeMap<String, PathElem>,
pub tag_seeds: Vec<(u32, Var, u8, Vec<u64>)>,
pub payload_seeds: Vec<(u32, u64, Var, u8, bool)>,
pub variant_consts: BTreeMap<String, (u64, u8)>,
pub consts: BTreeMap<String, Const>,
pub payload_paths: BTreeMap<String, String>,
pub enum_args: BTreeSet<String>,
pub ret_enum_tags: Option<(Var, u64, u64)>,
pub ret_payload_guards: BTreeMap<String, (Var, u64)>,
indexed: BTreeMap<String, (u32, u8, Option<u64>, bool)>,
sym_index: BTreeMap<String, Var>,
sym_index_names: BTreeMap<String, BTreeSet<String>>,
sym_chain: BTreeMap<String, Var>,
sym_bound: BTreeMap<String, IndexBound>,
declared: BTreeSet<String>,
}
impl FieldEnv {
pub fn with_consts(consts: BTreeMap<String, Const>) -> FieldEnv {
FieldEnv { consts, ..FieldEnv::default() }
}
fn name_is_free(&self, name: &str) -> bool {
!self.declared.contains(name)
}
pub fn bind(&mut self, local: u32, arg: &str, field: &str, index: u32, ty: &Ty) -> Option<()> {
self.bind_bits(local, arg, field, index, ty.width()?, ty.is_signed())
}
pub fn declare_arg(&mut self, name: &str) {
self.known_args.insert(name.to_string());
self.declared.insert(name.to_string());
}
pub fn bind_bits(
&mut self,
local: u32,
arg: &str,
field: &str,
index: u32,
w: u8,
signed: bool,
) -> Option<()> {
if !(1..=64).contains(&w) {
return None;
}
let slot = self.base + self.next_slot;
if slot as usize >= crate::smt::MAX_VARS {
return None;
}
let mangled = format!("{arg}__f{index}");
if !self.name_is_free(&mangled) {
return None;
}
self.next_slot += 1;
let v = smt::var_named(slot, w);
self.vars.insert(mangled.clone(), v);
self.seeds.push((local, index, v, signed));
if signed {
self.signed.insert(mangled.clone());
}
self.paths.insert(format!("{arg}.{field}"), mangled);
self.known_args.insert(arg.to_string());
Some(())
}
pub fn bind_nested(&mut self, local: u32, arg: &str, path: &str, chain: &[u32], ty: &Ty) -> Option<()> {
let w = ty.width()?;
let slot = self.base + self.next_slot;
if slot as usize >= crate::smt::MAX_VARS {
return None;
}
let mangled = format!(
"{arg}__n{}",
chain.iter().map(|i| i.to_string()).collect::<Vec<_>>().join("_")
);
if !self.name_is_free(&mangled) {
return None;
}
self.next_slot += 1;
let v = smt::var_named(slot, w);
self.vars.insert(mangled.clone(), v);
if ty.is_signed() {
self.signed.insert(mangled.clone());
}
self.nested_seeds.push((local, chain.to_vec(), v, ty.is_signed()));
self.nested_paths.insert(path.to_string(), mangled);
self.aggregate_args.insert(arg.to_string());
self.known_args.insert(arg.to_string());
Some(())
}
pub fn bind_path_elem(&mut self, path: &str, index: u64) -> Option<Var> {
let PathElem { arg, local, chain, elem_w, elem_signed, len } =
self.path_elem_types.get(path)?.clone();
if !(1..=64).contains(&elem_w) || index >= len {
return None;
}
let mangled = format!(
"{arg}__pe{}_e{index}",
chain.iter().map(|i| i.to_string()).collect::<Vec<_>>().join("_")
);
if let Some(v) = self.vars.get(&mangled) {
return Some(*v);
}
if !self.name_is_free(&mangled) {
return None;
}
let slot = self.base + self.next_slot;
if slot as usize >= crate::smt::MAX_VARS {
return None;
}
self.next_slot += 1;
let v = smt::var_named(slot, elem_w);
self.vars.insert(mangled.clone(), v);
if elem_signed {
self.signed.insert(mangled.clone());
}
self.paths.insert(format!("{path}[{index}]"), mangled);
self.path_elem_seeds.push((local, chain, index, v, elem_signed));
Some(v)
}
pub fn bind_nested_paths(
&mut self,
local: u32,
arg: &str,
ty: &Ty,
structs: &BTreeMap<String, StructDef>,
) {
let mut w = NestedWalk { local, arg, structs, on_path: Vec::new() };
self.walk_nested(&mut w, arg, &[], ty);
}
fn walk_nested(
&mut self,
w: &mut NestedWalk<'_>,
prefix: &str,
chain: &[u32],
ty: &Ty,
) {
let fields: Vec<(String, Ty)> = match ty {
Ty::Other(name) => match struct_lookup(w.structs, name) {
Some(def) => def.fields.clone(),
None => return,
},
Ty::Tuple(ts) => {
ts.iter().enumerate().map(|(i, t)| (i.to_string(), t.clone())).collect()
}
_ => return,
};
if let Ty::Other(name) = ty {
if w.on_path.iter().any(|n| n == name) {
return;
}
w.on_path.push(name.clone());
}
for (index, (fname, fty)) in fields.iter().enumerate() {
let mut child = chain.to_vec();
child.push(index as u32);
let path = format!("{prefix}.{fname}");
if child.len() >= 2 && fty.width().is_some() {
self.bind_nested(w.local, w.arg, &path, &child, fty);
}
if let Ty::Array(elem, n) = fty {
if let Some(ew) = elem.width() {
self.path_elem_types.insert(
path.clone(),
PathElem {
arg: w.arg.to_string(),
local: w.local,
chain: child.clone(),
elem_w: ew,
elem_signed: elem.is_signed(),
len: *n,
},
);
}
}
if matches!(fty, Ty::Other(_) | Ty::Tuple(_)) {
self.walk_nested(w, &path, &child, fty);
}
}
if matches!(ty, Ty::Other(_)) {
w.on_path.pop();
}
}
pub fn bind_enum(
&mut self,
local: u32,
arg: &str,
enum_name: &str,
def: &EnumDef,
) -> Option<()> {
if def.variants.is_empty() {
return None;
}
let width = def.tag_width();
let tag_slot = self.base + self.next_slot;
if tag_slot as usize >= crate::smt::MAX_VARS {
return None;
}
let tag_name = format!("{arg}__tag");
if !self.name_is_free(&tag_name) {
return None;
}
self.next_slot += 1;
let tag = smt::var_named(tag_slot, width);
self.vars.insert(tag_name, tag);
self.vars.insert(arg.to_string(), tag);
let discs: Vec<u64> = def.variants.iter().map(|(_, _, d)| *d).collect();
self.tag_seeds.push((local, tag, width, discs));
self.enum_args.insert(arg.to_string());
for (vname, payload, d) in def.variants.iter() {
self.variant_consts.insert(format!("{enum_name}::{vname}"), (*d, width));
self.variant_consts.insert(format!("{arg}::{vname}"), (*d, width));
let Some(first) = payload.first() else { continue };
let Some(w) = first.width() else { continue };
let slot = self.base + self.next_slot;
if slot as usize >= crate::smt::MAX_VARS {
continue;
}
let mangled = format!("{arg}__v{d}_0");
if !self.name_is_free(&mangled) {
continue;
}
self.next_slot += 1;
let v = smt::var_named(slot, w);
self.vars.insert(mangled.clone(), v);
self.payload_seeds.push((local, *d, v, w, first.is_signed()));
if first.is_signed() {
self.signed.insert(mangled.clone());
}
self.payload_paths.insert(format!("{arg}.{vname}"), mangled);
}
Some(())
}
}
impl FieldEnv {
pub fn bind_ret(&mut self, index: u32, ty: &Ty, v: Var) -> Option<()> {
ty.width()?;
let mangled = format!("ret__f{index}");
self.vars.insert(mangled.clone(), v);
if ty.is_signed() {
self.signed.insert(mangled.clone());
}
self.paths.insert(format!("ret.{index}"), mangled);
Some(())
}
pub fn bind_ret_enum(&mut self, tag: Var, success: u64, failure: u64) {
self.ret_enum_tags = Some((tag, success, failure));
}
pub fn bind_ret_payload(&mut self, vname: &str, var: Var, tag: Var, disc: u64, signed: bool) {
let mangled = format!("ret__v_{vname}");
if !self.name_is_free(&mangled) {
return;
}
self.vars.insert(mangled.clone(), var);
self.paths.insert(format!("ret.{vname}"), mangled.clone());
self.paths.insert(format!("result.{vname}"), mangled.clone());
if signed {
self.signed.insert(mangled.clone());
}
self.ret_payload_guards.insert(mangled, (tag, disc));
}
pub fn probe_ret_payloads(
&mut self,
ret_ty: &Ty,
enums: &BTreeMap<String, EnumDef>,
tag: Var,
ensures: &[String],
) {
let Some(def) = ret_enum_def(ret_ty, enums) else { return };
for (vname, payload, disc) in &def.variants {
let Some(first) = payload.first() else { continue };
let Some(w) = first.width() else { continue };
let named = ensures
.iter()
.any(|e| names_ret_variant(e, vname));
if !named {
continue;
}
let slot = self.base + self.next_slot + self.next_ret_slot;
if slot as usize >= crate::smt::MAX_VARS {
continue;
}
self.next_ret_slot += 1;
let v = smt::var_named(slot, w);
self.bind_ret_payload(vname, v, tag, *disc, first.is_signed());
}
}
pub fn probe_ret_enum_slot(&mut self, width: u8) -> Option<Var> {
let slot = self.base + self.next_slot + self.next_ret_slot;
if slot as usize >= crate::smt::MAX_VARS {
return None;
}
self.next_ret_slot += 1;
Some(smt::var_named(slot, width.clamp(1, 64)))
}
pub fn probe_ret_slot(&mut self, index: u32, ty: &Ty) -> Option<Var> {
let w = ty.width()?;
let slot = self.base + self.next_slot + self.next_ret_slot;
if slot as usize >= crate::smt::MAX_VARS {
return None;
}
self.next_ret_slot += 1;
let v = smt::var_named(slot, w);
self.bind_ret(index, ty, v)?;
Some(v)
}
pub fn bind_indexed_len(
&mut self,
local: u32,
arg: &str,
elem_w: u8,
elem_signed: bool,
) -> Option<Var> {
if elem_w != 0 && !(1..=64).contains(&elem_w) {
return None;
}
let len_name = format!("{arg}__len");
if !self.name_is_free(&len_name) {
return None;
}
let slot = self.base + self.next_slot;
if slot as usize >= crate::smt::MAX_VARS {
return None;
}
self.next_slot += 1;
let v = smt::var_named(slot, USIZE_WIDTH);
self.vars.insert(len_name, v);
self.paths.insert(format!("{arg}.len()"), format!("{arg}__len"));
self.indexed.insert(arg.to_string(), (local, elem_w, None, elem_signed));
self.len_seeds.push((local, v, elem_w, elem_signed));
self.known_args.insert(arg.to_string());
Some(v)
}
pub fn bind_array_len(
&mut self,
local: u32,
arg: &str,
elem_w: u8,
elem_signed: bool,
n: u64,
) -> Option<()> {
if !(1..=64).contains(&elem_w) {
return None;
}
let len_name = format!("{arg}__len");
if !self.name_is_free(&len_name) {
return None;
}
let v = smt::word(n, USIZE_WIDTH);
self.vars.insert(len_name, v);
self.paths.insert(format!("{arg}.len()"), format!("{arg}__len"));
self.indexed.insert(arg.to_string(), (local, elem_w, Some(n), elem_signed));
self.len_seeds.push((local, v, elem_w, elem_signed));
self.array_lens.push((local, n));
self.known_args.insert(arg.to_string());
Some(())
}
fn bind_indexed_elem(&mut self, arg: &str, index: u64) -> Option<Var> {
let (local, elem_w, fixed_len, elem_signed) = *self.indexed.get(arg)?;
if !(1..=64).contains(&elem_w) {
return None;
}
if let Some(n) = fixed_len {
if index >= n {
return None;
}
}
let mangled = format!("{arg}__e{index}");
if let Some(v) = self.vars.get(&mangled) {
return Some(*v);
}
if !self.name_is_free(&mangled) {
return None;
}
let slot = self.base + self.next_slot;
if slot as usize >= crate::smt::MAX_VARS {
return None;
}
self.next_slot += 1;
let v = smt::var_named(slot, elem_w);
self.vars.insert(mangled.clone(), v);
if elem_signed {
self.signed.insert(mangled.clone());
}
self.paths.insert(format!("{arg}[{index}]"), mangled);
self.elem_seeds.push((local, index, v, elem_signed));
Some(v)
}
pub fn bind_sym_index(
&mut self,
arg: &str,
elem_w: u8,
bound: IndexBound,
index_name: &str,
index: Var,
) -> Option<Var> {
if !(1..=64).contains(&elem_w) {
return None;
}
let steps = match bound {
IndexBound::Const(n) if n <= MAX_INDEX_CHAIN => n,
IndexBound::Const(_) => return None,
IndexBound::Len(_) => MAX_INDEX_CHAIN,
};
if let Some(v) = self.sym_index.get(arg) {
if *v != index {
return None;
}
self.sym_index_names.entry(arg.to_string()).or_default().insert(index_name.to_string());
return Some(*v);
}
let mut elems = Vec::with_capacity(steps as usize);
for k in 0..steps {
elems.push(self.bind_indexed_elem(arg, k)?);
}
let v = index;
self.sym_index.insert(arg.to_string(), v);
self.sym_index_names.entry(arg.to_string()).or_default().insert(index_name.to_string());
let mut chain = smt::word(0, elem_w);
for k in (0..steps).rev() {
chain = smt::ite(smt::eq_const(v, k), elems[k as usize], chain);
}
self.sym_chain.insert(arg.to_string(), chain);
let chain_name = format!("{arg}__chain");
if !self.name_is_free(&chain_name) {
return None;
}
self.vars.insert(chain_name.clone(), chain);
if self.indexed.get(arg).is_some_and(|&(_, _, _, es)| es) {
self.signed.insert(chain_name.clone());
}
self.paths.insert(chain_name.clone(), chain_name);
self.sym_bound.insert(arg.to_string(), bound);
Some(v)
}
pub fn index_guards(&self) -> Vec<(Var, IndexBound)> {
self.sym_index
.iter()
.filter_map(|(arg, v)| {
let bound = *self.sym_bound.get(arg)?;
Some((*v, bound))
})
.collect()
}
pub fn slice_chain_steps(&self) -> Vec<(u32, u64)> {
self.sym_bound
.iter()
.filter_map(|(arg, bound)| {
let (local, _, _, _) = self.indexed.get(arg)?;
match bound {
IndexBound::Len(_) => Some((*local, MAX_INDEX_CHAIN)),
IndexBound::Const(_) => None,
}
})
.collect()
}
pub fn bind_index_refs(&mut self, text: &str, args: &BTreeMap<String, Var>) {
let chars: Vec<char> = text.chars().collect();
let mut i = 0;
while i < chars.len() {
if chars[i].is_alphabetic() || chars[i] == '_' {
let start = i;
while i < chars.len() && (chars[i].is_alphanumeric() || chars[i] == '_') {
i += 1;
}
let ident: String = chars[start..i].iter().collect();
if chars.get(i) == Some(&'.') {
if let Some((end, path)) = longest_dotted_run(&chars, start) {
if self.path_elem_types.contains_key(&path) && chars.get(end) == Some(&'[') {
let mut j = end + 1;
let digits: String =
chars[j..].iter().take_while(|c| c.is_ascii_digit()).collect();
j += digits.len();
if !digits.is_empty() && chars.get(j) == Some(&']') {
if let Ok(k) = digits.parse::<u64>() {
self.bind_path_elem(&path, k);
}
i = j + 1;
continue;
}
}
}
}
if chars.get(i) == Some(&'[') {
let mut j = i + 1;
let digits: String = chars[j..].iter().take_while(|c| c.is_ascii_digit()).collect();
j += digits.len();
if !digits.is_empty() && chars.get(j) == Some(&']') {
if let Ok(k) = digits.parse::<u64>() {
self.bind_indexed_elem(&ident, k);
}
i = j + 1;
continue;
}
let close = chars[j..].iter().position(|c| *c == ']').map(|p| p + j);
if let Some(close) = close {
let inner: String = chars[i + 1..close].iter().collect();
if let Some(&index) = args.get(&inner) {
if let Some((_, elem_w, fixed_len, _)) =
self.indexed.get(&ident).copied()
{
let bound = match fixed_len {
Some(n) => Some(IndexBound::Const(n)),
None => self.vars.get(&format!("{ident}__len")).map(|l| {
IndexBound::Len(*l)
}),
};
if let Some(bound) = bound {
self.bind_sym_index(
&ident, elem_w, bound, &inner, index,
);
}
}
}
i = close + 1;
continue;
}
}
continue;
}
i += 1;
}
}
}
pub fn named_ret_components(texts: &[String]) -> BTreeSet<u32> {
let mut out = BTreeSet::new();
for text in texts {
let chars: Vec<char> = text.chars().collect();
let mut i = 0;
while i < chars.len() {
if chars[i].is_alphabetic() || chars[i] == '_' {
let start = i;
while i < chars.len() && (chars[i].is_alphanumeric() || chars[i] == '_') {
i += 1;
}
let ident: String = chars[start..i].iter().collect();
if ident == "ret" && chars.get(i) == Some(&'.') {
let j = i + 1;
let digits: String =
chars[j..].iter().take_while(|c| c.is_ascii_digit()).collect();
if !digits.is_empty() {
if let Ok(k) = digits.parse::<u32>() {
out.insert(k);
}
}
}
continue;
}
i += 1;
}
}
out
}
fn longest_dotted_run(chars: &[char], start: usize) -> Option<(usize, String)> {
let mut end = start;
while end < chars.len() && (chars[end].is_alphanumeric() || chars[end] == '_') {
end += 1;
}
if end == start {
return None;
}
let mut last = end;
while chars.get(end) == Some(&'.') {
let mut j = end + 1;
while j < chars.len() && (chars[j].is_alphanumeric() || chars[j] == '_') {
j += 1;
}
if j == end + 1 {
break;
}
end = j;
last = j;
}
Some((last, chars[start..last].iter().collect()))
}
fn longest_nested_match(
chars: &[char],
start: usize,
dot: usize,
fields: &FieldEnv,
) -> Option<(usize, String)> {
let mut best: Option<(usize, String)> = None;
let mut i = dot;
while chars.get(i) == Some(&'.') {
let mut j = i + 1;
while j < chars.len() && (chars[j].is_alphanumeric() || chars[j] == '_') {
j += 1;
}
if j == i + 1 {
break;
}
let candidate: String = chars[start..j].iter().collect();
if let Some(m) = fields.nested_paths.get(&candidate) {
best = Some((j, m.clone()));
}
i = j;
}
best
}
fn longest_bound_prefix(chars: &[char], start: usize, dot: usize, fields: &FieldEnv) -> String {
let mut last_bound_end = dot;
let mut i = dot;
while chars.get(i) == Some(&'.') {
let mut j = i + 1;
while j < chars.len() && (chars[j].is_alphanumeric() || chars[j] == '_') {
j += 1;
}
if j == i + 1 {
break;
}
let candidate: String = chars[start..j].iter().collect();
if fields.nested_paths.contains_key(&candidate) {
last_bound_end = j;
}
i = j;
}
let mut k = last_bound_end;
if chars.get(k) == Some(&'.') {
k += 1;
}
let mut e = k;
while e < chars.len() && (chars[e].is_alphanumeric() || chars[e] == '_') {
e += 1;
}
chars[k..e].iter().collect()
}
struct NestedWalk<'a> {
local: u32,
arg: &'a str,
structs: &'a BTreeMap<String, StructDef>,
on_path: Vec<String>,
}
fn rewrite_fields(text: &str, fields: &FieldEnv) -> Result<String, SpecError> {
if fields.paths.is_empty()
&& fields.known_args.is_empty()
&& fields.payload_paths.is_empty()
&& fields.nested_paths.is_empty()
{
return Ok(text.to_string());
}
let chars: Vec<char> = text.chars().collect();
let mut out = String::with_capacity(text.len());
let mut i = 0;
while i < chars.len() {
let c = chars[i];
if c.is_alphabetic() || c == '_' {
let start = i;
while i < chars.len() && (chars[i].is_alphanumeric() || chars[i] == '_') {
i += 1;
}
let ident: String = chars[start..i].iter().collect();
if chars.get(i) == Some(&'.') {
let dot = i;
let mut j = i + 1;
while j < chars.len() && (chars[j].is_alphanumeric() || chars[j] == '_') {
j += 1;
}
let field: String = chars[dot + 1..j].iter().collect();
if let Some(mangled) = fields.payload_paths.get(&format!("{ident}.{field}")) {
out.push_str(mangled);
i = j;
continue;
}
if fields.enum_args.contains(&ident)
&& fields.variant_consts.contains_key(&format!("{ident}::{field}"))
{
return Err(SpecError {
text: text.to_string(),
reason: format!(
"`{field}` is a variant of `{ident}` with no payload to read; \
compare the tag instead (`{ident} == ...`)"
),
});
}
let is_call = chars.get(j) == Some(&'(');
if field == "len" && is_call {
let close = j + 1;
if chars.get(close) == Some(&')') {
if let Some(mangled) = fields.paths.get(&format!("{ident}.len()")) {
out.push_str(mangled);
i = close + 1;
continue;
}
if fields.known_args.contains(&ident) {
return Err(SpecError {
text: text.to_string(),
reason: format!(
"`{ident}` is not a slice or array, so `len()` has no meaning here"
),
});
}
}
}
let key = format!("{ident}.{field}");
if !is_call && !field.is_empty() {
if let Some(mangled) = fields.paths.get(&key) {
out.push_str(mangled);
i = j;
continue;
}
if let Some((end, path)) = longest_dotted_run(&chars, start) {
if chars.get(end) == Some(&'[') {
let mut k = end + 1;
let digits: String =
chars[k..].iter().take_while(|c| c.is_ascii_digit()).collect();
k += digits.len();
if !digits.is_empty() && chars.get(k) == Some(&']') {
if let Some(mangled) =
fields.paths.get(&format!("{path}[{digits}]"))
{
out.push_str(mangled);
i = k + 1;
continue;
}
}
}
}
if let Some((end, mangled)) = longest_nested_match(&chars, start, dot, fields) {
out.push_str(&mangled);
i = end;
continue;
}
if fields.aggregate_args.contains(&ident) {
let bad = longest_bound_prefix(&chars, start, dot, fields);
return Err(SpecError {
text: text.to_string(),
reason: format!("unknown field `{bad}` of `{ident}`"),
});
}
if fields.known_args.contains(&ident) {
return Err(SpecError {
text: text.to_string(),
reason: format!("unknown field `{field}` of `{ident}`"),
});
}
}
}
if chars.get(i) == Some(&'[') {
let mut j = i + 1;
let digits: String = chars[j..].iter().take_while(|c| c.is_ascii_digit()).collect();
j += digits.len();
if !digits.is_empty() && chars.get(j) == Some(&']') {
if let Some(mangled) = fields.paths.get(&format!("{ident}[{digits}]")) {
out.push_str(mangled);
i = j + 1;
continue;
}
}
if let Some(close) = chars[j..].iter().position(|c| *c == ']').map(|p| p + j) {
let inner: String = chars[i + 1..close].iter().collect();
let is_bound_index = fields
.sym_index_names
.get(&ident)
.map(|names| names.contains(&inner))
.unwrap_or(false);
if is_bound_index {
if let Some(mangled) = fields.paths.get(&format!("{ident}__chain")) {
out.push_str(mangled);
i = close + 1;
continue;
}
}
}
}
out.push_str(&ident);
continue;
}
out.push(c);
i += 1;
}
Ok(out)
}
pub fn eval_requires(
text: &str,
args: &BTreeMap<String, Var>,
signed: &BTreeSet<String>,
fields: &FieldEnv,
) -> Result<Pred, SpecError> {
let orig = text;
let text = rewrite_fields(text, fields)?;
let mut names = args.clone();
names.extend(fields.vars.iter().map(|(k, v)| (k.clone(), *v)));
let mut sgn = signed.clone();
sgn.extend(fields.signed.iter().cloned());
let mut p = Parser::new(&text, &names, None, &sgn, false);
p.variant_consts = fields.variant_consts.clone();
p.enum_args = fields.enum_args.clone();
p.consts = fields.consts.clone();
let pred = p.parse_or().map_err(|e| e.about(orig))?;
p.expect_end().map_err(|e| e.about(orig))?;
Ok(pred)
}
pub const RET_IS_AGGREGATE: &str =
"the return type is an aggregate, so `ret` has no single value; name a component such as `ret.0`";
pub const RET_IS_UNKNOWN: &str = "the return value is not known on this path";
#[allow(clippy::too_many_arguments)]
pub fn eval_ensures(
text: &str,
args: &BTreeMap<String, Var>,
ret: Option<Var>,
ret_absent: &'static str,
signed: &BTreeSet<String>,
ret_signed: bool,
fields: &FieldEnv,
old_args: &BTreeMap<String, Var>,
) -> Result<Pred, SpecError> {
let orig = text;
let text = rewrite_fields(text, fields)?;
let mut names = args.clone();
names.extend(fields.vars.iter().map(|(k, v)| (k.clone(), *v)));
let mut sgn = signed.clone();
sgn.extend(fields.signed.iter().cloned());
let mut p = Parser::new(&text, &names, ret, &sgn, ret_signed);
p.ret_absent = ret_absent;
p.variant_consts = fields.variant_consts.clone();
p.enum_args = fields.enum_args.clone();
p.consts = fields.consts.clone();
p.old_args = old_args.clone();
p.ret_enum_tags = fields.ret_enum_tags;
p.ret_payload_guards = fields.ret_payload_guards.clone();
let pred = p.parse_or().map_err(|e| e.about(orig))?;
p.expect_end().map_err(|e| e.about(orig))?;
Ok(pred)
}
pub fn eval_invariant(
text: &str,
names: &BTreeMap<String, Var>,
signed: &BTreeSet<String>,
consts: &BTreeMap<String, Const>,
) -> Result<Pred, SpecError> {
let mut p = Parser::new(text, names, None, signed, false);
p.consts = consts.clone();
let pred = p.parse_or()?;
p.expect_end()?;
Ok(pred)
}
pub fn eval_measure(
text: &str,
names: &BTreeMap<String, Var>,
signed: &BTreeSet<String>,
consts: &BTreeMap<String, Const>,
) -> Result<(Var, bool), SpecError> {
let mut p = Parser::new(text, names, None, signed, false);
p.consts = consts.clone();
let (v, sgn) = p.parse_expr()?;
p.expect_end()?;
Ok((v, sgn.eval()))
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Sign {
Signed,
Unsigned,
NegLiteral,
Literal,
Opaque(Option<(i128, i128)>),
}
impl Sign {
fn from_bool(b: bool) -> Sign {
if b {
Sign::Signed
} else {
Sign::Unsigned
}
}
fn eval(self) -> bool {
matches!(self, Sign::Signed | Sign::NegLiteral)
}
fn is_opaque(self) -> bool {
matches!(self, Sign::Opaque(_))
}
fn opaque_operand(self) -> Option<(i128, i128)> {
if let Sign::Opaque(m) = self {
m
} else {
None
}
}
fn adapts(self) -> bool {
!self.fixes_type()
}
fn fixes_type(self) -> bool {
matches!(self, Sign::Signed | Sign::Unsigned)
}
fn typed(self) -> Option<bool> {
match self {
Sign::Signed | Sign::NegLiteral => Some(true),
Sign::Unsigned => Some(false),
Sign::Literal | Sign::Opaque(_) => None,
}
}
fn resolve(a: Sign, b: Sign) -> Option<bool> {
a.typed().or_else(|| b.typed())
}
fn combine(a: Sign, b: Sign) -> Sign {
if a.fixes_type() || b.fixes_type() {
if a == Sign::Signed || b == Sign::Signed {
Sign::Signed
} else {
Sign::Unsigned
}
} else if a.is_opaque() || b.is_opaque() {
Sign::Opaque(Sign::union_env(a.opaque_operand(), b.opaque_operand()))
} else if a == Sign::NegLiteral || b == Sign::NegLiteral {
Sign::NegLiteral
} else {
Sign::Literal
}
}
fn ambiguous(self) -> bool {
self.is_opaque()
}
fn union_env(a: Option<(i128, i128)>, b: Option<(i128, i128)>) -> Option<(i128, i128)> {
match (a, b) {
(Some((alo, ahi)), Some((blo, bhi))) => Some((alo.min(blo), ahi.max(bhi))),
(Some(e), None) | (None, Some(e)) => Some(e),
(None, None) => None,
}
}
}
struct Parser<'a> {
toks: Vec<Tok>,
pos: usize,
args: &'a BTreeMap<String, Var>,
ret: Option<Var>,
text: String,
signed: &'a BTreeSet<String>,
ret_signed: bool,
ret_absent: &'static str,
variant_consts: BTreeMap<String, (u64, u8)>,
enum_args: BTreeSet<String>,
consts: BTreeMap<String, Const>,
old_args: BTreeMap<String, Var>,
ret_enum_tags: Option<(Var, u64, u64)>,
ret_payload_guards: BTreeMap<String, (Var, u64)>,
range: BTreeMap<u32, (i128, i128)>,
bare_literals: BTreeSet<u32>,
guarded_groups: Vec<(usize, usize)>,
in_negation: bool,
amount_floor: u8,
name_tokens: BTreeSet<usize>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum Tok {
Ident(String),
Num(u64, Option<(u8, bool)>),
BadNum,
Char(u32),
BadChar,
Op(String),
}
fn read_char_literal(b: &[char], start: usize) -> Option<(u32, usize)> {
let mut i = start + 1;
let v = if *b.get(i)? == '\\' {
i += 1;
let e = *b.get(i)?;
i += 1;
match e {
'n' => 0x0a,
'r' => 0x0d,
't' => 0x09,
'\\' => 0x5c,
'\'' => 0x27,
'"' => 0x22,
'0' => 0x00,
'x' => {
let hi = b.get(i)?.to_digit(16)?;
let lo = b.get(i + 1)?.to_digit(16)?;
i += 2;
hi * 16 + lo
}
'u' => {
if *b.get(i)? != '{' {
return None;
}
i += 1;
let mut n = 0u32;
let mut any = false;
while let Some(d) = b.get(i).and_then(|c| c.to_digit(16)) {
n = n.checked_mul(16)?.checked_add(d)?;
any = true;
i += 1;
}
if !any || *b.get(i)? != '}' {
return None;
}
i += 1;
n
}
_ => return None,
}
} else {
let ch = *b.get(i)?;
if ch == '\'' {
return None;
}
i += 1;
ch as u32
};
if *b.get(i)? != '\'' {
return None;
}
char::from_u32(v)?;
Some((v, i + 1))
}
fn tokenize(s: &str) -> Vec<Tok> {
let mut out = Vec::new();
let b: Vec<char> = s.chars().collect();
let mut i = 0;
while i < b.len() {
let c = b[i];
if c == '\'' {
match read_char_literal(&b, i) {
Some((v, next)) => {
out.push(Tok::Char(v));
i = next;
}
None => {
out.push(Tok::BadChar);
i += 1;
while i < b.len() && b[i] != '\'' {
i += 1;
}
i = (i + 1).min(b.len());
}
}
continue;
}
if c.is_whitespace() {
i += 1;
continue;
}
if c.is_ascii_digit() {
let radix = if c == '0' {
match b.get(i + 1) {
Some('x' | 'X') => {
i += 2;
16
}
Some('b' | 'B') => {
i += 2;
2
}
Some('o' | 'O') => {
i += 2;
8
}
_ => 10,
}
} else {
10
};
let mut digits = String::new();
let mut suffix: Option<(u8, bool)> = None;
while i < b.len() && (b[i].is_digit(radix) || b[i] == '_') {
if b[i] != '_' {
digits.push(b[i]);
}
i += 1;
}
if b.get(i).is_some_and(|d| d.is_ascii_alphabetic()) {
let sfx_start = i;
while i < b.len() && (b[i].is_alphanumeric() || b[i] == '_') {
i += 1;
}
let sfx: String = b[sfx_start..i].iter().collect();
if !matches!(
sfx.as_str(),
"i8" | "i16"
| "i32"
| "i64"
| "i128"
| "isize"
| "u8"
| "u16"
| "u32"
| "u64"
| "u128"
| "usize"
) {
out.push(Tok::BadNum);
continue;
}
let ty = Ty::parse(&sfx);
let (signed, width) = (ty.is_signed(), ty.width().unwrap_or(64));
suffix = Some((width, signed));
}
let exact = i == b.len() || (!b[i].is_alphanumeric() && b[i] != '_');
let val = if digits.is_empty() {
None
} else {
u64::from_str_radix(&digits, radix).ok()
};
match (exact, val) {
(true, Some(v)) => out.push(Tok::Num(v, suffix)),
_ => out.push(Tok::BadNum),
}
continue;
}
if c.is_alphabetic() || c == '_' {
let mut n = String::new();
while i < b.len() && (b[i].is_alphanumeric() || b[i] == '_') {
n.push(b[i]);
i += 1;
}
out.push(Tok::Ident(n));
continue;
}
let two: String = b[i..(i + 2).min(b.len())].iter().collect();
if ["==", "!=", "<=", ">=", "<<", ">>", "&&", "||"].contains(&two.as_str()) {
out.push(Tok::Op(two));
i += 2;
continue;
}
out.push(Tok::Op(c.to_string()));
i += 1;
}
out
}
impl<'a> Parser<'a> {
fn new(
s: &str,
args: &'a BTreeMap<String, Var>,
ret: Option<Var>,
signed: &'a BTreeSet<String>,
ret_signed: bool,
) -> Parser<'a> {
Parser {
toks: tokenize(s),
pos: 0,
args,
ret,
text: s.to_string(),
signed,
ret_signed,
variant_consts: BTreeMap::new(),
enum_args: BTreeSet::new(),
consts: BTreeMap::new(),
old_args: BTreeMap::new(),
ret_enum_tags: None,
ret_payload_guards: BTreeMap::new(),
range: BTreeMap::new(),
bare_literals: BTreeSet::new(),
name_tokens: BTreeSet::new(),
guarded_groups: Vec::new(),
in_negation: false,
amount_floor: 0,
ret_absent: "`ret` is only meaningful in `ensures`",
}
}
fn is_signed_name(&self, name: &str) -> bool {
if name == "ret" || name == "result" {
return self.ret_signed;
}
self.signed.contains(name)
}
fn try_ret_variant_method(&mut self) -> Result<Option<Pred>, SpecError> {
let Some(Tok::Ident(base)) = self.peek() else { return Ok(None) };
if !matches!(self.toks.get(self.pos + 1), Some(Tok::Op(o)) if o == ".") {
return Ok(None);
}
let Some(Tok::Ident(method)) = self.toks.get(self.pos + 2) else { return Ok(None) };
if !matches!(self.toks.get(self.pos + 3), Some(Tok::Op(o)) if o == "(") {
return Ok(None);
}
if !matches!(self.toks.get(self.pos + 4), Some(Tok::Op(o)) if o == ")") {
return Ok(None);
}
let base = base.clone();
let method = method.clone();
let arg_tag = self.args.get(&format!("{base}__tag")).copied();
let (tag, success, failure) = if let Some(tag) = arg_tag {
let Some(sf) = self.arg_enum_discriminants(&base) else { return Ok(None) };
(tag, sf.0, sf.1)
} else if base == "ret" || base == "result" {
match self.ret_enum_tags {
Some(t) => t,
None => {
return Err(self.err(
"`is_ok`/`is_some`/`is_err`/`is_none` is only meaningful on an enum return",
))
}
}
} else {
return Ok(None);
};
let d = match method.as_str() {
"is_ok" | "is_some" => success,
"is_err" | "is_none" => failure,
_ => return Ok(None),
};
let p = smt::eq_const(tag, d);
self.pos += 5;
Ok(Some(p))
}
fn arg_enum_discriminants(&self, arg: &str) -> Option<(u64, u64)> {
let find = |v: &str| self.variant_consts.get(&format!("{arg}::{v}")).map(|(d, _)| *d);
let success = find("Ok").or_else(|| find("Some"))?;
let failure = find("Err").or_else(|| find("None"))?;
Some((success, failure))
}
fn peek(&self) -> Option<&Tok> {
self.toks.get(self.pos)
}
fn err(&self, reason: impl Into<String>) -> SpecError {
SpecError { text: self.text.clone(), reason: reason.into() }
}
fn eat_op(&mut self, op: &str) -> bool {
if let Some(Tok::Op(o)) = self.peek() {
if o == op {
self.pos += 1;
return true;
}
}
false
}
fn paren_is_predicate(&self) -> bool {
self.paren_is_predicate_from(self.pos)
}
fn paren_is_predicate_from(&self, start: usize) -> bool {
let mut depth = 0usize;
for (off, t) in self.toks[start..].iter().enumerate() {
match t {
Tok::Op(o) if o == "(" => {
if self.enum_method_is_predicate_from(start + off) {
return true;
}
depth += 1;
}
Tok::Op(o) if o == ")" => {
depth -= 1;
if depth == 0 {
return false;
}
}
Tok::Op(o)
if matches!(o.as_str(), "==" | "!=" | "<=" | ">=" | "<" | ">" | "&&" | "||") =>
{
return true
}
Tok::Ident(n) if n == "true" || n == "false" => return true,
_ => {}
}
}
false
}
fn enum_method_is_predicate_from(&self, start: usize) -> bool {
matches!(self.toks.get(start), Some(Tok::Op(o)) if o == "(")
&& self.enum_method_shape(start + 1)
}
fn enum_method_shape(&self, start: usize) -> bool {
if !matches!(self.toks.get(start), Some(Tok::Ident(_))) {
return false;
}
if !matches!(self.toks.get(start + 1), Some(Tok::Op(o)) if o == ".") {
return false;
}
let Some(Tok::Ident(m)) = self.toks.get(start + 2) else { return false };
if !matches!(m.as_str(), "is_ok" | "is_some" | "is_err" | "is_none") {
return false;
}
matches!(self.toks.get(start + 3), Some(Tok::Op(o)) if o == "(")
&& matches!(self.toks.get(start + 4), Some(Tok::Op(o)) if o == ")")
}
fn bang_is_predicate(&self) -> bool {
match self.toks.get(self.pos + 1) {
Some(Tok::Op(o)) if o == "(" => self.paren_is_predicate_from(self.pos + 1),
Some(Tok::Ident(n)) if n == "true" || n == "false" => true,
Some(Tok::Ident(_)) => self.enum_method_shape(self.pos + 1),
_ => false,
}
}
fn expect_end(&self) -> Result<(), SpecError> {
if self.pos == self.toks.len() {
Ok(())
} else {
Err(self.err(format!("trailing tokens from token {}", self.pos)))
}
}
fn parse_or(&mut self) -> Result<Pred, SpecError> {
let mut left = self.parse_and()?;
while self.eat_op("||") {
let right = self.parse_and()?;
left = smt::or(left, right);
}
Ok(left)
}
fn parse_and(&mut self) -> Result<Pred, SpecError> {
let start = self.pos;
let left = self.parse_cmp()?;
let mut left = self.guard_ret_payloads(start, self.pos, left);
while self.eat_op("&&") {
let start = self.pos;
let right = self.parse_cmp()?;
let right = self.guard_ret_payloads(start, self.pos, right);
left = smt::and(left, right);
}
Ok(left)
}
fn guard_ret_payloads(&self, from: usize, to: usize, p: Pred) -> Pred {
if self.ret_payload_guards.is_empty() {
return p;
}
if self.in_negation {
return p;
}
let mut guard: Option<Pred> = None;
for (i, t) in self.toks[from..to.min(self.toks.len())].iter().enumerate() {
let idx = from + i;
if self
.guarded_groups
.iter()
.any(|(s, e)| idx >= *s && idx < *e)
{
continue;
}
if let Tok::Ident(name) = t {
if let Some((tag, disc)) = self.ret_payload_guards.get(name) {
let g = smt::eq_const(*tag, *disc);
guard = Some(match guard {
None => g,
Some(prev) => smt::and(prev, g),
});
}
}
}
match guard {
None => p,
Some(g) => smt::implies(g, p),
}
}
fn ret_payload_guard_for(&self, from: usize, to: usize) -> (Option<Pred>, usize) {
if self.ret_payload_guards.is_empty() {
return (None, 0);
}
let mut guard: Option<Pred> = None;
let mut discs: Vec<u64> = Vec::new();
for t in &self.toks[from..to.min(self.toks.len())] {
if let Tok::Ident(name) = t {
if let Some((tag, disc)) = self.ret_payload_guards.get(name) {
if !discs.contains(disc) {
discs.push(*disc);
}
let g = smt::eq_const(*tag, *disc);
guard = Some(match guard {
None => g,
Some(prev) => smt::and(prev, g),
});
}
}
}
(guard, discs.len())
}
fn const_value(&self, v: Var) -> Option<u64> {
smt::evaluate(v, |_| None)
}
fn record_range(&mut self, v: Var, lo: i128, hi: i128) {
let e = self.range.entry(v.0 .0).or_insert((lo, hi));
e.0 = e.0.min(lo);
e.1 = e.1.max(hi);
}
fn range_of(&self, v: Var) -> Option<(i128, i128)> {
self.range.get(&v.0 .0).copied()
}
fn unshared_const(&self, k: u64, w: u8) -> Var {
smt::truncate(smt::word(k, 64), w)
}
fn const_item(&self, name: &str, c: &Const) -> Result<(Var, Sign), SpecError> {
match c {
Const::UInt(n, ty) => match ty.as_ref().and_then(|t| t.width()) {
Some(1) => Ok((smt::word(*n as u64 & 1, 1), Sign::Literal)),
Some(w) if w <= 64 => {
let signed = ty.as_ref().map(Ty::is_signed).unwrap_or(false);
Ok((self.unshared_const(*n as u64, w), Sign::from_bool(signed)))
}
_ => Err(self.err(format!(
"the constant `{name}` has no bit-vector width, so it is not modelled"
))),
},
Const::Bool(b) => Ok((smt::word(u64::from(*b), 1), Sign::Literal)),
Const::Unit | Const::Str(_) | Const::Bytes(_) | Const::Other(_) => Err(self.err(format!(
"the constant `{name}` is not a literal, so its value is not known to the \
contract reader"
))),
}
}
fn span_has_name(&self, lo: usize, hi: usize) -> bool {
self.name_tokens.range(lo..hi).next().is_some()
}
fn record_range_union(&mut self, v: Var, a: Var, b: Var) {
let (mut lo, mut hi) = (i128::MAX, i128::MIN);
let mut any = false;
for x in [a, b] {
if let Some((l, h)) = self.range_of(x) {
lo = lo.min(l);
hi = hi.max(h);
any = true;
}
}
if any {
self.record_range(v, lo, hi);
}
}
fn record_const(&mut self, v: Var, signed: bool) {
if let Some(val) = self.const_value(v) {
let w = smt::bits(v);
let sv: i128 = if signed {
if w >= 64 {
val as i64 as i128
} else if val & (1u64 << (w - 1)) != 0 {
val as i128 - (1i128 << w)
} else {
val as i128
}
} else {
val as i128
};
self.record_range(v, sv, sv);
}
}
fn record_fold_result(&mut self, v: Var, a: Var, b: Var, sgn: Sign) {
self.record_range_union(v, a, b);
if !sgn.is_opaque() && self.const_value(v).is_some() {
self.record_const(v, sgn.eval());
}
}
fn record_negation(&mut self, nv: Var, operand: Var, bare: bool) {
if let Some((lo, hi)) = self.range_of(operand) {
if !bare {
self.record_range(nv, lo, hi);
}
self.record_range(nv, -hi, -lo);
}
}
fn check_range(&self, v: Var, wide: u8, signed: bool) -> Result<(), SpecError> {
let Some((lo, hi)) = self.range_of(v) else {
return Ok(());
};
let fits = |x: i128| {
if signed {
x >= -(1i128 << (wide - 1)) && x < (1i128 << (wide - 1))
} else {
x >= 0 && (x as u128) < (1u128 << wide)
}
};
if !fits(lo) || !fits(hi) {
let shown = if !fits(lo) { lo } else { hi };
return Err(self.err(format!(
"a constant value `{shown}` does not fit the operand's {wide}-bit {} type, so \
the shape is refused",
if signed { "signed" } else { "unsigned" }
)));
}
Ok(())
}
fn refuse_mixed_signedness(
&self,
l: Var,
ls: Sign,
r: Var,
rs: Sign,
) -> Result<(), SpecError> {
let (Some(lb), Some(rb)) = (ls.typed(), rs.typed()) else {
return Ok(());
};
if lb == rb {
return Ok(());
}
let lconst = self.const_value(l).is_some();
let rconst = self.const_value(r).is_some();
if !lconst && !rconst {
return Err(self.err("operands of different signedness cannot be combined"));
}
Err(self.err(
"a signed constant cannot be combined with an unsigned operand",
))
}
fn signed_value(&self, v: Var, sgn: bool) -> i128 {
let w = smt::bits(v);
let val = self.const_value(v).unwrap_or(0);
if !sgn {
return val as i128;
}
if w >= 64 {
val as i64 as i128
} else if val & (1u64 << (w - 1)) != 0 {
val as i128 - (1i128 << w)
} else {
val as i128
}
}
#[allow(clippy::too_many_arguments)]
fn fold_const_arith(
&self,
op: &str,
a: Var,
sa: Sign,
b: Var,
sb: Sign,
a_is_name: bool,
b_is_name: bool,
) -> Result<Option<(Var, Sign)>, SpecError> {
let (Some(_), Some(_)) = (self.const_value(a), self.const_value(b)) else {
return Ok(None);
};
if a_is_name || b_is_name {
return Ok(None);
}
let w = smt::bits(a);
let signed = sa.eval() || sb.eval();
let (va, vb) = (self.signed_value(a, sa.eval()), self.signed_value(b, sb.eval()));
let min = -(1i128 << (w - 1));
if matches!(op, "/" | "%") {
if signed && vb == -1 && va == min {
return Err(self.err(format!(
"a constant `{op}` overflows the {w}-bit signed operand width"
)));
}
return Ok(None);
}
if !matches!(op, "+" | "-" | "*") {
return Ok(None);
}
let r: i128 = match op {
"+" => va + vb,
"-" => va - vb,
_ => va * vb,
};
let untyped_opaque =
(sa.is_opaque() || sb.is_opaque()) && !sa.fixes_type() && !sb.fixes_type();
if untyped_opaque && (sa == Sign::NegLiteral || sb == Sign::NegLiteral) {
return Err(self.err(format!(
"a constant `{op}` of an untyped operand and a negated literal is \
sign-ambiguous: the negation is legal only at a signed type"
)));
}
let fits = if signed {
let hi = (1i128 << (w - 1)) - 1;
r >= min && r <= hi
} else {
r >= 0 && (r as u128) < (1u128 << w)
};
if untyped_opaque && fits {
let alt = !signed;
let (av, bv) = (self.signed_value(a, alt), self.signed_value(b, alt));
let ar: i128 = match op {
"+" => av + bv,
"-" => av - bv,
_ => av * bv,
};
let alt_fits = if alt {
ar >= min && ar < (1i128 << (w - 1))
} else {
ar >= 0 && (ar as u128) < (1u128 << w)
};
if !alt_fits {
return Err(self.err(format!(
"a constant `{op}` of an untyped operand is sign-ambiguous: it overflows the \
{w}-bit operand width under one reading and not the other"
)));
}
}
if fits {
return Ok(None);
}
if !signed && r < 0 {
return Err(self.err(format!(
"a constant expression underflows the {w}-bit unsigned operand width"
)));
}
let mut width = 1u8;
let mut holds = false;
while width <= 64 {
holds = if signed {
r >= -(1i128 << (width - 1)) && r < (1i128 << (width - 1))
} else {
(r as u128) < (1u128 << width)
};
if holds {
break;
}
width += 1;
}
if !holds {
return Err(self
.err("a constant expression is wider than the engine's 64-bit words"));
}
let out = if signed {
Sign::Signed
} else if sa == Sign::Unsigned || sb == Sign::Unsigned {
Sign::Unsigned
} else if sa.is_opaque() || sb.is_opaque() {
return Err(self.err(format!(
"a constant `{op}` of an untyped operand is width-dependent and overflows the \
{w}-bit operand width, so its value is not known where it is read"
)));
} else {
Sign::Literal
};
let mask = if width >= 64 { u64::MAX } else { (1u64 << width) - 1 };
Ok(Some((smt::word(r as u64 & mask, width), out)))
}
fn resize_const(
&self,
v: Var,
wide: u8,
signed: bool,
own: Sign,
) -> Result<Var, SpecError> {
let w = smt::bits(v);
let val = self.const_value(v).expect("resize_const is only called on a constant");
self.check_range(v, wide, signed)?;
if own.is_opaque() {
if wide > w {
return Err(self.err(
"a widening of an untyped constant is not modelled: its value depends on the \
operand's width, which is not known where it is read",
));
}
if let Some((lo, hi)) = own.opaque_operand() {
let (min, max) = if signed {
(-(1i128 << (wide - 1)), (1i128 << (wide - 1)) - 1)
} else {
(0, (1i128 << wide) - 1)
};
if lo < min || hi > max {
let shown = if lo < min { lo } else { hi };
return Err(self.err(format!(
"the complement of `{shown}` does not fit the operand's {wide}-bit \
{} type, so the shape is refused",
if signed { "signed" } else { "unsigned" }
)));
}
}
return Ok(if wide < w { smt::truncate(v, wide) } else { v });
}
let effective_signed = own.eval();
let sval: i128 = if effective_signed {
if w >= 64 {
val as i64 as i128
} else if val & (1u64 << (w - 1)) != 0 {
val as i128 - (1i128 << w)
} else {
val as i128
}
} else {
val as i128
};
let fits = if signed {
let lo = -(1i128 << (wide - 1));
let hi = (1i128 << (wide - 1)) - 1;
sval >= lo && sval <= hi
} else {
sval >= 0 && (sval as u128) < (1u128 << wide)
};
if !fits {
let shown: i128 = if effective_signed { sval } else { val as i128 };
return Err(self.err(format!(
"literal {shown} does not fit the operand's {wide}-bit width"
)));
}
if wide >= w {
Ok(if effective_signed && wide > w {
smt::sign_extend(v, wide)
} else {
smt::word(val, wide)
})
} else {
Ok(smt::truncate(v, wide))
}
}
fn align_widths(
&self,
a: Var,
sa: Sign,
b: Var,
sb: Sign,
signed: Sign,
) -> Result<(Var, Var), SpecError> {
let signed = signed.eval();
let (wa, wb) = (smt::bits(a), smt::bits(b));
let a_adapts = sa.adapts();
let b_adapts = sb.adapts();
let mismatch = || self.err("operands of different widths cannot be combined");
match (self.const_value(a), self.const_value(b)) {
(Some(_), Some(_)) => match (a_adapts, b_adapts) {
(true, false) => Ok((self.resize_const(a, wb, signed, sa)?, b)),
(false, true) => Ok((a, self.resize_const(b, wa, signed, sb)?)),
(false, false) => {
if wa == wb {
let a = self.resize_const(a, wa, signed, sa)?;
let b = self.resize_const(b, wb, signed, sb)?;
Ok((a, b))
} else {
Err(mismatch())
}
}
(true, true) => {
if wa > wb {
Ok((self.resize_const(a, wb, signed, sa)?, b))
} else if wb > wa {
Ok((a, self.resize_const(b, wa, signed, sb)?))
} else {
let a = self.resize_const(a, wa, signed, sa)?;
let b = self.resize_const(b, wb, signed, sb)?;
Ok((a, b))
}
}
},
(Some(_), None) => {
if a_adapts || wa == wb {
Ok((self.resize_const(a, wb, signed, sa)?, b))
} else {
Err(mismatch())
}
}
(None, Some(_)) => {
if b_adapts || wa == wb {
Ok((a, self.resize_const(b, wa, signed, sb)?))
} else {
Err(mismatch())
}
}
(None, None) => {
if wa == wb {
Ok((a, b))
} else {
Err(mismatch())
}
}
}
}
fn parse_cmp(&mut self) -> Result<Pred, SpecError> {
if let Some(Tok::Ident(n)) = self.peek() {
if n == "true" || n == "false" {
let v = n == "true";
self.pos += 1;
return Ok(smt::truth(v));
}
}
if let Some(p) = self.try_ret_variant_method()? {
return Ok(p);
}
if self.bang_is_predicate() && self.eat_op("!") {
let start = self.pos;
let saved = self.in_negation;
self.in_negation = true;
let inner = self.parse_cmp();
self.in_negation = saved;
let inner = inner?;
let negated = smt::not(inner);
let (guard, distinct) = self.ret_payload_guard_for(start, self.pos);
if distinct > 1 {
return Err(self.err(
"a negated clause names payloads of more than one variant, which \
has no single scope",
));
}
return Ok(match guard {
Some(g) => smt::implies(g, negated),
None => negated,
});
}
if matches!(self.peek(), Some(Tok::Op(o)) if o == "(") && self.paren_is_predicate() {
let group_start = self.pos;
self.pos += 1;
let inner = self.parse_or()?;
if !self.eat_op(")") {
return Err(self.err("missing `)`"));
}
self.guarded_groups.push((group_start, self.pos));
return Ok(inner);
}
let (left, ls) = self.parse_expr()?;
for op in ["==", "!=", "<=", ">=", "<", ">"] {
if self.eat_op(op) {
let (right, rs) = self.parse_expr()?;
let signed = match Sign::resolve(ls, rs) {
Some(b) => b,
None => {
if ls.ambiguous() || rs.ambiguous() {
return Err(self.err(
"a comparison with no typed operand is sign-ambiguous: an untyped \
constant reads differently as signed and as unsigned",
));
}
false
}
};
self.refuse_mixed_signedness(left, ls, right, rs)?;
let (left, right) =
self.align_widths(left, ls, right, rs, Sign::from_bool(signed))?;
return Ok(match op {
"==" => smt::eq(left, right),
"!=" => smt::not(smt::eq(left, right)),
"<=" if signed => smt::sle(left, right),
">=" if signed => smt::sge(left, right),
"<" if signed => smt::slt(left, right),
">" if signed => smt::sgt(left, right),
"<=" => smt::ule(left, right),
">=" => smt::ule(right, left),
"<" => smt::ult(left, right),
">" => smt::ult(right, left),
_ => unreachable!(),
});
}
}
if smt::bits(left) == 1 {
return Ok(smt::not(smt::eq_const(left, 0)));
}
Err(self.err("expected a comparison operator"))
}
fn parse_expr(&mut self) -> Result<(Var, Sign), SpecError> {
self.parse_bitor()
}
fn parse_bitor(&mut self) -> Result<(Var, Sign), SpecError> {
let (mut left, mut sgn) = self.parse_bitxor()?;
while self.eat_op("|") {
let (r, rs) = self.parse_bitxor()?;
self.refuse_mixed_signedness(left, sgn, r, rs)?;
let (pl, pr) = (left, r);
let (l, r) = self.align_widths(left, sgn, r, rs, Sign::combine(sgn, rs))?;
left = smt::bor(l, r);
self.record_range_union(left, pl, pr);
sgn = Sign::combine(sgn, rs);
}
Ok((left, sgn))
}
fn parse_bitxor(&mut self) -> Result<(Var, Sign), SpecError> {
let (mut left, mut sgn) = self.parse_bitand()?;
while self.eat_op("^") {
let (r, rs) = self.parse_bitand()?;
self.refuse_mixed_signedness(left, sgn, r, rs)?;
let (pl, pr) = (left, r);
let (l, r) = self.align_widths(left, sgn, r, rs, Sign::combine(sgn, rs))?;
left = smt::bxor(l, r);
self.record_range_union(left, pl, pr);
sgn = Sign::combine(sgn, rs);
}
Ok((left, sgn))
}
fn parse_bitand(&mut self) -> Result<(Var, Sign), SpecError> {
let (mut left, mut sgn) = self.parse_shift()?;
while self.eat_op("&") {
let (r, rs) = self.parse_shift()?;
self.refuse_mixed_signedness(left, sgn, r, rs)?;
let (pl, pr) = (left, r);
let (l, r) = self.align_widths(left, sgn, r, rs, Sign::combine(sgn, rs))?;
left = smt::band(l, r);
self.record_range_union(left, pl, pr);
sgn = Sign::combine(sgn, rs);
if self.const_value(left).is_some()
&& (sgn == Sign::Literal || rs == Sign::Literal)
&& Sign::combine(sgn, rs).typed().is_none()
{
if let Some((lo, hi)) = Sign::union_env(sgn.opaque_operand(), rs.opaque_operand()) {
self.record_range(left, lo, hi);
}
sgn = Sign::Literal;
}
}
Ok((left, sgn))
}
fn amount_width(&self) -> u8 {
match self.scan_amount_add(self.pos).0 {
0 => 32,
w => w,
}
}
fn scan_amount_add(&self, mut i: usize) -> (u8, usize) {
loop {
let (w, j) = self.scan_amount_mul(i);
if w != 0 {
return (w, j);
}
i = j;
match self.toks.get(i) {
Some(Tok::Op(o)) if o == "+" || o == "-" => i += 1,
_ => return (0, i),
}
}
}
fn scan_amount_mul(&self, mut i: usize) -> (u8, usize) {
loop {
let (w, j) = self.scan_amount_atom(i);
if w != 0 {
return (w, j);
}
i = j;
match self.toks.get(i) {
Some(Tok::Op(o)) if o == "*" || o == "/" || o == "%" => i += 1,
_ => return (0, i),
}
}
}
fn scan_amount_atom(&self, i: usize) -> (u8, usize) {
let mut i = i;
while matches!(self.toks.get(i), Some(Tok::Op(o)) if o == "-" || o == "!") {
i += 1;
}
let (mut w, mut j) = match self.toks.get(i) {
Some(Tok::Num(_, Some((w, _)))) => (u8::min(*w, 64), i + 1),
Some(Tok::Op(o)) if o == "(" => (self.scan_amount_add(i + 1).0, self.after_paren(i)),
_ => (0, i + 1),
};
if matches!(self.toks.get(j), Some(Tok::Ident(n)) if n == "as") {
if let Some(Tok::Ident(ty)) = self.toks.get(j + 1) {
if let Some(cw) = Ty::parse(ty).width() {
w = cw.min(64);
j += 2;
}
}
}
(w, j)
}
fn after_paren(&self, i: usize) -> usize {
let mut depth = 0usize;
let mut j = i;
while let Some(t) = self.toks.get(j) {
match t {
Tok::Op(o) if o == "(" => depth += 1,
Tok::Op(o) if o == ")" => {
depth -= 1;
if depth == 0 {
return j + 1;
}
}
_ => {}
}
j += 1;
}
j
}
fn parse_shift(&mut self) -> Result<(Var, Sign), SpecError> {
let (mut left, sgn) = self.parse_add()?;
while let Some(op) = self.eat_any(&["<<", ">>"]) {
let saved = self.amount_floor;
self.amount_floor = if saved == 0 { self.amount_width() } else { saved };
let amount = self.parse_add();
self.amount_floor = saved;
let (r, rs) = amount?;
if rs.is_opaque() {
return Err(self.err(
"a shift amount that is an untyped complement is not modelled: its value \
depends on the operand's width",
));
}
let Some(k) = self.const_value(r) else {
return Err(self.err("a shift amount in a contract must be a constant"));
};
let base = left;
let w = smt::bits(left);
if k >= w as u64 {
return Err(self.err(format!(
"shift amount {k} is not below the operand width {w}"
)));
}
if !sgn.fixes_type() {
if k >= 8 {
return Err(self.err(format!(
"a shift of an untyped constant by {k} is refused: the operand's width is \
inferred from where the result is read, and {k} is not below the \
narrowest width"
)));
}
if matches!(sgn, Sign::Literal | Sign::NegLiteral) {
let sval = self.signed_value(left, sgn.eval());
if !(-128..=127).contains(&sval) {
return Err(self.err(format!(
"a shift of an untyped constant {sval} is refused: the operand's width \
is inferred from where the result is read, and {sval} does not fit \
the narrowest width"
)));
}
}
}
left = if op == "<<" {
smt::shl(left, k as u32)
} else if k == 0 {
left
} else {
match sgn {
Sign::Signed | Sign::NegLiteral => smt::ashr(left, k as u32),
Sign::Unsigned | Sign::Literal => smt::lshr(left, k as u32),
Sign::Opaque(_) => {
return Err(self.err(
"a right shift with no typed operand is sign-ambiguous: it reads \
differently as an arithmetic and as a logical shift",
))
}
}
};
self.record_range_union(left, base, base);
}
Ok((left, sgn))
}
fn parse_add(&mut self) -> Result<(Var, Sign), SpecError> {
let start = self.pos;
let (mut left, mut sgn) = self.parse_mul()?;
let mut left_is_name = self.span_has_name(start, self.pos);
while let Some(op) = self.eat_any(&["+", "-"]) {
let op_start = self.pos - 1;
let (r, rs) = self.parse_mul()?;
let r_is_name = self.span_has_name(op_start + 1, self.pos);
self.refuse_mixed_signedness(left, sgn, r, rs)?;
let (pl, pr) = (left, r);
let (l, r) = self.align_widths(left, sgn, r, rs, Sign::combine(sgn, rs))?;
if let Some((v, s)) =
self.fold_const_arith(op, l, sgn, r, rs, left_is_name, r_is_name)?
{
self.record_fold_result(v, pl, pr, s);
left = v;
sgn = s;
left_is_name = left_is_name || r_is_name;
continue;
}
left = if op == "+" { smt::add(l, r) } else { smt::sub(l, r) };
self.record_fold_result(left, pl, pr, Sign::combine(sgn, rs));
sgn = Sign::combine(sgn, rs);
left_is_name = left_is_name || r_is_name;
}
Ok((left, sgn))
}
fn parse_mul(&mut self) -> Result<(Var, Sign), SpecError> {
let start = self.pos;
let (mut left, mut sgn) = self.parse_cast()?;
let mut left_is_name = self.span_has_name(start, self.pos);
while let Some(op) = self.eat_any(&["*", "/", "%"]) {
let op_start = self.pos - 1;
let (r, rs) = self.parse_cast()?;
let r_is_name = self.span_has_name(op_start + 1, self.pos);
if op != "*" && self.const_value(r) == Some(0) {
return Err(self.err("a division or remainder by a constant zero"));
}
self.refuse_mixed_signedness(left, sgn, r, rs)?;
if op != "*" && Sign::resolve(sgn, rs).is_none() && (sgn.ambiguous() || rs.ambiguous())
{
return Err(self.err(
"a `/` or `%` with no typed operand is sign-ambiguous: it reads differently \
as signed and as unsigned",
));
}
let (pl, pr) = (left, r);
let (l, r) = self.align_widths(left, sgn, r, rs, Sign::combine(sgn, rs))?;
if let Some((v, s)) =
self.fold_const_arith(op, l, sgn, r, rs, left_is_name, r_is_name)?
{
self.record_fold_result(v, pl, pr, s);
left = v;
sgn = s;
left_is_name = left_is_name || r_is_name;
continue;
}
let signed = sgn.eval() || rs.eval();
left = match op {
"*" => smt::mul(l, r),
"/" if signed => smt::sdiv(l, r),
"/" => smt::udiv(l, r),
"%" if signed => smt::srem(l, r),
_ => smt::urem(l, r),
};
self.record_fold_result(left, pl, pr, Sign::combine(sgn, rs));
sgn = Sign::combine(sgn, rs);
left_is_name = left_is_name || r_is_name;
}
Ok((left, sgn))
}
fn eat_any<'b>(&mut self, ops: &[&'b str]) -> Option<&'b str> {
if let Some(Tok::Op(o)) = self.peek() {
for op in ops {
if o == op {
self.pos += 1;
return Some(op);
}
}
}
None
}
fn parse_cast(&mut self) -> Result<(Var, Sign), SpecError> {
let (v, sgn) = self.parse_neg()?;
self.cast_chain(v, sgn)
}
fn parse_neg(&mut self) -> Result<(Var, Sign), SpecError> {
if self.eat_op("*") {
let Some(Tok::Ident(inner)) = self.peek().cloned() else {
return Err(self.err("`*` must be applied to a name"));
};
self.pos += 1;
self.name_tokens.insert(self.pos - 1);
let v = *self
.args
.get(&inner)
.ok_or_else(|| self.err(format!("unknown name `{inner}`")))?;
return Ok((v, Sign::from_bool(self.is_signed_name(&inner))));
}
if self.eat_op("-") {
let (v, sgn) = self.parse_neg()?;
if sgn == Sign::Unsigned {
return Err(self.err("cannot apply unary `-` to an unsigned operand"));
}
let w = smt::bits(v);
let out = if sgn == Sign::Literal { Sign::NegLiteral } else { Sign::Signed };
let bare = self.bare_literals.contains(&v.0 .0);
if let Some(mag) = self.const_value(v) {
let fits = w >= 64 || mag <= (1u64 << (w - 1));
if !fits {
let nv = smt::sub(smt::word(0, w + 1), smt::word(mag, w + 1));
self.record_negation(nv, v, true);
return Ok((nv, out));
}
if !bare {
let sval: i128 = if w >= 64 {
mag as i64 as i128
} else if mag & (1u64 << (w - 1)) != 0 {
mag as i128 - (1i128 << w)
} else {
mag as i128
};
let fits_neg = if w >= 64 {
sval != i64::MIN as i128
} else {
sval > -(1i128 << (w - 1))
};
if !fits_neg {
return Err(self.err(
"negating a signed constant at its own type is out of range, so the \
shape is refused",
));
}
}
}
let nv = smt::sub(smt::word(0, w), v);
self.record_negation(nv, v, bare);
if let Some((lo, hi)) = sgn.opaque_operand() {
self.record_range(nv, lo, hi);
}
return Ok((nv, out));
}
if self.eat_op("!") {
let (v, sgn) = self.parse_neg()?;
if sgn.typed().is_some() {
let w = smt::bits(v);
return Ok((smt::bxor(v, smt::all_ones(w)), sgn));
}
if self.const_value(v).is_some() {
let val = self.const_value(v).expect("checked above");
let w = smt::bits(v);
let mask = if w >= 64 { u64::MAX } else { (1u64 << w) - 1 };
let operand = match sgn {
Sign::Literal | Sign::NegLiteral => self.range_of(v),
Sign::Opaque(env) => Sign::union_env(env, self.range_of(v)),
_ => None,
};
let cv = smt::word(!val & mask, w);
return Ok((cv, Sign::Opaque(operand)));
}
let w = smt::bits(v);
let cv = smt::bxor(v, smt::all_ones(w));
self.record_range_union(cv, v, v);
return Ok((cv, sgn));
}
self.parse_atom()
}
fn parse_atom(&mut self) -> Result<(Var, Sign), SpecError> {
let (v, s) = self.parse_primary()?;
self.parse_wrapping_postfix(v, s)
}
fn parse_wrapping_postfix(&mut self, v: Var, sgn: Sign) -> Result<(Var, Sign), SpecError> {
let (mut v, mut sgn) = (v, sgn);
loop {
if !matches!(self.peek(), Some(Tok::Op(o)) if o == ".") {
return Ok((v, sgn));
}
let Some(Tok::Ident(name)) = self.toks.get(self.pos + 1).cloned() else {
return Ok((v, sgn));
};
let takes_arg = match name.as_str() {
"wrapping_add" | "wrapping_sub" | "wrapping_mul" => true,
"wrapping_neg" => false,
_ => return Ok((v, sgn)),
};
if !sgn.fixes_type() {
return Err(self.err(format!(
"`{name}` needs a receiver whose integer type is known; a bare literal is an \
ambiguous `{{integer}}` in Rust"
)));
}
self.pos += 2;
if !self.eat_op("(") {
return Err(self.err(format!("`{name}` is a call: write `{name}(..)`")));
}
let (r, rs) = if takes_arg {
self.parse_expr()?
} else {
(v, sgn)
};
if !self.eat_op(")") {
return Err(self.err(format!("`{name}` is missing its closing `)`")));
}
let out = Sign::combine(sgn, rs);
let (l, r) = self.align_widths(v, sgn, r, rs, out)?;
v = match name.as_str() {
"wrapping_add" => smt::add(l, r),
"wrapping_sub" => smt::sub(l, r),
"wrapping_mul" => smt::mul(l, r),
_ => smt::sub(smt::word(0, smt::bits(l)), l),
};
self.record_fold_result(v, l, r, out);
sgn = out;
}
}
fn parse_primary(&mut self) -> Result<(Var, Sign), SpecError> {
match self.peek().cloned() {
Some(Tok::Num(n, suffix)) => {
self.pos += 1;
if let Some((w, signed)) = suffix {
if w > 64 {
return Err(self.err(format!(
"a `{w}`-bit type suffix is wider than the engine's 64-bit words, so \
a literal of that type is not modelled"
)));
}
let max = if signed {
1u128 << (w - 1)
} else {
(1u128 << w) - 1
};
if u128::from(n) > max {
return Err(self.err(format!(
"literal `{n}` is out of range for its `{}` type suffix",
if signed { "i" } else { "u" }
)));
}
let sign = if signed { Sign::Signed } else { Sign::Unsigned };
let v = smt::word(n, w);
let mag = i128::from(n);
self.record_range(v, mag, mag);
self.bare_literals.insert(v.0 .0);
return Ok((v, sign));
}
let need = (u64::BITS - n.leading_zeros()).max(1) as u8;
let scope = self
.args
.values()
.chain(self.ret.iter())
.map(|v| smt::bits(*v))
.max()
.unwrap_or(64);
let w = scope.max(need).max(self.amount_floor).min(64);
let v = smt::word(n, w);
self.record_const(v, false);
self.bare_literals.insert(v.0 .0);
Ok((v, Sign::Literal))
}
Some(Tok::Char(c)) => {
self.pos += 1;
let v = smt::word(u64::from(c), 32);
self.record_const(v, false);
Ok((v, Sign::Unsigned))
}
Some(Tok::Ident(name)) => {
self.pos += 1;
if name == "ret" || name == "result" {
self.name_tokens.insert(self.pos - 1);
let v = self.ret.ok_or_else(|| self.err(self.ret_absent))?;
if matches!(self.peek(), Some(Tok::Op(o)) if o == ".") {
let field = match self.toks.get(self.pos + 1) {
Some(Tok::Ident(f)) => f.clone(),
Some(Tok::Num(n, _)) => n.to_string(),
_ => String::new(),
};
return Err(self.err(format!(
"the return type has no component or variant `{field}` to read"
)));
}
return Ok((v, Sign::from_bool(self.ret_signed)));
}
if name == "true" || name == "false" {
return Ok((smt::word(u64::from(name == "true"), 1), Sign::Literal));
}
if name == "old" && matches!(self.peek(), Some(Tok::Op(o)) if o == "(") {
self.name_tokens.insert(self.pos - 1);
self.pos += 1;
self.eat_op("*");
let Some(Tok::Ident(inner)) = self.peek().cloned() else {
return Err(self.err("`old(...)` must name a variable"));
};
self.pos += 1;
self.name_tokens.insert(self.pos - 1);
if !self.eat_op(")") {
return Err(self.err("`old(...)` takes a single name"));
}
let Some(v) = self.old_args.get(&inner).copied() else {
return Err(self.err(format!(
"`old({inner})` is not a reference argument, so its entry value \
is not tracked"
)));
};
return Ok((v, Sign::from_bool(self.is_signed_name(&inner))));
}
let assoc = if let Some((ty, a)) = name.split_once("::") {
Some((ty.to_string(), a.to_string()))
} else if matches!(self.peek(), Some(Tok::Op(o)) if o == ":") {
let mut it = self.toks[self.pos..].iter();
match (it.next(), it.next(), it.next()) {
(Some(Tok::Op(c1)), Some(Tok::Op(c2)), Some(Tok::Ident(a)))
if c1 == ":" && c2 == ":" =>
{
let a = a.clone();
self.pos += 3;
Some((name.clone(), a))
}
_ => None,
}
} else {
None
};
if let Some((ty, a)) = assoc {
let key = format!("{ty}::{a}");
if let Some((k, w)) = self.variant_consts.get(&key).copied() {
return Ok((self.unshared_const(k, w), Sign::Literal));
}
if self.enum_args.contains(&ty) {
return Err(self.err(format!(
"`{ty}` has no variant `{a}` (or its layout was not readable)"
)));
}
if let Some(c) = self.consts.get(&format!("{ty}::{a}")) {
let key = format!("{ty}::{a}");
let c = c.clone();
return self.const_item(&key, &c);
}
if let Some((k, w)) = type_bound(&ty, &a) {
return Ok((self.unshared_const(k, w), Sign::from_bool(ty.starts_with('i'))));
}
return Err(self.err(format!("unknown constant `{ty}::{a}`")));
}
if let Some(v) = self.args.get(&name).copied() {
self.name_tokens.insert(self.pos - 1);
let s = self.is_signed_name(&name);
return Ok((v, Sign::from_bool(s)));
}
if let Some(c) = self.consts.get(&name) {
let c = c.clone();
return self.const_item(&name, &c);
}
Err(self.err(format!("unknown name `{name}` (not an argument)")))
}
Some(Tok::Op(o)) if o == "(" => {
let is_pred = self.paren_is_predicate();
self.pos += 1;
if is_pred {
let group_start = self.pos - 1;
let p = self.parse_or()?;
if !self.eat_op(")") {
return Err(self.err("missing `)`"));
}
self.guarded_groups.push((group_start, self.pos));
return Ok((smt::ite(p, smt::word(1, 1), smt::word(0, 1)), Sign::Unsigned));
}
let (v, s) = self.parse_expr()?;
if !self.eat_op(")") {
return Err(self.err("missing `)`"));
}
Ok((v, s))
}
Some(Tok::BadNum) => {
Err(self.err("a numeric literal that is not an exact integer (bad digit for its radix, or past u64)"))
}
Some(Tok::BadChar) => {
Err(self.err("a character literal that is not an exact Unicode scalar value (an unknown escape, a multi-character literal, or a missing quote)"))
}
Some(t) => Err(self.err(format!("unexpected token {t:?}"))),
None => Err(self.err("unexpected end of contract")),
}
}
fn cast_chain(&mut self, v: Var, sgn: Sign) -> Result<(Var, Sign), SpecError> {
let (mut v, mut sgn) = (v, sgn);
while matches!(self.peek(), Some(Tok::Ident(n)) if n == "as") {
let Some(Tok::Ident(ty_name)) = self.toks.get(self.pos + 1).cloned() else {
break;
};
let ty = Ty::parse(&ty_name);
let Some(w) = ty.width() else {
break;
};
if w > 64 {
return Err(self.err(format!(
"`{ty_name}` is wider than the engine's 64-bit words, so a cast to it is not \
modelled"
)));
}
self.pos += 2;
let src_signed = if sgn.ambiguous() {
if w > smt::bits(v) {
return Err(self.err(
"a widening cast of a sign-ambiguous constant is not modelled: it would \
have to guess whether to sign-extend or zero-fill",
));
}
false
} else {
sgn.eval()
};
v = if src_signed { smt::sign_extend(v, w) } else { smt::truncate(v, w) };
sgn = Sign::from_bool(ty.is_signed());
}
Ok((v, sgn))
}
}
enum StructHead {
Named { name: String, closed_inline: bool },
Tuple { name: String, fields: Vec<(String, String)> },
Unit { name: String },
}
pub(crate) fn struct_lookup<'a>(
structs: &'a BTreeMap<String, StructDef>,
name: &str,
) -> Option<&'a StructDef> {
if let Some(def) = structs.get(name) {
return Some(def);
}
let no_generics = name.split('<').next().unwrap_or(name);
if let Some(def) = structs.get(no_generics) {
return Some(def);
}
if no_generics.contains("::") {
return None;
}
structs.get(no_generics)
}
fn struct_head(line: &str) -> Option<StructHead> {
let t = line.trim_start_matches("pub(crate) ").trim_start_matches("pub ").trim();
let rest = t.strip_prefix("struct ")?;
let name = rest.split(|c: char| c == '{' || c == '(' || c == '<' || c == ';' || c.is_whitespace()).next()?;
if name.is_empty() {
return None;
}
if let Some(open) = rest.find('(') {
let brace = rest.find('{');
if brace.is_none() || open < brace.unwrap() {
let close = rest[open + 1..].find(')')? + open + 1;
let inner = &rest[open + 1..close];
let fields = split_top_level(inner, ',')
.into_iter()
.enumerate()
.filter_map(|(i, f)| {
let f = f.trim();
if f.is_empty() {
return None;
}
let f = f.trim_start_matches("pub(crate) ").trim_start_matches("pub ").trim();
Some((i.to_string(), f.to_string()))
})
.collect();
return Some(StructHead::Tuple { name: name.to_string(), fields });
}
}
let Some(open) = rest.find('{') else {
if rest.trim_end().ends_with(';') {
return Some(StructHead::Unit { name: name.to_string() });
}
return None;
};
let closed_inline = rest[open + 1..].contains('}');
Some(StructHead::Named { name: name.to_string(), closed_inline })
}
fn struct_field(line: &str) -> Option<(String, String)> {
let t = line.trim();
if t.is_empty() || t.starts_with("//") || t.starts_with('#') {
return None;
}
let t = t.trim_start_matches("pub(crate) ").trim_start_matches("pub ").trim();
let (name, ty) = t.split_once(':')?;
let name = name.trim();
if name.is_empty() || !name.chars().all(|c| c.is_alphanumeric() || c == '_') {
return None;
}
let ty = ty.split(',').next().unwrap_or(ty).trim();
if ty.is_empty() {
return None;
}
Some((name.to_string(), ty.to_string()))
}
enum EnumHead {
Inline(Vec<(String, Vec<Ty>, u64)>),
MultiLine,
Refused,
}
fn enum_head(line: &str) -> Option<(String, EnumHead)> {
let t = line.trim_start_matches("pub(crate) ").trim_start_matches("pub ").trim();
let rest = t.strip_prefix("enum ")?;
let name = rest.split(|c: char| c == '{' || c == '<' || c.is_whitespace()).next()?;
if name.is_empty() {
return None;
}
let open = rest.find('{')?;
let after = &rest[open + 1..];
if let Some(close) = after.rfind('}') {
let inner = &after[..close];
let mut def = EnumDef::default();
for v in split_top_level(inner, ',') {
match enum_variant(&v) {
VariantLine::Variant { name, payload, explicit } => {
push_variant(&mut def, name, payload, explicit);
}
VariantLine::NotAVariant => {}
VariantLine::UnreadableDiscriminant => {
return Some((name.to_string(), EnumHead::Refused))
}
}
}
return Some((name.to_string(), EnumHead::Inline(def.variants)));
}
if !after.trim().is_empty() {
return None;
}
Some((name.to_string(), EnumHead::MultiLine))
}
enum VariantLine {
Variant {
name: String,
payload: Vec<Ty>,
explicit: Option<u64>,
},
NotAVariant,
UnreadableDiscriminant,
}
fn enum_variant(line: &str) -> VariantLine {
let line = strip_line_comment(line);
let t = line.trim().trim_end_matches(',').trim();
if t.is_empty() || t.starts_with("//") || t.starts_with('#') || t.starts_with("}") {
return VariantLine::NotAVariant;
}
let t = t.trim_start_matches("pub(crate) ").trim_start_matches("pub ").trim();
let name: String = t.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
if name.is_empty() || !name.chars().next().map(|c| c.is_alphabetic() || c == '_').unwrap_or(false)
{
return VariantLine::NotAVariant;
}
let after = t[name.len()..].trim_start();
let (payload, rest) = if after.is_empty() {
(Vec::new(), "")
} else if let Some(inner_rest) = after.strip_prefix('(') {
let Some(close) = inner_rest.find(')') else { return VariantLine::NotAVariant };
let inner = inner_rest[..close].trim();
let tys = if inner.is_empty() {
Vec::new()
} else {
split_top_level(inner, ',').iter().map(|t| Ty::parse(t.trim())).collect()
};
(tys, inner_rest[close + 1..].trim_start())
} else if after.starts_with('{') {
let Some(close) = after.rfind('}') else { return VariantLine::NotAVariant };
(Vec::new(), after[close + 1..].trim_start())
} else if after.starts_with('=') {
(Vec::new(), after)
} else {
return VariantLine::NotAVariant;
};
if rest.is_empty() {
return VariantLine::Variant { name, payload, explicit: None };
}
let Some(expr) = rest.strip_prefix('=') else { return VariantLine::NotAVariant };
match parse_discriminant_literal(expr) {
Some(d) => VariantLine::Variant { name, payload, explicit: Some(d) },
None => VariantLine::UnreadableDiscriminant,
}
}
fn parse_discriminant_literal(s: &str) -> Option<u64> {
let s = s.trim().trim_end_matches(';').trim();
if s.is_empty() {
return None;
}
if s.starts_with('-') {
return None;
}
let body = strip_int_suffix(s);
let (radix, digits) = if let Some(r) = body.strip_prefix("0x").or_else(|| body.strip_prefix("0X")) {
(16u32, r)
} else if let Some(r) = body.strip_prefix("0b").or_else(|| body.strip_prefix("0B")) {
(2, r)
} else if let Some(r) = body.strip_prefix("0o").or_else(|| body.strip_prefix("0O")) {
(8, r)
} else {
(10, body)
};
let mut seen = false;
for c in digits.chars() {
if c == '_' {
continue;
}
if !c.is_digit(radix) {
return None;
}
seen = true;
}
if !seen {
return None;
}
let digits: String = digits.chars().filter(|c| *c != '_').collect();
u64::from_str_radix(&digits, radix).ok()
}
fn strip_line_comment(line: &str) -> &str {
let bytes = line.as_bytes();
let mut i = 0;
let mut in_str = false;
let mut in_char = false;
while i < bytes.len() {
let c = bytes[i];
if in_str {
if c == b'\\' {
i += 2;
continue;
}
if c == b'"' {
in_str = false;
}
} else if in_char {
if c == b'\\' {
i += 2;
continue;
}
if c == b'\'' {
in_char = false;
}
} else if c == b'"' {
in_str = true;
} else if c == b'\'' {
in_char = true;
} else if c == b'/' && bytes.get(i + 1) == Some(&b'/') {
return &line[..i];
}
i += 1;
}
line
}
fn strip_int_suffix(s: &str) -> &str {
for suf in [
"i8", "i16", "i32", "i64", "i128", "isize", "u8", "u16", "u32", "u64", "u128", "usize",
] {
if let Some(head) = s.strip_suffix(suf) {
return head.trim_end_matches('_');
}
}
s
}
fn push_variant(def: &mut EnumDef, name: String, payload: Vec<Ty>, explicit: Option<u64>) {
let d = match explicit {
Some(d) => d,
None => def.variants.last().map(|(_, _, d)| d + 1).unwrap_or(0),
};
def.variants.push((name, payload, d));
}
pub fn std_enum_def(name: &str) -> Option<EnumDef> {
let name = name.trim();
let inner = |head: &str| -> Option<String> {
let rest = name.strip_prefix(head)?.trim_start();
if !rest.starts_with('<') {
return None;
}
let close = {
let mut d = 0i32;
let mut end = None;
for (i, c) in rest.char_indices() {
match c {
'<' => d += 1,
'>' => {
d -= 1;
if d == 0 {
end = Some(i);
break;
}
}
_ => {}
}
}
end?
};
let args = &rest[1..close];
if !rest[close + 1..].trim().is_empty() {
return None;
}
Some(args.to_string())
};
let variant = |vname: &str, payload: Vec<Ty>, d: u64| (vname.to_string(), payload, d);
if let Some(args) = inner("Option") {
let t = Ty::parse(args.trim());
return Some(EnumDef {
variants: vec![variant("None", vec![], 0), variant("Some", vec![t], 1)],
});
}
if let Some(args) = inner("Result") {
let parts = split_top_level(&args, ',');
if parts.len() != 2 {
return None;
}
let ok = Ty::parse(parts[0].trim());
let err = Ty::parse(parts[1].trim());
return Some(EnumDef {
variants: vec![variant("Ok", vec![ok], 0), variant("Err", vec![err], 1)],
});
}
None
}
pub fn enum_ret_discriminants(
ret_ty: &Ty,
enums: &BTreeMap<String, EnumDef>,
) -> Option<(u64, u64)> {
let def = ret_enum_def(ret_ty, enums)?;
let find = |n: &str| def.variants.iter().find(|(vn, _, _)| vn == n).map(|(_, _, d)| *d);
let ok = find("Ok").or_else(|| find("Some"))?;
let err = find("Err").or_else(|| find("None"))?;
Some((ok, err))
}
pub fn ret_enum_def(ret_ty: &Ty, enums: &BTreeMap<String, EnumDef>) -> Option<EnumDef> {
let Ty::Other(name) = ret_ty else { return None };
let bare = strip_generics(name);
let segs: Vec<&str> = bare.split("::").filter(|s| !s.is_empty()).collect();
let short = segs.last().copied().unwrap_or(&bare);
if let Some(def) = enums.get(short).or_else(|| enums.get(&bare)) {
return Some(def.clone());
}
std_enum_def(&name.trim().replace("::<", "<"))
}
fn names_ret_variant(text: &str, vname: &str) -> bool {
let chars: Vec<char> = text.chars().collect();
let mut i = 0;
while i < chars.len() {
if chars[i].is_alphabetic() || chars[i] == '_' {
let start = i;
while i < chars.len() && (chars[i].is_alphanumeric() || chars[i] == '_') {
i += 1;
}
let ident: String = chars[start..i].iter().collect();
if (ident == "ret" || ident == "result") && chars.get(i) == Some(&'.') {
let j = i + 1;
let mut k = j;
while k < chars.len() && (chars[k].is_alphanumeric() || chars[k] == '_') {
k += 1;
}
let field: String = chars[j..k].iter().collect();
if field == vname {
return true;
}
}
continue;
}
i += 1;
}
false
}
pub fn bind_ret_payloads(
fields: &mut FieldEnv,
ret_ty: &Ty,
enums: &BTreeMap<String, EnumDef>,
tag: Var,
projs: &[(u64, Var)],
ensures: &[String],
) {
let Some(def) = ret_enum_def(ret_ty, enums) else { return };
for (vname, payload, disc) in &def.variants {
let Some(first) = payload.first() else { continue };
if first.width().is_none() {
continue;
}
if !ensures.iter().any(|e| names_ret_variant(e, vname)) {
continue;
}
if let Some((_, v)) = projs.iter().find(|(k, _)| k == disc) {
fields.bind_ret_payload(vname, *v, tag, *disc, first.is_signed());
}
}
}
fn strip_generics(s: &str) -> String {
crate::mir::parse::strip_generics(s)
}
pub fn field_env(
f: &crate::mir::parse::MirFn,
structs: &BTreeMap<String, StructDef>,
enums: &BTreeMap<String, EnumDef>,
) -> FieldEnv {
field_env_named(f, None, structs, enums)
}
pub fn field_env_named(
f: &crate::mir::parse::MirFn,
rename: Option<&ArgRename>,
structs: &BTreeMap<String, StructDef>,
enums: &BTreeMap<String, EnumDef>,
) -> FieldEnv {
let contract_name = |l: crate::mir::parse::LocalIdx| -> String {
rename
.and_then(|r| r.name_of(l))
.map(|s| s.to_string())
.unwrap_or_else(|| f.name_of(l))
};
let mut env =
FieldEnv { base: f.locals.keys().max().map(|m| m + 1).unwrap_or(0), ..Default::default() };
for &l in &f.arg_locals {
env.declared.insert(contract_name(l));
}
for &l in &f.arg_locals {
let Some(ty) = f.ty_of(l) else { continue };
let base = match ty {
Ty::Ref(inner) => inner.as_ref(),
other => other,
};
let arg = contract_name(l);
if let Ty::Slice(elem) = base {
match elem.width() {
Some(w) => {
env.bind_indexed_len(l, &arg, w, elem.is_signed());
}
None => {
env.bind_indexed_len(l, &arg, 0, false);
}
}
continue;
}
if let Ty::Array(elem, n) = base {
if let Some(w) = elem.width() {
env.bind_array_len(l, &arg, w, elem.is_signed(), *n);
}
continue;
}
let Ty::Other(name) = base else { continue };
if let Some(def) = enums.get(name) {
env.bind_enum(l, &arg, name, def);
continue;
}
if let Some(def) = std_enum_def(name) {
env.bind_enum(l, &arg, name, &def);
continue;
}
if name == "str" && struct_lookup(structs, name).is_none() {
env.bind_indexed_len(l, &arg, 0, false);
continue;
}
env.declare_arg(&arg);
let Some(def) = struct_lookup(structs, name) else { continue };
for (i, (fname, fty)) in def.fields.iter().enumerate() {
env.bind(l, &arg, fname, i as u32, fty);
if let Ty::Array(elem, n) = fty {
if let Some(w) = elem.width() {
env.path_elem_types.insert(
format!("{arg}.{fname}"),
PathElem {
arg: arg.clone(),
local: l,
chain: vec![i as u32],
elem_w: w,
elem_signed: elem.is_signed(),
len: *n,
},
);
}
}
}
env.bind_nested_paths(l, &arg, base, structs);
}
env
}
pub fn signed_args(f: &crate::mir::parse::MirFn) -> BTreeSet<String> {
signed_args_named(f, None)
}
pub fn signed_args_named(
f: &crate::mir::parse::MirFn,
rename: Option<&ArgRename>,
) -> BTreeSet<String> {
let mut out = BTreeSet::new();
for &l in &f.arg_locals {
if f.ty_of(l).map(|t| t.referent().is_signed()).unwrap_or(false) {
let name = rename
.and_then(|r| r.name_of(l))
.map(|s| s.to_string())
.unwrap_or_else(|| f.name_of(l));
out.insert(name);
}
}
if rename.is_some() {
return out;
}
for (name, local) in f.alias_locals() {
if f.ty_of(local).map(|t| t.is_signed()).unwrap_or(false) {
out.insert(name);
}
}
out
}
fn type_bound(ty: &str, assoc: &str) -> Option<(u64, u8)> {
let signed = ty.starts_with('i');
let unsigned = ty.starts_with('u');
if !signed && !unsigned {
return None;
}
let bits: u32 = match ty {
"i8" | "u8" => 8,
"i16" | "u16" => 16,
"i32" | "u32" => 32,
"i64" | "u64" => 64,
"isize" | "usize" => 64,
_ => return None,
};
let v = match assoc {
"MAX" if signed => (1u64 << (bits - 1)) - 1,
"MAX" => {
if bits == 64 {
u64::MAX
} else {
(1u64 << bits) - 1
}
}
"MIN" if signed => 1u64 << (bits - 1),
"MIN" => 0,
_ => return None,
};
Some((v, bits as u8))
}
pub fn arg_vars(f: &crate::mir::parse::MirFn) -> BTreeMap<String, Var> {
arg_vars_named(f, None)
}
pub struct ArgRename(BTreeMap<crate::mir::parse::LocalIdx, String>);
impl ArgRename {
fn name_of(&self, l: crate::mir::parse::LocalIdx) -> Option<&str> {
self.0.get(&l).map(|s| s.as_str())
}
}
pub fn arg_vars_named(
f: &crate::mir::parse::MirFn,
rename: Option<&ArgRename>,
) -> BTreeMap<String, Var> {
let mut out: BTreeMap<String, Var> =
arg_bindings(f, rename).into_iter().map(|(_, n, v)| (n, v)).collect();
if rename.is_some() {
return out;
}
for (name, local) in f.alias_locals() {
let ty = f.ty_of(local).cloned().unwrap_or(Ty::Other("?".into()));
if let Some(w) = ty.width() {
out.insert(name, smt::var_named(local, w));
}
}
out
}
fn arg_bindings(
f: &crate::mir::parse::MirFn,
rename: Option<&ArgRename>,
) -> Vec<(crate::mir::parse::LocalIdx, String, Var)> {
let mut out = Vec::new();
for &l in &f.arg_locals {
let ty = f.ty_of(l).cloned().unwrap_or(Ty::Other("?".into()));
if let Some(w) = ty.referent().width() {
let name = rename
.and_then(|r| r.name_of(l))
.map(|s| s.to_string())
.unwrap_or_else(|| f.name_of(l));
out.push((l, name, smt::var_named(l, w)));
}
}
out
}
pub fn arg_name_of(
f: &crate::mir::parse::MirFn,
rename: Option<&ArgRename>,
local: crate::mir::parse::LocalIdx,
) -> Option<String> {
arg_bindings(f, rename)
.into_iter()
.find(|(l, _, _)| *l == local)
.map(|(_, name, _)| name)
}
#[cfg(test)]
mod tests {
#[test]
fn fn_signature_reads_names_positionally_or_not_at_all() {
use super::{fn_signature, Ty};
let (p, r) = fn_signature("pub fn f(n: u32, mut m: i8) -> u16 {");
assert_eq!(
p,
vec![("n".to_string(), Ty::U32), ("m".to_string(), Ty::I8)]
);
assert_eq!(r, Some(Ty::U16));
let (p, r) = fn_signature(" fn ext(a: u32) -> u32;");
assert_eq!(p, vec![("a".to_string(), Ty::U32)]);
assert_eq!(r, Some(Ty::U32));
let (p, r) = fn_signature("fn g(a: u32) {");
assert_eq!(p, vec![("a".to_string(), Ty::U32)]);
assert_eq!(r, None);
for bad in [
"fn h(_: u32) {",
"fn h(self) {",
"fn h((a, b): (u32, u32)) {",
"fn h(a u32) {",
"fn h(a: u32",
] {
let (p, _) = fn_signature(bad);
assert!(p.is_empty(), "`{bad}` must yield no parameters, got {p:?}");
}
let (p, _) = fn_signature("fn k(a: (u8, u8), b: [u8; 2]) {");
assert_eq!(p.len(), 2, "a nested comma must not split a parameter: {p:?}");
}
use super::*;
fn def(src: &str) -> EnumDef {
let specs = extract(src);
specs.enums.get("E").cloned().unwrap_or_default()
}
#[test]
fn a_standard_enum_argument_gets_a_layout() {
let o = std_enum_def("Option<u8>").expect("Option<u8> has a layout");
assert_eq!(o.index_of("None"), Some(0));
assert_eq!(o.index_of("Some"), Some(1));
assert_eq!(o.tag_width(), 1);
assert_eq!(o.variants[1].1, vec![Ty::U8], "`Some` carries the type argument");
let r = std_enum_def("Result<u8, u16>").expect("Result<u8, u16> has a layout");
assert_eq!(r.index_of("Ok"), Some(0));
assert_eq!(r.index_of("Err"), Some(1));
assert_eq!(r.variants[0].1, vec![Ty::U8], "`Ok` carries the first argument");
assert_eq!(r.variants[1].1, vec![Ty::U16], "`Err` carries the second");
}
#[test]
fn a_nested_standard_enum_payload_is_one_type() {
let r = std_enum_def("Result<Option<u8>, u8>").expect("nested Result has a layout");
assert_eq!(r.variants[0].1, vec![Ty::Other("Option<u8>".into())]);
assert_eq!(r.variants[1].1, vec![Ty::U8]);
}
#[test]
fn a_non_standard_or_malformed_name_is_refused() {
assert!(std_enum_def("Mode").is_none());
assert!(std_enum_def("Option").is_none(), "no type argument is not Option<T>");
assert!(std_enum_def("Option<u8>X").is_none(), "trailing text is not Option<u8>");
assert!(std_enum_def("Result<u8>").is_none(), "Result needs two arguments");
}
#[test]
fn an_enum_return_type_gives_its_discriminants() {
let none = BTreeMap::new();
assert_eq!(
enum_ret_discriminants(&Ty::Other("Result<u8, u8>".into()), &none),
Some((0, 1)),
"Result: Ok is 0, Err is 1"
);
assert_eq!(
enum_ret_discriminants(&Ty::Other("Option<u8>".into()), &none),
Some((1, 0)),
"Option: Some is 1, None is 0"
);
assert_eq!(
enum_ret_discriminants(&Ty::Other("Option::<u8>".into()), &none),
Some((1, 0)),
"a turbofished spelling is the same type"
);
assert_eq!(enum_ret_discriminants(&Ty::U8, &none), None, "a scalar has no tag");
assert_eq!(
enum_ret_discriminants(&Ty::Other("Mode".into()), &none),
None,
"a non-standard name is not a tag"
);
let mut enums = BTreeMap::new();
enums.insert("E".to_string(), def("pub enum E { Ok(u8), Err }"));
assert_eq!(
enum_ret_discriminants(&Ty::Other("E".into()), &enums),
Some((0, 1)),
"a declared enum uses its own discriminants"
);
}
#[test]
fn an_enum_return_reads_the_discriminant_methods() {
let tag = smt::var_named(1, 64);
let mut fields = FieldEnv::default();
fields.bind_ret_enum(tag, 0, 1);
let args = BTreeMap::new();
let signed = BTreeSet::new();
let old = BTreeMap::new();
let at = |k: u64| move |i: u32| if i == 1 { Some(k) } else { None };
let read = |text: &str| {
eval_ensures(
text,
&args,
Some(tag),
RET_IS_UNKNOWN,
&signed,
false,
&fields,
&old,
)
.unwrap_or_else(|e| panic!("`{text}` must parse: {e}"))
};
for (text, on_ok, on_err) in [
("ret.is_ok()", true, false),
("ret.is_err()", false, true),
("ret.is_ok() || ret.is_err()", true, true),
("ret.is_ok() && ret.is_err()", false, false),
] {
let p = read(text);
assert_eq!(
smt::evaluate_pred(p, at(0)),
Some(on_ok),
"`{text}` at the Ok tag (0)"
);
assert_eq!(
smt::evaluate_pred(p, at(1)),
Some(on_err),
"`{text}` at the Err tag (1)"
);
}
let plain = FieldEnv::default();
let err = eval_ensures(
"ret.is_ok()",
&args,
Some(tag),
RET_IS_UNKNOWN,
&signed,
false,
&plain,
&old,
);
assert!(err.is_err(), "`ret.is_ok()` on a non-enum return must be refused");
}
#[test]
fn an_enum_return_reads_a_payload_guarded_on_the_discriminant() {
let tag = smt::var_named(1, 1);
let ok = smt::var_named(2, 8);
let mut fields = FieldEnv::default();
fields.bind_ret_enum(tag, 0, 1);
fields.bind_ret_payload("Ok", ok, tag, 0, false);
let args = BTreeMap::new();
let signed = BTreeSet::new();
let old = BTreeMap::new();
let at = |t: u64, o: u64| move |i: u32| match i {
1 => Some(t),
2 => Some(o),
_ => None,
};
let read = |text: &str| {
eval_ensures(text, &args, Some(tag), RET_IS_UNKNOWN, &signed, false, &fields, &old)
.unwrap_or_else(|e| panic!("`{text}` must parse: {e}"))
};
let p = read("ret.Ok <= 9");
assert_eq!(smt::evaluate_pred(p, at(0, 9)), Some(true), "Ok tag, payload 9");
assert_eq!(smt::evaluate_pred(p, at(0, 10)), Some(false), "Ok tag, payload 10");
assert_eq!(smt::evaluate_pred(p, at(1, 10)), Some(true), "Err tag is vacuous");
assert_ne!(smt::evaluate_pred(p, at(1, 10)), Some(false), "must not check on Err");
}
#[test]
fn an_enum_argument_reads_the_discriminant_methods() {
let tag = smt::var_named(7, 1);
let mut args = BTreeMap::new();
args.insert("r__tag".to_string(), tag);
let mut fields = FieldEnv::default();
fields.variant_consts.insert("r::Ok".to_string(), (0, 1));
fields.variant_consts.insert("r::Err".to_string(), (1, 1));
let signed = BTreeSet::new();
let at = |k: u64| move |i: u32| if i == 7 { Some(k) } else { None };
let read = |text: &str| {
eval_requires(text, &args, &signed, &fields)
.unwrap_or_else(|e| panic!("`{text}` must parse: {e}"))
};
assert_eq!(smt::evaluate_pred(read("r.is_ok()"), at(0)), Some(true), "Ok tag");
assert_eq!(smt::evaluate_pred(read("r.is_ok()"), at(1)), Some(false), "Err tag");
assert_eq!(smt::evaluate_pred(read("r.is_err()"), at(1)), Some(true), "Err tag");
assert_eq!(
smt::evaluate_pred(read("r.is_ok() || r.is_err()"), at(1)),
Some(true),
"the disjunction is a tautology"
);
assert_eq!(
smt::evaluate_pred(read("r.is_ok() && r.is_err()"), at(0)),
Some(false),
"the conjunction is refutable"
);
}
#[test]
fn a_grouped_or_negated_enum_method_is_a_predicate() {
let tag = smt::var_named(1, 64);
let mut fields = FieldEnv::default();
fields.bind_ret_enum(tag, 0, 1);
let args = BTreeMap::new();
let signed = BTreeSet::new();
let old = BTreeMap::new();
let at = |k: u64| move |i: u32| if i == 1 { Some(k) } else { None };
let read = |text: &str| {
eval_ensures(
text,
&args,
Some(tag),
RET_IS_UNKNOWN,
&signed,
false,
&fields,
&old,
)
.unwrap_or_else(|e| panic!("`{text}` must parse: {e}"))
};
for (text, on_ok, on_err) in [
("(ret.is_ok())", true, false),
("!(ret.is_ok())", false, true),
("!ret.is_ok()", false, true),
("((ret.is_err()))", false, true),
("!(ret.is_ok() && ret.is_err())", true, true),
] {
let p = read(text);
assert_eq!(
smt::evaluate_pred(p, at(0)),
Some(on_ok),
"`{text}` at the Ok tag (0)"
);
assert_eq!(
smt::evaluate_pred(p, at(1)),
Some(on_err),
"`{text}` at the Err tag (1)"
);
}
}
#[test]
fn a_parenthesized_comparison_is_a_bool_operand() {
let ret = smt::var_named(0, 1);
let x = smt::var_named(1, 8);
let mut args = BTreeMap::new();
args.insert("x".to_string(), x);
let unsigned = BTreeSet::new();
let old = BTreeMap::new();
let fields = FieldEnv::default();
let read = |text: &str| {
eval_ensures(
text,
&args,
Some(ret),
RET_IS_UNKNOWN,
&unsigned,
false,
&fields,
&old,
)
.unwrap_or_else(|e| panic!("`{text}` must parse: {e}"))
};
let eval = |p, r: u64, xv: u64| {
smt::evaluate_pred(p, move |i| match i {
0 => Some(r),
_ => Some(xv),
})
};
for text in [
"ret == (x == 1)",
"ret == ((x) == 1)",
"ret == (x + 1 == 2)",
"ret == ((x + 1) == 2)",
"!ret == !(x == 1)",
] {
let p = read(text);
for xv in [0u64, 1, 2, 255] {
let truth = xv == 1;
assert_eq!(eval(p, 1, xv), Some(truth), "`{text}` ret=1 x={xv}");
assert_eq!(eval(p, 0, xv), Some(!truth), "`{text}` ret=0 x={xv}");
}
}
let mut p = Parser::new("(x + 1) == 2", &args, None, &unsigned, false);
let pred = p.parse_cmp().expect("`(x + 1) == 2` parses");
assert_eq!(smt::evaluate_pred(pred, |i| Some(if i == 1 { 1 } else { 0 })), Some(true));
assert_eq!(eval(read("ret"), 1, 0), Some(true), "a bare `ret` reads as `ret != 0`");
assert_eq!(eval(read("!ret"), 1, 0), Some(false), "`!ret` negates the bit");
let err = eval_ensures(
"x",
&args,
Some(ret),
RET_IS_UNKNOWN,
&unsigned,
false,
&fields,
&old,
);
assert!(err.is_err(), "a bare `u32` is not a predicate");
}
#[test]
fn a_name_holding_a_constant_is_not_a_written_constant_expression() {
let mut names = BTreeMap::new();
names.insert("i".to_string(), smt::word(0, 32));
let signed = BTreeSet::new();
let consts = BTreeMap::new();
assert!(
eval_invariant("i - 1 <= 5", &names, &signed, &consts).is_ok(),
"a name holding `0` must not be read as the written constant `0`"
);
assert!(
eval_invariant("0 - 1 <= 5", &names, &signed, &consts).is_err(),
"the written `0 - 1` is still a rustc const-eval error"
);
}
#[test]
fn a_contract_cast_sets_the_target_width_and_sign() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::word(0, 8));
let unsigned = BTreeSet::new();
let signed: BTreeSet<String> = ["x".to_string()].into_iter().collect();
let mut p = Parser::new("x as u32", &args, None, &unsigned, false);
let (v, s) = p.parse_expr().expect("`x as u32` parses");
assert_eq!(smt::bits(v), 32);
assert!(!s.eval());
let mut p = Parser::new("x as i32", &args, None, &signed, false);
let (v, s) = p.parse_expr().expect("`x as i32` parses");
assert_eq!(smt::bits(v), 32);
assert!(s.eval());
let mut p = Parser::new("x as u16 as i32", &args, None, &unsigned, false);
let (v, s) = p.parse_expr().expect("the chain parses");
assert_eq!(smt::bits(v), 32);
assert!(s.eval());
}
#[test]
fn a_contract_expression_uses_rust_precedence() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::word(1, 8));
let unsigned = BTreeSet::new();
let eval = |text: &str| {
let mut p = Parser::new(text, &args, None, &unsigned, false);
let (v, _) = p.parse_expr().expect("parses");
p.expect_end().expect("no trailing tokens");
smt::evaluate(v, |_| None).expect("a constant")
};
assert_eq!(eval("x & 1 + 1"), 0, "`&` must bind looser than `+`");
assert_eq!(eval("x + 1 << 1"), 4, "`+` must bind tighter than `<<`");
assert_eq!(eval("x | 1 ^ 1"), 1, "`^` must bind tighter than `|`");
assert_eq!(eval("8 / 4 / 2"), 1, "`/` is left-associative");
}
#[test]
fn a_negated_literal_is_signed() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::word(1, 8));
let unsigned = BTreeSet::new();
let parse = |text: &str| {
let mut p = Parser::new(text, &args, None, &unsigned, false);
let (v, sgn) = p.parse_expr().expect("parses");
p.expect_end().expect("no trailing tokens");
(v, sgn)
};
let (_, sgn) = parse("-7");
assert!(sgn.eval(), "a negated literal is signed");
let (_, sgn) = parse("-7 % 3");
assert!(sgn.eval(), "a remainder of a negated literal is signed");
let (_, sgn) = parse("7 % 3");
assert!(!sgn.eval(), "a bare literal is unsigned");
let (v, _) = parse("-7");
assert_eq!(smt::evaluate(v, |_| None).expect("a constant"), 0xF9);
}
#[test]
fn a_literal_widened_to_a_signed_operand_zero_fills() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::var(8));
let unsigned = BTreeSet::new();
let eval_const = |text: &str| {
let mut p = Parser::new(text, &args, None, &unsigned, false);
let (v, _) = p.parse_expr().expect("parses");
p.expect_end().expect("no trailing tokens");
smt::evaluate(v, |_| None).expect("a constant")
};
let pred = |text: &str, x: u64| {
let mut p = Parser::new(text, &args, None, &unsigned, false);
let pr = p.parse_or().expect("parses as a predicate");
p.expect_end().expect("no trailing tokens");
smt::evaluate_pred(pr, |_| Some(x)).expect("decides")
};
assert!(pred("(x as i16) == 255", 255), "`255` widened to i16 is `255`");
assert_eq!(eval_const("255 as i32"), 255, "a bare literal zero-fills");
assert_eq!(eval_const("-1 as i32"), u32::MAX as u64, "a signed constant sign-extends");
}
#[test]
fn an_opaque_constant_widening_is_refused_but_a_fold_is_not() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::var(8));
let unsigned = BTreeSet::new();
let parses = |text: &str| {
let mut p = Parser::new(text, &args, None, &unsigned, false);
p.parse_or().is_ok()
};
assert!(!parses("(x as u16 + !0) == 255"), "`!0` against a `u16` is `65535`");
assert!(!parses("(x as u16 + !0) == 65535"), "the reader cannot model it either way");
assert!(!parses("(x as i16 + !128) == 127"), "`!128` against an `i16` is `-129`");
assert!(parses("x as u16 <= 200 + 100"), "`300` is a value, not a bit pattern");
assert!(parses("x <= 100 + 44"), "a fold that fits its operand still reads");
assert!(parses("(x as i16) == 255"), "a bare literal zero-extends");
assert!(parses("128i16 as i32 == 128"), "the bare literal widens to the cast width");
}
#[test]
fn a_suffixed_literal_is_sized_from_its_suffix_not_the_scope() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::var(8));
let unsigned = BTreeSet::new();
let pred = |text: &str| {
let mut p = Parser::new(text, &args, None, &unsigned, false);
let pr = p.parse_or().expect("parses");
p.expect_end().expect("no trailing tokens");
smt::evaluate_pred(pr, |_| Some(0)).expect("decides")
};
assert!(pred("128i16 as i32 == 128"), "`128i16 as i32` is `128`");
assert!(pred("128i16 == 128"), "the suffixed literal is its own value");
let mut p = Parser::new("128i16 as i32 == -128", &args, None, &unsigned, false);
if let Ok(pr) = p.parse_or() {
assert!(!smt::prove(pr).is_proved(), "`128i16 as i32` is `128`, never `-128`");
}
}
#[test]
fn a_u128_suffix_is_refused_before_the_range_shift() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::var(8));
let unsigned = BTreeSet::new();
for text in ["0u128 == 0u128", "0i128 == 0i128", "1u128 == 1"] {
let mut p = Parser::new(text, &args, None, &unsigned, false);
let err = p.parse_or().expect_err("a 128-bit suffix must be refused");
let msg = format!("{err}");
assert!(msg.contains("128") && msg.contains("64-bit"), "`{text}`: got {msg}");
}
let mut p = Parser::new("1u64 == 1", &args, None, &unsigned, false);
assert!(p.parse_or().is_ok(), "a `u64` suffix is modelled");
}
#[test]
fn a_typed_constant_mask_keeps_its_type() {
let mut args = BTreeMap::new();
args.insert("y".to_string(), smt::var(8));
let unsigned = BTreeSet::new();
for text in ["(-1i8 & 1) == y", "(1i8 & 1) == y", "(-1i8 & 1) < y"] {
let mut p = Parser::new(text, &args, None, &unsigned, false);
let err = p.parse_or().expect_err("a signed mask vs an unsigned name must be refused");
let msg = format!("{err}");
assert!(msg.contains("signed constant"), "`{text}`: got {msg}");
}
let mut signed = BTreeSet::new();
signed.insert("y".to_string());
for text in ["(1u8 & 1) == y", "(1u8 & 1) < y"] {
let mut p = Parser::new(text, &args, None, &signed, false);
let err = p.parse_or().expect_err("an unsigned mask vs a signed name must be refused");
let msg = format!("{err}");
assert!(msg.contains("signed constant"), "`{text}`: got {msg}");
}
let mut p = Parser::new("(!0 & 1) == y", &args, None, &unsigned, false);
assert!(p.parse_or().is_ok(), "an untyped constant mask still reads");
}
#[test]
fn a_fixed_width_constant_may_not_meet_a_partner_of_another_width() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::var(8));
let mut signed = BTreeSet::new();
signed.insert("x".to_string());
for text in [
"(x as i16) == 1i8",
"-1i8 < (x as i16)",
"(x as i16) < i8::MIN",
"1i8 == 1i16",
] {
let mut p = Parser::new(text, &args, None, &signed, false);
let err = p.parse_or().expect_err("a fixed-width mismatch must be refused");
let msg = format!("{err}");
assert!(msg.contains("different widths"), "`{text}`: got {msg}");
}
for text in ["(x as i16) == 1", "-1 < (x as i16)", "-1 < x", "(!0 & 1) == x"] {
let mut p = Parser::new(text, &args, None, &signed, false);
assert!(p.parse_or().is_ok(), "`{text}` infers its width and reads");
}
}
#[test]
fn an_untyped_fold_that_overflows_the_operand_width_is_refused() {
let mut args = BTreeMap::new();
args.insert("y".to_string(), smt::var(8));
args.insert("a".to_string(), smt::var(16));
let unsigned = BTreeSet::new();
let mut signed = BTreeSet::new();
signed.insert("y".to_string());
for text in ["(!0 + 1) < 1u8", "(!0 + 2) == 1u8", "(!0 + 1) <= y"] {
let mut p = Parser::new(text, &args, None, &signed, false);
let err = p.parse_or().expect_err("an overflowing untyped fold must be refused");
assert!(
format!("{err}").contains("width-dependent"),
"`{text}`: got {err}"
);
}
for text in ["(200 + 100) <= a", "(200 + 100) == 300"] {
let mut p = Parser::new(text, &args, None, &unsigned, false);
assert!(p.parse_or().is_ok(), "`{text}` fits and reads");
}
}
#[test]
fn the_complement_of_an_out_of_range_literal_is_refused() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::var(8));
args.insert("y".to_string(), smt::var(8));
args.insert("b".to_string(), smt::var(16));
let mut signed = BTreeSet::new();
signed.insert("y".to_string());
signed.insert("b".to_string());
for text in ["y <= (!128)", "y <= (!255)", "y <= (!!128)", "y <= (!(64 + 64))"] {
let mut p = Parser::new(text, &args, None, &signed, false);
let err = p.parse_or().expect_err("an out-of-range complement must be refused");
let msg = format!("{err}");
assert!(
msg.contains("complement") || msg.contains("does not fit"),
"`{text}`: got {msg}"
);
}
for text in ["y <= (!127)", "x <= (!255)", "x <= (!0)", "b <= (!128)"] {
let mut p = Parser::new(text, &args, None, &signed, false);
let r = p.parse_or();
assert!(
r.is_ok(),
"`{text}` fits the operand type and reads: {:?}",
r.err().map(|e| format!("{e}"))
);
}
}
#[test]
fn a_literal_inside_a_constant_fold_is_range_checked_too() {
let mut args = BTreeMap::new();
args.insert("y".to_string(), smt::var(8));
args.insert("x".to_string(), smt::var(8));
args.insert("a".to_string(), smt::var(16));
let mut signed = BTreeSet::new();
signed.insert("y".to_string());
for text in [
"y == (200 & 200)",
"y == (2 & 128)",
"y == (100 + 100)",
"y == ((100 + 100) & 0)",
"y == (128 - 63)",
"y == (200 | 0)",
"y <= (2 & 128)",
] {
let mut p = Parser::new(text, &args, None, &signed, false);
let err = p.parse_or().expect_err("an out-of-range literal must be refused");
assert!(
format!("{err}").contains("does not fit"),
"`{text}`: got {err}"
);
}
for text in ["x == (200 & 200)", "x == (255 & 255)", "y == -128", "y == (-128)"] {
let mut p = Parser::new(text, &args, None, &signed, false);
assert!(
p.parse_or().is_ok(),
"`{text}` fits the type it meets and reads"
);
}
for text in ["y == -(128 - 63)", "y == -(-128)"] {
let mut p = Parser::new(text, &args, None, &signed, false);
assert!(
p.parse_or().is_err(),
"`{text}` has an out-of-range literal and must be refused"
);
}
}
#[test]
fn a_sign_ambiguous_untyped_fold_is_refused() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::var(8));
args.insert("y".to_string(), smt::var(8));
let mut signed = BTreeSet::new();
signed.insert("y".to_string());
for text in ["y == ((!127) - 63)", "x == ((!127) - 63)"] {
let mut p = Parser::new(text, &args, None, &signed, false);
let err = p.parse_or().expect_err("a sign-ambiguous fold must be refused");
assert!(
format!("{err}").contains("sign-ambiguous"),
"`{text}`: got {err}"
);
}
{
let text = "x == ((!0) - 1)";
let mut p = Parser::new(text, &args, None, &signed, false);
let r = p.parse_or();
assert!(
r.is_ok(),
"`{text}` agrees under both readings and reads: {:?}",
r.err().map(|e| format!("{e}"))
);
}
let mut args = BTreeMap::new();
args.insert("a".to_string(), smt::var(16));
let unsigned = BTreeSet::new();
let mut p = Parser::new("a == ((!100) * (-0))", &args, None, &unsigned, false);
let err = p.parse_or().expect_err("a negated literal beside a complement is refused");
assert!(
format!("{err}").contains("sign-ambiguous"),
"`a == ((!100) * (-0))`: got {err}"
);
for text in ["a == ((!127) - 63)", "a == ((!0) * 0)"] {
let mut p = Parser::new(text, &args, None, &unsigned, false);
let r = p.parse_or();
assert!(
r.is_ok(),
"`{text}` agrees under both readings and reads: {:?}",
r.err().map(|e| format!("{e}"))
);
}
}
#[test]
fn a_suffixed_minimum_literal_is_checked_as_written() {
let mut args = BTreeMap::new();
args.insert("y".to_string(), smt::var(8));
let mut signed = BTreeSet::new();
signed.insert("y".to_string());
for text in ["y == -128i8", "y == -(128i8)", "y == i8::MIN"] {
let mut p = Parser::new(text, &args, None, &signed, false);
let r = p.parse_or();
assert!(r.is_ok(), "`{text}` is legal and must read: {:?}", r.err().map(|e| format!("{e}")));
}
for text in ["y == 128i8", "y == -(-128i8)"] {
let mut p = Parser::new(text, &args, None, &signed, false);
let err = p.parse_or().expect_err("an out-of-range magnitude is refused");
let msg = format!("{err}");
assert!(
msg.contains("does not fit") || msg.contains("out of range"),
"`{text}`: got {msg}"
);
}
let mut args = BTreeMap::new();
args.insert("b".to_string(), smt::var(16));
let mut signed = BTreeSet::new();
signed.insert("b".to_string());
for text in ["b == -32768i16", "b == -(32768i16)", "b == i16::MIN"] {
let mut p = Parser::new(text, &args, None, &signed, false);
let r = p.parse_or();
assert!(r.is_ok(), "`{text}` is legal and must read: {:?}", r.err().map(|e| format!("{e}")));
}
let mut p = Parser::new("b == 32768i16", &args, None, &signed, false);
assert!(p.parse_or().is_err(), "`32768i16` alone is out of range for an `i16`");
}
#[test]
fn a_complement_operand_does_not_pollute_a_bare_literal() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::var(8));
args.insert("y".to_string(), smt::var(8));
let mut signed = BTreeSet::new();
signed.insert("y".to_string());
for text in [
"x == !128 && y == 127",
"y == 127 && x == !128",
"x == !0 && y == 127",
] {
let mut p = Parser::new(text, &args, None, &signed, false);
let r = p.parse_or();
assert!(r.is_ok(), "`{text}` is valid Rust and must read: {:?}", r.err().map(|e| format!("{e}")));
}
for text in ["y == !128", "y <= (!128)"] {
let mut p = Parser::new(text, &args, None, &signed, false);
let err = p.parse_or().expect_err("`!128` for an `i8` is out of range");
let msg = format!("{err}");
assert!(
msg.contains("complement") || msg.contains("does not fit"),
"`{text}`: got {msg}"
);
}
let mut p = Parser::new("y <= (-(!128))", &args, None, &signed, false);
let err = p.parse_or().expect_err("`-!128` for an `i8` is out of range");
let msg = format!("{err}");
assert!(
msg.contains("complement") || msg.contains("does not fit"),
"`y <= (-(!128))`: got {msg}"
);
}
#[test]
fn a_nested_complement_keeps_the_fold_and_a_bound_keeps_its_own_fit() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::var(8));
args.insert("y".to_string(), smt::var(8));
let mut signed = BTreeSet::new();
signed.insert("y".to_string());
for text in ["y == !(!1 - 200)", "y == !(200 - !1)", "y == !(128 - 63)"] {
let mut p = Parser::new(text, &args, None, &signed, false);
assert!(
p.parse_or().is_err(),
"`{text}` is a rustc range error and must be refused"
);
}
for text in [
"y == -128i8 && y == i8::MIN",
"y == i8::MIN && y == -128i8",
"x == 128 && y == i8::MIN",
"y == i8::MIN && x == 128",
"y == i8::MIN && y == 127",
] {
let mut p = Parser::new(text, &args, None, &signed, false);
let r = p.parse_or();
assert!(r.is_ok(), "`{text}` is valid Rust and must read: {:?}", r.err().map(|e| format!("{e}")));
}
}
#[test]
fn a_shift_of_an_untyped_constant_is_refused_when_it_needs_a_wider_operand() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::var(8));
args.insert("y".to_string(), smt::var(8));
args.insert("a".to_string(), smt::var(16));
args.insert("c".to_string(), smt::var(32));
let mut unsigned = BTreeSet::new();
unsigned.insert("x".to_string());
unsigned.insert("a".to_string());
unsigned.insert("c".to_string());
let mut signed = BTreeSet::new();
signed.insert("y".to_string());
for text in ["(255 >> 8) <= x", "(255 >> 16) <= a", "(!0 << 8) <= x",
"(1 >> 16) <= a", "(255 >> 1) >= y"] {
let mut p = Parser::new(text, &args, None, &signed, false);
assert!(
p.parse_or().is_err(),
"`{text}` is only valid at the scope's width and must be refused"
);
}
for text in ["(x >> 1) == 0", "(a << 2) <= a", "(1 << 4) <= x", "(1 >> 1) <= x",
"(2 << 2) <= a"] {
let mut p = Parser::new(text, &args, None, &signed, false);
assert!(p.parse_or().is_ok(), "`{text}` has a known width and reads");
}
}
#[test]
fn a_shift_amount_is_evaluated_at_its_own_width_not_the_operands() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::var(8));
let mut unsigned = BTreeSet::new();
unsigned.insert("x".to_string());
for text in ["x >> (2 << 7) == 0", "x >> (2 << 6) == 0"] {
let mut p = Parser::new(text, &args, None, &unsigned, false);
assert!(
p.parse_or().is_err(),
"`{text}` overflows at the amount's own `i32` width and must be refused"
);
}
for text in ["(x >> (1 + 1)) == 0", "(x >> (2 * 2)) == 0", "(x >> (8 - 1)) == 0",
"(x >> 7) == 0"] {
let mut p = Parser::new(text, &args, None, &unsigned, false);
assert!(p.parse_or().is_ok(), "`{text}` has an in-range amount and reads");
}
}
#[test]
fn a_typed_amount_operand_fixes_the_amounts_width() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::var(8));
let mut unsigned = BTreeSet::new();
unsigned.insert("x".to_string());
let mut p = Parser::new("(x >> (1u8 + (2 << 7))) == 0", &args, None, &unsigned, false);
let pred = p.parse_or().expect("`x >> (1u8 + (2 << 7))` is valid Rust and must read");
assert!(smt::evaluate_pred(pred, |_| Some(0)).unwrap(), "0 >> 1 == 0");
assert!(!smt::evaluate_pred(pred, |_| Some(2)).unwrap(), "2 >> 1 == 1 != 0");
for text in [
"x >> (2 << 7) == 0",
"x >> (1u16 + (2 << 7)) == 0",
"x >> (1 + (2 << 7)) == 0",
"x >> (2 << 7u8) == 0",
"(x >> 300) == 2u8",
"(x >> 300) == 2",
"(x >> (1u8 + 1u16)) == 0",
"(x >> (1u8 + 1i8)) == 0",
"x >> ((1u8) as u16 + (2 << 7)) == 0",
"x >> (1u8 as u16 + (2 << 7)) == 0",
"(!0 + 1) < 1u8",
"(!0 + 2) == 1u8",
] {
let mut p = Parser::new(text, &args, None, &unsigned, false);
assert!(p.parse_or().is_err(), "`{text}` is a rustc error and must be refused");
}
}
#[test]
fn an_opaque_folds_provisional_value_is_not_range_checked() {
let mut args = BTreeMap::new();
args.insert("y".to_string(), smt::var(8));
let mut signed = BTreeSet::new();
signed.insert("y".to_string());
let mut p = Parser::new("y == !(!1 + 1)", &args, None, &signed, true);
let pred = p.parse_or().expect("`y == !(!1 + 1)` is valid Rust and must read");
assert!(smt::evaluate_pred(pred, |_| Some(0)).unwrap(), "y == 0 reads true at 0");
assert!(!smt::evaluate_pred(pred, |_| Some(1)).unwrap(), "y == 0 reads false at 1");
let mut p = Parser::new("y == !128", &args, None, &signed, true);
assert!(p.parse_or().is_err(), "`!128` meets an `i8` and must be refused");
}
#[test]
fn a_deeply_nested_amount_does_not_exhaust_the_stack() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::var(64));
let mut unsigned = BTreeSet::new();
unsigned.insert("x".to_string());
let mut amount = String::from("1");
for _ in 0..40 {
amount = format!("(1 + {amount})");
}
let text = format!("(x >> {amount}) == 0");
let mut p = Parser::new(&text, &args, None, &unsigned, false);
assert!(
p.parse_or().is_ok(),
"a 40-level nested amount fits the operand and must read without exhausting the stack"
);
}
#[test]
fn negating_a_signed_constant_is_checked_as_its_value() {
let mut args = BTreeMap::new();
args.insert("y".to_string(), smt::var(8));
let mut signed = BTreeSet::new();
signed.insert("y".to_string());
for text in [
"y == -(i8::MIN)",
"y == -(3 << 7)",
"y == -(1 << 7)",
"y <= (-(i8::MIN))",
"y == -(-128i8)",
] {
let mut p = Parser::new(text, &args, None, &signed, false);
assert!(
p.parse_or().is_err(),
"`{text}` negates a constant out of range at its own type and must be refused"
);
}
for text in ["y == -128i8", "y == -(128i8)", "y == i8::MIN", "y == -(i8::MAX)",
"y == -(127)"] {
let mut p = Parser::new(text, &args, None, &signed, false);
let r = p.parse_or();
assert!(r.is_ok(), "`{text}` is legal and must read: {:?}", r.err().map(|e| format!("{e}")));
}
}
#[test]
fn a_typed_constant_mask_with_a_same_signedness_partner_reads() {
let mut args = BTreeMap::new();
args.insert("y".to_string(), smt::var(8));
let mut signed = BTreeSet::new();
signed.insert("y".to_string());
let mut p = Parser::new("(-1i8 & 1) == y", &args, None, &signed, false);
let pr = p.parse_or().expect("a signed mask vs a signed name reads");
p.expect_end().expect("no trailing tokens");
assert!(smt::evaluate_pred(pr, |_| Some(1)).expect("decides"), "`1 == 1`");
assert!(!smt::evaluate_pred(pr, |_| Some(0)).expect("decides"), "`1 == 0` is false");
let unsigned = BTreeSet::new();
let mut p = Parser::new("(1u8 & 1) == y", &args, None, &unsigned, false);
let pr = p.parse_or().expect("an unsigned mask vs an unsigned name reads");
p.expect_end().expect("no trailing tokens");
assert!(smt::evaluate_pred(pr, |_| Some(1)).expect("decides"), "`1 == 1`");
assert!(!smt::evaluate_pred(pr, |_| Some(0)).expect("decides"), "`1 == 0` is false");
}
#[test]
fn a_negation_binds_tighter_than_a_cast() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::word(0, 8));
let mut signed = BTreeSet::new();
signed.insert("x".to_string());
let parse = |text: &str| {
let mut p = Parser::new(text, &args, None, &signed, false);
let (v, sgn) = p.parse_expr().expect("parses");
p.expect_end().expect("no trailing tokens");
(v, sgn)
};
let (_, sgn) = parse("-x as u8");
assert!(!sgn.eval(), "`-x as u8` is `(-x) as u8`, an unsigned type");
let (v, _) = parse("-x as u8");
assert_eq!(smt::bits(v), 8, "the cast target is the width");
let (_, sgn) = parse("(-x) as u8");
assert!(!sgn.eval(), "`(-x) as u8` is unsigned too");
let (_, sgn) = parse("-x");
assert!(sgn.eval(), "a negation with no cast is signed");
let unsigned = BTreeSet::new();
let mut p = Parser::new("-x", &args, None, &unsigned, false);
assert!(p.parse_expr().is_err(), "`-x` for a `u8` does not compile");
}
#[test]
fn a_bang_on_a_value_is_bitwise_not_and_binds_tight() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::var(8));
let unsigned = BTreeSet::new();
let eval_const = |text: &str| {
let mut p = Parser::new(text, &args, None, &unsigned, false);
let (v, _) = p.parse_expr().expect("parses");
p.expect_end().expect("no trailing tokens");
smt::evaluate(v, |_| None).expect("a constant")
};
let eval_at = |text: &str, x: u64| {
let mut p = Parser::new(text, &args, None, &unsigned, false);
let (v, _) = p.parse_expr().expect("parses");
p.expect_end().expect("no trailing tokens");
smt::evaluate(v, |_| Some(x)).expect("decides")
};
let pred = |text: &str, x: u64| {
let mut p = Parser::new(text, &args, None, &unsigned, false);
let pr = p.parse_or().expect("parses as a predicate");
p.expect_end().expect("no trailing tokens");
smt::evaluate_pred(pr, |_| Some(x)).expect("decides")
};
assert_eq!(eval_const("!0"), 0xFF, "`!` on a value is bitwise NOT");
assert_eq!(eval_const("!!0"), 0, "a double `!` is the identity");
assert_eq!(eval_const("!1 + 1"), 0xFF, "`!` binds tighter than `+`");
assert_eq!(eval_const("0 & !1"), 0, "`!` applies to the operand, not the `&`");
assert_eq!(eval_at("!x", 0), 0xFF, "a bare `!x` reads, and is bitwise");
assert_eq!(eval_at("!x", 250), 5, "`!250` is `5` at 8 bits");
assert_eq!(eval_at("!x & 1", 0), 1, "`!` binds tighter than `&`");
assert!(pred("!x == 5", 250), "`!x == 5` is `(!x) == 5`: true at 250");
assert!(!pred("!x == 5", 5), "`!x == 5` is `(!x) == 5`: false at 5");
assert!(!pred("!(x == 5)", 5), "`!(x == 5)` is `x != 5`: false at 5");
assert!(pred("!(x == 5)", 250), "`!(x == 5)` is `x != 5`: true at 250");
assert!(pred("!(x + 1) == 5", 249), "`!(x + 1)` is `(!(x + 1))`, a value");
assert!(!pred("!(x + 1) == 5", 5), "`!(x + 1)` is not a predicate negation");
}
#[test]
fn a_constant_expression_is_folded_before_it_is_classified() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::var(8));
args.insert("y".to_string(), smt::var(8));
let unsigned = BTreeSet::new();
let parse = |text: &str| {
let mut p = Parser::new(text, &args, None, &unsigned, false);
let (v, _) = p.parse_expr().expect("parses");
p.expect_end().expect("no trailing tokens");
v
};
let folded = parse("x >> 1 + 1");
let literal = parse("x >> 2");
assert_eq!(smt::evaluate(folded, |_| Some(8)), Some(2));
assert_eq!(
smt::evaluate(folded, |_| Some(8)),
smt::evaluate(literal, |_| Some(8)),
"`x >> 1 + 1` must read as `x >> 2`"
);
let mut p = Parser::new("x >> y", &args, None, &unsigned, false);
assert!(p.parse_expr().is_err(), "a symbolic shift amount is refused");
let mut p = Parser::new("x % (1 - 1)", &args, None, &unsigned, false);
assert!(p.parse_expr().is_err(), "a folded zero divisor is refused");
assert_eq!(smt::evaluate(parse("x / (1 + 1)"), |_| Some(4)), Some(2));
}
#[test]
fn a_char_literal_is_read_as_its_scalar_value_or_refused() {
let mut args = BTreeMap::new();
args.insert("c".to_string(), smt::var(32));
let unsigned = BTreeSet::new();
let val = |text: &str| {
let mut p = Parser::new(text, &args, None, &unsigned, false);
let (v, _) = p.parse_expr().expect("parses");
p.expect_end().expect("no trailing tokens");
smt::evaluate(v, |_| None).expect("a constant")
};
let refuses = |text: &str| {
let mut p = Parser::new(text, &args, None, &unsigned, false);
p.parse_expr().is_err() || p.expect_end().is_err()
};
assert_eq!(val("'0'"), 0x30, "`'0'` is 48");
assert_eq!(val("'A'"), 65);
assert_eq!(val("'\\n'"), 0x0a, "a newline escape");
assert_eq!(val("'\\t'"), 0x09);
assert_eq!(val("'\\\\'"), 0x5c, "a backslash escape");
assert_eq!(val("'\\''"), 0x27, "an escaped quote");
assert_eq!(val("'\\x41'"), 0x41, "a byte escape");
assert_eq!(val("'\\u{1F600}'"), 0x1F600, "a Unicode escape");
assert_eq!(val("'\u{130}'"), 0x130, "a literal non-ASCII char");
assert!(refuses("'ab'"), "a multi-character literal is refused");
assert!(refuses("'\\q'"), "an unknown escape is refused");
assert!(refuses("'a"), "an unterminated literal is refused");
assert!(refuses("''"), "an empty literal is refused");
assert!(refuses("'\\u{110000}'"), "past the Unicode range is refused");
}
#[test]
fn a_char_literal_does_not_resize_to_a_narrower_operand() {
let mut args = BTreeMap::new();
args.insert("b".to_string(), smt::var(8));
args.insert("c".to_string(), smt::var(32));
let unsigned = BTreeSet::new();
let parses = |text: &str| {
let mut p = Parser::new(text, &args, None, &unsigned, false);
p.parse_cmp().is_ok() && p.expect_end().is_ok()
};
assert!(parses("c == '0'"), "two `char`s compare");
assert!(!parses("b == '0'"), "`'0' == 0u8` is `E0308`, so it is refused");
}
#[test]
fn a_radix_literal_is_read_at_its_radix_or_refused() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::var(16));
let unsigned = BTreeSet::new();
let val = |text: &str| {
let mut p = Parser::new(text, &args, None, &unsigned, false);
let (v, _) = p.parse_expr().expect("parses");
p.expect_end().expect("no trailing tokens");
smt::evaluate(v, |_| None).expect("a constant")
};
let refuses = |text: &str| {
let mut p = Parser::new(text, &args, None, &unsigned, false);
p.parse_expr().is_err() || p.expect_end().is_err()
};
assert_eq!(val("0xFF"), 255, "`0xFF` is 255, not 0");
assert_eq!(val("0x10"), 16, "`0x10` is 16, not 0");
assert_eq!(val("0b1010"), 10, "`0b1010` is 10, not 0");
assert_eq!(val("0o17"), 15, "`0o17` is 15, not 0");
assert_eq!(val("0xFFFF"), 65535);
assert_eq!(val("0xFF_FF"), 65535);
assert_eq!(val("1_000"), 1000);
assert_eq!(val("0xFFu8"), 255);
assert_eq!(val("100_"), 100, "a trailing `_` is a separator");
assert!(refuses("0b12"), "`0b12` has a non-binary digit");
assert!(refuses("0o9"), "`0o9` has a non-octal digit");
assert!(refuses("0xg"), "`0xg` has no hex digits");
assert!(refuses("0xFFg"), "`0xFFg` has an unknown suffix");
assert!(refuses("18446744073709551616"), "past `u64` is refused");
}
#[test]
fn an_out_of_range_literal_is_refused_at_the_operand_width() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::var(8));
let mut signed = BTreeSet::new();
signed.insert("x".to_string());
let reads = |text: &str| {
let mut p = Parser::new(text, &args, None, &signed, false);
let pr = p.parse_or().expect("parses");
p.expect_end().expect("no trailing tokens");
smt::evaluate_pred(pr, |_| Some(0))
};
let mut p = Parser::new("x <= 128", &args, None, &signed, false);
assert!(p.parse_or().is_err(), "`x <= 128` must be refused for an `i8`");
let mut p = Parser::new("x >= -129", &args, None, &signed, false);
assert!(p.parse_or().is_err(), "`x >= -129` must be refused for an `i8`");
assert_eq!(reads("x <= 127"), Some(true), "127 is i8::MAX");
assert_eq!(reads("x >= -128"), Some(true), "-128 is i8::MIN");
let mut p = Parser::new("x == 128", &args, None, &signed, false);
assert!(p.parse_or().is_err(), "`x == 128` is refused too");
let mut p = Parser::new("128 <= i8::MAX", &args, None, &signed, false);
assert!(
p.parse_or().is_err(),
"`128 <= i8::MAX` must be refused (literal out of range for `i8`)"
);
let mut p = Parser::new("127 <= i8::MAX", &args, None, &signed, false);
assert!(p.parse_or().is_ok(), "`127 <= i8::MAX` is well-typed and must read");
let mut p = Parser::new("i8::MIN <= i8::MAX", &args, None, &signed, false);
assert!(p.parse_or().is_ok(), "`i8::MIN <= i8::MAX` must read");
}
#[test]
fn an_overflowing_constant_expression_is_refused_not_wrapped() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::var(8));
let signed: BTreeSet<String> = BTreeSet::new();
let parses = |text: &str| {
let mut p = Parser::new(text, &args, None, &signed, false);
p.parse_or().is_ok()
};
assert!(!parses("x <= 200 + 100"), "`200 + 100` overflows a `u8`");
assert!(!parses("x >= 0 - 1"), "`0 - 1` underflows a `u8`");
assert!(!parses("x == 255 + 1"), "`255 + 1` overflows a `u8`");
assert!(!parses("x <= 200 * 2"), "`200 * 2` overflows a `u8`");
assert!(parses("x <= 100 + 44"), "`100 + 44` fits a `u8` and must read");
assert!(parses("x as u16 <= 200 + 100"), "`300` fits a `u16` and must read");
assert!(parses("x <= 2 * 3 % 4"), "a fold that fits must still read");
let mut sargs = BTreeMap::new();
sargs.insert("y".to_string(), smt::var(8));
let mut sset = BTreeSet::new();
sset.insert("y".to_string());
let sparses = |text: &str| {
let mut p = Parser::new(text, &sargs, None, &sset, false);
p.parse_or().is_ok()
};
assert!(!sparses("y <= i8::MAX + 1"), "`i8::MAX + 1` overflows an `i8`");
assert!(!sparses("y <= 127 + 1"), "`127 + 1` overflows an `i8`");
assert!(sparses("y <= i8::MAX"), "`i8::MAX` must read");
assert!(sparses("y >= i8::MIN"), "`i8::MIN` must read");
}
#[test]
fn an_overflowing_constant_division_is_refused() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::var(8));
let mut signed = BTreeSet::new();
signed.insert("x".to_string());
let parses = |text: &str| {
let mut p = Parser::new(text, &args, None, &signed, false);
p.parse_or().is_ok()
};
assert!(!parses("x == i8::MIN / -1"), "`i8::MIN / -1` overflows an `i8`");
assert!(!parses("x == i8::MIN % -1"), "`i8::MIN % -1` overflows an `i8`");
assert!(parses("x == 100 / 2"), "`100 / 2` is `50` and must read");
assert!(parses("x == -100 / 2"), "`-100 / 2` is `-50` and must read");
}
#[test]
fn a_signed_constant_against_an_unsigned_operand_is_refused() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::var(8));
args.insert("y".to_string(), smt::var(8));
let mut signed = BTreeSet::new();
signed.insert("y".to_string());
let parses = |text: &str| {
let mut p = Parser::new(text, &args, None, &signed, false);
p.parse_or().is_ok()
};
assert!(!parses("x == -1"), "`-1` against a `u8` does not compile");
assert!(!parses("x >= -1"), "`-1` against a `u8` does not compile");
assert!(!parses("x <= -1"), "`-1` against a `u8` does not compile");
assert!(!parses("x + -1 >= 0"), "`x + -1` for a `u8` does not compile");
assert!(!parses("x - -1 <= 0"), "`x - -1` for a `u8` does not compile");
assert!(!parses("x % -1 == 0"), "`x % -1` for a `u8` does not compile");
assert!(!parses("x * -1 == 255"), "`x * -1` for a `u8` does not compile");
assert!(!parses("x & -1 == 255"), "`x & -1` for a `u8` does not compile");
assert!(!parses("x | -1 == 0"), "`x | -1` for a `u8` does not compile");
assert!(!parses("x ^ -1 == 0"), "`x ^ -1` for a `u8` does not compile");
assert!(parses("x <= 0xFF"), "a bare literal is unsigned and must read");
assert!(parses("x <= 255"), "a bare literal is unsigned and must read");
assert!(parses("x + 255 >= 0"), "an unsigned constant still adds and reads");
assert!(parses("x - 1 <= 255"), "an unsigned difference still reads");
assert!(parses("x & 255 == x"), "an unsigned mask still reads");
assert!(parses("x ^ 255 == 0"), "an unsigned xor still reads");
assert!(parses("y <= -1"), "a signed name against a signed literal reads");
assert!(parses("y >= i8::MIN"), "a signed bound against a signed name reads");
assert!(parses("y + -1 <= 0"), "a signed name with a signed constant reads");
assert!(parses("y ^ -1 == 0"), "a signed name with a signed mask reads");
for op in ["==", "!=", "<", "<=", ">", ">="] {
assert!(
!parses(&format!("x {op} -1")),
"`x {op} -1` for a `u8` does not compile and must be refused"
);
assert!(
parses(&format!("x {op} 1")),
"`x {op} 1` for a `u8` is legal and must still read"
);
}
for op in ["+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>"] {
assert!(
!parses(&format!("(x {op} -1) == 0")),
"`x {op} -1` for a `u8` does not compile and must be refused"
);
assert!(
parses(&format!("(x {op} 1) == 0")),
"`x {op} 1` for a `u8` is legal and must still read"
);
}
}
#[test]
fn a_suffixed_literal_carries_its_type_signedness() {
let args = BTreeMap::new();
let signed = BTreeSet::new();
let parses = |text: &str| {
let mut p = Parser::new(text, &args, None, &signed, false);
p.parse_or().is_ok()
};
assert!(!parses("-1 == 0u8"), "`-1 == 0u8` is `E0277` and must be refused");
assert!(!parses("-1 <= 0u8"), "`-1 <= 0u8` is `E0277` and must be refused");
assert!(!parses("-1 < 0u8"), "`-1 < 0u8` is `E0277` and must be refused");
assert!(!parses("0u8 > -1"), "`0u8 > -1` is `E0277` and must be refused");
assert!(!parses("-1i8 == 0u8"), "`-1i8 == 0u8` is `E0308` and must be refused");
assert!(!parses("-1i16 == 65535u16"), "`-1i16 == 65535u16` must be refused");
assert!(parses("-1 <= 0"), "`-1 <= 0` is legal and must read");
assert!(parses("-1i8 <= 0i8"), "`-1i8 <= 0i8` is legal and must read");
assert!(parses("0u8 <= 255u8"), "`0u8 <= 255u8` is legal and must read");
assert!(parses("-1 <= 255"), "a bare literal adopts the signed side and reads");
assert!(parses("255u8 == 255"), "a bare literal adopts the unsigned side");
}
#[test]
fn a_bang_literal_is_refused_where_its_sign_would_change_the_meaning() {
let mut args = BTreeMap::new();
args.insert("x".to_string(), smt::var(8));
let mut signed = BTreeSet::new();
signed.insert("x".to_string());
let parses = |text: &str| {
let mut p = Parser::new(text, &args, None, &signed, false);
p.parse_or().is_ok()
};
assert!(!parses("(!0 >> 1) == 0"), "`!0 >> 1` has no typed operand");
assert!(!parses("(!4 >> 2) == 0"), "`!4 >> 2` has no typed operand");
assert!(!parses("(!4 / 2) == 0"), "`!4 / 2` has no typed operand");
assert!(!parses("(!4 % 3) == 0"), "`!4 % 3` has no typed operand");
assert!(!parses("(!0) < 0"), "`!0 < 0` has no typed operand");
assert!(!parses("(!7) >= 0"), "`!7 >= 0` has no typed operand");
assert!(!parses("(!0) == 255"), "`!0 == 255` is `false` in Rust, not provable");
assert!(!parses("(!0) != 255"), "`!0 != 255` has no typed operand");
assert!(!parses("(!4) == 251"), "`!4 == 251` is `false` in Rust, not provable");
assert!(!parses("(!0) == (!0)"), "both operands untyped and ambiguous");
assert!(parses("2 == 2"), "two bare literals compare exactly");
assert!(parses("x == 0"), "a typed operand fixes the reading");
assert!(parses("x == !x"), "`!x` carries `x`'s type, so the pair is typed");
assert!(parses("x >> 1 < 0"), "a shift of a name is exact");
assert!(parses("(!x >> 1) < 0"), "a shift of `!x` is exact");
assert!(parses("x <= 5"), "a small literal is unambiguous");
}
#[test]
fn two_names_of_different_signedness_are_refused() {
let mut args = BTreeMap::new();
args.insert("s".to_string(), smt::var(8));
args.insert("u".to_string(), smt::var(8));
let mut signed = BTreeSet::new();
signed.insert("s".to_string());
let parses = |text: &str| {
let mut p = Parser::new(text, &args, None, &signed, false);
p.parse_or().is_ok()
};
for op in ["==", "!=", "<=", ">=", "<", ">"] {
assert!(
!parses(&format!("s {op} u")),
"`s {op} u` for an `i8` and a `u8` does not compile and must be refused"
);
assert!(
!parses(&format!("u {op} s")),
"`u {op} s` is the same mismatched comparison and must be refused"
);
}
for op in ["+", "-", "*", "/", "%", "&", "|", "^"] {
assert!(
!parses(&format!("(s {op} u) == 0")),
"`s {op} u` for an `i8` and a `u8` does not compile and must be refused"
);
assert!(
!parses(&format!("(u {op} s) == 0")),
"`u {op} s` is the same mismatched operation and must be refused"
);
}
assert!(parses("s <= s"), "two signed names read");
assert!(parses("u <= u"), "two unsigned names read");
assert!(parses("s < 0"), "a signed name against a bare literal reads");
assert!(parses("u < 255"), "an unsigned name against a bare literal reads");
assert!(parses("s < 0 && u > 0"), "both halves legal, the conjunction reads");
assert!(parses("(s >> 1) == 0"), "a signed shift by a constant reads");
}
#[test]
fn an_explicit_discriminant_renumbers_the_rest() {
let d = def("pub enum E { A, B = 3, C }\n");
assert_eq!(d.index_of("A"), Some(0));
assert_eq!(d.index_of("B"), Some(3));
assert_eq!(d.index_of("C"), Some(4));
assert_eq!(d.tag_width(), 3);
}
#[test]
fn a_radix_prefixed_discriminant_is_read() {
let d = def("pub enum E { A = 0x10, B = 0b101, C = 0o7, D }\n");
assert_eq!(d.index_of("A"), Some(16));
assert_eq!(d.index_of("B"), Some(5));
assert_eq!(d.index_of("C"), Some(7));
assert_eq!(d.index_of("D"), Some(8));
}
#[test]
fn an_unreadable_discriminant_refuses_the_whole_layout() {
let specs = extract("pub enum E { A, B = 1 << 4, C }\n");
assert!(!specs.enums.contains_key("E"), "the layout must not be recorded at all");
}
#[test]
fn a_struct_variant_still_takes_a_discriminant() {
let d = def("pub enum E {\n A,\n Pair { x: u8 },\n C,\n}\n");
assert_eq!(d.index_of("A"), Some(0));
assert_eq!(d.index_of("Pair"), Some(1));
assert_eq!(d.index_of("C"), Some(2));
}
#[test]
fn the_tag_domain_is_the_discriminants() {
let d = def("pub enum E { A, B = 3, C }\n");
assert_eq!(d.variants.iter().map(|(_, _, d)| *d).collect::<Vec<_>>(), vec![0, 3, 4]);
}
#[test]
fn an_unreadable_one_line_enum_does_not_swallow_the_next_contract() {
let src = "pub enum E { A, B = 1 << 4 }\n\n\
/// ensures: ret == 1\n\
pub fn f() -> u8 { 0 }\n";
let specs = extract(src);
assert!(!specs.enums.contains_key("E"), "the refused layout must not be recorded");
assert!(
specs.by_fn.contains_key("f"),
"the contract after a refused enum must still be read, got: {:?}",
specs.by_fn.keys().collect::<Vec<_>>()
);
}
#[test]
fn a_decreases_clause_is_read_and_counts_as_a_claim() {
let src = "/// decreases: n\n\
pub fn f(n: u8) -> u8 { n }\n";
let specs = extract(src);
let c = specs.by_fn.get("f").expect("a `decreases:` alone is a claim");
assert_eq!(c.decreases, vec!["n".to_string()], "the measure text must be kept");
assert!(c.requires.is_empty() && c.ensures.is_empty());
}
#[test]
fn an_unwind_clause_is_read_and_counts_as_a_claim() {
let src = "/// unwind: 40\n\
pub fn f(n: u8) -> u8 { n }\n";
let specs = extract(src);
let c = specs.by_fn.get("f").expect("an `unwind:` alone is a claim");
assert_eq!(c.unwind, Some(40), "the bound must be read as a number");
assert!(c.requires.is_empty() && c.ensures.is_empty());
}
#[test]
fn a_non_numeric_or_zero_unwind_is_refused() {
for bad in ["unwind: 0", "unwind: abc", "unwind: -1", "unwind: 1.5"] {
let src = format!("/// {bad}\npub fn f(n: u8) -> u8 {{ n }}\n");
let specs = extract(&src);
let c = specs.by_fn.get("f").expect("the item is still read");
assert!(
c.unwind.is_none(),
"`{bad}` must not become a bound; got {:?}",
c.unwind
);
}
}
#[test]
fn a_measure_takes_its_sign_from_its_arguments() {
let mut args = BTreeMap::new();
args.insert("n".to_string(), smt::var_named(1, 8));
let consts = BTreeMap::new();
let unsigned = BTreeSet::new();
let (_, u_signed) = eval_measure("n", &args, &unsigned, &consts).expect("`n` parses");
assert!(!u_signed, "an unsigned argument gives an unsigned measure");
let signed: BTreeSet<String> = ["n".to_string()].into_iter().collect();
let (_, s_signed) = eval_measure("n", &args, &signed, &consts).expect("`n` parses");
assert!(s_signed, "a signed argument gives a signed measure");
let (_, sum_signed) =
eval_measure("n + 1", &args, &signed, &consts).expect("`n + 1` parses");
assert!(sum_signed, "the sign must survive the addition");
}
#[test]
fn an_unreadable_measure_is_an_error() {
let mut args = BTreeMap::new();
args.insert("n".to_string(), smt::var_named(1, 8));
let consts = BTreeMap::new();
let signed = BTreeSet::new();
assert!(eval_measure("n +", &args, &signed, &consts).is_err(), "a dangling `+`");
assert!(eval_measure("nope", &args, &signed, &consts).is_err(), "an unknown name");
assert!(eval_measure("", &args, &signed, &consts).is_err(), "an empty measure");
}
#[test]
fn a_one_line_struct_does_not_swallow_the_next_contract() {
let src = "pub struct B { pub lo: u8 }\n\n\
/// ensures: ret == 1\n\
pub fn f() -> u8 { 0 }\n";
let specs = extract(src);
assert!(
specs.structs.contains_key("B"),
"a one-line struct body must still be recorded, got: {:?}",
specs.structs.keys().collect::<Vec<_>>()
);
assert_eq!(
specs.structs["B"].fields.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(),
vec!["lo"],
"the one-line body's field must be read out of the head line"
);
assert!(
specs.by_fn.contains_key("f"),
"the contract after a one-line struct must still be read, got: {:?}",
specs.by_fn.keys().collect::<Vec<_>>()
);
}
#[test]
fn a_refused_multi_line_enum_does_not_swallow_the_next_contract() {
let src = "pub enum E {\n A,\n B = 1 << 4,\n}\n\n\
/// ensures: ret == 1\n\
pub fn f() -> u8 { 0 }\n";
let specs = extract(src);
assert!(!specs.enums.contains_key("E"), "the refused layout must not be recorded");
assert!(
specs.by_fn.contains_key("f"),
"the contract after a refused multi-line enum must still be read, got: {:?}",
specs.by_fn.keys().collect::<Vec<_>>()
);
}
#[test]
fn a_contract_above_a_struct_does_not_attach_to_the_next_function() {
let src = "/// requires: x == 0\n\
pub struct S { pub v: u8 }\n\
/// ensures: ret == 0\n\
pub fn f(x: u8) -> u8 { x }\n";
let specs = extract(src);
let c = specs.by_fn.get("f").expect("`f` must carry a contract");
assert!(
c.requires.is_empty(),
"the struct's doc comment leaked into `f`: {:?}",
c.requires
);
assert_eq!(c.ensures, vec!["ret == 0"], "the function's own `ensures` must survive");
}
#[test]
fn a_contract_above_an_enum_does_not_attach_to_the_next_function() {
let src = "/// requires: x == 0\n\
pub enum E { A, B }\n\
/// ensures: ret == 0\n\
pub fn f(x: u8) -> u8 { x }\n";
let specs = extract(src);
let c = specs.by_fn.get("f").expect("`f` must carry a contract");
assert!(c.requires.is_empty(), "the enum's doc comment leaked into `f`: {:?}", c.requires);
assert_eq!(c.ensures, vec!["ret == 0"]);
}
#[test]
fn a_trailing_comment_on_a_variant_is_not_part_of_it() {
let src = "pub enum E {\n A,\n B = 3, // special\n C,\n}\n";
let d = def(src);
assert_eq!(d.index_of("A"), Some(0));
assert_eq!(d.index_of("B"), Some(3));
assert_eq!(d.index_of("C"), Some(4), "C follows B's explicit value, not its position");
}
#[test]
fn a_trailing_comment_on_an_implicit_variant_is_ignored() {
let src = "pub enum E {\n A, // first\n B,\n}\n";
let d = def(src);
assert_eq!(d.index_of("A"), Some(0));
assert_eq!(d.index_of("B"), Some(1));
}
fn field_env_with(consts: &[(&str, Const)]) -> FieldEnv {
let mut e = FieldEnv::default();
for (k, v) in consts {
e.consts.insert((*k).to_string(), v.clone());
}
e
}
#[test]
fn a_contract_reads_a_const_name_as_its_value() {
let args = BTreeMap::new();
let env = field_env_with(&[
("LIMIT", Const::UInt(10, Some(Ty::U8))),
("NEG", Const::UInt(0xff, Some(Ty::I8))),
("B", Const::Bool(true)),
]);
let p = eval_requires("LIMIT <= 10", &args, &BTreeSet::new(), &env).unwrap();
assert_eq!(smt::prove(p), smt::Verdict::Valid);
let p = eval_requires("LIMIT <= 9", &args, &BTreeSet::new(), &env).unwrap();
assert_ne!(smt::prove(p), smt::Verdict::Valid, "LIMIT is 10, so `<= 9` must not hold");
let p = eval_requires("NEG <= -1", &args, &BTreeSet::new(), &env).unwrap();
assert_eq!(smt::prove(p), smt::Verdict::Valid);
let p = eval_requires("NEG >= 0", &args, &BTreeSet::new(), &env).unwrap();
assert_ne!(smt::prove(p), smt::Verdict::Valid, "NEG is -1, so `>= 0` must not hold");
let p = eval_requires("B == true", &args, &BTreeSet::new(), &env).unwrap();
assert_eq!(smt::prove(p), smt::Verdict::Valid);
}
#[test]
fn an_argument_shadows_a_const_of_the_same_name() {
let mut args = BTreeMap::new();
args.insert("LIMIT".to_string(), smt::var_named(1, 8));
let env = field_env_with(&[("LIMIT", Const::UInt(10, Some(Ty::U8)))]);
let p = eval_requires("LIMIT <= 10", &args, &BTreeSet::new(), &env).unwrap();
assert_ne!(smt::prove(p), smt::Verdict::Valid);
}
#[test]
fn a_non_literal_const_name_is_refused() {
let args = BTreeMap::new();
let env = field_env_with(&[("EXPR", Const::Other("_".into()))]);
assert!(eval_requires("EXPR <= 1", &args, &BTreeSet::new(), &env).is_err());
assert!(eval_requires("LIMITT <= 1", &args, &BTreeSet::new(), &env).is_err());
}
#[test]
fn crate_level_consts_reads_only_module_scope_items() {
let src = r#"
// const COMMENTED: u8 = 1;
const LIMIT: u8 = 10;
pub const PUB_LIMIT: u8 = 11;
const TYPO: u8 = 12;
/// const DOC: u8 = 13;
pub fn f() -> u8 {
const LOCAL: u8 = 3;
let s = "const IN_STRING: u8 = 4";
let _ = s;
LOCAL
}
impl Foo {
const ASSOC: u8 = 5;
}
fn g<const N: usize>() -> usize { N }
fn h<
const SPLIT: usize,
>() -> usize {
SPLIT
}
"#;
let names = crate_level_consts(src);
assert!(names.contains("LIMIT"), "a crate-level const is read: {names:?}");
assert!(names.contains("PUB_LIMIT"), "a `pub const` is read: {names:?}");
assert!(names.contains("TYPO"), "a plain crate-level const is read: {names:?}");
assert!(!names.contains("COMMENTED"), "a commented-out item is not read: {names:?}");
assert!(!names.contains("DOC"), "a doc-comment line is not read: {names:?}");
assert!(!names.contains("LOCAL"), "a function-local const is not read: {names:?}");
assert!(!names.contains("IN_STRING"), "a const inside a string is not read: {names:?}");
assert!(!names.contains("ASSOC"), "an associated const is not read: {names:?}");
assert!(
!names.contains("N"),
"a `const` generic parameter is not a module-scope item: {names:?}"
);
assert!(
!names.contains("SPLIT"),
"a `const` generic parameter on its own line is not an item: {names:?}"
);
}
#[test]
fn const_generic_params_reads_only_parameters() {
let names = const_generic_params(
"fn f<const N: usize>() -> usize { N }\n\
fn g<\n const M: usize,\n>(x: usize) -> usize { x + M }\n\
const ITEM: u8 = 1;\n\
struct S<const K: usize>([u8; K]);\n\
// const COMMENT: u8 = 2;\n\
fn h() { let s = \"const STR: u8 = 3\"; let _ = s; }\n",
);
assert!(names.contains("N"), "an inline parameter is read: {names:?}");
assert!(names.contains("M"), "a parameter after a line break is read: {names:?}");
assert!(names.contains("K"), "a parameter in a type's list is read: {names:?}");
assert!(!names.contains("ITEM"), "a `const` item is not a parameter: {names:?}");
assert!(!names.contains("COMMENT"), "a commented-out parameter is not read: {names:?}");
assert!(!names.contains("STR"), "a parameter inside a string is not read: {names:?}");
}
#[test]
fn const_generic_params_survives_whitespace_and_comments() {
for source in [
"fn f<const\n N: usize>() -> usize { N }\n",
"fn f<const\tN: usize>() -> usize { N }\n",
"fn f<const/*c*/N: usize>() -> usize { N }\n",
"fn f<const // c\n N: usize>() -> usize { N }\n",
"struct S<A, const\n N: usize>([u8; N], A);\n",
] {
let names = const_generic_params(source);
assert!(
names.contains("N"),
"the parameter after the `const` keyword must be read: {source:?} -> {names:?}"
);
}
}
#[test]
fn const_generic_params_tolerates_an_unclosed_block_comment() {
for source in [
"fn f<const /*",
"fn f<const /*x",
"fn f<const /* ",
"fn f<const /*/",
"fn f<const /*x*",
"fn f<const /*x*/",
"fn f<const /*\n",
] {
let _ = const_generic_params(source);
}
}
#[test]
fn impl_trait_reads_the_trait_and_refuses_an_inherent_impl() {
assert_eq!(impl_trait("impl From<u8> for u16 {"), Some("From".to_string()));
assert_eq!(
impl_trait("impl std::convert::From<u8> for u16 {"),
Some("std::convert::From".to_string())
);
assert_eq!(impl_trait("impl core::cmp::Ord for Foo {"), Some("core::cmp::Ord".to_string()));
assert_eq!(impl_trait("impl<T> From<T> for Wrapper<T> {"), Some("From".to_string()));
assert_eq!(impl_trait("unsafe impl Send for Foo {}"), Some("Send".to_string()));
assert_eq!(impl_trait("impl u16 {"), None);
assert_eq!(impl_trait("impl<T> Wrapper<T> {"), None);
assert_eq!(
impl_trait("impl Convert<Option<u8>> for Foo {"),
Some("Convert".to_string())
);
}
#[test]
fn impl_traits_are_keyed_by_location_and_module_qualified() {
let src = "mod m {\n pub trait From<T> { fn from(t: T) -> Self; }\n \
impl From<u8> for u16 { fn from(_t: u8) -> u16 { 7 } }\n}\n\
struct Wrapper(u8);\n\
impl Wrapper { fn make() -> Wrapper { Wrapper(0) } }\n";
let specs = extract(src);
assert_eq!(specs.impl_traits.get(&(3, 5)), Some(&"m::From".to_string()));
assert_eq!(specs.impl_owners.get(&(3, 5)), Some(&"u16".to_string()));
assert_eq!(specs.impl_owners.get(&(6, 1)), Some(&"Wrapper".to_string()));
assert_eq!(specs.impl_traits.get(&(6, 1)), None);
}
#[test]
fn leading_attributes_are_peeled_and_a_cfg_is_reported() {
assert_eq!(split_leading_attrs("use a::B;"), ("use a::B;", false));
assert_eq!(split_leading_attrs("#[cfg(any())] use a::B;"), ("use a::B;", true));
assert_eq!(
split_leading_attrs("#[allow(unused)] #[cfg(test)] use a::B;"),
("use a::B;", true)
);
assert_eq!(split_leading_attrs("#[allow(dead_code)] use a::B;"), ("use a::B;", false));
assert_eq!(
split_leading_attrs("#[cfg(all(unix, target_os = \"linux\"))] use a::B;"),
("use a::B;", true)
);
assert_eq!(split_leading_attrs("#[cfg_attr(x, allow(y))] use a::B;"), ("use a::B;", true));
}
#[test]
fn a_use_behind_a_same_line_attribute_is_still_an_import() {
assert!(is_use_start("#[cfg(all())] use std::convert::From;"));
assert!(is_use_start("#[allow(unused)] pub(crate) use a::B;"));
assert!(!is_use_start("#[allow(unused)] let x = 1;"));
assert_eq!(strip_visibility("#[allow(x)] pub(crate) use a::B;"), "use a::B;");
}
#[test]
fn a_cfg_import_does_not_displace_a_live_binding() {
let lines: Vec<&str> = vec![
"mod m {",
" use std::convert::From as Conv;",
" #[cfg(any())]",
" use crate::Other as Conv;",
"}",
"struct Other;",
"use crate::Other as Root;",
];
let scopes = line_scopes(&lines.join("\n"));
let imports = module_imports(&scopes, &lines);
let m = &imports[1];
assert_eq!(m.get("Conv"), Some(&"std::convert::From".to_string()));
assert_eq!(imports[6].get("Root"), Some(&"crate::Other".to_string()));
}
#[test]
fn a_conditional_binding_is_held_below_an_unconditional_one() {
let lines: Vec<&str> = vec![
"mod m {",
" #[cfg(all())] use std::convert::From as Conv;",
" pub struct Local;",
"}",
];
let scopes = line_scopes(&lines.join("\n"));
let imports = module_imports(&scopes, &lines);
assert_eq!(imports[1].get("Conv"), Some(&"std::convert::From".to_string()));
let lines: Vec<&str> = vec![
"mod m {",
" #[cfg(any())] use crate::Other as Conv;",
" use std::convert::From as Conv;",
"}",
];
let scopes = line_scopes(&lines.join("\n"));
let imports = module_imports(&scopes, &lines);
assert_eq!(imports[1].get("Conv"), Some(&"std::convert::From".to_string()));
}
#[test]
fn a_multiline_cfg_attribute_is_seen_above_a_use() {
let lines: Vec<&str> = vec!["#[cfg(any())]", "use a::B as C;"];
assert!(is_cfg_use(&lines, 1));
let lines: Vec<&str> = vec![
"#[cfg(all(",
" any(),",
"))]",
"use a::B as C;",
];
assert!(is_cfg_use(&lines, 3), "a multi-line cfg must still be seen");
let lines: Vec<&str> = vec!["#[allow(unused)]", "use a::B as C;"];
assert!(!is_cfg_use(&lines, 1));
let lines: Vec<&str> = vec!["#[cfg(any())]", "struct X;", "use a::B as C;"];
assert!(!is_cfg_use(&lines, 2), "a non-attribute line ends the attribute block");
let lines: Vec<&str> = vec!["#[cfg(any())]", "", "use a::B as C;"];
assert!(!is_cfg_use(&lines, 2), "a blank line ends the attribute block");
let lines: Vec<&str> = vec![
"#[allow(",
" unused,",
")]",
"#[cfg(any())]",
"use a::B as C;",
];
assert!(is_cfg_use(&lines, 4), "a cfg below another attribute is still this item's");
}
#[test]
fn a_delimiter_inside_a_quoted_attribute_is_not_a_delimiter() {
let lines: Vec<&str> = vec![
"#[cfg(any())]",
"#[doc = \"(\"]",
"use a::B as C;",
];
assert!(is_cfg_use(&lines, 2), "an unmatched `(` in a string must not hide the cfg");
let lines: Vec<&str> = vec![
"#[cfg(any())]",
"#[doc = \"]\"]",
"use a::B as C;",
];
assert!(is_cfg_use(&lines, 2), "a `]` in a string must not close the attribute early");
let lines: Vec<&str> = vec![
"#[cfg(any())]",
"#[doc = \"\\\"(\"]",
"use a::B as C;",
];
assert!(is_cfg_use(&lines, 2), "an escaped quote must not end the string");
let lines: Vec<&str> = vec![
"#[cfg(any())]",
"#[doc = ')']",
"use a::B as C;",
];
assert!(is_cfg_use(&lines, 2), "a `)` in a char literal must not close the attribute");
let lines: Vec<&str> = vec![
"#[cfg(feature = \"(\")]",
"#[doc = \")\"]",
"use a::B as C;",
];
assert!(is_cfg_use(&lines, 2), "a quoted `(` in a cfg argument must not unbalance it");
let lines: Vec<&str> = vec!["#[allow('a)]", "use a::B as C;"];
assert!(!is_cfg_use(&lines, 1), "a lifetime must not open a char literal");
}
#[test]
fn a_raw_string_attribute_is_read_opaque() {
let lines: Vec<&str> = vec!["#[cfg(any())]", "#[doc = r\"\\\"]", "use a::B as C;"];
assert!(is_cfg_use(&lines, 2), "a trailing backslash in a raw string must not hide the cfg");
let lines: Vec<&str> = vec!["#[cfg(any())]", "#[doc = r#\"a \" b\"#]", "use a::B as C;"];
assert!(is_cfg_use(&lines, 2), "a raw string with hashes must be read whole");
let lines: Vec<&str> = vec!["#[cfg(any())]", "#[doc = br\"(\"]", "use a::B as C;"];
assert!(is_cfg_use(&lines, 2), "a byte raw string must be read whole");
let lines: Vec<&str> = vec!["#[cfg(any())]", "#[doc = r\")\"]", "use a::B as C;"];
assert!(is_cfg_use(&lines, 2), "a `)` inside a raw string must not close the attribute");
}
#[test]
fn a_comment_inside_an_attribute_is_not_code() {
let lines: Vec<&str> = vec!["#[cfg(any( // \" note", "))]", "use a::B as C;"];
assert!(is_cfg_use(&lines, 2), "a quote in a line comment must not open a string");
let lines: Vec<&str> = vec!["#[cfg(any() // ]", ")]", "use a::B as C;"];
assert!(is_cfg_use(&lines, 2), "a `]` in a line comment must not close the attribute");
let lines: Vec<&str> = vec!["#[cfg(any())]", "#[doc = /* \" */ \"x\"]", "use a::B as C;"];
assert!(is_cfg_use(&lines, 2), "a quote in a block comment must not open a string");
let lines: Vec<&str> = vec!["#[cfg(any())]", "#[doc = /* \"", "*/ \"x\"]", "use a::B as C;"];
assert!(is_cfg_use(&lines, 3), "a multi-line block comment must be skipped whole");
}
#[test]
fn a_quoted_attribute_on_the_use_line_does_not_hide_it() {
assert_eq!(
split_leading_attrs("#[doc = \"(\"] use a::B;"),
("use a::B;", false)
);
assert!(is_use_start("#[doc = \"(\"] use a::B;"));
assert_eq!(
split_leading_attrs("#[doc = r\"\\\"] use a::B;"),
("use a::B;", false)
);
assert_eq!(
split_leading_attrs("#[cfg(any())] #[doc = \")\"] use a::B;"),
("use a::B;", true)
);
}
}