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, Constructor, 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 /// An optional constructor.
39 pub constructor: Option<Constructor>,
40 /// The span associated with the program scope.
41 pub span: Span,
42}
43
44impl From<Stub> for ProgramScope {
45 fn from(stub: Stub) -> Self {
46 Self {
47 program_id: stub.stub_id,
48 consts: stub.consts,
49 structs: stub.structs,
50 mappings: stub.mappings,
51 functions: stub
52 .functions
53 .into_iter()
54 .map(|(symbol, function)| (symbol, Function::from(function)))
55 .collect(),
56 // A program scope constructed from a stub does not need a constructor, since they are not externally callable.
57 constructor: None,
58 span: stub.span,
59 }
60 }
61}
62
63impl fmt::Display for ProgramScope {
64 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
65 writeln!(f, "program {} {{", self.program_id)?;
66 for (_, const_decl) in self.consts.iter() {
67 writeln!(f, "{};", Indent(const_decl))?;
68 }
69 if let Some(constructor) = &self.constructor {
70 writeln!(f, "{}", Indent(constructor))?;
71 }
72 for (_, struct_) in self.structs.iter() {
73 writeln!(f, "{}", Indent(struct_))?;
74 }
75 for (_, mapping) in self.mappings.iter() {
76 writeln!(f, "{};", Indent(mapping))?;
77 }
78 for (_, function) in self.functions.iter() {
79 writeln!(f, "{}", Indent(function))?;
80 }
81 write!(f, "}}")
82 }
83}