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