1mod 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
36#[serde(rename_all = "kebab-case")]
37pub enum SourceKind {
38 Js,
41 Jsx,
43 Ts,
45 Tsx,
47}
48
49impl SourceKind {
50 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 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#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct MutationOptions {
76 pub operators: Vec<Operator>,
79 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#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
95#[serde(transparent)]
96pub struct MutantId(pub String);
97
98impl MutantId {
99 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#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
113pub struct FunctionRef {
114 pub name: Option<String>,
116 pub span: (u32, u32),
118}
119
120#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
122pub struct Mutant {
123 pub id: MutantId,
125 pub operator: Operator,
127 pub span: (u32, u32),
129 pub line: u32,
131 pub column: u32,
133 pub original: String,
135 pub replacement: String,
140 pub enclosing_function: Option<FunctionRef>,
142 pub change: MutantChange,
144}
145
146#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
153pub struct MutantChange {
154 pub from: &'static str,
156 pub to: &'static str,
158}
159
160impl MutantChange {
161 const CONDITION: &'static str = "<condition>";
163 const CALL: &'static str = "<call>";
165 const EXPRESSION: &'static str = "<expression>";
168 pub const STRING: &'static str = "<string>";
170 const TEMPLATE: &'static str = "<template>";
172 const STATEMENT: &'static str = "<statement>";
174 const STATEMENTS: &'static str = "<statements>";
177 const ARRAY: &'static str = "<array>";
179 const OBJECT: &'static str = "<object>";
181
182 pub const fn new(from: &'static str, to: &'static str) -> Self {
184 Self { from, to }
185 }
186}
187
188#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
190pub struct SpliceSegment {
191 pub generated_start: u32,
193 pub original_start: u32,
195 pub len: u32,
197}
198
199#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
205pub struct SpliceMap {
206 pub segments: Vec<SpliceSegment>,
208}
209
210impl SpliceMap {
211 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#[derive(Debug, Clone, PartialEq, Eq)]
225pub struct Instrumented {
226 pub mutants: Vec<Mutant>,
228 pub code: String,
230 pub map: SpliceMap,
232}
233
234#[derive(Debug, Clone, PartialEq, Eq)]
236pub enum MutationError {
237 Parse {
239 messages: Vec<String>,
241 },
242 TooLarge,
245 ReservedName {
248 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
272const fn is_identifier_byte(byte: u8) -> bool {
275 byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'$') || byte >= 0x80
276}
277
278pub const RESERVED_PREFIX: &str = "__fallow_m_";
287
288pub const ACTIVE_FUNCTION: &str = "__fallow_m_a";
294
295pub const HIT_FUNCTION: &str = "__fallow_m_c";
301
302pub 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
323struct TextInput<'s> {
325 pub(crate) source: &'s str,
326 pub(crate) path: &'s str,
327 pub(crate) kind: SourceKind,
328 pub(crate) role: Option<ScriptRole>,
330 pub(crate) prelude: bool,
332}
333
334fn 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 if u32::try_from(code.len()).is_err() {
410 return Err(MutationError::TooLarge);
411 }
412 Ok(Instrumented { mutants, code, map })
413}
414
415fn 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
437const 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
450fn 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
507fn 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
535fn 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
578const ASI_HAZARDS: [char; 6] = ['(', '[', '`', '+', '-', '/'];
581
582fn 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
590fn 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 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}