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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
use cairo_lang_debug::DebugWithDb;
use cairo_lang_defs::ids::{FreeFunctionId, LanguageElementId};
use cairo_lang_diagnostics::{skip_diagnostic, DiagnosticAdded, Diagnostics, Maybe, ToMaybe};
use cairo_lang_semantic::corelib::{
    core_felt_ty, core_jump_nz_func, core_nonzero_ty, get_core_function_id,
    get_enum_concrete_variant, get_panic_ty, jump_nz_nonzero_variant, jump_nz_zero_variant,
};
use cairo_lang_semantic::items::enm::SemanticEnumEx;
use cairo_lang_semantic::{ConcreteTypeId, GenericArgumentId, TypeLongId};
use cairo_lang_syntax::node::ids::SyntaxStablePtrId;
use cairo_lang_utils::unordered_hash_map::UnorderedHashMap;
use cairo_lang_utils::{extract_matches, try_extract_matches};
use id_arena::Arena;
use itertools::{chain, zip_eq, Itertools};
use num_traits::Zero;
use scope::{BlockScope, BlockScopeEnd};

use self::context::{
    lowering_flow_error_to_block_scope_end, LoweredExpr, LoweredExprExternEnum, LoweringContext,
    LoweringFlowError, StatementLoweringFlowError,
};
use self::external::{extern_facade_expr, extern_facade_return_tys};
use self::lower_if::lower_expr_if;
use self::scope::{generators, BlockFlowMerger, BlockMergerFinalized};
use self::variables::LivingVar;
use crate::blocks::FlatBlocks;
use crate::db::LoweringGroup;
use crate::diagnostic::LoweringDiagnostic;
use crate::diagnostic::LoweringDiagnosticKind::*;
use crate::lower::context::LoweringContextBuilder;
use crate::objects::{BlockId, Variable};

pub mod context;
mod external;
pub mod implicits;
mod lower_if;
mod scope;
mod semantic_map;
mod variables;

/// A lowered function code.
#[derive(Debug, PartialEq, Eq)]
pub struct Lowered {
    /// Diagnostics produced while lowering.
    pub diagnostics: Diagnostics<LoweringDiagnostic>,
    /// Block id for the start of the lowered function.
    pub root: Maybe<BlockId>,
    /// Arena of allocated lowered variables.
    pub variables: Arena<Variable>,
    /// Arena of allocated lowered blocks.
    pub blocks: FlatBlocks,
}

/// Lowers a semantic free function.
pub fn lower(db: &dyn LoweringGroup, free_function_id: FreeFunctionId) -> Maybe<Lowered> {
    log::trace!("Lowering a free function.");
    let is_empty_semantic_diagnostics =
        db.free_function_declaration_diagnostics(free_function_id).is_empty()
            && db.free_function_definition_diagnostics(free_function_id).is_empty();
    // Params.

    let lowering_builder = LoweringContextBuilder::new(db, free_function_id)?;
    let mut ctx = lowering_builder.ctx()?;

    let input_semantic_vars: Vec<cairo_lang_semantic::Variable> =
        ctx.signature.params.iter().cloned().map(cairo_lang_semantic::Variable::Param).collect();
    // TODO(spapini): Build semantic_defs in semantic model.
    let (input_semantic_var_ids, input_var_tys): (Vec<_>, Vec<_>) = input_semantic_vars
        .iter()
        .map(|semantic_var| (semantic_var.id(), semantic_var.ty()))
        .unzip();
    for semantic_var in input_semantic_vars {
        ctx.semantic_defs.insert(semantic_var.id(), semantic_var);
    }
    let input_var_tys = chain!(ctx.implicits.iter().copied(), input_var_tys).collect();
    let ref_params = ctx.ref_params;

    let root = if is_empty_semantic_diagnostics {
        // Fetch body block expr.
        let semantic_block = extract_matches!(
            &ctx.function_def.exprs[ctx.function_def.body],
            cairo_lang_semantic::Expr::Block
        );
        // Lower block to a BlockSealed.
        let (block_sealed_opt, mut merger_finalized) =
            BlockFlowMerger::with_root(&mut ctx, ref_params, |ctx, merger| {
                merger.run_in_subscope(ctx, input_var_tys, |ctx, scope, variables| {
                    let mut variables_iter = variables.into_iter();
                    for ty in ctx.implicits {
                        let var = variables_iter.next().to_maybe()?;
                        scope.put_implicit(ctx, *ty, var);
                    }

                    // Initialize implicits and params.
                    for (semantic_var_id, var) in zip_eq(input_semantic_var_ids, variables_iter) {
                        scope.put_semantic_variable(ctx, semantic_var_id, var);
                    }
                    lower_block(ctx, scope, semantic_block, true)
                })
            });
        block_sealed_opt
            .map(|block_sealed| merger_finalized.finalize_block(&mut ctx, block_sealed).block)
    } else {
        Err(DiagnosticAdded)
    };

    // Convert block to flat block.
    // TODO(spapini): Do this in another phase.
    let mut flat_blocks = FlatBlocks::new();
    for block in ctx.blocks.0.into_iter() {
        flat_blocks.alloc(block.try_into().expect("Panic block ends are not supported yet."));
    }

    Ok(Lowered {
        diagnostics: ctx.diagnostics.build(),
        root,
        variables: ctx.variables,
        blocks: flat_blocks,
    })
}

/// Lowers a semantic block.
fn lower_block(
    ctx: &mut LoweringContext<'_>,
    scope: &mut BlockScope,
    expr_block: &cairo_lang_semantic::ExprBlock,
    root: bool,
) -> Maybe<BlockScopeEnd> {
    log::trace!("Lowering a block.");
    for (i, stmt_id) in expr_block.statements.iter().enumerate() {
        let stmt = &ctx.function_def.statements[*stmt_id];
        let lowered_stmt = lower_statement(ctx, scope, stmt);

        // If flow is not reachable anymore, no need to continue emitting statements.
        match lowered_stmt {
            Ok(()) => {}
            Err(StatementLoweringFlowError::Failed(diag_added)) => return Err(diag_added),
            Err(StatementLoweringFlowError::End(end)) => {
                // TODO(spapini): We might want to report unreachable for expr that abruptly
                // ends, e.g. `5 + {return; 6}`.
                if i + 1 < expr_block.statements.len() {
                    let start_stmt = &ctx.function_def.statements[expr_block.statements[i + 1]];
                    let end_stmt =
                        &ctx.function_def.statements[*expr_block.statements.last().unwrap()];
                    // Emit diagnostic fo the rest of the statements with unreachable.
                    ctx.diagnostics.report(
                        start_stmt.stable_ptr().untyped(),
                        Unreachable { last_statement_ptr: end_stmt.stable_ptr().untyped() },
                    );
                }
                return Ok(end);
            }
        };
    }

    // Determine correct block end.
    match expr_block.tail {
        None if !root => Ok(BlockScopeEnd::Callsite(None)),
        _ => lower_tail_expr(ctx, scope, expr_block.tail, root),
    }
}

