use super::Node;
use gc::{Finalize, Trace};
use std::fmt;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Trace, Finalize, PartialEq)]
pub struct If {
cond: Box<Node>,
body: Box<Node>,
else_node: Option<Box<Node>>,
}
impl If {
pub fn cond(&self) -> &Node {
&self.cond
}
pub fn body(&self) -> &Node {
&self.body
}
pub fn else_node(&self) -> Option<&Node> {
self.else_node.as_ref().map(Box::as_ref)
}
pub fn new<C, B, E, OE>(condition: C, body: B, else_node: OE) -> Self
where
C: Into<Node>,
B: Into<Node>,
E: Into<Node>,
OE: Into<Option<E>>,
{
Self {
cond: Box::new(condition.into()),
body: Box::new(body.into()),
else_node: else_node.into().map(E::into).map(Box::new),
}
}
pub(super) fn display(&self, f: &mut fmt::Formatter<'_>, indent: usize) -> fmt::Result {
write!(f, "if ({}) ", self.cond())?;
match self.else_node() {
Some(else_e) => {
self.body().display(f, indent)?;
f.write_str(" else ")?;
else_e.display(f, indent)
}
None => self.body().display(f, indent),
}
}
}
impl fmt::Display for If {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.display(f, 0)
}
}
impl From<If> for Node {
fn from(if_stm: If) -> Node {
Self::If(if_stm)
}
}
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Trace, Finalize, PartialEq)]
pub struct ConditionalOp {
condition: Box<Node>,
if_true: Box<Node>,
if_false: Box<Node>,
}
impl ConditionalOp {
pub fn cond(&self) -> &Node {
&self.condition
}
pub fn if_true(&self) -> &Node {
&self.if_true
}
pub fn if_false(&self) -> &Node {
&self.if_false
}
pub fn new<C, T, F>(condition: C, if_true: T, if_false: F) -> Self
where
C: Into<Node>,
T: Into<Node>,
F: Into<Node>,
{
Self {
condition: Box::new(condition.into()),
if_true: Box::new(if_true.into()),
if_false: Box::new(if_false.into()),
}
}
}
impl fmt::Display for ConditionalOp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} ? {} : {}",
self.cond(),
self.if_true(),
self.if_false()
)
}
}
impl From<ConditionalOp> for Node {
fn from(cond_op: ConditionalOp) -> Node {
Self::ConditionalOp(cond_op)
}
}