leo_ast/program/program_scope.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
17//! A Leo program scope consists of const, composite, function, and mapping definitions.
18
19use crate::{
20 Composite,
21 ConstDeclaration,
22 Constructor,
23 Function,
24 Indent,
25 Interface,
26 Mapping,
27 ProgramId,
28 StorageVariable,
29 Type,
30};
31
32use leo_span::{Span, Symbol};
33use serde::{Deserialize, Serialize};
34use std::fmt;
35
36/// Stores the Leo program scope abstract syntax tree.
37#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
38pub struct ProgramScope {
39 /// The program id of the program scope.
40 pub program_id: ProgramId,
41 /// The interfaces this program implements
42 pub parents: Vec<(Span, Type)>,
43 /// A vector of const definitions.
44 pub consts: Vec<(Symbol, ConstDeclaration)>,
45 /// A vector of composite definitions.
46 pub composites: Vec<(Symbol, Composite)>,
47 /// A vector of mapping definitions.
48 pub mappings: Vec<(Symbol, Mapping)>,
49 /// A vector of storage variable definitions.
50 pub storage_variables: Vec<(Symbol, StorageVariable)>,
51 /// A vector of function definitions.
52 pub functions: Vec<(Symbol, Function)>,
53 /// A vector of interface definitions.
54 pub interfaces: Vec<(Symbol, Interface)>,
55 /// An optional constructor.
56 pub constructor: Option<Constructor>,
57 /// The span associated with the program scope.
58 pub span: Span,
59}
60
61impl fmt::Display for ProgramScope {
62 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
63 writeln!(f, "program {} {{", self.program_id)?;
64 for (_, const_decl) in self.consts.iter() {
65 writeln!(f, "{};", Indent(const_decl))?;
66 }
67 if let Some(constructor) = &self.constructor {
68 writeln!(f, "{}", Indent(constructor))?;
69 }
70 for (_, composite_) in self.composites.iter() {
71 writeln!(f, "{}", Indent(composite_))?;
72 }
73 for (_, mapping) in self.mappings.iter() {
74 writeln!(f, "{};", Indent(mapping))?;
75 }
76 for (_, function) in self.functions.iter().filter(|f| f.1.variant.is_entry()) {
77 writeln!(f, "{}", Indent(function))?;
78 }
79 writeln!(f, "}}")?;
80
81 for (_, function) in self.functions.iter().filter(|f| !f.1.variant.is_entry()) {
82 writeln!(f, "{}", Indent(function))?;
83 }
84 Ok(())
85 }
86}