/// Lowers an expression that is either a complete block, or the end (tail expreesion) of a
/// block.
pub fn lower_tail_expr(
    ctx: &mut LoweringContext<'_>,
    scope: &mut BlockScope,
    expr: Option<cairo_lang_semantic::ExprId>,
    root: bool,
) -> Maybe<BlockScopeEnd> {
    log::trace!("Lowering a tail expression.");
    let mut lowered_expr = if let Some(expr) = expr {
        lower_expr(ctx, scope, expr)
    } else {
        Ok(LoweredExpr::Tuple(vec![]))
    };
    if root {
        lowered_expr = lowered_expr.and_then(|expr| maybe_wrap_with_panic(ctx, expr, scope));
    }
    lowered_expr_to_block_scope_end(ctx, scope, lowered_expr, root)
}

/// Converts [Result<LoweredExpr, LoweringFlowError>] into `BlockScopeEnd`.
pub fn lowered_expr_to_block_scope_end(
    ctx: &mut LoweringContext<'_>,
    scope: &mut BlockScope,
    lowered_expr: Result<LoweredExpr, LoweringFlowError>,
    root: bool,
) -> Maybe<BlockScopeEnd> {
    Ok(match lowered_expr {
        Ok(LoweredExpr::Tuple(tys)) if !root && tys.is_empty() => BlockScopeEnd::Callsite(None),
        Ok(lowered_expr) => match lowered_expr.var(ctx, scope) {
            Ok(var) => BlockScopeEnd::Callsite(Some(var)),
            Err(err) => lowering_flow_error_to_block_scope_end(err)?,
        },
        Err(err) => lowering_flow_error_to_block_scope_end(err)?,
    })
}

/// Lowers a semantic statement.
pub fn lower_statement(
    ctx: &mut LoweringContext<'_>,
    scope: &mut BlockScope,
    stmt: &cairo_lang_semantic::Statement,
) -> Result<(), StatementLoweringFlowError> {
    match stmt {
        cairo_lang_semantic::Statement::Expr(cairo_lang_semantic::StatementExpr {
            expr,
            stable_ptr: _,
        }) => {
            log::trace!("Lowering an expression statement.");
            let lowered_expr = lower_expr(ctx, scope, *expr)?;
            // The LoweredExpr must be evaluated now to push/bring back variables in case it is
            // LoweredExpr::ExternEnum.
            match lowered_expr {
                LoweredExpr::ExternEnum(x) => {
                    x.var(ctx, scope)?;
                }
                LoweredExpr::AtVariable(_) | LoweredExpr::Tuple(_) => {}
            }
        }
        cairo_lang_semantic::Statement::Let(cairo_lang_semantic::StatementLet {
            pattern,
            expr,
            stable_ptr: _,
        }) => {
            log::trace!("Lowering a let statement.");
            let lowered_expr = lower_expr(ctx, scope, *expr)?;
            lower_single_pattern(ctx, scope, pattern, lowered_expr)?
        }
        cairo_lang_semantic::Statement::Return(cairo_lang_semantic::StatementReturn {
            expr,
            stable_ptr: _,
        }) => {
            log::trace!("Lowering a return statement.");
            let lowered_expr = lower_expr(ctx, scope, *expr)?;
            let (refs, returns) = get_full_return_vars(ctx, scope, lowered_expr)?;
            return Err(StatementLoweringFlowError::End(BlockScopeEnd::Return { refs, returns }));
        }
    }
    Ok(())
}

/// Returns the return variables, prefixed by the reference params. Wraps with PanicResult if
/// needed.
fn get_full_return_vars(
    ctx: &mut LoweringContext<'_>,
    scope: &mut BlockScope,
    value_expr: LoweredExpr,
) -> Result<(Vec<LivingVar>, Vec<LivingVar>), StatementLoweringFlowError> {
    let lowered_expr = maybe_wrap_with_panic(ctx, value_expr, scope)?;
    let value_vars = match lowered_expr {
        LoweredExpr::Tuple(tys) if tys.is_empty() => vec![],
        _ => vec![lowered_expr.var(ctx, scope)?],
    };
    Ok(get_plain_full_return_vars(ctx, scope, value_vars)?)
}

/// Wraps a LoweredExpr with PanicResult::Ok id the current function panics.
fn maybe_wrap_with_panic(
    ctx: &mut LoweringContext<'_>,
    value_expr: LoweredExpr,
    scope: &mut BlockScope,
) -> Result<LoweredExpr, LoweringFlowError> {
    let lowered_expr = if ctx.may_panic {
        let variant = get_enum_concrete_variant(
            ctx.db.upcast(),
            "PanicResult",
            vec![GenericArgumentId::Type(value_expr.ty(ctx))],
            "Ok",
        );
        LoweredExpr::AtVariable(
            generators::EnumConstruct { input: value_expr.var(ctx, scope)?, variant }
                .add(ctx, scope),
        )
    } else {
        value_expr
    };
    Ok(lowered_expr)
}

/// Returns the return variables, prefixed by the reference params, without wrapping with
/// PanicResult.
fn get_plain_full_return_vars(
    ctx: &mut LoweringContext<'_>,
    scope: &mut BlockScope,
    value_vars: Vec<LivingVar>,
) -> Result<(Vec<LivingVar>, Vec<LivingVar>), LoweringFlowError> {
    let implicit_vars = ctx
        .implicits
        .iter()
        .map(|ty| scope.take_implicit(*ty))
        .collect::<Option<Vec<_>>>()
        .to_maybe()
        .map_err(LoweringFlowError::Failed)?;

    let ref_vars = ctx
        .ref_params
        .iter()
        .map(|semantic_var_id| {
            use_semantic_var(
                ctx,
                scope,
                *semantic_var_id,
                semantic_var_id.untyped_stable_ptr(ctx.db.upcast()),
            )
        })
        .collect::<Result<Vec<_>, _>>()?;
    Ok((chain!(implicit_vars, ref_vars).collect(), value_vars))
}

