Skip to main content

targeted_mutation/instrument/
model.rs

1//! Data types describing discovered mutation sites.
2
3use serde::Serialize;
4
5use crate::plan::CmpOp;
6
7/// Name of the module injected into the crate root.
8pub const RUNTIME_MOD: &str = "__tmt_rt";
9
10#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
11#[serde(rename_all = "snake_case")]
12pub enum LiteralSide {
13    None,
14    Rhs(i128),
15    Lhs(i128),
16}
17
18#[derive(Clone, PartialEq, Eq, Debug)]
19pub enum SiteKind {
20    Cmp {
21        op: CmpOp,
22        lhs: String,
23        rhs: String,
24        literal: LiteralSide,
25        /// Byte range of the operator and the whitespace around it.
26        gap: (usize, usize),
27    },
28    /// `lhs && rhs` or `lhs || rhs`.
29    Logic {
30        and: bool,
31        lhs: String,
32        rhs: String,
33        gap: (usize, usize),
34    },
35    /// `lhs + rhs` and friends. Only primitive numbers are mutated; for other operand
36    /// types the probe performs the original operation and reports nothing.
37    Arith {
38        op: ArithOp,
39        /// `lhs op= rhs` rather than `lhs op rhs`.
40        assign: bool,
41        lhs: String,
42        rhs: String,
43        gap: (usize, usize),
44    },
45    /// `!operand`. Only `bool` is mutated (the `!` is dropped).
46    Not {
47        /// Byte range of the `!` and whatever separates it from the operand.
48        bang: (usize, usize),
49        operand: String,
50        /// Deleting `!` would glue the preceding and following tokens (`return!x`).
51        needs_space: bool,
52    },
53    /// The result of a function whose exits reach the probe. The site's range is the
54    /// inside of the body's braces and its text is the function signature.
55    Return {
56        name: String,
57        /// `None` for a function returning `bool`; for one returning `Option<T>`, the
58        /// return type as written.
59        option: Option<String>,
60        /// Byte range of the body when it is a single expression: the function's result
61        /// is then exactly that expression's value.
62        sole_expr: Option<(usize, usize)>,
63    },
64    /// `receiver.max(argument)` or `.min(..)`: the other of the two.
65    MinMax {
66        max: bool,
67        receiver: String,
68        argument: String,
69        /// Byte ranges of `.max(` and of the closing `)`.
70        call: (usize, usize),
71        close: (usize, usize),
72    },
73    /// `receiver.first()` or `.last()` of a slice, a `Vec`, an array or a `BTreeSet`: the
74    /// other end. The two are the same element while there is at most one.
75    SliceEnd {
76        first: bool,
77        receiver: String,
78        /// Byte range of `.first()`.
79        call: (usize, usize),
80        /// Byte range of the method's name.
81        method: (usize, usize),
82    },
83    /// `receiver.starts_with(pattern)` or `.ends_with(pattern)`: relaxed to `.contains(pattern)`.
84    StrAffix {
85        starts: bool,
86        receiver: String,
87        pattern: String,
88        /// Byte range of `.starts_with(` (from receiver end to pattern start).
89        call: (usize, usize),
90        /// Byte range of the closing `)` (from pattern end to closing paren end).
91        close: (usize, usize),
92        /// Byte range of the method name.
93        method: (usize, usize),
94    },
95    /// `receiver.replace(from, to)` <-> `receiver.replacen(from, to, 1)`.
96    StrReplace {
97        /// `true` for `.replace(from, to)`, `false` for `.replacen(from, to, 1)`.
98        replace_all: bool,
99        receiver: String,
100        from: String,
101        to: String,
102        /// Byte range from receiver end to `from` start.
103        call: (usize, usize),
104        /// Byte range from `from` end to `to` start.
105        comma: (usize, usize),
106        /// Byte range from `to` end to closing `)` end (includes `, 1)` for `replacen`).
107        close: (usize, usize),
108        /// Byte range of the method name.
109        method: (usize, usize),
110    },
111    /// `receiver.clamp(low, high)`: drop lower bound (`.min(high)`) or upper bound (`.max(low)`).
112    Clamp {
113        receiver: String,
114        low: String,
115        high: String,
116        /// Byte range from receiver end to `low` start.
117        call: (usize, usize),
118        /// Byte range from `low` end to `high` start.
119        comma: (usize, usize),
120        /// Byte range from `high` end to closing `)` end.
121        close: (usize, usize),
122    },
123    /// `receiver.floor()` / `.ceil()` / `.round()` / `.trunc()` on floats.
124    Rounding {
125        op: RoundingOp,
126        receiver: String,
127        /// Byte range of `.floor()`.
128        call: (usize, usize),
129        /// Byte range of the method name.
130        method: (usize, usize),
131    },
132    /// `receiver.all(pred)` <-> `receiver.any(pred)` on an iterator with a closure predicate.
133    Quantifier {
134        all: bool,
135        receiver: String,
136        predicate: String,
137        /// Byte range from receiver end to predicate start.
138        call: (usize, usize),
139        /// Byte range from predicate end to closing `)` end.
140        close: (usize, usize),
141        /// Byte range of the method name.
142        method: (usize, usize),
143    },
144    /// `[lit1, lit2, ...].contains(&x)`: drop one literal element at a time (source-built).
145    LiteralSet {
146        receiver: String,
147        argument: String,
148        /// `(element text, removal start, removal end)` for each element.
149        elements: Vec<(String, usize, usize)>,
150    },
151    /// `lhs..rhs` or `lhs..=rhs` on integers: the end moves by one.
152    Range {
153        inclusive: bool,
154        lhs: String,
155        rhs: String,
156        gap: (usize, usize),
157    },
158    /// An arm of a `match` that ends in a catch-all arm: without this arm the value falls
159    /// through to the arms below.
160    Arm {
161        pattern: String,
162        /// Where to put the probe: the start of the `=>`, or the range of an existing guard.
163        guard: ArmGuard,
164        removal: (usize, usize),
165    },
166    /// A call or assignment statement that can be deleted.
167    Stmt,
168    /// `-operand`: the minus is dropped.
169    Neg {
170        /// Byte range of the `-` and whatever separates it from the operand.
171        minus: (usize, usize),
172        operand: String,
173        /// The operand is a literal: its type is whatever the context asks for.
174        literal: bool,
175        /// Deleting `-` would glue the preceding and following tokens (`return-1`).
176        needs_space: bool,
177    },
178    /// The guard of a match arm: replaced by `true` or `false`.
179    Guard {
180        /// Whether `false` is a mutant of its own. It is not where the arm can be removed,
181        /// which is the same thing.
182        can_be_false: bool,
183    },
184    /// A field of a struct literal with a base (`..base`): the field is left to the base.
185    Field {
186        name: String,
187        /// Written without its name (`S { name, ..base }`).
188        shorthand: bool,
189        /// The expression used by a probe, where the base can safely be read again.
190        from_base: Option<String>,
191        /// The field and its trailing comma, including any attributes.
192        removal: (usize, usize),
193    },
194    /// The whole body of a function, replaced by a value of its return type. The site's
195    /// range is the inside of the body's braces and its text is the function signature.
196    Body {
197        name: String,
198        value: String,
199        /// The body when it is one expression that only computes its value (no call,
200        /// no macro, nothing assigned, no early exit): replacing the body by the value
201        /// that expression always had is then the same program for the tests.
202        sole_expr: Option<(usize, usize)>,
203    },
204}
205
206#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
207#[serde(rename_all = "snake_case")]
208pub enum RoundingOp {
209    Floor,
210    Ceil,
211    Round,
212    Trunc,
213}
214
215impl RoundingOp {
216    pub fn code(self) -> u8 {
217        match self {
218            RoundingOp::Floor => 0,
219            RoundingOp::Ceil => 1,
220            RoundingOp::Round => 2,
221            RoundingOp::Trunc => 3,
222        }
223    }
224
225    pub fn name(self) -> &'static str {
226        match self {
227            RoundingOp::Floor => "floor",
228            RoundingOp::Ceil => "ceil",
229            RoundingOp::Round => "round",
230            RoundingOp::Trunc => "trunc",
231        }
232    }
233
234    pub fn alt1(self) -> RoundingOp {
235        match self {
236            RoundingOp::Floor => RoundingOp::Trunc,
237            RoundingOp::Ceil => RoundingOp::Floor,
238            RoundingOp::Round => RoundingOp::Floor,
239            RoundingOp::Trunc => RoundingOp::Floor,
240        }
241    }
242
243    pub fn alt2(self) -> RoundingOp {
244        match self {
245            RoundingOp::Floor => RoundingOp::Ceil,
246            RoundingOp::Ceil => RoundingOp::Trunc,
247            RoundingOp::Round => RoundingOp::Trunc,
248            RoundingOp::Trunc => RoundingOp::Round,
249        }
250    }
251
252    /// Concrete input description distinguishing `self` from `other`.
253    pub fn differs_for(self, other: RoundingOp) -> &'static str {
254        match (self, other) {
255            (RoundingOp::Floor, RoundingOp::Trunc) | (RoundingOp::Trunc, RoundingOp::Floor) => {
256                "negative and not a whole number (e.g. -0.5)"
257            }
258            (RoundingOp::Ceil, RoundingOp::Trunc) | (RoundingOp::Trunc, RoundingOp::Ceil) => {
259                "positive and not a whole number (e.g. 0.5)"
260            }
261            (RoundingOp::Floor, RoundingOp::Round) | (RoundingOp::Round, RoundingOp::Floor) => {
262                "a number that rounds up (e.g. 1.5 or -1.4)"
263            }
264            (RoundingOp::Ceil, RoundingOp::Round) | (RoundingOp::Round, RoundingOp::Ceil) => {
265                "a number that rounds down (e.g. 1.4 or -1.6)"
266            }
267            (RoundingOp::Round, RoundingOp::Trunc) | (RoundingOp::Trunc, RoundingOp::Round) => {
268                "a number that rounds away from zero (e.g. 1.5 or -1.6)"
269            }
270            _ => "not a whole number (e.g. 0.5)",
271        }
272    }
273}
274
275#[derive(Clone, Copy, PartialEq, Eq, Debug)]
276pub enum ArmGuard {
277    /// No guard: one is added before the `=>` at this offset.
278    None(usize),
279    /// `if <expr>` with the expression at this byte range.
280    Existing(usize, usize),
281}
282
283#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
284#[serde(rename_all = "snake_case")]
285pub enum ArithOp {
286    Add,
287    Sub,
288    Mul,
289    Div,
290    Rem,
291    BitAnd,
292    BitOr,
293    BitXor,
294    Shl,
295    Shr,
296}
297
298impl ArithOp {
299    /// How tightly the operator binds: a higher number before a lower one.
300    pub fn binding(self) -> u8 {
301        match self {
302            ArithOp::Mul | ArithOp::Div | ArithOp::Rem => 5,
303            ArithOp::Add | ArithOp::Sub => 4,
304            ArithOp::Shl | ArithOp::Shr => 3,
305            ArithOp::BitAnd => 2,
306            ArithOp::BitXor => 1,
307            ArithOp::BitOr => 0,
308        }
309    }
310
311    pub const ALL: [ArithOp; 10] = [
312        ArithOp::Add,
313        ArithOp::Sub,
314        ArithOp::Mul,
315        ArithOp::Div,
316        ArithOp::Rem,
317        ArithOp::BitAnd,
318        ArithOp::BitOr,
319        ArithOp::BitXor,
320        ArithOp::Shl,
321        ArithOp::Shr,
322    ];
323
324    pub fn symbol(self) -> &'static str {
325        match self {
326            ArithOp::Add => "+",
327            ArithOp::Sub => "-",
328            ArithOp::Mul => "*",
329            ArithOp::Div => "/",
330            ArithOp::Rem => "%",
331            ArithOp::BitAnd => "&",
332            ArithOp::BitOr => "|",
333            ArithOp::BitXor => "^",
334            ArithOp::Shl => "<<",
335            ArithOp::Shr => ">>",
336        }
337    }
338
339    /// The operator the mutant uses instead.
340    pub fn swapped(self) -> ArithOp {
341        match self {
342            ArithOp::Add => ArithOp::Sub,
343            ArithOp::Sub => ArithOp::Add,
344            ArithOp::Mul => ArithOp::Div,
345            ArithOp::Div => ArithOp::Mul,
346            ArithOp::Rem => ArithOp::Div,
347            ArithOp::BitAnd => ArithOp::BitOr,
348            ArithOp::BitOr => ArithOp::BitAnd,
349            ArithOp::BitXor => ArithOp::BitAnd,
350            ArithOp::Shl => ArithOp::Shr,
351            ArithOp::Shr => ArithOp::Shl,
352        }
353    }
354
355    /// The second operator a mutant uses instead. The shifts have none.
356    pub fn swapped2(self) -> Option<ArithOp> {
357        Some(match self {
358            ArithOp::Add => ArithOp::Mul,
359            ArithOp::Sub => ArithOp::Div,
360            ArithOp::Mul => ArithOp::Add,
361            ArithOp::Div => ArithOp::Rem,
362            ArithOp::Rem => ArithOp::Add,
363            ArithOp::BitAnd | ArithOp::BitOr => ArithOp::BitXor,
364            ArithOp::BitXor => ArithOp::BitOr,
365            ArithOp::Shl | ArithOp::Shr => return None,
366        })
367    }
368
369    /// The second replacement where the operator is written as an assignment or not.
370    /// Bits collected with `|=` from zero are the same bits with `^=`, and `&=` with
371    /// `^=` is rarely a slip of the pen: as in cargo-mutants, those two are left out.
372    pub fn second(self, assign: bool) -> Option<ArithOp> {
373        if assign && matches!(self, ArithOp::BitAnd | ArithOp::BitOr) {
374            return None;
375        }
376        self.swapped2()
377    }
378
379    /// Bit operators exist for integers only, the others for floats too.
380    pub fn is_bitwise(self) -> bool {
381        matches!(
382            self,
383            ArithOp::BitAnd | ArithOp::BitOr | ArithOp::BitXor | ArithOp::Shl | ArithOp::Shr
384        )
385    }
386
387    /// The name the runtime uses for this operator in its probe methods and traits.
388    fn stem(self) -> (&'static str, &'static str) {
389        match self {
390            ArithOp::Add => ("add", "Add"),
391            ArithOp::Sub => ("sub", "Sub"),
392            ArithOp::Mul => ("mul", "Mul"),
393            ArithOp::Div => ("div", "Div"),
394            ArithOp::Rem => ("rem", "Rem"),
395            ArithOp::BitAnd => ("bitand", "BitAnd"),
396            ArithOp::BitOr => ("bitor", "BitOr"),
397            ArithOp::BitXor => ("bitxor", "BitXor"),
398            ArithOp::Shl => ("shl", "Shl"),
399            ArithOp::Shr => ("shr", "Shr"),
400        }
401    }
402
403    /// Name of the probe method in the runtime.
404    pub(crate) fn method(self, assign: bool) -> String {
405        format!(
406            "tmt_{}{}",
407            self.stem().0,
408            if assign { "_assign" } else { "" }
409        )
410    }
411
412    /// Trait with the probe for every type that is not a primitive number.
413    pub(crate) fn fallback_trait(self, assign: bool) -> String {
414        format!("Any{}{}", self.stem().1, if assign { "Assign" } else { "" })
415    }
416
417    /// Trait with the probe for primitive numbers.
418    pub(super) fn prim_trait(self, assign: bool) -> &'static str {
419        match (self.is_bitwise(), assign) {
420            (false, false) => "ArithPrim",
421            (true, false) => "BitPrim",
422            (false, true) => "ArithAssignPrim",
423            (true, true) => "BitAssignPrim",
424        }
425    }
426}
427
428#[derive(Clone, PartialEq, Eq, Debug)]
429pub struct Site {
430    pub id: u32,
431    pub kind: SiteKind,
432    /// 1-based line and column of the start of the site.
433    pub line: usize,
434    pub column: usize,
435    /// Byte range in the original source.
436    pub start: usize,
437    pub end: usize,
438    pub text: String,
439}
440
441#[derive(Debug, PartialEq, Eq)]
442pub struct TestModule {
443    pub name: String,
444    /// The `#[path = "..."]` of the declaration, relative to the declaring file's directory.
445    pub path: Option<String>,
446}
447
448#[derive(Debug, Default)]
449pub struct Discovery {
450    pub sites: Vec<Site>,
451    /// Sites that cannot be switched while the program runs: inside a `const fn`, the
452    /// body of a function that returns `impl Iterator`, a compound assignment to a place
453    /// that is more than a variable. Their mutants are built one by one
454    /// (`source_mutants`). They have no number.
455    pub rebuild_sites: Vec<Site>,
456    /// Functions that return nothing and consist of one statement that is a site: an
457    /// empty body is the mutant that deletes the statement, so it is not made twice.
458    pub single_statement_bodies: Vec<String>,
459    /// Out-of-line modules that only exist under `cfg(test)` (`#[cfg(test)] mod tests;`).
460    pub test_modules: Vec<TestModule>,
461}
462
463/// The number of a site that has none.
464pub const NO_ID: u32 = u32::MAX;