2022-04-23 15:39:37 +02:00
|
|
|
use super::expression::expression_node;
|
2022-04-19 00:46:33 +02:00
|
|
|
use crate::error::ErrorLocationWrapper;
|
2022-03-24 16:33:10 +01:00
|
|
|
use crate::lexer::{token, token::TokenType};
|
2022-04-06 17:39:19 +02:00
|
|
|
|
2022-03-24 16:33:10 +01:00
|
|
|
use std::iter;
|
|
|
|
use std::result::Result as StdResult;
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
2022-04-19 00:46:33 +02:00
|
|
|
pub enum InnerASTParsingError {
|
2022-04-06 17:39:19 +02:00
|
|
|
IncorrectToken(TokenType),
|
2022-03-24 16:33:10 +01:00
|
|
|
UnmatchedBrace,
|
|
|
|
}
|
2022-04-02 21:23:47 +02:00
|
|
|
|
2022-04-19 00:46:33 +02:00
|
|
|
impl std::fmt::Display for InnerASTParsingError {
|
2022-04-03 21:54:26 +02:00
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
match *self {
|
|
|
|
Self::UnmatchedBrace => write!(f, "Unmatched brace"),
|
2022-04-06 17:39:19 +02:00
|
|
|
Self::IncorrectToken(ref token) => write!(f, "Incorrect token {:?}", token),
|
2022-04-03 21:54:26 +02:00
|
|
|
}
|
2022-03-24 16:33:10 +01:00
|
|
|
}
|
|
|
|
}
|
2022-04-19 00:46:33 +02:00
|
|
|
impl std::error::Error for InnerASTParsingError {}
|
|
|
|
|
|
|
|
pub type ASTParsingError = ErrorLocationWrapper<InnerASTParsingError>;
|
2022-04-23 15:39:37 +02:00
|
|
|
pub(super) type Result<T> = StdResult<T, ASTParsingError>;
|
2022-03-24 16:33:10 +01:00
|
|
|
|
2022-04-02 21:23:47 +02:00
|
|
|
pub struct Parser<'a, T: Iterator<Item = token::Token<'a>>> {
|
2022-04-23 15:39:37 +02:00
|
|
|
pub(super) token_iter: iter::Peekable<T>,
|
2022-03-24 16:33:10 +01:00
|
|
|
}
|
|
|
|
|
2022-04-02 21:23:47 +02:00
|
|
|
impl<'a, T: Iterator<Item = token::Token<'a>>> Parser<'a, T> {
|
|
|
|
pub fn new(iter: T) -> Parser<'a, T> {
|
2022-03-24 16:33:10 +01:00
|
|
|
Parser {
|
|
|
|
token_iter: iter.peekable(),
|
|
|
|
}
|
|
|
|
}
|
2022-04-23 15:39:37 +02:00
|
|
|
pub fn parse_all(
|
|
|
|
&mut self,
|
|
|
|
) -> StdResult<Vec<expression_node::ExpressionNode>, Vec<ASTParsingError>> {
|
2022-03-24 16:33:10 +01:00
|
|
|
let mut tokens = Vec::new();
|
|
|
|
let mut errors = Vec::new();
|
|
|
|
|
|
|
|
while self.token_iter.peek().is_some() {
|
|
|
|
match self.expression() {
|
|
|
|
Ok(token) => {
|
|
|
|
if errors.is_empty() {
|
|
|
|
tokens.push(token)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Err(e) => errors.push(e),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if errors.is_empty() {
|
|
|
|
Ok(tokens)
|
|
|
|
} else {
|
|
|
|
Err(errors)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|