Skip to main content

targeted_mutation/instrument/
source_mutants.rs

1//! Source-level mutant edits for rebuild and audit modes.
2
3use syn::spanned::Spanned;
4
5use crate::plan::CmpOp;
6
7use super::discover::written_bool;
8use super::model::{ArmGuard, Site, SiteKind};
9
10/// A mutant as a change of the source text: `replacement` in place of `start..end`.
11#[derive(Clone, PartialEq, Eq, Debug)]
12pub struct SourceMutant {
13    pub start: usize,
14    pub end: usize,
15    pub replacement: String,
16    /// What is replaced and by what, in the words of cargo-mutants: (`<`, `==`),
17    /// (`-`, ``) for a deleted minus, (`guard`, `true`), (`body`, `0`).
18    pub what: String,
19    pub into: String,
20}
21
22/// The mutants of a site as changes of the source, for the sites that are mutated by
23/// building them. The replacements of an operator are those of cargo-mutants. Sites that
24/// only exist as probes (a result replaced after the body ran, the other of `min` /
25/// `max`) have none.
26/// A strict/non-strict boundary replacement for runs without operand observations.
27pub(crate) fn source_boundary_mutant(site: &Site) -> Option<SourceMutant> {
28    let SiteKind::Cmp { op, gap, .. } = &site.kind else {
29        return None;
30    };
31    let replacement = match op {
32        CmpOp::Le => "<",
33        CmpOp::Ge => ">",
34        _ => return None,
35    };
36    Some(SourceMutant {
37        start: gap.0,
38        end: gap.1,
39        replacement: format!(" {replacement} "),
40        what: op.symbol().to_string(),
41        into: replacement.to_string(),
42    })
43}
44
45/// Gives each mutant the line ends of what it replaces: the lines after it are the lines
46/// they were, so `line!()` and the place of a panic say the same in the mutant.
47pub fn keep_line_ends(source: &str, mutants: &mut [SourceMutant]) {
48    for mutant in mutants {
49        let Some(replaced) = source.get(mutant.start..mutant.end) else {
50            continue;
51        };
52        let lines = replaced.matches('\n').count();
53        let kept = mutant.replacement.matches('\n').count();
54        mutant
55            .replacement
56            .push_str(&"\n".repeat(lines.saturating_sub(kept)));
57    }
58}
59
60pub fn source_mutants(site: &Site) -> Vec<SourceMutant> {
61    let change =
62        |start: usize, end: usize, replacement: String, what: &str, into: &str| SourceMutant {
63            start,
64            end,
65            replacement,
66            what: what.to_string(),
67            into: into.to_string(),
68        };
69    // A replacement that binds otherwise than the original keeps the operands it had:
70    // `2 * 3` in `8 - 2 * 3` becomes `(2 + 3)`, and `8 - 2 * 3` becomes `(8) / (2 * 3)`.
71    let operator = |gap: &(usize, usize), from: String, to: String, binds: std::cmp::Ordering| {
72        // The operands as they are written, on either side of the operator.
73        let operands = gap
74            .0
75            .checked_sub(site.start)
76            .zip(gap.1.checked_sub(site.start))
77            .and_then(|(left, right)| {
78                Some((
79                    site.text.get(..left)?.trim_end(),
80                    site.text.get(right..)?.trim_start(),
81                    // The line ends between the operands stay between them: each
82                    // operand is on the lines it was on.
83                    "\n".repeat(site.text.get(left..right)?.matches('\n').count()),
84                ))
85            });
86        match (binds, operands) {
87            (std::cmp::Ordering::Less, Some((left, right, lines))) => change(
88                site.start,
89                site.end,
90                format!("({left} {to} {lines}{right})"),
91                &from,
92                &to,
93            ),
94            (std::cmp::Ordering::Greater, Some((left, right, lines))) => change(
95                site.start,
96                site.end,
97                format!("({left}) {to} {lines}({right})"),
98                &from,
99                &to,
100            ),
101            _ => change(gap.0, gap.1, format!(" {to} "), &from, &to),
102        }
103    };
104    let same = std::cmp::Ordering::Equal;
105    match &site.kind {
106        SiteKind::Cmp { op, gap, .. } => {
107            let others: &[CmpOp] = match op {
108                CmpOp::Lt => &[CmpOp::Eq, CmpOp::Gt, CmpOp::Le],
109                CmpOp::Gt => &[CmpOp::Eq, CmpOp::Lt, CmpOp::Ge],
110                CmpOp::Le => &[CmpOp::Gt],
111                CmpOp::Ge => &[CmpOp::Lt],
112                CmpOp::Eq => &[CmpOp::Ne],
113                CmpOp::Ne => &[CmpOp::Eq],
114            };
115            others
116                .iter()
117                .map(|other| operator(gap, op.symbol().into(), other.symbol().into(), same))
118                .collect()
119        }
120        SiteKind::Logic { and, gap, .. } => {
121            // `&&` binds tighter than `||`.
122            let (from, to, binds) = if *and {
123                ("&&", "||", std::cmp::Ordering::Less)
124            } else {
125                ("||", "&&", std::cmp::Ordering::Greater)
126            };
127            vec![operator(gap, from.into(), to.into(), binds)]
128        }
129        SiteKind::Arith {
130            op, assign, gap, ..
131        } => {
132            let eq = if *assign { "=" } else { "" };
133            [Some(op.swapped()), op.second(*assign)]
134                .into_iter()
135                .flatten()
136                .map(|other| {
137                    operator(
138                        gap,
139                        format!("{}{eq}", op.symbol()),
140                        format!("{}{eq}", other.symbol()),
141                        // An assignment has nothing around it and its operands to itself.
142                        if *assign {
143                            same
144                        } else {
145                            other.binding().cmp(&op.binding())
146                        },
147                    )
148                })
149                .collect()
150        }
151        SiteKind::Not {
152            bang, needs_space, ..
153        } => vec![change(
154            bang.0,
155            bang.1,
156            if *needs_space { " " } else { "" }.to_string(),
157            "!",
158            "",
159        )],
160        SiteKind::Neg {
161            minus, needs_space, ..
162        } => vec![change(
163            minus.0,
164            minus.1,
165            if *needs_space { " " } else { "" }.to_string(),
166            "-",
167            "",
168        )],
169        SiteKind::Body { value, .. } => {
170            vec![change(
171                site.start,
172                site.end,
173                format!(" {value} "),
174                "body",
175                value,
176            )]
177        }
178        SiteKind::Arm {
179            pattern,
180            guard,
181            removal,
182        } => vec![match guard {
183            ArmGuard::None(_) => change(removal.0, removal.1, String::new(), "arm", pattern),
184            ArmGuard::Existing(from, to) => change(*from, *to, "false".into(), "arm", pattern),
185        }],
186        SiteKind::Guard { can_be_false } => [true, false]
187            .into_iter()
188            .filter(|value| *value || *can_be_false)
189            // Not the value the guard is written as.
190            .filter(|value| {
191                syn::parse_str::<syn::Expr>(&site.text)
192                    .ok()
193                    .and_then(|guard| written_bool(&guard))
194                    != Some(*value)
195            })
196            .map(|value| {
197                change(
198                    site.start,
199                    site.end,
200                    value.to_string(),
201                    "guard",
202                    &value.to_string(),
203                )
204            })
205            .collect(),
206        SiteKind::Field { name, removal, .. } => {
207            vec![change(removal.0, removal.1, String::new(), "field", name)]
208        }
209        SiteKind::Stmt => vec![change(site.start, site.end, String::new(), "statement", "")],
210        // The end taken in or left out: the two dots and the `=` are all that changes.
211        SiteKind::Range { inclusive, gap, .. } => {
212            let (from, to) = if *inclusive {
213                ("..=", "..")
214            } else {
215                ("..", "..=")
216            };
217            vec![change(gap.0, gap.1, to.to_string(), from, to)]
218        }
219        // The other method's name in place of the first: whatever is written around
220        // it (a line that ends, a comment) stays.
221        SiteKind::SliceEnd { first, method, .. } => {
222            let (from, to) = if *first {
223                ("first", "last")
224            } else {
225                ("last", "first")
226            };
227            vec![change(method.0, method.1, to.to_string(), from, to)]
228        }
229        SiteKind::StrAffix { starts, method, .. } => {
230            let from = if *starts { "starts_with" } else { "ends_with" };
231            vec![change(
232                method.0,
233                method.1,
234                "contains".into(),
235                from,
236                "contains",
237            )]
238        }
239        SiteKind::StrReplace {
240            replace_all,
241            from,
242            to,
243            method,
244            close,
245            ..
246        } => {
247            // Preserve the original source slice covering `(from, to` so multiline
248            // arguments keep their exact line numbers.
249            let args_slice = method
250                .1
251                .checked_sub(site.start)
252                .zip(close.0.checked_sub(site.start))
253                .and_then(|(s, e)| site.text.get(s..e));
254            if *replace_all {
255                let replacement = match args_slice {
256                    Some(slice) => format!("replacen{slice}, 1)"),
257                    None => format!("replacen({from}, {to}, 1)"),
258                };
259                vec![change(
260                    method.0,
261                    close.1,
262                    replacement,
263                    "replace",
264                    "replacen(..., 1)",
265                )]
266            } else {
267                let replacement = match args_slice {
268                    Some(slice) => format!("replace{slice})"),
269                    None => format!("replace({from}, {to})"),
270                };
271                vec![change(
272                    method.0,
273                    close.1,
274                    replacement,
275                    "replacen",
276                    "replace",
277                )]
278            }
279        }
280        SiteKind::Clamp {
281            low,
282            high,
283            call,
284            comma,
285            close,
286            ..
287        } => {
288            // Keep surviving argument expressions on their original source lines.
289            let drop_lower = call
290                .0
291                .checked_sub(site.start)
292                .zip(comma.1.checked_sub(site.start))
293                .and_then(|(s, e)| site.text.get(s..e))
294                .map(|dropped| {
295                    change(
296                        call.0,
297                        comma.1,
298                        format!(".min({}", "\n".repeat(dropped.matches('\n').count())),
299                        "clamp",
300                        "min (drop lower)",
301                    )
302                })
303                .unwrap_or_else(|| {
304                    change(
305                        call.0,
306                        close.1,
307                        format!(".min({high})"),
308                        "clamp",
309                        "min (drop lower)",
310                    )
311                });
312            let drop_upper = call
313                .0
314                .checked_sub(site.start)
315                .zip(call.1.checked_sub(site.start))
316                .zip(comma.0.checked_sub(site.start))
317                .and_then(|((cs, ce), le)| {
318                    let before_low = site.text.get(cs..ce)?;
319                    let low_slice = site.text.get(ce..le)?;
320                    Some(change(
321                        call.0,
322                        close.1,
323                        format!(
324                            ".max({}{low_slice})",
325                            "\n".repeat(before_low.matches('\n').count())
326                        ),
327                        "clamp",
328                        "max (drop upper)",
329                    ))
330                })
331                .unwrap_or_else(|| {
332                    change(
333                        call.0,
334                        close.1,
335                        format!(".max({low})"),
336                        "clamp",
337                        "max (drop upper)",
338                    )
339                });
340            vec![drop_lower, drop_upper]
341        }
342        SiteKind::Rounding { op, method, .. } => vec![
343            change(
344                method.0,
345                method.1,
346                op.alt1().name().into(),
347                op.name(),
348                op.alt1().name(),
349            ),
350            change(
351                method.0,
352                method.1,
353                op.alt2().name().into(),
354                op.name(),
355                op.alt2().name(),
356            ),
357        ],
358        SiteKind::Quantifier { all, method, .. } => {
359            let (from, to) = if *all { ("all", "any") } else { ("any", "all") };
360            vec![change(method.0, method.1, to.into(), from, to)]
361        }
362        SiteKind::LiteralSet { elements, .. } => elements
363            .iter()
364            .map(|(elem, start, end)| change(*start, *end, String::new(), "literal_set", elem))
365            .collect(),
366        SiteKind::Return { .. } | SiteKind::MinMax { .. } => vec![],
367    }
368}
369
370/// Replace only the operator tokens, preserving their surrounding source.
371pub(crate) fn literal_operator_mutants(source: &str, site: &Site, mutants: &mut [SourceMutant]) {
372    let gap = match &site.kind {
373        SiteKind::Cmp { gap, .. } | SiteKind::Logic { gap, .. } | SiteKind::Arith { gap, .. } => {
374            gap
375        }
376        _ => return,
377    };
378    if let Ok(operator) = syn::parse_str::<syn::BinOp>(&source[gap.0..gap.1]) {
379        let span = operator.span().byte_range();
380        for mutant in mutants {
381            mutant.start = gap.0 + span.start;
382            mutant.end = gap.0 + span.end;
383            mutant.replacement.clone_from(&mutant.into);
384        }
385    }
386}