Skip to main content

runec/ide/
queries.rs

1use super::{
2    CodeAction, Completion, Hover, Index, Location, SemanticToken, SignatureHelp, Symbol,
3    SymbolKind, TextEdit, config, highlighting, index,
4};
5use crate::clientscript::hooks::transmit_id;
6use crate::diagnostics::{Diagnostic, DiagnosticsCollector, Phase};
7use crate::project::{Project, SourceId};
8use crate::sources::Scope;
9use crate::symbol::SymbolKind as RegistryKind;
10use crate::text::Position;
11use crate::token::Kind;
12use crate::trigger_table;
13use crate::types::Type;
14use std::collections::HashSet;
15use std::ops::Range;
16
17impl Project {
18    pub(super) fn symbol_index(&self) -> &Index {
19        self.index.get_or_init(|| Index::build(self))
20    }
21
22    pub fn hover(&self, source: SourceId, offset: usize) -> Option<Hover> {
23        let index = self.symbol_index();
24        let Some(reference) = index.at(source, offset) else {
25            return config::key_hover(self.document(source)?, offset);
26        };
27        let symbol = &index.symbols[reference.symbol];
28        Some(Hover {
29            range: reference.location.range.clone(),
30            kind: symbol.kind,
31            detail: symbol.detail.clone(),
32            documentation: symbol.documentation.clone(),
33        })
34    }
35
36    pub fn definition(&self, source: SourceId, offset: usize) -> Option<Location> {
37        let index = self.symbol_index();
38        index.symbols[index.at(source, offset)?.symbol]
39            .definition
40            .clone()
41    }
42
43    pub fn references(
44        &self,
45        source: SourceId,
46        offset: usize,
47        include_declaration: bool,
48    ) -> Vec<Location> {
49        let index = self.symbol_index();
50        let Some(selected) = index.at(source, offset) else {
51            return Vec::new();
52        };
53        index
54            .references
55            .iter()
56            .filter(|reference| {
57                reference.symbol == selected.symbol
58                    && (include_declaration || !reference.declaration)
59            })
60            .map(|reference| reference.location.clone())
61            .collect()
62    }
63
64    pub fn document_symbols(&self, source: SourceId) -> Vec<&Symbol> {
65        self.symbol_index()
66            .symbols
67            .iter()
68            .filter(|symbol| {
69                symbol
70                    .definition
71                    .as_ref()
72                    .is_some_and(|location| location.source == source)
73            })
74            .collect()
75    }
76
77    pub fn workspace_symbols(&self, query: &str, limit: usize) -> Vec<&Symbol> {
78        let query = query.to_lowercase();
79        self.symbol_index()
80            .symbols
81            .iter()
82            .filter(|symbol| {
83                symbol.container.is_none() && symbol.name.to_lowercase().contains(&query)
84            })
85            .take(limit)
86            .collect()
87    }
88
89    /// Rename only source-owned definitions. External config and engine symbols
90    /// require their host's editing support, so an incomplete edit is rejected.
91    pub fn rename(
92        &self,
93        source: SourceId,
94        offset: usize,
95        name: &str,
96    ) -> Result<Vec<TextEdit>, String> {
97        if name.is_empty()
98            || !name.bytes().enumerate().all(|(i, b)| {
99                b == b'_'
100                    || b.is_ascii_alphabetic()
101                    || (i > 0 && (b.is_ascii_digit() || b":+.".contains(&b)))
102            })
103        {
104            return Err("Expected an identifier containing letters, digits or underscores".into());
105        }
106        let index = self.symbol_index();
107        let selected = index
108            .at(source, offset)
109            .ok_or("No resolved symbol at this position")?;
110        let symbol = &index.symbols[selected.symbol];
111        let name = if matches!(symbol.value_type, Some(Type::Component | Type::DbColumn))
112            && let Some((parent, _)) = symbol.name.rsplit_once(':')
113        {
114            if let Some((new_parent, _)) = name.rsplit_once(':') {
115                if parent != new_parent {
116                    return Err("Rename the containing interface or table separately".into());
117                }
118                name.to_string()
119            } else {
120                format!("{parent}:{name}")
121            }
122        } else {
123            name.to_string()
124        };
125        if index
126            .symbols
127            .iter()
128            .filter(|other| other.key == symbol.key)
129            .count()
130            > 1
131        {
132            return Err("Resolve duplicate declarations before renaming this symbol".into());
133        }
134        if symbol.definition.is_none() {
135            return Err("This definition is supplied by the host; rename it through the host's config editor".into());
136        }
137        if index.symbols.iter().any(|other| {
138            other.name == name
139                && other.key != symbol.key
140                && (symbol.kind != SymbolKind::Config || other.value_type == symbol.value_type)
141                && other.container == symbol.container
142                && (other.scope == symbol.scope
143                    || symbol.scope == Some(Scope::Global)
144                    || other.scope == Some(Scope::Global))
145        }) {
146            return Err(format!(
147                "Renaming to '{name}' would conflict with an existing definition"
148            ));
149        }
150        if symbol.container.is_some()
151            && index.symbols.iter().any(|other| {
152                other.name == name
153                    && other.key != symbol.key
154                    && other.container.is_some()
155                    && other
156                        .extent
157                        .as_ref()
158                        .zip(symbol.extent.as_ref())
159                        .is_some_and(|(a, b)| {
160                            a.source == b.source
161                                && a.range.start < b.range.end
162                                && b.range.start < a.range.end
163                        })
164            })
165        {
166            return Err(format!(
167                "Renaming to '{name}' would capture or shadow a variable in an overlapping scope"
168            ));
169        }
170        if Type::from_name(&name).is_some()
171            || matches!(
172                name.as_str(),
173                "if" | "else"
174                    | "return"
175                    | "while"
176                    | "case"
177                    | "default"
178                    | "calc"
179                    | "true"
180                    | "false"
181                    | "null"
182            )
183        {
184            return Err(format!("'{name}' is reserved by the language"));
185        }
186        if symbol.container.is_some() && name.bytes().any(|b| b":+.".contains(&b)) {
187            return Err("Local names must contain letters, digits or underscores".into());
188        }
189        let mut edits = self
190            .references(source, offset, true)
191            .into_iter()
192            .map(|location| {
193                let old = &self.document(location.source).unwrap().text[location.range.clone()];
194                let replacement =
195                    if matches!(symbol.value_type, Some(Type::Component | Type::DbColumn)) {
196                        if let Some(slot) = old.strip_prefix(&format!("{}:", symbol.name)) {
197                            format!("{name}:{slot}")
198                        } else if !old.contains(':') {
199                            name.rsplit(':').next().unwrap().to_string()
200                        } else {
201                            name.clone()
202                        }
203                    } else {
204                        name.clone()
205                    };
206                TextEdit {
207                    location,
208                    replacement,
209                }
210            })
211            .collect::<Vec<_>>();
212        let child_type = match symbol.value_type {
213            Some(Type::Interface) => Some(Type::Component),
214            Some(Type::DbTable) => Some(Type::DbColumn),
215            _ => None,
216        };
217        if let Some(child_type) = child_type {
218            let prefix = format!("{}:", symbol.name);
219            for reference in &index.references {
220                let child = &index.symbols[reference.symbol];
221                if child.value_type != Some(child_type) || !child.name.starts_with(&prefix) {
222                    continue;
223                }
224                let old = &self.document(reference.location.source).unwrap().text
225                    [reference.location.range.clone()];
226                if let Some(suffix) = old.strip_prefix(&prefix) {
227                    edits.push(TextEdit {
228                        location: reference.location.clone(),
229                        replacement: format!("{name}:{suffix}"),
230                    });
231                }
232            }
233        }
234        edits.sort_by_key(|edit| (edit.location.source, edit.location.range.start));
235        edits.dedup_by(|a, b| a.location == b.location);
236        Ok(edits)
237    }
238
239    /// Bounded completion lists prevent copying entire cache registries on each keystroke.
240    pub fn completions(&self, source: SourceId, offset: usize, limit: usize) -> Vec<Completion> {
241        let Some(document) = self.document(source) else {
242            return Vec::new();
243        };
244        if !document.text.is_char_boundary(offset) {
245            return Vec::new();
246        }
247        if let Some(items) = config::completions(self, document, offset, limit) {
248            return items;
249        }
250        let Some(before) = document.text.get(..offset) else {
251            return Vec::new();
252        };
253        let start = before
254            .rfind(|ch: char| !ch.is_ascii_alphanumeric() && !"_:+.".contains(ch))
255            .map_or(0, |i| i + 1);
256        let prefix = &before[start..];
257        let index = self.symbol_index();
258        if !matches!(before[..start].chars().next_back(), Some('$' | '%' | '^'))
259            && let Some(kind) = index
260                .hooks
261                .get(&source)
262                .and_then(|hooks| hooks.iter().find_map(|hook| hook.transmit_at(offset)))
263        {
264            return index
265                .symbols
266                .iter()
267                .filter(|symbol| {
268                    symbol.name.starts_with(prefix)
269                        && index::visible(symbol, document, offset)
270                        && transmit_id(&self.registry, kind, &symbol.name).is_some()
271                })
272                .take(limit)
273                .map(|symbol| Completion {
274                    label: symbol.name.clone(),
275                    detail: symbol.detail.clone(),
276                    kind: symbol.kind,
277                    replacement: start..offset,
278                })
279                .collect();
280        }
281        if index.hooks.get(&source).is_some_and(|hooks| {
282            hooks
283                .iter()
284                .any(|hook| hook.callback.start <= offset && offset <= hook.callback.end)
285        }) {
286            return index
287                .symbols
288                .iter()
289                .filter(|symbol| {
290                    matches!(
291                        symbol.kind,
292                        SymbolKind::ClientScript | SymbolKind::Procedure
293                    ) && symbol.scope == Some(Scope::Client)
294                        && symbol.name.starts_with(prefix)
295                })
296                .take(limit)
297                .map(|symbol| Completion {
298                    label: symbol.name.clone(),
299                    detail: symbol.detail.clone(),
300                    kind: symbol.kind,
301                    replacement: start..offset,
302                })
303                .collect();
304        }
305        let sigil = before[..start].chars().next_back();
306        let mut result = Vec::new();
307        let mut seen = HashSet::new();
308        let line = before.rsplit('\n').next().unwrap_or(before).trim_start();
309        let header = line.strip_prefix('[').filter(|line| !line.contains(']'));
310        if header.is_some_and(|header| !header.contains(',')) {
311            let names = self.registry.profile.as_ref().map_or_else(
312                || trigger_table::names().collect::<Vec<_>>(),
313                |profile| profile.triggers.keys().map(String::as_str).collect(),
314            );
315            return names
316                .into_iter()
317                .filter(|name| name.starts_with(prefix))
318                .map(|name| Completion {
319                    label: name.into(),
320                    detail: "trigger".into(),
321                    kind: SymbolKind::Trigger,
322                    replacement: start..offset,
323                })
324                .take(limit)
325                .collect();
326        }
327        let trigger = header
328            .and_then(|header| header.split_once(','))
329            .map(|(trigger, _)| trigger.trim());
330        let expected = trigger
331            .and_then(|trigger| self.registry.trigger(trigger))
332            .and_then(|trigger| trigger.subject_type)
333            .or_else(|| {
334                self.signature_help(source, offset).and_then(|help| {
335                    help.parameters
336                        .get(help.active_parameter)
337                        .map(|(_, ty)| *ty)
338                })
339            });
340        let matches_type = |ty: Type| {
341            expected.is_none_or(|expected| {
342                expected == Type::Any
343                    || expected == ty
344                    || matches!(
345                        (expected, ty),
346                        (Type::NamedObj, Type::Obj) | (Type::Obj, Type::NamedObj)
347                    )
348                    || (trigger.is_some() && expected == Type::Interface && ty == Type::Component)
349            })
350        };
351        for symbol in &self.symbol_index().symbols {
352            if !symbol.name.starts_with(prefix) || !index::visible(symbol, document, offset) {
353                continue;
354            }
355            let inaccessible = match symbol.kind {
356                SymbolKind::Constant => self.registry.visibility.check(&document.label, "constant", &symbol.name, true).is_some(),
357                SymbolKind::GameVariable => self.registry.lookup_game_var(&symbol.name).is_some_and(|variable| {
358                    matches!(&variable.kind, RegistryKind::GameVar { category, .. } if self.registry.visibility.check(&document.label, category, &symbol.name, true).is_some())
359                }),
360                SymbolKind::Config => symbol.value_type.is_some_and(|ty| self.registry.visibility.typed(&document.label, &symbol.name, ty, &self.registry).is_some()),
361                _ => false,
362            };
363            if inaccessible {
364                continue;
365            }
366            if !matches!(sigil, Some('$' | '^' | '%' | '~' | '@')) {
367                if let Some(trigger) = trigger.filter(|_| expected.is_none()) {
368                    if !symbol.key.ends_with(&format!(":{trigger}:{}", symbol.name)) {
369                        continue;
370                    }
371                } else if let Some(expected) = expected {
372                    let script_type = matches!(
373                        expected,
374                        Type::Proc
375                            | Type::Label
376                            | Type::Queue
377                            | Type::Timer
378                            | Type::SoftTimer
379                            | Type::Walktrigger
380                            | Type::ClientScript
381                    );
382                    if script_type {
383                        if !symbol
384                            .key
385                            .ends_with(&format!(":{}:{}", expected.name(), symbol.name))
386                        {
387                            continue;
388                        }
389                    } else if symbol.kind != SymbolKind::Config
390                        || !symbol.value_type.is_some_and(matches_type)
391                    {
392                        continue;
393                    }
394                }
395            }
396            let matches = match sigil {
397                Some('$') => symbol.container.is_some(),
398                Some('^') => symbol.kind == SymbolKind::Constant,
399                Some('%') => symbol.kind == SymbolKind::GameVariable,
400                Some('~') => symbol.kind == SymbolKind::Procedure,
401                Some('@') => symbol.key.contains(":label:"),
402                _ => {
403                    symbol.container.is_none()
404                        && !matches!(symbol.kind, SymbolKind::Constant | SymbolKind::GameVariable)
405                }
406            };
407            if matches && seen.insert(symbol.name.clone()) {
408                result.push(Completion {
409                    label: symbol.name.clone(),
410                    detail: symbol.detail.clone(),
411                    kind: symbol.kind,
412                    replacement: start..offset,
413                });
414            }
415        }
416        if !matches!(sigil, Some('$' | '^' | '%' | '~' | '@'))
417            && trigger.is_none_or(|_| expected.is_some())
418        {
419            let mut configs = self
420                .registry
421                .entity_ids
422                .iter()
423                .filter(|(name, entry)| {
424                    name.starts_with(prefix)
425                        && entry.variants.iter().any(|(ty, _)| {
426                            matches_type(*ty)
427                                && self
428                                    .registry
429                                    .visibility
430                                    .typed(&document.label, name, *ty, &self.registry)
431                                    .is_none()
432                        })
433                })
434                .map(|(name, _)| name.as_str())
435                .collect::<Vec<_>>();
436            configs.sort_unstable();
437            for name in configs.into_iter().take(limit) {
438                if seen.insert(name.to_string()) {
439                    let entry = &self.registry.entity_ids[name];
440                    result.push(Completion {
441                        label: name.into(),
442                        detail: entry
443                            .variants
444                            .iter()
445                            .map(|(ty, id)| format!("{} {name} = {id}", ty.name()))
446                            .collect::<Vec<_>>()
447                            .join("\n"),
448                        kind: SymbolKind::Config,
449                        replacement: start..offset,
450                    });
451                }
452            }
453        }
454        if sigil.is_none_or(|sigil| !"$^%~@".contains(sigil))
455            && expected.is_none()
456            && header.is_none()
457        {
458            let keywords =
459                "if else while return case default calc switch_int switch_string true false null";
460            let types = "int boolean string long char colour coord loc npc obj namedobj player_uid npc_uid seq spotanim synth midi jingle graphic fontmetrics model texture idkit mesanim hitmark stat component iftype setposh setposv setsize settextalignh settextalignv interface toplevelinterface overlayinterface inv enum struct param dbtable dbrow dbcolumn category varp varn vars varbit mapzone maparea mapelement locshape npc_mode npc_stat area hunt movespeed entityoverlay stringvector writeinvobj controller regioncoord label proc clientscript queue softtimer timer walktrigger any";
461            for name in keywords
462                .split_whitespace()
463                .map(str::to_string)
464                .chain(types.split_whitespace().map(|ty| format!("def_{ty}")))
465            {
466                if name.starts_with(prefix) && seen.insert(name.clone()) {
467                    result.push(Completion {
468                        label: name.clone(),
469                        detail: "keyword".into(),
470                        kind: SymbolKind::Variable,
471                        replacement: start..offset,
472                    });
473                }
474            }
475        }
476        result.sort_by(|a, b| a.label.cmp(&b.label));
477        result.truncate(limit);
478        result
479    }
480
481    pub fn signature_help(&self, source: SourceId, offset: usize) -> Option<SignatureHelp> {
482        let document = self.document(source)?;
483        let tokens = index::tokens(
484            document,
485            &self.symbol_index().compounds,
486            self.symbol_index()
487                .hooks
488                .get(&source)
489                .map_or(&[][..], Vec::as_slice),
490        );
491        let mut stack: Vec<(Option<usize>, usize)> = Vec::new();
492        let mut previous = None;
493        let index = self.symbol_index();
494        for (token, range) in tokens.iter().filter(|(_, range)| range.start < offset) {
495            match token.kind {
496                Kind::LParen => {
497                    stack.push((
498                        previous
499                            .and_then(|position| index.at(source, position))
500                            .map(|reference| reference.symbol),
501                        0,
502                    ));
503                }
504                Kind::LBrace | Kind::LBracket => stack.push((None, 0)),
505                Kind::RParen | Kind::RBrace | Kind::RBracket => {
506                    stack.pop();
507                }
508                Kind::Comma => {
509                    if let Some((_, argument)) = stack.last_mut() {
510                        *argument += 1;
511                    }
512                }
513                Kind::SingleLineComment
514                | Kind::MultiLineComment
515                | Kind::StringLiteral
516                | Kind::RawStringLiteral => continue,
517                _ => {}
518            }
519            previous = Some(range.start);
520        }
521        let (symbol, argument) = stack
522            .into_iter()
523            .rev()
524            .find_map(|(symbol, argument)| symbol.map(|symbol| (symbol, argument)))?;
525        let symbol = &index.symbols[symbol];
526        Some(SignatureHelp {
527            label: symbol.detail.clone(),
528            parameters: symbol.parameters.clone(),
529            active_parameter: argument,
530            documentation: symbol.documentation.clone(),
531        })
532    }
533
534    /// Config values that do not name what their key holds.
535    pub fn config_diagnostics(&self) -> DiagnosticsCollector {
536        let mut diagnostics = DiagnosticsCollector::new();
537        for (source, problems) in &self.symbol_index().config_problems {
538            let Some(document) = self.document(*source) else {
539                continue;
540            };
541            for (line, message) in problems {
542                diagnostics.warning(
543                    document.label.clone(),
544                    *line,
545                    0,
546                    message.clone(),
547                    Phase::TypeChecking,
548                );
549            }
550        }
551        diagnostics
552    }
553
554    pub fn semantic_tokens(&self, source: SourceId) -> Vec<SemanticToken> {
555        let Some(document) = self.document(source) else {
556            return Vec::new();
557        };
558        if document.config.is_some() {
559            // Never waits for the index: until it exists, values typed by a
560            // declaration read as plain words.
561            return match self.index.get() {
562                Some(index) => config::tokens(document, &index.config_types),
563                None => config::tokens(document, &Default::default()),
564            };
565        }
566        highlighting::script(document, self.symbol_index())
567    }
568
569    pub fn folding_ranges(&self, source: SourceId) -> Vec<Range<usize>> {
570        let Some(document) = self.document(source) else {
571            return Vec::new();
572        };
573        let mut stack = Vec::new();
574        let mut ranges = Vec::new();
575        for (token, span) in document.tokens.iter().zip(&document.spans) {
576            match token.kind {
577                Kind::LBrace => stack.push(span.start),
578                Kind::RBrace => {
579                    if let Some(start) = stack.pop() {
580                        ranges.push(start..span.end);
581                    }
582                }
583                Kind::MultiLineComment => ranges.push(span.clone()),
584                _ => {}
585            }
586        }
587        ranges.extend(
588            self.document_symbols(source)
589                .into_iter()
590                .filter(|symbol| symbol.container.is_none())
591                .filter_map(|symbol| symbol.extent.as_ref().map(|extent| extent.range.clone())),
592        );
593        ranges.retain(|range| document.text[range.clone()].contains('\n'));
594        ranges.sort_by_key(|range| (range.start, range.end));
595        ranges
596    }
597
598    pub fn selection_ranges(&self, source: SourceId, offset: usize) -> Vec<Range<usize>> {
599        let Some(document) = self.document(source) else {
600            return Vec::new();
601        };
602        let mut ranges = self
603            .folding_ranges(source)
604            .into_iter()
605            .filter(|range| range.contains(&offset))
606            .collect::<Vec<_>>();
607        if let Some(range) = document.spans.iter().find(|range| range.contains(&offset)) {
608            ranges.push(range.clone());
609        }
610        if let Some(position) = document.lines.position(&document.text, offset)
611            && let Some(line) = document.lines.line(position.line)
612        {
613            ranges.push(line);
614        }
615        ranges.push(0..document.text.len());
616        ranges.sort_by_key(|range| range.len());
617        ranges.dedup();
618        let mut nested: Vec<Range<usize>> = Vec::new();
619        for range in ranges {
620            if nested
621                .last()
622                .is_none_or(|inner| range.start <= inner.start && range.end >= inner.end)
623            {
624                nested.push(range);
625            }
626        }
627        nested
628    }
629
630    /// Reindent without rewriting expressions, literals or comments.
631    /// Each edit is confined to whitespace outside string tokens.
632    pub fn format(&self, source: SourceId, tab_size: usize, spaces: bool) -> Vec<TextEdit> {
633        let Some(document) = self.document(source) else {
634            return Vec::new();
635        };
636        let mut edits = Vec::new();
637        let mut depth = 0usize;
638        let mut token_index = 0;
639        let protected = document
640            .tokens
641            .iter()
642            .zip(&document.spans)
643            .filter(|(token, _)| {
644                matches!(
645                    token.kind,
646                    Kind::StringLiteral | Kind::RawStringLiteral | Kind::MultiLineComment
647                )
648            })
649            .map(|(_, span)| span.clone())
650            .collect::<Vec<_>>();
651        let unit = if spaces {
652            " ".repeat(tab_size.clamp(1, 16))
653        } else {
654            "\t".into()
655        };
656        for line in 0..document.lines.line_count() {
657            let range = document.lines.line(line).unwrap();
658            let text = &document.text[range.clone()];
659            let content = text.trim_end_matches(['\r', '\n']);
660            let next = protected.partition_point(|span| span.end <= range.start);
661            let protected_line = protected[next..]
662                .iter()
663                .take_while(|span| span.start < range.end)
664                .any(|span| span.start < range.start || span.end > range.start + content.len());
665            let trimmed = content.trim();
666            let indent = depth.saturating_sub(usize::from(trimmed.starts_with('}')));
667            let formatted = if trimmed.is_empty() {
668                String::new()
669            } else {
670                format!("{}{trimmed}", unit.repeat(indent))
671            };
672            if !protected_line && content != formatted {
673                edits.push(TextEdit {
674                    location: Location {
675                        source,
676                        range: range.start..range.start + content.len(),
677                    },
678                    replacement: formatted,
679                });
680            }
681            while token_index < document.tokens.len()
682                && document.spans[token_index].start < range.end
683            {
684                match document.tokens[token_index].kind {
685                    Kind::LBrace => depth += 1,
686                    Kind::RBrace => depth = depth.saturating_sub(1),
687                    _ => {}
688                }
689                token_index += 1;
690            }
691        }
692        edits
693    }
694
695    pub fn code_actions(&self, diagnostics: &[Diagnostic]) -> Vec<CodeAction> {
696        let mut actions = Vec::new();
697        for diagnostic in diagnostics {
698            for help in &diagnostic.help {
699                let mut edits = Vec::new();
700                for suggestion in &help.suggestions {
701                    let Some(document) = self
702                        .documents
703                        .values()
704                        .find(|document| document.label == suggestion.file)
705                    else {
706                        continue;
707                    };
708                    let start = document
709                        .lines
710                        .line(suggestion.line_range.0.saturating_sub(1))
711                        .map_or(document.text.len(), |range| range.start);
712                    let end = document
713                        .lines
714                        .line(suggestion.line_range.1.saturating_sub(1))
715                        .map_or(document.text.len(), |range| range.end);
716                    edits.push(TextEdit {
717                        location: Location {
718                            source: document.id,
719                            range: start..end.max(start),
720                        },
721                        replacement: suggestion.replacement.clone(),
722                    });
723                }
724                if !edits.is_empty() {
725                    actions.push(CodeAction {
726                        title: help.message.clone(),
727                        kind: "quickfix",
728                        edits,
729                        applicability: help.applicability,
730                    });
731                }
732            }
733        }
734        actions
735    }
736
737    /// Verbose source excerpts from the current buffer, including unsaved edits.
738    pub fn render_diagnostic(&self, diagnostic: &Diagnostic) -> String {
739        let mut text = format!("{} [{}]\n", diagnostic, diagnostic.code());
740        if let Some(document) = self
741            .documents
742            .values()
743            .find(|document| document.label == diagnostic.file)
744        {
745            let range =
746                document
747                    .lines
748                    .diagnostic_range(&document.text, diagnostic.line, diagnostic.column);
749            if let Some(Position { line, .. }) =
750                document.lines.position(&document.text, range.start)
751                && let Some(line_range) = document.lines.line(line)
752            {
753                let excerpt = document.text[line_range.clone()].trim_end_matches(['\r', '\n']);
754                let column = document.text[line_range.start..range.start].chars().count();
755                text.push_str(&format!(
756                    "{:>5} | {excerpt}\n      | {}^\n",
757                    line + 1,
758                    " ".repeat(column)
759                ));
760            }
761        }
762        for help in &diagnostic.help {
763            text.push_str(&format!("help: {}\n", help.message));
764        }
765        text
766    }
767}
768
769impl Diagnostic {
770    /// Stable phase codes; message wording is not part of the diagnostic API.
771    pub fn code(&self) -> &'static str {
772        match self.phase {
773            Phase::Lexing => "RUNEC1001",
774            Phase::Parsing => "RUNEC1002",
775            Phase::SymbolRegistration => "RUNEC2001",
776            Phase::TypeChecking => "RUNEC2002",
777            Phase::CodeGeneration => "RUNEC3001",
778            Phase::PointerCheck => "RUNEC4001",
779        }
780    }
781}