leo_ast/struct/
mod.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
17pub mod member;
18pub use member::*;
19
20use crate::{Identifier, Indent, Mode, Node, NodeID, Type};
21use leo_span::{Span, Symbol};
22
23use itertools::Itertools;
24use serde::{Deserialize, Serialize};
25use std::fmt;
26
27use snarkvm::{
28    console::program::{RecordType, StructType},
29    prelude::{
30        EntryType::{Constant, Private, Public},
31        Network,
32    },
33};
34
35/// A composite type definition, e.g., `struct Foo { my_field: Bar }` and `record Token { owner: address, amount: u64}`.
36/// In some languages these are called `struct`s.
37///
38/// Type identity is decided by the full path including `struct_name`,
39/// as the record is nominal, not structural.
40/// The fields are named so `struct Foo(u8, u16)` is not allowed.
41#[derive(Clone, Debug, Serialize, Deserialize)]
42pub struct Composite {
43    /// The name of the type in the type system in this module.
44    pub identifier: Identifier,
45    /// The fields, constant variables, and functions of this structure.
46    pub members: Vec<Member>,
47    /// The external program the struct is defined in.
48    pub external: Option<Symbol>,
49    /// Was this a `record Foo { ... }`?
50    /// If so, it wasn't a composite.
51    pub is_record: bool,
52    /// The entire span of the composite definition.
53    pub span: Span,
54    /// The ID of the node.
55    pub id: NodeID,
56}
57
58impl PartialEq for Composite {
59    fn eq(&self, other: &Self) -> bool {
60        self.identifier == other.identifier && self.external == other.external
61    }
62}
63
64impl Eq for Composite {}
65
66impl Composite {
67    /// Returns the composite name as a Symbol.
68    pub fn name(&self) -> Symbol {
69        self.identifier.name
70    }
71
72    pub fn from_external_record<N: Network>(input: &RecordType<N>, external_program: Symbol) -> Self {
73        Self {
74            identifier: Identifier::from(input.name()),
75            members: [
76                vec![Member {
77                    mode: if input.owner().is_private() { Mode::Public } else { Mode::Private },
78                    identifier: Identifier::new(Symbol::intern("owner"), Default::default()),
79                    type_: Type::Address,
80                    span: Default::default(),
81                    id: Default::default(),
82                }],
83                input
84                    .entries()
85                    .iter()
86                    .map(|(id, entry)| Member {
87                        mode: if input.owner().is_public() { Mode::Public } else { Mode::Private },
88                        identifier: Identifier::from(id),
89                        type_: match entry {
90                            Public(t) => Type::from_snarkvm(t, None),
91                            Private(t) => Type::from_snarkvm(t, None),
92                            Constant(t) => Type::from_snarkvm(t, None),
93                        },
94                        span: Default::default(),
95                        id: Default::default(),
96                    })
97                    .collect_vec(),
98            ]
99            .concat(),
100            external: Some(external_program),
101            is_record: true,
102            span: Default::default(),
103            id: Default::default(),
104        }
105    }
106
107    pub fn from_snarkvm<N: Network>(input: &StructType<N>) -> Self {
108        Self {
109            identifier: Identifier::from(input.name()),
110            members: input
111                .members()
112                .iter()
113                .map(|(id, type_)| Member {
114                    mode: Mode::None,
115                    identifier: Identifier::from(id),
116                    type_: Type::from_snarkvm(type_, None),
117                    span: Default::default(),
118                    id: Default::default(),
119                })
120                .collect(),
121            external: None,
122            is_record: false,
123            span: Default::default(),
124            id: Default::default(),
125        }
126    }
127}
128
129impl fmt::Display for Composite {
130    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
131        f.write_str(if self.is_record { "record" } else { "struct" })?;
132        writeln!(f, " {} {{", self.identifier)?;
133        for field in self.members.iter() {
134            writeln!(f, "{},", Indent(field))?;
135        }
136        write!(f, "}}")
137    }
138}
139
140crate::simple_node_impl!(Composite);