crftng-intrprtrs/src/ast/parser.rs

59 lines
1.5 KiB
Rust
Raw Normal View History

use super::expression::expression_node;
2022-04-23 16:27:11 +02:00
use super::statement::statement_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>;
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>>> {
pub(super) token_iter: iter::Peekable<T>,
2022-03-24 16:33:10 +01:00
}
2022-04-23 16:27:11 +02:00
pub type ParseAllResult = StdResult<Vec<statement_node::Statement>, Vec<ASTParsingError>>;
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 16:27:11 +02:00
pub fn parse_all(&mut self) -> ParseAllResult {
let mut res = Ok(Vec::new());
while !matches!(self.token_iter.peek().unwrap().token_type, token::TokenType::Eof) {
match self.statement() {
Ok(s) => {
if let Ok(ref mut v) = res {
v.push(s)
2022-03-24 16:33:10 +01:00
}
}
2022-04-23 16:27:11 +02:00
Err(e) => match res {
Ok(_) => res = Err(vec![e]),
Err(ref mut v) => v.push(e),
},
2022-03-24 16:33:10 +01:00
}
}
2022-04-23 16:27:11 +02:00
res
2022-03-24 16:33:10 +01:00
}
}