Skip to main content

microcad_lang/lower/ir/expression/
mod.rs

1// Copyright © 2024-2026 The µcad authors <info@microcad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! µcad syntax elements related to expressions
5
6use crate::lower::{SingleIdentifier, ir};
7
8mod array_expression;
9mod marker;
10mod range_expression;
11mod tuple_expression;
12
13pub use array_expression::*;
14pub use marker::*;
15pub use range_expression::*;
16pub use tuple_expression::*;
17
18use microcad_lang_base::{Identifier, Refer, SrcRef, SrcReferrer};
19use microcad_lang_proc_macros::SrcReferrer;
20
21/// List of expressions.
22pub type ListExpression<EXPR = ir::Expression> = Vec<EXPR>;
23
24/// If statement.
25#[derive(Clone, Debug, SrcReferrer)]
26pub struct If<BODY = ir::Body> {
27    /// SrcRef of the `if` keyword.
28    pub if_ref: SrcRef,
29    /// If condition.
30    pub cond: ir::Expression,
31    /// Body if `true`.
32    pub body: BODY,
33    /// SrcRef of the `else` keyword, if present.
34    pub else_ref: Option<SrcRef>,
35    /// Body if `false`.
36    pub body_else: Option<BODY>,
37    /// SrcRef of the `else[ if]` keyword, if present.
38    pub next_if_ref: Option<SrcRef>,
39    /// Next if statement: `else if x == 1`.
40    pub next_if: Option<Box<If<BODY>>>,
41    /// Source code reference.
42    pub src_ref: SrcRef,
43}
44
45impl std::fmt::Display for If {
46    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
47        writeln!(f, "if {cond} {body}", cond = self.cond, body = self.body)?;
48        if let Some(next) = &self.next_if {
49            writeln!(f, "else {next}")?;
50        }
51        if let Some(body) = &self.body_else {
52            writeln!(f, "else {body}")?;
53        }
54        Ok(())
55    }
56}
57
58/// Any expression.
59#[derive(Clone, Debug, Default)]
60pub enum Expression {
61    /// Something went wrong (and an error will be reported)
62    #[default]
63    Invalid,
64    /// An integer, float, color or bool literal: 1, 1.0, #00FF00, false
65    Literal(ir::Literal),
66    /// A string that contains format expressions: "value = {a}"
67    FormatString(ir::FormatString),
68    /// A list: [a, b, c]
69    ArrayExpression(ArrayExpression),
70    /// A tuple: (a, b, c)
71    TupleExpression(TupleExpression),
72    /// A body: `{}`.
73    Body(ir::Body),
74    /// An if statement: `if {} else {}`.
75    If(Box<ir::If<ir::Body>>),
76    /// A call: `ops::subtract()`.
77    Call(ir::Call),
78    /// A qualified name: `foo::bar`.
79    QualifiedName(ir::QualifiedName),
80    /// A marker expression: `@input`.
81    Marker(Marker),
82    /// A binary operation: `a + b`
83    BinaryOp(BinaryOp),
84    /// A unary operation: !a
85    UnaryOp(UnaryOp),
86    /// Access an element of a list (`a[0]`) or a tuple (`a.0` or `a.b`)
87    ArrayElementAccess(Box<Expression>, Box<Expression>, SrcRef),
88    /// Access an element of a tuple: `a.b`.
89    PropertyAccess(Box<Expression>, Identifier, SrcRef),
90
91    /// Access an attribute of a model: `a#b`.
92    AttributeAccess(Box<Expression>, Identifier, SrcRef),
93
94    /// Call to a method: `[2,3].len()`
95    /// First expression must evaluate to a value
96    MethodCall(Box<Expression>, ir::MethodCall, SrcRef),
97}
98
99/// A binary operation: `a + b`
100#[derive(Clone, Debug)]
101pub struct BinaryOp<EXPR = ir::Expression> {
102    /// Left-hand side
103    pub lhs: Box<EXPR>,
104    /// Operator  ('+', '-', '/', '*', '<', '>', '≤', '≥', '&', '|')
105    pub op: Refer<String>,
106    /// Right -hand side
107    pub rhs: Box<EXPR>,
108    /// Source code reference
109    pub src_ref: SrcRef,
110}
111
112impl<EXPR> SrcReferrer for BinaryOp<EXPR> {
113    fn src_ref(&self) -> SrcRef {
114        self.src_ref
115    }
116}
117
118impl SingleIdentifier for BinaryOp {
119    fn single_identifier(&self) -> Option<&Identifier> {
120        match (self.lhs.single_identifier(), self.rhs.single_identifier()) {
121            (None, Some(lhs)) => Some(lhs),
122            (Some(rhs), None) => Some(rhs),
123            (Some(lhs), Some(rhs)) => {
124                if lhs == rhs {
125                    Some(lhs)
126                } else {
127                    None
128                }
129            }
130            _ => None,
131        }
132    }
133}
134
135impl<EXPR> std::fmt::Display for BinaryOp<EXPR>
136where
137    EXPR: std::fmt::Display,
138{
139    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140        write!(
141            f,
142            "{lhs} {op} {rhs}",
143            lhs = self.lhs,
144            op = self.op,
145            rhs = self.rhs
146        )
147    }
148}
149
150/// A unary operation: !a
151#[derive(Clone, Debug)]
152pub struct UnaryOp<EXPR = ir::Expression> {
153    /// Operator ('+', '-', '!')
154    pub op: Refer<String>,
155    /// Right -hand side
156    pub rhs: Box<EXPR>,
157    /// Source code reference
158    pub src_ref: SrcRef,
159}
160
161impl<EXPR> SrcReferrer for UnaryOp<EXPR> {
162    fn src_ref(&self) -> SrcRef {
163        self.src_ref
164    }
165}
166
167impl SingleIdentifier for UnaryOp {
168    fn single_identifier(&self) -> Option<&Identifier> {
169        self.rhs.single_identifier()
170    }
171}
172
173impl<EXPR> std::fmt::Display for UnaryOp<EXPR>
174where
175    EXPR: std::fmt::Display,
176{
177    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178        write!(f, "{op}{rhs}", op = self.op, rhs = self.rhs)
179    }
180}
181
182/// An expression that can be evaluated during `resolve` phase.
183///
184/// Use for `Constant` and default values for `Parameter`.
185#[derive(Debug, derive_more::From)]
186pub enum ConstantExpression {
187    Invalid,
188    Literal(ir::Literal),
189    Call(ir::Call<ConstantExpression>),
190    QualifiedName(ir::QualifiedName),
191    FormatString(ir::FormatString),
192    ArrayExpression(ir::ArrayExpression<ConstantExpression>),
193    TupleExpression(ir::TupleExpression<ConstantExpression>),
194    BinaryOp(ir::BinaryOp<ConstantExpression>),
195    UnaryOp(ir::UnaryOp<ConstantExpression>),
196    //ArrayElementAccess(Box<Expression>, Box<Expression>, SrcRef),
197}
198
199impl crate::lower::SingleIdentifier for Expression {
200    /// If the expression includes just one identifier, e.g. `a` or `a * (a + 2)`
201    fn single_identifier(&self) -> Option<&Identifier> {
202        match &self {
203            Expression::Invalid
204            | Expression::Literal(..)
205            | Expression::FormatString(..)
206            | Expression::Marker(..)
207            | Expression::PropertyAccess(..)
208            | Expression::AttributeAccess(..)
209            | Expression::MethodCall(..)
210            | Expression::ArrayExpression(..)
211            | Expression::TupleExpression(..)
212            | Expression::Body(..)
213            | Expression::If(..)
214            | Expression::Call(..) => None,
215
216            Expression::QualifiedName(qualified_name) => qualified_name.single_identifier(),
217            Expression::BinaryOp(binary_op) => binary_op.single_identifier(),
218            Expression::UnaryOp(unary_op) => unary_op.single_identifier(),
219            Expression::ArrayElementAccess(expression, ..) => expression.single_identifier(),
220        }
221    }
222}
223
224impl SrcReferrer for Expression {
225    fn src_ref(&self) -> SrcRef {
226        match self {
227            Self::Invalid => SrcRef::none(),
228            Self::Literal(l) => l.src_ref(),
229            Self::FormatString(fs) => fs.src_ref(),
230            Self::ArrayExpression(le) => le.src_ref(),
231            Self::TupleExpression(te) => te.src_ref(),
232            Self::Call(c) => c.src_ref(),
233            Self::Body(b) => b.src_ref(),
234            Self::If(i) => i.src_ref(),
235            Self::QualifiedName(q) => q.src_ref(),
236            Self::Marker(m) => m.src_ref(),
237            Self::BinaryOp(binary_op) => binary_op.src_ref(),
238            Self::UnaryOp(unary_op) => unary_op.src_ref(),
239            Self::ArrayElementAccess(_, _, src_ref) => *src_ref,
240            Self::PropertyAccess(_, _, src_ref) => *src_ref,
241            Self::AttributeAccess(_, _, src_ref) => *src_ref,
242            Self::MethodCall(_, _, src_ref) => *src_ref,
243        }
244    }
245}
246
247impl std::fmt::Display for Expression {
248    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
249        match self {
250            Self::Literal(literal) => write!(f, "{literal}"),
251            Self::FormatString(format_string) => write!(f, "{format_string}"),
252            Self::ArrayExpression(array_expression) => write!(f, "{array_expression}"),
253            Self::TupleExpression(tuple_expression) => write!(f, "{tuple_expression}"),
254            Self::BinaryOp(binary_op) => write!(f, "{binary_op}"),
255            Self::UnaryOp(unary_op) => write!(f, "{unary_op}"),
256            Self::ArrayElementAccess(lhs, rhs, _) => write!(f, "{lhs}[{rhs}]"),
257            Self::PropertyAccess(lhs, rhs, _) => write!(f, "{lhs}.{rhs}"),
258            Self::AttributeAccess(lhs, rhs, _) => write!(f, "{lhs}#{rhs}"),
259            Self::MethodCall(lhs, method_call, _) => write!(f, "{lhs}.{method_call}"),
260            Self::Call(call) => write!(f, "{call}"),
261            Self::Body(body) => write!(f, "{body}"),
262            Self::If(if_) => write!(f, "{if_}"),
263            Self::QualifiedName(qualified_name) => write!(f, "{qualified_name}"),
264            Self::Marker(marker) => write!(f, "{marker}"),
265            _ => unimplemented!(),
266        }
267    }
268}
269
270/*impl PartialEq for Expression {
271    fn eq(&self, other: &Self) -> bool {
272        match (self, other) {
273            (Self::Literal(l0), Self::Literal(r0)) => l0 == r0,
274            (Self::FormatString(l0), Self::FormatString(r0)) => l0 == r0,
275            (Self::ArrayExpression(l0), Self::ArrayExpression(r0)) => l0 == r0,
276            (Self::TupleExpression(l0), Self::TupleExpression(r0)) => l0 == r0,
277            (Self::QualifiedName(l0), Self::QualifiedName(r0)) => l0 == r0,
278            (
279                Self::BinaryOp {
280                    lhs: l_lhs,
281                    op: l_op,
282                    rhs: l_rhs,
283                    src_ref: l_src_ref,
284                },
285                Self::BinaryOp {
286                    lhs: r_lhs,
287                    op: r_op,
288                    rhs: r_rhs,
289                    src_ref: r_src_ref,
290                },
291            ) => l_lhs == r_lhs && l_op == r_op && l_rhs == r_rhs && l_src_ref == r_src_ref,
292            (
293                Self::UnaryOp {
294                    op: l_op,
295                    rhs: l_rhs,
296                    src_ref: l_src_ref,
297                },
298                Self::UnaryOp {
299                    op: r_op,
300                    rhs: r_rhs,
301                    src_ref: r_src_ref,
302                },
303            ) => l_op == r_op && l_rhs == r_rhs && l_src_ref == r_src_ref,
304            (Self::ArrayElementAccess(l0, l1, l2), Self::ArrayElementAccess(r0, r1, r2)) => {
305                l0 == r0 && l1 == r1 && l2 == r2
306            }
307            _ => unreachable!("PartialEq implemented for const expressions only"),
308        }
309    }
310}*/