1mod 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
42#[serde(rename_all = "kebab-case")]
43pub enum SourceKind {
44 Js,
47 Jsx,
49 Ts,
51 Tsx,
53}
54
55impl SourceKind {
56 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 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#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct MutationOptions {
82 pub operators: Vec<Operator>,
85 pub ranges: Option<Vec<(u32, u32)>>,
88 pub record_exports: bool,
92 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#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
111#[serde(transparent)]
112pub struct MutantId(pub String);
113
114impl MutantId {
115 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#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
129pub struct FunctionRef {
130 pub name: Option<String>,
132 pub span: (u32, u32),
134}
135
136#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
138pub struct Mutant {
139 pub id: MutantId,
141 pub operator: Operator,
143 pub span: (u32, u32),
145 pub line: u32,
147 pub column: u32,
149 pub original: String,
151 pub replacement: String,
156 pub enclosing_function: Option<FunctionRef>,
158 pub change: MutantChange,
160}
161
162#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
169pub struct MutantChange {
170 pub from: &'static str,
172 pub to: &'static str,
174}
175
176impl MutantChange {
177 const CONDITION: &'static str = "<condition>";
179 const CALL: &'static str = "<call>";
181 const EXPRESSION: &'static str = "<expression>";
184 pub const STRING: &'static str = "<string>";
186 const TEMPLATE: &'static str = "<template>";
188 const STATEMENT: &'static str = "<statement>";
190 const STATEMENTS: &'static str = "<statements>";
193 const ARRAY: &'static str = "<array>";
195 const OBJECT: &'static str = "<object>";
197 const FALLBACK: &'static str = "?? <expression>";
200
201 pub const fn new(from: &'static str, to: &'static str) -> Self {
203 Self { from, to }
204 }
205}
206
207#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
209pub struct SpliceSegment {
210 pub generated_start: u32,
212 pub original_start: u32,
214 pub len: u32,
216}
217
218#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
224pub struct SpliceMap {
225 pub segments: Vec<SpliceSegment>,
227}
228
229impl SpliceMap {
230 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#[derive(Debug, Clone, PartialEq, Eq)]
244pub struct Instrumented {
245 pub mutants: Vec<Mutant>,
247 pub code: String,
249 pub map: SpliceMap,
251}
252
253#[derive(Debug, Clone, PartialEq, Eq)]
255pub enum MutationError {
256 Parse {
258 messages: Vec<String>,
260 },
261 TooLarge,
264 ReservedName {
267 name: String,
269 },
270 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
296const fn is_identifier_byte(byte: u8) -> bool {
299 byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'$') || byte >= 0x80
300}
301
302pub const RESERVED_PREFIX: &str = "__fallow_m_";
311
312pub const ACTIVE_FUNCTION: &str = "__fallow_m_a";
320
321pub const HIT_FUNCTION: &str = "__fallow_m_c";
327
328pub 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
350pub 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
376pub 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
391struct TextInput<'s> {
393 pub(crate) source: &'s str,
394 pub(crate) path: &'s str,
395 pub(crate) kind: SourceKind,
396 pub(crate) role: Option<ScriptRole>,
398 pub(crate) prelude: bool,
400 pub(crate) probe: Option<&'s str>,
402}
403
404fn 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 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 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
516fn 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
537fn 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
552fn 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
582const 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
593const 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
602fn 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
665fn 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
693fn 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
736const ASI_HAZARDS: [char; 6] = ['(', '[', '`', '+', '-', '/'];
739
740fn 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
748fn 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 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}