Skip to main content

leo_ast/expressions/
mod.rs

1// Copyright (C) 2019-2026 Provable Inc.
2// This file is part of the Leo library.
3
4// The Leo library is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// The Leo library is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
16
17use crate::{Identifier, IntegerType, Intrinsic, Location, Mode, Node, NodeBuilder, NodeID, Path, Type};
18use leo_span::{Span, Symbol};
19
20use serde::{Deserialize, Serialize};
21use std::fmt;
22
23mod array_access;
24pub use array_access::*;
25
26mod async_;
27pub use async_::*;
28
29mod array;
30pub use array::*;
31
32mod binary;
33pub use binary::*;
34
35mod call;
36pub use call::*;
37
38mod cast;
39pub use cast::*;
40
41mod composite_init;
42pub use composite_init::*;
43
44mod dynamic_call;
45pub use dynamic_call::*;
46
47mod err;
48pub use err::*;
49
50mod member_access;
51pub use member_access::*;
52
53mod intrinsic;
54pub use intrinsic::*;
55
56mod repeat;
57pub use repeat::*;
58
59mod ternary;
60pub use ternary::*;
61
62mod tuple;
63pub use tuple::*;
64
65mod tuple_access;
66pub use tuple_access::*;
67
68mod unary;
69pub use unary::*;
70
71mod unit;
72pub use unit::*;
73
74mod literal;
75pub use literal::*;
76
77/// Expression that evaluates to a value.
78#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
79pub enum Expression {
80    /// An array access, e.g. `arr[i]`.
81    ArrayAccess(Box<ArrayAccess>),
82    /// An `async` block: e.g. `async { my_mapping.set(1, 2); }`.
83    Async(AsyncExpression),
84    /// An array expression, e.g., `[true, false, true, false]`.
85    Array(ArrayExpression),
86    /// A binary expression, e.g., `42 + 24`.
87    Binary(Box<BinaryExpression>),
88    /// An intrinsic expression, e.g., `_my_intrinsic(args)`.
89    Intrinsic(Box<IntrinsicExpression>),
90    /// A call expression, e.g., `my_fun(args)`.
91    Call(Box<CallExpression>),
92    /// A dynamic call expression, e.g., `MyInterface @ (target) :: foobar(args)`.
93    DynamicCall(Box<DynamicCallExpression>),
94    /// A cast expression, e.g., `42u32 as u8`.
95    Cast(Box<CastExpression>),
96    /// An expression of type "error".
97    /// Will result in a compile error eventually.
98    /// An expression constructing a composite like `Foo { bar: 42, baz }`.
99    Composite(CompositeExpression),
100    Err(ErrExpression),
101    /// A path to some item, e.g., `foo::bar::x`.
102    Path(Path),
103    /// A literal expression.
104    Literal(Literal),
105    /// An access of a composite member, e.g. `composite.member`.
106    MemberAccess(Box<MemberAccess>),
107    /// An array expression constructed from one repeated element, e.g., `[1u32; 5]`.
108    Repeat(Box<RepeatExpression>),
109    /// A ternary conditional expression `cond ? if_expr : else_expr`.
110    Ternary(Box<TernaryExpression>),
111    /// A tuple expression e.g., `(foo, 42, true)`.
112    Tuple(TupleExpression),
113    /// A tuple access expression e.g., `foo.2`.
114    TupleAccess(Box<TupleAccess>),
115    /// An unary expression.
116    Unary(Box<UnaryExpression>),
117    /// A unit expression e.g. `()`
118    Unit(UnitExpression),
119}
120
121impl Default for Expression {
122    fn default() -> Self {
123        Expression::Err(Default::default())
124    }
125}
126
127impl Node for Expression {
128    fn span(&self) -> Span {
129        use Expression::*;
130        match self {
131            ArrayAccess(n) => n.span(),
132            Array(n) => n.span(),
133            Async(n) => n.span(),
134            Binary(n) => n.span(),
135            Call(n) => n.span(),
136            DynamicCall(n) => n.span(),
137            Cast(n) => n.span(),
138            Composite(n) => n.span(),
139            Err(n) => n.span(),
140            Intrinsic(n) => n.span(),
141            Path(n) => n.span(),
142            Literal(n) => n.span(),
143            MemberAccess(n) => n.span(),
144            Repeat(n) => n.span(),
145            Ternary(n) => n.span(),
146            Tuple(n) => n.span(),
147            TupleAccess(n) => n.span(),
148            Unary(n) => n.span(),
149            Unit(n) => n.span(),
150        }
151    }
152
153    fn set_span(&mut self, span: Span) {
154        use Expression::*;
155        match self {
156            ArrayAccess(n) => n.set_span(span),
157            Array(n) => n.set_span(span),
158            Async(n) => n.set_span(span),
159            Binary(n) => n.set_span(span),
160            Call(n) => n.set_span(span),
161            DynamicCall(n) => n.set_span(span),
162            Cast(n) => n.set_span(span),
163            Composite(n) => n.set_span(span),
164            Err(n) => n.set_span(span),
165            Intrinsic(n) => n.set_span(span),
166            Path(n) => n.set_span(span),
167            Literal(n) => n.set_span(span),
168            MemberAccess(n) => n.set_span(span),
169            Repeat(n) => n.set_span(span),
170            Ternary(n) => n.set_span(span),
171            Tuple(n) => n.set_span(span),
172            TupleAccess(n) => n.set_span(span),
173            Unary(n) => n.set_span(span),
174            Unit(n) => n.set_span(span),
175        }
176    }
177
178    fn id(&self) -> NodeID {
179        use Expression::*;
180        match self {
181            Array(n) => n.id(),
182            ArrayAccess(n) => n.id(),
183            Async(n) => n.id(),
184            Binary(n) => n.id(),
185            Call(n) => n.id(),
186            DynamicCall(n) => n.id(),
187            Cast(n) => n.id(),
188            Composite(n) => n.id(),
189            Path(n) => n.id(),
190            Literal(n) => n.id(),
191            MemberAccess(n) => n.id(),
192            Repeat(n) => n.id(),
193            Err(n) => n.id(),
194            Intrinsic(n) => n.id(),
195            Ternary(n) => n.id(),
196            Tuple(n) => n.id(),
197            TupleAccess(n) => n.id(),
198            Unary(n) => n.id(),
199            Unit(n) => n.id(),
200        }
201    }
202
203    fn set_id(&mut self, id: NodeID) {
204        use Expression::*;
205        match self {
206            Array(n) => n.set_id(id),
207            ArrayAccess(n) => n.set_id(id),
208            Async(n) => n.set_id(id),
209            Binary(n) => n.set_id(id),
210            Call(n) => n.set_id(id),
211            DynamicCall(n) => n.set_id(id),
212            Cast(n) => n.set_id(id),
213            Composite(n) => n.set_id(id),
214            Path(n) => n.set_id(id),
215            Literal(n) => n.set_id(id),
216            MemberAccess(n) => n.set_id(id),
217            Repeat(n) => n.set_id(id),
218            Err(n) => n.set_id(id),
219            Intrinsic(n) => n.set_id(id),
220            Ternary(n) => n.set_id(id),
221            Tuple(n) => n.set_id(id),
222            TupleAccess(n) => n.set_id(id),
223            Unary(n) => n.set_id(id),
224            Unit(n) => n.set_id(id),
225        }
226    }
227}
228
229impl fmt::Display for Expression {
230    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
231        use Expression::*;
232        match &self {
233            Array(n) => n.fmt(f),
234            ArrayAccess(n) => n.fmt(f),
235            Async(n) => n.fmt(f),
236            Binary(n) => n.fmt(f),
237            Call(n) => n.fmt(f),
238            DynamicCall(n) => n.fmt(f),
239            Cast(n) => n.fmt(f),
240            Composite(n) => n.fmt(f),
241            Err(n) => n.fmt(f),
242            Intrinsic(n) => n.fmt(f),
243            Path(n) => n.fmt(f),
244            Literal(n) => n.fmt(f),
245            MemberAccess(n) => n.fmt(f),
246            Repeat(n) => n.fmt(f),
247            Ternary(n) => n.fmt(f),
248            Tuple(n) => n.fmt(f),
249            TupleAccess(n) => n.fmt(f),
250            Unary(n) => n.fmt(f),
251            Unit(n) => n.fmt(f),
252        }
253    }
254}
255
256#[derive(Clone, Copy, Eq, PartialEq)]
257pub(crate) enum Associativity {
258    Left,
259    Right,
260    None,
261}
262
263impl Expression {
264    pub(crate) fn precedence(&self) -> u32 {
265        use Expression::*;
266        match self {
267            Binary(e) => e.precedence(),
268            Cast(_) => 12,
269            Ternary(_) => 0,
270            Array(_) | ArrayAccess(_) | Async(_) | Call(_) | DynamicCall(_) | Composite(_) | Err(_) | Intrinsic(_)
271            | Path(_) | Literal(_) | MemberAccess(_) | Repeat(_) | Tuple(_) | TupleAccess(_) | Unary(_) | Unit(_) => 20,
272        }
273    }
274
275    pub(crate) fn associativity(&self) -> Associativity {
276        if let Expression::Binary(bin) = self { bin.associativity() } else { Associativity::None }
277    }
278
279    /// Returns `self` as a known `u32` if possible. Otherwise, returns a `None`. This allows for large and/or signed
280    /// types but only if they can be safely cast to a `u32`.
281    pub fn as_u32(&self) -> Option<u32> {
282        if let Expression::Literal(literal) = &self {
283            if let LiteralVariant::Integer(int_type, s, ..) = &literal.variant {
284                use crate::IntegerType::*;
285                let s = s.replace("_", "");
286
287                return match int_type {
288                    U8 => u8::from_str_by_radix(&s).map(|v| v as u32).ok(),
289                    U16 => u16::from_str_by_radix(&s).map(|v| v as u32).ok(),
290                    U32 => u32::from_str_by_radix(&s).ok(),
291                    U64 => u64::from_str_by_radix(&s).ok().and_then(|v| u32::try_from(v).ok()),
292                    U128 => u128::from_str_by_radix(&s).ok().and_then(|v| u32::try_from(v).ok()),
293                    I8 => i8::from_str_by_radix(&s).ok().and_then(|v| u32::try_from(v).ok()),
294                    I16 => i16::from_str_by_radix(&s).ok().and_then(|v| u32::try_from(v).ok()),
295                    I32 => i32::from_str_by_radix(&s).ok().and_then(|v| u32::try_from(v).ok()),
296                    I64 => i64::from_str_by_radix(&s).ok().and_then(|v| u32::try_from(v).ok()),
297                    I128 => i128::from_str_by_radix(&s).ok().and_then(|v| u32::try_from(v).ok()),
298                };
299            } else if let LiteralVariant::Unsuffixed(s) = &literal.variant {
300                // Assume unsuffixed literals are `u32`. The type checker should enforce that as the default type.
301                let s = s.replace("_", "");
302                return u32::from_str_by_radix(&s).ok();
303            }
304        }
305        None
306    }
307
308    pub fn is_none_expr(&self) -> bool {
309        matches!(self, Expression::Literal(Literal { variant: LiteralVariant::None, .. }))
310    }
311
312    /// Returns true if we can confidently say evaluating this expression has no side effects, false otherwise
313    pub fn is_pure(&self, get_type: &impl Fn(NodeID) -> Type) -> bool {
314        match self {
315            // Discriminate intrinsics
316            Expression::Intrinsic(intr) => {
317                if let Some(intrinsic) = Intrinsic::from_symbol(intr.name, &intr.type_parameters) {
318                    intrinsic.is_pure()
319                } else {
320                    false
321                }
322            }
323
324            // We may be indirectly referring to an impure item
325            // This analysis could be more granular
326            Expression::Call(..)
327            | Expression::DynamicCall(..)
328            | Expression::Err(..)
329            | Expression::Async(..)
330            | Expression::Cast(..) => false,
331
332            Expression::Binary(expr) => {
333                use BinaryOperation::*;
334                match expr.op {
335                    // These can halt for any of their operand types.
336                    Div | Mod | Rem | Shl | Shr => false,
337                    // These can only halt for integers.
338                    Add | Mul | Pow => !matches!(get_type(expr.id()), Type::Integer(..)),
339                    _ => expr.left.is_pure(get_type) && expr.right.is_pure(get_type),
340                }
341            }
342            Expression::Unary(expr) => {
343                use UnaryOperation::*;
344                match expr.op {
345                    // These can halt for any of their operand types.
346                    Abs | Inverse | SquareRoot => false,
347                    // Negate can only halt for integers.
348                    Negate => !matches!(get_type(expr.id()), Type::Integer(..)),
349                    _ => expr.receiver.is_pure(get_type),
350                }
351            }
352
353            // Always pure
354            Expression::Literal(..) | Expression::Path(..) | Expression::Unit(..) => true,
355
356            // Recurse
357            Expression::ArrayAccess(expr) => expr.array.is_pure(get_type) && expr.index.is_pure(get_type),
358            Expression::MemberAccess(expr) => expr.inner.is_pure(get_type),
359            Expression::Repeat(expr) => expr.expr.is_pure(get_type) && expr.count.is_pure(get_type),
360            Expression::TupleAccess(expr) => expr.tuple.is_pure(get_type),
361            Expression::Array(expr) => expr.elements.iter().all(|e| e.is_pure(get_type)),
362            Expression::Composite(expr) => {
363                expr.const_arguments.iter().all(|e| e.is_pure(get_type))
364                    && expr.members.iter().all(|init| init.expression.as_ref().is_none_or(|e| e.is_pure(get_type)))
365            }
366            Expression::Ternary(expr) => {
367                expr.condition.is_pure(get_type) && expr.if_true.is_pure(get_type) && expr.if_false.is_pure(get_type)
368            }
369            Expression::Tuple(expr) => expr.elements.iter().all(|e| e.is_pure(get_type)),
370        }
371    }
372
373    /// Returns the *zero value expression* for a given type, if one exists.
374    ///
375    /// This is used during lowering and reconstruction to provide default or
376    /// placeholder values (e.g., for `get_or_use` calls or composite initialization).
377    ///
378    /// Supported types:
379    /// - **Integers** (`i8`–`i128`, `u8`–`u128`): literal `0`
380    /// - **Boolean**: literal `false`
381    /// - **Field**, **Group**, **Scalar**: zero literals `"0"`
382    /// - **Composites**: recursively constructs a composite with all members zeroed
383    /// - **Arrays**: repeats a zero element for the array length
384    ///
385    /// Returns `None` if the type has no well-defined zero representation
386    /// (e.g. mapping, Future).
387    ///
388    /// The `composite_lookup` callback provides member definitions for composite types.
389    #[allow(clippy::type_complexity)]
390    pub fn zero(
391        ty: &Type,
392        span: Span,
393        node_builder: &NodeBuilder,
394        composite_lookup: &dyn Fn(&Location) -> Vec<(Symbol, Type)>,
395    ) -> Option<Self> {
396        let id = node_builder.next_id();
397
398        match ty {
399            // Numeric types
400            Type::Integer(IntegerType::I8) => Some(Literal::integer(IntegerType::I8, "0".to_string(), span, id).into()),
401            Type::Integer(IntegerType::I16) => {
402                Some(Literal::integer(IntegerType::I16, "0".to_string(), span, id).into())
403            }
404            Type::Integer(IntegerType::I32) => {
405                Some(Literal::integer(IntegerType::I32, "0".to_string(), span, id).into())
406            }
407            Type::Integer(IntegerType::I64) => {
408                Some(Literal::integer(IntegerType::I64, "0".to_string(), span, id).into())
409            }
410            Type::Integer(IntegerType::I128) => {
411                Some(Literal::integer(IntegerType::I128, "0".to_string(), span, id).into())
412            }
413            Type::Integer(IntegerType::U8) => Some(Literal::integer(IntegerType::U8, "0".to_string(), span, id).into()),
414            Type::Integer(IntegerType::U16) => {
415                Some(Literal::integer(IntegerType::U16, "0".to_string(), span, id).into())
416            }
417            Type::Integer(IntegerType::U32) => {
418                Some(Literal::integer(IntegerType::U32, "0".to_string(), span, id).into())
419            }
420            Type::Integer(IntegerType::U64) => {
421                Some(Literal::integer(IntegerType::U64, "0".to_string(), span, id).into())
422            }
423            Type::Integer(IntegerType::U128) => {
424                Some(Literal::integer(IntegerType::U128, "0".to_string(), span, id).into())
425            }
426
427            // Boolean
428            Type::Boolean => Some(Literal::boolean(false, span, id).into()),
429
430            // Address: addresses don't have a well defined _zero_ but this value is often used as
431            // the "zero" address in practical applications. It really should never be used directly though.
432            // It should only be used as a placeholder for representating `none` for example.
433            Type::Address => Some(
434                Literal::address(
435                    "aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc".to_string(),
436                    span,
437                    id,
438                )
439                .into(),
440            ),
441
442            // Field, Group, Scalar
443            Type::Field => Some(Literal::field("0".to_string(), span, id).into()),
444            Type::Group => Some(Literal::group("0".to_string(), span, id).into()),
445            Type::Scalar => Some(Literal::scalar("0".to_string(), span, id).into()),
446
447            // Signature: signatures don't have a well defined _zero_. The value chosen here is arbitrary.
448            // That being said, this value should really never be used directly. It should only be used as a 
449            // placeholder for representing `none` for example.
450            Type::Signature => Some(
451                Literal::signature(
452                    "sign195m229jvzr0wmnshj6f8gwplhkrkhjumgjmad553r997u7pjfgpfz4j2w0c9lp53mcqqdsmut2g3a2zuvgst85w38hv273mwjec3sqjsv9w6uglcy58gjh7x3l55z68zsf24kx7a73ctp8x8klhuw7l2p4s3aq8um5jp304js7qcnwdqj56q5r5088tyvxsgektun0rnmvtsuxpe6sj".to_string(),
453                    span,
454                    id,
455                )
456                .into(),
457            ),
458
459            // Composite types
460            Type::Composite(composite_type) => {
461                let path = &composite_type.path;
462                let members = composite_lookup(path.expect_global_location());
463
464                let composite_members = members
465                    .into_iter()
466                    .map(|(symbol, member_type)| {
467                        let member_id = node_builder.next_id();
468                        let zero_expr = Self::zero(&member_type, span, node_builder, composite_lookup)?;
469
470                        Some(CompositeFieldInitializer {
471                            span,
472                            id: member_id,
473                            identifier: Identifier::new(symbol, node_builder.next_id()),
474                            expression: Some(zero_expr),
475                        })
476                    })
477                    .collect::<Option<Vec<_>>>()?;
478
479                Some(Expression::Composite(CompositeExpression {
480                    span,
481                    id,
482                    path: path.clone(),
483                    const_arguments: composite_type.const_arguments.clone(),
484                    members: composite_members,
485                }))
486            }
487
488            // Arrays
489            Type::Array(array_type) => {
490                let element_ty = &array_type.element_type;
491
492                let element_expr = Self::zero(element_ty, span, node_builder, composite_lookup)?;
493
494                Some(Expression::Repeat(
495                    RepeatExpression { span, id, expr: element_expr, count: *array_type.length.clone() }.into(),
496                ))
497            }
498
499            // Other types are not expected or supported just yet
500            _ => None,
501        }
502    }
503}