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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/*!
Provides the crate's Error and Result types as well as helper functions.
 */

use std::fmt::{Debug, Display};
use tracing::error;

use crate::model::Span;

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

///
/// The Error type for this crate.
///
#[derive(Debug)]
pub enum Error {
    /// An error was signaled by the standard library I/O functions.
    IoError {
        source: std::io::Error,
    },
    /// An error was signaled by the standard string conversion functions.
    Utf8Error {
        source: core::str::Utf8Error,
    },
    /// An error was signaled by the standard string conversion functions.
    FromUtf8Error {
        source: std::string::FromUtf8Error,
    },
    TracingFilterError {
        source: tracing_subscriber::filter::ParseError,
    },
    TracingSubscriberError {
        source: tracing::subscriber::SetGlobalDefaultError,
    },
    CodespanReportingError {
        source: codespan_reporting::files::Error,
    },
    InvalidIdentifierError {
        input: String,
    },
    InvalidLanguageTagError {
        input: String,
    },
    InvalidNodeKind {
        rule: String,
        got: String,
    },
    UnexpectedNodeKind {
        rule: String,
        expected: String,
        got: String,
        span: Span,
    },
    MissingNodeKind {
        rule: String,
        expected: String,
    },
    MissingNodeVariable {
        rule: String,
        expected_name: String,
        expected_kind: String,
    },
    InvalidValueForType {
        value: String,
        type_name: String,
    },
    ModuleFileNotFound {
        name: String,
    },
    ModuleParseError {
        rule: Option<String>,
        node_name: String,
        span: Span,
    },
}

///
/// A Result type that specifically uses this crate's Error.
///
pub type Result<T> = std::result::Result<T, Error>;

// ------------------------------------------------------------------------------------------------
// Public Functions
// ------------------------------------------------------------------------------------------------

macro_rules! report_and_return {
    ($err: expr) => {
        let err = $err;
        error!("{}", err);
        return err;
    };
}

/// Construct an Error from the provided source.
#[inline]
pub fn io_error(source: std::io::Error) -> Error {
    report_and_return!(Error::IoError { source });
}

/// Construct an Error from the provided source.
#[inline]
pub fn utf8_error(source: core::str::Utf8Error) -> Error {
    report_and_return!(Error::Utf8Error { source });
}

/// Construct an Error from the provided source.
#[inline]
pub fn from_utf8_error(source: std::string::FromUtf8Error) -> Error {
    report_and_return!(Error::FromUtf8Error { source });
}

/// Construct an Error from the provided source.
#[inline]
pub fn tracing_filter_error(source: tracing_subscriber::filter::ParseError) -> Error {
    report_and_return!(Error::TracingFilterError { source });
}

/// Construct an Error from the provided source.
#[inline]
pub fn tracing_subscriber_error(source: tracing::subscriber::SetGlobalDefaultError) -> Error {
    report_and_return!(Error::TracingSubscriberError { source });
}

/// Construct an Error from the provided source.
#[inline]
pub fn codespan_reporting_error(source: codespan_reporting::files::Error) -> Error {
    report_and_return!(Error::CodespanReportingError { source });
}

/// Construct an invalid value Error from the provided input.
#[inline]
pub fn invalid_identifier_error<S>(input: S) -> Error
where
    S: Into<String>,
{
    report_and_return!(Error::InvalidIdentifierError {
        input: input.into()
    });
}

/// Construct an invalid value Error from the provided input.
#[inline]
pub fn invalid_language_tag_error<S>(input: S) -> Error
where
    S: Into<String>,
{
    report_and_return!(Error::InvalidLanguageTagError {
        input: input.into()
    });
}

/// Construct an invalid value Error from the provided input.
#[inline]
pub fn invalid_node_kind<S1, S2>(rule: S1, got: S2) -> Error
where
    S1: Into<String>,
    S2: Into<String>,
{
    report_and_return!(Error::InvalidNodeKind {
        rule: rule.into(),
        got: got.into()
    });
}

/// Construct an invalid value Error from the provided input.
#[inline]
pub fn unexpected_node_kind<S1, S2, S3>(rule: S1, expected: S2, got: S3, span: Span) -> Error
where
    S1: Into<String>,
    S2: Into<String>,
    S3: Into<String>,
{
    report_and_return!(Error::UnexpectedNodeKind {
        rule: rule.into(),
        expected: expected.into(),
        got: got.into(),
        span,
    });
}

/// Construct an invalid value Error from the provided input.
#[inline]
pub fn missing_node_kind<S1, S2>(rule: S1, expected: S2) -> Error
where
    S1: Into<String>,
    S2: Into<String>,
{
    report_and_return!(Error::MissingNodeKind {
        rule: rule.into(),
        expected: expected.into()
    });
}

