leo_passes/loop_unrolling/
ast.rs

1// Copyright (C) 2019-2025 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_ast::{Expression::Literal, interpreter_value::literal_to_value, *};
18
19use super::UnrollingVisitor;
20
21impl AstReconstructor for UnrollingVisitor<'_> {
22    type AdditionalInput = ();
23    type AdditionalOutput = ();
24
25    /* Expressions */
26    fn reconstruct_repeat(
27        &mut self,
28        input: RepeatExpression,
29        _additional: &(),
30    ) -> (Expression, Self::AdditionalOutput) {
31        // Because the value of `count` affects the type of a repeat expression, we need to assign a new ID to the
32        // reconstructed `RepeatExpression` and update the type table accordingly.
33        let new_id = self.state.node_builder.next_id();
34        let new_count = self.reconstruct_expression(input.count, &()).0;
35        let el_ty = self.state.type_table.get(&input.expr.id()).expect("guaranteed by type checking");
36        self.state.type_table.insert(new_id, Type::Array(ArrayType::new(el_ty, new_count.clone())));
37        (
38            RepeatExpression {
39                expr: self.reconstruct_expression(input.expr, &()).0,
40                count: new_count,
41                id: new_id,
42                ..input
43            }
44            .into(),
45            Default::default(),
46        )
47    }
48
49    fn reconstruct_block(&mut self, mut input: Block) -> (Block, Self::AdditionalOutput) {
50        self.in_scope(input.id(), |slf| {
51            input.statements = input.statements.into_iter().map(|stmt| slf.reconstruct_statement(stmt).0).collect();
52
53            (input, Default::default())
54        })
55    }
56
57    fn reconstruct_const(&mut self, input: ConstDeclaration) -> (Statement, Self::AdditionalOutput) {
58        (input.into(), Default::default())
59    }
60
61    fn reconstruct_definition(&mut self, input: DefinitionStatement) -> (Statement, Self::AdditionalOutput) {
62        (
63            DefinitionStatement {
64                type_: input.type_.map(|ty| self.reconstruct_type(ty).0),
65                value: self.reconstruct_expression(input.value, &()).0,
66                ..input
67            }
68            .into(),
69            Default::default(),
70        )
71    }
72
73    fn reconstruct_iteration(&mut self, input: IterationStatement) -> (Statement, Self::AdditionalOutput) {
74        // There's no need to reconstruct the bound expressions - they must be constants
75        // which can be evaluated through constant propagation.
76
77        let Literal(start_lit_ref) = &input.start else {
78            self.loop_not_unrolled = Some(input.start.span());
79            return (Statement::Iteration(Box::new(input)), Default::default());
80        };
81
82        let Literal(stop_lit_ref) = &input.stop else {
83            self.loop_not_unrolled = Some(input.stop.span());
84            return (Statement::Iteration(Box::new(input)), Default::default());
85        };
86
87        // Helper to clone and resolve Unsuffixed -> Integer literal based on type table
88        let resolve_unsuffixed = |lit: &leo_ast::Literal, expr_id| {
89            let mut resolved = lit.clone();
90            if let LiteralVariant::Unsuffixed(s) = &resolved.variant
91                && let Some(Type::Integer(integer_type)) = self.state.type_table.get(&expr_id)
92            {
93                resolved.variant = LiteralVariant::Integer(integer_type, s.clone());
94            }
95            resolved
96        };
97
98        // Clone and resolve both literals
99        let resolved_start_lit = resolve_unsuffixed(start_lit_ref, input.start.id());
100        let resolved_stop_lit = resolve_unsuffixed(stop_lit_ref, input.stop.id());
101
102        // Convert resolved literals into constant values
103        let start_value =
104            literal_to_value(&resolved_start_lit, &None).expect("Parsing and type checking guarantee this works.");
105        let stop_value =
106            literal_to_value(&resolved_stop_lit, &None).expect("Parsing and type checking guarantee this works.");
107
108        self.loop_unrolled = true;
109
110        // Actually unroll.
111        (
112            if start_value.gte(&stop_value).expect("Type checking guarantees these are the same type") {
113                let new_block_id = self.state.node_builder.next_id();
114                self.in_scope(new_block_id, |_| {
115                    Statement::from(Block { span: input.span, statements: vec![], id: new_block_id })
116                })
117            } else {
118                self.unroll_iteration_statement(input, start_value, stop_value)
119            },
120            Default::default(),
121        )
122    }
123}