From 527e450f9ee6ec2ab54c7591666dc003f6596e05 Mon Sep 17 00:00:00 2001 From: Klesti Selimaj Date: Fri, 15 May 2026 08:44:01 +0200 Subject: [PATCH] Common error handling --- parser/src/error.rs | 29 +++++++++-- parser/src/parser/common/expr.rs | 46 ++++++++---------- parser/src/parser/common/mod.rs | 40 +++++---------- parser/src/parser/common/statement.rs | 70 ++++++++++++--------------- 4 files changed, 87 insertions(+), 98 deletions(-) diff --git a/parser/src/error.rs b/parser/src/error.rs index a5d50dc..a3bf8cc 100644 --- a/parser/src/error.rs +++ b/parser/src/error.rs @@ -10,10 +10,10 @@ pub enum ParseError<'a, T> { #[derive(Debug, Clone)] pub struct AstError<'a, T> { - span: pest::Span<'a>, - error_code: ErrorCode, - error_message: String, - recovered: Option, + pub span: pest::Span<'a>, + pub error_code: ErrorCode, + pub error_message: String, + pub recovered: Option, } #[derive(Debug, Clone)] @@ -66,17 +66,36 @@ impl<'a, F> GetParseError<'a, Option> for Result, AstError<'a, F>> } } +impl<'a, F> GetParseError<'a, Option>> for Result>, AstError<'a, F>> { + fn get(self) -> AstResult<'a, Option>, T> { + match self { + Ok(v) => Ok(v), + Err(e) => Err(e.get()), + } + } +} + pub fn collect_recovered<'a, T, ET>( pairs: impl Iterator>, ) -> AstResult<'a, Vec, Vec> where T: TryFrom, Error = AstError<'a, ET>>, +{ + collect_recovered_map(pairs, T::try_from) +} + +pub fn collect_recovered_map<'a, T, F, ET>( + pairs: impl Iterator>, + f: F, +) -> AstResult<'a, Vec, Vec> +where + F: Fn(pest::iterators::Pair<'a, Rule>) -> AstResult<'a, T, ET>, { let mut items = Vec::new(); let mut last_error: Option> = None; for pair in pairs { - match T::try_from(pair) { + match f(pair) { Ok(item) => items.push(item), Err(e) => { last_error = Some(e); diff --git a/parser/src/parser/common/expr.rs b/parser/src/parser/common/expr.rs index 0d25e58..ff0ccd9 100644 --- a/parser/src/parser/common/expr.rs +++ b/parser/src/parser/common/expr.rs @@ -1,7 +1,7 @@ use crate::{ Rule, ast::*, - error::{AstError, AstResult}, + error::{AstError, AstResult, GetParseError, collect_recovered, collect_recovered_map}, }; impl<'a> TryFrom> for Expression { @@ -13,7 +13,7 @@ impl<'a> TryFrom> for Expression { match rule { Rule::expr => { - let prefixes: Vec = inner + let prefixes = inner .next() .map(|p| { p.into_inner() @@ -21,7 +21,8 @@ impl<'a> TryFrom> for Expression { .map(Prefix::try_from) .collect::, _>>() }) - .transpose()? + .transpose() + .get()? .unwrap_or_default(); let exp = Expression::try_from(inner.next().unwrap())?; @@ -30,17 +31,15 @@ impl<'a> TryFrom> for Expression { Ok(Expression::Fix { initial: Box::new(exp), prefixes, - postfixes: inner - .map(|p| Postfix::try_from(p)) - .collect::>>()?, + postfixes: collect_recovered(inner).get()?, }) } else { Ok(exp) } } Rule::primary => Expression::try_from(inner.next().unwrap()), - Rule::static_path => Ok(Expression::Path(Path::try_from(pair)?)), - Rule::literal => Ok(Expression::Literal(Literal::try_from(pair)?)), + Rule::static_path => Ok(Expression::Path(Path::try_from(pair).get()?)), + Rule::literal => Ok(Expression::Literal(Literal::try_from(pair).get()?)), _ => unimplemented!("{rule:#?}"), } } @@ -72,27 +71,24 @@ impl<'a> TryFrom> for Postfix { Ok(match rule { Rule::postfix => Postfix::try_from(inner.next().unwrap())?, - Rule::field_px => Postfix::FieldAccess(Identifier::try_from(inner.next().unwrap())?), + Rule::field_px => { + Postfix::FieldAccess(Identifier::try_from(inner.next().unwrap()).get()?) + } - Rule::call_px => Postfix::Call(inner.map(Expression::try_from).collect::, - _, - >>()?), + Rule::call_px => Postfix::Call(collect_recovered(inner).get()?), Rule::struct_px => Postfix::StructCall( - inner - .map(|p| { - let mut pi = p.into_inner(); - Ok(( - Identifier::try_from(pi.next().unwrap())?, - Expression::try_from(pi.next().unwrap())?, - )) - }) - .collect::>>()?, + collect_recovered_map(inner, |p| { + let mut pi = p.into_inner(); + Ok(( + Identifier::try_from(pi.next().unwrap())?, + Expression::try_from(pi.next().unwrap()).get()?, + )) + }) + .get()?, ), - Rule::index_px => Postfix::Index(Expression::try_from(inner.next().unwrap())?), + Rule::index_px => Postfix::Index(Expression::try_from(inner.next().unwrap()).get()?), Rule::binary_px => { let op_pair = inner.next().unwrap(); @@ -115,7 +111,7 @@ impl<'a> TryFrom> for Postfix { unimplemented!("Binary operator not implemented yet: {}", op_pair.as_str()) } }; - Postfix::Binary(op, Expression::try_from(inner.next().unwrap())?) + Postfix::Binary(op, Expression::try_from(inner.next().unwrap()).get()?) } Rule::macro_call_px => Postfix::MacroCall(inner.as_str().to_string()), diff --git a/parser/src/parser/common/mod.rs b/parser/src/parser/common/mod.rs index 9f3cbb4..f7852de 100644 --- a/parser/src/parser/common/mod.rs +++ b/parser/src/parser/common/mod.rs @@ -6,7 +6,7 @@ pub mod types; use crate::{ Rule, ast::*, - error::{AstError, AstResult}, + error::{AstError, GetParseError, collect_recovered}, parser::consume_rule, }; @@ -23,11 +23,7 @@ impl<'a> TryFrom> for Path { fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result { match pair.as_rule() { - Rule::static_path => Ok(Path( - pair.into_inner() - .map(Identifier::try_from) - .collect::>>()?, - )), + Rule::static_path => Ok(Path(collect_recovered(pair.into_inner()).get()?)), _ => unimplemented!("{pair:#?}"), } } @@ -47,11 +43,7 @@ impl<'a> TryFrom> for Literal { Rule::float => Literal::Float(pair.as_str().parse::().unwrap()), Rule::boolean => Literal::Bool(pair.as_str().parse::().unwrap()), Rule::string_lit => Literal::String(inner.as_str().to_string()), - Rule::tuple => Literal::Tuple( - inner - .map(Expression::try_from) - .collect::>>()?, - ), + Rule::tuple => Literal::Tuple(collect_recovered(inner).get()?), _ => unimplemented!("{rule:#?}"), }) } @@ -65,31 +57,23 @@ impl<'a> TryFrom> for Pattern { let mut inner = pair.clone().into_inner(); Ok(match rule { - Rule::tuple_pattern => Pattern::Tuple( - inner - .map(Identifier::try_from) - .collect::>>()?, - ), + Rule::tuple_pattern => Pattern::Tuple(collect_recovered(pair.into_inner()).get()?), Rule::named_tuple_pattern => Pattern::NamedTuple( - Path::try_from(inner.next().unwrap())?, - inner - .map(Identifier::try_from) - .collect::>>()?, + Path::try_from(inner.next().unwrap()).get()?, + collect_recovered(pair.into_inner()).get()?, ), Rule::struct_pattern => Pattern::Struct( - Path::try_from(inner.next().unwrap())?, - inner - .map(Identifier::try_from) - .collect::>>()?, + Path::try_from(inner.next().unwrap()).get()?, + collect_recovered(pair.into_inner()).get()?, ), - Rule::literal => Pattern::Literal(Literal::try_from(pair)?), + Rule::literal => Pattern::Literal(Literal::try_from(pair).get()?), - Rule::identifier => Pattern::Id(Identifier::try_from(pair)?), + Rule::identifier => Pattern::Id(Identifier::try_from(pair).get()?), - Rule::static_path => Pattern::Path(Path::try_from(pair)?), + Rule::static_path => Pattern::Path(Path::try_from(pair).get()?), _ => unimplemented!("{rule:?}"), }) @@ -103,7 +87,7 @@ impl<'a> TryFrom<&mut pest::iterators::Pairs<'a, Rule>> for Visibility { Ok(consume_rule(pairs, Rule::visibility) .map(|pair| -> Result> { if let Some(path) = pair.into_inner().next() { - Ok(Visibility::PublicTarget(Path::try_from(path)?)) + Ok(Visibility::PublicTarget(Path::try_from(path).get()?)) } else { Ok(Visibility::Public) } diff --git a/parser/src/parser/common/statement.rs b/parser/src/parser/common/statement.rs index d30c5d2..c4e22e4 100644 --- a/parser/src/parser/common/statement.rs +++ b/parser/src/parser/common/statement.rs @@ -1,7 +1,7 @@ use crate::{ Rule, ast::*, - error::{ErrorCode, AstError, AstResult}, + error::{AstError, AstResult, ErrorCode, GetParseError, collect_recovered}, parser::listen_rule, }; @@ -9,18 +9,9 @@ impl<'a> TryFrom> for Block { type Error = AstError<'a, Self>; fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result { - let statements = pair - .into_inner() - .flat_map(|pair| { - if pair.as_rule() == Rule::statement_list { - pair.into_inner().map(Statement::try_from).collect() - } else { - vec![Statement::try_from(pair)] - } - }) - .collect::>>()?; - - Ok(Block(statements)) + Ok(Block( + collect_recovered(pair.into_inner().next().unwrap().into_inner()).get()?, + )) } } @@ -34,14 +25,16 @@ impl<'a> TryFrom> for Statement { Ok(match rule { Rule::statement => Statement::try_from(inner.next().unwrap())?, - Rule::expr_stmt => Statement::Expression(Expression::try_from(inner.next().unwrap())?), + Rule::expr_stmt => { + Statement::Expression(Expression::try_from(inner.next().unwrap()).get()?) + } - Rule::block => Statement::Block(Block::try_from(inner.next().unwrap())?), + Rule::block => Statement::Block(Block::try_from(inner.next().unwrap()).get()?), - Rule::var_decl_statement => Statement::VarDecl(VarDeclStmt::try_from(pair)?), + Rule::var_decl_statement => Statement::VarDecl(VarDeclStmt::try_from(pair).get()?), Rule::return_stmt => { - Statement::Return(inner.next().map(Expression::try_from).transpose()?) + Statement::Return(inner.next().map(Expression::try_from).transpose().get()?) } Rule::break_stmt => Statement::Break, @@ -52,13 +45,8 @@ impl<'a> TryFrom> for Statement { let mut inner = inner.skip(2); Statement::If { - initial: StatementBranch::try_from(pair)?, - else_if: inner - .next() - .unwrap() - .into_inner() - .map(StatementBranch::try_from) - .collect::>>()?, + initial: StatementBranch::try_from(pair).get()?, + else_if: collect_recovered(inner.next().unwrap().into_inner()).get()?, else_branch: inner .next() .map(Statement::try_from) @@ -67,45 +55,47 @@ impl<'a> TryFrom> for Statement { } } - Rule::while_stmt => Statement::While(pair.try_into()?), + Rule::while_stmt => Statement::While(pair.try_into().get()?), Rule::c_for_stmt => Statement::CStyleFor { - init: Box::new(Statement::try_from(inner.next().unwrap())?), - condition: inner.next().unwrap().try_into()?, - update: Box::new(Statement::try_from(inner.next().unwrap())?), - body: Box::new(Statement::try_from(inner.next().unwrap())?), + init: Box::new(inner.next().unwrap().try_into().get()?), + condition: inner.next().unwrap().try_into().get()?, + update: Box::new(inner.next().unwrap().try_into().get()?), + body: Box::new(inner.next().unwrap().try_into().get()?), }, Rule::for_stmt => Statement::For { mutable: listen_rule(&mut inner, Rule::mutable), - pattern: Pattern::try_from(inner.next().unwrap())?, - iterator: inner.next().unwrap().try_into()?, + pattern: inner.next().unwrap().try_into().get()?, + iterator: inner.next().unwrap().try_into().get()?, body: Box::new(Statement::try_from(inner.next().unwrap())?), }, Rule::assign_statement => Statement::VarAssign(VarAssignStmt { - target: Expression::try_from(inner.next().unwrap())?, - value: Expression::try_from(inner.next().unwrap())?, + target: inner.next().unwrap().try_into().get()?, + value: inner.next().unwrap().try_into().get()?, }), Rule::match_stmt => Statement::Match( - Expression::try_from(inner.next().unwrap())?, + inner.next().unwrap().try_into().get()?, inner .map(|match_itms| { let mut match_inner = match_itms.into_inner(); Ok(( - Pattern::try_from(match_inner.next().unwrap())?, - Block::try_from(match_inner.next().unwrap())?, + Pattern::try_from(match_inner.next().unwrap()).get()?, + Block::try_from(match_inner.next().unwrap()).get()?, )) }) - .collect::>>()?, + .collect::>>() + .get()?, ), Rule::unexpected_statement => { - return Err(AstError::Ast { + return Err(AstError { span: pair.as_span(), error_code: ErrorCode::InvalidStatement, error_message: "Invalid Statement".to_string(), + recovered: None, }); } @@ -120,8 +110,8 @@ impl<'a> TryFrom> for StatementBranch { fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result { let mut inner = pair.into_inner(); - let condition = Expression::try_from(inner.next().unwrap())?; - let body = Statement::try_from(inner.next().unwrap())?; + let condition = inner.next().unwrap().try_into().get()?; + let body = inner.next().unwrap().try_into().get()?; Ok(StatementBranch { condition,