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