1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
/*!
This crate provides the common resolver, loader, and parser errors.

 */

use codespan_reporting::diagnostic::{Diagnostic, Severity};
use codespan_reporting::term::termcolor::{ColorChoice, StandardStream, WriteColor};
use codespan_reporting::term::Config;
use sdml_core::error::Error as CoreError;
use sdml_core::model::identifiers::Identifier;
use std::io::Write;
use std::ops::{Add, AddAssign};
use std::{error::Error, fmt::Display};

// ------------------------------------------------------------------------------------------------
// Public Macros
// ------------------------------------------------------------------------------------------------

// ------------------------------------------------------------------------------------------------
// Public Types
// ------------------------------------------------------------------------------------------------

///
/// An opaque identifier used to index the source associated with a loaded module.
///
pub type FileId = usize;

///
/// This type captures the constant components of a particular error.
///
#[derive(Clone, Debug)]
pub struct SimpleDiagnostic {
    severity: Severity,
    code: &'static str,
    message: &'static str,
}

///
/// This type is used to track the number of emitted diagnostics.
///
#[derive(Clone, Debug, Default)]
pub struct ErrorCounters {
    bugs: u32,
    errors: u32,
    warnings: u32,
    notes: u32,
    help: u32,
}

// ------------------------------------------------------------------------------------------------
// Public Error Values
// ------------------------------------------------------------------------------------------------

///
/// A [SimpleDiagnostic] representing a loader error.
///
pub const MODULE_NOT_FOUND: SimpleDiagnostic = SimpleDiagnostic {
    severity: Severity::Bug,
    code: "B001",
    message: "module not found",
};

///
/// A [SimpleDiagnostic] representing a tree-sitter error.
///
pub const TREE_SITTER_ERROR: SimpleDiagnostic = SimpleDiagnostic {
    severity: Severity::Error,
    code: "E010",
    message: "tree-sitter parse error",
};

///
/// A [SimpleDiagnostic] representing a tree-sitter error.
///
pub const UNEXPECTED_NODE_KIND: SimpleDiagnostic = SimpleDiagnostic {
    severity: Severity::Error,
    code: "E011",
    message: "unexpected tree-sitter node",
};

///
/// A [SimpleDiagnostic] representing a tree-sitter error.
///
pub const MISSING_NODE_KIND: SimpleDiagnostic = SimpleDiagnostic {
    severity: Severity::Error,
    code: "E012",
    message: "missing tree-sitter node",
};

///
/// A [SimpleDiagnostic] representing a tree-sitter error.
///
pub const MISSING_NODE_VARIABLE: SimpleDiagnostic = SimpleDiagnostic {
    severity: Severity::Error,
    code: "E013",
    message: "missing tree-sitter variable",
};

///
/// A [SimpleDiagnostic] representing a parser error.
///
pub const MODULE_ALREADY_IMPORTED: SimpleDiagnostic = SimpleDiagnostic {
    severity: Severity::Warning,
    code: "W020",
    message: "duplicate import of module",
};

///
/// A [SimpleDiagnostic] representing a parser error.
///
pub const MEMBER_ALREADY_IMPORTED: SimpleDiagnostic = SimpleDiagnostic {
    severity: Severity::Warning,
    code: "W021",
    message: "duplicate import of member",
};

///
/// A [SimpleDiagnostic] representing a parser error.
///
pub const TYPE_DEFINITION_NAME_USED: SimpleDiagnostic = SimpleDiagnostic {
    severity: Severity::Error,
    code: "E022",
    message: "a type definition with this name already exists",
};

///
/// A [SimpleDiagnostic] representing a parser error.
///
pub const MEMBER_NAME_USED: SimpleDiagnostic = SimpleDiagnostic {
    severity: Severity::Error,
    code: "E023",
    message: "a member with this name already exists",
};

///
/// A [SimpleDiagnostic] representing a parser error.
///
pub const VALUE_VARIANT_NAME_USED: SimpleDiagnostic = SimpleDiagnostic {
    severity: Severity::Error,
    code: "E024",
    message: "a value variant with this name already exists",
};

