leo_ast/program/program_scope.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
17//! A Leo program scope consists of struct, function, and mapping definitions.
18
19use crate::{Composite, ConstDeclaration, Function, Indent, Mapping, ProgramId, Stub};
20
21use leo_span::{Span, Symbol};
22use serde::{Deserialize, Serialize};
23use std::fmt;
24
25/// Stores the Leo program scope abstract syntax tree.
26#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
27pub struct ProgramScope {
28 /// The program id of the program scope.
29 pub program_id: ProgramId,
30 /// A vector of const definitions
31 pub consts: Vec<(Symbol, ConstDeclaration)>,
32 /// A vector of struct definitions.
33 pub structs: Vec<(Symbol, Composite)>,
34 /// A vector of mapping definitions.
35 pub mappings: Vec<(Symbol, Mapping)>,
36 /// A vector of function definitions.
37 pub functions: Vec<(Symbol, Function)>,
38 /// The span associated with the program scope.
39 pub span: Span,
40}
41
42impl From<Stub> for ProgramScope {
43 fn from(stub: Stub) -> Self {
44 Self {
45 program_id: stub.stub_id,
46 consts: stub.consts,
47 structs: stub.structs,
48 mappings: stub.mappings,
49 functions: stub
50 .functions
51 .into_iter()
52 .map(|(symbol, function)| (symbol, Function::from(function)))
53 .collect(),
54 span: stub.span,
55 }
56 }
57}
58
59impl fmt::Display for ProgramScope {
60 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
61 writeln!(f, "program {} {{", self.program_id)?;
62 for (_, const_decl) in self.consts.iter() {
63 writeln!(f, "{};", Indent(const_decl))?;
64 }
65 for (_, struct_) in self.structs.iter() {
66 writeln!(f, "{}", Indent(struct_))?;
67 }
68 for (_, mapping) in self.mappings.iter() {
69 writeln!(f, "{};", Indent(mapping))?;
70 }
71 for (_, function) in self.functions.iter() {
72 writeln!(f, "{}", Indent(function))?;
73 }
74 write!(f, "}}")
75 }
76}