use crate::mir::parse::{BinOp, Ty};
use crate::smt::{self, Pred, Var};
pub const DIV_MAX_WIDTH: u8 = 32;
pub const MUL_MAX_WIDTH: u8 = 32;
pub const POW_MAX_WIDTH: u8 = 8;
pub const SOME_TAG: u64 = 1;
pub const NONE_TAG: u64 = 0;
pub const OK_TAG: u64 = 0;
pub const CONTINUE_TAG: u64 = 0;
pub const BREAK_TAG: u64 = 1;
pub const ORDERING_LESS: i64 = -1;
pub const ORDERING_EQUAL: i64 = 0;
pub const ORDERING_GREATER: i64 = 1;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Intrinsic {
Wrapping(BinOp),
Saturating(BinOp),
Checked(BinOp),
Overflowing(BinOp),
Unary(Family, UnOp),
Bits(BitKind),
Ilog(LogKind),
CheckedIlog(LogKind),
NextMultipleOf,
CheckedNextMultipleOf,
NextPowerOfTwo,
CheckedNextPowerOfTwo,
Pow(Family),
MixedAdd(Family),
Bool(BoolKind),
SliceLen,
SliceIsEmpty,
SliceFirst,
SliceGet,
SliceLast,
VecMethod(VecMethod),
AbsDiff,
Rotate(RotateKind),
WrappingShift(ShiftKind),
Signum,
DivEuclid,
RemEuclid,
DivCeil,
Midpoint,
BitReverse,
ByteSwap,
ByteOrder(ByteOrderKind),
AsciiCase(AsciiCaseKind),
MinMax(MinMaxKind),
Cmp(PartialCmpKind),
OrdCmp,
Conversion(Conversion),
Abs,
UnsignedAbs,
SignednessCast,
PowPanic,
Clamp,
OptionMethod(OptionMethod),
Range(RangeMethod),
TryBranch,
FromResidual,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VecMethod {
New,
Push,
Len,
IsEmpty,
Pop,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RangeMethod {
New,
IntoIter,
Next,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Family {
Wrapping,
Saturating,
Checked,
Overflowing,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UnOp {
Neg,
Abs,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BoolKind {
PowerOfTwo,
Ascii(AsciiKind),
Negative,
Positive,
MultipleOf,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AsciiKind {
Digit,
Alphabetic,
Alphanumeric,
Uppercase,
Lowercase,
HexDigit,
Whitespace,
Punctuation,
Control,
Ascii,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MinMaxKind {
Min,
Max,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PartialCmpKind {
Eq,
Ne,
Lt,
Le,
Gt,
Ge,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ByteOrderKind {
Be,
Le,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AsciiCaseKind {
Upper,
Lower,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OptionMethod {
UnwrapOr,
UnwrapOrDefault,
Unwrap,
Expect,
IsSuccess,
IsFailure,
OkOr,
Ok,
Err,
Or,
And,
Copied,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Conversion {
From,
Into,
}
pub fn conversion_types(name: &str, kind: Conversion) -> Option<(Ty, Ty)> {
let (self_part, after_as) = name.rsplit_once(" as ")?;
let self_ty = Ty::parse(self_part.trim_start_matches('<'));
let open = after_as.find('<')?;
let close = after_as.find(">::")?;
if close <= open {
return None;
}
let param = after_as[open + 1..close].trim_end_matches('>');
let param_ty = Ty::parse(param);
Some(match kind {
Conversion::From => (param_ty, self_ty),
Conversion::Into => (self_ty, param_ty),
})
}
pub fn is_modelled_int(ty: &Ty) -> bool {
matches!(
ty,
Ty::U8 | Ty::U16 | Ty::U32 | Ty::U64 | Ty::Usize | Ty::I8 | Ty::I16 | Ty::I32 | Ty::I64
| Ty::Isize
)
}
pub fn int_width(ty: &Ty) -> Option<u8> {
if !is_modelled_int(ty) {
return None;
}
ty.width()
}
pub fn convert_value(x: Var, src_signed: bool, dst_w: u8) -> Var {
if src_signed {
smt::sign_extend(x, dst_w)
} else {
smt::truncate(x, dst_w)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BitKind {
Ones,
LeadingZeros,
TrailingZeros,
CountZeros,
LeadingOnes,
TrailingOnes,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LogKind {
Ilog2,
Ilog10,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RotateKind {
Left,
Right,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ShiftKind {
Left,
Right,
}
impl Intrinsic {
pub fn is_unary(self) -> bool {
matches!(
self,
Intrinsic::Unary(..)
| Intrinsic::Bits(_)
| Intrinsic::Ilog(_)
| Intrinsic::CheckedIlog(_)
| Intrinsic::Bool(
BoolKind::PowerOfTwo
| BoolKind::Ascii(_)
| BoolKind::Negative
| BoolKind::Positive
)
| Intrinsic::Abs
| Intrinsic::UnsignedAbs
| Intrinsic::SignednessCast
| Intrinsic::Signum
| Intrinsic::NextPowerOfTwo
| Intrinsic::CheckedNextPowerOfTwo
| Intrinsic::BitReverse
| Intrinsic::ByteSwap
| Intrinsic::ByteOrder(_)
| Intrinsic::AsciiCase(_)
| Intrinsic::OptionMethod(
OptionMethod::Unwrap
| OptionMethod::Expect
| OptionMethod::IsSuccess
| OptionMethod::IsFailure
)
)
}
}
#[derive(Clone, Copy, Debug)]
pub enum Outcome {
Value(Var),
Option { tag: Var, payload: Var },
Tuple { value: Var, overflowed: Pred },
Bool(Pred),
ValueOrPanic {
value: Var,
fails: Pred,
},
}
pub fn classify(name: &str) -> Option<Intrinsic> {
let short = name.rsplit("::").find(|s| !s.starts_with('<')).unwrap_or(name);
match short {
"count_ones" => return Some(Intrinsic::Bits(BitKind::Ones)),
"count_zeros" => return Some(Intrinsic::Bits(BitKind::CountZeros)),
"leading_zeros" => return Some(Intrinsic::Bits(BitKind::LeadingZeros)),
"leading_ones" => return Some(Intrinsic::Bits(BitKind::LeadingOnes)),
"trailing_zeros" => return Some(Intrinsic::Bits(BitKind::TrailingZeros)),
"trailing_ones" => return Some(Intrinsic::Bits(BitKind::TrailingOnes)),
_ => {}
}
if short == "is_power_of_two" {
return Some(Intrinsic::Bool(BoolKind::PowerOfTwo));
}
if short == "is_negative" {
return Some(Intrinsic::Bool(BoolKind::Negative));
}
if short == "is_positive" {
return Some(Intrinsic::Bool(BoolKind::Positive));
}
if short == "is_multiple_of" {
return Some(Intrinsic::Bool(BoolKind::MultipleOf));
}
if let Some(kind) = ascii_kind(short) {
return Some(Intrinsic::Bool(BoolKind::Ascii(kind)));
}
if names_slice_impl(name) {
if short == "is_empty" {
return Some(Intrinsic::SliceIsEmpty);
}
if short == "len" {
return Some(Intrinsic::SliceLen);
}
if short == "first" {
return Some(Intrinsic::SliceFirst);
}
if short == "last" {
return Some(Intrinsic::SliceLast);
}
if short == "get" || short.starts_with("get::<") {
return Some(Intrinsic::SliceGet);
}
}
if names_str_impl(name) {
if short == "is_empty" {
return Some(Intrinsic::SliceIsEmpty);
}
if short == "len" {
return Some(Intrinsic::SliceLen);
}
}
if names_vec_impl(name) {
match short {
"new" => return Some(Intrinsic::VecMethod(VecMethod::New)),
"push" => return Some(Intrinsic::VecMethod(VecMethod::Push)),
"len" => return Some(Intrinsic::VecMethod(VecMethod::Len)),
"is_empty" => return Some(Intrinsic::VecMethod(VecMethod::IsEmpty)),
"pop" => return Some(Intrinsic::VecMethod(VecMethod::Pop)),
_ => {}
}
}
if names_option_impl(name) {
match short {
"unwrap_or" => return Some(Intrinsic::OptionMethod(OptionMethod::UnwrapOr)),
"unwrap_or_default" => {
return Some(Intrinsic::OptionMethod(OptionMethod::UnwrapOrDefault))
}
"unwrap" => return Some(Intrinsic::OptionMethod(OptionMethod::Unwrap)),
"expect" => return Some(Intrinsic::OptionMethod(OptionMethod::Expect)),
"is_some" => return Some(Intrinsic::OptionMethod(OptionMethod::IsSuccess)),
"is_none" => return Some(Intrinsic::OptionMethod(OptionMethod::IsFailure)),
"ok_or" => return Some(Intrinsic::OptionMethod(OptionMethod::OkOr)),
"or" => return Some(Intrinsic::OptionMethod(OptionMethod::Or)),
"and" => return Some(Intrinsic::OptionMethod(OptionMethod::And)),
"copied" | "cloned" => {
return Some(Intrinsic::OptionMethod(OptionMethod::Copied))
}
_ => {}
}
}
if names_result_impl(name) {
match short {
"unwrap_or" => return Some(Intrinsic::OptionMethod(OptionMethod::UnwrapOr)),
"unwrap_or_default" => {
return Some(Intrinsic::OptionMethod(OptionMethod::UnwrapOrDefault))
}
"unwrap" => return Some(Intrinsic::OptionMethod(OptionMethod::Unwrap)),
"expect" => return Some(Intrinsic::OptionMethod(OptionMethod::Expect)),
"is_ok" => return Some(Intrinsic::OptionMethod(OptionMethod::IsSuccess)),
"is_err" => return Some(Intrinsic::OptionMethod(OptionMethod::IsFailure)),
"ok" => return Some(Intrinsic::OptionMethod(OptionMethod::Ok)),
"err" => return Some(Intrinsic::OptionMethod(OptionMethod::Err)),
_ => {}
}
}
if names_range(name) {
match short {
"new" => return Some(Intrinsic::Range(RangeMethod::New)),
"into_iter" => return Some(Intrinsic::Range(RangeMethod::IntoIter)),
"next" => return Some(Intrinsic::Range(RangeMethod::Next)),
_ => {}
}
}
if short == "branch" {
if !names_try(name) {
return None;
}
return Some(Intrinsic::TryBranch);
}
if short == "from_residual" {
if !names_from_residual(name) {
return None;
}
return Some(Intrinsic::FromResidual);
}
if short == "min" || short == "max" {
if !names_ord_trait(name) {
return None;
}
let kind = if short == "min" { MinMaxKind::Min } else { MinMaxKind::Max };
return Some(Intrinsic::MinMax(kind));
}
if let Some(kind) = partial_cmp_kind(short) {
if !names_cmp_trait(name) {
return None;
}
return Some(Intrinsic::Cmp(kind));
}
if short == "clamp" {
if !names_ord_trait(name) {
return None;
}
return Some(Intrinsic::Clamp);
}
if short == "cmp" {
if !names_ord_trait(name) {
return None;
}
return Some(Intrinsic::OrdCmp);
}
if short == "from" || short == "into" {
if !names_conversion_trait(name) {
return None;
}
let kind = if short == "from" { Conversion::From } else { Conversion::Into };
return Some(Intrinsic::Conversion(kind));
}
if short == "abs" {
return Some(Intrinsic::Abs);
}
if short == "unsigned_abs" {
return Some(Intrinsic::UnsignedAbs);
}
if short == "abs_diff" {
return Some(Intrinsic::AbsDiff);
}
if short == "rotate_left" {
return Some(Intrinsic::Rotate(RotateKind::Left));
}
if short == "rotate_right" {
return Some(Intrinsic::Rotate(RotateKind::Right));
}
if short == "wrapping_shl" {
return Some(Intrinsic::WrappingShift(ShiftKind::Left));
}
if short == "wrapping_shr" {
return Some(Intrinsic::WrappingShift(ShiftKind::Right));
}
if short == "signum" {
return Some(Intrinsic::Signum);
}
if short == "cast_unsigned" || short == "cast_signed" {
return Some(Intrinsic::SignednessCast);
}
if short == "div_euclid" {
return Some(Intrinsic::DivEuclid);
}
if short == "rem_euclid" {
return Some(Intrinsic::RemEuclid);
}
if short == "div_ceil" {
return Some(Intrinsic::DivCeil);
}
if short == "midpoint" {
return Some(Intrinsic::Midpoint);
}
if short == "next_multiple_of" {
return Some(Intrinsic::NextMultipleOf);
}
if short == "checked_next_multiple_of" {
return Some(Intrinsic::CheckedNextMultipleOf);
}
if short == "next_power_of_two" {
return Some(Intrinsic::NextPowerOfTwo);
}
if short == "checked_next_power_of_two" {
return Some(Intrinsic::CheckedNextPowerOfTwo);
}
if short == "ilog2" {
return Some(Intrinsic::Ilog(LogKind::Ilog2));
}
if short == "ilog10" {
return Some(Intrinsic::Ilog(LogKind::Ilog10));
}
if short == "checked_ilog2" {
return Some(Intrinsic::CheckedIlog(LogKind::Ilog2));
}
if short == "checked_ilog10" {
return Some(Intrinsic::CheckedIlog(LogKind::Ilog10));
}
if short == "pow" {
return Some(Intrinsic::PowPanic);
}
if short == "reverse_bits" {
return Some(Intrinsic::BitReverse);
}
if short == "swap_bytes" {
return Some(Intrinsic::ByteSwap);
}
if let Some(kind) = byte_order_kind(short) {
return Some(Intrinsic::ByteOrder(kind));
}
if let Some(kind) = ascii_case_kind(short) {
return Some(Intrinsic::AsciiCase(kind));
}
let (family, op) = if let Some(rest) = short.strip_prefix("wrapping_") {
(Family::Wrapping, rest)
} else if let Some(rest) = short.strip_prefix("saturating_") {
(Family::Saturating, rest)
} else if let Some(rest) = short.strip_prefix("overflowing_") {
(Family::Overflowing, rest)
} else {
(Family::Checked, short.strip_prefix("checked_")?)
};
match op {
"neg" => return Some(Intrinsic::Unary(family, UnOp::Neg)),
"abs" => return Some(Intrinsic::Unary(family, UnOp::Abs)),
"add_signed" | "add_unsigned" => return Some(Intrinsic::MixedAdd(family)),
"pow" => return Some(Intrinsic::Pow(family)),
_ => {}
}
let op = match op {
"add" => BinOp::Add,
"sub" => BinOp::Sub,
"mul" => BinOp::Mul,
"and" => BinOp::BitAnd,
"or" => BinOp::BitOr,
"xor" => BinOp::BitXor,
"div" => BinOp::Div,
"rem" => BinOp::Rem,
_ => return None,
};
Some(match family {
Family::Wrapping => Intrinsic::Wrapping(op),
Family::Saturating => Intrinsic::Saturating(op),
Family::Checked => Intrinsic::Checked(op),
Family::Overflowing => Intrinsic::Overflowing(op),
})
}
pub fn names_ord_trait(name: &str) -> bool {
matches!(trait_path(name), Some("Ord" | "core::cmp::Ord" | "std::cmp::Ord"))
}
pub fn partial_cmp_kind(short: &str) -> Option<PartialCmpKind> {
Some(match short {
"eq" => PartialCmpKind::Eq,
"ne" => PartialCmpKind::Ne,
"lt" => PartialCmpKind::Lt,
"le" => PartialCmpKind::Le,
"gt" => PartialCmpKind::Gt,
"ge" => PartialCmpKind::Ge,
_ => return None,
})
}
pub fn names_cmp_trait(name: &str) -> bool {
let Some(path) = trait_path(name) else { return false };
let Some(short) = name.rsplit("::").next() else { return false };
let eq_trait = matches!(path, "PartialEq" | "core::cmp::PartialEq" | "std::cmp::PartialEq");
let ord_trait =
matches!(path, "PartialOrd" | "core::cmp::PartialOrd" | "std::cmp::PartialOrd");
match short {
"eq" | "ne" => eq_trait,
"lt" | "le" | "gt" | "ge" => ord_trait,
_ => false,
}
}
pub fn names_try(name: &str) -> bool {
matches!(trait_path(name), Some("Try" | "core::ops::Try" | "std::ops::Try"))
}
pub fn names_from_residual(name: &str) -> bool {
matches!(
trait_path(name),
Some("FromResidual" | "core::ops::FromResidual" | "std::ops::FromResidual")
)
}
pub fn names_slice_impl(name: &str) -> bool {
name.contains("slice::<impl [")
}
pub fn names_str_impl(name: &str) -> bool {
name.contains("str::<impl str>")
}
pub fn names_vec_impl(name: &str) -> bool {
name.contains("vec::Vec") || name.starts_with("Vec::")
}
pub fn names_option_impl(name: &str) -> bool {
name.contains("option::Option") || name.starts_with("Option::")
}
pub fn names_result_impl(name: &str) -> bool {
name.contains("result::Result") || name.starts_with("Result::")
}
pub fn names_range(name: &str) -> bool {
let has_type = |seg: &str| {
name.match_indices(seg).any(|(i, _)| {
matches!(name[i + seg.len()..].chars().next(), None | Some(':') | Some('<') | Some('>'))
})
};
let is_range = has_type("ops::RangeInclusive")
|| has_type("ops::Range")
|| name.starts_with("RangeInclusive::")
|| name.starts_with("Range::")
|| name.starts_with("<RangeInclusive<")
|| name.starts_with("<Range<");
if !is_range {
return false;
}
match name.rsplit("::").next() {
Some("new") => true,
Some("into_iter") => names_std_range_trait(name, "IntoIterator"),
Some("next") => names_std_range_trait(name, "Iterator"),
_ => false,
}
}
fn names_std_range_trait(name: &str, want: &str) -> bool {
let Some(after) = name.rsplit_once(" as ").map(|(_, a)| a) else {
return false;
};
after.starts_with(&format!("{want}>")) || after.starts_with(&format!("{want}<"))
}
pub fn names_conversion_trait(name: &str) -> bool {
matches!(
trait_path(name),
Some(
"From"
| "core::convert::From"
| "std::convert::From"
| "Into"
| "core::convert::Into"
| "std::convert::Into"
)
)
}
fn trait_path(name: &str) -> Option<&str> {
let after_as = name.rsplit_once(" as ")?.1;
let (trait_ty, _) = after_as.split_once(">::")?;
Some(trait_ty.split_once('<').map(|(t, _)| t).unwrap_or(trait_ty))
}
pub fn is_modelled(op: Intrinsic, w: u8, signed: bool) -> bool {
if w == 0 || w > 64 {
return false;
}
match op {
Intrinsic::Bits(_) => true,
Intrinsic::Bool(BoolKind::Ascii(_)) => !signed,
Intrinsic::Bool(BoolKind::PowerOfTwo) => !signed,
Intrinsic::Bool(BoolKind::Negative | BoolKind::Positive) => signed,
Intrinsic::Bool(BoolKind::MultipleOf) => !signed,
Intrinsic::SliceLen
| Intrinsic::SliceIsEmpty
| Intrinsic::SliceFirst
| Intrinsic::SliceGet
| Intrinsic::SliceLast => true,
Intrinsic::VecMethod(_) => true,
Intrinsic::OptionMethod(_) => true,
Intrinsic::Range(_) => true,
Intrinsic::TryBranch | Intrinsic::FromResidual => true,
Intrinsic::OrdCmp => true,
Intrinsic::AbsDiff => (1..64).contains(&w),
Intrinsic::Rotate(_) => (1..=64).contains(&w) && w.is_power_of_two(),
Intrinsic::WrappingShift(_) => (1..=64).contains(&w) && w.is_power_of_two(),
Intrinsic::Signum => signed,
Intrinsic::DivEuclid | Intrinsic::RemEuclid => w <= DIV_MAX_WIDTH,
Intrinsic::DivCeil => !signed && w <= DIV_MAX_WIDTH,
Intrinsic::Midpoint => true,
Intrinsic::NextMultipleOf => !signed && w <= DIV_MAX_WIDTH,
Intrinsic::CheckedNextMultipleOf => !signed && w <= DIV_MAX_WIDTH,
Intrinsic::Ilog(_) => true,
Intrinsic::CheckedIlog(_) => true,
Intrinsic::NextPowerOfTwo | Intrinsic::CheckedNextPowerOfTwo => !signed,
Intrinsic::BitReverse | Intrinsic::ByteSwap | Intrinsic::ByteOrder(_) => true,
Intrinsic::AsciiCase(_) => !signed && w == 8,
Intrinsic::Unary(family, un) => match un {
UnOp::Abs => signed,
UnOp::Neg => !(family == Family::Saturating && !signed),
},
Intrinsic::Abs => signed,
Intrinsic::UnsignedAbs => signed,
Intrinsic::SignednessCast => true,
Intrinsic::Clamp => true,
Intrinsic::Wrapping(bin)
| Intrinsic::Saturating(bin)
| Intrinsic::Checked(bin)
| Intrinsic::Overflowing(bin) => match bin {
BinOp::Div | BinOp::Rem => {
matches!(op, Intrinsic::Checked(_)) && w <= DIV_MAX_WIDTH
}
BinOp::Mul => w <= MUL_MAX_WIDTH,
BinOp::Add | BinOp::Sub | BinOp::BitAnd | BinOp::BitOr | BinOp::BitXor => true,
BinOp::Shl | BinOp::Shr | BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt
| BinOp::Ge => false,
},
Intrinsic::Pow(_) => w <= POW_MAX_WIDTH,
Intrinsic::PowPanic => w <= POW_MAX_WIDTH,
Intrinsic::MixedAdd(_) => true,
Intrinsic::MinMax(_) => true,
Intrinsic::Cmp(_) => true,
Intrinsic::Conversion(_) => true,
}
}
pub fn eval(op: Intrinsic, x: Var, y: Var, w: u8, signed: bool, result_w: u8) -> Option<Outcome> {
if !is_modelled(op, w, signed) {
return None;
}
if matches!(
op,
Intrinsic::SliceLen
| Intrinsic::SliceIsEmpty
| Intrinsic::SliceFirst
| Intrinsic::SliceGet
| Intrinsic::SliceLast
) {
return None;
}
if matches!(op, Intrinsic::VecMethod(_)) {
return None;
}
if matches!(op, Intrinsic::OptionMethod(_)) {
return None;
}
if matches!(op, Intrinsic::Range(_)) {
return None;
}
if matches!(op, Intrinsic::TryBranch | Intrinsic::FromResidual) {
return None;
}
if matches!(op, Intrinsic::OrdCmp) {
return None;
}
Some(match op {
Intrinsic::SliceLen
| Intrinsic::SliceIsEmpty
| Intrinsic::SliceFirst
| Intrinsic::SliceGet
| Intrinsic::SliceLast => {
unreachable!("slice shapes are answered from the executor's stores")
}
Intrinsic::OptionMethod(_) => {
unreachable!("Option methods are answered from the tag and payload stores")
}
Intrinsic::Range(_) => {
unreachable!("range methods are answered from the struct field store")
}
Intrinsic::VecMethod(_) => {
unreachable!("Vec methods are answered from the length store")
}
Intrinsic::TryBranch | Intrinsic::FromResidual => {
unreachable!("the `?` operator's calls are answered from the enum stores")
}
Intrinsic::OrdCmp => {
unreachable!("`Ord::cmp` is answered from the discriminant store")
}
Intrinsic::Bits(kind) => {
if result_w == 0 || result_w > 64 {
return None;
}
Outcome::Value(smt::truncate(bit_count(kind, x), result_w))
}
Intrinsic::Bool(kind) => Outcome::Bool(bool_pred(kind, x, y)),
Intrinsic::Unary(family, un) => {
if result_w == 0 || result_w > 64 {
return None;
}
let fails = unary_failure(un, x, w, signed)?;
let plain = unary_result(un, x, w);
match family {
Family::Wrapping => Outcome::Value(smt::truncate(plain, result_w)),
Family::Saturating => {
let (_, hi) = bounds(w, signed)?;
Outcome::Value(smt::truncate(smt::ite(fails, hi, plain), result_w))
}
Family::Checked => Outcome::Option {
tag: smt::ite(fails, smt::word(0, w), smt::word(1, w)),
payload: smt::truncate(plain, result_w),
},
Family::Overflowing => {
Outcome::Tuple { value: smt::truncate(plain, result_w), overflowed: fails }
}
}
}
Intrinsic::Wrapping(bin) => {
if result_w == 0 || result_w > 64 {
return None;
}
let plain = plain_result(bin, x, y, signed)?;
Outcome::Value(smt::truncate(plain, result_w))
}
Intrinsic::Saturating(bin) => {
if result_w == 0 || result_w > 64 {
return None;
}
let plain = plain_result(bin, x, y, signed)?;
let bound = saturation_bound(bin, x, y, w, signed)?;
let fails = failure(bin, x, y, w, signed)?;
Outcome::Value(smt::truncate(smt::ite(fails, bound, plain), result_w))
}
Intrinsic::Checked(bin) => {
if result_w == 0 || result_w > 64 {
return None;
}
let plain = plain_result(bin, x, y, signed)?;
let fails = failure(bin, x, y, w, signed)?;
Outcome::Option {
tag: smt::ite(fails, smt::word(0, w), smt::word(1, w)),
payload: smt::truncate(plain, result_w),
}
}
Intrinsic::Overflowing(bin) => {
if result_w == 0 || result_w > 64 {
return None;
}
let plain = plain_result(bin, x, y, signed)?;
let fails = failure(bin, x, y, w, signed)?;
Outcome::Tuple { value: smt::truncate(plain, result_w), overflowed: fails }
}
Intrinsic::Pow(family) => {
if result_w != w {
return None;
}
let (value, fails) = pow_fold(x, y, w, signed)?;
match family {
Family::Wrapping => Outcome::Value(value),
Family::Saturating => {
Outcome::Value(smt::ite(fails, saturation_end(x, y, w, signed)?, value))
}
Family::Checked => Outcome::Option {
tag: smt::ite(fails, smt::word(0, w), smt::word(1, w)),
payload: value,
},
Family::Overflowing => Outcome::Tuple { value, overflowed: fails },
}
}
Intrinsic::PowPanic => {
if result_w != w {
return None;
}
let (value, fails) = pow_fold(x, y, w, signed)?;
Outcome::ValueOrPanic { value, fails }
}
Intrinsic::MixedAdd(family) => {
if result_w == 0 || result_w > 64 {
return None;
}
let plain = mixed_add_result(x, y);
let fails = mixed_add_failure(x, y, w, signed)?;
match family {
Family::Wrapping => Outcome::Value(smt::truncate(plain, result_w)),
Family::Saturating => {
let (_, hi) = bounds(w, signed)?;
let bound = if signed {
hi
} else {
smt::ite(smt::negative(y), smt::word(0, w), hi)
};
Outcome::Value(smt::truncate(smt::ite(fails, bound, plain), result_w))
}
Family::Checked => Outcome::Option {
tag: smt::ite(fails, smt::word(0, w), smt::word(1, w)),
payload: smt::truncate(plain, result_w),
},
Family::Overflowing => {
Outcome::Tuple { value: smt::truncate(plain, result_w), overflowed: fails }
}
}
}
Intrinsic::MinMax(kind) => {
if result_w == 0 || result_w > 64 {
return None;
}
Outcome::Value(smt::truncate(min_max_result(kind, x, y, signed), result_w))
}
Intrinsic::Cmp(kind) => Outcome::Bool(cmp_pred(kind, x, y, signed)),
Intrinsic::Conversion(_) => {
if result_w < w {
return None;
}
Outcome::Value(convert_value(x, signed, result_w))
}
Intrinsic::Abs => {
if result_w == 0 || result_w > 64 {
return None;
}
let fails = unary_failure(UnOp::Abs, x, w, signed)?;
Outcome::ValueOrPanic { value: smt::truncate(unary_result(UnOp::Abs, x, w), result_w), fails }
}
Intrinsic::UnsignedAbs => {
if result_w == 0 || result_w > 64 {
return None;
}
Outcome::Value(smt::truncate(unary_result(UnOp::Abs, x, w), result_w))
}
Intrinsic::SignednessCast => {
if result_w == 0 || result_w > 64 {
return None;
}
Outcome::Value(smt::truncate(x, result_w))
}
Intrinsic::AbsDiff => {
if w == 0 || w > 63 {
return None;
}
let wide = w + 1;
let diff = smt::sub(
if signed { smt::sign_extend(x, wide) } else { smt::truncate(x, wide) },
if signed { smt::sign_extend(y, wide) } else { smt::truncate(y, wide) },
);
let mag = smt::ite(
smt::slt(diff, smt::word(0, wide)),
smt::sub(smt::word(0, wide), diff),
diff,
);
Outcome::Value(smt::truncate(mag, w))
}
Intrinsic::Rotate(kind) => {
if w == 0 || w > 64 {
return None;
}
Outcome::Value(rotate(x, y, w, kind))
}
Intrinsic::WrappingShift(kind) => {
if w == 0 || w > 64 {
return None;
}
Outcome::Value(wrapping_shift(x, y, w, signed, kind))
}
Intrinsic::Signum => {
if result_w == 0 || result_w > 64 {
return None;
}
let zero = smt::word(0, w);
let minus_one = smt::all_ones(w);
let one = smt::word(1, w);
let v = smt::ite(smt::slt(x, zero), minus_one, smt::ite(smt::sgt(x, zero), one, zero));
Outcome::Value(smt::truncate(v, result_w))
}
Intrinsic::DivEuclid => {
if result_w == 0 || result_w > 64 {
return None;
}
let fails = failure(BinOp::Div, x, y, w, signed)?;
let value = if signed {
div_euclid_value(x, y, w)
} else {
smt::udiv(x, y)
};
Outcome::ValueOrPanic { value: smt::truncate(value, result_w), fails }
}
Intrinsic::RemEuclid => {
if result_w == 0 || result_w > 64 {
return None;
}
let fails = failure(BinOp::Rem, x, y, w, signed)?;
let value = if signed {
rem_euclid_value(x, y, w)
} else {
smt::urem(x, y)
};
Outcome::ValueOrPanic { value: smt::truncate(value, result_w), fails }
}
Intrinsic::DivCeil => {
if result_w == 0 || result_w > 64 {
return None;
}
let fails = failure(BinOp::Div, x, y, w, signed)?;
Outcome::ValueOrPanic { value: smt::truncate(div_ceil_value(x, y, w), result_w), fails }
}
Intrinsic::Midpoint => {
if result_w == 0 || result_w > 64 {
return None;
}
Outcome::Value(smt::truncate(midpoint(x, y, w, signed), result_w))
}
Intrinsic::NextMultipleOf => {
if result_w == 0 || result_w > 64 {
return None;
}
let fails = next_multiple_fails(x, y);
Outcome::ValueOrPanic {
value: smt::truncate(next_multiple_value(x, y), result_w),
fails,
}
}
Intrinsic::CheckedNextMultipleOf => {
if result_w == 0 || result_w > 64 {
return None;
}
let fails = next_multiple_fails(x, y);
Outcome::Option {
tag: smt::ite(fails, smt::word(0, w), smt::word(1, w)),
payload: smt::truncate(next_multiple_value(x, y), result_w),
}
}
Intrinsic::Ilog(kind) => {
if result_w == 0 || result_w > 64 {
return None;
}
let fails = ilog_fails(x, signed);
Outcome::ValueOrPanic { value: smt::truncate(ilog_value(kind, x, w), result_w), fails }
}
Intrinsic::CheckedIlog(kind) => {
if result_w == 0 || result_w > 64 {
return None;
}
let fails = ilog_fails(x, signed);
Outcome::Option {
tag: smt::ite(fails, smt::word(0, w), smt::word(1, w)),
payload: smt::truncate(ilog_value(kind, x, w), result_w),
}
}
Intrinsic::NextPowerOfTwo => {
if result_w != w {
return None;
}
Outcome::ValueOrPanic { value: next_power_of_two_value(x, w), fails: next_power_of_two_fails(x, w) }
}
Intrinsic::CheckedNextPowerOfTwo => {
if result_w != w {
return None;
}
let fails = next_power_of_two_fails(x, w);
Outcome::Option {
tag: smt::ite(fails, smt::word(0, w), smt::word(1, w)),
payload: next_power_of_two_value(x, w),
}
}
Intrinsic::BitReverse => Outcome::Value(smt::truncate(bit_reverse(x), result_w)),
Intrinsic::ByteSwap => Outcome::Value(smt::truncate(byte_swap(x, w), result_w)),
Intrinsic::ByteOrder(kind) => {
Outcome::Value(smt::truncate(byte_order_value(x, w, kind), result_w))
}
Intrinsic::AsciiCase(kind) => {
Outcome::Value(smt::truncate(ascii_case_value(x, kind), result_w))
}
Intrinsic::Clamp => return None,
})
}
pub fn rotate(x: Var, n: Var, w: u8, kind: RotateKind) -> Var {
let bits = (w as u32).trailing_zeros();
let low_mask = if bits >= 32 { u32::MAX } else { (1u32 << bits) - 1 };
let low = smt::band(n, smt::word(low_mask as u64, smt::bits(n)));
match kind {
RotateKind::Left => {
let hi = smt::shift_var(smt::Shift::Left, x, low);
let lo = smt::shift_var(smt::Shift::LogicalRight, x, smt::sub(smt::word(w as u64, smt::bits(n)), low));
smt::bor(hi, lo)
}
RotateKind::Right => {
let lo = smt::shift_var(smt::Shift::LogicalRight, x, low);
let hi = smt::shift_var(smt::Shift::Left, x, smt::sub(smt::word(w as u64, smt::bits(n)), low));
smt::bor(lo, hi)
}
}
}
pub fn wrapping_shift(x: Var, n: Var, w: u8, signed: bool, kind: ShiftKind) -> Var {
let bits = (w as u32).trailing_zeros();
let low_mask = if bits >= 32 { u32::MAX } else { (1u32 << bits) - 1 };
let low = smt::band(n, smt::word(low_mask as u64, smt::bits(n)));
match kind {
ShiftKind::Left => smt::shift_var(smt::Shift::Left, x, low),
ShiftKind::Right => {
let dir = if signed {
smt::Shift::ArithmeticRight
} else {
smt::Shift::LogicalRight
};
smt::shift_var(dir, x, low)
}
}
}
pub fn clamp(x: Var, lo: Var, hi: Var, w: u8, signed: bool) -> Option<Outcome> {
if !is_modelled(Intrinsic::Clamp, w, signed) {
return None;
}
let (below, above) = if signed {
(smt::slt(x, lo), smt::slt(hi, x))
} else {
(smt::ult(x, lo), smt::ult(hi, x))
};
let too_high = if signed { smt::slt(hi, lo) } else { smt::ult(hi, lo) };
let value = smt::ite(below, lo, smt::ite(above, hi, x));
Some(Outcome::ValueOrPanic { value, fails: too_high })
}
fn min_max_result(kind: MinMaxKind, x: Var, y: Var, signed: bool) -> Var {
let take_x = match (kind, signed) {
(MinMaxKind::Min, true) => smt::sle(x, y),
(MinMaxKind::Min, false) => smt::ule(x, y),
(MinMaxKind::Max, true) => smt::sge(x, y),
(MinMaxKind::Max, false) => smt::ule(y, x),
};
smt::ite(take_x, x, y)
}
fn div_euclid_value(x: Var, y: Var, w: u8) -> Var {
let q = smt::sdiv(x, y);
let r = smt::srem(x, y);
let zero = smt::word(0, w);
let one = smt::word(1, w);
let bump = smt::ite(smt::sgt(y, zero), smt::sub(q, one), smt::add(q, one));
smt::ite(smt::slt(r, zero), bump, q)
}
fn rem_euclid_value(x: Var, y: Var, w: u8) -> Var {
let r = smt::srem(x, y);
let zero = smt::word(0, w);
let abs_y = smt::ite(smt::slt(y, zero), smt::sub(zero, y), y);
smt::ite(smt::slt(r, zero), smt::add(r, abs_y), r)
}
fn div_ceil_value(x: Var, y: Var, w: u8) -> Var {
let q = smt::udiv(x, y);
let r = smt::urem(x, y);
let one = smt::word(1, w);
smt::ite(smt::eq_const(r, 0), q, smt::add(q, one))
}
fn midpoint(x: Var, y: Var, w: u8, signed: bool) -> Var {
let both = smt::band(x, y);
let diff = smt::bxor(x, y);
let half = if signed { smt::ashr(diff, 1) } else { smt::lshr(diff, 1) };
let floor = smt::add(both, half);
if !signed {
return floor;
}
let odd = smt::band(diff, smt::word(1, w));
let correction = smt::ite(smt::slt(floor, smt::word(0, w)), odd, smt::word(0, w));
smt::add(floor, correction)
}
fn next_multiple_value(x: Var, y: Var) -> Var {
let r = smt::urem(x, y);
let delta = smt::urem(smt::sub(y, r), y);
smt::add(x, delta)
}
fn next_multiple_fails(x: Var, y: Var) -> Pred {
let delta = smt::urem(smt::sub(y, smt::urem(x, y)), y);
let sum = smt::add(x, delta);
let overflow = smt::ult(sum, x);
smt::or(smt::eq_const(y, 0), overflow)
}
fn ilog_value(kind: LogKind, x: Var, w: u8) -> Var {
match kind {
LogKind::Ilog2 => {
let lz = bit_count(BitKind::LeadingZeros, x);
smt::sub(smt::word(u64::from(w) - 1, w), lz)
}
LogKind::Ilog10 => {
let one = smt::word(1, w);
let mut acc = smt::word(0, w);
for pow in POWERS_OF_TEN {
if pow > max_of_width(w) {
break;
}
acc = smt::add(acc, smt::ite(smt::uge_const(x, pow), one, smt::word(0, w)));
}
acc
}
}
}
const POWERS_OF_TEN: [u64; 19] = [
10,
100,
1_000,
10_000,
100_000,
1_000_000,
10_000_000,
100_000_000,
1_000_000_000,
10_000_000_000,
100_000_000_000,
1_000_000_000_000,
10_000_000_000_000,
100_000_000_000_000,
1_000_000_000_000_000,
10_000_000_000_000_000,
100_000_000_000_000_000,
1_000_000_000_000_000_000,
10_000_000_000_000_000_000,
];
fn max_of_width(w: u8) -> u64 {
if w >= 64 {
u64::MAX
} else {
(1u64 << w) - 1
}
}
fn ilog_fails(x: Var, signed: bool) -> Pred {
if signed {
smt::sle(x, smt::word(0, smt::bits(x)))
} else {
smt::eq_const(x, 0)
}
}
fn next_power_of_two_value(x: Var, w: u8) -> Var {
let one = smt::word(1, w);
let p = smt::ite(smt::ule_const(x, 1), smt::word(0, w), smt::sub(x, one));
let mut acc = p;
let mut shift = 1u32;
while shift < u32::from(w) {
acc = smt::bor(acc, smt::lshr(acc, shift));
shift <<= 1;
}
smt::add(acc, one)
}
fn next_power_of_two_fails(x: Var, w: u8) -> Pred {
smt::eq_const(next_power_of_two_value(x, w), 0)
}
fn bit_reverse(x: Var) -> Var {
let w = smt::bits(x);
let mut acc = smt::word(0, w);
for k in 0..w {
let src = (w - 1 - k) as u32;
let bit = smt::band(smt::lshr(x, src), smt::word(1, w));
acc = smt::bor(acc, smt::shl(bit, k as u32));
}
acc
}
fn byte_swap(x: Var, w: u8) -> Var {
if w <= 8 {
return x;
}
let half = smt::word(u64::from(w) / 2, w);
rotate(x, half, w, RotateKind::Left)
}
fn byte_order_value(x: Var, w: u8, kind: ByteOrderKind) -> Var {
let big_endian = cfg!(target_endian = "big");
let swap = match kind {
ByteOrderKind::Be => !big_endian,
ByteOrderKind::Le => big_endian,
};
if swap {
byte_swap(x, w)
} else {
x
}
}
fn ascii_case_value(x: Var, kind: AsciiCaseKind) -> Var {
let w = smt::bits(x);
let (lo, hi, delta) = match kind {
AsciiCaseKind::Upper => (b'a' as u64, b'z' as u64, -32i64),
AsciiCaseKind::Lower => (b'A' as u64, b'Z' as u64, 32i64),
};
let in_range =
smt::and(smt::ule_const(x, hi), smt::ule(smt::word(lo, w), x));
let shifted = if delta < 0 {
smt::sub(x, smt::word(delta.unsigned_abs(), w))
} else {
smt::add(x, smt::word(delta as u64, w))
};
smt::ite(in_range, shifted, x)
}
fn unary_result(un: UnOp, x: Var, w: u8) -> Var {
match un {
UnOp::Neg => smt::sub(smt::word(0, w), x),
UnOp::Abs => smt::ite(smt::negative(x), smt::sub(smt::word(0, w), x), x),
}
}
fn unary_failure(un: UnOp, x: Var, w: u8, signed: bool) -> Option<Pred> {
match un {
UnOp::Abs if !signed => None,
UnOp::Abs | UnOp::Neg if !signed => Some(smt::not(smt::eq_const(x, 0))),
UnOp::Abs => Some(smt::eq_const(x, min_value(w)?)),
UnOp::Neg => Some(smt::eq_const(x, min_value(w)?)),
}
}
fn bit_count(kind: BitKind, x: Var) -> Var {
let w = smt::bits(x);
let one = smt::word(1, w);
let zero = smt::word(0, w);
let bit = |k: u8| smt::ite(smt::bit_set(x, u32::from(k)), one, zero);
let mut acc = zero;
match kind {
BitKind::Ones => {
for k in 0..w {
acc = smt::add(acc, bit(k));
}
}
BitKind::LeadingZeros => {
for k in 0..w {
acc = smt::add(acc, smt::ite(smt::ult_const(x, 1u64 << k), one, zero));
}
}
BitKind::TrailingZeros => {
for k in 1..=w {
let mask = if k == w {
smt::all_ones(w)
} else {
smt::word((1u64 << k) - 1, w)
};
let low = smt::band(x, mask);
acc = smt::add(acc, smt::ite(smt::eq_const(low, 0), one, zero));
}
}
BitKind::CountZeros => return bit_count(BitKind::Ones, not_bits(x)),
BitKind::LeadingOnes => return bit_count(BitKind::LeadingZeros, not_bits(x)),
BitKind::TrailingOnes => return bit_count(BitKind::TrailingZeros, not_bits(x)),
}
acc
}
fn not_bits(x: Var) -> Var {
let w = smt::bits(x);
smt::bxor(x, smt::all_ones(w))
}
fn ascii_kind(short: &str) -> Option<AsciiKind> {
Some(match short {
"is_ascii_digit" => AsciiKind::Digit,
"is_ascii_alphabetic" => AsciiKind::Alphabetic,
"is_ascii_alphanumeric" => AsciiKind::Alphanumeric,
"is_ascii_uppercase" => AsciiKind::Uppercase,
"is_ascii_lowercase" => AsciiKind::Lowercase,
"is_ascii_hexdigit" => AsciiKind::HexDigit,
"is_ascii_whitespace" => AsciiKind::Whitespace,
"is_ascii_punctuation" => AsciiKind::Punctuation,
"is_ascii_control" => AsciiKind::Control,
"is_ascii" => AsciiKind::Ascii,
_ => return None,
})
}
fn byte_order_kind(short: &str) -> Option<ByteOrderKind> {
Some(match short {
"to_be" | "from_be" => ByteOrderKind::Be,
"to_le" | "from_le" => ByteOrderKind::Le,
_ => return None,
})
}
fn ascii_case_kind(short: &str) -> Option<AsciiCaseKind> {
Some(match short {
"to_ascii_uppercase" => AsciiCaseKind::Upper,
"to_ascii_lowercase" => AsciiCaseKind::Lower,
_ => return None,
})
}
fn cmp_pred(kind: PartialCmpKind, x: Var, y: Var, signed: bool) -> Pred {
match kind {
PartialCmpKind::Eq => smt::eq(x, y),
PartialCmpKind::Ne => smt::not(smt::eq(x, y)),
PartialCmpKind::Lt => {
if signed {
smt::slt(x, y)
} else {
smt::ult(x, y)
}
}
PartialCmpKind::Le => {
if signed {
smt::sle(x, y)
} else {
smt::ule(x, y)
}
}
PartialCmpKind::Gt => {
if signed {
smt::sgt(x, y)
} else {
smt::ult(y, x)
}
}
PartialCmpKind::Ge => {
if signed {
smt::sge(x, y)
} else {
smt::ule(y, x)
}
}
}
}
fn bool_pred(kind: BoolKind, x: Var, y: Var) -> Pred {
match kind {
BoolKind::PowerOfTwo => {
let w = smt::bits(x);
let cleared = smt::band(x, smt::sub(x, smt::word(1, w)));
smt::and(smt::not(smt::eq_const(x, 0)), smt::eq_const(cleared, 0))
}
BoolKind::Ascii(kind) => ascii_pred(kind, x),
BoolKind::Negative => smt::slt(x, smt::word(0, smt::bits(x))),
BoolKind::Positive => smt::sgt(x, smt::word(0, smt::bits(x))),
BoolKind::MultipleOf => smt::or(
smt::and(smt::not(smt::eq_const(y, 0)), smt::eq_const(smt::urem(x, y), 0)),
smt::eq_const(x, 0),
),
}
}
fn ascii_pred(kind: AsciiKind, x: Var) -> Pred {
let in_range = |lo: u8, hi: u8| -> Pred {
let w = smt::bits(x);
let lo = smt::word(lo as u64, w);
let hi = smt::word(hi as u64, w);
smt::and(smt::ule(lo, x), smt::ule(x, hi))
};
match kind {
AsciiKind::Digit => in_range(b'0', b'9'),
AsciiKind::Uppercase => in_range(b'A', b'Z'),
AsciiKind::Lowercase => in_range(b'a', b'z'),
AsciiKind::Alphabetic => smt::or(in_range(b'A', b'Z'), in_range(b'a', b'z')),
AsciiKind::Alphanumeric => smt::or(
in_range(b'0', b'9'),
smt::or(in_range(b'A', b'Z'), in_range(b'a', b'z')),
),
AsciiKind::HexDigit => smt::or(
in_range(b'0', b'9'),
smt::or(in_range(b'A', b'F'), in_range(b'a', b'f')),
),
AsciiKind::Whitespace => [0x20u64, 0x09, 0x0a, 0x0c, 0x0d]
.into_iter()
.map(|c| smt::eq_const(x, c))
.reduce(smt::or)
.unwrap_or_else(|| smt::truth(false)),
AsciiKind::Punctuation => smt::or(
in_range(b'!', b'/'),
smt::or(in_range(b':', b'@'), smt::or(in_range(b'[', b'`'), in_range(b'{', b'~'))),
),
AsciiKind::Control => smt::or(in_range(0, 0x1f), smt::eq_const(x, 0x7f)),
AsciiKind::Ascii => {
let w = smt::bits(x);
smt::ult(x, smt::word(128, w))
}
}
}
fn plain_result(op: BinOp, x: Var, y: Var, signed: bool) -> Option<Var> {
Some(match op {
BinOp::Add => smt::add(x, y),
BinOp::Sub => smt::sub(x, y),
BinOp::Mul => smt::mul(x, y),
BinOp::BitAnd => smt::band(x, y),
BinOp::BitOr => smt::bor(x, y),
BinOp::BitXor => smt::bxor(x, y),
BinOp::Div if signed => smt::sdiv(x, y),
BinOp::Rem if signed => smt::srem(x, y),
BinOp::Div => smt::udiv(x, y),
BinOp::Rem => smt::urem(x, y),
_ => return None,
})
}
fn failure(op: BinOp, x: Var, y: Var, w: u8, signed: bool) -> Option<Pred> {
Some(match op {
BinOp::Add if signed => {
let sum = smt::add(x, y);
smt::and(
smt::iff(smt::negative(x), smt::negative(y)),
smt::xor(smt::negative(x), smt::negative(sum)),
)
}
BinOp::Add => smt::ult(smt::add(x, y), x),
BinOp::Sub if signed => {
let diff = smt::sub(x, y);
smt::and(
smt::xor(smt::negative(x), smt::negative(y)),
smt::iff(smt::negative(y), smt::negative(diff)),
)
}
BinOp::Sub => smt::ult(x, y),
BinOp::Mul => return mul_failure(x, y, w, signed),
BinOp::Div | BinOp::Rem if signed => {
let min = min_value(w)?;
let zero_divisor = smt::eq_const(y, 0);
let min_by_neg_one =
smt::and(smt::eq_const(x, min), smt::eq_const(y, all_ones_value(w)));
smt::or(zero_divisor, min_by_neg_one)
}
BinOp::Div | BinOp::Rem => smt::eq_const(y, 0),
_ => return None,
})
}
fn mul_failure(x: Var, y: Var, w: u8, signed: bool) -> Option<Pred> {
let wide = w.saturating_mul(2).min(64);
if wide <= w || wide > 64 {
return None;
}
Some(if signed {
let exact = smt::mul(smt::sign_extend(x, wide), smt::sign_extend(y, wide));
let want = smt::sign_extend(smt::mul(x, y), wide);
smt::not(smt::eq(exact, want))
} else {
let exact = smt::mul(smt::truncate(x, wide), smt::truncate(y, wide));
let limit = 1u64 << (w - 1);
let limit = limit.saturating_mul(2);
smt::uge_const(exact, limit)
})
}
fn mixed_add_result(x: Var, y: Var) -> Var {
smt::add(x, y)
}
fn mixed_add_failure(x: Var, y: Var, w: u8, signed: bool) -> Option<Pred> {
let carry = failure(BinOp::Add, x, y, w, signed)?;
Some(smt::xor(carry, smt::negative(y)))
}
fn pow_fold(x: Var, exp: Var, w: u8, signed: bool) -> Option<(Var, Pred)> {
if let Some(e) = smt::const_of(exp) {
let e = e & 0xFFFF_FFFF;
let mut result = smt::word(1, w);
let mut base = x;
let mut flag = smt::truth(false);
let mut k = 0u32;
while k < 32 {
if (e >> k) & 1 == 1 {
let (product, product_overflows) = mul_step(result, base, w, signed)?;
result = product;
flag = smt::or(flag, product_overflows);
}
k += 1;
if k < 32 && (e >> k) != 0 {
let (square, square_overflows) = mul_step(base, base, w, signed)?;
base = square;
flag = smt::or(flag, square_overflows);
}
}
return Some((result, flag));
}
let one = smt::word(1, w);
let mut result = one;
let mut base = x;
let mut flag = smt::truth(false);
for k in 0..32 {
let bit = smt::bit_set(exp, k);
let (product, product_overflows) = mul_step(result, base, w, signed)?;
result = smt::ite(bit, product, result);
flag = smt::or(flag, smt::and(bit, product_overflows));
if k + 1 < 32 {
let higher = smt::uge_const(exp, 1u64 << (k + 1));
let (square, square_overflows) = mul_step(base, base, w, signed)?;
base = smt::ite(higher, square, base);
flag = smt::or(flag, smt::and(higher, square_overflows));
}
}
Some((result, flag))
}
fn mul_step(a: Var, b: Var, w: u8, signed: bool) -> Option<(Var, Pred)> {
Some((smt::mul(a, b), mul_failure(a, b, w, signed)?))
}
fn saturation_end(x: Var, exp: Var, w: u8, signed: bool) -> Option<Var> {
let (lo, hi) = bounds(w, signed)?;
if !signed {
return Some(hi);
}
Some(smt::ite(smt::and(smt::negative(x), smt::bit_set(exp, 0)), lo, hi))
}
pub fn pow_exponent_fits(exp_w: u8) -> bool {
exp_w <= 32
}
fn saturation_bound(op: BinOp, x: Var, y: Var, w: u8, signed: bool) -> Option<Var> {
let (lo, hi) = bounds(w, signed)?;
Some(match op {
BinOp::Add | BinOp::Mul if !signed => hi,
BinOp::Sub if !signed => lo,
BinOp::Add => smt::ite(smt::negative(x), lo, hi),
BinOp::Sub => smt::ite(smt::negative(x), lo, hi),
BinOp::Mul => smt::ite(smt::xor(smt::negative(x), smt::negative(y)), lo, hi),
_ => return None,
})
}
fn bounds(w: u8, signed: bool) -> Option<(Var, Var)> {
let max = max_value(w)?;
if signed {
Some((smt::word(min_value(w)?, w), smt::word(max >> 1, w)))
} else {
Some((smt::word(0, w), smt::word(max, w)))
}
}
fn max_value(w: u8) -> Option<u64> {
if w == 0 || w > 64 {
return None;
}
Some(if w == 64 { u64::MAX } else { (1u64 << w) - 1 })
}
fn min_value(w: u8) -> Option<u64> {
if w == 0 || w > 64 {
return None;
}
Some(1u64 << (w - 1))
}
fn all_ones_value(w: u8) -> u64 {
max_value(w).unwrap_or(0)
}
#[cfg(test)]
mod tests {
use super::*;
fn each_pair(w: u8, mut f: impl FnMut(u64, u64)) {
let n = 1u64 << w;
for x in 0..n {
for y in 0..n {
f(x, y);
}
}
}
fn read(outcome: Outcome, ai: u32, bi: u32, x: u64, y: u64) -> (Option<bool>, Option<u64>) {
let env = |i: u32| {
if i == ai {
Some(x)
} else if i == bi {
Some(y)
} else {
None
}
};
match outcome {
Outcome::Value(v) => (None, smt::evaluate(v, env)),
Outcome::Option { tag, payload } => {
(smt::evaluate(tag, env).map(|t| t != 0), smt::evaluate(payload, env))
}
Outcome::Tuple { value, overflowed } => {
(smt::evaluate_pred(overflowed, env), smt::evaluate(value, env))
}
Outcome::Bool(p) => (smt::evaluate_pred(p, env), None),
Outcome::ValueOrPanic { .. } => {
unreachable!("a value-or-panic outcome is read by its own helper")
}
}
}
fn check(
op: Intrinsic,
w: u8,
signed: bool,
from_bits: impl Fn(u64) -> i64,
to_bits: impl Fn(i64) -> u64,
rust: impl Fn(i64, i64) -> Option<i64>,
label: &str,
) {
smt::with_fresh(|| {
let a = smt::var(w);
let b = smt::var(w);
let outcome = eval(op, a, b, w, signed, w)
.unwrap_or_else(|| panic!("{label} at {w} bits must be modelled"));
let (ai, bi) = (smt::index(a), smt::index(b));
each_pair(w, |xb, yb| {
let (x, y) = (from_bits(xb), from_bits(yb));
let want = rust(x, y);
let (got_some, got_val) = read(outcome, ai, bi, xb, yb);
match (got_some, want) {
(Some(true), Some(r)) => assert_eq!(
got_val,
Some(to_bits(r)),
"{label} at ({x}, {y}): the model says {got_val:?}, Rust says {r}"
),
(Some(true), None) => panic!(
"{label} at ({x}, {y}): the model says `Some`, Rust says `None`"
),
(Some(false), Some(r)) => panic!(
"{label} at ({x}, {y}): the model says `None`, Rust says `{r}`"
),
(Some(false), None) => {}
(None, Some(r)) => assert_eq!(
got_val,
Some(to_bits(r)),
"{label} at ({x}, {y}): the model says {got_val:?}, Rust says {r}"
),
(None, None) => panic!("{label}: a plain outcome cannot match a failing oracle"),
}
});
});
}
fn ident(v: i64) -> u64 {
v as u64
}
fn unident(bits: u64) -> i64 {
bits as i64
}
fn check_tuple(
op: Intrinsic,
w: u8,
signed: bool,
from_bits: impl Fn(u64) -> i64,
to_bits: impl Fn(i64) -> u64,
rust: impl Fn(i64, i64) -> (i64, bool),
label: &str,
) {
smt::with_fresh(|| {
let a = smt::var(w);
let b = smt::var(w);
let outcome = eval(op, a, b, w, signed, w)
.unwrap_or_else(|| panic!("{label} at {w} bits must be modelled"));
let Outcome::Tuple { value, overflowed } = outcome else {
panic!("{label} must produce a tuple");
};
let (ai, bi) = (smt::index(a), smt::index(b));
each_pair(w, |xb, yb| {
let (x, y) = (from_bits(xb), from_bits(yb));
let (want_val, want_flag) = rust(x, y);
let env = |i: u32| {
if i == ai {
Some(xb)
} else if i == bi {
Some(yb)
} else {
None
}
};
assert_eq!(
smt::evaluate(value, env),
Some(to_bits(want_val)),
"{label} at ({x}, {y}): value mismatch"
);
assert_eq!(
smt::evaluate_pred(overflowed, env),
Some(want_flag),
"{label} at ({x}, {y}): overflow flag mismatch"
);
});
});
}
fn pow_exponents() -> Vec<u32> {
let mut e: Vec<u32> = (0..=256).collect();
for k in 0..=16u32 {
let p = 1u32 << k;
e.push(p.wrapping_sub(1));
e.push(p);
e.push(p.wrapping_add(1));
}
e.extend([
u32::MAX,
u32::MAX - 1,
u32::MAX / 2,
u32::MAX / 2 + 1,
1 << 30,
(1 << 24) + 1,
]);
e.sort_unstable();
e.dedup();
e
}
fn check_pow(
op: Intrinsic,
w: u8,
signed: bool,
base_from: impl Fn(u64) -> i64,
base_to: impl Fn(i64) -> u64,
oracle: impl Fn(i64, u32) -> Option<(i64, bool)>,
label: &str,
) {
smt::with_fresh(|| {
let base = smt::var(w);
let exp = smt::var(32);
let outcome = eval(op, base, exp, w, signed, w)
.unwrap_or_else(|| panic!("{label} at {w} bits must be modelled"));
let (bi, ei) = (smt::index(base), smt::index(exp));
let n = 1u64 << w;
for xb in 0..n {
let x = base_from(xb);
for e in pow_exponents() {
let env = |i: u32| {
if i == bi {
Some(xb)
} else if i == ei {
Some(u64::from(e))
} else {
None
}
};
let (got_some, got_val, got_flag) = match outcome {
Outcome::Value(v) => (None, smt::evaluate(v, env), None),
Outcome::Option { tag, payload } => (
smt::evaluate(tag, env).map(|t| t != 0),
smt::evaluate(payload, env),
None,
),
Outcome::Tuple { value, overflowed } => (
smt::evaluate_pred(overflowed, env),
smt::evaluate(value, env),
smt::evaluate_pred(overflowed, env),
),
Outcome::Bool(_) => unreachable!("`pow` is not a bool"),
Outcome::ValueOrPanic { .. } => {
unreachable!("`pow` is not a value-or-panic shape")
}
};
let want = oracle(x, e);
let Some((wv, wf)) = want else {
assert_eq!(
got_some,
Some(false),
"{label} at ({x}, {e}): the model says `Some`, Rust says `None`"
);
continue;
};
assert_eq!(
got_val,
Some(base_to(wv)),
"{label} at ({x}, {e}): value mismatch"
);
if let Some(gf) = got_flag {
assert_eq!(gf, wf, "{label} at ({x}, {e}): overflow flag mismatch");
}
}
}
});
}
#[test]
fn the_pow_families_agree_with_rust() {
check_pow(
Intrinsic::Pow(Family::Wrapping),
8,
false,
unident,
ident,
|x, e| Some((u8::wrapping_pow(x as u8, e) as i64, false)),
"wrapping_pow u8",
);
check_pow(
Intrinsic::Pow(Family::Wrapping),
8,
true,
to_i8,
i8_bits,
|x, e| Some((i8::wrapping_pow(x as i8, e) as i64, false)),
"wrapping_pow i8",
);
check_pow(
Intrinsic::Pow(Family::Overflowing),
8,
false,
unident,
ident,
|x, e| {
let (v, o) = u8::overflowing_pow(x as u8, e);
Some((v as i64, o))
},
"overflowing_pow u8",
);
check_pow(
Intrinsic::Pow(Family::Overflowing),
8,
true,
to_i8,
i8_bits,
|x, e| {
let (v, o) = i8::overflowing_pow(x as i8, e);
Some((v as i64, o))
},
"overflowing_pow i8",
);
check_pow(
Intrinsic::Pow(Family::Checked),
8,
false,
unident,
ident,
|x, e| u8::checked_pow(x as u8, e).map(|v| (v as i64, false)),
"checked_pow u8",
);
check_pow(
Intrinsic::Pow(Family::Checked),
8,
true,
to_i8,
i8_bits,
|x, e| i8::checked_pow(x as i8, e).map(|v| (v as i64, false)),
"checked_pow i8",
);
}
#[test]
fn saturating_pow_agrees_with_rust() {
check_pow(
Intrinsic::Pow(Family::Saturating),
8,
false,
unident,
ident,
|x, e| Some((u8::saturating_pow(x as u8, e) as i64, false)),
"saturating_pow u8",
);
check_pow(
Intrinsic::Pow(Family::Saturating),
8,
true,
to_i8,
i8_bits,
|x, e| Some((i8::saturating_pow(x as i8, e) as i64, false)),
"saturating_pow i8",
);
}
#[test]
fn a_constant_exponent_agrees_with_a_symbolic_one() {
for family in [Family::Wrapping, Family::Checked, Family::Saturating, Family::Overflowing] {
for signed in [false, true] {
let (w, to_signed, to_bits) = if signed {
(8u8, to_i8 as fn(u64) -> i64, i8_bits as fn(i64) -> u64)
} else {
(8u8, unident as fn(u64) -> i64, ident as fn(i64) -> u64)
};
smt::with_fresh(|| {
let base = smt::var(w);
let sym = smt::var(32);
let bi = smt::index(base);
let si = smt::index(sym);
for e in pow_exponents() {
let env = |i: u32| {
if i == bi {
None
} else if i == si {
Some(u64::from(e))
} else {
None
}
};
let constant = smt::word(u64::from(e), 32);
for xb in 0..(1u64 << w) {
let read = |outcome: Outcome| match outcome {
Outcome::Value(v) => (smt::evaluate(v, |i| {
if i == bi { Some(xb) } else { env(i) }
}), None, None),
Outcome::Option { tag, payload } => (
smt::evaluate(payload, |i| if i == bi { Some(xb) } else { env(i) }),
smt::evaluate(tag, |i| if i == bi { Some(xb) } else { env(i) }),
None,
),
Outcome::Tuple { value, overflowed } => (
smt::evaluate(value, |i| if i == bi { Some(xb) } else { env(i) }),
None,
smt::evaluate_pred(overflowed, |i| if i == bi { Some(xb) } else { env(i) }),
),
Outcome::Bool(_) => unreachable!("`pow` is not a bool"),
Outcome::ValueOrPanic { .. } => {
unreachable!("`pow` is not a value-or-panic shape")
}
};
let from_const = eval(Intrinsic::Pow(family), base, constant, w, signed, w)
.unwrap_or_else(|| panic!("{family:?} const must be modelled"));
let from_sym = eval(Intrinsic::Pow(family), base, sym, w, signed, w)
.unwrap_or_else(|| panic!("{family:?} symbolic must be modelled"));
assert_eq!(
read(from_const),
read(from_sym),
"{family:?} signed={signed} base={} exp={e}: the constant-exponent \
fast path and the symbolic fold disagree",
to_bits(to_signed(xb))
);
}
}
});
}
}
}
#[test]
fn pow_is_modelled_only_where_a_product_is() {
assert!(
u32::from(POW_MAX_WIDTH) < u32::from(MUL_MAX_WIDTH),
"pow's fold must keep the tighter bound"
);
assert!(is_modelled(Intrinsic::Pow(Family::Wrapping), POW_MAX_WIDTH, false));
assert!(!is_modelled(Intrinsic::Pow(Family::Wrapping), POW_MAX_WIDTH + 1, false));
assert!(!is_modelled(Intrinsic::Pow(Family::Wrapping), MUL_MAX_WIDTH, false));
assert!(eval(
Intrinsic::Pow(Family::Overflowing),
smt::var(POW_MAX_WIDTH),
smt::var(32),
POW_MAX_WIDTH,
false,
POW_MAX_WIDTH
)
.is_some());
assert!(eval(
Intrinsic::Pow(Family::Overflowing),
smt::var(POW_MAX_WIDTH + 1),
smt::var(32),
POW_MAX_WIDTH + 1,
false,
POW_MAX_WIDTH + 1
)
.is_none());
assert!(pow_exponent_fits(32));
assert!(!pow_exponent_fits(33));
assert!(!pow_exponent_fits(64));
}
#[test]
fn a_symbolic_pow_returns_a_verdict_instead_of_hanging() {
for w in [4u8, 6, 8] {
smt::with_fresh(|| {
let base = smt::var(w);
let exp = smt::var(32);
let outcome = eval(Intrinsic::Pow(Family::Wrapping), base, exp, w, false, w)
.expect("`wrapping_pow` at a small width must be modelled");
let Outcome::Value(value) = outcome else {
panic!("`wrapping_pow` yields a value, not an option or a tuple");
};
let verdict = smt::prove(smt::eq(value, value));
assert!(
matches!(verdict, crate::smt::Verdict::Valid | crate::smt::Verdict::Unknown),
"a symbolic `pow` on a tautology must be `Valid` or `Unknown`, got {verdict:?}"
);
});
}
}
#[test]
fn the_pow_names_classify_and_their_neighbours_do_not() {
assert_eq!(classify("wrapping_pow"), Some(Intrinsic::Pow(Family::Wrapping)));
assert_eq!(classify("saturating_pow"), Some(Intrinsic::Pow(Family::Saturating)));
assert_eq!(classify("checked_pow"), Some(Intrinsic::Pow(Family::Checked)));
assert_eq!(classify("overflowing_pow"), Some(Intrinsic::Pow(Family::Overflowing)));
assert_eq!(
classify("core::num::<impl u8>::wrapping_pow"),
Some(Intrinsic::Pow(Family::Wrapping))
);
assert_eq!(classify("pow"), Some(Intrinsic::PowPanic));
assert_eq!(classify("core::num::<impl u8>::pow"), Some(Intrinsic::PowPanic));
assert_eq!(classify("unchecked_pow"), None);
assert_eq!(classify("powf"), None);
assert_eq!(classify("next_power_of_two"), Some(Intrinsic::NextPowerOfTwo));
assert_eq!(
classify("checked_next_power_of_two"),
Some(Intrinsic::CheckedNextPowerOfTwo)
);
}
#[test]
fn the_option_and_result_method_names_classify_and_a_local_type_does_not() {
assert_eq!(
classify("core::option::Option::<u32>::unwrap_or"),
Some(Intrinsic::OptionMethod(OptionMethod::UnwrapOr))
);
assert_eq!(
classify("std::option::Option::<u8>::unwrap"),
Some(Intrinsic::OptionMethod(OptionMethod::Unwrap))
);
assert_eq!(
classify("Option::<u32>::expect"),
Some(Intrinsic::OptionMethod(OptionMethod::Expect))
);
assert_eq!(
classify("core::option::Option::<u8>::is_some"),
Some(Intrinsic::OptionMethod(OptionMethod::IsSuccess))
);
assert_eq!(
classify("core::option::Option::<u8>::is_none"),
Some(Intrinsic::OptionMethod(OptionMethod::IsFailure))
);
assert_eq!(
classify("core::result::Result::<u8, u16>::is_ok"),
Some(Intrinsic::OptionMethod(OptionMethod::IsSuccess))
);
assert_eq!(
classify("std::result::Result::<u8, u16>::is_err"),
Some(Intrinsic::OptionMethod(OptionMethod::IsFailure))
);
assert_eq!(
classify("Result::<u8, u16>::unwrap"),
Some(Intrinsic::OptionMethod(OptionMethod::Unwrap))
);
assert_eq!(
classify("core::result::Result::<u8, u16>::unwrap_or"),
Some(Intrinsic::OptionMethod(OptionMethod::UnwrapOr))
);
assert_eq!(
classify("core::option::Option::<u8>::ok_or::<i32>"),
Some(Intrinsic::OptionMethod(OptionMethod::OkOr))
);
assert_eq!(
classify("Option::<u32>::ok_or::<u32>"),
Some(Intrinsic::OptionMethod(OptionMethod::OkOr))
);
assert_eq!(
classify("core::result::Result::<u8, u16>::ok"),
Some(Intrinsic::OptionMethod(OptionMethod::Ok))
);
assert_eq!(
classify("core::result::Result::<u8, u16>::err"),
Some(Intrinsic::OptionMethod(OptionMethod::Err))
);
assert_eq!(classify("m::Option::<u8>::unwrap"), None);
assert_eq!(classify("m::Result::<u8, u16>::is_ok"), None);
assert_eq!(classify("m::Option::<u8>::ok_or::<u8>"), None);
assert_eq!(classify("core::option::Option::<u8>::map"), None);
assert_eq!(classify("core::result::Result::<u8, u16>::map"), None);
}
#[test]
fn a_method_turbofish_does_not_hide_the_method_name() {
assert_eq!(
classify("Option::<u8>::ok_or::<i32>"),
Some(Intrinsic::OptionMethod(OptionMethod::OkOr))
);
assert_eq!(
classify("core::option::Option::<u8>::is_some"),
Some(Intrinsic::OptionMethod(OptionMethod::IsSuccess))
);
assert_eq!(
classify("core::num::<impl u8>::wrapping_add"),
Some(Intrinsic::Wrapping(BinOp::Add))
);
}
#[test]
fn the_for_loop_range_names_classify_in_both_toolchain_spellings() {
assert_eq!(
classify("std::ops::RangeInclusive::<u32>::new"),
Some(Intrinsic::Range(RangeMethod::New))
);
assert_eq!(
classify("<std::ops::RangeInclusive<u32> as IntoIterator>::into_iter"),
Some(Intrinsic::Range(RangeMethod::IntoIter))
);
assert_eq!(
classify("<std::ops::RangeInclusive<u32> as Iterator>::next"),
Some(Intrinsic::Range(RangeMethod::Next))
);
assert_eq!(
classify("<RangeInclusive<u32> as IntoIterator>::into_iter"),
Some(Intrinsic::Range(RangeMethod::IntoIter))
);
assert_eq!(
classify("<RangeInclusive<i8> as IntoIterator>::into_iter"),
Some(Intrinsic::Range(RangeMethod::IntoIter))
);
assert_eq!(
classify("<RangeInclusive<u32> as Iterator>::next"),
Some(Intrinsic::Range(RangeMethod::Next))
);
assert_eq!(
classify("RangeInclusive::<u32>::new"),
Some(Intrinsic::Range(RangeMethod::New))
);
assert_eq!(
classify("std::ops::Range::<u32>::new"),
Some(Intrinsic::Range(RangeMethod::New))
);
assert_eq!(
classify("<Range<u32> as IntoIterator>::into_iter"),
Some(Intrinsic::Range(RangeMethod::IntoIter))
);
assert_eq!(
classify("<Range<u32> as Iterator>::next"),
Some(Intrinsic::Range(RangeMethod::Next))
);
assert_eq!(classify("m::RangeInclusive::<u32>::new"), None);
assert_eq!(classify("m::Range::<u32>::new"), None);
assert_eq!(classify("std::ops::RangeFrom::<u32>::new"), None);
assert_eq!(classify("std::ops::RangeTo::<u32>::new"), None);
assert_eq!(classify("<Range<u8> as a::Custom>::into_iter"), None);
assert_eq!(classify("<Range<u8> as a::Custom>::next"), None);
assert_eq!(classify("<RangeInclusive<u8> as m::IntoIterator>::into_iter"), None);
assert_eq!(classify("<Range<u8> as m::Iterator>::next"), None);
assert_eq!(classify("<Range<u8> as core::ops::RangeBounds<u8>>::into_iter"), None);
}
#[test]
fn the_overflowing_family_agrees_with_rust() {
check_tuple(
Intrinsic::Overflowing(BinOp::Add),
8,
false,
unident,
ident,
|x, y| {
let (v, o) = u8::overflowing_add(x as u8, y as u8);
(v as i64, o)
},
"overflowing_add u8",
);
check_tuple(
Intrinsic::Overflowing(BinOp::Sub),
8,
false,
unident,
ident,
|x, y| {
let (v, o) = u8::overflowing_sub(x as u8, y as u8);
(v as i64, o)
},
"overflowing_sub u8",
);
check_tuple(
Intrinsic::Overflowing(BinOp::Mul),
8,
false,
unident,
ident,
|x, y| {
let (v, o) = u8::overflowing_mul(x as u8, y as u8);
(v as i64, o)
},
"overflowing_mul u8",
);
check_tuple(
Intrinsic::Overflowing(BinOp::Add),
8,
true,
to_i8,
i8_bits,
|x, y| {
let (v, o) = i8::overflowing_add(x as i8, y as i8);
(v as i64, o)
},
"overflowing_add i8",
);
check_tuple(
Intrinsic::Overflowing(BinOp::Sub),
8,
true,
to_i8,
i8_bits,
|x, y| {
let (v, o) = i8::overflowing_sub(x as i8, y as i8);
(v as i64, o)
},
"overflowing_sub i8",
);
check_tuple(
Intrinsic::Overflowing(BinOp::Mul),
8,
true,
to_i8,
i8_bits,
|x, y| {
let (v, o) = i8::overflowing_mul(x as i8, y as i8);
(v as i64, o)
},
"overflowing_mul i8",
);
}
#[test]
fn overflowing_division_is_refused_like_the_other_panicking_families() {
for w in [8u8, 16, 32] {
for signed in [false, true] {
assert!(
!is_modelled(Intrinsic::Overflowing(BinOp::Div), w, signed),
"overflowing_div must be refused at {w} bits (signed={signed})"
);
assert!(
!is_modelled(Intrinsic::Overflowing(BinOp::Rem), w, signed),
"overflowing_rem must be refused at {w} bits (signed={signed})"
);
}
}
assert!(is_modelled(Intrinsic::Checked(BinOp::Div), 8, false));
assert!(is_modelled(Intrinsic::Checked(BinOp::Rem), 8, false));
}
#[test]
fn checked_u8_agrees_with_rust() {
check(
Intrinsic::Checked(BinOp::Add),
8,
false,
unident,
ident,
|x, y| u8::checked_add(x as u8, y as u8).map(|v| v as i64),
"checked_add u8",
);
check(
Intrinsic::Checked(BinOp::Sub),
8,
false,
unident,
ident,
|x, y| u8::checked_sub(x as u8, y as u8).map(|v| v as i64),
"checked_sub u8",
);
check(
Intrinsic::Checked(BinOp::Mul),
8,
false,
unident,
ident,
|x, y| u8::checked_mul(x as u8, y as u8).map(|v| v as i64),
"checked_mul u8",
);
}
#[test]
fn saturating_u8_agrees_with_rust() {
check(
Intrinsic::Saturating(BinOp::Add),
8,
false,
unident,
ident,
|x, y| Some(u8::saturating_add(x as u8, y as u8) as i64),
"saturating_add u8",
);
check(
Intrinsic::Saturating(BinOp::Sub),
8,
false,
unident,
ident,
|x, y| Some(u8::saturating_sub(x as u8, y as u8) as i64),
"saturating_sub u8",
);
check(
Intrinsic::Saturating(BinOp::Mul),
8,
false,
unident,
ident,
|x, y| Some(u8::saturating_mul(x as u8, y as u8) as i64),
"saturating_mul u8",
);
}
#[test]
fn wrapping_u8_agrees_with_rust() {
check(
Intrinsic::Wrapping(BinOp::Add),
8,
false,
unident,
ident,
|x, y| Some(u8::wrapping_add(x as u8, y as u8) as i64),
"wrapping_add u8",
);
check(
Intrinsic::Wrapping(BinOp::Sub),
8,
false,
unident,
ident,
|x, y| Some(u8::wrapping_sub(x as u8, y as u8) as i64),
"wrapping_sub u8",
);
check(
Intrinsic::Wrapping(BinOp::Mul),
8,
false,
unident,
ident,
|x, y| Some(u8::wrapping_mul(x as u8, y as u8) as i64),
"wrapping_mul u8",
);
}
#[test]
fn checked_div_and_rem_agree_with_rust() {
check(
Intrinsic::Checked(BinOp::Div),
8,
false,
unident,
ident,
|x, y| u8::checked_div(x as u8, y as u8).map(|v| v as i64),
"checked_div u8",
);
check(
Intrinsic::Checked(BinOp::Rem),
8,
false,
unident,
ident,
|x, y| u8::checked_rem(x as u8, y as u8).map(|v| v as i64),
"checked_rem u8",
);
}
fn to_i8(bits: u64) -> i64 {
(bits as u8) as i8 as i64
}
fn i8_bits(v: i64) -> u64 {
(v as i8) as u8 as u64
}
#[test]
fn checked_i8_agrees_with_rust() {
check(
Intrinsic::Checked(BinOp::Add),
8,
true,
to_i8,
i8_bits,
|x, y| i8::checked_add(x as i8, y as i8).map(|v| v as i64),
"checked_add i8",
);
check(
Intrinsic::Checked(BinOp::Sub),
8,
true,
to_i8,
i8_bits,
|x, y| i8::checked_sub(x as i8, y as i8).map(|v| v as i64),
"checked_sub i8",
);
check(
Intrinsic::Checked(BinOp::Mul),
8,
true,
to_i8,
i8_bits,
|x, y| i8::checked_mul(x as i8, y as i8).map(|v| v as i64),
"checked_mul i8",
);
check(
Intrinsic::Checked(BinOp::Div),
8,
true,
to_i8,
i8_bits,
|x, y| i8::checked_div(x as i8, y as i8).map(|v| v as i64),
"checked_div i8",
);
check(
Intrinsic::Checked(BinOp::Rem),
8,
true,
to_i8,
i8_bits,
|x, y| i8::checked_rem(x as i8, y as i8).map(|v| v as i64),
"checked_rem i8",
);
}
#[test]
fn saturating_and_wrapping_i8_agree_with_rust() {
check(
Intrinsic::Saturating(BinOp::Add),
8,
true,
to_i8,
i8_bits,
|x, y| Some(i8::saturating_add(x as i8, y as i8) as i64),
"saturating_add i8",
);
check(
Intrinsic::Saturating(BinOp::Sub),
8,
true,
to_i8,
i8_bits,
|x, y| Some(i8::saturating_sub(x as i8, y as i8) as i64),
"saturating_sub i8",
);
check(
Intrinsic::Saturating(BinOp::Mul),
8,
true,
to_i8,
i8_bits,
|x, y| Some(i8::saturating_mul(x as i8, y as i8) as i64),
"saturating_mul i8",
);
check(
Intrinsic::Wrapping(BinOp::Add),
8,
true,
to_i8,
i8_bits,
|x, y| Some(i8::wrapping_add(x as i8, y as i8) as i64),
"wrapping_add i8",
);
check(
Intrinsic::Wrapping(BinOp::Sub),
8,
true,
to_i8,
i8_bits,
|x, y| Some(i8::wrapping_sub(x as i8, y as i8) as i64),
"wrapping_sub i8",
);
check(
Intrinsic::Wrapping(BinOp::Mul),
8,
true,
to_i8,
i8_bits,
|x, y| Some(i8::wrapping_mul(x as i8, y as i8) as i64),
"wrapping_mul i8",
);
}
#[test]
fn saturating_u16_agrees_with_rust_at_the_boundaries() {
let vals: [u16; 12] = [0, 1, 2, 15, 100, 255, 256, 32767, 32768, 65534, 65535, 12345];
smt::with_fresh(|| {
let a = smt::var(16);
let b = smt::var(16);
let op = Intrinsic::Saturating(BinOp::Add);
let outcome = eval(op, a, b, 16, false, 16).expect("u16 is modelled");
let (ai, bi) = (smt::index(a), smt::index(b));
for &x in &vals {
for &y in &vals {
let (_, got) = read(outcome, ai, bi, x as u64, y as u64);
assert_eq!(
got,
Some(u16::saturating_add(x, y) as u64),
"saturating_add u16 at ({x}, {y})"
);
}
}
});
}
#[test]
fn signed_division_refuses_min_by_neg_one() {
smt::with_fresh(|| {
let a = smt::var(8);
let b = smt::var(8);
let op = Intrinsic::Checked(BinOp::Div);
let outcome = eval(op, a, b, 8, true, 8).expect("i8 is modelled");
let (ai, bi) = (smt::index(a), smt::index(b));
let (got_some, _) = read(outcome, ai, bi, i8_bits(i8::MIN as i64), i8_bits(-1));
assert_eq!(
got_some,
Some(false),
"the model must not produce a quotient for i8::MIN / -1"
);
assert_eq!(i8::checked_div(i8::MIN, -1), None, "the oracle must agree");
});
}
#[test]
fn unmodelled_names_are_refused() {
assert!(classify("checked_shl").is_none());
assert!(classify("overflowing_shl").is_none());
assert!(classify("saturating_shl").is_none());
assert!(classify("unchecked_add").is_none());
assert!(classify("wrapping_add_signed_thing").is_none());
assert!(classify("add_signed").is_none());
let sat_div = classify("core::num::<impl u8>::saturating_div")
.expect("the name is recognised, so it classifies");
assert_eq!(sat_div, Intrinsic::Saturating(BinOp::Div));
assert!(
eval(sat_div, smt::var(8), smt::var(8), 8, false, 8).is_none(),
"saturating_div must not be modelled: it panics on a zero divisor"
);
assert!(!is_modelled(sat_div, 8, false));
assert!(classify("core::num::<impl u8>::checked_add").is_some());
assert!(classify("saturating_sub").is_some());
}
#[test]
fn a_u16_product_is_modelled_and_exact() {
let vals: [u16; 16] = [
0, 1, 2, 3, 255, 256, 257, 32767, 32768, 32769, 43690, 65534, 65535, 12345, 40000, 513,
];
smt::with_fresh(|| {
let a = smt::var(16);
let b = smt::var(16);
let (ai, bi) = (smt::index(a), smt::index(b));
let checked = eval(Intrinsic::Checked(BinOp::Mul), a, b, 16, false, 16)
.expect("checked_mul u16 must be modelled");
let sat = eval(Intrinsic::Saturating(BinOp::Mul), a, b, 16, false, 16)
.expect("saturating_mul u16 must be modelled");
for &x in &vals {
for &y in &vals {
let (got_some, got_val) = read(checked, ai, bi, x as u64, y as u64);
assert_eq!(
got_some,
Some(u16::checked_mul(x, y).is_some()),
"checked_mul u16 at ({x}, {y}): the tag must match `core`"
);
if let Some(want) = u16::checked_mul(x, y) {
assert_eq!(
got_val,
Some(want as u64),
"checked_mul u16 at ({x}, {y}): the payload must match `core`"
);
}
let (_, sat_val) = read(sat, ai, bi, x as u64, y as u64);
assert_eq!(
sat_val,
Some(u16::saturating_mul(x, y) as u64),
"saturating_mul u16 at ({x}, {y})"
);
}
}
});
}
#[test]
fn a_u32_product_is_modelled_and_exact() {
let vals: [u32; 14] = [
0,
1,
2,
255,
65535,
65536,
65537,
46341,
0x8000_0000,
0xffff_fffe,
0xffff_ffff,
12345,
1_000_000,
65_537,
];
smt::with_fresh(|| {
let a = smt::var(32);
let b = smt::var(32);
let (ai, bi) = (smt::index(a), smt::index(b));
let checked = eval(Intrinsic::Checked(BinOp::Mul), a, b, 32, false, 32)
.expect("checked_mul u32 must be modelled");
let sat = eval(Intrinsic::Saturating(BinOp::Mul), a, b, 32, false, 32)
.expect("saturating_mul u32 must be modelled");
for &x in &vals {
for &y in &vals {
let (got_some, got_val) = read(checked, ai, bi, x as u64, y as u64);
assert_eq!(
got_some,
Some(u32::checked_mul(x, y).is_some()),
"checked_mul u32 at ({x}, {y}): the tag must match `core`"
);
if let Some(want) = u32::checked_mul(x, y) {
assert_eq!(
got_val,
Some(want as u64),
"checked_mul u32 at ({x}, {y}): the payload must match `core`"
);
}
let (_, sat_val) = read(sat, ai, bi, x as u64, y as u64);
assert_eq!(
sat_val,
Some(u32::saturating_mul(x, y) as u64),
"saturating_mul u32 at ({x}, {y})"
);
}
}
});
assert!(eval(Intrinsic::Saturating(BinOp::Mul), smt::var(64), smt::var(64), 64, false, 64).is_none());
assert!(!is_modelled(Intrinsic::Saturating(BinOp::Mul), 64, false));
}
#[test]
fn past_the_width_limits_the_model_declines() {
let mw = MUL_MAX_WIDTH + 1;
assert!(eval(Intrinsic::Saturating(BinOp::Mul), smt::var(mw), smt::var(mw), mw, false, mw).is_none());
let dw = DIV_MAX_WIDTH + 1;
assert!(eval(Intrinsic::Checked(BinOp::Div), smt::var(dw), smt::var(dw), dw, false, dw).is_none());
assert!(eval(
Intrinsic::Saturating(BinOp::Mul),
smt::var(MUL_MAX_WIDTH),
smt::var(MUL_MAX_WIDTH),
MUL_MAX_WIDTH,
false,
MUL_MAX_WIDTH
)
.is_some());
assert!(eval(
Intrinsic::Checked(BinOp::Div),
smt::var(DIV_MAX_WIDTH),
smt::var(DIV_MAX_WIDTH),
DIV_MAX_WIDTH,
false,
DIV_MAX_WIDTH
)
.is_some());
}
fn check_unary(
op: Intrinsic,
w: u8,
result_w: u8,
signed: bool,
oracle: impl Fn(u64) -> u64,
label: &str,
) {
smt::with_fresh(|| {
let a = smt::var(w);
let outcome = eval(op, a, a, w, signed, result_w)
.unwrap_or_else(|| panic!("{label} at {w} bits must be modelled"));
let ai = smt::index(a);
for xb in 0..(1u64 << w) {
let want = oracle(xb);
let Outcome::Value(v) = outcome else {
panic!("{label} must produce a plain value");
};
let got = smt::evaluate(v, |i| if i == ai { Some(xb) } else { None });
assert_eq!(
got,
Some(want),
"{label} at bits {xb}: the model says {got:?}, Rust says {want}"
);
}
});
}
fn check_unary_option(
op: Intrinsic,
w: u8,
signed: bool,
oracle: impl Fn(u64) -> Option<u64>,
label: &str,
) {
smt::with_fresh(|| {
let a = smt::var(w);
let outcome = eval(op, a, a, w, signed, w)
.unwrap_or_else(|| panic!("{label} at {w} bits must be modelled"));
let ai = smt::index(a);
for xb in 0..(1u64 << w) {
let want = oracle(xb);
let Outcome::Option { tag, payload } = outcome else {
panic!("{label} must produce an `Option`");
};
let got_tag = smt::evaluate(tag, |i| if i == ai { Some(xb) } else { None });
let got_val = smt::evaluate(payload, |i| if i == ai { Some(xb) } else { None });
match want {
Some(v) => {
assert_eq!(
got_tag,
Some(1),
"{label} at bits {xb}: Rust says `Some`, model says {got_tag:?}"
);
assert_eq!(
got_val,
Some(v),
"{label} at bits {xb}: the model says {got_val:?}, Rust says {v}"
);
}
None => {
assert_eq!(
got_tag,
Some(0),
"{label} at bits {xb}: Rust says `None`, model says {got_tag:?}"
);
}
}
}
});
}
fn check_unary_tuple(
op: Intrinsic,
w: u8,
signed: bool,
oracle: impl Fn(u64) -> (u64, bool),
label: &str,
) {
smt::with_fresh(|| {
let a = smt::var(w);
let outcome = eval(op, a, a, w, signed, w)
.unwrap_or_else(|| panic!("{label} at {w} bits must be modelled"));
let ai = smt::index(a);
for xb in 0..(1u64 << w) {
let (want_val, want_flag) = oracle(xb);
let Outcome::Tuple { value, overflowed } = outcome else {
panic!("{label} must produce a tuple");
};
let env = |i: u32| if i == ai { Some(xb) } else { None };
assert_eq!(
smt::evaluate(value, env),
Some(want_val),
"{label} at bits {xb}: value mismatch"
);
assert_eq!(
smt::evaluate_pred(overflowed, env),
Some(want_flag),
"{label} at bits {xb}: overflow flag mismatch"
);
}
});
}
#[test]
fn the_bit_counts_agree_with_rust() {
fn oracle(kind: BitKind, w: u8, b: u64) -> u64 {
let mask = (1u32 << w) - 1;
let v = (b as u32) & mask;
let c = !v & mask;
match kind {
BitKind::Ones => u64::from(v.count_ones()),
BitKind::LeadingZeros => u64::from(v.leading_zeros() - (32 - u32::from(w))),
BitKind::TrailingZeros => u64::from((v | (1u32 << w)).trailing_zeros()),
BitKind::CountZeros => u64::from(c.count_ones()),
BitKind::LeadingOnes => u64::from(c.leading_zeros() - (32 - u32::from(w))),
BitKind::TrailingOnes => u64::from((c | (1u32 << w)).trailing_zeros()),
}
}
for w in [1u8, 4, 8] {
for (kind, name) in [
(BitKind::Ones, "count_ones"),
(BitKind::LeadingZeros, "leading_zeros"),
(BitKind::TrailingZeros, "trailing_zeros"),
(BitKind::CountZeros, "count_zeros"),
(BitKind::LeadingOnes, "leading_ones"),
(BitKind::TrailingOnes, "trailing_ones"),
] {
let f = move |b: u64| oracle(kind, w, b);
check_unary(
Intrinsic::Bits(kind),
w,
32,
false,
f,
&format!("{name} (widened to u32)"),
);
check_unary(
Intrinsic::Bits(kind),
w,
w,
false,
f,
&format!("{name} (at operand width)"),
);
}
}
}
#[test]
fn the_64_bit_counts_agree_with_rust() {
let operands = [
0u64,
u64::MAX,
1,
1u64 << 63,
0x8000_0000_0000_0001,
0x0000_ffff_ffff_0000,
];
let check = |kind: BitKind, name: &str, oracle: fn(u64) -> u64| {
smt::with_fresh(|| {
let a = smt::var(64);
let ai = smt::index(a);
let outcome = eval(Intrinsic::Bits(kind), a, a, 64, false, 64)
.unwrap_or_else(|| panic!("{name} at 64 bits must be modelled"));
let Outcome::Value(v) = outcome else {
panic!("{name} must produce a plain value");
};
for xb in operands {
let want = oracle(xb);
let got = smt::evaluate(v, |i| if i == ai { Some(xb) } else { None });
assert_eq!(
got,
Some(want),
"{name} at bits {xb:#x}: the model says {got:?}, Rust says {want}"
);
}
});
};
check(BitKind::Ones, "count_ones", |v| u64::from(v.count_ones()));
check(BitKind::CountZeros, "count_zeros", |v| u64::from(v.count_zeros()));
check(BitKind::LeadingZeros, "leading_zeros", |v| u64::from(v.leading_zeros()));
check(BitKind::LeadingOnes, "leading_ones", |v| u64::from(v.leading_ones()));
check(BitKind::TrailingZeros, "trailing_zeros", |v| u64::from(v.trailing_zeros()));
check(BitKind::TrailingOnes, "trailing_ones", |v| u64::from(v.trailing_ones()));
}
fn check_bool(
op: Intrinsic,
w: u8,
signed: bool,
oracle: impl Fn(u64) -> bool,
label: &str,
) {
smt::with_fresh(|| {
let a = smt::var(w);
let outcome = eval(op, a, a, w, signed, w)
.unwrap_or_else(|| panic!("{label} at {w} bits must be modelled"));
let ai = smt::index(a);
for xb in 0..(1u64 << w) {
let want = oracle(xb);
let Outcome::Bool(p) = outcome else {
panic!("{label} must produce a `bool`");
};
let got = smt::evaluate_pred(p, |i| if i == ai { Some(xb) } else { None });
assert_eq!(
got,
Some(want),
"{label} at bits {xb}: the model says {got:?}, Rust says {want}"
);
}
});
}
#[test]
fn is_power_of_two_agrees_with_rust() {
for w in [8u8, 16] {
let oracle = move |b: u64| match w {
8 => u8::try_from(b).unwrap().is_power_of_two(),
16 => u16::try_from(b).unwrap().is_power_of_two(),
_ => unreachable!("the test walks 8 and 16 bits"),
};
check_bool(Intrinsic::Bool(BoolKind::PowerOfTwo), w, false, oracle, "is_power_of_two");
}
let p = |b: u64| {
smt::with_fresh(|| {
let a = smt::var(8);
let Outcome::Bool(p) =
eval(Intrinsic::Bool(BoolKind::PowerOfTwo), a, a, 8, false, 8)
.expect("is_power_of_two at 8 bits must be modelled")
else {
panic!("is_power_of_two must produce a `bool`");
};
let ai = smt::index(a);
smt::evaluate_pred(p, |i| if i == ai { Some(b) } else { None })
})
};
for (b, want, why) in [
(0u64, false, "zero is not a power of two"),
(1, true, "one is 1 << 0"),
(2, true, "two is 1 << 1"),
(127, false, "seven set bits"),
(128, true, "the top bit is 1 << 7"),
(255, false, "eight set bits"),
] {
assert_eq!(p(b), Some(want), "{why} (at bits {b})");
}
}
#[test]
fn the_sign_predicates_agree_with_rust() {
for w in [8u8, 16] {
let neg = move |b: u64| match w {
8 => (b as u8 as i8).is_negative(),
16 => (b as u16 as i16).is_negative(),
_ => unreachable!("the test walks 8 and 16 bits"),
};
let pos = move |b: u64| match w {
8 => (b as u8 as i8).is_positive(),
16 => (b as u16 as i16).is_positive(),
_ => unreachable!("the test walks 8 and 16 bits"),
};
check_bool(Intrinsic::Bool(BoolKind::Negative), w, true, neg, "is_negative");
check_bool(Intrinsic::Bool(BoolKind::Positive), w, true, pos, "is_positive");
}
let ev = |kind: BoolKind, b: u64| {
smt::with_fresh(|| {
let a = smt::var(8);
let Outcome::Bool(p) = eval(Intrinsic::Bool(kind), a, a, 8, true, 8)
.expect("a sign predicate at 8 bits must be modelled")
else {
panic!("a sign predicate must produce a `bool`");
};
let ai = smt::index(a);
smt::evaluate_pred(p, |i| if i == ai { Some(b) } else { None })
})
};
for (bits, neg, pos, why) in [
(0u64, false, false, "zero is neither negative nor positive"),
(1, false, true, "one is positive"),
(0x7f, false, true, "i8::MAX is positive"),
(0x80, true, false, "i8::MIN is negative -- an unsigned read would call it positive"),
(0xff, true, false, "-1 is negative"),
] {
assert_eq!(
ev(BoolKind::Negative, bits),
Some(neg),
"is_negative {why} (at bits {bits:#x})"
);
assert_eq!(
ev(BoolKind::Positive, bits),
Some(pos),
"is_positive {why} (at bits {bits:#x})"
);
}
}
#[test]
fn the_ascii_classes_agree_with_rust() {
type Case = (AsciiKind, fn(u8) -> bool, &'static str);
let classes: [Case; 10] = [
(AsciiKind::Digit, |b| b.is_ascii_digit(), "is_ascii_digit"),
(AsciiKind::Alphabetic, |b| b.is_ascii_alphabetic(), "is_ascii_alphabetic"),
(AsciiKind::Alphanumeric, |b| b.is_ascii_alphanumeric(), "is_ascii_alphanumeric"),
(AsciiKind::Uppercase, |b| b.is_ascii_uppercase(), "is_ascii_uppercase"),
(AsciiKind::Lowercase, |b| b.is_ascii_lowercase(), "is_ascii_lowercase"),
(AsciiKind::HexDigit, |b| b.is_ascii_hexdigit(), "is_ascii_hexdigit"),
(AsciiKind::Whitespace, |b| b.is_ascii_whitespace(), "is_ascii_whitespace"),
(AsciiKind::Punctuation, |b| b.is_ascii_punctuation(), "is_ascii_punctuation"),
(AsciiKind::Control, |b| b.is_ascii_control(), "is_ascii_control"),
(AsciiKind::Ascii, |b| b.is_ascii(), "is_ascii"),
];
for (kind, oracle, label) in classes {
check_bool(
Intrinsic::Bool(BoolKind::Ascii(kind)),
8,
false,
|b: u64| oracle(b as u8),
label,
);
}
let p = |kind: AsciiKind, b: u64| {
smt::with_fresh(|| {
let a = smt::var(8);
let Outcome::Bool(p) = eval(Intrinsic::Bool(BoolKind::Ascii(kind)), a, a, 8, false, 8)
.expect("an ASCII class at 8 bits must be modelled")
else {
panic!("an ASCII class must produce a `bool`");
};
let ai = smt::index(a);
smt::evaluate_pred(p, |i| if i == ai { Some(b) } else { None })
})
};
for (kind, b, want, why) in [
(AsciiKind::Whitespace, 0x0b, false, "vertical tab is not ASCII whitespace"),
(AsciiKind::Whitespace, b' ' as u64, true, "space is whitespace"),
(AsciiKind::Punctuation, b' ' as u64, false, "space is not punctuation"),
(AsciiKind::Punctuation, b'!' as u64, true, "`!` is punctuation"),
(AsciiKind::Control, 0x1f, true, "the last C0 control"),
(AsciiKind::Control, 0x20, false, "space is the first printable"),
(AsciiKind::Control, 0x7f, true, "DEL is a control"),
(AsciiKind::Control, 0x80, false, "0x80 is not a control"),
(AsciiKind::Ascii, 0x7f, true, "DEL is ASCII"),
(AsciiKind::Ascii, 0x80, false, "0x80 is not ASCII"),
] {
assert_eq!(p(kind, b), Some(want), "{why} (0x{b:02x})");
}
}
#[test]
fn the_ascii_classes_are_refused_when_signed() {
let digit = Intrinsic::Bool(BoolKind::Ascii(AsciiKind::Digit));
assert!(is_modelled(digit, 8, false));
assert!(is_modelled(digit, 32, false));
assert!(!is_modelled(digit, 8, true));
assert!(!is_modelled(digit, 32, true));
assert!(eval(digit, smt::var(8), smt::var(8), 8, true, 8).is_none());
assert!(eval(digit, smt::var(32), smt::var(32), 32, true, 32).is_none());
}
#[test]
fn the_ascii_classes_agree_with_char_over_the_whole_domain() {
let x = smt::var(32);
let digit = eval(
Intrinsic::Bool(BoolKind::Ascii(AsciiKind::Digit)),
x,
x,
32,
false,
32,
)
.expect("a `char` receiver is modelled");
let Outcome::Bool(p) = digit else {
panic!("an ASCII class is a predicate");
};
let idx = smt::index(x);
for v in [0x30u32, 0x39, 0x2f, 0x3a, 0x130, 0x1030, 0x1_0030, 0x139, 0x80, 0x100] {
let want = char::from_u32(v).is_some_and(|c| c.is_ascii_digit());
let got = smt::evaluate_pred(p, |i| (i == idx).then_some(v as u64));
assert_eq!(got, Some(want), "is_ascii_digit at {v:#x}");
}
}
#[test]
fn is_power_of_two_is_refused_when_signed() {
assert!(is_modelled(Intrinsic::Bool(BoolKind::PowerOfTwo), 8, false));
assert!(!is_modelled(Intrinsic::Bool(BoolKind::PowerOfTwo), 8, true));
assert!(eval(Intrinsic::Bool(BoolKind::PowerOfTwo), smt::var(8), smt::var(8), 8, true, 8)
.is_none());
}
#[test]
fn the_signed_unary_families_agree_with_rust() {
let x = |b: u64| i8::from_ne_bytes([b as u8]);
let bits = |v: i8| v as u8 as u64;
check_unary(
Intrinsic::Unary(Family::Wrapping, UnOp::Neg),
8,
8,
true,
|b| bits(x(b).wrapping_neg()),
"wrapping_neg i8",
);
check_unary(
Intrinsic::Unary(Family::Saturating, UnOp::Neg),
8,
8,
true,
|b| bits(x(b).saturating_neg()),
"saturating_neg i8",
);
check_unary_option(
Intrinsic::Unary(Family::Checked, UnOp::Neg),
8,
true,
|b| x(b).checked_neg().map(bits),
"checked_neg i8",
);
check_unary_tuple(
Intrinsic::Unary(Family::Overflowing, UnOp::Neg),
8,
true,
|b| {
let (v, o) = x(b).overflowing_neg();
(bits(v), o)
},
"overflowing_neg i8",
);
check_unary(
Intrinsic::Unary(Family::Wrapping, UnOp::Abs),
8,
8,
true,
|b| bits(x(b).wrapping_abs()),
"wrapping_abs i8",
);
check_unary(
Intrinsic::Unary(Family::Saturating, UnOp::Abs),
8,
8,
true,
|b| bits(x(b).saturating_abs()),
"saturating_abs i8",
);
check_unary_option(
Intrinsic::Unary(Family::Checked, UnOp::Abs),
8,
true,
|b| x(b).checked_abs().map(bits),
"checked_abs i8",
);
check_unary_tuple(
Intrinsic::Unary(Family::Overflowing, UnOp::Abs),
8,
true,
|b| {
let (v, o) = x(b).overflowing_abs();
(bits(v), o)
},
"overflowing_abs i8",
);
}
#[test]
fn unsigned_negation_is_modelled_except_where_the_method_does_not_exist() {
let bits = |v: u8| u64::from(v);
check_unary(
Intrinsic::Unary(Family::Wrapping, UnOp::Neg),
8,
8,
false,
|b| bits((b as u8).wrapping_neg()),
"wrapping_neg u8",
);
check_unary_option(
Intrinsic::Unary(Family::Checked, UnOp::Neg),
8,
false,
|b| (b as u8).checked_neg().map(bits),
"checked_neg u8",
);
check_unary_tuple(
Intrinsic::Unary(Family::Overflowing, UnOp::Neg),
8,
false,
|b| {
let (v, o) = (b as u8).overflowing_neg();
(bits(v), o)
},
"overflowing_neg u8",
);
assert!(!is_modelled(Intrinsic::Unary(Family::Saturating, UnOp::Neg), 8, false));
assert!(!is_modelled(Intrinsic::Unary(Family::Wrapping, UnOp::Abs), 8, false));
assert!(!is_modelled(Intrinsic::Unary(Family::Checked, UnOp::Abs), 8, false));
assert!(!is_modelled(Intrinsic::Unary(Family::Overflowing, UnOp::Abs), 8, false));
assert!(is_modelled(Intrinsic::Unary(Family::Saturating, UnOp::Neg), 8, true));
assert!(is_modelled(Intrinsic::Unary(Family::Wrapping, UnOp::Abs), 8, true));
}
#[test]
fn the_unary_names_classify_and_their_neighbours_do_not() {
assert_eq!(
classify("core::num::<impl i8>::wrapping_neg"),
Some(Intrinsic::Unary(Family::Wrapping, UnOp::Neg))
);
assert_eq!(classify("wrapping_abs"), Some(Intrinsic::Unary(Family::Wrapping, UnOp::Abs)));
assert_eq!(
classify("core::num::<impl u8>::overflowing_neg"),
Some(Intrinsic::Unary(Family::Overflowing, UnOp::Neg))
);
assert_eq!(
classify("saturating_abs"),
Some(Intrinsic::Unary(Family::Saturating, UnOp::Abs))
);
assert_eq!(classify("checked_neg"), Some(Intrinsic::Unary(Family::Checked, UnOp::Neg)));
assert_ne!(classify("checked_neg"), Some(Intrinsic::Checked(BinOp::Add)));
assert_eq!(classify("abs"), Some(Intrinsic::Abs));
assert!(classify("neg").is_none());
assert!(classify("wrapping_neg_signed").is_none());
assert!(classify("checked_abs_signed").is_none());
assert!(classify("powf").is_none());
assert!(classify("count_ones_signed").is_none());
assert_eq!(classify("count_zeros"), Some(Intrinsic::Bits(BitKind::CountZeros)));
assert!(classify("count_zeros_signed").is_none());
}
#[test]
fn the_bit_count_names_classify() {
assert_eq!(classify("core::num::<impl u8>::count_ones"), Some(Intrinsic::Bits(BitKind::Ones)));
assert_eq!(classify("count_ones"), Some(Intrinsic::Bits(BitKind::Ones)));
assert_eq!(classify("leading_zeros"), Some(Intrinsic::Bits(BitKind::LeadingZeros)));
assert_eq!(classify("trailing_zeros"), Some(Intrinsic::Bits(BitKind::TrailingZeros)));
assert_eq!(classify("count_zeros"), Some(Intrinsic::Bits(BitKind::CountZeros)));
assert_eq!(classify("leading_ones"), Some(Intrinsic::Bits(BitKind::LeadingOnes)));
assert_eq!(classify("trailing_ones"), Some(Intrinsic::Bits(BitKind::TrailingOnes)));
assert_ne!(classify("count_zeros"), Some(Intrinsic::Bits(BitKind::Ones)));
assert_ne!(classify("leading_ones"), Some(Intrinsic::Bits(BitKind::LeadingZeros)));
assert_ne!(classify("trailing_ones"), Some(Intrinsic::Bits(BitKind::TrailingZeros)));
assert!(classify("leading_ones_signed").is_none());
}
#[test]
fn the_bool_predicate_names_classify() {
assert_eq!(
classify("core::num::<impl u32>::is_power_of_two"),
Some(Intrinsic::Bool(BoolKind::PowerOfTwo))
);
assert_eq!(classify("is_power_of_two"), Some(Intrinsic::Bool(BoolKind::PowerOfTwo)));
assert_ne!(classify("is_power_of_two"), Some(Intrinsic::Bits(BitKind::Ones)));
assert_eq!(
classify("core::num::<impl u8>::is_ascii_digit"),
Some(Intrinsic::Bool(BoolKind::Ascii(AsciiKind::Digit)))
);
assert_eq!(
classify("core::num::<impl u8>::is_ascii_alphanumeric"),
Some(Intrinsic::Bool(BoolKind::Ascii(AsciiKind::Alphanumeric)))
);
assert_eq!(
classify("core::num::<impl u8>::is_ascii"),
Some(Intrinsic::Bool(BoolKind::Ascii(AsciiKind::Ascii)))
);
assert_ne!(
classify("is_ascii"),
Some(Intrinsic::Bool(BoolKind::Ascii(AsciiKind::Digit)))
);
assert!(classify("is_power_of_two_signed").is_none());
assert_eq!(classify("is_negative"), Some(Intrinsic::Bool(BoolKind::Negative)));
assert_eq!(classify("is_positive"), Some(Intrinsic::Bool(BoolKind::Positive)));
assert_eq!(classify("core::slice::<impl [u8]>::len"), Some(Intrinsic::SliceLen));
assert_eq!(classify("core::slice::<impl [u8]>::is_empty"), Some(Intrinsic::SliceIsEmpty));
assert_eq!(classify("core::slice::<impl [u8]>::first"), Some(Intrinsic::SliceFirst));
assert_eq!(classify("core::slice::<impl [u8]>::last"), Some(Intrinsic::SliceLast));
assert_eq!(classify("alloc::vec::Vec<u8>::len"), Some(Intrinsic::VecMethod(VecMethod::Len)));
assert_eq!(classify("Vec::<u8>::len"), Some(Intrinsic::VecMethod(VecMethod::Len)));
assert_eq!(classify("Vec::<u8>::new"), Some(Intrinsic::VecMethod(VecMethod::New)));
assert_eq!(classify("Vec::<u8>::push"), Some(Intrinsic::VecMethod(VecMethod::Push)));
assert!(classify("m::Vec::<u8>::len").is_none());
assert!(classify("str::len").is_none());
assert_eq!(classify("core::num::<impl u8>::abs_diff"), Some(Intrinsic::AbsDiff));
assert_eq!(
classify("core::num::<impl u8>::rotate_left"),
Some(Intrinsic::Rotate(RotateKind::Left))
);
assert_eq!(
classify("core::num::<impl i32>::rotate_right"),
Some(Intrinsic::Rotate(RotateKind::Right))
);
assert!(classify("rotate_left_signed").is_none());
assert!(classify("abs_diff_thing").is_none());
assert_eq!(
classify("core::num::<impl u8>::wrapping_shl"),
Some(Intrinsic::WrappingShift(ShiftKind::Left))
);
assert_eq!(
classify("core::num::<impl i32>::wrapping_shr"),
Some(Intrinsic::WrappingShift(ShiftKind::Right))
);
assert!(classify("core::num::<impl u8>::wrapping_shl_thing").is_none());
assert!(classify("core::num::<impl u8>::checked_shl").is_none());
assert!(classify("core::num::<impl u8>::overflowing_shr").is_none());
assert!(classify("core::num::<impl u8>::saturating_shl").is_none());
}
#[test]
fn the_documented_modelled_set_matches_classify() {
assert_eq!(classify("core::num::<impl u8>::abs_diff"), Some(Intrinsic::AbsDiff));
assert_eq!(
classify("core::num::<impl u8>::rotate_left"),
Some(Intrinsic::Rotate(RotateKind::Left))
);
assert_eq!(
classify("core::num::<impl u8>::rotate_right"),
Some(Intrinsic::Rotate(RotateKind::Right))
);
assert_eq!(
classify("core::num::<impl u8>::wrapping_shl"),
Some(Intrinsic::WrappingShift(ShiftKind::Left))
);
assert_eq!(
classify("core::num::<impl u8>::wrapping_shr"),
Some(Intrinsic::WrappingShift(ShiftKind::Right))
);
for name in [
"is_ascii_digit",
"is_ascii_alphabetic",
"is_ascii_alphanumeric",
"is_ascii_uppercase",
"is_ascii_lowercase",
"is_ascii_hexdigit",
"is_ascii_whitespace",
"is_ascii_punctuation",
"is_ascii_control",
"is_ascii",
] {
assert!(
classify(&format!("core::num::<impl u8>::{name}")).is_some(),
"the header says `{name}` is modelled, so it must classify"
);
}
assert_eq!(
classify("core::num::<impl i8>::is_negative"),
Some(Intrinsic::Bool(BoolKind::Negative))
);
assert_eq!(
classify("core::num::<impl i8>::is_positive"),
Some(Intrinsic::Bool(BoolKind::Positive))
);
assert_eq!(classify("core::num::<impl i32>::abs"), Some(Intrinsic::Abs));
assert_eq!(
classify("core::num::<impl i32>::unsigned_abs"),
Some(Intrinsic::UnsignedAbs)
);
}
#[test]
fn only_the_unary_shapes_are_unary() {
assert!(Intrinsic::Bits(BitKind::Ones).is_unary());
assert!(Intrinsic::Bool(BoolKind::PowerOfTwo).is_unary());
assert!(Intrinsic::Unary(Family::Wrapping, UnOp::Neg).is_unary());
assert!(Intrinsic::Unary(Family::Checked, UnOp::Abs).is_unary());
assert!(!Intrinsic::Wrapping(BinOp::Add).is_unary());
assert!(!Intrinsic::Saturating(BinOp::Sub).is_unary());
assert!(!Intrinsic::Checked(BinOp::Mul).is_unary());
assert!(!Intrinsic::Overflowing(BinOp::Add).is_unary());
assert!(!Intrinsic::MixedAdd(Family::Wrapping).is_unary());
}
#[test]
fn the_mixed_add_names_classify() {
assert_eq!(
classify("core::num::<impl u8>::wrapping_add_signed"),
Some(Intrinsic::MixedAdd(Family::Wrapping))
);
assert_eq!(
classify("saturating_add_signed"),
Some(Intrinsic::MixedAdd(Family::Saturating))
);
assert_eq!(classify("checked_add_signed"), Some(Intrinsic::MixedAdd(Family::Checked)));
assert_eq!(
classify("overflowing_add_signed"),
Some(Intrinsic::MixedAdd(Family::Overflowing))
);
assert_eq!(
classify("core::num::<impl i8>::wrapping_add_unsigned"),
Some(Intrinsic::MixedAdd(Family::Wrapping))
);
assert_eq!(
classify("overflowing_add_unsigned"),
Some(Intrinsic::MixedAdd(Family::Overflowing))
);
assert!(classify("add_signed").is_none());
assert!(classify("add_unsigned").is_none());
}
fn check_mixed(
op: Intrinsic,
self_is_unsigned: bool,
rust: impl Fn(u64, u64) -> (Option<bool>, Option<u64>),
label: &str,
) {
let w = 8u8;
smt::with_fresh(|| {
let a = smt::var(w);
let b = smt::var(w);
let signed = !self_is_unsigned;
let outcome = eval(op, a, b, w, signed, w)
.unwrap_or_else(|| panic!("{label} at {w} bits must be modelled"));
let (ai, bi) = (smt::index(a), smt::index(b));
each_pair(w, |xb, yb| {
let (want_tag, want_val) = rust(xb, yb);
let (got_tag, got_val) = read(outcome, ai, bi, xb, yb);
assert_eq!(
(got_tag, got_val),
(want_tag, want_val),
"{label} at (self={xb}, addend={yb}): the model says \
({got_tag:?}, {got_val:?}), Rust says ({want_tag:?}, {want_val:?})"
);
});
});
}
#[test]
fn the_wrapping_mixed_adds_agree_with_rust() {
check_mixed(
Intrinsic::MixedAdd(Family::Wrapping),
true,
|xb, yb| {
let (x, r) = (xb as u8, yb as u8 as i8);
(None, Some(u64::from(x.wrapping_add_signed(r))))
},
"wrapping_add_signed u8",
);
check_mixed(
Intrinsic::MixedAdd(Family::Wrapping),
false,
|xb, yb| {
let (x, r) = (xb as u8 as i8, yb as u8);
(None, Some(x.wrapping_add_unsigned(r) as u8 as u64))
},
"wrapping_add_unsigned i8",
);
}
#[test]
fn the_overflowing_mixed_adds_agree_with_rust() {
check_mixed(
Intrinsic::MixedAdd(Family::Overflowing),
true,
|xb, yb| {
let (x, r) = (xb as u8, yb as u8 as i8);
let (v, o) = x.overflowing_add_signed(r);
(Some(o), Some(u64::from(v)))
},
"overflowing_add_signed u8",
);
check_mixed(
Intrinsic::MixedAdd(Family::Overflowing),
false,
|xb, yb| {
let (x, r) = (xb as u8 as i8, yb as u8);
let (v, o) = x.overflowing_add_unsigned(r);
(Some(o), Some(v as u8 as u64))
},
"overflowing_add_unsigned i8",
);
}
#[test]
fn the_checked_mixed_adds_agree_with_rust() {
check_mixed(
Intrinsic::MixedAdd(Family::Checked),
true,
|xb, yb| {
let (x, r) = (xb as u8, yb as u8 as i8);
match x.checked_add_signed(r) {
Some(v) => (Some(true), Some(u64::from(v))),
None => (Some(false), Some(u64::from(x.wrapping_add_signed(r)))),
}
},
"checked_add_signed u8",
);
check_mixed(
Intrinsic::MixedAdd(Family::Checked),
false,
|xb, yb| {
let (x, r) = (xb as u8 as i8, yb as u8);
match x.checked_add_unsigned(r) {
Some(v) => (Some(true), Some(v as u8 as u64)),
None => (Some(false), Some(x.wrapping_add_unsigned(r) as u8 as u64)),
}
},
"checked_add_unsigned i8",
);
}
#[test]
fn the_saturating_mixed_adds_agree_with_rust() {
check_mixed(
Intrinsic::MixedAdd(Family::Saturating),
true,
|xb, yb| {
let (x, r) = (xb as u8, yb as u8 as i8);
(None, Some(u64::from(x.saturating_add_signed(r))))
},
"saturating_add_signed u8",
);
check_mixed(
Intrinsic::MixedAdd(Family::Saturating),
false,
|xb, yb| {
let (x, r) = (xb as u8 as i8, yb as u8);
(None, Some(x.saturating_add_unsigned(r) as u8 as u64))
},
"saturating_add_unsigned i8",
);
}
#[test]
fn the_ord_names_classify_and_their_neighbours_do_not() {
assert_eq!(classify("<u8 as Ord>::min"), Some(Intrinsic::MinMax(MinMaxKind::Min)));
assert_eq!(classify("<u8 as Ord>::max"), Some(Intrinsic::MinMax(MinMaxKind::Max)));
assert_eq!(classify("<i8 as Ord>::min"), Some(Intrinsic::MinMax(MinMaxKind::Min)));
assert_eq!(classify("<i8 as Ord>::max"), Some(Intrinsic::MinMax(MinMaxKind::Max)));
assert_ne!(classify("<u8 as Ord>::max"), Some(Intrinsic::MinMax(MinMaxKind::Min)));
assert!(classify("<u8 as m::Ord>::min").is_none());
assert!(classify("<u8 as MyOrd>::min").is_none());
assert!(classify("<u8 as ord_shim::Ord>::min").is_none());
assert_eq!(classify("<u8 as Ord>::clamp"), Some(Intrinsic::Clamp));
assert!(classify("<u8 as m::Ord>::clamp").is_none());
assert_eq!(
classify("<i8 as std::cmp::Ord>::max"),
Some(Intrinsic::MinMax(MinMaxKind::Max))
);
assert_eq!(
classify("<u8 as core::cmp::Ord>::min"),
Some(Intrinsic::MinMax(MinMaxKind::Min))
);
assert!(classify("<u8 as Ord>::min_signed").is_none());
assert_eq!(classify("<u8 as Ord>::cmp"), Some(Intrinsic::OrdCmp));
assert_eq!(classify("<i8 as core::cmp::Ord>::cmp"), Some(Intrinsic::OrdCmp));
assert_eq!(classify("<u32 as std::cmp::Ord>::cmp"), Some(Intrinsic::OrdCmp));
assert!(classify("<u8 as m::Ord>::cmp").is_none());
assert!(classify("<u8 as MyOrd>::cmp").is_none());
assert!(classify("<u8 as ord_shim::Ord>::cmp").is_none());
assert_ne!(classify("<u8 as Ord>::cmp"), Some(Intrinsic::MinMax(MinMaxKind::Min)));
}
#[test]
fn the_partial_cmp_names_classify_and_their_neighbours_do_not() {
for (name, kind) in [
("<u8 as PartialEq>::eq", PartialCmpKind::Eq),
("<u8 as PartialEq>::ne", PartialCmpKind::Ne),
("<u8 as PartialOrd>::lt", PartialCmpKind::Lt),
("<u8 as PartialOrd>::le", PartialCmpKind::Le),
("<u8 as PartialOrd>::gt", PartialCmpKind::Gt),
("<u8 as PartialOrd>::ge", PartialCmpKind::Ge),
("<i8 as std::cmp::PartialOrd>::lt", PartialCmpKind::Lt),
("<u8 as core::cmp::PartialEq>::eq", PartialCmpKind::Eq),
] {
assert_eq!(classify(name), Some(Intrinsic::Cmp(kind)), "{name}");
}
assert!(classify("<u8 as m::PartialOrd>::lt").is_none());
assert!(classify("<u8 as PartialEq>::lt").is_none());
assert!(classify("<u8 as PartialOrd>::eq").is_none());
assert!(classify("<u8 as PartialEq>::lt").is_none());
assert!(classify("<u8 as MyEq>::eq").is_none());
assert!(classify("<u8 as PartialOrd>::lt_signed").is_none());
}
#[test]
fn the_ord_min_max_agree_with_rust() {
check(
Intrinsic::MinMax(MinMaxKind::Min),
8,
false,
unident,
ident,
|x, y| Some(i64::from((x as u8).min(y as u8))),
"u8::min",
);
check(
Intrinsic::MinMax(MinMaxKind::Max),
8,
false,
unident,
ident,
|x, y| Some(i64::from((x as u8).max(y as u8))),
"u8::max",
);
check(
Intrinsic::MinMax(MinMaxKind::Min),
8,
true,
|b| i8::from_ne_bytes([b as u8]) as i64,
|v| v as u8 as u64,
|x, y| Some(i64::from((x as i8).min(y as i8))),
"i8::min",
);
check(
Intrinsic::MinMax(MinMaxKind::Max),
8,
true,
|b| i8::from_ne_bytes([b as u8]) as i64,
|v| v as u8 as u64,
|x, y| Some(i64::from((x as i8).max(y as i8))),
"i8::max",
);
let ord = |kind: MinMaxKind, signed: bool, xb: u64, yb: u64| {
smt::with_fresh(|| {
let (a, b) = (smt::var(8), smt::var(8));
let Outcome::Value(v) =
eval(Intrinsic::MinMax(kind), a, b, 8, signed, 8).expect("min/max at 8 bits")
else {
panic!("min/max must produce a plain value");
};
let (ai, bi) = (smt::index(a), smt::index(b));
smt::evaluate(v, |i| {
if i == ai {
Some(xb)
} else if i == bi {
Some(yb)
} else {
None
}
})
})
};
for (kind, signed, xb, yb, want, why) in [
(MinMaxKind::Min, false, 3, 7, 3u64, "unsigned min takes the smaller"),
(MinMaxKind::Max, false, 3, 7, 7, "unsigned max takes the larger"),
(MinMaxKind::Min, true, 0x80, 1, 0x80, "i8::MIN is the smallest signed value"),
(MinMaxKind::Max, true, 0x80, 1, 1, "i8::MIN is not the largest"),
(MinMaxKind::Min, true, 0xff, 0xfe, 0xfe, "0xfe is -2, below -1"),
(MinMaxKind::Max, true, 0xff, 0xfe, 0xff, "0xff is -1, above -2"),
] {
assert_eq!(ord(kind, signed, xb, yb), Some(want), "{why} ({xb:#x}, {yb:#x})");
}
}
#[test]
fn the_partial_cmp_methods_agree_with_the_operators() {
let run = |kind: PartialCmpKind, signed: bool, oracle: fn(i64, i64) -> bool, label: &str| {
smt::with_fresh(|| {
let a = smt::var(8);
let b = smt::var(8);
let Outcome::Bool(p) = eval(Intrinsic::Cmp(kind), a, b, 8, signed, 8)
.unwrap_or_else(|| panic!("{label} at 8 bits must be modelled"))
else {
panic!("{label} must produce a `bool`");
};
let (ai, bi) = (smt::index(a), smt::index(b));
each_pair(8, |xb, yb| {
let (x, y) = if signed {
(i8::from_ne_bytes([xb as u8]) as i64, i8::from_ne_bytes([yb as u8]) as i64)
} else {
(xb as i64, yb as i64)
};
let env = |i| {
if i == ai {
Some(xb)
} else if i == bi {
Some(yb)
} else {
None
}
};
assert_eq!(
smt::evaluate_pred(p, env),
Some(oracle(x, y)),
"{label} at ({x}, {y})"
);
});
});
};
for (kind, oracle, label) in [
(PartialCmpKind::Eq, (|x: i64, y: i64| x == y) as fn(i64, i64) -> bool, "eq"),
(PartialCmpKind::Ne, |x, y| x != y, "ne"),
(PartialCmpKind::Lt, |x, y| x < y, "lt"),
(PartialCmpKind::Le, |x, y| x <= y, "le"),
(PartialCmpKind::Gt, |x, y| x > y, "gt"),
(PartialCmpKind::Ge, |x, y| x >= y, "ge"),
] {
run(kind, false, oracle, &format!("u8::{label}"));
run(kind, true, oracle, &format!("i8::{label}"));
}
}
#[test]
fn abs_diff_and_rotations_agree_with_rust() {
check(
Intrinsic::AbsDiff,
8,
false,
unident,
ident,
|x, y| Some(i64::from((x as u8).abs_diff(y as u8))),
"u8::abs_diff",
);
check(
Intrinsic::AbsDiff,
8,
true,
|b| i8::from_ne_bytes([b as u8]) as i64,
|v| v as u8 as u64,
|x, y| Some(i64::from((x as i8).abs_diff(y as i8))),
"i8::abs_diff",
);
for (kind, label_l, label_r) in [
(RotateKind::Left, "u8::rotate_left", "i8::rotate_left"),
(RotateKind::Right, "u8::rotate_right", "i8::rotate_right"),
] {
let (left, _right) = match kind {
RotateKind::Left => (true, false),
RotateKind::Right => (false, true),
};
check(
Intrinsic::Rotate(kind),
8,
false,
unident,
ident,
move |x, y| {
let (x, n) = (x as u8, y as u32);
Some(i64::from(if left { x.rotate_left(n) } else { x.rotate_right(n) }))
},
label_l,
);
check(
Intrinsic::Rotate(kind),
8,
true,
|b| i8::from_ne_bytes([b as u8]) as i64,
|v| v as u8 as u64,
move |x, y| {
let (x, n) = (x as i8, y as u32);
Some(i64::from(if left { x.rotate_left(n) } else { x.rotate_right(n) } as u8))
},
label_r,
);
}
for (kind, x, n, want, why) in [
(RotateKind::Left, 0x81u8, 8u32, 0x81u8, "rotate_left by the width is the identity"),
(RotateKind::Left, 0x81, 9, 0x03, "rotate_left by w+1 is by 1"),
(RotateKind::Right, 0x81, 0, 0x81, "rotate_right by 0 is the identity"),
(RotateKind::Right, 0x81, 7, 0x03, "rotate_right by w-1"),
] {
let got = smt::with_fresh(|| {
let (a, b) = (smt::var(8), smt::var(32));
let Outcome::Value(v) = eval(Intrinsic::Rotate(kind), a, b, 8, false, 8)
.expect("a rotation is modelled")
else {
panic!("a rotation must produce a plain value");
};
let (ai, bi) = (smt::index(a), smt::index(b));
smt::evaluate(v, |i| {
if i == ai {
Some(x as u64)
} else if i == bi {
Some(n as u64)
} else {
None
}
})
});
assert_eq!(got, Some(want as u64), "{why} ({x:#x}, {n})");
}
}
#[test]
fn wrapping_shifts_agree_with_rust() {
for (signed, label) in [(false, "u8::wrapping_shl"), (true, "i8::wrapping_shl")] {
check(
Intrinsic::WrappingShift(ShiftKind::Left),
8,
signed,
if signed {
|b| i8::from_ne_bytes([b as u8]) as i64
} else {
|b| b as i64
},
if signed { |v| v as u8 as u64 } else { |v| v as u64 },
move |x, n| {
let r = if signed {
(x as i8).wrapping_shl(n as u32) as u8
} else {
(x as u8).wrapping_shl(n as u32)
};
Some(i64::from(r))
},
label,
);
}
check(
Intrinsic::WrappingShift(ShiftKind::Right),
8,
false,
|b| b as i64,
|v| v as u64,
|x, n| Some(i64::from((x as u8).wrapping_shr(n as u32))),
"u8::wrapping_shr",
);
check(
Intrinsic::WrappingShift(ShiftKind::Right),
8,
true,
|b| i8::from_ne_bytes([b as u8]) as i64,
|v| v as u8 as u64,
|x, n| Some(i64::from((x as i8).wrapping_shr(n as u32) as u8)),
"i8::wrapping_shr",
);
for (kind, signed, x, n, want, why) in [
(ShiftKind::Left, false, 1u8, 8u32, 1u8, "shl by the width is the identity"),
(ShiftKind::Left, false, 1, 9, 2, "shl by w+1 is by 1"),
(ShiftKind::Right, false, 128, 8, 128, "unsigned shr by the width is the identity"),
(ShiftKind::Right, false, 128, 9, 64, "unsigned shr by w+1 is by 1"),
(ShiftKind::Right, true, 0x80, 8, 0x80, "signed shr by the width is the identity"),
(ShiftKind::Right, true, 0x80, 9, 0xc0, "signed shr by w+1 is by 1, sign-filled"),
(ShiftKind::Right, true, 0xf8, 1, 0xfc, "signed shr by 1 fills from the sign"),
] {
let got = smt::with_fresh(|| {
let (a, b) = (smt::var(8), smt::var(32));
let Outcome::Value(v) =
eval(Intrinsic::WrappingShift(kind), a, b, 8, signed, 8)
.expect("a wrapping shift is modelled")
else {
panic!("a wrapping shift must produce a plain value");
};
let (ai, bi) = (smt::index(a), smt::index(b));
smt::evaluate(v, |i| {
if i == ai {
Some(x as u64)
} else if i == bi {
Some(n as u64)
} else {
None
}
})
});
assert_eq!(got, Some(want as u64), "{why} ({x:#x}, {n})");
}
}
fn check_value_or_panic_binary(
op: Intrinsic,
w: u8,
signed: bool,
from_bits: impl Fn(u64) -> i64,
rust: impl Fn(i64, i64) -> i64,
panics: impl Fn(i64, i64) -> bool,
label: &str,
) {
smt::with_fresh(|| {
let a = smt::var(w);
let b = smt::var(w);
let outcome = eval(op, a, b, w, signed, w)
.unwrap_or_else(|| panic!("{label} at {w} bits must be modelled"));
let Outcome::ValueOrPanic { value, fails } = outcome else {
panic!("{label} must produce a value-or-panic outcome");
};
let (ai, bi) = (smt::index(a), smt::index(b));
each_pair(w, |xb, yb| {
let (x, y) = (from_bits(xb), from_bits(yb));
let env = |i: u32| {
if i == ai {
Some(xb)
} else if i == bi {
Some(yb)
} else {
None
}
};
let p = panics(x, y);
assert_eq!(
smt::evaluate_pred(fails, env),
Some(p),
"{label} panic predicate at ({x}, {y})"
);
if !p {
let got = smt::evaluate(value, env);
let want = rust(x, y) as u64 & mask_of(w);
assert_eq!(got, Some(want), "{label} value at ({x}, {y})");
}
});
});
}
fn check_bool_binary(
op: Intrinsic,
w: u8,
signed: bool,
from_bits: impl Fn(u64) -> i64,
oracle: impl Fn(i64, i64) -> bool,
label: &str,
) {
smt::with_fresh(|| {
let a = smt::var(w);
let b = smt::var(w);
let outcome = eval(op, a, b, w, signed, w)
.unwrap_or_else(|| panic!("{label} at {w} bits must be modelled"));
let Outcome::Bool(p) = outcome else {
panic!("{label} must produce a `bool`");
};
let (ai, bi) = (smt::index(a), smt::index(b));
each_pair(w, |xb, yb| {
let (x, y) = (from_bits(xb), from_bits(yb));
let env = |i: u32| {
if i == ai {
Some(xb)
} else if i == bi {
Some(yb)
} else {
None
}
};
assert_eq!(
smt::evaluate_pred(p, env),
Some(oracle(x, y)),
"{label} at ({x}, {y})"
);
});
});
}
#[test]
fn is_multiple_of_agrees_with_rust() {
check_bool_binary(
Intrinsic::Bool(BoolKind::MultipleOf),
8,
false,
unident,
|x, y| {
let (a, b) = (x as u8, y as u8);
if b == 0 { a == 0 } else { a % b == 0 }
},
"u8::is_multiple_of",
);
}
#[test]
fn signum_agrees_with_rust() {
check_unary(
Intrinsic::Signum,
8,
8,
true,
|xb| signed_of(xb, 8).signum() as u64 & 0xff,
"i8::signum",
);
}
#[test]
fn the_signedness_casts_agree_with_rust() {
check_unary(
Intrinsic::SignednessCast,
8,
8,
true,
|xb| u64::from(signed_of(xb, 8) as u8),
"i8::cast_unsigned",
);
check_unary(
Intrinsic::SignednessCast,
8,
8,
false,
|xb| (u8::try_from(xb).unwrap() as i8 as u8) as u64,
"u8::cast_signed",
);
}
#[test]
fn the_plain_pow_agrees_with_rust() {
check_value_or_panic_binary(
Intrinsic::PowPanic,
8,
false,
|xb| xb as i64,
|x, y| i64::from((x as u8).pow(y as u32)),
|x, y| (x as u8).checked_pow(y as u32).is_none(),
"u8::pow",
);
check_value_or_panic_binary(
Intrinsic::PowPanic,
8,
true,
|xb| signed_of(xb, 8),
|x, y| i64::from((x as i8).pow(y as u32)),
|x, y| (x as i8).checked_pow(y as u32).is_none(),
"i8::pow",
);
}
#[test]
fn the_euclidean_pair_and_div_ceil_agree_with_rust() {
let i8_min = i8::MIN as i64;
check_value_or_panic_binary(
Intrinsic::DivEuclid,
8,
true,
|b| i8::from_ne_bytes([b as u8]) as i64,
|x, y| i64::from((x as i8).div_euclid(y as i8)),
|x, y| y == 0 || (x == i8_min && y == -1),
"i8::div_euclid",
);
check_value_or_panic_binary(
Intrinsic::RemEuclid,
8,
true,
|b| i8::from_ne_bytes([b as u8]) as i64,
|x, y| i64::from((x as i8).rem_euclid(y as i8)),
|x, y| y == 0 || (x == i8_min && y == -1),
"i8::rem_euclid",
);
check_value_or_panic_binary(
Intrinsic::DivCeil,
8,
false,
unident,
|x, y| i64::from((x as u8).div_ceil(y as u8)),
|_, y| y == 0,
"u8::div_ceil",
);
check_value_or_panic_binary(
Intrinsic::DivEuclid,
8,
false,
unident,
|x, y| i64::from((x as u8).div_euclid(y as u8)),
|_, y| y == 0,
"u8::div_euclid",
);
check_value_or_panic_binary(
Intrinsic::RemEuclid,
8,
false,
unident,
|x, y| i64::from((x as u8).rem_euclid(y as u8)),
|_, y| y == 0,
"u8::rem_euclid",
);
}
#[test]
fn midpoint_agrees_with_rust() {
check_unary_binary_value(
Intrinsic::Midpoint,
8,
false,
unident,
|x, y| i64::from(((x as u16 + y as u16) / 2) as u8),
"u8::midpoint",
);
check_unary_binary_value(
Intrinsic::Midpoint,
8,
true,
|b| i8::from_ne_bytes([b as u8]) as i64,
|x, y| i64::from(((x as i32 + y as i32) / 2) as i8),
"i8::midpoint",
);
}
#[test]
fn next_multiple_of_agrees_with_rust() {
smt::with_fresh(|| {
let a = smt::var(8);
let b = smt::var(8);
let outcome = eval(Intrinsic::NextMultipleOf, a, b, 8, false, 8)
.expect("next_multiple_of must be modelled at u8");
let Outcome::ValueOrPanic { value, fails } = outcome else {
panic!("next_multiple_of must produce a value-or-panic outcome");
};
let (ai, bi) = (smt::index(a), smt::index(b));
each_pair(8, |xb, yb| {
let (x, y) = (xb as u8, yb as u8);
let env = |i: u32| {
if i == ai {
Some(xb)
} else if i == bi {
Some(yb)
} else {
None
}
};
let want = x.checked_next_multiple_of(y);
assert_eq!(
smt::evaluate_pred(fails, env),
Some(want.is_none()),
"next_multiple_of panic predicate at ({x}, {y})"
);
if let Some(v) = want {
assert_eq!(
smt::evaluate(value, env),
Some(u64::from(v)),
"next_multiple_of value at ({x}, {y})"
);
}
});
});
}
#[test]
fn checked_next_multiple_of_agrees_with_rust() {
smt::with_fresh(|| {
let a = smt::var(8);
let b = smt::var(8);
let outcome = eval(Intrinsic::CheckedNextMultipleOf, a, b, 8, false, 8)
.expect("checked_next_multiple_of must be modelled at u8");
let Outcome::Option { tag, payload } = outcome else {
panic!("checked_next_multiple_of must produce an `Option` outcome");
};
let (ai, bi) = (smt::index(a), smt::index(b));
each_pair(8, |xb, yb| {
let (x, y) = (xb as u8, yb as u8);
let env = |i: u32| {
if i == ai {
Some(xb)
} else if i == bi {
Some(yb)
} else {
None
}
};
let want = x.checked_next_multiple_of(y);
assert_eq!(
smt::evaluate(tag, env),
Some(if want.is_some() { 1 } else { 0 }),
"checked_next_multiple_of tag at ({x}, {y})"
);
if let Some(v) = want {
assert_eq!(
smt::evaluate(payload, env),
Some(u64::from(v)),
"checked_next_multiple_of payload at ({x}, {y})"
);
}
});
});
}
#[test]
fn the_integer_logs_agree_with_rust() {
for (kind, oracle_u, oracle_i, label) in [
(
LogKind::Ilog2,
(|x: u8| u64::from(x.ilog2())) as fn(u8) -> u64,
(|x: i8| u64::from(x.ilog2())) as fn(i8) -> u64,
"ilog2",
),
(
LogKind::Ilog10,
(|x: u8| u64::from(x.ilog10())) as fn(u8) -> u64,
(|x: i8| u64::from(x.ilog10())) as fn(i8) -> u64,
"ilog10",
),
] {
for xb in 0..=u8::MAX {
let x = xb;
check_log(
Intrinsic::Ilog(kind),
8,
false,
xb as u64,
x > 0,
|| oracle_u(x),
&format!("u8::{label} at {x}"),
);
}
for xb in 0..=u8::MAX {
let x = i8::from_ne_bytes([xb]);
check_log(
Intrinsic::Ilog(kind),
8,
true,
xb as u64,
x > 0,
|| oracle_i(x),
&format!("i8::{label} at {x}"),
);
}
}
}
fn check_log(
op: Intrinsic,
w: u8,
signed: bool,
bits: u64,
defined: bool,
want: impl Fn() -> u64,
label: &str,
) {
smt::with_fresh(|| {
let a = smt::var(w);
let outcome = eval(op, a, a, w, signed, 32)
.unwrap_or_else(|| panic!("{label} must be modelled"));
let Outcome::ValueOrPanic { value, fails } = outcome else {
panic!("{label} must produce a value-or-panic outcome");
};
let ai = smt::index(a);
let env = |i: u32| if i == ai { Some(bits) } else { None };
assert_eq!(
smt::evaluate_pred(fails, env),
Some(!defined),
"{label}: panic predicate"
);
if defined {
assert_eq!(smt::evaluate(value, env), Some(want()), "{label}: value");
}
});
}
#[test]
fn the_checked_logs_agree_with_rust() {
for (kind, oracle_u, oracle_i, label) in [
(
LogKind::Ilog2,
(|x: u8| x.checked_ilog2().map(u64::from)) as fn(u8) -> Option<u64>,
(|x: i8| x.checked_ilog2().map(u64::from)) as fn(i8) -> Option<u64>,
"checked_ilog2",
),
(
LogKind::Ilog10,
(|x: u8| x.checked_ilog10().map(u64::from)) as fn(u8) -> Option<u64>,
(|x: i8| x.checked_ilog10().map(u64::from)) as fn(i8) -> Option<u64>,
"checked_ilog10",
),
] {
for xb in 0..=u8::MAX {
let x = xb;
check_checked_log(
Intrinsic::CheckedIlog(kind),
false,
xb as u64,
oracle_u(x),
&format!("u8::{label} at {x}"),
);
}
for xb in 0..=u8::MAX {
let x = i8::from_ne_bytes([xb]);
check_checked_log(
Intrinsic::CheckedIlog(kind),
true,
xb as u64,
oracle_i(x),
&format!("i8::{label} at {x}"),
);
}
}
}
fn check_checked_log(
op: Intrinsic,
signed: bool,
bits: u64,
want: Option<u64>,
label: &str,
) {
smt::with_fresh(|| {
let a = smt::var(8);
let outcome = eval(op, a, a, 8, signed, 32)
.unwrap_or_else(|| panic!("{label} must be modelled"));
let Outcome::Option { tag, payload } = outcome else {
panic!("{label} must produce an `Option` outcome");
};
let ai = smt::index(a);
let env = |i: u32| if i == ai { Some(bits) } else { None };
assert_eq!(
smt::evaluate(tag, env),
Some(if want.is_some() { 1 } else { 0 }),
"{label}: tag"
);
if let Some(v) = want {
assert_eq!(smt::evaluate(payload, env), Some(v), "{label}: payload");
}
});
}
fn next_power_of_two_oracle(xb: u64, w: u8) -> Option<u64> {
let x = xb & mask_of(w);
if x <= 1 {
return Some(1);
}
let k = 64 - (x - 1).leading_zeros();
if k >= u32::from(w) {
None
} else {
Some(1u64 << k)
}
}
#[test]
fn the_next_power_of_two_pair_agrees_with_rust() {
for w in [1u8, 4, 8, 16] {
for (op, is_checked) in
[(Intrinsic::NextPowerOfTwo, false), (Intrinsic::CheckedNextPowerOfTwo, true)]
{
smt::with_fresh(|| {
let a = smt::var(w);
let outcome = eval(op, a, a, w, false, w).expect("modelled");
let ai = smt::index(a);
for xb in 0..(1u64 << w) {
let want = next_power_of_two_oracle(xb, w);
let env = |i: u32| if i == ai { Some(xb) } else { None };
match &outcome {
Outcome::ValueOrPanic { value, fails } => {
assert!(!is_checked);
assert_eq!(
smt::evaluate_pred(*fails, env),
Some(want.is_none()),
"next_power_of_two panic at {w} bits, {xb:#x}"
);
if let Some(v) = want {
assert_eq!(
smt::evaluate(*value, env),
Some(v),
"next_power_of_two value at {w} bits, {xb:#x}"
);
}
}
Outcome::Option { tag, payload } => {
assert!(is_checked);
let want_tag = if want.is_some() { 1 } else { 0 };
assert_eq!(
smt::evaluate(*tag, env),
Some(want_tag),
"checked_next_power_of_two tag at {w} bits, {xb:#x}"
);
if let Some(v) = want {
assert_eq!(
smt::evaluate(*payload, env),
Some(v),
"checked_next_power_of_two payload at {w} bits, {xb:#x}"
);
}
}
_ => panic!("next_power_of_two must be a value-or-panic or an Option"),
}
}
});
}
}
}
fn check_unary_binary_value(
op: Intrinsic,
w: u8,
signed: bool,
from_bits: impl Fn(u64) -> i64,
rust: impl Fn(i64, i64) -> i64,
label: &str,
) {
smt::with_fresh(|| {
let a = smt::var(w);
let b = smt::var(w);
let outcome = eval(op, a, b, w, signed, w)
.unwrap_or_else(|| panic!("{label} at {w} bits must be modelled"));
let Outcome::Value(value) = outcome else {
panic!("{label} must produce a plain value");
};
let (ai, bi) = (smt::index(a), smt::index(b));
each_pair(w, |xb, yb| {
let (x, y) = (from_bits(xb), from_bits(yb));
let env = |i: u32| {
if i == ai {
Some(xb)
} else if i == bi {
Some(yb)
} else {
None
}
};
let want = rust(x, y) as u64 & mask_of(w);
assert_eq!(smt::evaluate(value, env), Some(want), "{label} at ({x}, {y})");
});
});
}
#[test]
fn the_byte_permutations_and_orderings_agree_with_rust() {
for w in [8u8, 16] {
check_unary(
Intrinsic::BitReverse,
w,
w,
false,
move |xb| match w {
8 => u8::try_from(xb).unwrap().reverse_bits() as u64,
16 => u16::try_from(xb).unwrap().reverse_bits() as u64,
_ => unreachable!(),
},
"reverse_bits",
);
check_unary(
Intrinsic::ByteSwap,
w,
w,
false,
move |xb| match w {
8 => u8::try_from(xb).unwrap().swap_bytes() as u64,
16 => u16::try_from(xb).unwrap().swap_bytes() as u64,
_ => unreachable!(),
},
"swap_bytes",
);
for (kind, label) in
[(ByteOrderKind::Be, "to_be"), (ByteOrderKind::Le, "to_le")]
{
check_unary(
Intrinsic::ByteOrder(kind),
w,
w,
false,
move |xb| match w {
8 => {
let x = u8::try_from(xb).unwrap();
match kind {
ByteOrderKind::Be => x.to_be() as u64,
ByteOrderKind::Le => x.to_le() as u64,
}
}
16 => {
let x = u16::try_from(xb).unwrap();
match kind {
ByteOrderKind::Be => x.to_be() as u64,
ByteOrderKind::Le => x.to_le() as u64,
}
}
_ => unreachable!(),
},
label,
);
}
}
}
#[test]
fn the_ascii_case_conversions_agree_with_rust() {
check_unary(
Intrinsic::AsciiCase(AsciiCaseKind::Upper),
8,
8,
false,
|xb| u8::try_from(xb).unwrap().to_ascii_uppercase() as u64,
"u8::to_ascii_uppercase",
);
check_unary(
Intrinsic::AsciiCase(AsciiCaseKind::Lower),
8,
8,
false,
|xb| u8::try_from(xb).unwrap().to_ascii_lowercase() as u64,
"u8::to_ascii_lowercase",
);
}
#[test]
fn the_new_value_names_classify_and_their_neighbours_do_not() {
assert_eq!(classify("core::num::<impl i32>::signum"), Some(Intrinsic::Signum));
assert_eq!(
classify("core::num::<impl i32>::cast_unsigned"),
Some(Intrinsic::SignednessCast)
);
assert_eq!(
classify("core::num::<impl u32>::cast_signed"),
Some(Intrinsic::SignednessCast)
);
assert_eq!(classify("core::num::<impl i32>::div_euclid"), Some(Intrinsic::DivEuclid));
assert_eq!(classify("core::num::<impl i32>::rem_euclid"), Some(Intrinsic::RemEuclid));
assert_eq!(classify("core::num::<impl u32>::div_ceil"), Some(Intrinsic::DivCeil));
assert_eq!(classify("core::num::<impl u8>::reverse_bits"), Some(Intrinsic::BitReverse));
assert_eq!(classify("core::num::<impl u16>::swap_bytes"), Some(Intrinsic::ByteSwap));
assert_eq!(classify("core::num::<impl u32>::to_be"), Some(Intrinsic::ByteOrder(ByteOrderKind::Be)));
assert_eq!(classify("core::num::<impl u32>::to_le"), Some(Intrinsic::ByteOrder(ByteOrderKind::Le)));
assert_eq!(classify("core::num::<impl u32>::from_be"), Some(Intrinsic::ByteOrder(ByteOrderKind::Be)));
assert_eq!(classify("core::num::<impl u32>::from_le"), Some(Intrinsic::ByteOrder(ByteOrderKind::Le)));
assert_eq!(classify("core::num::<impl u8>::to_ascii_uppercase"), Some(Intrinsic::AsciiCase(AsciiCaseKind::Upper)));
assert_eq!(classify("core::num::<impl u8>::to_ascii_lowercase"), Some(Intrinsic::AsciiCase(AsciiCaseKind::Lower)));
assert_eq!(classify("core::num::<impl u32>::is_multiple_of"), Some(Intrinsic::Bool(BoolKind::MultipleOf)));
assert_eq!(classify("core::num::<impl u32>::midpoint"), Some(Intrinsic::Midpoint));
assert_eq!(classify("core::num::<impl i32>::midpoint"), Some(Intrinsic::Midpoint));
assert_eq!(classify("core::num::<impl u32>::next_multiple_of"), Some(Intrinsic::NextMultipleOf));
assert_eq!(
classify("core::num::<impl u32>::checked_next_multiple_of"),
Some(Intrinsic::CheckedNextMultipleOf)
);
assert_eq!(classify("core::num::<impl u32>::ilog2"), Some(Intrinsic::Ilog(LogKind::Ilog2)));
assert_eq!(classify("core::num::<impl i32>::ilog2"), Some(Intrinsic::Ilog(LogKind::Ilog2)));
assert_eq!(classify("core::num::<impl u32>::ilog10"), Some(Intrinsic::Ilog(LogKind::Ilog10)));
assert_eq!(
classify("core::num::<impl u32>::checked_ilog2"),
Some(Intrinsic::CheckedIlog(LogKind::Ilog2))
);
assert_eq!(
classify("core::num::<impl i32>::checked_ilog10"),
Some(Intrinsic::CheckedIlog(LogKind::Ilog10))
);
assert_eq!(classify("core::num::<impl i32>::ilog10"), Some(Intrinsic::Ilog(LogKind::Ilog10)));
assert_eq!(classify("core::num::<impl u32>::to_be_bytes"), None);
assert_eq!(classify("core::num::<impl u32>::to_le_bytes"), None);
assert_eq!(classify("core::num::<impl u32>::signum_thing"), None);
assert_eq!(classify("core::num::<impl u32>::no_div_ceil"), None);
assert_eq!(classify("core::num::<impl u8>::to_ascii_uppercase_thing"), None);
}
#[test]
fn the_new_shapes_are_modelled_only_on_the_types_that_have_them() {
for w in [8u8, 16, 32] {
assert!(is_modelled(Intrinsic::Signum, w, true), "iN::signum exists");
assert!(!is_modelled(Intrinsic::Signum, w, false), "uN::signum does not exist");
assert!(is_modelled(Intrinsic::DivEuclid, w, true));
assert!(is_modelled(Intrinsic::DivEuclid, w, false));
assert!(is_modelled(Intrinsic::RemEuclid, w, true));
assert!(is_modelled(Intrinsic::RemEuclid, w, false));
assert!(is_modelled(Intrinsic::DivCeil, w, false));
assert!(!is_modelled(Intrinsic::DivCeil, w, true));
assert!(is_modelled(Intrinsic::Bool(BoolKind::MultipleOf), w, false));
assert!(!is_modelled(Intrinsic::Bool(BoolKind::MultipleOf), w, true));
assert!(is_modelled(Intrinsic::Midpoint, w, true));
assert!(is_modelled(Intrinsic::Midpoint, w, false));
assert!(is_modelled(Intrinsic::Ilog(LogKind::Ilog2), w, true));
assert!(is_modelled(Intrinsic::Ilog(LogKind::Ilog2), w, false));
assert!(is_modelled(Intrinsic::Ilog(LogKind::Ilog10), w, true));
assert!(is_modelled(Intrinsic::Ilog(LogKind::Ilog10), w, false));
assert!(is_modelled(Intrinsic::NextMultipleOf, w, false));
assert!(!is_modelled(Intrinsic::NextMultipleOf, w, true));
assert!(is_modelled(Intrinsic::NextPowerOfTwo, w, false));
assert!(!is_modelled(Intrinsic::NextPowerOfTwo, w, true));
assert!(is_modelled(Intrinsic::CheckedNextPowerOfTwo, w, false));
assert!(!is_modelled(Intrinsic::CheckedNextPowerOfTwo, w, true));
assert!(is_modelled(Intrinsic::BitReverse, w, true));
assert!(is_modelled(Intrinsic::BitReverse, w, false));
assert!(is_modelled(Intrinsic::ByteSwap, w, true));
assert!(is_modelled(Intrinsic::ByteOrder(ByteOrderKind::Be), w, false));
}
for op in [
Intrinsic::BitReverse,
Intrinsic::ByteSwap,
Intrinsic::ByteOrder(ByteOrderKind::Le),
] {
assert!(is_modelled(op, 64, true));
assert!(is_modelled(op, 64, false));
}
assert!(is_modelled(Intrinsic::Signum, 64, true));
assert!(is_modelled(Intrinsic::AsciiCase(AsciiCaseKind::Upper), 8, false));
assert!(!is_modelled(Intrinsic::AsciiCase(AsciiCaseKind::Upper), 16, false));
assert!(!is_modelled(Intrinsic::AsciiCase(AsciiCaseKind::Upper), 8, true));
assert!(!is_modelled(Intrinsic::DivEuclid, 64, true));
assert!(!is_modelled(Intrinsic::DivCeil, 64, false));
}
#[test]
fn the_abs_value_and_panic_predicate_agree_with_rust() {
for w in [1u8, 4, 8] {
smt::with_fresh(|| {
let a = smt::var(w);
let outcome = eval(Intrinsic::Abs, a, a, w, true, w).expect("abs is modelled");
let Outcome::ValueOrPanic { value, fails } = outcome else {
panic!("abs must produce a value-or-panic outcome");
};
let ai = smt::index(a);
for xb in 0..(1u64 << w) {
let x = signed_of(xb, w);
let env = |i: u32| if i == ai { Some(xb) } else { None };
let got = smt::evaluate(value, env);
let want = x.wrapping_abs() as u64 & mask_of(w);
assert_eq!(
got,
Some(want),
"abs at {w} bits, bits {xb:#x}: the model says {got:?}, Rust says {want:#x}"
);
let want_fails = x == i64::MIN >> (64 - w);
assert_eq!(
smt::evaluate_pred(fails, env),
Some(want_fails),
"abs panic at {w} bits, bits {xb:#x}: want {want_fails}"
);
}
});
}
}
#[test]
fn the_unsigned_abs_agrees_with_rust() {
for w in [1u8, 4, 8, 16] {
smt::with_fresh(|| {
let a = smt::var(w);
let outcome =
eval(Intrinsic::UnsignedAbs, a, a, w, true, w).expect("unsigned_abs is modelled");
let Outcome::Value(value) = outcome else {
panic!("unsigned_abs is total, so it must be a plain value, got a failure");
};
let ai = smt::index(a);
for xb in 0..(1u64 << w) {
let x = signed_of(xb, w);
let env = |i: u32| if i == ai { Some(xb) } else { None };
let got = smt::evaluate(value, env);
let want = x.unsigned_abs() & mask_of(w);
assert_eq!(
got,
Some(want),
"unsigned_abs at {w} bits, bits {xb:#x}: the model says {got:?}, Rust says {want:#x}"
);
}
});
}
}
#[test]
fn the_clamp_value_and_panic_predicate_agree_with_rust() {
for signed in [false, true] {
let w = 4u8;
smt::with_fresh(|| {
let (a, l, h) = (smt::var(w), smt::var(w), smt::var(w));
let outcome = clamp(a, l, h, w, signed).expect("clamp is modelled");
let Outcome::ValueOrPanic { value, fails } = outcome else {
panic!("clamp must produce a value-or-panic outcome");
};
let (ai, li, hi_i) = (smt::index(a), smt::index(l), smt::index(h));
for xb in 0..(1u64 << w) {
for lob in 0..(1u64 << w) {
for hib in 0..(1u64 << w) {
let (x, lo, hi) = if signed {
(signed_of(xb, w), signed_of(lob, w), signed_of(hib, w))
} else {
(xb as i64, lob as i64, hib as i64)
};
let env = |i: u32| {
if i == ai {
Some(xb)
} else if i == li {
Some(lob)
} else if i == hi_i {
Some(hib)
} else {
None
}
};
let want = (if x < lo {
lo
} else if x > hi {
hi
} else {
x
}) as u64
& mask_of(w);
let got = smt::evaluate(value, env);
assert_eq!(
got,
Some(want),
"clamp(signed={signed}) ({x}, {lo}, {hi}): model {got:?}, Rust {want}"
);
let want_fails = lo > hi;
assert_eq!(
smt::evaluate_pred(fails, env),
Some(want_fails),
"clamp panic(signed={signed}) ({x}, {lo}, {hi}): want {want_fails}"
);
}
}
}
});
}
}
#[test]
fn the_abs_and_clamp_names_classify_and_their_neighbours_do_not() {
assert_eq!(classify("core::num::<impl i32>::abs"), Some(Intrinsic::Abs));
assert_eq!(classify("abs"), Some(Intrinsic::Abs));
assert_eq!(classify("<u32 as Ord>::clamp"), Some(Intrinsic::Clamp));
assert_eq!(classify("<i8 as std::cmp::Ord>::clamp"), Some(Intrinsic::Clamp));
assert_eq!(classify("<i8 as core::cmp::Ord>::clamp"), Some(Intrinsic::Clamp));
assert_eq!(classify("<MyT as m::Ord>::clamp"), None);
assert_eq!(classify("<MyT as MyOrd>::clamp"), None);
assert_eq!(classify("clamp"), None);
assert_eq!(
classify("core::num::<impl i8>::wrapping_abs"),
Some(Intrinsic::Unary(Family::Wrapping, UnOp::Abs))
);
assert_eq!(classify("core::num::<impl i8>::checked_abs"),
Some(Intrinsic::Unary(Family::Checked, UnOp::Abs)));
assert_eq!(classify("core::num::<impl i8>::no_abs"), None);
}
fn mask_of(w: u8) -> u64 {
if w >= 64 {
u64::MAX
} else {
(1u64 << w) - 1
}
}
fn signed_of(bits: u64, w: u8) -> i64 {
let shift = 64 - u32::from(w);
((bits << shift) as i64) >> shift
}
#[test]
fn the_conversion_names_classify_and_their_neighbours_do_not() {
for name in [
"<u16 as From<u8>>::from",
"<u16 as core::convert::From<u8>>::from",
"<u16 as std::convert::From<u8>>::from",
"<i8 as Into<i32>>::into",
"<i8 as core::convert::Into<i32>>::into",
"<i8 as std::convert::Into<i32>>::into",
] {
assert!(classify(name).is_some(), "`{name}` must classify as a conversion");
}
assert_eq!(
classify("<u16 as From<u8>>::from"),
Some(Intrinsic::Conversion(Conversion::From))
);
assert_eq!(
classify("<u8 as Into<u16>>::into"),
Some(Intrinsic::Conversion(Conversion::Into))
);
assert_eq!(classify("<MyT as m::From<u8>>::from"), None);
assert_eq!(classify("<MyT as m::Into<u16>>::into"), None);
assert_eq!(classify("<MyT as MyFrom<u8>>::from"), None);
assert_eq!(classify("core::num::<impl u8>::from"), None);
assert_eq!(classify("from"), None);
assert_eq!(classify("into"), None);
assert_eq!(classify("<u8 as TryFrom<u16>>::try_from"), None);
assert_eq!(classify("<u16 as FromIterator<u8>>::from_iter"), None);
}
#[test]
fn a_conversion_reads_its_source_and_destination_from_the_name() {
assert_eq!(
conversion_types("<u16 as From<u8>>::from", Conversion::From),
Some((Ty::U8, Ty::U16))
);
assert_eq!(
conversion_types("<u8 as Into<u16>>::into", Conversion::Into),
Some((Ty::U8, Ty::U16))
);
assert_eq!(
conversion_types("<i8 as Into<i64>>::into", Conversion::Into),
Some((Ty::I8, Ty::I64))
);
assert_eq!(
conversion_types("<i16 as From<u8>>::from", Conversion::From),
Some((Ty::U8, Ty::I16))
);
let (src, dst) = conversion_types("<u8 as From<bool>>::from", Conversion::From).unwrap();
assert_eq!(src, Ty::Bool);
assert_eq!(int_width(&src), None);
assert_eq!(int_width(&dst), Some(8));
}
#[test]
fn the_conversion_agrees_with_rust() {
let check = |src_w: u8,
dst_w: u8,
src_signed: bool,
src_ty: Ty,
dst_ty: Ty,
rust: &dyn Fn(u64) -> u64,
label: &str| {
smt::with_fresh(|| {
let x = smt::var(src_w);
let xi = smt::index(x);
let Outcome::Value(v) = eval(
Intrinsic::Conversion(Conversion::From),
x,
x,
src_w,
src_signed,
dst_w,
)
.unwrap_or_else(|| panic!("{label}: must be modelled")) else {
panic!("{label}: a conversion produces a plain value");
};
for bits in 0..(1u64 << src_w) {
let got = smt::evaluate(v, |i| if i == xi { Some(bits) } else { None });
let want = rust(bits);
assert_eq!(
got,
Some(want),
"{label} at {bits:#x}: the model says {got:?}, Rust says {want:#x}"
);
}
assert_eq!(src_ty.is_signed(), src_signed, "{label}: source signedness");
assert_eq!(int_width(&src_ty), Some(src_w), "{label}: source width");
assert_eq!(int_width(&dst_ty), Some(dst_w), "{label}: destination width");
});
};
let u8_to_u16 = |bits: u64| u64::from(u16::from(bits as u8));
check(8, 16, false, Ty::U8, Ty::U16, &u8_to_u16, "u16::from(u8)");
let i8_to_i16 = |bits: u64| u64::from(i16::from(i8::from_ne_bytes([bits as u8])) as u16);
check(8, 16, true, Ty::I8, Ty::I16, &i8_to_i16, "i16::from(i8)");
let u8_to_i16 = |bits: u64| u64::from(i16::from(bits as u8) as u16);
check(8, 16, false, Ty::U8, Ty::I16, &u8_to_i16, "i16::from(u8)");
let i8_to_i64 = |bits: u64| i64::from(i8::from_ne_bytes([bits as u8])) as u64;
check(8, 64, true, Ty::I8, Ty::I64, &i8_to_i64, "i64::from(i8)");
let u8_to_u32 = |bits: u64| u64::from(u32::from(bits as u8));
check(8, 32, false, Ty::U8, Ty::U32, &u8_to_u32, "u32::from(u8)");
let i16_to_i32 =
|bits: u64| u64::from(i32::from(i16::from_ne_bytes((bits as u16).to_ne_bytes())) as u32);
check(16, 32, true, Ty::I16, Ty::I32, &i16_to_i32, "i32::from(i16)");
let widen = |src_w: u8, dst_w: u8, src_signed: bool, bits: u64| {
smt::with_fresh(|| {
let x = smt::var(src_w);
let xi = smt::index(x);
let Outcome::Value(v) = eval(
Intrinsic::Conversion(Conversion::From),
x,
x,
src_w,
src_signed,
dst_w,
)
.expect("a widening conversion is modelled") else {
panic!("a conversion produces a plain value");
};
smt::evaluate(v, |i| if i == xi { Some(bits) } else { None })
})
};
for (src_w, dst_w, signed, bits, want, why) in [
(8u8, 16u8, false, 0xff, 0xffu64, "unsigned widens by zero-fill"),
(8, 16, true, 0xff, 0xffff, "-1i8 widens to -1i16, not 255"),
(8, 16, true, 0x80, 0xff80, "i8::MIN widens to i16::MIN"),
(8, 64, true, 0x80, 0xffff_ffff_ffff_ff80, "i8::MIN widens to i64::MIN"),
(8, 16, false, 0x80, 0x80, "u8::128 stays 128 in a wider unsigned"),
(16, 32, true, 0x8000, 0xffff_8000, "i16::MIN widens to i32::MIN"),
] {
assert_eq!(
widen(src_w, dst_w, signed, bits),
Some(want),
"{why} ({bits:#x})"
);
}
smt::with_fresh(|| {
let x = smt::var(16);
assert!(
eval(Intrinsic::Conversion(Conversion::From), x, x, 16, false, 8).is_none(),
"a narrowing conversion must be refused"
);
});
smt::with_fresh(|| {
let x = smt::var(16);
assert!(
eval(Intrinsic::Conversion(Conversion::From), x, x, 16, false, 16).is_some(),
"a same-width conversion is the identity `core` implements, not a refusal"
);
});
}
#[test]
fn a_rotation_needs_a_power_of_two_width() {
let rot = Intrinsic::Rotate(RotateKind::Left);
for w in [8u8, 16, 32, 64] {
assert!(is_modelled(rot, w, false), "a rotation at width {w} must be modelled");
}
for w in [12u8, 24, 48] {
assert!(
!is_modelled(rot, w, false),
"a rotation at the non-power-of-two width {w} must be refused"
);
}
for w in [0u8, 65] {
assert!(!is_modelled(Intrinsic::Rotate(RotateKind::Right), w, false));
}
}
}