leo_ast/library.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
17use leo_span::Symbol;
18
19use crate::{Composite, ConstDeclaration, Function, Indent, Interface, Module, Stub};
20use indexmap::IndexMap;
21use serde::Serialize;
22use std::fmt;
23
24/// Stores the Leo library abstract syntax tree.
25///
26/// Libraries may contain `const` declarations, `struct` definitions, `fn` functions,
27/// `interface` definitions, and submodules (each a separate source file under the
28/// library's `src/` directory).
29#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
30pub struct Library {
31 pub name: Symbol,
32 /// Submodules of this library, keyed by their path (e.g., `[utils]` for `src/utils.leo`).
33 #[serde(with = "crate::program::module_map")]
34 pub modules: IndexMap<Vec<Symbol>, Module>,
35 /// The constants defined in this library.
36 pub consts: Vec<(Symbol, ConstDeclaration)>,
37 /// The struct definitions in this library.
38 pub structs: Vec<(Symbol, Composite)>,
39 /// The function definitions in this library.
40 pub functions: Vec<(Symbol, Function)>,
41 /// The interface definitions in this library.
42 pub interfaces: Vec<(Symbol, Interface)>,
43 /// Stubs for imported programs/libraries.
44 ///
45 /// Populated by `Compiler::add_import_stubs`; empty in freshly-parsed libraries.
46 pub stubs: IndexMap<Symbol, Stub>,
47}
48
49impl fmt::Display for Library {
50 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
51 for (_, stub) in self.stubs.iter() {
52 writeln!(f, "{stub}")?;
53 }
54
55 writeln!(f, "library {} {{", self.name)?;
56
57 for (_, interface) in self.interfaces.iter() {
58 writeln!(f, "{}", Indent(interface))?;
59 }
60
61 for (_, struct_def) in self.structs.iter() {
62 writeln!(f, "{}", Indent(struct_def))?;
63 }
64
65 for (_, const_decl) in self.consts.iter() {
66 writeln!(f, "{};", Indent(const_decl))?;
67 }
68
69 for (_, func) in self.functions.iter() {
70 writeln!(f, "{}", Indent(func))?;
71 }
72
73 for (_, module) in self.modules.iter() {
74 writeln!(f, "{}", module)?;
75 }
76
77 writeln!(f, "}}")
78 }
79}