// TODO(spapini): Separate match pattern from non-match (single) patterns in the semantic
// model.
/// Lowers a single-pattern (pattern that does not appear in a match. This includes structs,
/// tuples, variables, etc...
/// Adds the bound variables to the scope.
/// Note that single patterns are the only way to bind new local variables in the semantic
/// model.
fn lower_single_pattern(
    ctx: &mut LoweringContext<'_>,
    scope: &mut BlockScope,
    pattern: &cairo_lang_semantic::Pattern,
    lowered_expr: LoweredExpr,
) -> Result<(), LoweringFlowError> {
    log::trace!("Lowering a single pattern.");
    match pattern {
        cairo_lang_semantic::Pattern::Literal(_) => unreachable!(),
        cairo_lang_semantic::Pattern::Variable(cairo_lang_semantic::PatternVariable {
            name: _,
            var: sem_var,
        }) => {
            let sem_var = cairo_lang_semantic::Variable::Local(sem_var.clone());
            // Deposit the owned variable in the semantic variables store.
            let var = lowered_expr.var(ctx, scope)?;
            scope.put_semantic_variable(ctx, sem_var.id(), var);
            // TODO(spapini): Build semantic_defs in semantic model.
            ctx.semantic_defs.insert(sem_var.id(), sem_var);
        }
        cairo_lang_semantic::Pattern::Struct(strct) => {
            let members = ctx.db.struct_members(strct.id).map_err(LoweringFlowError::Failed)?;
            let mut required_members = UnorderedHashMap::from_iter(
                strct.field_patterns.iter().map(|(member, pattern)| (member.id, pattern)),
            );
            let generator = generators::StructDestructure {
                input: lowered_expr.var(ctx, scope)?,
                tys: members.iter().map(|(_, member)| member.ty).collect(),
            };
            for (var, (_, member)) in generator.add(ctx, scope).into_iter().zip(members.into_iter())
            {
                if let Some(member_pattern) = required_members.remove(&member.id) {
                    lower_single_pattern(ctx, scope, member_pattern, LoweredExpr::AtVariable(var))?;
                }
            }
        }
        cairo_lang_semantic::Pattern::Tuple(cairo_lang_semantic::PatternTuple {
            field_patterns,
            ty,
        }) => {
            let outputs = if let LoweredExpr::Tuple(exprs) = lowered_expr {
                exprs
            } else {
                let tys = extract_matches!(ctx.db.lookup_intern_type(*ty), TypeLongId::Tuple);
                generators::StructDestructure { input: lowered_expr.var(ctx, scope)?, tys }
                    .add(ctx, scope)
                    .into_iter()
                    .map(LoweredExpr::AtVariable)
                    .collect()
            };
            for (var, pattern) in zip_eq(outputs, field_patterns) {
                lower_single_pattern(ctx, scope, pattern, var)?;
            }
        }
        cairo_lang_semantic::Pattern::EnumVariant(_) => unreachable!(),
        cairo_lang_semantic::Pattern::Otherwise(_) => {}
    }
    Ok(())
}

/// Lowers a semantic expression.
fn lower_expr(
    ctx: &mut LoweringContext<'_>,
    scope: &mut BlockScope,
    expr_id: cairo_lang_semantic::ExprId,
) -> Result<LoweredExpr, LoweringFlowError> {
    let expr = &ctx.function_def.exprs[expr_id];
    match expr {
        cairo_lang_semantic::Expr::Tuple(expr) => lower_expr_tuple(ctx, expr, scope),
        cairo_lang_semantic::Expr::Assignment(expr) => lower_expr_assignment(ctx, expr, scope),
        cairo_lang_semantic::Expr::Block(expr) => lower_expr_block(ctx, scope, expr),
        cairo_lang_semantic::Expr::FunctionCall(expr) => lower_expr_function_call(ctx, expr, scope),
        cairo_lang_semantic::Expr::Match(expr) => lower_expr_match(ctx, expr, scope),
        cairo_lang_semantic::Expr::If(expr) => lower_expr_if(ctx, scope, expr),
        cairo_lang_semantic::Expr::Var(expr) => {
            log::trace!("Lowering a variable: {:?}", expr.debug(&ctx.expr_formatter));
            Ok(LoweredExpr::AtVariable(use_semantic_var(
                ctx,
                scope,
                expr.var,
                expr.stable_ptr.untyped(),
            )?))
        }
        cairo_lang_semantic::Expr::Literal(expr) => {
            log::trace!("Lowering a literal: {:?}", expr.debug(&ctx.expr_formatter));
            Ok(LoweredExpr::AtVariable(
                generators::Literal { value: expr.value.clone(), ty: expr.ty }.add(ctx, scope),
            ))
        }
        cairo_lang_semantic::Expr::MemberAccess(expr) => lower_expr_member_access(ctx, expr, scope),
        cairo_lang_semantic::Expr::StructCtor(expr) => lower_expr_struct_ctor(ctx, expr, scope),
        cairo_lang_semantic::Expr::EnumVariantCtor(expr) => lower_expr_enum_ctor(ctx, expr, scope),
        cairo_lang_semantic::Expr::PropagateError(expr) => {
            lower_expr_error_propagate(ctx, expr, scope)
        }
        cairo_lang_semantic::Expr::Missing(cairo_lang_semantic::ExprMissing {
            diag_added, ..
        }) => Err(LoweringFlowError::Failed(*diag_added)),
    }
}

/// Lowers an expression of type [cairo_lang_semantic::ExprTuple].
fn lower_expr_tuple(
    ctx: &mut LoweringContext<'_>,
    expr: &cairo_lang_semantic::ExprTuple,
    scope: &mut BlockScope,
) -> Result<LoweredExpr, LoweringFlowError> {
    log::trace!("Lowering a tuple: {:?}", expr.debug(&ctx.expr_formatter));
    let inputs = expr
        .items
        .iter()
        .map(|arg_expr_id| lower_expr(ctx, scope, *arg_expr_id))
        .collect::<Result<Vec<_>, _>>()?;
    Ok(LoweredExpr::Tuple(inputs))
}

/// Lowers an expression of type [cairo_lang_semantic::ExprBlock].
fn lower_expr_block(
    ctx: &mut LoweringContext<'_>,
    scope: &mut BlockScope,
    expr: &cairo_lang_semantic::ExprBlock,
) -> Result<LoweredExpr, LoweringFlowError> {
    log::trace!("Lowering a block expression: {:?}", expr.debug(&ctx.expr_formatter));
    let (block_sealed, mut finalized_merger) =
        BlockFlowMerger::with(ctx, scope, &[], |ctx, merger| {
            merger.run_in_subscope(ctx, vec![], |ctx, subscope, _| {
                lower_block(ctx, subscope, expr, false)
            })
        });
    let block_sealed = block_sealed.map_err(LoweringFlowError::Failed)?;
    let block_finalized = finalized_merger.finalize_block(ctx, block_sealed);

    // Emit the statement.
    let block_result = (generators::CallBlock {
        block: block_finalized.block,
        end_info: finalized_merger.end_info.clone(),
    })
    .add(ctx, scope);
    lowered_expr_from_block_result(ctx, scope, block_result, finalized_merger)
}

