1use lsp_types::{
2 CodeAction, CodeActionKind, CodeActionOrCommand, Position, Range, TextEdit, Url, WorkspaceEdit,
3};
4use std::collections::{HashMap, HashSet};
5
6use logicaffeine_language::suggest::{find_similar, KNOWN_WORDS};
7
8use crate::document::DocumentState;
9use crate::workspace::WorkspaceView;
10
11pub fn code_actions(
15 doc: &DocumentState,
16 range: Range,
17 uri: &lsp_types::Url,
18) -> Vec<CodeActionOrCommand> {
19 let mut actions = Vec::new();
20
21 let is_default_range = range == Range::default();
23 for diagnostic in &doc.diagnostics {
24 if !is_default_range && !ranges_overlap(&diagnostic.range, &range) {
25 continue;
26 }
27 let start_offset = doc.line_index.offset(diagnostic.range.start);
28 let end_offset = doc.line_index.offset(diagnostic.range.end);
29
30 let word = doc.source.get(start_offset..end_offset).unwrap_or("");
31
32 if diagnostic.code.is_none() && word.chars().count() >= 2 {
39 if let Some(suggestion) = find_similar(word, KNOWN_WORDS, 2) {
40 let mut changes = HashMap::new();
41 changes.insert(
42 uri.clone(),
43 vec![TextEdit {
44 range: diagnostic.range,
45 new_text: suggestion.to_string(),
46 }],
47 );
48
49 actions.push(CodeActionOrCommand::CodeAction(CodeAction {
50 title: format!("Did you mean '{}'?", suggestion),
51 kind: Some(CodeActionKind::QUICKFIX),
52 diagnostics: Some(vec![diagnostic.clone()]),
53 edit: Some(WorkspaceEdit {
54 changes: Some(changes),
55 ..Default::default()
56 }),
57 ..Default::default()
58 }));
59 }
60 }
61
62 let is_value_eq = diagnostic.code.as_ref().map_or(
64 false,
65 |c| matches!(c, lsp_types::NumberOrString::String(s) if s == "is-value-equality"),
66 );
67 if is_value_eq {
68 if let Some(is_pos) = doc
69 .source
70 .get(start_offset..end_offset)
71 .and_then(|s| s.find(" is "))
72 {
73 let abs_pos = start_offset + is_pos;
74 let is_range = Range {
75 start: doc.line_index.position(abs_pos),
76 end: doc.line_index.position(abs_pos + 4), };
78
79 let mut changes = HashMap::new();
80 changes.insert(
81 uri.clone(),
82 vec![TextEdit {
83 range: is_range,
84 new_text: " equals ".to_string(),
85 }],
86 );
87
88 actions.push(CodeActionOrCommand::CodeAction(CodeAction {
89 title: "Use 'equals' for value comparison".to_string(),
90 kind: Some(CodeActionKind::QUICKFIX),
91 diagnostics: Some(vec![diagnostic.clone()]),
92 edit: Some(WorkspaceEdit {
93 changes: Some(changes),
94 ..Default::default()
95 }),
96 ..Default::default()
97 }));
98 }
99 }
100
101 let is_use_after_move = diagnostic.code.as_ref().map_or(
106 false,
107 |c| matches!(c, lsp_types::NumberOrString::String(s) if s == "use-after-move"),
108 );
109 if is_use_after_move {
110 let variable = ownership_variable(&diagnostic.message, word);
111 let target = if variable == word {
112 diagnostic.range
113 } else {
114 last_word_range(doc, variable, end_offset).unwrap_or(diagnostic.range)
115 };
116 let mut changes = HashMap::new();
117 changes.insert(
118 uri.clone(),
119 vec![TextEdit {
120 range: target,
121 new_text: format!("a copy of {}", variable),
122 }],
123 );
124
125 actions.push(CodeActionOrCommand::CodeAction(CodeAction {
126 title: format!("Use 'a copy of {}' instead", variable),
127 kind: Some(CodeActionKind::QUICKFIX),
128 diagnostics: Some(vec![diagnostic.clone()]),
129 edit: Some(WorkspaceEdit {
130 changes: Some(changes),
131 ..Default::default()
132 }),
133 ..Default::default()
134 }));
135 }
136
137 let diag_code_str = diagnostic.code.as_ref().and_then(|c| {
139 if let lsp_types::NumberOrString::String(s) = c {
140 Some(s.as_str())
141 } else {
142 None
143 }
144 });
145
146 if matches!(diag_code_str, Some("escape-return")) {
147 let mut changes = HashMap::new();
148 changes.insert(
149 uri.clone(),
150 vec![TextEdit {
151 range: diagnostic.range,
152 new_text: format!("a copy of {}", word),
153 }],
154 );
155 actions.push(CodeActionOrCommand::CodeAction(CodeAction {
156 title: "Copy before returning".to_string(),
157 kind: Some(CodeActionKind::QUICKFIX),
158 diagnostics: Some(vec![diagnostic.clone()]),
159 edit: Some(WorkspaceEdit {
160 changes: Some(changes),
161 ..Default::default()
162 }),
163 ..Default::default()
164 }));
165 }
166
167 if matches!(diag_code_str, Some("escape-assignment")) {
168 let mut changes = HashMap::new();
169 changes.insert(
170 uri.clone(),
171 vec![TextEdit {
172 range: diagnostic.range,
173 new_text: format!("a copy of {}", word),
174 }],
175 );
176 actions.push(CodeActionOrCommand::CodeAction(CodeAction {
177 title: "Copy before assignment".to_string(),
178 kind: Some(CodeActionKind::QUICKFIX),
179 diagnostics: Some(vec![diagnostic.clone()]),
180 edit: Some(WorkspaceEdit {
181 changes: Some(changes),
182 ..Default::default()
183 }),
184 ..Default::default()
185 }));
186 }
187
188 if matches!(diag_code_str, Some("double-move")) {
190 let variable = ownership_variable(&diagnostic.message, word);
191 let target = if variable == word {
192 diagnostic.range
193 } else {
194 last_word_range(doc, variable, end_offset).unwrap_or(diagnostic.range)
195 };
196 let mut changes = HashMap::new();
197 changes.insert(
198 uri.clone(),
199 vec![TextEdit {
200 range: target,
201 new_text: format!("a copy of {}", variable),
202 }],
203 );
204 actions.push(CodeActionOrCommand::CodeAction(CodeAction {
205 title: format!("Give 'a copy of {}' instead", variable),
206 kind: Some(CodeActionKind::QUICKFIX),
207 diagnostics: Some(vec![diagnostic.clone()]),
208 edit: Some(WorkspaceEdit {
209 changes: Some(changes),
210 ..Default::default()
211 }),
212 ..Default::default()
213 }));
214 }
215
216 if matches!(diag_code_str, Some("zero-index")) {
218 let mut changes = HashMap::new();
219 changes.insert(
220 uri.clone(),
221 vec![TextEdit {
222 range: diagnostic.range,
223 new_text: "1".to_string(),
224 }],
225 );
226 actions.push(CodeActionOrCommand::CodeAction(CodeAction {
227 title: "Use 1-based indexing".to_string(),
228 kind: Some(CodeActionKind::QUICKFIX),
229 diagnostics: Some(vec![diagnostic.clone()]),
230 edit: Some(WorkspaceEdit {
231 changes: Some(changes),
232 ..Default::default()
233 }),
234 ..Default::default()
235 }));
236 }
237
238 if matches!(diag_code_str, Some("unused-variable")) {
240 let def_offset = doc.line_index.offset(diagnostic.range.start);
241 let stmt_span = doc
242 .symbol_index
243 .statement_spans
244 .iter()
245 .map(|(_, span)| span)
246 .filter(|span| span.start <= def_offset && def_offset <= span.end)
247 .min_by_key(|span| span.end - span.start);
248 if let Some(span) = stmt_span {
249 let mut delete_end = span.end;
250 let rest = doc.source.get(delete_end..).unwrap_or("");
251 if rest.starts_with("\r\n") {
252 delete_end += 2;
253 } else if rest.starts_with('\n') {
254 delete_end += 1;
255 }
256 let mut changes = HashMap::new();
257 changes.insert(
258 uri.clone(),
259 vec![TextEdit {
260 range: Range {
261 start: doc.line_index.position(span.start),
262 end: doc.line_index.position(delete_end),
263 },
264 new_text: String::new(),
265 }],
266 );
267 actions.push(CodeActionOrCommand::CodeAction(CodeAction {
268 title: format!("Remove unused '{}'", word),
269 kind: Some(CodeActionKind::QUICKFIX),
270 diagnostics: Some(vec![diagnostic.clone()]),
271 edit: Some(WorkspaceEdit {
272 changes: Some(changes),
273 ..Default::default()
274 }),
275 ..Default::default()
276 }));
277 }
278 }
279
280 if matches!(diag_code_str, Some("undefined-variable")) && !word.is_empty() {
282 let def_names: Vec<&str> = doc
283 .symbol_index
284 .definitions
285 .iter()
286 .map(|d| d.name.as_str())
287 .collect();
288 if let Some(suggestion) = find_similar(word, &def_names, 2) {
289 let mut changes = HashMap::new();
290 changes.insert(
291 uri.clone(),
292 vec![TextEdit {
293 range: diagnostic.range,
294 new_text: suggestion.to_string(),
295 }],
296 );
297 actions.push(CodeActionOrCommand::CodeAction(CodeAction {
298 title: format!("Did you mean '{}'?", suggestion),
299 kind: Some(CodeActionKind::QUICKFIX),
300 diagnostics: Some(vec![diagnostic.clone()]),
301 edit: Some(WorkspaceEdit {
302 changes: Some(changes),
303 ..Default::default()
304 }),
305 ..Default::default()
306 }));
307 }
308 }
309 }
310
311 actions
312}
313
314fn ranges_overlap(a: &Range, b: &Range) -> bool {
315 !(a.end.line < b.start.line
316 || (a.end.line == b.start.line && a.end.character < b.start.character)
317 || b.end.line < a.start.line
318 || (b.end.line == a.start.line && b.end.character < a.start.character))
319}
320
321pub fn import_code_actions(
328 doc: &DocumentState,
329 range: Range,
330 uri: &Url,
331 ws: &dyn WorkspaceView,
332) -> Vec<CodeActionOrCommand> {
333 let mut actions = Vec::new();
334 let is_default_range = range == Range::default();
335 let (insert_pos, blank_after) = import_insertion(&doc.source);
336 let mut seen: HashSet<(String, String)> = HashSet::new();
337
338 for reference in &doc.symbol_index.references {
339 if reference.definition_idx.is_some() {
341 continue;
342 }
343 let ref_range = Range {
344 start: doc.line_index.position(reference.span.start),
345 end: doc.line_index.position(reference.span.end),
346 };
347 if !is_default_range && !ranges_overlap(&ref_range, &range) {
348 continue;
349 }
350 let name = &reference.name;
351 if ws.is_imported(uri, name) {
352 continue;
353 }
354 for export in ws.module_exporting(name) {
355 if !seen.insert((name.clone(), export.module_name.clone())) {
356 continue;
357 }
358 let new_text = if blank_after {
359 format!("Import {}.\n\n", export.module_name)
360 } else {
361 format!("Import {}.\n", export.module_name)
362 };
363 let mut changes = HashMap::new();
364 changes.insert(
365 uri.clone(),
366 vec![TextEdit {
367 range: Range {
368 start: insert_pos,
369 end: insert_pos,
370 },
371 new_text,
372 }],
373 );
374 actions.push(CodeActionOrCommand::CodeAction(CodeAction {
375 title: format!("Import {}", export.module_name),
376 kind: Some(CodeActionKind::QUICKFIX),
377 edit: Some(WorkspaceEdit {
378 changes: Some(changes),
379 ..Default::default()
380 }),
381 ..Default::default()
382 }));
383 }
384 }
385 actions
386}
387
388fn import_insertion(source: &str) -> (Position, bool) {
393 let mut last_import: Option<u32> = None;
394 let mut first_block: Option<u32> = None;
395 for (i, line) in source.lines().enumerate() {
396 let t = line.trim();
397 if t.starts_with("## ") {
398 first_block = Some(i as u32);
399 break;
400 }
401 if t.starts_with("Import ") {
402 last_import = Some(i as u32);
403 }
404 }
405 if let Some(i) = last_import {
406 return (
407 Position {
408 line: i + 1,
409 character: 0,
410 },
411 false,
412 );
413 }
414 if let Some(i) = first_block {
415 return (
416 Position {
417 line: i,
418 character: 0,
419 },
420 true,
421 );
422 }
423 let after_title = source
424 .lines()
425 .next()
426 .is_some_and(|l| l.trim_start().starts_with('#'));
427 (
428 Position {
429 line: if after_title { 1 } else { 0 },
430 character: 0,
431 },
432 false,
433 )
434}
435
436pub fn unused_import_actions(
440 doc: &DocumentState,
441 range: Range,
442 uri: &Url,
443 ws: &dyn WorkspaceView,
444) -> Vec<CodeActionOrCommand> {
445 let referenced: HashSet<&str> = doc
446 .symbol_index
447 .references
448 .iter()
449 .map(|r| r.name.as_str())
450 .collect();
451 let module_urls: HashMap<String, Url> = ws.module_names().into_iter().collect();
452 let is_default_range = range == Range::default();
453 let mut actions = Vec::new();
454
455 for dep in logicaffeine_language::analysis::scan_dependencies(&doc.source) {
456 let start = doc.line_index.position(dep.start);
457 let end = doc.line_index.position(dep.end);
458 if !is_default_range && !ranges_overlap(&Range { start, end }, &range) {
459 continue;
460 }
461 let Some(module_url) = module_urls.get(&dep.alias) else {
463 continue;
464 };
465 let exports = ws.exports_of(module_url);
466 if exports.is_empty() {
467 continue; }
469 let names: Vec<String> = match &dep.selection {
470 Some(sel) => sel
471 .iter()
472 .map(|s| s.alias.clone().unwrap_or_else(|| s.name.clone()))
473 .collect(),
474 None => exports,
475 };
476 if names.iter().any(|n| referenced.contains(n.as_str())) {
477 continue; }
479 let del = Range {
481 start: Position {
482 line: start.line,
483 character: 0,
484 },
485 end: Position {
486 line: start.line + 1,
487 character: 0,
488 },
489 };
490 let mut changes = HashMap::new();
491 changes.insert(
492 uri.clone(),
493 vec![TextEdit {
494 range: del,
495 new_text: String::new(),
496 }],
497 );
498 actions.push(CodeActionOrCommand::CodeAction(CodeAction {
499 title: format!("Remove unused import `{}`", dep.alias),
500 kind: Some(CodeActionKind::QUICKFIX),
501 edit: Some(WorkspaceEdit {
502 changes: Some(changes),
503 ..Default::default()
504 }),
505 ..Default::default()
506 }));
507 }
508 actions
509}
510
511fn ownership_variable<'a>(message: &'a str, range_word: &'a str) -> &'a str {
514 message
515 .split('\'')
516 .nth(1)
517 .filter(|name| !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_'))
518 .unwrap_or(range_word)
519}
520
521fn last_word_range(doc: &DocumentState, name: &str, before: usize) -> Option<Range> {
524 let hay = doc.source.get(..before.min(doc.source.len()))?;
525 let bytes = hay.as_bytes();
526 let is_word = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
527 let mut search_end = hay.len();
528 while let Some(pos) = hay[..search_end].rfind(name) {
529 let end = pos + name.len();
530 let boundary_before = pos == 0 || !is_word(bytes[pos - 1]);
531 let boundary_after = end >= hay.len() || !is_word(bytes[end]);
532 if boundary_before && boundary_after {
533 return Some(Range {
534 start: doc.line_index.position(pos),
535 end: doc.line_index.position(end),
536 });
537 }
538 if pos == 0 {
539 break;
540 }
541 search_end = pos;
542 }
543 None
544}
545
546#[cfg(test)]
547#[path = "../../logicaffeine_tests/unit/logicaffeine_lsp/code_actions/tests.rs"]
548mod tests;