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)]
pub struct AstError<'a, T> {
span: pest::Span<'a>,
error_code: ErrorCode,
error_message: String,
recovered: Option<T>,
pub span: pest::Span<'a>,
pub error_code: ErrorCode,
pub error_message: String,
pub recovered: Option<T>,
}
#[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>(
pairs: impl Iterator<Item = pest::iterators::Pair<'a, Rule>>,
) -> AstResult<'a, Vec<T>, Vec<T>>
where
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 last_error: Option<AstError<'a, ET>> = None;
for pair in pairs {
match T::try_from(pair) {
match f(pair) {
Ok(item) => items.push(item),
Err(e) => {
last_error = Some(e);
+21 -25
View File
@@ -1,7 +1,7 @@
use crate::{
Rule,
ast::*,
error::{AstError, AstResult},
error::{AstError, AstResult, GetParseError, collect_recovered, collect_recovered_map},
};
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 {
Rule::expr => {
let prefixes: Vec<Prefix> = inner
let prefixes = inner
.next()
.map(|p| {
p.into_inner()
@@ -21,7 +21,8 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Expression {
.map(Prefix::try_from)
.collect::<AstResult<'a, Vec<_>, _>>()
})
.transpose()?
.transpose()
.get()?
.unwrap_or_default();
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 {
initial: Box::new(exp),
prefixes,
postfixes: inner
.map(|p| Postfix::try_from(p))
.collect::<AstResult<'a, Vec<_>>>()?,
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<pest::iterators::Pair<'a, Rule>> 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::<AstResult<
'a,
Vec<_>,
_,
>>()?),
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::<AstResult<'a, Vec<_>>>()?,
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<pest::iterators::Pair<'a, Rule>> 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()),
+12 -28
View File
@@ -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<pest::iterators::Pair<'a, Rule>> for Path {
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
match pair.as_rule() {
Rule::static_path => Ok(Path(
pair.into_inner()
.map(Identifier::try_from)
.collect::<AstResult<'a, Vec<_>>>()?,
)),
Rule::static_path => Ok(Path(collect_recovered(pair.into_inner()).get()?)),
_ => 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::boolean => Literal::Bool(pair.as_str().parse::<bool>().unwrap()),
Rule::string_lit => Literal::String(inner.as_str().to_string()),
Rule::tuple => Literal::Tuple(
inner
.map(Expression::try_from)
.collect::<AstResult<'a, Vec<_>>>()?,
),
Rule::tuple => Literal::Tuple(collect_recovered(inner).get()?),
_ => unimplemented!("{rule:#?}"),
})
}
@@ -65,31 +57,23 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Pattern {
let mut inner = pair.clone().into_inner();
Ok(match rule {
Rule::tuple_pattern => Pattern::Tuple(
inner
.map(Identifier::try_from)
.collect::<AstResult<'a, Vec<_>>>()?,
),
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::<AstResult<'a, Vec<_>>>()?,
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::<AstResult<'a, Vec<_>>>()?,
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<Visibility, AstError<'a, Self>> {
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)
}
+30 -40
View File
@@ -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<pest::iterators::Pair<'a, Rule>> for Block {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
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::<AstResult<'a, Vec<_>>>()?;
Ok(Block(statements))
Ok(Block(
collect_recovered(pair.into_inner().next().unwrap().into_inner()).get()?,
))
}
}
@@ -34,14 +25,16 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> 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<pest::iterators::Pair<'a, Rule>> 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::<AstResult<'a, Vec<_>>>()?,
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<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 {
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::<AstResult<'a, Vec<_>>>()?,
.collect::<AstResult<'a, Vec<_>>>()
.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<pest::iterators::Pair<'a, Rule>> for StatementBranch {
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
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,