leo-ast 4.0.2

Abstract syntax tree (AST) for the Leo programming language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
// Copyright (C) 2019-2026 Provable Inc.
// This file is part of the Leo library.

// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.

use crate::{
    ArrayType,
    CompositeType,
    FutureType,
    Identifier,
    IntegerType,
    Location,
    MappingType,
    OptionalType,
    Path,
    ProgramId,
    TupleType,
    VectorType,
};

use itertools::Itertools;
use serde::{Deserialize, Serialize};
use snarkvm::prelude::{
    LiteralType,
    Network,
    PlaintextType,
    PlaintextType::{Array, ExternalStruct, Literal, Struct},
};
use std::fmt;

/// Explicit type used for defining a variable or expression type
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum Type {
    /// The `address` type.
    Address,
    /// The array type.
    Array(ArrayType),
    /// The `bool` type.
    Boolean,
    /// The composite type.
    Composite(CompositeType),
    /// The `field` type.
    Field,
    /// The `future` type.
    Future(FutureType),
    /// The `group` type.
    Group,
    /// The `identifier` type.
    Identifier,
    /// The `dyn record` type.
    DynRecord,
    /// A reference to a built in type.
    Ident(Identifier),
    /// An integer type.
    Integer(IntegerType),
    /// A mapping type.
    Mapping(MappingType),
    /// A nullable type.
    Optional(OptionalType),
    /// The `scalar` type.
    Scalar,
    /// The `signature` type.
    Signature,
    /// The `string` type.
    String,
    /// A static tuple of at least one type.
    Tuple(TupleType),
    /// The vector type.
    Vector(VectorType),
    /// Numeric type which should be resolved to `Field`, `Group`, `Integer(_)`, or `Scalar`.
    Numeric,
    /// The `unit` type.
    Unit,
    /// Placeholder for a type that could not be resolved or was not well-formed.
    /// Will eventually lead to a compile error.
    #[default]
    Err,
}

impl Type {
    /// Are the types considered equal as far as the Leo user is concerned?
    ///
    /// In particular, any comparison involving an `Err` is `true`, and Futures which aren't explicit compare equal to
    /// other Futures.
    ///
    /// An array with an undetermined length (e.g., one that depends on a `const`) is considered equal to other arrays
    /// if their element types match. This allows const propagation to potentially resolve the length before type
    /// checking is performed again.
    ///
    /// Composite types are considered equal if their names and resolved program names match. If either side still has
    /// const generic arguments, they are treated as equal unconditionally since monomorphization and other passes of
    /// type-checking will handle mismatches later.
    pub fn eq_user(&self, other: &Type) -> bool {
        match (self, other) {
            (Type::Err, _)
            | (_, Type::Err)
            | (Type::Address, Type::Address)
            | (Type::Boolean, Type::Boolean)
            | (Type::Field, Type::Field)
            | (Type::Group, Type::Group)
            | (Type::Scalar, Type::Scalar)
            | (Type::Signature, Type::Signature)
            | (Type::String, Type::String)
            | (Type::Identifier, Type::Identifier)
            | (Type::DynRecord, Type::DynRecord)
            | (Type::Unit, Type::Unit) => true,
            (Type::Array(left), Type::Array(right)) => {
                (match (left.length.as_u32(), right.length.as_u32()) {
                    (Some(l1), Some(l2)) => l1 == l2,
                    _ => {
                        // An array with an undetermined length (e.g., one that depends on a `const`) is considered
                        // equal to other arrays because their lengths _may_ eventually be proven equal.
                        true
                    }
                }) && left.element_type().eq_user(right.element_type())
            }
            (Type::Ident(left), Type::Ident(right)) => left.name == right.name,
            (Type::Integer(left), Type::Integer(right)) => left == right,
            (Type::Mapping(left), Type::Mapping(right)) => {
                left.key.eq_user(&right.key) && left.value.eq_user(&right.value)
            }
            (Type::Optional(left), Type::Optional(right)) => left.inner.eq_user(&right.inner),
            (Type::Tuple(left), Type::Tuple(right)) if left.length() == right.length() => left
                .elements()
                .iter()
                .zip_eq(right.elements().iter())
                .all(|(left_type, right_type)| left_type.eq_user(right_type)),
            (Type::Vector(left), Type::Vector(right)) => left.element_type.eq_user(&right.element_type),
            (Type::Composite(left), Type::Composite(right)) => {
                // If either composite still has const generic arguments, treat them as equal;
                // monomorphization and a subsequent type-checking pass will handle mismatches.
                if !left.const_arguments.is_empty() || !right.const_arguments.is_empty() {
                    return true;
                }

                // Two composite types are the same if their global locations match.
                match (&left.path.try_global_location(), &right.path.try_global_location()) {
                    (Some(l), Some(r)) => l == r,
                    _ => false,
                }
            }

            (Type::Future(left), Type::Future(right)) if !left.is_explicit || !right.is_explicit => true,
            (Type::Future(left), Type::Future(right)) if left.inputs.len() == right.inputs.len() => left
                .inputs()
                .iter()
                .zip_eq(right.inputs().iter())
                .all(|(left_type, right_type)| left_type.eq_user(right_type)),
            _ => false,
        }
    }

