leo_ast/types/
array.rs

1// Copyright (C) 2019-2025 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::{Expression, IntegerType, Literal, LiteralVariant, Type};
18use snarkvm::console::program::ArrayType as ConsoleArrayType;
19
20use leo_span::{Span, Symbol};
21use serde::{Deserialize, Serialize};
22use snarkvm::prelude::Network;
23use std::fmt;
24
25/// An array type.
26#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
27pub struct ArrayType {
28    pub element_type: Box<Type>,
29    pub length: Box<Expression>,
30}
31
32impl ArrayType {
33    /// Creates a new array type.
34    pub fn new(element: Type, length: Expression) -> Self {
35        Self { element_type: Box::new(element), length: Box::new(length) }
36    }
37
38    /// Returns the element type of the array.
39    pub fn element_type(&self) -> &Type {
40        &self.element_type
41    }
42
43    /// Returns the base element type of the array.
44    pub fn base_element_type(&self) -> &Type {
45        match self.element_type.as_ref() {
46            Type::Array(array_type) => array_type.base_element_type(),
47            type_ => type_,
48        }
49    }
50
51    pub fn from_snarkvm<N: Network>(array_type: &ConsoleArrayType<N>, program: Option<Symbol>) -> Self {
52        Self {
53            element_type: Box::new(Type::from_snarkvm(array_type.next_element_type(), program)),
54            length: Box::new(Expression::Literal(Literal {
55                variant: LiteralVariant::Integer(IntegerType::U32, array_type.length().to_string().replace("u32", "")),
56                id: Default::default(),
57                span: Span::default(),
58            })),
59        }
60    }
61}
62
63impl fmt::Display for ArrayType {
64    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
65        // For display purposes (in error messages for example.), do not include the type suffix.
66        if let Expression::Literal(literal) = &*self.length {
67            if let LiteralVariant::Integer(_, s) = &literal.variant {
68                return write!(f, "[{}; {s}]", self.element_type);
69            }
70        }
71
72        write!(f, "[{}; {}]", self.element_type, self.length)
73    }
74}