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
// Copyright (C) 2019-2024 Aleo Systems 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::Destructurer;

use leo_ast::{
    AssignStatement,
    Block,
    ConditionalStatement,
    ConsoleStatement,
    DefinitionStatement,
    Expression,
    ExpressionReconstructor,
    Identifier,
    IterationStatement,
    Node,
    ReturnStatement,
    Statement,
    StatementReconstructor,
    TupleExpression,
    Type,
};

use itertools::Itertools;

impl StatementReconstructor for Destructurer<'_> {
    /// Flattens an assign statement, if necessary.
    /// Marks variables as structs as necessary.
    /// Note that new statements are only produced if the right hand side is a ternary expression over structs.
    /// Otherwise, the statement is returned as is.
    fn reconstruct_assign(&mut self, assign: AssignStatement) -> (Statement, Self::AdditionalOutput) {
        // Flatten the rhs of the assignment.
        let value = self.reconstruct_expression(assign.value).0;
        match (assign.place, value.clone()) {
            // If the lhs is an identifier and the rhs is a tuple, then add the tuple to `self.tuples`.
            // Return a dummy statement in its place.
            (Expression::Identifier(identifier), Expression::Tuple(tuple)) => {
                self.tuples.insert(identifier.name, tuple);
                // Note that tuple assignments are removed from the AST.
                (Statement::dummy(Default::default(), self.node_builder.next_id()), Default::default())
            }
            // If the lhs is an identifier and the rhs is an identifier that is a tuple, then add it to `self.tuples`.
            // Return a dummy statement in its place.
            (Expression::Identifier(lhs_identifier), Expression::Identifier(rhs_identifier))
                if self.tuples.contains_key(&rhs_identifier.name) =>
            {
                // Lookup the entry in `self.tuples` and add it for the lhs of the assignment.
                // Note that the `unwrap` is safe since the match arm checks that the entry exists.
                self.tuples.insert(lhs_identifier.name, self.tuples.get(&rhs_identifier.name).unwrap().clone());
                // Note that tuple assignments are removed from the AST.
                (Statement::dummy(Default::default(), self.node_builder.next_id()), Default::default())
            }
            // If the lhs is an identifier and the rhs is a function call that produces a tuple, then add it to `self.tuples`.
            (Expression::Identifier(lhs_identifier), Expression::Call(call)) => {
                // Retrieve the entry in the type table for the function call.
                let value_type = match self.type_table.get(&call.id()) {
                    Some(type_) => type_,
                    None => unreachable!("Type checking guarantees that the type of the rhs is in the type table."),
                };

                match &value_type {
                    // If the function returns a tuple, reconstruct the assignment and add an entry to `self.tuples`.
                    Type::Tuple(tuple) => {
                        // Create a new tuple expression with unique identifiers for each index of the lhs.
                        let tuple_expression = TupleExpression {
                            elements: (0..tuple.length())
                                .zip_eq(tuple.elements().iter())
                                .map(|(i, type_)| {
                                    // Return the identifier as an expression.
                                    Expression::Identifier(Identifier::new(
                                        self.assigner.unique_symbol(lhs_identifier.name, format!("$index${i}$")),
                                        {
                                            // Construct a node ID for the identifier.
                                            let id = self.node_builder.next_id();
                                            // Update the type table with the type.
                                            self.type_table.insert(id, type_.clone());
                                            id
                                        },
                                    ))
                                })
                                .collect(),
                            span: Default::default(),
                            id: {
                                // Construct a node ID for the tuple expression.
                                let id = self.node_builder.next_id();
                                // Update the type table with the type.
                                self.type_table.insert(id, Type::Tuple(tuple.clone()));
                                id
                            },
                        };
                        // Add the `tuple_expression` to `self.tuples`.
                        self.tuples.insert(lhs_identifier.name, tuple_expression.clone());

                        // Update the type table with the type of the tuple expression.
                        self.type_table.insert(tuple_expression.id, Type::Tuple(tuple.clone()));

                        // Construct a new assignment statement with a tuple expression on the lhs.
                        (
                            Statement::Assign(Box::new(AssignStatement {
                                place: Expression::Tuple(tuple_expression),
                                value: Expression::Call(call),
                                span: Default::default(),
                                id: self.node_builder.next_id(),
                            })),
                            Default::default(),
                        )
                    }
                    // Otherwise, reconstruct the assignment as is.
                    _ => (self.simple_assign_statement(lhs_identifier, Expression::Call(call)), Default::default()),
                }
            }
            (Expression::Identifier(identifier), expression) => {
                (self.simple_assign_statement(identifier, expression), Default::default())
            }
            // If the lhs is a tuple and the rhs is a function call, then return the reconstructed statement.
            (Expression::Tuple(tuple), Expression::Call(call)) => (
                Statement::Assign(Box::new(AssignStatement {
                    place: Expression::Tuple(tuple),
                    value: Expression::Call(call),
                    span: Default::default(),
                    id: self.node_builder.next_id(),
                })),
                Default::default(),
            ),
            // If the lhs is a tuple and the rhs is a tuple, create a new assign statement for each tuple element.
            (Expression::Tuple(lhs_tuple), Expression::Tuple(rhs_tuple)) => {
                let statements = lhs_tuple
                    .elements
                    .into_iter()
                    .zip_eq(rhs_tuple.elements)
                    .map(|(lhs, rhs)| {
                        // Get the type of the rhs.
                        let type_ = match self.type_table.get(&lhs.id()) {
                            Some(type_) => type_.clone(),
                            None => {
                                unreachable!("Type checking guarantees that the type of the lhs is in the type table.")
                            }
                        };
                        // Set the type of the lhs.
                        self.type_table.insert(rhs.id(), type_);
                        // Return the assign statement.
                        Statement::Assign(Box::new(AssignStatement {
                            place: lhs,
                            value: rhs,
                            span: Default::default(),
                            id: self.node_builder.next_id(),
                        }))
                    })
                    .collect();
                (Statement::dummy(Default::default(), self.node_builder.next_id()), statements)
            }
            // If the lhs is a tuple and the rhs is an identifier that is a tuple, create a new assign statement for each tuple element.
            (Expression::Tuple(lhs_tuple), Expression::Identifier(identifier))
                if self.tuples.contains_key(&identifier.name) =>
            {
                // Lookup the entry in `self.tuples`.
                // Note that the `unwrap` is safe since the match arm checks that the entry exists.
                let rhs_tuple = self.tuples.get(&identifier.name).unwrap().clone();
                // Create a new assign statement for each tuple element.
                let statements = lhs_tuple
                    .elements
                    .into_iter()
                    .zip_eq(rhs_tuple.elements)
                    .map(|(lhs, rhs)| {
                        // Get the type of the rhs.
                        let type_ = match self.type_table.get(&lhs.id()) {
                            Some(type_) => type_.clone(),
                            None => {
                                unreachable!("Type checking guarantees that the type of the lhs is in the type table.")
                            }
                        };
                        // Set the type of the lhs.
                        self.type_table.insert(rhs.id(), type_);
                        // Return the assign statement.
                        Statement::Assign(Box::new(AssignStatement {
                            place: lhs,
                            value: rhs,
                            span: Default::default(),
                            id: self.node_builder.next_id(),
                        }))
                    })
                    .collect();
                (Statement::dummy(Default::default(), self.node_builder.next_id()), statements)
            }
            // If the lhs of an assignment is a tuple, then the rhs can be one of the following:
            //  - A function call that produces a tuple. (handled above)
            //  - A tuple. (handled above)
            //  - An identifier that is a tuple. (handled above)
            //  - A ternary expression that produces a tuple. (handled when the rhs is flattened above)
            (Expression::Tuple(_), _) => {
                unreachable!("`Type checking guarantees that the rhs of an assignment to a tuple is a tuple.`")
            }
            _ => unreachable!("`AssignStatement`s can only have `Identifier`s or `Tuple`s on the left hand side."),
        }
    }

    fn reconstruct_block(&mut self, block: Block) -> (Block, Self::AdditionalOutput) {
        let mut statements = Vec::with_capacity(block.statements.len());

        // Reconstruct the statements in the block, accumulating any additional statements.
        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: self.node_builder.next_id() }, Default::default())
    }

    fn reconstruct_conditional(&mut self, input: ConditionalStatement) -> (Statement, Self::AdditionalOutput) {
        // Conditional statements can only exist in finalize blocks.
        if !self.is_async {
            unreachable!("`ConditionalStatement`s should not be in the AST at this phase of compilation.")
        } else {
            (
                Statement::Conditional(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,
                }),
                Default::default(),
            )
        }
    }

    fn reconstruct_console(&mut self, _: ConsoleStatement) -> (Statement, Self::AdditionalOutput) {
        unreachable!("`ConsoleStatement`s should not be in the AST at this phase of compilation.")
    }

    fn reconstruct_definition(&mut self, _: DefinitionStatement) -> (Statement, Self::AdditionalOutput) {
        unreachable!("`DefinitionStatement`s should not exist in the AST at this phase of compilation.")
    }

    fn reconstruct_iteration(&mut self, _: IterationStatement) -> (Statement, Self::AdditionalOutput) {
        unreachable!("`IterationStatement`s should not be in the AST at this phase of compilation.");
    }

    /// Reconstructs
    fn reconstruct_return(&mut self, input: ReturnStatement) -> (Statement, Self::AdditionalOutput) {
        // Note that SSA guarantees that `input.expression` is either a literal, identifier, or unit expression.
        let expression = match input.expression {
            // If the input is an identifier that maps to a tuple, use the tuple expression.
            Expression::Identifier(identifier) if self.tuples.contains_key(&identifier.name) => {
                // Note that the `unwrap` is safe since the match arm checks that the entry exists in `self.tuples`.
                let tuple = self.tuples.get(&identifier.name).unwrap().clone();
                Expression::Tuple(tuple)
            }
            // Otherwise, use the original expression.
            _ => input.expression,
        };

        (Statement::Return(ReturnStatement { expression, span: input.span, id: input.id }), Default::default())
    }
}