    /// Returns `true` if the self `Type` is equal to the other `Type` in all aspects besides composite program of origin.
    ///
    /// In the case of futures, it also makes sure that if both are not explicit, they are equal.
    ///
    /// Flattens array syntax: `[[u8; 1]; 2] == [u8; (2, 1)] == true`
    ///
    /// Composite types are considered equal if their names match. If either side still has const generic arguments,
    /// they are treated as equal unconditionally since monomorphization and other passes of type-checking will handle
    /// mismatches later.
    pub fn eq_flat_relaxed(&self, other: &Self) -> bool {
        match (self, other) {
            (Type::Address, Type::Address)
            | (Type::Boolean, Type::Boolean)
            | (Type::Field, Type::Field)
            | (Type::Group, Type::Group)
            | (Type::Scalar, Type::Scalar)
            | (Type::Signature, Type::Signature)
            | (Type::String, Type::String)
            | (Type::Identifier, Type::Identifier)
            | (Type::DynRecord, Type::DynRecord)
            | (Type::Unit, Type::Unit) => true,
            (Type::Array(left), Type::Array(right)) => {
                // Two arrays are equal if their element types are the same and if their lengths
                // are the same, assuming the lengths can be extracted as `u32`.
                (match (left.length.as_u32(), right.length.as_u32()) {
                    (Some(l1), Some(l2)) => l1 == l2,
                    _ => {
                        // An array with an undetermined length (e.g., one that depends on a `const`) is considered
                        // equal to other arrays because their lengths _may_ eventually be proven equal.
                        true
                    }
                }) && left.element_type().eq_flat_relaxed(right.element_type())
            }
            (Type::Ident(left), Type::Ident(right)) => left.matches(right),
            (Type::Integer(left), Type::Integer(right)) => left.eq(right),
            (Type::Mapping(left), Type::Mapping(right)) => {
                left.key.eq_flat_relaxed(&right.key) && left.value.eq_flat_relaxed(&right.value)
            }
            (Type::Optional(left), Type::Optional(right)) => left.inner.eq_flat_relaxed(&right.inner),
            (Type::Tuple(left), Type::Tuple(right)) if left.length() == right.length() => left
                .elements()
                .iter()
                .zip_eq(right.elements().iter())
                .all(|(left_type, right_type)| left_type.eq_flat_relaxed(right_type)),
            (Type::Vector(left), Type::Vector(right)) => left.element_type.eq_flat_relaxed(&right.element_type),
            (Type::Composite(left), Type::Composite(right)) => {
                // If either composite still has const generic arguments, treat them as equal.
                // Type checking will run again after monomorphization.
                if !left.const_arguments.is_empty() || !right.const_arguments.is_empty() {
                    return true;
                }

                // Two composite types are the same if their global paths match.
                // If the absolute paths are not available, then we really can't compare the two
                // types and we just return `false` to be conservative.
                match (&left.path.try_global_location(), &right.path.try_global_location()) {
                    (Some(l), Some(r)) => l.path == r.path,
                    _ => false,
                }
            }
            // Don't type check when type hasn't been explicitly defined.
            (Type::Future(left), Type::Future(right)) if !left.is_explicit || !right.is_explicit => true,
            (Type::Future(left), Type::Future(right)) if left.inputs.len() == right.inputs.len() => left
                .inputs()
                .iter()
                .zip_eq(right.inputs().iter())
                .all(|(left_type, right_type)| left_type.eq_flat_relaxed(right_type)),
            _ => false,
        }
    }

