mirror of
https://github.com/joshuadavidthomas/django-template-ast.git
synced 2025-08-04 08:58:17 +00:00
create ErrorMessage trait
This commit is contained in:
parent
c0cd3ba89e
commit
0988c53008
1 changed files with 38 additions and 15 deletions
53
src/error.rs
53
src/error.rs
|
@ -1,40 +1,63 @@
|
|||
use std::fmt;
|
||||
|
||||
pub trait ErrorMessage {
|
||||
fn message(&self) -> &str;
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum LexerError {
|
||||
EmptyToken(usize),
|
||||
UnexpectedCharacter(char, usize),
|
||||
LexicalError { message: String, position: usize },
|
||||
EmptyToken {
|
||||
line: usize,
|
||||
message: String,
|
||||
},
|
||||
UnexpectedCharacter {
|
||||
character: char,
|
||||
line: usize,
|
||||
message: String,
|
||||
},
|
||||
LexicalError {
|
||||
position: usize,
|
||||
message: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl LexerError {
|
||||
pub fn empty_token<T>(line: usize) -> Result<T, Self> {
|
||||
Err(LexerError::EmptyToken(line))
|
||||
Err(LexerError::EmptyToken {
|
||||
line,
|
||||
message: format!("Empty token at line {}", line),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn unexpected_character<T>(character: char, line: usize) -> Result<T, Self> {
|
||||
Err(LexerError::UnexpectedCharacter(character, line))
|
||||
Err(LexerError::UnexpectedCharacter {
|
||||
character,
|
||||
line,
|
||||
message: format!("Unexpected character '{}' at line {}", character, line),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn lexical_error<T>(message: &str, position: usize) -> Result<T, Self> {
|
||||
Err(LexerError::LexicalError {
|
||||
message: message.to_string(),
|
||||
position,
|
||||
message: format!("Lexical error at position {}: {}", position, message),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ErrorMessage for LexerError {
|
||||
fn message(&self) -> &str {
|
||||
match self {
|
||||
LexerError::EmptyToken { message, .. }
|
||||
| LexerError::UnexpectedCharacter { message, .. }
|
||||
| LexerError::LexicalError { message, .. } => message,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for LexerError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
LexerError::EmptyToken(line) => write!(f, "Empty token at line {}", line),
|
||||
LexerError::UnexpectedCharacter(c, line) => {
|
||||
write!(f, "Unexpected character '{}' at line {}", c, line)
|
||||
}
|
||||
LexerError::LexicalError { message, position } => {
|
||||
write!(f, "Lexical error at position {}: {}", position, message)
|
||||
}
|
||||
}
|
||||
write!(f, "{}", self.message())
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue