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::{BTreeSet, 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/// What a `cfg` predicate is, as far as the features that are on decide it: `None` when
1575/// it depends on something else (the target, `test`, a `--cfg` of the build).
1576fn cfg_value(meta: &syn::Meta, features: &BTreeSet<String>) -> Option<bool> {
1577    match meta {
1578        syn::Meta::NameValue(pair) if pair.path.is_ident("feature") => match &pair.value {
1579            syn::Expr::Lit(syn::ExprLit {
1580                lit: syn::Lit::Str(name),
1581                ..
1582            }) => Some(features.contains(&name.value())),
1583            _ => None,
1584        },
1585        syn::Meta::List(list) => {
1586            let parts = list
1587                .parse_args_with(
1588                    syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated,
1589                )
1590                .ok()?;
1591            let mut values = parts.iter().map(|part| cfg_value(part, features));
1592            if list.path.is_ident("not") && parts.len() == 1 {
1593                values.next()?.map(|value| !value)
1594            } else if list.path.is_ident("all") {
1595                // One part that is off settles it; otherwise every part must be known.
1596                values
1597                    .try_fold(Some(true), |all, value| match (all, value) {
1598                        (_, Some(false)) => Err(()),
1599                        (Some(true), Some(true)) => Ok(Some(true)),
1600                        _ => Ok(None),
1601                    })
1602                    .unwrap_or(Some(false))
1603            } else if list.path.is_ident("any") {
1604                values
1605                    .try_fold(Some(false), |any, value| match (any, value) {
1606                        (_, Some(true)) => Err(()),
1607                        (Some(false), Some(false)) => Ok(Some(false)),
1608                        _ => Ok(None),
1609                    })
1610                    .unwrap_or(Some(true))
1611            } else {
1612                None
1613            }
1614        }
1615        _ => None,
1616    }
1617}
1618
1619fn cfg_is_off(attrs: &[syn::Attribute], features: &BTreeSet<String>) -> bool {
1620    attrs.iter().any(|attr| {
1621        attr.path().is_ident("cfg")
1622            && attr
1623                .parse_args::<syn::Meta>()
1624                .is_ok_and(|meta| cfg_value(&meta, features) == Some(false))
1625    })
1626}
1627
1628/// Byte ranges of the code that the features that are on leave out of the build: what is
1629/// under a `cfg` that is off whatever the target is. Its mutants would change nothing.
1630pub(crate) fn inactive_ranges(
1631    source: &str,
1632    file: &syn::File,
1633    features: &BTreeSet<String>,
1634) -> Vec<(usize, usize)> {
1635    struct Inactive<'a> {
1636        source: &'a str,
1637        features: &'a BTreeSet<String>,
1638        found: Vec<(usize, usize)>,
1639    }
1640    impl Inactive<'_> {
1641        /// Whether the node is left out; then its range is noted and it is not entered.
1642        fn off(&mut self, attrs: &[syn::Attribute], span: Span) -> bool {
1643            if !cfg_is_off(attrs, self.features) {
1644                return false;
1645            }
1646            let range = span.byte_range();
1647            if self.source.get(range.clone()).is_some() {
1648                self.found.push((range.start, range.end));
1649            }
1650            true
1651        }
1652    }
1653    macro_rules! nodes {
1654        ($($visit:ident, $default:path, $node:ty;)*) => {
1655            impl<'ast> Visit<'ast> for Inactive<'_> {
1656                $(fn $visit(&mut self, node: &'ast $node) {
1657                    if !self.off(&node.attrs, node.span()) {
1658                        $default(self, node);
1659                    }
1660                })*
1661                fn visit_item(&mut self, node: &'ast syn::Item) {
1662                    if !self.off(item_attrs(node), node.span()) {
1663                        visit::visit_item(self, node);
1664                    }
1665                }
1666                fn visit_impl_item(&mut self, node: &'ast syn::ImplItem) {
1667                    let attrs = match node {
1668                        syn::ImplItem::Const(item) => &item.attrs[..],
1669                        syn::ImplItem::Fn(item) => &item.attrs,
1670                        syn::ImplItem::Type(item) => &item.attrs,
1671                        syn::ImplItem::Macro(item) => &item.attrs,
1672                        _ => &[],
1673                    };
1674                    if !self.off(attrs, node.span()) {
1675                        visit::visit_impl_item(self, node);
1676                    }
1677                }
1678                fn visit_trait_item(&mut self, node: &'ast syn::TraitItem) {
1679                    let attrs = match node {
1680                        syn::TraitItem::Const(item) => &item.attrs[..],
1681                        syn::TraitItem::Fn(item) => &item.attrs,
1682                        syn::TraitItem::Type(item) => &item.attrs,
1683                        syn::TraitItem::Macro(item) => &item.attrs,
1684                        _ => &[],
1685                    };
1686                    if !self.off(attrs, node.span()) {
1687                        visit::visit_trait_item(self, node);
1688                    }
1689                }
1690            }
1691        };
1692    }
1693    nodes! {
1694        visit_local, visit::visit_local, syn::Local;
1695        visit_arm, visit::visit_arm, syn::Arm;
1696        visit_field_value, visit::visit_field_value, syn::FieldValue;
1697        visit_stmt_macro, visit::visit_stmt_macro, syn::StmtMacro;
1698        visit_expr_block, visit::visit_expr_block, syn::ExprBlock;
1699        visit_expr_if, visit::visit_expr_if, syn::ExprIf;
1700        visit_expr_call, visit::visit_expr_call, syn::ExprCall;
1701        visit_expr_method_call, visit::visit_expr_method_call, syn::ExprMethodCall;
1702        visit_expr_macro, visit::visit_expr_macro, syn::ExprMacro;
1703        visit_expr_match, visit::visit_expr_match, syn::ExprMatch;
1704        visit_expr_assign, visit::visit_expr_assign, syn::ExprAssign;
1705        visit_expr_return, visit::visit_expr_return, syn::ExprReturn;
1706        visit_expr_for_loop, visit::visit_expr_for_loop, syn::ExprForLoop;
1707        visit_expr_while, visit::visit_expr_while, syn::ExprWhile;
1708        visit_expr_loop, visit::visit_expr_loop, syn::ExprLoop;
1709        visit_expr_unsafe, visit::visit_expr_unsafe, syn::ExprUnsafe;
1710        visit_expr_binary, visit::visit_expr_binary, syn::ExprBinary;
1711    }
1712    if cfg_is_off(&file.attrs, features) {
1713        return vec![(0, source.len())];
1714    }
1715    let mut inactive = Inactive {
1716        source,
1717        features,
1718        found: vec![],
1719    };
1720    inactive.visit_file(file);
1721    inactive.found
1722}
1723
1724fn item_attrs(item: &syn::Item) -> &[syn::Attribute] {
1725    match item {
1726        syn::Item::Const(item) => &item.attrs,
1727        syn::Item::Enum(item) => &item.attrs,
1728        syn::Item::ExternCrate(item) => &item.attrs,
1729        syn::Item::Fn(item) => &item.attrs,
1730        syn::Item::ForeignMod(item) => &item.attrs,
1731        syn::Item::Impl(item) => &item.attrs,
1732        syn::Item::Macro(item) => &item.attrs,
1733        syn::Item::Mod(item) => &item.attrs,
1734        syn::Item::Static(item) => &item.attrs,
1735        syn::Item::Struct(item) => &item.attrs,
1736        syn::Item::Trait(item) => &item.attrs,
1737        syn::Item::TraitAlias(item) => &item.attrs,
1738        syn::Item::Type(item) => &item.attrs,
1739        syn::Item::Union(item) => &item.attrs,
1740        syn::Item::Use(item) => &item.attrs,
1741        _ => &[],
1742    }
1743}
1744
1745/// Detect test attributes and cfg predicates that require `test` to be true.
1746pub(crate) fn is_test_only(attrs: &[syn::Attribute]) -> bool {
1747    attrs.iter().any(|attr| {
1748        let path = attr.path();
1749        if path.segments.last().is_some_and(|s| s.ident == "test") {
1750            return true;
1751        }
1752        path.is_ident("cfg")
1753            && attr
1754                .parse_args::<syn::Meta>()
1755                .is_ok_and(|meta| !cfg_possible_without_test(&meta, true))
1756    })
1757}
1758
1759impl<'ast> Visit<'ast> for Finder<'_> {
1760    fn visit_attribute(&mut self, _: &'ast syn::Attribute) {}
1761    fn visit_local(&mut self, node: &'ast syn::Local) {
1762        if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1763            visit::visit_local(self, node);
1764        }
1765    }
1766    fn visit_pat(&mut self, node: &'ast syn::Pat) {
1767        if let syn::Pat::Type(binding) = node {
1768            self.visit_type(&binding.ty);
1769        }
1770    }
1771    fn visit_type_macro(&mut self, _: &'ast syn::TypeMacro) {}
1772    fn visit_type_array(&mut self, node: &'ast syn::TypeArray) {
1773        self.visit_type(&node.elem);
1774        self.constant(&[], &node.len);
1775    }
1776    fn visit_const_param(&mut self, node: &'ast syn::ConstParam) {
1777        self.visit_type(&node.ty);
1778        if let Some(default) = &node.default {
1779            self.constant(&node.attrs, default);
1780        }
1781    }
1782    fn visit_generic_argument(&mut self, node: &'ast syn::GenericArgument) {
1783        match node {
1784            syn::GenericArgument::Const(value) => self.constant(&[], value),
1785            _ => visit::visit_generic_argument(self, node),
1786        }
1787    }
1788    fn visit_variant(&mut self, node: &'ast syn::Variant) {
1789        if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1790            self.visit_fields(&node.fields);
1791            if let Some((_, value)) = &node.discriminant {
1792                self.constant(&[], value);
1793            }
1794        }
1795    }
1796    fn visit_file(&mut self, node: &'ast syn::File) {
1797        if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1798            visit::visit_file(self, node);
1799        }
1800    }
1801    fn visit_item_enum(&mut self, node: &'ast syn::ItemEnum) {
1802        if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1803            visit::visit_item_enum(self, node);
1804        }
1805    }
1806    fn visit_item_struct(&mut self, node: &'ast syn::ItemStruct) {
1807        if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1808            visit::visit_item_struct(self, node);
1809        }
1810    }
1811    fn visit_item_union(&mut self, node: &'ast syn::ItemUnion) {
1812        if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1813            visit::visit_item_union(self, node);
1814        }
1815    }
1816    fn visit_item_trait(&mut self, node: &'ast syn::ItemTrait) {
1817        if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1818            visit::visit_item_trait(self, node);
1819        }
1820    }
1821    fn visit_item_type(&mut self, node: &'ast syn::ItemType) {
1822        if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1823            visit::visit_item_type(self, node);
1824        }
1825    }
1826    fn visit_field(&mut self, node: &'ast syn::Field) {
1827        if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1828            visit::visit_field(self, node);
1829        }
1830    }
1831    fn visit_impl_item_type(&mut self, node: &'ast syn::ImplItemType) {
1832        if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1833            visit::visit_impl_item_type(self, node);
1834        }
1835    }
1836    fn visit_trait_item_type(&mut self, node: &'ast syn::TraitItemType) {
1837        if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1838            visit::visit_trait_item_type(self, node);
1839        }
1840    }
1841    fn visit_item_const(&mut self, node: &'ast syn::ItemConst) {
1842        self.typed_constant(&node.attrs, &node.ty, Some(&node.expr));
1843    }
1844    fn visit_item_static(&mut self, node: &'ast syn::ItemStatic) {
1845        self.typed_constant(&node.attrs, &node.ty, Some(&node.expr));
1846    }
1847    fn visit_impl_item_const(&mut self, node: &'ast syn::ImplItemConst) {
1848        self.typed_constant(&node.attrs, &node.ty, Some(&node.expr));
1849    }
1850    fn visit_trait_item_const(&mut self, node: &'ast syn::TraitItemConst) {
1851        self.typed_constant(
1852            &node.attrs,
1853            &node.ty,
1854            node.default.as_ref().map(|(_, value)| value),
1855        );
1856    }
1857    fn visit_expr_const(&mut self, node: &'ast syn::ExprConst) {
1858        if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1859            self.const_depth += 1;
1860            self.visit_block(&node.block);
1861            self.const_depth -= 1;
1862        }
1863    }
1864
1865    fn visit_macro(&mut self, node: &'ast syn::Macro) {
1866        let Some(name) = node.path.segments.last().map(|s| s.ident.to_string()) else {
1867            return;
1868        };
1869        if !EXPR_MACROS.contains(&name.as_str()) || self.local_macros.contains(&name) {
1870            return;
1871        }
1872        if name == "matches" {
1873            // matches!(expr, pattern): only the scrutinee is an expression.
1874            let scrutinee = node.parse_body_with(|input: syn::parse::ParseStream| {
1875                let expr: syn::Expr = input.parse()?;
1876                input.parse::<proc_macro2::TokenStream>()?;
1877                Ok(expr)
1878            });
1879            if let Ok(expr) = scrutinee {
1880                self.visit_expr(&expr);
1881            }
1882            return;
1883        }
1884        type Args = syn::punctuated::Punctuated<syn::Expr, syn::Token![,]>;
1885        // `vec![x; n]`, named format arguments with odd syntax and the like do not parse
1886        // as a plain argument list: skipped.
1887        if let Ok(args) = node.parse_body_with(Args::parse_terminated) {
1888            for arg in &args {
1889                // `name = value` in a format string parses as an assignment; nothing
1890                // treats it as one here, and only its value holds sites.
1891                self.visit_expr(arg);
1892            }
1893        }
1894    }
1895
1896    fn visit_expr_repeat(&mut self, node: &'ast syn::ExprRepeat) {
1897        self.visit_expr(&node.expr);
1898        self.constant(&node.attrs, &node.len);
1899    }
1900
1901    fn visit_item_mod(&mut self, node: &'ast syn::ItemMod) {
1902        // The file of a module that is not analysed is left alone as a whole.
1903        if is_test_only(&node.attrs) || is_skipped(&node.attrs) {
1904            if node.content.is_none() {
1905                let path = node.attrs.iter().find_map(|attr| match &attr.meta {
1906                    syn::Meta::NameValue(nv) if nv.path.is_ident("path") => match &nv.value {
1907                        syn::Expr::Lit(syn::ExprLit {
1908                            lit: syn::Lit::Str(s),
1909                            ..
1910                        }) => Some(s.value()),
1911                        _ => None,
1912                    },
1913                    _ => None,
1914                });
1915                self.found.test_modules.push(TestModule {
1916                    name: node.ident.to_string(),
1917                    path,
1918                });
1919            }
1920            return;
1921        }
1922        visit::visit_item_mod(self, node);
1923    }
1924
1925    fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
1926        if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1927            // Nothing in a `const fn` can ask at run time which mutant is on.
1928            let constant = node.sig.constness.is_some() as usize;
1929            self.const_depth += constant;
1930            self.function_sites(&node.sig, &node.block);
1931            visit::visit_item_fn(self, node);
1932            self.const_depth -= constant;
1933        }
1934    }
1935
1936    fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
1937        if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1938            // Nothing in a `const fn` can ask at run time which mutant is on.
1939            let constant = node.sig.constness.is_some() as usize;
1940            self.const_depth += constant;
1941            self.function_sites(&node.sig, &node.block);
1942            visit::visit_impl_item_fn(self, node);
1943            self.const_depth -= constant;
1944        }
1945    }
1946
1947    fn visit_trait_item_fn(&mut self, node: &'ast syn::TraitItemFn) {
1948        if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1949            let constant = node.sig.constness.is_some() as usize;
1950            self.const_depth += constant;
1951            if let Some(body) = &node.default {
1952                self.function_sites(&node.sig, body);
1953            }
1954            visit::visit_trait_item_fn(self, node);
1955            self.const_depth -= constant;
1956        }
1957    }
1958
1959    fn visit_item_impl(&mut self, node: &'ast syn::ItemImpl) {
1960        if !is_test_only(&node.attrs) && !is_skipped(&node.attrs) {
1961            visit::visit_item_impl(self, node);
1962        }
1963    }
1964
1965    fn visit_expr_closure(&mut self, node: &'ast syn::ExprClosure) {
1966        if node.constness.is_none() {
1967            visit::visit_expr_closure(self, node);
1968        }
1969    }
1970
1971    fn visit_block(&mut self, node: &'ast syn::Block) {
1972        for stmt in &node.stmts {
1973            if let syn::Stmt::Expr(expr, Some(semi)) = stmt
1974                && deletable(expr)
1975                && let (Some((start, _)), Some((_, end))) =
1976                    (self.range(expr.span()), self.range(semi.span()))
1977                && in_order(start, end)
1978            {
1979                self.push(SiteKind::Stmt, start, end, expr.span());
1980            }
1981        }
1982        visit::visit_block(self, node);
1983    }
1984
1985    fn visit_expr_method_call(&mut self, node: &'ast syn::ExprMethodCall) {
1986        let name = node.method.to_string();
1987        if (name == "max" || name == "min")
1988            && node.args.len() == 1
1989            && node.turbofish.is_none()
1990            && node.attrs.is_empty()
1991            && let (
1992                Some((start, receiver_end)),
1993                Some((argument_start, argument_end)),
1994                Some((_, end)),
1995            ) = (
1996                self.range(node.receiver.span()),
1997                self.range(node.args[0].span()),
1998                self.range(node.paren_token.span.close()),
1999            )
2000            && in_order(receiver_end, argument_start)
2001            && in_order(argument_end, end)
2002        {
2003            let kind = SiteKind::MinMax {
2004                max: name == "max",
2005                receiver: self.source[start..receiver_end].to_string(),
2006                argument: self.source[argument_start..argument_end].to_string(),
2007                call: (receiver_end, argument_start),
2008                close: (argument_end, end),
2009            };
2010            self.push(kind, start, end, node.receiver.span());
2011        }
2012        visit::visit_expr_method_call(self, node);
2013    }
2014
2015    fn visit_expr_for_loop(&mut self, node: &'ast syn::ExprForLoop) {
2016        let mut over = &*node.expr;
2017        while let syn::Expr::Paren(syn::ExprParen { expr, .. })
2018        | syn::Expr::Group(syn::ExprGroup { expr, .. }) = over
2019        {
2020            over = expr;
2021        }
2022        if let syn::Expr::Range(syn::ExprRange {
2023            start: Some(from), ..
2024        }) = over
2025            && let Some((start, _)) = self.range(from.span())
2026        {
2027            self.for_ranges.insert(start);
2028        }
2029        visit::visit_expr_for_loop(self, node);
2030    }
2031
2032    fn visit_expr_range(&mut self, node: &'ast syn::ExprRange) {
2033        // With two literals nothing fixes the integer type before the probe is resolved,
2034        // and it would be taken for `i32` (`for i in 0..16 { words[i] }`).
2035        if let (Some(from), Some(to)) = (&node.start, &node.end)
2036            && node.attrs.is_empty()
2037            && let (Some((start, lhs_end)), Some((rhs_start, end))) =
2038                (self.range(from.span()), self.range(to.span()))
2039            && in_order(lhs_end, rhs_start)
2040        {
2041            let kind = SiteKind::Range {
2042                inclusive: matches!(node.limits, syn::RangeLimits::Closed(_)),
2043                lhs: self.source[start..lhs_end].to_string(),
2044                rhs: self.source[rhs_start..end].to_string(),
2045                gap: (lhs_end, rhs_start),
2046            };
2047            // `a..b + 1` in place of `a..=b` gives a `for` the same numbers, and that is
2048            // all a `for` takes from its range. Anywhere else the two are told apart (by
2049            // their type, by `end_bound`, by a field): there the mutant is the range as it
2050            // is written in the source, and it is built like the code of a `const fn`.
2051            // So is a range of two literals, wherever it is: nothing fixes their type
2052            // before a probe is resolved, and it would be taken for `i32`.
2053            let built = !self.for_ranges.contains(&start) || (is_literal(from) && is_literal(to));
2054            self.const_depth += built as usize;
2055            self.push(kind, start, end, from.span());
2056            self.const_depth -= built as usize;
2057        }
2058        visit::visit_expr_range(self, node);
2059    }
2060
2061    fn visit_expr_match(&mut self, node: &'ast syn::ExprMatch) {
2062        // A binding or `_` takes everything: with such a last arm the match stays
2063        // exhaustive when an arm above it stops matching.
2064        let catches_all = |arm: &syn::Arm| {
2065            arm.guard.is_none()
2066                && match &arm.pat {
2067                    syn::Pat::Wild(_) => true,
2068                    syn::Pat::Ident(p) => {
2069                        p.subpat.is_none()
2070                            && p.ident
2071                                .to_string()
2072                                .starts_with(|c: char| c.is_lowercase() || c == '_')
2073                    }
2074                    _ => false,
2075                }
2076        };
2077        let mut removable = vec![];
2078        let has_wildcard = node
2079            .arms
2080            .iter()
2081            .any(|arm| matches!(arm.pat, syn::Pat::Wild(_)));
2082        let final_catches_all = node.arms.last().is_some_and(catches_all);
2083        for arm in &node.arms {
2084            if is_test_only(&arm.attrs) || is_skipped(&arm.attrs) {
2085                continue;
2086            }
2087            // The last arm is not probed: where it takes everything, it is a catch-all.
2088            let probe = final_catches_all && arm.attrs.is_empty() && !catches_all(arm);
2089            let literal =
2090                has_wildcard && !matches!(arm.pat, syn::Pat::Wild(_)) && arm.guard.is_none();
2091            if !probe && !literal {
2092                continue;
2093            }
2094            let (Some((start, pat_end)), Some((remove_start, remove_end)), Some((arrow, _))) = (
2095                self.range(arm.pat.span()),
2096                self.range(arm.span()),
2097                self.range(arm.fat_arrow_token.span()),
2098            ) else {
2099                continue;
2100            };
2101            let guard = match &arm.guard {
2102                None => ArmGuard::None(arrow),
2103                Some((_, expr)) => match self.range(expr.span()) {
2104                    Some((from, to)) => ArmGuard::Existing(from, to),
2105                    None => continue,
2106                },
2107            };
2108            let pattern = match guard {
2109                ArmGuard::Existing(from, to) => format!(
2110                    "{} if {}",
2111                    &self.source[start..pat_end],
2112                    &self.source[from..to]
2113                ),
2114                ArmGuard::None(_) => self.source[start..pat_end].to_string(),
2115            };
2116            let end = arm
2117                .comma
2118                .as_ref()
2119                .and_then(|comma| self.range(comma.span()))
2120                .map_or(remove_end, |(_, end)| end);
2121            let at = arm.pat.span().start();
2122            removable.push(start);
2123            let site = Site {
2124                id: 0,
2125                kind: SiteKind::Arm {
2126                    pattern: pattern.clone(),
2127                    guard,
2128                    removal: (remove_start, end),
2129                },
2130                line: at.line,
2131                column: at.column + 1,
2132                start,
2133                end,
2134                text: format!("{pattern} => .."),
2135            };
2136            if probe {
2137                self.add(site);
2138            } else {
2139                self.add_rebuild(site);
2140            }
2141        }
2142        // Any guard can be `true` or `false` instead: a guarded arm never counts for
2143        // the match being exhaustive. A `let` in a guard binds names for the arm.
2144        for arm in node.arms.iter().filter(|arm| arm.attrs.is_empty()) {
2145            if let Some((_, guard)) = &arm.guard
2146                && !matches!(**guard, syn::Expr::Let(_))
2147                && !in_let_chain(guard)
2148                && let (Some((start, end)), Some((pattern, _))) =
2149                    (self.range(guard.span()), self.range(arm.pat.span()))
2150            {
2151                let kind = SiteKind::Guard {
2152                    can_be_false: !removable.contains(&pattern),
2153                };
2154                self.push(kind, start, end, guard.span());
2155            }
2156        }
2157        visit::visit_expr_match(self, node);
2158    }
2159
2160    fn visit_arm(&mut self, arm: &'ast syn::Arm) {
2161        if !is_test_only(&arm.attrs) && !is_skipped(&arm.attrs) {
2162            visit::visit_arm(self, arm);
2163        }
2164    }
2165
2166    fn visit_field_value(&mut self, field: &'ast syn::FieldValue) {
2167        if !is_test_only(&field.attrs) && !is_skipped(&field.attrs) {
2168            visit::visit_field_value(self, field);
2169        }
2170    }
2171
2172    fn visit_expr_struct(&mut self, node: &'ast syn::ExprStruct) {
2173        if is_test_only(&node.attrs) || is_skipped(&node.attrs) {
2174            return;
2175        }
2176        // Only probes read the base again. Source mutants delete a field in place.
2177        let from_base = node.rest.as_deref().and_then(|base| {
2178            if !node.attrs.is_empty() || node.qself.is_some() {
2179                return None;
2180            }
2181            let (from, to) = self.range(base.span())?;
2182            let written = &self.source[from..to];
2183            match base {
2184                base if is_plain_place(base) => Some(format!("({written})")),
2185                syn::Expr::Call(call)
2186                    if call.args.is_empty() && matches!(*call.func, syn::Expr::Path(_)) =>
2187                {
2188                    let (from, to) = self.range(node.path.span())?;
2189                    Some(format!("({} {{ ..{written} }})", &self.source[from..to]))
2190                }
2191                _ => None,
2192            }
2193        });
2194        if node.rest.is_some() {
2195            for pair in node.fields.pairs() {
2196                let field = pair.value();
2197                if is_test_only(&field.attrs) || is_skipped(&field.attrs) {
2198                    continue;
2199                }
2200                let name = match &field.member {
2201                    syn::Member::Named(name) => name.to_string(),
2202                    syn::Member::Unnamed(index) => index.index.to_string(),
2203                };
2204                let (Some((start, _)), Some((value, end)), Some((remove_start, _))) = (
2205                    self.range(field.member.span()),
2206                    self.range(field.expr.span()),
2207                    self.range(field.span()),
2208                ) else {
2209                    continue;
2210                };
2211                let remove_end = pair
2212                    .punct()
2213                    .and_then(|comma| self.range(comma.span()))
2214                    .map_or(end, |(_, end)| end);
2215                let from_base = from_base
2216                    .as_ref()
2217                    .filter(|_| field.attrs.is_empty())
2218                    .map(|base| format!("{base}.{name}"));
2219                let probe = from_base.is_some();
2220                let kind = SiteKind::Field {
2221                    from_base,
2222                    name,
2223                    shorthand: field.colon_token.is_none(),
2224                    removal: (remove_start, remove_end),
2225                };
2226                let at = field.member.span().start();
2227                let site = Site {
2228                    id: 0,
2229                    kind,
2230                    line: at.line,
2231                    column: at.column + 1,
2232                    start: if probe { value } else { remove_start },
2233                    end,
2234                    text: self.source[start..end].to_string(),
2235                };
2236                if probe {
2237                    self.add(site);
2238                } else {
2239                    self.add_rebuild(site);
2240                }
2241            }
2242        }
2243        visit::visit_expr_struct(self, node);
2244    }
2245
2246    fn visit_expr_unary(&mut self, node: &'ast syn::ExprUnary) {
2247        if let syn::UnOp::Not(bang) = &node.op
2248            && node.attrs.is_empty()
2249            && let (Some((start, _)), Some((operand_start, end))) =
2250                (self.range(bang.span()), self.range(node.expr.span()))
2251            && in_order(start, operand_start)
2252        {
2253            let kind = SiteKind::Not {
2254                bang: (start, operand_start),
2255                operand: self.source[operand_start..end].to_string(),
2256            };
2257            self.push(kind, start, end, bang.span());
2258        }
2259        if let syn::UnOp::Neg(minus) = &node.op
2260            && node.attrs.is_empty()
2261            && let (Some((start, _)), Some((operand_start, end))) =
2262                (self.range(minus.span()), self.range(node.expr.span()))
2263            && in_order(start, operand_start)
2264        {
2265            let zero = match &*node.expr {
2266                syn::Expr::Lit(syn::ExprLit {
2267                    lit: syn::Lit::Int(lit),
2268                    ..
2269                }) => lit.base10_parse::<u128>().is_ok_and(|v| v == 0),
2270                // Not a float: `-0.0` is not `0.0` (`1.0 / -0.0` is minus infinity).
2271                _ => false,
2272            };
2273            if !zero {
2274                let kind = SiteKind::Neg {
2275                    minus: (start, operand_start),
2276                    operand: self.source[operand_start..end].to_string(),
2277                    literal: matches!(*node.expr, syn::Expr::Lit(_)),
2278                };
2279                self.push(kind, start, end, minus.span());
2280            }
2281        }
2282        visit::visit_expr_unary(self, node);
2283    }
2284
2285    fn visit_expr_binary(&mut self, node: &'ast syn::ExprBinary) {
2286        if let Some(op) = cmp_op(&node.op)
2287            && node.attrs.is_empty()
2288            && let (Some((start, lhs_end)), Some((rhs_start, end))) =
2289                (self.range(node.left.span()), self.range(node.right.span()))
2290            && in_order(lhs_end, rhs_start)
2291        {
2292            let literal = match (int_literal(&node.left), int_literal(&node.right)) {
2293                (None, Some(k)) => LiteralSide::Rhs(k),
2294                (Some(k), None) => LiteralSide::Lhs(k),
2295                _ => LiteralSide::None,
2296            };
2297            let kind = SiteKind::Cmp {
2298                op,
2299                lhs: self.source[start..lhs_end].to_string(),
2300                rhs: self.source[rhs_start..end].to_string(),
2301                literal,
2302                gap: (lhs_end, rhs_start),
2303            };
2304            self.push(kind, start, end, node.left.span());
2305        } else if node.attrs.is_empty()
2306            && let (Some((start, lhs_end)), Some((rhs_start, end))) =
2307                (self.range(node.left.span()), self.range(node.right.span()))
2308            && in_order(lhs_end, rhs_start)
2309        {
2310            let lhs = self.source[start..lhs_end].to_string();
2311            let rhs = self.source[rhs_start..end].to_string();
2312            let gap = (lhs_end, rhs_start);
2313            let logic = match &node.op {
2314                syn::BinOp::And(_) => Some(true),
2315                syn::BinOp::Or(_) => Some(false),
2316                _ => None,
2317            };
2318            if let Some(and) = logic {
2319                if !in_let_chain(&node.left) && !matches!(*node.right, syn::Expr::Let(_)) {
2320                    self.push(
2321                        SiteKind::Logic { and, lhs, rhs, gap },
2322                        start,
2323                        end,
2324                        node.left.span(),
2325                    );
2326                }
2327            } else if let Some((op, assign)) = arith_op(&node.op) {
2328                let kind = SiteKind::Arith {
2329                    op,
2330                    assign,
2331                    lhs,
2332                    rhs,
2333                    gap,
2334                };
2335                // Two literals have no type until the context gives them one, and a
2336                // probe is a context of its own.
2337                let literals = is_literal(&node.left) && is_literal(&node.right);
2338                if !literals && (!assign || is_plain_place(&node.left)) {
2339                    self.push(kind, start, end, node.left.span());
2340                } else {
2341                    // Which of the place and the value is evaluated first depends on
2342                    // the type, which a probe would have to know.
2343                    let at = node.left.span().start();
2344                    self.found.rebuild_sites.push(Site {
2345                        id: NO_ID,
2346                        kind,
2347                        line: at.line,
2348                        column: at.column + 1,
2349                        start,
2350                        end,
2351                        text: self.source[start..end].to_string(),
2352                    });
2353                }
2354            }
2355        }
2356        visit::visit_expr_binary(self, node);
2357    }
2358}
2359
2360/// Instrumented text plus the mapping back to the original, used to blame a site for a
2361/// compile error in the rewritten file.
2362#[derive(Debug, PartialEq)]
2363pub struct Rendered {
2364    pub text: String,
2365    /// `(output offset, original offset, length)` of each stretch copied from the original,
2366    /// in output order.
2367    segments: Vec<(usize, usize, usize)>,
2368    /// `(output offset, length, site)` of each piece of text a probe added, in output order.
2369    inserted: Vec<(usize, usize, u32)>,
2370}
2371
2372impl Rendered {
2373    /// Maps a byte offset in the instrumented text to the original. Offsets inside inserted
2374    /// text map to the point of insertion.
2375    /// The site whose probe text contains the byte at `offset` of the instrumented text.
2376    pub fn inserted_by(&self, offset: usize) -> Option<u32> {
2377        let idx = self.inserted.partition_point(|(out, _, _)| *out <= offset);
2378        let (out, len, site) = self.inserted[idx.checked_sub(1)?];
2379        (offset - out < len).then_some(site)
2380    }
2381
2382    pub fn to_original(&self, offset: usize) -> usize {
2383        let idx = self.segments.partition_point(|(out, _, _)| *out <= offset);
2384        let Some((out, orig, len)) = idx.checked_sub(1).map(|i| self.segments[i]) else {
2385            return 0;
2386        };
2387        // Past the end of the copied stretch is inserted text, which sits at its end.
2388        orig + (offset - out).min(len)
2389    }
2390}
2391
2392struct Edit {
2393    pos: usize,
2394    end: usize,
2395    /// 0: closes a site, 1: replaces an operator, 2: opens a site.
2396    phase: u8,
2397    /// Closers: innermost first. Openers: outermost first.
2398    order: i64,
2399    text: String,
2400    /// The site the text belongs to.
2401    site: u32,
2402}
2403
2404/// Rewrites `source` with probes for the sites that `enabled` accepts.
2405pub fn render(source: &str, sites: &[Site], enabled: &dyn Fn(u32) -> bool) -> Rendered {
2406    let rt = format!("crate::{RUNTIME_MOD}");
2407    let mut edits = vec![];
2408    for site in sites.iter().filter(|s| enabled(s.id)) {
2409        // Edits at one position are ordered by the length of their site, doubled to leave
2410        // room: a site that wraps a whole expression goes around a site of that very
2411        // expression (`if a > b` as a guard and as a comparison).
2412        let wraps = matches!(
2413            site.kind,
2414            SiteKind::Return { .. }
2415                | SiteKind::Body { .. }
2416                | SiteKind::Guard { .. }
2417                | SiteKind::Field { .. }
2418        );
2419        // tmt:ignore `2 +` orders the same: nothing longer starts or ends where a wrapping site does
2420        let len = 2 * (site.end - site.start) as i64 + wraps as i64;
2421        let (open, close) = match &site.kind {
2422            SiteKind::Cmp { op, gap, .. } => {
2423                let func = if op.is_ordering() { "ord" } else { "eq" };
2424                edits.push(Edit {
2425                    pos: gap.0,
2426                    end: gap.1,
2427                    phase: 1,
2428                    order: 0,
2429                    text: "), &(".into(),
2430                    site: site.id,
2431                });
2432                (
2433                    "(match (&(".to_string(),
2434                    format!(
2435                        ")) {{ (__tmt_l, __tmt_r) => {{ #[allow(unused_imports)] use {rt}::{{ValAny as _, ValNum as _}}; \
2436                         {rt}::{func}({id}u32, {code}u8, __tmt_l, __tmt_r, (&{rt}::W(__tmt_l)).tmt_val(), (&{rt}::W(__tmt_r)).tmt_val()) }} }})",
2437                        id = site.id,
2438                        code = op.code(),
2439                    ),
2440                )
2441            }
2442            // In the probes below the user's operands are evaluated where no name the probe
2443            // introduces is in scope: in the scrutinee of a `match`, in the initialiser of a
2444            // `let`, or in an arm that binds nothing. A scrutinee keeps its temporaries
2445            // until the end of the enclosing statement, as an arithmetic operator does.
2446            SiteKind::Logic { and, gap, .. } => {
2447                // The right operand stays in place, so it is evaluated exactly when the
2448                // (possibly mutated) left operand asks for it.
2449                let id = site.id;
2450                edits.push(Edit {
2451                    pos: gap.0,
2452                    end: gap.1,
2453                    phase: 1,
2454                    order: 0,
2455                    text: format!("); __tmt_c }} {{ 2u8 => {rt}::rhs({id}u32, {and}, "),
2456                    site: site.id,
2457                });
2458                (
2459                    // Each operand of `&&` / `||` drops its temporaries when it is done.
2460                    // The `let` ends the left operand's; the arm ends the right one's.
2461                    format!("(match {{ let __tmt_c: u8 = {rt}::lhs({id}u32, {and}, "),
2462                    "), __tmt_c => __tmt_c == 1u8 })".to_string(),
2463                )
2464            }
2465            SiteKind::Arith {
2466                op, assign, gap, ..
2467            } => {
2468                // A compound assignment hands the probe the place to update.
2469                let (holder, lhs_open, lhs_close) = if *assign {
2470                    ("Aa", "&mut (", ")")
2471                } else {
2472                    ("Ar", "", "")
2473                };
2474                edits.push(Edit {
2475                    pos: gap.0,
2476                    end: gap.1,
2477                    phase: 1,
2478                    order: 0,
2479                    text: format!("{lhs_close}, "),
2480                    site: site.id,
2481                });
2482                (
2483                    format!("(match ({lhs_open}"),
2484                    format!(
2485                        ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{{any} as _, {prim} as _}}; \
2486                         (&{rt}::{holder}::new(__tmt_a, __tmt_b)).{method}({id}u32) }} }})",
2487                        any = op.fallback_trait(*assign),
2488                        prim = op.prim_trait(*assign),
2489                        method = op.method(*assign),
2490                        id = site.id,
2491                    ),
2492                )
2493            }
2494            SiteKind::Not { bang, .. } => {
2495                // Drop the `!`; the probe applies it (or not).
2496                edits.push(Edit {
2497                    pos: bang.0,
2498                    end: bang.1,
2499                    phase: 1,
2500                    order: 0,
2501                    text: String::new(),
2502                    site: site.id,
2503                });
2504                (
2505                    "(match (".to_string(),
2506                    format!(
2507                        ") {{ __tmt_a => {{ #[allow(unused_imports)] use {rt}::{{AnyNot as _, NotPrim as _}}; \
2508                         (&{rt}::Un::new(__tmt_a)).tmt_not({}u32) }} }})",
2509                        site.id
2510                    ),
2511                )
2512            }
2513            SiteKind::Return { option, .. } => match option {
2514                None => (
2515                    " let __tmt_v: bool = {".to_string(),
2516                    format!("}}; {rt}::ret({}u32, __tmt_v) ", site.id),
2517                ),
2518                Some(ty) => (
2519                    format!(" let __tmt_v: {ty} = {{"),
2520                    format!("}}; {rt}::ret_opt({}u32, __tmt_v) ", site.id),
2521                ),
2522            },
2523            SiteKind::MinMax {
2524                max, call, close, ..
2525            } => {
2526                // The receiver is borrowed, as a method call borrows it: a `max` that takes
2527                // `&self` leaves it where it is, and one that takes it by value copies it
2528                // out (or, for a type that cannot be copied, does not compile: no probe).
2529                edits.push(Edit {
2530                    pos: call.0,
2531                    end: call.1,
2532                    phase: 1,
2533                    order: 0,
2534                    text: "), ".into(),
2535                    site: site.id,
2536                });
2537                // The call's own `)` (and a trailing comma) is replaced by the probe.
2538                // The call is made as it was written, on the same operands; the probe only
2539                // decides which of the two it is.
2540                let (same, other) = if *max { ("max", "min") } else { ("min", "max") };
2541                edits.push(Edit {
2542                    pos: close.0,
2543                    end: close.1,
2544                    phase: 1,
2545                    order: 0,
2546                    text: format!(
2547                        ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{AnyMinMax as _, MinMaxPrim as _}}; \
2548                         if (&{rt}::Mm(__tmt_a, &__tmt_b)).tmt_other({}u32) {{ (*__tmt_a).{other}(__tmt_b) }} else {{ (*__tmt_a).{same}(__tmt_b) }} }} }})",
2549                        site.id
2550                    ),
2551                    site: site.id,
2552                });
2553                ("(match (&(".to_string(), String::new())
2554            }
2555            SiteKind::Range { inclusive, gap, .. } => {
2556                edits.push(Edit {
2557                    pos: gap.0,
2558                    end: gap.1,
2559                    phase: 1,
2560                    order: 0,
2561                    text: ", ".into(),
2562                    site: site.id,
2563                });
2564                let method = if *inclusive {
2565                    "tmt_range_inclusive"
2566                } else {
2567                    "tmt_range"
2568                };
2569                (
2570                    "(match (".to_string(),
2571                    format!(
2572                        ") {{ (__tmt_a, __tmt_b) => {{ #[allow(unused_imports)] use {rt}::{{AnyRange as _, RangePrim as _}}; \
2573                         (&{rt}::Ar::new(__tmt_a, __tmt_b)).{method}({}u32) }} }})",
2574                        site.id
2575                    ),
2576                )
2577            }
2578            SiteKind::Arm { guard, .. } => {
2579                // The probe goes into the arm's guard, where it runs only when the
2580                // pattern matched.
2581                match guard {
2582                    ArmGuard::None(arrow) => edits.push(Edit {
2583                        pos: *arrow,
2584                        end: *arrow,
2585                        phase: 2,
2586                        order: 0,
2587                        text: format!("if {rt}::arm({}u32) ", site.id),
2588                        site: site.id,
2589                    }),
2590                    ArmGuard::Existing(from, to) => {
2591                        let wider = 2 * (to - from + 1) as i64;
2592                        edits.push(Edit {
2593                            pos: *from,
2594                            end: *from,
2595                            phase: 2,
2596                            order: -wider,
2597                            text: format!("{rt}::arm({}u32) && (", site.id),
2598                            site: site.id,
2599                        });
2600                        edits.push(Edit {
2601                            pos: *to,
2602                            end: *to,
2603                            phase: 0,
2604                            order: wider,
2605                            text: ")".into(),
2606                            site: site.id,
2607                        });
2608                    }
2609                }
2610                (String::new(), String::new())
2611            }
2612            SiteKind::Stmt => (
2613                format!("if {rt}::live({}u32) {{ ", site.id),
2614                " }".to_string(),
2615            ),
2616            // A literal takes its type from where it stands, so it stays where it is.
2617            SiteKind::Neg {
2618                operand,
2619                literal: true,
2620                ..
2621            } => (
2622                format!("(if {rt}::live({}u32) {{ ", site.id),
2623                format!(" }} else {{ {operand} }})"),
2624            ),
2625            SiteKind::Neg { minus, .. } => {
2626                edits.push(Edit {
2627                    pos: minus.0,
2628                    end: minus.1,
2629                    phase: 1,
2630                    order: 0,
2631                    text: String::new(),
2632                    site: site.id,
2633                });
2634                (
2635                    "(match (".to_string(),
2636                    format!(
2637                        ") {{ __tmt_a => if {rt}::live({}u32) {{ -__tmt_a }} else {{ __tmt_a }} }})",
2638                        site.id
2639                    ),
2640                )
2641            }
2642            SiteKind::Guard { .. } => (format!("{rt}::ret({}u32, ", site.id), ")".to_string()),
2643            SiteKind::Field {
2644                name,
2645                shorthand,
2646                from_base: Some(from_base),
2647                ..
2648            } => (
2649                format!(
2650                    "{}if {rt}::live({}u32) {{ ",
2651                    if *shorthand {
2652                        format!("{name}: ")
2653                    } else {
2654                        String::new()
2655                    },
2656                    site.id
2657                ),
2658                format!(" }} else {{ {from_base} }}"),
2659            ),
2660            SiteKind::Field {
2661                from_base: None, ..
2662            } => continue,
2663            SiteKind::Body { value, .. } => (
2664                format!(" if !{rt}::live({}u32) {{ return {value}; }}", site.id),
2665                String::new(),
2666            ),
2667        };
2668        edits.push(Edit {
2669            pos: site.start,
2670            end: site.start,
2671            phase: 2,
2672            order: -len,
2673            text: open,
2674            site: site.id,
2675        });
2676        edits.push(Edit {
2677            pos: site.end,
2678            end: site.end,
2679            phase: 0,
2680            order: len,
2681            text: close,
2682            site: site.id,
2683        });
2684    }
2685    edits.sort_by_key(|e| (e.pos, e.phase, e.order));
2686
2687    // tmt:ignore the capacity is a hint: any number gives the same text
2688    let capacity = source.len() + edits.iter().map(|e| e.text.len()).sum::<usize>();
2689    let mut text = String::with_capacity(capacity);
2690    let mut segments = vec![];
2691    let mut inserted = vec![];
2692    let mut cursor = 0;
2693    for edit in edits {
2694        // Also when nothing lies between two edits: text inserted right after a replaced
2695        // stretch then maps to where it was inserted, not to where the stretch began.
2696        if edit.pos >= cursor {
2697            segments.push((text.len(), cursor, edit.pos - cursor));
2698            text.push_str(&source[cursor..edit.pos]);
2699        }
2700        inserted.push((text.len(), edit.text.len(), edit.site));
2701        text.push_str(&edit.text);
2702        cursor = cursor.max(edit.end);
2703    }
2704    segments.push((text.len(), cursor, source.len() - cursor));
2705    text.push_str(&source[cursor..]);
2706    Rendered {
2707        text,
2708        segments,
2709        inserted,
2710    }
2711}
2712
2713/// The sites to blame for a compile error at `offset` (original coordinates): the smallest
2714/// enabled sites that contain it.
2715pub fn blame(sites: &[Site], enabled: &dyn Fn(u32) -> bool, offset: usize) -> Vec<u32> {
2716    // A replaced body is blamed for what is wrong in its own text only (`inserted_by`):
2717    // by position it would answer for everything in the function.
2718    let containing = || {
2719        sites.iter().filter(|s| {
2720            enabled(s.id)
2721                && s.start <= offset
2722                && offset <= s.end
2723                && !matches!(s.kind, SiteKind::Body { .. })
2724        })
2725    };
2726    let Some(smallest) = containing().map(|s| s.end - s.start).min() else {
2727        return vec![];
2728    };
2729    containing()
2730        .filter(|s| s.end - s.start == smallest)
2731        .map(|s| s.id)
2732        .collect()
2733}
2734
2735#[cfg(test)]
2736mod tests {
2737    use super::*;
2738
2739    #[test]
2740    fn a_cfg_is_decided_only_as_far_as_the_features_decide_it() {
2741        let on: BTreeSet<String> = ["basic".to_string()].into();
2742        for (predicate, expected) in [
2743            (r#"feature = "basic""#, Some(true)),
2744            (r#"feature = "extra""#, Some(false)),
2745            (r#"not(feature = "extra")"#, Some(true)),
2746            (r#"not(feature = "basic")"#, Some(false)),
2747            ("test", None),
2748            (r#"target_os = "linux""#, None),
2749            ("not(test)", None),
2750            ("all()", Some(true)),
2751            ("any()", Some(false)),
2752            (r#"all(feature = "basic", feature = "extra")"#, Some(false)),
2753            (r#"all(test, feature = "extra")"#, Some(false)),
2754            (r#"all(feature = "extra", test)"#, Some(false)),
2755            (r#"all(test, feature = "basic")"#, None),
2756            (
2757                r#"all(feature = "basic", not(feature = "extra"))"#,
2758                Some(true),
2759            ),
2760            (r#"any(feature = "basic", feature = "extra")"#, Some(true)),
2761            (r#"any(test, feature = "basic")"#, Some(true)),
2762            (r#"any(feature = "basic", test)"#, Some(true)),
2763            (r#"any(test, feature = "extra")"#, None),
2764            (r#"any(feature = "extra", feature = "more")"#, Some(false)),
2765            (r#"not(any(test, feature = "basic"))"#, Some(false)),
2766            (r#"not(test, feature = "basic")"#, None),
2767            ("feature = 3", None),
2768            (r#"unknown(feature = "extra")"#, None),
2769            ("all(=)", None),
2770        ] {
2771            let meta: syn::Meta = syn::parse_str(predicate).unwrap();
2772            assert_eq!(cfg_value(&meta, &on), expected, "{predicate}");
2773        }
2774    }
2775
2776    #[test]
2777    fn code_under_a_feature_that_is_off_is_not_in_the_build() {
2778        let source = r#"
2779            #[cfg(feature = "extra")]
2780            pub fn item(n: u32) -> bool { n > 1 }
2781            #[cfg(feature = "basic")]
2782            pub fn kept(n: u32) -> bool { n > 2 }
2783            #[cfg(test)]
2784            fn only_tests(n: u32) -> bool { n > 3 }
2785            #[cfg(feature = "extra")]
2786            mod module { pub fn inside(n: u32) -> bool { n > 4 } }
2787            struct S;
2788            impl S {
2789                #[cfg(feature = "extra")]
2790                fn method(&self, n: u32) -> bool { n > 5 }
2791                fn open(&self, n: u32) -> bool { n > 6 }
2792            }
2793            trait T {
2794                #[cfg(feature = "extra")]
2795                fn provided(&self, n: u32) -> bool { n > 7 }
2796            }
2797            #[cfg(feature = "extra")]
2798            impl T for S {}
2799            fn body(n: u32) -> u32 {
2800                #[cfg(feature = "extra")]
2801                let n = n + 8;
2802                #[cfg(feature = "extra")]
2803                { return n + 9; }
2804                #[cfg(feature = "extra")]
2805                if n > 10 { return 0; }
2806                #[cfg(feature = "extra")]
2807                assert!(n > 11);
2808                match n {
2809                    #[cfg(feature = "extra")]
2810                    12 => 0,
2811                    _ => n + 13,
2812                }
2813            }
2814            #[cfg(not(feature = "extra"))]
2815            mod kept_module {
2816                #[cfg(feature = "extra")]
2817                const OFF: u32 = 14 + 1;
2818                const ON: u32 = 15 + 1;
2819            }
2820        "#;
2821        let file = parse_source(source).unwrap();
2822        let on: BTreeSet<String> = ["basic".to_string()].into();
2823        let ranges = inactive_ranges(source, &file, &on);
2824        let left_out = |text: &str| {
2825            let at = source.find(text).unwrap_or_else(|| panic!("{text}"));
2826            ranges.iter().any(|(from, to)| *from <= at && at < *to)
2827        };
2828        for off in [
2829            "n > 1 ", "n > 4", "n > 5", "n > 7", "n + 8", "n + 9", "n > 10", "n > 11", "12 =>",
2830            "14 + 1",
2831        ] {
2832            assert!(left_out(off), "{off}");
2833        }
2834        for on in ["n > 2", "n > 3", "n > 6", "n + 13", "15 + 1", "struct S"] {
2835            assert!(!left_out(on), "{on}");
2836        }
2837        // With the feature only what asks for its absence is left out, and a file that is
2838        // off as a whole is all out.
2839        let both: BTreeSet<String> = ["basic".to_string(), "extra".to_string()].into();
2840        let with_extra = inactive_ranges(source, &file, &both);
2841        assert_eq!(with_extra.len(), 1, "{with_extra:?}");
2842        assert!(source[with_extra[0].0..with_extra[0].1].starts_with("#[cfg(not(feature"));
2843        let whole = "#![cfg(feature = \"extra\")]\nfn f() {}\n";
2844        let file = parse_source(whole).unwrap();
2845        assert_eq!(inactive_ranges(whole, &file, &on), [(0, whole.len())]);
2846    }
2847
2848    fn all(_: u32) -> bool {
2849        true
2850    }
2851
2852    /// The sites of `src` without the function-level `Return` sites, numbered from
2853    /// `first_id`: most tests are about one expression inside a small function.
2854    fn found(src: &str, first_id: u32) -> Result<Discovery> {
2855        let mut all = discover(src, 0)?;
2856        all.sites
2857            .retain(|s| !matches!(s.kind, SiteKind::Return { .. } | SiteKind::Body { .. }));
2858        for (index, site) in all.sites.iter_mut().enumerate() {
2859            site.id = first_id + index as u32;
2860        }
2861        Ok(all)
2862    }
2863
2864    #[test]
2865    fn finds_a_comparison_with_a_literal() {
2866        let src = "pub fn is_eligible(age: u32) -> bool {\n    age >= 18\n}\n";
2867        let found = found(src, 5).unwrap();
2868        assert_eq!(found.sites.len(), 1);
2869        let site = &found.sites[0];
2870        assert_eq!(
2871            (site.id, site.line, site.column, site.text.as_str()),
2872            (5, 2, 5, "age >= 18")
2873        );
2874        let SiteKind::Cmp {
2875            op,
2876            lhs,
2877            rhs,
2878            literal,
2879            ..
2880        } = &site.kind
2881        else {
2882            panic!()
2883        };
2884        assert_eq!(
2885            (*op, lhs.as_str(), rhs.as_str(), *literal),
2886            (CmpOp::Ge, "age", "18", LiteralSide::Rhs(18))
2887        );
2888    }
2889
2890    #[test]
2891    fn literal_sides() {
2892        let src =
2893            "fn f(x: i32, y: i32) { let _ = (-5 < x, x == (3), 1 < 2, x <= y, x > 1.5 as i32); }";
2894        let literals: Vec<LiteralSide> = found(src, 0)
2895            .unwrap()
2896            .sites
2897            .iter()
2898            .filter_map(|s| match &s.kind {
2899                SiteKind::Cmp { literal, .. } => Some(*literal),
2900                SiteKind::Neg { .. } => None,
2901                _ => panic!(),
2902            })
2903            .collect();
2904        assert_eq!(
2905            literals,
2906            [
2907                LiteralSide::Lhs(-5),
2908                LiteralSide::Rhs(3),
2909                LiteralSide::None,
2910                LiteralSide::None,
2911                LiteralSide::None
2912            ]
2913        );
2914    }
2915
2916    #[test]
2917    fn renders_a_comparison_probe() {
2918        let src = "fn f(a: u8) -> bool { a  >=  18 }";
2919        let sites = found(src, 3).unwrap().sites;
2920        let out = render(src, &sites, &all);
2921        assert_eq!(
2922            out.text,
2923            "fn f(a: u8) -> bool { (match (&(a), &(18)) { (__tmt_l, __tmt_r) => { #[allow(unused_imports)] \
2924             use crate::__tmt_rt::{ValAny as _, ValNum as _}; crate::__tmt_rt::ord(3u32, 3u8, __tmt_l, __tmt_r, \
2925             (&crate::__tmt_rt::W(__tmt_l)).tmt_val(), (&crate::__tmt_rt::W(__tmt_r)).tmt_val()) } }) }"
2926        );
2927        assert_eq!(render(src, &sites, &|_| false).text, src);
2928    }
2929
2930    #[test]
2931    fn renders_statement_guards_and_nested_sites() {
2932        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}";
2933        let sites = found(src, 0).unwrap().sites;
2934        let kinds: Vec<&str> = sites.iter().map(|s| s.text.as_str()).collect();
2935        assert_eq!(
2936            kinds,
2937            [
2938                "check((a < 3) == true)?;",
2939                "v.push(a);",
2940                "v.clear();",
2941                "(a < 3) == true",
2942                "a < 3"
2943            ]
2944        );
2945        let out = render(src, &sites, &all);
2946        assert_eq!(
2947            out.text.lines().count(),
2948            src.lines().count(),
2949            "line numbers are preserved"
2950        );
2951        assert!(
2952            out.text
2953                .contains("if crate::__tmt_rt::live(0u32) { check((match (&(((match (&(a), &(3))"),
2954            "{}",
2955            out.text
2956        );
2957        assert!(out.text.contains("if crate::__tmt_rt::live(1u32) { v.push(a); }if crate::__tmt_rt::live(2u32) { v.clear(); }"), "{}", out.text);
2958        syn::parse_file(&out.text).expect("instrumented source parses");
2959
2960        // Only the inner comparison enabled.
2961        let inner = render(src, &sites, &|id| id == 4);
2962        assert!(
2963            inner.text.contains("check(((match (&(a), &(3))"),
2964            "{}",
2965            inner.text
2966        );
2967        assert!(inner.text.contains(") == true)?;"), "{}", inner.text);
2968        syn::parse_file(&inner.text).unwrap();
2969    }
2970
2971    #[test]
2972    fn skips_tests_const_contexts_and_macros() {
2973        let src = r#"
2974            const LIMIT: bool = 1 < 2;
2975            static S: bool = 3 > 2;
2976            const fn c(a: u8) -> bool { a < 1 }
2977            fn arr(a: u8) -> [u8; { 2 > 1 } as usize] { let _ = [0u8; (4 > 3) as usize]; assert!(a < 9); [a; 1] }
2978            enum E { A = (5 > 4) as isize }
2979            struct T;
2980            impl T { const K: bool = 6 < 7; const fn k(a: u8) -> bool { a > 6 } }
2981            #[cfg(test)]
2982            mod tests { fn t(a: u8) -> bool { a == 1 } }
2983            #[cfg(test)]
2984            mod more_tests;
2985            #[cfg(test)]
2986            #[doc = "not a path"]
2987            mod documented;
2988            #[cfg(test)]
2989            #[path = "support/helpers.rs"]
2990            mod helpers;
2991            #[cfg(all(test, feature = "x"))]
2992            fn helper(a: u8) -> bool { a != 1 }
2993            #[test]
2994            fn a_test() { let a = 1; if a == 2 { panic!() } }
2995            #[tokio::test]
2996            async fn async_test() { let a = 1; if a == 3 { panic!() } }
2997            #[cfg(not(test))]
2998            fn real(a: u8) -> bool { a == 100 }
2999            #[cfg(feature = "test-utils")]
3000            fn also_real(a: u8) -> bool { a == 101 }
3001            fn pat(a: u8) -> bool { matches!(a, 1..=2) || match a { 0..=9 => a == 102, _ => false } }
3002        "#;
3003        let found = found(src, 0).unwrap();
3004        let texts: Vec<&str> = found.sites.iter().map(|s| s.text.as_str()).collect();
3005        assert_eq!(
3006            texts,
3007            [
3008                "a == 100",
3009                "a == 101",
3010                "matches!(a, 1..=2) || match a { 0..=9 => a == 102, _ => false }",
3011                "0..=9 => ..",
3012                "a == 102"
3013            ]
3014        );
3015        assert_eq!(
3016            found.test_modules,
3017            [
3018                TestModule {
3019                    name: "more_tests".into(),
3020                    path: None
3021                },
3022                TestModule {
3023                    name: "documented".into(),
3024                    path: None
3025                },
3026                TestModule {
3027                    name: "helpers".into(),
3028                    path: Some("support/helpers.rs".into())
3029                },
3030            ]
3031        );
3032    }
3033
3034    #[test]
3035    fn deletable_statements() {
3036        let src = r#"
3037            async fn f(s: &mut S) -> Result<(), E> {
3038                s.validate()?;
3039                s.total += 1;
3040                s.flag = true;
3041                helper(s);
3042                s.flush().await?;
3043                s.sync().await;
3044                let x = s.get();
3045                println!("{x}");
3046                if x > 0 { return Ok(()); }
3047                s.done()
3048            }
3049        "#;
3050        let texts: Vec<String> = found(src, 0)
3051            .unwrap()
3052            .sites
3053            .into_iter()
3054            .filter(|s| s.kind == SiteKind::Stmt)
3055            .map(|s| s.text)
3056            .collect();
3057        assert_eq!(
3058            texts,
3059            [
3060                "s.validate()?;",
3061                "s.total += 1;",
3062                "s.flag = true;",
3063                "helper(s);",
3064                "s.flush().await?;",
3065                "s.sync().await;"
3066            ]
3067        );
3068    }
3069
3070    #[test]
3071    fn maps_offsets_back_and_blames_the_innermost_site() {
3072        let src = "fn f(a: u8, b: u8) -> bool { g(a < b); a > 1 }";
3073        let sites = found(src, 0).unwrap().sites;
3074        let out = render(src, &sites, &all);
3075        // Every original character keeps its identity through the mapping.
3076        for (orig, ch) in src.char_indices().filter(|(_, c)| c.is_alphanumeric()) {
3077            let hits: Vec<usize> = out
3078                .text
3079                .char_indices()
3080                .filter(|(o, c)| *c == ch && out.to_original(*o) == orig)
3081                .map(|(o, _)| o)
3082                .collect();
3083            assert!(
3084                !hits.is_empty(),
3085                "original offset {orig} ({ch}) is unreachable"
3086            );
3087        }
3088        // An error inside the probe of `a < b` blames it, not the enclosing statement.
3089        let probe = out.text.find("ord(1u32").unwrap();
3090        let orig = out.to_original(probe);
3091        assert_eq!(blame(&sites, &all, orig), [1]);
3092        // With the inner site disabled, the statement is next.
3093        assert_eq!(blame(&sites, &|id| id != 1, orig), [0]);
3094        assert_eq!(
3095            blame(&sites, &all, src.find("fn").unwrap()),
3096            Vec::<u32>::new()
3097        );
3098        assert_eq!(out.to_original(0), 0);
3099        assert_eq!(out.to_original(out.text.len()), src.len());
3100    }
3101
3102    #[test]
3103    fn blame_is_inclusive_at_both_ends() {
3104        let src = "fn f(a: u8) -> bool { a > 1 }";
3105        let sites = found(src, 0).unwrap().sites;
3106        let (start, end) = (sites[0].start, sites[0].end);
3107        assert_eq!(blame(&sites, &all, start - 1), Vec::<u32>::new());
3108        assert_eq!(blame(&sites, &all, start), [0]);
3109        assert_eq!(blame(&sites, &all, end), [0]);
3110        assert_eq!(blame(&sites, &all, end + 1), Vec::<u32>::new());
3111        // The probe opens before the first original character and closes after the last.
3112        let out = render(src, &sites, &all);
3113        assert_eq!(out.to_original(out.text.find("(match").unwrap()), start);
3114        assert_eq!(
3115            out.to_original(out.text.find("tmt_val()) } })").unwrap()),
3116            end
3117        );
3118        assert_eq!(
3119            out.to_original(out.text.find("), &(").unwrap() + 2),
3120            sites[0].start + 1
3121        );
3122    }
3123
3124    #[test]
3125    fn finds_sites_in_impls_and_array_elements() {
3126        let src = r#"
3127            struct T(u8);
3128            impl T { fn small(&self) -> bool { self.0 < 3 } }
3129            #[cfg(test)]
3130            impl T { fn only_in_tests(&self) -> bool { self.0 < 4 } }
3131            trait Tr { fn provided(&self, a: u8) -> bool { a < 5 } }
3132            fn arr(a: u8) -> [bool; 2] { [a < 6; 2] }
3133            fn closure(a: u8) -> bool { (|| a < 7)() }
3134        "#;
3135        let texts: Vec<String> = found(src, 0)
3136            .unwrap()
3137            .sites
3138            .into_iter()
3139            .map(|s| s.text)
3140            .collect();
3141        assert_eq!(texts, ["self.0 < 3", "a < 5", "a < 6", "a < 7"]);
3142    }
3143
3144    #[test]
3145    fn logic_and_arithmetic_sites() {
3146        let src = "fn f(a: bool, b: bool, x: u32, y: u32) -> u32 { if a && b || !a { x + y * 2 } else { x - 1 % y } }";
3147        let found = found(src, 0).unwrap().sites;
3148        let kinds: Vec<String> = found
3149            .iter()
3150            .map(|s| match &s.kind {
3151                SiteKind::Logic { and, lhs, rhs, .. } => format!("logic and={and} [{lhs}] [{rhs}]"),
3152                SiteKind::Arith { op, lhs, rhs, .. } => {
3153                    format!("arith {} [{lhs}] [{rhs}]", op.symbol())
3154                }
3155                SiteKind::Not { operand, .. } => format!("not [{operand}]"),
3156                other => format!("{other:?}"),
3157            })
3158            .collect();
3159        assert_eq!(
3160            kinds,
3161            [
3162                "logic and=false [a && b] [!a]",
3163                "logic and=true [a] [b]",
3164                "not [a]",
3165                "arith + [x] [y * 2]",
3166                "arith * [y] [2]",
3167                "arith - [x] [1 % y]",
3168                "arith % [1] [y]",
3169            ]
3170        );
3171        let out = render(src, &found, &all).text;
3172        syn::parse_file(&out).expect("instrumented source parses");
3173        assert!(
3174            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 })"),
3175            "{out}"
3176        );
3177        assert!(
3178            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) } })"),
3179            "{out}"
3180        );
3181        // Every probe the renderer can emit exists in the runtime under that name.
3182        for op in ArithOp::ALL {
3183            assert_ne!(op.swapped(), op);
3184            for assign in [false, true] {
3185                let method = op.method(assign);
3186                let fallback = format!("{} {method} ", op.fallback_trait(assign));
3187                assert!(
3188                    crate::RUNTIME_SOURCE.contains(&format!("fn {method}(")),
3189                    "{method}"
3190                );
3191                assert!(crate::RUNTIME_SOURCE.contains(&fallback), "{fallback}");
3192                assert!(
3193                    crate::RUNTIME_SOURCE.contains(&format!("trait {} ", op.prim_trait(assign))),
3194                    "{op:?}"
3195                );
3196            }
3197        }
3198    }
3199
3200    #[test]
3201    fn let_chains_and_literal_arithmetic_are_left_alone() {
3202        let src = r#"
3203            fn f(o: Option<u8>, a: bool, n: u32) -> u32 {
3204                if let Some(x) = o && a && x > 1 { return 1; }
3205                let k = 60 * 60;
3206                (n & 3) | (n << 1) ^ k
3207            }
3208        "#;
3209        let texts: Vec<String> = found(src, 0)
3210            .unwrap()
3211            .sites
3212            .into_iter()
3213            .map(|s| s.text)
3214            .collect();
3215        assert_eq!(
3216            texts,
3217            [
3218                "x > 1",
3219                "(n & 3) | (n << 1) ^ k",
3220                "n & 3",
3221                "(n << 1) ^ k",
3222                "n << 1"
3223            ]
3224        );
3225    }
3226
3227    #[test]
3228    fn attributes_const_methods_and_let_on_the_right() {
3229        let src = r#"
3230            struct T(u8);
3231            impl T {
3232                const fn in_const(&self) -> bool { self.0 < 1 }
3233                #[test]
3234                fn test_method(&self) -> bool { self.0 < 2 }
3235                fn real(&self) -> bool { self.0 < 3 }
3236            }
3237            trait Tr {
3238                #[cfg(test)]
3239                fn only_in_tests(&self, a: u8) -> bool { a < 4 }
3240            }
3241            fn f(s: &mut S, o: Option<u8>, a: bool) -> Result<(), E> {
3242                #[cfg(feature = "x")]
3243                s.guarded();
3244                #[allow(unused)]
3245                s.total += 1;
3246                #[allow(unused)]
3247                s.check()?;
3248                #[allow(unused)]
3249                s.sync().await;
3250                s.plain();
3251                if a && let Some(v) = o { s.use_it(v); }
3252                Ok(())
3253            }
3254        "#;
3255        let texts: Vec<String> = found(src, 0)
3256            .unwrap()
3257            .sites
3258            .into_iter()
3259            .map(|s| s.text)
3260            .collect();
3261        // syn attaches the attribute of `#[a] x += 1;` to the left operand, so that statement
3262        // is guarded together with its attribute; the guard is valid around it either way.
3263        assert_eq!(
3264            texts,
3265            [
3266                "self.0 < 3",
3267                "#[allow(unused)]\n                s.total += 1;",
3268                "s.plain();",
3269                "#[allow(unused)]\n                s.total += 1",
3270                "s.use_it(v);"
3271            ]
3272        );
3273        let found = found(src, 0).unwrap().sites;
3274        syn::parse_file(&render(src, &found, &all).text).expect("instrumented source parses");
3275    }
3276
3277    #[test]
3278    fn compound_assignment_negation_and_bit_operators() {
3279        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 }";
3280        let sites = found(src, 0).unwrap().sites;
3281        let kinds: Vec<String> = sites
3282            .iter()
3283            .map(|s| match &s.kind {
3284                SiteKind::Arith {
3285                    op,
3286                    assign,
3287                    lhs,
3288                    rhs,
3289                    ..
3290                } => format!(
3291                    "{lhs} {}{} {rhs}",
3292                    op.symbol(),
3293                    if *assign { "=" } else { "" }
3294                ),
3295                SiteKind::Not { operand, .. } => format!("!{operand}"),
3296                SiteKind::Stmt => "stmt".to_string(),
3297                other => format!("{other:?}"),
3298            })
3299            .collect();
3300        assert_eq!(
3301            kinds,
3302            [
3303                "stmt",
3304                "stmt",
3305                "*total += n",
3306                "*total <<= 1",
3307                "!ok",
3308                "!n",
3309                "!m",
3310                "n & 7"
3311            ]
3312        );
3313        let out = render(src, &sites, &all).text;
3314        syn::parse_file(&out).expect("instrumented source parses");
3315        for expected in [
3316            "(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) } });",
3317            "use crate::__tmt_rt::{AnyShlAssign as _, BitAssignPrim as _}; (&crate::__tmt_rt::Aa::new(__tmt_a, __tmt_b)).tmt_shl_assign(3u32) } });",
3318            "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) } }) {",
3319            "(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) } })",
3320        ] {
3321            assert!(out.contains(expected), "missing {expected}\nin {out}");
3322        }
3323        // `!a && b`: the negation and the conjunction start at the same character.
3324        let nested = "fn f(a: bool, b: bool) -> bool { !a && b }";
3325        let sites = found(nested, 0).unwrap().sites;
3326        let out = render(nested, &sites, &all).text;
3327        syn::parse_file(&out).expect("instrumented source parses");
3328        assert!(
3329            out.contains("(match { let __tmt_c: u8 = crate::__tmt_rt::lhs(0u32, true, (match (a) { __tmt_a => {"),
3330            "{out}"
3331        );
3332        // Names the probes introduce are never in scope where user code runs.
3333        let capture = "fn f(a: bool, __tmt_c: u8, __tmt_a: u8) -> bool { a && __tmt_c == 2 && __tmt_a + 1 > 0 }";
3334        let sites = found(capture, 0).unwrap().sites;
3335        let out = render(capture, &sites, &all).text;
3336        syn::parse_file(&out).expect("instrumented source parses");
3337        // The arms that bind a probe variable contain only probe code.
3338        for arm in out.split("__tmt_c => ").skip(1) {
3339            assert!(arm.starts_with("__tmt_c == 1u8 })"), "{arm}");
3340        }
3341        for arm in out.split("(__tmt_a, __tmt_b) => ").skip(1) {
3342            assert!(
3343                arm.starts_with("{ #[allow(unused_imports)] use crate::__tmt_rt::"),
3344                "{arm}"
3345            );
3346        }
3347    }
3348
3349    #[test]
3350    fn compound_assignment_is_probed_only_on_plain_places() {
3351        let src = r#"
3352            fn f(s: &mut S, v: &mut [u32], p: &mut u32, i: usize) {
3353                let mut local = 0u32;
3354                local += 1;
3355                s.count += 1;
3356                s.inner.total -= 2;
3357                *p *= 3;
3358                (*p) += 4;
3359                v[i] += 5;
3360                v[next()] += 6;
3361                s.get_mut().x += 7;
3362                *s.slot() += 8;
3363            }
3364        "#;
3365        let probed: Vec<String> = found(src, 0)
3366            .unwrap()
3367            .sites
3368            .into_iter()
3369            .filter(|s| matches!(s.kind, SiteKind::Arith { assign: true, .. }))
3370            .map(|s| s.text)
3371            .collect();
3372        assert_eq!(
3373            probed,
3374            [
3375                "local += 1",
3376                "s.count += 1",
3377                "s.inner.total -= 2",
3378                "*p *= 3",
3379                "(*p) += 4"
3380            ]
3381        );
3382        // The others are still statements that can be deleted.
3383        let deletable = found(src, 0)
3384            .unwrap()
3385            .sites
3386            .iter()
3387            .filter(|s| s.kind == SiteKind::Stmt)
3388            .count();
3389        assert_eq!(deletable, 9);
3390    }
3391
3392    #[test]
3393    fn bool_functions_are_return_sites() {
3394        let src = r#"
3395            pub fn is_ok(a: u8) -> bool { let b = a; b > 1 }
3396            fn count(a: u8) -> u8 { a }
3397            fn unit(a: u8) { let _ = a; }
3398            const fn in_const(a: u8) -> bool { a > 2 }
3399            #[test]
3400            fn a_test() -> bool { true }
3401            struct T;
3402            impl T { fn method(&self) -> bool { true } }
3403            trait Tr { fn required(&self) -> bool; fn provided(&self) -> bool { false } }
3404            fn boxed() -> Box<bool> { Box::new(true) }
3405            fn qualified() -> core::primitive::bool { true }
3406        "#;
3407        let sites = discover(src, 0).unwrap().sites;
3408        let returns: Vec<(&str, &str, usize)> = sites
3409            .iter()
3410            .filter_map(|s| match &s.kind {
3411                SiteKind::Return {
3412                    name, option: None, ..
3413                } => Some((name.as_str(), s.text.as_str(), s.line)),
3414                _ => None,
3415            })
3416            .collect();
3417        assert_eq!(
3418            returns,
3419            [
3420                ("is_ok", "fn is_ok(a: u8) -> bool", 2),
3421                ("method", "fn method(&self) -> bool", 9),
3422                ("provided", "fn provided(&self) -> bool", 10),
3423            ]
3424        );
3425        let out = render(src, &sites, &all).text;
3426        syn::parse_file(&out).expect("instrumented source parses");
3427        assert!(
3428            out.contains(
3429                "pub fn is_ok(a: u8) -> bool { let __tmt_v: bool = { \
3430                 if !crate::__tmt_rt::live(1u32) { return true; } \
3431                 if !crate::__tmt_rt::live(2u32) { return false; } let b = a; (match"
3432            ),
3433            "{out}"
3434        );
3435        assert!(
3436            out.contains("}) }; crate::__tmt_rt::ret(0u32, __tmt_v) }"),
3437            "{out}"
3438        );
3439        assert_eq!(
3440            out.lines().count(),
3441            src.lines().count(),
3442            "line numbers are preserved"
3443        );
3444        // A compile error in the wrapper is blamed on the function's site.
3445        let rendered = render(src, &sites, &all);
3446        let wrapper = rendered.text.find("ret(0u32").unwrap();
3447        assert_eq!(rendered.inserted_by(wrapper), Some(0));
3448        // And one in a replaced body on that replacement alone: by position they are
3449        // all the same place.
3450        let replaced = rendered.text.find("return false; } let b").unwrap();
3451        assert_eq!(rendered.inserted_by(replaced), Some(2));
3452        assert_eq!(blame(&sites, &all, rendered.to_original(replaced)), [0]);
3453    }
3454
3455    #[test]
3456    fn ids_are_consecutive_across_every_kind_of_site() {
3457        let src = r#"
3458            fn a(x: u8) -> bool { x > 1 }
3459            fn b(x: u8) -> bool { !(x > 2) && !!flag(x) }
3460            fn c(s: &mut S) { s.n += 1; s.go(); }
3461        "#;
3462        let sites = discover(src, 10).unwrap().sites;
3463        let ids: Vec<u32> = sites.iter().map(|s| s.id).collect();
3464        assert_eq!(ids, (10..10 + sites.len() as u32).collect::<Vec<_>>());
3465        let texts: Vec<&str> = sites
3466            .iter()
3467            .filter(|s| !matches!(s.kind, SiteKind::Body { .. }))
3468            .map(|s| s.text.as_str())
3469            .collect();
3470        assert_eq!(
3471            texts,
3472            [
3473                "fn a(x: u8) -> bool",
3474                "x > 1",
3475                "fn b(x: u8) -> bool",
3476                "!(x > 2) && !!flag(x)",
3477                "!(x > 2)",
3478                "x > 2",
3479                "!!flag(x)",
3480                "!flag(x)",
3481                "s.n += 1;",
3482                "s.go();",
3483                "s.n += 1",
3484            ]
3485        );
3486        syn::parse_file(&render(src, &sites, &all).text).expect("instrumented source parses");
3487    }
3488
3489    #[test]
3490    fn only_calls_and_assignments_are_deletable() {
3491        let src = r#"
3492            async fn f(s: &mut S, v: Vec<u8>) -> Result<(), E> {
3493                s.field;
3494                v[0];
3495                (s.a, s.b);
3496                s.value?;
3497                s.future.await;
3498                s.x = 1;
3499                s.x -= 1;
3500                s.x == 1;
3501                s.call().await?;
3502                Ok(())
3503            }
3504        "#;
3505        let texts: Vec<String> = found(src, 0)
3506            .unwrap()
3507            .sites
3508            .into_iter()
3509            .filter(|s| s.kind == SiteKind::Stmt)
3510            .map(|s| s.text)
3511            .collect();
3512        assert_eq!(texts, ["s.x = 1;", "s.x -= 1;", "s.call().await?;"]);
3513    }
3514
3515    #[test]
3516    fn ranges_match_arms_min_max_and_option_results() {
3517        let src = r#"
3518            fn find(v: &[u32], limit: u32) -> Option<u32> {
3519                for i in 0..v.len() {
3520                    let capped = v[i].min(limit).max(1);
3521                    match capped {
3522                        0 => return None,
3523                        n if n > 5 => return Some(n),
3524                        1..=3 => continue,
3525                        other => { let _ = other; }
3526                    }
3527                }
3528                let _ = &v[1..=2];
3529                for _ in 1..=limit as usize {}
3530                let _ = 'a'..'z';
3531                let _ = v.iter().max();
3532                None
3533            }
3534            fn exhaustive(k: Kind) -> u8 { match k { Kind::A => 1, Kind::B => 2 } }
3535            fn hidden() -> Option<impl Sized> { Some(1) }
3536            fn first(v: &[u32]) -> Option<u32> { v.first().copied() }
3537        "#;
3538        let sites = discover(src, 0).unwrap().sites;
3539        let kinds: Vec<String> = sites
3540            .iter()
3541            .filter_map(|s| match &s.kind {
3542                SiteKind::Return { name, option, .. } => Some(format!("return {name} {option:?}")),
3543                SiteKind::Range {
3544                    inclusive,
3545                    lhs,
3546                    rhs,
3547                    ..
3548                } => Some(format!("range {lhs} {rhs} inclusive={inclusive}")),
3549                SiteKind::Arm { pattern, guard, .. } => Some(format!(
3550                    "arm {pattern} guarded={}",
3551                    matches!(guard, ArmGuard::Existing(..))
3552                )),
3553                SiteKind::MinMax {
3554                    max,
3555                    receiver,
3556                    argument,
3557                    ..
3558                } => Some(format!("minmax {receiver} {argument} max={max}")),
3559                _ => None,
3560            })
3561            .collect();
3562        assert_eq!(
3563            kinds,
3564            [
3565                "range 0 v.len() inclusive=false",
3566                "minmax v[i].min(limit) 1 max=true",
3567                "minmax v[i] limit max=false",
3568                // The catch-all arm and the last arm stay; a match without one is left alone.
3569                "arm 0 guarded=false",
3570                "arm n if n > 5 guarded=true",
3571                "arm 1..=3 guarded=false",
3572                // `1..=2` and `'a'..'z'` have literals at both ends.
3573                "range 1 limit as usize inclusive=true",
3574                "return first Some(\"Option<u32>\")",
3575            ]
3576        );
3577        let out = render(src, &sites, &all).text;
3578        syn::parse_file(&out).expect("instrumented source parses");
3579        assert_eq!(out.lines().count(), src.lines().count());
3580        let option = sites
3581            .iter()
3582            .find(|site| matches!(&site.kind, SiteKind::Return { name, .. } if name == "first"))
3583            .unwrap();
3584        assert_eq!(out.matches("let __tmt_v: Option<u32> = {").count(), 1);
3585        assert!(
3586            out.contains(&format!(
3587                "crate::__tmt_rt::ret_opt({}u32, __tmt_v)",
3588                option.id
3589            )),
3590            "{out}"
3591        );
3592        assert!(out.contains("0 if crate::__tmt_rt::arm("), "{out}");
3593        assert!(
3594            out.contains("n if crate::__tmt_rt::arm(") && out.contains(") && ("),
3595            "{out}"
3596        );
3597        assert!(out.contains("1..=3 if crate::__tmt_rt::arm("), "{out}");
3598        assert!(
3599            out.contains(".tmt_range(") && out.contains(".tmt_range_inclusive("),
3600            "{out}"
3601        );
3602        // The call that was written, and the other one for the mutant, on the operands
3603        // as they were evaluated once; the receiver is borrowed, not moved.
3604        assert!(
3605            out.contains("(match (&(v[i]), limit) {")
3606                && out.contains(
3607                    "Mm(__tmt_a, &__tmt_b)).tmt_other(5u32) { (*__tmt_a).max(__tmt_b) } else { (*__tmt_a).min(__tmt_b) }"
3608                )
3609                && out.contains(
3610                    ".tmt_other(4u32) { (*__tmt_a).min(__tmt_b) } else { (*__tmt_a).max(__tmt_b) }"
3611                ),
3612            "{out}"
3613        );
3614        assert!(
3615            !out.contains(".min(limit)") && !out.contains(".max(1)"),
3616            "{out}"
3617        );
3618        assert!(
3619            out.contains("v.iter().max()"),
3620            "an iterator's max is another method: {out}"
3621        );
3622    }
3623
3624    #[test]
3625    fn macro_arguments() {
3626        let src = r#"
3627            fn f(a: u32, b: u32, out: &mut String) -> Vec<u32> {
3628                assert!(a < 100);
3629                debug_assert!(a < 101, "message {}", a < 102);
3630                assert_eq!(a < 1, b < 2, "context {}", a + 3);
3631                let _ = format!("{} {name}", a < 4, name = b < 5);
3632                write!(out, "{}", a < 6).unwrap();
3633                if matches!(a.cmp(&b), std::cmp::Ordering::Less if a < 7) || matches!(a < 8, true) { panic!("{}", a < 9); }
3634                custom!(a < 10);
3635                let _ = vec![a < 11; 2];
3636                vec![a + b, (a < 12) as u32]
3637            }
3638        "#;
3639        let texts: Vec<String> = found(src, 0)
3640            .unwrap()
3641            .sites
3642            .into_iter()
3643            .filter(|s| matches!(s.kind, SiteKind::Cmp { .. } | SiteKind::Arith { .. }))
3644            .map(|s| s.text)
3645            .collect();
3646        assert_eq!(
3647            texts,
3648            [
3649                "a < 1", "b < 2", "a + 3", "a < 4", "b < 5", "a < 6", "a < 8", "a < 9", "a + b",
3650                "a < 12"
3651            ]
3652        );
3653        let found = found(src, 0).unwrap().sites;
3654        syn::parse_file(&render(src, &found, &all).text).expect("instrumented source parses");
3655    }
3656
3657    #[test]
3658    fn non_ascii_source_keeps_byte_offsets() {
3659        let src = "fn f(a: u8) -> bool { let s = \"日本語\"; s.len() > 3 && a < 2 }";
3660        let sites = found(src, 0).unwrap().sites;
3661        let texts: Vec<&str> = sites.iter().map(|s| s.text.as_str()).collect();
3662        assert_eq!(texts, ["s.len() > 3 && a < 2", "s.len() > 3", "a < 2"]);
3663        syn::parse_file(&render(src, &sites, &all).text).unwrap();
3664    }
3665
3666    #[test]
3667    fn unparseable_source_is_an_error() {
3668        assert!(discover("fn f( {", 0).is_err());
3669    }
3670    /// Every site as `kind text`, in discovery order, without the replaced bodies.
3671    fn labelled(src: &str) -> Vec<String> {
3672        discover(src, 0)
3673            .unwrap()
3674            .sites
3675            .iter()
3676            .filter(|s| !matches!(s.kind, SiteKind::Body { .. }))
3677            .map(|s| {
3678                let kind = match &s.kind {
3679                    SiteKind::Cmp { .. } => "cmp",
3680                    SiteKind::Logic { .. } => "logic",
3681                    SiteKind::Arith { .. } => "arith",
3682                    SiteKind::Not { .. } => "not",
3683                    SiteKind::Return { .. } => "return",
3684                    SiteKind::MinMax { .. } => "minmax",
3685                    SiteKind::Range { .. } => "range",
3686                    SiteKind::Arm { .. } => "arm",
3687                    SiteKind::Stmt => "stmt",
3688                    SiteKind::Neg { .. } => "neg",
3689                    SiteKind::Guard { .. } => "guard",
3690                    SiteKind::Field { .. } => "field",
3691                    SiteKind::Body { .. } => "body",
3692                };
3693                format!("{kind} {}", s.text)
3694            })
3695            .collect()
3696    }
3697
3698    #[test]
3699    fn byte_order_mark_and_interpreter_line_are_refused() {
3700        let body = "fn f(a: u8) -> bool { a > 1 }";
3701        assert!(discover(&format!("\u{feff}{body}"), 0).is_err());
3702        assert!(discover(&format!("#!/usr/bin/env run\n{body}"), 0).is_err());
3703        // An inner attribute starts with the same two characters and is fine.
3704        assert_eq!(
3705            labelled(&format!("#![allow(dead_code)]\n{body}")),
3706            ["return fn f(a: u8) -> bool", "cmp a > 1"]
3707        );
3708    }
3709
3710    #[test]
3711    fn which_result_types_make_a_return_site() {
3712        let src = "fn a() -> <S as Tr>::Option<u8> { g() }\n\
3713                   fn b() -> Option { g() }\n\
3714                   fn c() -> Vec<u8> { g() }\n\
3715                   fn d() -> std::option::Option<u8> { g() }\n\
3716                   fn e() -> <S>::bool { g() }\n\
3717                   fn e2() -> <S as Tr>::bool { g() }\n\
3718                   fn one(a: u8) -> bool { a > 1 }\n\
3719                   fn two(a: u8) -> bool { let b = a; b > 1 }\n\
3720                   fn early(a: u8) -> bool { return a > 1; }\n";
3721        let returns: Vec<(String, Option<String>, Option<&str>)> = discover(src, 0)
3722            .unwrap()
3723            .sites
3724            .into_iter()
3725            .filter_map(|s| match s.kind {
3726                SiteKind::Return {
3727                    name,
3728                    option,
3729                    sole_expr,
3730                } => Some((name, option, sole_expr.map(|(from, to)| &src[from..to]))),
3731                _ => None,
3732            })
3733            .collect();
3734        assert_eq!(
3735            returns,
3736            [
3737                (
3738                    "d".to_string(),
3739                    Some("std::option::Option<u8>".to_string()),
3740                    Some("g()")
3741                ),
3742                // Only a body that is one expression has a "sole expression".
3743                ("one".to_string(), None, Some("a > 1")),
3744                ("two".to_string(), None, None),
3745            ]
3746        );
3747    }
3748
3749    #[test]
3750    fn places_chains_attributes_and_shadowed_macros() {
3751        // A parenthesised variable is still a plain place. An attribute on a statement
3752        // belongs to its leftmost operand, which is then not probed; the statement can
3753        // still be deleted.
3754        assert_eq!(
3755            labelled("fn f(mut x: i32) -> i32 { #[allow(unused)] x += 1; (x) += 2; x }"),
3756            [
3757                "stmt #[allow(unused)] x += 1;",
3758                "stmt (x) += 2;",
3759                "arith (x) += 2"
3760            ]
3761        );
3762        // `cond && let ..` is a let chain as much as `let .. && cond`.
3763        assert_eq!(
3764            labelled("fn f(a: u8, o: Option<u8>) { if a > 1 && let Some(b) = o { g(b); } }"),
3765            ["cmp a > 1", "stmt g(b);"]
3766        );
3767        // And so is everything joined to one.
3768        assert_eq!(
3769            labelled(
3770                "fn f(a: u8, o: Option<u8>) { if a > 1 && let Some(b) = o && b > 2 { g(b); } }"
3771            ),
3772            ["cmp a > 1", "cmp b > 2", "stmt g(b);"]
3773        );
3774        // A macro of this file under a standard name takes anything as its arguments.
3775        assert_eq!(
3776            labelled(
3777                "macro_rules! vec { ($($t:tt)*) => {} }\n\
3778                 fn f(a: u8) { let _ = vec![a > 1]; let _ = format!(\"{}\", a > 2); }"
3779            ),
3780            ["cmp a > 2"]
3781        );
3782        assert_eq!(
3783            labelled(
3784                "trait T { const fn f(a: u8) -> bool { a > 1 } fn g(a: u8) -> bool { a > 2 } }"
3785            ),
3786            ["return fn g(a: u8) -> bool", "cmp a > 2"]
3787        );
3788    }
3789
3790    #[test]
3791    fn min_max_and_ranges_that_are_left_alone() {
3792        assert_eq!(
3793            labelled(
3794                "fn f(a: u8, b: u8) -> u8 { let _ = a.max::<u8>(b); \
3795                 let _ = #[allow(unused)] a.min(b); let _ = a.max(b, 1); a.max(b) }"
3796            ),
3797            ["minmax a.max(b)"]
3798        );
3799        // One literal end is enough to fix the type; the ends are searched for sites.
3800        let src = "fn f(a: usize, b: usize, v: &[u8]) { for _ in a..10 {} for _ in 1..b {} \
3801                   for _ in (a + 1)..(b * 2) {} for _ in 3..4 {} for _ in (5)..(-6) {} }";
3802        assert_eq!(
3803            labelled(src),
3804            [
3805                "range a..10",
3806                "range 1..b",
3807                "range (a + 1)..(b * 2)",
3808                "arith a + 1",
3809                "arith b * 2",
3810                // Two literal ends are no range site; the minus in one is still a minus.
3811                "neg -6"
3812            ]
3813        );
3814        let out = render(src, &discover(src, 0).unwrap().sites, &all).text;
3815        // The `..` itself is gone: the ends are the two arguments of the probe.
3816        assert!(out.contains("for _ in (match (a, 10) {"), "{out}");
3817        assert!(!out.contains("a..10") && !out.contains("1..b"), "{out}");
3818        assert!(out.contains("3..4") && out.contains("(5)..((if "), "{out}");
3819    }
3820
3821    #[test]
3822    fn which_arms_can_be_removed() {
3823        let src = "fn f(k: u8) -> u8 {\n\
3824                   \x20   let a = match k { 1 => 1, x => x, 2 => 2, #[cfg(any())] 3 => 3, _rest => 0 };\n\
3825                   \x20   let b = match k { 1 => 1, NONE => 0 };\n\
3826                   \x20   let c = match k { 1 => 1, n @ 0..=9 => n };\n\
3827                   \x20   let d = match k {\n\
3828                   \x20       1 => 1,\n\
3829                   \x20       _ => 0,\n\
3830                   \x20   };\n\
3831                   \x20   a + b + c + d\n\
3832                   }\n";
3833        let arms: Vec<(u32, usize, usize, String)> = discover(src, 7)
3834            .unwrap()
3835            .sites
3836            .into_iter()
3837            .filter(|s| matches!(s.kind, SiteKind::Arm { .. }))
3838            .map(|s| (s.id, s.line, s.column, s.text))
3839            .collect();
3840        // Neither a catch-all arm in the middle nor an arm with an attribute; and no arm
3841        // at all when the last one is a constant or binds only part of the values.
3842        assert_eq!(
3843            arms,
3844            [
3845                // After the two replaced bodies of a function that returns `u8`.
3846                (9, 2, 23, "1 => ..".to_string()),
3847                (10, 2, 39, "2 => ..".to_string()),
3848                (11, 6, 9, "1 => ..".to_string()),
3849            ]
3850        );
3851    }
3852
3853    #[test]
3854    fn offsets_around_inserted_text() {
3855        let src = "fn f(a: u8) -> bool { a > 1 }";
3856        let sites = found(src, 0).unwrap().sites;
3857        let out = render(src, &sites, &all);
3858        let start = sites[0].start;
3859        // `a` is copied right after the opening text of the probe: the last inserted
3860        // character before it still maps to the point of insertion.
3861        let copied_a = out.text.find("a), &(").unwrap();
3862        assert_eq!(out.to_original(copied_a), start);
3863        assert_eq!(out.to_original(copied_a - 1), start);
3864        assert_eq!(out.to_original(copied_a + 1), start + 1);
3865        // Past the end is the end.
3866        assert_eq!(out.to_original(out.text.len() + 10), src.len());
3867
3868        // The probe of `b + 1` opens right after the replaced `..`: an error there is
3869        // inside `b + 1`, not in front of the `..`.
3870        let src = "fn f(a: usize, b: usize) { for _ in a..b + 1 {} }";
3871        let sites = discover(src, 0).unwrap().sites;
3872        let out = render(src, &sites, &all);
3873        let inner_probe = out.text.find("(match (a, ").unwrap() + "(match (a, ".len();
3874        assert!(
3875            out.text[inner_probe..].starts_with("(match (b, 1)"),
3876            "{}",
3877            out.text
3878        );
3879        assert_eq!(out.to_original(inner_probe), src.find("b + 1").unwrap());
3880        let arith = sites
3881            .iter()
3882            .find(|s| matches!(s.kind, SiteKind::Arith { .. }))
3883            .unwrap();
3884        assert_eq!(
3885            blame(&sites, &all, out.to_original(inner_probe)),
3886            [arith.id]
3887        );
3888        // The text of a probe knows its site without going through the original.
3889        assert_eq!(out.inserted_by(inner_probe), Some(arith.id));
3890        assert_eq!(out.inserted_by(out.text.find("b, 1").unwrap()), None);
3891        // From its first to its last byte, and not one further.
3892        let opening = "(match (b, ";
3893        let (first, last) = (inner_probe, inner_probe + "(match (".len() - 1);
3894        assert!(out.text[inner_probe..].starts_with(opening));
3895        assert_eq!(out.inserted_by(first), Some(arith.id));
3896        assert_eq!(out.inserted_by(last), Some(arith.id));
3897        assert_eq!(out.inserted_by(last + 1), None);
3898        assert_eq!(out.inserted_by(0), None);
3899    }
3900    fn values(ty: &str) -> Vec<String> {
3901        let function: syn::ItemFn = syn::parse_str(&format!("fn f() -> {ty} {{ todo!() }}"))
3902            .unwrap_or_else(|e| panic!("{ty}: {e}"));
3903        body_values(&function.sig.output)
3904    }
3905
3906    /// The table of cargo-mutants (https://mutants.rs/mutants.html), row by row.
3907    #[test]
3908    fn replacement_values_by_return_type() {
3909        let rows: &[(&str, &[&str])] = &[
3910            ("()", &["()"]),
3911            ("i8", &["0", "1", "-1"]),
3912            ("isize", &["0", "1", "-1"]),
3913            ("i128", &["0", "1", "-1"]),
3914            ("u8", &["0", "1"]),
3915            ("usize", &["0", "1"]),
3916            ("u128", &["0", "1"]),
3917            ("f32", &["0.0", "1.0", "-1.0"]),
3918            ("f64", &["0.0", "1.0", "-1.0"]),
3919            ("bool", &["true", "false"]),
3920            (
3921                "NonZeroI32",
3922                &["1.try_into().unwrap()", "(-1).try_into().unwrap()"],
3923            ),
3924            ("std::num::NonZeroU8", &["1.try_into().unwrap()"]),
3925            ("NonZero<u64>", &["1.try_into().unwrap()"]),
3926            (
3927                "NonZero<i64>",
3928                &["1.try_into().unwrap()", "(-1).try_into().unwrap()"],
3929            ),
3930            ("String", &["String::new()", "\"xyzzy\".into()"]),
3931            ("&str", &["\"\"", "\"xyzzy\""]),
3932            ("&'static str", &["\"\"", "\"xyzzy\""]),
3933            // A `str` that can be written to is not a literal.
3934            ("&mut str", &["Box::leak(Box::new(Default::default()))"]),
3935            ("&u8", &["Box::leak(Box::new(0))", "Box::leak(Box::new(1))"]),
3936            (
3937                "&mut bool",
3938                &["Box::leak(Box::new(true))", "Box::leak(Box::new(false))"],
3939            ),
3940            (
3941                "&[u8]",
3942                &[
3943                    "Vec::leak(Vec::new())",
3944                    "Vec::leak(vec![0])",
3945                    "Vec::leak(vec![1])",
3946                ],
3947            ),
3948            (
3949                "&mut [bool]",
3950                &[
3951                    "Vec::leak(Vec::new())",
3952                    "Vec::leak(vec![true])",
3953                    "Vec::leak(vec![false])",
3954                ],
3955            ),
3956            ("Result<bool, Error>", &["Ok(true)", "Ok(false)"]),
3957            ("io::Result<()>", &["Ok(())"]),
3958            // Without arguments it is an alias: `fmt::Result`, or the crate's own.
3959            ("fmt::Result", &["Ok(Default::default())"]),
3960            ("Result", &["Ok(Default::default())"]),
3961            ("Option<u8>", &["None", "Some(0)", "Some(1)"]),
3962            ("Vec<bool>", &["vec![]", "vec![true]", "vec![false]"]),
3963            ("Box<u8>", &["Box::new(0)", "Box::new(1)"]),
3964            (
3965                "std::rc::Rc<u8>",
3966                &["std::rc::Rc::new(0)", "std::rc::Rc::new(1)"],
3967            ),
3968            ("Arc<bool>", &["Arc::new(true)", "Arc::new(false)"]),
3969            ("RefCell<()>", &["RefCell::new(())"]),
3970            ("Mutex<()>", &["Mutex::new(())"]),
3971            ("Cell<()>", &["Cell::new(())"]),
3972            (
3973                "HashSet<u8>",
3974                &[
3975                    "HashSet::new()",
3976                    "HashSet::from_iter([0])",
3977                    "HashSet::from_iter([1])",
3978                ],
3979            ),
3980            (
3981                "BTreeSet<()>",
3982                &["BTreeSet::new()", "BTreeSet::from_iter([()])"],
3983            ),
3984            (
3985                "BinaryHeap<()>",
3986                &["BinaryHeap::new()", "BinaryHeap::from_iter([()])"],
3987            ),
3988            (
3989                "LinkedList<()>",
3990                &["LinkedList::new()", "LinkedList::from_iter([()])"],
3991            ),
3992            (
3993                "VecDeque<()>",
3994                &["VecDeque::new()", "VecDeque::from_iter([()])"],
3995            ),
3996            (
3997                "HashMap<bool, u8>",
3998                &[
3999                    "HashMap::new()",
4000                    "HashMap::from_iter([(true, 0)])",
4001                    "HashMap::from_iter([(true, 1)])",
4002                    "HashMap::from_iter([(false, 0)])",
4003                    "HashMap::from_iter([(false, 1)])",
4004                ],
4005            ),
4006            (
4007                "std::collections::BTreeMap<(), ()>",
4008                &[
4009                    "std::collections::BTreeMap::new()",
4010                    "std::collections::BTreeMap::from_iter([((), ())])",
4011                ],
4012            ),
4013            (
4014                "Cow<'a, str>",
4015                &[
4016                    "Cow::Borrowed(\"\")",
4017                    "Cow::Owned(\"\".to_owned())",
4018                    "Cow::Borrowed(\"xyzzy\")",
4019                    "Cow::Owned(\"xyzzy\".to_owned())",
4020                ],
4021            ),
4022            ("[u8; 4]", &["[0; 4]", "[1; 4]"]),
4023            ("[bool; N + 1]", &["[true; N + 1]", "[false; N + 1]"]),
4024            (
4025                "(u8, bool)",
4026                &["(0, true)", "(0, false)", "(1, true)", "(1, false)"],
4027            ),
4028            ("(bool,)", &["(true,)", "(false,)"]),
4029            ("HttpResponse", &["HttpResponse::Ok().finish()"]),
4030            (
4031                "actix_web::HttpResponse",
4032                &["actix_web::HttpResponse::Ok().finish()"],
4033            ),
4034            ("Config", &["Default::default()"]),
4035            ("Self", &["Default::default()"]),
4036            ("<T as Tr>::Out", &["Default::default()"]),
4037            // Not the `String` everyone knows.
4038            ("<T as Tr>::String", &["Default::default()"]),
4039            ("<T>::bool", &["Default::default()"]),
4040            ("fn(u8) -> u8", &["Default::default()"]),
4041            ("*const u8", &["Default::default()"]),
4042            // Nested: every value of the inner type, wrapped.
4043            (
4044                "Result<Option<String>, E>",
4045                &[
4046                    "Ok(None)",
4047                    "Ok(Some(String::new()))",
4048                    "Ok(Some(\"xyzzy\".into()))",
4049                ],
4050            ),
4051            ("(Vec<()>)", &["vec![]", "vec![()]"]),
4052            ("Option<Config>", &["None", "Some(Default::default())"]),
4053            // Nothing can be returned in place of these.
4054            ("!", &[]),
4055            ("impl Iterator<Item = u8>", &[]),
4056            ("Box<impl Fn()>", &[]),
4057            ("Option<!>", &["None"]),
4058        ];
4059        for (ty, expected) in rows {
4060            assert_eq!(values(ty), *expected, "{ty}");
4061        }
4062        // No return type at all is `()`.
4063        let unit: syn::ItemFn = syn::parse_str("fn f() {}").unwrap();
4064        assert_eq!(body_values(&unit.sig.output), ["()"]);
4065    }
4066
4067    #[test]
4068    fn which_functions_get_their_body_replaced() {
4069        let src = r#"
4070            fn plain(a: u8) -> u8 { a + 1 }
4071            fn already(a: u8) -> bool { let _ = a; true }
4072            fn sole() -> bool { true }
4073            fn spaced() -> (u8, bool) { ( 0 , true ) }
4074            unsafe fn raw(a: u8) -> u8 { a }
4075            fn empty() {}
4076            fn one_call(s: &mut S) { s.go(); }
4077            fn two_calls(s: &mut S) { s.go(); s.stop(); }
4078            fn typed(s: &mut S) -> u8 { s.exit(); }
4079            fn tight() -> bool {true}
4080            #[rustfmt::skip]
4081            fn formatted(a: u8) -> u8 { a + 6 }
4082            #[mutants::timeout(5)]
4083            fn slow(a: u8) -> u8 { a + 7 }
4084            impl S { #[mutants::skip] fn marked_method(&self, a: u8) -> u8 { a + 8 } }
4085            trait U { #[mutants::skip] fn marked_default(&self, a: u8) -> u8 { a + 9 } }
4086            fn one_let(a: u8) { let _ = a; }
4087            fn never() -> ! { loop {} }
4088            fn hidden() -> impl Sized { 1 }
4089            #[mutants::skip]
4090            fn marked(a: u8) -> u8 { a + 2 }
4091            #[cfg_attr(test, mutants::skip)]
4092            fn marked_in_tests(a: u8) -> u8 { a + 3 }
4093            #[mutants::skip]
4094            impl S { fn method(&self, a: u8) -> u8 { a + 4 } }
4095            #[mutants::skip]
4096            mod generated { fn inner(a: u8) -> u8 { a + 5 } }
4097            trait T { fn required(&self) -> u8; fn provided(&self) -> u8 { 7 } }
4098            async fn later() -> u8 { 9 }
4099        "#;
4100        let sites = discover(src, 0).unwrap().sites;
4101        let bodies: Vec<String> = sites
4102            .iter()
4103            .filter_map(|s| match &s.kind {
4104                SiteKind::Body { name, value, .. } => Some(format!("{name} {value}")),
4105                _ => None,
4106            })
4107            .collect();
4108        assert_eq!(
4109            bodies,
4110            [
4111                "plain 0",
4112                "plain 1",
4113                "already true",
4114                "already false",
4115                // The body is this value already, however it is spaced.
4116                "sole false",
4117                "spaced (0, false)",
4118                "spaced (1, true)",
4119                "spaced (1, false)",
4120                // One statement that can be deleted is the same mutant as no body.
4121                "two_calls ()",
4122                // With a result to return, one statement is not the whole of it.
4123                "typed 0",
4124                "typed 1",
4125                "tight false",
4126                // Other attributes with `skip` or `mutants` in them do not mark anything.
4127                "formatted 0",
4128                "formatted 1",
4129                "slow 0",
4130                "slow 1",
4131                "one_let ()",
4132                "provided 0",
4133                "provided 1",
4134                "later 0",
4135                "later 1",
4136            ]
4137        );
4138        // Nothing at all is mutated in what is marked to be skipped.
4139        let texts: Vec<&str> = sites.iter().map(|s| s.text.as_str()).collect();
4140        for skipped in ["a + 2", "a + 3", "a + 4", "a + 5", "a + 8", "a + 9"] {
4141            assert!(!texts.contains(&skipped), "{skipped}");
4142        }
4143        for mutated in ["a + 1", "a + 6", "a + 7"] {
4144            assert!(texts.contains(&mutated), "{mutated}");
4145        }
4146        let unsafe_sites: Vec<&Site> = sites.iter().filter(|s| s.text.contains("raw")).collect();
4147        assert!(unsafe_sites.is_empty(), "{unsafe_sites:?}");
4148
4149        let body = sites
4150            .iter()
4151            .find(|s| matches!(s.kind, SiteKind::Body { .. }))
4152            .unwrap();
4153        assert_eq!(
4154            (body.line, body.column, body.text.as_str()),
4155            (2, 13, "fn plain(a: u8) -> u8")
4156        );
4157        let out = render(src, &sites, &all).text;
4158        syn::parse_file(&out).expect("instrumented source parses");
4159        assert_eq!(out.lines().count(), src.lines().count());
4160        assert!(
4161            out.contains(
4162                "fn plain(a: u8) -> u8 { if !crate::__tmt_rt::live(0u32) { return 0; } \
4163                 if !crate::__tmt_rt::live(1u32) { return 1; } (match (a, 1)"
4164            ),
4165            "{out}"
4166        );
4167        // A body that is exactly its expression: the function-level probes go around
4168        // the probe of the expression.
4169        let tight = "fn f(a: u8, b: u8) -> bool {a > b}";
4170        let sites = discover(tight, 0).unwrap().sites;
4171        let out = render(tight, &sites, &all).text;
4172        syn::parse_file(&out).expect("instrumented source parses");
4173        assert!(
4174            out.starts_with(
4175                "fn f(a: u8, b: u8) -> bool { let __tmt_v: bool = { \
4176                 if !crate::__tmt_rt::live(1u32) { return true; } \
4177                 if !crate::__tmt_rt::live(2u32) { return false; }(match (&(a), &(b))"
4178            ),
4179            "{out}"
4180        );
4181        assert!(
4182            out.ends_with(" })}; crate::__tmt_rt::ret(0u32, __tmt_v) }"),
4183            "{out}"
4184        );
4185    }
4186
4187    #[test]
4188    fn minus_guards_and_fields() {
4189        let src = r#"
4190            fn f(x: i32, y: f64, k: Kind, base: Options) -> Options {
4191                let a = -x + -5 - -0 + (-0.0 * -y) as i32;
4192                let b = match k {
4193                    Kind::A(n) if n > 1 => 1,
4194                    Kind::A(n) if let Some(m) = half(n) => m,
4195                    Kind::B if x > 0 && let Some(m) = half(x) => m,
4196                    #[cfg(any())]
4197                    Kind::B if x > 2 => 2,
4198                    Kind::B => 3,
4199                };
4200                let c = match b { n if n > 3 => 1, _ => 0 };
4201                let first = Options { depth: a, name, ..base };
4202                let second = Options { depth: -b, ..Default::default() };
4203                let third = Wrap::<u8> { 0: c, ..Wrap::new() };
4204                let _ = Options { depth: 1, ..base.clone() };
4205                let _ = Options { depth: 2, ..make(3) };
4206                let _ = Options { depth: 6, ..(pick())() };
4207                let _ = -2.5 + y;
4208                let _ = Options { #[cfg(any())] depth: 4, strict: true, ..*other };
4209                let _ = Options { depth: 5, name: n, strict: false };
4210                first
4211            }
4212        "#;
4213        let sites = found(src, 0).unwrap().sites;
4214        let kinds: Vec<String> = sites
4215            .iter()
4216            .filter_map(|s| match &s.kind {
4217                SiteKind::Neg {
4218                    operand, literal, ..
4219                } => Some(format!("neg {} | {operand} | literal={literal}", s.text)),
4220                SiteKind::Guard { can_be_false } => {
4221                    Some(format!("guard {} | can_be_false={can_be_false}", s.text))
4222                }
4223                SiteKind::Field {
4224                    name,
4225                    shorthand,
4226                    from_base: Some(from_base),
4227                    ..
4228                } => Some(format!(
4229                    "field {} | {name} | shorthand={shorthand} | {from_base}",
4230                    s.text
4231                )),
4232                _ => None,
4233            })
4234            .collect();
4235        assert_eq!(
4236            kinds,
4237            [
4238                "neg -x | x | literal=false",
4239                "neg -5 | 5 | literal=true",
4240                // `-0` is 0 either way; `-0.0` is not `0.0`.
4241                "neg -0.0 | 0.0 | literal=true",
4242                "neg -y | y | literal=false",
4243                // No catch-all arm: the arm cannot be removed, so `false` is a mutant.
4244                "guard n > 1 | can_be_false=true",
4245                // Where the arm can be removed, that is the guard being `false`.
4246                "guard n > 3 | can_be_false=false",
4247                "field depth: a | depth | shorthand=false | (base).depth",
4248                "field name | name | shorthand=true | (base).name",
4249                "field depth: -b | depth | shorthand=false | (Options { ..Default::default() }).depth",
4250                "neg -b | b | literal=false",
4251                "field 0: c | 0 | shorthand=false | (Wrap::<u8> { ..Wrap::new() }).0",
4252                "neg -2.5 | 2.5 | literal=true",
4253                // Not with a base that has arguments, a receiver or a computed function,
4254                // not a field with an attribute, and not without a base.
4255                "field strict: true | strict | shorthand=false | (*other).strict",
4256            ]
4257        );
4258        // A field is reported where its name stands.
4259        let field = sites
4260            .iter()
4261            .find(|s| s.text == "depth: a")
4262            .expect("the field is a site");
4263        let line = src.lines().nth(field.line - 1).unwrap();
4264        assert_eq!(line.find("depth: a"), Some(field.column - 1), "{line}");
4265        assert_eq!(&src[field.start..field.end], "a");
4266        let out = render(src, &sites, &all).text;
4267        syn::parse_file(&out).expect("instrumented source parses");
4268        assert_eq!(out.lines().count(), src.lines().count());
4269        for expected in [
4270            // The operand is evaluated once, outside the names of the probe.
4271            "(match (x) { __tmt_a => if crate::__tmt_rt::live(",
4272            // A literal stays a literal, with the type its place gives it.
4273            "u32) { -__tmt_a } else { __tmt_a } })",
4274            "u32) { -5 } else { 5 })",
4275            // A guard and the comparison it consists of: the guard goes around.
4276            "Kind::A(n) if crate::__tmt_rt::ret(",
4277            "u32, (match (&(n), &(1))",
4278            "n if crate::__tmt_rt::arm(",
4279            ") && (crate::__tmt_rt::ret(",
4280            "depth: if crate::__tmt_rt::live(",
4281            "{ a } else { (base).depth }",
4282            // A field written by its name alone gets the name back.
4283            "name: if crate::__tmt_rt::live(",
4284            "{ name } else { (base).name }, ..base }",
4285            "} else { (Options { ..Default::default() }).depth }, ..Default::default() }",
4286            "0: if crate::__tmt_rt::live(",
4287            "Options { depth: 1, ..base.clone() }",
4288            "Options { depth: 2, ..make(3) }",
4289            "Options { depth: 6, ..(pick())() }",
4290            "Options { depth: 5, name: n, strict: false }",
4291        ] {
4292            assert!(out.contains(expected), "{expected}\n{out}");
4293        }
4294        assert!(
4295            !out.contains("{ -0 }") && out.contains("{ -0.0 } else { 0.0 }"),
4296            "{out}"
4297        );
4298    }
4299    /// The source with each mutant of each site applied, as `what -> into: text`.
4300    fn mutated(src: &str, sites: &[Site]) -> Vec<String> {
4301        sites
4302            .iter()
4303            .flat_map(|site| {
4304                source_mutants(site).into_iter().map(|m| {
4305                    let text = format!("{}{}{}", &src[..m.start], m.replacement, &src[m.end..]);
4306                    syn::parse_file(&text).unwrap_or_else(|e| panic!("{text}: {e}"));
4307                    format!("{} -> {}: {}", m.what, m.into, text.trim())
4308                })
4309            })
4310            .collect()
4311    }
4312
4313    #[test]
4314    fn what_cannot_be_probed_is_mutated_in_the_source() {
4315        // Everything in a `const fn`, a compound assignment to more than a variable,
4316        // and the body of a function that returns an iterator.
4317        let src = "const fn c(a: u8, b: u8) -> bool { a < b }\n\
4318                   fn f(m: &mut Map, k: u8) { *m.entry(k).or_insert(0) += 1; m.total -= 1; }\n\
4319                   fn evens(n: u8) -> impl Iterator<Item = u8> + '_ { (0..n).step_by(2) }\n\
4320                   impl S { const fn k(&self) -> u8 { -self.0 } }\n\
4321                   trait T { const fn d(a: u8) -> u8 { a } }\n";
4322        let found = discover(src, 0).unwrap();
4323        assert!(found.rebuild_sites.iter().all(|s| s.id == NO_ID));
4324        let places: Vec<(usize, usize, &str)> = found
4325            .rebuild_sites
4326            .iter()
4327            .filter(|s| !matches!(s.kind, SiteKind::Return { .. }))
4328            .map(|s| (s.line, s.column, s.text.as_str()))
4329            .collect();
4330        assert_eq!(
4331            places,
4332            [
4333                (1, 1, "const fn c(a: u8, b: u8) -> bool"),
4334                (1, 1, "const fn c(a: u8, b: u8) -> bool"),
4335                (1, 36, "a < b"),
4336                (2, 28, "*m.entry(k).or_insert(0) += 1"),
4337                (3, 1, "fn evens(n: u8) -> impl Iterator<Item = u8> + '_"),
4338                (3, 1, "fn evens(n: u8) -> impl Iterator<Item = u8> + '_"),
4339                (3, 1, "fn evens(n: u8) -> impl Iterator<Item = u8> + '_"),
4340                // A range that is not run through by a `for`.
4341                (3, 53, "0..n"),
4342                (4, 10, "const fn k(&self) -> u8"),
4343                (4, 10, "const fn k(&self) -> u8"),
4344                (4, 36, "-self.0"),
4345                (5, 11, "const fn d(a: u8) -> u8"),
4346                (5, 11, "const fn d(a: u8) -> u8"),
4347            ]
4348        );
4349        assert_eq!(
4350            found.sites.iter().map(|s| s.id).collect::<Vec<_>>(),
4351            (0..found.sites.len() as u32).collect::<Vec<_>>()
4352        );
4353        let numbered: Vec<&str> = found.sites.iter().map(|s| s.text.as_str()).collect();
4354        assert_eq!(
4355            numbered,
4356            [
4357                "fn f(m: &mut Map, k: u8)",
4358                "*m.entry(k).or_insert(0) += 1;",
4359                "m.total -= 1;",
4360                "m.total -= 1",
4361            ]
4362        );
4363        assert_eq!(
4364            mutated(src, &found.rebuild_sites)
4365                .iter()
4366                .map(|line| line.lines().next().unwrap().to_string())
4367                .take(5)
4368                .collect::<Vec<_>>(),
4369            [
4370                "body -> true: const fn c(a: u8, b: u8) -> bool { true }",
4371                "body -> false: const fn c(a: u8, b: u8) -> bool { false }",
4372                "< -> ==: const fn c(a: u8, b: u8) -> bool { a == b }",
4373                "< -> >: const fn c(a: u8, b: u8) -> bool { a > b }",
4374                "< -> <=: const fn c(a: u8, b: u8) -> bool { a <= b }",
4375            ]
4376        );
4377        let whats: Vec<String> = found
4378            .rebuild_sites
4379            .iter()
4380            .flat_map(|site| {
4381                source_mutants(site)
4382                    .into_iter()
4383                    .map(|m| format!("{}: {} -> {}", site.text, m.what, m.into))
4384            })
4385            .skip(5)
4386            .collect();
4387        assert_eq!(
4388            whats,
4389            [
4390                "*m.entry(k).or_insert(0) += 1: += -> -=",
4391                "*m.entry(k).or_insert(0) += 1: += -> *=",
4392                "fn evens(n: u8) -> impl Iterator<Item = u8> + '_: body -> ::core::iter::empty()",
4393                "fn evens(n: u8) -> impl Iterator<Item = u8> + '_: body -> ::core::iter::once(0)",
4394                "fn evens(n: u8) -> impl Iterator<Item = u8> + '_: body -> ::core::iter::once(1)",
4395                "0..n: .. -> ..=",
4396                "const fn k(&self) -> u8: body -> 0",
4397                "const fn k(&self) -> u8: body -> 1",
4398                "-self.0: - -> ",
4399                "const fn d(a: u8) -> u8: body -> 0",
4400                "const fn d(a: u8) -> u8: body -> 1",
4401            ]
4402        );
4403    }
4404
4405    #[test]
4406    fn fields_are_removed_from_arbitrary_struct_updates() {
4407        // Full-strength table from fields.pict.
4408        for base in ["base", "make(seed)", "builder.make(seed)"] {
4409            for field in ["value: 9", "value"] {
4410                for attribute in ["", "#[cfg(any())] "] {
4411                    let original =
4412                        format!("fn f() -> S {{ S {{ {attribute}{field}, other: 2, ..{base} }} }}");
4413                    let found = discover(&original, 0).unwrap();
4414                    let fields: Vec<_> = found
4415                        .sites
4416                        .iter()
4417                        .chain(&found.rebuild_sites)
4418                        .flat_map(source_mutants)
4419                        .filter(|mutant| mutant.what == "field" && mutant.into == "value")
4420                        .collect();
4421                    if attribute.is_empty() {
4422                        assert_eq!(fields.len(), 1, "{original}");
4423                        let m = &fields[0];
4424                        let changed = format!(
4425                            "{}{}{}",
4426                            &original[..m.start],
4427                            m.replacement,
4428                            &original[m.end..]
4429                        );
4430                        assert_eq!(
4431                            changed,
4432                            format!("fn f() -> S {{ S {{  other: 2, ..{base} }} }}")
4433                        );
4434                        syn::parse_file(&changed).unwrap();
4435                    } else {
4436                        assert!(fields.is_empty(), "{original}");
4437                    }
4438                }
4439            }
4440        }
4441        let plain = discover("fn plain() -> S { S { value: 9 } }", 0).unwrap();
4442        assert!(
4443            plain
4444                .sites
4445                .iter()
4446                .chain(&plain.rebuild_sites)
4447                .flat_map(source_mutants)
4448                .all(|m| m.what != "field")
4449        );
4450    }
4451
4452    #[test]
4453    fn unknown_wrappers_and_nested_iterators_have_source_body_candidates() {
4454        // Full-strength table from generics.pict.
4455        for outer in ["Wrapper", "Option", "Result"] {
4456            for inner in ["bool", "impl Iterator<Item = u8>"] {
4457                for error in [false, true] {
4458                    let error_values: &[&str] = if error { &["7"] } else { &[] };
4459                    let extra = if outer == "Result" { ", u8" } else { "" };
4460                    let source = format!("fn f() -> {outer}<{inner}{extra}> {{ todo!() }}");
4461                    let found = discover_with_errors(&source, 0, error_values).unwrap();
4462                    let values: Vec<&str> = found
4463                        .sites
4464                        .iter()
4465                        .chain(&found.rebuild_sites)
4466                        .filter_map(|site| match &site.kind {
4467                            SiteKind::Body { value, .. } => Some(value.as_str()),
4468                            _ => None,
4469                        })
4470                        .collect();
4471                    let example = match (outer, inner) {
4472                        ("Wrapper", "bool") => "Wrapper::from_iter([false])",
4473                        ("Option", "bool") => "Some(false)",
4474                        ("Result", "bool") => "Ok(false)",
4475                        ("Wrapper", _) => "Wrapper::new(::core::iter::once(1))",
4476                        ("Option", _) => "Some(::core::iter::once(1))",
4477                        ("Result", _) => "Ok(::core::iter::once(1))",
4478                        _ => unreachable!(),
4479                    };
4480                    assert!(values.contains(&example), "{source}: {values:?}");
4481                    assert_eq!(
4482                        values.contains(&"Err(7)"),
4483                        outer == "Result" && error,
4484                        "{source}"
4485                    );
4486                    if inner != "bool" {
4487                        assert!(found.sites.is_empty(), "{source}");
4488                    }
4489                }
4490            }
4491        }
4492    }
4493
4494    #[test]
4495    fn source_deletes_the_whole_statement_and_the_unguarded_arm() {
4496        let source = "fn clear(v: &mut Vec<u8>) { v.clear(); }\n\
4497            fn select(x: u8) -> u8 { match x { 0 => 4, #[allow(unused)] 1 => 5, _ => 6 } }";
4498        let found = discover(source, 0).unwrap();
4499        let removals: Vec<_> = found
4500            .sites
4501            .iter()
4502            .chain(&found.rebuild_sites)
4503            .flat_map(source_mutants)
4504            .filter(|mutant| mutant.replacement.is_empty())
4505            .map(|mutant| &source[mutant.start..mutant.end])
4506            .collect();
4507        assert!(removals.contains(&"v.clear();"), "{removals:?}");
4508        assert!(removals.contains(&"0 => 4,"), "{removals:?}");
4509        assert!(
4510            removals.contains(&"#[allow(unused)] 1 => 5,"),
4511            "{removals:?}"
4512        );
4513    }
4514
4515    #[test]
4516    fn source_mutants_of_every_kind() {
4517        let src = "fn f(a: i32, b: i32, k: K, base: O) -> O { \
4518                   let x = match k { K::A(n) if n >= 1 => !(a != b) || a <= -b, K::B => a % b > 0 && a == b, _ => false }; \
4519                   O { on: x, a, ..base } }";
4520        let sites = found(src, 0).unwrap().sites;
4521        // Every one of them is still a source file.
4522        assert_eq!(mutated(src, &sites).len(), 18);
4523        let changes: Vec<String> = sites
4524            .iter()
4525            .flat_map(source_mutants)
4526            .map(|m| {
4527                format!(
4528                    "{} -> {} | `{}` becomes `{}`",
4529                    m.what,
4530                    m.into,
4531                    &src[m.start..m.end],
4532                    m.replacement
4533                )
4534            })
4535            .collect();
4536        assert_eq!(
4537            changes,
4538            [
4539                // A guarded arm uses a false guard, and an unguarded arm is removed.
4540                "arm -> K::A(n) if n >= 1 | `n >= 1` becomes `false`",
4541                "arm -> K::B | `K::B => a % b > 0 && a == b,` becomes ``",
4542                "guard -> true | `n >= 1` becomes `true`",
4543                ">= -> < | ` >= ` becomes ` < `",
4544                "|| -> && | `!(a != b) || a <= -b` becomes `(!(a != b)) && (a <= -b)`",
4545                "! ->  | `!` becomes ``",
4546                "!= -> == | ` != ` becomes ` == `",
4547                "<= -> > | ` <= ` becomes ` > `",
4548                "- ->  | `-` becomes ``",
4549                "&& -> || | `a % b > 0 && a == b` becomes `(a % b > 0 || a == b)`",
4550                "> -> == | ` > ` becomes ` == `",
4551                "> -> < | ` > ` becomes ` < `",
4552                "> -> >= | ` > ` becomes ` >= `",
4553                "% -> / | ` % ` becomes ` / `",
4554                "% -> + | `a % b` becomes `(a + b)`",
4555                "== -> != | ` == ` becomes ` != `",
4556                "field -> on | `on: x,` becomes ``",
4557                "field -> a | `a,` becomes ``",
4558            ]
4559        );
4560        // What exists only as a probe has no mutant of the source.
4561        let src = "fn f(a: u8, b: u8) -> bool { g(); for _ in a..b {} a.max(b) > 1 }";
4562        let sites = discover(src, 0).unwrap().sites;
4563        for site in &sites {
4564            let none = matches!(site.kind, SiteKind::Return { .. } | SiteKind::MinMax { .. });
4565            assert_eq!(source_mutants(site).is_empty(), none, "{:?}", site.kind);
4566        }
4567        // A range has its end taken in or left out, whichever it is not.
4568        let ends = |src: &str| -> Vec<String> {
4569            discover(src, 0)
4570                .unwrap()
4571                .sites
4572                .iter()
4573                .filter(|site| matches!(site.kind, SiteKind::Range { .. }))
4574                .flat_map(source_mutants)
4575                .map(|m| format!("{}{}{}", &src[..m.start], m.replacement, &src[m.end..]))
4576                .collect()
4577        };
4578        assert_eq!(
4579            ends("fn f(a: u8, b: u8) { for _ in a..b {} }"),
4580            ["fn f(a: u8, b: u8) { for _ in a..=b {} }"]
4581        );
4582        assert_eq!(
4583            ends("fn f(a: u8, b: u8) { for _ in a ..= b {} }"),
4584            ["fn f(a: u8, b: u8) { for _ in a..b {} }"]
4585        );
4586    }
4587
4588    #[test]
4589    fn iterators_to_return_instead() {
4590        let values = |ty: &str| {
4591            let function: syn::ItemFn =
4592                syn::parse_str(&format!("fn f() -> {ty} {{ todo!() }}")).unwrap();
4593            iterator_values(&function.sig.output)
4594        };
4595        assert_eq!(
4596            values("impl Iterator<Item = bool>"),
4597            [
4598                "::core::iter::empty()",
4599                "::core::iter::once(true)",
4600                "::core::iter::once(false)"
4601            ]
4602        );
4603        assert_eq!(
4604            values("impl std::iter::Iterator<Item = String> + Send + 'a").len(),
4605            3
4606        );
4607        // The item is the binding called `Item`, wherever it stands.
4608        assert_eq!(
4609            values("impl Iterator<Extra = u8, Item = ()>"),
4610            ["::core::iter::empty()", "::core::iter::once(())"]
4611        );
4612        // An item that is itself opaque has no value to make up.
4613        assert_eq!(
4614            values("impl Iterator<Item = impl Sized>"),
4615            ["::core::iter::empty()"]
4616        );
4617        for other in [
4618            "impl Sized",
4619            "impl Iterator",
4620            "impl IntoIterator<Item = u8>",
4621            "Box<dyn Iterator<Item = u8>>",
4622            "u8",
4623            "()",
4624        ] {
4625            assert!(values(other).is_empty(), "{other}");
4626        }
4627        let unit: syn::ItemFn = syn::parse_str("fn f() {}").unwrap();
4628        assert!(iterator_values(&unit.sig.output).is_empty());
4629    }
4630
4631    /// The source with each mutant of its sites that are built, one after the other.
4632    fn built(src: &str) -> Vec<String> {
4633        let found = discover(src, 0).unwrap();
4634        found
4635            .rebuild_sites
4636            .iter()
4637            .flat_map(source_mutants)
4638            .map(|m| format!("{}{}{}", &src[..m.start], m.replacement, &src[m.end..]))
4639            .collect()
4640    }
4641
4642    #[test]
4643    fn a_body_that_is_written_as_the_value_and_one_that_only_computes() {
4644        let bodies = |src: &str| -> Vec<(String, bool)> {
4645            discover(src, 0)
4646                .unwrap()
4647                .sites
4648                .iter()
4649                .filter_map(|site| match &site.kind {
4650                    SiteKind::Body {
4651                        value, sole_expr, ..
4652                    } => Some((value.clone(), sole_expr.is_some())),
4653                    _ => None,
4654                })
4655                .collect()
4656        };
4657        let values = |src: &str| -> Vec<String> { bodies(src).into_iter().map(|b| b.0).collect() };
4658        // The value the body already is makes no mutant, however it is spaced.
4659        assert_eq!(values("fn t() -> bool { true }"), ["false"]);
4660        assert_eq!(values("fn n() -> u8 {  0  }"), ["1"]);
4661        assert_eq!(
4662            values("fn s() -> String { String :: new () }"),
4663            ["\"xyzzy\".into()"]
4664        );
4665        // White space inside a literal is not spacing: `" "` is not the empty string.
4666        assert_eq!(
4667            values("fn s() -> &'static str { \" \" }"),
4668            ["\"\"", "\"xyzzy\""]
4669        );
4670        // A body that only computes its value can be said at that expression; one
4671        // that calls, assigns or leaves early does more than give a value.
4672        for (body, only_computes) in [
4673            ("n > 0", true),
4674            ("!(self.limit < n) && n as u8 != 3", true),
4675            ("(n, 1).0 > *&n", true),
4676            ("self.push(n) > 0", false),
4677            ("next() > 0", false),
4678            ("matches!(n, 1)", false),
4679            ("(if n > 1 { n } else { 0 }) > 0", false),
4680            ("list[n] > 0", false),
4681            ("check(n)? > 0", false),
4682            ("(self.count += n) == ()", false),
4683            ("(self.count = n) == ()", false),
4684        ] {
4685            let src = format!("impl S {{ fn f(&mut self, n: usize) -> bool {{ {body} }} }}");
4686            let all = bodies(&src);
4687            assert_eq!(all.len(), 2, "{body}");
4688            assert!(all.iter().all(|b| b.1 == only_computes), "{body}: {all:?}");
4689        }
4690    }
4691
4692    #[test]
4693    fn items_are_named_by_what_is_around_them() {
4694        let src = "fn top(a: u8) -> u8 { fn inner(b: u8) -> u8 { b } inner(a) }\n\
4695                   mod m { pub fn in_mod() {} const K: u8 = 1; }\n\
4696                   impl Store { fn commit(&self) {} const LIMIT: u8 = 2; }\n\
4697                   impl<T> fmt::Display for Id<T> { fn fmt(&self) {} }\n\
4698                   trait Tr { fn provided(&self) {} fn required(&self); }\n\
4699                   static S: u8 = 3;\nlet";
4700        // Not a source file: nothing is named.
4701        assert!(named_items(src).is_empty());
4702        let src = src.strip_suffix("let").unwrap();
4703        let items = named_items(src);
4704        let names: Vec<&str> = items.iter().map(|item| item.name.as_str()).collect();
4705        assert_eq!(
4706            names,
4707            [
4708                "top",
4709                "top::inner",
4710                "m::in_mod",
4711                "m::K",
4712                "Store::commit",
4713                "Store::LIMIT",
4714                "<fmt::Display for Id<T>>::fmt",
4715                "Tr::provided",
4716                "Tr::required",
4717                "S",
4718            ]
4719        );
4720        // The innermost item a place is in; none between the items.
4721        let at = |text: &str| src.find(text).unwrap();
4722        assert_eq!(enclosing_item(&items, at("{ b }") + 2), "top::inner");
4723        assert_eq!(enclosing_item(&items, at("inner(a)")), "top");
4724        assert_eq!(enclosing_item(&items, at("fn top")), "top");
4725        assert_eq!(enclosing_item(&items, at("mod m")), "");
4726        assert_eq!(enclosing_item(&items, at("= 2") + 2), "Store::LIMIT");
4727        assert_eq!(enclosing_item(&items, src.len()), "");
4728        // An item is its first byte to its last, and not a byte more on either side.
4729        let (first, after) = (at("pub fn in_mod"), at("pub fn in_mod() {}") + 18);
4730        assert_eq!(enclosing_item(&items, first - 1), "");
4731        assert_eq!(enclosing_item(&items, first), "m::in_mod");
4732        assert_eq!(enclosing_item(&items, after - 1), "m::in_mod");
4733        assert_eq!(enclosing_item(&items, after), "");
4734        // Lines and columns count from one, columns in characters.
4735        let text = "ab\nçd e\n";
4736        assert_eq!(offset_of(text, 1, 1), Some(0));
4737        assert_eq!(offset_of(text, 1, 2), Some(1));
4738        assert_eq!(offset_of(text, 2, 1), Some(3));
4739        assert_eq!(offset_of(text, 2, 2), Some(5), "after the two bytes of `ç`");
4740        assert_eq!(offset_of(text, 2, 99), Some(text.len()));
4741        assert_eq!(offset_of(text, 0, 1), None);
4742        assert_eq!(offset_of(text, 1, 0), None);
4743    }
4744
4745    #[test]
4746    fn only_the_range_of_a_for_is_probed() {
4747        let src = "fn f(a: u8, b: u8, v: &[u8]) -> usize {\n\
4748                   for _ in a..b {}\n\
4749                   for _ in (a..=b) {}\n\
4750                   for _ in (a..b).rev() {}\n\
4751                   let kept = a..b;\n\
4752                   let _ = &v[a as usize..b as usize];\n\
4753                   for _ in kept.clone() {}\n\
4754                   for _ in 0..3 {}\n\
4755                   let _ = &v[0..3];\n\
4756                   (a..=b).count() }";
4757        let all = discover(src, 0).unwrap();
4758        let ranges = |sites: &[Site]| -> Vec<usize> {
4759            sites
4760                .iter()
4761                .filter(|site| matches!(site.kind, SiteKind::Range { .. }))
4762                .map(|site| site.line)
4763                .collect()
4764        };
4765        // Run through directly by a `for`, with or without parentheses.
4766        assert_eq!(ranges(&all.sites), [2, 3]);
4767        // Kept, indexed with, or given to a method: built, as the source says them.
4768        // And two literals wherever they are: nothing gives a probe their type.
4769        assert_eq!(ranges(&all.rebuild_sites), [4, 5, 6, 8, 9, 10]);
4770        let literal: Vec<(&str, String)> = all
4771            .rebuild_sites
4772            .iter()
4773            .filter(|site| site.line == 8 || site.line == 9)
4774            .flat_map(|site| {
4775                source_mutants(site)
4776                    .into_iter()
4777                    .map(move |mutant| (site.text.as_str(), mutant.replacement))
4778            })
4779            .collect();
4780        assert_eq!(
4781            literal,
4782            [("0..3", "..=".to_string()), ("0..3", "..=".to_string())]
4783        );
4784    }
4785
4786    #[test]
4787    fn what_marks_code_as_not_to_be_mutated() {
4788        let src = "#[allow(mutants, skip)] fn loosely(a: u8) -> u8 { a + 1 }\n\
4789                   #[doc = \"mutants skip\"] fn spoken_of(a: u8) -> u8 { a + 2 }\n\
4790                   #[mutants :: skip] fn spaced(a: u8) -> u8 { a + 3 }\n\
4791                   #[cfg_attr(test, mutants::skip)] fn conditional(a: u8) -> u8 { a + 4 }\n\
4792                   #[mutants::skip] mod generated;\n\
4793                   #[mutants::skip] #[path = \"gen/other.rs\"] mod other;\n\
4794                   mod plain;\n\
4795                   mod inline { fn inner(a: u8) -> u8 { a + 5 } }\n\
4796                   #[mutants::skip] mod marked { fn inner(a: u8) -> u8 { a + 6 } }\n";
4797        let all = discover(src, 0).unwrap();
4798        let texts: Vec<&str> = found_arith(&all.sites);
4799        assert_eq!(texts, ["a + 1", "a + 2", "a + 5"]);
4800        // The file of a marked module is not looked into either.
4801        assert_eq!(
4802            all.test_modules,
4803            [
4804                TestModule {
4805                    name: "generated".to_string(),
4806                    path: None
4807                },
4808                TestModule {
4809                    name: "other".to_string(),
4810                    path: Some("gen/other.rs".to_string())
4811                },
4812            ]
4813        );
4814    }
4815
4816    fn found_arith(sites: &[Site]) -> Vec<&str> {
4817        sites
4818            .iter()
4819            .filter(|site| matches!(site.kind, SiteKind::Arith { .. }))
4820            .map(|site| site.text.as_str())
4821            .collect()
4822    }
4823
4824    #[test]
4825    fn a_replaced_operator_keeps_its_operands() {
4826        // Every replacement is the same tree with another operator, also where the new
4827        // operator binds otherwise than the old one.
4828        assert_eq!(
4829            built("const X: i32 = 8 - 2 * 3;"),
4830            [
4831                "const X: i32 = 8 + 2 * 3;",
4832                "const X: i32 = (8) / (2 * 3);",
4833                "const X: i32 = 8 - 2 / 3;",
4834                "const X: i32 = 8 - (2 + 3);",
4835            ]
4836        );
4837        assert_eq!(
4838            built("const B: bool = P || Q && R;"),
4839            [
4840                "const B: bool = (P) && (Q && R);",
4841                "const B: bool = P || (Q || R);",
4842            ]
4843        );
4844        assert_eq!(
4845            built("const M: u8 = A & B | C;"),
4846            [
4847                "const M: u8 = (A & B) & (C);",
4848                "const M: u8 = (A & B) ^ (C);",
4849                "const M: u8 = (A | B) | C;",
4850                "const M: u8 = (A ^ B) | C;",
4851            ]
4852        );
4853        assert_eq!(
4854            built("const S: u8 = 1 << 2 + 1;"),
4855            [
4856                "const S: u8 = 1 >> 2 + 1;",
4857                "const S: u8 = 1 << 2 - 1;",
4858                "const S: u8 = 1 << (2) * (1);",
4859            ]
4860        );
4861        // Comparisons bind alike, and an assignment has its operands to itself.
4862        assert_eq!(
4863            built("const C: bool = A + 1 < B;")[..3],
4864            [
4865                "const C: bool = A + 1 == B;",
4866                "const C: bool = A + 1 > B;",
4867                "const C: bool = A + 1 <= B;",
4868            ]
4869        );
4870        let assigned = built("const fn f(mut x: u8) -> u8 { x += 2 * 3; x }");
4871        for expected in [
4872            "const fn f(mut x: u8) -> u8 { x -= 2 * 3; x }",
4873            "const fn f(mut x: u8) -> u8 { x *= 2 * 3; x }",
4874            "const fn f(mut x: u8) -> u8 { x += (2 + 3); x }",
4875        ] {
4876            assert!(assigned.iter().any(|text| text == expected), "{assigned:?}");
4877        }
4878    }
4879
4880    #[test]
4881    fn excluded_parent_items_do_not_contribute_const_sites() {
4882        let source = r#"
4883            #[cfg(test)] enum TestEnum { A = 1 + 2 }
4884            #[mutants::skip] struct Skip { a: [u8; 2 + 3] }
4885            #[cfg(test)] type Alias = [u8; 3 + 4];
4886            #[cfg(test)] union TestUnion { a: [u8; 4 + 5] }
4887            #[mutants::skip] trait Hidden { const DATA: [u8; 5 + 6]; }
4888            struct Data { #[cfg(test)] bytes: [u8; 6 + 7] }
4889            fn f() { #[cfg(test)] let _: [u8; 8 + 9] = [0; 17]; }
4890            const DATA: [u8; 7 + 8] = [0; 15];
4891        "#;
4892        let found = discover(source, 0).unwrap();
4893        let sites: Vec<_> = found
4894            .rebuild_sites
4895            .iter()
4896            .map(|site| site.text.as_str())
4897            .collect();
4898        assert_eq!(sites, ["7 + 8"]);
4899    }
4900
4901    #[test]
4902    fn compile_time_expressions_get_source_mutants_but_never_probes() {
4903        // Full strength-three table from const.pict.
4904        for (place, context) in [
4905            ("inline", "let _ = const { 6 * 7 };"),
4906            ("repeat", "let _ = [0u8; 6 * 7];"),
4907            ("type length", "let _: [u8; 6 * 7];"),
4908            ("discriminant", "enum Value { One = 6 * 7 }"),
4909            ("const argument", "let _: Items<{ 6 * 7 }>;"),
4910            ("const default", "struct Items<const N: usize = { 6 * 7 }>;"),
4911        ] {
4912            for qualifier in ["", "const "] {
4913                for marker in ["", "#[mutants::skip] "] {
4914                    let source =
4915                        format!("{marker}{qualifier}fn f(x: u32) -> u32 {{ {context} x * 2 }}");
4916                    let found = discover(&source, 0).unwrap();
4917                    let variants: Vec<_> = found
4918                        .rebuild_sites
4919                        .iter()
4920                        .filter(|site| site.text == "6 * 7")
4921                        .flat_map(source_mutants)
4922                        .map(|mutant| mutant.into)
4923                        .collect();
4924                    let expected: &[&str] = if marker.is_empty() { &["/", "+"] } else { &[] };
4925                    assert_eq!(variants, expected, "{place}: {source}");
4926                    assert!(
4927                        found.sites.iter().all(|site| site.text != "6 * 7"),
4928                        "{source}"
4929                    );
4930                    assert_eq!(
4931                        found.sites.iter().any(|site| site.text == "x * 2"),
4932                        marker.is_empty() && qualifier.is_empty(),
4933                        "{source}"
4934                    );
4935                }
4936            }
4937        }
4938    }
4939
4940    #[test]
4941    fn a_test_branch_or_skip_documentation_does_not_exclude_production_code() {
4942        let source = r#"
4943            /// The mutants::skip attribute is documented here.
4944            #[cfg(any(test, feature = "production"))]
4945            fn public(x: u32) -> u32 { x + 1 }
4946
4947            #[cfg(all(test, feature = "production"))]
4948            fn for_tests(x: u32) -> u32 { x + 2 }
4949
4950            #[cfg_attr(any(), mutants::skip)]
4951            fn skipped(x: u32) -> u32 { x + 3 }
4952        "#;
4953        let found = discover(source, 0).unwrap();
4954        let arithmetic: Vec<_> = found
4955            .sites
4956            .iter()
4957            .filter(|site| matches!(site.kind, SiteKind::Arith { .. }))
4958            .map(|site| site.text.as_str())
4959            .collect();
4960        assert_eq!(arithmetic, ["x + 1"]);
4961    }
4962
4963    #[test]
4964    fn constants_and_literal_arithmetic_are_mutated_in_the_source() {
4965        let src = "const HALF: u64 = SPAN / 2;\n\
4966                   static LIMIT: i32 = -(1 << 4);\n\
4967                   impl S { const K: bool = A < B; }\n\
4968                   trait T { const D: u8 = 3 + 4; const R: u8; }\n\
4969                   #[cfg(test)]\n\
4970                   const ONLY_IN_TESTS: u8 = 5 + 6;\n\
4971                   #[mutants::skip]\n\
4972                   const MARKED: u8 = 7 + 8;\n\
4973                   #[cfg(test)]\n\
4974                   static TEST_LIMIT: u8 = 9 + 1;\n\
4975                   impl S { #[mutants::skip] const SKIPPED: u8 = 9 + 2; }\n\
4976                   trait U { #[cfg(test)] const ONLY: u8 = 9 + 3; }\n\
4977                   fn f(x: u32) -> u32 { let _ = [0u8; 2 + 3]; x + 60 * 60 }\n\
4978                   fn one(s: &mut S) { s.go(); }\n\
4979                   fn two(s: &mut S) { s.go(); s.stop(); }\n\
4980                   fn value(s: &mut S) -> u8 { s.get() }\n";
4981        let found = discover(src, 0).unwrap();
4982        let built: Vec<String> = found
4983            .rebuild_sites
4984            .iter()
4985            .flat_map(|site| {
4986                source_mutants(site)
4987                    .into_iter()
4988                    .map(|m| format!("{}: {} -> {}", site.text, m.what, m.into))
4989            })
4990            .collect();
4991        assert_eq!(
4992            built,
4993            [
4994                "SPAN / 2: / -> *",
4995                "SPAN / 2: / -> %",
4996                "-(1 << 4): - -> ",
4997                "1 << 4: << -> >>",
4998                "A < B: < -> ==",
4999                "A < B: < -> >",
5000                "A < B: < -> <=",
5001                "3 + 4: + -> -",
5002                "3 + 4: + -> *",
5003                "2 + 3: + -> -",
5004                "2 + 3: + -> *",
5005                // Two literals in ordinary code too: a probe would give them a type.
5006                "60 * 60: * -> /",
5007                "60 * 60: * -> +",
5008            ]
5009        );
5010        mutated(src, &found.rebuild_sites);
5011        // The surrounding arithmetic is still probed.
5012        let probed: Vec<&str> = found
5013            .sites
5014            .iter()
5015            .filter(|s| matches!(s.kind, SiteKind::Arith { .. }))
5016            .map(|s| s.text.as_str())
5017            .collect();
5018        assert_eq!(probed, ["x + 60 * 60"]);
5019        // An empty body is not made where deleting the one statement is the same thing.
5020        assert_eq!(found.single_statement_bodies, ["one"]);
5021        let bodies: Vec<String> = found
5022            .sites
5023            .iter()
5024            .filter_map(|s| match &s.kind {
5025                SiteKind::Body { name, value, .. } => Some(format!("{name} {value}")),
5026                _ => None,
5027            })
5028            .collect();
5029        assert_eq!(bodies, ["f 0", "f 1", "two ()", "value 0", "value 1"]);
5030    }
5031    #[test]
5032    fn an_attribute_excludes_the_compile_time_expressions_of_what_it_is_on() {
5033        // `@` is where the attribute goes: without one the length is a mutant to build.
5034        for context in [
5035            "fn f() { @let _ = [0u8; 6 * 7]; }",
5036            "fn f() { let _ = @const { 6 * 7 }; }",
5037            "struct Items<@const N: usize = { 6 * 7 }>;",
5038            "@enum E { A = 6 * 7 }",
5039            "enum E { @A = 6 * 7 }",
5040            "enum E { @A([u8; 6 * 7]) }",
5041            "@struct S { a: [u8; 6 * 7] }",
5042            "struct S { @a: [u8; 6 * 7] }",
5043            "@union U { a: [u8; 6 * 7] }",
5044            "@trait T { const D: [u8; 6 * 7]; }",
5045            "trait T { @type A = [u8; 6 * 7]; }",
5046            "@type A = [u8; 6 * 7];",
5047            "impl T for S { @type A = [u8; 6 * 7]; }",
5048        ] {
5049            for attribute in ["", "#[mutants::skip] ", "#[cfg(test)] "] {
5050                let source = context.replace('@', attribute);
5051                let found = discover(&source, 0).unwrap();
5052                let expected: &[&str] = if attribute.is_empty() {
5053                    &["6 * 7"]
5054                } else {
5055                    &[]
5056                };
5057                assert_eq!(found_arith(&found.rebuild_sites), expected, "{source}");
5058                assert!(found_arith(&found.sites).is_empty(), "{source}");
5059            }
5060        }
5061        // On the file itself it excludes everything in it.
5062        for attribute in ["#![mutants::skip]", "#![cfg(test)]"] {
5063            let source =
5064                format!("{attribute}\nconst N: u8 = 6 * 7;\nfn f(a: u8) -> u8 {{ a + 1 }}");
5065            let found = discover(&source, 0).unwrap();
5066            assert!(found.sites.is_empty(), "{source}");
5067            assert!(found.rebuild_sites.is_empty(), "{source}");
5068        }
5069    }
5070
5071    #[test]
5072    fn compile_time_expressions_are_found_inside_types() {
5073        let built = |source: &str| -> Vec<String> {
5074            let found = discover(source, 0).unwrap();
5075            assert!(found_arith(&found.sites).is_empty(), "{source}");
5076            found_arith(&found.rebuild_sites)
5077                .into_iter()
5078                .map(str::to_string)
5079                .collect()
5080        };
5081        // The element of an array is a type with lengths of its own.
5082        assert_eq!(
5083            built("fn f() { let _: [[u8; 1 + 2]; 3 + 4]; }"),
5084            ["1 + 2", "3 + 4"]
5085        );
5086        // So is the type of a const parameter.
5087        assert_eq!(built("struct S<const N: [u8; 2 + 3]>;"), ["2 + 3"]);
5088        // A const argument is computed by the compiler whatever it consists of: it is
5089        // never probed.
5090        assert_eq!(built("fn f() { let _: Items<{ N + 1 }>; }"), ["N + 1"]);
5091    }
5092
5093    #[test]
5094    fn only_the_skip_mark_and_a_cfg_that_needs_test_exclude_code() {
5095        let src = "#[mutants] fn bare(a: u8) -> u8 { a + 1 }\n\
5096                   #[mutants::skip::deeper] fn longer(a: u8) -> u8 { a + 2 }\n\
5097                   #[cfg(all(test))] fn all_of_one(a: u8) -> u8 { a + 3 }\n\
5098                   #[cfg(not(not(test)))] fn twice_not(a: u8) -> u8 { a + 4 }\n\
5099                   #[cfg(not())] fn malformed(a: u8) -> u8 { a + 5 }\n\
5100                   #[labels(test)] fn labelled(a: u8) -> u8 { a + 6 }\n";
5101        let found = discover(src, 0).unwrap();
5102        assert_eq!(
5103            found_arith(&found.sites),
5104            ["a + 1", "a + 2", "a + 5", "a + 6"]
5105        );
5106    }
5107
5108    #[test]
5109    fn which_arms_are_probed_built_or_left_alone() {
5110        let src = "fn f(x: u8, k: Kind, c: bool, a: u8) -> u8 {\n\
5111                   \x20   let p = match x { 0 => 4, #[allow(unused)] 1 => 5, #[allow(unused)] 2 if c => 6, _ => 7 };\n\
5112                   \x20   let q = match k { Kind::A => 1, Kind::B => 2 };\n\
5113                   \x20   let r = match x { #[mutants::skip] 3 => a + 1, #[cfg(test)] 4 => a + 2, 5 => a + 3, _ => a + 4 };\n\
5114                   \x20   p + q + r\n\
5115                   }\n";
5116        let found = discover(src, 0).unwrap();
5117        let arms = |sites: &[Site]| -> Vec<String> {
5118            sites
5119                .iter()
5120                .filter(|site| matches!(site.kind, SiteKind::Arm { .. }))
5121                .map(|site| site.text.clone())
5122                .collect()
5123        };
5124        // Probed: an arm without attributes above a last arm that takes everything.
5125        assert_eq!(arms(&found.sites), ["0 => ..", "5 => .."]);
5126        // Built: an unguarded arm with an attribute, where a `_` arm keeps the match
5127        // exhaustive. Neither a guarded one, nor the `_` arm, nor an arm of a match
5128        // without `_`, nor one that is marked or only for tests.
5129        assert_eq!(arms(&found.rebuild_sites), ["1 => .."]);
5130        // What a marked or test-only arm does is not mutated either.
5131        let in_arms: Vec<&str> = found_arith(&found.sites)
5132            .into_iter()
5133            .filter(|text| text.starts_with("a + "))
5134            .collect();
5135        assert_eq!(in_arms, ["a + 3", "a + 4"]);
5136    }
5137
5138    #[test]
5139    fn which_fields_of_a_struct_update_are_probed_built_or_left_alone() {
5140        let src = "fn f(a: u8, base: S) {\n\
5141                   \x20   let _ = S { #[mutants::skip] v: a + 1, #[cfg(test)] w: a + 2, x: a + 3, ..base };\n\
5142                   \x20   g(#[mutants::skip] S { v: a + 4, ..base });\n\
5143                   \x20   g(#[cfg(test)] S { v: a + 5, ..base });\n\
5144                   \x20   g(#[allow(unused)] S { v: a + 6, ..base });\n\
5145                   \x20   g(<S as Tr>::Out { v: a + 7, ..base });\n\
5146                   }\n";
5147        let found = discover(src, 0).unwrap();
5148        let fields = |sites: &[Site]| -> Vec<String> {
5149            sites
5150                .iter()
5151                .filter_map(|site| match &site.kind {
5152                    SiteKind::Field { from_base, .. } => Some(format!(
5153                        "{} | {}",
5154                        site.text,
5155                        from_base.as_deref().unwrap_or("-")
5156                    )),
5157                    _ => None,
5158                })
5159                .collect()
5160        };
5161        // Probed: the field is read from the base instead.
5162        assert_eq!(fields(&found.sites), ["x: a + 3 | (base).x"]);
5163        // Built: an expression with an attribute or a qualified path is not written a
5164        // second time. Marked and test-only fields and expressions have no mutants.
5165        assert_eq!(
5166            fields(&found.rebuild_sites),
5167            ["v: a + 6 | -", "v: a + 7 | -"]
5168        );
5169        assert_eq!(found_arith(&found.sites), ["a + 3", "a + 6", "a + 7"]);
5170    }
5171
5172    #[test]
5173    fn body_values_that_are_only_built() {
5174        let bodies = |sites: &[Site]| -> Vec<String> {
5175            sites
5176                .iter()
5177                .filter_map(|site| match &site.kind {
5178                    SiteKind::Body { value, .. } => Some(value.clone()),
5179                    _ => None,
5180                })
5181                .collect()
5182        };
5183        // An unknown wrapper is probed with its default alone; its constructors are
5184        // guesses that have to compile, except the one the body already is.
5185        let found = discover("fn f() -> Wrapper<bool> { Wrapper::new() }", 0).unwrap();
5186        assert_eq!(bodies(&found.sites), ["Default::default()"]);
5187        assert_eq!(values("Wrapper<bool>"), ["Default::default()"]);
5188        assert_eq!(
5189            bodies(&found.rebuild_sites),
5190            [
5191                "Wrapper::from_iter([true])",
5192                "Wrapper::new(true)",
5193                "Wrapper::from(true)",
5194                "Wrapper::from_iter([false])",
5195                "Wrapper::new(false)",
5196                "Wrapper::from(false)",
5197            ]
5198        );
5199        // An opaque type anywhere in the return type leaves nothing to probe.
5200        assert!(values("(bool, impl Iterator<Item = u8>)").is_empty());
5201        // Iterators of iterators are built, and not offered to who asks for the
5202        // iterators to return.
5203        let nested = "impl Iterator<Item = impl Iterator<Item = u8>>";
5204        let found = discover(&format!("fn f() -> {nested} {{ todo!() }}"), 0).unwrap();
5205        assert!(bodies(&found.sites).is_empty());
5206        assert_eq!(
5207            bodies(&found.rebuild_sites),
5208            [
5209                "::core::iter::empty()",
5210                "::core::iter::once(::core::iter::empty())",
5211                "::core::iter::once(::core::iter::once(0))",
5212                "::core::iter::once(::core::iter::once(1))",
5213            ]
5214        );
5215        let function: syn::ItemFn =
5216            syn::parse_str(&format!("fn f() -> {nested} {{ todo!() }}")).unwrap();
5217        assert_eq!(
5218            iterator_values(&function.sig.output),
5219            ["::core::iter::empty()"]
5220        );
5221    }
5222}