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