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