leo_ast/module/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
17//! A Leo module represents a collection of declarations within a single scope,
18//! typically corresponding to a file or logical unit of code. It stores all
19//! relevant definitions associated with a module, including:
20//!
21//! - The name of the program the module belongs to (`program_name`)
22//! - The hierarchical path identifying the module (`path`)
23//! - A list of constant declarations (`consts`)
24//! - A list of struct type definitions (`structs`)
25//! - A list of function definitions (`functions`)
26
27use crate::{Composite, ConstDeclaration, Function, Indent};
28
29use leo_span::Symbol;
30
31use std::fmt;
32
33use itertools::Itertools;
34use serde::{Deserialize, Serialize};
35
36/// Stores the abstract syntax tree of a Leo module.
37#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
38pub struct Module {
39 /// The name of the program that this module belongs to.
40 pub program_name: Symbol,
41 /// The path to the module.
42 pub path: Vec<Symbol>,
43 /// A vector of const definitions.
44 pub consts: Vec<(Symbol, ConstDeclaration)>,
45 /// A vector of struct definitions.
46 pub structs: Vec<(Symbol, Composite)>,
47 /// A vector of function definitions.
48 pub functions: Vec<(Symbol, Function)>,
49}
50
51impl fmt::Display for Module {
52 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
53 writeln!(f, "module {} {{", self.path.iter().format("::"))?;
54 for (_, const_decl) in self.consts.iter() {
55 writeln!(f, "{};", Indent(const_decl))?;
56 }
57 for (_, struct_) in self.structs.iter() {
58 writeln!(f, "{}", Indent(struct_))?;
59 }
60 for (_, function) in self.functions.iter() {
61 writeln!(f, "{}", Indent(function))?;
62 }
63 writeln!(f, "}}")
64 }
65}