Updated parser

This commit is contained in:
2026-06-10 05:37:08 +02:00
parent 562bcd7f1e
commit 1619250ba5
6 changed files with 32 additions and 9 deletions
+1 -1
View File
@@ -28,7 +28,7 @@ pub struct TopLevel(pub Spanned<TopLevelKind>, pub Vec<Attribute>);
pub enum TopLevelKind {
ModAttribute,
Import(Visibility, Path),
Mod(Visibility, Identifier),
DeclareModule(Visibility, Identifier),
ImplDecl(ImplDecl),
TraitDecl {
visibility: Visibility,
+1
View File
@@ -24,6 +24,7 @@ pub struct AstError<'a, T> {
pub enum ErrorCode {
InvalidStatement,
AstGenBug,
Module,
}
impl<T> From<pest::error::Error<Rule>> for ParseError<'_, T> {
+3 -3
View File
@@ -220,8 +220,8 @@ import = {
visibility? ~ "use" ~ static_path ~ semicolon
}
mod_package = {
visibility? ~ "mod" ~ identifier ~ semicolon
declare_module = {
visibility? ~ "module" ~ identifier ~ semicolon
}
// ======================================================
@@ -334,7 +334,7 @@ function_decl = {
// ======================================================
top_level = {
(attributes ~ (import | impl_for_decl | impl_decl | trait_decl | struct_decl | enum_decl | class_decl | mod_package | function_decl))
(attributes ~ (import | impl_for_decl | impl_decl | trait_decl | struct_decl | enum_decl | class_decl | declare_module | function_decl))
| mod_attribute
}
+25 -3
View File
@@ -1,4 +1,4 @@
use pest::Parser;
use pest::{Parser, Span};
use pest_derive::Parser;
pub mod ast;
@@ -14,7 +14,9 @@ use crate::error::{IntoErr, ParseError};
#[grammar = "./src/grammar.pest"]
pub struct MistParser;
pub fn parse<'a>(source: &'a str) -> Result<Vec<TopLevel>, ParseError<'a, Vec<TopLevel>>> {
pub fn parse<'a>(
source: &'a str,
) -> Result<((Visibility, Identifier), Vec<TopLevel>), ParseError<'a, Vec<TopLevel>>> {
let mut pairs = MistParser::parse(Rule::program, source)?;
let mut statements = vec![];
@@ -27,8 +29,28 @@ pub fn parse<'a>(source: &'a str) -> Result<Vec<TopLevel>, ParseError<'a, Vec<To
}
}
let m = if let Some(v) = statements.get(0) {
if let TopLevelKind::DeclareModule(vis, name) = &v.0.item {
(vis.clone(), name.clone())
} else {
return Err(ParseError::Ast(error::AstError {
span: Span::new("", 0, 0).unwrap(),
error_code: error::ErrorCode::Module,
error_message: "Module must be declared, use `module <>;`".to_string(),
recovered: None,
}));
}
} else {
return Err(ParseError::Ast(error::AstError {
span: Span::new("", 0, 0).unwrap(),
error_code: error::ErrorCode::Module,
error_message: "Module must be declared, use `module <>;`".to_string(),
recovered: None,
}));
};
match analyzer.build(statements) {
Ok(v) => Ok(v),
Ok(v) => Ok((m, v)),
Err(e) => Err(ParseError::Ast(e)),
}
}
+1 -1
View File
@@ -93,7 +93,7 @@ impl<'a> TryFrom<pest::iterators::Pair<'a, Rule>> for TopLevelKind {
fields: collect_recovered(inner),
}),
Rule::mod_package => ast_expr!(TopLevelKind::Mod(
Rule::declare_module => ast_expr!(TopLevelKind::DeclareModule(
Visibility::try_from(&mut inner),
inner.next().unwrap().try_into(),
)),