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