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        };
111        let local_options = MutationOptions {
112            operators: options.operators.clone(),
113            ranges: options
114                .ranges
115                .as_ref()
116                .map(|ranges| local_ranges(ranges, block.span)),
117            record_exports: false,
118        };
119        let result = instrument_text(&input, &local_options, &mut seen_ids)?;
120        append_block(result, start, &starts, &mut output)?;
121        cursor = end;
122    }
123    copy_original(source, (cursor, source.len() as u32), &mut output);
124    output.mutants.sort_by_key(|mutant| mutant.span);
125    if u32::try_from(output.code.len()).is_err() {
126        return Err(MutationError::TooLarge);
127    }
128    Ok(output)
129}
130
131/// The blocks in file order, without a block that is outside the file, that
132/// does not start and end on a character boundary, or that overlaps an
133/// earlier block.
134fn valid_blocks(source: &str, blocks: &[ScriptBlock]) -> Vec<ScriptBlock> {
135    let mut ordered: Vec<ScriptBlock> = blocks
136        .iter()
137        .copied()
138        .filter(|block| {
139            let (start, end) = (block.span.0 as usize, block.span.1 as usize);
140            start <= end && source.get(start..end).is_some()
141        })
142        .collect();
143    ordered.sort_by_key(|block| block.span);
144    let mut end = 0;
145    ordered.retain(|block| {
146        let keep = block.span.0 >= end;
147        if keep {
148            end = block.span.1;
149        }
150        keep
151    });
152    ordered
153}
154
155/// The parts of `ranges` inside `block`, relative to the block start.
156fn local_ranges(ranges: &[(u32, u32)], block: (u32, u32)) -> Vec<(u32, u32)> {
157    ranges
158        .iter()
159        .filter_map(|&(from, to)| {
160            let start = from.max(block.0);
161            let end = to.min(block.1);
162            (start < end).then(|| (start - block.0, end - block.0))
163        })
164        .collect()
165}
166
167fn copy_original(source: &str, span: (u32, u32), output: &mut Instrumented) {
168    let (from, to) = span;
169    if to <= from {
170        return;
171    }
172    output.map.segments.push(SpliceSegment {
173        generated_start: output.code.len() as u32,
174        original_start: from,
175        len: to - from,
176    });
177    output.code.push_str(&source[from as usize..to as usize]);
178}
179
180/// Appends the instrumented block at the end of `output` and moves its
181/// mutants and map to the coordinates of the whole file.
182fn append_block(
183    block: Instrumented,
184    start: u32,
185    starts: &[u32],
186    output: &mut Instrumented,
187) -> Result<(), MutationError> {
188    let base = u32::try_from(output.code.len()).map_err(|_| MutationError::TooLarge)?;
189    output
190        .map
191        .segments
192        .extend(block.map.segments.into_iter().map(|segment| SpliceSegment {
193            generated_start: segment.generated_start + base,
194            original_start: segment.original_start + start,
195            len: segment.len,
196        }));
197    output.code.push_str(&block.code);
198    for mut mutant in block.mutants {
199        mutant.span = (mutant.span.0 + start, mutant.span.1 + start);
200        (mutant.line, mutant.column) = line_column(starts, mutant.span.0);
201        if let Some(function) = &mut mutant.enclosing_function {
202            function.span = (function.span.0 + start, function.span.1 + start);
203        }
204        output.mutants.push(mutant);
205    }
206    Ok(())
207}
208
209/// The spans that limit the sites of one block.
210#[derive(Debug, Default)]
211pub struct Protected {
212    /// A site that overlaps one of these spans gives no mutant.
213    overlap: Vec<(u32, u32)>,
214    /// A site that contains one of these spans gives no mutant.
215    contain: Vec<(u32, u32)>,
216}
217
218impl Protected {
219    /// True when the site with `span` gives no mutant.
220    pub fn excludes(&self, span: (u32, u32)) -> bool {
221        self.overlap
222            .iter()
223            .any(|&(start, end)| start < span.1 && span.0 < end)
224            || self
225                .contain
226                .iter()
227                .any(|&(start, end)| span.0 <= start && end <= span.1)
228    }
229}
230
231/// The Vue compiler macros. The compiler moves their arguments out of
232/// `setup()`, or replaces the call. A switch around a macro call hides it
233/// from the compiler, so the call and its arguments give no mutant.
234const VUE_MACROS: [&str; 7] = [
235    "defineProps",
236    "defineEmits",
237    "defineExpose",
238    "defineModel",
239    "defineOptions",
240    "defineSlots",
241    "withDefaults",
242];
243
244/// The Svelte runes. A rune call must stay in its own position.
245const SVELTE_RUNES: [&str; 7] = [
246    "$state",
247    "$derived",
248    "$effect",
249    "$props",
250    "$bindable",
251    "$inspect",
252    "$host",
253];
254
255/// The spans of `program` that limit the sites of a block with `role`.
256pub fn protected_spans(program: &Program<'_>, role: ScriptRole) -> Protected {
257    let mut protected = Protected::default();
258    match role {
259        ScriptRole::VueScript => {}
260        ScriptRole::VueSetup => {
261            let mut finder = CallFinder {
262                names: &VUE_MACROS,
263                declarators: true,
264                spans: Vec::new(),
265            };
266            finder.visit_program(program);
267            protected.overlap = finder.spans;
268        }
269        ScriptRole::SvelteModule | ScriptRole::SvelteInstance => {
270            let mut finder = CallFinder {
271                names: &SVELTE_RUNES,
272                declarators: false,
273                spans: Vec::new(),
274            };
275            finder.visit_program(program);
276            protected.contain = finder.spans;
277        }
278        ScriptRole::AstroFrontmatter => {
279            protected.overlap = program
280                .body
281                .iter()
282                .filter(|statement| {
283                    matches!(
284                        statement,
285                        Statement::ExportDeclaration(_) | Statement::ExportDefaultDeclaration(_)
286                    )
287                })
288                .map(|statement| {
289                    let span = statement.span();
290                    (span.start, span.end)
291                })
292                .collect();
293        }
294    }
295    protected
296}
297
298/// Finds the calls whose callee is one of `names`, or a member of one of
299/// `names` (`$state.raw(...)`, `$effect.pre(...)`).
300struct CallFinder {
301    names: &'static [&'static str],
302    /// Also gives the whole declarator when such a call is its initializer.
303    /// The Vue compiler moves the destructure defaults of
304    /// `const { size = 1 } = defineProps()` into the props options.
305    declarators: bool,
306    spans: Vec<(u32, u32)>,
307}
308
309impl CallFinder {
310    fn matches(&self, callee: &Expression<'_>) -> bool {
311        let mut current = callee;
312        loop {
313            match current {
314                Expression::Identifier(identifier) => {
315                    return self.names.contains(&identifier.name.as_str());
316                }
317                Expression::StaticMemberExpression(member) => current = &member.object,
318                Expression::ParenthesizedExpression(inner) => current = &inner.expression,
319                _ => return false,
320            }
321        }
322    }
323}
324
325impl<'a> Visit<'a> for CallFinder {
326    fn visit_variable_declarator(&mut self, it: &VariableDeclarator<'a>) {
327        let call = it
328            .init
329            .as_ref()
330            .and_then(|init| match init.without_parentheses() {
331                Expression::CallExpression(call) => Some(call),
332                _ => None,
333            });
334        if self.declarators && call.is_some_and(|call| self.matches(&call.callee)) {
335            self.spans.push((it.span.start, it.span.end));
336        }
337        walk::walk_variable_declarator(self, it);
338    }
339
340    fn visit_call_expression(&mut self, it: &CallExpression<'a>) {
341        if self.matches(&it.callee) {
342            self.spans.push((it.span.start, it.span.end));
343        }
344        walk::walk_call_expression(self, it);
345    }
346}