Parsing refactor pt4

master
Araozu 2024-03-15 16:59:28 -05:00
parent ec09dbfc0d
commit 61051ed11b
4 changed files with 10 additions and 30 deletions

View File

@ -13,7 +13,6 @@ mod lexic;
mod semantic;
// Transforms an AST to JS
mod codegen;
mod utils;
mod error_handling;

View File

@ -3,7 +3,6 @@ use super::utils::{parse_token_type, try_operator};
use super::{expression, ParseResult, ParsingError};
use crate::error_handling::SyntaxError;
use crate::lexic::token::{Token, TokenType};
use crate::utils::Result3;
pub fn try_parse<'a>(tokens: &'a Vec<Token>, pos: usize) -> ParseResult<Binding> {
let mut current_pos = pos;
@ -64,8 +63,8 @@ pub fn try_parse<'a>(tokens: &'a Vec<Token>, pos: usize) -> ParseResult<Binding>
* Equal (=) operator
*/
let equal_operator = match try_operator(tokens, current_pos, String::from("=")) {
Result3::Ok(t) => t,
Result3::Err(t) => {
Ok((t, _)) => t,
Err(ParsingError::Mismatch(t)) => {
// The parser found a token, but it's not the `=` operator
return ParseResult::Err(SyntaxError {
reason: format!("There should be an equal sign `=` after the identifier"),
@ -73,7 +72,7 @@ pub fn try_parse<'a>(tokens: &'a Vec<Token>, pos: usize) -> ParseResult<Binding>
error_end: t.get_end_position(),
});
}
Result3::None => {
_ => {
// The parser didn't find the `=` operator after the identifier
return ParseResult::Err(SyntaxError {
reason: format!("There should be an equal sign `=` after the identifier",),
@ -141,7 +140,7 @@ mod tests {
#[test]
fn should_parse_operator() {
let tokens = get_tokens(&String::from("=")).unwrap();
let token = *try_operator(&tokens, 0, String::from("=")).unwrap();
let (token, _) = try_operator(&tokens, 0, String::from("=")).unwrap();
assert_eq!("=", token.value);
}

View File

@ -1,7 +1,4 @@
use crate::{
lexic::token::{Token, TokenType},
utils::Result3,
};
use crate::lexic::token::{Token, TokenType};
use super::{ParsingError, ParsingResult};
@ -34,14 +31,14 @@ impl Tokenizer for Vec<Token> {
}
/// Expects the token at `pos` to be an operator of value `operator`. Doesn't ignore whitespace or newlines
pub fn try_operator(tokens: &Vec<Token>, pos: usize, operator: String) -> Result3<&Token> {
pub fn try_operator(tokens: &Vec<Token>, pos: usize, operator: String) -> ParsingResult<&Token> {
match tokens.get(pos) {
Some(t) if t.token_type == TokenType::Operator && t.value == operator => Result3::Ok(t),
Some(t) if t.token_type == TokenType::Operator && t.value == operator => Ok((t, pos + 1)),
Some(t) if t.token_type == TokenType::NewLine || t.token_type == TokenType::EOF => {
Result3::None
Err(ParsingError::Unmatched)
}
Some(t) => Result3::Err(t),
None => Result3::None,
Some(t) => Err(ParsingError::Mismatch(t)),
None => Err(ParsingError::Unmatched),
}
}

View File

@ -1,15 +0,0 @@
pub enum Result3<T> {
Ok(T),
Err(T),
None,
}
#[allow(dead_code)]
impl<T> Result3<T> {
pub fn unwrap(&self) -> &T {
match self {
Result3::Ok(t) => t,
_ => panic!(""),
}
}
}