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