Skip to main content

bynk_syntax/
fix.rs

1//! Selecting and applying the machine-applicable suggestions of a file's
2//! diagnostics — the rule behind the editor's `source.fixAll.bynk` (#2100
3//! slice 6) and `bynk check --fix` (#2642), which share it so the two cannot
4//! drift.
5//!
6//! #3537: a Hint-severity diagnostic's fix is never taken (see [`select`]).
7//!
8//! DECISION C (#2100): only a suggestion marked
9//! [`Applicability::MachineApplicable`] is taken, and only from a diagnostic
10//! that carries exactly one such suggestion. A diagnostic offering several
11//! (a choice between candidates) needs a human, so it stays an individual
12//! quick fix.
13//!
14//! Suggestions are taken in diagnostic order. A suggestion whose edits overlap
15//! an edit already taken is skipped whole, never applied in part. Two
16//! insertions at the same point overlap unless they are identical, so their
17//! order never matters. An identical edit is taken once (two diagnostics
18//! asking for the same `given` entry add it once). A skipped suggestion is
19//! still a quick fix, and the next fix-all picks it up once the first batch is
20//! applied.
21
22use crate::error::{Applicability, CompileError, Severity};
23use crate::span::Span;
24
25/// The one machine-applicable suggestion `error` carries, if it carries
26/// exactly one. `None` for no fix, a placeholder fix, or a choice between
27/// candidates.
28pub 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/// What [`select`] chose: the edits, and the category of each diagnostic whose
40/// suggestion contributed at least one.
41#[derive(Debug, Clone, Default, PartialEq, Eq)]
42pub struct Selection {
43    /// Sorted by position and non-overlapping.
44    pub edits: Vec<(Span, String)>,
45    pub categories: Vec<&'static str>,
46}
47
48/// Every edit fix-all would apply to `text`, the file whose `errors` these
49/// are, sorted by position and non-overlapping. Empty when there is nothing to
50/// fix. A suggestion with an edit span that isn't valid for `text` (out of
51/// bounds, reversed, or off a char boundary) is skipped whole.
52pub fn edits<'a>(
53    text: &str,
54    errors: impl IntoIterator<Item = &'a CompileError>,
55) -> Vec<(Span, String)> {
56    select(text, errors).edits
57}
58
59/// [`edits`], also naming the diagnostics the edits came from.
60pub fn select<'a>(text: &str, errors: impl IntoIterator<Item = &'a CompileError>) -> Selection {
61    // #3537: a hint is not shown by `check`, so a batch never takes its fix;
62    // it stays an individual quick fix in the editor.
63    pick(text, errors, |e| Severity::for_error(e) != Severity::Hint)
64}
65
66/// [`select`] restricted to the diagnostics whose code is in `codes` (#3537,
67/// `check --fix=<code>`). Naming a code is asking for its fixes, so a hint's
68/// fix is taken when its code is named.
69pub 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; // none, or a choice between candidates
90        };
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
121/// Two edit spans conflict: they share a character, or they are insertions
122/// at the same point. Spans that only touch (one ends where the next starts)
123/// don't, unless both are that same empty span.
124fn 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
131/// `span` is a range of `text`: in bounds, not reversed, on char boundaries.
132fn valid(text: &str, span: Span) -> bool {
133    span.start <= span.end && text.get(span.start..span.end).is_some()
134}
135
136/// The text with `edits` (sorted, non-overlapping) applied. An edit whose
137/// span isn't a valid range of `text`, or that overlaps the one before it, is
138/// skipped rather than panicking.
139pub 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    /// One suggestion: its `((start, end), replacement)` edits and applicability.
162    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    /// Long enough for every span the tests below use.
180    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            // Two machine-applicable candidates: a human picks.
204            diag((5, 6), &[(&[((5, 6), "x")], M), (&[((5, 6), "y")], M)]),
205            // One machine-applicable beside a placeholder one: still lone.
206            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            // Its second edit overlaps the first suggestion's: neither of its
216            // edits is taken.
217            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        // Two uses of an undeclared capability both ask to add it to the same
225        // `given` clause.
226        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            // Past the end of the text.
272            diag((0, 1), &[(&[((38, 99), "x")], M)]),
273            // Reversed.
274            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        // Off a char boundary: inside the two-byte `é`.
279        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            // Skipped: overlaps the first.
333            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}