Skip to main content

leo_passes/type_checking/
mod.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
17mod ast;
18
19mod program;
20
21mod scope_state;
22
23mod visitor;
24use visitor::*;
25
26use self::scope_state::ScopeState;
27use crate::{CompilerState, Pass};
28
29use leo_ast::{CallGraph, CompositeGraph, NetworkName, ProgramVisitor};
30use leo_errors::Result;
31
32use snarkvm::prelude::{CanaryV0, MainnetV0, Network, TestnetV0};
33
34use indexmap::{IndexMap, IndexSet};
35
36/// Specify network limits for type checking.
37#[derive(Clone)]
38pub struct TypeCheckingInput {
39    pub max_array_elements: usize,
40    pub max_mappings: usize,
41    pub max_functions: usize,
42    pub max_inputs: usize,
43    pub max_outputs: usize,
44}
45
46impl TypeCheckingInput {
47    /// Create a new `TypeCheckingInput` from the given network.
48    pub fn new(network: NetworkName) -> Self {
49        let (max_array_elements, max_mappings, max_functions, max_inputs, max_outputs) = match network {
50            NetworkName::MainnetV0 => (
51                MainnetV0::LATEST_MAX_ARRAY_ELEMENTS(),
52                MainnetV0::MAX_MAPPINGS,
53                MainnetV0::MAX_FUNCTIONS,
54                MainnetV0::MAX_INPUTS,
55                MainnetV0::MAX_OUTPUTS,
56            ),
57            NetworkName::TestnetV0 => (
58                TestnetV0::LATEST_MAX_ARRAY_ELEMENTS(),
59                TestnetV0::MAX_MAPPINGS,
60                TestnetV0::MAX_FUNCTIONS,
61                TestnetV0::MAX_INPUTS,
62                TestnetV0::MAX_OUTPUTS,
63            ),
64            NetworkName::CanaryV0 => (
65                CanaryV0::LATEST_MAX_ARRAY_ELEMENTS(),
66                CanaryV0::MAX_MAPPINGS,
67                CanaryV0::MAX_FUNCTIONS,
68                CanaryV0::MAX_INPUTS,
69                CanaryV0::MAX_OUTPUTS,
70            ),
71        };
72        Self { max_array_elements, max_mappings, max_functions, max_inputs, max_outputs }
73    }
74}
75
76/// A pass to check types.
77///
78/// Also constructs the composite graph, call graph, and local symbol table data.
79pub struct TypeChecking;
80
81impl Pass for TypeChecking {
82    type Input = TypeCheckingInput;
83    type Output = ();
84
85    const NAME: &'static str = "TypeChecking";
86
87    fn do_pass(input: Self::Input, state: &mut CompilerState) -> Result<Self::Output> {
88        let composite_names = state
89            .symbol_table
90            .iter_records()
91            .map(|(loc, _)| loc.clone())
92            .chain(state.symbol_table.iter_structs().map(|(loc, _)| loc.clone()))
93            .collect();
94        let function_names: IndexSet<leo_ast::Location> =
95            state.symbol_table.iter_functions().map(|(loc, _)| loc.clone()).collect();
96
97        let ast = std::mem::take(&mut state.ast);
98
99        // Initialize the composite graph with all the composites in the program.
100        state.composite_graph = CompositeGraph::new(composite_names);
101        // Reinitialize the call counts
102        state.call_count = function_names.iter().cloned().map(|n| (n, 0)).collect();
103        // Initialize the call graph with all the functions in the program.
104        state.call_graph = CallGraph::new(function_names);
105
106        let mut visitor = TypeCheckingVisitor {
107            state,
108            scope_state: ScopeState::new(),
109            async_function_input_types: IndexMap::new(),
110            async_function_callers: IndexMap::new(),
111            used_composites: IndexSet::new(),
112            conditional_scopes: Vec::new(),
113            limits: input,
114            async_block_id: None,
115        };
116
117        ast.visit(
118            |program| visitor.visit_program(program),
119            |_library| {
120                // no-op for libraries
121            },
122        );
123
124        visitor.state.handler.last_err()?;
125
126        // Records are always kept regardless of whether they appear in function bodies, because
127        // they are part of the program's public definition and required for interface conformance.
128        visitor.used_composites.extend(visitor.state.symbol_table.iter_records().map(|(loc, _)| loc.clone()));
129
130        // Remove unused composites from the composite graph.
131        // This prevents unused composite definitions from being included in the generated bytecode.
132        visitor.state.composite_graph.retain_nodes(&visitor.used_composites);
133        visitor.state.ast = ast;
134
135        Ok(())
136    }
137}