leo-passes 4.0.2

Compiler passes for the Leo programming language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
// Copyright (C) 2019-2026 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/>.

use crate::{CompilerState, Replacer, SsaFormingInput, static_single_assignment::visitor::SsaFormingVisitor};
use indexmap::{IndexMap, IndexSet};
use itertools::Itertools;
use leo_ast::{Function, Location, *};
use leo_errors::TypeCheckerWarning;
use leo_span::{Symbol, sym};

pub struct TransformVisitor<'a> {
    pub state: &'a mut CompilerState,
    /// Functions that should always be inlined.
    pub always_inline: IndexSet<Vec<Symbol>>,
    /// A map of reconstructed functions in the current program scope.
    pub reconstructed_functions: Vec<(Location, Function)>,
    /// The main program.
    pub program: Symbol,
    /// A map to provide faster lookup of functions.
    pub function_map: IndexMap<Location, Function>,
    /// Whether or not we are currently traversing a block that's executed onchain (either final block or final fn block).
    pub is_onchain: bool,
}

impl<'a> TransformVisitor<'a> {
    /// Check if a names an optional type. We don't need to check the type
    /// recursively with the sumbol table, hiding optionals behind structs is
    /// allowed.
    fn names_optional_type(ty: &Type) -> bool {
        match ty {
            Type::Optional(_) => true,
            Type::Tuple(tuple) => tuple.elements().iter().any(Self::names_optional_type),
            Type::Array(array) => Self::names_optional_type(array.element_type()),
            _ => false,
        }
    }
}

