use std::collections::BTreeMap;
use crate::mir::parse::{self, Term};
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum PanicKind {
OverflowAdd,
OverflowSub,
OverflowMul,
OverflowDiv,
OverflowRem,
OverflowNeg,
DivByZero,
RemByZero,
ShiftLeft,
ShiftRight,
Bounds,
Other(String),
}
impl PanicKind {
pub fn from_text_message(msg: &str) -> PanicKind {
let has = |s: &str| msg.contains(s);
if has("by zero") || has("divisor of zero") {
if has("remainder") {
PanicKind::RemByZero
} else {
PanicKind::DivByZero
}
} else if has("negate") {
PanicKind::OverflowNeg
} else if has("shift left") {
PanicKind::ShiftLeft
} else if has("shift right") {
PanicKind::ShiftRight
} else if has("index out of bounds") || has("slice index") {
PanicKind::Bounds
} else if has("{} - {}") {
PanicKind::OverflowSub
} else if has("{} + {}") {
PanicKind::OverflowAdd
} else if has("{} * {}") {
PanicKind::OverflowMul
} else if has("{} / {}") {
PanicKind::OverflowDiv
} else if has("{} % {}") {
PanicKind::OverflowRem
} else {
PanicKind::Other(msg.to_string())
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Polarity {
True,
Negated,
}
impl Polarity {
pub const fn from_negated(negated: bool) -> Self {
if negated {
Polarity::Negated
} else {
Polarity::True
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct AssertShape {
pub kind: PanicKind,
pub polarity: Polarity,
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct FnShape {
pub blocks: usize,
pub panics: Vec<AssertShape>,
}
pub fn of_text_mir(mir: &str) -> BTreeMap<String, Vec<FnShape>> {
let program = parse::parse_program(mir);
let mut out: BTreeMap<String, Vec<FnShape>> = BTreeMap::new();
for f in &program.fns {
let mut panics = Vec::new();
for block in &f.blocks {
if let Term::Assert { msg, negated, .. } = &block.term {
panics.push(AssertShape {
kind: PanicKind::from_text_message(msg),
polarity: Polarity::from_negated(*negated),
});
}
}
let key = f.name.rsplit("::").next().unwrap_or(&f.name).to_string();
out.entry(key).or_default().push(FnShape {
blocks: f.blocks.len(),
panics,
});
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn classifies_rustc_text_messages() {
let cases = [
("attempt to compute `{} - {}`, which would overflow", PanicKind::OverflowSub),
("attempt to compute `{} + {}`, which would overflow", PanicKind::OverflowAdd),
("attempt to compute `{} * {}`, which would overflow", PanicKind::OverflowMul),
("attempt to compute `{} / {}`, which would overflow", PanicKind::OverflowDiv),
("attempt to compute `{} % {}`, which would overflow", PanicKind::OverflowRem),
("attempt to negate `{}`, which would overflow", PanicKind::OverflowNeg),
("attempt to divide `{}` by zero", PanicKind::DivByZero),
("attempt to calculate the remainder with a divisor of zero", PanicKind::RemByZero),
("attempt to shift left by `{}`, which would overflow", PanicKind::ShiftLeft),
("attempt to shift right by `{}`, which would overflow", PanicKind::ShiftRight),
("index out of bounds: the len is {} but the index is {}", PanicKind::Bounds),
];
for (msg, want) in cases {
assert_eq!(PanicKind::from_text_message(msg), want, "message: {msg}");
}
}
#[test]
fn an_unknown_message_is_preserved() {
let kind = PanicKind::from_text_message("something entirely new");
assert_eq!(kind, PanicKind::Other("something entirely new".to_string()));
}
#[test]
fn shape_counts_blocks_from_a_real_dump() {
let dump = "\
fn simple(_1: u32, _2: u32) -> u32 {
let mut _0: u32;
let mut _3: bool;
bb0: {
_3 = Lt(_1, _2);
switchInt(move _3) -> [0: bb2, otherwise: bb1];
}
bb1: {
_0 = _1;
goto -> bb2;
}
bb2: {
return;
}
}
";
let shapes = of_text_mir(dump);
let s = shapes.get("simple").expect("function parsed");
assert_eq!(s.len(), 1, "one function named `simple`");
assert_eq!(s[0].blocks, 3);
assert!(s[0].panics.is_empty());
}
#[test]
fn polarity_is_recorded_and_distinguishes_inverted_guards() {
let dump = |cond: &str| {
format!(
"\
fn checked(_1: u32, _2: u32) -> u32 {{
let mut _0: u32;
let mut _3: bool;
bb0: {{
_3 = AddWithOverflow(_1, _2);
assert({cond}move (_3.1: bool), \"attempt to compute `{{}} + {{}}`, which would overflow\") -> [success: bb1, unwind continue];
}}
bb1: {{
_0 = _1;
return;
}}
}}
"
)
};
let normal = of_text_mir(&dump(""));
let inverted = of_text_mir(&dump("!"));
let n = &normal.get("checked").unwrap()[0];
let i = &inverted.get("checked").unwrap()[0];
assert_eq!(n.panics.len(), 1);
assert_eq!(n.panics[0].kind, PanicKind::OverflowAdd);
assert_eq!(i.panics[0].kind, PanicKind::OverflowAdd);
assert_eq!(n.panics[0].polarity, Polarity::True);
assert_eq!(i.panics[0].polarity, Polarity::Negated);
assert_ne!(
n, i,
"flipping the `!` must change the shape, or the oracle cannot see it"
);
}
#[test]
fn same_named_functions_are_both_kept() {
let dump = "\
fn check(_1: u32, _2: u32) -> u32 {
let mut _0: u32;
bb0: {
_0 = _1;
return;
}
}
fn check(_1: u32) -> u32 {
let mut _0: u32;
let mut _2: u32;
bb0: {
_0 = _1;
return;
}
bb1: {
return;
}
}
";
let shapes = of_text_mir(dump);
let group = shapes.get("check").expect("both methods present");
assert_eq!(group.len(), 2, "both `check`s must be kept, not overwritten");
let mut blocks: Vec<usize> = group.iter().map(|s| s.blocks).collect();
blocks.sort_unstable();
assert_eq!(blocks, vec![1, 2], "each shape is kept distinctly");
}
}