adjust error handling in item at

This commit is contained in:
Josh Thomas 2024-10-16 09:35:42 -05:00
parent 0757f1aead
commit 690e05b100
2 changed files with 19 additions and 18 deletions

View file

@ -6,11 +6,12 @@ pub enum LexerError {
EmptyToken { line: usize },
#[error("Unexpected character '{character}' at line {line}")]
UnexpectedCharacter { character: char, line: usize },
#[error("At beginning of input")]
AtBeginningOfInput,
#[error("At end of input")]
AtEndOfInput,
#[error("Source is empty")]
EmptySource,
#[error("At beginning of source")]
AtBeginningOfSource,
#[error("At end of source")]
AtEndOfSource,
#[error("Invalid character access")]
InvalidCharacterAccess,
}

View file

@ -244,19 +244,19 @@ impl<'a> Scanner for Lexer<'a> {
}
fn item_at(&self, index: usize) -> Result<Self::Item, Self::Error> {
match self.source.chars().nth(index) {
Some(ch) => Ok(ch),
None => {
let error = if self.source.is_empty() || index == 0 {
LexerError::AtBeginningOfInput
} else if index >= self.source.len() {
LexerError::AtEndOfInput
} else {
LexerError::InvalidCharacterAccess
};
Err(error)
}
if let Some(ch) = self.source.chars().nth(index) {
Ok(ch)
} else {
let error = if self.source.is_empty() {
LexerError::EmptySource
} else if index < self.state.current {
LexerError::AtBeginningOfSource
} else if index >= self.source.len() {
LexerError::AtEndOfSource
} else {
LexerError::InvalidCharacterAccess
};
Err(error)
}
}