Skip to main content

fallow_mutation/
blocks.rs

1//! Instrumentation of the script blocks in a component file.
2//!
3//! A Vue or Svelte single-file component and an Astro component hold their
4//! code in script blocks. The instrumented file is the whole component file
5//! with each script block replaced by its instrumented text, so the framework
6//! compiler sees the same template and styles. The caller finds the blocks;
7//! this crate has no component parser.
8//!
9//! The framework compilers move some code out of the block scope. A mutation
10//! switch in that code cannot reach the prelude, or the compiler refuses the
11//! switch. These positions give no mutant:
12//!
13//! - Vue `<script setup>`: a compiler macro call and its arguments
14//!   (`defineProps`, `defineExpose`, `withDefaults` and the other `define*`
15//!   macros), and the destructure defaults of a declaration with a macro
16//!   call. The compiler moves them out of `setup()` or replaces the call, so
17//!   a switch around the call hides the macro.
18//! - Svelte: an expression that holds a rune call (`$state(...)`,
19//!   `$effect(...)` and the other runes). A rune must stay in its own
20//!   position. The rune arguments still give mutants.
21//! - Astro frontmatter: an exported declaration. The compiler moves it out of
22//!   the render function.
23
24use std::collections::BTreeSet;
25
26use oxc_ast::ast::{CallExpression, Expression, Program, Statement, VariableDeclarator};
27use oxc_ast_visit::{Visit, walk};
28use oxc_span::GetSpan;
29
30use crate::{
31    Instrumented, MutantId, MutationError, MutationOptions, SourceKind, SpliceMap, SpliceSegment,
32    TextInput, instrument_text, line_column, line_starts,
33};
34
35/// The role of a script block in a component file.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum ScriptRole {
38    /// A Vue `<script>` block without `setup`. The code runs at module scope.
39    VueScript,
40    /// A Vue `<script setup>` block. The code runs in `setup()`.
41    VueSetup,
42    /// A Svelte module script (`<script module>` or
43    /// `<script context="module">`). The code runs at module scope.
44    SvelteModule,
45    /// A Svelte instance script. The code runs once for each component
46    /// instance.
47    SvelteInstance,
48    /// The frontmatter of an Astro component. The code runs in the render
49    /// function.
50    AstroFrontmatter,
51}
52
53impl ScriptRole {
54    /// True when the block code runs at module scope.
55    const fn is_module_scope(self) -> bool {
56        matches!(self, Self::VueScript | Self::SvelteModule)
57    }
58}
59
60/// One script block of a component file.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub struct ScriptBlock {
63    /// The byte span of the block body in the component file.
64    pub span: (u32, u32),
65    /// The language of the block body.
66    pub kind: SourceKind,
67    /// The role of the block.
68    pub role: ScriptRole,
69}
70
71/// Finds the mutants in the script blocks of a component file and returns
72/// the instrumented file.
73///
74/// The spans, lines and columns of the mutants, the ranges of `options` and
75/// the splice map use the coordinates of the whole file. The text outside
76/// the blocks stays the same. A block that is outside the file, or that
77/// overlaps an earlier block, is ignored.
78///
79/// The prelude goes into each block with module scope. When the file has no
80/// such block, it goes into each block, because each block then has its own
81/// scope.
82pub fn instrument_blocks(
83    source: &str,
84    path: &str,
85    blocks: &[ScriptBlock],
86    options: &MutationOptions,
87) -> Result<Instrumented, MutationError> {
88    if u32::try_from(source.len()).is_err() {
89        return Err(MutationError::TooLarge);
90    }
91    let ordered = valid_blocks(source, blocks);
92    let module_scope = ordered.iter().any(|block| block.role.is_module_scope());
93    let starts = line_starts(source);
94    let mut seen_ids: BTreeSet<MutantId> = BTreeSet::new();
95    let mut output = Instrumented {
96        mutants: Vec::new(),
97        code: String::with_capacity(source.len() * 2),
98        map: SpliceMap::default(),
99    };
100    let mut cursor = 0;
101    for block in ordered {
102        copy_original(source, (cursor, block.span.0), &mut output);
103        let (start, end) = block.span;
104        let input = TextInput {
105            source: &source[start as usize..end as usize],
106            path,
107            kind: block.kind,
108            role: Some(block.role),
109            prelude: !module_scope || block.role.is_module_scope(),
110            probe: None,
111        };
112        let local_options = MutationOptions {
113            operators: options.operators.clone(),
114            ranges: options
115                .ranges
116                .as_ref()
117                .map(|ranges| local_ranges(ranges, block.span)),
118            record_exports: false,
119            excluded: options.excluded.clone(),
120        };
121        let (result, _) = instrument_text(&input, &local_options, &mut seen_ids)?;
122        append_block(result, start, &starts, &mut output)?;
123        cursor = end;
124    }
125    copy_original(source, (cursor, source.len() as u32), &mut output);
126    output.mutants.sort_by_key(|mutant| mutant.span);
127    if u32::try_from(output.code.len()).is_err() {
128        return Err(MutationError::TooLarge);
129    }
130    Ok(output)
131}
132
133/// The blocks in file order, without a block that is outside the file, that
134/// does not start and end on a character boundary, or that overlaps an
135/// earlier block.
136fn valid_blocks(source: &str, blocks: &[ScriptBlock]) -> Vec<ScriptBlock> {
137    let mut ordered: Vec<ScriptBlock> = blocks
138        .iter()
139        .copied()
140        .filter(|block| {
141            let (start, end) = (block.span.0 as usize, block.span.1 as usize);
142            start <= end && source.get(start..end).is_some()
143        })
144        .collect();
145    ordered.sort_by_key(|block| block.span);
146    let mut end = 0;
147    ordered.retain(|block| {
148        let keep = block.span.0 >= end;
149        if keep {
150            end = block.span.1;
151        }
152        keep
153    });
154    ordered
155}
156
157/// The parts of `ranges` inside `block`, relative to the block start.
158fn local_ranges(ranges: &[(u32, u32)], block: (u32, u32)) -> Vec<(u32, u32)> {
159    ranges
160        .iter()
161        .filter_map(|&(from, to)| {
162            let start = from.max(block.0);
163            let end = to.min(block.1);
164            (start < end).then(|| (start - block.0, end - block.0))
165        })
166        .collect()
167}
168
169fn copy_original(source: &str, span: (u32, u32), output: &mut Instrumented) {
170    let (from, to) = span;
171    if to <= from {
172        return;
173    }
174    output.map.segments.push(SpliceSegment {
175        generated_start: output.code.len() as u32,
176        original_start: from,
177        len: to - from,
178    });
179    output.code.push_str(&source[from as usize..to as usize]);
180}
181
182/// Appends the instrumented block at the end of `output` and moves its
183/// mutants and map to the coordinates of the whole file.
184fn append_block(
185    block: Instrumented,
186    start: u32,
187    starts: &[u32],
188    output: &mut Instrumented,
189) -> Result<(), MutationError> {
190    let base = u32::try_from(output.code.len()).map_err(|_| MutationError::TooLarge)?;
191    output
192        .map
193        .segments
194        .extend(block.map.segments.into_iter().map(|segment| SpliceSegment {
195            generated_start: segment.generated_start + base,
196            original_start: segment.original_start + start,
197            len: segment.len,
198        }));
199    output.code.push_str(&block.code);
200    for mut mutant in block.mutants {
201        mutant.span = (mutant.span.0 + start, mutant.span.1 + start);
202        (mutant.line, mutant.column) = line_column(starts, mutant.span.0);
203        if let Some(function) = &mut mutant.enclosing_function {
204            function.span = (function.span.0 + start, function.span.1 + start);
205        }
206        output.mutants.push(mutant);
207    }
208    Ok(())
209}
210
211/// The spans that limit the sites of one block.
212#[derive(Debug, Default)]
213pub struct Protected {
214    /// A site that overlaps one of these spans gives no mutant.
215    overlap: Vec<(u32, u32)>,
216    /// A site that contains one of these spans gives no mutant.
217    contain: Vec<(u32, u32)>,
218}
219
220impl Protected {
221    /// True when the site with `span` gives no mutant.
222    pub fn excludes(&self, span: (u32, u32)) -> bool {
223        self.overlap
224            .iter()
225            .any(|&(start, end)| start < span.1 && span.0 < end)
226            || self
227                .contain
228                .iter()
229                .any(|&(start, end)| span.0 <= start && end <= span.1)
230    }
231}
232
233/// The Vue compiler macros. The compiler moves their arguments out of
234/// `setup()`, or replaces the call. A switch around a macro call hides it
235/// from the compiler, so the call and its arguments give no mutant.
236const VUE_MACROS: [&str; 7] = [
237    "defineProps",
238    "defineEmits",
239    "defineExpose",
240    "defineModel",
241    "defineOptions",
242    "defineSlots",
243    "withDefaults",
244];
245
246/// The Svelte runes. A rune call must stay in its own position.
247const SVELTE_RUNES: [&str; 7] = [
248    "$state",
249    "$derived",
250    "$effect",
251    "$props",
252    "$bindable",
253    "$inspect",
254    "$host",
255];
256
257/// The spans of `program` that limit the sites of a block with `role`.
258pub fn protected_spans(program: &Program<'_>, role: ScriptRole) -> Protected {
259    let mut protected = Protected::default();
260    match role {
261        ScriptRole::VueScript => {}
262        ScriptRole::VueSetup => {
263            let mut finder = CallFinder {
264                names: &VUE_MACROS,
265                declarators: true,
266                spans: Vec::new(),
267            };
268            finder.visit_program(program);
269            protected.overlap = finder.spans;
270        }
271        ScriptRole::SvelteModule | ScriptRole::SvelteInstance => {
272            let mut finder = CallFinder {
273                names: &SVELTE_RUNES,
274                declarators: false,
275                spans: Vec::new(),
276            };
277            finder.visit_program(program);
278            protected.contain = finder.spans;
279        }
280        ScriptRole::AstroFrontmatter => {
281            protected.overlap = program
282                .body
283                .iter()
284                .filter(|statement| {
285                    matches!(
286                        statement,
287                        Statement::ExportDeclaration(_) | Statement::ExportDefaultDeclaration(_)
288                    )
289                })
290                .map(|statement| {
291                    let span = statement.span();
292                    (span.start, span.end)
293                })
294                .collect();
295        }
296    }
297    protected
298}
299
300/// Finds the calls whose callee is one of `names`, or a member of one of
301/// `names` (`$state.raw(...)`, `$effect.pre(...)`).
302struct CallFinder {
303    names: &'static [&'static str],
304    /// Also gives the whole declarator when such a call is its initializer.
305    /// The Vue compiler moves the destructure defaults of
306    /// `const { size = 1 } = defineProps()` into the props options.
307    declarators: bool,
308    spans: Vec<(u32, u32)>,
309}
310
311impl CallFinder {
312    fn matches(&self, callee: &Expression<'_>) -> bool {
313        let mut current = callee;
314        loop {
315            match current {
316                Expression::Identifier(identifier) => {
317                    return self.names.contains(&identifier.name.as_str());
318                }
319                Expression::StaticMemberExpression(member) => current = &member.object,
320                Expression::ParenthesizedExpression(inner) => current = &inner.expression,
321                _ => return false,
322            }
323        }
324    }
325}
326
327impl<'a> Visit<'a> for CallFinder {
328    fn visit_variable_declarator(&mut self, it: &VariableDeclarator<'a>) {
329        let call = it
330            .init
331            .as_ref()
332            .and_then(|init| match init.without_parentheses() {
333                Expression::CallExpression(call) => Some(call),
334                _ => None,
335            });
336        if self.declarators && call.is_some_and(|call| self.matches(&call.callee)) {
337            self.spans.push((it.span.start, it.span.end));
338        }
339        walk::walk_variable_declarator(self, it);
340    }
341
342    fn visit_call_expression(&mut self, it: &CallExpression<'a>) {
343        if self.matches(&it.callee) {
344            self.spans.push((it.span.start, it.span.end));
345        }
346        walk::walk_call_expression(self, it);
347    }
348}