nyar_error/duplicates/
mod.rs1use diagnostic::{Color, Label, ReportKind, SourceSpan};
2use std::fmt::{Debug, Display, Formatter};
3
4use crate::{Diagnostic, NyarError, NyarErrorKind};
5
6mod kind;
7
8#[derive(Copy, Clone, Eq, PartialEq)]
9pub enum DuplicateKind {
10 Type = 1002,
11 Function = 1003,
12 Variable = 1004,
13 Key = 1005,
14}
15
16#[derive(Clone, Debug, Eq, PartialEq)]
17pub struct DuplicateError {
18 kind: DuplicateKind,
19 name: String,
20 this_item: SourceSpan,
21 last_item: SourceSpan,
22}
23
24impl Display for DuplicateError {
25 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
26 write!(f, "Duplicate {} `{}`", self.kind, self.name)
27 }
28}
29
30impl DuplicateError {
31 pub fn as_report(&self, level: ReportKind) -> Diagnostic {
32 let mut report = Diagnostic::new(level).with_code(self.kind as usize);
33 report.set_message(self.to_string());
34 report.add_label(
35 Label::new(self.this_item)
36 .with_message(format!("{:?} `{}` is defined here.", self.kind, self.name))
37 .with_color(Color::Blue),
38 );
39 report.add_label(
40 Label::new(self.last_item)
41 .with_message(format!("{} `{}` is defined here.", self.kind, self.name))
42 .with_color(Color::Cyan),
43 );
44 report.set_help(format!("Items must have unique names, rename one of the items to have a unique name"));
45 report.finish()
46 }
47}
48
49impl DuplicateError {
50 pub fn duplicate_type(name: String, this: SourceSpan, last: SourceSpan) -> Self {
51 DuplicateError { kind: DuplicateKind::Type, name, this_item: this, last_item: last }
52 }
53}
54
55impl NyarError {
56 pub fn duplicate_type(name: String, this: SourceSpan, last: SourceSpan) -> Self {
57 let this = DuplicateError { kind: DuplicateKind::Type, name, this_item: this, last_item: last };
58 NyarErrorKind::Duplicate(this).as_error(ReportKind::Error)
59 }
60 pub fn duplicate_function(name: String, this: SourceSpan, last: SourceSpan) -> Self {
61 let this = DuplicateError { kind: DuplicateKind::Function, name, this_item: this, last_item: last };
62 NyarErrorKind::Duplicate(this).as_error(ReportKind::Error)
63 }
64 pub fn duplicate_variable(name: String, this: SourceSpan, last: SourceSpan) -> Self {
65 let this = DuplicateError { kind: DuplicateKind::Variable, name, this_item: this, last_item: last };
66 NyarErrorKind::Duplicate(this).as_error(ReportKind::Error)
67 }
68 pub fn duplicate_key(name: String, this: SourceSpan, last: SourceSpan) -> Self {
69 let this = DuplicateError { kind: DuplicateKind::Key, name, this_item: this, last_item: last };
70 NyarErrorKind::Duplicate(this).as_error(ReportKind::Error)
71 }
72}