use super::expression::Expr;
use super::statement::Block;
#[derive(Debug, Clone, PartialEq)]
pub enum ControlFlow {
If {
condition: Expr,
then_branch: Block,
else_branch: Option<Block>,
},
While { condition: Expr, body: Block },
DoWhile { body: Block, condition: Expr },
For {
init: Option<Box<super::statement::Stmt>>,
condition: Option<Expr>,
update: Option<Expr>,
body: Block,
},
TryCatch {
try_body: Block,
catch_var: Option<String>,
catch_body: Option<Block>,
finally_body: Option<Block>,
},
Switch {
expr: Expr,
cases: Vec<(Expr, Block)>,
default: Option<Block>,
},
}
impl ControlFlow {
#[must_use]
pub fn if_then(condition: Expr, then_branch: Block) -> Self {
ControlFlow::If {
condition,
then_branch,
else_branch: None,
}
}
#[must_use]
pub fn if_else(condition: Expr, then_branch: Block, else_branch: Block) -> Self {
ControlFlow::If {
condition,
then_branch,
else_branch: Some(else_branch),
}
}
#[must_use]
pub fn while_loop(condition: Expr, body: Block) -> Self {
ControlFlow::While { condition, body }
}
#[must_use]
pub fn do_while(body: Block, condition: Expr) -> Self {
ControlFlow::DoWhile { body, condition }
}
pub fn for_loop(
init: Option<super::statement::Stmt>,
condition: Option<Expr>,
update: Option<Expr>,
body: Block,
) -> Self {
ControlFlow::For {
init: init.map(Box::new),
condition,
update,
body,
}
}
#[must_use]
pub fn try_catch(
try_body: Block,
catch_var: Option<String>,
catch_body: Option<Block>,
finally_body: Option<Block>,
) -> Self {
ControlFlow::TryCatch {
try_body,
catch_var,
catch_body,
finally_body,
}
}
}