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::{NonNegativeNumber, Type};
18use snarkvm::console::program::ArrayType as ConsoleArrayType;
19
20use leo_span::Symbol;
21use serde::{Deserialize, Serialize};
22use snarkvm::prelude::Network;
23use std::fmt;
24
25/// An array type.
26#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
27pub struct ArrayType {
28    element_type: Box<Type>,
29    length: NonNegativeNumber,
30}
31
32impl ArrayType {
33    /// Creates a new array type.
34    pub fn new(element: Type, length: NonNegativeNumber) -> Self {
35        Self { element_type: Box::new(element), 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 length of the array.
44    pub fn length(&self) -> usize {
45        self.length.value()
46    }
47
48    /// Returns the base element type of the array.
49    pub fn base_element_type(&self) -> &Type {
50        match self.element_type.as_ref() {
51            Type::Array(array_type) => array_type.base_element_type(),
52            type_ => type_,
53        }
54    }
55
56    pub fn from_snarkvm<N: Network>(array_type: &ConsoleArrayType<N>, program: Option<Symbol>) -> Self {
57        Self {
58            element_type: Box::new(Type::from_snarkvm(array_type.next_element_type(), program)),
59            length: NonNegativeNumber::from(array_type.length().to_string().replace("u32", "")),
60        }
61    }
62}
63
64impl fmt::Display for ArrayType {
65    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
66        write!(f, "[{}; {}]", self.element_type, self.length)
67    }
68}