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::Return { .. } | SiteKind::MinMax { .. } => vec![],
230 }
231}
232
233pub(crate) fn literal_operator_mutants(source: &str, site: &Site, mutants: &mut [SourceMutant]) {
235 let gap = match &site.kind {
236 SiteKind::Cmp { gap, .. } | SiteKind::Logic { gap, .. } | SiteKind::Arith { gap, .. } => {
237 gap
238 }
239 _ => return,
240 };
241 if let Ok(operator) = syn::parse_str::<syn::BinOp>(&source[gap.0..gap.1]) {
242 let span = operator.span().byte_range();
243 for mutant in mutants {
244 mutant.start = gap.0 + span.start;
245 mutant.end = gap.0 + span.end;
246 mutant.replacement.clone_from(&mutant.into);
247 }
248 }
249}