toasty_core/stmt/
expr_match.rs

1use super::{Expr, Value};
2
3/// A match expression that dispatches on a subject expression.
4///
5/// Each arm matches the subject against a constant value pattern and evaluates
6/// the corresponding expression. `Expr::Match` is never serialized to SQL -- it
7/// is either evaluated in the engine (for writes) or eliminated by the
8/// simplifier before the plan stage (for reads/queries).
9///
10/// # Examples
11///
12/// ```text
13/// match discriminant {
14///   I64(0) => "active",
15///   I64(1) => "inactive",
16///   _      => error("unknown variant"),
17/// }
18/// ```
19#[derive(Debug, Clone, PartialEq)]
20pub struct ExprMatch {
21    /// The expression to dispatch on.
22    pub subject: Box<Expr>,
23
24    /// The match arms, in order.
25    pub arms: Vec<MatchArm>,
26
27    /// Fallback expression evaluated when no arm matches.
28    pub else_expr: Box<Expr>,
29}
30
31/// A single arm in a match expression.
32#[derive(Debug, Clone, PartialEq)]
33pub struct MatchArm {
34    /// The constant value pattern this arm matches against.
35    pub pattern: Value,
36
37    /// The expression to evaluate when the pattern matches.
38    pub expr: Expr,
39}
40
41impl Expr {
42    /// Creates a `Match` expression that dispatches on `subject`.
43    pub fn match_expr(
44        subject: impl Into<Self>,
45        arms: Vec<MatchArm>,
46        else_expr: impl Into<Self>,
47    ) -> Self {
48        ExprMatch {
49            subject: Box::new(subject.into()),
50            arms,
51            else_expr: Box::new(else_expr.into()),
52        }
53        .into()
54    }
55}
56
57impl From<ExprMatch> for Expr {
58    fn from(value: ExprMatch) -> Self {
59        Self::Match(value)
60    }
61}