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