1use bynk_syntax::error::Applicability;
14use bynk_syntax::span::Span;
15use tower_lsp::lsp_types::*;
16
17pub 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 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
76fn intersects(a: Span, b: Span) -> bool {
79 a.start <= b.end && b.start <= a.end
80}
81
82pub 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
111pub 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 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 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 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 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 let only = [CodeActionKind::REFACTOR_EXTRACT];
218 assert!(filter_by_only(actions.clone(), Some(&only)).is_empty());
219
220 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 let only = [CodeActionKind::REFACTOR];
236 assert_eq!(filter_by_only(vec![action.clone()], Some(&only)).len(), 1);
237 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 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}