impl ProgramReconstructor for TransformVisitor<'_> {
    fn reconstruct_program_scope(&mut self, input: ProgramScope) -> ProgramScope {
        // Set the program name.
        self.program = input.program_id.as_symbol();

        // Get the post-order ordering of the call graph.
        // Note that the post-order always contains all nodes in the call graph.
        // Note that the unwrap is safe since type checking guarantees that the call graph is acyclic.
        // Keep full Location (program + path) to ensure correct lookups.
        let order: Vec<Location> = self
            .state
            .call_graph
            .post_order_with_filter(|location| location.program == self.program)
            .unwrap()
            .into_iter()
            .collect();

        // Reconstruct and accumulate each of the functions in post-order.
        for function_location in order {
            // None: If `function_location` is not in `function_map`, then it must be an external function.
            // TODO: Check that this is indeed an external function. Requires a redesign of the symbol table.
            if let Some(function) = self.function_map.shift_remove(&function_location) {
                // Reconstruct the function.
                let reconstructed_function = self.reconstruct_function(function);
                // Add the reconstructed function to the mapping.
                self.reconstructed_functions.push((function_location.clone(), reconstructed_function));
            }
        }

        // Drop any library functions that were not reachable from this program (dead library code).
        // They are not needed and would fail the sanity check below.
        self.function_map.retain(|loc, _| !self.state.symbol_table.is_library(loc.program));

        // This is a sanity check to ensure that all non-library functions in the program scope have been processed.
        assert!(self.function_map.is_empty(), "All functions in the program should have been processed.");

        // Reconstruct the constructor.
        // Note: This must be done after the functions have been reconstructed to ensure that every callee function has been inlined.
        let constructor = input.constructor.map(|constructor| self.reconstruct_constructor(constructor));

        // Partition reconstructed functions: retain library functions for later stub scopes to look up,
        // and collect only top-level functions from the current scope for output.
        let all_reconstructed = core::mem::take(&mut self.reconstructed_functions);
        let (library_fns, current_fns): (Vec<_>, Vec<_>) =
            all_reconstructed.into_iter().partition(|(loc, _)| loc.program != self.program);
        self.reconstructed_functions = library_fns;
        let functions = current_fns
            .into_iter()
            .filter_map(|(loc, f)| {
                // Emit only single-segment paths; Functions in submodules have all been
                // inlined at their call sites and must not appear as standalone functions in the output.
                loc.path.split_last().filter(|(_, rest)| rest.is_empty()).map(|(last, _)| (*last, f))
            })
            .collect();

        ProgramScope {
            program_id: input.program_id,
            parents: input.parents.into_iter().map(|(s, t)| (s, self.reconstruct_type(t).0)).collect(),
            composites: input.composites,
            mappings: input.mappings,
            storage_variables: input.storage_variables,
            constructor,
            functions,
            interfaces: input.interfaces,
            consts: input.consts,
            span: input.span,
        }
    }

    fn reconstruct_function(&mut self, input: Function) -> Function {
        Function {
            annotations: input.annotations,
            variant: input.variant,
            identifier: input.identifier,
            const_parameters: input.const_parameters,
            input: input.input,
            output: input.output,
            output_type: input.output_type,
            block: {
                // Set the `is_onchain` flag before reconstructing the block.
                self.is_onchain = input.variant.is_onchain();
                // Reconstruct the block.
                let block = self.reconstruct_block(input.block).0;
                // Reset the `is_onchain` flag.
                self.is_onchain = false;
                block
            },
            span: input.span,
            id: input.id,
        }
    }

    fn reconstruct_constructor(&mut self, input: Constructor) -> Constructor {
        Constructor {
            annotations: input.annotations,
            block: {
                // Set the `is_onchain` flag before reconstructing the block.
                self.is_onchain = true;
                // Reconstruct the block.
                let block = self.reconstruct_block(input.block).0;
                // Reset the `is_onchain` flag.
                self.is_onchain = false;
                block
            },
            span: input.span,
            id: input.id,
        }
    }

    fn reconstruct_program(&mut self, input: Program) -> Program {
        // Populate `self.function_map` using the functions in the program scopes and the modules.
        // Use full Location (program + path) as keys to avoid collisions between programs.
        input
            .modules
            .iter()
            .flat_map(|(module_path, m)| {
                let program = m.program_name;
                m.functions.iter().map(move |(name, f)| {
                    let path: Vec<Symbol> = module_path.iter().cloned().chain(std::iter::once(*name)).collect();
                    (Location::new(program, path), f.clone())
                })
            })
            .chain(input.program_scopes.iter().flat_map(|(program_name, scope)| {
                scope.functions.iter().map(move |(name, f)| (Location::new(*program_name, vec![*name]), f.clone()))
            }))
            .for_each(|(location, f)| {
                self.function_map.insert(location, f);
            });

        // Populate `function_map` with library functions from FromLibrary stubs.
        // Library functions are inlined at call sites just like module functions.
        input.stubs.iter().for_each(|(_, stub)| {
            if let Stub::FromLibrary { library, .. } = stub {
                library.functions.iter().for_each(|(name, f)| {
                    self.function_map.entry(Location::new(library.name, vec![*name])).or_insert_with(|| f.clone());
                });
                // Also seed module functions from the library.
                library.modules.iter().for_each(|(module_path, m)| {
                    m.functions.iter().for_each(|(name, f)| {
                        let path: Vec<Symbol> = module_path.iter().cloned().chain(std::iter::once(*name)).collect();
                        self.function_map.entry(Location::new(library.name, path)).or_insert_with(|| f.clone());
                    });
                });
            }
        });

        // Reconstruct program scopes. Inline functions defined in modules will be traversed
        // using the call graph and reconstructed in the right order.
        let program_scopes =
            input.program_scopes.into_iter().map(|(id, scope)| (id, self.reconstruct_program_scope(scope))).collect();

        // Process FromLeo stubs so that FinalFn functions are inlined within them.
        // This is necessary because code generation will emit bytecode for FromLeo stubs,
        // and FinalFn functions cannot exist as standalone functions in bytecode.
        let stubs = input
            .stubs
            .into_iter()
            .map(|(name, stub)| {
                match stub {
                    Stub::FromLeo { program, parents } => {
                        let processed_program = self.reconstruct_program(program);
                        (name, Stub::FromLeo { program: processed_program, parents })
                    }
                    // FromAleo stubs don't have Leo AST, so nothing to inline.
                    other @ Stub::FromAleo { .. } => (name, other),
                    // Similarly, nothing to do for libraries.
                    other @ Stub::FromLibrary { .. } => (name, other),
                }
            })
            .collect();

        Program { program_scopes, stubs, ..input }
    }
}

