Skip to main content

bynk_lsp/
fix_all.rs

1//! #2100 slice 6: the `source.fixAll.bynk` code action — apply every
2//! machine-applicable diagnostic suggestion in a file as one edit.
3//!
4//! The selection rule (DECISION C) lives in [`bynk_syntax::fix`], shared with
5//! `bynk check --fix` (#2642); this module adapts it to the IDE's
6//! [`bynk_ide::Diagnostic`] and builds the LSP action. The `code_action`
7//! handler adds DECISION B's safety gate: the combined edit is offered only if
8//! the re-analysed project has no diagnostic the round didn't already have.
9
10use bynk_syntax::span::Span;
11use tower_lsp::lsp_types::*;
12
13pub use bynk_syntax::fix::apply;
14
15/// The `source.fixAll.bynk` kind.
16pub fn kind() -> CodeActionKind {
17    CodeActionKind::new("source.fixAll.bynk")
18}
19
20/// Every edit fix-all would apply to `text`, the file whose `diagnostics`
21/// these are. See [`bynk_syntax::fix::edits`].
22pub fn edits(text: &str, diagnostics: &[bynk_ide::Diagnostic]) -> Vec<(Span, String)> {
23    bynk_syntax::fix::edits(text, diagnostics.iter().map(|d| &d.error))
24}
25
26/// The versioned `source.fixAll.bynk` action for `edits`.
27pub fn action(
28    text: &str,
29    edits: &[(Span, String)],
30    uri: &Url,
31    version: Option<i32>,
32) -> CodeActionOrCommand {
33    CodeActionOrCommand::CodeAction(CodeAction {
34        title: "Fix all auto-fixable problems".to_string(),
35        kind: Some(kind()),
36        edit: Some(WorkspaceEdit {
37            changes: None,
38            document_changes: Some(DocumentChanges::Edits(vec![TextDocumentEdit {
39                text_document: OptionalVersionedTextDocumentIdentifier {
40                    uri: uri.clone(),
41                    version,
42                },
43                edits: edits
44                    .iter()
45                    .map(|(span, new_text)| {
46                        OneOf::Left(TextEdit {
47                            range: crate::position::span_to_range(text, *span),
48                            new_text: new_text.clone(),
49                        })
50                    })
51                    .collect(),
52            }])),
53            change_annotations: None,
54        }),
55        ..Default::default()
56    })
57}
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62    use bynk_syntax::error::{Applicability, CompileError};
63
64    fn diag(span: (usize, usize), text: &str) -> bynk_ide::Diagnostic {
65        let error = CompileError::new("bynk.test", Span::new(span.0, span.1), "msg")
66            .with_suggestion(
67                "fix",
68                vec![(Span::new(span.0, span.1), text.to_string())],
69                Applicability::MachineApplicable,
70            );
71        bynk_ide::Diagnostic {
72            severity: bynk_syntax::Severity::Error,
73            label_files: Vec::new(),
74            error,
75        }
76    }
77
78    /// Constrained generics slice 0: fix-all migrates a file that compares an
79    /// unbounded type parameter in one action — `missing_eq_bound`'s suggestion
80    /// is machine-applicable and the result compiles.
81    #[test]
82    fn migrates_missing_eq_bounds_in_one_action() {
83        let text = "commons m\n\ntype Box[A] = { value: A }\n\nfn same[T](a: T, b: T) -> Bool { a == b }\n\nfn Box.has(self, x: A) -> Bool { self.value == x }\n";
84        let diagnostics = bynk_ide::diagnose(text);
85        let taken = edits(text, &diagnostics);
86        assert_eq!(taken.len(), 2, "{taken:?}");
87        let mut out = text.to_string();
88        for (span, replacement) in taken.iter().rev() {
89            out.replace_range(span.start..span.end, replacement);
90        }
91        assert!(out.contains("fn same[T: Eq](a: T, b: T)"), "{out}");
92        assert!(
93            out.contains("fn Box.has(self, x: A) -> Bool where A: Eq {"),
94            "{out}"
95        );
96        assert!(bynk_ide::diagnose(&out).is_empty());
97    }
98
99    /// Apply fix-all's edits for `text`, returning the result.
100    fn fixed(text: &str) -> String {
101        let diagnostics = bynk_ide::diagnose(text);
102        bynk_syntax::fix::apply(text, &edits(text, &diagnostics))
103    }
104
105    /// Constrained generics slice 1: fix-all adds `Ord` where a type parameter
106    /// is ordered without it — a missing bound, a bound `Eq` upgraded to `Ord`
107    /// (the edit replaces the `Eq`, leaving one bound), and a method's `where`.
108    #[test]
109    fn migrates_missing_ord_bounds_in_one_action() {
110        let text = "commons m\n\ntype Box[A] = { value: A }\n\nfn lt[T](a: T, b: T) -> Bool { a < b }\n\nfn le[T: Eq](a: T, b: T) -> Bool { a <= b }\n\nfn Box.big(self, x: A) -> Bool { self.value > x }\n";
111        let diagnostics = bynk_ide::diagnose(text);
112        let cats: Vec<&str> = diagnostics.iter().map(|d| d.error.category).collect();
113        assert_eq!(
114            cats.iter()
115                .filter(|c| **c == "bynk.generics.missing_ord_bound")
116                .count(),
117            3,
118            "{cats:?}"
119        );
120        let out = fixed(text);
121        assert!(out.contains("fn lt[T: Ord](a: T, b: T)"), "{out}");
122        assert!(out.contains("fn le[T: Ord](a: T, b: T)"), "{out}");
123        assert!(
124            !out.contains("Eq"),
125            "the Eq is replaced, not kept beside Ord: {out}"
126        );
127        assert!(
128            out.contains("fn Box.big(self, x: A) -> Bool where A: Ord {"),
129            "{out}"
130        );
131        assert!(bynk_ide::diagnose(&out).is_empty(), "{out}");
132    }
133
134    /// Constrained generics slice 2: fix-all adds `Key` where a type parameter
135    /// keys a `Map` or `Set` without it, replaces a bound `Eq`, and drops the
136    /// redundant `Eq` beside `Key`.
137    #[test]
138    fn migrates_missing_key_bounds_in_one_action() {
139        let text = "commons m\n\nfn mk[K](k: K) -> Map[K, Int] { Map.empty() }\n\nfn st[K: Eq](k: K) -> Set[K] { Set.empty() }\n\nfn both[K: Eq + Key](k: K) -> Set[K] { Set.empty() }\n";
140        let cats: Vec<&str> = bynk_ide::diagnose(text)
141            .iter()
142            .map(|d| d.error.category)
143            .collect();
144        assert!(
145            cats.contains(&"bynk.generics.missing_key_bound"),
146            "{cats:?}"
147        );
148        assert!(
149            cats.contains(&"bynk.generics.redundant_eq_bound"),
150            "{cats:?}"
151        );
152        let out = fixed(text);
153        assert!(out.contains("fn mk[K: Key](k: K)"), "{out}");
154        assert!(out.contains("fn st[K: Key](k: K)"), "{out}");
155        assert!(out.contains("fn both[K: Key](k: K)"), "{out}");
156        assert!(bynk_ide::diagnose(&out).is_empty(), "{out}");
157    }
158
159    /// Constrained generics slice 3: fix-all adds `Codable` where a type parameter
160    /// is encoded or decoded without it, beside an existing `Eq` (which `Codable`,
161    /// unlike `Ord` and `Key`, does not imply).
162    #[test]
163    fn migrates_missing_codable_bounds_in_one_action() {
164        let text = "commons m\n\nfn enc[T](v: T) -> String { Json.encode(v) }\n\nfn keep[T: Eq](v: T) -> String { Json.encode(v) }\n";
165        let cats: Vec<&str> = bynk_ide::diagnose(text)
166            .iter()
167            .map(|d| d.error.category)
168            .collect();
169        assert!(
170            cats.contains(&"bynk.generics.missing_codable_bound"),
171            "{cats:?}"
172        );
173        let out = fixed(text);
174        assert!(out.contains("fn enc[T: Codable](v: T)"), "{out}");
175        assert!(out.contains("fn keep[T: Eq + Codable](v: T)"), "{out}");
176        assert!(bynk_ide::diagnose(&out).is_empty(), "{out}");
177    }
178
179    /// Constrained generics slice 1: the redundant `Eq` beside `Ord`, and a
180    /// `derives` of an automatic constraint, are removed by fix-all.
181    #[test]
182    fn removes_redundant_eq_and_automatic_derives() {
183        let text = "commons m\n\nfn lt[T: Eq + Ord](a: T, b: T) -> Bool { a < b }\n\nfn gt[T: Ord + Eq](a: T, b: T) -> Bool { a > b }\n\ntype P = { a: Int } derives Eq\n\ntype Q = { a: Int } derives Ord + Key\n";
184        let cats: Vec<&str> = bynk_ide::diagnose(text)
185            .iter()
186            .map(|d| d.error.category)
187            .collect();
188        for c in [
189            "bynk.generics.redundant_eq_bound",
190            "bynk.types.derives_automatic",
191        ] {
192            assert!(cats.contains(&c), "{c} in {cats:?}");
193        }
194        let out = fixed(text);
195        assert!(out.contains("fn lt[T: Ord](a: T"), "{out}");
196        assert!(out.contains("fn gt[T: Ord](a: T"), "{out}");
197        assert!(out.contains("type Q = { a: Int } derives Ord\n"), "{out}");
198        assert!(bynk_ide::diagnose(&out).is_empty(), "{out}");
199    }
200
201    /// Constrained generics slice 1: `not_orderable`'s "add `derives Ord`" is
202    /// `MaybeIncorrect` (it changes what the type means), so fix-all never
203    /// takes it — and is offered only as a non-preferred quick fix.
204    #[test]
205    fn never_applies_the_not_orderable_suggestion() {
206        let text = "commons m\n\ntype R = { a: Int }\n\nfn lt(x: R, y: R) -> Bool { x < y }\n";
207        let diagnostics = bynk_ide::diagnose(text);
208        let d = diagnostics
209            .iter()
210            .find(|d| d.error.category == "bynk.types.not_orderable")
211            .expect("`R` is not orderable");
212        let s = d
213            .error
214            .suggestions
215            .iter()
216            .find(|s| s.message.contains("derives Ord"))
217            .expect("a `derives Ord` suggestion");
218        assert_eq!(
219            s.applicability,
220            bynk_syntax::error::Applicability::MaybeIncorrect
221        );
222        assert!(edits(text, &diagnostics).is_empty());
223        assert_eq!(fixed(text), text);
224        // …yet the quick fix is there, and not preferred.
225        let uri = Url::parse("file:///a.bynk").unwrap();
226        let fixes =
227            crate::code_actions::quick_fixes(text, &diagnostics, d.error.span, &uri, Some(1));
228        let [CodeActionOrCommand::CodeAction(a)] = fixes.as_slice() else {
229            panic!("one quick fix: {fixes:?}");
230        };
231        assert!(a.title.contains("derives Ord"), "{}", a.title);
232        assert_ne!(a.is_preferred, Some(true));
233        assert_eq!(a.kind, Some(CodeActionKind::QUICKFIX));
234    }
235
236    /// #3161: a bare expression statement carries a machine-applicable fix, so
237    /// fix-all binds it (an effectful-looking call with `let _ <-`, a pure one
238    /// with `let _ =`) and the editor offers it as a quick fix.
239    #[test]
240    fn binds_a_bare_expression_statement() {
241        let text = "context m\n\nconsumes bynk { Logger }\n\nfn g(x: Int) -> Int { x }\n\nservice s from http {\n  on GET(\"/\") () -> Effect[HttpResult[String]] by v: Visitor given Logger {\n    Logger.info(\"hi\")\n    g(1)\n    Ok(\"x\")\n  }\n}\n";
242        let diagnostics = bynk_ide::diagnose(text);
243        let bare: Vec<_> = diagnostics
244            .iter()
245            .filter(|d| d.error.category == "bynk.parse.bare_expression_statement")
246            .collect();
247        assert_eq!(
248            bare.len(),
249            2,
250            "{:?}",
251            diagnostics
252                .iter()
253                .map(|d| d.error.category)
254                .collect::<Vec<_>>()
255        );
256        let out = fixed(text);
257        assert!(out.contains("let _ <- Logger.info(\"hi\")"), "{out}");
258        // #3537: the `let _ =` guess may drop an effect, so fix-all leaves it.
259        assert!(!out.contains("let _ = g(1)"), "{out}");
260        let uri = Url::parse("file:///a.bynk").unwrap();
261        let fixes =
262            crate::code_actions::quick_fixes(text, &diagnostics, bare[0].error.span, &uri, Some(1));
263        let [CodeActionOrCommand::CodeAction(a)] = fixes.as_slice() else {
264            panic!("one quick fix: {fixes:?}");
265        };
266        assert!(a.title.contains("let _ <-"), "{}", a.title);
267        assert_ne!(a.is_preferred, Some(false));
268        assert_eq!(a.kind, Some(CodeActionKind::QUICKFIX));
269    }
270
271    /// The selection rule itself is tested in `bynk_syntax::fix`; this pins
272    /// the adapter that feeds it the IDE's diagnostics.
273    #[test]
274    fn edits_adapts_ide_diagnostics_to_the_shared_rule() {
275        let ds = [diag((4, 6), "b"), diag((0, 2), "a")];
276        assert_eq!(
277            edits("0123456789", &ds),
278            vec![
279                (Span::new(0, 2), "a".to_string()),
280                (Span::new(4, 6), "b".to_string())
281            ]
282        );
283        assert_eq!(apply("0123456789", &edits("0123456789", &ds)), "a23b6789");
284    }
285}