Skip to main content

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