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