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 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#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
108#[serde(transparent)]
109pub struct MutantId(pub String);
110
111impl MutantId {
112 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#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
126pub struct FunctionRef {
127 pub name: Option<String>,
129 pub span: (u32, u32),
131}
132
133#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
135pub struct Mutant {
136 pub id: MutantId,
138 pub operator: Operator,
140 pub span: (u32, u32),
142 pub line: u32,
144 pub column: u32,
146 pub original: String,
148 pub replacement: String,
153 pub enclosing_function: Option<FunctionRef>,
155 pub change: MutantChange,
157}
158
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
166pub struct MutantChange {
167 pub from: &'static str,
169 pub to: &'static str,
171}
172
173impl MutantChange {
174 const CONDITION: &'static str = "<condition>";
176 const CALL: &'static str = "<call>";
178 const EXPRESSION: &'static str = "<expression>";
181 pub const STRING: &'static str = "<string>";
183 const TEMPLATE: &'static str = "<template>";
185 const STATEMENT: &'static str = "<statement>";
187 const STATEMENTS: &'static str = "<statements>";
190 const ARRAY: &'static str = "<array>";
192 const OBJECT: &'static str = "<object>";
194 const FALLBACK: &'static str = "?? <expression>";
197
198 pub const fn new(from: &'static str, to: &'static str) -> Self {
200 Self { from, to }
201 }
202}
203
204#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
206pub struct SpliceSegment {
207 pub generated_start: u32,
209 pub original_start: u32,
211 pub len: u32,
213}
214
215#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
221pub struct SpliceMap {
222 pub segments: Vec<SpliceSegment>,
224}
225
226impl SpliceMap {
227 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#[derive(Debug, Clone, PartialEq, Eq)]
241pub struct Instrumented {
242 pub mutants: Vec<Mutant>,
244 pub code: String,
246 pub map: SpliceMap,
248}
249
250#[derive(Debug, Clone, PartialEq, Eq)]
252pub enum MutationError {
253 Parse {
255 messages: Vec<String>,
257 },
258 TooLarge,
261 ReservedName {
264 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
288const fn is_identifier_byte(byte: u8) -> bool {
291 byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'$') || byte >= 0x80
292}
293
294pub const RESERVED_PREFIX: &str = "__fallow_m_";
303
304pub const ACTIVE_FUNCTION: &str = "__fallow_m_a";
312
313pub const HIT_FUNCTION: &str = "__fallow_m_c";
319
320pub 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
341struct TextInput<'s> {
343 pub(crate) source: &'s str,
344 pub(crate) path: &'s str,
345 pub(crate) kind: SourceKind,
346 pub(crate) role: Option<ScriptRole>,
348 pub(crate) prelude: bool,
350}
351
352fn 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 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 if u32::try_from(code.len()).is_err() {
451 return Err(MutationError::TooLarge);
452 }
453 Ok(Instrumented { mutants, code, map })
454}
455
456fn 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
480const 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
491const 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
500fn 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
563fn 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
591fn 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
634const ASI_HAZARDS: [char; 6] = ['(', '[', '`', '+', '-', '/'];
637
638fn 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
646fn 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 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}