/// Construct an invalid value Error from the provided input.
#[inline]
pub fn missing_node_variable<S1, S2, S3>(rule: S1, expected_name: S2, expected_kind: S3) -> Error
where
    S1: Into<String>,
    S2: Into<String>,
    S3: Into<String>,
{
    report_and_return!(Error::MissingNodeVariable {
        rule: rule.into(),
        expected_name: expected_name.into(),
        expected_kind: expected_kind.into(),
    });
}

/// Construct an invalid value Error from the provided input.
#[inline]
pub fn invalid_value_for_type<S1, S2>(value: S1, type_name: S2) -> Error
where
    S1: Into<String>,
    S2: Into<String>,
{
    report_and_return!(Error::InvalidValueForType {
        value: value.into(),
        type_name: type_name.into()
    });
}

/// Construct an invalid value Error from the provided input.
#[inline]
pub fn module_file_not_found<S>(name: S) -> Error
where
    S: Into<String>,
{
    report_and_return!(Error::ModuleFileNotFound { name: name.into() });
}

/// Construct an invalid value Error from the provided input.
#[inline]
pub fn module_parse_error<S1, S2>(node_name: S1, span: Span, rule: Option<S2>) -> Error
where
    S1: Into<String>,
    S2: Into<String>,
{
    report_and_return!(Error::ModuleParseError {
        rule: rule.map(|s| s.into()),
        node_name: node_name.into(),
        span,
    });
}

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

impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::IoError { source } => format!("An I/O error occurred; source: {source}"),
                Self::Utf8Error { source } =>
                    format!("A UTF-8 conversion error occurred; source: {source}"),
                Self::FromUtf8Error { source } =>
                    format!("A UTF-8 conversion error occurred; source: {source}"),
                Self::TracingFilterError { source } => format!(
                    "A error occurred parsing a tracing filter; source: {source}"),
                Self::TracingSubscriberError { source } => format!(
                    "A error occurred setting the tracing subscriber; source: {source}"),
                Self::CodespanReportingError { source } => format!(
                    "An error occurred formatting codespan reports; source: {source}"),
                Self::InvalidIdentifierError { input } => format!(
                    "Provided input is not a valid identifier; input: {input:?}"),
                Self::InvalidLanguageTagError { input } => format!(
                    "Provided input is not a valid language tag; input: {input:?}"),
                Self::InvalidNodeKind { rule, got } =>
                    format!("Unexpected node kind; got: {got}, in rule: {rule}"),
                Self::UnexpectedNodeKind {
                    rule,
                    expected,
                    got,
                    span,
                } => format!(
                    "Invalid node kind; expecting: {expected}, got: {got}, in rule: {rule}, span: {span}"),
                Self::InvalidValueForType { value, type_name } => format!(
                    "Invalid value for type; value: {value}, type: {type_name}"),
                Self::MissingNodeKind { rule, expected } => format!(
                    "Missing node kind; expecting: {expected}, in rule: {rule}"),
                Self::MissingNodeVariable { rule, expected_name, expected_kind } => format!(
                    "Missing node variable; expecting variable: {expected_name}, kind {expected_kind}, in rule: {rule}"),
                Self::ModuleFileNotFound { name } =>
                    format!("Could not resolve module name to a file; name: {name}"),
                Self::ModuleParseError {
                    rule,
                    node_name,
                    span,
                } => format!(
                    "Error reported parsing module; node name: {node_name} span: {span}{}",
                    if let Some(rule) = rule {
                        format!(", in rule: {}", rule)
                    } else {
                        String::new()
                    }
                ),
            }
        )
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        #[allow(unreachable_patterns)]
        match self {
            Error::IoError { source } => Some(source),
            _ => None,
        }
    }
}

impl<T> From<Error> for Result<T> {
    fn from(value: Error) -> Self {
        Err(value)
    }
}

impl From<std::io::Error> for Error {
    fn from(source: std::io::Error) -> Self {
        io_error(source)
    }
}

impl From<core::str::Utf8Error> for Error {
    fn from(source: core::str::Utf8Error) -> Self {
        utf8_error(source)
    }
}

impl From<std::string::FromUtf8Error> for Error {
    fn from(source: std::string::FromUtf8Error) -> Self {
        from_utf8_error(source)
    }
}

impl From<tracing_subscriber::filter::ParseError> for Error {
    fn from(source: tracing_subscriber::filter::ParseError) -> Self {
        tracing_filter_error(source)
    }
}

impl From<tracing::subscriber::SetGlobalDefaultError> for Error {
    fn from(source: tracing::subscriber::SetGlobalDefaultError) -> Self {
        tracing_subscriber_error(source)
    }
}

impl From<codespan_reporting::files::Error> for Error {
    fn from(source: codespan_reporting::files::Error) -> Self {
        codespan_reporting_error(source)
    }
}