1mod 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
39#[serde(rename_all = "kebab-case")]
40pub enum SourceKind {
41 Js,
44 Jsx,
46 Ts,
48 Tsx,
50}
51
52impl SourceKind {
53 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 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#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct MutationOptions {
79 pub operators: Vec<Operator>,
82 pub ranges: Option<Vec<(u32, u32)>>,
85 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#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
103#[serde(transparent)]
104pub struct MutantId(pub String);
105
106impl MutantId {
107 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#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
121pub struct FunctionRef {
122 pub name: Option<String>,
124 pub span: (u32, u32),
126}
127
128#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
130pub struct Mutant {
131 pub id: MutantId,
133 pub operator: Operator,
135 pub span: (u32, u32),
137 pub line: u32,
139 pub column: u32,
141 pub original: String,
143 pub replacement: String,
148 pub enclosing_function: Option<FunctionRef>,
150 pub change: MutantChange,
152}
153
154#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
161pub struct MutantChange {
162 pub from: &'static str,
164 pub to: &'static str,
166}
167
168impl MutantChange {
169 const CONDITION: &'static str = "<condition>";
171 const CALL: &'static str = "<call>";
173 const EXPRESSION: &'static str = "<expression>";
176 pub const STRING: &'static str = "<string>";
178 const TEMPLATE: &'static str = "<template>";
180 const STATEMENT: &'static str = "<statement>";
182 const STATEMENTS: &'static str = "<statements>";
185 const ARRAY: &'static str = "<array>";
187 const OBJECT: &'static str = "<object>";
189 const FALLBACK: &'static str = "?? <expression>";
192
193 pub const fn new(from: &'static str, to: &'static str) -> Self {
195 Self { from, to }
196 }
197}
198
199#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
201pub struct SpliceSegment {
202 pub generated_start: u32,
204 pub original_start: u32,
206 pub len: u32,
208}
209
210#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
216pub struct SpliceMap {
217 pub segments: Vec<SpliceSegment>,
219}
220
221impl SpliceMap {
222 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#[derive(Debug, Clone, PartialEq, Eq)]
236pub struct Instrumented {
237 pub mutants: Vec<Mutant>,
239 pub code: String,
241 pub map: SpliceMap,
243}
244
245#[derive(Debug, Clone, PartialEq, Eq)]
247pub enum MutationError {
248 Parse {
250 messages: Vec<String>,
252 },
253 TooLarge,
256 ReservedName {
259 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
283const fn is_identifier_byte(byte: u8) -> bool {
286 byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'$') || byte >= 0x80
287}
288
289pub const RESERVED_PREFIX: &str = "__fallow_m_";
298
299pub const ACTIVE_FUNCTION: &str = "__fallow_m_a";
307
308pub const HIT_FUNCTION: &str = "__fallow_m_c";
314
315pub 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
336struct TextInput<'s> {
338 pub(crate) source: &'s str,
339 pub(crate) path: &'s str,
340 pub(crate) kind: SourceKind,
341 pub(crate) role: Option<ScriptRole>,
343 pub(crate) prelude: bool,
345}
346
347fn 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 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 if u32::try_from(code.len()).is_err() {
440 return Err(MutationError::TooLarge);
441 }
442 Ok(Instrumented { mutants, code, map })
443}
444
445fn 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
469const 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
480const 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
489fn 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
552fn 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
580fn 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
623const ASI_HAZARDS: [char; 6] = ['(', '[', '`', '+', '-', '/'];
626
627fn 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
635fn 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 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}