valkyrie_errors/duplicates/
mod.rs1use std::fmt::{Debug, Display, Formatter};
2
3use ariadne::{Color, Report, ReportKind};
4
5use crate::{errors::ValkyrieReport, FileSpan, ValkyrieError, ValkyrieErrorKind};
6
7mod kind;
8
9#[derive(Copy, Clone)]
10pub enum DuplicateKind {
11 Type = 1002,
12 Function = 1003,
13 Variable = 1004,
14}
15
16#[derive(Clone, Debug)]
17pub struct DuplicateError {
18 kind: DuplicateKind,
19 name: String,
20 this_item: FileSpan,
21 last_item: FileSpan,
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) -> ValkyrieReport {
32 let mut report = Report::build(level, self.this_item.file, 0).with_code(self.kind as u32);
33 report.set_message(self.to_string());
34 report.add_label(
35 self.this_item.as_label(format!("{:?} `{}` is defined here.", self.kind, self.name)).with_color(Color::Blue),
36 );
37 report.add_label(
38 self.last_item
39 .as_label(format!("But {} `{}` has been defined here.", self.kind, self.name))
40 .with_color(Color::Cyan),
41 );
42 report.set_help(format!("Items must have unique names, rename one of the items to have a unique name"));
43 report.finish()
44 }
45}
46
47impl ValkyrieError {
48 pub fn duplicate_type(name: String, this: FileSpan, last: FileSpan) -> Self {
49 let this = DuplicateError { kind: DuplicateKind::Type, name, this_item: this, last_item: last };
50 Self { kind: ValkyrieErrorKind::Duplicate(Box::new(this)), level: ReportKind::Error }
51 }
52 pub fn duplicate_function(name: String, this: FileSpan, last: FileSpan) -> Self {
53 let this = DuplicateError { kind: DuplicateKind::Function, name, this_item: this, last_item: last };
54 Self { kind: ValkyrieErrorKind::Duplicate(Box::new(this)), level: ReportKind::Error }
55 }
56 pub fn duplicate_variable(name: String, this: FileSpan, last: FileSpan) -> Self {
57 let this = DuplicateError { kind: DuplicateKind::Variable, name, this_item: this, last_item: last };
58 Self { kind: ValkyrieErrorKind::Duplicate(Box::new(this)), level: ReportKind::Error }
59 }
60}