leo-passes 2.6.1

Compiler passes for the Leo programming language
Documentation
// Copyright (C) 2019-2025 Provable Inc.
// This file is part of the Leo library.

// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.

mod expression;

mod program;

mod scope_state;

mod statement;

mod visitor;
use visitor::*;

use self::scope_state::ScopeState;
use crate::{CallGraph, CompilerState, Pass, StructGraph};

use leo_ast::ProgramVisitor;
use leo_errors::Result;

use indexmap::{IndexMap, IndexSet};

/// Specify network limits for type checking.
pub struct TypeCheckingInput {
    pub max_array_elements: usize,
    pub max_mappings: usize,
    pub max_functions: usize,
}

/// A pass to check types.
///
/// Also constructs the struct graph, call graph, and local symbol table data.
pub struct TypeChecking;

impl Pass for TypeChecking {
    type Input = TypeCheckingInput;
    type Output = ();

    const NAME: &'static str = "TypeChecking";

    fn do_pass(input: Self::Input, state: &mut CompilerState) -> Result<Self::Output> {
        let struct_names = state
            .symbol_table
            .iter_records()
            .map(|(loc, _)| loc.name)
            .chain(state.symbol_table.iter_structs().map(|(name, _)| name))
            .collect();
        let function_names = state.symbol_table.iter_functions().map(|(loc, _)| loc.name).collect();

        let ast = std::mem::take(&mut state.ast);

        // Note that the `struct_graph` and `call_graph` are initialized with their full node sets.
        state.struct_graph = StructGraph::new(struct_names);
        state.call_graph = CallGraph::new(function_names);

        let mut visitor = TypeCheckingVisitor {
            state,
            scope_state: ScopeState::new(),
            async_function_input_types: IndexMap::new(),
            async_function_callers: IndexMap::new(),
            used_structs: IndexSet::new(),
            conditional_scopes: Vec::new(),
            limits: input,
        };
        visitor.visit_program(ast.as_repr());
        visitor.state.handler.last_err().map_err(|e| *e)?;

        // Remove unused structs from the struct graph.
        // This prevents unused struct definitions from being included in the generated bytecode.
        visitor.state.struct_graph.retain_nodes(&visitor.used_structs);
        visitor.state.ast = ast;

        Ok(())
    }
}