/// Lowers an expression of type [cairo_lang_semantic::ExprFunctionCall].
fn lower_expr_function_call(
    ctx: &mut LoweringContext<'_>,
    expr: &cairo_lang_semantic::ExprFunctionCall,
    scope: &mut BlockScope,
) -> Result<LoweredExpr, LoweringFlowError> {
    log::trace!("Lowering a function call expression: {:?}", expr.debug(&ctx.expr_formatter));

    // TODO(spapini): Use the correct stable pointer.
    let arg_inputs = lower_exprs_as_vars(ctx, &expr.args, scope)?;
    let (ref_tys, ref_inputs): (_, Vec<LivingVar>) = expr
        .ref_args
        .iter()
        .map(|semantic_var_id| {
            Ok((
                ctx.semantic_defs[*semantic_var_id].ty(),
                take_semantic_var(ctx, scope, *semantic_var_id, expr.stable_ptr.untyped())?,
            ))
        })
        .collect::<Result<Vec<_>, _>>()?
        .into_iter()
        .unzip();
    let callee_implicit_types =
        ctx.db.function_all_implicits(expr.function).map_err(LoweringFlowError::Failed)?;
    let implicits = callee_implicit_types
        .iter()
        .map(|ty| scope.take_implicit(*ty))
        .collect::<Option<Vec<_>>>()
        .to_maybe()
        .map_err(LoweringFlowError::Failed)?;
    // TODO(orizi): Support ref args that are not the first arguments.
    let inputs = chain!(implicits, ref_inputs, arg_inputs.into_iter()).collect();

    // If the function is panic(), do something special.
    if expr.function == get_core_function_id(ctx.db.upcast(), "panic".into(), vec![]) {
        let [input] = <[_; 1]>::try_from(inputs).ok().unwrap();
        return lower_panic(ctx, scope, input);
    }

    // The following is relevant only to extern functions.
    if let Some(extern_function_id) = expr.function.try_get_extern_function_id(ctx.db.upcast()) {
        if let cairo_lang_semantic::TypeLongId::Concrete(
            cairo_lang_semantic::ConcreteTypeId::Enum(concrete_enum_id),
        ) = ctx.db.lookup_intern_type(expr.ty)
        {
            let lowered_expr = LoweredExprExternEnum {
                function: expr.function,
                concrete_enum_id,
                inputs,
                ref_args: expr.ref_args.clone(),
                implicits: callee_implicit_types,
                stable_ptr: expr.stable_ptr.untyped(),
            };

            if let Ok(refs) = ctx.db.extern_function_declaration_refs(extern_function_id) {
                if !refs.is_empty() {
                    // Don't optimize in case the extern function has ref parameters.
                    //
                    // TODO(yuval): This is a temporary measure as there is a problem when a match
                    // arm returns(moves) a variable that was passed to the
                    // libfunc call in the match as a reference. To fix it, we
                    // need: to ensure that if one arm uses a variable, all arms either use it or
                    // drop it (all refs must be passed to all arms as inputs). Then, if a var that
                    // was passed to the libfunc as a ref parameter is returned by one of the arms,
                    // it must be rebound to do that (today it is returned as the same var id).
                    return Ok(LoweredExpr::AtVariable(lowered_expr.var(ctx, scope)?));
                }
            }

            // It is still unknown whether we directly match on this enum result, or store it to a
            // variable. Thus we can't perform the call. Performing it and pushing/bringing-back
            // variables are done on the 2 places where this result is used:
            // 1. [lower_optimized_extern_match]
            // 2. [context::LoweredExprExternEnum::var]
            return Ok(LoweredExpr::ExternEnum(lowered_expr));
        }
    }

    let may_panic = ctx.db.function_may_panic(expr.function).map_err(LoweringFlowError::Failed)?;
    let expr_ty = if may_panic { get_panic_ty(ctx.db.upcast(), expr.ty) } else { expr.ty };

    let (implicit_outputs, ref_outputs, res) =
        perform_function_call(ctx, scope, expr.function, inputs, ref_tys, expr_ty)?;

    // Rebind the implicits.
    for (implicit_type, implicit_output) in zip_eq(callee_implicit_types, implicit_outputs) {
        scope.put_implicit(ctx, implicit_type, implicit_output);
    }
    // Rebind the ref variables.
    for (semantic_var_id, output_var) in zip_eq(&expr.ref_args, ref_outputs) {
        scope.put_semantic_variable(ctx, *semantic_var_id, output_var);
    }

    if may_panic {
        return lower_panic_error_propagate(ctx, scope, res, expr.ty);
    }
    Ok(res)
}

/// Creates a LoweredExpr for a function call, taking into consideration external function facades:
/// For external functions, sometimes the high level signature doesn't exactly correspond to the
/// external function returned variables / branches.
fn perform_function_call(
    ctx: &mut LoweringContext<'_>,
    scope: &mut BlockScope,
    function: cairo_lang_semantic::FunctionId,
    inputs: Vec<LivingVar>,
    ref_tys: Vec<cairo_lang_semantic::TypeId>,
    ret_ty: cairo_lang_semantic::TypeId,
) -> Result<(Vec<LivingVar>, Vec<LivingVar>, LoweredExpr), LoweringFlowError> {
    // If the function is not extern, simply call it.
    if function.try_get_extern_function_id(ctx.db.upcast()).is_none() {
        let call_result =
            generators::Call { function, inputs, ref_tys, ret_tys: vec![ret_ty] }.add(ctx, scope);
        let res = LoweredExpr::AtVariable(call_result.returns.into_iter().next().unwrap());
        return Ok((call_result.implicit_outputs, call_result.ref_outputs, res));
    };

    // Extern function.
    let ret_tys = extern_facade_return_tys(ctx, ret_ty);
    let call_result = generators::Call { function, inputs, ref_tys, ret_tys }.add(ctx, scope);
    Ok((
        call_result.implicit_outputs,
        call_result.ref_outputs,
        extern_facade_expr(ctx, ret_ty, call_result.returns),
    ))
}

/// Lowers a panic(data) expr.
fn lower_panic(
    ctx: &mut LoweringContext<'_>,
    scope: &mut BlockScope,
    data_var: LivingVar,
) -> Result<LoweredExpr, LoweringFlowError> {
    let func_err_variant = get_enum_concrete_variant(
        ctx.db.upcast(),
        "PanicResult",
        vec![GenericArgumentId::Type(ctx.signature.return_type)],
        "Err",
    );
    let value_var =
        generators::EnumConstruct { input: data_var, variant: func_err_variant }.add(ctx, scope);
    let (refs, returns) = get_plain_full_return_vars(ctx, scope, vec![value_var])?;
    Err(LoweringFlowError::Return { refs, returns })
}

