leo_passes/pass.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 crate::{Assigner, SymbolTable, TypeTable};
18
19use indexmap::IndexMap;
20use leo_ast::{Ast, CallGraph, CompositeGraph, Location, NetworkName, NodeBuilder};
21use leo_errors::{Handler, LeoWarning, Result};
22
23use std::{collections::HashSet, rc::Rc};
24
25/// Contains data shared by many compiler passes.
26#[derive(Default)]
27pub struct CompilerState {
28 /// The Abstract Syntax Tree.
29 pub ast: Ast,
30 /// The error Handler.
31 pub handler: Handler,
32 /// Maps node IDs to types.
33 pub type_table: TypeTable,
34 /// Creates incrementing node IDs.
35 pub node_builder: Rc<NodeBuilder>,
36 /// Creates unique symbols and definitions.
37 pub assigner: Assigner,
38 /// Contains data about the variables and other entities in the program.
39 pub symbol_table: SymbolTable,
40 /// A graph of which composite refer to each other.
41 pub composite_graph: CompositeGraph,
42 /// A graph of which functions call each other.
43 pub call_graph: CallGraph,
44 /// How many times a given function is called.
45 pub call_count: IndexMap<Location, usize>,
46 /// A set of the warnings collected. This is used to make sure we don't emit the same exact warning twice.
47 pub warnings: HashSet<LeoWarning>,
48 /// Is this a test program?
49 pub is_test: bool,
50 /// The network.
51 pub network: NetworkName,
52}
53
54/// A compiler pass.
55///
56/// Every pass has access to `CompilerState`, and may also specify
57/// an `Input` and `Output`.
58pub trait Pass {
59 type Input;
60 type Output;
61
62 const NAME: &str;
63
64 /// Runs the compiler pass.
65 fn do_pass(input: Self::Input, state: &mut CompilerState) -> Result<Self::Output>;
66}