Merge pull request #29 from mist-go/error-recovery-system

Error recovery system
This commit is contained in:
2026-05-16 07:32:15 +02:00
committed by GitHub
17 changed files with 398 additions and 302 deletions
+1 -1
View File
@@ -69,4 +69,4 @@ pub class Logger {
return write!(f, "logger ({})", self.prefix); return write!(f, "logger ({})", self.prefix);
} }
} }
} }
+6
View File
@@ -272,3 +272,9 @@ pub enum Literal {
Bool(bool), Bool(bool),
Tuple(Vec<Expression>), Tuple(Vec<Expression>),
} }
impl TypeExpr {
pub fn no_px(kind: TypeExprKind) -> Self {
Self(kind, Vec::new())
}
}
+71 -27
View File
@@ -1,3 +1,7 @@
use std::fmt::Debug;
use pest::iterators::Pair;
use crate::Rule; use crate::Rule;
pub type AstResult<'a, T, ET = T> = Result<T, AstError<'a, ET>>; pub type AstResult<'a, T, ET = T> = Result<T, AstError<'a, ET>>;
@@ -18,7 +22,8 @@ pub struct AstError<'a, T> {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum ErrorCode { pub enum ErrorCode {
InvalidStatement = 200, InvalidStatement,
AstGenBug,
} }
impl<T> From<pest::error::Error<Rule>> for ParseError<'_, T> { impl<T> From<pest::error::Error<Rule>> for ParseError<'_, T> {
@@ -42,40 +47,48 @@ impl<'a, F> AstError<'a, F> {
recovered: None, recovered: None,
} }
} }
}
pub trait GetParseError<'a, F> { pub fn bug_unimplemented<T>(pair: Pair<'a, Rule>) -> AstResult<'a, T, F> {
fn get<T>(self) -> AstResult<'a, F, T>; Err(Self {
} span: pair.as_span(),
error_code: ErrorCode::AstGenBug,
impl<'a, F> GetParseError<'a, F> for AstResult<'a, F> { error_message: format!("Possible bug, unimplemented: {:#?}", pair.as_rule()),
fn get<T>(self) -> AstResult<'a, F, T> { recovered: None,
match self { })
Ok(v) => Ok(v),
Err(e) => Err(e.get()),
}
} }
} }
impl<'a, F> GetParseError<'a, Option<F>> for Result<Option<F>, AstError<'a, F>> { pub trait IntoErr<T, FA, FR> {
fn get<T>(self) -> AstResult<'a, Option<F>, T> { fn get(self) -> T;
match self { fn get_map(self, m: impl Fn(FA) -> FR) -> T;
Ok(v) => Ok(v), }
Err(e) => Err(e.get()),
} impl<'a, T, TE, TE2> IntoErr<AstResult<'a, T, TE2>, TE, TE2> for AstResult<'a, T, TE> {
fn get(self) -> AstResult<'a, T, TE2> {
self.map_err(AstError::get)
}
fn get_map(self, m: impl Fn(TE) -> TE2) -> AstResult<'a, T, TE2> {
self.map_err(|e| AstError {
span: e.span,
error_code: e.error_code,
error_message: e.error_message,
recovered: e.recovered.map(m),
})
} }
} }
impl<'a, F> GetParseError<'a, Option<Vec<F>>> for Result<Option<Vec<F>>, AstError<'a, F>> { pub trait GetLength {
fn get<T>(self) -> AstResult<'a, Option<Vec<F>>, T> { fn len(&self) -> usize;
match self { }
Ok(v) => Ok(v),
Err(e) => Err(e.get()), impl<T, E> GetLength for Result<Vec<T>, E> {
} fn len(&self) -> usize {
if let Ok(v) = self { v.len() } else { 0 }
} }
} }
pub fn collect_recovered<'a, T, ET>( pub fn collect_recovered<'a, T: Debug, 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
@@ -84,7 +97,7 @@ where
collect_recovered_map(pairs, T::try_from) collect_recovered_map(pairs, T::try_from)
} }
pub fn collect_recovered_map<'a, T, F, ET>( pub fn collect_recovered_map<'a, T: Debug, F, ET>(
pairs: impl Iterator<Item = pest::iterators::Pair<'a, Rule>>, pairs: impl Iterator<Item = pest::iterators::Pair<'a, Rule>>,
f: F, f: F,
) -> AstResult<'a, Vec<T>, Vec<T>> ) -> AstResult<'a, Vec<T>, Vec<T>>
@@ -108,8 +121,39 @@ where
span: ast_err.span, span: ast_err.span,
error_code: ast_err.error_code, error_code: ast_err.error_code,
error_message: ast_err.error_message, error_message: ast_err.error_message,
recovered: None, recovered: Some(items),
}), }),
None => Ok(items), None => Ok(items),
} }
} }
pub struct AstErrorAnalyzer<'a, T>(pub Option<AstError<'a, T>>);
impl<'a, T> AstErrorAnalyzer<'a, T> {
pub fn get<V: Clone, V2: Clone + Into<V>>(
&mut self,
r: AstResult<'a, V, V2>,
) -> AstResult<'a, V, V2> {
if let Err(e) = r {
self.0 = Some(e.clone().get());
if let Some(recovered) = e.recovered {
Ok(recovered.into())
} else {
Err(e)
}
} else {
r
}
}
pub fn build(self, v: T) -> AstResult<'a, T> {
if let Some(mut e) = self.0 {
e.recovered = Some(v);
Err(e)
} else {
Ok(v)
}
}
}
+5 -3
View File
@@ -357,8 +357,10 @@ assign_statement = {
// CONDITIONALS // CONDITIONALS
// ------------------------------------------------------ // ------------------------------------------------------
statement_branch = { "(" ~ expr ~ ")" ~ statement }
else_if = { else_if = {
"else" ~ "if" ~ "(" ~ expr ~ ")" ~ statement "else" ~ "if" ~ statement_branch
} }
else_if_list = { else_if_list = {
@@ -366,7 +368,7 @@ else_if_list = {
} }
if_stmt = { if_stmt = {
"if" ~ "(" ~ expr ~ ")" ~ statement ~ else_if_list ~ ("else" ~ statement)? "if" ~ statement_branch ~ else_if_list ~ ("else" ~ statement)?
} }
// ------------------------------------------------------ // ------------------------------------------------------
@@ -374,7 +376,7 @@ if_stmt = {
// ------------------------------------------------------ // ------------------------------------------------------
while_stmt = { while_stmt = {
"while" ~ "(" ~ expr ~ ")" ~ statement "while" ~ statement_branch
} }
c_for_stmt = { c_for_stmt = {
+47 -3
View File
@@ -7,7 +7,7 @@ pub mod parser;
use ast::*; use ast::*;
use crate::error::{GetParseError, ParseError}; use crate::error::{IntoErr, ParseError};
#[derive(Parser)] #[derive(Parser)]
#[grammar = "./src/grammar.pest"] #[grammar = "./src/grammar.pest"]
@@ -18,11 +18,55 @@ pub fn parse<'a>(source: &'a str) -> Result<Vec<TopLevel>, ParseError<'a, Vec<To
let mut statements = vec![]; let mut statements = vec![];
let mut analyzer = error::AstErrorAnalyzer(None);
for pair in pairs.next().unwrap().into_inner() { for pair in pairs.next().unwrap().into_inner() {
if pair.as_rule() != Rule::EOI { if pair.as_rule() != Rule::EOI {
statements.push(TopLevel::try_from(pair).get()?); statements.push(analyzer.get(TopLevel::try_from(pair)).get()?);
} }
} }
Ok(statements) match analyzer.build(statements) {
Ok(v) => Ok(v),
Err(e) => Err(ParseError::Ast(e)),
}
}
#[macro_export]
macro_rules! ast_ensure {
($pair:expr, $rule:expr => $body:block) => {
if $pair.as_rule() == $rule
$body
else {
Err(AstError {
span: $pair.as_span(),
error_code: crate::error::ErrorCode::AstGenBug,
error_message: format!("Possible bug: expected {:?}, got {}", $rule, $pair),
recovered: None,
})
}
};
}
#[macro_export]
macro_rules! ast_expr {
($($item:ident)::+ { $($k:ident: $v:expr),* $(,)? }) => {{
let mut analyzer = $crate::error::AstErrorAnalyzer(None);
let v = $($item)::+ { $($k: analyzer.get($v).get()?),* };
analyzer.build(v)
}};
($($item:ident)::+ ( $($v:expr),* $(,)? )) => {{
let mut analyzer = $crate::error::AstErrorAnalyzer(None);
let v = $($item)::+ ( $(analyzer.get($v).get()?),* );
analyzer.build(v)
}};
($($item:ident)::+) => {
$($item)::+
};
} }
+25 -31
View File
@@ -1,7 +1,8 @@
use crate::{ use crate::{
Rule, Rule,
ast::*, ast::*,
error::{AstError, GetParseError}, ast_expr,
error::{AstError, AstResult, IntoErr},
parser::listen_rule, parser::listen_rule,
}; };
@@ -13,14 +14,13 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDeclStmt {
Rule::var_decl_statement => { Rule::var_decl_statement => {
let mut inner = pair.into_inner(); let mut inner = pair.into_inner();
let decl = VarDecl::try_from(inner.next().unwrap()).get()?; ast_expr!(VarDeclStmt {
decl: inner.next().unwrap().try_into(),
let init = inner.next().map(Expression::try_from).transpose().get()?; init: inner.next().map(Expression::try_from).transpose()
})
Ok(VarDeclStmt { decl, init })
} }
_ => unimplemented!(), _ => AstError::bug_unimplemented(pair),
} }
} }
} }
@@ -33,14 +33,13 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FieldDeclStmt {
Rule::class_field => { Rule::class_field => {
let mut inner = pair.into_inner(); let mut inner = pair.into_inner();
let decl = FieldDecl::try_from(inner.next().unwrap()).get()?; ast_expr!(FieldDeclStmt {
decl: inner.next().unwrap().try_into(),
let init = inner.next().map(Expression::try_from).transpose().get()?; init: inner.next().map(Expression::try_from).transpose(),
})
Ok(FieldDeclStmt { decl, init })
} }
_ => unimplemented!(), _ => AstError::bug_unimplemented(pair),
} }
} }
} }
@@ -62,21 +61,20 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for VarDecl {
Some(TypeExpr::try_from(pair)) Some(TypeExpr::try_from(pair))
} }
}) })
.transpose() .transpose();
.get()?;
let mutable = listen_rule(&mut inner, Rule::mutable); let mutable: AstResult<'_, bool> = Ok(listen_rule(&mut inner, Rule::mutable));
let name = Pattern::try_from(inner.next().unwrap()).get()?; let name = Pattern::try_from(inner.next().unwrap());
Ok(VarDecl { ast_expr!(VarDecl {
mutable, type_: type_,
name, mutable: mutable,
type_, name: name,
}) })
} }
_ => unimplemented!("{:?}", pair.as_rule()), _ => AstError::bug_unimplemented(pair),
} }
} }
} }
@@ -89,18 +87,14 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FieldDecl {
Rule::field => { Rule::field => {
let mut inner = pair.into_inner(); let mut inner = pair.into_inner();
let visibility = Visibility::try_from(&mut inner).get()?; ast_expr!(FieldDecl {
let type_ = TypeExpr::try_from(inner.next().unwrap()).get()?; visibility: Visibility::try_from(&mut inner),
let name = Identifier::try_from(inner.next().unwrap()).get()?; type_: TypeExpr::try_from(inner.next().unwrap()),
name: Identifier::try_from(inner.next().unwrap()),
Ok(FieldDecl {
visibility,
type_,
name,
}) })
} }
_ => unimplemented!("{:?}", pair.as_rule()), _ => AstError::bug_unimplemented(pair),
} }
} }
} }
+39 -44
View File
@@ -1,7 +1,8 @@
use crate::{ use crate::{
Rule, Rule,
ast::*, ast::*,
error::{AstError, AstResult, GetParseError, collect_recovered, collect_recovered_map}, ast_expr,
error::{AstError, GetLength, IntoErr, 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 {
@@ -15,32 +16,27 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Expression {
Rule::expr => { Rule::expr => {
let prefixes = inner let prefixes = inner
.next() .next()
.map(|p| { .map(|p| collect_recovered::<Prefix, Prefix>(p.into_inner()))
p.into_inner() .unwrap_or_else(|| Ok(Vec::new()));
.into_iter()
.map(Prefix::try_from)
.collect::<AstResult<'a, Vec<_>, _>>()
})
.transpose()
.get()?
.unwrap_or_default();
let exp = Expression::try_from(inner.next().unwrap())?; let exp = Expression::try_from(inner.next().unwrap());
if inner.len() > 0 || prefixes.len() > 0 { if inner.len() > 0 || prefixes.len() > 0 {
Ok(Expression::Fix { ast_expr!(Expression::Fix {
initial: Box::new(exp), initial: exp.map(Box::new),
prefixes, prefixes: prefixes,
postfixes: collect_recovered(inner).get()?, postfixes: collect_recovered(inner),
}) })
} else { } else {
Ok(exp) exp
} }
} }
Rule::primary => Expression::try_from(inner.next().unwrap()),
Rule::static_path => Ok(Expression::Path(Path::try_from(pair).get()?)), Rule::primary => inner.next().unwrap().try_into(),
Rule::literal => Ok(Expression::Literal(Literal::try_from(pair).get()?)), Rule::static_path => ast_expr!(Expression::Path(pair.try_into())),
_ => unimplemented!("{rule:#?}"), Rule::literal => ast_expr!(Expression::Literal(pair.try_into())),
_ => AstError::bug_unimplemented(pair),
} }
} }
} }
@@ -56,7 +52,8 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Prefix {
Rule::ref_px => Self::Ref, Rule::ref_px => Self::Ref,
Rule::new_px => Self::New, Rule::new_px => Self::New,
Rule::not_px => Self::Not, Rule::not_px => Self::Not,
_ => unimplemented!("{pair:#?}"),
_ => return AstError::bug_unimplemented(pair),
}) })
} }
} }
@@ -66,29 +63,28 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Postfix {
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 rule = pair.as_rule(); let rule = pair.as_rule();
let mut inner = pair.into_inner(); let mut inner = pair.clone().into_inner();
Ok(match rule { match rule {
Rule::postfix => Postfix::try_from(inner.next().unwrap())?, Rule::postfix => Postfix::try_from(inner.next().unwrap()),
Rule::field_px => { Rule::field_px => {
Postfix::FieldAccess(Identifier::try_from(inner.next().unwrap()).get()?) ast_expr!(Postfix::FieldAccess(inner.next().unwrap().try_into()))
} }
Rule::call_px => Postfix::Call(collect_recovered(inner).get()?), Rule::call_px => ast_expr!(Postfix::Call(collect_recovered(inner))),
Rule::struct_px => Postfix::StructCall( Rule::struct_px => ast_expr!(Postfix::StructCall(collect_recovered_map(inner, |p| {
collect_recovered_map(inner, |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()).get()?,
Expression::try_from(pi.next().unwrap()).get()?, ))
)) }))),
})
.get()?,
),
Rule::index_px => Postfix::Index(Expression::try_from(inner.next().unwrap()).get()?), Rule::index_px => {
ast_expr!(Postfix::Index(Expression::try_from(inner.next().unwrap())))
}
Rule::binary_px => { Rule::binary_px => {
let op_pair = inner.next().unwrap(); let op_pair = inner.next().unwrap();
@@ -107,16 +103,15 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Postfix {
"&&" => BinaryOp::And, "&&" => BinaryOp::And,
"||" => BinaryOp::Or, "||" => BinaryOp::Or,
_ => { _ => return AstError::bug_unimplemented(op_pair),
unimplemented!("Binary operator not implemented yet: {}", op_pair.as_str())
}
}; };
Postfix::Binary(op, Expression::try_from(inner.next().unwrap()).get()?)
Ok(Postfix::Binary(op, inner.next().unwrap().try_into().get()?))
} }
Rule::macro_call_px => Postfix::MacroCall(inner.as_str().to_string()), Rule::macro_call_px => Ok(Postfix::MacroCall(inner.as_str().to_string())),
_ => unimplemented!("{rule:#?}"), _ => AstError::bug_unimplemented(pair),
}) }
} }
} }
+23 -20
View File
@@ -6,7 +6,8 @@ pub mod types;
use crate::{ use crate::{
Rule, Rule,
ast::*, ast::*,
error::{AstError, GetParseError, collect_recovered}, ast_ensure, ast_expr,
error::{AstError, IntoErr, collect_recovered},
parser::consume_rule, parser::consume_rule,
}; };
@@ -14,7 +15,9 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Identifier {
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> {
Ok(Identifier(pair.as_str().to_string())) ast_ensure!(pair, Rule::identifier => {
Ok(Identifier(pair.as_str().to_string()))
})
} }
} }
@@ -24,7 +27,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(collect_recovered(pair.into_inner()).get()?)), Rule::static_path => Ok(Path(collect_recovered(pair.into_inner()).get()?)),
_ => unimplemented!("{pair:#?}"), _ => AstError::bug_unimplemented(pair),
} }
} }
} }
@@ -44,7 +47,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Literal {
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(collect_recovered(inner).get()?), Rule::tuple => Literal::Tuple(collect_recovered(inner).get()?),
_ => unimplemented!("{rule:#?}"), _ => return AstError::bug_unimplemented(pair),
}) })
} }
} }
@@ -56,27 +59,27 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Pattern {
let rule = pair.as_rule(); let rule = pair.as_rule();
let mut inner = pair.clone().into_inner(); let mut inner = pair.clone().into_inner();
Ok(match rule { match rule {
Rule::tuple_pattern => Pattern::Tuple(collect_recovered(pair.into_inner()).get()?), Rule::tuple_pattern => ast_expr!(Pattern::Tuple(collect_recovered(pair.into_inner()))),
Rule::named_tuple_pattern => Pattern::NamedTuple( Rule::named_tuple_pattern => ast_expr!(Pattern::NamedTuple(
Path::try_from(inner.next().unwrap()).get()?, Path::try_from(inner.next().unwrap()),
collect_recovered(inner).get()?, collect_recovered(inner),
), )),
Rule::struct_pattern => Pattern::Struct( Rule::struct_pattern => ast_expr!(Pattern::Struct(
Path::try_from(inner.next().unwrap()).get()?, Path::try_from(inner.next().unwrap()),
collect_recovered(inner).get()?, collect_recovered(inner),
), )),
Rule::literal => Pattern::Literal(Literal::try_from(pair).get()?), Rule::literal => ast_expr!(Pattern::Literal(pair.try_into())),
Rule::identifier => Pattern::Id(Identifier::try_from(pair).get()?), Rule::identifier => ast_expr!(Pattern::Id(pair.try_into())),
Rule::static_path => Pattern::Path(Path::try_from(pair).get()?), Rule::static_path => ast_expr!(Pattern::Path(pair.try_into())),
_ => unimplemented!("{rule:?}"), _ => AstError::bug_unimplemented(pair),
}) }
} }
} }
@@ -87,7 +90,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).get()?)) ast_expr!(Visibility::PublicTarget(Path::try_from(path)))
} else { } else {
Ok(Visibility::Public) Ok(Visibility::Public)
} }
+62 -70
View File
@@ -1,7 +1,8 @@
use crate::{ use crate::{
Rule, Rule,
ast::*, ast::*,
error::{AstError, AstResult, ErrorCode, GetParseError, collect_recovered}, ast_ensure, ast_expr,
error::{AstError, AstResult, ErrorCode, IntoErr, collect_recovered},
parser::listen_rule, parser::listen_rule,
}; };
@@ -9,19 +10,24 @@ 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> {
if pair.as_rule() == Rule::block { ast_ensure!(pair, Rule::block => {
Ok(Block(collect_recovered(pair.into_inner()).get()?)) ast_expr!(Block(collect_recovered(pair.into_inner())))
} else { })
Err(AstError { }
span: pair.as_span(), }
error_code: ErrorCode::InvalidStatement,
error_message: format!( impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for StatementBranch {
"BUG: AST requires a block, this isn't a block, it's a {:?}", type Error = AstError<'a, Self>;
pair.as_rule()
), fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
recovered: None, let mut inner = pair.clone().into_inner();
ast_ensure!(pair, Rule::statement_branch => {
ast_expr!(StatementBranch {
condition: inner.next().unwrap().try_into(),
body: inner.next().unwrap().try_into().map(Box::new),
}) })
} })
} }
} }
@@ -32,62 +38,65 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Statement {
let rule = pair.as_rule(); let rule = pair.as_rule();
let mut inner = pair.clone().into_inner(); let mut inner = pair.clone().into_inner();
Ok(match rule { match rule {
Rule::statement => Statement::try_from(inner.next().unwrap())?, Rule::statement => Statement::try_from(inner.next().unwrap()),
Rule::expr_stmt => { Rule::expr_stmt => {
Statement::Expression(Expression::try_from(inner.next().unwrap()).get()?) ast_expr!(Statement::Expression(inner.next().unwrap().try_into()))
} }
Rule::block => Statement::Block(pair.try_into().get()?), Rule::block => ast_expr!(Statement::Block(pair.try_into())),
Rule::var_decl_statement => Statement::VarDecl(VarDeclStmt::try_from(pair).get()?), Rule::var_decl_statement => ast_expr!(Statement::VarDecl(pair.try_into())),
Rule::return_stmt => { Rule::return_stmt => {
Statement::Return(inner.next().map(Expression::try_from).transpose().get()?) ast_expr!(Statement::Return(
inner.next().map(Expression::try_from).transpose()
))
} }
Rule::break_stmt => Statement::Break, Rule::break_stmt => Ok(Statement::Break),
Rule::continue_stmt => Statement::Continue, Rule::continue_stmt => Ok(Statement::Continue),
Rule::if_stmt => { Rule::if_stmt => {
let mut inner = inner.skip(2); ast_expr!(Statement::If {
initial: inner.next().unwrap().try_into(),
Statement::If { else_if: collect_recovered(inner.next().unwrap().into_inner()),
initial: StatementBranch::try_from(pair).get()?,
else_if: collect_recovered(inner.next().unwrap().into_inner()).get()?,
else_branch: inner else_branch: inner
.next() .next()
.map(Statement::try_from) .map(Statement::try_from)
.transpose()? .transpose()
.map(Box::new), .map(|v| v.map(Box::new))
} .get_map(|v| { Some(Box::new(v)) }),
})
} }
Rule::while_stmt => Statement::While(pair.try_into().get()?), Rule::while_stmt => ast_expr!(Statement::While(inner.next().unwrap().try_into())),
Rule::c_for_stmt => Statement::CStyleFor { Rule::c_for_stmt => ast_expr!(Statement::CStyleFor {
init: Box::new(inner.next().unwrap().try_into().get()?), init: inner.next().unwrap().try_into().map(Box::new),
condition: inner.next().unwrap().try_into().get()?, condition: inner.next().unwrap().try_into(),
update: Box::new(inner.next().unwrap().try_into().get()?), update: inner.next().unwrap().try_into().map(Box::new),
body: Box::new(inner.next().unwrap().try_into().get()?), body: inner.next().unwrap().try_into().map(Box::new),
},
Rule::for_stmt => Statement::For {
mutable: listen_rule(&mut inner, Rule::mutable),
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: inner.next().unwrap().try_into().get()?,
value: inner.next().unwrap().try_into().get()?,
}), }),
Rule::match_stmt => Statement::Match( Rule::for_stmt => ast_expr!(Statement::For {
inner.next().unwrap().try_into().get()?, mutable: Ok(listen_rule(&mut inner, Rule::mutable)) as AstResult<'_, bool>,
pattern: inner.next().unwrap().try_into(),
iterator: inner.next().unwrap().try_into(),
body: inner.next().unwrap().try_into().map(Box::new),
}),
Rule::assign_statement => ast_expr!(VarAssignStmt {
target: inner.next().unwrap().try_into(),
value: inner.next().unwrap().try_into(),
})
.map(Statement::VarAssign)
.get_map(Statement::VarAssign),
Rule::match_stmt => ast_expr!(Statement::Match(
inner.next().unwrap().try_into(),
inner inner
.map(|match_itms| { .map(|match_itms| {
let mut match_inner = match_itms.into_inner(); let mut match_inner = match_itms.into_inner();
@@ -96,9 +105,8 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Statement {
Block::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 => { Rule::unexpected_statement => {
return Err(AstError { return Err(AstError {
@@ -109,23 +117,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Statement {
}); });
} }
_ => unimplemented!("{rule:#?}"), _ => AstError::bug_unimplemented(pair),
}) }
}
}
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for StatementBranch {
type Error = AstError<'a, Self>;
fn try_from(pair: pest::iterators::Pair<'a, Rule>) -> Result<Self, Self::Error> {
let mut inner = pair.into_inner();
let condition = inner.next().unwrap().try_into().get()?;
let body = inner.next().unwrap().try_into().get()?;
Ok(StatementBranch {
condition,
body: Box::new(body),
})
} }
} }
+28 -26
View File
@@ -1,7 +1,8 @@
use crate::{ use crate::{
Rule, Rule,
ast::*, ast::*,
error::{AstError, GetParseError, collect_recovered}, ast_expr,
error::{AstError, GetLength, IntoErr, collect_recovered},
parser::{consume_rule, listen_rule}, parser::{consume_rule, listen_rule},
}; };
@@ -10,7 +11,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypePostfix {
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 rule = pair.as_rule(); let rule = pair.as_rule();
let mut inner = pair.into_inner(); let mut inner = pair.clone().into_inner();
match rule { match rule {
Rule::ref_type => { Rule::ref_type => {
@@ -34,7 +35,8 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypePostfix {
} }
}) })
} }
_ => unimplemented!("{rule:#?}"),
_ => AstError::bug_unimplemented(pair),
} }
} }
} }
@@ -44,21 +46,21 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypeExprKind {
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 rule = pair.as_rule(); let rule = pair.as_rule();
let mut inner = pair.into_inner(); let mut inner = pair.clone().into_inner();
match rule { match rule {
Rule::tuple_type => Ok(TypeExprKind::Tuple(collect_recovered(inner).get()?)), Rule::tuple_type => ast_expr!(TypeExprKind::Tuple(collect_recovered(inner))),
Rule::path_type => { Rule::path_type => {
let path = Path::try_from(inner.next().unwrap()).get()?; let path = Path::try_from(inner.next().unwrap());
let params = collect_recovered(inner).get()?; let params = collect_recovered(inner);
if params.len() == 0 { if params.len() == 0 {
Ok(TypeExprKind::Path(path)) ast_expr!(TypeExprKind::Path(path))
} else { } else {
Ok(TypeExprKind::PathParams(path, params)) ast_expr!(TypeExprKind::PathParams(path, params))
} }
} }
_ => unimplemented!("{rule:#?}"), _ => AstError::bug_unimplemented(pair),
} }
} }
} }
@@ -68,19 +70,19 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TypeExpr {
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 rule = pair.as_rule(); let rule = pair.as_rule();
let mut inner = pair.into_inner(); let mut inner = pair.clone().into_inner();
match rule { match rule {
Rule::type_expr => Ok(TypeExpr( Rule::type_expr => ast_expr!(TypeExpr(
inner.next().unwrap().try_into().get()?, inner.next().unwrap().try_into(),
collect_recovered(inner).get()?, collect_recovered(inner),
)), )),
Rule::type_expr_param => Self::try_from(inner.next().unwrap()), Rule::type_expr_param => Self::try_from(inner.next().unwrap()),
Rule::lifetime => Ok(TypeExpr( Rule::lifetime => ast_expr!(TypeExprKind::Lifetime(inner.next().unwrap().try_into()))
TypeExprKind::Lifetime(inner.next().unwrap().try_into().get()?), .get_map(TypeExpr::no_px)
Vec::new(), .map(TypeExpr::no_px),
)),
_ => unimplemented!("{rule:#?}"), _ => AstError::bug_unimplemented(pair),
} }
} }
} }
@@ -93,8 +95,8 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Generics {
let inner = pair.clone().into_inner(); let inner = pair.clone().into_inner();
match rule { match rule {
Rule::generics => Ok(Generics(collect_recovered(inner).get()?)), Rule::generics => ast_expr!(Generics(collect_recovered(inner))),
_ => unimplemented!("{rule:#?}"), _ => AstError::bug_unimplemented(pair),
} }
} }
} }
@@ -106,13 +108,13 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Generic {
let mut inner = pair.clone().into_inner(); let mut inner = pair.clone().into_inner();
if let Some(pair) = consume_rule(&mut inner, Rule::lifetime) { if let Some(pair) = consume_rule(&mut inner, Rule::lifetime) {
Ok(Generic::Lifetime( ast_expr!(Generic::Lifetime(
pair.into_inner().next().unwrap().try_into().get()?, pair.into_inner().next().unwrap().try_into(),
)) ))
} else { } else {
Ok(Generic::Type( ast_expr!(Generic::Type(
inner.next().unwrap().try_into().get()?, inner.next().unwrap().try_into(),
collect_recovered(inner).get()?, collect_recovered(inner),
)) ))
} }
} }
+1 -1
View File
@@ -1,7 +1,7 @@
use crate::{ use crate::{
Rule, Rule,
ast::*, ast::*,
error::{AstError, GetParseError, collect_recovered}, error::{AstError, IntoErr, collect_recovered},
}; };
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Attribute { impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for Attribute {
+2 -2
View File
@@ -1,7 +1,7 @@
use crate::{ use crate::{
Rule, Rule,
ast::*, ast::*,
error::{AstError, GetParseError}, error::{AstError, IntoErr},
parser::consume_rule, parser::consume_rule,
}; };
@@ -44,7 +44,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ClassItem {
Rule::method => Ok(ClassItem::Method(pair.try_into().get()?)), Rule::method => Ok(ClassItem::Method(pair.try_into().get()?)),
_ => unimplemented!("{rule:#?}"), _ => AstError::bug_unimplemented(pair),
} }
} }
} }
+3 -3
View File
@@ -1,7 +1,7 @@
use crate::{ use crate::{
Rule, Rule,
ast::*, ast::*,
error::{AstError, GetParseError, collect_recovered}, error::{AstError, IntoErr, collect_recovered},
}; };
impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for EnumItem { impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for EnumItem {
@@ -25,11 +25,11 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for EnumItem {
.next() .next()
.map(|pair| collect_recovered::<FieldDecl, FieldDecl>(pair.into_inner())) .map(|pair| collect_recovered::<FieldDecl, FieldDecl>(pair.into_inner()))
.transpose() .transpose()
.get::<Self>()? .get()?
.unwrap_or_default(), .unwrap_or_default(),
)), )),
_ => unimplemented!("{rule:#?}"), _ => AstError::bug_unimplemented(pair),
} }
} }
} }
+16 -17
View File
@@ -1,7 +1,8 @@
use crate::{ use crate::{
Rule, Rule,
ast::*, ast::*,
error::{AstError, AstResult, GetParseError, collect_recovered}, ast_expr,
error::{AstError, AstResult, IntoErr, collect_recovered},
parser::{consume_rule, listen_rule}, parser::{consume_rule, listen_rule},
}; };
@@ -10,14 +11,14 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FunctionDecl {
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 visibility = Visibility::try_from(&mut inner).get()?; let visibility = Visibility::try_from(&mut inner);
let return_type = TypeExpr::try_from(inner.next().unwrap()).get()?; let return_type = TypeExpr::try_from(inner.next().unwrap());
let name = Identifier::try_from(inner.next().unwrap()).get()?; let name = Identifier::try_from(inner.next().unwrap());
let generics = consume_rule(&mut inner, Rule::generics) let generics = consume_rule(&mut inner, Rule::generics)
.map(Generics::try_from) .map(Generics::try_from)
.transpose() .transpose()
.get()? .map(|v| v.unwrap_or_default());
.unwrap_or_default();
let self_param = consume_rule(&mut inner, Rule::self_param).map(|param| { let self_param = consume_rule(&mut inner, Rule::self_param).map(|param| {
let mut param_inner = param.into_inner(); let mut param_inner = param.into_inner();
@@ -56,19 +57,17 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for FunctionDecl {
Ok(params) Ok(params)
} }
}) })
.transpose() .unwrap_or_else(|| Ok(ParamList(self_param.into_iter().collect())));
.get()?
.unwrap_or_else(|| ParamList(self_param.into_iter().collect()));
let body = inner.next().map(Block::try_from).transpose().get()?; let body = inner.next().map(Block::try_from).transpose();
Ok(Self { ast_expr!(Self {
visibility, visibility: visibility,
name, return_type: return_type,
generics, name: name,
params, generics: generics,
return_type, params: params,
body, body: body,
}) })
} }
} }
+2 -2
View File
@@ -1,7 +1,7 @@
use crate::{ use crate::{
Rule, Rule,
ast::*, ast::*,
error::{AstError, GetParseError, collect_recovered}, error::{AstError, IntoErr, collect_recovered},
parser::consume_rule, parser::consume_rule,
}; };
@@ -35,7 +35,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for ImplDecl {
methods: collect_recovered(inner).get()?, methods: collect_recovered(inner).get()?,
}), }),
_ => unimplemented!("{rule:#?}"), _ => AstError::bug_unimplemented(pair),
} }
} }
} }
+47 -51
View File
@@ -7,7 +7,8 @@ pub mod impl_decl;
use crate::{ use crate::{
Rule, Rule,
ast::*, ast::*,
error::{AstError, GetParseError, collect_recovered}, ast_expr,
error::{AstError, IntoErr, collect_recovered},
parser::consume_rule, parser::consume_rule,
}; };
@@ -17,14 +18,13 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TopLevel {
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 attributes = collect_recovered(inner.next().unwrap().into_inner()).get()?; let attributes = collect_recovered(inner.next().unwrap().into_inner());
Ok(TopLevel( ast_expr!(TopLevel(
inner inner
.next() .next()
.map(TopLevelKind::try_from) .map(TopLevelKind::try_from)
.unwrap_or(Ok(TopLevelKind::ModAttribute)) .unwrap_or(Ok(TopLevelKind::ModAttribute)),
.get()?,
attributes, attributes,
)) ))
} }
@@ -37,93 +37,89 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TopLevelKind {
let rule = pair.as_rule(); let rule = pair.as_rule();
let mut inner = pair.clone().into_inner(); let mut inner = pair.clone().into_inner();
Ok(match rule { match rule {
Rule::import => TopLevelKind::Import( Rule::import => ast_expr!(TopLevelKind::Import(
Visibility::try_from(&mut inner).get()?, Visibility::try_from(&mut inner),
Path::try_from(inner.next().unwrap()).get()?, Path::try_from(inner.next().unwrap()),
), )),
Rule::function_decl => TopLevelKind::FunctionDecl(pair.try_into().get()?), Rule::function_decl => ast_expr!(TopLevelKind::FunctionDecl(pair.try_into())),
Rule::struct_decl => TopLevelKind::StructDecl { Rule::struct_decl => ast_expr!(TopLevelKind::StructDecl {
visibility: Visibility::try_from(&mut inner).get()?, visibility: Visibility::try_from(&mut inner),
name: inner.next().unwrap().try_into().get()?, name: inner.next().unwrap().try_into(),
generics: consume_rule(&mut inner, Rule::generics) generics: consume_rule(&mut inner, Rule::generics)
.map(Generics::try_from) .map(Generics::try_from)
.transpose() .transpose()
.get()? .map(|v| v.unwrap_or_default()),
.unwrap_or_default(),
fields: inner fields: inner
.next() .next()
.map(|pair| collect_recovered::<FieldDecl, FieldDecl>(pair.into_inner())) .map(|pair| collect_recovered::<FieldDecl, FieldDecl>(pair.into_inner()))
.transpose() .transpose()
.get()? .map(|v| v.unwrap_or_default()),
.unwrap_or_default(), }),
},
Rule::class_decl => TopLevelKind::ClassDecl { Rule::class_decl => ast_expr!(TopLevelKind::ClassDecl {
visibility: Visibility::try_from(&mut inner).get()?, visibility: Visibility::try_from(&mut inner),
name: inner.next().unwrap().try_into().get()?, name: inner.next().unwrap().try_into(),
generics: consume_rule(&mut inner, Rule::generics) generics: consume_rule(&mut inner, Rule::generics)
.map(Generics::try_from) .map(Generics::try_from)
.transpose() .transpose()
.get()? .map(|v| v.unwrap_or_default()),
.unwrap_or_default(),
fields: collect_recovered(inner.next().unwrap().into_inner()).get()?, fields: collect_recovered(inner.next().unwrap().into_inner()),
constructor: inner.next().unwrap().try_into().get()?, constructor: inner.next().unwrap().try_into(),
items: collect_recovered(inner).get()?, items: collect_recovered(inner),
}, }),
Rule::enum_decl => TopLevelKind::EnumDecl { Rule::enum_decl => ast_expr!(TopLevelKind::EnumDecl {
visibility: Visibility::try_from(&mut inner).get()?, visibility: Visibility::try_from(&mut inner),
name: inner.next().unwrap().try_into().get()?, name: inner.next().unwrap().try_into(),
generics: consume_rule(&mut inner, Rule::generics) generics: consume_rule(&mut inner, Rule::generics)
.map(Generics::try_from) .map(Generics::try_from)
.transpose() .transpose()
.get()? .map(|v| v.unwrap_or_default()),
.unwrap_or_default(),
fields: collect_recovered(inner).get()?, fields: collect_recovered(inner),
}, }),
Rule::mod_package => TopLevelKind::Mod( Rule::mod_package => ast_expr!(TopLevelKind::Mod(
Visibility::try_from(&mut inner).get()?, Visibility::try_from(&mut inner),
inner.next().unwrap().try_into().get()?, inner.next().unwrap().try_into(),
), )),
Rule::impl_for_decl | Rule::impl_decl => TopLevelKind::ImplDecl(pair.try_into().get()?), Rule::impl_for_decl | Rule::impl_decl => {
ast_expr!(TopLevelKind::ImplDecl(pair.try_into()))
}
Rule::trait_decl => TopLevelKind::TraitDecl { Rule::trait_decl => ast_expr!(TopLevelKind::TraitDecl {
visibility: Visibility::try_from(&mut inner).get()?, visibility: Visibility::try_from(&mut inner),
name: inner.next().unwrap().try_into().get()?, name: inner.next().unwrap().try_into(),
generics: consume_rule(&mut inner, Rule::generics) generics: consume_rule(&mut inner, Rule::generics)
.map(Generics::try_from) .map(Generics::try_from)
.transpose() .transpose()
.get()? .map(|v| v.unwrap_or_default()),
.unwrap_or_default(),
requirements: consume_rule(&mut inner, Rule::trait_requirements) requirements: consume_rule(&mut inner, Rule::trait_requirements)
.map(|pair| collect_recovered::<TypeExpr, TypeExpr>(pair.into_inner())) .map(|pair| collect_recovered::<TypeExpr, TypeExpr>(pair.into_inner()))
.transpose() .transpose()
.get()? .map(|v| v.unwrap_or_default()),
.unwrap_or_default(),
items: collect_recovered(inner).get()?, items: collect_recovered(inner),
}, }),
_ => unimplemented!("{rule:#?}"), _ => AstError::bug_unimplemented(pair),
}) }
} }
} }
+20 -1
View File
@@ -5,6 +5,7 @@ use std::{
time::Instant, time::Instant,
}; };
use mist_parser::error::ParseError;
use serde::Deserialize; use serde::Deserialize;
#[derive(Deserialize)] #[derive(Deserialize)]
@@ -100,7 +101,25 @@ fn build_dir(root: &Path, base_src: &Path, current_dir: &Path, out_dir: &Path) {
} }
}; };
let parser_result = mist_parser::parse(&source).map_err(|e| format!("{e:?}")); let parser_result = mist_parser::parse(&source).map_err(|e| match e {
ParseError::Ast(e) => {
let start_pos = e.span.start_pos().line_col();
let span = e.span.as_str();
format!(
"\n{}:{}:{}\n \x1b[31mError\x1b[0m: {}\n\t{}{}\t{}",
path.as_os_str().display(),
start_pos.0,
start_pos.1,
e.error_message,
span,
if span.ends_with("\n") { "" } else { "\n" },
"^".repeat(span.trim().len()),
)
}
ParseError::PreAst(e) => format!("{e}"),
});
let ast = match parser_result { let ast = match parser_result {
Ok(ast) => ast, Ok(ast) => ast,