/// Lowers an expression of type [cairo_lang_semantic::ExprMatch].
fn lower_expr_match(
    ctx: &mut LoweringContext<'_>,
    expr: &cairo_lang_semantic::ExprMatch,
    scope: &mut BlockScope,
) -> Result<LoweredExpr, LoweringFlowError> {
    log::trace!("Lowering a match expression: {:?}", expr.debug(&ctx.expr_formatter));
    let lowered_expr = lower_expr(ctx, scope, expr.matched_expr)?;

    if ctx.function_def.exprs[expr.matched_expr].ty() == ctx.db.core_felt_ty() {
        let var = lowered_expr.var(ctx, scope)?;
        return lower_expr_match_felt(ctx, expr, var, scope);
    }

    // TODO(spapini): Use diagnostics.
    // TODO(spapini): Handle more than just enums.
    if let LoweredExpr::ExternEnum(extern_enum) = lowered_expr {
        return lower_optimized_extern_match(ctx, scope, extern_enum, &expr.arms);
    }

    let (concrete_enum_id, concrete_variants) = extract_concrete_enum(ctx, expr)?;
    let expr_var = lowered_expr.var(ctx, scope)?;

    // Merge arm blocks.
    let (res, mut finalized_merger) =
        BlockFlowMerger::with(ctx, scope, &[], |ctx, merger| -> Result<_, LoweringFlowError> {
            // Create a sealed block for each arm.
            let block_opts =
                zip_eq(&concrete_variants, &expr.arms).map(|(concrete_variant, arm)| {
                    let input_tys = vec![concrete_variant.ty];

                    // Create a scope for the arm block.
                    merger.run_in_subscope(ctx, input_tys, |ctx, subscope, arm_inputs| {
                        // TODO(spapini): Make a better diagnostic.
                        let enum_pattern = try_extract_matches!(
                            &arm.pattern,
                            cairo_lang_semantic::Pattern::EnumVariant
                        )
                        .ok_or_else(|| {
                            ctx.diagnostics.report(expr.stable_ptr.untyped(), UnsupportedMatchArm)
                        })?;
                        // TODO(spapini): Make a better diagnostic.
                        if &enum_pattern.variant != concrete_variant {
                            return Err(ctx
                                .diagnostics
                                .report(expr.stable_ptr.untyped(), UnsupportedMatchArm));
                        }
                        // This assert is ok.
                        assert_eq!(arm_inputs.len(), 1);

                        let variant_expr =
                            LoweredExpr::AtVariable(arm_inputs.into_iter().next().unwrap());
                        match lower_single_pattern(
                            ctx,
                            subscope,
                            &enum_pattern.inner_pattern,
                            variant_expr,
                        ) {
                            Ok(_) => {
                                // Lower the arm expression.
                                lower_tail_expr(ctx, subscope, Some(arm.expression), false)
                            }
                            Err(err) => lowering_flow_error_to_block_scope_end(err),
                        }
                    })
                });
            block_opts.collect::<Maybe<Vec<_>>>().map_err(LoweringFlowError::Failed)
        });
    let finalized_blocks =
        res?.into_iter().map(|sealed| finalized_merger.finalize_block(ctx, sealed).block);

    let arms = zip_eq(concrete_variants, finalized_blocks).collect();

    // Emit the statement.
    let block_result = (generators::MatchEnum {
        input: expr_var,
        concrete_enum_id,
        arms,
        end_info: finalized_merger.end_info.clone(),
    })
    .add(ctx, scope);
    lowered_expr_from_block_result(ctx, scope, block_result, finalized_merger)
}

/// Lowers a match expression on a LoweredExpr::ExternEnum lowered expression.
fn lower_optimized_extern_match(
    ctx: &mut LoweringContext<'_>,
    scope: &mut BlockScope,
    extern_enum: LoweredExprExternEnum,
    match_arms: &[cairo_lang_semantic::MatchArm],
) -> Result<LoweredExpr, LoweringFlowError> {
    log::trace!("Started lowering of an optimized extern match.");
    let concrete_variants = ctx
        .db
        .concrete_enum_variants(extern_enum.concrete_enum_id)
        .map_err(LoweringFlowError::Failed)?;
    if match_arms.len() != concrete_variants.len() {
        return Err(LoweringFlowError::Failed(skip_diagnostic()));
    }
    // Merge arm blocks.
    let (blocks, mut finalized_merger) = BlockFlowMerger::with(
        ctx,
        scope,
        &extern_enum.ref_args,
        |ctx, merger| -> Result<_, LoweringFlowError> {
            // Create a sealed block for each arm.
            let block_opts =
                zip_eq(&concrete_variants, match_arms).map(|(concrete_variant, arm)| {
                    let input_tys = match_extern_variant_arm_input_types(
                        ctx,
                        concrete_variant.ty,
                        &extern_enum,
                    );

                    // Create a scope for the arm block.
                    merger.run_in_subscope(ctx, input_tys, |ctx, subscope, mut arm_inputs| {
                        // TODO(spapini): Make a better diagnostic.
                        let enum_pattern = try_extract_matches!(
                            &arm.pattern,
                            cairo_lang_semantic::Pattern::EnumVariant
                        )
                        .ok_or_else(|| {
                            ctx.diagnostics.report(extern_enum.stable_ptr, UnsupportedMatchArm)
                        })?;
                        // TODO(spapini): Make a better diagnostic.
                        if &enum_pattern.variant != concrete_variant {
                            return Err(ctx
                                .diagnostics
                                .report(extern_enum.stable_ptr, UnsupportedMatchArm));
                        }

                        // Bind the arm inputs to implicits and semantic variables.
                        match_extern_arm_ref_args_bind(
                            ctx,
                            &mut arm_inputs,
                            &extern_enum,
                            subscope,
                        );

                        let variant_expr = extern_facade_expr(ctx, concrete_variant.ty, arm_inputs);
                        match lower_single_pattern(
                            ctx,
                            subscope,
                            &enum_pattern.inner_pattern,
                            variant_expr,
                        ) {
                            Ok(_) => {
                                // Lower the arm expression.
                                lower_tail_expr(ctx, subscope, Some(arm.expression), false)
                            }
                            Err(err) => lowering_flow_error_to_block_scope_end(err),
                        }
                    })
                });
            block_opts.collect::<Maybe<Vec<_>>>().map_err(LoweringFlowError::Failed)
        },
    );

    let finalized_blocks = blocks?
        .into_iter()
        .map(|sealed| finalized_merger.finalize_block(ctx, sealed).block)
        .collect_vec();
    let arms = zip_eq(concrete_variants, finalized_blocks).collect();

    // Emit the statement.
    let block_result = generators::MatchExtern {
        function: extern_enum.function,
        inputs: extern_enum.inputs,
        arms,
        end_info: finalized_merger.end_info.clone(),
    }
    .add(ctx, scope);
    lowered_expr_from_block_result(ctx, scope, block_result, finalized_merger)
}

