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