Skip to main content

brooks_lib/mel/compiler/
error.rs

1// brooks, Copyright 2026, Will Hawkins
2//
3// This file is part of brooks.
4
5// This file is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// This program is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with this program. If not, see <https://www.gnu.org/licenses/>.
17
18use std::fmt::Display;
19
20use crate::common::TextLocation;
21
22#[derive(Debug, Clone)]
23pub enum CompilerError {
24    NoSuchVisitor(String),
25    EmptyContext,
26    BadGrammarElement,
27    BadLiteral(String),
28    InvalidRange,
29    UnexpectedExprType(String, String),
30    SyntaxError(String),
31}
32
33#[derive(Debug, Clone)]
34pub struct CompilerLocatableError {
35    pub error: CompilerError,
36    pub location: TextLocation,
37}
38
39impl Display for CompilerError {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        match self {
42            CompilerError::NoSuchVisitor(e) => write!(f, "No such visitor: {e}"),
43            CompilerError::EmptyContext => write!(f, "Empty context"),
44            CompilerError::BadGrammarElement => write!(f, "Bad grammar element"),
45            CompilerError::BadLiteral(e) => write!(f, "Bad literal: {e}"),
46            CompilerError::InvalidRange => write!(f, "Invalid range"),
47            CompilerError::UnexpectedExprType(expected, actual) => write!(
48                f,
49                "Unexpected expression type: expected {expected} but got {actual}"
50            ),
51            CompilerError::SyntaxError(e) => write!(f, "Syntax error: {e}"),
52        }
53    }
54}
55
56impl Display for CompilerLocatableError {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        write!(f, "{} ({})", self.error, self.location)
59    }
60}
61
62pub type CompileResult<T> = Result<T, CompilerLocatableError>;