    pub fn from_snarkvm<N: Network>(t: &PlaintextType<N>, program_id: ProgramId) -> Self {
        match t {
            Literal(lit) => (*lit).into(),
            Struct(s) => Type::Composite(CompositeType {
                path: {
                    let ident = Identifier::from(s);
                    Path::from(ident).to_global(Location::new(program_id.as_symbol(), vec![ident.name]))
                },
                const_arguments: Vec::new(),
            }),
            ExternalStruct(l) => Type::Composite(CompositeType {
                path: {
                    let external_program = ProgramId::from(l.program_id());
                    let name = Identifier::from(l.resource());
                    Path::from(name)
                        .with_user_program(external_program)
                        .to_global(Location::new(external_program.as_symbol(), vec![name.name]))
                },
                const_arguments: Vec::new(),
            }),
            Array(array) => Type::Array(ArrayType::from_snarkvm(array, program_id)),
        }
    }

    // Attempts to convert `self` to a snarkVM `PlaintextType`.
    pub fn to_snarkvm<N: Network>(&self) -> anyhow::Result<PlaintextType<N>> {
        match self {
            Type::Address => Ok(PlaintextType::Literal(snarkvm::prelude::LiteralType::Address)),
            Type::Boolean => Ok(PlaintextType::Literal(snarkvm::prelude::LiteralType::Boolean)),
            Type::Field => Ok(PlaintextType::Literal(snarkvm::prelude::LiteralType::Field)),
            Type::Group => Ok(PlaintextType::Literal(snarkvm::prelude::LiteralType::Group)),
            Type::Integer(int_type) => match int_type {
                IntegerType::U8 => Ok(PlaintextType::Literal(snarkvm::prelude::LiteralType::U8)),
                IntegerType::U16 => Ok(PlaintextType::Literal(snarkvm::prelude::LiteralType::U16)),
                IntegerType::U32 => Ok(PlaintextType::Literal(snarkvm::prelude::LiteralType::U32)),
                IntegerType::U64 => Ok(PlaintextType::Literal(snarkvm::prelude::LiteralType::U64)),
                IntegerType::U128 => Ok(PlaintextType::Literal(snarkvm::prelude::LiteralType::U128)),
                IntegerType::I8 => Ok(PlaintextType::Literal(snarkvm::prelude::LiteralType::I8)),
                IntegerType::I16 => Ok(PlaintextType::Literal(snarkvm::prelude::LiteralType::I16)),
                IntegerType::I32 => Ok(PlaintextType::Literal(snarkvm::prelude::LiteralType::I32)),
                IntegerType::I64 => Ok(PlaintextType::Literal(snarkvm::prelude::LiteralType::I64)),
                IntegerType::I128 => Ok(PlaintextType::Literal(snarkvm::prelude::LiteralType::I128)),
            },
            Type::Scalar => Ok(PlaintextType::Literal(snarkvm::prelude::LiteralType::Scalar)),
            Type::Signature => Ok(PlaintextType::Literal(snarkvm::prelude::LiteralType::Signature)),
            Type::Array(array_type) => Ok(PlaintextType::<N>::Array(array_type.to_snarkvm()?)),
            _ => anyhow::bail!("Converting from type {self} to snarkVM type is not supported"),
        }
    }

    // A helper function to get the size in bits of the input type.
    pub fn size_in_bits<N: Network, F0, F1>(
        &self,
        is_raw: bool,
        get_structs: F0,
        get_external_structs: F1,
    ) -> anyhow::Result<usize>
    where
        F0: Fn(&snarkvm::prelude::Identifier<N>) -> anyhow::Result<snarkvm::prelude::StructType<N>>,
        F1: Fn(&snarkvm::prelude::Locator<N>) -> anyhow::Result<snarkvm::prelude::StructType<N>>,
    {
        match is_raw {
            false => self.to_snarkvm::<N>()?.size_in_bits(&get_structs, &get_external_structs),
            true => self.to_snarkvm::<N>()?.size_in_bits_raw(&get_structs, &get_external_structs),
        }
    }

