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    /// `receiver.position(pred)` <-> `receiver.rposition(pred)` on a double-ended exact-size
175    /// iterator with a closure predicate.
176    Position {
177        /// `true` for `.position(pred)`, `false` for `.rposition(pred)`.
178        forward: bool,
179        receiver: String,
180        predicate: String,
181        /// Byte range from receiver end to predicate start.
182        call: (usize, usize),
183        /// Byte range from predicate end to closing `)` end.
184        close: (usize, usize),
185        /// Byte range of the method name.
186        method: (usize, usize),
187    },
188    /// `receiver.saturating_{add,sub,mul}(arg)` <-> `receiver.wrapping_{add,sub,mul}(arg)`.
189    SaturatingArith {
190        op: SaturatingOp,
191        receiver: String,
192        argument: String,
193        /// Byte range from receiver end to argument start.
194        call: (usize, usize),
195        /// Byte range from argument end to closing `)` end.
196        close: (usize, usize),
197        /// Byte range of the method name.
198        method: (usize, usize),
199    },
200    /// `receiver.trim()` / `.trim_start()` / `.trim_end()` on strings.
201    StrTrim {
202        op: TrimOp,
203        receiver: String,
204        /// Byte range of `.trim()`.
205        call: (usize, usize),
206        /// Byte range of the method name.
207        method: (usize, usize),
208    },
209    /// `receiver.eq_ignore_ascii_case(arg)` -> strict equality (`==`).
210    StrCaseEq {
211        receiver: String,
212        argument: String,
213        /// Byte range from receiver end to argument start.
214        call: (usize, usize),
215        /// Byte range from argument end to closing `)` end.
216        close: (usize, usize),
217        /// Byte range of the method name.
218        method: (usize, usize),
219    },
220    /// `receiver.abs()` -> `receiver` on signed integers and floats.
221    Abs {
222        receiver: String,
223        /// Byte range of `.abs()`.
224        call: (usize, usize),
225        /// Byte range of the method name.
226        method: (usize, usize),
227    },
228    /// `iter.take(n)` -> `iter.take(usize::MAX)` or `iter.skip(n)` -> `iter.skip(0)`.
229    IterLimit {
230        take: bool,
231        receiver: String,
232        count: String,
233        /// Byte range from receiver end to count start.
234        call: (usize, usize),
235        /// Byte range from count end to closing `)` end.
236        close: (usize, usize),
237        /// Byte range of the method name.
238        method: (usize, usize),
239    },
240    /// `x.to_be_bytes()` <-> `x.to_le_bytes()`, `x.to_be()` <-> `x.to_le()` on multi-byte ints.
241    EndianSwap {
242        op: EndianOp,
243        receiver: String,
244        /// Byte range of `.to_be_bytes()` / `.to_be()`.
245        call: (usize, usize),
246        /// Byte range of the method name.
247        method: (usize, usize),
248    },
249    /// `x.leading_zeros()` <-> `x.trailing_zeros()`, `leading_ones` <-> `trailing_ones`.
250    BitCount {
251        op: BitCountOp,
252        receiver: String,
253        /// Byte range of `.leading_zeros()`.
254        call: (usize, usize),
255        /// Byte range of the method name.
256        method: (usize, usize),
257    },
258    /// Unlabeled, value-less `break` <-> `continue` directly inside a loop.
259    LoopCtrl { is_break: bool },
260    /// `[lit1, lit2, ...].contains(&x)`: drop one literal element at a time.
261    LiteralSet {
262        receiver: String,
263        argument: String,
264        /// Byte range from receiver end to argument start (`.contains(`).
265        call: (usize, usize),
266        /// Byte range from argument end to closing `)` end.
267        close: (usize, usize),
268        /// `(element text, removal start, removal end)` for each element.
269        elements: Vec<(String, usize, usize)>,
270    },
271    /// `(lhs..rhs).contains(arg)` <-> `(lhs..=rhs).contains(arg)` on primitive ordered types.
272    RangeContains {
273        inclusive: bool,
274        lhs: String,
275        rhs: String,
276        argument: String,
277        /// Byte range from site start to `lhs` start (leading `(`).
278        open: (usize, usize),
279        /// Byte range of `..` / `..=` and surrounding whitespace.
280        gap: (usize, usize),
281        /// Byte range from `rhs` end to `arg` start (`).contains(`).
282        call: (usize, usize),
283        /// Byte range from `arg` end to closing `)` end.
284        close: (usize, usize),
285    },
286    /// `lhs..rhs` or `lhs..=rhs` on integers (or inside an indexing expression): the end
287    /// moves by one.
288    Range {
289        inclusive: bool,
290        lhs: String,
291        rhs: String,
292        gap: (usize, usize),
293        /// Present when the range is probed by switching an enclosing indexing expression
294        /// (`&xs[a..b]`, `&mut xs[a..b]`, or `xs[a..b].read_method(...)`).
295        index: Option<RangeIndex>,
296    },
297    /// An arm of a `match` that ends in a catch-all arm: without this arm the value falls
298    /// through to the arms below.
299    Arm {
300        pattern: String,
301        /// Where to put the probe: the start of the `=>`, or the range of an existing guard.
302        guard: ArmGuard,
303        removal: (usize, usize),
304    },
305    /// A call or assignment statement that can be deleted.
306    Stmt,
307    /// `-operand`: the minus is dropped.
308    Neg {
309        /// Byte range of the `-` and whatever separates it from the operand.
310        minus: (usize, usize),
311        operand: String,
312        /// The operand is a literal: its type is whatever the context asks for.
313        literal: bool,
314        /// Deleting `-` would glue the preceding and following tokens (`return-1`).
315        needs_space: bool,
316    },
317    /// The guard of a match arm: replaced by `true` or `false`.
318    Guard {
319        /// Whether `false` is a mutant of its own. It is not where the arm can be removed,
320        /// which is the same thing.
321        can_be_false: bool,
322    },
323    /// A field of a struct literal with a base (`..base`): the field is left to the base.
324    Field {
325        name: String,
326        /// Written without its name (`S { name, ..base }`).
327        shorthand: bool,
328        /// The expression used by a probe, where the base can safely be read again.
329        from_base: Option<String>,
330        /// The field and its trailing comma, including any attributes.
331        removal: (usize, usize),
332    },
333    /// The whole body of a function, replaced by a value of its return type. The site's
334    /// range is the inside of the body's braces and its text is the function signature.
335    Body {
336        name: String,
337        value: String,
338        /// The body when it is one expression that only computes its value (no call,
339        /// no macro, nothing assigned, no early exit): replacing the body by the value
340        /// that expression always had is then the same program for the tests.
341        sole_expr: Option<(usize, usize)>,
342    },
343}
344
345#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
346#[serde(rename_all = "snake_case")]
347pub enum RoundingOp {
348    Floor,
349    Ceil,
350    Round,
351    Trunc,
352}
353
354impl RoundingOp {
355    pub fn code(self) -> u8 {
356        match self {
357            RoundingOp::Floor => 0,
358            RoundingOp::Ceil => 1,
359            RoundingOp::Round => 2,
360            RoundingOp::Trunc => 3,
361        }
362    }
363
364    pub fn name(self) -> &'static str {
365        match self {
366            RoundingOp::Floor => "floor",
367            RoundingOp::Ceil => "ceil",
368            RoundingOp::Round => "round",
369            RoundingOp::Trunc => "trunc",
370        }
371    }
372
373    pub fn alt1(self) -> RoundingOp {
374        match self {
375            RoundingOp::Floor => RoundingOp::Trunc,
376            RoundingOp::Ceil => RoundingOp::Floor,
377            RoundingOp::Round => RoundingOp::Floor,
378            RoundingOp::Trunc => RoundingOp::Floor,
379        }
380    }
381
382    pub fn alt2(self) -> RoundingOp {
383        match self {
384            RoundingOp::Floor => RoundingOp::Ceil,
385            RoundingOp::Ceil => RoundingOp::Trunc,
386            RoundingOp::Round => RoundingOp::Trunc,
387            RoundingOp::Trunc => RoundingOp::Round,
388        }
389    }
390
391    /// Concrete input description distinguishing `self` from `other`.
392    pub fn differs_for(self, other: RoundingOp) -> &'static str {
393        match (self, other) {
394            (RoundingOp::Floor, RoundingOp::Trunc) | (RoundingOp::Trunc, RoundingOp::Floor) => {
395                "negative and not a whole number (e.g. -0.5)"
396            }
397            (RoundingOp::Ceil, RoundingOp::Trunc) | (RoundingOp::Trunc, RoundingOp::Ceil) => {
398                "positive and not a whole number (e.g. 0.5)"
399            }
400            (RoundingOp::Floor, RoundingOp::Round) | (RoundingOp::Round, RoundingOp::Floor) => {
401                "a number that rounds up (e.g. 1.5 or -1.4)"
402            }
403            (RoundingOp::Ceil, RoundingOp::Round) | (RoundingOp::Round, RoundingOp::Ceil) => {
404                "a number that rounds down (e.g. 1.4 or -1.6)"
405            }
406            (RoundingOp::Round, RoundingOp::Trunc) | (RoundingOp::Trunc, RoundingOp::Round) => {
407                "a number that rounds away from zero (e.g. 1.5 or -1.6)"
408            }
409            _ => "not a whole number (e.g. 0.5)",
410        }
411    }
412}
413
414#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
415#[serde(rename_all = "snake_case")]
416pub enum SaturatingOp {
417    SatAdd,
418    SatSub,
419    SatMul,
420    WrapAdd,
421    WrapSub,
422    WrapMul,
423}
424
425impl SaturatingOp {
426    pub fn code(self) -> u8 {
427        match self {
428            SaturatingOp::SatAdd => 0,
429            SaturatingOp::SatSub => 1,
430            SaturatingOp::SatMul => 2,
431            SaturatingOp::WrapAdd => 3,
432            SaturatingOp::WrapSub => 4,
433            SaturatingOp::WrapMul => 5,
434        }
435    }
436
437    pub fn name(self) -> &'static str {
438        match self {
439            SaturatingOp::SatAdd => "saturating_add",
440            SaturatingOp::SatSub => "saturating_sub",
441            SaturatingOp::SatMul => "saturating_mul",
442            SaturatingOp::WrapAdd => "wrapping_add",
443            SaturatingOp::WrapSub => "wrapping_sub",
444            SaturatingOp::WrapMul => "wrapping_mul",
445        }
446    }
447
448    pub fn swapped(self) -> Self {
449        match self {
450            SaturatingOp::SatAdd => SaturatingOp::WrapAdd,
451            SaturatingOp::SatSub => SaturatingOp::WrapSub,
452            SaturatingOp::SatMul => SaturatingOp::WrapMul,
453            SaturatingOp::WrapAdd => SaturatingOp::SatAdd,
454            SaturatingOp::WrapSub => SaturatingOp::SatSub,
455            SaturatingOp::WrapMul => SaturatingOp::SatMul,
456        }
457    }
458
459    pub fn overflow_phrase(self) -> &'static str {
460        match self {
461            SaturatingOp::SatAdd | SaturatingOp::WrapAdd => "whose sum overflows",
462            SaturatingOp::SatSub | SaturatingOp::WrapSub => {
463                "whose difference underflows or overflows"
464            }
465            SaturatingOp::SatMul | SaturatingOp::WrapMul => "whose product overflows",
466        }
467    }
468}
469
470#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
471#[serde(rename_all = "snake_case")]
472pub enum TrimOp {
473    Trim,
474    TrimStart,
475    TrimEnd,
476}
477
478impl TrimOp {
479    pub fn code(self) -> u8 {
480        match self {
481            TrimOp::Trim => 0,
482            TrimOp::TrimStart => 1,
483            TrimOp::TrimEnd => 2,
484        }
485    }
486
487    pub fn name(self) -> &'static str {
488        match self {
489            TrimOp::Trim => "trim",
490            TrimOp::TrimStart => "trim_start",
491            TrimOp::TrimEnd => "trim_end",
492        }
493    }
494
495    pub fn alt1(self) -> Self {
496        match self {
497            TrimOp::Trim => TrimOp::TrimStart,
498            TrimOp::TrimStart | TrimOp::TrimEnd => TrimOp::Trim,
499        }
500    }
501
502    pub fn alt2(self) -> Option<Self> {
503        match self {
504            TrimOp::Trim => Some(TrimOp::TrimEnd),
505            TrimOp::TrimStart | TrimOp::TrimEnd => None,
506        }
507    }
508
509    pub fn whitespace_phrase(self, alt: TrimOp) -> &'static str {
510        match (self, alt) {
511            (TrimOp::Trim, TrimOp::TrimStart) | (TrimOp::TrimStart, TrimOp::Trim) => {
512                "trailing whitespace"
513            }
514            (TrimOp::Trim, TrimOp::TrimEnd) | (TrimOp::TrimEnd, TrimOp::Trim) => {
515                "leading whitespace"
516            }
517            _ => "leading or trailing whitespace",
518        }
519    }
520}
521
522#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
523#[serde(rename_all = "snake_case")]
524pub enum EndianOp {
525    ToBeBytes,
526    ToLeBytes,
527    ToBe,
528    ToLe,
529}
530
531impl EndianOp {
532    pub fn code(self) -> u8 {
533        match self {
534            EndianOp::ToBeBytes => 0,
535            EndianOp::ToLeBytes => 1,
536            EndianOp::ToBe => 2,
537            EndianOp::ToLe => 3,
538        }
539    }
540
541    pub fn name(self) -> &'static str {
542        match self {
543            EndianOp::ToBeBytes => "to_be_bytes",
544            EndianOp::ToLeBytes => "to_le_bytes",
545            EndianOp::ToBe => "to_be",
546            EndianOp::ToLe => "to_le",
547        }
548    }
549
550    pub fn swapped(self) -> Self {
551        match self {
552            EndianOp::ToBeBytes => EndianOp::ToLeBytes,
553            EndianOp::ToLeBytes => EndianOp::ToBeBytes,
554            EndianOp::ToBe => EndianOp::ToLe,
555            EndianOp::ToLe => EndianOp::ToBe,
556        }
557    }
558}
559
560#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
561#[serde(rename_all = "snake_case")]
562pub enum BitCountOp {
563    LeadingZeros,
564    TrailingZeros,
565    LeadingOnes,
566    TrailingOnes,
567}
568
569impl BitCountOp {
570    pub fn code(self) -> u8 {
571        match self {
572            BitCountOp::LeadingZeros => 0,
573            BitCountOp::TrailingZeros => 1,
574            BitCountOp::LeadingOnes => 2,
575            BitCountOp::TrailingOnes => 3,
576        }
577    }
578
579    pub fn name(self) -> &'static str {
580        match self {
581            BitCountOp::LeadingZeros => "leading_zeros",
582            BitCountOp::TrailingZeros => "trailing_zeros",
583            BitCountOp::LeadingOnes => "leading_ones",
584            BitCountOp::TrailingOnes => "trailing_ones",
585        }
586    }
587
588    pub fn swapped(self) -> Self {
589        match self {
590            BitCountOp::LeadingZeros => BitCountOp::TrailingZeros,
591            BitCountOp::TrailingZeros => BitCountOp::LeadingZeros,
592            BitCountOp::LeadingOnes => BitCountOp::TrailingOnes,
593            BitCountOp::TrailingOnes => BitCountOp::LeadingOnes,
594        }
595    }
596}
597
598#[derive(Clone, Copy, PartialEq, Eq, Debug)]
599pub enum RangeIndexMode {
600    /// `&xs[a..b]`
601    Ref,
602    /// `&mut xs[a..b]`
603    RefMut,
604    /// `xs[a..b]` used as the receiver of a known `&self` read-only method.
605    Deref,
606    /// `xs.get(a..b)`
607    Get,
608    /// `xs.get_mut(a..b)`
609    GetMut,
610}
611
612#[derive(Clone, PartialEq, Eq, Debug)]
613pub struct RangeIndex {
614    pub mode: RangeIndexMode,
615    /// Source text of the plain-place base expression (e.g. `xs`, `self.source`).
616    pub base: String,
617    /// Byte range from outer expression start to range start (`&xs[`, `&mut xs[`, or `xs[`).
618    pub head: (usize, usize),
619    /// Byte range from range end to closing `]` end.
620    pub close_bracket: (usize, usize),
621}
622
623#[derive(Clone, Copy, PartialEq, Eq, Debug)]
624pub enum ArmGuard {
625    /// No guard: one is added before the `=>` at this offset.
626    None(usize),
627    /// `if <expr>` with the expression at this byte range.
628    Existing(usize, usize),
629}
630
631#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
632#[serde(rename_all = "snake_case")]
633pub enum ArithOp {
634    Add,
635    Sub,
636    Mul,
637    Div,
638    Rem,
639    BitAnd,
640    BitOr,
641    BitXor,
642    Shl,
643    Shr,
644}
645
646impl ArithOp {
647    /// How tightly the operator binds: a higher number before a lower one.
648    pub fn binding(self) -> u8 {
649        match self {
650            ArithOp::Mul | ArithOp::Div | ArithOp::Rem => 5,
651            ArithOp::Add | ArithOp::Sub => 4,
652            ArithOp::Shl | ArithOp::Shr => 3,
653            ArithOp::BitAnd => 2,
654            ArithOp::BitXor => 1,
655            ArithOp::BitOr => 0,
656        }
657    }
658
659    pub const ALL: [ArithOp; 10] = [
660        ArithOp::Add,
661        ArithOp::Sub,
662        ArithOp::Mul,
663        ArithOp::Div,
664        ArithOp::Rem,
665        ArithOp::BitAnd,
666        ArithOp::BitOr,
667        ArithOp::BitXor,
668        ArithOp::Shl,
669        ArithOp::Shr,
670    ];
671
672    pub fn symbol(self) -> &'static str {
673        match self {
674            ArithOp::Add => "+",
675            ArithOp::Sub => "-",
676            ArithOp::Mul => "*",
677            ArithOp::Div => "/",
678            ArithOp::Rem => "%",
679            ArithOp::BitAnd => "&",
680            ArithOp::BitOr => "|",
681            ArithOp::BitXor => "^",
682            ArithOp::Shl => "<<",
683            ArithOp::Shr => ">>",
684        }
685    }
686
687    /// The operator the mutant uses instead.
688    pub fn swapped(self) -> ArithOp {
689        match self {
690            ArithOp::Add => ArithOp::Sub,
691            ArithOp::Sub => ArithOp::Add,
692            ArithOp::Mul => ArithOp::Div,
693            ArithOp::Div => ArithOp::Mul,
694            ArithOp::Rem => ArithOp::Div,
695            ArithOp::BitAnd => ArithOp::BitOr,
696            ArithOp::BitOr => ArithOp::BitAnd,
697            ArithOp::BitXor => ArithOp::BitAnd,
698            ArithOp::Shl => ArithOp::Shr,
699            ArithOp::Shr => ArithOp::Shl,
700        }
701    }
702
703    /// The second operator a mutant uses instead. The shifts have none.
704    pub fn swapped2(self) -> Option<ArithOp> {
705        Some(match self {
706            ArithOp::Add => ArithOp::Mul,
707            ArithOp::Sub => ArithOp::Div,
708            ArithOp::Mul => ArithOp::Add,
709            ArithOp::Div => ArithOp::Rem,
710            ArithOp::Rem => ArithOp::Add,
711            ArithOp::BitAnd | ArithOp::BitOr => ArithOp::BitXor,
712            ArithOp::BitXor => ArithOp::BitOr,
713            ArithOp::Shl | ArithOp::Shr => return None,
714        })
715    }
716
717    /// The second replacement where the operator is written as an assignment or not.
718    /// Bits collected with `|=` from zero are the same bits with `^=`, and `&=` with
719    /// `^=` is rarely a slip of the pen: as in cargo-mutants, those two are left out.
720    pub fn second(self, assign: bool) -> Option<ArithOp> {
721        if assign && matches!(self, ArithOp::BitAnd | ArithOp::BitOr) {
722            return None;
723        }
724        self.swapped2()
725    }
726
727    /// Bit operators exist for integers only, the others for floats too.
728    pub fn is_bitwise(self) -> bool {
729        matches!(
730            self,
731            ArithOp::BitAnd | ArithOp::BitOr | ArithOp::BitXor | ArithOp::Shl | ArithOp::Shr
732        )
733    }
734
735    /// The name the runtime uses for this operator in its probe methods and traits.
736    fn stem(self) -> (&'static str, &'static str) {
737        match self {
738            ArithOp::Add => ("add", "Add"),
739            ArithOp::Sub => ("sub", "Sub"),
740            ArithOp::Mul => ("mul", "Mul"),
741            ArithOp::Div => ("div", "Div"),
742            ArithOp::Rem => ("rem", "Rem"),
743            ArithOp::BitAnd => ("bitand", "BitAnd"),
744            ArithOp::BitOr => ("bitor", "BitOr"),
745            ArithOp::BitXor => ("bitxor", "BitXor"),
746            ArithOp::Shl => ("shl", "Shl"),
747            ArithOp::Shr => ("shr", "Shr"),
748        }
749    }
750
751    /// Name of the probe method in the runtime.
752    pub(crate) fn method(self, assign: bool) -> String {
753        format!(
754            "tmt_{}{}",
755            self.stem().0,
756            if assign { "_assign" } else { "" }
757        )
758    }
759
760    /// Trait with the probe for every type that is not a primitive number.
761    pub(crate) fn fallback_trait(self, assign: bool) -> String {
762        format!("Any{}{}", self.stem().1, if assign { "Assign" } else { "" })
763    }
764
765    /// Trait with the probe for primitive numbers.
766    pub(super) fn prim_trait(self, assign: bool) -> &'static str {
767        match (self.is_bitwise(), assign) {
768            (false, false) => "ArithPrim",
769            (true, false) => "BitPrim",
770            (false, true) => "ArithAssignPrim",
771            (true, true) => "BitAssignPrim",
772        }
773    }
774}
775
776#[derive(Clone, PartialEq, Eq, Debug)]
777pub struct Site {
778    pub id: u32,
779    pub kind: SiteKind,
780    /// 1-based line and column of the start of the site.
781    pub line: usize,
782    pub column: usize,
783    /// Byte range in the original source.
784    pub start: usize,
785    pub end: usize,
786    pub text: String,
787}
788
789#[derive(Debug, PartialEq, Eq)]
790pub struct TestModule {
791    pub name: String,
792    /// The `#[path = "..."]` of the declaration, relative to the declaring file's directory.
793    pub path: Option<String>,
794}
795
796#[derive(Debug, Default)]
797pub struct Discovery {
798    pub sites: Vec<Site>,
799    /// Sites that cannot be switched while the program runs: inside a `const fn`, the
800    /// body of a function that returns `impl Iterator`, a compound assignment to a place
801    /// that is more than a variable. Their mutants are built one by one
802    /// (`source_mutants`). They have no number.
803    pub rebuild_sites: Vec<Site>,
804    /// Functions that return nothing and consist of one statement that is a site: an
805    /// empty body is the mutant that deletes the statement, so it is not made twice.
806    pub single_statement_bodies: Vec<String>,
807    /// Out-of-line modules that only exist under `cfg(test)` (`#[cfg(test)] mod tests;`).
808    pub test_modules: Vec<TestModule>,
809}
810
811/// The number of a site that has none.
812pub const NO_ID: u32 = u32::MAX;