use std::fmt::{self, Display, Write};
use crate::{Block, Expr, Formatter};
#[derive(Debug, Clone)]
pub struct IfElse {
cond: Expr,
then: Block,
other: Block,
}
impl IfElse {
pub fn new(cond: &Expr) -> Self {
Self::with_expr(cond.clone())
}
pub fn with_expr(cond: Expr) -> Self {
IfElse {
cond,
then: Block::new(),
other: Block::new(),
}
}
pub fn with_block(cond: Expr, then: Block) -> Self {
IfElse {
cond,
then,
other: Block::new(),
}
}
pub fn set_then(&mut self, then: Block) -> &mut Self {
self.then = then;
self
}
pub fn set_other(&mut self, other: Block) -> &mut Self {
self.other = other;
self
}
pub fn then_branch(&mut self) -> &mut Block {
&mut self.then
}
pub fn other_branch(&mut self) -> &mut Block {
&mut self.other
}
pub fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
write!(fmt, "if (")?;
self.cond.fmt(fmt)?;
write!(fmt, ")")?;
fmt.block(|f| self.then.fmt(f))?;
if !self.other.is_empty() {
write!(fmt, " else ")?;
fmt.block(|f| self.other.fmt(f))?;
}
writeln!(fmt)
}
}
impl Display for IfElse {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut ret = String::new();
self.fmt(&mut Formatter::new(&mut ret)).unwrap();
write!(f, "{ret}")
}
}