fallow_engine/mutation/mod.rs
1//! The static half of mutation testing: select, map, prune and rank mutants.
2//!
3//! The plan reads only facts that the dead-code analysis already has: the
4//! module graph with its test reachability (including the `vi.mock`
5//! replacement masks), the dead-code results, the function complexity of each
6//! module, and the captured security sink sites. It reads the source text of
7//! each selected file one time to instrument it, and it holds the
8//! instrumented code in memory. It never writes a file and never runs user
9//! code.
10//!
11//! Each mutant gets one disposition:
12//!
13//! - `planned`: a test file reaches the file, and no static rule prunes the
14//! mutant. The runner executes these mutants in rank order.
15//! - `pending`: a planned mutant after the `max_mutants` limit.
16//! - `no-coverage`: no test file reaches the file in the graph. A test that
17//! replaces the module with `vi.mock` does not reach it.
18//! - `pruned`: a static rule removes the mutant (see [`PruneReason`](crate::mutation::PruneReason)).
19
20mod database_write;
21mod layout;
22mod plan;
23mod reach;
24#[cfg(test)]
25mod tests;
26
27use std::collections::{BTreeMap, BTreeSet};
28use std::path::{Path, PathBuf};
29
30use serde::Serialize;
31
32pub use fallow_mutation::{
33 FunctionRef, Mutant, MutantChange, MutantId, MutationError, Operator, RESERVED_PREFIX,
34 SourceKind,
35};
36pub use fallow_output::DiffIndex;
37pub use layout::{instrument_source, is_component_file};
38
39use crate::EngineError;
40use crate::module_graph::{ExportTestReach, RetainedModuleGraph};
41use crate::session::AnalysisSession;
42use crate::source::ModuleInfo;
43use fallow_types::results::AnalysisResults;
44
45/// The runner config modules at the project root. Each test run loads them,
46/// so they and the files that they reach through static imports are in
47/// [`MutationPlan::support_files`].
48pub const RUNNER_CONFIG_MODULES: [&str; 18] = [
49 "vitest.config.ts",
50 "vitest.config.mts",
51 "vitest.config.cts",
52 "vitest.config.js",
53 "vitest.config.mjs",
54 "vitest.config.cjs",
55 "vite.config.ts",
56 "vite.config.mts",
57 "vite.config.cts",
58 "vite.config.js",
59 "vite.config.mjs",
60 "vite.config.cjs",
61 "vitest.workspace.ts",
62 "vitest.workspace.mts",
63 "vitest.workspace.cts",
64 "vitest.workspace.js",
65 "vitest.workspace.mjs",
66 "vitest.workspace.cjs",
67];
68
69/// The files and lines that a plan mutates.
70#[derive(Debug, Clone)]
71pub enum MutationScope {
72 /// The added lines of a diff against the base ref. Build the index with
73 /// the existing diff machinery (`changed_files::try_get_changed_diff`,
74 /// `DiffIndex::from_unified_diff` and `diff_source::place_diff`). Only
75 /// mutants that overlap an added line are kept.
76 ChangedSinceBase(DiffIndex),
77 /// Each source file of the project.
78 All,
79 /// The files at these paths, or below these directories. A relative path
80 /// is relative to the project root.
81 Paths(Vec<PathBuf>),
82}
83
84/// What to plan.
85#[derive(Debug, Clone)]
86pub struct MutationPlanRequest {
87 /// The files and lines to mutate.
88 pub scope: MutationScope,
89 /// The operators to use. `None` uses each operator.
90 pub operators: Option<Vec<Operator>>,
91 /// Keep the mutants in functions that call a file system, child process,
92 /// network or database sink. The default prunes them, because a mutant
93 /// can turn a guarded side effect into an unguarded one.
94 pub allow_side_effects: bool,
95 /// The maximum number of planned mutants. The mutants after this limit,
96 /// in rank order, become `pending`.
97 pub max_mutants: Option<usize>,
98 /// Leave each Vue, Svelte and Astro component file out of the plan,
99 /// with the skip reason [`SkipReason::RunnerCannotLoad`]. Set it when
100 /// the test runner has no loader for a component file.
101 pub skip_component_files: bool,
102}
103
104impl MutationPlanRequest {
105 /// A request with the default options for `scope`.
106 #[must_use]
107 pub const fn new(scope: MutationScope) -> Self {
108 Self {
109 scope,
110 operators: None,
111 allow_side_effects: false,
112 max_mutants: None,
113 skip_component_files: false,
114 }
115 }
116}
117
118/// Framework config exports, by root-relative file path.
119///
120/// A framework plugin marks some exports as used by the framework, for
121/// example `export const revalidate = 60` in a Next.js page. A mutant in such
122/// an export changes framework config, not tested logic, so the plan prunes
123/// it. Mutants inside a function in the export are not pruned.
124#[derive(Debug, Clone, Default, PartialEq, Eq)]
125pub struct FrameworkConfigExports {
126 files: BTreeMap<String, BTreeSet<String>>,
127 config_files: BTreeSet<String>,
128}
129
130impl FrameworkConfigExports {
131 /// Records that the framework uses `export` of the root-relative `file`.
132 pub fn insert(&mut self, file: impl Into<String>, export: impl Into<String>) {
133 self.files
134 .entry(file.into())
135 .or_default()
136 .insert(export.into());
137 }
138
139 /// Records that the root-relative `file` is a tool config file. The tool
140 /// reads its default export, and a top-level `module.exports = ...`
141 /// statement counts as that default export.
142 pub fn insert_config_file(&mut self, file: impl Into<String>) {
143 let file = file.into();
144 self.insert(file.clone(), DEFAULT_EXPORT);
145 self.config_files.insert(file);
146 }
147
148 /// True when [`Self::insert_config_file`] recorded the root-relative
149 /// `file`.
150 #[must_use]
151 pub fn is_config_file(&self, file: &str) -> bool {
152 self.config_files.contains(file)
153 }
154
155 /// The framework config export names of one root-relative file.
156 #[must_use]
157 pub fn exports_for(&self, file: &str) -> Option<&BTreeSet<String>> {
158 self.files.get(file)
159 }
160}
161
162/// The analysis facts that a plan reads.
163#[derive(Clone, Copy)]
164pub struct MutationPlanInputs<'a> {
165 /// The project root.
166 pub root: &'a Path,
167 /// The module graph of the analysis.
168 pub graph: &'a RetainedModuleGraph,
169 /// The parsed modules, with complexity.
170 pub modules: &'a [ModuleInfo],
171 /// The dead-code results of the analysis.
172 pub results: &'a AnalysisResults,
173 /// The framework config exports. `None` when the caller has no plugin
174 /// facts. The plan then prunes no `framework-config` mutants and sets
175 /// [`MutationPlan::framework_config_checked`] to false.
176 pub framework_config_exports: Option<&'a FrameworkConfigExports>,
177 /// The setup files of the test runner config, absolute or relative to
178 /// the root, with or without an extension. They fill
179 /// [`MutationPlan::support_files`], with the runner config modules at the
180 /// root.
181 pub setup_files: &'a [PathBuf],
182}
183
184/// Why a static rule removes a mutant.
185#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
186#[serde(rename_all = "kebab-case")]
187pub enum PruneReason {
188 /// The file is unused: no entry point reaches it.
189 DeadCode,
190 /// The file is generated code.
191 Generated,
192 /// The enclosing function calls a file system, child process, network or
193 /// database sink of the security catalogue. A mutant outside each
194 /// function gets this reason when the module calls such a sink outside
195 /// each function, because that sink runs on each import of the module.
196 /// A sink that only shapes a response or a navigation (a redirect, a
197 /// header, a cookie, a CORS policy) does not count.
198 SideEffectSink,
199 /// The mutant is in an export that a framework reads as config.
200 FrameworkConfig,
201}
202
203/// The status of a mutant in a plan.
204#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
205#[serde(tag = "status", content = "reason", rename_all = "kebab-case")]
206pub enum MutantDisposition {
207 /// The runner executes the mutant.
208 Planned,
209 /// A planned mutant after the `max_mutants` limit.
210 Pending,
211 /// No test file reaches the file of the mutant.
212 NoCoverage,
213 /// A static rule removes the mutant.
214 Pruned(PruneReason),
215}
216
217/// The facts of the function that contains a mutant.
218#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
219pub struct FunctionFacts {
220 /// The function name. The complexity name wins over the syntax name, so
221 /// that the name is the same as in `health` output.
222 pub name: Option<String>,
223 /// The byte span of the function.
224 pub span: (u32, u32),
225 /// The 1-based first line of the function.
226 pub line: u32,
227 /// The 1-based last line of the function.
228 pub end_line: u32,
229 /// The cyclomatic complexity, when the analysis measured the function.
230 pub cyclomatic: Option<u16>,
231 /// True when an added line of the diff is in the function.
232 pub in_diff: bool,
233}
234
235/// One mutant of the plan.
236#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
237pub struct PlannedMutant {
238 /// The mutant.
239 pub mutant: Mutant,
240 /// The root-relative path of the file, with forward slashes.
241 pub file: String,
242 /// The 1-based execution rank of a planned or pending mutant.
243 pub rank: Option<u32>,
244 /// The status of the mutant.
245 pub disposition: MutantDisposition,
246 /// The function that contains the mutant.
247 pub function: Option<FunctionFacts>,
248 /// How tests reach the code of the mutant in the module graph. `None`
249 /// for a pruned mutant.
250 pub test_reach: Option<MutantTestReach>,
251}
252
253/// How tests reach the code of one mutant, from the module graph.
254///
255/// A mutant in the top-level statement that declares a value export gets the
256/// class of that export. A mutant outside each such statement gets the class
257/// of its file: `none-file` when no test loads the file, `mocked-only` when no
258/// test loads the file and a mock explains an export of the file, and `none`
259/// when a test loads the file.
260#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
261pub struct MutantTestReach {
262 /// The reach class.
263 pub reach: ExportTestReach,
264 /// The export whose declaration holds the mutant. `None` for a mutant
265 /// outside each value export declaration.
266 pub export_name: Option<String>,
267 /// For `mocked-only`: the test files whose references a mock removed,
268 /// sorted.
269 pub tests: Vec<String>,
270 /// Static test-file reach for this exported declaration. Internal plan
271 /// evidence only. This is not per-test runtime export coverage.
272 #[serde(skip)]
273 pub export_test_files: Vec<String>,
274 /// For `mocked-only`: the mocked modules on the reference paths, sorted.
275 pub mocked_targets: Vec<String>,
276}
277
278/// One file that the runner loads in its instrumented form.
279#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
280pub struct PlannedFile {
281 /// The root-relative path, with forward slashes.
282 pub path: String,
283 /// The SHA-256 digest of the file bytes, as lowercase hex.
284 pub source_sha256: String,
285 /// The instrumented source text.
286 pub instrumented_code: String,
287 /// The test files that reach the file through imports, sorted. A test
288 /// that replaces the file, or a module on each import path to it, with
289 /// `vi.mock` is not in the list.
290 pub static_test_files: Vec<String>,
291}
292
293/// Why the plan did not instrument a selected file.
294#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
295#[serde(rename_all = "kebab-case")]
296pub enum SkipReason {
297 /// The file could not be read.
298 Unreadable,
299 /// The file changed after the analysis parsed it.
300 Stale,
301 /// The file does not parse.
302 Parse,
303 /// The file declares a name that the instrumentation reserves.
304 ReservedName,
305 /// The file is larger than 4 GiB.
306 TooLarge,
307 /// The module graph has the file, but the analysis kept no module facts
308 /// for it, for example because extraction could not read it.
309 NotAnalyzed,
310 /// The test runner cannot load the file: a component file under a runner
311 /// with no component loader.
312 RunnerCannotLoad,
313}
314
315/// A selected file that the plan did not instrument.
316#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
317pub struct SkippedFile {
318 /// The root-relative path, with forward slashes.
319 pub path: String,
320 /// Why the plan skipped the file.
321 pub reason: SkipReason,
322}
323
324/// The number of pruned mutants for each reason.
325#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
326pub struct PruneCounts {
327 /// Mutants in unused files.
328 pub dead_code: usize,
329 /// Mutants in generated files.
330 pub generated: usize,
331 /// Mutants in functions that call a side-effect sink, and top-level
332 /// mutants of a module with a top-level side-effect sink.
333 pub side_effect_sink: usize,
334 /// Mutants in framework config exports.
335 pub framework_config: usize,
336}
337
338/// The number of mutants for each disposition.
339#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
340pub struct MutationPlanCounts {
341 /// Each mutant of the plan.
342 pub total: usize,
343 /// Planned mutants.
344 pub planned: usize,
345 /// Planned mutants after the `max_mutants` limit.
346 pub pending: usize,
347 /// Mutants that no test file reaches.
348 pub no_coverage: usize,
349 /// Pruned mutants, by reason.
350 pub pruned: PruneCounts,
351}
352
353/// The static mutation plan.
354#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
355pub struct MutationPlan {
356 /// The files with a planned or pending mutant, sorted by path.
357 pub files: Vec<PlannedFile>,
358 /// Each mutant. Ranked mutants come first in rank order, then the other
359 /// mutants by file, span and id.
360 pub mutants: Vec<PlannedMutant>,
361 /// The union of the static test files of `files`, sorted.
362 pub test_files: Vec<String>,
363 /// The files that the test files reach through static imports, sorted.
364 /// [`MutationPlan::test_file_reach`] indexes into this list.
365 #[serde(skip)]
366 pub reach_files: Vec<String>,
367 /// The files that each test file of `test_files` reaches through static
368 /// imports, as sorted indices into `reach_files`. The list leaves out the
369 /// test file itself and ignores `vi.mock`, so it is a superset of the
370 /// files that the test loads. The result cache of a run keys on the
371 /// content of these files.
372 #[serde(skip)]
373 pub test_file_reach: BTreeMap<String, Vec<u32>>,
374 /// The setup files of the test runner, the runner config modules at the
375 /// root ([`RUNNER_CONFIG_MODULES`]), and the files that they reach through
376 /// static imports, sorted. Each test loads them, so the result cache keys
377 /// on their content for each mutant.
378 #[serde(skip)]
379 pub support_files: Vec<String>,
380 /// The number of mutants for each disposition.
381 pub counts: MutationPlanCounts,
382 /// True when the project has no test files. Each mutant is then
383 /// `no-coverage`, and a report shows this one fact instead of one line
384 /// for each mutant.
385 pub no_test_files: bool,
386 /// True when the plan applied the `framework-config` prune rule. False
387 /// when the caller gave no framework config exports, so that a mutant in
388 /// such an export can be `planned`.
389 pub framework_config_checked: bool,
390 /// The selected files that the plan did not instrument, sorted by path.
391 pub skipped_files: Vec<SkippedFile>,
392 /// The paths of a `Paths` scope that select no source file, as given and
393 /// with forward slashes, sorted. A path can select no file because it
394 /// does not exist, or because it names only test code, declaration files
395 /// or files outside the module graph.
396 pub unmatched_paths: Vec<String>,
397}
398
399impl MutationPlan {
400 /// The files that `test_file` reaches through static imports, sorted.
401 /// Empty for a file that is not a test file of the plan.
402 pub fn test_file_reach_paths<'a>(&'a self, test_file: &str) -> impl Iterator<Item = &'a str> {
403 self.test_file_reach
404 .get(test_file)
405 .into_iter()
406 .flatten()
407 .filter_map(|&index| self.reach_files.get(index as usize))
408 .map(String::as_str)
409 }
410}
411
412/// An error from [`plan_mutations_for_session`].
413#[derive(Debug, Clone, PartialEq, Eq)]
414pub enum MutationPlanError {
415 /// The analysis failed.
416 Analysis(EngineError),
417 /// The analysis did not keep an artifact that the plan reads.
418 MissingArtifact(&'static str),
419 /// The plugin stage failed, so the plan cannot read the framework config
420 /// exports.
421 Plugins(String),
422}
423
424impl std::fmt::Display for MutationPlanError {
425 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
426 match self {
427 Self::Analysis(error) => write!(f, "the analysis failed: {error}"),
428 Self::MissingArtifact(name) => {
429 write!(
430 f,
431 "the analysis did not keep the {name} for the mutation plan"
432 )
433 }
434 Self::Plugins(message) => write!(f, "the plugin stage failed: {message}"),
435 }
436 }
437}
438
439impl std::error::Error for MutationPlanError {}
440
441impl From<EngineError> for MutationPlanError {
442 fn from(error: EngineError) -> Self {
443 Self::Analysis(error)
444 }
445}
446
447/// Builds the mutation plan from the facts of one analysis.
448#[must_use]
449pub fn plan_mutations(
450 inputs: &MutationPlanInputs<'_>,
451 request: &MutationPlanRequest,
452) -> MutationPlan {
453 plan::build(inputs, request)
454}
455
456/// Runs the dead-code analysis of `session` with complexity and the graph,
457/// then builds the mutation plan.
458///
459/// The framework config exports come from the plugin used-export rules of
460/// the session, the same rules that the unused-export analysis reads. The
461/// plugin stage runs one more time for them.
462///
463/// # Errors
464///
465/// Returns an error when the analysis or the plugin stage fails.
466pub fn plan_mutations_for_session(
467 session: &AnalysisSession,
468 request: &MutationPlanRequest,
469) -> Result<MutationPlan, MutationPlanError> {
470 plan_mutations_for_session_with(session, request, |_| false)
471}
472
473/// Like [`plan_mutations_for_session`], but `skip_components` reads the
474/// first plan and decides if the component files leave the plan. The test
475/// runner can depend on the test files of the plan, so the caller decides
476/// after the first plan. When the first plan has a component mutant and
477/// `skip_components` returns true, the plan is built again from the same
478/// analysis with [`MutationPlanRequest::skip_component_files`] set.
479///
480/// # Errors
481///
482/// Returns an error when the analysis or the plugin stage fails.
483pub fn plan_mutations_for_session_with(
484 session: &AnalysisSession,
485 request: &MutationPlanRequest,
486 skip_components: impl FnOnce(&MutationPlan) -> bool,
487) -> Result<MutationPlan, MutationPlanError> {
488 let artifacts = session.analyze_dead_code_with_artifacts(true, true)?;
489 let graph = artifacts
490 .graph
491 .as_ref()
492 .ok_or(MutationPlanError::MissingArtifact("module graph"))?;
493 let modules = artifacts
494 .modules
495 .as_deref()
496 .ok_or(MutationPlanError::MissingArtifact("parsed modules"))?;
497 let inventory = crate::list_inventory::collect_listing_inventory(session, false)
498 .map_err(|error| MutationPlanError::Plugins(error.message().to_owned()))?;
499 let framework_config_exports = framework_config_exports(session, graph, &inventory);
500 let setup_files = inventory.plugins.backend().setup_files();
501 let inputs = MutationPlanInputs {
502 root: session.root(),
503 graph,
504 modules,
505 results: &artifacts.results,
506 framework_config_exports: Some(&framework_config_exports),
507 setup_files: &setup_files,
508 };
509 let plan = plan_mutations(&inputs, request);
510 let has_component = plan
511 .mutants
512 .iter()
513 .any(|mutant| is_component_file(&mutant.file));
514 if request.skip_component_files || !has_component || !skip_components(&plan) {
515 return Ok(plan);
516 }
517 let request = MutationPlanRequest {
518 skip_component_files: true,
519 ..request.clone()
520 };
521 Ok(plan_mutations(&inputs, &request))
522}
523
524/// The plugin used-export names of each module of the graph. A tool reads
525/// the default export of its config file, so the default export of each file
526/// that a tool config glob of an active plugin matches is framework config
527/// too.
528fn framework_config_exports(
529 session: &AnalysisSession,
530 graph: &RetainedModuleGraph,
531 inventory: &crate::list_inventory::ListingInventory,
532) -> FrameworkConfigExports {
533 let backend = inventory.plugins.backend();
534 let names = backend.used_export_names();
535 let active = backend.active_plugins();
536 let external = session
537 .config()
538 .external_plugins
539 .iter()
540 .filter(|plugin| active.contains(&plugin.name))
541 .flat_map(|plugin| {
542 plugin
543 .config_patterns
544 .iter()
545 .chain(&plugin.always_used)
546 .cloned()
547 });
548 // Some plugins list their config file as always used, not as a config
549 // glob. The tool config name filter keeps the other always-used files
550 // out.
551 let patterns: Vec<String> = backend
552 .config_patterns()
553 .into_iter()
554 .chain(backend.always_used_patterns())
555 .chain(external)
556 .collect();
557 let config_files = config_file_globs(&patterns);
558 let mut exports = FrameworkConfigExports::default();
559 for node in &graph.as_graph().modules {
560 let rel = crate::module_graph::relative_key_path(&node.path, session.root());
561 for name in names.names_for(&rel) {
562 exports.insert(rel.clone(), name);
563 }
564 if config_files.is_match(&rel) {
565 exports.insert_config_file(rel);
566 }
567 }
568 exports
569}
570
571/// The export name of `export default` and of `module.exports = ...`.
572const DEFAULT_EXPORT: &str = "default";
573
574/// The word in a file name that marks a tool config file, as in
575/// `vite.config.ts`, `stryker.conf.js` or `tsconfig.json`.
576const CONFIG_NAME_MARKERS: [&str; 2] = ["config", ".conf."];
577
578/// True when the file name part of a plugin config glob names a tool config
579/// file: it holds `config` or `.conf.`, or an `rc` suffix as in
580/// `.eslintrc.js`. Some plugins also list application files as config, for
581/// example `codegen*.ts`, `src/module.ts` or `app/routes.ts`. Tests can load
582/// those files, so their default export stays in the plan.
583fn is_tool_config_glob(pattern: &str) -> bool {
584 let name = pattern
585 .rsplit('/')
586 .next()
587 .unwrap_or(pattern)
588 .to_ascii_lowercase();
589 if CONFIG_NAME_MARKERS
590 .iter()
591 .any(|marker| name.contains(marker))
592 {
593 return true;
594 }
595 let stem = name.split(['.', '{']).find(|part| !part.is_empty());
596 stem.is_some_and(|stem| stem.ends_with("rc"))
597}
598
599/// The tool config globs, each also tried under `**/`, because a glob is
600/// relative to the directory that the plugin searches, for example a
601/// workspace package.
602fn config_file_globs(patterns: &[String]) -> globset::GlobSet {
603 let mut builder = globset::GlobSetBuilder::new();
604 for pattern in patterns
605 .iter()
606 .filter(|pattern| is_tool_config_glob(pattern))
607 {
608 let anywhere = if pattern.starts_with("**/") {
609 pattern.clone()
610 } else {
611 format!("**/{pattern}")
612 };
613 for candidate in [pattern.as_str(), anywhere.as_str()] {
614 if let Ok(glob) = globset::Glob::new(candidate) {
615 builder.add(glob);
616 }
617 }
618 }
619 builder
620 .build()
621 .unwrap_or_else(|_| globset::GlobSet::empty())
622}