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