use std::collections::{BTreeSet, HashSet};
use anyhow::{Context, Result};
use proc_macro2::{Span, TokenStream, TokenTree};
use quote::ToTokens;
use serde::Serialize;
use syn::spanned::Spanned;
use syn::visit::{self, Visit};
use crate::plan::CmpOp;
pub const RUNTIME_MOD: &str = "__tmt_rt";
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum LiteralSide {
None,
Rhs(i128),
Lhs(i128),
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum SiteKind {
Cmp {
op: CmpOp,
lhs: String,
rhs: String,
literal: LiteralSide,
gap: (usize, usize),
},
Logic {
and: bool,
lhs: String,
rhs: String,
gap: (usize, usize),
},
Arith {
op: ArithOp,
assign: bool,
lhs: String,
rhs: String,
gap: (usize, usize),
},
Not {
bang: (usize, usize),
operand: String,
},
Return {
name: String,
option: Option<String>,
sole_expr: Option<(usize, usize)>,
},
MinMax {
max: bool,
receiver: String,
argument: String,
call: (usize, usize),
close: (usize, usize),
},
Range {
inclusive: bool,
lhs: String,
rhs: String,
gap: (usize, usize),
},
Arm {
pattern: String,
guard: ArmGuard,
removal: (usize, usize),
},
Stmt,
Neg {
minus: (usize, usize),
operand: String,
literal: bool,
},
Guard {
can_be_false: bool,
},
Field {
name: String,
shorthand: bool,
from_base: Option<String>,
removal: (usize, usize),
},
Body {
name: String,
value: String,
sole_expr: Option<(usize, usize)>,
},
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ArmGuard {
None(usize),
Existing(usize, usize),
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ArithOp {
Add,
Sub,
Mul,
Div,
Rem,
BitAnd,
BitOr,
BitXor,
Shl,
Shr,
}
impl ArithOp {
pub fn binding(self) -> u8 {
match self {
ArithOp::Mul | ArithOp::Div | ArithOp::Rem => 5,
ArithOp::Add | ArithOp::Sub => 4,
ArithOp::Shl | ArithOp::Shr => 3,
ArithOp::BitAnd => 2,
ArithOp::BitXor => 1,
ArithOp::BitOr => 0,
}
}
pub const ALL: [ArithOp; 10] = [
ArithOp::Add,
ArithOp::Sub,
ArithOp::Mul,
ArithOp::Div,
ArithOp::Rem,
ArithOp::BitAnd,
ArithOp::BitOr,
ArithOp::BitXor,
ArithOp::Shl,
ArithOp::Shr,
];
pub fn symbol(self) -> &'static str {
match self {
ArithOp::Add => "+",
ArithOp::Sub => "-",
ArithOp::Mul => "*",
ArithOp::Div => "/",
ArithOp::Rem => "%",
ArithOp::BitAnd => "&",
ArithOp::BitOr => "|",
ArithOp::BitXor => "^",
ArithOp::Shl => "<<",
ArithOp::Shr => ">>",
}
}
pub fn swapped(self) -> ArithOp {
match self {
ArithOp::Add => ArithOp::Sub,
ArithOp::Sub => ArithOp::Add,
ArithOp::Mul => ArithOp::Div,
ArithOp::Div => ArithOp::Mul,
ArithOp::Rem => ArithOp::Div,
ArithOp::BitAnd => ArithOp::BitOr,
ArithOp::BitOr => ArithOp::BitAnd,
ArithOp::BitXor => ArithOp::BitAnd,
ArithOp::Shl => ArithOp::Shr,
ArithOp::Shr => ArithOp::Shl,
}
}
pub fn swapped2(self) -> Option<ArithOp> {
Some(match self {
ArithOp::Add => ArithOp::Mul,
ArithOp::Sub => ArithOp::Div,
ArithOp::Mul => ArithOp::Add,
ArithOp::Div => ArithOp::Rem,
ArithOp::Rem => ArithOp::Add,
ArithOp::BitAnd | ArithOp::BitOr => ArithOp::BitXor,
ArithOp::BitXor => ArithOp::BitOr,
ArithOp::Shl | ArithOp::Shr => return None,
})
}
pub fn second(self, assign: bool) -> Option<ArithOp> {
if assign && matches!(self, ArithOp::BitAnd | ArithOp::BitOr) {
return None;
}
self.swapped2()
}
pub fn is_bitwise(self) -> bool {
matches!(
self,
ArithOp::BitAnd | ArithOp::BitOr | ArithOp::BitXor | ArithOp::Shl | ArithOp::Shr
)
}
fn stem(self) -> (&'static str, &'static str) {
match self {
ArithOp::Add => ("add", "Add"),
ArithOp::Sub => ("sub", "Sub"),
ArithOp::Mul => ("mul", "Mul"),
ArithOp::Div => ("div", "Div"),
ArithOp::Rem => ("rem", "Rem"),
ArithOp::BitAnd => ("bitand", "BitAnd"),
ArithOp::BitOr => ("bitor", "BitOr"),
ArithOp::BitXor => ("bitxor", "BitXor"),
ArithOp::Shl => ("shl", "Shl"),
ArithOp::Shr => ("shr", "Shr"),
}
}
pub(crate) fn method(self, assign: bool) -> String {
format!(
"tmt_{}{}",
self.stem().0,
if assign { "_assign" } else { "" }
)
}
pub(crate) fn fallback_trait(self, assign: bool) -> String {
format!("Any{}{}", self.stem().1, if assign { "Assign" } else { "" })
}
fn prim_trait(self, assign: bool) -> &'static str {
match (self.is_bitwise(), assign) {
(false, false) => "ArithPrim",
(true, false) => "BitPrim",
(false, true) => "ArithAssignPrim",
(true, true) => "BitAssignPrim",
}
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Site {
pub id: u32,
pub kind: SiteKind,
pub line: usize,
pub column: usize,
pub start: usize,
pub end: usize,
pub text: String,
}
#[derive(Debug, PartialEq, Eq)]
pub struct TestModule {
pub name: String,
pub path: Option<String>,
}
#[derive(Debug, Default)]
pub struct Discovery {
pub sites: Vec<Site>,
pub rebuild_sites: Vec<Site>,
pub single_statement_bodies: Vec<String>,
pub test_modules: Vec<TestModule>,
}
pub fn discover(source: &str, first_id: u32) -> Result<Discovery> {
discover_with_errors(source, first_id, &[])
}
pub(crate) fn discover_with_errors(
source: &str,
first_id: u32,
error_values: &[&str],
) -> Result<Discovery> {
let file = parse_source(source)?;
Ok(discover_parsed(source, &file, first_id, error_values))
}
pub(crate) fn parse_source(source: &str) -> Result<syn::File> {
if source.starts_with('\u{feff}') || (source.starts_with("#!") && !source.starts_with("#![")) {
anyhow::bail!("starts with a byte order mark or a `#!` line");
}
syn::parse_file(source).context("not parseable as a Rust source file")
}
pub(crate) fn discover_parsed(
source: &str,
file: &syn::File,
first_id: u32,
error_values: &[&str],
) -> Discovery {
let local_macros = file
.items
.iter()
.filter_map(|item| match item {
syn::Item::Macro(m) => m.ident.as_ref().map(|i| i.to_string()),
_ => None,
})
.collect();
let mut finder = Finder {
source,
next_id: first_id,
found: Discovery::default(),
local_macros,
const_depth: 0,
error_values,
for_ranges: std::collections::HashSet::new(),
};
finder.visit_file(file);
finder.found
}
struct Finder<'s> {
error_values: &'s [&'s str],
local_macros: Vec<String>,
source: &'s str,
next_id: u32,
found: Discovery,
const_depth: usize,
for_ranges: std::collections::HashSet<usize>,
}
impl Finder<'_> {
fn function_sites(&mut self, sig: &syn::Signature, body: &syn::Block) {
if body.stmts.is_empty() {
return;
}
let braces = body.brace_token.span;
let (Some((_, start)), Some((end, _)), Some((sig_start, sig_end))) = (
self.range(braces.open()),
self.range(braces.close()),
self.range(sig.span()),
) else {
return;
};
if !in_order(start, end) {
return;
}
let at = sig.span().start();
let text = self.source[sig_start..sig_end].to_string();
let (sole_expr, sole_plain) = match &body.stmts[..] {
[syn::Stmt::Expr(expr, None)] => {
let range = self.range(expr.span());
(range, range.filter(|_| does_nothing_else(expr)))
}
_ => (None, None),
};
let push = |finder: &mut Self, kind: SiteKind| {
finder.add(Site {
id: 0,
kind,
line: at.line,
column: at.column + 1,
start,
end,
text: text.clone(),
});
};
let name = sig.ident.to_string();
if let Some(option) = self.result_kind(&sig.output)
&& !may_bypass_result_probe(body)
{
let kind = SiteKind::Return {
name: name.clone(),
option,
sole_expr,
};
push(self, kind);
}
let one_deletable_statement = matches!(sig.output, syn::ReturnType::Default)
&& matches!(&body.stmts[..], [syn::Stmt::Expr(expr, Some(_))] if deletable(expr));
if sig.unsafety.is_some() {
return;
}
if one_deletable_statement {
self.found.single_statement_bodies.push(name);
return;
}
let written = sole_expr.map(|(from, to)| tokens_of(&self.source[from..to]));
let is_written = |value: &str| {
written
.as_deref()
.is_some_and(|text| text == tokens_of(value))
};
let probe_values = body_values_with_errors(&sig.output, self.error_values, false);
let probe_index = (probe_values.len() > 32).then(|| {
probe_values
.iter()
.map(String::as_str)
.collect::<HashSet<_>>()
});
for value in body_values_with_errors(&sig.output, self.error_values, true) {
let is_probe = probe_index.as_ref().map_or_else(
|| probe_values.contains(&value),
|index| index.contains(value.as_str()),
);
if !is_probe && !is_written(&value) {
self.add_rebuild(Site {
id: NO_ID,
kind: SiteKind::Body {
name: name.clone(),
value,
sole_expr: sole_plain,
},
line: at.line,
column: at.column + 1,
start,
end,
text: text.clone(),
});
}
}
for value in probe_values {
if !is_written(&value) {
push(
self,
SiteKind::Body {
name: name.clone(),
value,
sole_expr: sole_plain,
},
);
}
}
}
fn result_kind(&self, output: &syn::ReturnType) -> Option<Option<String>> {
let syn::ReturnType::Type(_, ty) = output else {
return None;
};
match &**ty {
syn::Type::Path(p) if p.path.is_ident("bool") => Some(None),
syn::Type::Path(p)
if p.qself.is_none()
&& p.path.segments.last().is_some_and(|s| {
s.ident == "Option"
&& matches!(s.arguments, syn::PathArguments::AngleBracketed(_))
}) =>
{
match self
.range(ty.span())
.map(|(from, to)| &self.source[from..to])
{
Some(written) if !written.contains("impl ") => Some(Some(written.to_string())),
_ => None,
}
}
_ => None,
}
}
fn range(&self, span: Span) -> Option<(usize, usize)> {
let range = span.byte_range();
let located = !range.is_empty() && self.source.get(range.clone()).is_some();
located.then_some((range.start, range.end))
}
fn push(&mut self, kind: SiteKind, start: usize, end: usize, span: Span) {
let at = span.start();
self.add(Site {
id: 0,
kind,
line: at.line,
column: at.column + 1,
start,
end,
text: self.source[start..end].to_string(),
});
}
fn constant(&mut self, attrs: &[syn::Attribute], value: &syn::Expr) {
if !is_test_only(attrs) && !is_skipped(attrs) {
self.const_depth += 1;
self.visit_expr(value);
self.const_depth -= 1;
}
}
fn typed_constant(
&mut self,
attrs: &[syn::Attribute],
ty: &syn::Type,
value: Option<&syn::Expr>,
) {
if !is_test_only(attrs) && !is_skipped(attrs) {
self.visit_type(ty);
if let Some(value) = value {
self.constant(&[], value);
}
}
}
fn add_rebuild(&mut self, mut site: Site) {
site.id = NO_ID;
self.found.rebuild_sites.push(site);
}
fn add(&mut self, mut site: Site) {
if self.const_depth > 0 {
self.add_rebuild(site);
} else {
site.id = self.next_id;
self.found.sites.push(site);
self.next_id += 1;
}
}
}
fn cmp_op(op: &syn::BinOp) -> Option<CmpOp> {
Some(match op {
syn::BinOp::Lt(_) => CmpOp::Lt,
syn::BinOp::Le(_) => CmpOp::Le,
syn::BinOp::Gt(_) => CmpOp::Gt,
syn::BinOp::Ge(_) => CmpOp::Ge,
syn::BinOp::Eq(_) => CmpOp::Eq,
syn::BinOp::Ne(_) => CmpOp::Ne,
_ => return None,
})
}
fn arith_op(op: &syn::BinOp) -> Option<(ArithOp, bool)> {
use syn::BinOp as B;
Some(match op {
B::Add(_) => (ArithOp::Add, false),
B::Sub(_) => (ArithOp::Sub, false),
B::Mul(_) => (ArithOp::Mul, false),
B::Div(_) => (ArithOp::Div, false),
B::Rem(_) => (ArithOp::Rem, false),
B::BitAnd(_) => (ArithOp::BitAnd, false),
B::BitOr(_) => (ArithOp::BitOr, false),
B::BitXor(_) => (ArithOp::BitXor, false),
B::Shl(_) => (ArithOp::Shl, false),
B::Shr(_) => (ArithOp::Shr, false),
B::AddAssign(_) => (ArithOp::Add, true),
B::SubAssign(_) => (ArithOp::Sub, true),
B::MulAssign(_) => (ArithOp::Mul, true),
B::DivAssign(_) => (ArithOp::Div, true),
B::RemAssign(_) => (ArithOp::Rem, true),
B::BitAndAssign(_) => (ArithOp::BitAnd, true),
B::BitOrAssign(_) => (ArithOp::BitOr, true),
B::BitXorAssign(_) => (ArithOp::BitXor, true),
B::ShlAssign(_) => (ArithOp::Shl, true),
B::ShrAssign(_) => (ArithOp::Shr, true),
_ => return None,
})
}
fn is_plain_place(expr: &syn::Expr) -> bool {
match expr {
syn::Expr::Path(e) => e.attrs.is_empty(),
syn::Expr::Field(e) => is_plain_place(&e.base),
syn::Expr::Unary(syn::ExprUnary {
op: syn::UnOp::Deref(_),
expr,
..
}) => is_plain_place(expr),
syn::Expr::Paren(e) => is_plain_place(&e.expr),
syn::Expr::Group(e) => is_plain_place(&e.expr),
_ => false,
}
}
fn is_literal(expr: &syn::Expr) -> bool {
match expr {
syn::Expr::Paren(e) => is_literal(&e.expr),
syn::Expr::Group(e) => is_literal(&e.expr),
syn::Expr::Lit(_) => true,
syn::Expr::Unary(syn::ExprUnary {
op: syn::UnOp::Neg(_),
expr,
..
}) => is_literal(expr),
_ => false,
}
}
fn in_order(earlier: usize, later: usize) -> bool {
earlier <= later }
fn in_let_chain(expr: &syn::Expr) -> bool {
match expr {
syn::Expr::Let(_) => true,
syn::Expr::Binary(syn::ExprBinary {
op: syn::BinOp::And(_),
left,
right,
..
}) => in_let_chain(left) || matches!(**right, syn::Expr::Let(_)),
_ => false,
}
}
const EXPR_MACROS: [&str; 18] = [
"assert_eq",
"assert_ne",
"debug_assert_eq",
"debug_assert_ne",
"vec",
"format",
"print",
"println",
"eprint",
"eprintln",
"write",
"writeln",
"panic",
"unreachable",
"todo",
"unimplemented",
"format_args",
"matches",
];
fn is_assign_op(op: &syn::BinOp) -> bool {
use syn::BinOp::*;
matches!(
op,
AddAssign(_)
| SubAssign(_)
| MulAssign(_)
| DivAssign(_)
| RemAssign(_)
| BitXorAssign(_)
| BitAndAssign(_)
| BitOrAssign(_)
| ShlAssign(_)
| ShrAssign(_)
)
}
fn int_literal(expr: &syn::Expr) -> Option<i128> {
match expr {
syn::Expr::Paren(e) => int_literal(&e.expr),
syn::Expr::Group(e) => int_literal(&e.expr),
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Int(lit),
..
}) => lit.base10_parse().ok(),
syn::Expr::Unary(syn::ExprUnary {
op: syn::UnOp::Neg(_),
expr,
..
}) => int_literal(expr).and_then(i128::checked_neg),
_ => None,
}
}
fn deletable(expr: &syn::Expr) -> bool {
match expr {
syn::Expr::Call(e) => e.attrs.is_empty(),
syn::Expr::MethodCall(e) => e.attrs.is_empty(),
syn::Expr::Assign(e) => e.attrs.is_empty(),
syn::Expr::Binary(e) => is_assign_op(&e.op),
syn::Expr::Try(e) => e.attrs.is_empty() && deletable_call(&e.expr),
syn::Expr::Await(e) => e.attrs.is_empty() && deletable_call(&e.base),
_ => false,
}
}
fn deletable_call(expr: &syn::Expr) -> bool {
match expr {
syn::Expr::Call(_) | syn::Expr::MethodCall(_) => true,
syn::Expr::Await(e) => deletable_call(&e.base),
_ => false,
}
}
fn has_ident(tokens: TokenStream, name: &str) -> bool {
tokens.into_iter().any(|tree| match tree {
TokenTree::Ident(ident) => ident == name,
TokenTree::Group(group) => has_ident(group.stream(), name),
_ => false,
})
}
pub const NO_ID: u32 = u32::MAX;
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct NamedItem {
pub start: usize,
pub end: usize,
pub name: String,
}
pub fn named_items(source: &str) -> Vec<NamedItem> {
struct Namer {
path: Vec<String>,
items: Vec<NamedItem>,
}
impl Namer {
fn inside(&mut self, name: String, span: Option<Span>, visit: impl FnOnce(&mut Self)) {
self.path.push(name);
if let Some(span) = span {
let range = span.byte_range();
self.items.push(NamedItem {
start: range.start,
end: range.end,
name: self.path.join("::"),
});
}
visit(self);
self.path.pop();
}
}
impl<'ast> Visit<'ast> for Namer {
fn visit_item_mod(&mut self, node: &'ast syn::ItemMod) {
self.inside(node.ident.to_string(), None, |namer| {
visit::visit_item_mod(namer, node)
});
}
fn visit_item_trait(&mut self, node: &'ast syn::ItemTrait) {
self.inside(node.ident.to_string(), None, |namer| {
visit::visit_item_trait(namer, node)
});
}
fn visit_item_impl(&mut self, node: &'ast syn::ItemImpl) {
let of = squeezed(&node.self_ty.to_token_stream().to_string());
let name = match &node.trait_ {
Some((_, path, _)) => {
format!(
"<{} for {of}>",
squeezed(&path.to_token_stream().to_string())
)
}
None => of,
};
self.inside(name, None, |namer| visit::visit_item_impl(namer, node));
}
fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
self.inside(node.sig.ident.to_string(), Some(node.span()), |namer| {
visit::visit_item_fn(namer, node)
});
}
fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
self.inside(node.sig.ident.to_string(), Some(node.span()), |namer| {
visit::visit_impl_item_fn(namer, node)
});
}
fn visit_trait_item_fn(&mut self, node: &'ast syn::TraitItemFn) {
self.inside(node.sig.ident.to_string(), Some(node.span()), |namer| {
visit::visit_trait_item_fn(namer, node)
});
}
fn visit_item_const(&mut self, node: &'ast syn::ItemConst) {
self.inside(node.ident.to_string(), Some(node.span()), |_| {});
}
fn visit_item_static(&mut self, node: &'ast syn::ItemStatic) {
self.inside(node.ident.to_string(), Some(node.span()), |_| {});
}
fn visit_impl_item_const(&mut self, node: &'ast syn::ImplItemConst) {
self.inside(node.ident.to_string(), Some(node.span()), |_| {});
}
}
let Ok(file) = syn::parse_file(source) else {
return vec![];
};
let mut namer = Namer {
path: vec![],
items: vec![],
};
namer.visit_file(&file);
namer.items
}
pub fn enclosing_item(items: &[NamedItem], offset: usize) -> &str {
items
.iter()
.filter(|item| item.start <= offset && offset < item.end)
.min_by_key(|item| item.end - item.start)
.map_or("", |item| item.name.as_str())
}
pub fn offset_of(source: &str, line: usize, column: usize) -> Option<usize> {
let start: usize = source
.split_inclusive('\n')
.take(line.checked_sub(1)?)
.map(str::len)
.sum();
let rest = source.get(start..)?;
let within = rest
.char_indices()
.nth(column.checked_sub(1)?)
.map_or(rest.len(), |(at, _)| at);
Some(start + within)
}
pub(crate) struct ItemIndex<'a>(Vec<(usize, &'a str)>);
impl<'a> ItemIndex<'a> {
pub(crate) fn new(items: &'a [NamedItem]) -> Self {
use std::{cmp::Reverse, collections::BinaryHeap};
let mut starts: Vec<_> = items.iter().enumerate().collect();
starts.sort_unstable_by_key(|&(_, item)| item.start);
let mut boundaries: Vec<_> = items
.iter()
.flat_map(|item| [item.start, item.end])
.collect();
boundaries.sort_unstable();
let mut starts = starts.into_iter().peekable();
let mut active = BinaryHeap::new();
let mut intervals = Vec::new();
for boundary in boundaries {
while let Some(&(index, item)) =
starts.peek().filter(|(_, item)| item.start <= boundary)
{
starts.next();
active.push(Reverse((item.end - item.start, index)));
}
while active
.peek()
.is_some_and(|&Reverse((_, index))| items[index].end <= boundary)
{
active.pop();
}
let name = active
.peek()
.map_or("", |&Reverse((_, index))| items[index].name.as_str());
if intervals
.last()
.is_none_or(|&(_, previous)| previous != name)
{
intervals.push((boundary, name));
}
}
Self(intervals)
}
pub(crate) fn at(&self, offset: usize) -> &'a str {
let end = self.0.partition_point(|&(start, _)| start <= offset);
self.0[..end].last().map_or("", |&(_, name)| name)
}
}
#[cfg(test)]
#[test]
fn indexed_item_boundaries_agree_with_the_previous_search() {
let items = [
(6, 10, "first tie"),
(0, 16, "outer"),
(2, 6, "before tie"),
(6, 10, "second tie"),
(4, 13, "overlap"),
(7, 9, "inner"),
(7, 7, "empty"),
(17, 18, "after outer"),
]
.map(|(start, end, name)| NamedItem {
start,
end,
name: name.to_string(),
});
let indexed = ItemIndex::new(&items);
for offset in 0..=20 {
assert_eq!(
indexed.at(offset),
enclosing_item(&items, offset),
"{offset}"
);
assert_eq!(ItemIndex::new(&[]).at(offset), "");
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct SourceMutant {
pub start: usize,
pub end: usize,
pub replacement: String,
pub what: String,
pub into: String,
}
pub(crate) fn source_boundary_mutant(site: &Site) -> Option<SourceMutant> {
let SiteKind::Cmp { op, gap, .. } = &site.kind else {
return None;
};
let replacement = match op {
CmpOp::Le => "<",
CmpOp::Ge => ">",
_ => return None,
};
Some(SourceMutant {
start: gap.0,
end: gap.1,
replacement: format!(" {replacement} "),
what: op.symbol().to_string(),
into: replacement.to_string(),
})
}
pub fn source_mutants(site: &Site) -> Vec<SourceMutant> {
let change =
|start: usize, end: usize, replacement: String, what: &str, into: &str| SourceMutant {
start,
end,
replacement,
what: what.to_string(),
into: into.to_string(),
};
let operator = |gap: &(usize, usize), from: String, to: String, binds: std::cmp::Ordering| {
let operands = gap
.0
.checked_sub(site.start)
.zip(gap.1.checked_sub(site.start))
.and_then(|(left, right)| {
Some((
site.text.get(..left)?.trim_end(),
site.text.get(right..)?.trim_start(),
))
});
match (binds, operands) {
(std::cmp::Ordering::Less, Some((left, right))) => change(
site.start,
site.end,
format!("({left} {to} {right})"),
&from,
&to,
),
(std::cmp::Ordering::Greater, Some((left, right))) => change(
site.start,
site.end,
format!("({left}) {to} ({right})"),
&from,
&to,
),
_ => change(gap.0, gap.1, format!(" {to} "), &from, &to),
}
};
let same = std::cmp::Ordering::Equal;
match &site.kind {
SiteKind::Cmp { op, gap, .. } => {
let others: &[CmpOp] = match op {
CmpOp::Lt => &[CmpOp::Eq, CmpOp::Gt, CmpOp::Le],
CmpOp::Gt => &[CmpOp::Eq, CmpOp::Lt, CmpOp::Ge],
CmpOp::Le => &[CmpOp::Gt],
CmpOp::Ge => &[CmpOp::Lt],
CmpOp::Eq => &[CmpOp::Ne],
CmpOp::Ne => &[CmpOp::Eq],
};
others
.iter()
.map(|other| operator(gap, op.symbol().into(), other.symbol().into(), same))
.collect()
}
SiteKind::Logic { and, gap, .. } => {
let (from, to, binds) = if *and {
("&&", "||", std::cmp::Ordering::Less)
} else {
("||", "&&", std::cmp::Ordering::Greater)
};
vec![operator(gap, from.into(), to.into(), binds)]
}
SiteKind::Arith {
op, assign, gap, ..
} => {
let eq = if *assign { "=" } else { "" };
[Some(op.swapped()), op.second(*assign)]
.into_iter()
.flatten()
.map(|other| {
operator(
gap,
format!("{}{eq}", op.symbol()),
format!("{}{eq}", other.symbol()),
if *assign {
same
} else {
other.binding().cmp(&op.binding())
},
)
})
.collect()
}
SiteKind::Not { bang, .. } => vec![change(bang.0, bang.1, String::new(), "!", "")],
SiteKind::Neg { minus, .. } => vec![change(minus.0, minus.1, String::new(), "-", "")],
SiteKind::Body { value, .. } => {
vec![change(
site.start,
site.end,
format!(" {value} "),
"body",
value,
)]
}
SiteKind::Arm {
pattern,
guard,
removal,
} => vec![match guard {
ArmGuard::None(_) => change(removal.0, removal.1, String::new(), "arm", pattern),
ArmGuard::Existing(from, to) => change(*from, *to, "false".into(), "arm", pattern),
}],
SiteKind::Guard { can_be_false } => [true, false]
.into_iter()
.filter(|value| *value || *can_be_false)
.map(|value| {
change(
site.start,
site.end,
value.to_string(),
"guard",
&value.to_string(),
)
})
.collect(),
SiteKind::Field { name, removal, .. } => {
vec![change(removal.0, removal.1, String::new(), "field", name)]
}
SiteKind::Stmt => vec![change(site.start, site.end, String::new(), "statement", "")],
SiteKind::Range { inclusive, gap, .. } => {
let (from, to) = if *inclusive {
("..=", "..")
} else {
("..", "..=")
};
vec![change(gap.0, gap.1, to.to_string(), from, to)]
}
SiteKind::Return { .. } | SiteKind::MinMax { .. } => vec![],
}
}
pub(crate) fn literal_operator_mutants(source: &str, site: &Site, mutants: &mut [SourceMutant]) {
let gap = match &site.kind {
SiteKind::Cmp { gap, .. } | SiteKind::Logic { gap, .. } | SiteKind::Arith { gap, .. } => {
gap
}
_ => return,
};
if let Ok(operator) = syn::parse_str::<syn::BinOp>(&source[gap.0..gap.1]) {
let span = operator.span().byte_range();
for mutant in mutants {
mutant.start = gap.0 + span.start;
mutant.end = gap.0 + span.end;
mutant.replacement.clone_from(&mutant.into);
}
}
}
pub fn iterator_values(output: &syn::ReturnType) -> Vec<String> {
let syn::ReturnType::Type(_, ty) = output else {
return vec![];
};
let syn::Type::ImplTrait(opaque) = &**ty else {
return vec![];
};
iterator_type_values(opaque, &[], false)
}
fn iterator_type_values(
opaque: &syn::TypeImplTrait,
error_values: &[&str],
extended: bool,
) -> Vec<String> {
let item = opaque.bounds.iter().find_map(|bound| {
let syn::TypeParamBound::Trait(bound) = bound else {
return None;
};
let last = bound.path.segments.last()?;
let syn::PathArguments::AngleBracketed(list) = &last.arguments else {
return None;
};
(last.ident == "Iterator").then_some(())?;
list.args.iter().find_map(|arg| match arg {
syn::GenericArgument::AssocType(item) if item.ident == "Item" => Some(&item.ty),
_ => None,
})
});
let Some(item) = item else {
return vec![];
};
if !extended && has_ident(item.to_token_stream(), "impl") {
return vec!["::core::iter::empty()".to_string()];
}
let mut values = vec!["::core::iter::empty()".to_string()];
values.extend(
values_of(item, error_values, extended)
.iter()
.map(|value| format!("::core::iter::once({value})")),
);
values
}
fn squeezed(text: &str) -> String {
text.chars().filter(|c| !c.is_whitespace()).collect()
}
fn tokens_of(text: &str) -> String {
match text.parse::<TokenStream>() {
Ok(tokens) => tokens.to_string(),
Err(_) => text.to_string(),
}
}
fn may_bypass_result_probe(body: &syn::Block) -> bool {
struct EarlyExit(bool);
impl<'ast> Visit<'ast> for EarlyExit {
fn visit_expr(&mut self, expr: &'ast syn::Expr) {
if self.0 {
return;
}
match expr {
syn::Expr::Return(_) | syn::Expr::Try(_) | syn::Expr::Verbatim(_) => self.0 = true,
syn::Expr::Async(_) | syn::Expr::Closure(_) | syn::Expr::Const(_) => {}
_ => visit::visit_expr(self, expr),
}
}
fn visit_macro(&mut self, _: &'ast syn::Macro) {
self.0 = true;
}
fn visit_item(&mut self, _: &'ast syn::Item) {}
fn visit_pat(&mut self, _: &'ast syn::Pat) {}
fn visit_type(&mut self, _: &'ast syn::Type) {}
}
let mut exits = EarlyExit(false);
exits.visit_block(body);
exits.0
}
fn does_nothing_else(expr: &syn::Expr) -> bool {
struct Effects(bool);
impl<'ast> Visit<'ast> for Effects {
fn visit_expr(&mut self, expr: &'ast syn::Expr) {
match expr {
syn::Expr::Binary(_)
| syn::Expr::Unary(_)
| syn::Expr::Paren(_)
| syn::Expr::Group(_)
| syn::Expr::Path(_)
| syn::Expr::Lit(_)
| syn::Expr::Field(_)
| syn::Expr::Reference(_)
| syn::Expr::Cast(_)
| syn::Expr::Tuple(_) => syn::visit::visit_expr(self, expr),
_ => self.0 = true,
}
}
fn visit_bin_op(&mut self, op: &'ast syn::BinOp) {
use syn::BinOp::*;
if !matches!(
op,
Add(_)
| Sub(_)
| Mul(_)
| Div(_)
| Rem(_)
| And(_)
| Or(_)
| BitXor(_)
| BitAnd(_)
| BitOr(_)
| Shl(_)
| Shr(_)
| Eq(_)
| Lt(_)
| Le(_)
| Ne(_)
| Ge(_)
| Gt(_)
) {
self.0 = true; }
}
}
let mut effects = Effects(false);
effects.visit_expr(expr);
!effects.0
}
pub fn body_values(output: &syn::ReturnType) -> Vec<String> {
body_values_with_errors(output, &[], false)
}
fn body_values_with_errors(
output: &syn::ReturnType,
error_values: &[&str],
extended: bool,
) -> Vec<String> {
match output {
syn::ReturnType::Default => vec!["()".to_string()],
syn::ReturnType::Type(_, ty) => {
if !extended && has_ident(ty.to_token_stream(), "impl") {
return vec![];
}
values_of(ty, error_values, extended)
}
}
}
fn product(parts: &[Vec<String>], format: impl Fn(&[&str]) -> String) -> Vec<String> {
if parts.iter().any(Vec::is_empty) {
return vec![];
}
let mut positions = vec![0; parts.len()];
let mut row: Vec<_> = parts.iter().map(|part| part[0].as_str()).collect();
let mut results = vec![];
loop {
results.push(format(&row));
let Some(next) = (0..parts.len())
.rev()
.find(|&i| positions[i] + 1 < parts[i].len())
else {
return results;
};
positions[next] += 1;
row[next] = &parts[next][positions[next]];
for i in next + 1..parts.len() {
positions[i] = 0;
row[i] = &parts[i][0];
}
}
}
fn values_of(ty: &syn::Type, error_values: &[&str], extended: bool) -> Vec<String> {
let each = |inner: &syn::Type, wrap: &dyn Fn(&str) -> String| -> Vec<String> {
values_of(inner, error_values, extended)
.iter()
.map(|v| wrap(v))
.collect()
};
match ty {
syn::Type::Paren(t) => values_of(&t.elem, error_values, extended),
syn::Type::Group(t) => values_of(&t.elem, error_values, extended),
syn::Type::Never(_) => vec![],
syn::Type::ImplTrait(opaque) => iterator_type_values(opaque, error_values, extended),
syn::Type::Tuple(t) => {
let parts: Vec<Vec<String>> = t
.elems
.iter()
.map(|ty| values_of(ty, error_values, extended))
.collect();
product(&parts, |row| match row {
[one] => format!("({one},)"),
_ => format!("({})", row.join(", ")),
})
}
syn::Type::Array(t) => {
let len = t.len.to_token_stream().to_string();
each(&t.elem, &|v| format!("[{v}; {len}]"))
}
syn::Type::Reference(t) => match &*t.elem {
syn::Type::Path(p) if p.path.is_ident("str") && t.mutability.is_none() => {
vec!["\"\"".to_string(), "\"xyzzy\"".to_string()]
}
syn::Type::Slice(slice) => {
let mut values = vec!["Vec::leak(Vec::new())".to_string()];
values.extend(each(&slice.elem, &|v| format!("Vec::leak(vec![{v}])")));
values
}
inner => each(inner, &|v| format!("Box::leak(Box::new({v}))")),
},
syn::Type::Path(p) if p.qself.is_none() => {
let Some(last) = p.path.segments.last() else {
return vec!["Default::default()".to_string()];
};
let mut bare = p.path.clone();
if let Some(segment) = bare.segments.last_mut() {
segment.arguments = syn::PathArguments::None;
}
let bare = squeezed(&bare.to_token_stream().to_string());
let arguments: Vec<&syn::Type> = match &last.arguments {
syn::PathArguments::AngleBracketed(list) => list
.args
.iter()
.filter_map(|arg| match arg {
syn::GenericArgument::Type(ty) => Some(ty),
_ => None,
})
.collect(),
_ => vec![],
};
let name = last.ident.to_string();
let texts = |list: &[&str]| list.iter().map(|v| v.to_string()).collect::<Vec<_>>();
let one = |text: String| "1.try_into().unwrap()".replace('1', &text);
match (name.as_str(), &arguments[..]) {
("bool", []) => texts(&["true", "false"]),
("i8" | "i16" | "i32" | "i64" | "i128" | "isize", []) => texts(&["0", "1", "-1"]),
("u8" | "u16" | "u32" | "u64" | "u128" | "usize", []) => texts(&["0", "1"]),
("f32" | "f64", []) => texts(&["0.0", "1.0", "-1.0"]),
(
"NonZeroI8" | "NonZeroI16" | "NonZeroI32" | "NonZeroI64" | "NonZeroI128"
| "NonZeroIsize",
[],
) => vec![one("1".into()), one("(-1)".into())],
(
"NonZeroU8" | "NonZeroU16" | "NonZeroU32" | "NonZeroU64" | "NonZeroU128"
| "NonZeroUsize",
[],
) => vec![one("1".into())],
("NonZero", [inner]) => {
let unsigned = squeezed(&inner.to_token_stream().to_string()).starts_with('u');
let mut values = vec![one("1".into())];
if !unsigned {
values.push(one("(-1)".into()));
}
values
}
("String", []) => texts(&["String::new()", "\"xyzzy\".into()"]),
("Result", arguments) => {
let mut values = match arguments.first() {
Some(ok) => each(ok, &|v| format!("Ok({v})")),
None => vec!["Ok(Default::default())".to_string()],
};
values.extend(error_values.iter().map(|expression| {
let end = if expression.rsplit('\n').next().unwrap_or("").contains("//") {
"\n"
} else {
""
};
format!("Err({expression}{end})")
}));
values
}
("Option", [inner]) => {
let mut values = vec!["None".to_string()];
values.extend(each(inner, &|v| format!("Some({v})")));
values
}
("Vec", [inner]) => {
let mut values = vec!["vec![]".to_string()];
values.extend(each(inner, &|v| format!("vec![{v}]")));
values
}
("Box" | "Rc" | "Arc" | "Cell" | "RefCell" | "Mutex", [inner]) => {
each(inner, &|v| format!("{bare}::new({v})"))
}
("BinaryHeap" | "BTreeSet" | "HashSet" | "LinkedList" | "VecDeque", [inner]) => {
let mut values = vec![format!("{bare}::new()")];
values.extend(each(inner, &|v| format!("{bare}::from_iter([{v}])")));
values
}
("BTreeMap" | "HashMap", [key, value]) => {
let mut values = vec![format!("{bare}::new()")];
values.extend(product(
&[
values_of(key, error_values, extended),
values_of(value, error_values, extended),
],
|row| format!("{bare}::from_iter([({})])", row.join(", ")),
));
values
}
("Cow", [inner]) => {
let borrowed: syn::Type = syn::parse_quote!(&#inner);
values_of(&borrowed, error_values, extended)
.iter()
.flat_map(|v| {
[
format!("{bare}::Borrowed({v})"),
format!("{bare}::Owned({v}.to_owned())"),
]
})
.collect()
}
("HttpResponse", []) => vec![format!("{bare}::Ok().finish()")],
(_, [inner]) if extended => {
let mut values = vec![format!("{bare}::new()")];
for value in values_of(inner, error_values, extended) {
values.extend([
format!("{bare}::from_iter([{value}])"),
format!("{bare}::new({value})"),
format!("{bare}::from({value})"),
]);
}
values
}
_ => vec!["Default::default()".to_string()],
}
}
_ => vec!["Default::default()".to_string()],
}
}
pub(crate) fn is_skipped(attrs: &[syn::Attribute]) -> bool {
fn marked(meta: &syn::Meta) -> bool {
let path = meta.path();
if path.segments.len() == 2
&& path.segments[0].ident == "mutants"
&& path.segments[1].ident == "skip"
{
return true;
}
if path.is_ident("cfg_attr")
&& let syn::Meta::List(list) = meta
&& let Ok(parts) = list.parse_args_with(
syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated,
)
{
return parts.iter().skip(1).any(marked);
}
false
}
attrs.iter().any(|attr| marked(&attr.meta))
}
pub(crate) fn cfg_possible_without_test(meta: &syn::Meta, desired: bool) -> bool {
if meta.path().is_ident("test") {
return !desired;
}
let syn::Meta::List(list) = meta else {
return true;
};
let Ok(parts) = list.parse_args_with(
syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated,
) else {
return true;
};
if list.path.is_ident("not") && parts.len() == 1 {
return cfg_possible_without_test(&parts[0], !desired);
}
if list.path.is_ident("all") || list.path.is_ident("any") {
return if list.path.is_ident("all") == desired {
parts
.iter()
.all(|part| cfg_possible_without_test(part, desired))
} else {
parts
.iter()
.any(|part| cfg_possible_without_test(part, desired))
};
}
true
}
fn cfg_value(meta: &syn::Meta, features: &BTreeSet<String>) -> Option<bool> {
match meta {
syn::Meta::NameValue(pair) if pair.path.is_ident("feature") => match &pair.value {
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(name),
..
}) => Some(features.contains(&name.value())),
_ => None,
},
syn::Meta::List(list) => {
let parts = list
.parse_args_with(
syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated,
)
.ok()?;
let mut values = parts.iter().map(|part| cfg_value(part, features));
if list.path.is_ident("not") && parts.len() == 1 {
values.next()?.map(|value| !value)
} else if list.path.is_ident("all") {
values
.try_fold(Some(true), |all, value| match (all, value) {
(_, Some(false)) => Err(()),
(Some(true), Some(true)) => Ok(Some(true)),
_ => Ok(None),
})
.unwrap_or(Some(false))
} else if list.path.is_ident("any") {
values
.try_fold(Some(false), |any, value| match (any, value) {
(_, Some(true)) => Err(()),
(Some(false), Some(false)) => Ok(Some(false)),
_ => Ok(None),
})
.unwrap_or(Some(true))
} else {
None
}
}
_ => None,
}
}
fn cfg_is_off(attrs: &[syn::Attribute], features: &BTreeSet<String>) -> bool {
attrs.iter().any(|attr| {
attr.path().is_ident("cfg")
&& attr
.parse_args::<syn::Meta>()
.is_ok_and(|meta| cfg_value(&meta, features) == Some(false))
})
}
pub(crate) fn inactive_ranges(
source: &str,
file: &syn::File,
features: &BTreeSet<String>,
) -> Vec<(usize, usize)> {
struct Inactive<'a> {
source: &'a str,
features: &'a BTreeSet<String>,
found: Vec<(usize, usize)>,
}
impl Inactive<'_> {
fn off(&mut self, attrs: &[syn::Attribute], span: Span) -> bool {
if !cfg_is_off(attrs, self.features) {
return false;
}
let range = span.byte_range();
if self.source.get(range.clone()).is_some() {
self.found.push((range.start, range.end));
}
true
}
}
macro_rules! nodes {
($($visit:ident, $default:path, $node:ty;)*) => {
impl<'ast> Visit<'ast> for Inactive<'_> {
$(fn $visit(&mut self, node: &'ast $node) {
if !self.off(&node.attrs, node.span()) {
$default(self, node);
}
})*
fn visit_item(&mut self, node: &'ast syn::Item) {
if !self.off(item_attrs(node), node.span()) {
visit::visit_item(self, node);
}
}
fn visit_impl_item(&mut self, node: &'ast syn::ImplItem) {
let attrs = match node {
syn::ImplItem::Const(item) => &item.attrs[..],
syn::ImplItem::Fn(item) => &item.attrs,
syn::ImplItem::Type(item) => &item.attrs,
syn::ImplItem::Macro(item) => &item.attrs,
_ => &[],
};
if !self.off(attrs, node.span()) {
visit::visit_impl_item(self, node);
}
}
fn visit_trait_item(&mut self, node: &'ast syn::TraitItem) {
let attrs = match node {
syn::TraitItem::Const(item) => &item.attrs[..],
syn::TraitItem::Fn(item) => &item.attrs,
syn::TraitItem::Type(item) => &item.attrs,
syn::TraitItem::Macro(item) => &item.attrs,
_ => &[],
};
if !self.off(attrs, node.span()) {
visit::visit_trait_item(self, node);
}
}
}
};
}
nodes! {
visit_local, visit::visit_local, syn::Local;
visit_arm, visit::visit_arm, syn::Arm;
visit_field_value, visit::visit_field_value, syn::FieldValue;
visit_stmt_macro, visit::visit_stmt_macro, syn::StmtMacro;
visit_expr_block, visit::visit_expr_block, syn::ExprBlock;
visit_expr_if, visit::visit_expr_if, syn::ExprIf;
visit_expr_call, visit::visit_expr_call, syn::ExprCall;
visit_expr_method_call, visit::visit_expr_method_call, syn::ExprMethodCall;
visit_expr_macro, visit::visit_expr_macro, syn::ExprMacro;
visit_expr_match, visit::visit_expr_match, syn::ExprMatch;
visit_expr_assign, visit::visit_expr_assign, syn::ExprAssign;
visit_expr_return, visit::visit_expr_return, syn::ExprReturn;
visit_expr_for_loop, visit::visit_expr_for_loop, syn::ExprForLoop;
visit_expr_while, visit::visit_expr_while, syn::ExprWhile;
visit_expr_loop, visit::visit_expr_loop, syn::ExprLoop;
visit_expr_unsafe, visit::visit_expr_unsafe, syn::ExprUnsafe;
visit_expr_binary, visit::visit_expr_binary, syn::ExprBinary;
}
if cfg_is_off(&file.attrs, features) {
return vec![(0, source.len())];
}
let mut inactive = Inactive {
source,
features,
found: vec![],
};
inactive.visit_file(file);
inactive.found
}
pub(crate) fn reach(expr: &str) -> Option<crate::plan::Reach> {
use crate::plan::Reach;
fn literal(expr: &syn::Expr) -> Option<i128> {
match expr {
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Int(integer),
..
}) => integer.base10_parse().ok(),
syn::Expr::Paren(inner) => literal(&inner.expr),
_ => None,
}
}
let mut expr = &syn::parse_str::<syn::Expr>(expr).ok()?;
while let syn::Expr::Paren(inner) = expr {
expr = &inner.expr;
}
let syn::Expr::Binary(binary) = expr else {
return None;
};
let (left, right) = (literal(&binary.left), literal(&binary.right));
let power_of_two = |k: i128| k >= 2 && k & (k - 1) == 0;
match binary.op {
syn::BinOp::Mul(_) => left
.or(right)
.filter(|k| power_of_two(*k))
.map(Reach::Multiples),
syn::BinOp::Shl(_) => right
.filter(|bits| (1..=100).contains(bits))
.map(|bits| Reach::Multiples(1 << bits)),
syn::BinOp::BitAnd(_) => left.or(right).filter(|mask| *mask >= 0).map(Reach::Bits),
syn::BinOp::Rem(_) => right.filter(|limit| *limit >= 1).map(Reach::Below),
_ => None,
}
}
pub(crate) fn test_only_ranges(source: &str, file: &syn::File) -> Vec<(usize, usize)> {
if is_test_only(&file.attrs) {
return vec![(0, source.len())];
}
let mut found = vec![];
for item in &file.items {
test_only_items(source, item, &mut found);
}
found
}
fn test_only_items(source: &str, item: &syn::Item, found: &mut Vec<(usize, usize)>) {
let mut note = |attrs: &[syn::Attribute], span: Span| {
let test_only = is_test_only(attrs);
let range = span.byte_range();
if test_only && source.get(range.clone()).is_some() {
found.push((range.start, range.end));
}
test_only
};
if note(item_attrs(item), item.span()) {
return;
}
match item {
syn::Item::Mod(module) => {
for inner in module.content.iter().flat_map(|(_, items)| items) {
test_only_items(source, inner, found);
}
}
syn::Item::Impl(block) => {
for inner in &block.items {
if let syn::ImplItem::Fn(function) = inner {
note(&function.attrs, inner.span());
}
}
}
_ => {}
}
}
pub(crate) fn same_tokens(a: &str, b: &str) -> Option<bool> {
fn tokens(stream: TokenStream, out: &mut Vec<String>) {
let mut trees = stream.into_iter().peekable();
while let Some(tree) = trees.next() {
match tree {
TokenTree::Punct(hash) if hash.as_char() == '#' => {
let bang =
matches!(trees.peek(), Some(TokenTree::Punct(p)) if p.as_char() == '!')
.then(|| trees.next());
let is_doc = matches!(trees.peek(), Some(TokenTree::Group(group))
if group.delimiter() == proc_macro2::Delimiter::Bracket
&& matches!(group.stream().into_iter().next(),
Some(TokenTree::Ident(name)) if name == "doc"));
if is_doc {
trees.next();
continue;
}
out.push("#".to_string());
if bang.is_some() {
out.push("!".to_string());
}
}
TokenTree::Group(group) => {
out.push(format!("{:?}(", group.delimiter()));
tokens(group.stream(), out);
out.push(")".to_string());
}
other => out.push(other.to_string()),
}
}
}
let lex = |text: &str| -> Option<Vec<String>> {
let mut out = vec![];
tokens(text.parse::<TokenStream>().ok()?, &mut out);
Some(out)
};
Some(lex(a)? == lex(b)?)
}
fn item_attrs(item: &syn::Item) -> &[syn::Attribute] {
match item {
syn::Item::Const(item) => &item.attrs,
syn::Item::Enum(item) => &item.attrs,
syn::Item::ExternCrate(item) => &item.attrs,
syn::Item::Fn(item) => &item.attrs,
syn::Item::ForeignMod(item) => &item.attrs,
syn::Item::Impl(item) => &item.attrs,
syn::Item::Macro(item) => &item.attrs,
syn::Item::Mod(item) => &item.attrs,
syn::Item::Static(item) => &item.attrs,
syn::Item::Struct(item) => &item.attrs,
syn::Item::Trait(item) => &item.attrs,
syn::Item::TraitAlias(item) => &item.attrs,
syn::Item::Type(item) => &item.attrs,
syn::Item::Union(item) => &item.attrs,
syn::Item::Use(item) => &item.attrs,
_ => &[],
}
}
pub(crate) fn is_test_only(attrs: &[syn::Attribute]) -> bool {
attrs.iter().any(|attr| {
let path = attr.path();
if path.segments.last().is_some_and(|s| s.ident == "test") {
return true;
}
path.is_ident("cfg")
&& attr
.parse_args::<syn::Meta>()
.is_ok_and(|meta| !cfg_possible_without_test(&meta, true))
})
}
impl<'ast> Visit<'ast> for Finder<'_> {
fn visit_attribute(&mut self, _: &'ast syn::Attribute) {}
fn visit_local(&mut self, node: &'ast syn::Local) {
if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
visit::visit_local(self, node);
}
}
fn visit_pat(&mut self, node: &'ast syn::Pat) {
if let syn::Pat::Type(binding) = node {
self.visit_type(&binding.ty);
}
}
fn visit_type_macro(&mut self, _: &'ast syn::TypeMacro) {}
fn visit_type_array(&mut self, node: &'ast syn::TypeArray) {
self.visit_type(&node.elem);
self.constant(&[], &node.len);
}
fn visit_const_param(&mut self, node: &'ast syn::ConstParam) {
self.visit_type(&node.ty);
if let Some(default) = &node.default {
self.constant(&node.attrs, default);
}
}
fn visit_generic_argument(&mut self, node: &'ast syn::GenericArgument) {
match node {
syn::GenericArgument::Const(value) => self.constant(&[], value),
_ => visit::visit_generic_argument(self, node),
}
}
fn visit_variant(&mut self, node: &'ast syn::Variant) {
if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
self.visit_fields(&node.fields);
if let Some((_, value)) = &node.discriminant {
self.constant(&[], value);
}
}
}
fn visit_file(&mut self, node: &'ast syn::File) {
if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
visit::visit_file(self, node);
}
}
fn visit_item_enum(&mut self, node: &'ast syn::ItemEnum) {
if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
visit::visit_item_enum(self, node);
}
}
fn visit_item_struct(&mut self, node: &'ast syn::ItemStruct) {
if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
visit::visit_item_struct(self, node);
}
}
fn visit_item_union(&mut self, node: &'ast syn::ItemUnion) {
if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
visit::visit_item_union(self, node);
}
}
fn visit_item_trait(&mut self, node: &'ast syn::ItemTrait) {
if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
visit::visit_item_trait(self, node);
}
}
fn visit_item_type(&mut self, node: &'ast syn::ItemType) {
if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
visit::visit_item_type(self, node);
}
}
fn visit_field(&mut self, node: &'ast syn::Field) {
if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
visit::visit_field(self, node);
}
}
fn visit_impl_item_type(&mut self, node: &'ast syn::ImplItemType) {
if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
visit::visit_impl_item_type(self, node);
}
}
fn visit_trait_item_type(&mut self, node: &'ast syn::TraitItemType) {
if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
visit::visit_trait_item_type(self, node);
}
}
fn visit_item_const(&mut self, node: &'ast syn::ItemConst) {
self.typed_constant(&node.attrs, &node.ty, Some(&node.expr));
}
fn visit_item_static(&mut self, node: &'ast syn::ItemStatic) {
self.typed_constant(&node.attrs, &node.ty, Some(&node.expr));
}
fn visit_impl_item_const(&mut self, node: &'ast syn::ImplItemConst) {
self.typed_constant(&node.attrs, &node.ty, Some(&node.expr));
}
fn visit_trait_item_const(&mut self, node: &'ast syn::TraitItemConst) {
self.typed_constant(
&node.attrs,
&node.ty,
node.default.as_ref().map(|(_, value)| value),
);
}
fn visit_expr_const(&mut self, node: &'ast syn::ExprConst) {
if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
self.const_depth += 1;
self.visit_block(&node.block);
self.const_depth -= 1;
}
}
fn visit_macro(&mut self, node: &'ast syn::Macro) {
let Some(name) = node.path.segments.last().map(|s| s.ident.to_string()) else {
return;
};
if !EXPR_MACROS.contains(&name.as_str()) || self.local_macros.contains(&name) {
return;
}
if name == "matches" {
let scrutinee = node.parse_body_with(|input: syn::parse::ParseStream| {
let expr: syn::Expr = input.parse()?;
input.parse::<proc_macro2::TokenStream>()?;
Ok(expr)
});
if let Ok(expr) = scrutinee {
self.visit_expr(&expr);
}
return;
}
type Args = syn::punctuated::Punctuated<syn::Expr, syn::Token![,]>;
if let Ok(args) = node.parse_body_with(Args::parse_terminated) {
for arg in &args {
self.visit_expr(arg);
}
}
}
fn visit_expr_repeat(&mut self, node: &'ast syn::ExprRepeat) {
self.visit_expr(&node.expr);
self.constant(&node.attrs, &node.len);
}
fn visit_item_mod(&mut self, node: &'ast syn::ItemMod) {
if is_test_only(&node.attrs) || is_skipped(&node.attrs) {
if node.content.is_none() {
let path = node.attrs.iter().find_map(|attr| match &attr.meta {
syn::Meta::NameValue(nv) if nv.path.is_ident("path") => match &nv.value {
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(s),
..
}) => Some(s.value()),
_ => None,
},
_ => None,
});
self.found.test_modules.push(TestModule {
name: node.ident.to_string(),
path,
});
}
return;
}
visit::visit_item_mod(self, node);
}
fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
let constant = node.sig.constness.is_some() as usize;
self.const_depth += constant;
self.function_sites(&node.sig, &node.block);
visit::visit_item_fn(self, node);
self.const_depth -= constant;
}
}
fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
let constant = node.sig.constness.is_some() as usize;
self.const_depth += constant;
self.function_sites(&node.sig, &node.block);
visit::visit_impl_item_fn(self, node);
self.const_depth -= constant;
}
}
fn visit_trait_item_fn(&mut self, node: &'ast syn::TraitItemFn) {
if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
let constant = node.sig.constness.is_some() as usize;
self.const_depth += constant;
if let Some(body) = &node.default {
self.function_sites(&node.sig, body);
}
visit::visit_trait_item_fn(self, node);
self.const_depth -= constant;
}
}
fn visit_item_impl(&mut self, node: &'ast syn::ItemImpl) {
if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
visit::visit_item_impl(self, node);
}
}
fn visit_expr_closure(&mut self, node: &'ast syn::ExprClosure) {
if node.constness.is_none() {
visit::visit_expr_closure(self, node);
}
}
fn visit_block(&mut self, node: &'ast syn::Block) {
for stmt in &node.stmts {
if let syn::Stmt::Expr(expr, Some(semi)) = stmt
&& deletable(expr)
&& let (Some((start, _)), Some((_, end))) =
(self.range(expr.span()), self.range(semi.span()))
&& in_order(start, end)
{
self.push(SiteKind::Stmt, start, end, expr.span());
}
}
visit::visit_block(self, node);
}
fn visit_expr_method_call(&mut self, node: &'ast syn::ExprMethodCall) {
let name = node.method.to_string();
if (name == "max" || name == "min")
&& node.args.len() == 1
&& node.turbofish.is_none()
&& node.attrs.is_empty()
&& let (
Some((start, receiver_end)),
Some((argument_start, argument_end)),
Some((_, end)),
) = (
self.range(node.receiver.span()),
self.range(node.args[0].span()),
self.range(node.paren_token.span.close()),
)
&& in_order(receiver_end, argument_start)
&& in_order(argument_end, end)
{
let kind = SiteKind::MinMax {
max: name == "max",
receiver: self.source[start..receiver_end].to_string(),
argument: self.source[argument_start..argument_end].to_string(),
call: (receiver_end, argument_start),
close: (argument_end, end),
};
self.push(kind, start, end, node.receiver.span());
}
visit::visit_expr_method_call(self, node);
}
fn visit_expr_for_loop(&mut self, node: &'ast syn::ExprForLoop) {
let mut over = &*node.expr;
while let syn::Expr::Paren(syn::ExprParen { expr, .. })
| syn::Expr::Group(syn::ExprGroup { expr, .. }) = over
{
over = expr;
}
if let syn::Expr::Range(syn::ExprRange {
start: Some(from), ..
}) = over
&& let Some((start, _)) = self.range(from.span())
{
self.for_ranges.insert(start);
}
visit::visit_expr_for_loop(self, node);
}
fn visit_expr_range(&mut self, node: &'ast syn::ExprRange) {
if let (Some(from), Some(to)) = (&node.start, &node.end)
&& node.attrs.is_empty()
&& let (Some((start, lhs_end)), Some((rhs_start, end))) =
(self.range(from.span()), self.range(to.span()))
&& in_order(lhs_end, rhs_start)
{
let kind = SiteKind::Range {
inclusive: matches!(node.limits, syn::RangeLimits::Closed(_)),
lhs: self.source[start..lhs_end].to_string(),
rhs: self.source[rhs_start..end].to_string(),
gap: (lhs_end, rhs_start),
};
let built = !self.for_ranges.contains(&start) || (is_literal(from) && is_literal(to));
self.const_depth += built as usize;
self.push(kind, start, end, from.span());
self.const_depth -= built as usize;
}
visit::visit_expr_range(self, node);
}
fn visit_expr_match(&mut self, node: &'ast syn::ExprMatch) {
let catches_all = |arm: &syn::Arm| {
arm.guard.is_none()
&& match &arm.pat {
syn::Pat::Wild(_) => true,
syn::Pat::Ident(p) => {
p.subpat.is_none()
&& p.ident
.to_string()
.starts_with(|c: char| c.is_lowercase() || c == '_')
}
_ => false,
}
};
let mut removable = vec![];
let has_wildcard = node
.arms
.iter()
.any(|arm| matches!(arm.pat, syn::Pat::Wild(_)));
let final_catches_all = node.arms.last().is_some_and(catches_all);
for arm in &node.arms {
if is_test_only(&arm.attrs) || is_skipped(&arm.attrs) {
continue;
}
let probe = final_catches_all && arm.attrs.is_empty() && !catches_all(arm);
let literal =
has_wildcard && !matches!(arm.pat, syn::Pat::Wild(_)) && arm.guard.is_none();
if !probe && !literal {
continue;
}
let (Some((start, pat_end)), Some((remove_start, remove_end)), Some((arrow, _))) = (
self.range(arm.pat.span()),
self.range(arm.span()),
self.range(arm.fat_arrow_token.span()),
) else {
continue;
};
let guard = match &arm.guard {
None => ArmGuard::None(arrow),
Some((_, expr)) => match self.range(expr.span()) {
Some((from, to)) => ArmGuard::Existing(from, to),
None => continue,
},
};
let pattern = match guard {
ArmGuard::Existing(from, to) => format!(
"{} if {}",
&self.source[start..pat_end],
&self.source[from..to]
),
ArmGuard::None(_) => self.source[start..pat_end].to_string(),
};
let end = arm
.comma
.as_ref()
.and_then(|comma| self.range(comma.span()))
.map_or(remove_end, |(_, end)| end);
let at = arm.pat.span().start();
removable.push(start);
let site = Site {
id: 0,
kind: SiteKind::Arm {
pattern: pattern.clone(),
guard,
removal: (remove_start, end),
},
line: at.line,
column: at.column + 1,
start,
end,
text: format!("{pattern} => .."),
};
if probe {
self.add(site);
} else {
self.add_rebuild(site);
}
}
for arm in node.arms.iter().filter(|arm| arm.attrs.is_empty()) {
if let Some((_, guard)) = &arm.guard
&& !matches!(**guard, syn::Expr::Let(_))
&& !in_let_chain(guard)
&& let (Some((start, end)), Some((pattern, _))) =
(self.range(guard.span()), self.range(arm.pat.span()))
{
let kind = SiteKind::Guard {
can_be_false: !removable.contains(&pattern),
};
self.push(kind, start, end, guard.span());
}
}
visit::visit_expr_match(self, node);
}
fn visit_arm(&mut self, arm: &'ast syn::Arm) {
if !is_test_only(&arm.attrs) && !is_skipped(&arm.attrs) {
visit::visit_arm(self, arm);
}
}
fn visit_field_value(&mut self, field: &'ast syn::FieldValue) {
if !is_test_only(&field.attrs) && !is_skipped(&field.attrs) {
visit::visit_field_value(self, field);
}
}
fn visit_expr_struct(&mut self, node: &'ast syn::ExprStruct) {
if is_test_only(&node.attrs) || is_skipped(&node.attrs) {
return;
}
let from_base = node.rest.as_deref().and_then(|base| {
if !node.attrs.is_empty() || node.qself.is_some() {
return None;
}
let (from, to) = self.range(base.span())?;
let written = &self.source[from..to];
match base {
base if is_plain_place(base) => Some(format!("({written})")),
syn::Expr::Call(call)
if call.args.is_empty() && matches!(*call.func, syn::Expr::Path(_)) =>
{
let (from, to) = self.range(node.path.span())?;
Some(format!("({} {{ ..{written} }})", &self.source[from..to]))
}
_ => None,
}
});
if node.rest.is_some() {
for pair in node.fields.pairs() {
let field = pair.value();
if is_test_only(&field.attrs) || is_skipped(&field.attrs) {
continue;
}
let name = match &field.member {
syn::Member::Named(name) => name.to_string(),
syn::Member::Unnamed(index) => index.index.to_string(),
};
let (Some((start, _)), Some((value, end)), Some((remove_start, _))) = (
self.range(field.member.span()),
self.range(field.expr.span()),
self.range(field.span()),
) else {
continue;
};
let remove_end = pair
.punct()
.and_then(|comma| self.range(comma.span()))
.map_or(end, |(_, end)| end);
let from_base = from_base
.as_ref()
.filter(|_| field.attrs.is_empty())
.map(|base| format!("{base}.{name}"));
let probe = from_base.is_some();
let kind = SiteKind::Field {
from_base,
name,
shorthand: field.colon_token.is_none(),
removal: (remove_start, remove_end),
};
let at = field.member.span().start();
let site = Site {
id: 0,
kind,
line: at.line,
column: at.column + 1,
start: if probe { value } else { remove_start },
end,
text: self.source[start..end].to_string(),
};
if probe {
self.add(site);
} else {
self.add_rebuild(site);
}
}
}
visit::visit_expr_struct(self, node);
}
fn visit_expr_unary(&mut self, node: &'ast syn::ExprUnary) {
if let syn::UnOp::Not(bang) = &node.op
&& node.attrs.is_empty()
&& let (Some((start, _)), Some((operand_start, end))) =
(self.range(bang.span()), self.range(node.expr.span()))
&& in_order(start, operand_start)
{
let kind = SiteKind::Not {
bang: (start, operand_start),
operand: self.source[operand_start..end].to_string(),
};
self.push(kind, start, end, bang.span());
}
if let syn::UnOp::Neg(minus) = &node.op
&& node.attrs.is_empty()
&& let (Some((start, _)), Some((operand_start, end))) =
(self.range(minus.span()), self.range(node.expr.span()))
&& in_order(start, operand_start)
{
let zero = match &*node.expr {
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Int(lit),
..
}) => lit.base10_parse::<u128>().is_ok_and(|v| v == 0),
_ => false,
};
if !zero {
let kind = SiteKind::Neg {
minus: (start, operand_start),
operand: self.source[operand_start..end].to_string(),
literal: matches!(*node.expr, syn::Expr::Lit(_)),
};
self.push(kind, start, end, minus.span());
}
}
visit::visit_expr_unary(self, node);
}
fn visit_expr_binary(&mut self, node: &'ast syn::ExprBinary) {
if let Some(op) = cmp_op(&node.op)
&& node.attrs.is_empty()
&& let (Some((start, lhs_end)), Some((rhs_start, end))) =
(self.range(node.left.span()), self.range(node.right.span()))
&& in_order(lhs_end, rhs_start)
{
let literal = match (int_literal(&node.left), int_literal(&node.right)) {
(None, Some(k)) => LiteralSide::Rhs(k),
(Some(k), None) => LiteralSide::Lhs(k),
_ => LiteralSide::None,
};
let kind = SiteKind::Cmp {
op,
lhs: self.source[start..lhs_end].to_string(),
rhs: self.source[rhs_start..end].to_string(),
literal,
gap: (lhs_end, rhs_start),
};
self.push(kind, start, end, node.left.span());
} else if node.attrs.is_empty()
&& let (Some((start, lhs_end)), Some((rhs_start, end))) =
(self.range(node.left.span()), self.range(node.right.span()))
&& in_order(lhs_end, rhs_start)
{
let lhs = self.source[start..lhs_end].to_string();
let rhs = self.source[rhs_start..end].to_string();
let gap = (lhs_end, rhs_start);
let logic = match &node.op {
syn::BinOp::And(_) => Some(true),
syn::BinOp::Or(_) => Some(false),
_ => None,
};
if let Some(and) = logic {
if !in_let_chain(&node.left) && !matches!(*node.right, syn::Expr::Let(_)) {
self.push(
SiteKind::Logic { and, lhs, rhs, gap },
start,
end,
node.left.span(),
);
}
} else if let Some((op, assign)) = arith_op(&node.op) {
let kind = SiteKind::Arith {
op,
assign,
lhs,
rhs,
gap,
};
let literals = is_literal(&node.left) && is_literal(&node.right);
if !literals && (!assign || is_plain_place(&node.left)) {
self.push(kind, start, end, node.left.span());
} else {
let at = node.left.span().start();
self.found.rebuild_sites.push(Site {
id: NO_ID,
kind,
line: at.line,
column: at.column + 1,
start,
end,
text: self.source[start..end].to_string(),
});
}
}
}
visit::visit_expr_binary(self, node);
}
}
#[derive(Debug, PartialEq)]
pub struct Rendered {
pub text: String,
segments: Vec<(usize, usize, usize)>,
inserted: Vec<(usize, usize, u32)>,
}
impl Rendered {
pub fn copied(&self, from: usize, to: usize) -> Option<(usize, usize)> {
self.segments
.iter()
.find(|(_, start, len)| *start <= from && to <= start + len)
.map(|(out, start, _)| (out + from - start, out + to - start))
}
pub fn inserted_by(&self, offset: usize) -> Option<u32> {
let idx = self.inserted.partition_point(|(out, _, _)| *out <= offset);
let (out, len, site) = self.inserted[idx.checked_sub(1)?];
(offset - out < len).then_some(site)
}
pub fn to_original(&self, offset: usize) -> usize {
let idx = self.segments.partition_point(|(out, _, _)| *out <= offset);
let Some((out, orig, len)) = idx.checked_sub(1).map(|i| self.segments[i]) else {
return 0;
};
orig + (offset - out).min(len)
}
}
struct Edit {
pos: usize,
end: usize,
phase: u8,
order: i64,
text: String,
site: u32,
}
pub fn render(source: &str, sites: &[Site], enabled: &dyn Fn(u32) -> bool) -> Rendered {
let rt = format!("crate::{RUNTIME_MOD}");
let mut edits = vec![];
for site in sites.iter().filter(|s| enabled(s.id)) {
let wraps = matches!(
site.kind,
SiteKind::Return { .. }
| SiteKind::Body { .. }
| SiteKind::Guard { .. }
| SiteKind::Field { .. }
);
let len = 2 * (site.end - site.start) as i64 + wraps as i64;
let (open, close) = match &site.kind {
SiteKind::Cmp { op, gap, .. } => {
let func = if op.is_ordering() { "ord" } else { "eq" };
edits.push(Edit {
pos: gap.0,
end: gap.1,
phase: 1,
order: 0,
text: "), &(".into(),
site: site.id,
});
(
"(match (&(".to_string(),
format!(
")) {{ (__tmt_l, __tmt_r) => {{ #[allow(unused_imports)] use {rt}::{{ValAny as _, ValNum as _}}; \
{rt}::{func}({id}u32, {code}u8, __tmt_l, __tmt_r, (&{rt}::W(__tmt_l)).tmt_val(), (&{rt}::W(__tmt_r)).tmt_val()) }} }})",
id = site.id,
code = op.code(),
),
)
}
SiteKind::Logic { and, gap, .. } => {
let id = site.id;
edits.push(Edit {
pos: gap.0,
end: gap.1,
phase: 1,
order: 0,
text: format!("); __tmt_c }} {{ 2u8 => {rt}::rhs({id}u32, {and}, "),
site: site.id,
});
(
format!("(match {{ let __tmt_c: u8 = {rt}::lhs({id}u32, {and}, "),
"), __tmt_c => __tmt_c == 1u8 })".to_string(),
)
}
SiteKind::Arith {
op, assign, gap, ..
} => {
let (holder, lhs_open, lhs_close) = if *assign {
("Aa", "&mut (", ")")
} else {
("Ar", "", "")
};
edits.push(Edit {
pos: gap.0,
end: gap.1,
phase: 1,
order: 0,
text: format!("{lhs_close}, "),
site: site.id,
});
(
format!("(match ({lhs_open}"),
format!(
") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{{any} as _, {prim} as _}}; \
(&{rt}::{holder}::new(__tmt_a, __tmt_b)).{method}({id}u32) }} }})",
any = op.fallback_trait(*assign),
prim = op.prim_trait(*assign),
method = op.method(*assign),
id = site.id,
),
)
}
SiteKind::Not { bang, .. } => {
edits.push(Edit {
pos: bang.0,
end: bang.1,
phase: 1,
order: 0,
text: String::new(),
site: site.id,
});
(
"(match (".to_string(),
format!(
") {{ __tmt_a => {{ #[allow(unused_imports)] use {rt}::{{AnyNot as _, NotPrim as _}}; \
(&{rt}::Un::new(__tmt_a)).tmt_not({}u32) }} }})",
site.id
),
)
}
SiteKind::Return { option, .. } => match option {
None => (
" let __tmt_v: bool = {".to_string(),
format!("}}; {rt}::ret({}u32, __tmt_v) ", site.id),
),
Some(ty) => (
format!(" let __tmt_v: {ty} = {{"),
format!("}}; {rt}::ret_opt({}u32, __tmt_v) ", site.id),
),
},
SiteKind::MinMax {
max, call, close, ..
} => {
edits.push(Edit {
pos: call.0,
end: call.1,
phase: 1,
order: 0,
text: "), ".into(),
site: site.id,
});
let (same, other) = if *max { ("max", "min") } else { ("min", "max") };
edits.push(Edit {
pos: close.0,
end: close.1,
phase: 1,
order: 0,
text: format!(
") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{AnyMinMax as _, MinMaxPrim as _}}; \
if (&{rt}::Mm(__tmt_a, &__tmt_b)).tmt_other({}u32) {{ (*__tmt_a).{other}(__tmt_b) }} else {{ (*__tmt_a).{same}(__tmt_b) }} }} }})",
site.id
),
site: site.id,
});
("(match (&(".to_string(), String::new())
}
SiteKind::Range { inclusive, gap, .. } => {
edits.push(Edit {
pos: gap.0,
end: gap.1,
phase: 1,
order: 0,
text: ", ".into(),
site: site.id,
});
let method = if *inclusive {
"tmt_range_inclusive"
} else {
"tmt_range"
};
(
"(match (".to_string(),
format!(
") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{AnyRange as _, RangePrim as _}}; \
(&{rt}::Ar::new(__tmt_a, __tmt_b)).{method}({}u32) }} }})",
site.id
),
)
}
SiteKind::Arm { guard, .. } => {
match guard {
ArmGuard::None(arrow) => edits.push(Edit {
pos: *arrow,
end: *arrow,
phase: 2,
order: 0,
text: format!("if {rt}::arm({}u32) ", site.id),
site: site.id,
}),
ArmGuard::Existing(from, to) => {
let wider = 2 * (to - from + 1) as i64;
edits.push(Edit {
pos: *from,
end: *from,
phase: 2,
order: -wider,
text: format!("{rt}::arm({}u32) && (", site.id),
site: site.id,
});
edits.push(Edit {
pos: *to,
end: *to,
phase: 0,
order: wider,
text: ")".into(),
site: site.id,
});
}
}
(String::new(), String::new())
}
SiteKind::Stmt => (
format!("if {rt}::live({}u32) {{ ", site.id),
" }".to_string(),
),
SiteKind::Neg {
operand,
literal: true,
..
} => (
format!("(if {rt}::live({}u32) {{ ", site.id),
format!(" }} else {{ {operand} }})"),
),
SiteKind::Neg { minus, .. } => {
edits.push(Edit {
pos: minus.0,
end: minus.1,
phase: 1,
order: 0,
text: String::new(),
site: site.id,
});
(
"(match (".to_string(),
format!(
") {{ __tmt_a => if {rt}::live({}u32) {{ -__tmt_a }} else {{ __tmt_a }} }})",
site.id
),
)
}
SiteKind::Guard { .. } => (format!("{rt}::ret({}u32, ", site.id), ")".to_string()),
SiteKind::Field {
name,
shorthand,
from_base: Some(from_base),
..
} => (
format!(
"{}if {rt}::live({}u32) {{ ",
if *shorthand {
format!("{name}: ")
} else {
String::new()
},
site.id
),
format!(" }} else {{ {from_base} }}"),
),
SiteKind::Field {
from_base: None, ..
} => continue,
SiteKind::Body { value, .. } => (
format!(" if !{rt}::live({}u32) {{ return {value}; }}", site.id),
String::new(),
),
};
edits.push(Edit {
pos: site.start,
end: site.start,
phase: 2,
order: -len,
text: open,
site: site.id,
});
edits.push(Edit {
pos: site.end,
end: site.end,
phase: 0,
order: len,
text: close,
site: site.id,
});
}
edits.sort_by_key(|e| (e.pos, e.phase, e.order));
let capacity = source.len() + edits.iter().map(|e| e.text.len()).sum::<usize>();
let mut text = String::with_capacity(capacity);
let mut segments = vec![];
let mut inserted = vec![];
let mut cursor = 0;
for edit in edits {
if edit.pos >= cursor {
segments.push((text.len(), cursor, edit.pos - cursor));
text.push_str(&source[cursor..edit.pos]);
}
inserted.push((text.len(), edit.text.len(), edit.site));
text.push_str(&edit.text);
cursor = cursor.max(edit.end);
}
segments.push((text.len(), cursor, source.len() - cursor));
text.push_str(&source[cursor..]);
Rendered {
text,
segments,
inserted,
}
}
pub fn blame(sites: &[Site], enabled: &dyn Fn(u32) -> bool, offset: usize) -> Vec<u32> {
let containing = || {
sites.iter().filter(|s| {
enabled(s.id)
&& s.start <= offset
&& offset <= s.end
&& !matches!(s.kind, SiteKind::Body { .. })
})
};
let Some(smallest) = containing().map(|s| s.end - s.start).min() else {
return vec![];
};
containing()
.filter(|s| s.end - s.start == smallest)
.map(|s| s.id)
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn what_an_expression_can_be_is_read_from_its_last_operation() {
use crate::plan::Reach;
for (expr, expected) in [
("blocks * 8", Some(Reach::Multiples(8))),
("8 * blocks", Some(Reach::Multiples(8))),
("(blocks * (2))", Some(Reach::Multiples(2))),
("blocks << 3", Some(Reach::Multiples(8))),
("flags & 0xF0", Some(Reach::Bits(0xF0))),
("0b1010u8 & flags", Some(Reach::Bits(0b1010))),
("n % 10", Some(Reach::Below(10))),
("(a + b) % 7_u32", Some(Reach::Below(7))),
("cents * 10", None),
("blocks * 1", None),
("blocks * 0", None),
("a * b", None),
("3 << blocks", None),
("blocks << 0", None),
("blocks << 200", None),
("10 % n", None),
("n % 0", None),
("blocks * 8 + 1", None),
("(blocks * 8) as u8", None),
("-(blocks * 8)", None),
("blocks", None),
("flags | 0xF0", None),
("blocks / 8", None),
("x * 8.0", None),
("not rust (", None),
] {
assert_eq!(reach(expr), expected, "{expr}");
}
}
#[test]
fn code_of_the_tests_is_told_from_the_rest() {
let source = r#"
pub fn open(n: u32) -> bool { n > 1 }
#[test]
fn at_the_top() { assert!(open(2)); }
#[cfg(test)]
mod tests { fn helper() -> u32 { 3 } }
mod plain {
pub fn inside(n: u32) -> bool { n > 4 }
#[cfg(test)]
fn only_tested() -> u32 { 5 }
}
struct S;
impl S {
fn method(&self) -> u32 { 6 }
#[cfg(test)]
fn test_method(&self) -> u32 { 7 }
}
#[cfg(not(test))]
fn never_in_tests() -> u32 { 8 }
"#;
let file = parse_source(source).unwrap();
let ranges = test_only_ranges(source, &file);
let of_tests = |text: &str| {
let at = source.find(text).unwrap_or_else(|| panic!("{text}"));
ranges.iter().any(|(from, to)| *from <= at && at < *to)
};
for text in ["open(2)", "{ 3 }", "{ 5 }", "{ 7 }", "fn at_the_top"] {
assert!(of_tests(text), "{text}");
}
for text in ["n > 1", "n > 4", "{ 6 }", "{ 8 }", "struct S", "mod plain"] {
assert!(!of_tests(text), "{text}");
}
let whole = "#![cfg(test)]\nfn f() {}\n";
let file = parse_source(whole).unwrap();
assert_eq!(test_only_ranges(whole, &file), [(0, whole.len())]);
}
#[test]
fn comments_documentation_and_spacing_are_not_program_text() {
let code = "/// Says.\n#[inline]\nfn f(a: u8) -> u8 {\n a + 1 // one more\n}\n";
for same in [
"#[inline] fn f(a:u8)->u8{a+1}",
"/// Says something else.\n#[inline]\nfn f(a: u8) -> u8 { /* why */ a + 1 }",
"#[doc = \"other\"] #[inline] fn f(a: u8) -> u8 { a + 1 }",
] {
assert_eq!(same_tokens(code, same), Some(true), "{same}");
}
for other in [
"#[inline] fn f(a: u8) -> u8 { a + 2 }",
"fn f(a: u8) -> u8 { a + 1 }",
"#[inline] fn f(a: u8) -> u8 { (a + 1) }",
"#[inline] fn f(a: u8) -> u8 { a + 1 } fn g() {}",
"#![inline] fn f(a: u8) -> u8 { a + 1 }",
"#[inline] fn f(a: u8) -> u8 { [a + 1][0] }",
] {
assert_eq!(same_tokens(code, other), Some(false), "{other}");
}
assert_eq!(
same_tokens("#![doc = \"a\"] fn f() {}", "fn f() {}"),
Some(true)
);
assert_eq!(same_tokens(code, "fn f( {"), None);
assert_eq!(same_tokens("fn f( {", code), None);
}
#[test]
fn a_cfg_is_decided_only_as_far_as_the_features_decide_it() {
let on: BTreeSet<String> = ["basic".to_string()].into();
for (predicate, expected) in [
(r#"feature = "basic""#, Some(true)),
(r#"feature = "extra""#, Some(false)),
(r#"not(feature = "extra")"#, Some(true)),
(r#"not(feature = "basic")"#, Some(false)),
("test", None),
(r#"target_os = "linux""#, None),
("not(test)", None),
("all()", Some(true)),
("any()", Some(false)),
(r#"all(feature = "basic", feature = "extra")"#, Some(false)),
(r#"all(test, feature = "extra")"#, Some(false)),
(r#"all(feature = "extra", test)"#, Some(false)),
(r#"all(test, feature = "basic")"#, None),
(
r#"all(feature = "basic", not(feature = "extra"))"#,
Some(true),
),
(r#"any(feature = "basic", feature = "extra")"#, Some(true)),
(r#"any(test, feature = "basic")"#, Some(true)),
(r#"any(feature = "basic", test)"#, Some(true)),
(r#"any(test, feature = "extra")"#, None),
(r#"any(feature = "extra", feature = "more")"#, Some(false)),
(r#"not(any(test, feature = "basic"))"#, Some(false)),
(r#"not(test, feature = "basic")"#, None),
("feature = 3", None),
(r#"unknown(feature = "extra")"#, None),
("all(=)", None),
] {
let meta: syn::Meta = syn::parse_str(predicate).unwrap();
assert_eq!(cfg_value(&meta, &on), expected, "{predicate}");
}
}
#[test]
fn code_under_a_feature_that_is_off_is_not_in_the_build() {
let source = r#"
#[cfg(feature = "extra")]
pub fn item(n: u32) -> bool { n > 1 }
#[cfg(feature = "basic")]
pub fn kept(n: u32) -> bool { n > 2 }
#[cfg(test)]
fn only_tests(n: u32) -> bool { n > 3 }
#[cfg(feature = "extra")]
mod module { pub fn inside(n: u32) -> bool { n > 4 } }
struct S;
impl S {
#[cfg(feature = "extra")]
fn method(&self, n: u32) -> bool { n > 5 }
fn open(&self, n: u32) -> bool { n > 6 }
}
trait T {
#[cfg(feature = "extra")]
fn provided(&self, n: u32) -> bool { n > 7 }
}
#[cfg(feature = "extra")]
impl T for S {}
fn body(n: u32) -> u32 {
#[cfg(feature = "extra")]
let n = n + 8;
#[cfg(feature = "extra")]
{ return n + 9; }
#[cfg(feature = "extra")]
if n > 10 { return 0; }
#[cfg(feature = "extra")]
assert!(n > 11);
match n {
#[cfg(feature = "extra")]
12 => 0,
_ => n + 13,
}
}
#[cfg(not(feature = "extra"))]
mod kept_module {
#[cfg(feature = "extra")]
const OFF: u32 = 14 + 1;
const ON: u32 = 15 + 1;
}
"#;
let file = parse_source(source).unwrap();
let on: BTreeSet<String> = ["basic".to_string()].into();
let ranges = inactive_ranges(source, &file, &on);
let left_out = |text: &str| {
let at = source.find(text).unwrap_or_else(|| panic!("{text}"));
ranges.iter().any(|(from, to)| *from <= at && at < *to)
};
for off in [
"n > 1 ", "n > 4", "n > 5", "n > 7", "n + 8", "n + 9", "n > 10", "n > 11", "12 =>",
"14 + 1",
] {
assert!(left_out(off), "{off}");
}
for on in ["n > 2", "n > 3", "n > 6", "n + 13", "15 + 1", "struct S"] {
assert!(!left_out(on), "{on}");
}
let both: BTreeSet<String> = ["basic".to_string(), "extra".to_string()].into();
let with_extra = inactive_ranges(source, &file, &both);
assert_eq!(with_extra.len(), 1, "{with_extra:?}");
assert!(source[with_extra[0].0..with_extra[0].1].starts_with("#[cfg(not(feature"));
let whole = "#![cfg(feature = \"extra\")]\nfn f() {}\n";
let file = parse_source(whole).unwrap();
assert_eq!(inactive_ranges(whole, &file, &on), [(0, whole.len())]);
}
fn all(_: u32) -> bool {
true
}
fn found(src: &str, first_id: u32) -> Result<Discovery> {
let mut all = discover(src, 0)?;
all.sites
.retain(|s| !matches!(s.kind, SiteKind::Return { .. } | SiteKind::Body { .. }));
for (index, site) in all.sites.iter_mut().enumerate() {
site.id = first_id + index as u32;
}
Ok(all)
}
#[test]
fn finds_a_comparison_with_a_literal() {
let src = "pub fn is_eligible(age: u32) -> bool {\n age >= 18\n}\n";
let found = found(src, 5).unwrap();
assert_eq!(found.sites.len(), 1);
let site = &found.sites[0];
assert_eq!(
(site.id, site.line, site.column, site.text.as_str()),
(5, 2, 5, "age >= 18")
);
let SiteKind::Cmp {
op,
lhs,
rhs,
literal,
..
} = &site.kind
else {
panic!()
};
assert_eq!(
(*op, lhs.as_str(), rhs.as_str(), *literal),
(CmpOp::Ge, "age", "18", LiteralSide::Rhs(18))
);
}
#[test]
fn literal_sides() {
let src =
"fn f(x: i32, y: i32) { let _ = (-5 < x, x == (3), 1 < 2, x <= y, x > 1.5 as i32); }";
let literals: Vec<LiteralSide> = found(src, 0)
.unwrap()
.sites
.iter()
.filter_map(|s| match &s.kind {
SiteKind::Cmp { literal, .. } => Some(*literal),
SiteKind::Neg { .. } => None,
_ => panic!(),
})
.collect();
assert_eq!(
literals,
[
LiteralSide::Lhs(-5),
LiteralSide::Rhs(3),
LiteralSide::None,
LiteralSide::None,
LiteralSide::None
]
);
}
#[test]
fn renders_a_comparison_probe() {
let src = "fn f(a: u8) -> bool { a >= 18 }";
let sites = found(src, 3).unwrap().sites;
let out = render(src, &sites, &all);
assert_eq!(
out.text,
"fn f(a: u8) -> bool { (match (&(a), &(18)) { (__tmt_l, __tmt_r) => { #[allow(unused_imports)] \
use crate::__tmt_rt::{ValAny as _, ValNum as _}; crate::__tmt_rt::ord(3u32, 3u8, __tmt_l, __tmt_r, \
(&crate::__tmt_rt::W(__tmt_l)).tmt_val(), (&crate::__tmt_rt::W(__tmt_r)).tmt_val()) } }) }"
);
assert_eq!(render(src, &sites, &|_| false).text, src);
}
#[test]
fn renders_statement_guards_and_nested_sites() {
let src = "fn f(v: &mut Vec<u8>, a: u8) -> Result<(), ()> {\n check((a < 3) == true)?;\n v.push(a);v.clear();\n Ok(())\n}";
let sites = found(src, 0).unwrap().sites;
let kinds: Vec<&str> = sites.iter().map(|s| s.text.as_str()).collect();
assert_eq!(
kinds,
[
"check((a < 3) == true)?;",
"v.push(a);",
"v.clear();",
"(a < 3) == true",
"a < 3"
]
);
let out = render(src, &sites, &all);
assert_eq!(
out.text.lines().count(),
src.lines().count(),
"line numbers are preserved"
);
assert!(
out.text
.contains("if crate::__tmt_rt::live(0u32) { check((match (&(((match (&(a), &(3))"),
"{}",
out.text
);
assert!(out.text.contains("if crate::__tmt_rt::live(1u32) { v.push(a); }if crate::__tmt_rt::live(2u32) { v.clear(); }"), "{}", out.text);
syn::parse_file(&out.text).expect("instrumented source parses");
let inner = render(src, &sites, &|id| id == 4);
assert!(
inner.text.contains("check(((match (&(a), &(3))"),
"{}",
inner.text
);
assert!(inner.text.contains(") == true)?;"), "{}", inner.text);
syn::parse_file(&inner.text).unwrap();
}
#[test]
fn skips_tests_const_contexts_and_macros() {
let src = r#"
const LIMIT: bool = 1 < 2;
static S: bool = 3 > 2;
const fn c(a: u8) -> bool { a < 1 }
fn arr(a: u8) -> [u8; { 2 > 1 } as usize] { let _ = [0u8; (4 > 3) as usize]; assert!(a < 9); [a; 1] }
enum E { A = (5 > 4) as isize }
struct T;
impl T { const K: bool = 6 < 7; const fn k(a: u8) -> bool { a > 6 } }
#[cfg(test)]
mod tests { fn t(a: u8) -> bool { a == 1 } }
#[cfg(test)]
mod more_tests;
#[cfg(test)]
#[doc = "not a path"]
mod documented;
#[cfg(test)]
#[path = "support/helpers.rs"]
mod helpers;
#[cfg(all(test, feature = "x"))]
fn helper(a: u8) -> bool { a != 1 }
#[test]
fn a_test() { let a = 1; if a == 2 { panic!() } }
#[tokio::test]
async fn async_test() { let a = 1; if a == 3 { panic!() } }
#[cfg(not(test))]
fn real(a: u8) -> bool { a == 100 }
#[cfg(feature = "test-utils")]
fn also_real(a: u8) -> bool { a == 101 }
fn pat(a: u8) -> bool { matches!(a, 1..=2) || match a { 0..=9 => a == 102, _ => false } }
"#;
let found = found(src, 0).unwrap();
let texts: Vec<&str> = found.sites.iter().map(|s| s.text.as_str()).collect();
assert_eq!(
texts,
[
"a == 100",
"a == 101",
"matches!(a, 1..=2) || match a { 0..=9 => a == 102, _ => false }",
"0..=9 => ..",
"a == 102"
]
);
assert_eq!(
found.test_modules,
[
TestModule {
name: "more_tests".into(),
path: None
},
TestModule {
name: "documented".into(),
path: None
},
TestModule {
name: "helpers".into(),
path: Some("support/helpers.rs".into())
},
]
);
}
#[test]
fn deletable_statements() {
let src = r#"
async fn f(s: &mut S) -> Result<(), E> {
s.validate()?;
s.total += 1;
s.flag = true;
helper(s);
s.flush().await?;
s.sync().await;
let x = s.get();
println!("{x}");
if x > 0 { return Ok(()); }
s.done()
}
"#;
let texts: Vec<String> = found(src, 0)
.unwrap()
.sites
.into_iter()
.filter(|s| s.kind == SiteKind::Stmt)
.map(|s| s.text)
.collect();
assert_eq!(
texts,
[
"s.validate()?;",
"s.total += 1;",
"s.flag = true;",
"helper(s);",
"s.flush().await?;",
"s.sync().await;"
]
);
}
#[test]
fn maps_offsets_back_and_blames_the_innermost_site() {
let src = "fn f(a: u8, b: u8) -> bool { g(a < b); a > 1 }";
let sites = found(src, 0).unwrap().sites;
let out = render(src, &sites, &all);
for (orig, ch) in src.char_indices().filter(|(_, c)| c.is_alphanumeric()) {
let hits: Vec<usize> = out
.text
.char_indices()
.filter(|(o, c)| *c == ch && out.to_original(*o) == orig)
.map(|(o, _)| o)
.collect();
assert!(
!hits.is_empty(),
"original offset {orig} ({ch}) is unreachable"
);
}
let probe = out.text.find("ord(1u32").unwrap();
let orig = out.to_original(probe);
assert_eq!(blame(&sites, &all, orig), [1]);
assert_eq!(blame(&sites, &|id| id != 1, orig), [0]);
assert_eq!(
blame(&sites, &all, src.find("fn").unwrap()),
Vec::<u32>::new()
);
assert_eq!(out.to_original(0), 0);
assert_eq!(out.to_original(out.text.len()), src.len());
}
#[test]
fn blame_is_inclusive_at_both_ends() {
let src = "fn f(a: u8) -> bool { a > 1 }";
let sites = found(src, 0).unwrap().sites;
let (start, end) = (sites[0].start, sites[0].end);
assert_eq!(blame(&sites, &all, start - 1), Vec::<u32>::new());
assert_eq!(blame(&sites, &all, start), [0]);
assert_eq!(blame(&sites, &all, end), [0]);
assert_eq!(blame(&sites, &all, end + 1), Vec::<u32>::new());
let out = render(src, &sites, &all);
assert_eq!(out.to_original(out.text.find("(match").unwrap()), start);
assert_eq!(
out.to_original(out.text.find("tmt_val()) } })").unwrap()),
end
);
assert_eq!(
out.to_original(out.text.find("), &(").unwrap() + 2),
sites[0].start + 1
);
}
#[test]
fn finds_sites_in_impls_and_array_elements() {
let src = r#"
struct T(u8);
impl T { fn small(&self) -> bool { self.0 < 3 } }
#[cfg(test)]
impl T { fn only_in_tests(&self) -> bool { self.0 < 4 } }
trait Tr { fn provided(&self, a: u8) -> bool { a < 5 } }
fn arr(a: u8) -> [bool; 2] { [a < 6; 2] }
fn closure(a: u8) -> bool { (|| a < 7)() }
"#;
let texts: Vec<String> = found(src, 0)
.unwrap()
.sites
.into_iter()
.map(|s| s.text)
.collect();
assert_eq!(texts, ["self.0 < 3", "a < 5", "a < 6", "a < 7"]);
}
#[test]
fn logic_and_arithmetic_sites() {
let src = "fn f(a: bool, b: bool, x: u32, y: u32) -> u32 { if a && b || !a { x + y * 2 } else { x - 1 % y } }";
let found = found(src, 0).unwrap().sites;
let kinds: Vec<String> = found
.iter()
.map(|s| match &s.kind {
SiteKind::Logic { and, lhs, rhs, .. } => format!("logic and={and} [{lhs}] [{rhs}]"),
SiteKind::Arith { op, lhs, rhs, .. } => {
format!("arith {} [{lhs}] [{rhs}]", op.symbol())
}
SiteKind::Not { operand, .. } => format!("not [{operand}]"),
other => format!("{other:?}"),
})
.collect();
assert_eq!(
kinds,
[
"logic and=false [a && b] [!a]",
"logic and=true [a] [b]",
"not [a]",
"arith + [x] [y * 2]",
"arith * [y] [2]",
"arith - [x] [1 % y]",
"arith % [1] [y]",
]
);
let out = render(src, &found, &all).text;
syn::parse_file(&out).expect("instrumented source parses");
assert!(
out.contains("(match { let __tmt_c: u8 = crate::__tmt_rt::lhs(1u32, true, a); __tmt_c } { 2u8 => crate::__tmt_rt::rhs(1u32, true, b), __tmt_c => __tmt_c == 1u8 })"),
"{out}"
);
assert!(
out.contains("(match (y, 2) { (__tmt_a, __tmt_b) => { #[allow(unused_imports)] use crate::__tmt_rt::{AnyMul as _, ArithPrim as _}; (&crate::__tmt_rt::Ar::new(__tmt_a, __tmt_b)).tmt_mul(4u32) } })"),
"{out}"
);
for op in ArithOp::ALL {
assert_ne!(op.swapped(), op);
for assign in [false, true] {
let method = op.method(assign);
let fallback = format!("{} {method} ", op.fallback_trait(assign));
assert!(
crate::RUNTIME_SOURCE.contains(&format!("fn {method}(")),
"{method}"
);
assert!(crate::RUNTIME_SOURCE.contains(&fallback), "{fallback}");
assert!(
crate::RUNTIME_SOURCE.contains(&format!("trait {} ", op.prim_trait(assign))),
"{op:?}"
);
}
}
}
#[test]
fn let_chains_and_literal_arithmetic_are_left_alone() {
let src = r#"
fn f(o: Option<u8>, a: bool, n: u32) -> u32 {
if let Some(x) = o && a && x > 1 { return 1; }
let k = 60 * 60;
(n & 3) | (n << 1) ^ k
}
"#;
let texts: Vec<String> = found(src, 0)
.unwrap()
.sites
.into_iter()
.map(|s| s.text)
.collect();
assert_eq!(
texts,
[
"x > 1",
"(n & 3) | (n << 1) ^ k",
"n & 3",
"(n << 1) ^ k",
"n << 1"
]
);
}
#[test]
fn attributes_const_methods_and_let_on_the_right() {
let src = r#"
struct T(u8);
impl T {
const fn in_const(&self) -> bool { self.0 < 1 }
#[test]
fn test_method(&self) -> bool { self.0 < 2 }
fn real(&self) -> bool { self.0 < 3 }
}
trait Tr {
#[cfg(test)]
fn only_in_tests(&self, a: u8) -> bool { a < 4 }
}
fn f(s: &mut S, o: Option<u8>, a: bool) -> Result<(), E> {
#[cfg(feature = "x")]
s.guarded();
#[allow(unused)]
s.total += 1;
#[allow(unused)]
s.check()?;
#[allow(unused)]
s.sync().await;
s.plain();
if a && let Some(v) = o { s.use_it(v); }
Ok(())
}
"#;
let texts: Vec<String> = found(src, 0)
.unwrap()
.sites
.into_iter()
.map(|s| s.text)
.collect();
assert_eq!(
texts,
[
"self.0 < 3",
"#[allow(unused)]\n s.total += 1;",
"s.plain();",
"#[allow(unused)]\n s.total += 1",
"s.use_it(v);"
]
);
let found = found(src, 0).unwrap().sites;
syn::parse_file(&render(src, &found, &all).text).expect("instrumented source parses");
}
#[test]
fn compound_assignment_negation_and_bit_operators() {
let src = "fn f(total: &mut u32, n: u32, ok: bool, m: Mask) -> u32 { *total += n; *total <<= 1; if !ok { return !n; } let _ = !m; n & 7 }";
let sites = found(src, 0).unwrap().sites;
let kinds: Vec<String> = sites
.iter()
.map(|s| match &s.kind {
SiteKind::Arith {
op,
assign,
lhs,
rhs,
..
} => format!(
"{lhs} {}{} {rhs}",
op.symbol(),
if *assign { "=" } else { "" }
),
SiteKind::Not { operand, .. } => format!("!{operand}"),
SiteKind::Stmt => "stmt".to_string(),
other => format!("{other:?}"),
})
.collect();
assert_eq!(
kinds,
[
"stmt",
"stmt",
"*total += n",
"*total <<= 1",
"!ok",
"!n",
"!m",
"n & 7"
]
);
let out = render(src, &sites, &all).text;
syn::parse_file(&out).expect("instrumented source parses");
for expected in [
"(match (&mut (*total), n) { (__tmt_a, __tmt_b) => { #[allow(unused_imports)] use crate::__tmt_rt::{AnyAddAssign as _, ArithAssignPrim as _}; (&crate::__tmt_rt::Aa::new(__tmt_a, __tmt_b)).tmt_add_assign(2u32) } });",
"use crate::__tmt_rt::{AnyShlAssign as _, BitAssignPrim as _}; (&crate::__tmt_rt::Aa::new(__tmt_a, __tmt_b)).tmt_shl_assign(3u32) } });",
"if (match (ok) { __tmt_a => { #[allow(unused_imports)] use crate::__tmt_rt::{AnyNot as _, NotPrim as _}; (&crate::__tmt_rt::Un::new(__tmt_a)).tmt_not(4u32) } }) {",
"(match (n, 7) { (__tmt_a, __tmt_b) => { #[allow(unused_imports)] use crate::__tmt_rt::{AnyBitAnd as _, BitPrim as _}; (&crate::__tmt_rt::Ar::new(__tmt_a, __tmt_b)).tmt_bitand(7u32) } })",
] {
assert!(out.contains(expected), "missing {expected}\nin {out}");
}
let nested = "fn f(a: bool, b: bool) -> bool { !a && b }";
let sites = found(nested, 0).unwrap().sites;
let out = render(nested, &sites, &all).text;
syn::parse_file(&out).expect("instrumented source parses");
assert!(
out.contains("(match { let __tmt_c: u8 = crate::__tmt_rt::lhs(0u32, true, (match (a) { __tmt_a => {"),
"{out}"
);
let capture = "fn f(a: bool, __tmt_c: u8, __tmt_a: u8) -> bool { a && __tmt_c == 2 && __tmt_a + 1 > 0 }";
let sites = found(capture, 0).unwrap().sites;
let out = render(capture, &sites, &all).text;
syn::parse_file(&out).expect("instrumented source parses");
for arm in out.split("__tmt_c => ").skip(1) {
assert!(arm.starts_with("__tmt_c == 1u8 })"), "{arm}");
}
for arm in out.split("(__tmt_a, __tmt_b) => ").skip(1) {
assert!(
arm.starts_with("{ #[allow(unused_imports)] use crate::__tmt_rt::"),
"{arm}"
);
}
}
#[test]
fn compound_assignment_is_probed_only_on_plain_places() {
let src = r#"
fn f(s: &mut S, v: &mut [u32], p: &mut u32, i: usize) {
let mut local = 0u32;
local += 1;
s.count += 1;
s.inner.total -= 2;
*p *= 3;
(*p) += 4;
v[i] += 5;
v[next()] += 6;
s.get_mut().x += 7;
*s.slot() += 8;
}
"#;
let probed: Vec<String> = found(src, 0)
.unwrap()
.sites
.into_iter()
.filter(|s| matches!(s.kind, SiteKind::Arith { assign: true, .. }))
.map(|s| s.text)
.collect();
assert_eq!(
probed,
[
"local += 1",
"s.count += 1",
"s.inner.total -= 2",
"*p *= 3",
"(*p) += 4"
]
);
let deletable = found(src, 0)
.unwrap()
.sites
.iter()
.filter(|s| s.kind == SiteKind::Stmt)
.count();
assert_eq!(deletable, 9);
}
#[test]
fn bool_functions_are_return_sites() {
let src = r#"
pub fn is_ok(a: u8) -> bool { let b = a; b > 1 }
fn count(a: u8) -> u8 { a }
fn unit(a: u8) { let _ = a; }
const fn in_const(a: u8) -> bool { a > 2 }
#[test]
fn a_test() -> bool { true }
struct T;
impl T { fn method(&self) -> bool { true } }
trait Tr { fn required(&self) -> bool; fn provided(&self) -> bool { false } }
fn boxed() -> Box<bool> { Box::new(true) }
fn qualified() -> core::primitive::bool { true }
"#;
let sites = discover(src, 0).unwrap().sites;
let returns: Vec<(&str, &str, usize)> = sites
.iter()
.filter_map(|s| match &s.kind {
SiteKind::Return {
name, option: None, ..
} => Some((name.as_str(), s.text.as_str(), s.line)),
_ => None,
})
.collect();
assert_eq!(
returns,
[
("is_ok", "fn is_ok(a: u8) -> bool", 2),
("method", "fn method(&self) -> bool", 9),
("provided", "fn provided(&self) -> bool", 10),
]
);
let out = render(src, &sites, &all).text;
syn::parse_file(&out).expect("instrumented source parses");
assert!(
out.contains(
"pub fn is_ok(a: u8) -> bool { let __tmt_v: bool = { \
if !crate::__tmt_rt::live(1u32) { return true; } \
if !crate::__tmt_rt::live(2u32) { return false; } let b = a; (match"
),
"{out}"
);
assert!(
out.contains("}) }; crate::__tmt_rt::ret(0u32, __tmt_v) }"),
"{out}"
);
assert_eq!(
out.lines().count(),
src.lines().count(),
"line numbers are preserved"
);
let rendered = render(src, &sites, &all);
let wrapper = rendered.text.find("ret(0u32").unwrap();
assert_eq!(rendered.inserted_by(wrapper), Some(0));
let replaced = rendered.text.find("return false; } let b").unwrap();
assert_eq!(rendered.inserted_by(replaced), Some(2));
assert_eq!(blame(&sites, &all, rendered.to_original(replaced)), [0]);
}
#[test]
fn ids_are_consecutive_across_every_kind_of_site() {
let src = r#"
fn a(x: u8) -> bool { x > 1 }
fn b(x: u8) -> bool { !(x > 2) && !!flag(x) }
fn c(s: &mut S) { s.n += 1; s.go(); }
"#;
let sites = discover(src, 10).unwrap().sites;
let ids: Vec<u32> = sites.iter().map(|s| s.id).collect();
assert_eq!(ids, (10..10 + sites.len() as u32).collect::<Vec<_>>());
let texts: Vec<&str> = sites
.iter()
.filter(|s| !matches!(s.kind, SiteKind::Body { .. }))
.map(|s| s.text.as_str())
.collect();
assert_eq!(
texts,
[
"fn a(x: u8) -> bool",
"x > 1",
"fn b(x: u8) -> bool",
"!(x > 2) && !!flag(x)",
"!(x > 2)",
"x > 2",
"!!flag(x)",
"!flag(x)",
"s.n += 1;",
"s.go();",
"s.n += 1",
]
);
syn::parse_file(&render(src, &sites, &all).text).expect("instrumented source parses");
}
#[test]
fn only_calls_and_assignments_are_deletable() {
let src = r#"
async fn f(s: &mut S, v: Vec<u8>) -> Result<(), E> {
s.field;
v[0];
(s.a, s.b);
s.value?;
s.future.await;
s.x = 1;
s.x -= 1;
s.x == 1;
s.call().await?;
Ok(())
}
"#;
let texts: Vec<String> = found(src, 0)
.unwrap()
.sites
.into_iter()
.filter(|s| s.kind == SiteKind::Stmt)
.map(|s| s.text)
.collect();
assert_eq!(texts, ["s.x = 1;", "s.x -= 1;", "s.call().await?;"]);
}
#[test]
fn ranges_match_arms_min_max_and_option_results() {
let src = r#"
fn find(v: &[u32], limit: u32) -> Option<u32> {
for i in 0..v.len() {
let capped = v[i].min(limit).max(1);
match capped {
0 => return None,
n if n > 5 => return Some(n),
1..=3 => continue,
other => { let _ = other; }
}
}
let _ = &v[1..=2];
for _ in 1..=limit as usize {}
let _ = 'a'..'z';
let _ = v.iter().max();
None
}
fn exhaustive(k: Kind) -> u8 { match k { Kind::A => 1, Kind::B => 2 } }
fn hidden() -> Option<impl Sized> { Some(1) }
fn first(v: &[u32]) -> Option<u32> { v.first().copied() }
"#;
let sites = discover(src, 0).unwrap().sites;
let kinds: Vec<String> = sites
.iter()
.filter_map(|s| match &s.kind {
SiteKind::Return { name, option, .. } => Some(format!("return {name} {option:?}")),
SiteKind::Range {
inclusive,
lhs,
rhs,
..
} => Some(format!("range {lhs} {rhs} inclusive={inclusive}")),
SiteKind::Arm { pattern, guard, .. } => Some(format!(
"arm {pattern} guarded={}",
matches!(guard, ArmGuard::Existing(..))
)),
SiteKind::MinMax {
max,
receiver,
argument,
..
} => Some(format!("minmax {receiver} {argument} max={max}")),
_ => None,
})
.collect();
assert_eq!(
kinds,
[
"range 0 v.len() inclusive=false",
"minmax v[i].min(limit) 1 max=true",
"minmax v[i] limit max=false",
"arm 0 guarded=false",
"arm n if n > 5 guarded=true",
"arm 1..=3 guarded=false",
"range 1 limit as usize inclusive=true",
"return first Some(\"Option<u32>\")",
]
);
let out = render(src, &sites, &all).text;
syn::parse_file(&out).expect("instrumented source parses");
assert_eq!(out.lines().count(), src.lines().count());
let option = sites
.iter()
.find(|site| matches!(&site.kind, SiteKind::Return { name, .. } if name == "first"))
.unwrap();
assert_eq!(out.matches("let __tmt_v: Option<u32> = {").count(), 1);
assert!(
out.contains(&format!(
"crate::__tmt_rt::ret_opt({}u32, __tmt_v)",
option.id
)),
"{out}"
);
assert!(out.contains("0 if crate::__tmt_rt::arm("), "{out}");
assert!(
out.contains("n if crate::__tmt_rt::arm(") && out.contains(") && ("),
"{out}"
);
assert!(out.contains("1..=3 if crate::__tmt_rt::arm("), "{out}");
assert!(
out.contains(".tmt_range(") && out.contains(".tmt_range_inclusive("),
"{out}"
);
assert!(
out.contains("(match (&(v[i]), limit) {")
&& out.contains(
"Mm(__tmt_a, &__tmt_b)).tmt_other(5u32) { (*__tmt_a).max(__tmt_b) } else { (*__tmt_a).min(__tmt_b) }"
)
&& out.contains(
".tmt_other(4u32) { (*__tmt_a).min(__tmt_b) } else { (*__tmt_a).max(__tmt_b) }"
),
"{out}"
);
assert!(
!out.contains(".min(limit)") && !out.contains(".max(1)"),
"{out}"
);
assert!(
out.contains("v.iter().max()"),
"an iterator's max is another method: {out}"
);
}
#[test]
fn macro_arguments() {
let src = r#"
fn f(a: u32, b: u32, out: &mut String) -> Vec<u32> {
assert!(a < 100);
debug_assert!(a < 101, "message {}", a < 102);
assert_eq!(a < 1, b < 2, "context {}", a + 3);
let _ = format!("{} {name}", a < 4, name = b < 5);
write!(out, "{}", a < 6).unwrap();
if matches!(a.cmp(&b), std::cmp::Ordering::Less if a < 7) || matches!(a < 8, true) { panic!("{}", a < 9); }
custom!(a < 10);
let _ = vec![a < 11; 2];
vec![a + b, (a < 12) as u32]
}
"#;
let texts: Vec<String> = found(src, 0)
.unwrap()
.sites
.into_iter()
.filter(|s| matches!(s.kind, SiteKind::Cmp { .. } | SiteKind::Arith { .. }))
.map(|s| s.text)
.collect();
assert_eq!(
texts,
[
"a < 1", "b < 2", "a + 3", "a < 4", "b < 5", "a < 6", "a < 8", "a < 9", "a + b",
"a < 12"
]
);
let found = found(src, 0).unwrap().sites;
syn::parse_file(&render(src, &found, &all).text).expect("instrumented source parses");
}
#[test]
fn non_ascii_source_keeps_byte_offsets() {
let src = "fn f(a: u8) -> bool { let s = \"日本語\"; s.len() > 3 && a < 2 }";
let sites = found(src, 0).unwrap().sites;
let texts: Vec<&str> = sites.iter().map(|s| s.text.as_str()).collect();
assert_eq!(texts, ["s.len() > 3 && a < 2", "s.len() > 3", "a < 2"]);
syn::parse_file(&render(src, &sites, &all).text).unwrap();
}
#[test]
fn unparseable_source_is_an_error() {
assert!(discover("fn f( {", 0).is_err());
}
fn labelled(src: &str) -> Vec<String> {
discover(src, 0)
.unwrap()
.sites
.iter()
.filter(|s| !matches!(s.kind, SiteKind::Body { .. }))
.map(|s| {
let kind = match &s.kind {
SiteKind::Cmp { .. } => "cmp",
SiteKind::Logic { .. } => "logic",
SiteKind::Arith { .. } => "arith",
SiteKind::Not { .. } => "not",
SiteKind::Return { .. } => "return",
SiteKind::MinMax { .. } => "minmax",
SiteKind::Range { .. } => "range",
SiteKind::Arm { .. } => "arm",
SiteKind::Stmt => "stmt",
SiteKind::Neg { .. } => "neg",
SiteKind::Guard { .. } => "guard",
SiteKind::Field { .. } => "field",
SiteKind::Body { .. } => "body",
};
format!("{kind} {}", s.text)
})
.collect()
}
#[test]
fn byte_order_mark_and_interpreter_line_are_refused() {
let body = "fn f(a: u8) -> bool { a > 1 }";
assert!(discover(&format!("\u{feff}{body}"), 0).is_err());
assert!(discover(&format!("#!/usr/bin/env run\n{body}"), 0).is_err());
assert_eq!(
labelled(&format!("#![allow(dead_code)]\n{body}")),
["return fn f(a: u8) -> bool", "cmp a > 1"]
);
}
#[test]
fn which_result_types_make_a_return_site() {
let src = "fn a() -> <S as Tr>::Option<u8> { g() }\n\
fn b() -> Option { g() }\n\
fn c() -> Vec<u8> { g() }\n\
fn d() -> std::option::Option<u8> { g() }\n\
fn e() -> <S>::bool { g() }\n\
fn e2() -> <S as Tr>::bool { g() }\n\
fn one(a: u8) -> bool { a > 1 }\n\
fn two(a: u8) -> bool { let b = a; b > 1 }\n\
fn early(a: u8) -> bool { return a > 1; }\n";
let returns: Vec<(String, Option<String>, Option<&str>)> = discover(src, 0)
.unwrap()
.sites
.into_iter()
.filter_map(|s| match s.kind {
SiteKind::Return {
name,
option,
sole_expr,
} => Some((name, option, sole_expr.map(|(from, to)| &src[from..to]))),
_ => None,
})
.collect();
assert_eq!(
returns,
[
(
"d".to_string(),
Some("std::option::Option<u8>".to_string()),
Some("g()")
),
("one".to_string(), None, Some("a > 1")),
("two".to_string(), None, None),
]
);
}
#[test]
fn places_chains_attributes_and_shadowed_macros() {
assert_eq!(
labelled("fn f(mut x: i32) -> i32 { #[allow(unused)] x += 1; (x) += 2; x }"),
[
"stmt #[allow(unused)] x += 1;",
"stmt (x) += 2;",
"arith (x) += 2"
]
);
assert_eq!(
labelled("fn f(a: u8, o: Option<u8>) { if a > 1 && let Some(b) = o { g(b); } }"),
["cmp a > 1", "stmt g(b);"]
);
assert_eq!(
labelled(
"fn f(a: u8, o: Option<u8>) { if a > 1 && let Some(b) = o && b > 2 { g(b); } }"
),
["cmp a > 1", "cmp b > 2", "stmt g(b);"]
);
assert_eq!(
labelled(
"macro_rules! vec { ($($t:tt)*) => {} }\n\
fn f(a: u8) { let _ = vec![a > 1]; let _ = format!(\"{}\", a > 2); }"
),
["cmp a > 2"]
);
assert_eq!(
labelled(
"trait T { const fn f(a: u8) -> bool { a > 1 } fn g(a: u8) -> bool { a > 2 } }"
),
["return fn g(a: u8) -> bool", "cmp a > 2"]
);
}
#[test]
fn min_max_and_ranges_that_are_left_alone() {
assert_eq!(
labelled(
"fn f(a: u8, b: u8) -> u8 { let _ = a.max::<u8>(b); \
let _ = #[allow(unused)] a.min(b); let _ = a.max(b, 1); a.max(b) }"
),
["minmax a.max(b)"]
);
let src = "fn f(a: usize, b: usize, v: &[u8]) { for _ in a..10 {} for _ in 1..b {} \
for _ in (a + 1)..(b * 2) {} for _ in 3..4 {} for _ in (5)..(-6) {} }";
assert_eq!(
labelled(src),
[
"range a..10",
"range 1..b",
"range (a + 1)..(b * 2)",
"arith a + 1",
"arith b * 2",
"neg -6"
]
);
let out = render(src, &discover(src, 0).unwrap().sites, &all).text;
assert!(out.contains("for _ in (match (a, 10) {"), "{out}");
assert!(!out.contains("a..10") && !out.contains("1..b"), "{out}");
assert!(out.contains("3..4") && out.contains("(5)..((if "), "{out}");
}
#[test]
fn which_arms_can_be_removed() {
let src = "fn f(k: u8) -> u8 {\n\
\x20 let a = match k { 1 => 1, x => x, 2 => 2, #[cfg(any())] 3 => 3, _rest => 0 };\n\
\x20 let b = match k { 1 => 1, NONE => 0 };\n\
\x20 let c = match k { 1 => 1, n @ 0..=9 => n };\n\
\x20 let d = match k {\n\
\x20 1 => 1,\n\
\x20 _ => 0,\n\
\x20 };\n\
\x20 a + b + c + d\n\
}\n";
let arms: Vec<(u32, usize, usize, String)> = discover(src, 7)
.unwrap()
.sites
.into_iter()
.filter(|s| matches!(s.kind, SiteKind::Arm { .. }))
.map(|s| (s.id, s.line, s.column, s.text))
.collect();
assert_eq!(
arms,
[
(9, 2, 23, "1 => ..".to_string()),
(10, 2, 39, "2 => ..".to_string()),
(11, 6, 9, "1 => ..".to_string()),
]
);
}
#[test]
fn offsets_around_inserted_text() {
let src = "fn f(a: u8) -> bool { a > 1 }";
let sites = found(src, 0).unwrap().sites;
let out = render(src, &sites, &all);
let start = sites[0].start;
let copied_a = out.text.find("a), &(").unwrap();
assert_eq!(out.to_original(copied_a), start);
assert_eq!(out.to_original(copied_a - 1), start);
assert_eq!(out.to_original(copied_a + 1), start + 1);
assert_eq!(out.to_original(out.text.len() + 10), src.len());
let src = "fn f(a: usize, b: usize) { for _ in a..b + 1 {} }";
let sites = discover(src, 0).unwrap().sites;
let out = render(src, &sites, &all);
let inner_probe = out.text.find("(match (a, ").unwrap() + "(match (a, ".len();
assert!(
out.text[inner_probe..].starts_with("(match (b, 1)"),
"{}",
out.text
);
assert_eq!(out.to_original(inner_probe), src.find("b + 1").unwrap());
let arith = sites
.iter()
.find(|s| matches!(s.kind, SiteKind::Arith { .. }))
.unwrap();
assert_eq!(
blame(&sites, &all, out.to_original(inner_probe)),
[arith.id]
);
assert_eq!(out.inserted_by(inner_probe), Some(arith.id));
assert_eq!(out.inserted_by(out.text.find("b, 1").unwrap()), None);
let opening = "(match (b, ";
let (first, last) = (inner_probe, inner_probe + "(match (".len() - 1);
assert!(out.text[inner_probe..].starts_with(opening));
assert_eq!(out.inserted_by(first), Some(arith.id));
assert_eq!(out.inserted_by(last), Some(arith.id));
assert_eq!(out.inserted_by(last + 1), None);
assert_eq!(out.inserted_by(0), None);
}
fn values(ty: &str) -> Vec<String> {
let function: syn::ItemFn = syn::parse_str(&format!("fn f() -> {ty} {{ todo!() }}"))
.unwrap_or_else(|e| panic!("{ty}: {e}"));
body_values(&function.sig.output)
}
#[test]
fn replacement_values_by_return_type() {
let rows: &[(&str, &[&str])] = &[
("()", &["()"]),
("i8", &["0", "1", "-1"]),
("isize", &["0", "1", "-1"]),
("i128", &["0", "1", "-1"]),
("u8", &["0", "1"]),
("usize", &["0", "1"]),
("u128", &["0", "1"]),
("f32", &["0.0", "1.0", "-1.0"]),
("f64", &["0.0", "1.0", "-1.0"]),
("bool", &["true", "false"]),
(
"NonZeroI32",
&["1.try_into().unwrap()", "(-1).try_into().unwrap()"],
),
("std::num::NonZeroU8", &["1.try_into().unwrap()"]),
("NonZero<u64>", &["1.try_into().unwrap()"]),
(
"NonZero<i64>",
&["1.try_into().unwrap()", "(-1).try_into().unwrap()"],
),
("String", &["String::new()", "\"xyzzy\".into()"]),
("&str", &["\"\"", "\"xyzzy\""]),
("&'static str", &["\"\"", "\"xyzzy\""]),
("&mut str", &["Box::leak(Box::new(Default::default()))"]),
("&u8", &["Box::leak(Box::new(0))", "Box::leak(Box::new(1))"]),
(
"&mut bool",
&["Box::leak(Box::new(true))", "Box::leak(Box::new(false))"],
),
(
"&[u8]",
&[
"Vec::leak(Vec::new())",
"Vec::leak(vec![0])",
"Vec::leak(vec![1])",
],
),
(
"&mut [bool]",
&[
"Vec::leak(Vec::new())",
"Vec::leak(vec![true])",
"Vec::leak(vec![false])",
],
),
("Result<bool, Error>", &["Ok(true)", "Ok(false)"]),
("io::Result<()>", &["Ok(())"]),
("fmt::Result", &["Ok(Default::default())"]),
("Result", &["Ok(Default::default())"]),
("Option<u8>", &["None", "Some(0)", "Some(1)"]),
("Vec<bool>", &["vec![]", "vec![true]", "vec![false]"]),
("Box<u8>", &["Box::new(0)", "Box::new(1)"]),
(
"std::rc::Rc<u8>",
&["std::rc::Rc::new(0)", "std::rc::Rc::new(1)"],
),
("Arc<bool>", &["Arc::new(true)", "Arc::new(false)"]),
("RefCell<()>", &["RefCell::new(())"]),
("Mutex<()>", &["Mutex::new(())"]),
("Cell<()>", &["Cell::new(())"]),
(
"HashSet<u8>",
&[
"HashSet::new()",
"HashSet::from_iter([0])",
"HashSet::from_iter([1])",
],
),
(
"BTreeSet<()>",
&["BTreeSet::new()", "BTreeSet::from_iter([()])"],
),
(
"BinaryHeap<()>",
&["BinaryHeap::new()", "BinaryHeap::from_iter([()])"],
),
(
"LinkedList<()>",
&["LinkedList::new()", "LinkedList::from_iter([()])"],
),
(
"VecDeque<()>",
&["VecDeque::new()", "VecDeque::from_iter([()])"],
),
(
"HashMap<bool, u8>",
&[
"HashMap::new()",
"HashMap::from_iter([(true, 0)])",
"HashMap::from_iter([(true, 1)])",
"HashMap::from_iter([(false, 0)])",
"HashMap::from_iter([(false, 1)])",
],
),
(
"std::collections::BTreeMap<(), ()>",
&[
"std::collections::BTreeMap::new()",
"std::collections::BTreeMap::from_iter([((), ())])",
],
),
(
"Cow<'a, str>",
&[
"Cow::Borrowed(\"\")",
"Cow::Owned(\"\".to_owned())",
"Cow::Borrowed(\"xyzzy\")",
"Cow::Owned(\"xyzzy\".to_owned())",
],
),
("[u8; 4]", &["[0; 4]", "[1; 4]"]),
("[bool; N + 1]", &["[true; N + 1]", "[false; N + 1]"]),
(
"(u8, bool)",
&["(0, true)", "(0, false)", "(1, true)", "(1, false)"],
),
("(bool,)", &["(true,)", "(false,)"]),
("HttpResponse", &["HttpResponse::Ok().finish()"]),
(
"actix_web::HttpResponse",
&["actix_web::HttpResponse::Ok().finish()"],
),
("Config", &["Default::default()"]),
("Self", &["Default::default()"]),
("<T as Tr>::Out", &["Default::default()"]),
("<T as Tr>::String", &["Default::default()"]),
("<T>::bool", &["Default::default()"]),
("fn(u8) -> u8", &["Default::default()"]),
("*const u8", &["Default::default()"]),
(
"Result<Option<String>, E>",
&[
"Ok(None)",
"Ok(Some(String::new()))",
"Ok(Some(\"xyzzy\".into()))",
],
),
("(Vec<()>)", &["vec![]", "vec![()]"]),
("Option<Config>", &["None", "Some(Default::default())"]),
("!", &[]),
("impl Iterator<Item = u8>", &[]),
("Box<impl Fn()>", &[]),
("Option<!>", &["None"]),
];
for (ty, expected) in rows {
assert_eq!(values(ty), *expected, "{ty}");
}
let unit: syn::ItemFn = syn::parse_str("fn f() {}").unwrap();
assert_eq!(body_values(&unit.sig.output), ["()"]);
}
#[test]
fn which_functions_get_their_body_replaced() {
let src = r#"
fn plain(a: u8) -> u8 { a + 1 }
fn already(a: u8) -> bool { let _ = a; true }
fn sole() -> bool { true }
fn spaced() -> (u8, bool) { ( 0 , true ) }
unsafe fn raw(a: u8) -> u8 { a }
fn empty() {}
fn one_call(s: &mut S) { s.go(); }
fn two_calls(s: &mut S) { s.go(); s.stop(); }
fn typed(s: &mut S) -> u8 { s.exit(); }
fn tight() -> bool {true}
#[rustfmt::skip]
fn formatted(a: u8) -> u8 { a + 6 }
#[mutants::timeout(5)]
fn slow(a: u8) -> u8 { a + 7 }
impl S { #[mutants::skip] fn marked_method(&self, a: u8) -> u8 { a + 8 } }
trait U { #[mutants::skip] fn marked_default(&self, a: u8) -> u8 { a + 9 } }
fn one_let(a: u8) { let _ = a; }
fn never() -> ! { loop {} }
fn hidden() -> impl Sized { 1 }
#[mutants::skip]
fn marked(a: u8) -> u8 { a + 2 }
#[cfg_attr(test, mutants::skip)]
fn marked_in_tests(a: u8) -> u8 { a + 3 }
#[mutants::skip]
impl S { fn method(&self, a: u8) -> u8 { a + 4 } }
#[mutants::skip]
mod generated { fn inner(a: u8) -> u8 { a + 5 } }
trait T { fn required(&self) -> u8; fn provided(&self) -> u8 { 7 } }
async fn later() -> u8 { 9 }
"#;
let sites = discover(src, 0).unwrap().sites;
let bodies: Vec<String> = sites
.iter()
.filter_map(|s| match &s.kind {
SiteKind::Body { name, value, .. } => Some(format!("{name} {value}")),
_ => None,
})
.collect();
assert_eq!(
bodies,
[
"plain 0",
"plain 1",
"already true",
"already false",
"sole false",
"spaced (0, false)",
"spaced (1, true)",
"spaced (1, false)",
"two_calls ()",
"typed 0",
"typed 1",
"tight false",
"formatted 0",
"formatted 1",
"slow 0",
"slow 1",
"one_let ()",
"provided 0",
"provided 1",
"later 0",
"later 1",
]
);
let texts: Vec<&str> = sites.iter().map(|s| s.text.as_str()).collect();
for skipped in ["a + 2", "a + 3", "a + 4", "a + 5", "a + 8", "a + 9"] {
assert!(!texts.contains(&skipped), "{skipped}");
}
for mutated in ["a + 1", "a + 6", "a + 7"] {
assert!(texts.contains(&mutated), "{mutated}");
}
let unsafe_sites: Vec<&Site> = sites.iter().filter(|s| s.text.contains("raw")).collect();
assert!(unsafe_sites.is_empty(), "{unsafe_sites:?}");
let body = sites
.iter()
.find(|s| matches!(s.kind, SiteKind::Body { .. }))
.unwrap();
assert_eq!(
(body.line, body.column, body.text.as_str()),
(2, 13, "fn plain(a: u8) -> u8")
);
let out = render(src, &sites, &all).text;
syn::parse_file(&out).expect("instrumented source parses");
assert_eq!(out.lines().count(), src.lines().count());
assert!(
out.contains(
"fn plain(a: u8) -> u8 { if !crate::__tmt_rt::live(0u32) { return 0; } \
if !crate::__tmt_rt::live(1u32) { return 1; } (match (a, 1)"
),
"{out}"
);
let tight = "fn f(a: u8, b: u8) -> bool {a > b}";
let sites = discover(tight, 0).unwrap().sites;
let out = render(tight, &sites, &all).text;
syn::parse_file(&out).expect("instrumented source parses");
assert!(
out.starts_with(
"fn f(a: u8, b: u8) -> bool { let __tmt_v: bool = { \
if !crate::__tmt_rt::live(1u32) { return true; } \
if !crate::__tmt_rt::live(2u32) { return false; }(match (&(a), &(b))"
),
"{out}"
);
assert!(
out.ends_with(" })}; crate::__tmt_rt::ret(0u32, __tmt_v) }"),
"{out}"
);
}
#[test]
fn minus_guards_and_fields() {
let src = r#"
fn f(x: i32, y: f64, k: Kind, base: Options) -> Options {
let a = -x + -5 - -0 + (-0.0 * -y) as i32;
let b = match k {
Kind::A(n) if n > 1 => 1,
Kind::A(n) if let Some(m) = half(n) => m,
Kind::B if x > 0 && let Some(m) = half(x) => m,
#[cfg(any())]
Kind::B if x > 2 => 2,
Kind::B => 3,
};
let c = match b { n if n > 3 => 1, _ => 0 };
let first = Options { depth: a, name, ..base };
let second = Options { depth: -b, ..Default::default() };
let third = Wrap::<u8> { 0: c, ..Wrap::new() };
let _ = Options { depth: 1, ..base.clone() };
let _ = Options { depth: 2, ..make(3) };
let _ = Options { depth: 6, ..(pick())() };
let _ = -2.5 + y;
let _ = Options { #[cfg(any())] depth: 4, strict: true, ..*other };
let _ = Options { depth: 5, name: n, strict: false };
first
}
"#;
let sites = found(src, 0).unwrap().sites;
let kinds: Vec<String> = sites
.iter()
.filter_map(|s| match &s.kind {
SiteKind::Neg {
operand, literal, ..
} => Some(format!("neg {} | {operand} | literal={literal}", s.text)),
SiteKind::Guard { can_be_false } => {
Some(format!("guard {} | can_be_false={can_be_false}", s.text))
}
SiteKind::Field {
name,
shorthand,
from_base: Some(from_base),
..
} => Some(format!(
"field {} | {name} | shorthand={shorthand} | {from_base}",
s.text
)),
_ => None,
})
.collect();
assert_eq!(
kinds,
[
"neg -x | x | literal=false",
"neg -5 | 5 | literal=true",
"neg -0.0 | 0.0 | literal=true",
"neg -y | y | literal=false",
"guard n > 1 | can_be_false=true",
"guard n > 3 | can_be_false=false",
"field depth: a | depth | shorthand=false | (base).depth",
"field name | name | shorthand=true | (base).name",
"field depth: -b | depth | shorthand=false | (Options { ..Default::default() }).depth",
"neg -b | b | literal=false",
"field 0: c | 0 | shorthand=false | (Wrap::<u8> { ..Wrap::new() }).0",
"neg -2.5 | 2.5 | literal=true",
"field strict: true | strict | shorthand=false | (*other).strict",
]
);
let field = sites
.iter()
.find(|s| s.text == "depth: a")
.expect("the field is a site");
let line = src.lines().nth(field.line - 1).unwrap();
assert_eq!(line.find("depth: a"), Some(field.column - 1), "{line}");
assert_eq!(&src[field.start..field.end], "a");
let out = render(src, &sites, &all).text;
syn::parse_file(&out).expect("instrumented source parses");
assert_eq!(out.lines().count(), src.lines().count());
for expected in [
"(match (x) { __tmt_a => if crate::__tmt_rt::live(",
"u32) { -__tmt_a } else { __tmt_a } })",
"u32) { -5 } else { 5 })",
"Kind::A(n) if crate::__tmt_rt::ret(",
"u32, (match (&(n), &(1))",
"n if crate::__tmt_rt::arm(",
") && (crate::__tmt_rt::ret(",
"depth: if crate::__tmt_rt::live(",
"{ a } else { (base).depth }",
"name: if crate::__tmt_rt::live(",
"{ name } else { (base).name }, ..base }",
"} else { (Options { ..Default::default() }).depth }, ..Default::default() }",
"0: if crate::__tmt_rt::live(",
"Options { depth: 1, ..base.clone() }",
"Options { depth: 2, ..make(3) }",
"Options { depth: 6, ..(pick())() }",
"Options { depth: 5, name: n, strict: false }",
] {
assert!(out.contains(expected), "{expected}\n{out}");
}
assert!(
!out.contains("{ -0 }") && out.contains("{ -0.0 } else { 0.0 }"),
"{out}"
);
}
fn mutated(src: &str, sites: &[Site]) -> Vec<String> {
sites
.iter()
.flat_map(|site| {
source_mutants(site).into_iter().map(|m| {
let text = format!("{}{}{}", &src[..m.start], m.replacement, &src[m.end..]);
syn::parse_file(&text).unwrap_or_else(|e| panic!("{text}: {e}"));
format!("{} -> {}: {}", m.what, m.into, text.trim())
})
})
.collect()
}
#[test]
fn what_cannot_be_probed_is_mutated_in_the_source() {
let src = "const fn c(a: u8, b: u8) -> bool { a < b }\n\
fn f(m: &mut Map, k: u8) { *m.entry(k).or_insert(0) += 1; m.total -= 1; }\n\
fn evens(n: u8) -> impl Iterator<Item = u8> + '_ { (0..n).step_by(2) }\n\
impl S { const fn k(&self) -> u8 { -self.0 } }\n\
trait T { const fn d(a: u8) -> u8 { a } }\n";
let found = discover(src, 0).unwrap();
assert!(found.rebuild_sites.iter().all(|s| s.id == NO_ID));
let places: Vec<(usize, usize, &str)> = found
.rebuild_sites
.iter()
.filter(|s| !matches!(s.kind, SiteKind::Return { .. }))
.map(|s| (s.line, s.column, s.text.as_str()))
.collect();
assert_eq!(
places,
[
(1, 1, "const fn c(a: u8, b: u8) -> bool"),
(1, 1, "const fn c(a: u8, b: u8) -> bool"),
(1, 36, "a < b"),
(2, 28, "*m.entry(k).or_insert(0) += 1"),
(3, 1, "fn evens(n: u8) -> impl Iterator<Item = u8> + '_"),
(3, 1, "fn evens(n: u8) -> impl Iterator<Item = u8> + '_"),
(3, 1, "fn evens(n: u8) -> impl Iterator<Item = u8> + '_"),
(3, 53, "0..n"),
(4, 10, "const fn k(&self) -> u8"),
(4, 10, "const fn k(&self) -> u8"),
(4, 36, "-self.0"),
(5, 11, "const fn d(a: u8) -> u8"),
(5, 11, "const fn d(a: u8) -> u8"),
]
);
assert_eq!(
found.sites.iter().map(|s| s.id).collect::<Vec<_>>(),
(0..found.sites.len() as u32).collect::<Vec<_>>()
);
let numbered: Vec<&str> = found.sites.iter().map(|s| s.text.as_str()).collect();
assert_eq!(
numbered,
[
"fn f(m: &mut Map, k: u8)",
"*m.entry(k).or_insert(0) += 1;",
"m.total -= 1;",
"m.total -= 1",
]
);
assert_eq!(
mutated(src, &found.rebuild_sites)
.iter()
.map(|line| line.lines().next().unwrap().to_string())
.take(5)
.collect::<Vec<_>>(),
[
"body -> true: const fn c(a: u8, b: u8) -> bool { true }",
"body -> false: const fn c(a: u8, b: u8) -> bool { false }",
"< -> ==: const fn c(a: u8, b: u8) -> bool { a == b }",
"< -> >: const fn c(a: u8, b: u8) -> bool { a > b }",
"< -> <=: const fn c(a: u8, b: u8) -> bool { a <= b }",
]
);
let whats: Vec<String> = found
.rebuild_sites
.iter()
.flat_map(|site| {
source_mutants(site)
.into_iter()
.map(|m| format!("{}: {} -> {}", site.text, m.what, m.into))
})
.skip(5)
.collect();
assert_eq!(
whats,
[
"*m.entry(k).or_insert(0) += 1: += -> -=",
"*m.entry(k).or_insert(0) += 1: += -> *=",
"fn evens(n: u8) -> impl Iterator<Item = u8> + '_: body -> ::core::iter::empty()",
"fn evens(n: u8) -> impl Iterator<Item = u8> + '_: body -> ::core::iter::once(0)",
"fn evens(n: u8) -> impl Iterator<Item = u8> + '_: body -> ::core::iter::once(1)",
"0..n: .. -> ..=",
"const fn k(&self) -> u8: body -> 0",
"const fn k(&self) -> u8: body -> 1",
"-self.0: - -> ",
"const fn d(a: u8) -> u8: body -> 0",
"const fn d(a: u8) -> u8: body -> 1",
]
);
}
#[test]
fn fields_are_removed_from_arbitrary_struct_updates() {
for base in ["base", "make(seed)", "builder.make(seed)"] {
for field in ["value: 9", "value"] {
for attribute in ["", "#[cfg(any())] "] {
let original =
format!("fn f() -> S {{ S {{ {attribute}{field}, other: 2, ..{base} }} }}");
let found = discover(&original, 0).unwrap();
let fields: Vec<_> = found
.sites
.iter()
.chain(&found.rebuild_sites)
.flat_map(source_mutants)
.filter(|mutant| mutant.what == "field" && mutant.into == "value")
.collect();
if attribute.is_empty() {
assert_eq!(fields.len(), 1, "{original}");
let m = &fields[0];
let changed = format!(
"{}{}{}",
&original[..m.start],
m.replacement,
&original[m.end..]
);
assert_eq!(
changed,
format!("fn f() -> S {{ S {{ other: 2, ..{base} }} }}")
);
syn::parse_file(&changed).unwrap();
} else {
assert!(fields.is_empty(), "{original}");
}
}
}
}
let plain = discover("fn plain() -> S { S { value: 9 } }", 0).unwrap();
assert!(
plain
.sites
.iter()
.chain(&plain.rebuild_sites)
.flat_map(source_mutants)
.all(|m| m.what != "field")
);
}
#[test]
fn unknown_wrappers_and_nested_iterators_have_source_body_candidates() {
for outer in ["Wrapper", "Option", "Result"] {
for inner in ["bool", "impl Iterator<Item = u8>"] {
for error in [false, true] {
let error_values: &[&str] = if error { &["7"] } else { &[] };
let extra = if outer == "Result" { ", u8" } else { "" };
let source = format!("fn f() -> {outer}<{inner}{extra}> {{ todo!() }}");
let found = discover_with_errors(&source, 0, error_values).unwrap();
let values: Vec<&str> = found
.sites
.iter()
.chain(&found.rebuild_sites)
.filter_map(|site| match &site.kind {
SiteKind::Body { value, .. } => Some(value.as_str()),
_ => None,
})
.collect();
let example = match (outer, inner) {
("Wrapper", "bool") => "Wrapper::from_iter([false])",
("Option", "bool") => "Some(false)",
("Result", "bool") => "Ok(false)",
("Wrapper", _) => "Wrapper::new(::core::iter::once(1))",
("Option", _) => "Some(::core::iter::once(1))",
("Result", _) => "Ok(::core::iter::once(1))",
_ => unreachable!(),
};
assert!(values.contains(&example), "{source}: {values:?}");
assert_eq!(
values.contains(&"Err(7)"),
outer == "Result" && error,
"{source}"
);
if inner != "bool" {
assert!(found.sites.is_empty(), "{source}");
}
}
}
}
}
#[test]
fn source_deletes_the_whole_statement_and_the_unguarded_arm() {
let source = "fn clear(v: &mut Vec<u8>) { v.clear(); }\n\
fn select(x: u8) -> u8 { match x { 0 => 4, #[allow(unused)] 1 => 5, _ => 6 } }";
let found = discover(source, 0).unwrap();
let removals: Vec<_> = found
.sites
.iter()
.chain(&found.rebuild_sites)
.flat_map(source_mutants)
.filter(|mutant| mutant.replacement.is_empty())
.map(|mutant| &source[mutant.start..mutant.end])
.collect();
assert!(removals.contains(&"v.clear();"), "{removals:?}");
assert!(removals.contains(&"0 => 4,"), "{removals:?}");
assert!(
removals.contains(&"#[allow(unused)] 1 => 5,"),
"{removals:?}"
);
}
#[test]
fn source_mutants_of_every_kind() {
let src = "fn f(a: i32, b: i32, k: K, base: O) -> O { \
let x = match k { K::A(n) if n >= 1 => !(a != b) || a <= -b, K::B => a % b > 0 && a == b, _ => false }; \
O { on: x, a, ..base } }";
let sites = found(src, 0).unwrap().sites;
assert_eq!(mutated(src, &sites).len(), 18);
let changes: Vec<String> = sites
.iter()
.flat_map(source_mutants)
.map(|m| {
format!(
"{} -> {} | `{}` becomes `{}`",
m.what,
m.into,
&src[m.start..m.end],
m.replacement
)
})
.collect();
assert_eq!(
changes,
[
"arm -> K::A(n) if n >= 1 | `n >= 1` becomes `false`",
"arm -> K::B | `K::B => a % b > 0 && a == b,` becomes ``",
"guard -> true | `n >= 1` becomes `true`",
">= -> < | ` >= ` becomes ` < `",
"|| -> && | `!(a != b) || a <= -b` becomes `(!(a != b)) && (a <= -b)`",
"! -> | `!` becomes ``",
"!= -> == | ` != ` becomes ` == `",
"<= -> > | ` <= ` becomes ` > `",
"- -> | `-` becomes ``",
"&& -> || | `a % b > 0 && a == b` becomes `(a % b > 0 || a == b)`",
"> -> == | ` > ` becomes ` == `",
"> -> < | ` > ` becomes ` < `",
"> -> >= | ` > ` becomes ` >= `",
"% -> / | ` % ` becomes ` / `",
"% -> + | `a % b` becomes `(a + b)`",
"== -> != | ` == ` becomes ` != `",
"field -> on | `on: x,` becomes ``",
"field -> a | `a,` becomes ``",
]
);
let src = "fn f(a: u8, b: u8) -> bool { g(); for _ in a..b {} a.max(b) > 1 }";
let sites = discover(src, 0).unwrap().sites;
for site in &sites {
let none = matches!(site.kind, SiteKind::Return { .. } | SiteKind::MinMax { .. });
assert_eq!(source_mutants(site).is_empty(), none, "{:?}", site.kind);
}
let ends = |src: &str| -> Vec<String> {
discover(src, 0)
.unwrap()
.sites
.iter()
.filter(|site| matches!(site.kind, SiteKind::Range { .. }))
.flat_map(source_mutants)
.map(|m| format!("{}{}{}", &src[..m.start], m.replacement, &src[m.end..]))
.collect()
};
assert_eq!(
ends("fn f(a: u8, b: u8) { for _ in a..b {} }"),
["fn f(a: u8, b: u8) { for _ in a..=b {} }"]
);
assert_eq!(
ends("fn f(a: u8, b: u8) { for _ in a ..= b {} }"),
["fn f(a: u8, b: u8) { for _ in a..b {} }"]
);
}
#[test]
fn iterators_to_return_instead() {
let values = |ty: &str| {
let function: syn::ItemFn =
syn::parse_str(&format!("fn f() -> {ty} {{ todo!() }}")).unwrap();
iterator_values(&function.sig.output)
};
assert_eq!(
values("impl Iterator<Item = bool>"),
[
"::core::iter::empty()",
"::core::iter::once(true)",
"::core::iter::once(false)"
]
);
assert_eq!(
values("impl std::iter::Iterator<Item = String> + Send + 'a").len(),
3
);
assert_eq!(
values("impl Iterator<Extra = u8, Item = ()>"),
["::core::iter::empty()", "::core::iter::once(())"]
);
assert_eq!(
values("impl Iterator<Item = impl Sized>"),
["::core::iter::empty()"]
);
for other in [
"impl Sized",
"impl Iterator",
"impl IntoIterator<Item = u8>",
"Box<dyn Iterator<Item = u8>>",
"u8",
"()",
] {
assert!(values(other).is_empty(), "{other}");
}
let unit: syn::ItemFn = syn::parse_str("fn f() {}").unwrap();
assert!(iterator_values(&unit.sig.output).is_empty());
}
fn built(src: &str) -> Vec<String> {
let found = discover(src, 0).unwrap();
found
.rebuild_sites
.iter()
.flat_map(source_mutants)
.map(|m| format!("{}{}{}", &src[..m.start], m.replacement, &src[m.end..]))
.collect()
}
#[test]
fn a_body_that_is_written_as_the_value_and_one_that_only_computes() {
let bodies = |src: &str| -> Vec<(String, bool)> {
discover(src, 0)
.unwrap()
.sites
.iter()
.filter_map(|site| match &site.kind {
SiteKind::Body {
value, sole_expr, ..
} => Some((value.clone(), sole_expr.is_some())),
_ => None,
})
.collect()
};
let values = |src: &str| -> Vec<String> { bodies(src).into_iter().map(|b| b.0).collect() };
assert_eq!(values("fn t() -> bool { true }"), ["false"]);
assert_eq!(values("fn n() -> u8 { 0 }"), ["1"]);
assert_eq!(
values("fn s() -> String { String :: new () }"),
["\"xyzzy\".into()"]
);
assert_eq!(
values("fn s() -> &'static str { \" \" }"),
["\"\"", "\"xyzzy\""]
);
for (body, only_computes) in [
("n > 0", true),
("!(self.limit < n) && n as u8 != 3", true),
("(n, 1).0 > *&n", true),
("self.push(n) > 0", false),
("next() > 0", false),
("matches!(n, 1)", false),
("(if n > 1 { n } else { 0 }) > 0", false),
("list[n] > 0", false),
("check(n)? > 0", false),
("(self.count += n) == ()", false),
("(self.count = n) == ()", false),
] {
let src = format!("impl S {{ fn f(&mut self, n: usize) -> bool {{ {body} }} }}");
let all = bodies(&src);
assert_eq!(all.len(), 2, "{body}");
assert!(all.iter().all(|b| b.1 == only_computes), "{body}: {all:?}");
}
}
#[test]
fn items_are_named_by_what_is_around_them() {
let src = "fn top(a: u8) -> u8 { fn inner(b: u8) -> u8 { b } inner(a) }\n\
mod m { pub fn in_mod() {} const K: u8 = 1; }\n\
impl Store { fn commit(&self) {} const LIMIT: u8 = 2; }\n\
impl<T> fmt::Display for Id<T> { fn fmt(&self) {} }\n\
trait Tr { fn provided(&self) {} fn required(&self); }\n\
static S: u8 = 3;\nlet";
assert!(named_items(src).is_empty());
let src = src.strip_suffix("let").unwrap();
let items = named_items(src);
let names: Vec<&str> = items.iter().map(|item| item.name.as_str()).collect();
assert_eq!(
names,
[
"top",
"top::inner",
"m::in_mod",
"m::K",
"Store::commit",
"Store::LIMIT",
"<fmt::Display for Id<T>>::fmt",
"Tr::provided",
"Tr::required",
"S",
]
);
let at = |text: &str| src.find(text).unwrap();
assert_eq!(enclosing_item(&items, at("{ b }") + 2), "top::inner");
assert_eq!(enclosing_item(&items, at("inner(a)")), "top");
assert_eq!(enclosing_item(&items, at("fn top")), "top");
assert_eq!(enclosing_item(&items, at("mod m")), "");
assert_eq!(enclosing_item(&items, at("= 2") + 2), "Store::LIMIT");
assert_eq!(enclosing_item(&items, src.len()), "");
let (first, after) = (at("pub fn in_mod"), at("pub fn in_mod() {}") + 18);
assert_eq!(enclosing_item(&items, first - 1), "");
assert_eq!(enclosing_item(&items, first), "m::in_mod");
assert_eq!(enclosing_item(&items, after - 1), "m::in_mod");
assert_eq!(enclosing_item(&items, after), "");
let text = "ab\nçd e\n";
assert_eq!(offset_of(text, 1, 1), Some(0));
assert_eq!(offset_of(text, 1, 2), Some(1));
assert_eq!(offset_of(text, 2, 1), Some(3));
assert_eq!(offset_of(text, 2, 2), Some(5), "after the two bytes of `ç`");
assert_eq!(offset_of(text, 2, 99), Some(text.len()));
assert_eq!(offset_of(text, 0, 1), None);
assert_eq!(offset_of(text, 1, 0), None);
}
#[test]
fn only_the_range_of_a_for_is_probed() {
let src = "fn f(a: u8, b: u8, v: &[u8]) -> usize {\n\
for _ in a..b {}\n\
for _ in (a..=b) {}\n\
for _ in (a..b).rev() {}\n\
let kept = a..b;\n\
let _ = &v[a as usize..b as usize];\n\
for _ in kept.clone() {}\n\
for _ in 0..3 {}\n\
let _ = &v[0..3];\n\
(a..=b).count() }";
let all = discover(src, 0).unwrap();
let ranges = |sites: &[Site]| -> Vec<usize> {
sites
.iter()
.filter(|site| matches!(site.kind, SiteKind::Range { .. }))
.map(|site| site.line)
.collect()
};
assert_eq!(ranges(&all.sites), [2, 3]);
assert_eq!(ranges(&all.rebuild_sites), [4, 5, 6, 8, 9, 10]);
let literal: Vec<(&str, String)> = all
.rebuild_sites
.iter()
.filter(|site| site.line == 8 || site.line == 9)
.flat_map(|site| {
source_mutants(site)
.into_iter()
.map(move |mutant| (site.text.as_str(), mutant.replacement))
})
.collect();
assert_eq!(
literal,
[("0..3", "..=".to_string()), ("0..3", "..=".to_string())]
);
}
#[test]
fn what_marks_code_as_not_to_be_mutated() {
let src = "#[allow(mutants, skip)] fn loosely(a: u8) -> u8 { a + 1 }\n\
#[doc = \"mutants skip\"] fn spoken_of(a: u8) -> u8 { a + 2 }\n\
#[mutants :: skip] fn spaced(a: u8) -> u8 { a + 3 }\n\
#[cfg_attr(test, mutants::skip)] fn conditional(a: u8) -> u8 { a + 4 }\n\
#[mutants::skip] mod generated;\n\
#[mutants::skip] #[path = \"gen/other.rs\"] mod other;\n\
mod plain;\n\
mod inline { fn inner(a: u8) -> u8 { a + 5 } }\n\
#[mutants::skip] mod marked { fn inner(a: u8) -> u8 { a + 6 } }\n";
let all = discover(src, 0).unwrap();
let texts: Vec<&str> = found_arith(&all.sites);
assert_eq!(texts, ["a + 1", "a + 2", "a + 5"]);
assert_eq!(
all.test_modules,
[
TestModule {
name: "generated".to_string(),
path: None
},
TestModule {
name: "other".to_string(),
path: Some("gen/other.rs".to_string())
},
]
);
}
fn found_arith(sites: &[Site]) -> Vec<&str> {
sites
.iter()
.filter(|site| matches!(site.kind, SiteKind::Arith { .. }))
.map(|site| site.text.as_str())
.collect()
}
#[test]
fn a_replaced_operator_keeps_its_operands() {
assert_eq!(
built("const X: i32 = 8 - 2 * 3;"),
[
"const X: i32 = 8 + 2 * 3;",
"const X: i32 = (8) / (2 * 3);",
"const X: i32 = 8 - 2 / 3;",
"const X: i32 = 8 - (2 + 3);",
]
);
assert_eq!(
built("const B: bool = P || Q && R;"),
[
"const B: bool = (P) && (Q && R);",
"const B: bool = P || (Q || R);",
]
);
assert_eq!(
built("const M: u8 = A & B | C;"),
[
"const M: u8 = (A & B) & (C);",
"const M: u8 = (A & B) ^ (C);",
"const M: u8 = (A | B) | C;",
"const M: u8 = (A ^ B) | C;",
]
);
assert_eq!(
built("const S: u8 = 1 << 2 + 1;"),
[
"const S: u8 = 1 >> 2 + 1;",
"const S: u8 = 1 << 2 - 1;",
"const S: u8 = 1 << (2) * (1);",
]
);
assert_eq!(
built("const C: bool = A + 1 < B;")[..3],
[
"const C: bool = A + 1 == B;",
"const C: bool = A + 1 > B;",
"const C: bool = A + 1 <= B;",
]
);
let assigned = built("const fn f(mut x: u8) -> u8 { x += 2 * 3; x }");
for expected in [
"const fn f(mut x: u8) -> u8 { x -= 2 * 3; x }",
"const fn f(mut x: u8) -> u8 { x *= 2 * 3; x }",
"const fn f(mut x: u8) -> u8 { x += (2 + 3); x }",
] {
assert!(assigned.iter().any(|text| text == expected), "{assigned:?}");
}
}
#[test]
fn excluded_parent_items_do_not_contribute_const_sites() {
let source = r#"
#[cfg(test)] enum TestEnum { A = 1 + 2 }
#[mutants::skip] struct Skip { a: [u8; 2 + 3] }
#[cfg(test)] type Alias = [u8; 3 + 4];
#[cfg(test)] union TestUnion { a: [u8; 4 + 5] }
#[mutants::skip] trait Hidden { const DATA: [u8; 5 + 6]; }
struct Data { #[cfg(test)] bytes: [u8; 6 + 7] }
fn f() { #[cfg(test)] let _: [u8; 8 + 9] = [0; 17]; }
const DATA: [u8; 7 + 8] = [0; 15];
"#;
let found = discover(source, 0).unwrap();
let sites: Vec<_> = found
.rebuild_sites
.iter()
.map(|site| site.text.as_str())
.collect();
assert_eq!(sites, ["7 + 8"]);
}
#[test]
fn compile_time_expressions_get_source_mutants_but_never_probes() {
for (place, context) in [
("inline", "let _ = const { 6 * 7 };"),
("repeat", "let _ = [0u8; 6 * 7];"),
("type length", "let _: [u8; 6 * 7];"),
("discriminant", "enum Value { One = 6 * 7 }"),
("const argument", "let _: Items<{ 6 * 7 }>;"),
("const default", "struct Items<const N: usize = { 6 * 7 }>;"),
] {
for qualifier in ["", "const "] {
for marker in ["", "#[mutants::skip] "] {
let source =
format!("{marker}{qualifier}fn f(x: u32) -> u32 {{ {context} x * 2 }}");
let found = discover(&source, 0).unwrap();
let variants: Vec<_> = found
.rebuild_sites
.iter()
.filter(|site| site.text == "6 * 7")
.flat_map(source_mutants)
.map(|mutant| mutant.into)
.collect();
let expected: &[&str] = if marker.is_empty() { &["/", "+"] } else { &[] };
assert_eq!(variants, expected, "{place}: {source}");
assert!(
found.sites.iter().all(|site| site.text != "6 * 7"),
"{source}"
);
assert_eq!(
found.sites.iter().any(|site| site.text == "x * 2"),
marker.is_empty() && qualifier.is_empty(),
"{source}"
);
}
}
}
}
#[test]
fn a_test_branch_or_skip_documentation_does_not_exclude_production_code() {
let source = r#"
/// The mutants::skip attribute is documented here.
#[cfg(any(test, feature = "production"))]
fn public(x: u32) -> u32 { x + 1 }
#[cfg(all(test, feature = "production"))]
fn for_tests(x: u32) -> u32 { x + 2 }
#[cfg_attr(any(), mutants::skip)]
fn skipped(x: u32) -> u32 { x + 3 }
"#;
let found = discover(source, 0).unwrap();
let arithmetic: Vec<_> = found
.sites
.iter()
.filter(|site| matches!(site.kind, SiteKind::Arith { .. }))
.map(|site| site.text.as_str())
.collect();
assert_eq!(arithmetic, ["x + 1"]);
}
#[test]
fn constants_and_literal_arithmetic_are_mutated_in_the_source() {
let src = "const HALF: u64 = SPAN / 2;\n\
static LIMIT: i32 = -(1 << 4);\n\
impl S { const K: bool = A < B; }\n\
trait T { const D: u8 = 3 + 4; const R: u8; }\n\
#[cfg(test)]\n\
const ONLY_IN_TESTS: u8 = 5 + 6;\n\
#[mutants::skip]\n\
const MARKED: u8 = 7 + 8;\n\
#[cfg(test)]\n\
static TEST_LIMIT: u8 = 9 + 1;\n\
impl S { #[mutants::skip] const SKIPPED: u8 = 9 + 2; }\n\
trait U { #[cfg(test)] const ONLY: u8 = 9 + 3; }\n\
fn f(x: u32) -> u32 { let _ = [0u8; 2 + 3]; x + 60 * 60 }\n\
fn one(s: &mut S) { s.go(); }\n\
fn two(s: &mut S) { s.go(); s.stop(); }\n\
fn value(s: &mut S) -> u8 { s.get() }\n";
let found = discover(src, 0).unwrap();
let built: Vec<String> = found
.rebuild_sites
.iter()
.flat_map(|site| {
source_mutants(site)
.into_iter()
.map(|m| format!("{}: {} -> {}", site.text, m.what, m.into))
})
.collect();
assert_eq!(
built,
[
"SPAN / 2: / -> *",
"SPAN / 2: / -> %",
"-(1 << 4): - -> ",
"1 << 4: << -> >>",
"A < B: < -> ==",
"A < B: < -> >",
"A < B: < -> <=",
"3 + 4: + -> -",
"3 + 4: + -> *",
"2 + 3: + -> -",
"2 + 3: + -> *",
"60 * 60: * -> /",
"60 * 60: * -> +",
]
);
mutated(src, &found.rebuild_sites);
let probed: Vec<&str> = found
.sites
.iter()
.filter(|s| matches!(s.kind, SiteKind::Arith { .. }))
.map(|s| s.text.as_str())
.collect();
assert_eq!(probed, ["x + 60 * 60"]);
assert_eq!(found.single_statement_bodies, ["one"]);
let bodies: Vec<String> = found
.sites
.iter()
.filter_map(|s| match &s.kind {
SiteKind::Body { name, value, .. } => Some(format!("{name} {value}")),
_ => None,
})
.collect();
assert_eq!(bodies, ["f 0", "f 1", "two ()", "value 0", "value 1"]);
}
#[test]
fn an_attribute_excludes_the_compile_time_expressions_of_what_it_is_on() {
for context in [
"fn f() { @let _ = [0u8; 6 * 7]; }",
"fn f() { let _ = @const { 6 * 7 }; }",
"struct Items<@const N: usize = { 6 * 7 }>;",
"@enum E { A = 6 * 7 }",
"enum E { @A = 6 * 7 }",
"enum E { @A([u8; 6 * 7]) }",
"@struct S { a: [u8; 6 * 7] }",
"struct S { @a: [u8; 6 * 7] }",
"@union U { a: [u8; 6 * 7] }",
"@trait T { const D: [u8; 6 * 7]; }",
"trait T { @type A = [u8; 6 * 7]; }",
"@type A = [u8; 6 * 7];",
"impl T for S { @type A = [u8; 6 * 7]; }",
] {
for attribute in ["", "#[mutants::skip] ", "#[cfg(test)] "] {
let source = context.replace('@', attribute);
let found = discover(&source, 0).unwrap();
let expected: &[&str] = if attribute.is_empty() {
&["6 * 7"]
} else {
&[]
};
assert_eq!(found_arith(&found.rebuild_sites), expected, "{source}");
assert!(found_arith(&found.sites).is_empty(), "{source}");
}
}
for attribute in ["#![mutants::skip]", "#![cfg(test)]"] {
let source =
format!("{attribute}\nconst N: u8 = 6 * 7;\nfn f(a: u8) -> u8 {{ a + 1 }}");
let found = discover(&source, 0).unwrap();
assert!(found.sites.is_empty(), "{source}");
assert!(found.rebuild_sites.is_empty(), "{source}");
}
}
#[test]
fn compile_time_expressions_are_found_inside_types() {
let built = |source: &str| -> Vec<String> {
let found = discover(source, 0).unwrap();
assert!(found_arith(&found.sites).is_empty(), "{source}");
found_arith(&found.rebuild_sites)
.into_iter()
.map(str::to_string)
.collect()
};
assert_eq!(
built("fn f() { let _: [[u8; 1 + 2]; 3 + 4]; }"),
["1 + 2", "3 + 4"]
);
assert_eq!(built("struct S<const N: [u8; 2 + 3]>;"), ["2 + 3"]);
assert_eq!(built("fn f() { let _: Items<{ N + 1 }>; }"), ["N + 1"]);
}
#[test]
fn only_the_skip_mark_and_a_cfg_that_needs_test_exclude_code() {
let src = "#[mutants] fn bare(a: u8) -> u8 { a + 1 }\n\
#[mutants::skip::deeper] fn longer(a: u8) -> u8 { a + 2 }\n\
#[cfg(all(test))] fn all_of_one(a: u8) -> u8 { a + 3 }\n\
#[cfg(not(not(test)))] fn twice_not(a: u8) -> u8 { a + 4 }\n\
#[cfg(not())] fn malformed(a: u8) -> u8 { a + 5 }\n\
#[labels(test)] fn labelled(a: u8) -> u8 { a + 6 }\n";
let found = discover(src, 0).unwrap();
assert_eq!(
found_arith(&found.sites),
["a + 1", "a + 2", "a + 5", "a + 6"]
);
}
#[test]
fn which_arms_are_probed_built_or_left_alone() {
let src = "fn f(x: u8, k: Kind, c: bool, a: u8) -> u8 {\n\
\x20 let p = match x { 0 => 4, #[allow(unused)] 1 => 5, #[allow(unused)] 2 if c => 6, _ => 7 };\n\
\x20 let q = match k { Kind::A => 1, Kind::B => 2 };\n\
\x20 let r = match x { #[mutants::skip] 3 => a + 1, #[cfg(test)] 4 => a + 2, 5 => a + 3, _ => a + 4 };\n\
\x20 p + q + r\n\
}\n";
let found = discover(src, 0).unwrap();
let arms = |sites: &[Site]| -> Vec<String> {
sites
.iter()
.filter(|site| matches!(site.kind, SiteKind::Arm { .. }))
.map(|site| site.text.clone())
.collect()
};
assert_eq!(arms(&found.sites), ["0 => ..", "5 => .."]);
assert_eq!(arms(&found.rebuild_sites), ["1 => .."]);
let in_arms: Vec<&str> = found_arith(&found.sites)
.into_iter()
.filter(|text| text.starts_with("a + "))
.collect();
assert_eq!(in_arms, ["a + 3", "a + 4"]);
}
#[test]
fn which_fields_of_a_struct_update_are_probed_built_or_left_alone() {
let src = "fn f(a: u8, base: S) {\n\
\x20 let _ = S { #[mutants::skip] v: a + 1, #[cfg(test)] w: a + 2, x: a + 3, ..base };\n\
\x20 g(#[mutants::skip] S { v: a + 4, ..base });\n\
\x20 g(#[cfg(test)] S { v: a + 5, ..base });\n\
\x20 g(#[allow(unused)] S { v: a + 6, ..base });\n\
\x20 g(<S as Tr>::Out { v: a + 7, ..base });\n\
}\n";
let found = discover(src, 0).unwrap();
let fields = |sites: &[Site]| -> Vec<String> {
sites
.iter()
.filter_map(|site| match &site.kind {
SiteKind::Field { from_base, .. } => Some(format!(
"{} | {}",
site.text,
from_base.as_deref().unwrap_or("-")
)),
_ => None,
})
.collect()
};
assert_eq!(fields(&found.sites), ["x: a + 3 | (base).x"]);
assert_eq!(
fields(&found.rebuild_sites),
["v: a + 6 | -", "v: a + 7 | -"]
);
assert_eq!(found_arith(&found.sites), ["a + 3", "a + 6", "a + 7"]);
}
#[test]
fn body_values_that_are_only_built() {
let bodies = |sites: &[Site]| -> Vec<String> {
sites
.iter()
.filter_map(|site| match &site.kind {
SiteKind::Body { value, .. } => Some(value.clone()),
_ => None,
})
.collect()
};
let found = discover("fn f() -> Wrapper<bool> { Wrapper::new() }", 0).unwrap();
assert_eq!(bodies(&found.sites), ["Default::default()"]);
assert_eq!(values("Wrapper<bool>"), ["Default::default()"]);
assert_eq!(
bodies(&found.rebuild_sites),
[
"Wrapper::from_iter([true])",
"Wrapper::new(true)",
"Wrapper::from(true)",
"Wrapper::from_iter([false])",
"Wrapper::new(false)",
"Wrapper::from(false)",
]
);
assert!(values("(bool, impl Iterator<Item = u8>)").is_empty());
let nested = "impl Iterator<Item = impl Iterator<Item = u8>>";
let found = discover(&format!("fn f() -> {nested} {{ todo!() }}"), 0).unwrap();
assert!(bodies(&found.sites).is_empty());
assert_eq!(
bodies(&found.rebuild_sites),
[
"::core::iter::empty()",
"::core::iter::once(::core::iter::empty())",
"::core::iter::once(::core::iter::once(0))",
"::core::iter::once(::core::iter::once(1))",
]
);
let function: syn::ItemFn =
syn::parse_str(&format!("fn f() -> {nested} {{ todo!() }}")).unwrap();
assert_eq!(
iterator_values(&function.sig.output),
["::core::iter::empty()"]
);
}
}