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