///
/// A [SimpleDiagnostic] representing a parser error.
///
pub const TYPE_VARIANT_NAME_USED: SimpleDiagnostic = SimpleDiagnostic {
    severity: Severity::Error,
    code: "E025",
    message: "a type variant with this type or name already exists",
};

// ------------------------------------------------------------------------------------------------
// Implementations
// ------------------------------------------------------------------------------------------------

impl ErrorCounters {
    #[inline(always)]
    pub fn bugs(&self) -> u32 {
        self.bugs
    }

    #[inline(always)]
    pub fn report(&mut self, severity: Severity) {
        match severity {
            Severity::Bug => self.bugs += 1,
            Severity::Error => self.errors += 1,
            Severity::Warning => self.warnings += 1,
            Severity::Note => self.notes += 1,
            Severity::Help => self.help += 1,
        }
    }

    #[inline(always)]
    pub fn errors(&self) -> u32 {
        self.errors
    }

    #[inline(always)]
    pub fn warnings(&self) -> u32 {
        self.warnings
    }

    #[inline(always)]
    pub fn notes(&self) -> u32 {
        self.notes
    }

    #[inline(always)]
    pub fn help(&self) -> u32 {
        self.help
    }

    #[inline(always)]
    pub fn total(&self) -> u64 {
        (self.bugs + self.errors + self.warnings + self.notes + self.help) as u64
    }

    pub fn display(&self, name: &Identifier) -> Result<(), CoreError> {
        if self.total() > 0 {
            let config = Config::default();
            let stream = StandardStream::stderr(ColorChoice::Always);
            let mut writer = stream.lock();

            let (severity, count) = if self.bugs > 0 {
                (Severity::Bug, self.bugs)
            } else if self.errors > 0 {
                (Severity::Error, self.errors)
            } else if self.warnings > 0 {
                (Severity::Warning, self.warnings)
            } else if self.notes > 0 {
                (Severity::Note, self.notes)
            } else if self.help > 0 {
                (Severity::Help, self.help)
            } else {
                unreachable!();
            };

            writer.set_color(config.styles.header(severity))?;
            writer.write_all(severity_str(severity).as_bytes())?;
            writer.reset()?;
            writer.write_all(format!(": module `{name}` generated {count} bugs").as_bytes())?;
            // TODO: include other counts in short form
            writer.write_all(b".\n")?;
        }
        Ok(())
    }
}

impl Add for ErrorCounters {
    type Output = ErrorCounters;

    fn add(self, rhs: Self) -> Self::Output {
        Self {
            bugs: self.bugs + rhs.bugs,
            errors: self.errors + rhs.errors,
            warnings: self.warnings + rhs.warnings,
            notes: self.notes + rhs.notes,
            help: self.help + rhs.help,
        }
    }
}

impl AddAssign for ErrorCounters {
    fn add_assign(&mut self, rhs: Self) {
        self.bugs += rhs.bugs;
        self.errors += rhs.errors;
        self.warnings += rhs.warnings;
        self.notes += rhs.notes;
        self.help += rhs.help;
    }
}

// ------------------------------------------------------------------------------------------------

impl Display for SimpleDiagnostic {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl Error for SimpleDiagnostic {}

impl SimpleDiagnostic {
    pub fn into_diagnostic(&self) -> Diagnostic<FileId> {
        let new = match self.severity {
            Severity::Bug => Diagnostic::bug(),
            Severity::Error => Diagnostic::error(),
            Severity::Warning => Diagnostic::warning(),
            Severity::Note => Diagnostic::note(),
            Severity::Help => Diagnostic::help(),
        };
        new.with_code(self.code).with_message(self.message)
    }
}

// ------------------------------------------------------------------------------------------------
// Private Functions
// ------------------------------------------------------------------------------------------------

#[inline(always)]
fn severity_str(severity: Severity) -> &'static str {
    match severity {
        Severity::Bug => "bug",
        Severity::Error => "error",
        Severity::Warning => "warning",
        Severity::Note => "note",
        Severity::Help => "help",
    }
}