Refactor: If statement

This commit is contained in:
2026-05-05 15:55:24 +02:00
parent 6125ecfde4
commit 95c4826b5f
2 changed files with 31 additions and 21 deletions
+5 -1
View File
@@ -86,8 +86,12 @@ var_decl_statement = { var_decl ~ ("=" ~ expr)? ~ ";" }
assign_statement = { expr ~ "=" ~ expr ~ ";" }
else_if = { "else" ~ "if" ~ "(" ~ expr ~ ")" ~ statement }
else_if_list = { else_if* }
if_stmt = {
"if" ~ "(" ~ expr ~ ")" ~ statement ~ ("else" ~ statement)?
"if" ~ "(" ~ expr ~ ")" ~ statement ~ else_if_list ~ ("else" ~ statement)?
}
while_stmt = {
+26 -20
View File
@@ -196,6 +196,20 @@ impl From<pest::iterators::Pair<'_, Rule>> for TopLevel {
}
}
impl From<pest::iterators::Pair<'_, Rule>> for StatementBranch {
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
let mut inner = pair.into_inner();
let condition = Expression::from(inner.next().unwrap());
let body = Statement::from(inner.next().unwrap());
StatementBranch {
condition,
body: Box::new(body),
}
}
}
impl From<pest::iterators::Pair<'_, Rule>> for TopLevelKind {
fn from(pair: pest::iterators::Pair<'_, Rule>) -> Self {
let rule = pair.as_rule();
@@ -303,29 +317,21 @@ impl From<pest::iterators::Pair<'_, Rule>> for Statement {
Rule::continue_stmt => Statement::Continue,
Rule::if_stmt => {
let condition = Expression::from(inner.next().unwrap());
let then_branch = Statement::from(inner.next().unwrap());
let mut inner = inner.skip(2);
let else_branch = inner.next().map(Statement::from);
Statement::Break
// Statement::If(IfStmt {
// condition,
// then_branch: Box::new(then_branch),
// else_branch: else_branch.map(Box::new),
// })
Statement::If {
initial: pair.into(),
else_if: inner
.next()
.unwrap()
.into_inner()
.map(StatementBranch::from)
.collect(),
else_branch: inner.next().map(Statement::from).map(Box::new),
}
}
Rule::while_stmt => {
let condition = Expression::from(inner.next().unwrap());
let body = Statement::from(inner.next().unwrap());
Statement::While(StatementBranch {
condition,
body: Box::new(body),
})
}
Rule::while_stmt => Statement::While(pair.into()),
Rule::assign_statement => Statement::VarAssign(VarAssignStmt {
target: Expression::from(inner.next().unwrap()),