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");
}
#[test]
fn the_shape_sees_structure_and_guards_but_not_places() {
let shape_of = |src: &str| of_text_mir(src).remove("f");
let parsed = |src: &str, blocks: usize| {
let mut group = shape_of(src).expect("the dump must parse to a function `f`");
assert_eq!(group.len(), 1, "the dump must yield exactly one `f`");
let s = group.remove(0);
assert_eq!(
s.blocks, blocks,
"the parsing control expects {blocks} block(s), got {}",
s.blocks
);
s
};
let len_old = "\
fn f(_1: &[u8], _2: usize) -> u8 {
let mut _0: u8;
let mut _3: usize;
let mut _4: bool;
bb0: {
_3 = Len((*_1));
_4 = Lt(copy _2, copy _3);
assert(move _4, \"index out of bounds: the len is {} but the index is {}\") -> [success: bb1, unwind continue];
}
bb1: {
_0 = const 1u8;
return;
}
}
";
let len_new = len_old.replace("Len((*_1))", "PtrMetadata(copy _1)");
let old_shape = parsed(len_old, 2);
let new_shape = parsed(&len_new, 2);
assert_eq!(
old_shape, new_shape,
"a place's spelling is invisible to the shape -- gate 10 cannot catch a \
printer change that only re-spells a place"
);
let wrong_local = len_new.replace("Lt(copy _2, copy _3)", "Lt(copy _1, copy _3)");
assert_eq!(
new_shape,
parsed(&wrong_local, 2),
"which local an operand reads is invisible to the shape"
);
let field_0 = "\
fn f(_1: (u8, u8)) -> u8 {
let mut _0: u8;
bb0: {
_0 = copy (_1.0: u8);
return;
}
}
";
let field_1 = field_0.replace("(_1.0: u8)", "(_1.1: u8)");
assert_eq!(
parsed(field_0, 1),
parsed(&field_1, 1),
"which field a projection reads is invisible to the shape"
);
let one_block = "\
fn f(_1: u32) -> u32 {
let mut _0: u32;
bb0: {
_0 = copy _1;
return;
}
}
";
let three_blocks = "\
fn f(_1: u32) -> u32 {
let mut _0: u32;
let mut _2: bool;
bb0: {
_2 = Lt(copy _1, const 3u32);
switchInt(move _2) -> [0: bb2, otherwise: bb1];
}
bb1: {
_0 = copy _1;
goto -> bb2;
}
bb2: {
return;
}
}
";
assert_ne!(
parsed(one_block, 1),
parsed(three_blocks, 3),
"the block count must distinguish a branch -- this is the shape's whole job"
);
let guard = "\
fn f(_1: u32, _2: u32) -> u32 {
let mut _0: u32;
let mut _3: bool;
bb0: {
_3 = AddWithOverflow(_1, _2);
assert(move (_3.1: bool), \"attempt to compute `{} + {}`, which would overflow\") -> [success: bb1, unwind continue];
}
bb1: {
_0 = copy _1;
return;
}
}
";
let flipped = guard.replace("assert(move (_3.1", "assert(!move (_3.1");
assert_ne!(
parsed(guard, 2),
parsed(&flipped, 2),
"a flipped guard polarity must be visible"
);
}
}