/// Lowers an expression of type [cairo_lang_semantic::ExprMatch] where the matched expression is a
/// felt. Currently only a simple match-zero is supported.
fn lower_expr_match_felt(
    ctx: &mut LoweringContext<'_>,
    expr: &cairo_lang_semantic::ExprMatch,
    expr_var: LivingVar,
    scope: &mut BlockScope,
) -> Result<LoweredExpr, LoweringFlowError> {
    log::trace!("Lowering a match-felt expression.");
    // Check that the match has the expected form.
    let (literal, block0, block_otherwise) = if let [
        cairo_lang_semantic::MatchArm {
            pattern:
                cairo_lang_semantic::Pattern::Literal(cairo_lang_semantic::PatternLiteral {
                    literal,
                    ..
                }),
            expression: block0,
        },
        cairo_lang_semantic::MatchArm {
            pattern: cairo_lang_semantic::Pattern::Otherwise(_),
            expression: block_otherwise,
        },
    ] = &expr.arms[..]
    {
        (literal, block0, block_otherwise)
    } else {
        return Err(LoweringFlowError::Failed(
            ctx.diagnostics.report(expr.stable_ptr.untyped(), OnlyMatchZeroIsSupported),
        ));
    };

    // Make sure literal is 0.
    if !literal.value.is_zero() {
        return Err(LoweringFlowError::Failed(
            ctx.diagnostics.report(literal.stable_ptr.untyped(), NonZeroValueInMatch),
        ));
    }

    let semantic_db = ctx.db.upcast();

    // Lower both blocks.
    let (res, mut finalized_merger) = BlockFlowMerger::with(ctx, scope, &[], |ctx, merger| {
        let block0_end = merger.run_in_subscope(ctx, vec![], |ctx, subscope, _| {
            lower_tail_expr(ctx, subscope, Some(*block0), false)
        });
        let non_zero_type = core_nonzero_ty(semantic_db, core_felt_ty(semantic_db));
        let block_otherwise_end =
            merger.run_in_subscope(ctx, vec![non_zero_type], |ctx, subscope, _| {
                lower_tail_expr(ctx, subscope, Some(*block_otherwise), false)
            });
        Ok((block0_end, block_otherwise_end))
    });
    let (block0_sealed, block_otherwise_sealed) = res.map_err(LoweringFlowError::Failed)?;
    let block0_finalized =
        finalized_merger.finalize_block(ctx, block0_sealed.map_err(LoweringFlowError::Failed)?);
    let block_otherwise_finalized = finalized_merger
        .finalize_block(ctx, block_otherwise_sealed.map_err(LoweringFlowError::Failed)?);

    let concrete_variants =
        vec![jump_nz_zero_variant(ctx.db.upcast()), jump_nz_nonzero_variant(ctx.db.upcast())];
    let arms = zip_eq(concrete_variants, [block0_finalized.block, block_otherwise_finalized.block])
        .collect();

    // Emit the statement.
    let block_result = (generators::MatchExtern {
        function: core_jump_nz_func(semantic_db),
        inputs: vec![expr_var],
        arms,
        end_info: finalized_merger.end_info.clone(),
    })
    .add(ctx, scope);
    lowered_expr_from_block_result(ctx, scope, block_result, finalized_merger)
}

/// Extracts concrete enum and variants from a match expression. Assumes it is indeed a concrete
/// enum.
fn extract_concrete_enum(
    ctx: &mut LoweringContext<'_>,
    expr: &cairo_lang_semantic::ExprMatch,
) -> Result<
    (cairo_lang_semantic::ConcreteEnumId, Vec<cairo_lang_semantic::ConcreteVariant>),
    LoweringFlowError,
> {
    let concrete_ty = try_extract_matches!(
        ctx.db.lookup_intern_type(ctx.function_def.exprs[expr.matched_expr].ty()),
        TypeLongId::Concrete
    )
    .to_maybe()
    .map_err(LoweringFlowError::Failed)?;
    let concrete_enum_id = try_extract_matches!(concrete_ty, ConcreteTypeId::Enum)
        .to_maybe()
        .map_err(LoweringFlowError::Failed)?;
    let enum_id = concrete_enum_id.enum_id(ctx.db.upcast());
    let variants = ctx.db.enum_variants(enum_id).map_err(LoweringFlowError::Failed)?;
    let concrete_variants = variants
        .values()
        .map(|variant_id| {
            let variant =
                ctx.db.variant_semantic(enum_id, *variant_id).map_err(LoweringFlowError::Failed)?;

            ctx.db
                .concrete_enum_variant(concrete_enum_id, &variant)
                .map_err(LoweringFlowError::Failed)
        })
        .collect::<Result<Vec<_>, _>>()?;

    if expr.arms.len() != concrete_variants.len() {
        return Err(LoweringFlowError::Failed(
            ctx.diagnostics.report(expr.stable_ptr.untyped(), UnsupportedMatch),
        ));
    }
    Ok((concrete_enum_id, concrete_variants))
}

/// Lowers a sequence of expressions and return them all. If the flow ended in the middle,
/// propagates that flow error without returning any variable.
fn lower_exprs_as_vars(
    ctx: &mut LoweringContext<'_>,
    exprs: &[cairo_lang_semantic::ExprId],
    scope: &mut BlockScope,
) -> Result<Vec<LivingVar>, LoweringFlowError> {
    exprs
        .iter()
        .map(|arg_expr_id| lower_expr(ctx, scope, *arg_expr_id)?.var(ctx, scope))
        .collect::<Result<Vec<_>, _>>()
}

/// Lowers an expression of type [cairo_lang_semantic::ExprEnumVariantCtor].
fn lower_expr_enum_ctor(
    ctx: &mut LoweringContext<'_>,
    expr: &cairo_lang_semantic::ExprEnumVariantCtor,
    scope: &mut BlockScope,
) -> Result<LoweredExpr, LoweringFlowError> {
    log::trace!(
        "Started lowering of an enum c'tor expression: {:?}",
        expr.debug(&ctx.expr_formatter)
    );
    Ok(LoweredExpr::AtVariable(
        generators::EnumConstruct {
            input: lower_expr(ctx, scope, expr.value_expr)?.var(ctx, scope)?,
            variant: expr.variant.clone(),
        }
        .add(ctx, scope),
    ))
}

/// Lowers an expression of type [cairo_lang_semantic::ExprMemberAccess].
fn lower_expr_member_access(
    ctx: &mut LoweringContext<'_>,
    expr: &cairo_lang_semantic::ExprMemberAccess,
    scope: &mut BlockScope,
) -> Result<LoweredExpr, LoweringFlowError> {
    log::trace!("Lowering a member-access expression: {:?}", expr.debug(&ctx.expr_formatter));
    let members = ctx.db.struct_members(expr.struct_id).map_err(LoweringFlowError::Failed)?;
    let member_idx = members
        .iter()
        .position(|(_, member)| member.id == expr.member)
        .to_maybe()
        .map_err(LoweringFlowError::Failed)?;
    Ok(LoweredExpr::AtVariable(
        generators::StructMemberAccess {
            input: lower_expr(ctx, scope, expr.expr)?.var(ctx, scope)?,
            member_tys: members.into_iter().map(|(_, member)| member.ty).collect(),
            member_idx,
        }
        .add(ctx, scope),
    ))
}

