Skip to main content

fallow_mutation/
lib.rs

1//! Mutant site discovery and mutation-switching instrumentation.
2//!
3//! The crate is pure: it reads one source text and returns the mutants and
4//! the instrumented text. It does no IO, and it depends on no other Fallow
5//! workspace crate. The engine joins the mutants to graph, diff and
6//! complexity facts.
7//!
8//! The instrumented text is a splice over the original text. The crate never
9//! reprints the AST, so the output keeps the language of the input (TypeScript
10//! stays TypeScript, JSX stays JSX) and runner transforms see the original
11//! syntax.
12//!
13//! Two rules can give the same replacement at the same span, for example the
14//! relational constant `true` of `a === b` and the `negate-condition` mutant
15//! of `a === b` as an operand of `&&`. The site keeps the first candidate
16//! that the selected operators allow, so each mutated text is one mutant.
17//!
18//! User documentation is on [`fallow mutation`](https://fallow.tools/docs/cli/mutation/).
19
20mod blocks;
21mod collect;
22mod emit;
23mod exports;
24mod id;
25mod logging_only;
26mod operator;
27mod record;
28mod regex;
29mod replacements;
30
31use serde::Serialize;
32
33pub use blocks::{ScriptBlock, ScriptRole, instrument_blocks};
34pub use exports::export_containing;
35pub use operator::Operator;
36
37/// The language of a source text.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
39#[serde(rename_all = "kebab-case")]
40pub enum SourceKind {
41    /// JavaScript. JSX syntax is accepted, and module or script mode is
42    /// detected from the content.
43    Js,
44    /// JavaScript with JSX.
45    Jsx,
46    /// TypeScript without JSX.
47    Ts,
48    /// TypeScript with JSX.
49    Tsx,
50}
51
52impl SourceKind {
53    /// Selects the kind from the file extension of `path`.
54    pub fn from_path(path: &str) -> Option<Self> {
55        let extension = path.rsplit_once('.')?.1;
56        match extension {
57            "js" | "mjs" | "cjs" => Some(Self::Js),
58            "jsx" => Some(Self::Jsx),
59            "ts" | "mts" | "cts" => Some(Self::Ts),
60            "tsx" => Some(Self::Tsx),
61            _ => None,
62        }
63    }
64
65    /// The Oxc source type for this kind.
66    pub const fn source_type(self) -> oxc_span::SourceType {
67        match self {
68            Self::Js => oxc_span::SourceType::unambiguous().with_jsx(true),
69            Self::Jsx => oxc_span::SourceType::jsx(),
70            Self::Ts => oxc_span::SourceType::ts(),
71            Self::Tsx => oxc_span::SourceType::tsx(),
72        }
73    }
74}
75
76/// Options for [`instrument`].
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct MutationOptions {
79    /// The operators that may produce mutants. The default is
80    /// [`Operator::DEFAULT`].
81    pub operators: Vec<Operator>,
82    /// Byte ranges in the original text. When set, a mutant is kept only when
83    /// its span overlaps one of the ranges. `None` mutates the whole file.
84    pub ranges: Option<Vec<(u32, u32)>>,
85    /// Wrap each exported function that holds a kept mutant, so that the
86    /// runtime can record its arguments. The wraps do not change the mutant
87    /// ids. A script block of a component gets no wrap.
88    pub record_exports: bool,
89}
90
91impl Default for MutationOptions {
92    fn default() -> Self {
93        Self {
94            operators: Operator::DEFAULT.to_vec(),
95            ranges: None,
96            record_exports: false,
97        }
98    }
99}
100
101/// The stable identity of a mutant: 16 lowercase hex digits.
102#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
103#[serde(transparent)]
104pub struct MutantId(pub String);
105
106impl MutantId {
107    /// The id as text.
108    pub fn as_str(&self) -> &str {
109        &self.0
110    }
111}
112
113impl std::fmt::Display for MutantId {
114    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        f.write_str(&self.0)
116    }
117}
118
119/// The function that contains a mutant.
120#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
121pub struct FunctionRef {
122    /// The function name, when the syntax gives one.
123    pub name: Option<String>,
124    /// The original byte span of the function.
125    pub span: (u32, u32),
126}
127
128/// One mutant.
129#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
130pub struct Mutant {
131    /// The stable id.
132    pub id: MutantId,
133    /// The operator that produced the mutant.
134    pub operator: Operator,
135    /// The original byte span that the mutant replaces.
136    pub span: (u32, u32),
137    /// The 1-based line of the span start.
138    pub line: u32,
139    /// The 0-based byte column of the span start.
140    pub column: u32,
141    /// The original text of the span.
142    pub original: String,
143    /// The text that replaces the span. The original source with this
144    /// replacement applied is the mutated program. At the start of an
145    /// expression statement, the text can start with `void 0,`, so that the
146    /// statement does not join the line before it.
147    pub replacement: String,
148    /// The innermost function that contains the mutant.
149    pub enclosing_function: Option<FunctionRef>,
150    /// The edit in a form without project text.
151    pub change: MutantChange,
152}
153
154/// The edit of a mutant without project text.
155///
156/// Each side is an operator token, a fixed literal, or a placeholder for a
157/// side that is project code. The values are `&'static str`, so a side can
158/// never hold text of the source. An empty side means that the edit removes
159/// the token.
160#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
161pub struct MutantChange {
162    /// The token or placeholder before the edit.
163    pub from: &'static str,
164    /// The token or placeholder after the edit.
165    pub to: &'static str,
166}
167
168impl MutantChange {
169    /// Placeholder for the test of a condition.
170    const CONDITION: &'static str = "<condition>";
171    /// Placeholder for a call statement.
172    const CALL: &'static str = "<call>";
173    /// Placeholder for an expression, for example a returned value or a
174    /// comparison.
175    const EXPRESSION: &'static str = "<expression>";
176    /// Placeholder for a non-empty string literal.
177    pub const STRING: &'static str = "<string>";
178    /// Placeholder for a non-empty template literal.
179    const TEMPLATE: &'static str = "<template>";
180    /// Placeholder for one statement, for example a `throw` statement.
181    const STATEMENT: &'static str = "<statement>";
182    /// Placeholder for the statements of a block, a function body or a
183    /// `case` clause.
184    const STATEMENTS: &'static str = "<statements>";
185    /// Placeholder for a non-empty array literal.
186    const ARRAY: &'static str = "<array>";
187    /// Placeholder for a non-empty object literal.
188    const OBJECT: &'static str = "<object>";
189    /// The `??` token and the fallback operand that `nullish-fallback`
190    /// removes.
191    const FALLBACK: &'static str = "?? <expression>";
192
193    /// A change from `from` to `to`.
194    pub const fn new(from: &'static str, to: &'static str) -> Self {
195        Self { from, to }
196    }
197}
198
199/// One copied run of original text in the instrumented output.
200#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
201pub struct SpliceSegment {
202    /// The byte offset in the instrumented output.
203    pub generated_start: u32,
204    /// The byte offset in the original text.
205    pub original_start: u32,
206    /// The length in bytes.
207    pub len: u32,
208}
209
210/// Maps instrumented byte offsets back to original byte offsets.
211///
212/// Each segment is a run of original text that the output copies unchanged.
213/// Text that the instrumentation adds has no segment. The segments are in
214/// increasing `generated_start` order.
215#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
216pub struct SpliceMap {
217    /// The copied runs, in output order.
218    pub segments: Vec<SpliceSegment>,
219}
220
221impl SpliceMap {
222    /// The original offset of a generated offset, or `None` when the
223    /// instrumentation added the byte.
224    pub fn original_offset(&self, generated: u32) -> Option<u32> {
225        let index = self
226            .segments
227            .partition_point(|segment| segment.generated_start <= generated);
228        let segment = self.segments.get(index.checked_sub(1)?)?;
229        let delta = generated - segment.generated_start;
230        (delta < segment.len).then_some(segment.original_start + delta)
231    }
232}
233
234/// The result of [`instrument`].
235#[derive(Debug, Clone, PartialEq, Eq)]
236pub struct Instrumented {
237    /// The mutants, in source order.
238    pub mutants: Vec<Mutant>,
239    /// The instrumented source text.
240    pub code: String,
241    /// The map from output offsets to original offsets.
242    pub map: SpliceMap,
243}
244
245/// An error from [`instrument`].
246#[derive(Debug, Clone, PartialEq, Eq)]
247pub enum MutationError {
248    /// The source text does not parse.
249    Parse {
250        /// The parser messages.
251        messages: Vec<String>,
252    },
253    /// The source text or the instrumented text is larger than `u32::MAX`
254    /// bytes.
255    TooLarge,
256    /// The source declares a binding with a name that the prelude uses. See
257    /// [`RESERVED_PREFIX`].
258    ReservedName {
259        /// The declared name.
260        name: String,
261    },
262}
263
264impl std::fmt::Display for MutationError {
265    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
266        match self {
267            Self::Parse { messages } => {
268                write!(f, "the source does not parse: {}", messages.join("; "))
269            }
270            Self::TooLarge => {
271                f.write_str("the source or the instrumented output is larger than 4 GiB")
272            }
273            Self::ReservedName { name } => write!(
274                f,
275                "the source declares `{name}`, a name that the mutation prelude reserves"
276            ),
277        }
278    }
279}
280
281impl std::error::Error for MutationError {}
282
283/// True for a byte that can continue an identifier. Non-ASCII bytes count,
284/// so that an edit never joins a Unicode identifier with a keyword.
285const fn is_identifier_byte(byte: u8) -> bool {
286    byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'$') || byte >= 0x80
287}
288
289/// The name prefix that the instrumentation reserves.
290///
291/// The prelude declares [`ACTIVE_FUNCTION`] and [`HIT_FUNCTION`] at the top
292/// level of each instrumented file. A source that declares a binding with one
293/// of these two names, at any scope, gives [`MutationError::ReservedName`],
294/// because that binding would replace or shadow the prelude function. Other
295/// names with this prefix do not give an error now. Do not use names with
296/// this prefix in project code, because a later prelude can use them.
297pub const RESERVED_PREFIX: &str = "__fallow_m_";
298
299/// The prelude function that asks the runtime whether a mutant is active.
300///
301/// The instrumented output calls `__fallow_m_a(id)` before each mutated
302/// branch. The function returns `globalThis.__fallowMutation.a(id)`, or
303/// `false` when the runtime object is not set. Each call has a `typeof`
304/// guard, so code that runs in another realm without the prelude runs the
305/// original branch.
306pub const ACTIVE_FUNCTION: &str = "__fallow_m_a";
307
308/// The prelude function that reports a hit on the original branch.
309///
310/// The instrumented output calls `__fallow_m_c(id)` for each mutant of a site
311/// before the original branch runs. The function calls
312/// `globalThis.__fallowMutation.c(id)` when the runtime object is set.
313pub const HIT_FUNCTION: &str = "__fallow_m_c";
314
315/// Finds the mutants in `source` and returns the instrumented text.
316///
317/// `path` is part of each mutant id. Use the project-relative path, so that
318/// ids are the same on each machine.
319pub fn instrument(
320    source: &str,
321    path: &str,
322    source_type: SourceKind,
323    options: &MutationOptions,
324) -> Result<Instrumented, MutationError> {
325    let mut seen_ids = std::collections::BTreeSet::new();
326    let text = TextInput {
327        source,
328        path,
329        kind: source_type,
330        role: None,
331        prelude: true,
332    };
333    instrument_text(&text, options, &mut seen_ids)
334}
335
336/// One source text for [`instrument_text`]: a whole file or one script block.
337struct TextInput<'s> {
338    pub(crate) source: &'s str,
339    pub(crate) path: &'s str,
340    pub(crate) kind: SourceKind,
341    /// The role of a script block, or `None` for a whole file.
342    pub(crate) role: Option<ScriptRole>,
343    /// True when the text gets the prelude.
344    pub(crate) prelude: bool,
345}
346
347/// Instruments one text. The spans, lines and columns of the result are
348/// relative to the text. `seen_ids` holds the ids of earlier texts of the
349/// same file, so that each id stays unique in the file.
350fn instrument_text(
351    input: &TextInput<'_>,
352    options: &MutationOptions,
353    seen_ids: &mut std::collections::BTreeSet<MutantId>,
354) -> Result<Instrumented, MutationError> {
355    let source = input.source;
356    if u32::try_from(source.len()).is_err() {
357        return Err(MutationError::TooLarge);
358    }
359    let allocator = oxc_allocator::Allocator::default();
360    let parsed = oxc_parser::Parser::new(&allocator, source, input.kind.source_type()).parse();
361    if parsed.fatal_error || parsed.diagnostics.has_errors() {
362        let messages = parsed.diagnostics.iter().map(ToString::to_string).collect();
363        return Err(MutationError::Parse { messages });
364    }
365    if let Some(name) = reserved_binding(&parsed.program) {
366        return Err(MutationError::ReservedName { name });
367    }
368    let collected = collect::collect(&parsed.program, source);
369    let protected = input
370        .role
371        .map(|role| blocks::protected_spans(&parsed.program, role))
372        .unwrap_or_default();
373    // A component block has no module exports to wrap.
374    let record = options.record_exports && input.role.is_none() && input.prelude;
375    let insertions = header_insertions(&parsed.program, source, input.prelude, record);
376    let line_starts = line_starts(source);
377
378    let mut mutants = Vec::new();
379    let mut emit_sites = Vec::new();
380    for site in collected.sites {
381        if protected.excludes(site.span) {
382            continue;
383        }
384        let kept = select_candidates(source, &site, &collected.statement_starts, options);
385        if kept.is_empty() {
386            continue;
387        }
388        let mut emit_mutants = Vec::with_capacity(kept.len());
389        for candidate in kept {
390            let id = unique_id(input.path, source, &site, &candidate, seen_ids);
391            let (line, column) = line_column(&line_starts, candidate.region.0);
392            emit_mutants.push(emit::EmitMutant {
393                id: id.0.clone(),
394                region: candidate.region,
395                replacement: candidate.replacement.clone(),
396            });
397            mutants.push(Mutant {
398                id,
399                operator: candidate.operator,
400                span: candidate.region,
401                line,
402                column,
403                original: slice(source, candidate.region).to_owned(),
404                replacement: candidate.replacement,
405                enclosing_function: site.function.clone(),
406                change: candidate.change,
407            });
408        }
409        emit_sites.push(emit::EmitSite {
410            span: site.span,
411            statement: site.statement,
412            mutants: emit_mutants,
413        });
414    }
415    mutants.sort_by_key(|mutant| mutant.span);
416    let top_level = if record {
417        let mutant_spans: Vec<(u32, u32)> = mutants.iter().map(|mutant| mutant.span).collect();
418        let site_spans: Vec<(u32, u32)> = emit_sites.iter().map(|site| site.span).collect();
419        record::record_insertions(
420            &parsed.program,
421            &record::RecordInput {
422                path: input.path,
423                mutants: &mutant_spans,
424                sites: &site_spans,
425            },
426        )
427    } else {
428        Vec::new()
429    };
430    let (code, map) = emit::emit(
431        source,
432        &emit_sites,
433        &collected.statement_starts,
434        &insertions,
435        &top_level,
436    );
437    // The splice map holds `u32` offsets. When the output fits, no offset
438    // was truncated.
439    if u32::try_from(code.len()).is_err() {
440        return Err(MutationError::TooLarge);
441    }
442    Ok(Instrumented { mutants, code, map })
443}
444
445/// The first binding in `program` with the name of a prelude function.
446fn reserved_binding(program: &oxc_ast::ast::Program<'_>) -> Option<String> {
447    use oxc_ast_visit::Visit;
448
449    #[derive(Default)]
450    struct Finder {
451        found: Option<String>,
452    }
453    impl<'a> Visit<'a> for Finder {
454        fn visit_binding_identifier(&mut self, it: &oxc_ast::ast::BindingIdentifier<'a>) {
455            let name = it.name.as_str();
456            if self.found.is_none()
457                && (name == ACTIVE_FUNCTION || name == HIT_FUNCTION || name == RECORD_FUNCTION)
458            {
459                self.found = Some(name.to_owned());
460            }
461        }
462    }
463
464    let mut finder = Finder::default();
465    finder.visit_program(program);
466    finder.found
467}
468
469/// The prelude: two function declarations that call the runtime.
470///
471/// The prelude uses hoisted function declarations, not a `const`. In a module
472/// cycle, another module can call a hoisted function of this module before
473/// the prelude line runs. A `const` binding is then in its temporal dead
474/// zone and throws a `ReferenceError`. A function declaration exists from
475/// the start of the module, and each call reads the runtime object again.
476/// Two classic scripts can also declare the same functions without a
477/// redeclaration error.
478const PRELUDE: &str = "function __fallow_m_a(id) { const m = globalThis.__fallowMutation; return m ? m.a(id) : false; } function __fallow_m_c(id) { const m = globalThis.__fallowMutation; if (m) m.c(id); }";
479
480/// The prelude part of the argument recording wraps (see `record.rs`). It
481/// follows [`PRELUDE`] only when the options record exports.
482/// The prelude function of the argument recording wraps.
483const RECORD_FUNCTION: &str = "__fallow_m_w";
484
485const RECORD_PRELUDE: &str = " function __fallow_m_w(k, f) { const m = globalThis.__fallowMutation; return m && m.w ? m.w(k, f) : f; }";
486
487const TS_NOCHECK: &str = "// @ts-nocheck";
488
489/// The `// @ts-nocheck` comment goes after the hashbang and the leading
490/// comments, so that pragmas such as `@jsxImportSource` stay before the first
491/// token. The prelude goes after the directive prologue, so that
492/// `"use strict"` and `"use client"` stay the first statements.
493///
494/// A directive can share a line with the last leading comment. The line
495/// comment then ends with a newline, or the directive and the prelude become
496/// comment text.
497///
498/// A script block without the prelude gets only the comment.
499fn header_insertions(
500    program: &oxc_ast::ast::Program<'_>,
501    source: &str,
502    prelude: bool,
503    record: bool,
504) -> Vec<emit::Insertion> {
505    let prelude_text = if record {
506        format!("{PRELUDE}{RECORD_PRELUDE}")
507    } else {
508        PRELUDE.to_owned()
509    };
510    let offset = leading_end(program, source);
511    let line_break_follows = source
512        .get(offset as usize..)
513        .is_some_and(|rest| rest.starts_with(['\n', '\r', '\u{2028}', '\u{2029}']));
514    let nocheck = if offset == 0 {
515        format!("{TS_NOCHECK}\n")
516    } else if program.directives.is_empty() || line_break_follows {
517        format!("\n{TS_NOCHECK}")
518    } else {
519        format!("\n{TS_NOCHECK}\n")
520    };
521    if !prelude {
522        return vec![emit::Insertion {
523            offset,
524            text: nocheck,
525        }];
526    }
527    let Some(last) = program.directives.last() else {
528        let text = if offset == 0 {
529            format!("{nocheck}{prelude_text}\n")
530        } else {
531            format!("{nocheck}\n{prelude_text}")
532        };
533        return vec![emit::Insertion { offset, text }];
534    };
535    let end = last.span.end;
536    let terminated = source
537        .get(..end as usize)
538        .is_some_and(|text| text.ends_with(';'));
539    let separator = if terminated { "" } else { ";" };
540    vec![
541        emit::Insertion {
542            offset,
543            text: nocheck,
544        },
545        emit::Insertion {
546            offset: end,
547            text: format!("{separator}{prelude_text}"),
548        },
549    ]
550}
551
552/// The end of the hashbang and of the comments before the first token.
553fn leading_end(program: &oxc_ast::ast::Program<'_>, source: &str) -> u32 {
554    use oxc_span::GetSpan;
555    let first_token = program
556        .directives
557        .first()
558        .map(|directive| directive.span.start)
559        .or_else(|| program.body.first().map(|statement| statement.span().start))
560        .unwrap_or(source.len() as u32);
561    let hashbang_end = program
562        .hashbang
563        .as_ref()
564        .map_or(0, |hashbang| hashbang.span.end);
565    program
566        .comments
567        .iter()
568        .take_while(|comment| comment.span.end <= first_token)
569        .map(|comment| comment.span.end)
570        .last()
571        .map_or(hashbang_end, |end| end.max(hashbang_end))
572}
573
574fn slice(source: &str, span: (u32, u32)) -> &str {
575    source
576        .get(span.0 as usize..span.1 as usize)
577        .unwrap_or_default()
578}
579
580/// Applies the operator and range options, then drops candidates that give
581/// the original text or the same text as an earlier candidate of the site.
582fn select_candidates(
583    source: &str,
584    site: &collect::Site,
585    statement_starts: &std::collections::BTreeSet<u32>,
586    options: &MutationOptions,
587) -> Vec<collect::Candidate> {
588    let original = slice(source, site.span);
589    let mut texts = std::collections::BTreeSet::new();
590    let mut kept = Vec::new();
591    for candidate in &site.candidates {
592        if !options.operators.contains(&candidate.operator) {
593            continue;
594        }
595        let (start, end) = candidate.region;
596        let in_range = options
597            .ranges
598            .as_ref()
599            .is_none_or(|ranges| ranges.iter().any(|&(from, to)| start < to && from < end));
600        if !in_range {
601            continue;
602        }
603        let replacement = guard_statement_start(source, statement_starts, candidate);
604        let mutated = format!(
605            "{}{}{}",
606            slice(source, (site.span.0, start)),
607            replacement,
608            slice(source, (end, site.span.1)),
609        );
610        if mutated == original || !texts.insert(mutated) {
611            continue;
612        }
613        kept.push(collect::Candidate {
614            operator: candidate.operator,
615            region: candidate.region,
616            replacement,
617            change: candidate.change,
618        });
619    }
620    kept
621}
622
623/// Characters that continue the previous line when a statement starts with
624/// them and that line has no semicolon.
625const ASI_HAZARDS: [char; 6] = ['(', '[', '`', '+', '-', '/'];
626
627/// True when a statement that starts with `text` can join the line before it.
628/// A prefix `++` or `--` cannot, because the postfix forms forbid a line
629/// break before the operator.
630fn starts_with_asi_hazard(text: &str) -> bool {
631    let hazard = text.starts_with(ASI_HAZARDS);
632    hazard && !text.starts_with("++") && !text.starts_with("--")
633}
634
635/// Prefixes `void 0,` to a replacement that starts an expression statement
636/// with an ASI hazard, so that the original source with the replacement
637/// applied keeps the statement boundary. When the original also starts with a
638/// hazard, the line before it already ends the statement, and no prefix is
639/// needed.
640///
641/// The comma has the lowest precedence, so the rest of the statement keeps
642/// its grouping: `f() ** 2` becomes `void 0, (void 0) ** 2`, and
643/// `!x ? a() : b()` becomes `void 0, (x) ? a() : b()`. A `void` prefix alone
644/// would bind to the replacement only, which is a syntax error before `**`
645/// and makes the test of `? :` always `undefined`.
646fn guard_statement_start(
647    source: &str,
648    statement_starts: &std::collections::BTreeSet<u32>,
649    candidate: &collect::Candidate,
650) -> String {
651    let (start, end) = candidate.region;
652    let guarded = statement_starts.contains(&start)
653        && starts_with_asi_hazard(&candidate.replacement)
654        && !starts_with_asi_hazard(slice(source, (start, end)));
655    if !guarded {
656        return candidate.replacement.clone();
657    }
658    // `do!f()` has no space after the keyword; `dovoid` would be a name.
659    let joins = source
660        .as_bytes()
661        .get((start as usize).wrapping_sub(1))
662        .is_some_and(|&byte| is_identifier_byte(byte));
663    let prefix = if joins { " void 0, " } else { "void 0, " };
664    format!("{prefix}{}", candidate.replacement)
665}
666
667fn unique_id(
668    path: &str,
669    source: &str,
670    site: &collect::Site,
671    candidate: &collect::Candidate,
672    seen: &mut std::collections::BTreeSet<MutantId>,
673) -> MutantId {
674    let anchor_start = site.anchor.0;
675    let input = id::IdInput {
676        path,
677        anchor_text: slice(source, site.anchor),
678        relative: (
679            candidate.region.0.saturating_sub(anchor_start),
680            candidate.region.1.saturating_sub(anchor_start),
681        ),
682        operator: candidate.operator,
683        replacement: &candidate.replacement,
684    };
685    let mut occurrence = 0;
686    loop {
687        let id = id::mutant_id(&input, occurrence);
688        if seen.insert(id.clone()) {
689            return id;
690        }
691        occurrence += 1;
692    }
693}
694
695fn line_starts(source: &str) -> Vec<u32> {
696    std::iter::once(0)
697        .chain(
698            source
699                .match_indices('\n')
700                .map(|(index, _)| index as u32 + 1),
701        )
702        .collect()
703}
704
705fn line_column(line_starts: &[u32], offset: u32) -> (u32, u32) {
706    let index = line_starts
707        .partition_point(|&start| start <= offset)
708        .saturating_sub(1);
709    let start = line_starts.get(index).copied().unwrap_or(0);
710    (index as u32 + 1, offset - start)
711}