1use crate::error::{Applicability, CompileError, Severity};
23use crate::span::Span;
24
25pub fn lone_fix(error: &CompileError) -> Option<&crate::error::Suggestion> {
29 let mut applicable = error
30 .suggestions
31 .iter()
32 .filter(|s| s.applicability == Applicability::MachineApplicable);
33 match (applicable.next(), applicable.next()) {
34 (Some(s), None) => Some(s),
35 _ => None,
36 }
37}
38
39#[derive(Debug, Clone, Default, PartialEq, Eq)]
42pub struct Selection {
43 pub edits: Vec<(Span, String)>,
45 pub categories: Vec<&'static str>,
46}
47
48pub fn edits<'a>(
53 text: &str,
54 errors: impl IntoIterator<Item = &'a CompileError>,
55) -> Vec<(Span, String)> {
56 select(text, errors).edits
57}
58
59pub fn select<'a>(text: &str, errors: impl IntoIterator<Item = &'a CompileError>) -> Selection {
61 pick(text, errors, |e| Severity::for_error(e) != Severity::Hint)
64}
65
66pub fn select_codes<'a>(
70 text: &str,
71 errors: impl IntoIterator<Item = &'a CompileError>,
72 codes: &[String],
73) -> Selection {
74 pick(text, errors, |e| codes.iter().any(|c| c == e.category))
75}
76
77fn pick<'a>(
78 text: &str,
79 errors: impl IntoIterator<Item = &'a CompileError>,
80 admit: impl Fn(&CompileError) -> bool,
81) -> Selection {
82 let mut taken: Vec<(Span, String)> = Vec::new();
83 let mut categories = Vec::new();
84 for e in errors {
85 if !admit(e) {
86 continue;
87 }
88 let Some(s) = lone_fix(e) else {
89 continue; };
91 if !s.edits.iter().all(|(span, _)| valid(text, *span)) {
92 continue;
93 }
94 let fresh: Vec<&(Span, String)> = s
95 .edits
96 .iter()
97 .filter(|e| !taken.iter().any(|t| t.0 == e.0 && t.1 == e.1))
98 .collect();
99 if fresh
100 .iter()
101 .any(|e| taken.iter().any(|t| overlaps(t.0, e.0)))
102 || fresh
103 .iter()
104 .enumerate()
105 .any(|(i, a)| fresh[i + 1..].iter().any(|b| overlaps(a.0, b.0)))
106 {
107 continue;
108 }
109 if !fresh.is_empty() {
110 categories.push(e.category);
111 }
112 taken.extend(fresh.into_iter().cloned());
113 }
114 taken.sort_by_key(|(span, _)| (span.start, span.end));
115 Selection {
116 edits: taken,
117 categories,
118 }
119}
120
121fn overlaps(a: Span, b: Span) -> bool {
125 if a.start == a.end && b.start == b.end {
126 return a.start == b.start;
127 }
128 a.start < b.end && b.start < a.end
129}
130
131fn valid(text: &str, span: Span) -> bool {
133 span.start <= span.end && text.get(span.start..span.end).is_some()
134}
135
136pub fn apply(text: &str, edits: &[(Span, String)]) -> String {
140 let mut out = String::with_capacity(text.len());
141 let mut last = 0;
142 for (span, new_text) in edits {
143 let Some(before) = text.get(last..span.start) else {
144 continue;
145 };
146 if !valid(text, *span) {
147 continue;
148 }
149 out.push_str(before);
150 out.push_str(new_text);
151 last = span.end;
152 }
153 out.push_str(&text[last..]);
154 out
155}
156
157#[cfg(test)]
158mod tests {
159 use super::*;
160
161 type Fix<'a> = (&'a [((usize, usize), &'a str)], Applicability);
163
164 fn diag(span: (usize, usize), fixes: &[Fix]) -> CompileError {
165 let mut error = CompileError::new("bynk.test", Span::new(span.0, span.1), "msg");
166 for (edits, applicability) in fixes {
167 error = error.with_suggestion(
168 "fix",
169 edits
170 .iter()
171 .map(|((s, e), t)| (Span::new(*s, *e), t.to_string()))
172 .collect(),
173 *applicability,
174 );
175 }
176 error
177 }
178
179 const TEXT: &str = "0123456789012345678901234567890123456789";
181 const M: Applicability = Applicability::MachineApplicable;
182 const P: Applicability = Applicability::HasPlaceholders;
183
184 #[test]
185 fn takes_every_lone_machine_applicable_suggestion_in_position_order() {
186 let ds = [
187 diag((10, 12), &[(&[((10, 12), "b")], M)]),
188 diag((0, 2), &[(&[((0, 2), "a")], M)]),
189 ];
190 assert_eq!(
191 edits(TEXT, &ds),
192 vec![
193 (Span::new(0, 2), "a".to_string()),
194 (Span::new(10, 12), "b".to_string())
195 ]
196 );
197 }
198
199 #[test]
200 fn skips_placeholders_and_choices() {
201 let ds = [
202 diag((0, 2), &[(&[((0, 2), "<T>")], P)]),
203 diag((5, 6), &[(&[((5, 6), "x")], M), (&[((5, 6), "y")], M)]),
205 diag((8, 9), &[(&[((8, 9), "z")], M), (&[((8, 9), "<T>")], P)]),
207 ];
208 assert_eq!(edits(TEXT, &ds), vec![(Span::new(8, 9), "z".to_string())]);
209 }
210
211 #[test]
212 fn an_overlapping_suggestion_is_skipped_whole() {
213 let ds = [
214 diag((0, 4), &[(&[((0, 4), "a")], M)]),
215 diag((10, 12), &[(&[((10, 12), "b"), ((2, 3), "c")], M)]),
218 ];
219 assert_eq!(edits(TEXT, &ds), vec![(Span::new(0, 4), "a".to_string())]);
220 }
221
222 #[test]
223 fn an_identical_edit_is_taken_once() {
224 let ds = [
227 diag((20, 24), &[(&[((14, 14), ", Used")], M)]),
228 diag((30, 34), &[(&[((14, 14), ", Used")], M)]),
229 ];
230 assert_eq!(
231 edits(TEXT, &ds),
232 vec![(Span::new(14, 14), ", Used".to_string())]
233 );
234 }
235
236 #[test]
237 fn different_insertions_at_one_point_conflict() {
238 let ds = [
239 diag((20, 24), &[(&[((14, 14), ", A")], M)]),
240 diag((30, 34), &[(&[((14, 14), ", B")], M)]),
241 ];
242 assert_eq!(
243 edits(TEXT, &ds),
244 vec![(Span::new(14, 14), ", A".to_string())]
245 );
246 }
247
248 #[test]
249 fn touching_edits_do_not_conflict() {
250 let ds = [
251 diag((0, 2), &[(&[((0, 2), "a")], M)]),
252 diag((2, 4), &[(&[((2, 4), "b")], M)]),
253 diag((4, 4), &[(&[((4, 4), "c")], M)]),
254 ];
255 assert_eq!(edits(TEXT, &ds).len(), 3);
256 assert_eq!(apply("0123456", &edits(TEXT, &ds)), "abc456");
257 }
258
259 #[test]
260 fn an_insertion_inside_a_replacement_conflicts() {
261 let ds = [
262 diag((0, 4), &[(&[((0, 4), "a")], M)]),
263 diag((2, 2), &[(&[((2, 2), "b")], M)]),
264 ];
265 assert_eq!(edits(TEXT, &ds), vec![(Span::new(0, 4), "a".to_string())]);
266 }
267
268 #[test]
269 fn a_suggestion_with_a_bad_span_is_skipped() {
270 let ds = [
271 diag((0, 1), &[(&[((38, 99), "x")], M)]),
273 diag((0, 1), &[(&[((5, 3), "y")], M)]),
275 diag((0, 1), &[(&[((0, 1), "z")], M)]),
276 ];
277 assert_eq!(edits(TEXT, &ds), vec![(Span::new(0, 1), "z".to_string())]);
278 let ds = [diag((0, 1), &[(&[((2, 2), "w")], M)])];
280 assert!(edits("aé", &ds).is_empty());
281 }
282
283 #[test]
284 fn apply_skips_a_bad_span_instead_of_panicking() {
285 let bad = [
286 (Span::new(0, 1), "A".to_string()),
287 (Span::new(2, 99), "!".to_string()),
288 ];
289 assert_eq!(apply("abc", &bad), "Abc");
290 assert_eq!(apply("aé", &[(Span::new(2, 2), "w".to_string())]), "aé");
291 }
292
293 #[test]
294 fn a_hint_fix_is_never_taken() {
295 let hint = CompileError::new("bynk.parse.let_else_staircase", Span::new(0, 2), "msg")
296 .with_suggestion("flatten", vec![(Span::new(0, 2), "a".to_string())], M);
297 assert_eq!(Severity::for_error(&hint), Severity::Hint);
298 assert!(edits(TEXT, &[hint]).is_empty());
299 }
300
301 #[test]
302 fn named_codes_select_only_those_diagnostics_hints_included() {
303 let hint = CompileError::new("bynk.parse.let_else_staircase", Span::new(0, 2), "msg")
304 .with_suggestion("flatten", vec![(Span::new(0, 2), "a".to_string())], M);
305 let other = diag((10, 12), &[(&[((10, 12), "b")], M)]);
306 let errors = [hint, other];
307 let only = |codes: &[&str]| {
308 let codes: Vec<String> = codes.iter().map(|c| c.to_string()).collect();
309 select_codes(TEXT, &errors, &codes).edits
310 };
311 assert_eq!(
312 only(&["bynk.test"]),
313 vec![(Span::new(10, 12), "b".to_string())]
314 );
315 assert_eq!(
316 only(&["bynk.parse.let_else_staircase"]),
317 vec![(Span::new(0, 2), "a".to_string())]
318 );
319 assert!(only(&["bynk.nothing"]).is_empty());
320 }
321
322 #[test]
323 fn nothing_to_fix_is_empty() {
324 assert!(edits(TEXT, &[] as &[CompileError]).is_empty());
325 assert!(edits(TEXT, &[diag((0, 1), &[])]).is_empty());
326 }
327
328 #[test]
329 fn select_names_the_diagnostics_it_took_from() {
330 let ds = [
331 diag((0, 2), &[(&[((0, 2), "a")], M)]),
332 diag((1, 3), &[(&[((1, 3), "b")], M)]),
334 diag((10, 12), &[(&[((10, 12), "c")], M)]),
335 ];
336 let s = select(TEXT, &ds);
337 assert_eq!(s.edits.len(), 2);
338 assert_eq!(s.categories, vec!["bynk.test", "bynk.test"]);
339 }
340
341 #[test]
342 fn lone_fix_is_only_a_single_machine_applicable_suggestion() {
343 assert!(lone_fix(&diag((0, 1), &[(&[((0, 1), "a")], M)])).is_some());
344 assert!(lone_fix(&diag((0, 1), &[(&[((0, 1), "a")], P)])).is_none());
345 assert!(
346 lone_fix(&diag(
347 (0, 1),
348 &[(&[((0, 1), "a")], M), (&[((0, 1), "b")], M)]
349 ))
350 .is_none()
351 );
352 assert!(lone_fix(&diag((0, 1), &[])).is_none());
353 }
354}