Skip to main content

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, Module};
20use indexmap::IndexMap;
21use serde::{Deserialize, 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/// and submodules (each a separate source file under the library's `src/` directory).
28#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
29pub struct Library {
30    pub name: Symbol,
31    /// Submodules of this library, keyed by their path (e.g., `[utils]` for `src/utils.leo`).
32    pub modules: IndexMap<Vec<Symbol>, Module>,
33    /// The constants defined in this library.
34    pub consts: Vec<(Symbol, ConstDeclaration)>,
35    /// The struct definitions in this library.
36    pub structs: Vec<(Symbol, Composite)>,
37    /// The function definitions in this library.
38    pub functions: Vec<(Symbol, Function)>,
39}
40
41impl fmt::Display for Library {
42    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
43        writeln!(f, "library {} {{", self.name)?;
44
45        for (_, struct_def) in self.structs.iter() {
46            writeln!(f, "{}", Indent(struct_def))?;
47        }
48
49        for (_, const_decl) in self.consts.iter() {
50            writeln!(f, "{};", Indent(const_decl))?;
51        }
52
53        for (_, func) in self.functions.iter() {
54            writeln!(f, "{}", Indent(func))?;
55        }
56
57        for (_, module) in self.modules.iter() {
58            writeln!(f, "{}", module)?;
59        }
60
61        writeln!(f, "}}")
62    }
63}