1use syn::spanned::Spanned;
4
5use crate::plan::CmpOp;
6
7use super::discover::written_bool;
8use super::model::{ArmGuard, Site, SiteKind};
9
10#[derive(Clone, PartialEq, Eq, Debug)]
12pub struct SourceMutant {
13 pub start: usize,
14 pub end: usize,
15 pub replacement: String,
16 pub what: String,
19 pub into: String,
20}
21
22pub(crate) fn source_boundary_mutant(site: &Site) -> Option<SourceMutant> {
28 let SiteKind::Cmp { op, gap, .. } = &site.kind else {
29 return None;
30 };
31 let replacement = match op {
32 CmpOp::Le => "<",
33 CmpOp::Ge => ">",
34 _ => return None,
35 };
36 Some(SourceMutant {
37 start: gap.0,
38 end: gap.1,
39 replacement: format!(" {replacement} "),
40 what: op.symbol().to_string(),
41 into: replacement.to_string(),
42 })
43}
44
45pub fn keep_line_ends(source: &str, mutants: &mut [SourceMutant]) {
48 for mutant in mutants {
49 let Some(replaced) = source.get(mutant.start..mutant.end) else {
50 continue;
51 };
52 let lines = replaced.matches('\n').count();
53 let kept = mutant.replacement.matches('\n').count();
54 mutant
55 .replacement
56 .push_str(&"\n".repeat(lines.saturating_sub(kept)));
57 }
58}
59
60pub fn source_mutants(site: &Site) -> Vec<SourceMutant> {
61 let change =
62 |start: usize, end: usize, replacement: String, what: &str, into: &str| SourceMutant {
63 start,
64 end,
65 replacement,
66 what: what.to_string(),
67 into: into.to_string(),
68 };
69 let operator = |gap: &(usize, usize), from: String, to: String, binds: std::cmp::Ordering| {
72 let operands = gap
74 .0
75 .checked_sub(site.start)
76 .zip(gap.1.checked_sub(site.start))
77 .and_then(|(left, right)| {
78 Some((
79 site.text.get(..left)?.trim_end(),
80 site.text.get(right..)?.trim_start(),
81 "\n".repeat(site.text.get(left..right)?.matches('\n').count()),
84 ))
85 });
86 match (binds, operands) {
87 (std::cmp::Ordering::Less, Some((left, right, lines))) => change(
88 site.start,
89 site.end,
90 format!("({left} {to} {lines}{right})"),
91 &from,
92 &to,
93 ),
94 (std::cmp::Ordering::Greater, Some((left, right, lines))) => change(
95 site.start,
96 site.end,
97 format!("({left}) {to} {lines}({right})"),
98 &from,
99 &to,
100 ),
101 _ => change(gap.0, gap.1, format!(" {to} "), &from, &to),
102 }
103 };
104 let same = std::cmp::Ordering::Equal;
105 match &site.kind {
106 SiteKind::Cmp { op, gap, .. } => {
107 let others: &[CmpOp] = match op {
108 CmpOp::Lt => &[CmpOp::Eq, CmpOp::Gt, CmpOp::Le],
109 CmpOp::Gt => &[CmpOp::Eq, CmpOp::Lt, CmpOp::Ge],
110 CmpOp::Le => &[CmpOp::Gt],
111 CmpOp::Ge => &[CmpOp::Lt],
112 CmpOp::Eq => &[CmpOp::Ne],
113 CmpOp::Ne => &[CmpOp::Eq],
114 };
115 others
116 .iter()
117 .map(|other| operator(gap, op.symbol().into(), other.symbol().into(), same))
118 .collect()
119 }
120 SiteKind::Logic { and, gap, .. } => {
121 let (from, to, binds) = if *and {
123 ("&&", "||", std::cmp::Ordering::Less)
124 } else {
125 ("||", "&&", std::cmp::Ordering::Greater)
126 };
127 vec![operator(gap, from.into(), to.into(), binds)]
128 }
129 SiteKind::Arith {
130 op, assign, gap, ..
131 } => {
132 let eq = if *assign { "=" } else { "" };
133 [Some(op.swapped()), op.second(*assign)]
134 .into_iter()
135 .flatten()
136 .map(|other| {
137 operator(
138 gap,
139 format!("{}{eq}", op.symbol()),
140 format!("{}{eq}", other.symbol()),
141 if *assign {
143 same
144 } else {
145 other.binding().cmp(&op.binding())
146 },
147 )
148 })
149 .collect()
150 }
151 SiteKind::Not {
152 bang, needs_space, ..
153 } => vec![change(
154 bang.0,
155 bang.1,
156 if *needs_space { " " } else { "" }.to_string(),
157 "!",
158 "",
159 )],
160 SiteKind::Neg {
161 minus, needs_space, ..
162 } => vec![change(
163 minus.0,
164 minus.1,
165 if *needs_space { " " } else { "" }.to_string(),
166 "-",
167 "",
168 )],
169 SiteKind::Body { value, .. } => {
170 vec![change(
171 site.start,
172 site.end,
173 format!(" {value} "),
174 "body",
175 value,
176 )]
177 }
178 SiteKind::Arm {
179 pattern,
180 guard,
181 removal,
182 } => vec![match guard {
183 ArmGuard::None(_) => change(removal.0, removal.1, String::new(), "arm", pattern),
184 ArmGuard::Existing(from, to) => change(*from, *to, "false".into(), "arm", pattern),
185 }],
186 SiteKind::Guard { can_be_false } => [true, false]
187 .into_iter()
188 .filter(|value| *value || *can_be_false)
189 .filter(|value| {
191 syn::parse_str::<syn::Expr>(&site.text)
192 .ok()
193 .and_then(|guard| written_bool(&guard))
194 != Some(*value)
195 })
196 .map(|value| {
197 change(
198 site.start,
199 site.end,
200 value.to_string(),
201 "guard",
202 &value.to_string(),
203 )
204 })
205 .collect(),
206 SiteKind::Field { name, removal, .. } => {
207 vec![change(removal.0, removal.1, String::new(), "field", name)]
208 }
209 SiteKind::Stmt => vec![change(site.start, site.end, String::new(), "statement", "")],
210 SiteKind::Range { inclusive, gap, .. } => {
212 let (from, to) = if *inclusive {
213 ("..=", "..")
214 } else {
215 ("..", "..=")
216 };
217 vec![change(gap.0, gap.1, to.to_string(), from, to)]
218 }
219 SiteKind::SliceEnd { first, method, .. } => {
222 let (from, to) = if *first {
223 ("first", "last")
224 } else {
225 ("last", "first")
226 };
227 vec![change(method.0, method.1, to.to_string(), from, to)]
228 }
229 SiteKind::StrAffix { starts, method, .. } => {
230 let from = if *starts { "starts_with" } else { "ends_with" };
231 vec![change(
232 method.0,
233 method.1,
234 "contains".into(),
235 from,
236 "contains",
237 )]
238 }
239 SiteKind::StrReplace {
240 replace_all,
241 from,
242 to,
243 method,
244 close,
245 ..
246 } => {
247 let args_slice = method
250 .1
251 .checked_sub(site.start)
252 .zip(close.0.checked_sub(site.start))
253 .and_then(|(s, e)| site.text.get(s..e));
254 if *replace_all {
255 let replacement = match args_slice {
256 Some(slice) => format!("replacen{slice}, 1)"),
257 None => format!("replacen({from}, {to}, 1)"),
258 };
259 vec![change(
260 method.0,
261 close.1,
262 replacement,
263 "replace",
264 "replacen(..., 1)",
265 )]
266 } else {
267 let replacement = match args_slice {
268 Some(slice) => format!("replace{slice})"),
269 None => format!("replace({from}, {to})"),
270 };
271 vec![change(
272 method.0,
273 close.1,
274 replacement,
275 "replacen",
276 "replace",
277 )]
278 }
279 }
280 SiteKind::Clamp {
281 low,
282 high,
283 call,
284 comma,
285 close,
286 ..
287 } => {
288 let drop_lower = call
290 .0
291 .checked_sub(site.start)
292 .zip(comma.1.checked_sub(site.start))
293 .and_then(|(s, e)| site.text.get(s..e))
294 .map(|dropped| {
295 change(
296 call.0,
297 comma.1,
298 format!(".min({}", "\n".repeat(dropped.matches('\n').count())),
299 "clamp",
300 "min (drop lower)",
301 )
302 })
303 .unwrap_or_else(|| {
304 change(
305 call.0,
306 close.1,
307 format!(".min({high})"),
308 "clamp",
309 "min (drop lower)",
310 )
311 });
312 let drop_upper = call
313 .0
314 .checked_sub(site.start)
315 .zip(call.1.checked_sub(site.start))
316 .zip(comma.0.checked_sub(site.start))
317 .and_then(|((cs, ce), le)| {
318 let before_low = site.text.get(cs..ce)?;
319 let low_slice = site.text.get(ce..le)?;
320 Some(change(
321 call.0,
322 close.1,
323 format!(
324 ".max({}{low_slice})",
325 "\n".repeat(before_low.matches('\n').count())
326 ),
327 "clamp",
328 "max (drop upper)",
329 ))
330 })
331 .unwrap_or_else(|| {
332 change(
333 call.0,
334 close.1,
335 format!(".max({low})"),
336 "clamp",
337 "max (drop upper)",
338 )
339 });
340 vec![drop_lower, drop_upper]
341 }
342 SiteKind::Rounding { op, method, .. } => vec![
343 change(
344 method.0,
345 method.1,
346 op.alt1().name().into(),
347 op.name(),
348 op.alt1().name(),
349 ),
350 change(
351 method.0,
352 method.1,
353 op.alt2().name().into(),
354 op.name(),
355 op.alt2().name(),
356 ),
357 ],
358 SiteKind::Quantifier { all, method, .. } => {
359 let (from, to) = if *all { ("all", "any") } else { ("any", "all") };
360 vec![change(method.0, method.1, to.into(), from, to)]
361 }
362 SiteKind::SaturatingArith { op, method, .. } => {
363 let to = op.swapped().name();
364 vec![change(method.0, method.1, to.into(), op.name(), to)]
365 }
366 SiteKind::StrTrim { op, method, .. } => {
367 let mut out = vec![change(
368 method.0,
369 method.1,
370 op.alt1().name().into(),
371 op.name(),
372 op.alt1().name(),
373 )];
374 if let Some(alt2) = op.alt2() {
375 out.push(change(
376 method.0,
377 method.1,
378 alt2.name().into(),
379 op.name(),
380 alt2.name(),
381 ));
382 }
383 out
384 }
385 SiteKind::StrCaseEq { method, .. } => {
386 vec![change(
389 method.0,
390 method.1,
391 "eq".into(),
392 "eq_ignore_ascii_case",
393 "eq",
394 )]
395 }
396 SiteKind::Abs { call, .. } => {
397 vec![change(call.0, call.1, String::new(), ".abs()", "")]
398 }
399 SiteKind::IterLimit {
400 take,
401 count,
402 call,
403 close,
404 ..
405 } => {
406 let (from, target) = if *take {
407 ("take", "usize::MAX")
408 } else {
409 ("skip", "0")
410 };
411 let count_slice = call
412 .1
413 .checked_sub(site.start)
414 .zip(close.0.checked_sub(site.start))
415 .and_then(|(s, e)| site.text.get(s..e))
416 .unwrap_or(count.as_str());
417 let pure_count = syn::parse_str::<syn::Expr>(count_slice)
418 .ok()
419 .is_some_and(|e| matches!(e, syn::Expr::Lit(_) | syn::Expr::Path(_)));
420 let replacement = if pure_count {
421 target.to_string()
422 } else {
423 format!("{{ let _ = ({count_slice}); {target} }}")
424 };
425 vec![change(call.1, close.0, replacement, from, target)]
426 }
427 SiteKind::EndianSwap { op, method, .. } => {
428 let to = op.swapped().name();
429 vec![change(method.0, method.1, to.into(), op.name(), to)]
430 }
431 SiteKind::BitCount { op, method, .. } => {
432 let to = op.swapped().name();
433 vec![change(method.0, method.1, to.into(), op.name(), to)]
434 }
435 SiteKind::LoopCtrl { is_break } => {
436 let (from, to) = if *is_break {
437 ("break", "continue")
438 } else {
439 ("continue", "break")
440 };
441 vec![change(site.start, site.end, to.into(), from, to)]
442 }
443 SiteKind::LiteralSet { elements, .. } => elements
444 .iter()
445 .map(|(elem, start, end)| change(*start, *end, String::new(), "literal_set", elem))
446 .collect(),
447 SiteKind::Return { .. } | SiteKind::MinMax { .. } => vec![],
448 }
449}
450
451pub(crate) fn literal_operator_mutants(source: &str, site: &Site, mutants: &mut [SourceMutant]) {
453 let gap = match &site.kind {
454 SiteKind::Cmp { gap, .. } | SiteKind::Logic { gap, .. } | SiteKind::Arith { gap, .. } => {
455 gap
456 }
457 _ => return,
458 };
459 if let Ok(operator) = syn::parse_str::<syn::BinOp>(&source[gap.0..gap.1]) {
460 let span = operator.span().byte_range();
461 for mutant in mutants {
462 mutant.start = gap.0 + span.start;
463 mutant.end = gap.0 + span.end;
464 mutant.replacement.clone_from(&mutant.into);
465 }
466 }
467}