toasty_core/stmt/
condition.rs

1use crate::stmt::{Expr, Node, Statement, Visit, VisitMut};
2
3#[derive(Debug, Default, Clone, PartialEq)]
4pub struct Condition {
5    pub expr: Option<Expr>,
6}
7
8impl Condition {
9    pub fn new(expr: impl Into<Expr>) -> Condition {
10        Condition {
11            expr: Some(expr.into()),
12        }
13    }
14
15    pub fn is_some(&self) -> bool {
16        self.expr.is_some()
17    }
18
19    pub fn is_none(&self) -> bool {
20        self.expr.is_none()
21    }
22}
23
24impl Statement {
25    pub fn condition(&self) -> Option<&Condition> {
26        match self {
27            Statement::Update(update) if update.condition.is_some() => Some(&update.condition),
28            _ => None,
29        }
30    }
31
32    /// Returns a mutable reference to the statement's condition.
33    ///
34    /// Returns `None` for statements that do not support conditions.
35    pub fn condition_mut(&mut self) -> Option<&mut Condition> {
36        match self {
37            Statement::Update(update) => Some(&mut update.condition),
38            _ => None,
39        }
40    }
41
42    /// Returns a mutable reference to the statement's condition.
43    ///
44    /// # Panics
45    ///
46    /// Panics if the statement does not support conditions.
47    #[track_caller]
48    pub fn condition_mut_unwrap(&mut self) -> &mut Condition {
49        match self {
50            Statement::Update(update) => &mut update.condition,
51            _ => panic!("expected Statement with condition"),
52        }
53    }
54}
55
56impl Node for Condition {
57    fn visit<V: Visit>(&self, mut visit: V) {
58        visit.visit_condition(self);
59    }
60
61    fn visit_mut<V: VisitMut>(&mut self, mut visit: V) {
62        visit.visit_condition_mut(self);
63    }
64}
65
66impl<T> From<T> for Condition
67where
68    Expr: From<T>,
69{
70    fn from(value: T) -> Self {
71        Condition {
72            expr: Some(value.into()),
73        }
74    }
75}