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 || {
315 if self.target_scope() == Scope::Client {
316 triggers::TRIGGERS
317 .iter()
318 .map(|trigger| trigger.name)
319 .collect::<Vec<_>>()
320 } else {
321 trigger_table::names().collect()
322 }
323 },
324 |profile| profile.triggers.keys().map(String::as_str).collect(),
325 );
326 return names
327 .into_iter()
328 .filter(|name| name.starts_with(prefix))
329 .map(|name| Completion {
330 label: name.into(),
331 detail: "trigger".into(),
332 kind: SymbolKind::Trigger,
333 replacement: start..offset,
334 })
335 .take(limit)
336 .collect();
337 }
338 let trigger = header
339 .and_then(|header| header.split_once(','))
340 .map(|(trigger, _)| trigger.trim());
341 let expected = trigger
342 .and_then(|trigger| {
343 if self.target_scope() == Scope::Client {
344 triggers::lookup(trigger).and_then(|trigger| trigger.subject_type)
345 } else {
346 self.registry
347 .trigger(trigger)
348 .and_then(|trigger| trigger.subject_type)
349 }
350 })
351 .or_else(|| {
352 self.signature_help(source, offset).and_then(|help| {
353 help.parameters
354 .get(help.active_parameter)
355 .map(|(_, ty)| *ty)
356 })
357 });
358 let matches_type = |ty: Type| {
359 expected.is_none_or(|expected| {
360 expected == Type::Any
361 || expected == ty
362 || matches!(
363 (expected, ty),
364 (Type::NamedObj, Type::Obj) | (Type::Obj, Type::NamedObj)
365 )
366 || (trigger.is_some() && expected == Type::Interface && ty == Type::Component)
367 })
368 };
369 for symbol in self.symbol_index().symbols() {
370 if !symbol.name.starts_with(prefix) || !index::visible(symbol, document, offset) {
371 continue;
372 }
373 let inaccessible = match symbol.kind {
374 SymbolKind::Constant => self.registry.visibility.check(&document.label, "constant", &symbol.name, true).is_some(),
375 SymbolKind::GameVariable => self.registry.lookup_game_var(&symbol.name).is_some_and(|variable| {
376 matches!(&variable.kind, RegistryKind::GameVar { category, .. } if self.registry.visibility.check(&document.label, category, &symbol.name, true).is_some())
377 }),
378 SymbolKind::Config => symbol.value_type.is_some_and(|ty| self.registry.visibility.typed(&document.label, &symbol.name, ty, &self.registry).is_some()),
379 _ => false,
380 };
381 if inaccessible {
382 continue;
383 }
384 if !matches!(sigil, Some('$' | '^' | '%' | '~' | '@')) {
385 if let Some(trigger) = trigger.filter(|_| expected.is_none()) {
386 if !symbol.key.ends_with(&format!(":{trigger}:{}", symbol.name)) {
387 continue;
388 }
389 } else if let Some(expected) = expected {
390 let script_type = matches!(
391 expected,
392 Type::Proc
393 | Type::Label
394 | Type::Queue
395 | Type::Timer
396 | Type::SoftTimer
397 | Type::Walktrigger
398 | Type::ControllerQueue
399 | Type::NpcQueue
400 | Type::ClientScript
401 );
402 if script_type {
403 if !symbol
404 .key
405 .ends_with(&format!(":{}:{}", expected.name(), symbol.name))
406 {
407 continue;
408 }
409 } else if symbol.kind != SymbolKind::Config
410 || !symbol.value_type.is_some_and(matches_type)
411 {
412 continue;
413 }
414 }
415 }
416 let matches = match sigil {
417 Some('$') => symbol.container.is_some(),
418 Some('^') => symbol.kind == SymbolKind::Constant,
419 Some('%') => symbol.kind == SymbolKind::GameVariable,
420 Some('~') => symbol.kind == SymbolKind::Procedure,
421 Some('@') => symbol.key.contains(":label:"),
422 _ => {
423 symbol.container.is_none()
424 && !matches!(symbol.kind, SymbolKind::Constant | SymbolKind::GameVariable)
425 }
426 };
427 if matches && seen.insert(symbol.name.clone()) {
428 result.push(Completion {
429 label: symbol.name.clone(),
430 detail: symbol.detail.clone(),
431 kind: symbol.kind,
432 replacement: start..offset,
433 });
434 }
435 }
436 if !matches!(sigil, Some('$' | '^' | '%' | '~' | '@'))
437 && trigger.is_none_or(|_| expected.is_some())
438 {
439 let mut configs = self
440 .registry
441 .entity_ids
442 .iter()
443 .filter(|(name, entry)| {
444 name.starts_with(prefix)
445 && entry.variants.iter().any(|(ty, _)| {
446 matches_type(*ty)
447 && self
448 .registry
449 .visibility
450 .typed(&document.label, name, *ty, &self.registry)
451 .is_none()
452 })
453 })
454 .map(|(name, _)| name.as_str())
455 .collect::<Vec<_>>();
456 configs.sort_unstable();
457 for name in configs.into_iter().take(limit) {
458 if seen.insert(name.to_string()) {
459 let entry = &self.registry.entity_ids[name];
460 result.push(Completion {
461 label: name.into(),
462 detail: entry
463 .variants
464 .iter()
465 .map(|(ty, id)| format!("{} {name} = {id}", ty.name()))
466 .collect::<Vec<_>>()
467 .join("\n"),
468 kind: SymbolKind::Config,
469 replacement: start..offset,
470 });
471 }
472 }
473 }
474 if sigil.is_none_or(|sigil| !"$^%~@".contains(sigil))
475 && expected.is_none()
476 && header.is_none()
477 {
478 let keywords =
479 "if else while return case default calc switch_int switch_string true false null";
480 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";
481 for name in keywords
482 .split_whitespace()
483 .map(str::to_string)
484 .chain(types.split_whitespace().map(|ty| format!("def_{ty}")))
485 {
486 if name.starts_with(prefix) && seen.insert(name.clone()) {
487 result.push(Completion {
488 label: name.clone(),
489 detail: "keyword".into(),
490 kind: SymbolKind::Variable,
491 replacement: start..offset,
492 });
493 }
494 }
495 }
496 result.sort_by(|a, b| a.label.cmp(&b.label));
497 result.truncate(limit);
498 result
499 }
500
501 pub fn signature_help(&self, source: SourceId, offset: usize) -> Option<SignatureHelp> {
502 let document = self.document(source)?;
503 let tokens = index::tokens(
504 document,
505 &|name| self.symbol_index().is_compound(name),
506 self.symbol_index()
507 .hooks
508 .get(&source)
509 .map_or(&[][..], Vec::as_slice),
510 );
511 let mut stack: Vec<(Option<usize>, usize)> = Vec::new();
512 let mut previous = None;
513 let index = self.symbol_index();
514 for (token, range) in tokens.iter().filter(|(_, range)| range.start < offset) {
515 match token.kind {
516 Kind::LParen => {
517 stack.push((
518 previous
519 .and_then(|position| index.at(source, position))
520 .map(|reference| reference.symbol),
521 0,
522 ));
523 }
524 Kind::LBrace | Kind::LBracket => stack.push((None, 0)),
525 Kind::RParen | Kind::RBrace | Kind::RBracket => {
526 stack.pop();
527 }
528 Kind::Comma => {
529 if let Some((_, argument)) = stack.last_mut() {
530 *argument += 1;
531 }
532 }
533 Kind::SingleLineComment
534 | Kind::MultiLineComment
535 | Kind::StringLiteral
536 | Kind::RawStringLiteral => continue,
537 _ => {}
538 }
539 previous = Some(range.start);
540 }
541 let (symbol, argument) = stack
542 .into_iter()
543 .rev()
544 .find_map(|(symbol, argument)| symbol.map(|symbol| (symbol, argument)))?;
545 let symbol = index.symbol(symbol);
546 Some(SignatureHelp {
547 label: symbol.detail.clone(),
548 parameters: symbol.parameters.clone(),
549 active_parameter: argument,
550 documentation: symbol.documentation.clone(),
551 })
552 }
553
554 pub fn config_diagnostics(&self) -> DiagnosticsCollector {
556 let mut diagnostics = DiagnosticsCollector::new();
557 for (source, problems) in self.configs().problems() {
558 let Some(document) = self.document(*source) else {
559 continue;
560 };
561 for (line, message) in problems {
562 diagnostics.warning(
563 document.label.clone(),
564 *line,
565 0,
566 message.clone(),
567 Phase::TypeChecking,
568 );
569 }
570 }
571 diagnostics
572 }
573
574 pub fn semantic_tokens(&self, source: SourceId) -> Vec<SemanticToken> {
575 let Some(document) = self.document(source) else {
576 return Vec::new();
577 };
578 if document.config.is_some() {
579 return match self.configs.lock().unwrap().as_ref() {
582 Some(configs) => config::tokens(document, configs.types()),
583 None => config::tokens(document, &Default::default()),
584 };
585 }
586 highlighting::script(document, self.symbol_index())
587 }
588
589 pub fn folding_ranges(&self, source: SourceId) -> Vec<Range<usize>> {
590 let Some(document) = self.document(source) else {
591 return Vec::new();
592 };
593 let mut stack = Vec::new();
594 let mut ranges = Vec::new();
595 for (token, span) in document.tokens.iter().zip(&document.spans) {
596 match token.kind {
597 Kind::LBrace => stack.push(span.start),
598 Kind::RBrace => {
599 if let Some(start) = stack.pop() {
600 ranges.push(start..span.end);
601 }
602 }
603 Kind::MultiLineComment => ranges.push(span.clone()),
604 _ => {}
605 }
606 }
607 ranges.extend(
608 self.document_symbols(source)
609 .into_iter()
610 .filter(|symbol| symbol.container.is_none())
611 .filter_map(|symbol| symbol.extent.as_ref().map(|extent| extent.range.clone())),
612 );
613 ranges.retain(|range| document.text[range.clone()].contains('\n'));
614 ranges.sort_by_key(|range| (range.start, range.end));
615 ranges
616 }
617
618 pub fn selection_ranges(&self, source: SourceId, offset: usize) -> Vec<Range<usize>> {
619 let Some(document) = self.document(source) else {
620 return Vec::new();
621 };
622 let mut ranges = self
623 .folding_ranges(source)
624 .into_iter()
625 .filter(|range| range.contains(&offset))
626 .collect::<Vec<_>>();
627 if let Some(range) = document.spans.iter().find(|range| range.contains(&offset)) {
628 ranges.push(range.clone());
629 }
630 if let Some(position) = document.lines.position(&document.text, offset)
631 && let Some(line) = document.lines.line(position.line)
632 {
633 ranges.push(line);
634 }
635 ranges.push(0..document.text.len());
636 ranges.sort_by_key(|range| range.len());
637 ranges.dedup();
638 let mut nested: Vec<Range<usize>> = Vec::new();
639 for range in ranges {
640 if nested
641 .last()
642 .is_none_or(|inner| range.start <= inner.start && range.end >= inner.end)
643 {
644 nested.push(range);
645 }
646 }
647 nested
648 }
649
650 pub fn format(&self, source: SourceId, tab_size: usize, spaces: bool) -> Vec<TextEdit> {
653 let Some(document) = self.document(source) else {
654 return Vec::new();
655 };
656 let mut edits = Vec::new();
657 let mut depth = 0usize;
658 let mut token_index = 0;
659 let protected = document
660 .tokens
661 .iter()
662 .zip(&document.spans)
663 .filter(|(token, _)| {
664 matches!(
665 token.kind,
666 Kind::StringLiteral | Kind::RawStringLiteral | Kind::MultiLineComment
667 )
668 })
669 .map(|(_, span)| span.clone())
670 .collect::<Vec<_>>();
671 let unit = if spaces {
672 " ".repeat(tab_size.clamp(1, 16))
673 } else {
674 "\t".into()
675 };
676 for line in 0..document.lines.line_count() {
677 let range = document.lines.line(line).unwrap();
678 let text = &document.text[range.clone()];
679 let content = text.trim_end_matches(['\r', '\n']);
680 let next = protected.partition_point(|span| span.end <= range.start);
681 let protected_line = protected[next..]
682 .iter()
683 .take_while(|span| span.start < range.end)
684 .any(|span| span.start < range.start || span.end > range.start + content.len());
685 let trimmed = content.trim();
686 let indent = depth.saturating_sub(usize::from(trimmed.starts_with('}')));
687 let formatted = if trimmed.is_empty() {
688 String::new()
689 } else {
690 format!("{}{trimmed}", unit.repeat(indent))
691 };
692 if !protected_line && content != formatted {
693 edits.push(TextEdit {
694 location: Location {
695 source,
696 range: range.start..range.start + content.len(),
697 },
698 replacement: formatted,
699 });
700 }
701 while token_index < document.tokens.len()
702 && document.spans[token_index].start < range.end
703 {
704 match document.tokens[token_index].kind {
705 Kind::LBrace => depth += 1,
706 Kind::RBrace => depth = depth.saturating_sub(1),
707 _ => {}
708 }
709 token_index += 1;
710 }
711 }
712 edits
713 }
714
715 pub fn code_actions(&self, diagnostics: &[Diagnostic]) -> Vec<CodeAction> {
716 let mut actions = Vec::new();
717 for diagnostic in diagnostics {
718 for help in &diagnostic.help {
719 let mut edits = Vec::new();
720 for suggestion in &help.suggestions {
721 let Some(document) = self
722 .documents
723 .values()
724 .find(|document| document.label == suggestion.file)
725 else {
726 continue;
727 };
728 let start = document
729 .lines
730 .line(suggestion.line_range.0.saturating_sub(1))
731 .map_or(document.text.len(), |range| range.start);
732 let end = document
733 .lines
734 .line(suggestion.line_range.1.saturating_sub(1))
735 .map_or(document.text.len(), |range| range.end);
736 edits.push(TextEdit {
737 location: Location {
738 source: document.id,
739 range: start..end.max(start),
740 },
741 replacement: suggestion.replacement.clone(),
742 });
743 }
744 if !edits.is_empty() {
745 actions.push(CodeAction {
746 title: help.message.clone(),
747 kind: "quickfix",
748 edits,
749 applicability: help.applicability,
750 });
751 }
752 }
753 }
754 actions
755 }
756
757 pub fn render_diagnostic(&self, diagnostic: &Diagnostic) -> String {
759 let mut text = format!("{} [{}]\n", diagnostic, diagnostic.code());
760 if let Some(document) = self
761 .documents
762 .values()
763 .find(|document| document.label == diagnostic.file)
764 {
765 let range =
766 document
767 .lines
768 .diagnostic_range(&document.text, diagnostic.line, diagnostic.column);
769 if let Some(Position { line, .. }) =
770 document.lines.position(&document.text, range.start)
771 && let Some(line_range) = document.lines.line(line)
772 {
773 let excerpt = document.text[line_range.clone()].trim_end_matches(['\r', '\n']);
774 let column = document.text[line_range.start..range.start].chars().count();
775 text.push_str(&format!(
776 "{:>5} | {excerpt}\n | {}^\n",
777 line + 1,
778 " ".repeat(column)
779 ));
780 }
781 }
782 for help in &diagnostic.help {
783 text.push_str(&format!("help: {}\n", help.message));
784 }
785 text
786 }
787}
788
789impl Diagnostic {
790 pub fn code(&self) -> &'static str {
792 match self.phase {
793 Phase::Lexing => "RUNEC1001",
794 Phase::Parsing => "RUNEC1002",
795 Phase::SymbolRegistration => "RUNEC2001",
796 Phase::TypeChecking => "RUNEC2002",
797 Phase::CodeGeneration => "RUNEC3001",
798 Phase::PointerCheck => "RUNEC4001",
799 }
800 }
801}