leo-passes 3.4.0

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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
// 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/>.

use super::*;

use leo_ast::{
    ArrayAccess,
    ArrayExpression,
    AssociatedConstantExpression,
    AssociatedFunctionExpression,
    BinaryExpression,
    BinaryOperation,
    CallExpression,
    CastExpression,
    CoreFunction,
    Expression,
    IntegerType,
    Literal,
    LiteralVariant,
    Location,
    LocatorExpression,
    MemberAccess,
    NetworkName,
    Node,
    Path,
    ProgramId,
    RepeatExpression,
    StructExpression,
    TernaryExpression,
    TupleExpression,
    Type,
    UnaryExpression,
    UnaryOperation,
    Variant,
};
use leo_span::sym;
use snarkvm::{
    prelude::{CanaryV0, MainnetV0, TestnetV0},
    synthesizer::program::SerializeVariant,
};

use anyhow::bail;
use std::borrow::Borrow;

/// Implement the necessary methods to visit nodes in the AST.
impl CodeGeneratingVisitor<'_> {
    pub fn visit_expression(&mut self, input: &Expression) -> (Option<AleoExpr>, Vec<AleoStmt>) {
        let is_empty_type = self.state.type_table.get(&input.id()).map(|ty| ty.is_empty()).unwrap_or(false);
        let is_pure = input.is_pure();

        if is_empty_type && is_pure {
            // ignore expresssion
            return (None, vec![]);
        }

        let some_expr = |(expr, stmts): (AleoExpr, Vec<AleoStmt>)| (Some(expr), stmts);

        match input {
            Expression::ArrayAccess(expr) => (Some(self.visit_array_access(expr)), vec![]),
            Expression::AssociatedConstant(expr) => (Some(self.visit_associated_constant(expr)), vec![]),
            Expression::MemberAccess(expr) => (Some(self.visit_member_access(expr)), vec![]),
            Expression::Path(expr) => (Some(self.visit_path(expr)), vec![]),
            Expression::Literal(expr) => (Some(self.visit_value(expr)), vec![]),
            Expression::Locator(expr) => (Some(self.visit_locator(expr)), vec![]),

            Expression::Array(expr) => some_expr(self.visit_array(expr)),
            Expression::Binary(expr) => some_expr(self.visit_binary(expr)),
            Expression::Call(expr) => some_expr(self.visit_call(expr)),
            Expression::Cast(expr) => some_expr(self.visit_cast(expr)),
            Expression::Struct(expr) => some_expr(self.visit_struct_init(expr)),
            Expression::Repeat(expr) => some_expr(self.visit_repeat(expr)),
            Expression::Ternary(expr) => some_expr(self.visit_ternary(expr)),
            Expression::Tuple(expr) => some_expr(self.visit_tuple(expr)),
            Expression::Unary(expr) => some_expr(self.visit_unary(expr)),

            Expression::AssociatedFunction(expr) => self.visit_associated_function(expr),

            Expression::Async(..) => {
                panic!("`AsyncExpression`s should not be in the AST at this phase of compilation.")
            }
            Expression::Err(..) => panic!("`ErrExpression`s should not be in the AST at this phase of compilation."),
            Expression::TupleAccess(..) => panic!("Tuple accesses should not appear in the AST at this point."),
            Expression::Unit(..) => panic!("`UnitExpression`s should not be visited during code generation."),
        }
    }

    fn visit_path(&mut self, input: &Path) -> AleoExpr {
        // The only relevant paths here are paths to local variable or to mappings, so we really only care about their
        // names since mappings are only allowed in the top level program scope
        let var_name = input.identifier().name;
        self.variable_mapping.get(&var_name).or_else(|| self.global_mapping.get(&var_name)).unwrap().clone()
    }

    fn visit_value(&mut self, input: &Literal) -> AleoExpr {
        // AVM can only parse decimal numbers.
        let literal = if let LiteralVariant::Unsuffixed(value) = &input.variant {
            // For unsuffixed lierals, consult the `type_table` for their types. The type checker
            // ensures that their type can only be `Integer`, `Field`, `Group`, or `Scalar`.
            match self.state.type_table.get(&input.id) {
                Some(Type::Integer(int_ty)) => Literal {
                    variant: LiteralVariant::Integer(int_ty, value.clone()),
                    id: self.state.node_builder.next_id(),
                    span: input.span,
                },
                Some(Type::Field) => Literal {
                    variant: LiteralVariant::Field(value.clone()),
                    id: self.state.node_builder.next_id(),
                    span: input.span,
                },
                Some(Type::Group) => Literal {
                    variant: LiteralVariant::Group(value.clone()),
                    id: self.state.node_builder.next_id(),
                    span: input.span,
                },
                Some(Type::Scalar) => Literal {
                    variant: LiteralVariant::Scalar(value.clone()),
                    id: self.state.node_builder.next_id(),
                    span: input.span,
                },
                _ => panic!(
                    "Unexpected type for unsuffixed integer literal. This should have been caught by the type checker"
                ),
            }
        } else {
            input.clone()
        };
        AleoExpr::Literal(literal)
    }

    fn visit_locator(&mut self, input: &LocatorExpression) -> AleoExpr {
        if input.program.name.name == self.program_id.expect("Locators only appear within programs.").name.name {
            // This locator refers to the current program, so we only output the name, not the program.
            AleoExpr::RawName(input.name.to_string())
        } else {
            AleoExpr::RawName(input.to_string())
        }
    }

    fn visit_binary(&mut self, input: &BinaryExpression) -> (AleoExpr, Vec<AleoStmt>) {
        let (left, left_instructions) = self.visit_expression(&input.left);
        let (right, right_instructions) = self.visit_expression(&input.right);
        let left = left.expect("Trying to operate on an empty expression");
        let right = right.expect("Trying to operate on an empty expression");

        let dest_reg = self.next_register();

        let binary_instruction = match input.op {
            BinaryOperation::Add => AleoStmt::Add(left, right, dest_reg.clone()),
            BinaryOperation::AddWrapped => AleoStmt::AddWrapped(left, right, dest_reg.clone()),
            BinaryOperation::And | BinaryOperation::BitwiseAnd => AleoStmt::And(left, right, dest_reg.clone()),
            BinaryOperation::Div => AleoStmt::Div(left, right, dest_reg.clone()),
            BinaryOperation::DivWrapped => AleoStmt::DivWrapped(left, right, dest_reg.clone()),
            BinaryOperation::Eq => AleoStmt::Eq(left, right, dest_reg.clone()),
            BinaryOperation::Gte => AleoStmt::Gte(left, right, dest_reg.clone()),
            BinaryOperation::Gt => AleoStmt::Gt(left, right, dest_reg.clone()),
            BinaryOperation::Lte => AleoStmt::Lte(left, right, dest_reg.clone()),
            BinaryOperation::Lt => AleoStmt::Lt(left, right, dest_reg.clone()),
            BinaryOperation::Mod => AleoStmt::Mod(left, right, dest_reg.clone()),
            BinaryOperation::Mul => AleoStmt::Mul(left, right, dest_reg.clone()),
            BinaryOperation::MulWrapped => AleoStmt::MulWrapped(left, right, dest_reg.clone()),
            BinaryOperation::Nand => AleoStmt::Nand(left, right, dest_reg.clone()),
            BinaryOperation::Neq => AleoStmt::Neq(left, right, dest_reg.clone()),
            BinaryOperation::Nor => AleoStmt::Nor(left, right, dest_reg.clone()),
            BinaryOperation::Or | BinaryOperation::BitwiseOr => AleoStmt::Or(left, right, dest_reg.clone()),
            BinaryOperation::Pow => AleoStmt::Pow(left, right, dest_reg.clone()),
            BinaryOperation::PowWrapped => AleoStmt::PowWrapped(left, right, dest_reg.clone()),
            BinaryOperation::Rem => AleoStmt::Rem(left, right, dest_reg.clone()),
            BinaryOperation::RemWrapped => AleoStmt::RemWrapped(left, right, dest_reg.clone()),
            BinaryOperation::Shl => AleoStmt::Shl(left, right, dest_reg.clone()),
            BinaryOperation::ShlWrapped => AleoStmt::ShlWrapped(left, right, dest_reg.clone()),
            BinaryOperation::Shr => AleoStmt::Shr(left, right, dest_reg.clone()),
            BinaryOperation::ShrWrapped => AleoStmt::ShrWrapped(left, right, dest_reg.clone()),
            BinaryOperation::Sub => AleoStmt::Sub(left, right, dest_reg.clone()),
            BinaryOperation::SubWrapped => AleoStmt::SubWrapped(left, right, dest_reg.clone()),
            BinaryOperation::Xor => AleoStmt::Xor(left, right, dest_reg.clone()),
        };

        // Concatenate the instructions.
        let mut instructions = left_instructions;
        instructions.extend(right_instructions);
        instructions.push(binary_instruction);

        (AleoExpr::Reg(dest_reg), instructions)
    }

    fn visit_cast(&mut self, input: &CastExpression) -> (AleoExpr, Vec<AleoStmt>) {
        let (operand, mut instructions) = self.visit_expression(&input.expression);
        let operand = operand.expect("Trying to cast an empty expression");

        // Construct the destination register.
        let dest_reg = self.next_register();

        let cast_instruction = AleoStmt::Cast(operand, dest_reg.clone(), Self::visit_type(&input.type_));

        // Concatenate the instructions.
        instructions.push(cast_instruction);

        (AleoExpr::Reg(dest_reg), instructions)
    }

    fn visit_array(&mut self, input: &ArrayExpression) -> (AleoExpr, Vec<AleoStmt>) {
        let mut instructions = vec![];
        let operands = input
            .elements
            .iter()
            .map(|expr| self.visit_expression(expr))
            .filter_map(|(operand, operand_instructions)| {
                instructions.extend(operand_instructions);
                operand
            })
            .collect();

        // Construct the destination register.
        let destination_register = self.next_register();

        // Get the array type.
        let Some(array_type @ Type::Array(..)) = self.state.type_table.get(&input.id) else {
            panic!("All types should be known at this phase of compilation");
        };
        let array_type: AleoType = Self::visit_type(&array_type);

        let array_instruction = AleoStmt::Cast(AleoExpr::Tuple(operands), destination_register.clone(), array_type);

        // Concatenate the instructions.
        instructions.push(array_instruction);

        (AleoExpr::Reg(destination_register), instructions)
    }

    fn visit_unary(&mut self, input: &UnaryExpression) -> (AleoExpr, Vec<AleoStmt>) {
        let (operand, stmts) = self.visit_expression(&input.receiver);
        let operand = operand.expect("Trying to operate on an empty value");

        let dest_reg = self.next_register();

        // Note that non-empty suffixes must be preceded by a space.
        let unary_instruction = match input.op {
            UnaryOperation::Abs => AleoStmt::Abs(operand, dest_reg.clone()),
            UnaryOperation::AbsWrapped => AleoStmt::AbsW(operand, dest_reg.clone()),
            UnaryOperation::Double => AleoStmt::Double(operand, dest_reg.clone()),
            UnaryOperation::Inverse => AleoStmt::Inv(operand, dest_reg.clone()),
            UnaryOperation::Not => AleoStmt::Not(operand, dest_reg.clone()),
            UnaryOperation::Negate => AleoStmt::Neg(operand, dest_reg.clone()),
            UnaryOperation::Square => AleoStmt::Square(operand, dest_reg.clone()),
            UnaryOperation::SquareRoot => AleoStmt::Sqrt(operand, dest_reg.clone()),
            UnaryOperation::ToXCoordinate => AleoStmt::Cast(operand, dest_reg.clone(), AleoType::GroupX),
            UnaryOperation::ToYCoordinate => AleoStmt::Cast(operand, dest_reg.clone(), AleoType::GroupY),
        };

        // Concatenate the instructions.
        let mut instructions = stmts;
        instructions.push(unary_instruction);

        (AleoExpr::Reg(dest_reg), instructions)
    }

    fn visit_ternary(&mut self, input: &TernaryExpression) -> (AleoExpr, Vec<AleoStmt>) {
        let (cond, cond_stmts) = self.visit_expression(&input.condition);
        let (if_true, if_true_stmts) = self.visit_expression(&input.if_true);
        let (if_false, if_false_stmts) = self.visit_expression(&input.if_false);
        let cond = cond.expect("Trying to build a ternary with an empty expression.");
        let if_true = if_true.expect("Trying to build a ternary with an empty expression.");
        let if_false = if_false.expect("Trying to build a ternary with an empty expression.");

        let dest_reg = self.next_register();
        let ternary_instruction = AleoStmt::Ternary(cond, if_true, if_false, dest_reg.clone());

        // Concatenate the instructions.
        let mut stmts = cond_stmts;
        stmts.extend(if_true_stmts);
        stmts.extend(if_false_stmts);
        stmts.push(ternary_instruction);

        (AleoExpr::Reg(dest_reg), stmts)
    }

    fn visit_struct_init(&mut self, input: &StructExpression) -> (AleoExpr, Vec<AleoStmt>) {
        // Lookup struct or record.
        let struct_type = if let Some(is_record) = self.composite_mapping.get(&input.path.absolute_path()) {
            if *is_record {
                // record.private;
                let [record_name] = &input.path.absolute_path()[..] else {
                    panic!("Absolute paths to records can only have a single segment at this stage.")
                };
                AleoType::Record { name: record_name.to_string(), program: None }
            } else {
                // foo; // no visibility for structs
                AleoType::Ident {
                    name: Self::legalize_path(&input.path.absolute_path())
                        .expect("path format cannot be legalized at this point"),
                }
            }
        } else {
            panic!("All composite types should be known at this phase of compilation")
        };

        // Initialize instruction builder strings.
        let mut instructions = vec![];

        // Visit each struct member and accumulate instructions from expressions.
        let operands: Vec<AleoExpr> = input
            .members
            .iter()
            .filter_map(|member| {
                if let Some(expr) = member.expression.as_ref() {
                    // Visit variable expression.
                    let (variable_operand, variable_instructions) = self.visit_expression(expr);
                    instructions.extend(variable_instructions);

                    variable_operand
                } else {
                    Some(self.visit_path(&Path::from(member.identifier).into_absolute()))
                }
            })
            .collect();

        // Push destination register to struct init instruction.
        let dest_reg = self.next_register();

        let struct_init_instruction = AleoStmt::Cast(AleoExpr::Tuple(operands), dest_reg.clone(), struct_type);

        instructions.push(struct_init_instruction);

        (AleoExpr::Reg(dest_reg), instructions)
    }

    fn visit_array_access(&mut self, input: &ArrayAccess) -> AleoExpr {
        let (array_operand, _) = self.visit_expression(&input.array);
        let array_operand = array_operand.expect("Trying to access an element of an empty expression.");

        assert!(
            matches!(self.state.type_table.get(&input.index.id()), Some(Type::Integer(_))),
            "unexpected type for for array index. This should have been caught by the type checker."
        );

        let index_operand = match &input.index {
            Expression::Literal(Literal {
                variant: LiteralVariant::Integer(_, s) | LiteralVariant::Unsuffixed(s),
                ..
            }) => AleoExpr::U32(s.parse().unwrap()),
            _ => panic!("Array indices must be integer literals"),
        };

        AleoExpr::ArrayAccess(Box::new(array_operand), Box::new(index_operand))
    }

    fn visit_member_access(&mut self, input: &MemberAccess) -> AleoExpr {
        // Handle `self.address`, `self.caller`, `self.checksum`, `self.edition`, `self.id`, `self.program_owner`, `self.signer`.
        if let Expression::Path(path) = input.inner.borrow()
            && matches!(path.try_absolute_path().as_deref(), Some([sym::SelfLower]))
        {
            // Get the current program ID.
            let program_id = self.program_id.expect("Program ID should be set before traversing the program");

            match input.name.name {
                // Return the program ID directly.
                sym::address | sym::id => {
                    return AleoExpr::RawName(program_id.to_string());
                }
                // Return the appropriate snarkVM operand.
                name @ (sym::checksum | sym::edition | sym::program_owner) => {
                    return AleoExpr::RawName(name.to_string());
                }
                _ => {} // Do nothing as `self.signer` and `self.caller` are handled below.
            }
        }

        let (inner_expr, _) = self.visit_expression(&input.inner);
        let inner_expr = inner_expr.expect("Trying to access a member of an empty expression.");

        AleoExpr::MemberAccess(Box::new(inner_expr), input.name.to_string())
    }

    fn visit_repeat(&mut self, input: &RepeatExpression) -> (AleoExpr, Vec<AleoStmt>) {
        let (operand, mut operand_instructions) = self.visit_expression(&input.expr);
        let operand = operand.expect("Trying to repeat an empty expression");

        let count = input.count.as_u32().expect("repeat count should be known at this point");

        let expression_operands = std::iter::repeat_n(operand, count as usize).collect::<Vec<_>>();

        // Construct the destination register.
        let dest_reg = self.next_register();

        // Get the array type.
        let Some(array_type @ Type::Array(..)) = self.state.type_table.get(&input.id) else {
            panic!("All types should be known at this phase of compilation");
        };
        let array_type = Self::visit_type(&array_type);

        let array_instruction = AleoStmt::Cast(AleoExpr::Tuple(expression_operands), dest_reg.clone(), array_type);

        // Concatenate the instructions.
        operand_instructions.push(array_instruction);

        (AleoExpr::Reg(dest_reg), operand_instructions)
    }

    // group::GEN -> group::GEN
    fn visit_associated_constant(&mut self, input: &AssociatedConstantExpression) -> AleoExpr {
        AleoExpr::RawName(format!("{input}"))
    }

    // Pedersen64::hash() -> hash.ped64
    fn visit_associated_function(&mut self, input: &AssociatedFunctionExpression) -> (Option<AleoExpr>, Vec<AleoStmt>) {
        let mut instructions = vec![];

        // Visit each function argument and accumulate instructions from expressions.
        let arguments = input
            .arguments
            .iter()
            .filter_map(|argument| {
                let (arg_string, arg_instructions) = self.visit_expression(argument);
                instructions.extend(arg_instructions);
                arg_string
            })
            .collect::<Vec<_>>();

        // A helper function to help with `Program::checksum`, `Program::edition`, and `Program::program_owner`.
        let generate_program_core = |program: &str, name: &str| {
            // Get the program ID from the first argument.
            let program_id = ProgramId::from_str_with_network(&program.replace("\"", ""), self.state.network)
                .expect("Type checking guarantees that the program name is valid");
            // If the program name matches the current program ID, then use the operand directly, otherwise fully qualify the operand.
            match program_id.to_string()
                == self.program_id.expect("The program ID is set before traversing the program").to_string()
            {
                true => name.to_string(),
                false => format!("{program_id}/{name}"),
            }
        };

        // Construct the instruction.
        let (destination, instruction) = match CoreFunction::try_from(input).ok() {
            Some(CoreFunction::Commit(variant, ref type_)) => {
                let type_ = AleoType::from(*type_);
                let dest_reg = self.next_register();
                let instruction =
                    AleoStmt::Commit(variant, arguments[0].clone(), arguments[1].clone(), dest_reg.clone(), type_);
                (Some(AleoExpr::Reg(dest_reg)), vec![instruction])
            }
            Some(CoreFunction::Hash(variant, ref type_)) => {
                let dest_reg = self.next_register();
                let type_ = match self.state.network {
                    NetworkName::TestnetV0 => {
                        AleoType::from(type_.to_snarkvm::<TestnetV0>().expect("TYC guarantees that the type is valid"))
                    }
                    NetworkName::CanaryV0 => {
                        AleoType::from(type_.to_snarkvm::<CanaryV0>().expect("TYC guarantees that the type is valid"))
                    }
                    NetworkName::MainnetV0 => {
                        AleoType::from(type_.to_snarkvm::<MainnetV0>().expect("TYC guarantees that the type is valid"))
                    }
                };
                let instruction = AleoStmt::Hash(variant, arguments[0].clone(), dest_reg.clone(), type_);
                (Some(AleoExpr::Reg(dest_reg)), vec![instruction])
            }
            Some(CoreFunction::Get) => {
                let dest_reg = self.next_register();
                let instruction = AleoStmt::Get(arguments[0].clone(), arguments[1].clone(), dest_reg.clone());
                (Some(AleoExpr::Reg(dest_reg)), vec![instruction])
            }
            Some(CoreFunction::MappingGetOrUse) => {
                let dest_reg = self.next_register();
                let instruction = AleoStmt::GetOrUse(
                    arguments[0].clone(),
                    arguments[1].clone(),
                    arguments[2].clone(),
                    dest_reg.clone(),
                );
                (Some(AleoExpr::Reg(dest_reg)), vec![instruction])
            }
            Some(CoreFunction::Set) => {
                let instruction = AleoStmt::Set(arguments[2].clone(), arguments[0].clone(), arguments[1].clone());
                (None, vec![instruction])
            }
            Some(CoreFunction::MappingRemove) => {
                let instruction = AleoStmt::Remove(arguments[0].clone(), arguments[1].clone());
                (None, vec![instruction])
            }
            Some(CoreFunction::MappingContains) => {
                let dest_reg = self.next_register();
                let instruction = AleoStmt::Contains(arguments[0].clone(), arguments[1].clone(), dest_reg.clone());
                (Some(AleoExpr::Reg(dest_reg)), vec![instruction])
            }
            Some(CoreFunction::GroupToXCoordinate) => {
                let dest_reg = self.next_register();
                let instruction = AleoStmt::Cast(arguments[0].clone(), dest_reg.clone(), AleoType::GroupX);
                (Some(AleoExpr::Reg(dest_reg)), vec![instruction])
            }
            Some(CoreFunction::GroupToYCoordinate) => {
                let dest_reg = self.next_register();
                let instruction = AleoStmt::Cast(arguments[0].clone(), dest_reg.clone(), AleoType::GroupY);
                (Some(AleoExpr::Reg(dest_reg)), vec![instruction])
            }
            Some(CoreFunction::ChaChaRand(type_)) => {
                let dest_reg = self.next_register();
                let instruction = AleoStmt::RandChacha(dest_reg.clone(), type_.into());
                (Some(AleoExpr::Reg(dest_reg)), vec![instruction])
            }
            Some(CoreFunction::SignatureVerify) => {
                let dest_reg = self.next_register();
                let instruction = AleoStmt::SignVerify(
                    arguments[0].clone(),
                    arguments[1].clone(),
                    arguments[2].clone(),
                    dest_reg.clone(),
                );
                (Some(AleoExpr::Reg(dest_reg)), vec![instruction])
            }
            Some(CoreFunction::ECDSAVerify(variant)) => {
                let dest_reg = self.next_register();
                let instruction = AleoStmt::EcdsaVerify(
                    variant,
                    arguments[0].clone(),
                    arguments[1].clone(),
                    arguments[2].clone(),
                    dest_reg.clone(),
                );
                (Some(AleoExpr::Reg(dest_reg)), vec![instruction])
            }
            Some(CoreFunction::FutureAwait) => {
                let instruction = AleoStmt::Await(arguments[0].clone());
                (None, vec![instruction])
            }
            Some(CoreFunction::ProgramChecksum) => {
                (Some(AleoExpr::RawName(generate_program_core(&arguments[0].to_string(), "checksum"))), vec![])
            }
            Some(CoreFunction::ProgramEdition) => {
                (Some(AleoExpr::RawName(generate_program_core(&arguments[0].to_string(), "edition"))), vec![])
            }
            Some(CoreFunction::ProgramOwner) => {
                (Some(AleoExpr::RawName(generate_program_core(&arguments[0].to_string(), "program_owner"))), vec![])
            }
            Some(CoreFunction::CheatCodePrintMapping)
            | Some(CoreFunction::CheatCodeSetBlockHeight)
            | Some(CoreFunction::CheatCodeSetBlockTimestamp)
            | Some(CoreFunction::CheatCodeSetSigner) => {
                (None, vec![])
                // Do nothing. Cheat codes do not generate instructions.
            }
            Some(CoreFunction::Serialize(variant)) => {
                // Get the input type.
                let Some(input_type) = self.state.type_table.get(&input.arguments[0].id()) else {
                    panic!("All types should be known at this phase of compilation");
                };
                // Get the instruction variant.
                let is_raw = matches!(variant, SerializeVariant::ToBitsRaw);
                // Get the size in bits of the input type.
                let size_in_bits = match self.state.network {
                    NetworkName::TestnetV0 => {
                        input_type.size_in_bits::<TestnetV0, _>(is_raw, |_| bail!("structs are not supported"))
                    }
                    NetworkName::MainnetV0 => {
                        input_type.size_in_bits::<MainnetV0, _>(is_raw, |_| bail!("structs are not supported"))
                    }
                    NetworkName::CanaryV0 => {
                        input_type.size_in_bits::<CanaryV0, _>(is_raw, |_| bail!("structs are not supported"))
                    }
                }
                .expect("TYC guarantees that all types have a valid size in bits");

                let dest_reg = self.next_register();
                let output_type = AleoType::Array { inner: Box::new(AleoType::Boolean), len: size_in_bits as u32 };
                let input_type = Self::visit_type(&input_type);
                let instruction =
                    AleoStmt::Serialize(variant, arguments[0].clone(), input_type, dest_reg.clone(), output_type);

                (Some(AleoExpr::Reg(dest_reg)), vec![instruction])
            }
            Some(CoreFunction::Deserialize(variant, output_type)) => {
                // Get the input type.
                let Some(input_type) = self.state.type_table.get(&input.arguments[0].id()) else {
                    panic!("All types should be known at this phase of compilation");
                };

                let dest_reg = self.next_register();
                let input_type = Self::visit_type(&input_type);
                let output_type = Self::visit_type(&output_type);
                let instruction =
                    AleoStmt::Deserialize(variant, arguments[0].clone(), input_type, dest_reg.clone(), output_type);

                (Some(AleoExpr::Reg(dest_reg)), vec![instruction])
            }
            Some(CoreFunction::OptionalUnwrap) | Some(CoreFunction::OptionalUnwrapOr) => {
                panic!("`Optional` core functions should have been lowered before code generation")
            }
            Some(CoreFunction::VectorPush)
            | Some(CoreFunction::VectorPop)
            | Some(CoreFunction::VectorLen)
            | Some(CoreFunction::VectorClear)
            | Some(CoreFunction::VectorSwapRemove) => {
                panic!("`Vector` core functions should have been lowered before code generation")
            }
            None => {
                panic!("All core functions should be known at this phase of compilation")
            }
        };
        // Add the instruction to the list of instructions.
        instructions.extend(instruction);

        (destination, instructions)
    }

    fn visit_call(&mut self, input: &CallExpression) -> (AleoExpr, Vec<AleoStmt>) {
        let caller_program = self.program_id.expect("Calls only appear within programs.").name.name;
        let callee_program = input.program.unwrap_or(caller_program);
        let func_symbol = self
            .state
            .symbol_table
            .lookup_function(&Location::new(callee_program, input.function.absolute_path().to_vec()))
            .expect("Type checking guarantees functions exist");

        let mut instructions = vec![];

        let arguments = input
            .arguments
            .iter()
            .filter_map(|argument| {
                let (argument, argument_instructions) = self.visit_expression(argument);
                instructions.extend(argument_instructions);
                argument
            })
            .collect();

        // Initialize storage for the destination registers.
        let mut destinations = Vec::new();

        // Create operands for the output registers.
        match func_symbol.function.output_type.clone() {
            t if t.is_empty() => {} // Do nothing
            Type::Tuple(tuple) => match tuple.length() {
                0 | 1 => panic!("Parsing guarantees that a tuple type has at least two elements"),
                len => {
                    for _ in 0..len {
                        destinations.push(self.next_register());
                    }
                }
            },
            _ => {
                destinations.push(self.next_register());
            }
        }

        // Add a register for async functions to represent the future created.
        if func_symbol.function.variant == Variant::AsyncFunction {
            destinations.push(self.next_register());
        }

        // Need to determine the program the function originated from as well as if the function has a finalize block.
        let call_instruction = if caller_program != callee_program {
            // All external functions must be defined as stubs.
            assert!(
                self.program.stubs.get(&callee_program).is_some(),
                "Type checking guarantees that imported and stub programs are present."
            );

            AleoStmt::Call(format!("{}.aleo/{}", callee_program, input.function), arguments, destinations.clone())
        } else if func_symbol.function.variant.is_async() {
            AleoStmt::Async(self.current_function.unwrap().identifier.to_string(), arguments, destinations.clone())
        } else {
            AleoStmt::Call(input.function.to_string(), arguments, destinations.clone())
        };

        // Push the call instruction to the list of instructions.
        instructions.push(call_instruction);

        // Return the output operands and the instructions.
        (AleoExpr::Tuple(destinations.into_iter().map(AleoExpr::Reg).collect()), instructions)
    }

    fn visit_tuple(&mut self, input: &TupleExpression) -> (AleoExpr, Vec<AleoStmt>) {
        let mut instructions = vec![];

        // Visit each tuple element and accumulate instructions from expressions.
        let tuple_elements = input
            .elements
            .iter()
            .filter_map(|element| {
                let (element, element_instructions) = self.visit_expression(element);
                instructions.extend(element_instructions);
                element
            })
            .collect();

        // CAUTION: does not return the destination_register.
        (AleoExpr::Tuple(tuple_elements), instructions)
    }

    pub fn clone_register(&mut self, register: &AleoExpr, typ: &Type) -> (AleoExpr, Vec<AleoStmt>) {
        let new_reg = self.next_register();
        match typ {
            Type::Address => {
                let ins = AleoStmt::Cast(register.clone(), new_reg.clone(), AleoType::Address);
                ((AleoExpr::Reg(new_reg)), vec![ins])
            }
            Type::Boolean => {
                let ins = AleoStmt::Cast(register.clone(), new_reg.clone(), AleoType::Boolean);
                ((AleoExpr::Reg(new_reg)), vec![ins])
            }
            Type::Field => {
                let ins = AleoStmt::Cast(register.clone(), new_reg.clone(), AleoType::Field);
                ((AleoExpr::Reg(new_reg)), vec![ins])
            }
            Type::Group => {
                let ins = AleoStmt::Cast(register.clone(), new_reg.clone(), AleoType::Group);
                ((AleoExpr::Reg(new_reg)), vec![ins])
            }
            Type::Scalar => {
                let ins = AleoStmt::Cast(register.clone(), new_reg.clone(), AleoType::Scalar);
                ((AleoExpr::Reg(new_reg)), vec![ins])
            }
            Type::Signature => {
                let ins = AleoStmt::Cast(register.clone(), new_reg.clone(), AleoType::Signature);
                ((AleoExpr::Reg(new_reg)), vec![ins])
            }
            Type::Integer(int) => {
                let ins = AleoStmt::Cast(register.clone(), new_reg.clone(), match int {
                    IntegerType::U8 => AleoType::U8,
                    IntegerType::U16 => AleoType::U16,
                    IntegerType::U32 => AleoType::U32,
                    IntegerType::U64 => AleoType::U64,
                    IntegerType::U128 => AleoType::U128,
                    IntegerType::I8 => AleoType::I8,
                    IntegerType::I16 => AleoType::I16,
                    IntegerType::I32 => AleoType::I32,
                    IntegerType::I64 => AleoType::I64,
                    IntegerType::I128 => AleoType::I128,
                });
                ((AleoExpr::Reg(new_reg)), vec![ins])
            }

            Type::Array(array_type) => {
                // We need to cast the old array's members into the new array.
                let elems = (0..array_type.length.as_u32().expect("length should be known at this point"))
                    .map(|i| AleoExpr::ArrayAccess(Box::new(register.clone()), Box::new(AleoExpr::U32(i))))
                    .collect::<Vec<_>>();

                let ins = AleoStmt::Cast(AleoExpr::Tuple(elems), new_reg.clone(), Self::visit_type(typ));
                ((AleoExpr::Reg(new_reg)), vec![ins])
            }

            Type::Composite(comp_ty) => {
                // We need to cast the old struct or record's members into the new one.
                let program = comp_ty.program.unwrap_or(self.program_id.unwrap().name.name);
                let location = Location::new(program, comp_ty.path.absolute_path().to_vec());
                let comp = self
                    .state
                    .symbol_table
                    .lookup_record(&location)
                    .or_else(|| self.state.symbol_table.lookup_struct(&comp_ty.path.absolute_path()))
                    .unwrap();
                let elems = comp
                    .members
                    .iter()
                    .map(|member| {
                        AleoExpr::MemberAccess(Box::new(register.clone()), member.identifier.name.to_string())
                    })
                    .collect();
                let instruction = AleoStmt::Cast(
                    AleoExpr::Tuple(elems),
                    new_reg.clone(),
                    self.visit_type_with_visibility(typ, None).0,
                );
                ((AleoExpr::Reg(new_reg)), vec![instruction])
            }

            Type::Optional(_) => panic!("All optional types should have been lowered by now."),

            Type::Vector(_) => panic!("All vector types should have been lowered by now."),

            Type::Mapping(..)
            | Type::Future(..)
            | Type::Tuple(..)
            | Type::Identifier(..)
            | Type::String
            | Type::Unit
            | Type::Numeric
            | Type::Err => panic!("Objects of type {typ} cannot be cloned."),
        }
    }
}