/// Lowers an expression of type [cairo_lang_semantic::ExprStructCtor].
fn lower_expr_struct_ctor(
    ctx: &mut LoweringContext<'_>,
    expr: &cairo_lang_semantic::ExprStructCtor,
    scope: &mut BlockScope,
) -> Result<LoweredExpr, LoweringFlowError> {
    log::trace!("Lowering a struct c'tor expression: {:?}", expr.debug(&ctx.expr_formatter));
    let members = ctx.db.struct_members(expr.struct_id).map_err(LoweringFlowError::Failed)?;
    let member_expr = UnorderedHashMap::from_iter(expr.members.iter().cloned());
    Ok(LoweredExpr::AtVariable(
        generators::StructConstruct {
            inputs: members
                .into_iter()
                .map(|(_, member)| lower_expr(ctx, scope, member_expr[member.id])?.var(ctx, scope))
                .collect::<Result<Vec<_>, _>>()?,
            ty: expr.ty,
        }
        .add(ctx, scope),
    ))
}

/// Lowers an expression of type [cairo_lang_semantic::ExprPropagateError].
fn lower_panic_error_propagate(
    ctx: &mut LoweringContext<'_>,
    scope: &mut BlockScope,
    lowered_expr: LoweredExpr,
    ty: cairo_lang_semantic::TypeId,
) -> Result<LoweredExpr, LoweringFlowError> {
    let ok_variant = get_enum_concrete_variant(
        ctx.db.upcast(),
        "PanicResult",
        vec![GenericArgumentId::Type(ty)],
        "Ok",
    );
    let err_variant = get_enum_concrete_variant(
        ctx.db.upcast(),
        "PanicResult",
        vec![GenericArgumentId::Type(ty)],
        "Err",
    );
    let func_err_variant = get_enum_concrete_variant(
        ctx.db.upcast(),
        "PanicResult",
        vec![GenericArgumentId::Type(ctx.signature.return_type)],
        "Err",
    );
    lower_error_propagate(
        ctx,
        scope,
        lowered_expr,
        &ok_variant,
        &err_variant,
        &func_err_variant,
        true,
    )
}

/// Lowers an expression of type [cairo_lang_semantic::ExprPropagateError].
fn lower_expr_error_propagate(
    ctx: &mut LoweringContext<'_>,
    expr: &cairo_lang_semantic::ExprPropagateError,
    scope: &mut BlockScope,
) -> Result<LoweredExpr, LoweringFlowError> {
    log::trace!(
        "Started lowering of an error-propagate expression: {:?}",
        expr.debug(&ctx.expr_formatter)
    );
    let lowered_expr = lower_expr(ctx, scope, expr.inner)?;
    lower_error_propagate(
        ctx,
        scope,
        lowered_expr,
        &expr.ok_variant,
        &expr.err_variant,
        &expr.func_err_variant,
        false,
    )
}

/// Lowers an error propagation.
fn lower_error_propagate(
    ctx: &mut LoweringContext<'_>,
    scope: &mut BlockScope,
    lowered_expr: LoweredExpr,
    ok_variant: &cairo_lang_semantic::ConcreteVariant,
    err_variant: &cairo_lang_semantic::ConcreteVariant,
    func_err_variant: &cairo_lang_semantic::ConcreteVariant,
    panic_error: bool,
) -> Result<LoweredExpr, LoweringFlowError> {
    if let LoweredExpr::ExternEnum(extern_enum) = lowered_expr {
        return lower_optimized_extern_error_propagate(
            ctx,
            scope,
            extern_enum,
            ok_variant,
            err_variant,
            func_err_variant,
            panic_error,
        );
    }

    let var = lowered_expr.var(ctx, scope)?;
    // Merge arm blocks.
    let (res, mut finalized_merger) =
        BlockFlowMerger::with(ctx, scope, &[], |ctx, merger| -> Result<_, LoweringFlowError> {
            Ok([
                merger
                    .run_in_subscope(ctx, vec![ok_variant.ty], |_ctx, _subscope, arm_inputs| {
                        let [var] = <[_; 1]>::try_from(arm_inputs).ok().unwrap();
                        Ok(BlockScopeEnd::Callsite(Some(var)))
                    })
                    .map_err(LoweringFlowError::Failed)?,
                merger
                    .run_in_subscope(ctx, vec![err_variant.ty], |ctx, subscope, arm_inputs| {
                        let [var] = <[_; 1]>::try_from(arm_inputs).ok().unwrap();
                        let value_var = generators::EnumConstruct {
                            input: var,
                            variant: func_err_variant.clone(),
                        }
                        .add(ctx, subscope);
                        let (refs, returns) = if panic_error {
                            get_plain_full_return_vars(ctx, subscope, vec![value_var])
                                .ok()
                                .to_maybe()?
                        } else {
                            get_full_return_vars(ctx, subscope, LoweredExpr::AtVariable(value_var))
                                .ok()
                                .to_maybe()?
                        };
                        Ok(BlockScopeEnd::Return { refs, returns })
                    })
                    .map_err(LoweringFlowError::Failed)?,
            ])
        });
    let finalized_blocks = res?.map(|sealed| finalized_merger.finalize_block(ctx, sealed).block);

    let arms = zip_eq([ok_variant.clone(), err_variant.clone()], finalized_blocks).collect();

    // Emit the statement.
    let block_result = (generators::MatchEnum {
        input: var,
        concrete_enum_id: ok_variant.concrete_enum_id,
        arms,
        end_info: finalized_merger.end_info.clone(),
    })
    .add(ctx, scope);
    lowered_expr_from_block_result(ctx, scope, block_result, finalized_merger)
}

/// Lowers an error propagation expression on a LoweredExpr::ExternEnum lowered expression.
fn lower_optimized_extern_error_propagate(
    ctx: &mut LoweringContext<'_>,
    scope: &mut BlockScope,
    extern_enum: LoweredExprExternEnum,
    ok_variant: &cairo_lang_semantic::ConcreteVariant,
    err_variant: &cairo_lang_semantic::ConcreteVariant,
    func_err_variant: &cairo_lang_semantic::ConcreteVariant,
    panic_error: bool,
) -> Result<LoweredExpr, LoweringFlowError> {
    log::trace!("Started lowering of an optimized error-propagate expression.");
    let (blocks, mut finalized_merger) = BlockFlowMerger::with(
        ctx,
        scope,
        &extern_enum.ref_args,
        |ctx, merger| -> Result<_, LoweringFlowError> {
            Ok([
                {
                    let input_tys =
                        match_extern_variant_arm_input_types(ctx, ok_variant.ty, &extern_enum);
                    merger
                        .run_in_subscope(ctx, input_tys, |ctx, subscope, mut arm_inputs| {
                            match_extern_arm_ref_args_bind(
                                ctx,
                                &mut arm_inputs,
                                &extern_enum,
                                subscope,
                            );

                            let variant_expr = extern_facade_expr(ctx, ok_variant.ty, arm_inputs);
                            Ok(BlockScopeEnd::Callsite(Some(
                                variant_expr.var(ctx, subscope).ok().to_maybe()?,
                            )))
                        })
                        .map_err(LoweringFlowError::Failed)?
                },
                {
                    let input_tys =
                        match_extern_variant_arm_input_types(ctx, err_variant.ty, &extern_enum);
                    merger
                        .run_in_subscope(ctx, input_tys, |ctx, subscope, mut arm_inputs| {
                            match_extern_arm_ref_args_bind(
                                ctx,
                                &mut arm_inputs,
                                &extern_enum,
                                subscope,
                            );
                            let variant_expr = extern_facade_expr(ctx, err_variant.ty, arm_inputs);
                            let input = variant_expr.var(ctx, subscope).ok().to_maybe()?;
                            let value_var = generators::EnumConstruct {
                                input,
                                variant: func_err_variant.clone(),
                            }
                            .add(ctx, subscope);
                            let (refs, returns) = if panic_error {
                                get_plain_full_return_vars(ctx, subscope, vec![value_var])
                                    .ok()
                                    .to_maybe()?
                            } else {
                                get_full_return_vars(
                                    ctx,
                                    subscope,
                                    LoweredExpr::AtVariable(value_var),
                                )
                                .ok()
                                .to_maybe()?
                            };
                            Ok(BlockScopeEnd::Return { refs, returns })
                        })
                        .map_err(LoweringFlowError::Failed)?
                },
            ])
        },
    );
    let finalized_blocks =
        blocks?.map(|sealed| finalized_merger.finalize_block(ctx, sealed).block).to_vec();
    let arms = zip_eq(vec![ok_variant.clone(), err_variant.clone()], finalized_blocks).collect();

    let block_result = generators::MatchExtern {
        function: extern_enum.function,
        inputs: extern_enum.inputs,
        arms,
        end_info: finalized_merger.end_info.clone(),
    }
    .add(ctx, scope);
    lowered_expr_from_block_result(ctx, scope, block_result, finalized_merger)
}