impl AstReconstructor for TransformVisitor<'_> {
    type AdditionalInput = ();
    type AdditionalOutput = Vec<Statement>;

    /* Expressions */
    fn reconstruct_call(&mut self, input: CallExpression, _additional: &()) -> (Expression, Self::AdditionalOutput) {
        let function_location = input.function.expect_global_location();

        // Pass through calls to external programs (non-library). Library functions and module
        // functions are always inlined; only true cross-program calls are left as-is.
        if function_location.program != self.program && !self.state.symbol_table.is_library(function_location.program) {
            return (input.into(), Default::default());
        }

        // Lookup the reconstructed callee function.
        // Since this pass processes functions in post-order, the callee function is guaranteed to exist in `self.reconstructed_functions`
        // Use full Location (program + path) to ensure correct lookup across multiple programs.
        let (_, callee) = self
            .reconstructed_functions
            .iter()
            .find(|(loc, _)| loc == function_location)
            .expect("guaranteed to exist due to post-order traversal of the call graph.");

        let call_count_ref = self.state.call_count.get_mut(function_location).expect("Guaranteed by type checking");

        let has_no_inline_annotation = callee.annotations.iter().any(|a| a.identifier.name == sym::no_inline);

        // Mandatory inlining conditions
        let mandatory_cond = |cond: bool, msg: &str| -> bool {
            if has_no_inline_annotation {
                self.state.handler.emit_warning(TypeCheckerWarning::no_inline_ignored(
                    callee.identifier.name,
                    msg,
                    callee.annotations.iter().find(|a| a.identifier.name == sym::no_inline).unwrap().span,
                ));
            }
            cond
        };

        let optional_cond = |cond: bool| -> bool { !has_no_inline_annotation && cond };

        let should_inline = mandatory_cond(
            function_location.program == self.program && function_location.path.len() > 1,
            "this is a module function",
        ) || match callee.variant {
            // Always inline library functions (they cannot exist as standalone Aleo functions).
            _ if self.state.symbol_table.is_library(function_location.program) => {
                mandatory_cond(true, "this is a library function")
            }
            Variant::FinalFn => mandatory_cond(true, "this is a final fn"),
            Variant::Fn => {
                mandatory_cond(
                    self.is_onchain,
                    "the function is called from an on-chain context (constructor or finalize)",
                ) ||
                mandatory_cond(!callee.const_parameters.is_empty(), "the function has const parameters") ||
                mandatory_cond(callee.input.len() > 16, "this function has more than 16 arguments") ||
                mandatory_cond(
                    Self::names_optional_type(&callee.output_type),
                    "this function returns a type naming an optional",
                ) ||
                mandatory_cond(
                    callee.input.iter().any(|arg| Self::names_optional_type(&arg.type_)),
                    "this function has an argument naming an optional",
                ) ||
                mandatory_cond(
                    self.always_inline.contains(&vec![callee.identifier.name]),
                    "this function has been called from another function",
                ) ||
                // Called only once
                optional_cond(*call_count_ref == 1) ||
                // Has no arguments
                optional_cond(callee.input.is_empty()) ||
                // Has only empty arguments
                optional_cond(callee.input.iter().all(|arg| arg.type_.is_empty()))
            }
            Variant::EntryPoint | Variant::Finalize => false,
        };

        // Inline the callee function, if required, otherwise, return the call expression.
        if should_inline {
            // We are inlining, thus removing one call
            *call_count_ref -= 1;

            // Construct a mapping from input variables of the callee function to arguments passed to the callee.
            let parameter_to_argument = callee
                .input
                .iter()
                .map(|input| input.identifier().name)
                .zip_eq(input.arguments)
                .collect::<IndexMap<_, _>>();

            // Function to replace path expressions with their corresponding const argument or keep them unchanged.
            let replace_path = |expr: &Expression| match expr {
                Expression::Path(path) => parameter_to_argument
                    .get(&path.identifier().name)
                    .map_or(Expression::Path(path.clone()), |expr| expr.clone()),
                _ => expr.clone(),
            };

            // Replace path expressions with their corresponding const argument or keep them unchanged.
            let reconstructed_block = Replacer::new(replace_path, false /* refresh IDs */, self.state)
                .reconstruct_block(callee.block.clone())
                .0;

            // Run SSA formation on the inlined block and rename definitions. Renaming is necessary to avoid shadowing variables.
            let mut inlined_statements =
                SsaFormingVisitor::new(self.state, SsaFormingInput { rename_defs: true }, self.program)
                    .consume_block(reconstructed_block);

            // If the inlined block returns a value, then use the value in place of the call expression; otherwise, use the unit expression.
            let result = match inlined_statements.last() {
                Some(Statement::Return(_)) => {
                    // Note that this unwrap is safe since we know that the last statement is a return statement.
                    match inlined_statements.pop().unwrap() {
                        Statement::Return(ReturnStatement { expression, .. }) => expression,
                        _ => panic!("This branch checks that the last statement is a return statement."),
                    }
                }
                _ => {
                    let id = self.state.node_builder.next_id();
                    self.state.type_table.insert(id, Type::Unit);
                    UnitExpression { span: Default::default(), id }.into()
                }
            };

            (result, inlined_statements)
        } else {
            (input.into(), Default::default())
        }
    }

    /* Statements */
    fn reconstruct_assign(&mut self, _input: AssignStatement) -> (Statement, Self::AdditionalOutput) {
        panic!("`AssignStatement`s should not exist in the AST at this phase of compilation.")
    }

    /// Reconstructs the statements inside a basic block, accumulating any statements produced by function inlining.
    fn reconstruct_block(&mut self, block: Block) -> (Block, Self::AdditionalOutput) {
        let mut statements = Vec::with_capacity(block.statements.len());

        for statement in block.statements {
            let (reconstructed_statement, additional_statements) = self.reconstruct_statement(statement);
            statements.extend(additional_statements);
            statements.push(reconstructed_statement);
        }

        (Block { span: block.span, statements, id: block.id }, Default::default())
    }

    /// Flattening removes conditional statements from the program.
    fn reconstruct_conditional(&mut self, input: ConditionalStatement) -> (Statement, Self::AdditionalOutput) {
        if !self.is_onchain {
            panic!("`ConditionalStatement`s should not be in the AST at this phase of compilation.")
        } else {
            (
                ConditionalStatement {
                    condition: self.reconstruct_expression(input.condition, &()).0,
                    then: self.reconstruct_block(input.then).0,
                    otherwise: input.otherwise.map(|n| Box::new(self.reconstruct_statement(*n).0)),
                    span: input.span,
                    id: input.id,
                }
                .into(),
                Default::default(),
            )
        }
    }

    /// Reconstruct a definition statement by inlining any function calls.
    /// This function also segments tuple assignment statements into multiple assignment statements.
    fn reconstruct_definition(&mut self, mut input: DefinitionStatement) -> (Statement, Self::AdditionalOutput) {
        let (value, mut statements) = self.reconstruct_expression(input.value, &());
        match (input.place, value) {
            // If we just inlined the production of a tuple literal, we need multiple definition statements.
            (DefinitionPlace::Multiple(left), Expression::Tuple(right)) => {
                assert_eq!(left.len(), right.elements.len());
                for (identifier, rhs_value) in left.into_iter().zip(right.elements) {
                    let stmt = DefinitionStatement {
                        place: DefinitionPlace::Single(identifier),
                        type_: None,
                        value: rhs_value,
                        span: Default::default(),
                        id: self.state.node_builder.next_id(),
                    }
                    .into();

                    statements.push(stmt);
                }
                (Statement::dummy(), statements)
            }

            (place, value) => {
                input.value = value;
                input.place = place;
                (input.into(), statements)
            }
        }
    }

    /// Reconstructs expression statements by inlining any function calls.
    fn reconstruct_expression_statement(&mut self, input: ExpressionStatement) -> (Statement, Self::AdditionalOutput) {
        // Reconstruct the expression.
        // Note that type checking guarantees that the expression is a function call.
        let (expression, additional_statements) = self.reconstruct_expression(input.expression, &());

        // If the resulting expression is a unit expression, return a dummy statement.
        let statement = match expression {
            Expression::Unit(_) => Statement::dummy(),
            _ => ExpressionStatement { expression, ..input }.into(),
        };

        (statement, additional_statements)
    }

    /// Loop unrolling unrolls and removes iteration statements from the program.
    fn reconstruct_iteration(&mut self, _: IterationStatement) -> (Statement, Self::AdditionalOutput) {
        panic!("`IterationStatement`s should not be in the AST at this phase of compilation.");
    }
}