Skip to main content

bynk_lsp/
code_actions.rs

1//! v0.26 (ADR 0054): pure `codeAction` computation — quick-fixes from the
2//! structured [`bynk_syntax::error::Suggestion`]s riding on a cached analysis
3//! round's diagnostics.
4//!
5//! Keying rule: a diagnostic's suggestions are offered when the requested
6//! range intersects the **diagnostic's** span — never the edits' spans,
7//! which for both `given` fixes land away from the squiggle (the usage site
8//! in the body vs the clause in the signature). Positions convert against
9//! the analysed snapshot (the v0.24 rule); edits are **versioned** against
10//! the analysed document version, so a drifted buffer rejects the edit
11//! rather than mis-applying it.
12
13use bynk_syntax::error::Applicability;
14use bynk_syntax::span::Span;
15use tower_lsp::lsp_types::*;
16
17/// Quick-fixes for every suggestion whose owning diagnostic intersects the
18/// requested range. `text` and `version` are the analysed snapshot and the
19/// open-document version captured with it.
20pub fn quick_fixes(
21    text: &str,
22    diagnostics: &[bynk_ide::Diagnostic],
23    requested: Span,
24    uri: &Url,
25    version: Option<i32>,
26) -> Vec<CodeActionOrCommand> {
27    let mut out = Vec::new();
28    for d in diagnostics {
29        if !intersects(d.error.span, requested) {
30            continue;
31        }
32        for s in &d.error.suggestions {
33            // `MachineApplicable` fixes are one-click edits, and the only ones
34            // `source.fixAll.bynk` takes. `MaybeIncorrect` fixes (a suggestion
35            // that changes meaning, e.g. `derives Ord`) are offered too, but
36            // never as the preferred fix and never by fix-all.
37            // `HasPlaceholders` has no concrete replacement to apply.
38            if !matches!(
39                s.applicability,
40                Applicability::MachineApplicable | Applicability::MaybeIncorrect
41            ) {
42                continue;
43            }
44            let edits: Vec<OneOf<TextEdit, AnnotatedTextEdit>> = s
45                .edits
46                .iter()
47                .map(|(span, replacement)| {
48                    OneOf::Left(TextEdit {
49                        range: crate::position::span_to_range(text, *span),
50                        new_text: replacement.clone(),
51                    })
52                })
53                .collect();
54            out.push(CodeActionOrCommand::CodeAction(CodeAction {
55                title: s.message.clone(),
56                kind: Some(CodeActionKind::QUICKFIX),
57                is_preferred: (s.applicability == Applicability::MaybeIncorrect).then_some(false),
58                edit: Some(WorkspaceEdit {
59                    changes: None,
60                    document_changes: Some(DocumentChanges::Edits(vec![TextDocumentEdit {
61                        text_document: OptionalVersionedTextDocumentIdentifier {
62                            uri: uri.clone(),
63                            version,
64                        },
65                        edits,
66                    }])),
67                    change_annotations: None,
68                }),
69                ..Default::default()
70            }));
71        }
72    }
73    out
74}
75
76/// Closed intersection over half-open spans: a cursor request (an empty
77/// range) sitting on either boundary of the diagnostic still matches.
78fn intersects(a: Span, b: Span) -> bool {
79    a.start <= b.end && b.start <= a.end
80}
81
82/// #804: filters a combined `codeAction` response against
83/// `CodeActionParams.context.only`, the LSP field a client sets to restrict
84/// which action kinds it wants back. `None` (the field unset) returns
85/// `actions` unchanged. A requested kind matches an action's kind if they're
86/// equal or the action's kind is a dotted child of it (LSP prefix-match
87/// semantics: `refactor` matches `refactor.extract`). An action with no kind,
88/// or a bare `Command`, never matches a non-empty `only` — the client can't
89/// have asked for a kind we don't advertise.
90pub fn filter_by_only(
91    actions: Vec<CodeActionOrCommand>,
92    only: Option<&[CodeActionKind]>,
93) -> Vec<CodeActionOrCommand> {
94    let Some(only) = only else {
95        return actions;
96    };
97    actions
98        .into_iter()
99        .filter(|action| {
100            let CodeActionOrCommand::CodeAction(action) = action else {
101                return false;
102            };
103            action
104                .kind
105                .as_ref()
106                .is_some_and(|kind| only.iter().any(|requested| kind_matches(kind, requested)))
107        })
108        .collect()
109}
110
111/// `kind` is `requested` or a dotted child of it (the LSP prefix match).
112pub fn kind_matches(kind: &CodeActionKind, requested: &CodeActionKind) -> bool {
113    let (kind, requested) = (kind.as_str(), requested.as_str());
114    kind == requested
115        || kind
116            .strip_prefix(requested)
117            .is_some_and(|rest| rest.starts_with('.'))
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123    use bynk_syntax::error::CompileError;
124
125    fn diag_with_suggestion() -> bynk_ide::Diagnostic {
126        // text: "-> T given Cap { Used.op() }" — diagnostic on the usage at
127        // 17..21, fix inserting at the clause (14, far from the squiggle).
128        bynk_ide::Diagnostic {
129            severity: bynk_syntax::Severity::Error,
130            label_files: Vec::new(),
131            error: CompileError::new(
132                "bynk.given.undeclared_capability",
133                Span::new(17, 21),
134                "capability `Used` is used but not listed",
135            )
136            .with_suggestion(
137                "add `Used` to the `given` clause",
138                vec![(Span::new(14, 14), ", Used".to_string())],
139                Applicability::MachineApplicable,
140            ),
141        }
142    }
143
144    #[test]
145    fn keyed_on_the_diagnostic_span_not_the_edit_span() {
146        let text = "-> T given Cap { Used.op() }";
147        let uri = Url::parse("file:///a.bynk").unwrap();
148        // Cursor on the squiggle (the usage site): the fix is offered even
149        // though its edit lands elsewhere.
150        let on_diag = quick_fixes(
151            text,
152            &[diag_with_suggestion()],
153            Span::new(18, 18),
154            &uri,
155            Some(7),
156        );
157        assert_eq!(on_diag.len(), 1);
158        // Cursor away from the diagnostic (even on the edit's own span):
159        // nothing is offered.
160        let on_edit = quick_fixes(
161            text,
162            &[diag_with_suggestion()],
163            Span::new(14, 14),
164            &uri,
165            Some(7),
166        );
167        assert!(on_edit.is_empty());
168    }
169
170    #[test]
171    fn action_carries_a_versioned_quickfix_edit() {
172        let text = "-> T given Cap { Used.op() }";
173        let uri = Url::parse("file:///a.bynk").unwrap();
174        let actions = quick_fixes(
175            text,
176            &[diag_with_suggestion()],
177            Span::new(17, 21),
178            &uri,
179            Some(7),
180        );
181        let CodeActionOrCommand::CodeAction(action) = &actions[0] else {
182            panic!("expected a CodeAction");
183        };
184        assert_eq!(action.title, "add `Used` to the `given` clause");
185        assert_eq!(action.kind, Some(CodeActionKind::QUICKFIX));
186        let Some(DocumentChanges::Edits(doc_edits)) =
187            &action.edit.as_ref().unwrap().document_changes
188        else {
189            panic!("expected versioned document edits");
190        };
191        assert_eq!(doc_edits[0].text_document.version, Some(7));
192        assert_eq!(doc_edits[0].text_document.uri, uri);
193        let OneOf::Left(edit) = &doc_edits[0].edits[0] else {
194            panic!("expected a plain TextEdit");
195        };
196        assert_eq!(edit.new_text, ", Used");
197        // The insertion converts to an empty range at the clause position.
198        assert_eq!(edit.range.start, edit.range.end);
199        assert_eq!(edit.range.start.character, 14);
200    }
201
202    #[test]
203    fn only_filters_out_non_matching_kinds() {
204        let text = "-> T given Cap { Used.op() }";
205        let uri = Url::parse("file:///a.bynk").unwrap();
206        let actions = quick_fixes(
207            text,
208            &[diag_with_suggestion()],
209            Span::new(18, 18),
210            &uri,
211            Some(7),
212        );
213        assert_eq!(actions.len(), 1);
214
215        // A client asking only for `refactor.extract` gets nothing back —
216        // the quick-fix's kind is `quickfix`, not a dotted child of it.
217        let only = [CodeActionKind::REFACTOR_EXTRACT];
218        assert!(filter_by_only(actions.clone(), Some(&only)).is_empty());
219
220        // Asking for `quickfix` (or leaving `only` unset) keeps it.
221        let only = [CodeActionKind::QUICKFIX];
222        assert_eq!(filter_by_only(actions.clone(), Some(&only)).len(), 1);
223        assert_eq!(filter_by_only(actions, None).len(), 1);
224    }
225
226    #[test]
227    fn only_matches_dotted_children_by_prefix() {
228        let action = CodeActionOrCommand::CodeAction(CodeAction {
229            title: "extract".to_string(),
230            kind: Some(CodeActionKind::REFACTOR_EXTRACT),
231            ..Default::default()
232        });
233        // A parent kind (`refactor`) matches its dotted child
234        // (`refactor.extract`), per the LSP's prefix-match semantics.
235        let only = [CodeActionKind::REFACTOR];
236        assert_eq!(filter_by_only(vec![action.clone()], Some(&only)).len(), 1);
237        // A same-prefix sibling (`refactorx`) must not match.
238        let only = [CodeActionKind::new("refactorx")];
239        assert!(filter_by_only(vec![action], Some(&only)).is_empty());
240    }
241
242    #[test]
243    fn only_quickfix_drops_the_extract_variable_action() {
244        // #804 regression: a selection that legitimately offers both a
245        // quick-fix and an extract-variable action, combined exactly as the
246        // `code_action` handler does — `only: [quickfix]` must drop the
247        // refactor, not just fail to add it.
248        let text = "context c\n\nfn f() -> Int {\n  let y = 1 + 2\n  y\n}\n";
249        let uri = Url::parse("file:///a.bynk").unwrap();
250        let start = text.find("1 + 2").unwrap();
251        let span = Span::new(start, start + "1 + 2".len());
252        let diag = bynk_ide::Diagnostic {
253            severity: bynk_syntax::Severity::Error,
254            label_files: Vec::new(),
255            error: CompileError::new("bynk.test", span, "msg").with_suggestion(
256                "a fix",
257                vec![(span, "0".to_string())],
258                Applicability::MachineApplicable,
259            ),
260        };
261
262        let mut actions = quick_fixes(text, &[diag], span, &uri, Some(1));
263        actions.extend(crate::extract::extract_variable(text, span, &uri, Some(1)));
264        assert_eq!(actions.len(), 2, "both actions are offered unfiltered");
265
266        let only = [CodeActionKind::QUICKFIX];
267        let filtered = filter_by_only(actions, Some(&only));
268        assert_eq!(filtered.len(), 1);
269        let CodeActionOrCommand::CodeAction(action) = &filtered[0] else {
270            panic!("expected a CodeAction");
271        };
272        assert_eq!(action.kind, Some(CodeActionKind::QUICKFIX));
273    }
274
275    #[test]
276    fn placeholder_suggestions_are_not_offered() {
277        let text = "x";
278        let uri = Url::parse("file:///a.bynk").unwrap();
279        let d = bynk_ide::Diagnostic {
280            severity: bynk_syntax::Severity::Error,
281            label_files: Vec::new(),
282            error: CompileError::new("bynk.test", Span::new(0, 1), "msg").with_suggestion(
283                "fill in <T>",
284                vec![(Span::new(0, 1), "<T>".to_string())],
285                Applicability::HasPlaceholders,
286            ),
287        };
288        assert!(quick_fixes(text, &[d], Span::new(0, 1), &uri, None).is_empty());
289    }
290}