/// Returns the input types for an extern match variant arm.
fn match_extern_variant_arm_input_types(
    ctx: &mut LoweringContext<'_>,
    ty: cairo_lang_semantic::TypeId,
    extern_enum: &LoweredExprExternEnum,
) -> Vec<cairo_lang_semantic::TypeId> {
    let variant_input_tys = extern_facade_return_tys(ctx, ty);
    let ref_tys =
        extern_enum.ref_args.iter().map(|semantic_var_id| ctx.semantic_defs[*semantic_var_id].ty());
    chain!(extern_enum.implicits.clone(), ref_tys, variant_input_tys.into_iter()).collect()
}

/// Binds input references and implicits when matching on extern functions.
fn match_extern_arm_ref_args_bind(
    ctx: &mut LoweringContext<'_>,
    arm_inputs: &mut Vec<LivingVar>,
    extern_enum: &LoweredExprExternEnum,
    subscope: &mut BlockScope,
) {
    let implicit_outputs: Vec<_> = arm_inputs.drain(0..extern_enum.implicits.len()).collect();
    // Bind the implicits.
    for (ty, output_var) in zip_eq(&extern_enum.implicits, implicit_outputs) {
        subscope.put_implicit(ctx, *ty, output_var);
    }
    let ref_outputs: Vec<_> = arm_inputs.drain(0..extern_enum.ref_args.len()).collect();
    // Bind the ref variables.
    for (semantic_var_id, output_var) in zip_eq(&extern_enum.ref_args, ref_outputs) {
        subscope.put_semantic_variable(ctx, *semantic_var_id, output_var);
    }
}

/// Lowers an expression of type [cairo_lang_semantic::ExprAssignment].
fn lower_expr_assignment(
    ctx: &mut LoweringContext<'_>,
    expr: &cairo_lang_semantic::ExprAssignment,
    scope: &mut BlockScope,
) -> Result<LoweredExpr, LoweringFlowError> {
    log::trace!(
        "Started lowering of an assignment expression: {:?}",
        expr.debug(&ctx.expr_formatter)
    );
    scope.try_ensure_semantic_variable(ctx, expr.var);
    let var = lower_expr(ctx, scope, expr.rhs)?.var(ctx, scope)?;
    scope.put_semantic_variable(ctx, expr.var, var);
    Ok(LoweredExpr::Tuple(vec![]))
}

/// Retrieves a LivingVar that corresponds to a semantic var in the current scope.
/// Moves it if necessary. If it is already moved, fails and emits a diagnostic.
fn use_semantic_var(
    ctx: &mut LoweringContext<'_>,
    scope: &mut BlockScope,
    semantic_var: cairo_lang_semantic::VarId,
    stable_ptr: SyntaxStablePtrId,
) -> Result<LivingVar, LoweringFlowError> {
    scope
        .use_semantic_variable(ctx, semantic_var)
        .take_var()
        .ok_or_else(|| LoweringFlowError::Failed(ctx.diagnostics.report(stable_ptr, VariableMoved)))
}

/// Retrieves a LivingVar that corresponds to a semantic var in the current scope.
/// Always moves. If it is already moved, fails and emits a diagnostic.
fn take_semantic_var(
    ctx: &mut LoweringContext<'_>,
    scope: &mut BlockScope,
    semantic_var: cairo_lang_semantic::VarId,
    stable_ptr: SyntaxStablePtrId,
) -> Result<LivingVar, LoweringFlowError> {
    scope
        .take_semantic_variable(ctx, semantic_var)
        .take_var()
        .ok_or_else(|| LoweringFlowError::Failed(ctx.diagnostics.report(stable_ptr, VariableMoved)))
}

/// Converts a CallBlockResult for a LoweredExpr.
/// Some statements end with a CallBlockResult (CallBlock, Match, etc..), which represents all
/// the information of the "ending" of the call.
/// Binds the semantic variables from the call
/// Returns the proper flow error if needed.
fn lowered_expr_from_block_result(
    ctx: &mut LoweringContext<'_>,
    scope: &mut BlockScope,
    block_result: generators::CallBlockResult,
    finalized_merger: BlockMergerFinalized,
) -> Result<LoweredExpr, LoweringFlowError> {
    match block_result {
        generators::CallBlockResult::Callsite { maybe_output, pushes } => {
            let mut pushes_iter = pushes.into_iter();
            for implicit_type in finalized_merger.outer_implicit_info.pushes {
                let var = pushes_iter.next().unwrap();
                scope.put_implicit(ctx, implicit_type, var);
                scope.mark_implicit_changed(implicit_type);
            }
            for (semantic_var_id, var) in
                zip_eq(finalized_merger.outer_var_info.pushes, pushes_iter)
            {
                scope.put_semantic_variable(ctx, semantic_var_id, var);
            }

            // Bring back the unused implicits.
            for (ty, implicit_var) in finalized_merger.outer_implicit_info.unchanged {
                scope.put_implicit(ctx, ty, implicit_var);
            }

            // Bring back the untouched semantic vars.
            for (semantic_var_id, var) in finalized_merger.outer_var_info.bring_back {
                scope.put_semantic_variable(ctx, semantic_var_id, var);
            }

            Ok(match maybe_output {
                Some(output) => LoweredExpr::AtVariable(output),
                None => LoweredExpr::Tuple(vec![]),
            })
        }
        generators::CallBlockResult::End => Err(LoweringFlowError::Unreachable),
    }
}