    /// Determines whether `self` can be coerced to the `expected` type.
    ///
    /// This method checks if the current type can be implicitly coerced to the expected type
    /// according to specific rules:
    /// - `Optional<T>` can be coerced to `Optional<T>`.
    /// - `T` can be coerced to `Optional<T>`.
    /// - Arrays `[T; N]` can be coerced to `[Optional<T>; N]` if lengths match or are unknown,
    ///   and element types are coercible.
    /// - Falls back to an equality check for other types.
    ///
    /// # Arguments
    /// * `expected` - The type to which `self` is being coerced.
    ///
    /// # Returns
    /// `true` if coercion is allowed; `false` otherwise.
    pub fn can_coerce_to(&self, expected: &Type) -> bool {
        use Type::*;

        match (self, expected) {
            // Allow Optional<T> → Optional<T>
            (Optional(actual_opt), Optional(expected_opt)) => actual_opt.inner.can_coerce_to(&expected_opt.inner),

            // Allow T → Optional<T>
            (a, Optional(opt)) => a.can_coerce_to(&opt.inner),

            // Allow [T; N] → [Optional<T>; N]
            (Array(a_arr), Array(e_arr)) => {
                let lengths_equal = match (a_arr.length.as_u32(), e_arr.length.as_u32()) {
                    (Some(l1), Some(l2)) => l1 == l2,
                    _ => true,
                };

                lengths_equal && a_arr.element_type().can_coerce_to(e_arr.element_type())
            }

            // Fallback: check for exact match
            _ => self.eq_user(expected),
        }
    }

    pub fn is_optional(&self) -> bool {
        matches!(self, Self::Optional(_))
    }

    pub fn is_vector(&self) -> bool {
        matches!(self, Self::Vector(_))
    }

    pub fn is_mapping(&self) -> bool {
        matches!(self, Self::Mapping(_))
    }

    pub fn to_optional(&self) -> Type {
        Type::Optional(OptionalType { inner: Box::new(self.clone()) })
    }

    pub fn is_empty(&self) -> bool {
        match self {
            Type::Unit => true,
            Type::Array(array_type) => {
                if let Some(length) = array_type.length.as_u32() {
                    length == 0
                } else {
                    false
                }
            }
            _ => false,
        }
    }
}

impl From<LiteralType> for Type {
    fn from(value: LiteralType) -> Self {
        match value {
            LiteralType::Identifier => Type::Identifier,
            LiteralType::Address => Type::Address,
            LiteralType::Boolean => Type::Boolean,
            LiteralType::Field => Type::Field,
            LiteralType::Group => Type::Group,
            LiteralType::U8 => Type::Integer(IntegerType::U8),
            LiteralType::U16 => Type::Integer(IntegerType::U16),
            LiteralType::U32 => Type::Integer(IntegerType::U32),
            LiteralType::U64 => Type::Integer(IntegerType::U64),
            LiteralType::U128 => Type::Integer(IntegerType::U128),
            LiteralType::I8 => Type::Integer(IntegerType::I8),
            LiteralType::I16 => Type::Integer(IntegerType::I16),
            LiteralType::I32 => Type::Integer(IntegerType::I32),
            LiteralType::I64 => Type::Integer(IntegerType::I64),
            LiteralType::I128 => Type::Integer(IntegerType::I128),
            LiteralType::Scalar => Type::Scalar,
            LiteralType::Signature => Type::Signature,
            LiteralType::String => Type::String,
        }
    }
}

impl fmt::Display for Type {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Type::Address => write!(f, "address"),
            Type::Identifier => write!(f, "identifier"),
            Type::DynRecord => write!(f, "dyn record"),
            Type::Array(ref array_type) => write!(f, "{array_type}"),
            Type::Boolean => write!(f, "bool"),
            Type::Field => write!(f, "field"),
            Type::Future(ref future_type) => write!(f, "{future_type}"),
            Type::Group => write!(f, "group"),
            Type::Ident(ref variable) => write!(f, "{variable}"),
            Type::Integer(ref integer_type) => write!(f, "{integer_type}"),
            Type::Mapping(ref mapping_type) => write!(f, "{mapping_type}"),
            Type::Optional(ref optional_type) => write!(f, "{optional_type}"),
            Type::Scalar => write!(f, "scalar"),
            Type::Signature => write!(f, "signature"),
            Type::String => write!(f, "string"),
            Type::Composite(ref composite_type) => write!(f, "{composite_type}"),
            Type::Tuple(ref tuple) => write!(f, "{tuple}"),
            Type::Vector(ref vector_type) => write!(f, "{vector_type}"),
            Type::Numeric => write!(f, "numeric"),
            Type::Unit => write!(f, "()"),
            Type::Err => write!(f, "error"),
        }
    }
}