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 };
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
131fn 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
155fn 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
180fn 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#[derive(Debug, Default)]
211pub struct Protected {
212 overlap: Vec<(u32, u32)>,
214 contain: Vec<(u32, u32)>,
216}
217
218impl Protected {
219 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
231const VUE_MACROS: [&str; 7] = [
235 "defineProps",
236 "defineEmits",
237 "defineExpose",
238 "defineModel",
239 "defineOptions",
240 "defineSlots",
241 "withDefaults",
242];
243
244const SVELTE_RUNES: [&str; 7] = [
246 "$state",
247 "$derived",
248 "$effect",
249 "$props",
250 "$bindable",
251 "$inspect",
252 "$host",
253];
254
255pub 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
298struct CallFinder {
301 names: &'static [&'static str],
302 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}