Refactored for loops

This commit is contained in:
2026-05-05 16:30:41 +02:00
parent ec45c24854
commit 0d00ebcd2c
3 changed files with 32 additions and 37 deletions
+6 -9
View File
@@ -106,7 +106,12 @@ pub enum Statement {
else_branch: Option<Box<Statement>>, else_branch: Option<Box<Statement>>,
}, },
While(StatementBranch), While(StatementBranch),
For(ForStmt), CStyleFor {
init: Box<Statement>,
condition: Box<Expression>,
update: Box<Statement>,
body: Box<Statement>,
},
Return(Option<Expression>), Return(Option<Expression>),
Break, Break,
@@ -138,14 +143,6 @@ pub struct StatementBranch {
pub body: Box<Statement>, pub body: Box<Statement>,
} }
#[derive(Debug, Clone, Serialize)]
pub struct ForStmt {
pub init: (bool, String, Option<Expression>),
pub condition: Option<Expression>,
pub update: Option<Box<Statement>>,
pub body: Box<Statement>,
}
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
pub enum Expression { pub enum Expression {
Literal(Literal), Literal(Literal),
+25 -2
View File
@@ -390,8 +390,31 @@ impl ToRust for Statement {
cg.ensure_brackets(body); cg.ensure_brackets(body);
} }
Statement::For { .. } => { Statement::CStyleFor {
cg.add_indentedln("// TODO: transform into iterator-based loop"); init,
condition,
update,
body,
} => {
cg.add_indentedln("{");
cg.indent += 1;
init.to_rust(cg);
cg.add_indentedln(&format!("while {}", condition.get_rust()));
cg.add_indentedln("{");
cg.indent += 1;
cg.ensure_brackets(body);
update.to_rust(cg);
cg.indent -= 1;
cg.add_indentedln("}");
cg.indent -= 1;
cg.add_indentedln("}");
} }
Statement::Return(expr) => { Statement::Return(expr) => {
+1 -26
View File
@@ -1,28 +1,3 @@
#![allow(unused_mut)]
#[derive(Debug)]
public struct ApiCall {
i32 x,
i32 y,
}
void main() { void main() {
ApiCall mut call = ApiCall { x: 10, y: 12 };
if (call.x == 20) {
println!("= 20");
} else if (call.x == 10) {
println!("= 10");
} else if (call.x == 5) {
println!("= 5");
} else {
println!("= unknown");
}
while (call.x <= 40) {
call.x = call.x - 1;
println!("while");
}
println!("{call:?}");
} }