Skip to main content

targeted_mutation/
instrument.rs

1//! Finds mutation sites in Rust source and rewrites them into probes.
2//!
3//! Every site stays in the compiled code (mutant schemata): a comparison `a >= b` becomes a
4//! call that records what it saw and, when a mutant is switched on, returns the mutated
5//! result. One build serves the trace run and every mutant.
6//!
7//! The rewrite only inserts text on the line where the site is, so line numbers in compiler
8//! diagnostics still match the original file.
9
10use anyhow::{Context, Result};
11use proc_macro2::{Span, TokenStream, TokenTree};
12use quote::ToTokens;
13use serde::Serialize;
14use syn::spanned::Spanned;
15use syn::visit::{self, Visit};
16
17use crate::plan::CmpOp;
18
19/// Name of the module injected into the crate root.
20pub const RUNTIME_MOD: &str = "__tmt_rt";
21
22#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
23#[serde(rename_all = "snake_case")]
24pub enum LiteralSide {
25    None,
26    Rhs(i128),
27    Lhs(i128),
28}
29
30#[derive(Clone, PartialEq, Eq, Debug)]
31pub enum SiteKind {
32    Cmp {
33        op: CmpOp,
34        lhs: String,
35        rhs: String,
36        literal: LiteralSide,
37        /// Byte range of the operator and the whitespace around it.
38        gap: (usize, usize),
39    },
40    /// `lhs && rhs` or `lhs || rhs`.
41    Logic {
42        and: bool,
43        lhs: String,
44        rhs: String,
45        gap: (usize, usize),
46    },
47    /// `lhs + rhs` and friends. Only primitive numbers are mutated; for other operand
48    /// types the probe performs the original operation and reports nothing.
49    Arith {
50        op: ArithOp,
51        /// `lhs op= rhs` rather than `lhs op rhs`.
52        assign: bool,
53        lhs: String,
54        rhs: String,
55        gap: (usize, usize),
56    },
57    /// `!operand`. Only `bool` is mutated (the `!` is dropped).
58    Not {
59        /// Byte range of the `!` and whatever separates it from the operand.
60        bang: (usize, usize),
61        operand: String,
62    },
63    /// The body of a function that returns `bool`. The site's range is the inside of the
64    /// body's braces and its text is the function signature.
65    Return {
66        name: String,
67        /// `None` for a function returning `bool`; for one returning `Option<T>`, the
68        /// return type as written.
69        option: Option<String>,
70        /// Byte range of the body when it is a single expression: the function's result
71        /// is then exactly that expression's value.
72        sole_expr: Option<(usize, usize)>,
73    },
74    /// `receiver.max(argument)` or `.min(..)`: the other of the two.
75    MinMax {
76        max: bool,
77        receiver: String,
78        argument: String,
79        /// Byte ranges of `.max(` and of the closing `)`.
80        call: (usize, usize),
81        close: (usize, usize),
82    },
83    /// `lhs..rhs` or `lhs..=rhs` on integers: the end moves by one.
84    Range {
85        inclusive: bool,
86        lhs: String,
87        rhs: String,
88        gap: (usize, usize),
89    },
90    /// An arm of a `match` that ends in a catch-all arm: without this arm the value falls
91    /// through to the arms below.
92    Arm {
93        pattern: String,
94        /// Where to put the probe: the start of the `=>`, or the range of an existing guard.
95        guard: ArmGuard,
96    },
97    /// A call or assignment statement that can be deleted.
98    Stmt,
99    /// `-operand`: the minus is dropped.
100    Neg {
101        /// Byte range of the `-` and whatever separates it from the operand.
102        minus: (usize, usize),
103        operand: String,
104        /// The operand is a literal: its type is whatever the context asks for.
105        literal: bool,
106    },
107    /// The guard of a match arm: replaced by `true` or `false`.
108    Guard {
109        /// Whether `false` is a mutant of its own. It is not where the arm can be removed,
110        /// which is the same thing.
111        can_be_false: bool,
112    },
113    /// A field of a struct literal with a base (`..base`): the field is left to the base.
114    Field {
115        name: String,
116        /// Written without its name (`S { name, ..base }`).
117        shorthand: bool,
118        /// The expression that reads the field from the base.
119        from_base: String,
120    },
121    /// The whole body of a function, replaced by a value of its return type. The site's
122    /// range is the inside of the body's braces and its text is the function signature.
123    Body {
124        name: String,
125        value: String,
126        /// The body when it is one expression that only computes its value (no call,
127        /// no macro, nothing assigned, no early exit): replacing the body by the value
128        /// that expression always had is then the same program for the tests.
129        sole_expr: Option<(usize, usize)>,
130    },
131}
132
133#[derive(Clone, Copy, PartialEq, Eq, Debug)]
134pub enum ArmGuard {
135    /// No guard: one is added before the `=>` at this offset.
136    None(usize),
137    /// `if <expr>` with the expression at this byte range.
138    Existing(usize, usize),
139}
140
141#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
142#[serde(rename_all = "snake_case")]
143pub enum ArithOp {
144    Add,
145    Sub,
146    Mul,
147    Div,
148    Rem,
149    BitAnd,
150    BitOr,
151    BitXor,
152    Shl,
153    Shr,
154}
155
156impl ArithOp {
157    /// How tightly the operator binds: a higher number before a lower one.
158    pub fn binding(self) -> u8 {
159        match self {
160            ArithOp::Mul | ArithOp::Div | ArithOp::Rem => 5,
161            ArithOp::Add | ArithOp::Sub => 4,
162            ArithOp::Shl | ArithOp::Shr => 3,
163            ArithOp::BitAnd => 2,
164            ArithOp::BitXor => 1,
165            ArithOp::BitOr => 0,
166        }
167    }
168
169    pub const ALL: [ArithOp; 10] = [
170        ArithOp::Add,
171        ArithOp::Sub,
172        ArithOp::Mul,
173        ArithOp::Div,
174        ArithOp::Rem,
175        ArithOp::BitAnd,
176        ArithOp::BitOr,
177        ArithOp::BitXor,
178        ArithOp::Shl,
179        ArithOp::Shr,
180    ];
181
182    pub fn symbol(self) -> &'static str {
183        match self {
184            ArithOp::Add => "+",
185            ArithOp::Sub => "-",
186            ArithOp::Mul => "*",
187            ArithOp::Div => "/",
188            ArithOp::Rem => "%",
189            ArithOp::BitAnd => "&",
190            ArithOp::BitOr => "|",
191            ArithOp::BitXor => "^",
192            ArithOp::Shl => "<<",
193            ArithOp::Shr => ">>",
194        }
195    }
196
197    /// The operator the mutant uses instead.
198    pub fn swapped(self) -> ArithOp {
199        match self {
200            ArithOp::Add => ArithOp::Sub,
201            ArithOp::Sub => ArithOp::Add,
202            ArithOp::Mul => ArithOp::Div,
203            ArithOp::Div => ArithOp::Mul,
204            ArithOp::Rem => ArithOp::Div,
205            ArithOp::BitAnd => ArithOp::BitOr,
206            ArithOp::BitOr => ArithOp::BitAnd,
207            ArithOp::BitXor => ArithOp::BitAnd,
208            ArithOp::Shl => ArithOp::Shr,
209            ArithOp::Shr => ArithOp::Shl,
210        }
211    }
212
213    /// The second operator a mutant uses instead. The shifts have none.
214    pub fn swapped2(self) -> Option<ArithOp> {
215        Some(match self {
216            ArithOp::Add => ArithOp::Mul,
217            ArithOp::Sub => ArithOp::Div,
218            ArithOp::Mul => ArithOp::Add,
219            ArithOp::Div => ArithOp::Rem,
220            ArithOp::Rem => ArithOp::Add,
221            ArithOp::BitAnd | ArithOp::BitOr => ArithOp::BitXor,
222            ArithOp::BitXor => ArithOp::BitOr,
223            ArithOp::Shl | ArithOp::Shr => return None,
224        })
225    }
226
227    /// The second replacement where the operator is written as an assignment or not.
228    /// Bits collected with `|=` from zero are the same bits with `^=`, and `&=` with
229    /// `^=` is rarely a slip of the pen: as in cargo-mutants, those two are left out.
230    pub fn second(self, assign: bool) -> Option<ArithOp> {
231        if assign && matches!(self, ArithOp::BitAnd | ArithOp::BitOr) {
232            return None;
233        }
234        self.swapped2()
235    }
236
237    /// Bit operators exist for integers only, the others for floats too.
238    pub fn is_bitwise(self) -> bool {
239        matches!(
240            self,
241            ArithOp::BitAnd | ArithOp::BitOr | ArithOp::BitXor | ArithOp::Shl | ArithOp::Shr
242        )
243    }
244
245    /// The name the runtime uses for this operator in its probe methods and traits.
246    fn stem(self) -> (&'static str, &'static str) {
247        match self {
248            ArithOp::Add => ("add", "Add"),
249            ArithOp::Sub => ("sub", "Sub"),
250            ArithOp::Mul => ("mul", "Mul"),
251            ArithOp::Div => ("div", "Div"),
252            ArithOp::Rem => ("rem", "Rem"),
253            ArithOp::BitAnd => ("bitand", "BitAnd"),
254            ArithOp::BitOr => ("bitor", "BitOr"),
255            ArithOp::BitXor => ("bitxor", "BitXor"),
256            ArithOp::Shl => ("shl", "Shl"),
257            ArithOp::Shr => ("shr", "Shr"),
258        }
259    }
260
261    /// Name of the probe method in the runtime.
262    pub(crate) fn method(self, assign: bool) -> String {
263        format!(
264            "tmt_{}{}",
265            self.stem().0,
266            if assign { "_assign" } else { "" }
267        )
268    }
269
270    /// Trait with the probe for every type that is not a primitive number.
271    pub(crate) fn fallback_trait(self, assign: bool) -> String {
272        format!("Any{}{}", self.stem().1, if assign { "Assign" } else { "" })
273    }
274
275    /// Trait with the probe for primitive numbers.
276    fn prim_trait(self, assign: bool) -> &'static str {
277        match (self.is_bitwise(), assign) {
278            (false, false) => "ArithPrim",
279            (true, false) => "BitPrim",
280            (false, true) => "ArithAssignPrim",
281            (true, true) => "BitAssignPrim",
282        }
283    }
284}
285
286#[derive(Clone, PartialEq, Eq, Debug)]
287pub struct Site {
288    pub id: u32,
289    pub kind: SiteKind,
290    /// 1-based line and column of the start of the site.
291    pub line: usize,
292    pub column: usize,
293    /// Byte range in the original source.
294    pub start: usize,
295    pub end: usize,
296    pub text: String,
297}
298
299#[derive(Debug, PartialEq, Eq)]
300pub struct TestModule {
301    pub name: String,
302    /// The `#[path = "..."]` of the declaration, relative to the declaring file's directory.
303    pub path: Option<String>,
304}
305
306#[derive(Debug, Default)]
307pub struct Discovery {
308    pub sites: Vec<Site>,
309    /// Sites that cannot be switched while the program runs: inside a `const fn`, the
310    /// body of a function that returns `impl Iterator`, a compound assignment to a place
311    /// that is more than a variable. Their mutants are built one by one
312    /// (`source_mutants`). They have no number.
313    pub rebuild_sites: Vec<Site>,
314    /// Functions that return nothing and consist of one statement that is a site: an
315    /// empty body is the mutant that deletes the statement, so it is not made twice.
316    pub single_statement_bodies: Vec<String>,
317    /// Out-of-line modules that only exist under `cfg(test)` (`#[cfg(test)] mod tests;`).
318    pub test_modules: Vec<TestModule>,
319}
320
321/// Finds the sites in one source file, numbering them from `first_id`.
322pub fn discover(source: &str, first_id: u32) -> Result<Discovery> {
323    // The parser drops a byte order mark and a `#!` line before it numbers bytes, so its
324    // offsets would not be offsets into `source`.
325    if source.starts_with('\u{feff}') || (source.starts_with("#!") && !source.starts_with("#![")) {
326        anyhow::bail!("starts with a byte order mark or a `#!` line");
327    }
328    let file = syn::parse_file(source).context("not parseable as a Rust source file")?;
329    // A macro defined here under the name of a standard one (`macro_rules! vec`) can do
330    // anything with its arguments.
331    let local_macros = file
332        .items
333        .iter()
334        .filter_map(|item| match item {
335            syn::Item::Macro(m) => m.ident.as_ref().map(|i| i.to_string()),
336            _ => None,
337        })
338        .collect();
339    let mut finder = Finder {
340        source,
341        next_id: first_id,
342        found: Discovery::default(),
343        local_macros,
344        const_depth: 0,
345        for_ranges: std::collections::HashSet::new(),
346    };
347    finder.visit_file(&file);
348    Ok(finder.found)
349}
350
351struct Finder<'s> {
352    /// Names of the macros this file defines at its top level.
353    local_macros: Vec<String>,
354    source: &'s str,
355    next_id: u32,
356    found: Discovery,
357    /// How many `const fn` the visitor is inside of.
358    const_depth: usize,
359    /// Where the ranges start that a `for` runs through directly.
360    for_ranges: std::collections::HashSet<usize>,
361}
362
363impl Finder<'_> {
364    /// Registers the sites of a function as a whole: its result (for `bool` and
365    /// `Option<T>`), and its body replaced by each value its return type suggests.
366    fn function_sites(&mut self, sig: &syn::Signature, body: &syn::Block) {
367        if body.stmts.is_empty() {
368            return;
369        }
370        let braces = body.brace_token.span;
371        let (Some((_, start)), Some((end, _)), Some((sig_start, sig_end))) = (
372            self.range(braces.open()),
373            self.range(braces.close()),
374            self.range(sig.span()),
375        ) else {
376            return;
377        };
378        if !in_order(start, end) {
379            return;
380        }
381        let at = sig.span().start();
382        let text = self.source[sig_start..sig_end].to_string();
383        let (sole_expr, sole_plain) = match &body.stmts[..] {
384            [syn::Stmt::Expr(expr, None)] => {
385                let range = self.range(expr.span());
386                (range, range.filter(|_| does_nothing_else(expr)))
387            }
388            _ => (None, None),
389        };
390        let push = |finder: &mut Self, kind: SiteKind| {
391            finder.add(Site {
392                id: 0,
393                kind,
394                line: at.line,
395                column: at.column + 1,
396                start,
397                end,
398                text: text.clone(),
399            });
400        };
401        let name = sig.ident.to_string();
402        if let Some(option) = self.result_kind(&sig.output) {
403            let kind = SiteKind::Return {
404                name: name.clone(),
405                option,
406                sole_expr,
407            };
408            push(self, kind);
409        }
410        // Deleting the only statement of a function that returns nothing is the same
411        // mutant as an empty body.
412        let one_deletable_statement = matches!(sig.output, syn::ReturnType::Default)
413            && matches!(&body.stmts[..], [syn::Stmt::Expr(expr, Some(_))] if deletable(expr));
414        if sig.unsafety.is_some() {
415            return;
416        }
417        if one_deletable_statement {
418            self.found.single_statement_bodies.push(name);
419            return;
420        }
421        let written = sole_expr.map(|(from, to)| tokens_of(&self.source[from..to]));
422        // An iterator of another type cannot be returned beside the body's own.
423        for value in iterator_values(&sig.output) {
424            self.found.rebuild_sites.push(Site {
425                id: NO_ID,
426                kind: SiteKind::Body {
427                    name: name.clone(),
428                    value,
429                    sole_expr: sole_plain,
430                },
431                line: at.line,
432                column: at.column + 1,
433                start,
434                end,
435                text: text.clone(),
436            });
437        }
438        for value in body_values(&sig.output) {
439            if written.as_deref() != Some(tokens_of(&value).as_str()) {
440                push(
441                    self,
442                    SiteKind::Body {
443                        name: name.clone(),
444                        value,
445                        sole_expr: sole_plain,
446                    },
447                );
448            }
449        }
450    }
451
452    /// `Some(None)` for a function that returns `bool`, `Some(Some(type))` for one that
453    /// returns `Option<T>` written in a way a `let` can repeat.
454    fn result_kind(&self, output: &syn::ReturnType) -> Option<Option<String>> {
455        let syn::ReturnType::Type(_, ty) = output else {
456            return None;
457        };
458        match &**ty {
459            // `<T>::bool` and `<T as Tr>::bool` are not a single identifier either.
460            syn::Type::Path(p) if p.path.is_ident("bool") => Some(None),
461            syn::Type::Path(p)
462                if p.qself.is_none()
463                    && p.path.segments.last().is_some_and(|s| {
464                        s.ident == "Option"
465                            && matches!(s.arguments, syn::PathArguments::AngleBracketed(_))
466                    }) =>
467            {
468                match self
469                    .range(ty.span())
470                    .map(|(from, to)| &self.source[from..to])
471                {
472                    // `impl Trait` cannot be written in a `let`.
473                    Some(written) if !written.contains("impl ") => Some(Some(written.to_string())),
474                    _ => None,
475                }
476            }
477            _ => None,
478        }
479    }
480    fn range(&self, span: Span) -> Option<(usize, usize)> {
481        let range = span.byte_range();
482        // Spans produced by macro hygiene tricks or empty token streams carry no location.
483        // tmt:ignore defensive: every span of a file parsed from `source` lies inside it
484        let located = !range.is_empty() && self.source.get(range.clone()).is_some();
485        located.then_some((range.start, range.end))
486    }
487
488    fn push(&mut self, kind: SiteKind, start: usize, end: usize, span: Span) {
489        let at = span.start();
490        self.add(Site {
491            id: 0,
492            kind,
493            line: at.line,
494            column: at.column + 1,
495            start,
496            end,
497            text: self.source[start..end].to_string(),
498        });
499    }
500
501    /// The value of a `const` or `static`. The compiler computes it: like the code of a
502    /// `const fn`, it is mutated by building.
503    fn constant(&mut self, attrs: &[syn::Attribute], value: &syn::Expr) {
504        if !is_test_only(attrs) && !is_skipped(attrs) {
505            self.const_depth += 1;
506            self.visit_expr(value);
507            self.const_depth -= 1;
508        }
509    }
510
511    /// Registers a site: numbered, or among those that need a build of their own.
512    fn add(&mut self, mut site: Site) {
513        if self.const_depth > 0 {
514            site.id = NO_ID;
515            self.found.rebuild_sites.push(site);
516        } else {
517            site.id = self.next_id;
518            self.found.sites.push(site);
519            self.next_id += 1;
520        }
521    }
522}
523
524fn cmp_op(op: &syn::BinOp) -> Option<CmpOp> {
525    Some(match op {
526        syn::BinOp::Lt(_) => CmpOp::Lt,
527        syn::BinOp::Le(_) => CmpOp::Le,
528        syn::BinOp::Gt(_) => CmpOp::Gt,
529        syn::BinOp::Ge(_) => CmpOp::Ge,
530        syn::BinOp::Eq(_) => CmpOp::Eq,
531        syn::BinOp::Ne(_) => CmpOp::Ne,
532        _ => return None,
533    })
534}
535
536/// The arithmetic or bit operator, and whether it is the compound assignment form.
537fn arith_op(op: &syn::BinOp) -> Option<(ArithOp, bool)> {
538    use syn::BinOp as B;
539    Some(match op {
540        B::Add(_) => (ArithOp::Add, false),
541        B::Sub(_) => (ArithOp::Sub, false),
542        B::Mul(_) => (ArithOp::Mul, false),
543        B::Div(_) => (ArithOp::Div, false),
544        B::Rem(_) => (ArithOp::Rem, false),
545        B::BitAnd(_) => (ArithOp::BitAnd, false),
546        B::BitOr(_) => (ArithOp::BitOr, false),
547        B::BitXor(_) => (ArithOp::BitXor, false),
548        B::Shl(_) => (ArithOp::Shl, false),
549        B::Shr(_) => (ArithOp::Shr, false),
550        B::AddAssign(_) => (ArithOp::Add, true),
551        B::SubAssign(_) => (ArithOp::Sub, true),
552        B::MulAssign(_) => (ArithOp::Mul, true),
553        B::DivAssign(_) => (ArithOp::Div, true),
554        B::RemAssign(_) => (ArithOp::Rem, true),
555        B::BitAndAssign(_) => (ArithOp::BitAnd, true),
556        B::BitOrAssign(_) => (ArithOp::BitOr, true),
557        B::BitXorAssign(_) => (ArithOp::BitXor, true),
558        B::ShlAssign(_) => (ArithOp::Shl, true),
559        B::ShrAssign(_) => (ArithOp::Shr, true),
560        _ => return None,
561    })
562}
563
564/// A place whose evaluation has no effect and cannot fail: a variable, a field of one, or
565/// a dereference of one.
566///
567/// For numbers `place op= value` evaluates `value` first, for other types `place` first.
568/// The probe always takes the place first, which is the same thing only when evaluating
569/// the place cannot be observed. Indexing can panic and calls can do anything, so
570/// `v[i] += 1` and `f().x += 1` are not instrumented as operators (they can still be
571/// deleted as statements).
572fn is_plain_place(expr: &syn::Expr) -> bool {
573    match expr {
574        syn::Expr::Path(e) => e.attrs.is_empty(),
575        syn::Expr::Field(e) => is_plain_place(&e.base),
576        syn::Expr::Unary(syn::ExprUnary {
577            op: syn::UnOp::Deref(_),
578            expr,
579            ..
580        }) => is_plain_place(expr),
581        syn::Expr::Paren(e) => is_plain_place(&e.expr),
582        syn::Expr::Group(e) => is_plain_place(&e.expr),
583        _ => false,
584    }
585}
586
587fn is_literal(expr: &syn::Expr) -> bool {
588    match expr {
589        syn::Expr::Paren(e) => is_literal(&e.expr),
590        syn::Expr::Group(e) => is_literal(&e.expr),
591        syn::Expr::Lit(_) => true,
592        syn::Expr::Unary(syn::ExprUnary {
593            op: syn::UnOp::Neg(_),
594            expr,
595            ..
596        }) => is_literal(expr),
597        _ => false,
598    }
599}
600
601/// The spans of the parts of one parsed expression come in source order. The edits are
602/// built on that, so it is checked rather than assumed; no source makes it false.
603// tmt:ignore defensive: never false, so no test can make it return false
604fn in_order(earlier: usize, later: usize) -> bool {
605    earlier <= later // tmt:ignore defensive: as above
606}
607
608/// `if let P = e && cond` is a let chain, not a boolean expression: it cannot be wrapped.
609fn in_let_chain(expr: &syn::Expr) -> bool {
610    match expr {
611        syn::Expr::Let(_) => true,
612        syn::Expr::Binary(syn::ExprBinary {
613            op: syn::BinOp::And(_),
614            left,
615            right,
616            ..
617        }) => in_let_chain(left) || matches!(**right, syn::Expr::Let(_)),
618        _ => false,
619    }
620}
621
622/// Macros whose arguments are ordinary expressions separated by commas. Macros that turn
623/// their argument into text (`assert!`, `debug_assert!`, `dbg!`, `stringify!`) are left
624/// alone: rewriting the argument would change the message a test may expect.
625const EXPR_MACROS: [&str; 18] = [
626    "assert_eq",
627    "assert_ne",
628    "debug_assert_eq",
629    "debug_assert_ne",
630    "vec",
631    "format",
632    "print",
633    "println",
634    "eprint",
635    "eprintln",
636    "write",
637    "writeln",
638    "panic",
639    "unreachable",
640    "todo",
641    "unimplemented",
642    "format_args",
643    "matches",
644];
645
646fn is_assign_op(op: &syn::BinOp) -> bool {
647    use syn::BinOp::*;
648    matches!(
649        op,
650        AddAssign(_)
651            | SubAssign(_)
652            | MulAssign(_)
653            | DivAssign(_)
654            | RemAssign(_)
655            | BitXorAssign(_)
656            | BitAndAssign(_)
657            | BitOrAssign(_)
658            | ShlAssign(_)
659            | ShrAssign(_)
660    )
661}
662
663fn int_literal(expr: &syn::Expr) -> Option<i128> {
664    match expr {
665        syn::Expr::Paren(e) => int_literal(&e.expr),
666        syn::Expr::Group(e) => int_literal(&e.expr),
667        syn::Expr::Lit(syn::ExprLit {
668            lit: syn::Lit::Int(lit),
669            ..
670        }) => lit.base10_parse().ok(),
671        syn::Expr::Unary(syn::ExprUnary {
672            op: syn::UnOp::Neg(_),
673            expr,
674            ..
675        }) => int_literal(expr).and_then(i128::checked_neg),
676        _ => None,
677    }
678}
679
680/// Statements whose removal is a plausible bug: a forgotten call, check or update.
681fn deletable(expr: &syn::Expr) -> bool {
682    match expr {
683        syn::Expr::Call(e) => e.attrs.is_empty(),
684        syn::Expr::MethodCall(e) => e.attrs.is_empty(),
685        syn::Expr::Assign(e) => e.attrs.is_empty(),
686        // An attribute in front of `a += 1` belongs to `a`, never to the operation.
687        syn::Expr::Binary(e) => is_assign_op(&e.op),
688        syn::Expr::Try(e) => e.attrs.is_empty() && deletable_call(&e.expr),
689        syn::Expr::Await(e) => e.attrs.is_empty() && deletable_call(&e.base),
690        _ => false,
691    }
692}
693
694fn deletable_call(expr: &syn::Expr) -> bool {
695    match expr {
696        syn::Expr::Call(_) | syn::Expr::MethodCall(_) => true,
697        syn::Expr::Await(e) => deletable_call(&e.base),
698        _ => false,
699    }
700}
701
702fn has_ident(tokens: TokenStream, name: &str) -> bool {
703    tokens.into_iter().any(|tree| match tree {
704        TokenTree::Ident(ident) => ident == name,
705        TokenTree::Group(group) => has_ident(group.stream(), name),
706        _ => false,
707    })
708}
709
710/// The number of a site that has none.
711pub const NO_ID: u32 = u32::MAX;
712
713/// A function or constant of a file with the stretch of source it takes up, named by the
714/// modules, impls and functions around it: `Store::commit`, `<Display for Id>::fmt`.
715#[derive(Debug, PartialEq, Eq, Clone)]
716pub struct NamedItem {
717    pub start: usize,
718    pub end: usize,
719    pub name: String,
720}
721
722/// The functions and constants of a source file. A finding is told from another one on
723/// the same code by the item it is in, which stays the same when lines move.
724pub fn named_items(source: &str) -> Vec<NamedItem> {
725    struct Namer {
726        path: Vec<String>,
727        items: Vec<NamedItem>,
728    }
729    impl Namer {
730        fn inside(&mut self, name: String, span: Option<Span>, visit: impl FnOnce(&mut Self)) {
731            self.path.push(name);
732            if let Some(span) = span {
733                let range = span.byte_range();
734                self.items.push(NamedItem {
735                    start: range.start,
736                    end: range.end,
737                    name: self.path.join("::"),
738                });
739            }
740            visit(self);
741            self.path.pop();
742        }
743    }
744    impl<'ast> Visit<'ast> for Namer {
745        fn visit_item_mod(&mut self, node: &'ast syn::ItemMod) {
746            self.inside(node.ident.to_string(), None, |namer| {
747                visit::visit_item_mod(namer, node)
748            });
749        }
750        fn visit_item_trait(&mut self, node: &'ast syn::ItemTrait) {
751            self.inside(node.ident.to_string(), None, |namer| {
752                visit::visit_item_trait(namer, node)
753            });
754        }
755        fn visit_item_impl(&mut self, node: &'ast syn::ItemImpl) {
756            let of = squeezed(&node.self_ty.to_token_stream().to_string());
757            let name = match &node.trait_ {
758                Some((_, path, _)) => {
759                    format!(
760                        "<{} for {of}>",
761                        squeezed(&path.to_token_stream().to_string())
762                    )
763                }
764                None => of,
765            };
766            self.inside(name, None, |namer| visit::visit_item_impl(namer, node));
767        }
768        fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
769            self.inside(node.sig.ident.to_string(), Some(node.span()), |namer| {
770                visit::visit_item_fn(namer, node)
771            });
772        }
773        fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
774            self.inside(node.sig.ident.to_string(), Some(node.span()), |namer| {
775                visit::visit_impl_item_fn(namer, node)
776            });
777        }
778        fn visit_trait_item_fn(&mut self, node: &'ast syn::TraitItemFn) {
779            self.inside(node.sig.ident.to_string(), Some(node.span()), |namer| {
780                visit::visit_trait_item_fn(namer, node)
781            });
782        }
783        fn visit_item_const(&mut self, node: &'ast syn::ItemConst) {
784            self.inside(node.ident.to_string(), Some(node.span()), |_| {});
785        }
786        fn visit_item_static(&mut self, node: &'ast syn::ItemStatic) {
787            self.inside(node.ident.to_string(), Some(node.span()), |_| {});
788        }
789        fn visit_impl_item_const(&mut self, node: &'ast syn::ImplItemConst) {
790            self.inside(node.ident.to_string(), Some(node.span()), |_| {});
791        }
792    }
793    let Ok(file) = syn::parse_file(source) else {
794        return vec![];
795    };
796    let mut namer = Namer {
797        path: vec![],
798        items: vec![],
799    };
800    namer.visit_file(&file);
801    namer.items
802}
803
804/// The name of the innermost item that `offset` lies in; empty outside of all of them.
805pub fn enclosing_item(items: &[NamedItem], offset: usize) -> &str {
806    items
807        .iter()
808        .filter(|item| item.start <= offset && offset < item.end)
809        .min_by_key(|item| item.end - item.start)
810        .map_or("", |item| item.name.as_str())
811}
812
813/// Where the 1-based `line` and `column` (in characters) of a source text are, in bytes.
814pub fn offset_of(source: &str, line: usize, column: usize) -> Option<usize> {
815    let start: usize = source
816        .split_inclusive('\n')
817        .take(line.checked_sub(1)?)
818        .map(str::len)
819        .sum();
820    let rest = source.get(start..)?;
821    let within = rest
822        .char_indices()
823        .nth(column.checked_sub(1)?)
824        .map_or(rest.len(), |(at, _)| at);
825    Some(start + within)
826}
827
828/// A mutant as a change of the source text: `replacement` in place of `start..end`.
829#[derive(Clone, PartialEq, Eq, Debug)]
830pub struct SourceMutant {
831    pub start: usize,
832    pub end: usize,
833    pub replacement: String,
834    /// What is replaced and by what, in the words of cargo-mutants: (`<`, `==`),
835    /// (`-`, ``) for a deleted minus, (`guard`, `true`), (`body`, `0`).
836    pub what: String,
837    pub into: String,
838}
839
840/// The mutants of a site as changes of the source, for the sites that are mutated by
841/// building them. The replacements of an operator are those of cargo-mutants. Sites that
842/// only exist as probes (a result replaced after the body ran, a deleted statement, the
843/// other of `min` / `max`, the end of a range) have none.
844/// A strict/non-strict boundary replacement for runs without operand observations.
845pub(crate) fn source_boundary_mutant(site: &Site) -> Option<SourceMutant> {
846    let SiteKind::Cmp { op, gap, .. } = &site.kind else {
847        return None;
848    };
849    let replacement = match op {
850        CmpOp::Le => "<",
851        CmpOp::Ge => ">",
852        _ => return None,
853    };
854    Some(SourceMutant {
855        start: gap.0,
856        end: gap.1,
857        replacement: format!(" {replacement} "),
858        what: op.symbol().to_string(),
859        into: replacement.to_string(),
860    })
861}
862
863pub fn source_mutants(site: &Site) -> Vec<SourceMutant> {
864    let change =
865        |start: usize, end: usize, replacement: String, what: &str, into: &str| SourceMutant {
866            start,
867            end,
868            replacement,
869            what: what.to_string(),
870            into: into.to_string(),
871        };
872    // A replacement that binds otherwise than the original keeps the operands it had:
873    // `2 * 3` in `8 - 2 * 3` becomes `(2 + 3)`, and `8 - 2 * 3` becomes `(8) / (2 * 3)`.
874    let operator = |gap: &(usize, usize), from: String, to: String, binds: std::cmp::Ordering| {
875        // The operands as they are written, on either side of the operator.
876        let operands = gap
877            .0
878            .checked_sub(site.start)
879            .zip(gap.1.checked_sub(site.start))
880            .and_then(|(left, right)| {
881                Some((
882                    site.text.get(..left)?.trim_end(),
883                    site.text.get(right..)?.trim_start(),
884                ))
885            });
886        match (binds, operands) {
887            (std::cmp::Ordering::Less, Some((left, right))) => change(
888                site.start,
889                site.end,
890                format!("({left} {to} {right})"),
891                &from,
892                &to,
893            ),
894            (std::cmp::Ordering::Greater, Some((left, right))) => change(
895                site.start,
896                site.end,
897                format!("({left}) {to} ({right})"),
898                &from,
899                &to,
900            ),
901            _ => change(gap.0, gap.1, format!(" {to} "), &from, &to),
902        }
903    };
904    let same = std::cmp::Ordering::Equal;
905    match &site.kind {
906        SiteKind::Cmp { op, gap, .. } => {
907            let others: &[CmpOp] = match op {
908                CmpOp::Lt => &[CmpOp::Eq, CmpOp::Gt, CmpOp::Le],
909                CmpOp::Gt => &[CmpOp::Eq, CmpOp::Lt, CmpOp::Ge],
910                CmpOp::Le => &[CmpOp::Gt],
911                CmpOp::Ge => &[CmpOp::Lt],
912                CmpOp::Eq => &[CmpOp::Ne],
913                CmpOp::Ne => &[CmpOp::Eq],
914            };
915            others
916                .iter()
917                .map(|other| operator(gap, op.symbol().into(), other.symbol().into(), same))
918                .collect()
919        }
920        SiteKind::Logic { and, gap, .. } => {
921            // `&&` binds tighter than `||`.
922            let (from, to, binds) = if *and {
923                ("&&", "||", std::cmp::Ordering::Less)
924            } else {
925                ("||", "&&", std::cmp::Ordering::Greater)
926            };
927            vec![operator(gap, from.into(), to.into(), binds)]
928        }
929        SiteKind::Arith {
930            op, assign, gap, ..
931        } => {
932            let eq = if *assign { "=" } else { "" };
933            [Some(op.swapped()), op.second(*assign)]
934                .into_iter()
935                .flatten()
936                .map(|other| {
937                    operator(
938                        gap,
939                        format!("{}{eq}", op.symbol()),
940                        format!("{}{eq}", other.symbol()),
941                        // An assignment has nothing around it and its operands to itself.
942                        if *assign {
943                            same
944                        } else {
945                            other.binding().cmp(&op.binding())
946                        },
947                    )
948                })
949                .collect()
950        }
951        SiteKind::Not { bang, .. } => vec![change(bang.0, bang.1, String::new(), "!", "")],
952        SiteKind::Neg { minus, .. } => vec![change(minus.0, minus.1, String::new(), "-", "")],
953        SiteKind::Body { value, .. } => {
954            vec![change(
955                site.start,
956                site.end,
957                format!(" {value} "),
958                "body",
959                value,
960            )]
961        }
962        // An arm whose guard is `false` is an arm that is not there.
963        SiteKind::Arm { pattern, guard } => vec![match guard {
964            ArmGuard::None(arrow) => change(*arrow, *arrow, "if false ".into(), "arm", pattern),
965            ArmGuard::Existing(from, to) => change(*from, *to, "false".into(), "arm", pattern),
966        }],
967        SiteKind::Guard { can_be_false } => [true, false]
968            .into_iter()
969            .filter(|value| *value || *can_be_false)
970            .map(|value| {
971                change(
972                    site.start,
973                    site.end,
974                    value.to_string(),
975                    "guard",
976                    &value.to_string(),
977                )
978            })
979            .collect(),
980        SiteKind::Field {
981            name,
982            shorthand,
983            from_base,
984        } => {
985            let prefix = if *shorthand {
986                format!("{name}: ")
987            } else {
988                String::new()
989            };
990            vec![change(
991                site.start,
992                site.end,
993                format!("{prefix}{from_base}"),
994                "field",
995                name,
996            )]
997        }
998        // The end taken in or left out: the two dots and the `=` are all that changes.
999        SiteKind::Range { inclusive, gap, .. } => {
1000            let (from, to) = if *inclusive {
1001                ("..=", "..")
1002            } else {
1003                ("..", "..=")
1004            };
1005            vec![change(gap.0, gap.1, to.to_string(), from, to)]
1006        }
1007        SiteKind::Return { .. } | SiteKind::MinMax { .. } | SiteKind::Stmt => vec![],
1008    }
1009}
1010
1011/// The iterators to return in place of the body of a function that returns
1012/// `impl Iterator<Item = T>`: an empty one, and one of each value of `T`.
1013pub fn iterator_values(output: &syn::ReturnType) -> Vec<String> {
1014    let syn::ReturnType::Type(_, ty) = output else {
1015        return vec![];
1016    };
1017    let syn::Type::ImplTrait(opaque) = &**ty else {
1018        return vec![];
1019    };
1020    let item = opaque.bounds.iter().find_map(|bound| {
1021        let syn::TypeParamBound::Trait(bound) = bound else {
1022            return None;
1023        };
1024        let last = bound.path.segments.last()?;
1025        let syn::PathArguments::AngleBracketed(list) = &last.arguments else {
1026            return None;
1027        };
1028        (last.ident == "Iterator").then_some(())?;
1029        list.args.iter().find_map(|arg| match arg {
1030            syn::GenericArgument::AssocType(item) if item.ident == "Item" => Some(&item.ty),
1031            _ => None,
1032        })
1033    });
1034    let Some(item) = item else {
1035        return vec![];
1036    };
1037    if has_ident(item.to_token_stream(), "impl") {
1038        return vec!["::core::iter::empty()".to_string()];
1039    }
1040    let mut values = vec!["::core::iter::empty()".to_string()];
1041    values.extend(
1042        values_of(item)
1043            .iter()
1044            .map(|value| format!("::core::iter::once({value})")),
1045    );
1046    values
1047}
1048
1049/// Text without its white space.
1050fn squeezed(text: &str) -> String {
1051    text.chars().filter(|c| !c.is_whitespace()).collect()
1052}
1053
1054/// The tokens of an expression, to compare two ways of writing it: the white space
1055/// between them does not count, the one inside a literal does (`" "` is not `""`).
1056fn tokens_of(text: &str) -> String {
1057    match text.parse::<TokenStream>() {
1058        Ok(tokens) => tokens.to_string(),
1059        Err(_) => text.to_string(),
1060    }
1061}
1062
1063/// Whether evaluating the expression does nothing but give its value, as far as the
1064/// source says: operators on a user's type can do anything, which is not assumed.
1065fn does_nothing_else(expr: &syn::Expr) -> bool {
1066    struct Effects(bool);
1067    impl<'ast> Visit<'ast> for Effects {
1068        fn visit_expr(&mut self, expr: &'ast syn::Expr) {
1069            match expr {
1070                syn::Expr::Binary(_)
1071                | syn::Expr::Unary(_)
1072                | syn::Expr::Paren(_)
1073                | syn::Expr::Group(_)
1074                | syn::Expr::Path(_)
1075                | syn::Expr::Lit(_)
1076                | syn::Expr::Field(_)
1077                | syn::Expr::Reference(_)
1078                | syn::Expr::Cast(_)
1079                | syn::Expr::Tuple(_) => syn::visit::visit_expr(self, expr),
1080                _ => self.0 = true,
1081            }
1082        }
1083        fn visit_bin_op(&mut self, op: &'ast syn::BinOp) {
1084            use syn::BinOp::*;
1085            if !matches!(
1086                op,
1087                Add(_)
1088                    | Sub(_)
1089                    | Mul(_)
1090                    | Div(_)
1091                    | Rem(_)
1092                    | And(_)
1093                    | Or(_)
1094                    | BitXor(_)
1095                    | BitAnd(_)
1096                    | BitOr(_)
1097                    | Shl(_)
1098                    | Shr(_)
1099                    | Eq(_)
1100                    | Lt(_)
1101                    | Le(_)
1102                    | Ne(_)
1103                    | Ge(_)
1104                    | Gt(_)
1105            ) {
1106                self.0 = true; // an assignment
1107            }
1108        }
1109    }
1110    let mut effects = Effects(false);
1111    effects.visit_expr(expr);
1112    !effects.0
1113}
1114
1115/// The values to replace a function's body with, by its return type. The table is that
1116/// of cargo-mutants (https://mutants.rs/mutants.html), applied to the type as written.
1117pub fn body_values(output: &syn::ReturnType) -> Vec<String> {
1118    match output {
1119        syn::ReturnType::Default => vec!["()".to_string()],
1120        syn::ReturnType::Type(_, ty) => {
1121            // What an `impl Trait` stands for is the type of the body: no other value
1122            // can be returned beside it.
1123            if has_ident(ty.to_token_stream(), "impl") {
1124                return vec![];
1125            }
1126            values_of(ty)
1127        }
1128    }
1129}
1130
1131fn product(parts: &[Vec<String>]) -> Vec<Vec<String>> {
1132    parts.iter().fold(vec![vec![]], |rows, part| {
1133        rows.iter()
1134            .flat_map(|row| {
1135                part.iter().map(move |value| {
1136                    let mut row = row.clone();
1137                    row.push(value.clone());
1138                    row
1139                })
1140            })
1141            .collect()
1142    })
1143}
1144
1145fn values_of(ty: &syn::Type) -> Vec<String> {
1146    let each = |inner: &syn::Type, wrap: &dyn Fn(&str) -> String| -> Vec<String> {
1147        values_of(inner).iter().map(|v| wrap(v)).collect()
1148    };
1149    match ty {
1150        syn::Type::Paren(t) => values_of(&t.elem),
1151        syn::Type::Group(t) => values_of(&t.elem),
1152        syn::Type::Never(_) => vec![],
1153        // Also the empty one: one row of no values, written `()`.
1154        syn::Type::Tuple(t) => {
1155            let parts: Vec<Vec<String>> = t.elems.iter().map(values_of).collect();
1156            product(&parts)
1157                .into_iter()
1158                .map(|row| match &row[..] {
1159                    [one] => format!("({one},)"),
1160                    _ => format!("({})", row.join(", ")),
1161                })
1162                .collect()
1163        }
1164        syn::Type::Array(t) => {
1165            let len = t.len.to_token_stream().to_string();
1166            each(&t.elem, &|v| format!("[{v}; {len}]"))
1167        }
1168        syn::Type::Reference(t) => match &*t.elem {
1169            syn::Type::Path(p) if p.path.is_ident("str") && t.mutability.is_none() => {
1170                vec!["\"\"".to_string(), "\"xyzzy\"".to_string()]
1171            }
1172            syn::Type::Slice(slice) => {
1173                let mut values = vec!["Vec::leak(Vec::new())".to_string()];
1174                values.extend(each(&slice.elem, &|v| format!("Vec::leak(vec![{v}])")));
1175                values
1176            }
1177            inner => each(inner, &|v| format!("Box::leak(Box::new({v}))")),
1178        },
1179        syn::Type::Path(p) if p.qself.is_none() => {
1180            let Some(last) = p.path.segments.last() else {
1181                return vec!["Default::default()".to_string()];
1182            };
1183            // The type as written, without its generic arguments: `std::rc::Rc`.
1184            let mut bare = p.path.clone();
1185            if let Some(segment) = bare.segments.last_mut() {
1186                segment.arguments = syn::PathArguments::None;
1187            }
1188            let bare = squeezed(&bare.to_token_stream().to_string());
1189            let arguments: Vec<&syn::Type> = match &last.arguments {
1190                syn::PathArguments::AngleBracketed(list) => list
1191                    .args
1192                    .iter()
1193                    .filter_map(|arg| match arg {
1194                        syn::GenericArgument::Type(ty) => Some(ty),
1195                        _ => None,
1196                    })
1197                    .collect(),
1198                _ => vec![],
1199            };
1200            let name = last.ident.to_string();
1201            let texts = |list: &[&str]| list.iter().map(|v| v.to_string()).collect::<Vec<_>>();
1202            let one = |text: String| "1.try_into().unwrap()".replace('1', &text);
1203            match (name.as_str(), &arguments[..]) {
1204                ("bool", []) => texts(&["true", "false"]),
1205                ("i8" | "i16" | "i32" | "i64" | "i128" | "isize", []) => texts(&["0", "1", "-1"]),
1206                ("u8" | "u16" | "u32" | "u64" | "u128" | "usize", []) => texts(&["0", "1"]),
1207                ("f32" | "f64", []) => texts(&["0.0", "1.0", "-1.0"]),
1208                (
1209                    "NonZeroI8" | "NonZeroI16" | "NonZeroI32" | "NonZeroI64" | "NonZeroI128"
1210                    | "NonZeroIsize",
1211                    [],
1212                ) => vec![one("1".into()), one("(-1)".into())],
1213                (
1214                    "NonZeroU8" | "NonZeroU16" | "NonZeroU32" | "NonZeroU64" | "NonZeroU128"
1215                    | "NonZeroUsize",
1216                    [],
1217                ) => vec![one("1".into())],
1218                ("NonZero", [inner]) => {
1219                    let unsigned = squeezed(&inner.to_token_stream().to_string()).starts_with('u');
1220                    let mut values = vec![one("1".into())];
1221                    if !unsigned {
1222                        values.push(one("(-1)".into()));
1223                    }
1224                    values
1225                }
1226                ("String", []) => texts(&["String::new()", "\"xyzzy\".into()"]),
1227                ("Result", [ok, ..]) => each(ok, &|v| format!("Ok({v})")),
1228                // `fmt::Result`, or an alias of the crate's own.
1229                ("Result", []) => vec!["Ok(Default::default())".to_string()],
1230                ("Option", [inner]) => {
1231                    let mut values = vec!["None".to_string()];
1232                    values.extend(each(inner, &|v| format!("Some({v})")));
1233                    values
1234                }
1235                ("Vec", [inner]) => {
1236                    let mut values = vec!["vec![]".to_string()];
1237                    values.extend(each(inner, &|v| format!("vec![{v}]")));
1238                    values
1239                }
1240                ("Box" | "Rc" | "Arc" | "Cell" | "RefCell" | "Mutex", [inner]) => {
1241                    each(inner, &|v| format!("{bare}::new({v})"))
1242                }
1243                ("BinaryHeap" | "BTreeSet" | "HashSet" | "LinkedList" | "VecDeque", [inner]) => {
1244                    let mut values = vec![format!("{bare}::new()")];
1245                    values.extend(each(inner, &|v| format!("{bare}::from_iter([{v}])")));
1246                    values
1247                }
1248                ("BTreeMap" | "HashMap", [key, value]) => {
1249                    let mut values = vec![format!("{bare}::new()")];
1250                    values.extend(
1251                        product(&[values_of(key), values_of(value)])
1252                            .into_iter()
1253                            .map(|row| format!("{bare}::from_iter([({})])", row.join(", "))),
1254                    );
1255                    values
1256                }
1257                ("Cow", [inner]) => {
1258                    let borrowed: syn::Type = syn::parse_quote!(&#inner);
1259                    values_of(&borrowed)
1260                        .iter()
1261                        .flat_map(|v| {
1262                            [
1263                                format!("{bare}::Borrowed({v})"),
1264                                format!("{bare}::Owned({v}.to_owned())"),
1265                            ]
1266                        })
1267                        .collect()
1268                }
1269                ("HttpResponse", []) => vec![format!("{bare}::Ok().finish()")],
1270                _ => vec!["Default::default()".to_string()],
1271            }
1272        }
1273        _ => vec!["Default::default()".to_string()],
1274    }
1275}
1276
1277/// `#[mutants::skip]`, also inside `cfg_attr`: the mark cargo-mutants uses for code that
1278/// is not to be mutated.
1279fn is_skipped(attrs: &[syn::Attribute]) -> bool {
1280    attrs
1281        .iter()
1282        .any(|attr| squeezed(&attr.meta.to_token_stream().to_string()).contains("mutants::skip"))
1283}
1284
1285/// `#[test]`, `#[tokio::test]`, `#[cfg(test)]`, `#[cfg(all(test, ...))]`; not `#[cfg(not(test))]`.
1286fn is_test_only(attrs: &[syn::Attribute]) -> bool {
1287    attrs.iter().any(|attr| {
1288        let path = attr.path();
1289        if path.segments.last().is_some_and(|s| s.ident == "test") {
1290            return true;
1291        }
1292        if !path.is_ident("cfg") {
1293            return false;
1294        }
1295        let syn::Meta::List(list) = &attr.meta else {
1296            return false;
1297        };
1298        has_ident(list.tokens.clone(), "test") && !has_ident(list.tokens.clone(), "not")
1299    })
1300}
1301
1302impl<'ast> Visit<'ast> for Finder<'_> {
1303    // Nothing in these can call a non-const function or is worth mutating.
1304    fn visit_attribute(&mut self, _: &'ast syn::Attribute) {}
1305    fn visit_type(&mut self, _: &'ast syn::Type) {}
1306    fn visit_pat(&mut self, _: &'ast syn::Pat) {}
1307    fn visit_generics(&mut self, _: &'ast syn::Generics) {}
1308    fn visit_generic_argument(&mut self, _: &'ast syn::GenericArgument) {}
1309    fn visit_variant(&mut self, _: &'ast syn::Variant) {}
1310    fn visit_item_const(&mut self, node: &'ast syn::ItemConst) {
1311        self.constant(&node.attrs, &node.expr);
1312    }
1313    fn visit_item_static(&mut self, node: &'ast syn::ItemStatic) {
1314        self.constant(&node.attrs, &node.expr);
1315    }
1316    fn visit_impl_item_const(&mut self, node: &'ast syn::ImplItemConst) {
1317        self.constant(&node.attrs, &node.expr);
1318    }
1319    fn visit_trait_item_const(&mut self, node: &'ast syn::TraitItemConst) {
1320        if let Some((_, value)) = &node.default {
1321            self.constant(&node.attrs, value);
1322        }
1323    }
1324    fn visit_expr_const(&mut self, _: &'ast syn::ExprConst) {}
1325
1326    fn visit_macro(&mut self, node: &'ast syn::Macro) {
1327        let Some(name) = node.path.segments.last().map(|s| s.ident.to_string()) else {
1328            return;
1329        };
1330        if !EXPR_MACROS.contains(&name.as_str()) || self.local_macros.contains(&name) {
1331            return;
1332        }
1333        if name == "matches" {
1334            // matches!(expr, pattern): only the scrutinee is an expression.
1335            let scrutinee = node.parse_body_with(|input: syn::parse::ParseStream| {
1336                let expr: syn::Expr = input.parse()?;
1337                input.parse::<proc_macro2::TokenStream>()?;
1338                Ok(expr)
1339            });
1340            if let Ok(expr) = scrutinee {
1341                self.visit_expr(&expr);
1342            }
1343            return;
1344        }
1345        type Args = syn::punctuated::Punctuated<syn::Expr, syn::Token![,]>;
1346        // `vec![x; n]`, named format arguments with odd syntax and the like do not parse
1347        // as a plain argument list: skipped.
1348        if let Ok(args) = node.parse_body_with(Args::parse_terminated) {
1349            for arg in &args {
1350                // `name = value` in a format string parses as an assignment; nothing
1351                // treats it as one here, and only its value holds sites.
1352                self.visit_expr(arg);
1353            }
1354        }
1355    }
1356
1357    fn visit_expr_repeat(&mut self, node: &'ast syn::ExprRepeat) {
1358        self.visit_expr(&node.expr); // the length is a const expression
1359    }
1360
1361    fn visit_item_mod(&mut self, node: &'ast syn::ItemMod) {
1362        // The file of a module that is not analysed is left alone as a whole.
1363        if is_test_only(&node.attrs) || is_skipped(&node.attrs) {
1364            if node.content.is_none() {
1365                let path = node.attrs.iter().find_map(|attr| match &attr.meta {
1366                    syn::Meta::NameValue(nv) if nv.path.is_ident("path") => match &nv.value {
1367                        syn::Expr::Lit(syn::ExprLit {
1368                            lit: syn::Lit::Str(s),
1369                            ..
1370                        }) => Some(s.value()),
1371                        _ => None,
1372                    },
1373                    _ => None,
1374                });
1375                self.found.test_modules.push(TestModule {
1376                    name: node.ident.to_string(),
1377                    path,
1378                });
1379            }
1380            return;
1381        }
1382        visit::visit_item_mod(self, node);
1383    }
1384
1385    fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
1386        if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1387            // Nothing in a `const fn` can ask at run time which mutant is on.
1388            let constant = node.sig.constness.is_some() as usize;
1389            self.const_depth += constant;
1390            self.function_sites(&node.sig, &node.block);
1391            visit::visit_item_fn(self, node);
1392            self.const_depth -= constant;
1393        }
1394    }
1395
1396    fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
1397        if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1398            // Nothing in a `const fn` can ask at run time which mutant is on.
1399            let constant = node.sig.constness.is_some() as usize;
1400            self.const_depth += constant;
1401            self.function_sites(&node.sig, &node.block);
1402            visit::visit_impl_item_fn(self, node);
1403            self.const_depth -= constant;
1404        }
1405    }
1406
1407    fn visit_trait_item_fn(&mut self, node: &'ast syn::TraitItemFn) {
1408        if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1409            let constant = node.sig.constness.is_some() as usize;
1410            self.const_depth += constant;
1411            if let Some(body) = &node.default {
1412                self.function_sites(&node.sig, body);
1413            }
1414            visit::visit_trait_item_fn(self, node);
1415            self.const_depth -= constant;
1416        }
1417    }
1418
1419    fn visit_item_impl(&mut self, node: &'ast syn::ItemImpl) {
1420        if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1421            visit::visit_item_impl(self, node);
1422        }
1423    }
1424
1425    fn visit_expr_closure(&mut self, node: &'ast syn::ExprClosure) {
1426        if node.constness.is_none() {
1427            visit::visit_expr_closure(self, node);
1428        }
1429    }
1430
1431    fn visit_block(&mut self, node: &'ast syn::Block) {
1432        for stmt in &node.stmts {
1433            if let syn::Stmt::Expr(expr, Some(semi)) = stmt
1434                && deletable(expr)
1435                && let (Some((start, _)), Some((_, end))) =
1436                    (self.range(expr.span()), self.range(semi.span()))
1437                && in_order(start, end)
1438            {
1439                self.push(SiteKind::Stmt, start, end, expr.span());
1440            }
1441        }
1442        visit::visit_block(self, node);
1443    }
1444
1445    fn visit_expr_method_call(&mut self, node: &'ast syn::ExprMethodCall) {
1446        let name = node.method.to_string();
1447        if (name == "max" || name == "min")
1448            && node.args.len() == 1
1449            && node.turbofish.is_none()
1450            && node.attrs.is_empty()
1451            && let (
1452                Some((start, receiver_end)),
1453                Some((argument_start, argument_end)),
1454                Some((_, end)),
1455            ) = (
1456                self.range(node.receiver.span()),
1457                self.range(node.args[0].span()),
1458                self.range(node.paren_token.span.close()),
1459            )
1460            && in_order(receiver_end, argument_start)
1461            && in_order(argument_end, end)
1462        {
1463            let kind = SiteKind::MinMax {
1464                max: name == "max",
1465                receiver: self.source[start..receiver_end].to_string(),
1466                argument: self.source[argument_start..argument_end].to_string(),
1467                call: (receiver_end, argument_start),
1468                close: (argument_end, end),
1469            };
1470            self.push(kind, start, end, node.receiver.span());
1471        }
1472        visit::visit_expr_method_call(self, node);
1473    }
1474
1475    fn visit_expr_for_loop(&mut self, node: &'ast syn::ExprForLoop) {
1476        let mut over = &*node.expr;
1477        while let syn::Expr::Paren(syn::ExprParen { expr, .. })
1478        | syn::Expr::Group(syn::ExprGroup { expr, .. }) = over
1479        {
1480            over = expr;
1481        }
1482        if let syn::Expr::Range(syn::ExprRange {
1483            start: Some(from), ..
1484        }) = over
1485            && let Some((start, _)) = self.range(from.span())
1486        {
1487            self.for_ranges.insert(start);
1488        }
1489        visit::visit_expr_for_loop(self, node);
1490    }
1491
1492    fn visit_expr_range(&mut self, node: &'ast syn::ExprRange) {
1493        // With two literals nothing fixes the integer type before the probe is resolved,
1494        // and it would be taken for `i32` (`for i in 0..16 { words[i] }`).
1495        if let (Some(from), Some(to)) = (&node.start, &node.end)
1496            && node.attrs.is_empty()
1497            && let (Some((start, lhs_end)), Some((rhs_start, end))) =
1498                (self.range(from.span()), self.range(to.span()))
1499            && in_order(lhs_end, rhs_start)
1500        {
1501            let kind = SiteKind::Range {
1502                inclusive: matches!(node.limits, syn::RangeLimits::Closed(_)),
1503                lhs: self.source[start..lhs_end].to_string(),
1504                rhs: self.source[rhs_start..end].to_string(),
1505                gap: (lhs_end, rhs_start),
1506            };
1507            // `a..b + 1` in place of `a..=b` gives a `for` the same numbers, and that is
1508            // all a `for` takes from its range. Anywhere else the two are told apart (by
1509            // their type, by `end_bound`, by a field): there the mutant is the range as it
1510            // is written in the source, and it is built like the code of a `const fn`.
1511            // So is a range of two literals, wherever it is: nothing fixes their type
1512            // before a probe is resolved, and it would be taken for `i32`.
1513            let built = !self.for_ranges.contains(&start) || (is_literal(from) && is_literal(to));
1514            self.const_depth += built as usize;
1515            self.push(kind, start, end, from.span());
1516            self.const_depth -= built as usize;
1517        }
1518        visit::visit_expr_range(self, node);
1519    }
1520
1521    fn visit_expr_match(&mut self, node: &'ast syn::ExprMatch) {
1522        // A binding or `_` takes everything: with such a last arm the match stays
1523        // exhaustive when an arm above it stops matching.
1524        let catches_all = |arm: &syn::Arm| {
1525            arm.guard.is_none()
1526                && match &arm.pat {
1527                    syn::Pat::Wild(_) => true,
1528                    syn::Pat::Ident(p) => {
1529                        p.subpat.is_none()
1530                            && p.ident
1531                                .to_string()
1532                                .starts_with(|c: char| c.is_lowercase() || c == '_')
1533                    }
1534                    _ => false,
1535                }
1536        };
1537        // Where the arms that can be removed start.
1538        let mut removable: Vec<usize> = vec![];
1539        if let Some((last, others)) = node.arms.split_last()
1540            && catches_all(last)
1541        {
1542            for arm in others
1543                .iter()
1544                .filter(|arm| arm.attrs.is_empty() && !catches_all(arm))
1545            {
1546                let (Some((start, pat_end)), Some((_, end)), Some((arrow, _))) = (
1547                    self.range(arm.pat.span()),
1548                    self.range(arm.body.span()),
1549                    self.range(arm.fat_arrow_token.span()),
1550                ) else {
1551                    continue;
1552                };
1553                let guard = match &arm.guard {
1554                    None => ArmGuard::None(arrow),
1555                    Some((_, expr)) => match self.range(expr.span()) {
1556                        Some((from, to)) => ArmGuard::Existing(from, to),
1557                        None => continue,
1558                    },
1559                };
1560                let pattern = match guard {
1561                    ArmGuard::Existing(from, to) => {
1562                        format!(
1563                            "{} if {}",
1564                            &self.source[start..pat_end],
1565                            &self.source[from..to]
1566                        )
1567                    }
1568                    ArmGuard::None(_) => self.source[start..pat_end].to_string(),
1569                };
1570                let at = arm.pat.span().start();
1571                removable.push(start);
1572                self.add(Site {
1573                    id: 0,
1574                    kind: SiteKind::Arm {
1575                        pattern: pattern.clone(),
1576                        guard,
1577                    },
1578                    line: at.line,
1579                    column: at.column + 1,
1580                    start,
1581                    end,
1582                    text: format!("{pattern} => .."),
1583                });
1584            }
1585        }
1586        // Any guard can be `true` or `false` instead: a guarded arm never counts for
1587        // the match being exhaustive. A `let` in a guard binds names for the arm.
1588        for arm in node.arms.iter().filter(|arm| arm.attrs.is_empty()) {
1589            if let Some((_, guard)) = &arm.guard
1590                && !matches!(**guard, syn::Expr::Let(_))
1591                && !in_let_chain(guard)
1592                && let (Some((start, end)), Some((pattern, _))) =
1593                    (self.range(guard.span()), self.range(arm.pat.span()))
1594            {
1595                let kind = SiteKind::Guard {
1596                    can_be_false: !removable.contains(&pattern),
1597                };
1598                self.push(kind, start, end, guard.span());
1599            }
1600        }
1601        visit::visit_expr_match(self, node);
1602    }
1603
1604    fn visit_expr_struct(&mut self, node: &'ast syn::ExprStruct) {
1605        // The base is read a second time by the mutant, so it has to be something that
1606        // can be: a place, or a call without arguments (`Default::default()`).
1607        let from_base = node.rest.as_deref().and_then(|base| {
1608            let (from, to) = self.range(base.span())?;
1609            let written = &self.source[from..to];
1610            match base {
1611                base if is_plain_place(base) => Some(format!("({written})")),
1612                syn::Expr::Call(call)
1613                    if call.args.is_empty() && matches!(*call.func, syn::Expr::Path(_)) =>
1614                {
1615                    let (from, to) = self.range(node.path.span())?;
1616                    Some(format!("({} {{ ..{written} }})", &self.source[from..to]))
1617                }
1618                _ => None,
1619            }
1620        });
1621        if let Some(from_base) = from_base
1622            && node.attrs.is_empty()
1623            && node.qself.is_none()
1624        {
1625            for field in node.fields.iter().filter(|field| field.attrs.is_empty()) {
1626                let name = match &field.member {
1627                    syn::Member::Named(ident) => ident.to_string(),
1628                    syn::Member::Unnamed(index) => index.index.to_string(),
1629                };
1630                let (Some((start, _)), Some((_, end))) = (
1631                    self.range(field.member.span()),
1632                    self.range(field.expr.span()),
1633                ) else {
1634                    continue;
1635                };
1636                let Some((value, _)) = self.range(field.expr.span()) else {
1637                    continue;
1638                };
1639                let shorthand = field.colon_token.is_none();
1640                let kind = SiteKind::Field {
1641                    from_base: format!("{from_base}.{name}"),
1642                    name,
1643                    shorthand,
1644                };
1645                let at = field.member.span().start();
1646                self.add(Site {
1647                    id: 0,
1648                    kind,
1649                    line: at.line,
1650                    column: at.column + 1,
1651                    // The probe goes around the value; the report shows the whole field.
1652                    start: value,
1653                    end,
1654                    text: self.source[start..end].to_string(),
1655                });
1656            }
1657        }
1658        visit::visit_expr_struct(self, node);
1659    }
1660
1661    fn visit_expr_unary(&mut self, node: &'ast syn::ExprUnary) {
1662        if let syn::UnOp::Not(bang) = &node.op
1663            && node.attrs.is_empty()
1664            && let (Some((start, _)), Some((operand_start, end))) =
1665                (self.range(bang.span()), self.range(node.expr.span()))
1666            && in_order(start, operand_start)
1667        {
1668            let kind = SiteKind::Not {
1669                bang: (start, operand_start),
1670                operand: self.source[operand_start..end].to_string(),
1671            };
1672            self.push(kind, start, end, bang.span());
1673        }
1674        if let syn::UnOp::Neg(minus) = &node.op
1675            && node.attrs.is_empty()
1676            && let (Some((start, _)), Some((operand_start, end))) =
1677                (self.range(minus.span()), self.range(node.expr.span()))
1678            && in_order(start, operand_start)
1679        {
1680            let zero = match &*node.expr {
1681                syn::Expr::Lit(syn::ExprLit {
1682                    lit: syn::Lit::Int(lit),
1683                    ..
1684                }) => lit.base10_parse::<u128>().is_ok_and(|v| v == 0),
1685                // Not a float: `-0.0` is not `0.0` (`1.0 / -0.0` is minus infinity).
1686                _ => false,
1687            };
1688            if !zero {
1689                let kind = SiteKind::Neg {
1690                    minus: (start, operand_start),
1691                    operand: self.source[operand_start..end].to_string(),
1692                    literal: matches!(*node.expr, syn::Expr::Lit(_)),
1693                };
1694                self.push(kind, start, end, minus.span());
1695            }
1696        }
1697        visit::visit_expr_unary(self, node);
1698    }
1699
1700    fn visit_expr_binary(&mut self, node: &'ast syn::ExprBinary) {
1701        if let Some(op) = cmp_op(&node.op)
1702            && node.attrs.is_empty()
1703            && let (Some((start, lhs_end)), Some((rhs_start, end))) =
1704                (self.range(node.left.span()), self.range(node.right.span()))
1705            && in_order(lhs_end, rhs_start)
1706        {
1707            let literal = match (int_literal(&node.left), int_literal(&node.right)) {
1708                (None, Some(k)) => LiteralSide::Rhs(k),
1709                (Some(k), None) => LiteralSide::Lhs(k),
1710                _ => LiteralSide::None,
1711            };
1712            let kind = SiteKind::Cmp {
1713                op,
1714                lhs: self.source[start..lhs_end].to_string(),
1715                rhs: self.source[rhs_start..end].to_string(),
1716                literal,
1717                gap: (lhs_end, rhs_start),
1718            };
1719            self.push(kind, start, end, node.left.span());
1720        } else if node.attrs.is_empty()
1721            && let (Some((start, lhs_end)), Some((rhs_start, end))) =
1722                (self.range(node.left.span()), self.range(node.right.span()))
1723            && in_order(lhs_end, rhs_start)
1724        {
1725            let lhs = self.source[start..lhs_end].to_string();
1726            let rhs = self.source[rhs_start..end].to_string();
1727            let gap = (lhs_end, rhs_start);
1728            let logic = match &node.op {
1729                syn::BinOp::And(_) => Some(true),
1730                syn::BinOp::Or(_) => Some(false),
1731                _ => None,
1732            };
1733            if let Some(and) = logic {
1734                if !in_let_chain(&node.left) && !matches!(*node.right, syn::Expr::Let(_)) {
1735                    self.push(
1736                        SiteKind::Logic { and, lhs, rhs, gap },
1737                        start,
1738                        end,
1739                        node.left.span(),
1740                    );
1741                }
1742            } else if let Some((op, assign)) = arith_op(&node.op) {
1743                let kind = SiteKind::Arith {
1744                    op,
1745                    assign,
1746                    lhs,
1747                    rhs,
1748                    gap,
1749                };
1750                // Two literals have no type until the context gives them one, and a
1751                // probe is a context of its own.
1752                let literals = is_literal(&node.left) && is_literal(&node.right);
1753                if !literals && (!assign || is_plain_place(&node.left)) {
1754                    self.push(kind, start, end, node.left.span());
1755                } else {
1756                    // Which of the place and the value is evaluated first depends on
1757                    // the type, which a probe would have to know.
1758                    let at = node.left.span().start();
1759                    self.found.rebuild_sites.push(Site {
1760                        id: NO_ID,
1761                        kind,
1762                        line: at.line,
1763                        column: at.column + 1,
1764                        start,
1765                        end,
1766                        text: self.source[start..end].to_string(),
1767                    });
1768                }
1769            }
1770        }
1771        visit::visit_expr_binary(self, node);
1772    }
1773}
1774
1775/// Instrumented text plus the mapping back to the original, used to blame a site for a
1776/// compile error in the rewritten file.
1777#[derive(Debug, PartialEq)]
1778pub struct Rendered {
1779    pub text: String,
1780    /// `(output offset, original offset, length)` of each stretch copied from the original,
1781    /// in output order.
1782    segments: Vec<(usize, usize, usize)>,
1783    /// `(output offset, length, site)` of each piece of text a probe added, in output order.
1784    inserted: Vec<(usize, usize, u32)>,
1785}
1786
1787impl Rendered {
1788    /// Maps a byte offset in the instrumented text to the original. Offsets inside inserted
1789    /// text map to the point of insertion.
1790    /// The site whose probe text contains the byte at `offset` of the instrumented text.
1791    pub fn inserted_by(&self, offset: usize) -> Option<u32> {
1792        let idx = self.inserted.partition_point(|(out, _, _)| *out <= offset);
1793        let (out, len, site) = self.inserted[idx.checked_sub(1)?];
1794        (offset - out < len).then_some(site)
1795    }
1796
1797    pub fn to_original(&self, offset: usize) -> usize {
1798        let idx = self.segments.partition_point(|(out, _, _)| *out <= offset);
1799        let Some((out, orig, len)) = idx.checked_sub(1).map(|i| self.segments[i]) else {
1800            return 0;
1801        };
1802        // Past the end of the copied stretch is inserted text, which sits at its end.
1803        orig + (offset - out).min(len)
1804    }
1805}
1806
1807struct Edit {
1808    pos: usize,
1809    end: usize,
1810    /// 0: closes a site, 1: replaces an operator, 2: opens a site.
1811    phase: u8,
1812    /// Closers: innermost first. Openers: outermost first.
1813    order: i64,
1814    text: String,
1815    /// The site the text belongs to.
1816    site: u32,
1817}
1818
1819/// Rewrites `source` with probes for the sites that `enabled` accepts.
1820pub fn render(source: &str, sites: &[Site], enabled: &dyn Fn(u32) -> bool) -> Rendered {
1821    let rt = format!("crate::{RUNTIME_MOD}");
1822    let mut edits = vec![];
1823    for site in sites.iter().filter(|s| enabled(s.id)) {
1824        // Edits at one position are ordered by the length of their site, doubled to leave
1825        // room: a site that wraps a whole expression goes around a site of that very
1826        // expression (`if a > b` as a guard and as a comparison).
1827        let wraps = matches!(
1828            site.kind,
1829            SiteKind::Return { .. }
1830                | SiteKind::Body { .. }
1831                | SiteKind::Guard { .. }
1832                | SiteKind::Field { .. }
1833        );
1834        // tmt:ignore `2 +` orders the same: nothing longer starts or ends where a wrapping site does
1835        let len = 2 * (site.end - site.start) as i64 + wraps as i64;
1836        let (open, close) = match &site.kind {
1837            SiteKind::Cmp { op, gap, .. } => {
1838                let func = if op.is_ordering() { "ord" } else { "eq" };
1839                edits.push(Edit {
1840                    pos: gap.0,
1841                    end: gap.1,
1842                    phase: 1,
1843                    order: 0,
1844                    text: "), &(".into(),
1845                    site: site.id,
1846                });
1847                (
1848                    "(match (&(".to_string(),
1849                    format!(
1850                        ")) {{ (__tmt_l, __tmt_r) => {{ #[allow(unused_imports)] use {rt}::{{ValAny as _, ValNum as _}}; \
1851                         {rt}::{func}({id}u32, {code}u8, __tmt_l, __tmt_r, (&{rt}::W(__tmt_l)).tmt_val(), (&{rt}::W(__tmt_r)).tmt_val()) }} }})",
1852                        id = site.id,
1853                        code = op.code(),
1854                    ),
1855                )
1856            }
1857            // In the probes below the user's operands are evaluated where no name the probe
1858            // introduces is in scope: in the scrutinee of a `match`, in the initialiser of a
1859            // `let`, or in an arm that binds nothing. A scrutinee keeps its temporaries
1860            // until the end of the enclosing statement, as an arithmetic operator does.
1861            SiteKind::Logic { and, gap, .. } => {
1862                // The right operand stays in place, so it is evaluated exactly when the
1863                // (possibly mutated) left operand asks for it.
1864                let id = site.id;
1865                edits.push(Edit {
1866                    pos: gap.0,
1867                    end: gap.1,
1868                    phase: 1,
1869                    order: 0,
1870                    text: format!("); __tmt_c }} {{ 2u8 => {rt}::rhs({id}u32, {and}, "),
1871                    site: site.id,
1872                });
1873                (
1874                    // Each operand of `&&` / `||` drops its temporaries when it is done.
1875                    // The `let` ends the left operand's; the arm ends the right one's.
1876                    format!("(match {{ let __tmt_c: u8 = {rt}::lhs({id}u32, {and}, "),
1877                    "), __tmt_c => __tmt_c == 1u8 })".to_string(),
1878                )
1879            }
1880            SiteKind::Arith {
1881                op, assign, gap, ..
1882            } => {
1883                // A compound assignment hands the probe the place to update.
1884                let (holder, lhs_open, lhs_close) = if *assign {
1885                    ("Aa", "&mut (", ")")
1886                } else {
1887                    ("Ar", "", "")
1888                };
1889                edits.push(Edit {
1890                    pos: gap.0,
1891                    end: gap.1,
1892                    phase: 1,
1893                    order: 0,
1894                    text: format!("{lhs_close}, "),
1895                    site: site.id,
1896                });
1897                (
1898                    format!("(match ({lhs_open}"),
1899                    format!(
1900                        ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{{any} as _, {prim} as _}}; \
1901                         (&{rt}::{holder}::new(__tmt_a, __tmt_b)).{method}({id}u32) }} }})",
1902                        any = op.fallback_trait(*assign),
1903                        prim = op.prim_trait(*assign),
1904                        method = op.method(*assign),
1905                        id = site.id,
1906                    ),
1907                )
1908            }
1909            SiteKind::Not { bang, .. } => {
1910                // Drop the `!`; the probe applies it (or not).
1911                edits.push(Edit {
1912                    pos: bang.0,
1913                    end: bang.1,
1914                    phase: 1,
1915                    order: 0,
1916                    text: String::new(),
1917                    site: site.id,
1918                });
1919                (
1920                    "(match (".to_string(),
1921                    format!(
1922                        ") {{ __tmt_a => {{ #[allow(unused_imports)] use {rt}::{{AnyNot as _, NotPrim as _}}; \
1923                         (&{rt}::Un::new(__tmt_a)).tmt_not({}u32) }} }})",
1924                        site.id
1925                    ),
1926                )
1927            }
1928            SiteKind::Return { option, .. } => match option {
1929                None => (
1930                    " let __tmt_v: bool = {".to_string(),
1931                    format!("}}; {rt}::ret({}u32, __tmt_v) ", site.id),
1932                ),
1933                Some(ty) => (
1934                    format!(" let __tmt_v: {ty} = {{"),
1935                    format!("}}; {rt}::ret_opt({}u32, __tmt_v) ", site.id),
1936                ),
1937            },
1938            SiteKind::MinMax {
1939                max, call, close, ..
1940            } => {
1941                // The receiver is borrowed, as a method call borrows it: a `max` that takes
1942                // `&self` leaves it where it is, and one that takes it by value copies it
1943                // out (or, for a type that cannot be copied, does not compile: no probe).
1944                edits.push(Edit {
1945                    pos: call.0,
1946                    end: call.1,
1947                    phase: 1,
1948                    order: 0,
1949                    text: "), ".into(),
1950                    site: site.id,
1951                });
1952                // The call's own `)` (and a trailing comma) is replaced by the probe.
1953                // The call is made as it was written, on the same operands; the probe only
1954                // decides which of the two it is.
1955                let (same, other) = if *max { ("max", "min") } else { ("min", "max") };
1956                edits.push(Edit {
1957                    pos: close.0,
1958                    end: close.1,
1959                    phase: 1,
1960                    order: 0,
1961                    text: format!(
1962                        ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{AnyMinMax as _, MinMaxPrim as _}}; \
1963                         if (&{rt}::Mm(__tmt_a, &__tmt_b)).tmt_other({}u32) {{ (*__tmt_a).{other}(__tmt_b) }} else {{ (*__tmt_a).{same}(__tmt_b) }} }} }})",
1964                        site.id
1965                    ),
1966                    site: site.id,
1967                });
1968                ("(match (&(".to_string(), String::new())
1969            }
1970            SiteKind::Range { inclusive, gap, .. } => {
1971                edits.push(Edit {
1972                    pos: gap.0,
1973                    end: gap.1,
1974                    phase: 1,
1975                    order: 0,
1976                    text: ", ".into(),
1977                    site: site.id,
1978                });
1979                let method = if *inclusive {
1980                    "tmt_range_inclusive"
1981                } else {
1982                    "tmt_range"
1983                };
1984                (
1985                    "(match (".to_string(),
1986                    format!(
1987                        ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{AnyRange as _, RangePrim as _}}; \
1988                         (&{rt}::Ar::new(__tmt_a, __tmt_b)).{method}({}u32) }} }})",
1989                        site.id
1990                    ),
1991                )
1992            }
1993            SiteKind::Arm { guard, .. } => {
1994                // The probe goes into the arm's guard, where it runs only when the
1995                // pattern matched.
1996                match guard {
1997                    ArmGuard::None(arrow) => edits.push(Edit {
1998                        pos: *arrow,
1999                        end: *arrow,
2000                        phase: 2,
2001                        order: 0,
2002                        text: format!("if {rt}::arm({}u32) ", site.id),
2003                        site: site.id,
2004                    }),
2005                    ArmGuard::Existing(from, to) => {
2006                        let wider = 2 * (to - from + 1) as i64;
2007                        edits.push(Edit {
2008                            pos: *from,
2009                            end: *from,
2010                            phase: 2,
2011                            order: -wider,
2012                            text: format!("{rt}::arm({}u32) && (", site.id),
2013                            site: site.id,
2014                        });
2015                        edits.push(Edit {
2016                            pos: *to,
2017                            end: *to,
2018                            phase: 0,
2019                            order: wider,
2020                            text: ")".into(),
2021                            site: site.id,
2022                        });
2023                    }
2024                }
2025                (String::new(), String::new())
2026            }
2027            SiteKind::Stmt => (
2028                format!("if {rt}::live({}u32) {{ ", site.id),
2029                " }".to_string(),
2030            ),
2031            // A literal takes its type from where it stands, so it stays where it is.
2032            SiteKind::Neg {
2033                operand,
2034                literal: true,
2035                ..
2036            } => (
2037                format!("(if {rt}::live({}u32) {{ ", site.id),
2038                format!(" }} else {{ {operand} }})"),
2039            ),
2040            SiteKind::Neg { minus, .. } => {
2041                edits.push(Edit {
2042                    pos: minus.0,
2043                    end: minus.1,
2044                    phase: 1,
2045                    order: 0,
2046                    text: String::new(),
2047                    site: site.id,
2048                });
2049                (
2050                    "(match (".to_string(),
2051                    format!(
2052                        ") {{ __tmt_a => if {rt}::live({}u32) {{ -__tmt_a }} else {{ __tmt_a }} }})",
2053                        site.id
2054                    ),
2055                )
2056            }
2057            SiteKind::Guard { .. } => (format!("{rt}::ret({}u32, ", site.id), ")".to_string()),
2058            SiteKind::Field {
2059                name,
2060                shorthand,
2061                from_base,
2062            } => (
2063                format!(
2064                    "{}if {rt}::live({}u32) {{ ",
2065                    if *shorthand {
2066                        format!("{name}: ")
2067                    } else {
2068                        String::new()
2069                    },
2070                    site.id
2071                ),
2072                format!(" }} else {{ {from_base} }}"),
2073            ),
2074            SiteKind::Body { value, .. } => (
2075                format!(" if !{rt}::live({}u32) {{ return {value}; }}", site.id),
2076                String::new(),
2077            ),
2078        };
2079        edits.push(Edit {
2080            pos: site.start,
2081            end: site.start,
2082            phase: 2,
2083            order: -len,
2084            text: open,
2085            site: site.id,
2086        });
2087        edits.push(Edit {
2088            pos: site.end,
2089            end: site.end,
2090            phase: 0,
2091            order: len,
2092            text: close,
2093            site: site.id,
2094        });
2095    }
2096    edits.sort_by_key(|e| (e.pos, e.phase, e.order));
2097
2098    // tmt:ignore the capacity is a hint: any number gives the same text
2099    let capacity = source.len() + edits.iter().map(|e| e.text.len()).sum::<usize>();
2100    let mut text = String::with_capacity(capacity);
2101    let mut segments = vec![];
2102    let mut inserted = vec![];
2103    let mut cursor = 0;
2104    for edit in edits {
2105        // Also when nothing lies between two edits: text inserted right after a replaced
2106        // stretch then maps to where it was inserted, not to where the stretch began.
2107        if edit.pos >= cursor {
2108            segments.push((text.len(), cursor, edit.pos - cursor));
2109            text.push_str(&source[cursor..edit.pos]);
2110        }
2111        inserted.push((text.len(), edit.text.len(), edit.site));
2112        text.push_str(&edit.text);
2113        cursor = cursor.max(edit.end);
2114    }
2115    segments.push((text.len(), cursor, source.len() - cursor));
2116    text.push_str(&source[cursor..]);
2117    Rendered {
2118        text,
2119        segments,
2120        inserted,
2121    }
2122}
2123
2124/// The sites to blame for a compile error at `offset` (original coordinates): the smallest
2125/// enabled sites that contain it.
2126pub fn blame(sites: &[Site], enabled: &dyn Fn(u32) -> bool, offset: usize) -> Vec<u32> {
2127    // A replaced body is blamed for what is wrong in its own text only (`inserted_by`):
2128    // by position it would answer for everything in the function.
2129    let containing = || {
2130        sites.iter().filter(|s| {
2131            enabled(s.id)
2132                && s.start <= offset
2133                && offset <= s.end
2134                && !matches!(s.kind, SiteKind::Body { .. })
2135        })
2136    };
2137    let Some(smallest) = containing().map(|s| s.end - s.start).min() else {
2138        return vec![];
2139    };
2140    containing()
2141        .filter(|s| s.end - s.start == smallest)
2142        .map(|s| s.id)
2143        .collect()
2144}
2145
2146#[cfg(test)]
2147mod tests {
2148    use super::*;
2149
2150    fn all(_: u32) -> bool {
2151        true
2152    }
2153
2154    /// The sites of `src` without the function-level `Return` sites, numbered from
2155    /// `first_id`: most tests are about one expression inside a small function.
2156    fn found(src: &str, first_id: u32) -> Result<Discovery> {
2157        let mut all = discover(src, 0)?;
2158        all.sites
2159            .retain(|s| !matches!(s.kind, SiteKind::Return { .. } | SiteKind::Body { .. }));
2160        for (index, site) in all.sites.iter_mut().enumerate() {
2161            site.id = first_id + index as u32;
2162        }
2163        Ok(all)
2164    }
2165
2166    #[test]
2167    fn finds_a_comparison_with_a_literal() {
2168        let src = "pub fn is_eligible(age: u32) -> bool {\n    age >= 18\n}\n";
2169        let found = found(src, 5).unwrap();
2170        assert_eq!(found.sites.len(), 1);
2171        let site = &found.sites[0];
2172        assert_eq!(
2173            (site.id, site.line, site.column, site.text.as_str()),
2174            (5, 2, 5, "age >= 18")
2175        );
2176        let SiteKind::Cmp {
2177            op,
2178            lhs,
2179            rhs,
2180            literal,
2181            ..
2182        } = &site.kind
2183        else {
2184            panic!()
2185        };
2186        assert_eq!(
2187            (*op, lhs.as_str(), rhs.as_str(), *literal),
2188            (CmpOp::Ge, "age", "18", LiteralSide::Rhs(18))
2189        );
2190    }
2191
2192    #[test]
2193    fn literal_sides() {
2194        let src =
2195            "fn f(x: i32, y: i32) { let _ = (-5 < x, x == (3), 1 < 2, x <= y, x > 1.5 as i32); }";
2196        let literals: Vec<LiteralSide> = found(src, 0)
2197            .unwrap()
2198            .sites
2199            .iter()
2200            .filter_map(|s| match &s.kind {
2201                SiteKind::Cmp { literal, .. } => Some(*literal),
2202                SiteKind::Neg { .. } => None,
2203                _ => panic!(),
2204            })
2205            .collect();
2206        assert_eq!(
2207            literals,
2208            [
2209                LiteralSide::Lhs(-5),
2210                LiteralSide::Rhs(3),
2211                LiteralSide::None,
2212                LiteralSide::None,
2213                LiteralSide::None
2214            ]
2215        );
2216    }
2217
2218    #[test]
2219    fn renders_a_comparison_probe() {
2220        let src = "fn f(a: u8) -> bool { a  >=  18 }";
2221        let sites = found(src, 3).unwrap().sites;
2222        let out = render(src, &sites, &all);
2223        assert_eq!(
2224            out.text,
2225            "fn f(a: u8) -> bool { (match (&(a), &(18)) { (__tmt_l, __tmt_r) => { #[allow(unused_imports)] \
2226             use crate::__tmt_rt::{ValAny as _, ValNum as _}; crate::__tmt_rt::ord(3u32, 3u8, __tmt_l, __tmt_r, \
2227             (&crate::__tmt_rt::W(__tmt_l)).tmt_val(), (&crate::__tmt_rt::W(__tmt_r)).tmt_val()) } }) }"
2228        );
2229        assert_eq!(render(src, &sites, &|_| false).text, src);
2230    }
2231
2232    #[test]
2233    fn renders_statement_guards_and_nested_sites() {
2234        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}";
2235        let sites = found(src, 0).unwrap().sites;
2236        let kinds: Vec<&str> = sites.iter().map(|s| s.text.as_str()).collect();
2237        assert_eq!(
2238            kinds,
2239            [
2240                "check((a < 3) == true)?;",
2241                "v.push(a);",
2242                "v.clear();",
2243                "(a < 3) == true",
2244                "a < 3"
2245            ]
2246        );
2247        let out = render(src, &sites, &all);
2248        assert_eq!(
2249            out.text.lines().count(),
2250            src.lines().count(),
2251            "line numbers are preserved"
2252        );
2253        assert!(
2254            out.text
2255                .contains("if crate::__tmt_rt::live(0u32) { check((match (&(((match (&(a), &(3))"),
2256            "{}",
2257            out.text
2258        );
2259        assert!(out.text.contains("if crate::__tmt_rt::live(1u32) { v.push(a); }if crate::__tmt_rt::live(2u32) { v.clear(); }"), "{}", out.text);
2260        syn::parse_file(&out.text).expect("instrumented source parses");
2261
2262        // Only the inner comparison enabled.
2263        let inner = render(src, &sites, &|id| id == 4);
2264        assert!(
2265            inner.text.contains("check(((match (&(a), &(3))"),
2266            "{}",
2267            inner.text
2268        );
2269        assert!(inner.text.contains(") == true)?;"), "{}", inner.text);
2270        syn::parse_file(&inner.text).unwrap();
2271    }
2272
2273    #[test]
2274    fn skips_tests_const_contexts_and_macros() {
2275        let src = r#"
2276            const LIMIT: bool = 1 < 2;
2277            static S: bool = 3 > 2;
2278            const fn c(a: u8) -> bool { a < 1 }
2279            fn arr(a: u8) -> [u8; { 2 > 1 } as usize] { let _ = [0u8; (4 > 3) as usize]; assert!(a < 9); [a; 1] }
2280            enum E { A = (5 > 4) as isize }
2281            struct T;
2282            impl T { const K: bool = 6 < 7; const fn k(a: u8) -> bool { a > 6 } }
2283            #[cfg(test)]
2284            mod tests { fn t(a: u8) -> bool { a == 1 } }
2285            #[cfg(test)]
2286            mod more_tests;
2287            #[cfg(test)]
2288            #[doc = "not a path"]
2289            mod documented;
2290            #[cfg(test)]
2291            #[path = "support/helpers.rs"]
2292            mod helpers;
2293            #[cfg(all(test, feature = "x"))]
2294            fn helper(a: u8) -> bool { a != 1 }
2295            #[test]
2296            fn a_test() { let a = 1; if a == 2 { panic!() } }
2297            #[tokio::test]
2298            async fn async_test() { let a = 1; if a == 3 { panic!() } }
2299            #[cfg(not(test))]
2300            fn real(a: u8) -> bool { a == 100 }
2301            #[cfg(feature = "test-utils")]
2302            fn also_real(a: u8) -> bool { a == 101 }
2303            fn pat(a: u8) -> bool { matches!(a, 1..=2) || match a { 0..=9 => a == 102, _ => false } }
2304        "#;
2305        let found = found(src, 0).unwrap();
2306        let texts: Vec<&str> = found.sites.iter().map(|s| s.text.as_str()).collect();
2307        assert_eq!(
2308            texts,
2309            [
2310                "a == 100",
2311                "a == 101",
2312                "matches!(a, 1..=2) || match a { 0..=9 => a == 102, _ => false }",
2313                "0..=9 => ..",
2314                "a == 102"
2315            ]
2316        );
2317        assert_eq!(
2318            found.test_modules,
2319            [
2320                TestModule {
2321                    name: "more_tests".into(),
2322                    path: None
2323                },
2324                TestModule {
2325                    name: "documented".into(),
2326                    path: None
2327                },
2328                TestModule {
2329                    name: "helpers".into(),
2330                    path: Some("support/helpers.rs".into())
2331                },
2332            ]
2333        );
2334    }
2335
2336    #[test]
2337    fn deletable_statements() {
2338        let src = r#"
2339            async fn f(s: &mut S) -> Result<(), E> {
2340                s.validate()?;
2341                s.total += 1;
2342                s.flag = true;
2343                helper(s);
2344                s.flush().await?;
2345                s.sync().await;
2346                let x = s.get();
2347                println!("{x}");
2348                if x > 0 { return Ok(()); }
2349                s.done()
2350            }
2351        "#;
2352        let texts: Vec<String> = found(src, 0)
2353            .unwrap()
2354            .sites
2355            .into_iter()
2356            .filter(|s| s.kind == SiteKind::Stmt)
2357            .map(|s| s.text)
2358            .collect();
2359        assert_eq!(
2360            texts,
2361            [
2362                "s.validate()?;",
2363                "s.total += 1;",
2364                "s.flag = true;",
2365                "helper(s);",
2366                "s.flush().await?;",
2367                "s.sync().await;"
2368            ]
2369        );
2370    }
2371
2372    #[test]
2373    fn maps_offsets_back_and_blames_the_innermost_site() {
2374        let src = "fn f(a: u8, b: u8) -> bool { g(a < b); a > 1 }";
2375        let sites = found(src, 0).unwrap().sites;
2376        let out = render(src, &sites, &all);
2377        // Every original character keeps its identity through the mapping.
2378        for (orig, ch) in src.char_indices().filter(|(_, c)| c.is_alphanumeric()) {
2379            let hits: Vec<usize> = out
2380                .text
2381                .char_indices()
2382                .filter(|(o, c)| *c == ch && out.to_original(*o) == orig)
2383                .map(|(o, _)| o)
2384                .collect();
2385            assert!(
2386                !hits.is_empty(),
2387                "original offset {orig} ({ch}) is unreachable"
2388            );
2389        }
2390        // An error inside the probe of `a < b` blames it, not the enclosing statement.
2391        let probe = out.text.find("ord(1u32").unwrap();
2392        let orig = out.to_original(probe);
2393        assert_eq!(blame(&sites, &all, orig), [1]);
2394        // With the inner site disabled, the statement is next.
2395        assert_eq!(blame(&sites, &|id| id != 1, orig), [0]);
2396        assert_eq!(
2397            blame(&sites, &all, src.find("fn").unwrap()),
2398            Vec::<u32>::new()
2399        );
2400        assert_eq!(out.to_original(0), 0);
2401        assert_eq!(out.to_original(out.text.len()), src.len());
2402    }
2403
2404    #[test]
2405    fn blame_is_inclusive_at_both_ends() {
2406        let src = "fn f(a: u8) -> bool { a > 1 }";
2407        let sites = found(src, 0).unwrap().sites;
2408        let (start, end) = (sites[0].start, sites[0].end);
2409        assert_eq!(blame(&sites, &all, start - 1), Vec::<u32>::new());
2410        assert_eq!(blame(&sites, &all, start), [0]);
2411        assert_eq!(blame(&sites, &all, end), [0]);
2412        assert_eq!(blame(&sites, &all, end + 1), Vec::<u32>::new());
2413        // The probe opens before the first original character and closes after the last.
2414        let out = render(src, &sites, &all);
2415        assert_eq!(out.to_original(out.text.find("(match").unwrap()), start);
2416        assert_eq!(
2417            out.to_original(out.text.find("tmt_val()) } })").unwrap()),
2418            end
2419        );
2420        assert_eq!(
2421            out.to_original(out.text.find("), &(").unwrap() + 2),
2422            sites[0].start + 1
2423        );
2424    }
2425
2426    #[test]
2427    fn finds_sites_in_impls_and_array_elements() {
2428        let src = r#"
2429            struct T(u8);
2430            impl T { fn small(&self) -> bool { self.0 < 3 } }
2431            #[cfg(test)]
2432            impl T { fn only_in_tests(&self) -> bool { self.0 < 4 } }
2433            trait Tr { fn provided(&self, a: u8) -> bool { a < 5 } }
2434            fn arr(a: u8) -> [bool; 2] { [a < 6; 2] }
2435            fn closure(a: u8) -> bool { (|| a < 7)() }
2436        "#;
2437        let texts: Vec<String> = found(src, 0)
2438            .unwrap()
2439            .sites
2440            .into_iter()
2441            .map(|s| s.text)
2442            .collect();
2443        assert_eq!(texts, ["self.0 < 3", "a < 5", "a < 6", "a < 7"]);
2444    }
2445
2446    #[test]
2447    fn logic_and_arithmetic_sites() {
2448        let src = "fn f(a: bool, b: bool, x: u32, y: u32) -> u32 { if a && b || !a { x + y * 2 } else { x - 1 % y } }";
2449        let found = found(src, 0).unwrap().sites;
2450        let kinds: Vec<String> = found
2451            .iter()
2452            .map(|s| match &s.kind {
2453                SiteKind::Logic { and, lhs, rhs, .. } => format!("logic and={and} [{lhs}] [{rhs}]"),
2454                SiteKind::Arith { op, lhs, rhs, .. } => {
2455                    format!("arith {} [{lhs}] [{rhs}]", op.symbol())
2456                }
2457                SiteKind::Not { operand, .. } => format!("not [{operand}]"),
2458                other => format!("{other:?}"),
2459            })
2460            .collect();
2461        assert_eq!(
2462            kinds,
2463            [
2464                "logic and=false [a && b] [!a]",
2465                "logic and=true [a] [b]",
2466                "not [a]",
2467                "arith + [x] [y * 2]",
2468                "arith * [y] [2]",
2469                "arith - [x] [1 % y]",
2470                "arith % [1] [y]",
2471            ]
2472        );
2473        let out = render(src, &found, &all).text;
2474        syn::parse_file(&out).expect("instrumented source parses");
2475        assert!(
2476            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 })"),
2477            "{out}"
2478        );
2479        assert!(
2480            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) } })"),
2481            "{out}"
2482        );
2483        // Every probe the renderer can emit exists in the runtime under that name.
2484        for op in ArithOp::ALL {
2485            assert_ne!(op.swapped(), op);
2486            for assign in [false, true] {
2487                let method = op.method(assign);
2488                let fallback = format!("{} {method} ", op.fallback_trait(assign));
2489                assert!(
2490                    crate::RUNTIME_SOURCE.contains(&format!("fn {method}(")),
2491                    "{method}"
2492                );
2493                assert!(crate::RUNTIME_SOURCE.contains(&fallback), "{fallback}");
2494                assert!(
2495                    crate::RUNTIME_SOURCE.contains(&format!("trait {} ", op.prim_trait(assign))),
2496                    "{op:?}"
2497                );
2498            }
2499        }
2500    }
2501
2502    #[test]
2503    fn let_chains_and_literal_arithmetic_are_left_alone() {
2504        let src = r#"
2505            fn f(o: Option<u8>, a: bool, n: u32) -> u32 {
2506                if let Some(x) = o && a && x > 1 { return 1; }
2507                let k = 60 * 60;
2508                (n & 3) | (n << 1) ^ k
2509            }
2510        "#;
2511        let texts: Vec<String> = found(src, 0)
2512            .unwrap()
2513            .sites
2514            .into_iter()
2515            .map(|s| s.text)
2516            .collect();
2517        assert_eq!(
2518            texts,
2519            [
2520                "x > 1",
2521                "(n & 3) | (n << 1) ^ k",
2522                "n & 3",
2523                "(n << 1) ^ k",
2524                "n << 1"
2525            ]
2526        );
2527    }
2528
2529    #[test]
2530    fn attributes_const_methods_and_let_on_the_right() {
2531        let src = r#"
2532            struct T(u8);
2533            impl T {
2534                const fn in_const(&self) -> bool { self.0 < 1 }
2535                #[test]
2536                fn test_method(&self) -> bool { self.0 < 2 }
2537                fn real(&self) -> bool { self.0 < 3 }
2538            }
2539            trait Tr {
2540                #[cfg(test)]
2541                fn only_in_tests(&self, a: u8) -> bool { a < 4 }
2542            }
2543            fn f(s: &mut S, o: Option<u8>, a: bool) -> Result<(), E> {
2544                #[cfg(feature = "x")]
2545                s.guarded();
2546                #[allow(unused)]
2547                s.total += 1;
2548                #[allow(unused)]
2549                s.check()?;
2550                #[allow(unused)]
2551                s.sync().await;
2552                s.plain();
2553                if a && let Some(v) = o { s.use_it(v); }
2554                Ok(())
2555            }
2556        "#;
2557        let texts: Vec<String> = found(src, 0)
2558            .unwrap()
2559            .sites
2560            .into_iter()
2561            .map(|s| s.text)
2562            .collect();
2563        // syn attaches the attribute of `#[a] x += 1;` to the left operand, so that statement
2564        // is guarded together with its attribute; the guard is valid around it either way.
2565        assert_eq!(
2566            texts,
2567            [
2568                "self.0 < 3",
2569                "#[allow(unused)]\n                s.total += 1;",
2570                "s.plain();",
2571                "#[allow(unused)]\n                s.total += 1",
2572                "s.use_it(v);"
2573            ]
2574        );
2575        let found = found(src, 0).unwrap().sites;
2576        syn::parse_file(&render(src, &found, &all).text).expect("instrumented source parses");
2577    }
2578
2579    #[test]
2580    fn compound_assignment_negation_and_bit_operators() {
2581        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 }";
2582        let sites = found(src, 0).unwrap().sites;
2583        let kinds: Vec<String> = sites
2584            .iter()
2585            .map(|s| match &s.kind {
2586                SiteKind::Arith {
2587                    op,
2588                    assign,
2589                    lhs,
2590                    rhs,
2591                    ..
2592                } => format!(
2593                    "{lhs} {}{} {rhs}",
2594                    op.symbol(),
2595                    if *assign { "=" } else { "" }
2596                ),
2597                SiteKind::Not { operand, .. } => format!("!{operand}"),
2598                SiteKind::Stmt => "stmt".to_string(),
2599                other => format!("{other:?}"),
2600            })
2601            .collect();
2602        assert_eq!(
2603            kinds,
2604            [
2605                "stmt",
2606                "stmt",
2607                "*total += n",
2608                "*total <<= 1",
2609                "!ok",
2610                "!n",
2611                "!m",
2612                "n & 7"
2613            ]
2614        );
2615        let out = render(src, &sites, &all).text;
2616        syn::parse_file(&out).expect("instrumented source parses");
2617        for expected in [
2618            "(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) } });",
2619            "use crate::__tmt_rt::{AnyShlAssign as _, BitAssignPrim as _}; (&crate::__tmt_rt::Aa::new(__tmt_a, __tmt_b)).tmt_shl_assign(3u32) } });",
2620            "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) } }) {",
2621            "(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) } })",
2622        ] {
2623            assert!(out.contains(expected), "missing {expected}\nin {out}");
2624        }
2625        // `!a && b`: the negation and the conjunction start at the same character.
2626        let nested = "fn f(a: bool, b: bool) -> bool { !a && b }";
2627        let sites = found(nested, 0).unwrap().sites;
2628        let out = render(nested, &sites, &all).text;
2629        syn::parse_file(&out).expect("instrumented source parses");
2630        assert!(
2631            out.contains("(match { let __tmt_c: u8 = crate::__tmt_rt::lhs(0u32, true, (match (a) { __tmt_a => {"),
2632            "{out}"
2633        );
2634        // Names the probes introduce are never in scope where user code runs.
2635        let capture = "fn f(a: bool, __tmt_c: u8, __tmt_a: u8) -> bool { a && __tmt_c == 2 && __tmt_a + 1 > 0 }";
2636        let sites = found(capture, 0).unwrap().sites;
2637        let out = render(capture, &sites, &all).text;
2638        syn::parse_file(&out).expect("instrumented source parses");
2639        // The arms that bind a probe variable contain only probe code.
2640        for arm in out.split("__tmt_c => ").skip(1) {
2641            assert!(arm.starts_with("__tmt_c == 1u8 })"), "{arm}");
2642        }
2643        for arm in out.split("(__tmt_a, __tmt_b) => ").skip(1) {
2644            assert!(
2645                arm.starts_with("{ #[allow(unused_imports)] use crate::__tmt_rt::"),
2646                "{arm}"
2647            );
2648        }
2649    }
2650
2651    #[test]
2652    fn compound_assignment_is_probed_only_on_plain_places() {
2653        let src = r#"
2654            fn f(s: &mut S, v: &mut [u32], p: &mut u32, i: usize) {
2655                let mut local = 0u32;
2656                local += 1;
2657                s.count += 1;
2658                s.inner.total -= 2;
2659                *p *= 3;
2660                (*p) += 4;
2661                v[i] += 5;
2662                v[next()] += 6;
2663                s.get_mut().x += 7;
2664                *s.slot() += 8;
2665            }
2666        "#;
2667        let probed: Vec<String> = found(src, 0)
2668            .unwrap()
2669            .sites
2670            .into_iter()
2671            .filter(|s| matches!(s.kind, SiteKind::Arith { assign: true, .. }))
2672            .map(|s| s.text)
2673            .collect();
2674        assert_eq!(
2675            probed,
2676            [
2677                "local += 1",
2678                "s.count += 1",
2679                "s.inner.total -= 2",
2680                "*p *= 3",
2681                "(*p) += 4"
2682            ]
2683        );
2684        // The others are still statements that can be deleted.
2685        let deletable = found(src, 0)
2686            .unwrap()
2687            .sites
2688            .iter()
2689            .filter(|s| s.kind == SiteKind::Stmt)
2690            .count();
2691        assert_eq!(deletable, 9);
2692    }
2693
2694    #[test]
2695    fn bool_functions_are_return_sites() {
2696        let src = r#"
2697            pub fn is_ok(a: u8) -> bool { let b = a; b > 1 }
2698            fn count(a: u8) -> u8 { a }
2699            fn unit(a: u8) { let _ = a; }
2700            const fn in_const(a: u8) -> bool { a > 2 }
2701            #[test]
2702            fn a_test() -> bool { true }
2703            struct T;
2704            impl T { fn method(&self) -> bool { true } }
2705            trait Tr { fn required(&self) -> bool; fn provided(&self) -> bool { false } }
2706            fn boxed() -> Box<bool> { Box::new(true) }
2707            fn qualified() -> core::primitive::bool { true }
2708        "#;
2709        let sites = discover(src, 0).unwrap().sites;
2710        let returns: Vec<(&str, &str, usize)> = sites
2711            .iter()
2712            .filter_map(|s| match &s.kind {
2713                SiteKind::Return {
2714                    name, option: None, ..
2715                } => Some((name.as_str(), s.text.as_str(), s.line)),
2716                _ => None,
2717            })
2718            .collect();
2719        assert_eq!(
2720            returns,
2721            [
2722                ("is_ok", "fn is_ok(a: u8) -> bool", 2),
2723                ("method", "fn method(&self) -> bool", 9),
2724                ("provided", "fn provided(&self) -> bool", 10),
2725            ]
2726        );
2727        let out = render(src, &sites, &all).text;
2728        syn::parse_file(&out).expect("instrumented source parses");
2729        assert!(
2730            out.contains(
2731                "pub fn is_ok(a: u8) -> bool { let __tmt_v: bool = { \
2732                 if !crate::__tmt_rt::live(1u32) { return true; } \
2733                 if !crate::__tmt_rt::live(2u32) { return false; } let b = a; (match"
2734            ),
2735            "{out}"
2736        );
2737        assert!(
2738            out.contains("}) }; crate::__tmt_rt::ret(0u32, __tmt_v) }"),
2739            "{out}"
2740        );
2741        assert_eq!(
2742            out.lines().count(),
2743            src.lines().count(),
2744            "line numbers are preserved"
2745        );
2746        // A compile error in the wrapper is blamed on the function's site.
2747        let rendered = render(src, &sites, &all);
2748        let wrapper = rendered.text.find("ret(0u32").unwrap();
2749        assert_eq!(rendered.inserted_by(wrapper), Some(0));
2750        // And one in a replaced body on that replacement alone: by position they are
2751        // all the same place.
2752        let replaced = rendered.text.find("return false; } let b").unwrap();
2753        assert_eq!(rendered.inserted_by(replaced), Some(2));
2754        assert_eq!(blame(&sites, &all, rendered.to_original(replaced)), [0]);
2755    }
2756
2757    #[test]
2758    fn ids_are_consecutive_across_every_kind_of_site() {
2759        let src = r#"
2760            fn a(x: u8) -> bool { x > 1 }
2761            fn b(x: u8) -> bool { !(x > 2) && !!flag(x) }
2762            fn c(s: &mut S) { s.n += 1; s.go(); }
2763        "#;
2764        let sites = discover(src, 10).unwrap().sites;
2765        let ids: Vec<u32> = sites.iter().map(|s| s.id).collect();
2766        assert_eq!(ids, (10..10 + sites.len() as u32).collect::<Vec<_>>());
2767        let texts: Vec<&str> = sites
2768            .iter()
2769            .filter(|s| !matches!(s.kind, SiteKind::Body { .. }))
2770            .map(|s| s.text.as_str())
2771            .collect();
2772        assert_eq!(
2773            texts,
2774            [
2775                "fn a(x: u8) -> bool",
2776                "x > 1",
2777                "fn b(x: u8) -> bool",
2778                "!(x > 2) && !!flag(x)",
2779                "!(x > 2)",
2780                "x > 2",
2781                "!!flag(x)",
2782                "!flag(x)",
2783                "s.n += 1;",
2784                "s.go();",
2785                "s.n += 1",
2786            ]
2787        );
2788        syn::parse_file(&render(src, &sites, &all).text).expect("instrumented source parses");
2789    }
2790
2791    #[test]
2792    fn only_calls_and_assignments_are_deletable() {
2793        let src = r#"
2794            async fn f(s: &mut S, v: Vec<u8>) -> Result<(), E> {
2795                s.field;
2796                v[0];
2797                (s.a, s.b);
2798                s.value?;
2799                s.future.await;
2800                s.x = 1;
2801                s.x -= 1;
2802                s.x == 1;
2803                s.call().await?;
2804                Ok(())
2805            }
2806        "#;
2807        let texts: Vec<String> = found(src, 0)
2808            .unwrap()
2809            .sites
2810            .into_iter()
2811            .filter(|s| s.kind == SiteKind::Stmt)
2812            .map(|s| s.text)
2813            .collect();
2814        assert_eq!(texts, ["s.x = 1;", "s.x -= 1;", "s.call().await?;"]);
2815    }
2816
2817    #[test]
2818    fn ranges_match_arms_min_max_and_option_results() {
2819        let src = r#"
2820            fn find(v: &[u32], limit: u32) -> Option<u32> {
2821                for i in 0..v.len() {
2822                    let capped = v[i].min(limit).max(1);
2823                    match capped {
2824                        0 => return None,
2825                        n if n > 5 => return Some(n),
2826                        1..=3 => continue,
2827                        other => { let _ = other; }
2828                    }
2829                }
2830                let _ = &v[1..=2];
2831                for _ in 1..=limit as usize {}
2832                let _ = 'a'..'z';
2833                let _ = v.iter().max();
2834                None
2835            }
2836            fn exhaustive(k: Kind) -> u8 { match k { Kind::A => 1, Kind::B => 2 } }
2837            fn hidden() -> Option<impl Sized> { Some(1) }
2838        "#;
2839        let sites = discover(src, 0).unwrap().sites;
2840        let kinds: Vec<String> = sites
2841            .iter()
2842            .filter_map(|s| match &s.kind {
2843                SiteKind::Return { name, option, .. } => Some(format!("return {name} {option:?}")),
2844                SiteKind::Range {
2845                    inclusive,
2846                    lhs,
2847                    rhs,
2848                    ..
2849                } => Some(format!("range {lhs} {rhs} inclusive={inclusive}")),
2850                SiteKind::Arm { pattern, guard } => Some(format!(
2851                    "arm {pattern} guarded={}",
2852                    matches!(guard, ArmGuard::Existing(..))
2853                )),
2854                SiteKind::MinMax {
2855                    max,
2856                    receiver,
2857                    argument,
2858                    ..
2859                } => Some(format!("minmax {receiver} {argument} max={max}")),
2860                _ => None,
2861            })
2862            .collect();
2863        assert_eq!(
2864            kinds,
2865            [
2866                "return find Some(\"Option<u32>\")",
2867                "range 0 v.len() inclusive=false",
2868                "minmax v[i].min(limit) 1 max=true",
2869                "minmax v[i] limit max=false",
2870                // The catch-all arm and the last arm stay; a match without one is left alone.
2871                "arm 0 guarded=false",
2872                "arm n if n > 5 guarded=true",
2873                "arm 1..=3 guarded=false",
2874                // `1..=2` and `'a'..'z'` have literals at both ends.
2875                "range 1 limit as usize inclusive=true",
2876            ]
2877        );
2878        let out = render(src, &sites, &all).text;
2879        syn::parse_file(&out).expect("instrumented source parses");
2880        assert_eq!(out.lines().count(), src.lines().count());
2881        assert!(out.contains("let __tmt_v: Option<u32> = {"), "{out}");
2882        assert!(
2883            out.contains("crate::__tmt_rt::ret_opt(0u32, __tmt_v)"),
2884            "{out}"
2885        );
2886        assert!(out.contains("0 if crate::__tmt_rt::arm("), "{out}");
2887        assert!(
2888            out.contains("n if crate::__tmt_rt::arm(") && out.contains(") && ("),
2889            "{out}"
2890        );
2891        assert!(out.contains("1..=3 if crate::__tmt_rt::arm("), "{out}");
2892        assert!(
2893            out.contains(".tmt_range(") && out.contains(".tmt_range_inclusive("),
2894            "{out}"
2895        );
2896        // The call that was written, and the other one for the mutant, on the operands
2897        // as they were evaluated once; the receiver is borrowed, not moved.
2898        assert!(
2899            out.contains("(match (&(v[i]), limit) {")
2900                && out.contains(
2901                    "Mm(__tmt_a, &__tmt_b)).tmt_other(6u32) { (*__tmt_a).max(__tmt_b) } else { (*__tmt_a).min(__tmt_b) }"
2902                )
2903                && out.contains(
2904                    ".tmt_other(5u32) { (*__tmt_a).min(__tmt_b) } else { (*__tmt_a).max(__tmt_b) }"
2905                ),
2906            "{out}"
2907        );
2908        assert!(
2909            !out.contains(".min(limit)") && !out.contains(".max(1)"),
2910            "{out}"
2911        );
2912        assert!(
2913            out.contains("v.iter().max()"),
2914            "an iterator's max is another method: {out}"
2915        );
2916    }
2917
2918    #[test]
2919    fn macro_arguments() {
2920        let src = r#"
2921            fn f(a: u32, b: u32, out: &mut String) -> Vec<u32> {
2922                assert!(a < 100);
2923                debug_assert!(a < 101, "message {}", a < 102);
2924                assert_eq!(a < 1, b < 2, "context {}", a + 3);
2925                let _ = format!("{} {name}", a < 4, name = b < 5);
2926                write!(out, "{}", a < 6).unwrap();
2927                if matches!(a.cmp(&b), std::cmp::Ordering::Less if a < 7) || matches!(a < 8, true) { panic!("{}", a < 9); }
2928                custom!(a < 10);
2929                let _ = vec![a < 11; 2];
2930                vec![a + b, (a < 12) as u32]
2931            }
2932        "#;
2933        let texts: Vec<String> = found(src, 0)
2934            .unwrap()
2935            .sites
2936            .into_iter()
2937            .filter(|s| matches!(s.kind, SiteKind::Cmp { .. } | SiteKind::Arith { .. }))
2938            .map(|s| s.text)
2939            .collect();
2940        assert_eq!(
2941            texts,
2942            [
2943                "a < 1", "b < 2", "a + 3", "a < 4", "b < 5", "a < 6", "a < 8", "a < 9", "a + b",
2944                "a < 12"
2945            ]
2946        );
2947        let found = found(src, 0).unwrap().sites;
2948        syn::parse_file(&render(src, &found, &all).text).expect("instrumented source parses");
2949    }
2950
2951    #[test]
2952    fn non_ascii_source_keeps_byte_offsets() {
2953        let src = "fn f(a: u8) -> bool { let s = \"日本語\"; s.len() > 3 && a < 2 }";
2954        let sites = found(src, 0).unwrap().sites;
2955        let texts: Vec<&str> = sites.iter().map(|s| s.text.as_str()).collect();
2956        assert_eq!(texts, ["s.len() > 3 && a < 2", "s.len() > 3", "a < 2"]);
2957        syn::parse_file(&render(src, &sites, &all).text).unwrap();
2958    }
2959
2960    #[test]
2961    fn unparseable_source_is_an_error() {
2962        assert!(discover("fn f( {", 0).is_err());
2963    }
2964    /// Every site as `kind text`, in discovery order, without the replaced bodies.
2965    fn labelled(src: &str) -> Vec<String> {
2966        discover(src, 0)
2967            .unwrap()
2968            .sites
2969            .iter()
2970            .filter(|s| !matches!(s.kind, SiteKind::Body { .. }))
2971            .map(|s| {
2972                let kind = match &s.kind {
2973                    SiteKind::Cmp { .. } => "cmp",
2974                    SiteKind::Logic { .. } => "logic",
2975                    SiteKind::Arith { .. } => "arith",
2976                    SiteKind::Not { .. } => "not",
2977                    SiteKind::Return { .. } => "return",
2978                    SiteKind::MinMax { .. } => "minmax",
2979                    SiteKind::Range { .. } => "range",
2980                    SiteKind::Arm { .. } => "arm",
2981                    SiteKind::Stmt => "stmt",
2982                    SiteKind::Neg { .. } => "neg",
2983                    SiteKind::Guard { .. } => "guard",
2984                    SiteKind::Field { .. } => "field",
2985                    SiteKind::Body { .. } => "body",
2986                };
2987                format!("{kind} {}", s.text)
2988            })
2989            .collect()
2990    }
2991
2992    #[test]
2993    fn byte_order_mark_and_interpreter_line_are_refused() {
2994        let body = "fn f(a: u8) -> bool { a > 1 }";
2995        assert!(discover(&format!("\u{feff}{body}"), 0).is_err());
2996        assert!(discover(&format!("#!/usr/bin/env run\n{body}"), 0).is_err());
2997        // An inner attribute starts with the same two characters and is fine.
2998        assert_eq!(
2999            labelled(&format!("#![allow(dead_code)]\n{body}")),
3000            ["return fn f(a: u8) -> bool", "cmp a > 1"]
3001        );
3002    }
3003
3004    #[test]
3005    fn which_result_types_make_a_return_site() {
3006        let src = "fn a() -> <S as Tr>::Option<u8> { g() }\n\
3007                   fn b() -> Option { g() }\n\
3008                   fn c() -> Vec<u8> { g() }\n\
3009                   fn d() -> std::option::Option<u8> { g() }\n\
3010                   fn e() -> <S>::bool { g() }\n\
3011                   fn e2() -> <S as Tr>::bool { g() }\n\
3012                   fn one(a: u8) -> bool { a > 1 }\n\
3013                   fn two(a: u8) -> bool { let b = a; b > 1 }\n\
3014                   fn early(a: u8) -> bool { return a > 1; }\n";
3015        let returns: Vec<(String, Option<String>, Option<&str>)> = discover(src, 0)
3016            .unwrap()
3017            .sites
3018            .into_iter()
3019            .filter_map(|s| match s.kind {
3020                SiteKind::Return {
3021                    name,
3022                    option,
3023                    sole_expr,
3024                } => Some((name, option, sole_expr.map(|(from, to)| &src[from..to]))),
3025                _ => None,
3026            })
3027            .collect();
3028        assert_eq!(
3029            returns,
3030            [
3031                (
3032                    "d".to_string(),
3033                    Some("std::option::Option<u8>".to_string()),
3034                    Some("g()")
3035                ),
3036                // Only a body that is one expression has a "sole expression".
3037                ("one".to_string(), None, Some("a > 1")),
3038                ("two".to_string(), None, None),
3039                ("early".to_string(), None, None),
3040            ]
3041        );
3042    }
3043
3044    #[test]
3045    fn places_chains_attributes_and_shadowed_macros() {
3046        // A parenthesised variable is still a plain place. An attribute on a statement
3047        // belongs to its leftmost operand, which is then not probed; the statement can
3048        // still be deleted.
3049        assert_eq!(
3050            labelled("fn f(mut x: i32) -> i32 { #[allow(unused)] x += 1; (x) += 2; x }"),
3051            [
3052                "stmt #[allow(unused)] x += 1;",
3053                "stmt (x) += 2;",
3054                "arith (x) += 2"
3055            ]
3056        );
3057        // `cond && let ..` is a let chain as much as `let .. && cond`.
3058        assert_eq!(
3059            labelled("fn f(a: u8, o: Option<u8>) { if a > 1 && let Some(b) = o { g(b); } }"),
3060            ["cmp a > 1", "stmt g(b);"]
3061        );
3062        // And so is everything joined to one.
3063        assert_eq!(
3064            labelled(
3065                "fn f(a: u8, o: Option<u8>) { if a > 1 && let Some(b) = o && b > 2 { g(b); } }"
3066            ),
3067            ["cmp a > 1", "cmp b > 2", "stmt g(b);"]
3068        );
3069        // A macro of this file under a standard name takes anything as its arguments.
3070        assert_eq!(
3071            labelled(
3072                "macro_rules! vec { ($($t:tt)*) => {} }\n\
3073                 fn f(a: u8) { let _ = vec![a > 1]; let _ = format!(\"{}\", a > 2); }"
3074            ),
3075            ["cmp a > 2"]
3076        );
3077        assert_eq!(
3078            labelled(
3079                "trait T { const fn f(a: u8) -> bool { a > 1 } fn g(a: u8) -> bool { a > 2 } }"
3080            ),
3081            ["return fn g(a: u8) -> bool", "cmp a > 2"]
3082        );
3083    }
3084
3085    #[test]
3086    fn min_max_and_ranges_that_are_left_alone() {
3087        assert_eq!(
3088            labelled(
3089                "fn f(a: u8, b: u8) -> u8 { let _ = a.max::<u8>(b); \
3090                 let _ = #[allow(unused)] a.min(b); let _ = a.max(b, 1); a.max(b) }"
3091            ),
3092            ["minmax a.max(b)"]
3093        );
3094        // One literal end is enough to fix the type; the ends are searched for sites.
3095        let src = "fn f(a: usize, b: usize, v: &[u8]) { for _ in a..10 {} for _ in 1..b {} \
3096                   for _ in (a + 1)..(b * 2) {} for _ in 3..4 {} for _ in (5)..(-6) {} }";
3097        assert_eq!(
3098            labelled(src),
3099            [
3100                "range a..10",
3101                "range 1..b",
3102                "range (a + 1)..(b * 2)",
3103                "arith a + 1",
3104                "arith b * 2",
3105                // Two literal ends are no range site; the minus in one is still a minus.
3106                "neg -6"
3107            ]
3108        );
3109        let out = render(src, &discover(src, 0).unwrap().sites, &all).text;
3110        // The `..` itself is gone: the ends are the two arguments of the probe.
3111        assert!(out.contains("for _ in (match (a, 10) {"), "{out}");
3112        assert!(!out.contains("a..10") && !out.contains("1..b"), "{out}");
3113        assert!(out.contains("3..4") && out.contains("(5)..((if "), "{out}");
3114    }
3115
3116    #[test]
3117    fn which_arms_can_be_removed() {
3118        let src = "fn f(k: u8) -> u8 {\n\
3119                   \x20   let a = match k { 1 => 1, x => x, 2 => 2, #[cfg(any())] 3 => 3, _rest => 0 };\n\
3120                   \x20   let b = match k { 1 => 1, NONE => 0 };\n\
3121                   \x20   let c = match k { 1 => 1, n @ 0..=9 => n };\n\
3122                   \x20   let d = match k {\n\
3123                   \x20       1 => 1,\n\
3124                   \x20       _ => 0,\n\
3125                   \x20   };\n\
3126                   \x20   a + b + c + d\n\
3127                   }\n";
3128        let arms: Vec<(u32, usize, usize, String)> = discover(src, 7)
3129            .unwrap()
3130            .sites
3131            .into_iter()
3132            .filter(|s| matches!(s.kind, SiteKind::Arm { .. }))
3133            .map(|s| (s.id, s.line, s.column, s.text))
3134            .collect();
3135        // Neither a catch-all arm in the middle nor an arm with an attribute; and no arm
3136        // at all when the last one is a constant or binds only part of the values.
3137        assert_eq!(
3138            arms,
3139            [
3140                // After the two replaced bodies of a function that returns `u8`.
3141                (9, 2, 23, "1 => ..".to_string()),
3142                (10, 2, 39, "2 => ..".to_string()),
3143                (11, 6, 9, "1 => ..".to_string()),
3144            ]
3145        );
3146    }
3147
3148    #[test]
3149    fn offsets_around_inserted_text() {
3150        let src = "fn f(a: u8) -> bool { a > 1 }";
3151        let sites = found(src, 0).unwrap().sites;
3152        let out = render(src, &sites, &all);
3153        let start = sites[0].start;
3154        // `a` is copied right after the opening text of the probe: the last inserted
3155        // character before it still maps to the point of insertion.
3156        let copied_a = out.text.find("a), &(").unwrap();
3157        assert_eq!(out.to_original(copied_a), start);
3158        assert_eq!(out.to_original(copied_a - 1), start);
3159        assert_eq!(out.to_original(copied_a + 1), start + 1);
3160        // Past the end is the end.
3161        assert_eq!(out.to_original(out.text.len() + 10), src.len());
3162
3163        // The probe of `b + 1` opens right after the replaced `..`: an error there is
3164        // inside `b + 1`, not in front of the `..`.
3165        let src = "fn f(a: usize, b: usize) { for _ in a..b + 1 {} }";
3166        let sites = discover(src, 0).unwrap().sites;
3167        let out = render(src, &sites, &all);
3168        let inner_probe = out.text.find("(match (a, ").unwrap() + "(match (a, ".len();
3169        assert!(
3170            out.text[inner_probe..].starts_with("(match (b, 1)"),
3171            "{}",
3172            out.text
3173        );
3174        assert_eq!(out.to_original(inner_probe), src.find("b + 1").unwrap());
3175        let arith = sites
3176            .iter()
3177            .find(|s| matches!(s.kind, SiteKind::Arith { .. }))
3178            .unwrap();
3179        assert_eq!(
3180            blame(&sites, &all, out.to_original(inner_probe)),
3181            [arith.id]
3182        );
3183        // The text of a probe knows its site without going through the original.
3184        assert_eq!(out.inserted_by(inner_probe), Some(arith.id));
3185        assert_eq!(out.inserted_by(out.text.find("b, 1").unwrap()), None);
3186        // From its first to its last byte, and not one further.
3187        let opening = "(match (b, ";
3188        let (first, last) = (inner_probe, inner_probe + "(match (".len() - 1);
3189        assert!(out.text[inner_probe..].starts_with(opening));
3190        assert_eq!(out.inserted_by(first), Some(arith.id));
3191        assert_eq!(out.inserted_by(last), Some(arith.id));
3192        assert_eq!(out.inserted_by(last + 1), None);
3193        assert_eq!(out.inserted_by(0), None);
3194    }
3195    fn values(ty: &str) -> Vec<String> {
3196        let function: syn::ItemFn = syn::parse_str(&format!("fn f() -> {ty} {{ todo!() }}"))
3197            .unwrap_or_else(|e| panic!("{ty}: {e}"));
3198        body_values(&function.sig.output)
3199    }
3200
3201    /// The table of cargo-mutants (https://mutants.rs/mutants.html), row by row.
3202    #[test]
3203    fn replacement_values_by_return_type() {
3204        let rows: &[(&str, &[&str])] = &[
3205            ("()", &["()"]),
3206            ("i8", &["0", "1", "-1"]),
3207            ("isize", &["0", "1", "-1"]),
3208            ("i128", &["0", "1", "-1"]),
3209            ("u8", &["0", "1"]),
3210            ("usize", &["0", "1"]),
3211            ("u128", &["0", "1"]),
3212            ("f32", &["0.0", "1.0", "-1.0"]),
3213            ("f64", &["0.0", "1.0", "-1.0"]),
3214            ("bool", &["true", "false"]),
3215            (
3216                "NonZeroI32",
3217                &["1.try_into().unwrap()", "(-1).try_into().unwrap()"],
3218            ),
3219            ("std::num::NonZeroU8", &["1.try_into().unwrap()"]),
3220            ("NonZero<u64>", &["1.try_into().unwrap()"]),
3221            (
3222                "NonZero<i64>",
3223                &["1.try_into().unwrap()", "(-1).try_into().unwrap()"],
3224            ),
3225            ("String", &["String::new()", "\"xyzzy\".into()"]),
3226            ("&str", &["\"\"", "\"xyzzy\""]),
3227            ("&'static str", &["\"\"", "\"xyzzy\""]),
3228            // A `str` that can be written to is not a literal.
3229            ("&mut str", &["Box::leak(Box::new(Default::default()))"]),
3230            ("&u8", &["Box::leak(Box::new(0))", "Box::leak(Box::new(1))"]),
3231            (
3232                "&mut bool",
3233                &["Box::leak(Box::new(true))", "Box::leak(Box::new(false))"],
3234            ),
3235            (
3236                "&[u8]",
3237                &[
3238                    "Vec::leak(Vec::new())",
3239                    "Vec::leak(vec![0])",
3240                    "Vec::leak(vec![1])",
3241                ],
3242            ),
3243            (
3244                "&mut [bool]",
3245                &[
3246                    "Vec::leak(Vec::new())",
3247                    "Vec::leak(vec![true])",
3248                    "Vec::leak(vec![false])",
3249                ],
3250            ),
3251            ("Result<bool, Error>", &["Ok(true)", "Ok(false)"]),
3252            ("io::Result<()>", &["Ok(())"]),
3253            // Without arguments it is an alias: `fmt::Result`, or the crate's own.
3254            ("fmt::Result", &["Ok(Default::default())"]),
3255            ("Result", &["Ok(Default::default())"]),
3256            ("Option<u8>", &["None", "Some(0)", "Some(1)"]),
3257            ("Vec<bool>", &["vec![]", "vec![true]", "vec![false]"]),
3258            ("Box<u8>", &["Box::new(0)", "Box::new(1)"]),
3259            (
3260                "std::rc::Rc<u8>",
3261                &["std::rc::Rc::new(0)", "std::rc::Rc::new(1)"],
3262            ),
3263            ("Arc<bool>", &["Arc::new(true)", "Arc::new(false)"]),
3264            ("RefCell<()>", &["RefCell::new(())"]),
3265            ("Mutex<()>", &["Mutex::new(())"]),
3266            ("Cell<()>", &["Cell::new(())"]),
3267            (
3268                "HashSet<u8>",
3269                &[
3270                    "HashSet::new()",
3271                    "HashSet::from_iter([0])",
3272                    "HashSet::from_iter([1])",
3273                ],
3274            ),
3275            (
3276                "BTreeSet<()>",
3277                &["BTreeSet::new()", "BTreeSet::from_iter([()])"],
3278            ),
3279            (
3280                "BinaryHeap<()>",
3281                &["BinaryHeap::new()", "BinaryHeap::from_iter([()])"],
3282            ),
3283            (
3284                "LinkedList<()>",
3285                &["LinkedList::new()", "LinkedList::from_iter([()])"],
3286            ),
3287            (
3288                "VecDeque<()>",
3289                &["VecDeque::new()", "VecDeque::from_iter([()])"],
3290            ),
3291            (
3292                "HashMap<bool, u8>",
3293                &[
3294                    "HashMap::new()",
3295                    "HashMap::from_iter([(true, 0)])",
3296                    "HashMap::from_iter([(true, 1)])",
3297                    "HashMap::from_iter([(false, 0)])",
3298                    "HashMap::from_iter([(false, 1)])",
3299                ],
3300            ),
3301            (
3302                "std::collections::BTreeMap<(), ()>",
3303                &[
3304                    "std::collections::BTreeMap::new()",
3305                    "std::collections::BTreeMap::from_iter([((), ())])",
3306                ],
3307            ),
3308            (
3309                "Cow<'a, str>",
3310                &[
3311                    "Cow::Borrowed(\"\")",
3312                    "Cow::Owned(\"\".to_owned())",
3313                    "Cow::Borrowed(\"xyzzy\")",
3314                    "Cow::Owned(\"xyzzy\".to_owned())",
3315                ],
3316            ),
3317            ("[u8; 4]", &["[0; 4]", "[1; 4]"]),
3318            ("[bool; N + 1]", &["[true; N + 1]", "[false; N + 1]"]),
3319            (
3320                "(u8, bool)",
3321                &["(0, true)", "(0, false)", "(1, true)", "(1, false)"],
3322            ),
3323            ("(bool,)", &["(true,)", "(false,)"]),
3324            ("HttpResponse", &["HttpResponse::Ok().finish()"]),
3325            (
3326                "actix_web::HttpResponse",
3327                &["actix_web::HttpResponse::Ok().finish()"],
3328            ),
3329            ("Config", &["Default::default()"]),
3330            ("Self", &["Default::default()"]),
3331            ("<T as Tr>::Out", &["Default::default()"]),
3332            // Not the `String` everyone knows.
3333            ("<T as Tr>::String", &["Default::default()"]),
3334            ("<T>::bool", &["Default::default()"]),
3335            ("fn(u8) -> u8", &["Default::default()"]),
3336            ("*const u8", &["Default::default()"]),
3337            // Nested: every value of the inner type, wrapped.
3338            (
3339                "Result<Option<String>, E>",
3340                &[
3341                    "Ok(None)",
3342                    "Ok(Some(String::new()))",
3343                    "Ok(Some(\"xyzzy\".into()))",
3344                ],
3345            ),
3346            ("(Vec<()>)", &["vec![]", "vec![()]"]),
3347            ("Option<Config>", &["None", "Some(Default::default())"]),
3348            // Nothing can be returned in place of these.
3349            ("!", &[]),
3350            ("impl Iterator<Item = u8>", &[]),
3351            ("Box<impl Fn()>", &[]),
3352            ("Option<!>", &["None"]),
3353        ];
3354        for (ty, expected) in rows {
3355            assert_eq!(values(ty), *expected, "{ty}");
3356        }
3357        // No return type at all is `()`.
3358        let unit: syn::ItemFn = syn::parse_str("fn f() {}").unwrap();
3359        assert_eq!(body_values(&unit.sig.output), ["()"]);
3360    }
3361
3362    #[test]
3363    fn which_functions_get_their_body_replaced() {
3364        let src = r#"
3365            fn plain(a: u8) -> u8 { a + 1 }
3366            fn already(a: u8) -> bool { let _ = a; true }
3367            fn sole() -> bool { true }
3368            fn spaced() -> (u8, bool) { ( 0 , true ) }
3369            unsafe fn raw(a: u8) -> u8 { a }
3370            fn empty() {}
3371            fn one_call(s: &mut S) { s.go(); }
3372            fn two_calls(s: &mut S) { s.go(); s.stop(); }
3373            fn typed(s: &mut S) -> u8 { s.exit(); }
3374            fn tight() -> bool {true}
3375            #[rustfmt::skip]
3376            fn formatted(a: u8) -> u8 { a + 6 }
3377            #[mutants::timeout(5)]
3378            fn slow(a: u8) -> u8 { a + 7 }
3379            impl S { #[mutants::skip] fn marked_method(&self, a: u8) -> u8 { a + 8 } }
3380            trait U { #[mutants::skip] fn marked_default(&self, a: u8) -> u8 { a + 9 } }
3381            fn one_let(a: u8) { let _ = a; }
3382            fn never() -> ! { loop {} }
3383            fn hidden() -> impl Sized { 1 }
3384            #[mutants::skip]
3385            fn marked(a: u8) -> u8 { a + 2 }
3386            #[cfg_attr(test, mutants::skip)]
3387            fn marked_in_tests(a: u8) -> u8 { a + 3 }
3388            #[mutants::skip]
3389            impl S { fn method(&self, a: u8) -> u8 { a + 4 } }
3390            #[mutants::skip]
3391            mod generated { fn inner(a: u8) -> u8 { a + 5 } }
3392            trait T { fn required(&self) -> u8; fn provided(&self) -> u8 { 7 } }
3393            async fn later() -> u8 { 9 }
3394        "#;
3395        let sites = discover(src, 0).unwrap().sites;
3396        let bodies: Vec<String> = sites
3397            .iter()
3398            .filter_map(|s| match &s.kind {
3399                SiteKind::Body { name, value, .. } => Some(format!("{name} {value}")),
3400                _ => None,
3401            })
3402            .collect();
3403        assert_eq!(
3404            bodies,
3405            [
3406                "plain 0",
3407                "plain 1",
3408                "already true",
3409                "already false",
3410                // The body is this value already, however it is spaced.
3411                "sole false",
3412                "spaced (0, false)",
3413                "spaced (1, true)",
3414                "spaced (1, false)",
3415                // One statement that can be deleted is the same mutant as no body.
3416                "two_calls ()",
3417                // With a result to return, one statement is not the whole of it.
3418                "typed 0",
3419                "typed 1",
3420                "tight false",
3421                // Other attributes with `skip` or `mutants` in them do not mark anything.
3422                "formatted 0",
3423                "formatted 1",
3424                "slow 0",
3425                "slow 1",
3426                "one_let ()",
3427                "provided 0",
3428                "provided 1",
3429                "later 0",
3430                "later 1",
3431            ]
3432        );
3433        // Nothing at all is mutated in what is marked to be skipped.
3434        let texts: Vec<&str> = sites.iter().map(|s| s.text.as_str()).collect();
3435        for skipped in ["a + 2", "a + 3", "a + 4", "a + 5", "a + 8", "a + 9"] {
3436            assert!(!texts.contains(&skipped), "{skipped}");
3437        }
3438        for mutated in ["a + 1", "a + 6", "a + 7"] {
3439            assert!(texts.contains(&mutated), "{mutated}");
3440        }
3441        let unsafe_sites: Vec<&Site> = sites.iter().filter(|s| s.text.contains("raw")).collect();
3442        assert!(unsafe_sites.is_empty(), "{unsafe_sites:?}");
3443
3444        let body = sites
3445            .iter()
3446            .find(|s| matches!(s.kind, SiteKind::Body { .. }))
3447            .unwrap();
3448        assert_eq!(
3449            (body.line, body.column, body.text.as_str()),
3450            (2, 13, "fn plain(a: u8) -> u8")
3451        );
3452        let out = render(src, &sites, &all).text;
3453        syn::parse_file(&out).expect("instrumented source parses");
3454        assert_eq!(out.lines().count(), src.lines().count());
3455        assert!(
3456            out.contains(
3457                "fn plain(a: u8) -> u8 { if !crate::__tmt_rt::live(0u32) { return 0; } \
3458                 if !crate::__tmt_rt::live(1u32) { return 1; } (match (a, 1)"
3459            ),
3460            "{out}"
3461        );
3462        // A body that is exactly its expression: the function-level probes go around
3463        // the probe of the expression.
3464        let tight = "fn f(a: u8, b: u8) -> bool {a > b}";
3465        let sites = discover(tight, 0).unwrap().sites;
3466        let out = render(tight, &sites, &all).text;
3467        syn::parse_file(&out).expect("instrumented source parses");
3468        assert!(
3469            out.starts_with(
3470                "fn f(a: u8, b: u8) -> bool { let __tmt_v: bool = { \
3471                 if !crate::__tmt_rt::live(1u32) { return true; } \
3472                 if !crate::__tmt_rt::live(2u32) { return false; }(match (&(a), &(b))"
3473            ),
3474            "{out}"
3475        );
3476        assert!(
3477            out.ends_with(" })}; crate::__tmt_rt::ret(0u32, __tmt_v) }"),
3478            "{out}"
3479        );
3480    }
3481
3482    #[test]
3483    fn minus_guards_and_fields() {
3484        let src = r#"
3485            fn f(x: i32, y: f64, k: Kind, base: Options) -> Options {
3486                let a = -x + -5 - -0 + (-0.0 * -y) as i32;
3487                let b = match k {
3488                    Kind::A(n) if n > 1 => 1,
3489                    Kind::A(n) if let Some(m) = half(n) => m,
3490                    Kind::B if x > 0 && let Some(m) = half(x) => m,
3491                    #[cfg(any())]
3492                    Kind::B if x > 2 => 2,
3493                    Kind::B => 3,
3494                };
3495                let c = match b { n if n > 3 => 1, _ => 0 };
3496                let first = Options { depth: a, name, ..base };
3497                let second = Options { depth: -b, ..Default::default() };
3498                let third = Wrap::<u8> { 0: c, ..Wrap::new() };
3499                let _ = Options { depth: 1, ..base.clone() };
3500                let _ = Options { depth: 2, ..make(3) };
3501                let _ = Options { depth: 6, ..(pick())() };
3502                let _ = -2.5 + y;
3503                let _ = Options { #[cfg(any())] depth: 4, strict: true, ..*other };
3504                let _ = Options { depth: 5, name: n, strict: false };
3505                first
3506            }
3507        "#;
3508        let sites = found(src, 0).unwrap().sites;
3509        let kinds: Vec<String> = sites
3510            .iter()
3511            .filter_map(|s| match &s.kind {
3512                SiteKind::Neg {
3513                    operand, literal, ..
3514                } => Some(format!("neg {} | {operand} | literal={literal}", s.text)),
3515                SiteKind::Guard { can_be_false } => {
3516                    Some(format!("guard {} | can_be_false={can_be_false}", s.text))
3517                }
3518                SiteKind::Field {
3519                    name,
3520                    shorthand,
3521                    from_base,
3522                } => Some(format!(
3523                    "field {} | {name} | shorthand={shorthand} | {from_base}",
3524                    s.text
3525                )),
3526                _ => None,
3527            })
3528            .collect();
3529        assert_eq!(
3530            kinds,
3531            [
3532                "neg -x | x | literal=false",
3533                "neg -5 | 5 | literal=true",
3534                // `-0` is 0 either way; `-0.0` is not `0.0`.
3535                "neg -0.0 | 0.0 | literal=true",
3536                "neg -y | y | literal=false",
3537                // No catch-all arm: the arm cannot be removed, so `false` is a mutant.
3538                "guard n > 1 | can_be_false=true",
3539                // Where the arm can be removed, that is the guard being `false`.
3540                "guard n > 3 | can_be_false=false",
3541                "field depth: a | depth | shorthand=false | (base).depth",
3542                "field name | name | shorthand=true | (base).name",
3543                "field depth: -b | depth | shorthand=false | (Options { ..Default::default() }).depth",
3544                "neg -b | b | literal=false",
3545                "field 0: c | 0 | shorthand=false | (Wrap::<u8> { ..Wrap::new() }).0",
3546                "neg -2.5 | 2.5 | literal=true",
3547                // Not with a base that has arguments, a receiver or a computed function,
3548                // not a field with an attribute, and not without a base.
3549                "field strict: true | strict | shorthand=false | (*other).strict",
3550            ]
3551        );
3552        // A field is reported where its name stands.
3553        let field = sites
3554            .iter()
3555            .find(|s| s.text == "depth: a")
3556            .expect("the field is a site");
3557        let line = src.lines().nth(field.line - 1).unwrap();
3558        assert_eq!(line.find("depth: a"), Some(field.column - 1), "{line}");
3559        assert_eq!(&src[field.start..field.end], "a");
3560        let out = render(src, &sites, &all).text;
3561        syn::parse_file(&out).expect("instrumented source parses");
3562        assert_eq!(out.lines().count(), src.lines().count());
3563        for expected in [
3564            // The operand is evaluated once, outside the names of the probe.
3565            "(match (x) { __tmt_a => if crate::__tmt_rt::live(",
3566            // A literal stays a literal, with the type its place gives it.
3567            "u32) { -__tmt_a } else { __tmt_a } })",
3568            "u32) { -5 } else { 5 })",
3569            // A guard and the comparison it consists of: the guard goes around.
3570            "Kind::A(n) if crate::__tmt_rt::ret(",
3571            "u32, (match (&(n), &(1))",
3572            "n if crate::__tmt_rt::arm(",
3573            ") && (crate::__tmt_rt::ret(",
3574            "depth: if crate::__tmt_rt::live(",
3575            "{ a } else { (base).depth }",
3576            // A field written by its name alone gets the name back.
3577            "name: if crate::__tmt_rt::live(",
3578            "{ name } else { (base).name }, ..base }",
3579            "} else { (Options { ..Default::default() }).depth }, ..Default::default() }",
3580            "0: if crate::__tmt_rt::live(",
3581            "Options { depth: 1, ..base.clone() }",
3582            "Options { depth: 2, ..make(3) }",
3583            "Options { depth: 6, ..(pick())() }",
3584            "Options { depth: 5, name: n, strict: false }",
3585        ] {
3586            assert!(out.contains(expected), "{expected}\n{out}");
3587        }
3588        assert!(
3589            !out.contains("{ -0 }") && out.contains("{ -0.0 } else { 0.0 }"),
3590            "{out}"
3591        );
3592    }
3593    /// The source with each mutant of each site applied, as `what -> into: text`.
3594    fn mutated(src: &str, sites: &[Site]) -> Vec<String> {
3595        sites
3596            .iter()
3597            .flat_map(|site| {
3598                source_mutants(site).into_iter().map(|m| {
3599                    let text = format!("{}{}{}", &src[..m.start], m.replacement, &src[m.end..]);
3600                    syn::parse_file(&text).unwrap_or_else(|e| panic!("{text}: {e}"));
3601                    format!("{} -> {}: {}", m.what, m.into, text.trim())
3602                })
3603            })
3604            .collect()
3605    }
3606
3607    #[test]
3608    fn what_cannot_be_probed_is_mutated_in_the_source() {
3609        // Everything in a `const fn`, a compound assignment to more than a variable,
3610        // and the body of a function that returns an iterator.
3611        let src = "const fn c(a: u8, b: u8) -> bool { a < b }\n\
3612                   fn f(m: &mut Map, k: u8) { *m.entry(k).or_insert(0) += 1; m.total -= 1; }\n\
3613                   fn evens(n: u8) -> impl Iterator<Item = u8> + '_ { (0..n).step_by(2) }\n\
3614                   impl S { const fn k(&self) -> u8 { -self.0 } }\n\
3615                   trait T { const fn d(a: u8) -> u8 { a } }\n";
3616        let found = discover(src, 0).unwrap();
3617        assert!(found.rebuild_sites.iter().all(|s| s.id == NO_ID));
3618        let places: Vec<(usize, usize, &str)> = found
3619            .rebuild_sites
3620            .iter()
3621            .filter(|s| !matches!(s.kind, SiteKind::Return { .. }))
3622            .map(|s| (s.line, s.column, s.text.as_str()))
3623            .collect();
3624        assert_eq!(
3625            places,
3626            [
3627                (1, 1, "const fn c(a: u8, b: u8) -> bool"),
3628                (1, 1, "const fn c(a: u8, b: u8) -> bool"),
3629                (1, 36, "a < b"),
3630                (2, 28, "*m.entry(k).or_insert(0) += 1"),
3631                (3, 1, "fn evens(n: u8) -> impl Iterator<Item = u8> + '_"),
3632                (3, 1, "fn evens(n: u8) -> impl Iterator<Item = u8> + '_"),
3633                (3, 1, "fn evens(n: u8) -> impl Iterator<Item = u8> + '_"),
3634                // A range that is not run through by a `for`.
3635                (3, 53, "0..n"),
3636                (4, 10, "const fn k(&self) -> u8"),
3637                (4, 10, "const fn k(&self) -> u8"),
3638                (4, 36, "-self.0"),
3639                (5, 11, "const fn d(a: u8) -> u8"),
3640                (5, 11, "const fn d(a: u8) -> u8"),
3641            ]
3642        );
3643        assert_eq!(
3644            found.sites.iter().map(|s| s.id).collect::<Vec<_>>(),
3645            (0..found.sites.len() as u32).collect::<Vec<_>>()
3646        );
3647        let numbered: Vec<&str> = found.sites.iter().map(|s| s.text.as_str()).collect();
3648        assert_eq!(
3649            numbered,
3650            [
3651                "fn f(m: &mut Map, k: u8)",
3652                "*m.entry(k).or_insert(0) += 1;",
3653                "m.total -= 1;",
3654                "m.total -= 1",
3655            ]
3656        );
3657        assert_eq!(
3658            mutated(src, &found.rebuild_sites)
3659                .iter()
3660                .map(|line| line.lines().next().unwrap().to_string())
3661                .take(5)
3662                .collect::<Vec<_>>(),
3663            [
3664                "body -> true: const fn c(a: u8, b: u8) -> bool { true }",
3665                "body -> false: const fn c(a: u8, b: u8) -> bool { false }",
3666                "< -> ==: const fn c(a: u8, b: u8) -> bool { a == b }",
3667                "< -> >: const fn c(a: u8, b: u8) -> bool { a > b }",
3668                "< -> <=: const fn c(a: u8, b: u8) -> bool { a <= b }",
3669            ]
3670        );
3671        let whats: Vec<String> = found
3672            .rebuild_sites
3673            .iter()
3674            .flat_map(|site| {
3675                source_mutants(site)
3676                    .into_iter()
3677                    .map(|m| format!("{}: {} -> {}", site.text, m.what, m.into))
3678            })
3679            .skip(5)
3680            .collect();
3681        assert_eq!(
3682            whats,
3683            [
3684                "*m.entry(k).or_insert(0) += 1: += -> -=",
3685                "*m.entry(k).or_insert(0) += 1: += -> *=",
3686                "fn evens(n: u8) -> impl Iterator<Item = u8> + '_: body -> ::core::iter::empty()",
3687                "fn evens(n: u8) -> impl Iterator<Item = u8> + '_: body -> ::core::iter::once(0)",
3688                "fn evens(n: u8) -> impl Iterator<Item = u8> + '_: body -> ::core::iter::once(1)",
3689                "0..n: .. -> ..=",
3690                "const fn k(&self) -> u8: body -> 0",
3691                "const fn k(&self) -> u8: body -> 1",
3692                "-self.0: - -> ",
3693                "const fn d(a: u8) -> u8: body -> 0",
3694                "const fn d(a: u8) -> u8: body -> 1",
3695            ]
3696        );
3697    }
3698
3699    #[test]
3700    fn source_mutants_of_every_kind() {
3701        let src = "fn f(a: i32, b: i32, k: K, base: O) -> O { \
3702                   let x = match k { K::A(n) if n >= 1 => !(a != b) || a <= -b, K::B => a % b > 0 && a == b, _ => false }; \
3703                   O { on: x, a, ..base } }";
3704        let sites = found(src, 0).unwrap().sites;
3705        // Every one of them is still a source file.
3706        assert_eq!(mutated(src, &sites).len(), 18);
3707        let changes: Vec<String> = sites
3708            .iter()
3709            .flat_map(source_mutants)
3710            .map(|m| {
3711                format!(
3712                    "{} -> {} | `{}` becomes `{}`",
3713                    m.what,
3714                    m.into,
3715                    &src[m.start..m.end],
3716                    m.replacement
3717                )
3718            })
3719            .collect();
3720        assert_eq!(
3721            changes,
3722            [
3723                // An arm goes by a guard that is never true.
3724                "arm -> K::A(n) if n >= 1 | `n >= 1` becomes `false`",
3725                "arm -> K::B | `` becomes `if false `",
3726                "guard -> true | `n >= 1` becomes `true`",
3727                ">= -> < | ` >= ` becomes ` < `",
3728                "|| -> && | `!(a != b) || a <= -b` becomes `(!(a != b)) && (a <= -b)`",
3729                "! ->  | `!` becomes ``",
3730                "!= -> == | ` != ` becomes ` == `",
3731                "<= -> > | ` <= ` becomes ` > `",
3732                "- ->  | `-` becomes ``",
3733                "&& -> || | `a % b > 0 && a == b` becomes `(a % b > 0 || a == b)`",
3734                "> -> == | ` > ` becomes ` == `",
3735                "> -> < | ` > ` becomes ` < `",
3736                "> -> >= | ` > ` becomes ` >= `",
3737                "% -> / | ` % ` becomes ` / `",
3738                "% -> + | `a % b` becomes `(a + b)`",
3739                "== -> != | ` == ` becomes ` != `",
3740                "field -> on | `x` becomes `(base).on`",
3741                "field -> a | `a` becomes `a: (base).a`",
3742            ]
3743        );
3744        // What exists only as a probe has no mutant of the source.
3745        let src = "fn f(a: u8, b: u8) -> bool { g(); for _ in a..b {} a.max(b) > 1 }";
3746        let sites = discover(src, 0).unwrap().sites;
3747        for site in &sites {
3748            let none = matches!(
3749                site.kind,
3750                SiteKind::Return { .. } | SiteKind::Stmt | SiteKind::MinMax { .. }
3751            );
3752            assert_eq!(source_mutants(site).is_empty(), none, "{:?}", site.kind);
3753        }
3754        // A range has its end taken in or left out, whichever it is not.
3755        let ends = |src: &str| -> Vec<String> {
3756            discover(src, 0)
3757                .unwrap()
3758                .sites
3759                .iter()
3760                .filter(|site| matches!(site.kind, SiteKind::Range { .. }))
3761                .flat_map(source_mutants)
3762                .map(|m| format!("{}{}{}", &src[..m.start], m.replacement, &src[m.end..]))
3763                .collect()
3764        };
3765        assert_eq!(
3766            ends("fn f(a: u8, b: u8) { for _ in a..b {} }"),
3767            ["fn f(a: u8, b: u8) { for _ in a..=b {} }"]
3768        );
3769        assert_eq!(
3770            ends("fn f(a: u8, b: u8) { for _ in a ..= b {} }"),
3771            ["fn f(a: u8, b: u8) { for _ in a..b {} }"]
3772        );
3773    }
3774
3775    #[test]
3776    fn iterators_to_return_instead() {
3777        let values = |ty: &str| {
3778            let function: syn::ItemFn =
3779                syn::parse_str(&format!("fn f() -> {ty} {{ todo!() }}")).unwrap();
3780            iterator_values(&function.sig.output)
3781        };
3782        assert_eq!(
3783            values("impl Iterator<Item = bool>"),
3784            [
3785                "::core::iter::empty()",
3786                "::core::iter::once(true)",
3787                "::core::iter::once(false)"
3788            ]
3789        );
3790        assert_eq!(
3791            values("impl std::iter::Iterator<Item = String> + Send + 'a").len(),
3792            3
3793        );
3794        // The item is the binding called `Item`, wherever it stands.
3795        assert_eq!(
3796            values("impl Iterator<Extra = u8, Item = ()>"),
3797            ["::core::iter::empty()", "::core::iter::once(())"]
3798        );
3799        // An item that is itself opaque has no value to make up.
3800        assert_eq!(
3801            values("impl Iterator<Item = impl Sized>"),
3802            ["::core::iter::empty()"]
3803        );
3804        for other in [
3805            "impl Sized",
3806            "impl Iterator",
3807            "impl IntoIterator<Item = u8>",
3808            "Box<dyn Iterator<Item = u8>>",
3809            "u8",
3810            "()",
3811        ] {
3812            assert!(values(other).is_empty(), "{other}");
3813        }
3814        let unit: syn::ItemFn = syn::parse_str("fn f() {}").unwrap();
3815        assert!(iterator_values(&unit.sig.output).is_empty());
3816    }
3817
3818    /// The source with each mutant of its sites that are built, one after the other.
3819    fn built(src: &str) -> Vec<String> {
3820        let found = discover(src, 0).unwrap();
3821        found
3822            .rebuild_sites
3823            .iter()
3824            .flat_map(source_mutants)
3825            .map(|m| format!("{}{}{}", &src[..m.start], m.replacement, &src[m.end..]))
3826            .collect()
3827    }
3828
3829    #[test]
3830    fn a_body_that_is_written_as_the_value_and_one_that_only_computes() {
3831        let bodies = |src: &str| -> Vec<(String, bool)> {
3832            discover(src, 0)
3833                .unwrap()
3834                .sites
3835                .iter()
3836                .filter_map(|site| match &site.kind {
3837                    SiteKind::Body {
3838                        value, sole_expr, ..
3839                    } => Some((value.clone(), sole_expr.is_some())),
3840                    _ => None,
3841                })
3842                .collect()
3843        };
3844        let values = |src: &str| -> Vec<String> { bodies(src).into_iter().map(|b| b.0).collect() };
3845        // The value the body already is makes no mutant, however it is spaced.
3846        assert_eq!(values("fn t() -> bool { true }"), ["false"]);
3847        assert_eq!(values("fn n() -> u8 {  0  }"), ["1"]);
3848        assert_eq!(
3849            values("fn s() -> String { String :: new () }"),
3850            ["\"xyzzy\".into()"]
3851        );
3852        // White space inside a literal is not spacing: `" "` is not the empty string.
3853        assert_eq!(
3854            values("fn s() -> &'static str { \" \" }"),
3855            ["\"\"", "\"xyzzy\""]
3856        );
3857        // A body that only computes its value can be said at that expression; one
3858        // that calls, assigns or leaves early does more than give a value.
3859        for (body, only_computes) in [
3860            ("n > 0", true),
3861            ("!(self.limit < n) && n as u8 != 3", true),
3862            ("(n, 1).0 > *&n", true),
3863            ("self.push(n) > 0", false),
3864            ("next() > 0", false),
3865            ("matches!(n, 1)", false),
3866            ("(if n > 1 { n } else { 0 }) > 0", false),
3867            ("list[n] > 0", false),
3868            ("check(n)? > 0", false),
3869            ("(self.count += n) == ()", false),
3870            ("(self.count = n) == ()", false),
3871        ] {
3872            let src = format!("impl S {{ fn f(&mut self, n: usize) -> bool {{ {body} }} }}");
3873            let all = bodies(&src);
3874            assert_eq!(all.len(), 2, "{body}");
3875            assert!(all.iter().all(|b| b.1 == only_computes), "{body}: {all:?}");
3876        }
3877    }
3878
3879    #[test]
3880    fn items_are_named_by_what_is_around_them() {
3881        let src = "fn top(a: u8) -> u8 { fn inner(b: u8) -> u8 { b } inner(a) }\n\
3882                   mod m { pub fn in_mod() {} const K: u8 = 1; }\n\
3883                   impl Store { fn commit(&self) {} const LIMIT: u8 = 2; }\n\
3884                   impl<T> fmt::Display for Id<T> { fn fmt(&self) {} }\n\
3885                   trait Tr { fn provided(&self) {} fn required(&self); }\n\
3886                   static S: u8 = 3;\nlet";
3887        // Not a source file: nothing is named.
3888        assert!(named_items(src).is_empty());
3889        let src = src.strip_suffix("let").unwrap();
3890        let items = named_items(src);
3891        let names: Vec<&str> = items.iter().map(|item| item.name.as_str()).collect();
3892        assert_eq!(
3893            names,
3894            [
3895                "top",
3896                "top::inner",
3897                "m::in_mod",
3898                "m::K",
3899                "Store::commit",
3900                "Store::LIMIT",
3901                "<fmt::Display for Id<T>>::fmt",
3902                "Tr::provided",
3903                "Tr::required",
3904                "S",
3905            ]
3906        );
3907        // The innermost item a place is in; none between the items.
3908        let at = |text: &str| src.find(text).unwrap();
3909        assert_eq!(enclosing_item(&items, at("{ b }") + 2), "top::inner");
3910        assert_eq!(enclosing_item(&items, at("inner(a)")), "top");
3911        assert_eq!(enclosing_item(&items, at("fn top")), "top");
3912        assert_eq!(enclosing_item(&items, at("mod m")), "");
3913        assert_eq!(enclosing_item(&items, at("= 2") + 2), "Store::LIMIT");
3914        assert_eq!(enclosing_item(&items, src.len()), "");
3915        // An item is its first byte to its last, and not a byte more on either side.
3916        let (first, after) = (at("pub fn in_mod"), at("pub fn in_mod() {}") + 18);
3917        assert_eq!(enclosing_item(&items, first - 1), "");
3918        assert_eq!(enclosing_item(&items, first), "m::in_mod");
3919        assert_eq!(enclosing_item(&items, after - 1), "m::in_mod");
3920        assert_eq!(enclosing_item(&items, after), "");
3921        // Lines and columns count from one, columns in characters.
3922        let text = "ab\nçd e\n";
3923        assert_eq!(offset_of(text, 1, 1), Some(0));
3924        assert_eq!(offset_of(text, 1, 2), Some(1));
3925        assert_eq!(offset_of(text, 2, 1), Some(3));
3926        assert_eq!(offset_of(text, 2, 2), Some(5), "after the two bytes of `ç`");
3927        assert_eq!(offset_of(text, 2, 99), Some(text.len()));
3928        assert_eq!(offset_of(text, 0, 1), None);
3929        assert_eq!(offset_of(text, 1, 0), None);
3930    }
3931
3932    #[test]
3933    fn only_the_range_of_a_for_is_probed() {
3934        let src = "fn f(a: u8, b: u8, v: &[u8]) -> usize {\n\
3935                   for _ in a..b {}\n\
3936                   for _ in (a..=b) {}\n\
3937                   for _ in (a..b).rev() {}\n\
3938                   let kept = a..b;\n\
3939                   let _ = &v[a as usize..b as usize];\n\
3940                   for _ in kept.clone() {}\n\
3941                   for _ in 0..3 {}\n\
3942                   let _ = &v[0..3];\n\
3943                   (a..=b).count() }";
3944        let all = discover(src, 0).unwrap();
3945        let ranges = |sites: &[Site]| -> Vec<usize> {
3946            sites
3947                .iter()
3948                .filter(|site| matches!(site.kind, SiteKind::Range { .. }))
3949                .map(|site| site.line)
3950                .collect()
3951        };
3952        // Run through directly by a `for`, with or without parentheses.
3953        assert_eq!(ranges(&all.sites), [2, 3]);
3954        // Kept, indexed with, or given to a method: built, as the source says them.
3955        // And two literals wherever they are: nothing gives a probe their type.
3956        assert_eq!(ranges(&all.rebuild_sites), [4, 5, 6, 8, 9, 10]);
3957        let literal: Vec<(&str, String)> = all
3958            .rebuild_sites
3959            .iter()
3960            .filter(|site| site.line == 8 || site.line == 9)
3961            .flat_map(|site| {
3962                source_mutants(site)
3963                    .into_iter()
3964                    .map(move |mutant| (site.text.as_str(), mutant.replacement))
3965            })
3966            .collect();
3967        assert_eq!(
3968            literal,
3969            [("0..3", "..=".to_string()), ("0..3", "..=".to_string())]
3970        );
3971    }
3972
3973    #[test]
3974    fn what_marks_code_as_not_to_be_mutated() {
3975        let src = "#[allow(mutants, skip)] fn loosely(a: u8) -> u8 { a + 1 }\n\
3976                   #[doc = \"mutants skip\"] fn spoken_of(a: u8) -> u8 { a + 2 }\n\
3977                   #[mutants :: skip] fn spaced(a: u8) -> u8 { a + 3 }\n\
3978                   #[cfg_attr(test, mutants::skip)] fn conditional(a: u8) -> u8 { a + 4 }\n\
3979                   #[mutants::skip] mod generated;\n\
3980                   #[mutants::skip] #[path = \"gen/other.rs\"] mod other;\n\
3981                   mod plain;\n\
3982                   mod inline { fn inner(a: u8) -> u8 { a + 5 } }\n\
3983                   #[mutants::skip] mod marked { fn inner(a: u8) -> u8 { a + 6 } }\n";
3984        let all = discover(src, 0).unwrap();
3985        let texts: Vec<&str> = found_arith(&all.sites);
3986        assert_eq!(texts, ["a + 1", "a + 2", "a + 5"]);
3987        // The file of a marked module is not looked into either.
3988        assert_eq!(
3989            all.test_modules,
3990            [
3991                TestModule {
3992                    name: "generated".to_string(),
3993                    path: None
3994                },
3995                TestModule {
3996                    name: "other".to_string(),
3997                    path: Some("gen/other.rs".to_string())
3998                },
3999            ]
4000        );
4001    }
4002
4003    fn found_arith(sites: &[Site]) -> Vec<&str> {
4004        sites
4005            .iter()
4006            .filter(|site| matches!(site.kind, SiteKind::Arith { .. }))
4007            .map(|site| site.text.as_str())
4008            .collect()
4009    }
4010
4011    #[test]
4012    fn a_replaced_operator_keeps_its_operands() {
4013        // Every replacement is the same tree with another operator, also where the new
4014        // operator binds otherwise than the old one.
4015        assert_eq!(
4016            built("const X: i32 = 8 - 2 * 3;"),
4017            [
4018                "const X: i32 = 8 + 2 * 3;",
4019                "const X: i32 = (8) / (2 * 3);",
4020                "const X: i32 = 8 - 2 / 3;",
4021                "const X: i32 = 8 - (2 + 3);",
4022            ]
4023        );
4024        assert_eq!(
4025            built("const B: bool = P || Q && R;"),
4026            [
4027                "const B: bool = (P) && (Q && R);",
4028                "const B: bool = P || (Q || R);",
4029            ]
4030        );
4031        assert_eq!(
4032            built("const M: u8 = A & B | C;"),
4033            [
4034                "const M: u8 = (A & B) & (C);",
4035                "const M: u8 = (A & B) ^ (C);",
4036                "const M: u8 = (A | B) | C;",
4037                "const M: u8 = (A ^ B) | C;",
4038            ]
4039        );
4040        assert_eq!(
4041            built("const S: u8 = 1 << 2 + 1;"),
4042            [
4043                "const S: u8 = 1 >> 2 + 1;",
4044                "const S: u8 = 1 << 2 - 1;",
4045                "const S: u8 = 1 << (2) * (1);",
4046            ]
4047        );
4048        // Comparisons bind alike, and an assignment has its operands to itself.
4049        assert_eq!(
4050            built("const C: bool = A + 1 < B;")[..3],
4051            [
4052                "const C: bool = A + 1 == B;",
4053                "const C: bool = A + 1 > B;",
4054                "const C: bool = A + 1 <= B;",
4055            ]
4056        );
4057        let assigned = built("const fn f(mut x: u8) -> u8 { x += 2 * 3; x }");
4058        for expected in [
4059            "const fn f(mut x: u8) -> u8 { x -= 2 * 3; x }",
4060            "const fn f(mut x: u8) -> u8 { x *= 2 * 3; x }",
4061            "const fn f(mut x: u8) -> u8 { x += (2 + 3); x }",
4062        ] {
4063            assert!(assigned.iter().any(|text| text == expected), "{assigned:?}");
4064        }
4065    }
4066
4067    #[test]
4068    fn constants_and_literal_arithmetic_are_mutated_in_the_source() {
4069        let src = "const HALF: u64 = SPAN / 2;\n\
4070                   static LIMIT: i32 = -(1 << 4);\n\
4071                   impl S { const K: bool = A < B; }\n\
4072                   trait T { const D: u8 = 3 + 4; const R: u8; }\n\
4073                   #[cfg(test)]\n\
4074                   const ONLY_IN_TESTS: u8 = 5 + 6;\n\
4075                   #[mutants::skip]\n\
4076                   const MARKED: u8 = 7 + 8;\n\
4077                   #[cfg(test)]\n\
4078                   static TEST_LIMIT: u8 = 9 + 1;\n\
4079                   impl S { #[mutants::skip] const SKIPPED: u8 = 9 + 2; }\n\
4080                   trait U { #[cfg(test)] const ONLY: u8 = 9 + 3; }\n\
4081                   fn f(x: u32) -> u32 { let _ = [0u8; 2 + 3]; x + 60 * 60 }\n\
4082                   fn one(s: &mut S) { s.go(); }\n\
4083                   fn two(s: &mut S) { s.go(); s.stop(); }\n\
4084                   fn value(s: &mut S) -> u8 { s.get() }\n";
4085        let found = discover(src, 0).unwrap();
4086        let built: Vec<String> = found
4087            .rebuild_sites
4088            .iter()
4089            .flat_map(|site| {
4090                source_mutants(site)
4091                    .into_iter()
4092                    .map(|m| format!("{}: {} -> {}", site.text, m.what, m.into))
4093            })
4094            .collect();
4095        assert_eq!(
4096            built,
4097            [
4098                "SPAN / 2: / -> *",
4099                "SPAN / 2: / -> %",
4100                "-(1 << 4): - -> ",
4101                "1 << 4: << -> >>",
4102                "A < B: < -> ==",
4103                "A < B: < -> >",
4104                "A < B: < -> <=",
4105                "3 + 4: + -> -",
4106                "3 + 4: + -> *",
4107                // Two literals in ordinary code too: a probe would give them a type.
4108                "60 * 60: * -> /",
4109                "60 * 60: * -> +",
4110            ]
4111        );
4112        mutated(src, &found.rebuild_sites);
4113        // The rest of that function is probed as usual; an array length is left alone.
4114        let probed: Vec<&str> = found
4115            .sites
4116            .iter()
4117            .filter(|s| matches!(s.kind, SiteKind::Arith { .. }))
4118            .map(|s| s.text.as_str())
4119            .collect();
4120        assert_eq!(probed, ["x + 60 * 60"]);
4121        // An empty body is not made where deleting the one statement is the same thing.
4122        assert_eq!(found.single_statement_bodies, ["one"]);
4123        let bodies: Vec<String> = found
4124            .sites
4125            .iter()
4126            .filter_map(|s| match &s.kind {
4127                SiteKind::Body { name, value, .. } => Some(format!("{name} {value}")),
4128                _ => None,
4129            })
4130            .collect();
4131        assert_eq!(bodies, ["f 0", "f 1", "two ()", "value 0", "value 1"]);
4132    }
4133}