toasty_core/stmt/expr_cast.rs
1use super::{Expr, Type};
2
3/// A type cast expression.
4///
5/// Converts an expression's value to a different type.
6///
7/// # Examples
8///
9/// ```text
10/// cast(x, i64) // cast `x` to `i64`
11/// cast(y, string) // cast `y` to `string`
12/// ```
13#[derive(Debug, Clone, PartialEq)]
14pub struct ExprCast {
15 /// The expression to cast.
16 pub expr: Box<Expr>,
17
18 /// The source type, when the value alone cannot direct the conversion.
19 ///
20 /// Most casts are directed by the target type and the value's own shape,
21 /// and leave this `None`. The exception is a `#[document]` column's
22 /// lowering cast (`Type::Model` → `Type::Object`): the structural target
23 /// does not name the embedded model and a positional `Value::Record` is
24 /// not self-describing, so the cast carries the model-level source type
25 /// to resolve the embed's field names.
26 pub from: Option<Type>,
27
28 /// The target type.
29 pub ty: Type,
30}
31
32impl Expr {
33 /// Creates a type cast expression that converts `expr` to the target type.
34 pub fn cast(expr: impl Into<Self>, ty: impl Into<Type>) -> Self {
35 ExprCast {
36 expr: Box::new(expr.into()),
37 from: None,
38 ty: ty.into(),
39 }
40 .into()
41 }
42
43 /// Creates a type cast expression whose conversion is directed by the
44 /// source type as well as the target type. See [`ExprCast::from`].
45 pub fn cast_from(expr: impl Into<Self>, from: impl Into<Type>, ty: impl Into<Type>) -> Self {
46 ExprCast {
47 expr: Box::new(expr.into()),
48 from: Some(from.into()),
49 ty: ty.into(),
50 }
51 .into()
52 }
53
54 /// Returns `true` if this expression is a type cast.
55 pub fn is_cast(&self) -> bool {
56 matches!(self, Self::Cast(_))
57 }
58}
59
60impl From<ExprCast> for Expr {
61 fn from(value: ExprCast) -> Self {
62 Self::Cast(value)
63 }
64}