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        // tmt:ignore performance only: the set answers what `probe_values.contains` answers
459        let probe_index = (probe_values.len() > 32).then(|| {
460            probe_values
461                .iter()
462                .map(String::as_str)
463                .collect::<HashSet<_>>()
464        });
465        for value in body_values_with_errors(&sig.output, self.error_values, true) {
466            let is_probe = probe_index.as_ref().map_or_else(
467                || probe_values.contains(&value),
468                |index| index.contains(value.as_str()),
469            );
470            if !is_probe && !is_written(&value) {
471                self.add_rebuild(Site {
472                    id: NO_ID,
473                    kind: SiteKind::Body {
474                        name: name.clone(),
475                        value,
476                        sole_expr: sole_plain,
477                    },
478                    line: at.line,
479                    column: at.column + 1,
480                    start,
481                    end,
482                    text: text.clone(),
483                });
484            }
485        }
486        for value in probe_values {
487            if !is_written(&value) {
488                push(
489                    self,
490                    SiteKind::Body {
491                        name: name.clone(),
492                        value,
493                        sole_expr: sole_plain,
494                    },
495                );
496            }
497        }
498    }
499
500    /// `Some(None)` for a function that returns `bool`, `Some(Some(type))` for one that
501    /// returns `Option<T>` written in a way a `let` can repeat.
502    fn result_kind(&self, output: &syn::ReturnType) -> Option<Option<String>> {
503        let syn::ReturnType::Type(_, ty) = output else {
504            return None;
505        };
506        match &**ty {
507            // `<T>::bool` and `<T as Tr>::bool` are not a single identifier either.
508            syn::Type::Path(p) if p.path.is_ident("bool") => Some(None),
509            syn::Type::Path(p)
510                if p.qself.is_none()
511                    && p.path.segments.last().is_some_and(|s| {
512                        s.ident == "Option"
513                            && matches!(s.arguments, syn::PathArguments::AngleBracketed(_))
514                    }) =>
515            {
516                match self
517                    .range(ty.span())
518                    .map(|(from, to)| &self.source[from..to])
519                {
520                    // `impl Trait` cannot be written in a `let`.
521                    Some(written) if !written.contains("impl ") => Some(Some(written.to_string())),
522                    _ => None,
523                }
524            }
525            _ => None,
526        }
527    }
528    fn range(&self, span: Span) -> Option<(usize, usize)> {
529        let range = span.byte_range();
530        // Spans produced by macro hygiene tricks or empty token streams carry no location.
531        // tmt:ignore defensive: every span of a file parsed from `source` lies inside it
532        let located = !range.is_empty() && self.source.get(range.clone()).is_some();
533        located.then_some((range.start, range.end))
534    }
535
536    fn push(&mut self, kind: SiteKind, start: usize, end: usize, span: Span) {
537        let at = span.start();
538        self.add(Site {
539            id: 0,
540            kind,
541            line: at.line,
542            column: at.column + 1,
543            start,
544            end,
545            text: self.source[start..end].to_string(),
546        });
547    }
548
549    /// The value of a `const` or `static`. The compiler computes it: like the code of a
550    /// `const fn`, it is mutated by building.
551    fn constant(&mut self, attrs: &[syn::Attribute], value: &syn::Expr) {
552        if !is_test_only(attrs) && !is_skipped(attrs) {
553            self.const_depth += 1;
554            self.visit_expr(value);
555            self.const_depth -= 1;
556        }
557    }
558
559    fn typed_constant(
560        &mut self,
561        attrs: &[syn::Attribute],
562        ty: &syn::Type,
563        value: Option<&syn::Expr>,
564    ) {
565        if !is_test_only(attrs) && !is_skipped(attrs) {
566            self.visit_type(ty);
567            if let Some(value) = value {
568                self.constant(&[], value);
569            }
570        }
571    }
572
573    /// Registers a site: numbered, or among those that need a build of their own.
574    fn add_rebuild(&mut self, mut site: Site) {
575        site.id = NO_ID;
576        self.found.rebuild_sites.push(site);
577    }
578
579    fn add(&mut self, mut site: Site) {
580        if self.const_depth > 0 {
581            self.add_rebuild(site);
582        } else {
583            site.id = self.next_id;
584            self.found.sites.push(site);
585            self.next_id += 1;
586        }
587    }
588}
589
590fn cmp_op(op: &syn::BinOp) -> Option<CmpOp> {
591    Some(match op {
592        syn::BinOp::Lt(_) => CmpOp::Lt,
593        syn::BinOp::Le(_) => CmpOp::Le,
594        syn::BinOp::Gt(_) => CmpOp::Gt,
595        syn::BinOp::Ge(_) => CmpOp::Ge,
596        syn::BinOp::Eq(_) => CmpOp::Eq,
597        syn::BinOp::Ne(_) => CmpOp::Ne,
598        _ => return None,
599    })
600}
601
602/// The arithmetic or bit operator, and whether it is the compound assignment form.
603fn arith_op(op: &syn::BinOp) -> Option<(ArithOp, bool)> {
604    use syn::BinOp as B;
605    Some(match op {
606        B::Add(_) => (ArithOp::Add, false),
607        B::Sub(_) => (ArithOp::Sub, false),
608        B::Mul(_) => (ArithOp::Mul, false),
609        B::Div(_) => (ArithOp::Div, false),
610        B::Rem(_) => (ArithOp::Rem, false),
611        B::BitAnd(_) => (ArithOp::BitAnd, false),
612        B::BitOr(_) => (ArithOp::BitOr, false),
613        B::BitXor(_) => (ArithOp::BitXor, false),
614        B::Shl(_) => (ArithOp::Shl, false),
615        B::Shr(_) => (ArithOp::Shr, false),
616        B::AddAssign(_) => (ArithOp::Add, true),
617        B::SubAssign(_) => (ArithOp::Sub, true),
618        B::MulAssign(_) => (ArithOp::Mul, true),
619        B::DivAssign(_) => (ArithOp::Div, true),
620        B::RemAssign(_) => (ArithOp::Rem, true),
621        B::BitAndAssign(_) => (ArithOp::BitAnd, true),
622        B::BitOrAssign(_) => (ArithOp::BitOr, true),
623        B::BitXorAssign(_) => (ArithOp::BitXor, true),
624        B::ShlAssign(_) => (ArithOp::Shl, true),
625        B::ShrAssign(_) => (ArithOp::Shr, true),
626        _ => return None,
627    })
628}
629
630/// A place whose evaluation has no effect and cannot fail: a variable, a field of one, or
631/// a dereference of one.
632///
633/// For numbers `place op= value` evaluates `value` first, for other types `place` first.
634/// The probe always takes the place first, which is the same thing only when evaluating
635/// the place cannot be observed. Indexing can panic and calls can do anything, so
636/// `v[i] += 1` and `f().x += 1` are not instrumented as operators (they can still be
637/// deleted as statements).
638fn is_plain_place(expr: &syn::Expr) -> bool {
639    match expr {
640        syn::Expr::Path(e) => e.attrs.is_empty(),
641        syn::Expr::Field(e) => is_plain_place(&e.base),
642        syn::Expr::Unary(syn::ExprUnary {
643            op: syn::UnOp::Deref(_),
644            expr,
645            ..
646        }) => is_plain_place(expr),
647        syn::Expr::Paren(e) => is_plain_place(&e.expr),
648        syn::Expr::Group(e) => is_plain_place(&e.expr),
649        _ => false,
650    }
651}
652
653fn is_literal(expr: &syn::Expr) -> bool {
654    match expr {
655        syn::Expr::Paren(e) => is_literal(&e.expr),
656        syn::Expr::Group(e) => is_literal(&e.expr),
657        syn::Expr::Lit(_) => true,
658        syn::Expr::Unary(syn::ExprUnary {
659            op: syn::UnOp::Neg(_),
660            expr,
661            ..
662        }) => is_literal(expr),
663        _ => false,
664    }
665}
666
667/// The spans of the parts of one parsed expression come in source order. The edits are
668/// built on that, so it is checked rather than assumed; no source makes it false.
669// tmt:ignore defensive: never false, so no test can make it return false
670fn in_order(earlier: usize, later: usize) -> bool {
671    earlier <= later // tmt:ignore defensive: as above
672}
673
674/// `if let P = e && cond` is a let chain, not a boolean expression: it cannot be wrapped.
675fn in_let_chain(expr: &syn::Expr) -> bool {
676    match expr {
677        syn::Expr::Let(_) => true,
678        syn::Expr::Binary(syn::ExprBinary {
679            op: syn::BinOp::And(_),
680            left,
681            right,
682            ..
683        }) => in_let_chain(left) || matches!(**right, syn::Expr::Let(_)),
684        _ => false,
685    }
686}
687
688/// Macros whose arguments are ordinary expressions separated by commas. Macros that turn
689/// their argument into text (`assert!`, `debug_assert!`, `dbg!`, `stringify!`) are left
690/// alone: rewriting the argument would change the message a test may expect.
691const EXPR_MACROS: [&str; 18] = [
692    "assert_eq",
693    "assert_ne",
694    "debug_assert_eq",
695    "debug_assert_ne",
696    "vec",
697    "format",
698    "print",
699    "println",
700    "eprint",
701    "eprintln",
702    "write",
703    "writeln",
704    "panic",
705    "unreachable",
706    "todo",
707    "unimplemented",
708    "format_args",
709    "matches",
710];
711
712fn is_assign_op(op: &syn::BinOp) -> bool {
713    use syn::BinOp::*;
714    matches!(
715        op,
716        AddAssign(_)
717            | SubAssign(_)
718            | MulAssign(_)
719            | DivAssign(_)
720            | RemAssign(_)
721            | BitXorAssign(_)
722            | BitAndAssign(_)
723            | BitOrAssign(_)
724            | ShlAssign(_)
725            | ShrAssign(_)
726    )
727}
728
729fn int_literal(expr: &syn::Expr) -> Option<i128> {
730    match expr {
731        syn::Expr::Paren(e) => int_literal(&e.expr),
732        syn::Expr::Group(e) => int_literal(&e.expr),
733        syn::Expr::Lit(syn::ExprLit {
734            lit: syn::Lit::Int(lit),
735            ..
736        }) => lit.base10_parse().ok(),
737        syn::Expr::Unary(syn::ExprUnary {
738            op: syn::UnOp::Neg(_),
739            expr,
740            ..
741        }) => int_literal(expr).and_then(i128::checked_neg),
742        _ => None,
743    }
744}
745
746/// Statements whose removal is a plausible bug: a forgotten call, check or update.
747fn deletable(expr: &syn::Expr) -> bool {
748    match expr {
749        syn::Expr::Call(e) => e.attrs.is_empty(),
750        syn::Expr::MethodCall(e) => e.attrs.is_empty(),
751        syn::Expr::Assign(e) => e.attrs.is_empty(),
752        // An attribute in front of `a += 1` belongs to `a`, never to the operation.
753        syn::Expr::Binary(e) => is_assign_op(&e.op),
754        syn::Expr::Try(e) => e.attrs.is_empty() && deletable_call(&e.expr),
755        syn::Expr::Await(e) => e.attrs.is_empty() && deletable_call(&e.base),
756        _ => false,
757    }
758}
759
760fn deletable_call(expr: &syn::Expr) -> bool {
761    match expr {
762        syn::Expr::Call(_) | syn::Expr::MethodCall(_) => true,
763        syn::Expr::Await(e) => deletable_call(&e.base),
764        _ => false,
765    }
766}
767
768fn has_ident(tokens: TokenStream, name: &str) -> bool {
769    tokens.into_iter().any(|tree| match tree {
770        TokenTree::Ident(ident) => ident == name,
771        TokenTree::Group(group) => has_ident(group.stream(), name),
772        _ => false,
773    })
774}
775
776/// The number of a site that has none.
777pub const NO_ID: u32 = u32::MAX;
778
779/// A function or constant of a file with the stretch of source it takes up, named by the
780/// modules, impls and functions around it: `Store::commit`, `<Display for Id>::fmt`.
781#[derive(Debug, PartialEq, Eq, Clone)]
782pub struct NamedItem {
783    pub start: usize,
784    pub end: usize,
785    pub name: String,
786}
787
788/// The functions and constants of a source file. A finding is told from another one on
789/// the same code by the item it is in, which stays the same when lines move.
790pub fn named_items(source: &str) -> Vec<NamedItem> {
791    struct Namer {
792        path: Vec<String>,
793        items: Vec<NamedItem>,
794    }
795    impl Namer {
796        fn inside(&mut self, name: String, span: Option<Span>, visit: impl FnOnce(&mut Self)) {
797            self.path.push(name);
798            if let Some(span) = span {
799                let range = span.byte_range();
800                self.items.push(NamedItem {
801                    start: range.start,
802                    end: range.end,
803                    name: self.path.join("::"),
804                });
805            }
806            visit(self);
807            self.path.pop();
808        }
809    }
810    impl<'ast> Visit<'ast> for Namer {
811        fn visit_item_mod(&mut self, node: &'ast syn::ItemMod) {
812            self.inside(node.ident.to_string(), None, |namer| {
813                visit::visit_item_mod(namer, node)
814            });
815        }
816        fn visit_item_trait(&mut self, node: &'ast syn::ItemTrait) {
817            self.inside(node.ident.to_string(), None, |namer| {
818                visit::visit_item_trait(namer, node)
819            });
820        }
821        fn visit_item_impl(&mut self, node: &'ast syn::ItemImpl) {
822            let of = squeezed(&node.self_ty.to_token_stream().to_string());
823            let name = match &node.trait_ {
824                Some((_, path, _)) => {
825                    format!(
826                        "<{} for {of}>",
827                        squeezed(&path.to_token_stream().to_string())
828                    )
829                }
830                None => of,
831            };
832            self.inside(name, None, |namer| visit::visit_item_impl(namer, node));
833        }
834        fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
835            self.inside(node.sig.ident.to_string(), Some(node.span()), |namer| {
836                visit::visit_item_fn(namer, node)
837            });
838        }
839        fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
840            self.inside(node.sig.ident.to_string(), Some(node.span()), |namer| {
841                visit::visit_impl_item_fn(namer, node)
842            });
843        }
844        fn visit_trait_item_fn(&mut self, node: &'ast syn::TraitItemFn) {
845            self.inside(node.sig.ident.to_string(), Some(node.span()), |namer| {
846                visit::visit_trait_item_fn(namer, node)
847            });
848        }
849        fn visit_item_const(&mut self, node: &'ast syn::ItemConst) {
850            self.inside(node.ident.to_string(), Some(node.span()), |_| {});
851        }
852        fn visit_item_static(&mut self, node: &'ast syn::ItemStatic) {
853            self.inside(node.ident.to_string(), Some(node.span()), |_| {});
854        }
855        fn visit_impl_item_const(&mut self, node: &'ast syn::ImplItemConst) {
856            self.inside(node.ident.to_string(), Some(node.span()), |_| {});
857        }
858    }
859    let Ok(file) = syn::parse_file(source) else {
860        return vec![];
861    };
862    let mut namer = Namer {
863        path: vec![],
864        items: vec![],
865    };
866    namer.visit_file(&file);
867    namer.items
868}
869
870/// The name of the innermost item that `offset` lies in; empty outside of all of them.
871pub fn enclosing_item(items: &[NamedItem], offset: usize) -> &str {
872    items
873        .iter()
874        .filter(|item| item.start <= offset && offset < item.end)
875        .min_by_key(|item| item.end - item.start)
876        .map_or("", |item| item.name.as_str())
877}
878
879/// Where the 1-based `line` and `column` (in characters) of a source text are, in bytes.
880pub fn offset_of(source: &str, line: usize, column: usize) -> Option<usize> {
881    let start: usize = source
882        .split_inclusive('\n')
883        .take(line.checked_sub(1)?)
884        .map(str::len)
885        .sum();
886    let rest = source.get(start..)?;
887    let within = rest
888        .char_indices()
889        .nth(column.checked_sub(1)?)
890        .map_or(rest.len(), |(at, _)| at);
891    Some(start + within)
892}
893
894/// The innermost item's name for each interval between item boundaries.
895pub(crate) struct ItemIndex<'a>(Vec<(usize, &'a str)>);
896
897impl<'a> ItemIndex<'a> {
898    pub(crate) fn new(items: &'a [NamedItem]) -> Self {
899        use std::{cmp::Reverse, collections::BinaryHeap};
900
901        let mut starts: Vec<_> = items.iter().enumerate().collect();
902        starts.sort_unstable_by_key(|&(_, item)| item.start);
903        let mut boundaries: Vec<_> = items
904            .iter()
905            .flat_map(|item| [item.start, item.end])
906            .collect();
907        boundaries.sort_unstable();
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 arm in &node.arms {
1913            if is_test_only(&arm.attrs) || is_skipped(&arm.attrs) {
1914                continue;
1915            }
1916            // The last arm is not probed: where it takes everything, it is a catch-all.
1917            let probe = final_catches_all && arm.attrs.is_empty() && !catches_all(arm);
1918            let literal =
1919                has_wildcard && !matches!(arm.pat, syn::Pat::Wild(_)) && arm.guard.is_none();
1920            if !probe && !literal {
1921                continue;
1922            }
1923            let (Some((start, pat_end)), Some((remove_start, remove_end)), Some((arrow, _))) = (
1924                self.range(arm.pat.span()),
1925                self.range(arm.span()),
1926                self.range(arm.fat_arrow_token.span()),
1927            ) else {
1928                continue;
1929            };
1930            let guard = match &arm.guard {
1931                None => ArmGuard::None(arrow),
1932                Some((_, expr)) => match self.range(expr.span()) {
1933                    Some((from, to)) => ArmGuard::Existing(from, to),
1934                    None => continue,
1935                },
1936            };
1937            let pattern = match guard {
1938                ArmGuard::Existing(from, to) => format!(
1939                    "{} if {}",
1940                    &self.source[start..pat_end],
1941                    &self.source[from..to]
1942                ),
1943                ArmGuard::None(_) => self.source[start..pat_end].to_string(),
1944            };
1945            let end = arm
1946                .comma
1947                .as_ref()
1948                .and_then(|comma| self.range(comma.span()))
1949                .map_or(remove_end, |(_, end)| end);
1950            let at = arm.pat.span().start();
1951            removable.push(start);
1952            let site = Site {
1953                id: 0,
1954                kind: SiteKind::Arm {
1955                    pattern: pattern.clone(),
1956                    guard,
1957                    removal: (remove_start, end),
1958                },
1959                line: at.line,
1960                column: at.column + 1,
1961                start,
1962                end,
1963                text: format!("{pattern} => .."),
1964            };
1965            if probe {
1966                self.add(site);
1967            } else {
1968                self.add_rebuild(site);
1969            }
1970        }
1971        // Any guard can be `true` or `false` instead: a guarded arm never counts for
1972        // the match being exhaustive. A `let` in a guard binds names for the arm.
1973        for arm in node.arms.iter().filter(|arm| arm.attrs.is_empty()) {
1974            if let Some((_, guard)) = &arm.guard
1975                && !matches!(**guard, syn::Expr::Let(_))
1976                && !in_let_chain(guard)
1977                && let (Some((start, end)), Some((pattern, _))) =
1978                    (self.range(guard.span()), self.range(arm.pat.span()))
1979            {
1980                let kind = SiteKind::Guard {
1981                    can_be_false: !removable.contains(&pattern),
1982                };
1983                self.push(kind, start, end, guard.span());
1984            }
1985        }
1986        visit::visit_expr_match(self, node);
1987    }
1988
1989    fn visit_arm(&mut self, arm: &'ast syn::Arm) {
1990        if !is_test_only(&arm.attrs) && !is_skipped(&arm.attrs) {
1991            visit::visit_arm(self, arm);
1992        }
1993    }
1994
1995    fn visit_field_value(&mut self, field: &'ast syn::FieldValue) {
1996        if !is_test_only(&field.attrs) && !is_skipped(&field.attrs) {
1997            visit::visit_field_value(self, field);
1998        }
1999    }
2000
2001    fn visit_expr_struct(&mut self, node: &'ast syn::ExprStruct) {
2002        if is_test_only(&node.attrs) || is_skipped(&node.attrs) {
2003            return;
2004        }
2005        // Only probes read the base again. Source mutants delete a field in place.
2006        let from_base = node.rest.as_deref().and_then(|base| {
2007            if !node.attrs.is_empty() || node.qself.is_some() {
2008                return None;
2009            }
2010            let (from, to) = self.range(base.span())?;
2011            let written = &self.source[from..to];
2012            match base {
2013                base if is_plain_place(base) => Some(format!("({written})")),
2014                syn::Expr::Call(call)
2015                    if call.args.is_empty() && matches!(*call.func, syn::Expr::Path(_)) =>
2016                {
2017                    let (from, to) = self.range(node.path.span())?;
2018                    Some(format!("({} {{ ..{written} }})", &self.source[from..to]))
2019                }
2020                _ => None,
2021            }
2022        });
2023        if node.rest.is_some() {
2024            for pair in node.fields.pairs() {
2025                let field = pair.value();
2026                if is_test_only(&field.attrs) || is_skipped(&field.attrs) {
2027                    continue;
2028                }
2029                let name = match &field.member {
2030                    syn::Member::Named(name) => name.to_string(),
2031                    syn::Member::Unnamed(index) => index.index.to_string(),
2032                };
2033                let (Some((start, _)), Some((value, end)), Some((remove_start, _))) = (
2034                    self.range(field.member.span()),
2035                    self.range(field.expr.span()),
2036                    self.range(field.span()),
2037                ) else {
2038                    continue;
2039                };
2040                let remove_end = pair
2041                    .punct()
2042                    .and_then(|comma| self.range(comma.span()))
2043                    .map_or(end, |(_, end)| end);
2044                let from_base = from_base
2045                    .as_ref()
2046                    .filter(|_| field.attrs.is_empty())
2047                    .map(|base| format!("{base}.{name}"));
2048                let probe = from_base.is_some();
2049                let kind = SiteKind::Field {
2050                    from_base,
2051                    name,
2052                    shorthand: field.colon_token.is_none(),
2053                    removal: (remove_start, remove_end),
2054                };
2055                let at = field.member.span().start();
2056                let site = Site {
2057                    id: 0,
2058                    kind,
2059                    line: at.line,
2060                    column: at.column + 1,
2061                    start: if probe { value } else { remove_start },
2062                    end,
2063                    text: self.source[start..end].to_string(),
2064                };
2065                if probe {
2066                    self.add(site);
2067                } else {
2068                    self.add_rebuild(site);
2069                }
2070            }
2071        }
2072        visit::visit_expr_struct(self, node);
2073    }
2074
2075    fn visit_expr_unary(&mut self, node: &'ast syn::ExprUnary) {
2076        if let syn::UnOp::Not(bang) = &node.op
2077            && node.attrs.is_empty()
2078            && let (Some((start, _)), Some((operand_start, end))) =
2079                (self.range(bang.span()), self.range(node.expr.span()))
2080            && in_order(start, operand_start)
2081        {
2082            let kind = SiteKind::Not {
2083                bang: (start, operand_start),
2084                operand: self.source[operand_start..end].to_string(),
2085            };
2086            self.push(kind, start, end, bang.span());
2087        }
2088        if let syn::UnOp::Neg(minus) = &node.op
2089            && node.attrs.is_empty()
2090            && let (Some((start, _)), Some((operand_start, end))) =
2091                (self.range(minus.span()), self.range(node.expr.span()))
2092            && in_order(start, operand_start)
2093        {
2094            let zero = match &*node.expr {
2095                syn::Expr::Lit(syn::ExprLit {
2096                    lit: syn::Lit::Int(lit),
2097                    ..
2098                }) => lit.base10_parse::<u128>().is_ok_and(|v| v == 0),
2099                // Not a float: `-0.0` is not `0.0` (`1.0 / -0.0` is minus infinity).
2100                _ => false,
2101            };
2102            if !zero {
2103                let kind = SiteKind::Neg {
2104                    minus: (start, operand_start),
2105                    operand: self.source[operand_start..end].to_string(),
2106                    literal: matches!(*node.expr, syn::Expr::Lit(_)),
2107                };
2108                self.push(kind, start, end, minus.span());
2109            }
2110        }
2111        visit::visit_expr_unary(self, node);
2112    }
2113
2114    fn visit_expr_binary(&mut self, node: &'ast syn::ExprBinary) {
2115        if let Some(op) = cmp_op(&node.op)
2116            && node.attrs.is_empty()
2117            && let (Some((start, lhs_end)), Some((rhs_start, end))) =
2118                (self.range(node.left.span()), self.range(node.right.span()))
2119            && in_order(lhs_end, rhs_start)
2120        {
2121            let literal = match (int_literal(&node.left), int_literal(&node.right)) {
2122                (None, Some(k)) => LiteralSide::Rhs(k),
2123                (Some(k), None) => LiteralSide::Lhs(k),
2124                _ => LiteralSide::None,
2125            };
2126            let kind = SiteKind::Cmp {
2127                op,
2128                lhs: self.source[start..lhs_end].to_string(),
2129                rhs: self.source[rhs_start..end].to_string(),
2130                literal,
2131                gap: (lhs_end, rhs_start),
2132            };
2133            self.push(kind, start, end, node.left.span());
2134        } else if node.attrs.is_empty()
2135            && let (Some((start, lhs_end)), Some((rhs_start, end))) =
2136                (self.range(node.left.span()), self.range(node.right.span()))
2137            && in_order(lhs_end, rhs_start)
2138        {
2139            let lhs = self.source[start..lhs_end].to_string();
2140            let rhs = self.source[rhs_start..end].to_string();
2141            let gap = (lhs_end, rhs_start);
2142            let logic = match &node.op {
2143                syn::BinOp::And(_) => Some(true),
2144                syn::BinOp::Or(_) => Some(false),
2145                _ => None,
2146            };
2147            if let Some(and) = logic {
2148                if !in_let_chain(&node.left) && !matches!(*node.right, syn::Expr::Let(_)) {
2149                    self.push(
2150                        SiteKind::Logic { and, lhs, rhs, gap },
2151                        start,
2152                        end,
2153                        node.left.span(),
2154                    );
2155                }
2156            } else if let Some((op, assign)) = arith_op(&node.op) {
2157                let kind = SiteKind::Arith {
2158                    op,
2159                    assign,
2160                    lhs,
2161                    rhs,
2162                    gap,
2163                };
2164                // Two literals have no type until the context gives them one, and a
2165                // probe is a context of its own.
2166                let literals = is_literal(&node.left) && is_literal(&node.right);
2167                if !literals && (!assign || is_plain_place(&node.left)) {
2168                    self.push(kind, start, end, node.left.span());
2169                } else {
2170                    // Which of the place and the value is evaluated first depends on
2171                    // the type, which a probe would have to know.
2172                    let at = node.left.span().start();
2173                    self.found.rebuild_sites.push(Site {
2174                        id: NO_ID,
2175                        kind,
2176                        line: at.line,
2177                        column: at.column + 1,
2178                        start,
2179                        end,
2180                        text: self.source[start..end].to_string(),
2181                    });
2182                }
2183            }
2184        }
2185        visit::visit_expr_binary(self, node);
2186    }
2187}
2188
2189/// Instrumented text plus the mapping back to the original, used to blame a site for a
2190/// compile error in the rewritten file.
2191#[derive(Debug, PartialEq)]
2192pub struct Rendered {
2193    pub text: String,
2194    /// `(output offset, original offset, length)` of each stretch copied from the original,
2195    /// in output order.
2196    segments: Vec<(usize, usize, usize)>,
2197    /// `(output offset, length, site)` of each piece of text a probe added, in output order.
2198    inserted: Vec<(usize, usize, u32)>,
2199}
2200
2201impl Rendered {
2202    /// Maps a byte offset in the instrumented text to the original. Offsets inside inserted
2203    /// text map to the point of insertion.
2204    /// The site whose probe text contains the byte at `offset` of the instrumented text.
2205    pub fn inserted_by(&self, offset: usize) -> Option<u32> {
2206        let idx = self.inserted.partition_point(|(out, _, _)| *out <= offset);
2207        let (out, len, site) = self.inserted[idx.checked_sub(1)?];
2208        (offset - out < len).then_some(site)
2209    }
2210
2211    pub fn to_original(&self, offset: usize) -> usize {
2212        let idx = self.segments.partition_point(|(out, _, _)| *out <= offset);
2213        let Some((out, orig, len)) = idx.checked_sub(1).map(|i| self.segments[i]) else {
2214            return 0;
2215        };
2216        // Past the end of the copied stretch is inserted text, which sits at its end.
2217        orig + (offset - out).min(len)
2218    }
2219}
2220
2221struct Edit {
2222    pos: usize,
2223    end: usize,
2224    /// 0: closes a site, 1: replaces an operator, 2: opens a site.
2225    phase: u8,
2226    /// Closers: innermost first. Openers: outermost first.
2227    order: i64,
2228    text: String,
2229    /// The site the text belongs to.
2230    site: u32,
2231}
2232
2233/// Rewrites `source` with probes for the sites that `enabled` accepts.
2234pub fn render(source: &str, sites: &[Site], enabled: &dyn Fn(u32) -> bool) -> Rendered {
2235    let rt = format!("crate::{RUNTIME_MOD}");
2236    let mut edits = vec![];
2237    for site in sites.iter().filter(|s| enabled(s.id)) {
2238        // Edits at one position are ordered by the length of their site, doubled to leave
2239        // room: a site that wraps a whole expression goes around a site of that very
2240        // expression (`if a > b` as a guard and as a comparison).
2241        let wraps = matches!(
2242            site.kind,
2243            SiteKind::Return { .. }
2244                | SiteKind::Body { .. }
2245                | SiteKind::Guard { .. }
2246                | SiteKind::Field { .. }
2247        );
2248        // tmt:ignore `2 +` orders the same: nothing longer starts or ends where a wrapping site does
2249        let len = 2 * (site.end - site.start) as i64 + wraps as i64;
2250        let (open, close) = match &site.kind {
2251            SiteKind::Cmp { op, gap, .. } => {
2252                let func = if op.is_ordering() { "ord" } else { "eq" };
2253                edits.push(Edit {
2254                    pos: gap.0,
2255                    end: gap.1,
2256                    phase: 1,
2257                    order: 0,
2258                    text: "), &(".into(),
2259                    site: site.id,
2260                });
2261                (
2262                    "(match (&(".to_string(),
2263                    format!(
2264                        ")) {{ (__tmt_l, __tmt_r) => {{ #[allow(unused_imports)] use {rt}::{{ValAny as _, ValNum as _}}; \
2265                         {rt}::{func}({id}u32, {code}u8, __tmt_l, __tmt_r, (&{rt}::W(__tmt_l)).tmt_val(), (&{rt}::W(__tmt_r)).tmt_val()) }} }})",
2266                        id = site.id,
2267                        code = op.code(),
2268                    ),
2269                )
2270            }
2271            // In the probes below the user's operands are evaluated where no name the probe
2272            // introduces is in scope: in the scrutinee of a `match`, in the initialiser of a
2273            // `let`, or in an arm that binds nothing. A scrutinee keeps its temporaries
2274            // until the end of the enclosing statement, as an arithmetic operator does.
2275            SiteKind::Logic { and, gap, .. } => {
2276                // The right operand stays in place, so it is evaluated exactly when the
2277                // (possibly mutated) left operand asks for it.
2278                let id = site.id;
2279                edits.push(Edit {
2280                    pos: gap.0,
2281                    end: gap.1,
2282                    phase: 1,
2283                    order: 0,
2284                    text: format!("); __tmt_c }} {{ 2u8 => {rt}::rhs({id}u32, {and}, "),
2285                    site: site.id,
2286                });
2287                (
2288                    // Each operand of `&&` / `||` drops its temporaries when it is done.
2289                    // The `let` ends the left operand's; the arm ends the right one's.
2290                    format!("(match {{ let __tmt_c: u8 = {rt}::lhs({id}u32, {and}, "),
2291                    "), __tmt_c => __tmt_c == 1u8 })".to_string(),
2292                )
2293            }
2294            SiteKind::Arith {
2295                op, assign, gap, ..
2296            } => {
2297                // A compound assignment hands the probe the place to update.
2298                let (holder, lhs_open, lhs_close) = if *assign {
2299                    ("Aa", "&mut (", ")")
2300                } else {
2301                    ("Ar", "", "")
2302                };
2303                edits.push(Edit {
2304                    pos: gap.0,
2305                    end: gap.1,
2306                    phase: 1,
2307                    order: 0,
2308                    text: format!("{lhs_close}, "),
2309                    site: site.id,
2310                });
2311                (
2312                    format!("(match ({lhs_open}"),
2313                    format!(
2314                        ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{{any} as _, {prim} as _}}; \
2315                         (&{rt}::{holder}::new(__tmt_a, __tmt_b)).{method}({id}u32) }} }})",
2316                        any = op.fallback_trait(*assign),
2317                        prim = op.prim_trait(*assign),
2318                        method = op.method(*assign),
2319                        id = site.id,
2320                    ),
2321                )
2322            }
2323            SiteKind::Not { bang, .. } => {
2324                // Drop the `!`; the probe applies it (or not).
2325                edits.push(Edit {
2326                    pos: bang.0,
2327                    end: bang.1,
2328                    phase: 1,
2329                    order: 0,
2330                    text: String::new(),
2331                    site: site.id,
2332                });
2333                (
2334                    "(match (".to_string(),
2335                    format!(
2336                        ") {{ __tmt_a => {{ #[allow(unused_imports)] use {rt}::{{AnyNot as _, NotPrim as _}}; \
2337                         (&{rt}::Un::new(__tmt_a)).tmt_not({}u32) }} }})",
2338                        site.id
2339                    ),
2340                )
2341            }
2342            SiteKind::Return { option, .. } => match option {
2343                None => (
2344                    " let __tmt_v: bool = {".to_string(),
2345                    format!("}}; {rt}::ret({}u32, __tmt_v) ", site.id),
2346                ),
2347                Some(ty) => (
2348                    format!(" let __tmt_v: {ty} = {{"),
2349                    format!("}}; {rt}::ret_opt({}u32, __tmt_v) ", site.id),
2350                ),
2351            },
2352            SiteKind::MinMax {
2353                max, call, close, ..
2354            } => {
2355                // The receiver is borrowed, as a method call borrows it: a `max` that takes
2356                // `&self` leaves it where it is, and one that takes it by value copies it
2357                // out (or, for a type that cannot be copied, does not compile: no probe).
2358                edits.push(Edit {
2359                    pos: call.0,
2360                    end: call.1,
2361                    phase: 1,
2362                    order: 0,
2363                    text: "), ".into(),
2364                    site: site.id,
2365                });
2366                // The call's own `)` (and a trailing comma) is replaced by the probe.
2367                // The call is made as it was written, on the same operands; the probe only
2368                // decides which of the two it is.
2369                let (same, other) = if *max { ("max", "min") } else { ("min", "max") };
2370                edits.push(Edit {
2371                    pos: close.0,
2372                    end: close.1,
2373                    phase: 1,
2374                    order: 0,
2375                    text: format!(
2376                        ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{AnyMinMax as _, MinMaxPrim as _}}; \
2377                         if (&{rt}::Mm(__tmt_a, &__tmt_b)).tmt_other({}u32) {{ (*__tmt_a).{other}(__tmt_b) }} else {{ (*__tmt_a).{same}(__tmt_b) }} }} }})",
2378                        site.id
2379                    ),
2380                    site: site.id,
2381                });
2382                ("(match (&(".to_string(), String::new())
2383            }
2384            SiteKind::Range { inclusive, gap, .. } => {
2385                edits.push(Edit {
2386                    pos: gap.0,
2387                    end: gap.1,
2388                    phase: 1,
2389                    order: 0,
2390                    text: ", ".into(),
2391                    site: site.id,
2392                });
2393                let method = if *inclusive {
2394                    "tmt_range_inclusive"
2395                } else {
2396                    "tmt_range"
2397                };
2398                (
2399                    "(match (".to_string(),
2400                    format!(
2401                        ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{AnyRange as _, RangePrim as _}}; \
2402                         (&{rt}::Ar::new(__tmt_a, __tmt_b)).{method}({}u32) }} }})",
2403                        site.id
2404                    ),
2405                )
2406            }
2407            SiteKind::Arm { guard, .. } => {
2408                // The probe goes into the arm's guard, where it runs only when the
2409                // pattern matched.
2410                match guard {
2411                    ArmGuard::None(arrow) => edits.push(Edit {
2412                        pos: *arrow,
2413                        end: *arrow,
2414                        phase: 2,
2415                        order: 0,
2416                        text: format!("if {rt}::arm({}u32) ", site.id),
2417                        site: site.id,
2418                    }),
2419                    ArmGuard::Existing(from, to) => {
2420                        let wider = 2 * (to - from + 1) as i64;
2421                        edits.push(Edit {
2422                            pos: *from,
2423                            end: *from,
2424                            phase: 2,
2425                            order: -wider,
2426                            text: format!("{rt}::arm({}u32) && (", site.id),
2427                            site: site.id,
2428                        });
2429                        edits.push(Edit {
2430                            pos: *to,
2431                            end: *to,
2432                            phase: 0,
2433                            order: wider,
2434                            text: ")".into(),
2435                            site: site.id,
2436                        });
2437                    }
2438                }
2439                (String::new(), String::new())
2440            }
2441            SiteKind::Stmt => (
2442                format!("if {rt}::live({}u32) {{ ", site.id),
2443                " }".to_string(),
2444            ),
2445            // A literal takes its type from where it stands, so it stays where it is.
2446            SiteKind::Neg {
2447                operand,
2448                literal: true,
2449                ..
2450            } => (
2451                format!("(if {rt}::live({}u32) {{ ", site.id),
2452                format!(" }} else {{ {operand} }})"),
2453            ),
2454            SiteKind::Neg { minus, .. } => {
2455                edits.push(Edit {
2456                    pos: minus.0,
2457                    end: minus.1,
2458                    phase: 1,
2459                    order: 0,
2460                    text: String::new(),
2461                    site: site.id,
2462                });
2463                (
2464                    "(match (".to_string(),
2465                    format!(
2466                        ") {{ __tmt_a => if {rt}::live({}u32) {{ -__tmt_a }} else {{ __tmt_a }} }})",
2467                        site.id
2468                    ),
2469                )
2470            }
2471            SiteKind::Guard { .. } => (format!("{rt}::ret({}u32, ", site.id), ")".to_string()),
2472            SiteKind::Field {
2473                name,
2474                shorthand,
2475                from_base: Some(from_base),
2476                ..
2477            } => (
2478                format!(
2479                    "{}if {rt}::live({}u32) {{ ",
2480                    if *shorthand {
2481                        format!("{name}: ")
2482                    } else {
2483                        String::new()
2484                    },
2485                    site.id
2486                ),
2487                format!(" }} else {{ {from_base} }}"),
2488            ),
2489            SiteKind::Field {
2490                from_base: None, ..
2491            } => continue,
2492            SiteKind::Body { value, .. } => (
2493                format!(" if !{rt}::live({}u32) {{ return {value}; }}", site.id),
2494                String::new(),
2495            ),
2496        };
2497        edits.push(Edit {
2498            pos: site.start,
2499            end: site.start,
2500            phase: 2,
2501            order: -len,
2502            text: open,
2503            site: site.id,
2504        });
2505        edits.push(Edit {
2506            pos: site.end,
2507            end: site.end,
2508            phase: 0,
2509            order: len,
2510            text: close,
2511            site: site.id,
2512        });
2513    }
2514    edits.sort_by_key(|e| (e.pos, e.phase, e.order));
2515
2516    // tmt:ignore the capacity is a hint: any number gives the same text
2517    let capacity = source.len() + edits.iter().map(|e| e.text.len()).sum::<usize>();
2518    let mut text = String::with_capacity(capacity);
2519    let mut segments = vec![];
2520    let mut inserted = vec![];
2521    let mut cursor = 0;
2522    for edit in edits {
2523        // Also when nothing lies between two edits: text inserted right after a replaced
2524        // stretch then maps to where it was inserted, not to where the stretch began.
2525        if edit.pos >= cursor {
2526            segments.push((text.len(), cursor, edit.pos - cursor));
2527            text.push_str(&source[cursor..edit.pos]);
2528        }
2529        inserted.push((text.len(), edit.text.len(), edit.site));
2530        text.push_str(&edit.text);
2531        cursor = cursor.max(edit.end);
2532    }
2533    segments.push((text.len(), cursor, source.len() - cursor));
2534    text.push_str(&source[cursor..]);
2535    Rendered {
2536        text,
2537        segments,
2538        inserted,
2539    }
2540}
2541
2542/// The sites to blame for a compile error at `offset` (original coordinates): the smallest
2543/// enabled sites that contain it.
2544pub fn blame(sites: &[Site], enabled: &dyn Fn(u32) -> bool, offset: usize) -> Vec<u32> {
2545    // A replaced body is blamed for what is wrong in its own text only (`inserted_by`):
2546    // by position it would answer for everything in the function.
2547    let containing = || {
2548        sites.iter().filter(|s| {
2549            enabled(s.id)
2550                && s.start <= offset
2551                && offset <= s.end
2552                && !matches!(s.kind, SiteKind::Body { .. })
2553        })
2554    };
2555    let Some(smallest) = containing().map(|s| s.end - s.start).min() else {
2556        return vec![];
2557    };
2558    containing()
2559        .filter(|s| s.end - s.start == smallest)
2560        .map(|s| s.id)
2561        .collect()
2562}
2563
2564#[cfg(test)]
2565mod tests {
2566    use super::*;
2567
2568    fn all(_: u32) -> bool {
2569        true
2570    }
2571
2572    /// The sites of `src` without the function-level `Return` sites, numbered from
2573    /// `first_id`: most tests are about one expression inside a small function.
2574    fn found(src: &str, first_id: u32) -> Result<Discovery> {
2575        let mut all = discover(src, 0)?;
2576        all.sites
2577            .retain(|s| !matches!(s.kind, SiteKind::Return { .. } | SiteKind::Body { .. }));
2578        for (index, site) in all.sites.iter_mut().enumerate() {
2579            site.id = first_id + index as u32;
2580        }
2581        Ok(all)
2582    }
2583
2584    #[test]
2585    fn finds_a_comparison_with_a_literal() {
2586        let src = "pub fn is_eligible(age: u32) -> bool {\n    age >= 18\n}\n";
2587        let found = found(src, 5).unwrap();
2588        assert_eq!(found.sites.len(), 1);
2589        let site = &found.sites[0];
2590        assert_eq!(
2591            (site.id, site.line, site.column, site.text.as_str()),
2592            (5, 2, 5, "age >= 18")
2593        );
2594        let SiteKind::Cmp {
2595            op,
2596            lhs,
2597            rhs,
2598            literal,
2599            ..
2600        } = &site.kind
2601        else {
2602            panic!()
2603        };
2604        assert_eq!(
2605            (*op, lhs.as_str(), rhs.as_str(), *literal),
2606            (CmpOp::Ge, "age", "18", LiteralSide::Rhs(18))
2607        );
2608    }
2609
2610    #[test]
2611    fn literal_sides() {
2612        let src =
2613            "fn f(x: i32, y: i32) { let _ = (-5 < x, x == (3), 1 < 2, x <= y, x > 1.5 as i32); }";
2614        let literals: Vec<LiteralSide> = found(src, 0)
2615            .unwrap()
2616            .sites
2617            .iter()
2618            .filter_map(|s| match &s.kind {
2619                SiteKind::Cmp { literal, .. } => Some(*literal),
2620                SiteKind::Neg { .. } => None,
2621                _ => panic!(),
2622            })
2623            .collect();
2624        assert_eq!(
2625            literals,
2626            [
2627                LiteralSide::Lhs(-5),
2628                LiteralSide::Rhs(3),
2629                LiteralSide::None,
2630                LiteralSide::None,
2631                LiteralSide::None
2632            ]
2633        );
2634    }
2635
2636    #[test]
2637    fn renders_a_comparison_probe() {
2638        let src = "fn f(a: u8) -> bool { a  >=  18 }";
2639        let sites = found(src, 3).unwrap().sites;
2640        let out = render(src, &sites, &all);
2641        assert_eq!(
2642            out.text,
2643            "fn f(a: u8) -> bool { (match (&(a), &(18)) { (__tmt_l, __tmt_r) => { #[allow(unused_imports)] \
2644             use crate::__tmt_rt::{ValAny as _, ValNum as _}; crate::__tmt_rt::ord(3u32, 3u8, __tmt_l, __tmt_r, \
2645             (&crate::__tmt_rt::W(__tmt_l)).tmt_val(), (&crate::__tmt_rt::W(__tmt_r)).tmt_val()) } }) }"
2646        );
2647        assert_eq!(render(src, &sites, &|_| false).text, src);
2648    }
2649
2650    #[test]
2651    fn renders_statement_guards_and_nested_sites() {
2652        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}";
2653        let sites = found(src, 0).unwrap().sites;
2654        let kinds: Vec<&str> = sites.iter().map(|s| s.text.as_str()).collect();
2655        assert_eq!(
2656            kinds,
2657            [
2658                "check((a < 3) == true)?;",
2659                "v.push(a);",
2660                "v.clear();",
2661                "(a < 3) == true",
2662                "a < 3"
2663            ]
2664        );
2665        let out = render(src, &sites, &all);
2666        assert_eq!(
2667            out.text.lines().count(),
2668            src.lines().count(),
2669            "line numbers are preserved"
2670        );
2671        assert!(
2672            out.text
2673                .contains("if crate::__tmt_rt::live(0u32) { check((match (&(((match (&(a), &(3))"),
2674            "{}",
2675            out.text
2676        );
2677        assert!(out.text.contains("if crate::__tmt_rt::live(1u32) { v.push(a); }if crate::__tmt_rt::live(2u32) { v.clear(); }"), "{}", out.text);
2678        syn::parse_file(&out.text).expect("instrumented source parses");
2679
2680        // Only the inner comparison enabled.
2681        let inner = render(src, &sites, &|id| id == 4);
2682        assert!(
2683            inner.text.contains("check(((match (&(a), &(3))"),
2684            "{}",
2685            inner.text
2686        );
2687        assert!(inner.text.contains(") == true)?;"), "{}", inner.text);
2688        syn::parse_file(&inner.text).unwrap();
2689    }
2690
2691    #[test]
2692    fn skips_tests_const_contexts_and_macros() {
2693        let src = r#"
2694            const LIMIT: bool = 1 < 2;
2695            static S: bool = 3 > 2;
2696            const fn c(a: u8) -> bool { a < 1 }
2697            fn arr(a: u8) -> [u8; { 2 > 1 } as usize] { let _ = [0u8; (4 > 3) as usize]; assert!(a < 9); [a; 1] }
2698            enum E { A = (5 > 4) as isize }
2699            struct T;
2700            impl T { const K: bool = 6 < 7; const fn k(a: u8) -> bool { a > 6 } }
2701            #[cfg(test)]
2702            mod tests { fn t(a: u8) -> bool { a == 1 } }
2703            #[cfg(test)]
2704            mod more_tests;
2705            #[cfg(test)]
2706            #[doc = "not a path"]
2707            mod documented;
2708            #[cfg(test)]
2709            #[path = "support/helpers.rs"]
2710            mod helpers;
2711            #[cfg(all(test, feature = "x"))]
2712            fn helper(a: u8) -> bool { a != 1 }
2713            #[test]
2714            fn a_test() { let a = 1; if a == 2 { panic!() } }
2715            #[tokio::test]
2716            async fn async_test() { let a = 1; if a == 3 { panic!() } }
2717            #[cfg(not(test))]
2718            fn real(a: u8) -> bool { a == 100 }
2719            #[cfg(feature = "test-utils")]
2720            fn also_real(a: u8) -> bool { a == 101 }
2721            fn pat(a: u8) -> bool { matches!(a, 1..=2) || match a { 0..=9 => a == 102, _ => false } }
2722        "#;
2723        let found = found(src, 0).unwrap();
2724        let texts: Vec<&str> = found.sites.iter().map(|s| s.text.as_str()).collect();
2725        assert_eq!(
2726            texts,
2727            [
2728                "a == 100",
2729                "a == 101",
2730                "matches!(a, 1..=2) || match a { 0..=9 => a == 102, _ => false }",
2731                "0..=9 => ..",
2732                "a == 102"
2733            ]
2734        );
2735        assert_eq!(
2736            found.test_modules,
2737            [
2738                TestModule {
2739                    name: "more_tests".into(),
2740                    path: None
2741                },
2742                TestModule {
2743                    name: "documented".into(),
2744                    path: None
2745                },
2746                TestModule {
2747                    name: "helpers".into(),
2748                    path: Some("support/helpers.rs".into())
2749                },
2750            ]
2751        );
2752    }
2753
2754    #[test]
2755    fn deletable_statements() {
2756        let src = r#"
2757            async fn f(s: &mut S) -> Result<(), E> {
2758                s.validate()?;
2759                s.total += 1;
2760                s.flag = true;
2761                helper(s);
2762                s.flush().await?;
2763                s.sync().await;
2764                let x = s.get();
2765                println!("{x}");
2766                if x > 0 { return Ok(()); }
2767                s.done()
2768            }
2769        "#;
2770        let texts: Vec<String> = found(src, 0)
2771            .unwrap()
2772            .sites
2773            .into_iter()
2774            .filter(|s| s.kind == SiteKind::Stmt)
2775            .map(|s| s.text)
2776            .collect();
2777        assert_eq!(
2778            texts,
2779            [
2780                "s.validate()?;",
2781                "s.total += 1;",
2782                "s.flag = true;",
2783                "helper(s);",
2784                "s.flush().await?;",
2785                "s.sync().await;"
2786            ]
2787        );
2788    }
2789
2790    #[test]
2791    fn maps_offsets_back_and_blames_the_innermost_site() {
2792        let src = "fn f(a: u8, b: u8) -> bool { g(a < b); a > 1 }";
2793        let sites = found(src, 0).unwrap().sites;
2794        let out = render(src, &sites, &all);
2795        // Every original character keeps its identity through the mapping.
2796        for (orig, ch) in src.char_indices().filter(|(_, c)| c.is_alphanumeric()) {
2797            let hits: Vec<usize> = out
2798                .text
2799                .char_indices()
2800                .filter(|(o, c)| *c == ch && out.to_original(*o) == orig)
2801                .map(|(o, _)| o)
2802                .collect();
2803            assert!(
2804                !hits.is_empty(),
2805                "original offset {orig} ({ch}) is unreachable"
2806            );
2807        }
2808        // An error inside the probe of `a < b` blames it, not the enclosing statement.
2809        let probe = out.text.find("ord(1u32").unwrap();
2810        let orig = out.to_original(probe);
2811        assert_eq!(blame(&sites, &all, orig), [1]);
2812        // With the inner site disabled, the statement is next.
2813        assert_eq!(blame(&sites, &|id| id != 1, orig), [0]);
2814        assert_eq!(
2815            blame(&sites, &all, src.find("fn").unwrap()),
2816            Vec::<u32>::new()
2817        );
2818        assert_eq!(out.to_original(0), 0);
2819        assert_eq!(out.to_original(out.text.len()), src.len());
2820    }
2821
2822    #[test]
2823    fn blame_is_inclusive_at_both_ends() {
2824        let src = "fn f(a: u8) -> bool { a > 1 }";
2825        let sites = found(src, 0).unwrap().sites;
2826        let (start, end) = (sites[0].start, sites[0].end);
2827        assert_eq!(blame(&sites, &all, start - 1), Vec::<u32>::new());
2828        assert_eq!(blame(&sites, &all, start), [0]);
2829        assert_eq!(blame(&sites, &all, end), [0]);
2830        assert_eq!(blame(&sites, &all, end + 1), Vec::<u32>::new());
2831        // The probe opens before the first original character and closes after the last.
2832        let out = render(src, &sites, &all);
2833        assert_eq!(out.to_original(out.text.find("(match").unwrap()), start);
2834        assert_eq!(
2835            out.to_original(out.text.find("tmt_val()) } })").unwrap()),
2836            end
2837        );
2838        assert_eq!(
2839            out.to_original(out.text.find("), &(").unwrap() + 2),
2840            sites[0].start + 1
2841        );
2842    }
2843
2844    #[test]
2845    fn finds_sites_in_impls_and_array_elements() {
2846        let src = r#"
2847            struct T(u8);
2848            impl T { fn small(&self) -> bool { self.0 < 3 } }
2849            #[cfg(test)]
2850            impl T { fn only_in_tests(&self) -> bool { self.0 < 4 } }
2851            trait Tr { fn provided(&self, a: u8) -> bool { a < 5 } }
2852            fn arr(a: u8) -> [bool; 2] { [a < 6; 2] }
2853            fn closure(a: u8) -> bool { (|| a < 7)() }
2854        "#;
2855        let texts: Vec<String> = found(src, 0)
2856            .unwrap()
2857            .sites
2858            .into_iter()
2859            .map(|s| s.text)
2860            .collect();
2861        assert_eq!(texts, ["self.0 < 3", "a < 5", "a < 6", "a < 7"]);
2862    }
2863
2864    #[test]
2865    fn logic_and_arithmetic_sites() {
2866        let src = "fn f(a: bool, b: bool, x: u32, y: u32) -> u32 { if a && b || !a { x + y * 2 } else { x - 1 % y } }";
2867        let found = found(src, 0).unwrap().sites;
2868        let kinds: Vec<String> = found
2869            .iter()
2870            .map(|s| match &s.kind {
2871                SiteKind::Logic { and, lhs, rhs, .. } => format!("logic and={and} [{lhs}] [{rhs}]"),
2872                SiteKind::Arith { op, lhs, rhs, .. } => {
2873                    format!("arith {} [{lhs}] [{rhs}]", op.symbol())
2874                }
2875                SiteKind::Not { operand, .. } => format!("not [{operand}]"),
2876                other => format!("{other:?}"),
2877            })
2878            .collect();
2879        assert_eq!(
2880            kinds,
2881            [
2882                "logic and=false [a && b] [!a]",
2883                "logic and=true [a] [b]",
2884                "not [a]",
2885                "arith + [x] [y * 2]",
2886                "arith * [y] [2]",
2887                "arith - [x] [1 % y]",
2888                "arith % [1] [y]",
2889            ]
2890        );
2891        let out = render(src, &found, &all).text;
2892        syn::parse_file(&out).expect("instrumented source parses");
2893        assert!(
2894            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 })"),
2895            "{out}"
2896        );
2897        assert!(
2898            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) } })"),
2899            "{out}"
2900        );
2901        // Every probe the renderer can emit exists in the runtime under that name.
2902        for op in ArithOp::ALL {
2903            assert_ne!(op.swapped(), op);
2904            for assign in [false, true] {
2905                let method = op.method(assign);
2906                let fallback = format!("{} {method} ", op.fallback_trait(assign));
2907                assert!(
2908                    crate::RUNTIME_SOURCE.contains(&format!("fn {method}(")),
2909                    "{method}"
2910                );
2911                assert!(crate::RUNTIME_SOURCE.contains(&fallback), "{fallback}");
2912                assert!(
2913                    crate::RUNTIME_SOURCE.contains(&format!("trait {} ", op.prim_trait(assign))),
2914                    "{op:?}"
2915                );
2916            }
2917        }
2918    }
2919
2920    #[test]
2921    fn let_chains_and_literal_arithmetic_are_left_alone() {
2922        let src = r#"
2923            fn f(o: Option<u8>, a: bool, n: u32) -> u32 {
2924                if let Some(x) = o && a && x > 1 { return 1; }
2925                let k = 60 * 60;
2926                (n & 3) | (n << 1) ^ k
2927            }
2928        "#;
2929        let texts: Vec<String> = found(src, 0)
2930            .unwrap()
2931            .sites
2932            .into_iter()
2933            .map(|s| s.text)
2934            .collect();
2935        assert_eq!(
2936            texts,
2937            [
2938                "x > 1",
2939                "(n & 3) | (n << 1) ^ k",
2940                "n & 3",
2941                "(n << 1) ^ k",
2942                "n << 1"
2943            ]
2944        );
2945    }
2946
2947    #[test]
2948    fn attributes_const_methods_and_let_on_the_right() {
2949        let src = r#"
2950            struct T(u8);
2951            impl T {
2952                const fn in_const(&self) -> bool { self.0 < 1 }
2953                #[test]
2954                fn test_method(&self) -> bool { self.0 < 2 }
2955                fn real(&self) -> bool { self.0 < 3 }
2956            }
2957            trait Tr {
2958                #[cfg(test)]
2959                fn only_in_tests(&self, a: u8) -> bool { a < 4 }
2960            }
2961            fn f(s: &mut S, o: Option<u8>, a: bool) -> Result<(), E> {
2962                #[cfg(feature = "x")]
2963                s.guarded();
2964                #[allow(unused)]
2965                s.total += 1;
2966                #[allow(unused)]
2967                s.check()?;
2968                #[allow(unused)]
2969                s.sync().await;
2970                s.plain();
2971                if a && let Some(v) = o { s.use_it(v); }
2972                Ok(())
2973            }
2974        "#;
2975        let texts: Vec<String> = found(src, 0)
2976            .unwrap()
2977            .sites
2978            .into_iter()
2979            .map(|s| s.text)
2980            .collect();
2981        // syn attaches the attribute of `#[a] x += 1;` to the left operand, so that statement
2982        // is guarded together with its attribute; the guard is valid around it either way.
2983        assert_eq!(
2984            texts,
2985            [
2986                "self.0 < 3",
2987                "#[allow(unused)]\n                s.total += 1;",
2988                "s.plain();",
2989                "#[allow(unused)]\n                s.total += 1",
2990                "s.use_it(v);"
2991            ]
2992        );
2993        let found = found(src, 0).unwrap().sites;
2994        syn::parse_file(&render(src, &found, &all).text).expect("instrumented source parses");
2995    }
2996
2997    #[test]
2998    fn compound_assignment_negation_and_bit_operators() {
2999        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 }";
3000        let sites = found(src, 0).unwrap().sites;
3001        let kinds: Vec<String> = sites
3002            .iter()
3003            .map(|s| match &s.kind {
3004                SiteKind::Arith {
3005                    op,
3006                    assign,
3007                    lhs,
3008                    rhs,
3009                    ..
3010                } => format!(
3011                    "{lhs} {}{} {rhs}",
3012                    op.symbol(),
3013                    if *assign { "=" } else { "" }
3014                ),
3015                SiteKind::Not { operand, .. } => format!("!{operand}"),
3016                SiteKind::Stmt => "stmt".to_string(),
3017                other => format!("{other:?}"),
3018            })
3019            .collect();
3020        assert_eq!(
3021            kinds,
3022            [
3023                "stmt",
3024                "stmt",
3025                "*total += n",
3026                "*total <<= 1",
3027                "!ok",
3028                "!n",
3029                "!m",
3030                "n & 7"
3031            ]
3032        );
3033        let out = render(src, &sites, &all).text;
3034        syn::parse_file(&out).expect("instrumented source parses");
3035        for expected in [
3036            "(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) } });",
3037            "use crate::__tmt_rt::{AnyShlAssign as _, BitAssignPrim as _}; (&crate::__tmt_rt::Aa::new(__tmt_a, __tmt_b)).tmt_shl_assign(3u32) } });",
3038            "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) } }) {",
3039            "(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) } })",
3040        ] {
3041            assert!(out.contains(expected), "missing {expected}\nin {out}");
3042        }
3043        // `!a && b`: the negation and the conjunction start at the same character.
3044        let nested = "fn f(a: bool, b: bool) -> bool { !a && b }";
3045        let sites = found(nested, 0).unwrap().sites;
3046        let out = render(nested, &sites, &all).text;
3047        syn::parse_file(&out).expect("instrumented source parses");
3048        assert!(
3049            out.contains("(match { let __tmt_c: u8 = crate::__tmt_rt::lhs(0u32, true, (match (a) { __tmt_a => {"),
3050            "{out}"
3051        );
3052        // Names the probes introduce are never in scope where user code runs.
3053        let capture = "fn f(a: bool, __tmt_c: u8, __tmt_a: u8) -> bool { a && __tmt_c == 2 && __tmt_a + 1 > 0 }";
3054        let sites = found(capture, 0).unwrap().sites;
3055        let out = render(capture, &sites, &all).text;
3056        syn::parse_file(&out).expect("instrumented source parses");
3057        // The arms that bind a probe variable contain only probe code.
3058        for arm in out.split("__tmt_c => ").skip(1) {
3059            assert!(arm.starts_with("__tmt_c == 1u8 })"), "{arm}");
3060        }
3061        for arm in out.split("(__tmt_a, __tmt_b) => ").skip(1) {
3062            assert!(
3063                arm.starts_with("{ #[allow(unused_imports)] use crate::__tmt_rt::"),
3064                "{arm}"
3065            );
3066        }
3067    }
3068
3069    #[test]
3070    fn compound_assignment_is_probed_only_on_plain_places() {
3071        let src = r#"
3072            fn f(s: &mut S, v: &mut [u32], p: &mut u32, i: usize) {
3073                let mut local = 0u32;
3074                local += 1;
3075                s.count += 1;
3076                s.inner.total -= 2;
3077                *p *= 3;
3078                (*p) += 4;
3079                v[i] += 5;
3080                v[next()] += 6;
3081                s.get_mut().x += 7;
3082                *s.slot() += 8;
3083            }
3084        "#;
3085        let probed: Vec<String> = found(src, 0)
3086            .unwrap()
3087            .sites
3088            .into_iter()
3089            .filter(|s| matches!(s.kind, SiteKind::Arith { assign: true, .. }))
3090            .map(|s| s.text)
3091            .collect();
3092        assert_eq!(
3093            probed,
3094            [
3095                "local += 1",
3096                "s.count += 1",
3097                "s.inner.total -= 2",
3098                "*p *= 3",
3099                "(*p) += 4"
3100            ]
3101        );
3102        // The others are still statements that can be deleted.
3103        let deletable = found(src, 0)
3104            .unwrap()
3105            .sites
3106            .iter()
3107            .filter(|s| s.kind == SiteKind::Stmt)
3108            .count();
3109        assert_eq!(deletable, 9);
3110    }
3111
3112    #[test]
3113    fn bool_functions_are_return_sites() {
3114        let src = r#"
3115            pub fn is_ok(a: u8) -> bool { let b = a; b > 1 }
3116            fn count(a: u8) -> u8 { a }
3117            fn unit(a: u8) { let _ = a; }
3118            const fn in_const(a: u8) -> bool { a > 2 }
3119            #[test]
3120            fn a_test() -> bool { true }
3121            struct T;
3122            impl T { fn method(&self) -> bool { true } }
3123            trait Tr { fn required(&self) -> bool; fn provided(&self) -> bool { false } }
3124            fn boxed() -> Box<bool> { Box::new(true) }
3125            fn qualified() -> core::primitive::bool { true }
3126        "#;
3127        let sites = discover(src, 0).unwrap().sites;
3128        let returns: Vec<(&str, &str, usize)> = sites
3129            .iter()
3130            .filter_map(|s| match &s.kind {
3131                SiteKind::Return {
3132                    name, option: None, ..
3133                } => Some((name.as_str(), s.text.as_str(), s.line)),
3134                _ => None,
3135            })
3136            .collect();
3137        assert_eq!(
3138            returns,
3139            [
3140                ("is_ok", "fn is_ok(a: u8) -> bool", 2),
3141                ("method", "fn method(&self) -> bool", 9),
3142                ("provided", "fn provided(&self) -> bool", 10),
3143            ]
3144        );
3145        let out = render(src, &sites, &all).text;
3146        syn::parse_file(&out).expect("instrumented source parses");
3147        assert!(
3148            out.contains(
3149                "pub fn is_ok(a: u8) -> bool { let __tmt_v: bool = { \
3150                 if !crate::__tmt_rt::live(1u32) { return true; } \
3151                 if !crate::__tmt_rt::live(2u32) { return false; } let b = a; (match"
3152            ),
3153            "{out}"
3154        );
3155        assert!(
3156            out.contains("}) }; crate::__tmt_rt::ret(0u32, __tmt_v) }"),
3157            "{out}"
3158        );
3159        assert_eq!(
3160            out.lines().count(),
3161            src.lines().count(),
3162            "line numbers are preserved"
3163        );
3164        // A compile error in the wrapper is blamed on the function's site.
3165        let rendered = render(src, &sites, &all);
3166        let wrapper = rendered.text.find("ret(0u32").unwrap();
3167        assert_eq!(rendered.inserted_by(wrapper), Some(0));
3168        // And one in a replaced body on that replacement alone: by position they are
3169        // all the same place.
3170        let replaced = rendered.text.find("return false; } let b").unwrap();
3171        assert_eq!(rendered.inserted_by(replaced), Some(2));
3172        assert_eq!(blame(&sites, &all, rendered.to_original(replaced)), [0]);
3173    }
3174
3175    #[test]
3176    fn ids_are_consecutive_across_every_kind_of_site() {
3177        let src = r#"
3178            fn a(x: u8) -> bool { x > 1 }
3179            fn b(x: u8) -> bool { !(x > 2) && !!flag(x) }
3180            fn c(s: &mut S) { s.n += 1; s.go(); }
3181        "#;
3182        let sites = discover(src, 10).unwrap().sites;
3183        let ids: Vec<u32> = sites.iter().map(|s| s.id).collect();
3184        assert_eq!(ids, (10..10 + sites.len() as u32).collect::<Vec<_>>());
3185        let texts: Vec<&str> = sites
3186            .iter()
3187            .filter(|s| !matches!(s.kind, SiteKind::Body { .. }))
3188            .map(|s| s.text.as_str())
3189            .collect();
3190        assert_eq!(
3191            texts,
3192            [
3193                "fn a(x: u8) -> bool",
3194                "x > 1",
3195                "fn b(x: u8) -> bool",
3196                "!(x > 2) && !!flag(x)",
3197                "!(x > 2)",
3198                "x > 2",
3199                "!!flag(x)",
3200                "!flag(x)",
3201                "s.n += 1;",
3202                "s.go();",
3203                "s.n += 1",
3204            ]
3205        );
3206        syn::parse_file(&render(src, &sites, &all).text).expect("instrumented source parses");
3207    }
3208
3209    #[test]
3210    fn only_calls_and_assignments_are_deletable() {
3211        let src = r#"
3212            async fn f(s: &mut S, v: Vec<u8>) -> Result<(), E> {
3213                s.field;
3214                v[0];
3215                (s.a, s.b);
3216                s.value?;
3217                s.future.await;
3218                s.x = 1;
3219                s.x -= 1;
3220                s.x == 1;
3221                s.call().await?;
3222                Ok(())
3223            }
3224        "#;
3225        let texts: Vec<String> = found(src, 0)
3226            .unwrap()
3227            .sites
3228            .into_iter()
3229            .filter(|s| s.kind == SiteKind::Stmt)
3230            .map(|s| s.text)
3231            .collect();
3232        assert_eq!(texts, ["s.x = 1;", "s.x -= 1;", "s.call().await?;"]);
3233    }
3234
3235    #[test]
3236    fn ranges_match_arms_min_max_and_option_results() {
3237        let src = r#"
3238            fn find(v: &[u32], limit: u32) -> Option<u32> {
3239                for i in 0..v.len() {
3240                    let capped = v[i].min(limit).max(1);
3241                    match capped {
3242                        0 => return None,
3243                        n if n > 5 => return Some(n),
3244                        1..=3 => continue,
3245                        other => { let _ = other; }
3246                    }
3247                }
3248                let _ = &v[1..=2];
3249                for _ in 1..=limit as usize {}
3250                let _ = 'a'..'z';
3251                let _ = v.iter().max();
3252                None
3253            }
3254            fn exhaustive(k: Kind) -> u8 { match k { Kind::A => 1, Kind::B => 2 } }
3255            fn hidden() -> Option<impl Sized> { Some(1) }
3256            fn first(v: &[u32]) -> Option<u32> { v.first().copied() }
3257        "#;
3258        let sites = discover(src, 0).unwrap().sites;
3259        let kinds: Vec<String> = sites
3260            .iter()
3261            .filter_map(|s| match &s.kind {
3262                SiteKind::Return { name, option, .. } => Some(format!("return {name} {option:?}")),
3263                SiteKind::Range {
3264                    inclusive,
3265                    lhs,
3266                    rhs,
3267                    ..
3268                } => Some(format!("range {lhs} {rhs} inclusive={inclusive}")),
3269                SiteKind::Arm { pattern, guard, .. } => Some(format!(
3270                    "arm {pattern} guarded={}",
3271                    matches!(guard, ArmGuard::Existing(..))
3272                )),
3273                SiteKind::MinMax {
3274                    max,
3275                    receiver,
3276                    argument,
3277                    ..
3278                } => Some(format!("minmax {receiver} {argument} max={max}")),
3279                _ => None,
3280            })
3281            .collect();
3282        assert_eq!(
3283            kinds,
3284            [
3285                "range 0 v.len() inclusive=false",
3286                "minmax v[i].min(limit) 1 max=true",
3287                "minmax v[i] limit max=false",
3288                // The catch-all arm and the last arm stay; a match without one is left alone.
3289                "arm 0 guarded=false",
3290                "arm n if n > 5 guarded=true",
3291                "arm 1..=3 guarded=false",
3292                // `1..=2` and `'a'..'z'` have literals at both ends.
3293                "range 1 limit as usize inclusive=true",
3294                "return first Some(\"Option<u32>\")",
3295            ]
3296        );
3297        let out = render(src, &sites, &all).text;
3298        syn::parse_file(&out).expect("instrumented source parses");
3299        assert_eq!(out.lines().count(), src.lines().count());
3300        let option = sites
3301            .iter()
3302            .find(|site| matches!(&site.kind, SiteKind::Return { name, .. } if name == "first"))
3303            .unwrap();
3304        assert_eq!(out.matches("let __tmt_v: Option<u32> = {").count(), 1);
3305        assert!(
3306            out.contains(&format!(
3307                "crate::__tmt_rt::ret_opt({}u32, __tmt_v)",
3308                option.id
3309            )),
3310            "{out}"
3311        );
3312        assert!(out.contains("0 if crate::__tmt_rt::arm("), "{out}");
3313        assert!(
3314            out.contains("n if crate::__tmt_rt::arm(") && out.contains(") && ("),
3315            "{out}"
3316        );
3317        assert!(out.contains("1..=3 if crate::__tmt_rt::arm("), "{out}");
3318        assert!(
3319            out.contains(".tmt_range(") && out.contains(".tmt_range_inclusive("),
3320            "{out}"
3321        );
3322        // The call that was written, and the other one for the mutant, on the operands
3323        // as they were evaluated once; the receiver is borrowed, not moved.
3324        assert!(
3325            out.contains("(match (&(v[i]), limit) {")
3326                && out.contains(
3327                    "Mm(__tmt_a, &__tmt_b)).tmt_other(5u32) { (*__tmt_a).max(__tmt_b) } else { (*__tmt_a).min(__tmt_b) }"
3328                )
3329                && out.contains(
3330                    ".tmt_other(4u32) { (*__tmt_a).min(__tmt_b) } else { (*__tmt_a).max(__tmt_b) }"
3331                ),
3332            "{out}"
3333        );
3334        assert!(
3335            !out.contains(".min(limit)") && !out.contains(".max(1)"),
3336            "{out}"
3337        );
3338        assert!(
3339            out.contains("v.iter().max()"),
3340            "an iterator's max is another method: {out}"
3341        );
3342    }
3343
3344    #[test]
3345    fn macro_arguments() {
3346        let src = r#"
3347            fn f(a: u32, b: u32, out: &mut String) -> Vec<u32> {
3348                assert!(a < 100);
3349                debug_assert!(a < 101, "message {}", a < 102);
3350                assert_eq!(a < 1, b < 2, "context {}", a + 3);
3351                let _ = format!("{} {name}", a < 4, name = b < 5);
3352                write!(out, "{}", a < 6).unwrap();
3353                if matches!(a.cmp(&b), std::cmp::Ordering::Less if a < 7) || matches!(a < 8, true) { panic!("{}", a < 9); }
3354                custom!(a < 10);
3355                let _ = vec![a < 11; 2];
3356                vec![a + b, (a < 12) as u32]
3357            }
3358        "#;
3359        let texts: Vec<String> = found(src, 0)
3360            .unwrap()
3361            .sites
3362            .into_iter()
3363            .filter(|s| matches!(s.kind, SiteKind::Cmp { .. } | SiteKind::Arith { .. }))
3364            .map(|s| s.text)
3365            .collect();
3366        assert_eq!(
3367            texts,
3368            [
3369                "a < 1", "b < 2", "a + 3", "a < 4", "b < 5", "a < 6", "a < 8", "a < 9", "a + b",
3370                "a < 12"
3371            ]
3372        );
3373        let found = found(src, 0).unwrap().sites;
3374        syn::parse_file(&render(src, &found, &all).text).expect("instrumented source parses");
3375    }
3376
3377    #[test]
3378    fn non_ascii_source_keeps_byte_offsets() {
3379        let src = "fn f(a: u8) -> bool { let s = \"日本語\"; s.len() > 3 && a < 2 }";
3380        let sites = found(src, 0).unwrap().sites;
3381        let texts: Vec<&str> = sites.iter().map(|s| s.text.as_str()).collect();
3382        assert_eq!(texts, ["s.len() > 3 && a < 2", "s.len() > 3", "a < 2"]);
3383        syn::parse_file(&render(src, &sites, &all).text).unwrap();
3384    }
3385
3386    #[test]
3387    fn unparseable_source_is_an_error() {
3388        assert!(discover("fn f( {", 0).is_err());
3389    }
3390    /// Every site as `kind text`, in discovery order, without the replaced bodies.
3391    fn labelled(src: &str) -> Vec<String> {
3392        discover(src, 0)
3393            .unwrap()
3394            .sites
3395            .iter()
3396            .filter(|s| !matches!(s.kind, SiteKind::Body { .. }))
3397            .map(|s| {
3398                let kind = match &s.kind {
3399                    SiteKind::Cmp { .. } => "cmp",
3400                    SiteKind::Logic { .. } => "logic",
3401                    SiteKind::Arith { .. } => "arith",
3402                    SiteKind::Not { .. } => "not",
3403                    SiteKind::Return { .. } => "return",
3404                    SiteKind::MinMax { .. } => "minmax",
3405                    SiteKind::Range { .. } => "range",
3406                    SiteKind::Arm { .. } => "arm",
3407                    SiteKind::Stmt => "stmt",
3408                    SiteKind::Neg { .. } => "neg",
3409                    SiteKind::Guard { .. } => "guard",
3410                    SiteKind::Field { .. } => "field",
3411                    SiteKind::Body { .. } => "body",
3412                };
3413                format!("{kind} {}", s.text)
3414            })
3415            .collect()
3416    }
3417
3418    #[test]
3419    fn byte_order_mark_and_interpreter_line_are_refused() {
3420        let body = "fn f(a: u8) -> bool { a > 1 }";
3421        assert!(discover(&format!("\u{feff}{body}"), 0).is_err());
3422        assert!(discover(&format!("#!/usr/bin/env run\n{body}"), 0).is_err());
3423        // An inner attribute starts with the same two characters and is fine.
3424        assert_eq!(
3425            labelled(&format!("#![allow(dead_code)]\n{body}")),
3426            ["return fn f(a: u8) -> bool", "cmp a > 1"]
3427        );
3428    }
3429
3430    #[test]
3431    fn which_result_types_make_a_return_site() {
3432        let src = "fn a() -> <S as Tr>::Option<u8> { g() }\n\
3433                   fn b() -> Option { g() }\n\
3434                   fn c() -> Vec<u8> { g() }\n\
3435                   fn d() -> std::option::Option<u8> { g() }\n\
3436                   fn e() -> <S>::bool { g() }\n\
3437                   fn e2() -> <S as Tr>::bool { g() }\n\
3438                   fn one(a: u8) -> bool { a > 1 }\n\
3439                   fn two(a: u8) -> bool { let b = a; b > 1 }\n\
3440                   fn early(a: u8) -> bool { return a > 1; }\n";
3441        let returns: Vec<(String, Option<String>, Option<&str>)> = discover(src, 0)
3442            .unwrap()
3443            .sites
3444            .into_iter()
3445            .filter_map(|s| match s.kind {
3446                SiteKind::Return {
3447                    name,
3448                    option,
3449                    sole_expr,
3450                } => Some((name, option, sole_expr.map(|(from, to)| &src[from..to]))),
3451                _ => None,
3452            })
3453            .collect();
3454        assert_eq!(
3455            returns,
3456            [
3457                (
3458                    "d".to_string(),
3459                    Some("std::option::Option<u8>".to_string()),
3460                    Some("g()")
3461                ),
3462                // Only a body that is one expression has a "sole expression".
3463                ("one".to_string(), None, Some("a > 1")),
3464                ("two".to_string(), None, None),
3465            ]
3466        );
3467    }
3468
3469    #[test]
3470    fn places_chains_attributes_and_shadowed_macros() {
3471        // A parenthesised variable is still a plain place. An attribute on a statement
3472        // belongs to its leftmost operand, which is then not probed; the statement can
3473        // still be deleted.
3474        assert_eq!(
3475            labelled("fn f(mut x: i32) -> i32 { #[allow(unused)] x += 1; (x) += 2; x }"),
3476            [
3477                "stmt #[allow(unused)] x += 1;",
3478                "stmt (x) += 2;",
3479                "arith (x) += 2"
3480            ]
3481        );
3482        // `cond && let ..` is a let chain as much as `let .. && cond`.
3483        assert_eq!(
3484            labelled("fn f(a: u8, o: Option<u8>) { if a > 1 && let Some(b) = o { g(b); } }"),
3485            ["cmp a > 1", "stmt g(b);"]
3486        );
3487        // And so is everything joined to one.
3488        assert_eq!(
3489            labelled(
3490                "fn f(a: u8, o: Option<u8>) { if a > 1 && let Some(b) = o && b > 2 { g(b); } }"
3491            ),
3492            ["cmp a > 1", "cmp b > 2", "stmt g(b);"]
3493        );
3494        // A macro of this file under a standard name takes anything as its arguments.
3495        assert_eq!(
3496            labelled(
3497                "macro_rules! vec { ($($t:tt)*) => {} }\n\
3498                 fn f(a: u8) { let _ = vec![a > 1]; let _ = format!(\"{}\", a > 2); }"
3499            ),
3500            ["cmp a > 2"]
3501        );
3502        assert_eq!(
3503            labelled(
3504                "trait T { const fn f(a: u8) -> bool { a > 1 } fn g(a: u8) -> bool { a > 2 } }"
3505            ),
3506            ["return fn g(a: u8) -> bool", "cmp a > 2"]
3507        );
3508    }
3509
3510    #[test]
3511    fn min_max_and_ranges_that_are_left_alone() {
3512        assert_eq!(
3513            labelled(
3514                "fn f(a: u8, b: u8) -> u8 { let _ = a.max::<u8>(b); \
3515                 let _ = #[allow(unused)] a.min(b); let _ = a.max(b, 1); a.max(b) }"
3516            ),
3517            ["minmax a.max(b)"]
3518        );
3519        // One literal end is enough to fix the type; the ends are searched for sites.
3520        let src = "fn f(a: usize, b: usize, v: &[u8]) { for _ in a..10 {} for _ in 1..b {} \
3521                   for _ in (a + 1)..(b * 2) {} for _ in 3..4 {} for _ in (5)..(-6) {} }";
3522        assert_eq!(
3523            labelled(src),
3524            [
3525                "range a..10",
3526                "range 1..b",
3527                "range (a + 1)..(b * 2)",
3528                "arith a + 1",
3529                "arith b * 2",
3530                // Two literal ends are no range site; the minus in one is still a minus.
3531                "neg -6"
3532            ]
3533        );
3534        let out = render(src, &discover(src, 0).unwrap().sites, &all).text;
3535        // The `..` itself is gone: the ends are the two arguments of the probe.
3536        assert!(out.contains("for _ in (match (a, 10) {"), "{out}");
3537        assert!(!out.contains("a..10") && !out.contains("1..b"), "{out}");
3538        assert!(out.contains("3..4") && out.contains("(5)..((if "), "{out}");
3539    }
3540
3541    #[test]
3542    fn which_arms_can_be_removed() {
3543        let src = "fn f(k: u8) -> u8 {\n\
3544                   \x20   let a = match k { 1 => 1, x => x, 2 => 2, #[cfg(any())] 3 => 3, _rest => 0 };\n\
3545                   \x20   let b = match k { 1 => 1, NONE => 0 };\n\
3546                   \x20   let c = match k { 1 => 1, n @ 0..=9 => n };\n\
3547                   \x20   let d = match k {\n\
3548                   \x20       1 => 1,\n\
3549                   \x20       _ => 0,\n\
3550                   \x20   };\n\
3551                   \x20   a + b + c + d\n\
3552                   }\n";
3553        let arms: Vec<(u32, usize, usize, String)> = discover(src, 7)
3554            .unwrap()
3555            .sites
3556            .into_iter()
3557            .filter(|s| matches!(s.kind, SiteKind::Arm { .. }))
3558            .map(|s| (s.id, s.line, s.column, s.text))
3559            .collect();
3560        // Neither a catch-all arm in the middle nor an arm with an attribute; and no arm
3561        // at all when the last one is a constant or binds only part of the values.
3562        assert_eq!(
3563            arms,
3564            [
3565                // After the two replaced bodies of a function that returns `u8`.
3566                (9, 2, 23, "1 => ..".to_string()),
3567                (10, 2, 39, "2 => ..".to_string()),
3568                (11, 6, 9, "1 => ..".to_string()),
3569            ]
3570        );
3571    }
3572
3573    #[test]
3574    fn offsets_around_inserted_text() {
3575        let src = "fn f(a: u8) -> bool { a > 1 }";
3576        let sites = found(src, 0).unwrap().sites;
3577        let out = render(src, &sites, &all);
3578        let start = sites[0].start;
3579        // `a` is copied right after the opening text of the probe: the last inserted
3580        // character before it still maps to the point of insertion.
3581        let copied_a = out.text.find("a), &(").unwrap();
3582        assert_eq!(out.to_original(copied_a), start);
3583        assert_eq!(out.to_original(copied_a - 1), start);
3584        assert_eq!(out.to_original(copied_a + 1), start + 1);
3585        // Past the end is the end.
3586        assert_eq!(out.to_original(out.text.len() + 10), src.len());
3587
3588        // The probe of `b + 1` opens right after the replaced `..`: an error there is
3589        // inside `b + 1`, not in front of the `..`.
3590        let src = "fn f(a: usize, b: usize) { for _ in a..b + 1 {} }";
3591        let sites = discover(src, 0).unwrap().sites;
3592        let out = render(src, &sites, &all);
3593        let inner_probe = out.text.find("(match (a, ").unwrap() + "(match (a, ".len();
3594        assert!(
3595            out.text[inner_probe..].starts_with("(match (b, 1)"),
3596            "{}",
3597            out.text
3598        );
3599        assert_eq!(out.to_original(inner_probe), src.find("b + 1").unwrap());
3600        let arith = sites
3601            .iter()
3602            .find(|s| matches!(s.kind, SiteKind::Arith { .. }))
3603            .unwrap();
3604        assert_eq!(
3605            blame(&sites, &all, out.to_original(inner_probe)),
3606            [arith.id]
3607        );
3608        // The text of a probe knows its site without going through the original.
3609        assert_eq!(out.inserted_by(inner_probe), Some(arith.id));
3610        assert_eq!(out.inserted_by(out.text.find("b, 1").unwrap()), None);
3611        // From its first to its last byte, and not one further.
3612        let opening = "(match (b, ";
3613        let (first, last) = (inner_probe, inner_probe + "(match (".len() - 1);
3614        assert!(out.text[inner_probe..].starts_with(opening));
3615        assert_eq!(out.inserted_by(first), Some(arith.id));
3616        assert_eq!(out.inserted_by(last), Some(arith.id));
3617        assert_eq!(out.inserted_by(last + 1), None);
3618        assert_eq!(out.inserted_by(0), None);
3619    }
3620    fn values(ty: &str) -> Vec<String> {
3621        let function: syn::ItemFn = syn::parse_str(&format!("fn f() -> {ty} {{ todo!() }}"))
3622            .unwrap_or_else(|e| panic!("{ty}: {e}"));
3623        body_values(&function.sig.output)
3624    }
3625
3626    /// The table of cargo-mutants (https://mutants.rs/mutants.html), row by row.
3627    #[test]
3628    fn replacement_values_by_return_type() {
3629        let rows: &[(&str, &[&str])] = &[
3630            ("()", &["()"]),
3631            ("i8", &["0", "1", "-1"]),
3632            ("isize", &["0", "1", "-1"]),
3633            ("i128", &["0", "1", "-1"]),
3634            ("u8", &["0", "1"]),
3635            ("usize", &["0", "1"]),
3636            ("u128", &["0", "1"]),
3637            ("f32", &["0.0", "1.0", "-1.0"]),
3638            ("f64", &["0.0", "1.0", "-1.0"]),
3639            ("bool", &["true", "false"]),
3640            (
3641                "NonZeroI32",
3642                &["1.try_into().unwrap()", "(-1).try_into().unwrap()"],
3643            ),
3644            ("std::num::NonZeroU8", &["1.try_into().unwrap()"]),
3645            ("NonZero<u64>", &["1.try_into().unwrap()"]),
3646            (
3647                "NonZero<i64>",
3648                &["1.try_into().unwrap()", "(-1).try_into().unwrap()"],
3649            ),
3650            ("String", &["String::new()", "\"xyzzy\".into()"]),
3651            ("&str", &["\"\"", "\"xyzzy\""]),
3652            ("&'static str", &["\"\"", "\"xyzzy\""]),
3653            // A `str` that can be written to is not a literal.
3654            ("&mut str", &["Box::leak(Box::new(Default::default()))"]),
3655            ("&u8", &["Box::leak(Box::new(0))", "Box::leak(Box::new(1))"]),
3656            (
3657                "&mut bool",
3658                &["Box::leak(Box::new(true))", "Box::leak(Box::new(false))"],
3659            ),
3660            (
3661                "&[u8]",
3662                &[
3663                    "Vec::leak(Vec::new())",
3664                    "Vec::leak(vec![0])",
3665                    "Vec::leak(vec![1])",
3666                ],
3667            ),
3668            (
3669                "&mut [bool]",
3670                &[
3671                    "Vec::leak(Vec::new())",
3672                    "Vec::leak(vec![true])",
3673                    "Vec::leak(vec![false])",
3674                ],
3675            ),
3676            ("Result<bool, Error>", &["Ok(true)", "Ok(false)"]),
3677            ("io::Result<()>", &["Ok(())"]),
3678            // Without arguments it is an alias: `fmt::Result`, or the crate's own.
3679            ("fmt::Result", &["Ok(Default::default())"]),
3680            ("Result", &["Ok(Default::default())"]),
3681            ("Option<u8>", &["None", "Some(0)", "Some(1)"]),
3682            ("Vec<bool>", &["vec![]", "vec![true]", "vec![false]"]),
3683            ("Box<u8>", &["Box::new(0)", "Box::new(1)"]),
3684            (
3685                "std::rc::Rc<u8>",
3686                &["std::rc::Rc::new(0)", "std::rc::Rc::new(1)"],
3687            ),
3688            ("Arc<bool>", &["Arc::new(true)", "Arc::new(false)"]),
3689            ("RefCell<()>", &["RefCell::new(())"]),
3690            ("Mutex<()>", &["Mutex::new(())"]),
3691            ("Cell<()>", &["Cell::new(())"]),
3692            (
3693                "HashSet<u8>",
3694                &[
3695                    "HashSet::new()",
3696                    "HashSet::from_iter([0])",
3697                    "HashSet::from_iter([1])",
3698                ],
3699            ),
3700            (
3701                "BTreeSet<()>",
3702                &["BTreeSet::new()", "BTreeSet::from_iter([()])"],
3703            ),
3704            (
3705                "BinaryHeap<()>",
3706                &["BinaryHeap::new()", "BinaryHeap::from_iter([()])"],
3707            ),
3708            (
3709                "LinkedList<()>",
3710                &["LinkedList::new()", "LinkedList::from_iter([()])"],
3711            ),
3712            (
3713                "VecDeque<()>",
3714                &["VecDeque::new()", "VecDeque::from_iter([()])"],
3715            ),
3716            (
3717                "HashMap<bool, u8>",
3718                &[
3719                    "HashMap::new()",
3720                    "HashMap::from_iter([(true, 0)])",
3721                    "HashMap::from_iter([(true, 1)])",
3722                    "HashMap::from_iter([(false, 0)])",
3723                    "HashMap::from_iter([(false, 1)])",
3724                ],
3725            ),
3726            (
3727                "std::collections::BTreeMap<(), ()>",
3728                &[
3729                    "std::collections::BTreeMap::new()",
3730                    "std::collections::BTreeMap::from_iter([((), ())])",
3731                ],
3732            ),
3733            (
3734                "Cow<'a, str>",
3735                &[
3736                    "Cow::Borrowed(\"\")",
3737                    "Cow::Owned(\"\".to_owned())",
3738                    "Cow::Borrowed(\"xyzzy\")",
3739                    "Cow::Owned(\"xyzzy\".to_owned())",
3740                ],
3741            ),
3742            ("[u8; 4]", &["[0; 4]", "[1; 4]"]),
3743            ("[bool; N + 1]", &["[true; N + 1]", "[false; N + 1]"]),
3744            (
3745                "(u8, bool)",
3746                &["(0, true)", "(0, false)", "(1, true)", "(1, false)"],
3747            ),
3748            ("(bool,)", &["(true,)", "(false,)"]),
3749            ("HttpResponse", &["HttpResponse::Ok().finish()"]),
3750            (
3751                "actix_web::HttpResponse",
3752                &["actix_web::HttpResponse::Ok().finish()"],
3753            ),
3754            ("Config", &["Default::default()"]),
3755            ("Self", &["Default::default()"]),
3756            ("<T as Tr>::Out", &["Default::default()"]),
3757            // Not the `String` everyone knows.
3758            ("<T as Tr>::String", &["Default::default()"]),
3759            ("<T>::bool", &["Default::default()"]),
3760            ("fn(u8) -> u8", &["Default::default()"]),
3761            ("*const u8", &["Default::default()"]),
3762            // Nested: every value of the inner type, wrapped.
3763            (
3764                "Result<Option<String>, E>",
3765                &[
3766                    "Ok(None)",
3767                    "Ok(Some(String::new()))",
3768                    "Ok(Some(\"xyzzy\".into()))",
3769                ],
3770            ),
3771            ("(Vec<()>)", &["vec![]", "vec![()]"]),
3772            ("Option<Config>", &["None", "Some(Default::default())"]),
3773            // Nothing can be returned in place of these.
3774            ("!", &[]),
3775            ("impl Iterator<Item = u8>", &[]),
3776            ("Box<impl Fn()>", &[]),
3777            ("Option<!>", &["None"]),
3778        ];
3779        for (ty, expected) in rows {
3780            assert_eq!(values(ty), *expected, "{ty}");
3781        }
3782        // No return type at all is `()`.
3783        let unit: syn::ItemFn = syn::parse_str("fn f() {}").unwrap();
3784        assert_eq!(body_values(&unit.sig.output), ["()"]);
3785    }
3786
3787    #[test]
3788    fn which_functions_get_their_body_replaced() {
3789        let src = r#"
3790            fn plain(a: u8) -> u8 { a + 1 }
3791            fn already(a: u8) -> bool { let _ = a; true }
3792            fn sole() -> bool { true }
3793            fn spaced() -> (u8, bool) { ( 0 , true ) }
3794            unsafe fn raw(a: u8) -> u8 { a }
3795            fn empty() {}
3796            fn one_call(s: &mut S) { s.go(); }
3797            fn two_calls(s: &mut S) { s.go(); s.stop(); }
3798            fn typed(s: &mut S) -> u8 { s.exit(); }
3799            fn tight() -> bool {true}
3800            #[rustfmt::skip]
3801            fn formatted(a: u8) -> u8 { a + 6 }
3802            #[mutants::timeout(5)]
3803            fn slow(a: u8) -> u8 { a + 7 }
3804            impl S { #[mutants::skip] fn marked_method(&self, a: u8) -> u8 { a + 8 } }
3805            trait U { #[mutants::skip] fn marked_default(&self, a: u8) -> u8 { a + 9 } }
3806            fn one_let(a: u8) { let _ = a; }
3807            fn never() -> ! { loop {} }
3808            fn hidden() -> impl Sized { 1 }
3809            #[mutants::skip]
3810            fn marked(a: u8) -> u8 { a + 2 }
3811            #[cfg_attr(test, mutants::skip)]
3812            fn marked_in_tests(a: u8) -> u8 { a + 3 }
3813            #[mutants::skip]
3814            impl S { fn method(&self, a: u8) -> u8 { a + 4 } }
3815            #[mutants::skip]
3816            mod generated { fn inner(a: u8) -> u8 { a + 5 } }
3817            trait T { fn required(&self) -> u8; fn provided(&self) -> u8 { 7 } }
3818            async fn later() -> u8 { 9 }
3819        "#;
3820        let sites = discover(src, 0).unwrap().sites;
3821        let bodies: Vec<String> = sites
3822            .iter()
3823            .filter_map(|s| match &s.kind {
3824                SiteKind::Body { name, value, .. } => Some(format!("{name} {value}")),
3825                _ => None,
3826            })
3827            .collect();
3828        assert_eq!(
3829            bodies,
3830            [
3831                "plain 0",
3832                "plain 1",
3833                "already true",
3834                "already false",
3835                // The body is this value already, however it is spaced.
3836                "sole false",
3837                "spaced (0, false)",
3838                "spaced (1, true)",
3839                "spaced (1, false)",
3840                // One statement that can be deleted is the same mutant as no body.
3841                "two_calls ()",
3842                // With a result to return, one statement is not the whole of it.
3843                "typed 0",
3844                "typed 1",
3845                "tight false",
3846                // Other attributes with `skip` or `mutants` in them do not mark anything.
3847                "formatted 0",
3848                "formatted 1",
3849                "slow 0",
3850                "slow 1",
3851                "one_let ()",
3852                "provided 0",
3853                "provided 1",
3854                "later 0",
3855                "later 1",
3856            ]
3857        );
3858        // Nothing at all is mutated in what is marked to be skipped.
3859        let texts: Vec<&str> = sites.iter().map(|s| s.text.as_str()).collect();
3860        for skipped in ["a + 2", "a + 3", "a + 4", "a + 5", "a + 8", "a + 9"] {
3861            assert!(!texts.contains(&skipped), "{skipped}");
3862        }
3863        for mutated in ["a + 1", "a + 6", "a + 7"] {
3864            assert!(texts.contains(&mutated), "{mutated}");
3865        }
3866        let unsafe_sites: Vec<&Site> = sites.iter().filter(|s| s.text.contains("raw")).collect();
3867        assert!(unsafe_sites.is_empty(), "{unsafe_sites:?}");
3868
3869        let body = sites
3870            .iter()
3871            .find(|s| matches!(s.kind, SiteKind::Body { .. }))
3872            .unwrap();
3873        assert_eq!(
3874            (body.line, body.column, body.text.as_str()),
3875            (2, 13, "fn plain(a: u8) -> u8")
3876        );
3877        let out = render(src, &sites, &all).text;
3878        syn::parse_file(&out).expect("instrumented source parses");
3879        assert_eq!(out.lines().count(), src.lines().count());
3880        assert!(
3881            out.contains(
3882                "fn plain(a: u8) -> u8 { if !crate::__tmt_rt::live(0u32) { return 0; } \
3883                 if !crate::__tmt_rt::live(1u32) { return 1; } (match (a, 1)"
3884            ),
3885            "{out}"
3886        );
3887        // A body that is exactly its expression: the function-level probes go around
3888        // the probe of the expression.
3889        let tight = "fn f(a: u8, b: u8) -> bool {a > b}";
3890        let sites = discover(tight, 0).unwrap().sites;
3891        let out = render(tight, &sites, &all).text;
3892        syn::parse_file(&out).expect("instrumented source parses");
3893        assert!(
3894            out.starts_with(
3895                "fn f(a: u8, b: u8) -> bool { let __tmt_v: bool = { \
3896                 if !crate::__tmt_rt::live(1u32) { return true; } \
3897                 if !crate::__tmt_rt::live(2u32) { return false; }(match (&(a), &(b))"
3898            ),
3899            "{out}"
3900        );
3901        assert!(
3902            out.ends_with(" })}; crate::__tmt_rt::ret(0u32, __tmt_v) }"),
3903            "{out}"
3904        );
3905    }
3906
3907    #[test]
3908    fn minus_guards_and_fields() {
3909        let src = r#"
3910            fn f(x: i32, y: f64, k: Kind, base: Options) -> Options {
3911                let a = -x + -5 - -0 + (-0.0 * -y) as i32;
3912                let b = match k {
3913                    Kind::A(n) if n > 1 => 1,
3914                    Kind::A(n) if let Some(m) = half(n) => m,
3915                    Kind::B if x > 0 && let Some(m) = half(x) => m,
3916                    #[cfg(any())]
3917                    Kind::B if x > 2 => 2,
3918                    Kind::B => 3,
3919                };
3920                let c = match b { n if n > 3 => 1, _ => 0 };
3921                let first = Options { depth: a, name, ..base };
3922                let second = Options { depth: -b, ..Default::default() };
3923                let third = Wrap::<u8> { 0: c, ..Wrap::new() };
3924                let _ = Options { depth: 1, ..base.clone() };
3925                let _ = Options { depth: 2, ..make(3) };
3926                let _ = Options { depth: 6, ..(pick())() };
3927                let _ = -2.5 + y;
3928                let _ = Options { #[cfg(any())] depth: 4, strict: true, ..*other };
3929                let _ = Options { depth: 5, name: n, strict: false };
3930                first
3931            }
3932        "#;
3933        let sites = found(src, 0).unwrap().sites;
3934        let kinds: Vec<String> = sites
3935            .iter()
3936            .filter_map(|s| match &s.kind {
3937                SiteKind::Neg {
3938                    operand, literal, ..
3939                } => Some(format!("neg {} | {operand} | literal={literal}", s.text)),
3940                SiteKind::Guard { can_be_false } => {
3941                    Some(format!("guard {} | can_be_false={can_be_false}", s.text))
3942                }
3943                SiteKind::Field {
3944                    name,
3945                    shorthand,
3946                    from_base: Some(from_base),
3947                    ..
3948                } => Some(format!(
3949                    "field {} | {name} | shorthand={shorthand} | {from_base}",
3950                    s.text
3951                )),
3952                _ => None,
3953            })
3954            .collect();
3955        assert_eq!(
3956            kinds,
3957            [
3958                "neg -x | x | literal=false",
3959                "neg -5 | 5 | literal=true",
3960                // `-0` is 0 either way; `-0.0` is not `0.0`.
3961                "neg -0.0 | 0.0 | literal=true",
3962                "neg -y | y | literal=false",
3963                // No catch-all arm: the arm cannot be removed, so `false` is a mutant.
3964                "guard n > 1 | can_be_false=true",
3965                // Where the arm can be removed, that is the guard being `false`.
3966                "guard n > 3 | can_be_false=false",
3967                "field depth: a | depth | shorthand=false | (base).depth",
3968                "field name | name | shorthand=true | (base).name",
3969                "field depth: -b | depth | shorthand=false | (Options { ..Default::default() }).depth",
3970                "neg -b | b | literal=false",
3971                "field 0: c | 0 | shorthand=false | (Wrap::<u8> { ..Wrap::new() }).0",
3972                "neg -2.5 | 2.5 | literal=true",
3973                // Not with a base that has arguments, a receiver or a computed function,
3974                // not a field with an attribute, and not without a base.
3975                "field strict: true | strict | shorthand=false | (*other).strict",
3976            ]
3977        );
3978        // A field is reported where its name stands.
3979        let field = sites
3980            .iter()
3981            .find(|s| s.text == "depth: a")
3982            .expect("the field is a site");
3983        let line = src.lines().nth(field.line - 1).unwrap();
3984        assert_eq!(line.find("depth: a"), Some(field.column - 1), "{line}");
3985        assert_eq!(&src[field.start..field.end], "a");
3986        let out = render(src, &sites, &all).text;
3987        syn::parse_file(&out).expect("instrumented source parses");
3988        assert_eq!(out.lines().count(), src.lines().count());
3989        for expected in [
3990            // The operand is evaluated once, outside the names of the probe.
3991            "(match (x) { __tmt_a => if crate::__tmt_rt::live(",
3992            // A literal stays a literal, with the type its place gives it.
3993            "u32) { -__tmt_a } else { __tmt_a } })",
3994            "u32) { -5 } else { 5 })",
3995            // A guard and the comparison it consists of: the guard goes around.
3996            "Kind::A(n) if crate::__tmt_rt::ret(",
3997            "u32, (match (&(n), &(1))",
3998            "n if crate::__tmt_rt::arm(",
3999            ") && (crate::__tmt_rt::ret(",
4000            "depth: if crate::__tmt_rt::live(",
4001            "{ a } else { (base).depth }",
4002            // A field written by its name alone gets the name back.
4003            "name: if crate::__tmt_rt::live(",
4004            "{ name } else { (base).name }, ..base }",
4005            "} else { (Options { ..Default::default() }).depth }, ..Default::default() }",
4006            "0: if crate::__tmt_rt::live(",
4007            "Options { depth: 1, ..base.clone() }",
4008            "Options { depth: 2, ..make(3) }",
4009            "Options { depth: 6, ..(pick())() }",
4010            "Options { depth: 5, name: n, strict: false }",
4011        ] {
4012            assert!(out.contains(expected), "{expected}\n{out}");
4013        }
4014        assert!(
4015            !out.contains("{ -0 }") && out.contains("{ -0.0 } else { 0.0 }"),
4016            "{out}"
4017        );
4018    }
4019    /// The source with each mutant of each site applied, as `what -> into: text`.
4020    fn mutated(src: &str, sites: &[Site]) -> Vec<String> {
4021        sites
4022            .iter()
4023            .flat_map(|site| {
4024                source_mutants(site).into_iter().map(|m| {
4025                    let text = format!("{}{}{}", &src[..m.start], m.replacement, &src[m.end..]);
4026                    syn::parse_file(&text).unwrap_or_else(|e| panic!("{text}: {e}"));
4027                    format!("{} -> {}: {}", m.what, m.into, text.trim())
4028                })
4029            })
4030            .collect()
4031    }
4032
4033    #[test]
4034    fn what_cannot_be_probed_is_mutated_in_the_source() {
4035        // Everything in a `const fn`, a compound assignment to more than a variable,
4036        // and the body of a function that returns an iterator.
4037        let src = "const fn c(a: u8, b: u8) -> bool { a < b }\n\
4038                   fn f(m: &mut Map, k: u8) { *m.entry(k).or_insert(0) += 1; m.total -= 1; }\n\
4039                   fn evens(n: u8) -> impl Iterator<Item = u8> + '_ { (0..n).step_by(2) }\n\
4040                   impl S { const fn k(&self) -> u8 { -self.0 } }\n\
4041                   trait T { const fn d(a: u8) -> u8 { a } }\n";
4042        let found = discover(src, 0).unwrap();
4043        assert!(found.rebuild_sites.iter().all(|s| s.id == NO_ID));
4044        let places: Vec<(usize, usize, &str)> = found
4045            .rebuild_sites
4046            .iter()
4047            .filter(|s| !matches!(s.kind, SiteKind::Return { .. }))
4048            .map(|s| (s.line, s.column, s.text.as_str()))
4049            .collect();
4050        assert_eq!(
4051            places,
4052            [
4053                (1, 1, "const fn c(a: u8, b: u8) -> bool"),
4054                (1, 1, "const fn c(a: u8, b: u8) -> bool"),
4055                (1, 36, "a < b"),
4056                (2, 28, "*m.entry(k).or_insert(0) += 1"),
4057                (3, 1, "fn evens(n: u8) -> impl Iterator<Item = u8> + '_"),
4058                (3, 1, "fn evens(n: u8) -> impl Iterator<Item = u8> + '_"),
4059                (3, 1, "fn evens(n: u8) -> impl Iterator<Item = u8> + '_"),
4060                // A range that is not run through by a `for`.
4061                (3, 53, "0..n"),
4062                (4, 10, "const fn k(&self) -> u8"),
4063                (4, 10, "const fn k(&self) -> u8"),
4064                (4, 36, "-self.0"),
4065                (5, 11, "const fn d(a: u8) -> u8"),
4066                (5, 11, "const fn d(a: u8) -> u8"),
4067            ]
4068        );
4069        assert_eq!(
4070            found.sites.iter().map(|s| s.id).collect::<Vec<_>>(),
4071            (0..found.sites.len() as u32).collect::<Vec<_>>()
4072        );
4073        let numbered: Vec<&str> = found.sites.iter().map(|s| s.text.as_str()).collect();
4074        assert_eq!(
4075            numbered,
4076            [
4077                "fn f(m: &mut Map, k: u8)",
4078                "*m.entry(k).or_insert(0) += 1;",
4079                "m.total -= 1;",
4080                "m.total -= 1",
4081            ]
4082        );
4083        assert_eq!(
4084            mutated(src, &found.rebuild_sites)
4085                .iter()
4086                .map(|line| line.lines().next().unwrap().to_string())
4087                .take(5)
4088                .collect::<Vec<_>>(),
4089            [
4090                "body -> true: const fn c(a: u8, b: u8) -> bool { true }",
4091                "body -> false: const fn c(a: u8, b: u8) -> bool { false }",
4092                "< -> ==: const fn c(a: u8, b: u8) -> bool { a == b }",
4093                "< -> >: const fn c(a: u8, b: u8) -> bool { a > b }",
4094                "< -> <=: const fn c(a: u8, b: u8) -> bool { a <= b }",
4095            ]
4096        );
4097        let whats: Vec<String> = found
4098            .rebuild_sites
4099            .iter()
4100            .flat_map(|site| {
4101                source_mutants(site)
4102                    .into_iter()
4103                    .map(|m| format!("{}: {} -> {}", site.text, m.what, m.into))
4104            })
4105            .skip(5)
4106            .collect();
4107        assert_eq!(
4108            whats,
4109            [
4110                "*m.entry(k).or_insert(0) += 1: += -> -=",
4111                "*m.entry(k).or_insert(0) += 1: += -> *=",
4112                "fn evens(n: u8) -> impl Iterator<Item = u8> + '_: body -> ::core::iter::empty()",
4113                "fn evens(n: u8) -> impl Iterator<Item = u8> + '_: body -> ::core::iter::once(0)",
4114                "fn evens(n: u8) -> impl Iterator<Item = u8> + '_: body -> ::core::iter::once(1)",
4115                "0..n: .. -> ..=",
4116                "const fn k(&self) -> u8: body -> 0",
4117                "const fn k(&self) -> u8: body -> 1",
4118                "-self.0: - -> ",
4119                "const fn d(a: u8) -> u8: body -> 0",
4120                "const fn d(a: u8) -> u8: body -> 1",
4121            ]
4122        );
4123    }
4124
4125    #[test]
4126    fn fields_are_removed_from_arbitrary_struct_updates() {
4127        // Full-strength table from fields.pict.
4128        for base in ["base", "make(seed)", "builder.make(seed)"] {
4129            for field in ["value: 9", "value"] {
4130                for attribute in ["", "#[cfg(any())] "] {
4131                    let original =
4132                        format!("fn f() -> S {{ S {{ {attribute}{field}, other: 2, ..{base} }} }}");
4133                    let found = discover(&original, 0).unwrap();
4134                    let fields: Vec<_> = found
4135                        .sites
4136                        .iter()
4137                        .chain(&found.rebuild_sites)
4138                        .flat_map(source_mutants)
4139                        .filter(|mutant| mutant.what == "field" && mutant.into == "value")
4140                        .collect();
4141                    if attribute.is_empty() {
4142                        assert_eq!(fields.len(), 1, "{original}");
4143                        let m = &fields[0];
4144                        let changed = format!(
4145                            "{}{}{}",
4146                            &original[..m.start],
4147                            m.replacement,
4148                            &original[m.end..]
4149                        );
4150                        assert_eq!(
4151                            changed,
4152                            format!("fn f() -> S {{ S {{  other: 2, ..{base} }} }}")
4153                        );
4154                        syn::parse_file(&changed).unwrap();
4155                    } else {
4156                        assert!(fields.is_empty(), "{original}");
4157                    }
4158                }
4159            }
4160        }
4161        let plain = discover("fn plain() -> S { S { value: 9 } }", 0).unwrap();
4162        assert!(
4163            plain
4164                .sites
4165                .iter()
4166                .chain(&plain.rebuild_sites)
4167                .flat_map(source_mutants)
4168                .all(|m| m.what != "field")
4169        );
4170    }
4171
4172    #[test]
4173    fn unknown_wrappers_and_nested_iterators_have_source_body_candidates() {
4174        // Full-strength table from generics.pict.
4175        for outer in ["Wrapper", "Option", "Result"] {
4176            for inner in ["bool", "impl Iterator<Item = u8>"] {
4177                for error in [false, true] {
4178                    let error_values: &[&str] = if error { &["7"] } else { &[] };
4179                    let extra = if outer == "Result" { ", u8" } else { "" };
4180                    let source = format!("fn f() -> {outer}<{inner}{extra}> {{ todo!() }}");
4181                    let found = discover_with_errors(&source, 0, error_values).unwrap();
4182                    let values: Vec<&str> = found
4183                        .sites
4184                        .iter()
4185                        .chain(&found.rebuild_sites)
4186                        .filter_map(|site| match &site.kind {
4187                            SiteKind::Body { value, .. } => Some(value.as_str()),
4188                            _ => None,
4189                        })
4190                        .collect();
4191                    let example = match (outer, inner) {
4192                        ("Wrapper", "bool") => "Wrapper::from_iter([false])",
4193                        ("Option", "bool") => "Some(false)",
4194                        ("Result", "bool") => "Ok(false)",
4195                        ("Wrapper", _) => "Wrapper::new(::core::iter::once(1))",
4196                        ("Option", _) => "Some(::core::iter::once(1))",
4197                        ("Result", _) => "Ok(::core::iter::once(1))",
4198                        _ => unreachable!(),
4199                    };
4200                    assert!(values.contains(&example), "{source}: {values:?}");
4201                    assert_eq!(
4202                        values.contains(&"Err(7)"),
4203                        outer == "Result" && error,
4204                        "{source}"
4205                    );
4206                    if inner != "bool" {
4207                        assert!(found.sites.is_empty(), "{source}");
4208                    }
4209                }
4210            }
4211        }
4212    }
4213
4214    #[test]
4215    fn source_deletes_the_whole_statement_and_the_unguarded_arm() {
4216        let source = "fn clear(v: &mut Vec<u8>) { v.clear(); }\n\
4217            fn select(x: u8) -> u8 { match x { 0 => 4, #[allow(unused)] 1 => 5, _ => 6 } }";
4218        let found = discover(source, 0).unwrap();
4219        let removals: Vec<_> = found
4220            .sites
4221            .iter()
4222            .chain(&found.rebuild_sites)
4223            .flat_map(source_mutants)
4224            .filter(|mutant| mutant.replacement.is_empty())
4225            .map(|mutant| &source[mutant.start..mutant.end])
4226            .collect();
4227        assert!(removals.contains(&"v.clear();"), "{removals:?}");
4228        assert!(removals.contains(&"0 => 4,"), "{removals:?}");
4229        assert!(
4230            removals.contains(&"#[allow(unused)] 1 => 5,"),
4231            "{removals:?}"
4232        );
4233    }
4234
4235    #[test]
4236    fn source_mutants_of_every_kind() {
4237        let src = "fn f(a: i32, b: i32, k: K, base: O) -> O { \
4238                   let x = match k { K::A(n) if n >= 1 => !(a != b) || a <= -b, K::B => a % b > 0 && a == b, _ => false }; \
4239                   O { on: x, a, ..base } }";
4240        let sites = found(src, 0).unwrap().sites;
4241        // Every one of them is still a source file.
4242        assert_eq!(mutated(src, &sites).len(), 18);
4243        let changes: Vec<String> = sites
4244            .iter()
4245            .flat_map(source_mutants)
4246            .map(|m| {
4247                format!(
4248                    "{} -> {} | `{}` becomes `{}`",
4249                    m.what,
4250                    m.into,
4251                    &src[m.start..m.end],
4252                    m.replacement
4253                )
4254            })
4255            .collect();
4256        assert_eq!(
4257            changes,
4258            [
4259                // A guarded arm uses a false guard, and an unguarded arm is removed.
4260                "arm -> K::A(n) if n >= 1 | `n >= 1` becomes `false`",
4261                "arm -> K::B | `K::B => a % b > 0 && a == b,` becomes ``",
4262                "guard -> true | `n >= 1` becomes `true`",
4263                ">= -> < | ` >= ` becomes ` < `",
4264                "|| -> && | `!(a != b) || a <= -b` becomes `(!(a != b)) && (a <= -b)`",
4265                "! ->  | `!` becomes ``",
4266                "!= -> == | ` != ` becomes ` == `",
4267                "<= -> > | ` <= ` becomes ` > `",
4268                "- ->  | `-` becomes ``",
4269                "&& -> || | `a % b > 0 && a == b` becomes `(a % b > 0 || a == b)`",
4270                "> -> == | ` > ` becomes ` == `",
4271                "> -> < | ` > ` becomes ` < `",
4272                "> -> >= | ` > ` becomes ` >= `",
4273                "% -> / | ` % ` becomes ` / `",
4274                "% -> + | `a % b` becomes `(a + b)`",
4275                "== -> != | ` == ` becomes ` != `",
4276                "field -> on | `on: x,` becomes ``",
4277                "field -> a | `a,` becomes ``",
4278            ]
4279        );
4280        // What exists only as a probe has no mutant of the source.
4281        let src = "fn f(a: u8, b: u8) -> bool { g(); for _ in a..b {} a.max(b) > 1 }";
4282        let sites = discover(src, 0).unwrap().sites;
4283        for site in &sites {
4284            let none = matches!(site.kind, SiteKind::Return { .. } | SiteKind::MinMax { .. });
4285            assert_eq!(source_mutants(site).is_empty(), none, "{:?}", site.kind);
4286        }
4287        // A range has its end taken in or left out, whichever it is not.
4288        let ends = |src: &str| -> Vec<String> {
4289            discover(src, 0)
4290                .unwrap()
4291                .sites
4292                .iter()
4293                .filter(|site| matches!(site.kind, SiteKind::Range { .. }))
4294                .flat_map(source_mutants)
4295                .map(|m| format!("{}{}{}", &src[..m.start], m.replacement, &src[m.end..]))
4296                .collect()
4297        };
4298        assert_eq!(
4299            ends("fn f(a: u8, b: u8) { for _ in a..b {} }"),
4300            ["fn f(a: u8, b: u8) { for _ in a..=b {} }"]
4301        );
4302        assert_eq!(
4303            ends("fn f(a: u8, b: u8) { for _ in a ..= b {} }"),
4304            ["fn f(a: u8, b: u8) { for _ in a..b {} }"]
4305        );
4306    }
4307
4308    #[test]
4309    fn iterators_to_return_instead() {
4310        let values = |ty: &str| {
4311            let function: syn::ItemFn =
4312                syn::parse_str(&format!("fn f() -> {ty} {{ todo!() }}")).unwrap();
4313            iterator_values(&function.sig.output)
4314        };
4315        assert_eq!(
4316            values("impl Iterator<Item = bool>"),
4317            [
4318                "::core::iter::empty()",
4319                "::core::iter::once(true)",
4320                "::core::iter::once(false)"
4321            ]
4322        );
4323        assert_eq!(
4324            values("impl std::iter::Iterator<Item = String> + Send + 'a").len(),
4325            3
4326        );
4327        // The item is the binding called `Item`, wherever it stands.
4328        assert_eq!(
4329            values("impl Iterator<Extra = u8, Item = ()>"),
4330            ["::core::iter::empty()", "::core::iter::once(())"]
4331        );
4332        // An item that is itself opaque has no value to make up.
4333        assert_eq!(
4334            values("impl Iterator<Item = impl Sized>"),
4335            ["::core::iter::empty()"]
4336        );
4337        for other in [
4338            "impl Sized",
4339            "impl Iterator",
4340            "impl IntoIterator<Item = u8>",
4341            "Box<dyn Iterator<Item = u8>>",
4342            "u8",
4343            "()",
4344        ] {
4345            assert!(values(other).is_empty(), "{other}");
4346        }
4347        let unit: syn::ItemFn = syn::parse_str("fn f() {}").unwrap();
4348        assert!(iterator_values(&unit.sig.output).is_empty());
4349    }
4350
4351    /// The source with each mutant of its sites that are built, one after the other.
4352    fn built(src: &str) -> Vec<String> {
4353        let found = discover(src, 0).unwrap();
4354        found
4355            .rebuild_sites
4356            .iter()
4357            .flat_map(source_mutants)
4358            .map(|m| format!("{}{}{}", &src[..m.start], m.replacement, &src[m.end..]))
4359            .collect()
4360    }
4361
4362    #[test]
4363    fn a_body_that_is_written_as_the_value_and_one_that_only_computes() {
4364        let bodies = |src: &str| -> Vec<(String, bool)> {
4365            discover(src, 0)
4366                .unwrap()
4367                .sites
4368                .iter()
4369                .filter_map(|site| match &site.kind {
4370                    SiteKind::Body {
4371                        value, sole_expr, ..
4372                    } => Some((value.clone(), sole_expr.is_some())),
4373                    _ => None,
4374                })
4375                .collect()
4376        };
4377        let values = |src: &str| -> Vec<String> { bodies(src).into_iter().map(|b| b.0).collect() };
4378        // The value the body already is makes no mutant, however it is spaced.
4379        assert_eq!(values("fn t() -> bool { true }"), ["false"]);
4380        assert_eq!(values("fn n() -> u8 {  0  }"), ["1"]);
4381        assert_eq!(
4382            values("fn s() -> String { String :: new () }"),
4383            ["\"xyzzy\".into()"]
4384        );
4385        // White space inside a literal is not spacing: `" "` is not the empty string.
4386        assert_eq!(
4387            values("fn s() -> &'static str { \" \" }"),
4388            ["\"\"", "\"xyzzy\""]
4389        );
4390        // A body that only computes its value can be said at that expression; one
4391        // that calls, assigns or leaves early does more than give a value.
4392        for (body, only_computes) in [
4393            ("n > 0", true),
4394            ("!(self.limit < n) && n as u8 != 3", true),
4395            ("(n, 1).0 > *&n", true),
4396            ("self.push(n) > 0", false),
4397            ("next() > 0", false),
4398            ("matches!(n, 1)", false),
4399            ("(if n > 1 { n } else { 0 }) > 0", false),
4400            ("list[n] > 0", false),
4401            ("check(n)? > 0", false),
4402            ("(self.count += n) == ()", false),
4403            ("(self.count = n) == ()", false),
4404        ] {
4405            let src = format!("impl S {{ fn f(&mut self, n: usize) -> bool {{ {body} }} }}");
4406            let all = bodies(&src);
4407            assert_eq!(all.len(), 2, "{body}");
4408            assert!(all.iter().all(|b| b.1 == only_computes), "{body}: {all:?}");
4409        }
4410    }
4411
4412    #[test]
4413    fn items_are_named_by_what_is_around_them() {
4414        let src = "fn top(a: u8) -> u8 { fn inner(b: u8) -> u8 { b } inner(a) }\n\
4415                   mod m { pub fn in_mod() {} const K: u8 = 1; }\n\
4416                   impl Store { fn commit(&self) {} const LIMIT: u8 = 2; }\n\
4417                   impl<T> fmt::Display for Id<T> { fn fmt(&self) {} }\n\
4418                   trait Tr { fn provided(&self) {} fn required(&self); }\n\
4419                   static S: u8 = 3;\nlet";
4420        // Not a source file: nothing is named.
4421        assert!(named_items(src).is_empty());
4422        let src = src.strip_suffix("let").unwrap();
4423        let items = named_items(src);
4424        let names: Vec<&str> = items.iter().map(|item| item.name.as_str()).collect();
4425        assert_eq!(
4426            names,
4427            [
4428                "top",
4429                "top::inner",
4430                "m::in_mod",
4431                "m::K",
4432                "Store::commit",
4433                "Store::LIMIT",
4434                "<fmt::Display for Id<T>>::fmt",
4435                "Tr::provided",
4436                "Tr::required",
4437                "S",
4438            ]
4439        );
4440        // The innermost item a place is in; none between the items.
4441        let at = |text: &str| src.find(text).unwrap();
4442        assert_eq!(enclosing_item(&items, at("{ b }") + 2), "top::inner");
4443        assert_eq!(enclosing_item(&items, at("inner(a)")), "top");
4444        assert_eq!(enclosing_item(&items, at("fn top")), "top");
4445        assert_eq!(enclosing_item(&items, at("mod m")), "");
4446        assert_eq!(enclosing_item(&items, at("= 2") + 2), "Store::LIMIT");
4447        assert_eq!(enclosing_item(&items, src.len()), "");
4448        // An item is its first byte to its last, and not a byte more on either side.
4449        let (first, after) = (at("pub fn in_mod"), at("pub fn in_mod() {}") + 18);
4450        assert_eq!(enclosing_item(&items, first - 1), "");
4451        assert_eq!(enclosing_item(&items, first), "m::in_mod");
4452        assert_eq!(enclosing_item(&items, after - 1), "m::in_mod");
4453        assert_eq!(enclosing_item(&items, after), "");
4454        // Lines and columns count from one, columns in characters.
4455        let text = "ab\nçd e\n";
4456        assert_eq!(offset_of(text, 1, 1), Some(0));
4457        assert_eq!(offset_of(text, 1, 2), Some(1));
4458        assert_eq!(offset_of(text, 2, 1), Some(3));
4459        assert_eq!(offset_of(text, 2, 2), Some(5), "after the two bytes of `ç`");
4460        assert_eq!(offset_of(text, 2, 99), Some(text.len()));
4461        assert_eq!(offset_of(text, 0, 1), None);
4462        assert_eq!(offset_of(text, 1, 0), None);
4463    }
4464
4465    #[test]
4466    fn only_the_range_of_a_for_is_probed() {
4467        let src = "fn f(a: u8, b: u8, v: &[u8]) -> usize {\n\
4468                   for _ in a..b {}\n\
4469                   for _ in (a..=b) {}\n\
4470                   for _ in (a..b).rev() {}\n\
4471                   let kept = a..b;\n\
4472                   let _ = &v[a as usize..b as usize];\n\
4473                   for _ in kept.clone() {}\n\
4474                   for _ in 0..3 {}\n\
4475                   let _ = &v[0..3];\n\
4476                   (a..=b).count() }";
4477        let all = discover(src, 0).unwrap();
4478        let ranges = |sites: &[Site]| -> Vec<usize> {
4479            sites
4480                .iter()
4481                .filter(|site| matches!(site.kind, SiteKind::Range { .. }))
4482                .map(|site| site.line)
4483                .collect()
4484        };
4485        // Run through directly by a `for`, with or without parentheses.
4486        assert_eq!(ranges(&all.sites), [2, 3]);
4487        // Kept, indexed with, or given to a method: built, as the source says them.
4488        // And two literals wherever they are: nothing gives a probe their type.
4489        assert_eq!(ranges(&all.rebuild_sites), [4, 5, 6, 8, 9, 10]);
4490        let literal: Vec<(&str, String)> = all
4491            .rebuild_sites
4492            .iter()
4493            .filter(|site| site.line == 8 || site.line == 9)
4494            .flat_map(|site| {
4495                source_mutants(site)
4496                    .into_iter()
4497                    .map(move |mutant| (site.text.as_str(), mutant.replacement))
4498            })
4499            .collect();
4500        assert_eq!(
4501            literal,
4502            [("0..3", "..=".to_string()), ("0..3", "..=".to_string())]
4503        );
4504    }
4505
4506    #[test]
4507    fn what_marks_code_as_not_to_be_mutated() {
4508        let src = "#[allow(mutants, skip)] fn loosely(a: u8) -> u8 { a + 1 }\n\
4509                   #[doc = \"mutants skip\"] fn spoken_of(a: u8) -> u8 { a + 2 }\n\
4510                   #[mutants :: skip] fn spaced(a: u8) -> u8 { a + 3 }\n\
4511                   #[cfg_attr(test, mutants::skip)] fn conditional(a: u8) -> u8 { a + 4 }\n\
4512                   #[mutants::skip] mod generated;\n\
4513                   #[mutants::skip] #[path = \"gen/other.rs\"] mod other;\n\
4514                   mod plain;\n\
4515                   mod inline { fn inner(a: u8) -> u8 { a + 5 } }\n\
4516                   #[mutants::skip] mod marked { fn inner(a: u8) -> u8 { a + 6 } }\n";
4517        let all = discover(src, 0).unwrap();
4518        let texts: Vec<&str> = found_arith(&all.sites);
4519        assert_eq!(texts, ["a + 1", "a + 2", "a + 5"]);
4520        // The file of a marked module is not looked into either.
4521        assert_eq!(
4522            all.test_modules,
4523            [
4524                TestModule {
4525                    name: "generated".to_string(),
4526                    path: None
4527                },
4528                TestModule {
4529                    name: "other".to_string(),
4530                    path: Some("gen/other.rs".to_string())
4531                },
4532            ]
4533        );
4534    }
4535
4536    fn found_arith(sites: &[Site]) -> Vec<&str> {
4537        sites
4538            .iter()
4539            .filter(|site| matches!(site.kind, SiteKind::Arith { .. }))
4540            .map(|site| site.text.as_str())
4541            .collect()
4542    }
4543
4544    #[test]
4545    fn a_replaced_operator_keeps_its_operands() {
4546        // Every replacement is the same tree with another operator, also where the new
4547        // operator binds otherwise than the old one.
4548        assert_eq!(
4549            built("const X: i32 = 8 - 2 * 3;"),
4550            [
4551                "const X: i32 = 8 + 2 * 3;",
4552                "const X: i32 = (8) / (2 * 3);",
4553                "const X: i32 = 8 - 2 / 3;",
4554                "const X: i32 = 8 - (2 + 3);",
4555            ]
4556        );
4557        assert_eq!(
4558            built("const B: bool = P || Q && R;"),
4559            [
4560                "const B: bool = (P) && (Q && R);",
4561                "const B: bool = P || (Q || R);",
4562            ]
4563        );
4564        assert_eq!(
4565            built("const M: u8 = A & B | C;"),
4566            [
4567                "const M: u8 = (A & B) & (C);",
4568                "const M: u8 = (A & B) ^ (C);",
4569                "const M: u8 = (A | B) | C;",
4570                "const M: u8 = (A ^ B) | C;",
4571            ]
4572        );
4573        assert_eq!(
4574            built("const S: u8 = 1 << 2 + 1;"),
4575            [
4576                "const S: u8 = 1 >> 2 + 1;",
4577                "const S: u8 = 1 << 2 - 1;",
4578                "const S: u8 = 1 << (2) * (1);",
4579            ]
4580        );
4581        // Comparisons bind alike, and an assignment has its operands to itself.
4582        assert_eq!(
4583            built("const C: bool = A + 1 < B;")[..3],
4584            [
4585                "const C: bool = A + 1 == B;",
4586                "const C: bool = A + 1 > B;",
4587                "const C: bool = A + 1 <= B;",
4588            ]
4589        );
4590        let assigned = built("const fn f(mut x: u8) -> u8 { x += 2 * 3; x }");
4591        for expected in [
4592            "const fn f(mut x: u8) -> u8 { x -= 2 * 3; x }",
4593            "const fn f(mut x: u8) -> u8 { x *= 2 * 3; x }",
4594            "const fn f(mut x: u8) -> u8 { x += (2 + 3); x }",
4595        ] {
4596            assert!(assigned.iter().any(|text| text == expected), "{assigned:?}");
4597        }
4598    }
4599
4600    #[test]
4601    fn excluded_parent_items_do_not_contribute_const_sites() {
4602        let source = r#"
4603            #[cfg(test)] enum TestEnum { A = 1 + 2 }
4604            #[mutants::skip] struct Skip { a: [u8; 2 + 3] }
4605            #[cfg(test)] type Alias = [u8; 3 + 4];
4606            #[cfg(test)] union TestUnion { a: [u8; 4 + 5] }
4607            #[mutants::skip] trait Hidden { const DATA: [u8; 5 + 6]; }
4608            struct Data { #[cfg(test)] bytes: [u8; 6 + 7] }
4609            fn f() { #[cfg(test)] let _: [u8; 8 + 9] = [0; 17]; }
4610            const DATA: [u8; 7 + 8] = [0; 15];
4611        "#;
4612        let found = discover(source, 0).unwrap();
4613        let sites: Vec<_> = found
4614            .rebuild_sites
4615            .iter()
4616            .map(|site| site.text.as_str())
4617            .collect();
4618        assert_eq!(sites, ["7 + 8"]);
4619    }
4620
4621    #[test]
4622    fn compile_time_expressions_get_source_mutants_but_never_probes() {
4623        // Full strength-three table from const.pict.
4624        for (place, context) in [
4625            ("inline", "let _ = const { 6 * 7 };"),
4626            ("repeat", "let _ = [0u8; 6 * 7];"),
4627            ("type length", "let _: [u8; 6 * 7];"),
4628            ("discriminant", "enum Value { One = 6 * 7 }"),
4629            ("const argument", "let _: Items<{ 6 * 7 }>;"),
4630            ("const default", "struct Items<const N: usize = { 6 * 7 }>;"),
4631        ] {
4632            for qualifier in ["", "const "] {
4633                for marker in ["", "#[mutants::skip] "] {
4634                    let source =
4635                        format!("{marker}{qualifier}fn f(x: u32) -> u32 {{ {context} x * 2 }}");
4636                    let found = discover(&source, 0).unwrap();
4637                    let variants: Vec<_> = found
4638                        .rebuild_sites
4639                        .iter()
4640                        .filter(|site| site.text == "6 * 7")
4641                        .flat_map(source_mutants)
4642                        .map(|mutant| mutant.into)
4643                        .collect();
4644                    let expected: &[&str] = if marker.is_empty() { &["/", "+"] } else { &[] };
4645                    assert_eq!(variants, expected, "{place}: {source}");
4646                    assert!(
4647                        found.sites.iter().all(|site| site.text != "6 * 7"),
4648                        "{source}"
4649                    );
4650                    assert_eq!(
4651                        found.sites.iter().any(|site| site.text == "x * 2"),
4652                        marker.is_empty() && qualifier.is_empty(),
4653                        "{source}"
4654                    );
4655                }
4656            }
4657        }
4658    }
4659
4660    #[test]
4661    fn a_test_branch_or_skip_documentation_does_not_exclude_production_code() {
4662        let source = r#"
4663            /// The mutants::skip attribute is documented here.
4664            #[cfg(any(test, feature = "production"))]
4665            fn public(x: u32) -> u32 { x + 1 }
4666
4667            #[cfg(all(test, feature = "production"))]
4668            fn for_tests(x: u32) -> u32 { x + 2 }
4669
4670            #[cfg_attr(any(), mutants::skip)]
4671            fn skipped(x: u32) -> u32 { x + 3 }
4672        "#;
4673        let found = discover(source, 0).unwrap();
4674        let arithmetic: Vec<_> = found
4675            .sites
4676            .iter()
4677            .filter(|site| matches!(site.kind, SiteKind::Arith { .. }))
4678            .map(|site| site.text.as_str())
4679            .collect();
4680        assert_eq!(arithmetic, ["x + 1"]);
4681    }
4682
4683    #[test]
4684    fn constants_and_literal_arithmetic_are_mutated_in_the_source() {
4685        let src = "const HALF: u64 = SPAN / 2;\n\
4686                   static LIMIT: i32 = -(1 << 4);\n\
4687                   impl S { const K: bool = A < B; }\n\
4688                   trait T { const D: u8 = 3 + 4; const R: u8; }\n\
4689                   #[cfg(test)]\n\
4690                   const ONLY_IN_TESTS: u8 = 5 + 6;\n\
4691                   #[mutants::skip]\n\
4692                   const MARKED: u8 = 7 + 8;\n\
4693                   #[cfg(test)]\n\
4694                   static TEST_LIMIT: u8 = 9 + 1;\n\
4695                   impl S { #[mutants::skip] const SKIPPED: u8 = 9 + 2; }\n\
4696                   trait U { #[cfg(test)] const ONLY: u8 = 9 + 3; }\n\
4697                   fn f(x: u32) -> u32 { let _ = [0u8; 2 + 3]; x + 60 * 60 }\n\
4698                   fn one(s: &mut S) { s.go(); }\n\
4699                   fn two(s: &mut S) { s.go(); s.stop(); }\n\
4700                   fn value(s: &mut S) -> u8 { s.get() }\n";
4701        let found = discover(src, 0).unwrap();
4702        let built: Vec<String> = found
4703            .rebuild_sites
4704            .iter()
4705            .flat_map(|site| {
4706                source_mutants(site)
4707                    .into_iter()
4708                    .map(|m| format!("{}: {} -> {}", site.text, m.what, m.into))
4709            })
4710            .collect();
4711        assert_eq!(
4712            built,
4713            [
4714                "SPAN / 2: / -> *",
4715                "SPAN / 2: / -> %",
4716                "-(1 << 4): - -> ",
4717                "1 << 4: << -> >>",
4718                "A < B: < -> ==",
4719                "A < B: < -> >",
4720                "A < B: < -> <=",
4721                "3 + 4: + -> -",
4722                "3 + 4: + -> *",
4723                "2 + 3: + -> -",
4724                "2 + 3: + -> *",
4725                // Two literals in ordinary code too: a probe would give them a type.
4726                "60 * 60: * -> /",
4727                "60 * 60: * -> +",
4728            ]
4729        );
4730        mutated(src, &found.rebuild_sites);
4731        // The surrounding arithmetic is still probed.
4732        let probed: Vec<&str> = found
4733            .sites
4734            .iter()
4735            .filter(|s| matches!(s.kind, SiteKind::Arith { .. }))
4736            .map(|s| s.text.as_str())
4737            .collect();
4738        assert_eq!(probed, ["x + 60 * 60"]);
4739        // An empty body is not made where deleting the one statement is the same thing.
4740        assert_eq!(found.single_statement_bodies, ["one"]);
4741        let bodies: Vec<String> = found
4742            .sites
4743            .iter()
4744            .filter_map(|s| match &s.kind {
4745                SiteKind::Body { name, value, .. } => Some(format!("{name} {value}")),
4746                _ => None,
4747            })
4748            .collect();
4749        assert_eq!(bodies, ["f 0", "f 1", "two ()", "value 0", "value 1"]);
4750    }
4751    #[test]
4752    fn an_attribute_excludes_the_compile_time_expressions_of_what_it_is_on() {
4753        // `@` is where the attribute goes: without one the length is a mutant to build.
4754        for context in [
4755            "fn f() { @let _ = [0u8; 6 * 7]; }",
4756            "fn f() { let _ = @const { 6 * 7 }; }",
4757            "struct Items<@const N: usize = { 6 * 7 }>;",
4758            "@enum E { A = 6 * 7 }",
4759            "enum E { @A = 6 * 7 }",
4760            "enum E { @A([u8; 6 * 7]) }",
4761            "@struct S { a: [u8; 6 * 7] }",
4762            "struct S { @a: [u8; 6 * 7] }",
4763            "@union U { a: [u8; 6 * 7] }",
4764            "@trait T { const D: [u8; 6 * 7]; }",
4765            "trait T { @type A = [u8; 6 * 7]; }",
4766            "@type A = [u8; 6 * 7];",
4767            "impl T for S { @type A = [u8; 6 * 7]; }",
4768        ] {
4769            for attribute in ["", "#[mutants::skip] ", "#[cfg(test)] "] {
4770                let source = context.replace('@', attribute);
4771                let found = discover(&source, 0).unwrap();
4772                let expected: &[&str] = if attribute.is_empty() {
4773                    &["6 * 7"]
4774                } else {
4775                    &[]
4776                };
4777                assert_eq!(found_arith(&found.rebuild_sites), expected, "{source}");
4778                assert!(found_arith(&found.sites).is_empty(), "{source}");
4779            }
4780        }
4781        // On the file itself it excludes everything in it.
4782        for attribute in ["#![mutants::skip]", "#![cfg(test)]"] {
4783            let source =
4784                format!("{attribute}\nconst N: u8 = 6 * 7;\nfn f(a: u8) -> u8 {{ a + 1 }}");
4785            let found = discover(&source, 0).unwrap();
4786            assert!(found.sites.is_empty(), "{source}");
4787            assert!(found.rebuild_sites.is_empty(), "{source}");
4788        }
4789    }
4790
4791    #[test]
4792    fn compile_time_expressions_are_found_inside_types() {
4793        let built = |source: &str| -> Vec<String> {
4794            let found = discover(source, 0).unwrap();
4795            assert!(found_arith(&found.sites).is_empty(), "{source}");
4796            found_arith(&found.rebuild_sites)
4797                .into_iter()
4798                .map(str::to_string)
4799                .collect()
4800        };
4801        // The element of an array is a type with lengths of its own.
4802        assert_eq!(
4803            built("fn f() { let _: [[u8; 1 + 2]; 3 + 4]; }"),
4804            ["1 + 2", "3 + 4"]
4805        );
4806        // So is the type of a const parameter.
4807        assert_eq!(built("struct S<const N: [u8; 2 + 3]>;"), ["2 + 3"]);
4808        // A const argument is computed by the compiler whatever it consists of: it is
4809        // never probed.
4810        assert_eq!(built("fn f() { let _: Items<{ N + 1 }>; }"), ["N + 1"]);
4811    }
4812
4813    #[test]
4814    fn only_the_skip_mark_and_a_cfg_that_needs_test_exclude_code() {
4815        let src = "#[mutants] fn bare(a: u8) -> u8 { a + 1 }\n\
4816                   #[mutants::skip::deeper] fn longer(a: u8) -> u8 { a + 2 }\n\
4817                   #[cfg(all(test))] fn all_of_one(a: u8) -> u8 { a + 3 }\n\
4818                   #[cfg(not(not(test)))] fn twice_not(a: u8) -> u8 { a + 4 }\n\
4819                   #[cfg(not())] fn malformed(a: u8) -> u8 { a + 5 }\n\
4820                   #[labels(test)] fn labelled(a: u8) -> u8 { a + 6 }\n";
4821        let found = discover(src, 0).unwrap();
4822        assert_eq!(
4823            found_arith(&found.sites),
4824            ["a + 1", "a + 2", "a + 5", "a + 6"]
4825        );
4826    }
4827
4828    #[test]
4829    fn which_arms_are_probed_built_or_left_alone() {
4830        let src = "fn f(x: u8, k: Kind, c: bool, a: u8) -> u8 {\n\
4831                   \x20   let p = match x { 0 => 4, #[allow(unused)] 1 => 5, #[allow(unused)] 2 if c => 6, _ => 7 };\n\
4832                   \x20   let q = match k { Kind::A => 1, Kind::B => 2 };\n\
4833                   \x20   let r = match x { #[mutants::skip] 3 => a + 1, #[cfg(test)] 4 => a + 2, 5 => a + 3, _ => a + 4 };\n\
4834                   \x20   p + q + r\n\
4835                   }\n";
4836        let found = discover(src, 0).unwrap();
4837        let arms = |sites: &[Site]| -> Vec<String> {
4838            sites
4839                .iter()
4840                .filter(|site| matches!(site.kind, SiteKind::Arm { .. }))
4841                .map(|site| site.text.clone())
4842                .collect()
4843        };
4844        // Probed: an arm without attributes above a last arm that takes everything.
4845        assert_eq!(arms(&found.sites), ["0 => ..", "5 => .."]);
4846        // Built: an unguarded arm with an attribute, where a `_` arm keeps the match
4847        // exhaustive. Neither a guarded one, nor the `_` arm, nor an arm of a match
4848        // without `_`, nor one that is marked or only for tests.
4849        assert_eq!(arms(&found.rebuild_sites), ["1 => .."]);
4850        // What a marked or test-only arm does is not mutated either.
4851        let in_arms: Vec<&str> = found_arith(&found.sites)
4852            .into_iter()
4853            .filter(|text| text.starts_with("a + "))
4854            .collect();
4855        assert_eq!(in_arms, ["a + 3", "a + 4"]);
4856    }
4857
4858    #[test]
4859    fn which_fields_of_a_struct_update_are_probed_built_or_left_alone() {
4860        let src = "fn f(a: u8, base: S) {\n\
4861                   \x20   let _ = S { #[mutants::skip] v: a + 1, #[cfg(test)] w: a + 2, x: a + 3, ..base };\n\
4862                   \x20   g(#[mutants::skip] S { v: a + 4, ..base });\n\
4863                   \x20   g(#[cfg(test)] S { v: a + 5, ..base });\n\
4864                   \x20   g(#[allow(unused)] S { v: a + 6, ..base });\n\
4865                   \x20   g(<S as Tr>::Out { v: a + 7, ..base });\n\
4866                   }\n";
4867        let found = discover(src, 0).unwrap();
4868        let fields = |sites: &[Site]| -> Vec<String> {
4869            sites
4870                .iter()
4871                .filter_map(|site| match &site.kind {
4872                    SiteKind::Field { from_base, .. } => Some(format!(
4873                        "{} | {}",
4874                        site.text,
4875                        from_base.as_deref().unwrap_or("-")
4876                    )),
4877                    _ => None,
4878                })
4879                .collect()
4880        };
4881        // Probed: the field is read from the base instead.
4882        assert_eq!(fields(&found.sites), ["x: a + 3 | (base).x"]);
4883        // Built: an expression with an attribute or a qualified path is not written a
4884        // second time. Marked and test-only fields and expressions have no mutants.
4885        assert_eq!(
4886            fields(&found.rebuild_sites),
4887            ["v: a + 6 | -", "v: a + 7 | -"]
4888        );
4889        assert_eq!(found_arith(&found.sites), ["a + 3", "a + 6", "a + 7"]);
4890    }
4891
4892    #[test]
4893    fn body_values_that_are_only_built() {
4894        let bodies = |sites: &[Site]| -> Vec<String> {
4895            sites
4896                .iter()
4897                .filter_map(|site| match &site.kind {
4898                    SiteKind::Body { value, .. } => Some(value.clone()),
4899                    _ => None,
4900                })
4901                .collect()
4902        };
4903        // An unknown wrapper is probed with its default alone; its constructors are
4904        // guesses that have to compile, except the one the body already is.
4905        let found = discover("fn f() -> Wrapper<bool> { Wrapper::new() }", 0).unwrap();
4906        assert_eq!(bodies(&found.sites), ["Default::default()"]);
4907        assert_eq!(values("Wrapper<bool>"), ["Default::default()"]);
4908        assert_eq!(
4909            bodies(&found.rebuild_sites),
4910            [
4911                "Wrapper::from_iter([true])",
4912                "Wrapper::new(true)",
4913                "Wrapper::from(true)",
4914                "Wrapper::from_iter([false])",
4915                "Wrapper::new(false)",
4916                "Wrapper::from(false)",
4917            ]
4918        );
4919        // An opaque type anywhere in the return type leaves nothing to probe.
4920        assert!(values("(bool, impl Iterator<Item = u8>)").is_empty());
4921        // Iterators of iterators are built, and not offered to who asks for the
4922        // iterators to return.
4923        let nested = "impl Iterator<Item = impl Iterator<Item = u8>>";
4924        let found = discover(&format!("fn f() -> {nested} {{ todo!() }}"), 0).unwrap();
4925        assert!(bodies(&found.sites).is_empty());
4926        assert_eq!(
4927            bodies(&found.rebuild_sites),
4928            [
4929                "::core::iter::empty()",
4930                "::core::iter::once(::core::iter::empty())",
4931                "::core::iter::once(::core::iter::once(0))",
4932                "::core::iter::once(::core::iter::once(1))",
4933            ]
4934        );
4935        let function: syn::ItemFn =
4936            syn::parse_str(&format!("fn f() -> {nested} {{ todo!() }}")).unwrap();
4937        assert_eq!(
4938            iterator_values(&function.sig.output),
4939            ["::core::iter::empty()"]
4940        );
4941    }
4942}