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;
#[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)]
pub struct Block(pub Vec<Statement>);
@@ -34,7 +37,7 @@ pub enum TopLevel {
StructDecl {
export: bool,
name: String,
fields: ParamList,
fields: FieldList,
},
FunctionDecl {
export: bool,
@@ -71,13 +74,18 @@ pub enum Statement {
}
#[derive(Debug, Clone, Serialize)]
pub struct VarDeclStmt {
pub struct VarDecl {
pub mutable: bool,
pub name: String,
pub init: Option<Expression>,
pub type_: Option<TypeExpr>,
}
#[derive(Debug, Clone, Serialize)]
pub struct VarDeclStmt {
pub decl: VarDecl,
pub init: Option<Expression>,
}
#[derive(Debug, Clone, Serialize)]
pub struct VarAssignStmt {
pub target: Expression,
+65 -38
View File
@@ -1,5 +1,3 @@
use std::collections::HashMap;
use pest::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> {
let mut pairs = MistParser::parse(Rule::program, source)?;
println!("{pairs:#?}");
let mut statements = vec![];
for pair in pairs.next().unwrap().into_inner() {
@@ -49,25 +45,32 @@ impl TryFrom<pest::iterators::Pair<'_, Rule>> for TypeExpr {
}
}
impl From<(bool, pest::iterators::Pair<'_, Rule>)> for ParamList {
fn from((export_allowed, pair): (bool, pest::iterators::Pair<Rule>)) -> Self {
impl From<pest::iterators::Pair<'_, Rule>> for FieldList {
fn from(pair: pest::iterators::Pair<Rule>) -> Self {
let params = pair
.into_inner()
.map(|p| {
let mut param_inner = p.into_inner();
let export =
if export_allowed && param_inner.peek().unwrap().as_rule() == Rule::export {
param_inner.next().unwrap();
true
} else {
false
};
let export = if param_inner.peek().unwrap().as_rule() == Rule::export {
param_inner.next().unwrap();
true
} else {
false
};
let param_type = TypeExpr::try_from(param_inner.next().unwrap()).unwrap();
let param_name = param_inner.next().unwrap().as_str().to_string();
(param_name, (export, param_type))
})
.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)
}
}
@@ -106,9 +109,9 @@ impl TryFrom<pest::iterators::Pair<'_, Rule>> for TopLevel {
let name = inner.next().unwrap().as_str().to_string();
let params = if inner.peek().unwrap().as_rule() == Rule::param_list {
ParamList::from((false, inner.next().unwrap()))
ParamList::from(inner.next().unwrap())
} else {
ParamList(HashMap::new())
ParamList(Vec::new())
};
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 fields_pair = inner.next().unwrap();
let fields = ParamList::from((true, fields_pair));
let fields = FieldList::from(fields_pair);
Ok(TopLevel::StructDecl {
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::var_decl_statement => {
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::var_decl_statement => Statement::VarDecl(VarDeclStmt::from(pair)),
Rule::return_stmt => {
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
.0
.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<_>>()
.join(", ");
@@ -131,15 +139,11 @@ impl RustCodegen {
self.add_indentedln("}");
}
Statement::VarDecl(VarDeclStmt {
mutable,
name,
init,
type_,
}) => {
let mutability = if *mutable { "mut " } else { "" };
Statement::VarDecl(VarDeclStmt { decl, init }) => {
let mutability = if decl.mutable { "mut " } else { "" };
let ty = type_
let ty = decl
.type_
.as_ref()
.map(|t| format!(": {}", self.translate_type(t)))
.unwrap_or_default();
@@ -149,7 +153,7 @@ impl RustCodegen {
.map(|e| format!(" = {}", self.generate_expression(e)))
.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 }) => {
+1 -1
View File
@@ -1,3 +1,3 @@
int test() {
int test(int mut b) {
int mut a = 10;
}