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    /// `lhs..rhs` or `lhs..=rhs` on integers: the end moves by one.
84    Range {
85        inclusive: bool,
86        lhs: String,
87        rhs: String,
88        gap: (usize, usize),
89    },
90    /// An arm of a `match` that ends in a catch-all arm: without this arm the value falls
91    /// through to the arms below.
92    Arm {
93        pattern: String,
94        /// Where to put the probe: the start of the `=>`, or the range of an existing guard.
95        guard: ArmGuard,
96        removal: (usize, usize),
97    },
98    /// A call or assignment statement that can be deleted.
99    Stmt,
100    /// `-operand`: the minus is dropped.
101    Neg {
102        /// Byte range of the `-` and whatever separates it from the operand.
103        minus: (usize, usize),
104        operand: String,
105        /// The operand is a literal: its type is whatever the context asks for.
106        literal: bool,
107        /// Deleting `-` would glue the preceding and following tokens (`return-1`).
108        needs_space: 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    pub(super) 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/// The number of a site that has none.
327pub const NO_ID: u32 = u32::MAX;