1use super::{CodeAction, Location, SymbolKind, TextEdit, index};
2use crate::diagnostics::{Applicability, Diagnostic};
3use crate::find_testscript_line;
4use crate::lexer::Lexer;
5use crate::parser::{Parser, Statement};
6use crate::project::{Document, Project, SourceId};
7use crate::token::Kind;
8use crate::types::Type;
9use std::collections::HashSet;
10use std::ops::Range;
11
12fn distance(left: &str, right: &str) -> usize {
13 let mut row: Vec<usize> = (0..=right.len()).collect();
14 for (i, a) in left.bytes().enumerate() {
15 let mut diagonal = row[0];
16 row[0] = i + 1;
17 for (j, b) in right.bytes().enumerate() {
18 let old = row[j + 1];
19 row[j + 1] = (row[j + 1] + 1)
20 .min(row[j] + 1)
21 .min(diagonal + usize::from(a != b));
22 diagonal = old;
23 }
24 }
25 row[right.len()]
26}
27
28fn insertion(document: &Document, offset: usize) -> usize {
29 find_testscript_line(&document.text)
30 .and_then(|line| document.lines.line(line.saturating_sub(1)))
31 .map(|line| line.start)
32 .filter(|marker| offset < *marker)
33 .unwrap_or(document.text.len())
34}
35
36impl Project {
37 pub fn quick_fixes(&self, source: SourceId, diagnostics: &[Diagnostic]) -> Vec<CodeAction> {
38 if diagnostics.is_empty() {
39 return Vec::new();
40 }
41 let mut actions = self.code_actions(diagnostics);
42 let Some(document) = self.document(source) else {
43 return actions;
44 };
45 let index = self.symbol_index();
46 for diagnostic in diagnostics {
47 if diagnostic.message.contains("from production code") {
48 continue;
49 }
50 let Some(line) = document.lines.line(diagnostic.line.saturating_sub(1)) else {
51 continue;
52 };
53 if diagnostic.message.starts_with("Type mismatch:") {
54 let types = diagnostic.message.split('\'').collect::<Vec<_>>();
55 if let (Some(given), Some(expected)) = (types.get(1), types.get(3)) {
56 for (declared, inferred) in [(given, expected), (expected, given)] {
57 if Type::from_name(inferred).is_none() {
58 continue;
59 }
60 if let Some(range) = document.tokens.iter().zip(&document.spans).find_map(
61 |(token, range)| {
62 (token.kind == Kind::Def
63 && line.contains(&range.start)
64 && document.text[range.clone()] == format!("def_{declared}"))
65 .then_some(range.clone())
66 },
67 ) {
68 actions.push(CodeAction {
69 title: format!("Change declared type to 'def_{inferred}'"),
70 kind: "quickfix",
71 edits: vec![TextEdit {
72 location: Location { source, range },
73 replacement: format!("def_{inferred}"),
74 }],
75 applicability: Applicability::MaybeIncorrect,
76 });
77 }
78 }
79 }
80 }
81 let Some(raw) = diagnostic.message.split('\'').nth(1) else {
82 continue;
83 };
84 let name = raw.trim_start_matches(['~', '@', '^', '%', '$']);
85 let Some(range) = document
86 .spans
87 .iter()
88 .find(|range| {
89 line.contains(&range.start) && document.text[(*range).clone()] == *name
90 })
91 .cloned()
92 else {
93 continue;
94 };
95 if diagnostic.message.contains("bare value")
96 && let Some(symbol) = index
97 .symbols
98 .iter()
99 .find(|symbol| symbol.kind == SymbolKind::Command && symbol.name == name)
100 {
101 let args = symbol
102 .parameters
103 .iter()
104 .map(|(_, ty)| match ty {
105 Type::String => "\"\"",
106 Type::Boolean => "false",
107 Type::Long => "0L",
108 _ => "0",
109 })
110 .collect::<Vec<_>>()
111 .join(", ");
112 actions.push(CodeAction {
113 title: format!("Call '{name}' with arguments"),
114 kind: "quickfix",
115 edits: vec![TextEdit {
116 location: Location {
117 source,
118 range: range.clone(),
119 },
120 replacement: format!("{name}({args})"),
121 }],
122 applicability: Applicability::HasPlaceholders,
123 });
124 continue;
125 }
126 let kind = if diagnostic.message.contains("constant") {
127 Some(SymbolKind::Constant)
128 } else if diagnostic.message.contains("proc") {
129 Some(SymbolKind::Procedure)
130 } else if diagnostic.message.contains("command") {
131 Some(SymbolKind::Command)
132 } else if diagnostic.message.contains("label") {
133 Some(SymbolKind::Trigger)
134 } else {
135 None
136 };
137 if diagnostic.message.contains("resolve") || diagnostic.message.contains("Unknown") {
138 let mut candidates = index
139 .symbols
140 .iter()
141 .filter(|symbol| {
142 kind.is_none_or(|kind| symbol.kind == kind)
143 && symbol.name.len().abs_diff(name.len()) <= 3
144 && index::visible(symbol, document, range.start)
145 })
146 .map(|symbol| (distance(name, &symbol.name), &symbol.name))
147 .filter(|(distance, _)| *distance > 0 && *distance <= 3)
148 .collect::<Vec<_>>();
149 candidates.sort();
150 candidates.dedup();
151 for (_, candidate) in candidates.into_iter().take(3) {
152 actions.push(CodeAction {
153 title: format!("Change to '{candidate}'"),
154 kind: "quickfix",
155 edits: vec![TextEdit {
156 location: Location {
157 source,
158 range: range.clone(),
159 },
160 replacement: candidate.clone(),
161 }],
162 applicability: Applicability::MaybeIncorrect,
163 });
164 }
165 if matches!(kind, Some(SymbolKind::Procedure | SymbolKind::Trigger)) {
166 let trigger = if kind == Some(SymbolKind::Procedure) {
167 "proc"
168 } else {
169 "label"
170 };
171 let insertion = insertion(document, range.start);
172 actions.push(CodeAction {
173 title: format!("Create [{trigger},{name}]"),
174 kind: "quickfix",
175 edits: vec![TextEdit {
176 location: Location {
177 source,
178 range: insertion..insertion,
179 },
180 replacement: format!("\n\n[{trigger},{name}]\nreturn;\n"),
181 }],
182 applicability: Applicability::MaybeIncorrect,
183 });
184 }
185 if diagnostic.message.contains("symbol") {
186 actions.push(CodeAction {
187 title: format!("Quote '{name}' as a string"),
188 kind: "quickfix",
189 edits: vec![TextEdit {
190 location: Location {
191 source,
192 range: range.clone(),
193 },
194 replacement: format!("\"{name}\""),
195 }],
196 applicability: Applicability::MaybeIncorrect,
197 });
198 }
199 }
200 }
201 actions
202 }
203
204 pub fn extract_proc(
205 &self,
206 source: SourceId,
207 range: Range<usize>,
208 name: &str,
209 ) -> Result<CodeAction, String> {
210 let document = self.document(source).ok_or("Unknown source")?;
211 if range.is_empty() || document.config.is_some() {
212 return Err("Select statements inside a script".into());
213 }
214 let text = document
215 .text
216 .get(range.clone())
217 .ok_or("Invalid selection")?;
218 let index = self.symbol_index();
219 if index
220 .symbols()
221 .any(|symbol| symbol.container.is_none() && symbol.name == name)
222 {
223 return Err("A script with this name already exists".into());
224 }
225 if name.is_empty()
226 || !name
227 .bytes()
228 .enumerate()
229 .all(|(i, b)| b == b'_' || b.is_ascii_alphabetic() || (i > 0 && b.is_ascii_digit()))
230 {
231 return Err("Invalid procedure name".into());
232 }
233 let enclosing = index
234 .symbols()
235 .find(|symbol| {
236 symbol.container.is_none()
237 && symbol.kind != SymbolKind::Command
238 && symbol.extent.as_ref().is_some_and(|extent| {
239 extent.source == source
240 && extent.range.start < range.start
241 && range.end <= extent.range.end
242 })
243 })
244 .ok_or("Selection must stay inside one script")?;
245 let selected = document
246 .tokens
247 .iter()
248 .zip(&document.spans)
249 .filter(|(_, span)| range.start <= span.start && span.start < range.end)
250 .collect::<Vec<_>>();
251 if selected
252 .iter()
253 .any(|(token, _)| token.kind == Kind::JumpCall)
254 {
255 return Err("A jump cannot be extracted into a returning procedure".into());
256 }
257 let mut params = Vec::new();
258 let mut outputs = Vec::new();
259 let mut seen = HashSet::new();
260 for reference in index
261 .references_in(source)
262 .filter(|r| range.contains(&r.location.range.start))
263 {
264 let symbol = index.symbol(reference.symbol);
265 if symbol.container.is_none() || !seen.insert(reference.symbol) {
266 continue;
267 }
268 let defined_inside = symbol
269 .definition
270 .as_ref()
271 .is_some_and(|definition| range.contains(&definition.range.start));
272 if !defined_inside {
273 params.push(symbol);
274 }
275 let used_after = index
276 .references_in(source)
277 .any(|r| r.symbol == reference.symbol && r.location.range.start >= range.end);
278 let assigned = index
279 .references_in(source)
280 .filter(|r| r.symbol == reference.symbol && range.contains(&r.location.range.start))
281 .any(|r| {
282 document
283 .spans
284 .iter()
285 .position(|span| *span == r.location.range)
286 .is_some_and(|i| {
287 document
288 .tokens
289 .iter()
290 .skip(i + 1)
291 .find(|token| {
292 !matches!(
293 token.kind,
294 Kind::Comma | Kind::LocalVar | Kind::Identifier
295 )
296 })
297 .is_some_and(|token| token.kind == Kind::Equals)
298 })
299 });
300 if used_after && (defined_inside || assigned) {
301 outputs.push((symbol, defined_inside));
302 }
303 }
304 let has_return = selected.iter().any(|(token, _)| token.kind == Kind::Return);
305 let probe = format!("[proc,{name}]\n{text}");
306 let tokens = Lexer::new(&probe, &document.label)
307 .tokenize()
308 .map_err(|_| "Select complete statements")?;
309 let (parsed, errors) = Parser::new(tokens, &document.label).parse_recovering();
310 if !errors.is_empty() || parsed.scripts.len() != 1 {
311 return Err("Select complete statements".into());
312 }
313 if has_return
314 && !parsed.scripts[0]
315 .body
316 .last()
317 .is_some_and(|statement| matches!(statement, Statement::Return { .. }))
318 {
319 return Err("A selection with returns must end with an unconditional return".into());
320 }
321 if params.iter().any(|symbol| {
322 symbol.definition.as_ref().is_some_and(|definition| {
323 document
324 .spans
325 .iter()
326 .position(|span| *span == definition.range)
327 .is_some_and(|i| {
328 document
329 .tokens
330 .get(i + 1)
331 .is_some_and(|token| token.kind == Kind::LParen)
332 })
333 })
334 }) {
335 return Err("An array local cannot be passed as a scalar parameter".into());
336 }
337 let parameters = params
338 .iter()
339 .map(|symbol| {
340 format!(
341 "{} ${}",
342 symbol.value_type.unwrap_or(Type::Int).name(),
343 symbol.name
344 )
345 })
346 .collect::<Vec<_>>()
347 .join(", ");
348 let arguments = params
349 .iter()
350 .map(|symbol| format!("${}", symbol.name))
351 .collect::<Vec<_>>()
352 .join(", ");
353 let returns = if has_return {
354 enclosing
355 .returns
356 .iter()
357 .map(|ty| ty.name())
358 .collect::<Vec<_>>()
359 .join(", ")
360 } else {
361 outputs
362 .iter()
363 .map(|(symbol, _)| symbol.value_type.unwrap_or(Type::Int).name())
364 .collect::<Vec<_>>()
365 .join(", ")
366 };
367 let values = outputs
368 .iter()
369 .map(|(symbol, _)| format!("${}", symbol.name))
370 .collect::<Vec<_>>()
371 .join(", ");
372 let mut replacement = String::new();
373 for (symbol, new) in outputs.iter().filter(|_| !has_return) {
374 if *new {
375 replacement.push_str(&format!(
376 "def_{} ${};\n",
377 symbol.value_type.unwrap_or(Type::Int).name(),
378 symbol.name
379 ));
380 }
381 }
382 if has_return && !enclosing.returns.is_empty() {
383 replacement.push_str("return(");
384 } else if !has_return && !outputs.is_empty() {
385 replacement.push_str(&format!("{values} = "));
386 }
387 replacement.push_str(&format!("~{name}({arguments})"));
388 replacement.push_str(if has_return && !enclosing.returns.is_empty() {
389 ");"
390 } else {
391 ";"
392 });
393 if has_return && enclosing.returns.is_empty() {
394 replacement.push_str("\nreturn;");
395 }
396 let body = format!(
397 "\n\n[proc,{name}]({parameters}){}\n{}\n{}\n",
398 if returns.is_empty() {
399 String::new()
400 } else {
401 format!("({returns})")
402 },
403 text.trim(),
404 if has_return {
405 String::new()
406 } else if outputs.is_empty() {
407 "return;".into()
408 } else {
409 format!("return({values});")
410 }
411 );
412 let insertion = insertion(document, range.start);
413 Ok(CodeAction {
414 title: format!("Extract procedure '{name}'"),
415 kind: "refactor.extract",
416 edits: vec![
417 TextEdit {
418 location: Location { source, range },
419 replacement,
420 },
421 TextEdit {
422 location: Location {
423 source,
424 range: insertion..insertion,
425 },
426 replacement: body,
427 },
428 ],
429 applicability: Applicability::MaybeIncorrect,
430 })
431 }
432}