1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum ScriptRole {
38 VueScript,
40 VueSetup,
42 SvelteModule,
45 SvelteInstance,
48 AstroFrontmatter,
51}
52
53impl ScriptRole {
54 const fn is_module_scope(self) -> bool {
56 matches!(self, Self::VueScript | Self::SvelteModule)
57 }
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub struct ScriptBlock {
63 pub span: (u32, u32),
65 pub kind: SourceKind,
67 pub role: ScriptRole,
69}
70
71pub 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
133fn 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
157fn 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
182fn 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#[derive(Debug, Default)]
213pub struct Protected {
214 overlap: Vec<(u32, u32)>,
216 contain: Vec<(u32, u32)>,
218}
219
220impl Protected {
221 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
233const VUE_MACROS: [&str; 7] = [
237 "defineProps",
238 "defineEmits",
239 "defineExpose",
240 "defineModel",
241 "defineOptions",
242 "defineSlots",
243 "withDefaults",
244];
245
246const SVELTE_RUNES: [&str; 7] = [
248 "$state",
249 "$derived",
250 "$effect",
251 "$props",
252 "$bindable",
253 "$inspect",
254 "$host",
255];
256
257pub 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
300struct CallFinder {
303 names: &'static [&'static str],
304 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}