-
Notifications
You must be signed in to change notification settings - Fork 490
/
mod.rs
1847 lines (1724 loc) · 71.3 KB
/
mod.rs
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
use std::vec;
use block_builder::BlockBuilder;
use cairo_lang_debug::DebugWithDb;
use cairo_lang_diagnostics::{Diagnostics, Maybe};
use cairo_lang_semantic::corelib::{unwrap_error_propagation_type, ErrorPropagationType};
use cairo_lang_semantic::db::SemanticGroup;
use cairo_lang_semantic::{corelib, ExprVar, LocalVariable, VarId};
use cairo_lang_syntax::node::ids::SyntaxStablePtrId;
use cairo_lang_syntax::node::TypedStablePtr;
use cairo_lang_utils::ordered_hash_map::OrderedHashMap;
use cairo_lang_utils::unordered_hash_map::{Entry, UnorderedHashMap};
use cairo_lang_utils::{extract_matches, try_extract_matches, Intern, LookupIntern};
use defs::ids::TopLevelLanguageElementId;
use itertools::{chain, izip, zip_eq, Itertools};
use num_bigint::{BigInt, Sign};
use num_traits::ToPrimitive;
use semantic::corelib::{
core_felt252_ty, core_submodule, get_core_function_id, get_core_ty_by_name, get_function_id,
never_ty, unit_ty,
};
use semantic::items::constant::{value_as_const_value, ConstValue};
use semantic::items::structure::SemanticStructEx;
use semantic::literals::try_extract_minus_literal;
use semantic::types::{peel_snapshots, wrap_in_snapshots};
use semantic::{
ExprFunctionCallArg, ExprId, ExprPropagateError, ExprVarMemberPath, GenericArgumentId,
MatchArmSelector, SemanticDiagnostic, TypeLongId,
};
use {cairo_lang_defs as defs, cairo_lang_semantic as semantic};
use self::block_builder::SealedBlockBuilder;
use self::context::{
lowering_flow_error_to_sealed_block, EncapsulatingLoweringContext, LoweredExpr,
LoweredExprExternEnum, LoweringContext, LoweringFlowError,
};
use self::external::{extern_facade_expr, extern_facade_return_tys};
use self::logical_op::lower_logical_op;
use self::lower_if::lower_expr_if;
use self::lower_match::lower_expr_match;
use crate::blocks::FlatBlocks;
use crate::db::LoweringGroup;
use crate::diagnostic::LoweringDiagnosticKind::{self, *};
use crate::diagnostic::{LoweringDiagnosticsBuilder, MatchDiagnostic, MatchError, MatchKind};
use crate::ids::{
FunctionLongId, FunctionWithBodyId, FunctionWithBodyLongId, GeneratedFunction, LocationId,
SemanticFunctionIdEx, Signature,
};
use crate::lower::context::{LoweringResult, VarRequest};
use crate::lower::generators::StructDestructure;
use crate::lower::lower_match::{
lower_concrete_enum_match, lower_expr_match_tuple, lower_optimized_extern_match,
MatchArmWrapper, TupleInfo,
};
use crate::{
BlockId, FlatLowered, MatchArm, MatchEnumInfo, MatchExternInfo, MatchInfo, VarUsage, VariableId,
};
mod block_builder;
pub mod context;
mod external;
pub mod generators;
mod logical_op;
mod lower_if;
mod lower_match;
pub mod refs;
pub mod usage;
#[cfg(test)]
mod generated_test;
/// Lowering of a function together with extra generated functions.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MultiLowering {
pub main_lowering: FlatLowered,
pub generated_lowerings: OrderedHashMap<semantic::ExprId, FlatLowered>,
}
/// Lowers a semantic free function.
pub fn lower_semantic_function(
db: &dyn LoweringGroup,
semantic_function_id: defs::ids::FunctionWithBodyId,
) -> Maybe<MultiLowering> {
let declaration_diagnostics = db.function_declaration_diagnostics(semantic_function_id);
check_error_free_or_warn(db, declaration_diagnostics, semantic_function_id, "declaration")?;
let body_diagnostics = db.function_body_diagnostics(semantic_function_id);
check_error_free_or_warn(db, body_diagnostics, semantic_function_id, "body")?;
let mut encapsulating_ctx = EncapsulatingLoweringContext::new(db, semantic_function_id)?;
let function_id = FunctionWithBodyLongId::Semantic(semantic_function_id).intern(db);
let signature = db.function_with_body_signature(semantic_function_id)?;
// TODO(spapini): Build semantic_defs in semantic model.
for semantic_var in &signature.params {
encapsulating_ctx.semantic_defs.insert(
semantic::VarId::Param(semantic_var.id),
semantic::Variable::Param(semantic_var.clone()),
);
}
let block_expr_id = encapsulating_ctx.function_body.body_expr;
let main_lowering = lower_function(
&mut encapsulating_ctx,
function_id,
Signature::from_semantic(db, signature),
block_expr_id,
)?;
Ok(MultiLowering { main_lowering, generated_lowerings: encapsulating_ctx.lowerings })
}
/// Lowers a function into [FlatLowered].
pub fn lower_function(
encapsulating_ctx: &mut EncapsulatingLoweringContext<'_>,
function_id: FunctionWithBodyId,
signature: Signature,
block_expr_id: semantic::ExprId,
) -> Maybe<FlatLowered> {
log::trace!("Lowering a free function.");
let mut ctx = LoweringContext::new(encapsulating_ctx, function_id, signature)?;
// Fetch body block expr.
let semantic_block =
extract_matches!(&ctx.function_body.exprs[block_expr_id], semantic::Expr::Block).clone();
// Initialize builder.
let root_block_id = alloc_empty_block(&mut ctx);
let mut builder = BlockBuilder::root(&mut ctx, root_block_id);
let parameters = ctx
.signature
.params
.clone()
.into_iter()
.map(|param| {
let location = ctx.get_location(param.stable_ptr().untyped());
let var = ctx.new_var(VarRequest { ty: param.ty(), location });
// TODO(spapini): Introduce member paths, not just base variables.
let param_var = extract_matches!(param, ExprVarMemberPath::Var);
builder.put_semantic(param_var.var, var);
var
})
.collect_vec();
let root_ok = {
let maybe_sealed_block = lower_block(&mut ctx, builder, &semantic_block);
maybe_sealed_block.and_then(|block_sealed| {
wrap_sealed_block_as_function(
&mut ctx,
block_sealed,
semantic_block.stable_ptr.untyped(),
)?;
Ok(root_block_id)
})
};
let blocks = root_ok
.map(|_| ctx.blocks.build().expect("Root block must exist."))
.unwrap_or_else(FlatBlocks::new_errored);
Ok(FlatLowered {
diagnostics: ctx.diagnostics.build(),
variables: ctx.variables.variables,
blocks,
signature: ctx.signature.clone(),
parameters,
})
}
/// Lowers an expression of type [semantic::ExprFor].
pub fn lower_for_loop(
ctx: &mut LoweringContext<'_, '_>,
builder: &mut BlockBuilder,
loop_expr: semantic::ExprFor,
loop_expr_id: semantic::ExprId,
) -> LoweringResult<LoweredExpr> {
let semantic_db: &dyn SemanticGroup = ctx.db.upcast();
let for_location = ctx.get_location(loop_expr.stable_ptr.untyped());
let next_semantic_signature =
semantic_db.concrete_function_signature(loop_expr.next_function_id).unwrap();
let into_iter = builder.get_ref(ctx, &loop_expr.into_iter_member_path).unwrap();
let next_call = generators::Call {
function: loop_expr.next_function_id.lowered(ctx.db),
inputs: vec![into_iter],
coupon_input: None,
extra_ret_tys: vec![next_semantic_signature.params.first().unwrap().ty],
ret_tys: vec![next_semantic_signature.return_type],
location: for_location,
}
.add(ctx, &mut builder.statements);
let next_iterator = next_call.extra_outputs.first().unwrap();
let next_value = next_call.returns.first().unwrap();
let ErrorPropagationType::Option { some_variant, none_variant } =
unwrap_error_propagation_type(semantic_db, ctx.variables[next_value.var_id].ty)
.expect("Expected Option type for next function return.")
else {
unreachable!("Return type for next function must be Option.")
};
let next_value_type = some_variant.ty;
builder.update_ref(ctx, &loop_expr.into_iter_member_path, next_iterator.var_id);
let pattern = ctx.function_body.patterns[loop_expr.pattern].clone();
let unit_ty = corelib::unit_ty(semantic_db);
let some_block: cairo_lang_semantic::ExprBlock =
extract_matches!(&ctx.function_body.exprs[loop_expr.body], semantic::Expr::Block).clone();
let mut some_subscope = create_subscope(ctx, builder);
let some_subscope_block_id = some_subscope.block_id;
let some_var_id = ctx.new_var(VarRequest {
ty: next_value_type,
location: ctx.get_location(some_block.stable_ptr.untyped()),
});
let variant_expr = LoweredExpr::AtVariable(VarUsage {
var_id: some_var_id,
location: ctx.get_location(some_block.stable_ptr.untyped()),
});
let lowered_pattern = lower_single_pattern(ctx, &mut some_subscope, pattern, variant_expr);
let sealed_some = match lowered_pattern {
Ok(_) => {
let block_expr = (|| {
lower_expr_block(ctx, &mut some_subscope, &some_block)?;
// Add recursive call.
let signature = ctx.signature.clone();
call_loop_func(
ctx,
signature,
&mut some_subscope,
loop_expr_id,
loop_expr.stable_ptr.untyped(),
)
})();
lowered_expr_to_block_scope_end(ctx, some_subscope, block_expr)
}
Err(err) => lowering_flow_error_to_sealed_block(ctx, some_subscope.clone(), err),
}
.map_err(LoweringFlowError::Failed)?;
let none_subscope = create_subscope(ctx, builder);
let none_var_id = ctx.new_var(VarRequest {
ty: unit_ty,
location: ctx.get_location(some_block.stable_ptr.untyped()),
});
let sealed_none = lowered_expr_to_block_scope_end(
ctx,
none_subscope.clone(),
Ok(LoweredExpr::Tuple { exprs: vec![], location: for_location }),
)
.map_err(LoweringFlowError::Failed)?;
let match_info = MatchInfo::Enum(MatchEnumInfo {
concrete_enum_id: some_variant.concrete_enum_id,
input: *next_value,
arms: vec![
MatchArm {
arm_selector: MatchArmSelector::VariantId(some_variant),
block_id: some_subscope_block_id,
var_ids: vec![some_var_id],
},
MatchArm {
arm_selector: MatchArmSelector::VariantId(none_variant),
block_id: none_subscope.block_id,
var_ids: vec![none_var_id],
},
],
location: for_location,
});
builder.merge_and_end_with_match(ctx, match_info, vec![sealed_some, sealed_none], for_location)
}
/// Lowers an expression of type [semantic::ExprWhile].
pub fn lower_while_loop(
ctx: &mut LoweringContext<'_, '_>,
builder: &mut BlockBuilder,
loop_expr: semantic::ExprWhile,
loop_expr_id: semantic::ExprId,
) -> LoweringResult<LoweredExpr> {
let semantic_condition = match &loop_expr.condition {
semantic::Condition::BoolExpr(semantic_condition) => *semantic_condition,
semantic::Condition::Let(match_expr, patterns) => {
return lower_expr_while_let(
ctx,
builder,
&loop_expr,
*match_expr,
patterns,
MatchKind::WhileLet(loop_expr_id, loop_expr.stable_ptr.untyped()),
);
}
};
let condition = lower_expr_to_var_usage(ctx, builder, semantic_condition)?;
let semantic_db = ctx.db.upcast();
let unit_ty = corelib::unit_ty(semantic_db);
let while_location = ctx.get_location(loop_expr.stable_ptr.untyped());
// Main block.
let mut subscope_main = create_subscope_with_bound_refs(ctx, builder);
let block_main_id = subscope_main.block_id;
let main_block =
extract_matches!(&ctx.function_body.exprs[loop_expr.body], semantic::Expr::Block).clone();
let main_block_var_id = ctx.new_var(VarRequest {
ty: unit_ty,
location: ctx.get_location(main_block.stable_ptr.untyped()),
});
let block_expr = (|| {
lower_expr_block(ctx, &mut subscope_main, &main_block)?;
// Add recursive call.
let signature = ctx.signature.clone();
call_loop_func(
ctx,
signature,
&mut subscope_main,
loop_expr_id,
loop_expr.stable_ptr.untyped(),
)
})();
let block_main = lowered_expr_to_block_scope_end(ctx, subscope_main, block_expr)
.map_err(LoweringFlowError::Failed)?;
// Empty else block.
let subscope_else = create_subscope_with_bound_refs(ctx, builder);
let block_else_id = subscope_else.block_id;
let else_block_input_var_id = ctx.new_var(VarRequest { ty: unit_ty, location: while_location });
let block_else = lowered_expr_to_block_scope_end(
ctx,
subscope_else,
Ok(LoweredExpr::Tuple { exprs: vec![], location: while_location }),
)
.map_err(LoweringFlowError::Failed)?;
let match_info = MatchInfo::Enum(MatchEnumInfo {
concrete_enum_id: corelib::core_bool_enum(semantic_db),
input: condition,
arms: vec![
MatchArm {
arm_selector: MatchArmSelector::VariantId(corelib::false_variant(semantic_db)),
block_id: block_else_id,
var_ids: vec![else_block_input_var_id],
},
MatchArm {
arm_selector: MatchArmSelector::VariantId(corelib::true_variant(semantic_db)),
block_id: block_main_id,
var_ids: vec![main_block_var_id],
},
],
location: while_location,
});
builder.merge_and_end_with_match(ctx, match_info, vec![block_main, block_else], while_location)
}
/// Lowers an expression of type if where the condition is of type [semantic::Condition::Let].
pub fn lower_expr_while_let(
ctx: &mut LoweringContext<'_, '_>,
builder: &mut BlockBuilder,
loop_expr: &semantic::ExprWhile,
matched_expr: semantic::ExprId,
patterns: &[semantic::PatternId],
match_type: MatchKind,
) -> LoweringResult<LoweredExpr> {
log::trace!("Lowering a match expression: {:?}", loop_expr.debug(&ctx.expr_formatter));
let location = ctx.get_location(loop_expr.stable_ptr.untyped());
let lowered_expr = lower_expr(ctx, builder, matched_expr)?;
let matched_expr = ctx.function_body.exprs[matched_expr].clone();
let ty = matched_expr.ty();
if ty == ctx.db.core_felt252_ty()
|| corelib::get_convert_to_felt252_libfunc_name_by_type(ctx.db.upcast(), ty).is_some()
{
return Err(LoweringFlowError::Failed(ctx.diagnostics.report(
loop_expr.stable_ptr.untyped(),
LoweringDiagnosticKind::MatchError(MatchError {
kind: match_type,
error: MatchDiagnostic::UnsupportedNumericInLetCondition,
}),
)));
}
let (n_snapshots, long_type_id) = peel_snapshots(ctx.db.upcast(), ty);
let arms = vec![
MatchArmWrapper { patterns: patterns.into(), expr: Some(loop_expr.body) },
MatchArmWrapper { patterns: vec![], expr: None },
];
if let Some(types) = try_extract_matches!(long_type_id, TypeLongId::Tuple) {
return lower_expr_match_tuple(
ctx,
builder,
lowered_expr,
&matched_expr,
&TupleInfo { types, n_snapshots },
&arms,
match_type,
);
}
if let LoweredExpr::ExternEnum(extern_enum) = lowered_expr {
return lower_optimized_extern_match(ctx, builder, extern_enum, &arms, match_type);
}
lower_concrete_enum_match(
ctx,
builder,
&matched_expr,
lowered_expr,
&arms,
location,
match_type,
)
}
/// Lowers a loop inner function into [FlatLowered].
/// Similar to `lower_function`, but adds a recursive call.
// TODO(spapini): Unite with `lower_function`.
pub fn lower_loop_function(
encapsulating_ctx: &mut EncapsulatingLoweringContext<'_>,
function_id: FunctionWithBodyId,
loop_signature: Signature,
loop_expr_id: semantic::ExprId,
) -> Maybe<FlatLowered> {
let mut ctx = LoweringContext::new(encapsulating_ctx, function_id, loop_signature.clone())?;
let old_loop_expr_id = std::mem::replace(&mut ctx.current_loop_expr_id, Some(loop_expr_id));
// Initialize builder.
let root_block_id = alloc_empty_block(&mut ctx);
let mut builder = BlockBuilder::root(&mut ctx, root_block_id);
let parameters = ctx
.signature
.params
.clone()
.into_iter()
.map(|param| {
let location = ctx.get_location(param.stable_ptr().untyped());
let var = ctx.new_var(VarRequest { ty: param.ty(), location });
builder.semantics.introduce((¶m).into(), var);
var
})
.collect_vec();
let root_ok = (|| {
let (block_expr, stable_ptr) = match ctx.function_body.exprs[loop_expr_id].clone() {
semantic::Expr::Loop(semantic::ExprLoop { body, stable_ptr, .. }) => {
// Fetch body block expr.
let semantic_block =
extract_matches!(&ctx.function_body.exprs[body], semantic::Expr::Block).clone();
let block_expr = (|| {
lower_expr_block(&mut ctx, &mut builder, &semantic_block)?;
// Add recursive call.
let signature = ctx.signature.clone();
call_loop_func(
&mut ctx,
signature,
&mut builder,
loop_expr_id,
stable_ptr.untyped(),
)
})();
(block_expr, stable_ptr)
}
semantic::Expr::While(while_expr) => {
let stable_ptr = while_expr.stable_ptr;
let block_expr = lower_while_loop(&mut ctx, &mut builder, while_expr, loop_expr_id);
(block_expr, stable_ptr)
}
semantic::Expr::For(for_expr) => {
let stable_ptr: cairo_lang_syntax::node::ast::ExprPtr = for_expr.stable_ptr;
let block_expr: Result<LoweredExpr, LoweringFlowError> =
lower_for_loop(&mut ctx, &mut builder, for_expr, loop_expr_id);
(block_expr, stable_ptr)
}
_ => unreachable!("Loop expression must be either loop, while or for."),
};
let block_sealed = lowered_expr_to_block_scope_end(&mut ctx, builder, block_expr)?;
wrap_sealed_block_as_function(&mut ctx, block_sealed, stable_ptr.untyped())?;
Ok(root_block_id)
})();
ctx.current_loop_expr_id = old_loop_expr_id;
let blocks = root_ok
.map(|_| ctx.blocks.build().expect("Root block must exist."))
.unwrap_or_else(FlatBlocks::new_errored);
Ok(FlatLowered {
diagnostics: ctx.diagnostics.build(),
variables: ctx.variables.variables,
blocks,
signature: ctx.signature.clone(),
parameters,
})
}
/// Wraps `block_sealed` as the root block of a function.
fn wrap_sealed_block_as_function(
ctx: &mut LoweringContext<'_, '_>,
block_sealed: SealedBlockBuilder,
stable_ptr: SyntaxStablePtrId,
) -> Maybe<()> {
let SealedBlockBuilder::GotoCallsite { mut builder, expr } = block_sealed else {
return Ok(());
};
let location = ctx.get_location(stable_ptr);
match &expr {
Some(expr) if ctx.variables[expr.var_id].ty == never_ty(ctx.db.upcast()) => {
// If the expression is of type never, then the block is unreachable, so add a match on
// never to make it a viable block end.
let semantic::TypeLongId::Concrete(semantic::ConcreteTypeId::Enum(concrete_enum_id)) =
ctx.variables[expr.var_id].ty.lookup_intern(ctx.db)
else {
unreachable!("Never type must be a concrete enum.");
};
builder.unreachable_match(
ctx,
MatchInfo::Enum(MatchEnumInfo {
concrete_enum_id,
input: *expr,
arms: vec![],
location,
}),
);
Ok(())
}
_ => {
// Convert to a return.
let var_usage = expr.unwrap_or_else(|| {
generators::StructConstruct {
inputs: vec![],
ty: unit_ty(ctx.db.upcast()),
location,
}
.add(ctx, &mut builder.statements)
});
builder.ret(ctx, var_usage, location)
}
}
}
/// Lowers a semantic block.
fn lower_block(
ctx: &mut LoweringContext<'_, '_>,
mut builder: BlockBuilder,
semantic_block: &semantic::ExprBlock,
) -> Maybe<SealedBlockBuilder> {
let block_expr = lower_expr_block(ctx, &mut builder, semantic_block);
lowered_expr_to_block_scope_end(ctx, builder, block_expr)
}
/// Lowers a semantic block.
fn lower_expr_block(
ctx: &mut LoweringContext<'_, '_>,
builder: &mut BlockBuilder,
expr_block: &semantic::ExprBlock,
) -> LoweringResult<LoweredExpr> {
log::trace!("Lowering a block.");
for (i, stmt_id) in expr_block.statements.iter().enumerate() {
let stmt = ctx.function_body.statements[*stmt_id].clone();
let Err(err) = lower_statement(ctx, builder, &stmt) else {
continue;
};
if err.is_unreachable() {
// If flow is not reachable anymore, no need to continue emitting statements.
// 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_body.statements[expr_block.statements[i + 1]];
let end_stmt =
&ctx.function_body.statements[*expr_block.statements.last().unwrap()];
// Emit diagnostic for the rest of the statements with unreachable.
ctx.diagnostics.report(
start_stmt.stable_ptr().untyped(),
Unreachable { last_statement_ptr: end_stmt.into() },
);
}
}
return Err(err);
}
// Determine correct block end.
let location = ctx.get_location(expr_block.stable_ptr.untyped());
expr_block
.tail
.map(|expr| lower_expr(ctx, builder, expr))
.unwrap_or_else(|| Ok(LoweredExpr::Tuple { exprs: vec![], location }))
}
/// Lowers an expression that is either a complete block, or the end (tail expression) of a
/// block.
pub fn lower_tail_expr(
ctx: &mut LoweringContext<'_, '_>,
mut builder: BlockBuilder,
expr: semantic::ExprId,
) -> Maybe<SealedBlockBuilder> {
log::trace!("Lowering a tail expression.");
let lowered_expr = lower_expr(ctx, &mut builder, expr);
lowered_expr_to_block_scope_end(ctx, builder, lowered_expr)
}
/// Converts [`LoweringResult<LoweredExpr>`] into `BlockScopeEnd`.
pub fn lowered_expr_to_block_scope_end(
ctx: &mut LoweringContext<'_, '_>,
mut builder: BlockBuilder,
lowered_expr: LoweringResult<LoweredExpr>,
) -> Maybe<SealedBlockBuilder> {
Ok(match lowered_expr {
Ok(LoweredExpr::Tuple { exprs, .. }) if exprs.is_empty() => builder.goto_callsite(None),
Ok(lowered_expr) => match lowered_expr.as_var_usage(ctx, &mut builder) {
Ok(var) => builder.goto_callsite(Some(var)),
Err(err) => lowering_flow_error_to_sealed_block(ctx, builder, err)?,
},
Err(err) => lowering_flow_error_to_sealed_block(ctx, builder, err)?,
})
}
/// Lowers a semantic statement.
pub fn lower_statement(
ctx: &mut LoweringContext<'_, '_>,
builder: &mut BlockBuilder,
stmt: &semantic::Statement,
) -> Result<(), LoweringFlowError> {
match stmt {
semantic::Statement::Expr(semantic::StatementExpr { expr, stable_ptr: _ }) => {
log::trace!("Lowering an expression statement.");
let lowered_expr = lower_expr(ctx, builder, *expr)?;
// The LoweredExpr must be evaluated now to push/bring back variables in case it is
// LoweredExpr::ExternEnum.
if let LoweredExpr::ExternEnum(x) = lowered_expr {
x.as_var_usage(ctx, builder)?;
}
}
semantic::Statement::Let(semantic::StatementLet { pattern, expr, stable_ptr: _ }) => {
log::trace!("Lowering a let statement.");
let lowered_expr = lower_expr(ctx, builder, *expr)?;
let pattern = ctx.function_body.patterns[*pattern].clone();
lower_single_pattern(ctx, builder, pattern, lowered_expr)?
}
semantic::Statement::Continue(semantic::StatementContinue { stable_ptr }) => {
log::trace!("Lowering a continue statement.");
let lowered_expr = call_loop_func(
ctx,
ctx.signature.clone(),
builder,
ctx.current_loop_expr_id.unwrap(),
stable_ptr.untyped(),
)?;
let ret_var = lowered_expr.as_var_usage(ctx, builder)?;
return Err(LoweringFlowError::Return(ret_var, ctx.get_location(stable_ptr.untyped())));
}
semantic::Statement::Return(semantic::StatementReturn { expr_option, stable_ptr })
| semantic::Statement::Break(semantic::StatementBreak { expr_option, stable_ptr }) => {
log::trace!("Lowering a return | break statement.");
let ret_var = match expr_option {
None => {
let location = ctx.get_location(stable_ptr.untyped());
LoweredExpr::Tuple { exprs: vec![], location }.as_var_usage(ctx, builder)?
}
Some(expr) => lower_expr_to_var_usage(ctx, builder, *expr)?,
};
return Err(LoweringFlowError::Return(ret_var, ctx.get_location(stable_ptr.untyped())));
}
}
Ok(())
}
// 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 builder.
/// Note that single patterns are the only way to bind new local variables in the semantic
/// model.
fn lower_single_pattern(
ctx: &mut LoweringContext<'_, '_>,
builder: &mut BlockBuilder,
pattern: semantic::Pattern,
lowered_expr: LoweredExpr,
) -> Result<(), LoweringFlowError> {
log::trace!("Lowering a single pattern.");
match pattern {
semantic::Pattern::Literal(_)
| semantic::Pattern::StringLiteral(_)
| semantic::Pattern::EnumVariant(_) => {
return Err(LoweringFlowError::Failed(
ctx.diagnostics.report(&pattern, UnsupportedPattern),
));
}
semantic::Pattern::Variable(semantic::PatternVariable {
name: _,
var: sem_var,
stable_ptr,
}) => {
let sem_var = semantic::Variable::Local(sem_var);
// Deposit the owned variable in the semantic variables store.
let var = lowered_expr.as_var_usage(ctx, builder)?.var_id;
// Override variable location.
ctx.variables.variables[var].location = ctx.get_location(stable_ptr.untyped());
builder.put_semantic(sem_var.id(), var);
// TODO(spapini): Build semantic_defs in semantic model.
ctx.semantic_defs.insert(sem_var.id(), sem_var);
}
semantic::Pattern::Struct(structure) => {
let members = ctx
.db
.concrete_struct_members(structure.concrete_struct_id)
.map_err(LoweringFlowError::Failed)?;
let mut required_members = UnorderedHashMap::<_, _>::from_iter(
structure.field_patterns.iter().map(|(member, pattern)| (member.id, pattern)),
);
let generator = generators::StructDestructure {
input: lowered_expr.as_var_usage(ctx, builder)?.var_id,
var_reqs: members
.iter()
.map(|(_, member)| VarRequest {
ty: wrap_in_snapshots(ctx.db.upcast(), member.ty, structure.n_snapshots),
location: ctx.get_location(
required_members
.get(&member.id)
.map(|pattern| {
ctx.function_body.patterns[**pattern].stable_ptr().untyped()
})
.unwrap_or_else(|| structure.stable_ptr.untyped()),
),
})
.collect(),
};
for (var_id, (_, member)) in izip!(generator.add(ctx, &mut builder.statements), members)
{
if let Some(member_pattern) = required_members.remove(&member.id) {
let member_pattern = ctx.function_body.patterns[*member_pattern].clone();
let stable_ptr = member_pattern.stable_ptr();
lower_single_pattern(
ctx,
builder,
member_pattern,
LoweredExpr::AtVariable(VarUsage {
var_id,
location: ctx.get_location(stable_ptr.untyped()),
}),
)?;
}
}
}
semantic::Pattern::Tuple(semantic::PatternTuple {
field_patterns: patterns, ty, ..
})
| semantic::Pattern::FixedSizeArray(semantic::PatternFixedSizeArray {
elements_patterns: patterns,
ty,
..
}) => {
lower_tuple_like_pattern_helper(ctx, builder, lowered_expr, &patterns, ty)?;
}
semantic::Pattern::Otherwise(_) => {}
semantic::Pattern::Missing(_) => unreachable!("Missing pattern in semantic model."),
}
Ok(())
}
/// An helper function to handle patterns of tuples or fixed size arrays.
fn lower_tuple_like_pattern_helper(
ctx: &mut LoweringContext<'_, '_>,
builder: &mut BlockBuilder,
lowered_expr: LoweredExpr,
patterns: &[semantic::PatternId],
ty: semantic::TypeId,
) -> LoweringResult<()> {
let outputs = match lowered_expr {
LoweredExpr::Tuple { exprs, .. } => exprs,
LoweredExpr::FixedSizeArray { exprs, .. } => exprs,
_ => {
let (n_snapshots, long_type_id) = peel_snapshots(ctx.db.upcast(), ty);
let tys = match long_type_id {
TypeLongId::Tuple(tys) => tys,
TypeLongId::FixedSizeArray { type_id, size } => {
let size = size
.lookup_intern(ctx.db)
.into_int()
.expect("Expected ConstValue::Int for size")
.to_usize()
.unwrap();
vec![type_id; size]
}
_ => unreachable!("Tuple-like pattern must be a tuple or fixed size array."),
};
let reqs = patterns
.iter()
.zip_eq(tys)
.map(|(pattern, ty)| VarRequest {
ty: wrap_in_snapshots(ctx.db.upcast(), ty, n_snapshots),
location: ctx
.get_location(ctx.function_body.patterns[*pattern].stable_ptr().untyped()),
})
.collect();
generators::StructDestructure {
input: lowered_expr.as_var_usage(ctx, builder)?.var_id,
var_reqs: reqs,
}
.add(ctx, &mut builder.statements)
.into_iter()
.map(|var_id| {
LoweredExpr::AtVariable(VarUsage {
var_id,
location: ctx.variables[var_id].location,
})
})
.collect()
}
};
for (var, pattern) in zip_eq(outputs, patterns) {
lower_single_pattern(ctx, builder, ctx.function_body.patterns[*pattern].clone(), var)?;
}
Ok(())
}
/// Lowers a semantic expression to a VarUsage.
///
/// For example, if we have the code:
/// foo(a + b)
///
/// then `a + b` will be assigned variable and a VarUsage object whose origin
/// is the location of the `a + b` expression.
fn lower_expr_to_var_usage(
ctx: &mut LoweringContext<'_, '_>,
builder: &mut BlockBuilder,
expr_id: semantic::ExprId,
) -> LoweringResult<VarUsage> {
lower_expr(ctx, builder, expr_id)?.as_var_usage(ctx, builder)
}
/// Lowers a semantic expression.
fn lower_expr(
ctx: &mut LoweringContext<'_, '_>,
builder: &mut BlockBuilder,
expr_id: semantic::ExprId,
) -> LoweringResult<LoweredExpr> {
let expr = ctx.function_body.exprs[expr_id].clone();
match &expr {
semantic::Expr::Constant(expr) => lower_expr_constant(ctx, expr, builder),
semantic::Expr::Tuple(expr) => lower_expr_tuple(ctx, expr, builder),
semantic::Expr::Snapshot(expr) => lower_expr_snapshot(ctx, expr, builder),
semantic::Expr::Desnap(expr) => lower_expr_desnap(ctx, expr, builder),
semantic::Expr::Assignment(expr) => lower_expr_assignment(ctx, expr, builder),
semantic::Expr::LogicalOperator(expr) => lower_logical_op(ctx, builder, expr),
semantic::Expr::Block(expr) => lower_expr_block(ctx, builder, expr),
semantic::Expr::FunctionCall(expr) => lower_expr_function_call(ctx, expr, builder),
semantic::Expr::Match(expr) => lower_expr_match(ctx, expr, builder),
semantic::Expr::If(expr) => lower_expr_if(ctx, builder, expr),
semantic::Expr::Loop(_) | semantic::Expr::While(_) | semantic::Expr::For(_) => {
lower_expr_loop(ctx, builder, expr_id)
}
semantic::Expr::Var(expr) => {
let member_path = ExprVarMemberPath::Var(expr.clone());
log::trace!("Lowering a variable: {:?}", expr.debug(&ctx.expr_formatter));
Ok(LoweredExpr::Member(member_path, ctx.get_location(expr.stable_ptr.untyped())))
}
semantic::Expr::Literal(expr) => lower_expr_literal(ctx, expr, builder),
semantic::Expr::StringLiteral(expr) => lower_expr_string_literal(ctx, expr, builder),
semantic::Expr::MemberAccess(expr) => lower_expr_member_access(ctx, expr, builder),
semantic::Expr::StructCtor(expr) => lower_expr_struct_ctor(ctx, expr, builder),
semantic::Expr::EnumVariantCtor(expr) => lower_expr_enum_ctor(ctx, expr, builder),
semantic::Expr::FixedSizeArray(expr) => lower_expr_fixed_size_array(ctx, expr, builder),
semantic::Expr::PropagateError(expr) => lower_expr_error_propagate(ctx, expr, builder),
semantic::Expr::Missing(semantic::ExprMissing { diag_added, .. }) => {
Err(LoweringFlowError::Failed(*diag_added))
}
}
}
fn lower_expr_literal(
ctx: &mut LoweringContext<'_, '_>,
expr: &semantic::ExprLiteral,
builder: &mut BlockBuilder,
) -> LoweringResult<LoweredExpr> {
log::trace!("Lowering a literal: {:?}", expr.debug(&ctx.expr_formatter));
lower_expr_literal_helper(ctx, expr.stable_ptr.untyped(), expr.ty, &expr.value, builder)
}
/// Lowers a semantic expression that is a literal, possibly including a negation.
fn lower_expr_literal_helper(
ctx: &mut LoweringContext<'_, '_>,
stable_ptr: SyntaxStablePtrId,
ty: semantic::TypeId,
value: &BigInt,
builder: &mut BlockBuilder,
) -> LoweringResult<LoweredExpr> {
let value = value_as_const_value(ctx.db.upcast(), ty, value)
.map_err(|err| {
ctx.diagnostics.report(stable_ptr, LoweringDiagnosticKind::LiteralError(err))
})
.unwrap_or_else(ConstValue::Missing);
let location = ctx.get_location(stable_ptr);
Ok(LoweredExpr::AtVariable(
generators::Const { value, ty, location }.add(ctx, &mut builder.statements),
))
}
fn lower_expr_string_literal(
ctx: &mut LoweringContext<'_, '_>,
expr: &semantic::ExprStringLiteral,
builder: &mut BlockBuilder,
) -> LoweringResult<LoweredExpr> {
log::trace!("Lowering a string literal: {:?}", expr.debug(&ctx.expr_formatter));
let semantic_db = ctx.db.upcast();
// Get all the relevant types from the corelib.
let bytes31_ty = get_core_ty_by_name(semantic_db, "bytes31".into(), vec![]);
let data_array_ty =
get_core_ty_by_name(semantic_db, "Array".into(), vec![GenericArgumentId::Type(bytes31_ty)]);
let byte_array_ty = get_core_ty_by_name(semantic_db, "ByteArray".into(), vec![]);
let array_submodule = core_submodule(semantic_db, "array");
let data_array_new_function = FunctionLongId::Semantic(get_function_id(
semantic_db,
array_submodule,
"array_new".into(),
vec![GenericArgumentId::Type(bytes31_ty)],
))
.intern(ctx.db);
let data_array_append_function = FunctionLongId::Semantic(get_function_id(
semantic_db,
array_submodule,
"array_append".into(),
vec![GenericArgumentId::Type(bytes31_ty)],
))
.intern(ctx.db);
// Emit lowering statements to build the ByteArray struct components.
let mut data_array_usage =
build_empty_data_array(ctx, builder, expr, data_array_new_function, data_array_ty);
let remainder = add_chunks_to_data_array(
ctx,
builder,
expr,
bytes31_ty,
&mut data_array_usage,
data_array_append_function,
data_array_ty,
);
let (pending_word_usage, pending_word_len_usage) =
add_pending_word(ctx, builder, expr, remainder);
// Emit the lowering statement for creating the ByteArray struct.
let byte_array_usage = generators::StructConstruct {
inputs: vec![data_array_usage, pending_word_usage, pending_word_len_usage],
ty: byte_array_ty,
location: ctx.get_location(expr.stable_ptr.untyped()),
}
.add(ctx, &mut builder.statements);
Ok(LoweredExpr::AtVariable(byte_array_usage))
}
/// Emits lowering statements to build an empty data array.
fn build_empty_data_array(
ctx: &mut LoweringContext<'_, '_>,
builder: &mut BlockBuilder,
expr: &semantic::ExprStringLiteral,
data_array_new_function: crate::ids::FunctionId,
data_array_ty: semantic::TypeId,
) -> VarUsage {
generators::Call {
function: data_array_new_function,
inputs: vec![],
coupon_input: None,
extra_ret_tys: vec![],
ret_tys: vec![data_array_ty],
location: ctx.get_location(expr.stable_ptr.untyped()),
}
.add(ctx, &mut builder.statements)
.returns[0]
}
/// Emits lowering statements to add 31-byte words to the given data array.
fn add_chunks_to_data_array<'a>(
ctx: &mut LoweringContext<'_, '_>,
builder: &mut BlockBuilder,
expr: &'a semantic::ExprStringLiteral,
bytes31_ty: semantic::TypeId,
data_array_usage: &mut VarUsage,
data_array_append_function: crate::ids::FunctionId,
data_array_ty: semantic::TypeId,
) -> &'a [u8] {
let expr_stable_ptr = expr.stable_ptr.untyped();
let chunks = expr.value.as_bytes().chunks_exact(31);
let remainder = chunks.remainder();
for chunk in chunks {
let chunk_usage = generators::Const {
value: ConstValue::Int(BigInt::from_bytes_be(Sign::Plus, chunk), bytes31_ty),
ty: bytes31_ty,
location: ctx.get_location(expr_stable_ptr),
}
.add(ctx, &mut builder.statements);
*data_array_usage = generators::Call {
function: data_array_append_function,
inputs: vec![*data_array_usage, chunk_usage],
coupon_input: None,
extra_ret_tys: vec![data_array_ty],
ret_tys: vec![],
location: ctx.get_location(expr_stable_ptr),
}