Refactoring variable definition parsing

This commit is contained in:
2026-05-04 06:59:31 +02:00
parent 4dcb3fae7b
commit a4c1f787ff
4 changed files with 92 additions and 53 deletions
+12 -4
View File
@@ -3,7 +3,10 @@ use std::collections::HashMap;
use serde::Serialize; use serde::Serialize;
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub struct ParamList(pub HashMap<String, (bool, TypeExpr)>); pub struct FieldList(pub HashMap<String, (bool, TypeExpr)>);
#[derive(Debug, Clone, Serialize)]
pub struct ParamList(pub Vec<VarDecl>);
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub struct Block(pub Vec<Statement>); pub struct Block(pub Vec<Statement>);
@@ -34,7 +37,7 @@ pub enum TopLevel {
StructDecl { StructDecl {
export: bool, export: bool,
name: String, name: String,
fields: ParamList, fields: FieldList,
}, },
FunctionDecl { FunctionDecl {
export: bool, export: bool,
@@ -71,13 +74,18 @@ pub enum Statement {
} }
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub struct VarDeclStmt { pub struct VarDecl {
pub mutable: bool, pub mutable: bool,
pub name: String, pub name: String,
pub init: Option<Expression>,
pub type_: Option<TypeExpr>, pub type_: Option<TypeExpr>,
} }
#[derive(Debug, Clone, Serialize)]
pub struct VarDeclStmt {
pub decl: VarDecl,
pub init: Option<Expression>,
}
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub struct VarAssignStmt { pub struct VarAssignStmt {
pub target: Expression, pub target: Expression,
+60 -33
View File
@@ -1,5 +1,3 @@
use std::collections::HashMap;
use pest::Parser; use pest::Parser;
use pest_derive::Parser; use pest_derive::Parser;
@@ -17,8 +15,6 @@ pub type ParseError = pest::error::Error<Rule>;
pub fn parse(source: &str) -> Result<Vec<TopLevel>, ParseError> { pub fn parse(source: &str) -> Result<Vec<TopLevel>, ParseError> {
let mut pairs = MistParser::parse(Rule::program, source)?; let mut pairs = MistParser::parse(Rule::program, source)?;
println!("{pairs:#?}");
let mut statements = vec![]; let mut statements = vec![];
for pair in pairs.next().unwrap().into_inner() { for pair in pairs.next().unwrap().into_inner() {
@@ -49,14 +45,13 @@ impl TryFrom<pest::iterators::Pair<'_, Rule>> for TypeExpr {
} }
} }
impl From<(bool, pest::iterators::Pair<'_, Rule>)> for ParamList { impl From<pest::iterators::Pair<'_, Rule>> for FieldList {
fn from((export_allowed, pair): (bool, pest::iterators::Pair<Rule>)) -> Self { fn from(pair: pest::iterators::Pair<Rule>) -> Self {
let params = pair let params = pair
.into_inner() .into_inner()
.map(|p| { .map(|p| {
let mut param_inner = p.into_inner(); let mut param_inner = p.into_inner();
let export = let export = if param_inner.peek().unwrap().as_rule() == Rule::export {
if export_allowed && param_inner.peek().unwrap().as_rule() == Rule::export {
param_inner.next().unwrap(); param_inner.next().unwrap();
true true
} else { } else {
@@ -68,6 +63,14 @@ impl From<(bool, pest::iterators::Pair<'_, Rule>)> for ParamList {
}) })
.collect(); .collect();
FieldList(params)
}
}
impl From<pest::iterators::Pair<'_, Rule>> for ParamList {
fn from(pair: pest::iterators::Pair<Rule>) -> Self {
let params = pair.into_inner().map(VarDecl::from).collect();
ParamList(params) ParamList(params)
} }
} }
@@ -106,9 +109,9 @@ impl TryFrom<pest::iterators::Pair<'_, Rule>> for TopLevel {
let name = inner.next().unwrap().as_str().to_string(); let name = inner.next().unwrap().as_str().to_string();
let params = if inner.peek().unwrap().as_rule() == Rule::param_list { let params = if inner.peek().unwrap().as_rule() == Rule::param_list {
ParamList::from((false, inner.next().unwrap())) ParamList::from(inner.next().unwrap())
} else { } else {
ParamList(HashMap::new()) ParamList(Vec::new())
}; };
let body = Block::from(inner.next().unwrap()); let body = Block::from(inner.next().unwrap());
@@ -136,7 +139,7 @@ impl TryFrom<pest::iterators::Pair<'_, Rule>> for TopLevel {
}; };
let name = inner.next().unwrap().as_str().to_string(); let name = inner.next().unwrap().as_str().to_string();
let fields_pair = inner.next().unwrap(); let fields_pair = inner.next().unwrap();
let fields = ParamList::from((true, fields_pair)); let fields = FieldList::from(fields_pair);
Ok(TopLevel::StructDecl { Ok(TopLevel::StructDecl {
export, export,
@@ -182,28 +185,7 @@ impl From<pest::iterators::Pair<'_, Rule>> for Statement {
Rule::block => Statement::Block(Block::from(pair.into_inner().next().unwrap())), Rule::block => Statement::Block(Block::from(pair.into_inner().next().unwrap())),
Rule::var_decl_statement => { Rule::var_decl_statement => Statement::VarDecl(VarDeclStmt::from(pair)),
let mut inner = pair.into_inner();
let mut var_decl = inner.next().unwrap().into_inner();
let type_ = var_decl.next().map(TypeExpr::try_from).unwrap().ok();
let mutable = if var_decl.peek().unwrap().as_rule() == Rule::mutable {
var_decl.next();
true
} else {
false
};
let name = var_decl.next().unwrap().as_str().to_string();
let init = inner.next().map(Expression::from);
Statement::VarDecl(VarDeclStmt {
mutable,
name: name.as_str().to_string(),
init,
type_,
})
}
Rule::return_stmt => { Rule::return_stmt => {
let mut inner = pair.into_inner(); let mut inner = pair.into_inner();
@@ -348,3 +330,48 @@ impl From<pest::iterators::Pair<'_, Rule>> for Postfix {
} }
} }
} }
impl From<pest::iterators::Pair<'_, Rule>> for VarDeclStmt {
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
match pair.as_rule() {
Rule::var_decl_statement => {
let mut inner = pair.into_inner();
let decl = VarDecl::from(inner.next().unwrap());
let init = inner.next().map(Expression::from);
VarDeclStmt { decl, init }
}
_ => unimplemented!(),
}
}
}
impl From<pest::iterators::Pair<'_, Rule>> for VarDecl {
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
match pair.as_rule() {
Rule::var_decl => {
let mut inner = pair.into_inner();
let type_ = inner.next().map(TypeExpr::try_from).unwrap().ok();
let mutable = if inner.peek().unwrap().as_rule() == Rule::mutable {
inner.next();
true
} else {
false
};
let name = inner.next().unwrap().as_str().to_string();
VarDecl {
mutable,
name: name.as_str().to_string(),
type_,
}
}
_ => unimplemented!("{:?}", pair.as_rule()),
}
}
}
+14 -10
View File
@@ -78,7 +78,15 @@ impl RustCodegen {
let params_str = params let params_str = params
.0 .0
.iter() .iter()
.map(|(n, (_, t))| format!("{}: {}", n, self.translate_type(t))) .map(|v| {
format!(
"{name}{}",
v.type_
.as_ref()
.map(|t| format!(": {}", self.translate_type(t)))
.unwrap_or_default()
)
})
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", "); .join(", ");
@@ -131,15 +139,11 @@ impl RustCodegen {
self.add_indentedln("}"); self.add_indentedln("}");
} }
Statement::VarDecl(VarDeclStmt { Statement::VarDecl(VarDeclStmt { decl, init }) => {
mutable, let mutability = if decl.mutable { "mut " } else { "" };
name,
init,
type_,
}) => {
let mutability = if *mutable { "mut " } else { "" };
let ty = type_ let ty = decl
.type_
.as_ref() .as_ref()
.map(|t| format!(": {}", self.translate_type(t))) .map(|t| format!(": {}", self.translate_type(t)))
.unwrap_or_default(); .unwrap_or_default();
@@ -149,7 +153,7 @@ impl RustCodegen {
.map(|e| format!(" = {}", self.generate_expression(e))) .map(|e| format!(" = {}", self.generate_expression(e)))
.unwrap_or_default(); .unwrap_or_default();
self.add_indentedln(&format!("let {}{}{}{};", mutability, name, ty, init)); self.add_indentedln(&format!("let {}{}{}{};", mutability, decl.name, ty, init));
} }
Statement::VarAssign(VarAssignStmt { target, value }) => { Statement::VarAssign(VarAssignStmt { target, value }) => {
+1 -1
View File
@@ -1,3 +1,3 @@
int test() { int test(int mut b) {
int mut a = 10; int mut a = 10;
} }