Common error handling

This commit is contained in:
2026-05-15 08:44:01 +02:00
parent 459c4b1ee0
commit 527e450f9e
4 changed files with 87 additions and 98 deletions
+24 -5
View File
@@ -10,10 +10,10 @@ pub enum ParseError<'a, T> {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct AstError<'a, T> { pub struct AstError<'a, T> {
span: pest::Span<'a>, pub span: pest::Span<'a>,
error_code: ErrorCode, pub error_code: ErrorCode,
error_message: String, pub error_message: String,
recovered: Option<T>, pub recovered: Option<T>,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@@ -66,17 +66,36 @@ impl<'a, F> GetParseError<'a, Option<F>> for Result<Option<F>, AstError<'a, F>>
} }
} }
impl<'a, F> GetParseError<'a, Option<Vec<F>>> for Result<Option<Vec<F>>, AstError<'a, F>> {
fn get<T>(self) -> AstResult<'a, Option<Vec<F>>, T> {
match self {
Ok(v) => Ok(v),
Err(e) => Err(e.get()),
}
}
}
pub fn collect_recovered<'a, T, ET>( pub fn collect_recovered<'a, T, ET>(
pairs: impl Iterator<Item = pest::iterators::Pair<'a, Rule>>, pairs: impl Iterator<Item = pest::iterators::Pair<'a, Rule>>,
) -> AstResult<'a, Vec<T>, Vec<T>> ) -> AstResult<'a, Vec<T>, Vec<T>>
where where
T: TryFrom<pest::iterators::Pair<'a, Rule>, Error = AstError<'a, ET>>, T: TryFrom<pest::iterators::Pair<'a, Rule>, Error = AstError<'a, ET>>,
{
collect_recovered_map(pairs, T::try_from)
}
pub fn collect_recovered_map<'a, T, F, ET>(
pairs: impl Iterator<Item = pest::iterators::Pair<'a, Rule>>,
f: F,
) -> AstResult<'a, Vec<T>, Vec<T>>
where
F: Fn(pest::iterators::Pair<'a, Rule>) -> AstResult<'a, T, ET>,
{ {
let mut items = Vec::new(); let mut items = Vec::new();
let mut last_error: Option<AstError<'a, ET>> = None; let mut last_error: Option<AstError<'a, ET>> = None;
for pair in pairs { for pair in pairs {
match T::try_from(pair) { match f(pair) {
Ok(item) => items.push(item), Ok(item) => items.push(item),
Err(e) => { Err(e) => {
last_error = Some(e); last_error = Some(e);
+16 -20
View File
@@ -1,7 +1,7 @@
use crate::{ use crate::{
Rule, Rule,
ast::*, ast::*,
error::{AstError, AstResult}, error::{AstError, AstResult, GetParseError, collect_recovered, collect_recovered_map},
}; };
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Expression { impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Expression {
@@ -13,7 +13,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Expression {
match rule { match rule {
Rule::expr => { Rule::expr => {
let prefixes: Vec<Prefix> = inner let prefixes = inner
.next() .next()
.map(|p| { .map(|p| {
p.into_inner() p.into_inner()
@@ -21,7 +21,8 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Expression {
.map(Prefix::try_from) .map(Prefix::try_from)
.collect::<AstResult<'a, Vec<_>, _>>() .collect::<AstResult<'a, Vec<_>, _>>()
}) })
.transpose()? .transpose()
.get()?
.unwrap_or_default(); .unwrap_or_default();
let exp = Expression::try_from(inner.next().unwrap())?; let exp = Expression::try_from(inner.next().unwrap())?;
@@ -30,17 +31,15 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Expression {
Ok(Expression::Fix { Ok(Expression::Fix {
initial: Box::new(exp), initial: Box::new(exp),
prefixes, prefixes,
postfixes: inner postfixes: collect_recovered(inner).get()?,
.map(|p| Postfix::try_from(p))
.collect::<AstResult<'a, Vec<_>>>()?,
}) })
} else { } else {
Ok(exp) Ok(exp)
} }
} }
Rule::primary => Expression::try_from(inner.next().unwrap()), Rule::primary => Expression::try_from(inner.next().unwrap()),
Rule::static_path => Ok(Expression::Path(Path::try_from(pair)?)), Rule::static_path => Ok(Expression::Path(Path::try_from(pair).get()?)),
Rule::literal => Ok(Expression::Literal(Literal::try_from(pair)?)), Rule::literal => Ok(Expression::Literal(Literal::try_from(pair).get()?)),
_ => unimplemented!("{rule:#?}"), _ => unimplemented!("{rule:#?}"),
} }
} }
@@ -72,27 +71,24 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Postfix {
Ok(match rule { Ok(match rule {
Rule::postfix => Postfix::try_from(inner.next().unwrap())?, 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::<AstResult< Rule::call_px => Postfix::Call(collect_recovered(inner).get()?),
'a,
Vec<_>,
_,
>>()?),
Rule::struct_px => Postfix::StructCall( Rule::struct_px => Postfix::StructCall(
inner collect_recovered_map(inner, |p| {
.map(|p| {
let mut pi = p.into_inner(); let mut pi = p.into_inner();
Ok(( Ok((
Identifier::try_from(pi.next().unwrap())?, Identifier::try_from(pi.next().unwrap())?,
Expression::try_from(pi.next().unwrap())?, Expression::try_from(pi.next().unwrap()).get()?,
)) ))
}) })
.collect::<AstResult<'a, Vec<_>>>()?, .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 => { Rule::binary_px => {
let op_pair = inner.next().unwrap(); let op_pair = inner.next().unwrap();
@@ -115,7 +111,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Postfix {
unimplemented!("Binary operator not implemented yet: {}", op_pair.as_str()) 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()), Rule::macro_call_px => Postfix::MacroCall(inner.as_str().to_string()),
+12 -28
View File
@@ -6,7 +6,7 @@ pub mod types;
use crate::{ use crate::{
Rule, Rule,
ast::*, ast::*,
error::{AstError, AstResult}, error::{AstError, GetParseError, collect_recovered},
parser::consume_rule, parser::consume_rule,
}; };
@@ -23,11 +23,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Path {
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> { fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
match pair.as_rule() { match pair.as_rule() {
Rule::static_path => Ok(Path( Rule::static_path => Ok(Path(collect_recovered(pair.into_inner()).get()?)),
pair.into_inner()
.map(Identifier::try_from)
.collect::<AstResult<'a, Vec<_>>>()?,
)),
_ => unimplemented!("{pair:#?}"), _ => unimplemented!("{pair:#?}"),
} }
} }
@@ -47,11 +43,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Literal {
Rule::float => Literal::Float(pair.as_str().parse::<f64>().unwrap()), Rule::float => Literal::Float(pair.as_str().parse::<f64>().unwrap()),
Rule::boolean => Literal::Bool(pair.as_str().parse::<bool>().unwrap()), Rule::boolean => Literal::Bool(pair.as_str().parse::<bool>().unwrap()),
Rule::string_lit => Literal::String(inner.as_str().to_string()), Rule::string_lit => Literal::String(inner.as_str().to_string()),
Rule::tuple => Literal::Tuple( Rule::tuple => Literal::Tuple(collect_recovered(inner).get()?),
inner
.map(Expression::try_from)
.collect::<AstResult<'a, Vec<_>>>()?,
),
_ => unimplemented!("{rule:#?}"), _ => unimplemented!("{rule:#?}"),
}) })
} }
@@ -65,31 +57,23 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Pattern {
let mut inner = pair.clone().into_inner(); let mut inner = pair.clone().into_inner();
Ok(match rule { Ok(match rule {
Rule::tuple_pattern => Pattern::Tuple( Rule::tuple_pattern => Pattern::Tuple(collect_recovered(pair.into_inner()).get()?),
inner
.map(Identifier::try_from)
.collect::<AstResult<'a, Vec<_>>>()?,
),
Rule::named_tuple_pattern => Pattern::NamedTuple( Rule::named_tuple_pattern => Pattern::NamedTuple(
Path::try_from(inner.next().unwrap())?, Path::try_from(inner.next().unwrap()).get()?,
inner collect_recovered(pair.into_inner()).get()?,
.map(Identifier::try_from)
.collect::<AstResult<'a, Vec<_>>>()?,
), ),
Rule::struct_pattern => Pattern::Struct( Rule::struct_pattern => Pattern::Struct(
Path::try_from(inner.next().unwrap())?, Path::try_from(inner.next().unwrap()).get()?,
inner collect_recovered(pair.into_inner()).get()?,
.map(Identifier::try_from)
.collect::<AstResult<'a, Vec<_>>>()?,
), ),
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:?}"), _ => unimplemented!("{rule:?}"),
}) })
@@ -103,7 +87,7 @@ impl<'a> TryFrom<&mut pest::iterators::Pairs<'a, Rule>> for Visibility {
Ok(consume_rule(pairs, Rule::visibility) Ok(consume_rule(pairs, Rule::visibility)
.map(|pair| -> Result<Visibility, AstError<'a, Self>> { .map(|pair| -> Result<Visibility, AstError<'a, Self>> {
if let Some(path) = pair.into_inner().next() { if let Some(path) = pair.into_inner().next() {
Ok(Visibility::PublicTarget(Path::try_from(path)?)) Ok(Visibility::PublicTarget(Path::try_from(path).get()?))
} else { } else {
Ok(Visibility::Public) Ok(Visibility::Public)
} }
+30 -40
View File
@@ -1,7 +1,7 @@
use crate::{ use crate::{
Rule, Rule,
ast::*, ast::*,
error::{ErrorCode, AstError, AstResult}, error::{AstError, AstResult, ErrorCode, GetParseError, collect_recovered},
parser::listen_rule, parser::listen_rule,
}; };
@@ -9,18 +9,9 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Block {
type Error = AstError<'a, Self>; type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> { fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let statements = pair Ok(Block(
.into_inner() collect_recovered(pair.into_inner().next().unwrap().into_inner()).get()?,
.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::<AstResult<'a, Vec<_>>>()?;
Ok(Block(statements))
} }
} }
@@ -34,14 +25,16 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Statement {
Ok(match rule { Ok(match rule {
Rule::statement => Statement::try_from(inner.next().unwrap())?, 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 => { 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, Rule::break_stmt => Statement::Break,
@@ -52,13 +45,8 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Statement {
let mut inner = inner.skip(2); let mut inner = inner.skip(2);
Statement::If { Statement::If {
initial: StatementBranch::try_from(pair)?, initial: StatementBranch::try_from(pair).get()?,
else_if: inner else_if: collect_recovered(inner.next().unwrap().into_inner()).get()?,
.next()
.unwrap()
.into_inner()
.map(StatementBranch::try_from)
.collect::<AstResult<'a, Vec<_>>>()?,
else_branch: inner else_branch: inner
.next() .next()
.map(Statement::try_from) .map(Statement::try_from)
@@ -67,45 +55,47 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> 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 { Rule::c_for_stmt => Statement::CStyleFor {
init: Box::new(Statement::try_from(inner.next().unwrap())?), init: Box::new(inner.next().unwrap().try_into().get()?),
condition: inner.next().unwrap().try_into()?, condition: inner.next().unwrap().try_into().get()?,
update: Box::new(Statement::try_from(inner.next().unwrap())?), update: Box::new(inner.next().unwrap().try_into().get()?),
body: Box::new(Statement::try_from(inner.next().unwrap())?), body: Box::new(inner.next().unwrap().try_into().get()?),
}, },
Rule::for_stmt => Statement::For { Rule::for_stmt => Statement::For {
mutable: listen_rule(&mut inner, Rule::mutable), mutable: listen_rule(&mut inner, Rule::mutable),
pattern: Pattern::try_from(inner.next().unwrap())?, pattern: inner.next().unwrap().try_into().get()?,
iterator: inner.next().unwrap().try_into()?, iterator: inner.next().unwrap().try_into().get()?,
body: Box::new(Statement::try_from(inner.next().unwrap())?), body: Box::new(Statement::try_from(inner.next().unwrap())?),
}, },
Rule::assign_statement => Statement::VarAssign(VarAssignStmt { Rule::assign_statement => Statement::VarAssign(VarAssignStmt {
target: Expression::try_from(inner.next().unwrap())?, target: inner.next().unwrap().try_into().get()?,
value: Expression::try_from(inner.next().unwrap())?, value: inner.next().unwrap().try_into().get()?,
}), }),
Rule::match_stmt => Statement::Match( Rule::match_stmt => Statement::Match(
Expression::try_from(inner.next().unwrap())?, inner.next().unwrap().try_into().get()?,
inner inner
.map(|match_itms| { .map(|match_itms| {
let mut match_inner = match_itms.into_inner(); let mut match_inner = match_itms.into_inner();
Ok(( Ok((
Pattern::try_from(match_inner.next().unwrap())?, Pattern::try_from(match_inner.next().unwrap()).get()?,
Block::try_from(match_inner.next().unwrap())?, Block::try_from(match_inner.next().unwrap()).get()?,
)) ))
}) })
.collect::<AstResult<'a, Vec<_>>>()?, .collect::<AstResult<'a, Vec<_>>>()
.get()?,
), ),
Rule::unexpected_statement => { Rule::unexpected_statement => {
return Err(AstError::Ast { return Err(AstError {
span: pair.as_span(), span: pair.as_span(),
error_code: ErrorCode::InvalidStatement, error_code: ErrorCode::InvalidStatement,
error_message: "Invalid Statement".to_string(), error_message: "Invalid Statement".to_string(),
recovered: None,
}); });
} }
@@ -120,8 +110,8 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for StatementBranch {
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> { fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let mut inner = pair.into_inner(); let mut inner = pair.into_inner();
let condition = Expression::try_from(inner.next().unwrap())?; let condition = inner.next().unwrap().try_into().get()?;
let body = Statement::try_from(inner.next().unwrap())?; let body = inner.next().unwrap().try_into().get()?;
Ok(StatementBranch { Ok(StatementBranch {
condition, condition,