cairo-lang-semantic 2.18.0

Cairo semantic model.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
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
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
use std::iter::zip;
use std::sync::Arc;

use cairo_lang_debug::DebugWithDb;
use cairo_lang_defs::db::DefsGroup;
use cairo_lang_defs::ids::{
    ConstantId, ExternFunctionId, GenericParamId, LanguageElementId, LookupItemId, ModuleItemId,
    NamedLanguageElementId, TraitConstantId, TraitId, VarId,
};
use cairo_lang_diagnostics::{
    DiagnosticAdded, DiagnosticEntry, DiagnosticNote, Diagnostics, Maybe, MaybeAsRef,
    skip_diagnostic,
};
use cairo_lang_proc_macros::{DebugWithDb, HeapSize, SemanticObject};
use cairo_lang_syntax::node::ast::ItemConstant;
use cairo_lang_syntax::node::ids::SyntaxStablePtrId;
use cairo_lang_syntax::node::{TypedStablePtr, TypedSyntaxNode};
use cairo_lang_utils::ordered_hash_map::OrderedHashMap;
use cairo_lang_utils::ordered_hash_set::OrderedHashSet;
use cairo_lang_utils::unordered_hash_map::UnorderedHashMap;
use cairo_lang_utils::unordered_hash_set::UnorderedHashSet;
use cairo_lang_utils::{Intern, define_short_id, extract_matches, require, try_extract_matches};
use itertools::Itertools;
use num_bigint::BigInt;
use num_traits::{ToPrimitive, Zero};
use salsa::Database;
use starknet_types_core::felt::{CAIRO_PRIME_BIGINT, Felt as Felt252};

use super::functions::{GenericFunctionId, GenericFunctionWithBodyId};
use super::imp::{ImplId, ImplLongId};
use crate::corelib::{
    CoreInfo, CorelibSemantic, core_nonzero_ty, false_variant, true_variant,
    try_extract_bounded_int_type_ranges, try_extract_nz_wrapped_type, unit_ty, validate_literal,
};
use crate::diagnostic::{SemanticDiagnosticKind, SemanticDiagnostics, SemanticDiagnosticsBuilder};
use crate::expr::compute::{ComputationContext, ExprAndId, compute_expr_semantic};
use crate::expr::inference::conform::InferenceConform;
use crate::expr::inference::{ConstVar, InferenceId};
use crate::helper::ModuleHelper;
use crate::items::enm::SemanticEnumEx;
use crate::items::extern_function::ExternFunctionSemantic;
use crate::items::free_function::FreeFunctionSemantic;
use crate::items::function_with_body::FunctionWithBodySemantic;
use crate::items::generics::GenericParamSemantic;
use crate::items::imp::ImplSemantic;
use crate::items::structure::StructSemantic;
use crate::items::trt::TraitSemantic;
use crate::resolve::{Resolver, ResolverData};
use crate::substitution::{GenericSubstitution, SemanticRewriter};
use crate::types::resolve_type;
use crate::{
    Arenas, ConcreteFunction, ConcreteTypeId, ConcreteVariant, Condition, Expr, ExprBlock,
    ExprConstant, ExprFunctionCall, ExprFunctionCallArg, ExprId, ExprMemberAccess, ExprStructCtor,
    FunctionId, GenericParam, LogicalOperator, Pattern, PatternId, SemanticDiagnostic, Statement,
    TypeId, TypeLongId, semantic_object_for_id,
};

#[derive(Clone, Debug, PartialEq, Eq, DebugWithDb)]
#[debug_db(dyn Database)]
pub struct Constant<'db> {
    /// The actual id of the const expression value.
    pub value: ExprId,
    /// The arena of all the expressions for the const calculation.
    pub arenas: Arc<Arenas<'db>>,
}

// TODO: Review this well.
unsafe impl<'db> salsa::Update for Constant<'db> {
    unsafe fn maybe_update(old_pointer: *mut Self, new_value: Self) -> bool {
        let old_constant: &mut Constant<'db> = unsafe { &mut *old_pointer };

        if old_constant.value != new_value.value {
            *old_constant = new_value;
            return true;
        }

        false
    }
}

impl<'db> Constant<'db> {
    pub fn ty(&self) -> TypeId<'db> {
        self.arenas.exprs[self.value].ty()
    }
}

/// Information about a constant definition.
///
/// Helper struct for the data returned by [ConstantSemantic::constant_semantic_data].
#[derive(Clone, Debug, PartialEq, Eq, DebugWithDb, salsa::Update)]
#[debug_db(dyn Database)]
pub struct ConstantData<'db> {
    pub diagnostics: Diagnostics<'db, SemanticDiagnostic<'db>>,
    pub constant: Maybe<Constant<'db>>,
    pub const_value: ConstValueId<'db>,
    pub resolver_data: Arc<ResolverData<'db>>,
}

define_short_id!(ConstValueId, ConstValue<'db>);
semantic_object_for_id!(ConstValueId, ConstValue<'a>);
impl<'db> ConstValueId<'db> {
    /// Creates a new const value from a BigInt.
    pub fn from_int(db: &'db dyn Database, ty: TypeId<'db>, value: &BigInt) -> Self {
        let get_basic_const_value = |ty| {
            let info = db.const_calc_info();
            if ty != info.u256 {
                ConstValue::Int(value.clone(), ty).intern(db)
            } else {
                let mask128 = BigInt::from(u128::MAX);
                let low = value & mask128;
                let high = value >> 128;
                ConstValue::Struct(
                    vec![
                        (ConstValue::Int(low, info.u128).intern(db)),
                        (ConstValue::Int(high, info.u128).intern(db)),
                    ],
                    ty,
                )
                .intern(db)
            }
        };
        if let Some(inner) = try_extract_nz_wrapped_type(db, ty) {
            ConstValue::NonZero(get_basic_const_value(inner)).intern(db)
        } else {
            get_basic_const_value(ty)
        }
    }
    /// Returns a formatted string of the const value.
    pub fn format(&self, db: &dyn Database) -> String {
        format!("{:?}", self.long(db).debug(db))
    }

    /// Returns true if the const does not depend on any generics.
    pub fn is_fully_concrete(&self, db: &dyn Database) -> bool {
        self.long(db).is_fully_concrete(db)
    }

    /// Returns true if the const does not contain any inference variables.
    pub fn is_var_free(&self, db: &dyn Database) -> bool {
        self.long(db).is_var_free(db)
    }

    /// Returns the type of the const.
    pub fn ty(&self, db: &'db dyn Database) -> Maybe<TypeId<'db>> {
        self.long(db).ty(db)
    }

    /// A utility function for extracting the generic parameters arguments from a ConstValueId.
    /// Uses memoization via `visited` to avoid re-traversing shared subtypes in DAG structures.
    pub fn extract_generic_params(
        &self,
        db: &'db dyn Database,
        generic_parameters: &mut OrderedHashSet<GenericParamId<'db>>,
        visited: &mut OrderedHashSet<TypeId<'db>>,
    ) -> Maybe<()> {
        match self.long(db) {
            ConstValue::Int(_, type_id) | ConstValue::Struct(_, type_id) => {
                type_id.extract_generic_params(db, generic_parameters, visited)?
            }
            ConstValue::Enum(_, const_value_id) => {
                const_value_id.ty(db)?.extract_generic_params(db, generic_parameters, visited)?
            }
            ConstValue::NonZero(const_value_id) => {
                const_value_id.extract_generic_params(db, generic_parameters, visited)?
            }
            ConstValue::Generic(generic_param_id) => {
                generic_parameters.insert(*generic_param_id);
            }
            ConstValue::ImplConstant(impl_constant_id) => {
                for garg in impl_constant_id.impl_id().concrete_trait(db)?.generic_args(db) {
                    garg.extract_generic_params(db, generic_parameters, visited)?;
                }
            }
            ConstValue::Var(_, type_id) => {
                type_id.extract_generic_params(db, generic_parameters, visited)?
            }
            ConstValue::Missing(diagnostic_added) => return Err(*diagnostic_added),
        }
        Ok(())
    }
}

/// Moves the value of a felt252, to the range of `[range_min, range_min + PRIME)`.
pub fn felt252_for_downcast(value: &BigInt, range_min: &BigInt) -> BigInt {
    Felt252::from(value - range_min).to_bigint() + range_min
}

/// Canonicalize the value of a felt252, to the range of `(-PRIME, PRIME)`.
pub fn canonical_felt252(value: &BigInt) -> BigInt {
    value % &*CAIRO_PRIME_BIGINT
}

/// A constant value.
#[derive(Clone, Debug, Hash, PartialEq, Eq, SemanticObject, HeapSize, salsa::Update)]
pub enum ConstValue<'db> {
    Int(#[dont_rewrite] BigInt, TypeId<'db>),
    Struct(Vec<ConstValueId<'db>>, TypeId<'db>),
    Enum(ConcreteVariant<'db>, ConstValueId<'db>),
    NonZero(ConstValueId<'db>),
    Generic(#[dont_rewrite] GenericParamId<'db>),
    ImplConstant(ImplConstantId<'db>),
    Var(ConstVar<'db>, TypeId<'db>),
    /// A missing value, used in cases where the value is not known due to diagnostics.
    Missing(#[dont_rewrite] DiagnosticAdded),
}
impl<'db> ConstValue<'db> {
    /// Returns true if the const does not depend on any generics.
    pub fn is_fully_concrete(&self, db: &dyn Database) -> bool {
        self.ty(db).unwrap().is_fully_concrete(db)
            && match self {
                ConstValue::Int(_, _) => true,
                ConstValue::Struct(members, _) => {
                    members.iter().all(|member| member.is_fully_concrete(db))
                }
                ConstValue::Enum(_, val) | ConstValue::NonZero(val) => val.is_fully_concrete(db),
                ConstValue::Generic(_)
                | ConstValue::Var(_, _)
                | ConstValue::Missing(_)
                | ConstValue::ImplConstant(_) => false,
            }
    }

    /// Returns true if the const does not contain any inference variables.
    pub fn is_var_free(&self, db: &dyn Database) -> bool {
        self.ty(db).unwrap().is_var_free(db)
            && match self {
                ConstValue::Int(_, _) | ConstValue::Generic(_) | ConstValue::Missing(_) => true,
                ConstValue::Struct(members, _) => {
                    members.iter().all(|member| member.is_var_free(db))
                }
                ConstValue::Enum(_, val) | ConstValue::NonZero(val) => val.is_var_free(db),
                ConstValue::Var(_, _) => false,
                ConstValue::ImplConstant(impl_constant) => impl_constant.impl_id().is_var_free(db),
            }
    }

    /// Returns the type of the const.
    pub fn ty(&self, db: &'db dyn Database) -> Maybe<TypeId<'db>> {
        Ok(match self {
            ConstValue::Int(_, ty) => *ty,
            ConstValue::Struct(_, ty) => *ty,
            ConstValue::Enum(variant, _) => {
                TypeLongId::Concrete(ConcreteTypeId::Enum(variant.concrete_enum_id)).intern(db)
            }
            ConstValue::NonZero(value) => core_nonzero_ty(db, value.ty(db)?),
            ConstValue::Generic(param) => {
                extract_matches!(db.generic_param_semantic(*param)?, GenericParam::Const).ty
            }
            ConstValue::Var(_, ty) => *ty,
            ConstValue::Missing(_) => TypeId::missing(db, skip_diagnostic()),
            ConstValue::ImplConstant(impl_constant_id) => {
                db.impl_constant_concrete_implized_type(*impl_constant_id)?
            }
        })
    }

    /// Returns the value of an int const as a BigInt.
    pub fn to_int(&self) -> Option<&BigInt> {
        match self {
            ConstValue::Int(value, _) => Some(value),
            _ => None,
        }
    }
}

/// An impl item of kind const.
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, SemanticObject, HeapSize, salsa::Update)]
pub struct ImplConstantId<'db> {
    /// The impl the item const is in.
    impl_id: ImplId<'db>,
    /// The trait const this impl const "implements".
    trait_constant_id: TraitConstantId<'db>,
}

impl<'db> ImplConstantId<'db> {
    /// Creates a new impl constant id. For an impl constant of a concrete impl, asserts that the
    /// trait constant belongs to the same trait that the impl implements (panics if not).
    pub fn new(
        impl_id: ImplId<'db>,
        trait_constant_id: TraitConstantId<'db>,
        db: &dyn Database,
    ) -> Self {
        if let ImplLongId::Concrete(concrete_impl) = impl_id.long(db) {
            let impl_def_id = concrete_impl.impl_def_id(db);
            assert_eq!(Ok(trait_constant_id.trait_id(db)), db.impl_def_trait(impl_def_id));
        }

        ImplConstantId { impl_id, trait_constant_id }
    }
    pub fn impl_id(&self) -> ImplId<'db> {
        self.impl_id
    }
    pub fn trait_constant_id(&self) -> TraitConstantId<'db> {
        self.trait_constant_id
    }

    pub fn format(&self, db: &dyn Database) -> String {
        format!("{}::{}", self.impl_id.name(db), self.trait_constant_id.name(db).long(db))
    }
}
impl<'db> DebugWithDb<'db> for ImplConstantId<'db> {
    type Db = dyn Database;

    fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &'db dyn Database) -> std::fmt::Result {
        write!(f, "{}", self.format(db))
    }
}

/// Returns the semantic data of a constant.
#[salsa::tracked(returns(ref), cycle_result=constant_semantic_data_cycle)]
fn constant_semantic_data<'db>(
    db: &'db dyn Database,
    const_id: ConstantId<'db>,
    in_cycle: bool,
) -> Maybe<ConstantData<'db>> {
    let lookup_item_id = LookupItemId::ModuleItem(ModuleItemId::Constant(const_id));
    if in_cycle {
        constant_semantic_data_cycle_helper(
            db,
            &db.module_constant_by_id(const_id)?,
            lookup_item_id,
            None,
            &const_id,
        )
    } else {
        constant_semantic_data_helper(
            db,
            &db.module_constant_by_id(const_id)?,
            lookup_item_id,
            None,
            &const_id,
        )
    }
}

/// Cycle handling for [ConstantSemantic::constant_semantic_data].
fn constant_semantic_data_cycle<'db>(
    db: &'db dyn Database,
    _id: salsa::Id,
    const_id: ConstantId<'db>,
    _in_cycle: bool,
) -> Maybe<ConstantData<'db>> {
    let lookup_item_id = LookupItemId::ModuleItem(ModuleItemId::Constant(const_id));
    constant_semantic_data_cycle_helper(
        db,
        &db.module_constant_by_id(const_id)?,
        lookup_item_id,
        None,
        &const_id,
    )
}

/// Returns constant semantic data for the given ItemConstant.
pub fn constant_semantic_data_helper<'db>(
    db: &'db dyn Database,
    constant_ast: &ItemConstant<'db>,
    lookup_item_id: LookupItemId<'db>,
    parent_resolver_data: Option<Arc<ResolverData<'db>>>,
    element_id: &impl LanguageElementId<'db>,
) -> Maybe<ConstantData<'db>> {
    let module_id = element_id.parent_module(db);
    let mut diagnostics: SemanticDiagnostics<'_> = SemanticDiagnostics::new(module_id);
    // TODO(spapini): when code changes in a file, all the AST items change (as they contain a path
    // to the green root that changes. Once ASTs are rooted on items, use a selector that picks only
    // the item instead of all the module data.

    let inference_id = InferenceId::LookupItemDeclaration(lookup_item_id);

    let mut resolver = match parent_resolver_data {
        Some(parent_resolver_data) => {
            Resolver::with_data(db, parent_resolver_data.clone_with_inference_id(db, inference_id))
        }
        None => Resolver::new(db, module_id, inference_id),
    };
    resolver.set_feature_config(element_id, constant_ast, &mut diagnostics);

    let ty_syntax = constant_ast.type_clause(db).ty(db);
    let constant_type = resolve_type(db, &mut diagnostics, &mut resolver, &ty_syntax);
    // The type of a constant must not rely on its value, to create better stability for the
    // constant signature.
    if !constant_type.is_var_free(db) {
        diagnostics.report(
            ty_syntax.stable_ptr(db).untyped(),
            SemanticDiagnosticKind::ConstTypeNotVarFree,
        );
    }

    let mut ctx = ComputationContext::new_global(db, &mut diagnostics, &mut resolver);

    let value = compute_expr_semantic(&mut ctx, &constant_ast.value(db));
    let const_value = resolve_const_expr_and_evaluate(
        db,
        &mut ctx,
        &value,
        constant_ast.stable_ptr(db).untyped(),
        constant_type,
        true,
    );
    let constant = Ok(Constant { value: value.id, arenas: Arc::new(ctx.arenas) });
    let const_value = resolver
        .inference()
        .rewrite(const_value)
        .unwrap_or_else(|_| ConstValue::Missing(skip_diagnostic()).intern(db));
    let resolver_data = Arc::new(resolver.data);
    Ok(ConstantData { diagnostics: diagnostics.build(), const_value, constant, resolver_data })
}

/// Helper for cycle handling of constants.
pub fn constant_semantic_data_cycle_helper<'db>(
    db: &'db dyn Database,
    constant_ast: &ItemConstant<'db>,
    lookup_item_id: LookupItemId<'db>,
    parent_resolver_data: Option<Arc<ResolverData<'db>>>,
    element_id: &impl LanguageElementId<'db>,
) -> Maybe<ConstantData<'db>> {
    let module_id = element_id.parent_module(db);
    let mut diagnostics: SemanticDiagnostics<'_> = SemanticDiagnostics::new(module_id);

    let inference_id = InferenceId::LookupItemDeclaration(lookup_item_id);

    let resolver = match parent_resolver_data {
        Some(parent_resolver_data) => {
            Resolver::with_data(db, parent_resolver_data.clone_with_inference_id(db, inference_id))
        }
        None => Resolver::new(db, module_id, inference_id),
    };

    let resolver_data = Arc::new(resolver.data);

    let diagnostic_added =
        diagnostics.report(constant_ast.stable_ptr(db), SemanticDiagnosticKind::ConstCycle);
    Ok(ConstantData {
        constant: Err(diagnostic_added),
        const_value: ConstValue::Missing(diagnostic_added).intern(db),
        diagnostics: diagnostics.build(),
        resolver_data,
    })
}

/// Checks if the given expression only involved constant calculations.
pub fn validate_const_expr<'db>(ctx: &mut ComputationContext<'db, '_>, expr_id: ExprId) {
    let info = ctx.db.const_calc_info();
    let mut eval_ctx = ConstantEvaluateContext {
        db: ctx.db,
        info: info.as_ref(),
        arenas: &ctx.arenas,
        vars: Default::default(),
        generic_substitution: Default::default(),
        depth: 0,
        diagnostics: ctx.diagnostics,
    };
    eval_ctx.validate(expr_id);
}

/// Resolves the given const expression and evaluates its value.
pub fn resolve_const_expr_and_evaluate<'db, 'mt>(
    db: &'db dyn Database,
    ctx: &'mt mut ComputationContext<'db, '_>,
    value: &ExprAndId<'db>,
    const_stable_ptr: SyntaxStablePtrId<'db>,
    target_type: TypeId<'db>,
    finalize: bool,
) -> ConstValueId<'db> {
    let prev_err_count = ctx.diagnostics.error_count;
    let mut_ref = &mut ctx.resolver;
    let mut inference: crate::expr::inference::Inference<'db, '_> = mut_ref.inference();
    if let Err(err_set) = inference.conform_ty(value.ty(), target_type) {
        inference.report_on_pending_error(err_set, ctx.diagnostics, const_stable_ptr);
    }

    if finalize {
        // Check fully resolved.
        inference.finalize(ctx.diagnostics, const_stable_ptr);
    } else if let Err(err_set) = inference.solve() {
        inference.report_on_pending_error(err_set, ctx.diagnostics, const_stable_ptr);
    }

    // TODO(orizi): Consider moving this to be called only upon creating const values, other callees
    // don't necessarily need it.
    ctx.apply_inference_rewriter_to_exprs();

    match &value.expr {
        Expr::Constant(ExprConstant { const_value_id, .. }) => *const_value_id,
        // Check that the expression is a valid constant.
        _ if ctx.diagnostics.error_count > prev_err_count => {
            ConstValue::Missing(skip_diagnostic()).intern(db)
        }
        _ => {
            let info = db.const_calc_info();
            let mut eval_ctx = ConstantEvaluateContext {
                db,
                info: info.as_ref(),
                arenas: &ctx.arenas,
                vars: Default::default(),
                generic_substitution: Default::default(),
                depth: 0,
                diagnostics: ctx.diagnostics,
            };
            eval_ctx.validate(value.id);
            if eval_ctx.diagnostics.error_count > prev_err_count {
                ConstValue::Missing(skip_diagnostic()).intern(db)
            } else {
                eval_ctx.evaluate(value.id)
            }
        }
    }
}

/// A context for evaluating constant expressions.
struct ConstantEvaluateContext<'a, 'r, 'mt> {
    db: &'a dyn Database,
    info: &'r ConstCalcInfo<'a>,
    arenas: &'r Arenas<'a>,
    vars: OrderedHashMap<VarId<'a>, ConstValueId<'a>>,
    generic_substitution: GenericSubstitution<'a>,
    depth: usize,
    diagnostics: &'mt mut SemanticDiagnostics<'a>,
}
impl<'a, 'r, 'mt> ConstantEvaluateContext<'a, 'r, 'mt> {
    /// Validate the given expression can be used as constant.
    fn validate(&mut self, expr_id: ExprId) {
        match &self.arenas.exprs[expr_id] {
            Expr::Var(_) | Expr::Constant(_) | Expr::Missing(_) => {}
            Expr::Block(ExprBlock { statements, tail: Some(inner), .. }) => {
                for statement_id in statements {
                    match &self.arenas.statements[*statement_id] {
                        Statement::Let(statement) => {
                            self.validate(statement.expr);
                        }
                        Statement::Expr(expr) => {
                            self.validate(expr.expr);
                        }
                        other => {
                            self.diagnostics.report(
                                other.stable_ptr(),
                                SemanticDiagnosticKind::UnsupportedConstant,
                            );
                        }
                    }
                }
                self.validate(*inner);
            }
            Expr::FunctionCall(expr) => {
                for arg in &expr.args {
                    match arg {
                        ExprFunctionCallArg::Value(arg) => self.validate(*arg),
                        ExprFunctionCallArg::Reference(var) => {
                            self.diagnostics.report(
                                var.stable_ptr(),
                                SemanticDiagnosticKind::UnsupportedConstant,
                            );
                        }
                        ExprFunctionCallArg::TempReference(expr_id) => {
                            self.diagnostics.report(
                                self.arenas.exprs[*expr_id].stable_ptr(),
                                SemanticDiagnosticKind::UnsupportedConstant,
                            );
                        }
                    }
                }
                if !self.is_function_const(expr.function) {
                    self.diagnostics.report(
                        expr.stable_ptr.untyped(),
                        SemanticDiagnosticKind::UnsupportedConstant,
                    );
                }
            }
            Expr::Literal(expr) => {
                if let Err(err) = validate_literal(self.db, expr.ty, &expr.value) {
                    self.diagnostics.report(
                        expr.stable_ptr.untyped(),
                        SemanticDiagnosticKind::LiteralError(err),
                    );
                }
            }
            Expr::Tuple(expr) => {
                for item in &expr.items {
                    self.validate(*item);
                }
            }
            Expr::StructCtor(ExprStructCtor { members, base_struct: None, .. }) => {
                for (expr_id, _) in members {
                    self.validate(*expr_id);
                }
            }
            Expr::EnumVariantCtor(expr) => self.validate(expr.value_expr),
            Expr::MemberAccess(expr) => self.validate(expr.expr),
            Expr::FixedSizeArray(expr) => match &expr.items {
                crate::FixedSizeArrayItems::Items(items) => {
                    for item in items {
                        self.validate(*item);
                    }
                }
                crate::FixedSizeArrayItems::ValueAndSize(value, _) => {
                    self.validate(*value);
                }
            },
            Expr::Snapshot(expr) => self.validate(expr.inner),
            Expr::Desnap(expr) => self.validate(expr.inner),
            Expr::LogicalOperator(expr) => {
                self.validate(expr.lhs);
                self.validate(expr.rhs);
            }
            Expr::Match(expr) => {
                self.validate(expr.matched_expr);
                for arm in &expr.arms {
                    self.validate(arm.expression);
                }
            }
            Expr::If(expr) => {
                for condition in &expr.conditions {
                    self.validate(match condition {
                        Condition::BoolExpr(id) | Condition::Let(id, _) => *id,
                    });
                }
                self.validate(expr.if_block);
                if let Some(else_block) = expr.else_block {
                    self.validate(else_block);
                }
            }
            other => {
                self.diagnostics.report(
                    other.stable_ptr().untyped(),
                    SemanticDiagnosticKind::UnsupportedConstant,
                );
            }
        }
    }

    /// Returns true if the given function is allowed to be called in constant context.
    fn is_function_const(&self, function_id: FunctionId<'a>) -> bool {
        if function_id == self.panic_with_felt252 {
            return true;
        }
        let db = self.db;
        let concrete_function = function_id.get_concrete(db);
        let signature = (|| match concrete_function.generic_function {
            GenericFunctionId::Free(id) => db.free_function_signature(id),
            GenericFunctionId::Extern(id) => db.extern_function_signature(id),
            GenericFunctionId::Impl(id) => {
                if let ImplLongId::Concrete(impl_id) = id.impl_id.long(db)
                    && let Ok(Some(impl_function_id)) = impl_id.get_impl_function(db, id.function)
                {
                    return self.db.impl_function_signature(impl_function_id);
                }
                self.db.trait_function_signature(id.function)
            }
        })();
        if signature.map(|s| s.is_const) == Ok(true) {
            return true;
        }
        let Ok(Some(body)) = concrete_function.body(db) else { return false };
        let GenericFunctionWithBodyId::Impl(imp) = body.generic_function(db) else {
            return false;
        };
        let impl_def = imp.concrete_impl_id.impl_def_id(db);
        if impl_def.parent_module(db).owning_crate(db) != db.core_crate() {
            return false;
        }
        let Ok(trait_id) = db.impl_def_trait(impl_def) else {
            return false;
        };
        self.const_traits.contains(&trait_id)
    }

    /// Evaluate the given const expression value.
    fn evaluate<'ctx>(&'ctx mut self, expr_id: ExprId) -> ConstValueId<'a> {
        let expr = &self.arenas.exprs[expr_id];
        let db = self.db;
        let to_missing = |diag_added| ConstValue::Missing(diag_added).intern(db);
        match expr {
            Expr::Var(expr) => self.vars.get(&expr.var).copied().unwrap_or_else(|| {
                to_missing(
                    self.diagnostics
                        .report(expr.stable_ptr, SemanticDiagnosticKind::UnsupportedConstant),
                )
            }),
            Expr::Constant(expr) => self
                .generic_substitution
                .substitute(self.db, expr.const_value_id)
                .unwrap_or_else(to_missing),
            Expr::Block(ExprBlock { statements, tail: Some(inner), .. }) => {
                for statement_id in statements {
                    match &self.arenas.statements[*statement_id] {
                        Statement::Let(statement) => {
                            let value = self.evaluate(statement.expr);
                            self.destructure_pattern(statement.pattern, value);
                        }
                        Statement::Expr(expr) => {
                            self.evaluate(expr.expr);
                        }
                        other => {
                            self.diagnostics.report(
                                other.stable_ptr(),
                                SemanticDiagnosticKind::UnsupportedConstant,
                            );
                        }
                    }
                }
                self.evaluate(*inner)
            }
            Expr::FunctionCall(expr) => self.evaluate_function_call(expr),
            Expr::Literal(expr) => ConstValueId::from_int(db, expr.ty, &expr.value),
            Expr::Tuple(expr) => ConstValue::Struct(
                expr.items.iter().map(|expr_id| self.evaluate(*expr_id)).collect(),
                expr.ty,
            )
            .intern(db),
            Expr::StructCtor(ExprStructCtor {
                members,
                base_struct: None,
                ty,
                concrete_struct_id,
                ..
            }) => {
                let member_order = match db.concrete_struct_members(*concrete_struct_id) {
                    Ok(member_order) => member_order,
                    Err(diag_add) => return to_missing(diag_add),
                };
                ConstValue::Struct(
                    member_order
                        .values()
                        .map(|m| {
                            members
                                .iter()
                                .find(|(_, member_id)| m.id == *member_id)
                                .map(|(expr_id, _)| self.evaluate(*expr_id))
                                // Semantic validation already reported an error, suppress cascading
                                // errors from const evaluation.
                                .unwrap_or_else(|| ConstValue::Missing(skip_diagnostic()).intern(db))
                        })
                        .collect(),
                    *ty,
                )
                .intern(db)
            }
            Expr::EnumVariantCtor(expr) => {
                ConstValue::Enum(expr.variant, self.evaluate(expr.value_expr)).intern(db)
            }
            Expr::MemberAccess(expr) => {
                self.evaluate_member_access(expr).unwrap_or_else(to_missing)
            }
            Expr::FixedSizeArray(expr) => ConstValue::Struct(
                match &expr.items {
                    crate::FixedSizeArrayItems::Items(items) => {
                        items.iter().map(|expr_id| self.evaluate(*expr_id)).collect()
                    }
                    crate::FixedSizeArrayItems::ValueAndSize(value, count) => {
                        let value = self.evaluate(*value);
                        if let Some(count) = count.long(db).to_int() {
                            vec![value; count.to_usize().unwrap()]
                        } else {
                            self.diagnostics.report(
                                expr.stable_ptr.untyped(),
                                SemanticDiagnosticKind::UnsupportedConstant,
                            );
                            vec![]
                        }
                    }
                },
                expr.ty,
            )
            .intern(db),
            Expr::Snapshot(expr) => self.evaluate(expr.inner),
            Expr::Desnap(expr) => self.evaluate(expr.inner),
            Expr::LogicalOperator(expr) => {
                let lhs = self.evaluate(expr.lhs);
                if let ConstValue::Enum(v, _) = lhs.long(db) {
                    let early_return_variant = match expr.op {
                        LogicalOperator::AndAnd => false_variant(self.db),
                        LogicalOperator::OrOr => true_variant(self.db),
                    };
                    if *v == early_return_variant { lhs } else { self.evaluate(expr.rhs) }
                } else {
                    to_missing(skip_diagnostic())
                }
            }
            Expr::Match(expr) => {
                let value = self.evaluate(expr.matched_expr);
                let ConstValue::Enum(variant, value) = value.long(db) else {
                    return to_missing(skip_diagnostic());
                };
                for arm in &expr.arms {
                    for pattern_id in &arm.patterns {
                        let pattern = &self.arenas.patterns[*pattern_id];
                        if matches!(pattern, Pattern::Otherwise(_)) {
                            return self.evaluate(arm.expression);
                        }
                        let Pattern::EnumVariant(pattern) = pattern else {
                            continue;
                        };
                        if pattern.variant.idx != variant.idx {
                            continue;
                        }
                        if let Some(inner_pattern) = pattern.inner_pattern {
                            self.destructure_pattern(inner_pattern, *value);
                        }
                        return self.evaluate(arm.expression);
                    }
                }
                to_missing(
                    self.diagnostics.report(
                        expr.stable_ptr.untyped(),
                        SemanticDiagnosticKind::UnsupportedConstant,
                    ),
                )
            }
            Expr::If(expr) => {
                let mut if_condition: bool = true;
                for condition in &expr.conditions {
                    match condition {
                        crate::Condition::BoolExpr(id) => {
                            let condition = self.evaluate(*id);
                            let ConstValue::Enum(variant, _) = condition.long(db) else {
                                return to_missing(skip_diagnostic());
                            };
                            if *variant != true_variant(self.db) {
                                if_condition = false;
                                break;
                            }
                        }
                        crate::Condition::Let(id, patterns) => {
                            let value = self.evaluate(*id);
                            let ConstValue::Enum(variant, value) = value.long(db) else {
                                return to_missing(skip_diagnostic());
                            };
                            let mut found_pattern = false;
                            for pattern_id in patterns {
                                let Pattern::EnumVariant(pattern) =
                                    &self.arenas.patterns[*pattern_id]
                                else {
                                    continue;
                                };
                                if pattern.variant != *variant {
                                    // Continue to the next option in the `|` list.
                                    continue;
                                }
                                if let Some(inner_pattern) = pattern.inner_pattern {
                                    self.destructure_pattern(inner_pattern, *value);
                                }
                                found_pattern = true;
                                break;
                            }
                            if !found_pattern {
                                if_condition = false;
                                break;
                            }
                        }
                    }
                }

                if if_condition {
                    self.evaluate(expr.if_block)
                } else if let Some(else_block) = expr.else_block {
                    self.evaluate(else_block)
                } else {
                    self.unit_const
                }
            }
            _ => to_missing(skip_diagnostic()),
        }
    }

    /// Attempts to evaluate constants from a const function call.
    fn evaluate_function_call(&mut self, expr: &ExprFunctionCall<'a>) -> ConstValueId<'a> {
        let db = self.db;
        let to_missing = |diag_added| ConstValue::Missing(diag_added).intern(db);
        let args = expr
            .args
            .iter()
            .filter_map(|arg| try_extract_matches!(arg, ExprFunctionCallArg::Value))
            .map(|arg| self.evaluate(*arg))
            .collect_vec();
        if expr.function == self.panic_with_felt252 {
            return to_missing(self.diagnostics.report(
                expr.stable_ptr.untyped(),
                SemanticDiagnosticKind::FailedConstantCalculation,
            ));
        }
        let concrete_function =
            match self.generic_substitution.substitute(db, expr.function.get_concrete(db)) {
                Ok(v) => v,
                Err(err) => return to_missing(err),
            };
        if let Some(calc_result) =
            self.evaluate_const_function_call(&concrete_function, &args, expr)
        {
            return calc_result;
        }

        let imp = extract_matches!(concrete_function.generic_function, GenericFunctionId::Impl);
        let bool_value = |condition: bool| {
            if condition { self.true_const } else { self.false_const }
        };

        if imp.function == self.eq_fn {
            return bool_value(args[0] == args[1]);
        } else if imp.function == self.ne_fn {
            return bool_value(args[0] != args[1]);
        } else if imp.function == self.not_fn {
            return bool_value(args[0] == self.false_const);
        }

        let mut all_args_concrete = true;
        let args = match args
            .into_iter()
            .map(|arg| {
                // Track if any argument is not fully concrete (e.g., ImplConstant with a generic
                // impl parameter) so we can report a diagnostic if NumericArg conversion fails.
                if !arg.is_fully_concrete(db) && !matches!(arg.long(db), ConstValue::Missing(_)) {
                    all_args_concrete = false;
                }
                NumericArg::try_new(db, arg)
            })
            .collect::<Option<Vec<_>>>()
        {
            Some(args) => args,
            None => {
                return to_missing(if all_args_concrete {
                    // Diagnostic can be skipped as there would be a semantic error for a bad arg,
                    // or the arg itself is Missing.
                    skip_diagnostic()
                } else {
                    self.diagnostics.report(
                        expr.stable_ptr.untyped(),
                        SemanticDiagnosticKind::UnsupportedConstant,
                    )
                });
            }
        };
        let value = match imp.function {
            id if id == self.neg_fn => -&args[0].v,
            id if id == self.add_fn => &args[0].v + &args[1].v,
            id if id == self.sub_fn => &args[0].v - &args[1].v,
            id if id == self.mul_fn => &args[0].v * &args[1].v,
            id if (id == self.div_fn || id == self.rem_fn) && args[1].v.is_zero() => {
                return to_missing(
                    self.diagnostics
                        .report(expr.stable_ptr.untyped(), SemanticDiagnosticKind::DivisionByZero),
                );
            }
            id if id == self.div_fn => &args[0].v / &args[1].v,
            id if id == self.rem_fn => &args[0].v % &args[1].v,
            id if id == self.bitand_fn => &args[0].v & &args[1].v,
            id if id == self.bitor_fn => &args[0].v | &args[1].v,
            id if id == self.bitxor_fn => &args[0].v ^ &args[1].v,
            id if id == self.lt_fn => return bool_value(args[0].v < args[1].v),
            id if id == self.le_fn => return bool_value(args[0].v <= args[1].v),
            id if id == self.gt_fn => return bool_value(args[0].v > args[1].v),
            id if id == self.ge_fn => return bool_value(args[0].v >= args[1].v),
            id if id == self.div_rem_fn => {
                // No need for non-zero check as this is type checked to begin with.
                // Also results are always in the range of the input type, so `unwrap`s are ok.
                return ConstValue::Struct(
                    vec![
                        ConstValueId::from_int(db, args[0].ty, &(&args[0].v / &args[1].v)),
                        ConstValueId::from_int(db, args[0].ty, &(&args[0].v % &args[1].v)),
                    ],
                    expr.ty,
                )
                .intern(db);
            }
            _ => {
                unreachable!("Unexpected function call in constant lowering: {:?}", expr)
            }
        };
        if expr.ty == self.felt252 {
            ConstValue::Int(canonical_felt252(&value), expr.ty).intern(db)
        } else if let Err(err) = validate_literal(db, expr.ty, &value) {
            to_missing(
                self.diagnostics
                    .report(expr.stable_ptr.untyped(), SemanticDiagnosticKind::LiteralError(err)),
            )
        } else {
            ConstValueId::from_int(db, expr.ty, &value)
        }
    }

    /// Attempts to evaluate a constant function call.
    fn evaluate_const_function_call(
        &mut self,
        concrete_function: &ConcreteFunction<'a>,
        args: &[ConstValueId<'a>],
        expr: &ExprFunctionCall<'a>,
    ) -> Option<ConstValueId<'a>> {
        let db = self.db;
        if let GenericFunctionId::Extern(extern_fn) = concrete_function.generic_function {
            let expr_ty = self.generic_substitution.substitute(db, expr.ty).ok()?;
            if self.upcast_fns.contains(&extern_fn) {
                let [arg] = args else { return None };
                return Some(ConstValueId::from_int(db, expr_ty, arg.long(db).to_int()?));
            } else if self.unwrap_non_zero == extern_fn {
                let [arg] = args else { return None };
                return try_extract_matches!(arg.long(db), ConstValue::NonZero).copied();
            } else if self.u128s_from_felt252 == extern_fn {
                let [arg] = args else { return None };
                let TypeLongId::Concrete(ConcreteTypeId::Enum(enm)) = expr_ty.long(db) else {
                    return None;
                };
                let (narrow, wide) =
                    db.concrete_enum_variants(*enm).ok()?.into_iter().collect_tuple()?;
                let value = felt252_for_downcast(arg.long(db).to_int()?, &BigInt::ZERO);
                let mask128 = BigInt::from(u128::MAX);
                let low = (&value) & mask128;
                let high: BigInt = (&value) >> 128;
                return Some(if high.is_zero() {
                    ConstValue::Enum(narrow, ConstValue::Int(low, narrow.ty).intern(db)).intern(db)
                } else {
                    ConstValue::Enum(
                        wide,
                        ConstValue::Struct(
                            vec![
                                (ConstValue::Int(high, self.u128).intern(db)),
                                (ConstValue::Int(low, self.u128).intern(db)),
                            ],
                            wide.ty,
                        )
                        .intern(db),
                    )
                    .intern(db)
                });
            } else if let Some(reversed) = self.downcast_fns.get(&extern_fn) {
                let [arg] = args else { return None };
                let ConstValue::Int(value, input_ty) = arg.long(db) else { return None };
                let TypeLongId::Concrete(ConcreteTypeId::Enum(enm)) = expr_ty.long(db) else {
                    return None;
                };
                let (variant0, variant1) =
                    db.concrete_enum_variants(*enm).ok()?.into_iter().collect_tuple()?;
                let (some, none) =
                    if *reversed { (variant1, variant0) } else { (variant0, variant1) };
                let success_ty = some.ty;
                let out_range = self
                    .type_value_ranges
                    .get(&success_ty)
                    .cloned()
                    .or_else(|| {
                        let (min, max) = try_extract_bounded_int_type_ranges(db, success_ty)?;
                        Some(TypeRange::new(min, max))
                    })
                    .unwrap_or_else(|| {
                        unreachable!(
                            "`downcast` is only allowed into types that can be literals. Got `{}`.",
                            success_ty.format(db)
                        )
                    });
                let value = if *input_ty == self.felt252 {
                    felt252_for_downcast(value, &out_range.min)
                } else {
                    value.clone()
                };
                return Some(if value >= out_range.min && value <= out_range.max {
                    ConstValue::Enum(some, ConstValue::Int(value, success_ty).intern(db)).intern(db)
                } else {
                    ConstValue::Enum(none, self.unit_const).intern(db)
                });
            } else if self.nz_fns.contains(&extern_fn) {
                let [arg] = args else { return None };
                let (ty, is_zero) = match arg.long(db) {
                    ConstValue::Int(val, ty) => (ty, val.is_zero()),
                    ConstValue::Struct(members, ty) => (
                        ty,
                        // For u256 struct with (low, high), check if both are zero
                        members.iter().all(|member| match member.long(db) {
                            ConstValue::Int(val, _) => val.is_zero(),
                            _ => false,
                        }),
                    ),
                    _ => unreachable!(
                        "`is_zero` is only allowed for integers got `{}`",
                        arg.ty(db).unwrap().format(db)
                    ),
                };

                return Some(
                    if is_zero {
                        ConstValue::Enum(
                            crate::corelib::jump_nz_zero_variant(db, *ty),
                            self.unit_const,
                        )
                    } else {
                        ConstValue::Enum(
                            crate::corelib::jump_nz_nonzero_variant(db, *ty),
                            ConstValue::NonZero(*arg).intern(db),
                        )
                    }
                    .intern(db),
                );
            } else {
                return Some(
                    ConstValue::Missing(self.diagnostics.report(
                        expr.stable_ptr.untyped(),
                        SemanticDiagnosticKind::UnsupportedConstant,
                    ))
                    .intern(db),
                );
            }
        }
        let body_id = concrete_function.body(db).ok()??;
        let concrete_body_id = body_id.function_with_body_id(db);
        let signature = db.function_with_body_signature(concrete_body_id).ok()?;
        require(signature.is_const)?;
        let generic_substitution = body_id.substitution(db).ok()?;
        let body = db.function_body(concrete_body_id).ok()?;
        const MAX_CONST_EVAL_DEPTH: usize = 100;
        if self.depth > MAX_CONST_EVAL_DEPTH {
            return Some(
                ConstValue::Missing(self.diagnostics.report(
                    expr.stable_ptr,
                    SemanticDiagnosticKind::ConstantCalculationDepthExceeded,
                ))
                .intern(db),
            );
        }
        let mut diagnostics = SemanticDiagnostics::new(concrete_body_id.parent_module(db));
        let mut inner = ConstantEvaluateContext {
            db,
            info: self.info,
            arenas: &body.arenas,
            vars: signature
                .params
                .iter()
                .map(|p| VarId::Param(p.id))
                .zip(args.iter().cloned())
                .collect(),
            generic_substitution,
            depth: self.depth + 1,
            diagnostics: &mut diagnostics,
        };
        let value = inner.evaluate(body.body_expr);
        for diagnostic in diagnostics.build().get_all() {
            let location = diagnostic.location(db);
            let (inner_diag, mut notes) = match diagnostic.kind {
                SemanticDiagnosticKind::ConstantCalculationDepthExceeded => {
                    self.diagnostics.report(
                        expr.stable_ptr,
                        SemanticDiagnosticKind::ConstantCalculationDepthExceeded,
                    );
                    continue;
                }
                SemanticDiagnosticKind::InnerFailedConstantCalculation(inner_diag, notes) => {
                    (inner_diag, notes)
                }
                _ => (diagnostic.into(), vec![]),
            };
            notes.push(DiagnosticNote::with_location(
                format!("In `{}`", concrete_function.full_path(db)),
                location,
            ));
            self.diagnostics.report(
                expr.stable_ptr,
                SemanticDiagnosticKind::InnerFailedConstantCalculation(inner_diag, notes),
            );
        }
        Some(value)
    }

    /// Extract const member access from a const value.
    fn evaluate_member_access(&mut self, expr: &ExprMemberAccess<'a>) -> Maybe<ConstValueId<'a>> {
        let full_struct = self.evaluate(expr.expr);
        let ConstValue::Struct(values, _) = full_struct.long(self.db) else {
            // A semantic diagnostic should have been reported.
            return Err(skip_diagnostic());
        };
        let members = self.db.concrete_struct_members(expr.concrete_struct_id)?;
        let Some(member_idx) = members.iter().position(|(_, member)| member.id == expr.member)
        else {
            // A semantic diagnostic should have been reported.
            return Err(skip_diagnostic());
        };
        Ok(values[member_idx])
    }

    /// Destructures the pattern into the const value of the variables in scope.
    fn destructure_pattern(&mut self, pattern_id: PatternId, value: ConstValueId<'a>) {
        let pattern = &self.arenas.patterns[pattern_id];
        let db = self.db;
        match pattern {
            Pattern::Literal(_)
            | Pattern::StringLiteral(_)
            | Pattern::Otherwise(_)
            | Pattern::Missing(_) => {}
            Pattern::Variable(pattern) => {
                self.vars.insert(VarId::Local(pattern.var.id), value);
            }
            Pattern::Struct(pattern) => {
                if let ConstValue::Struct(inner_values, _) = value.long(db) {
                    let member_order = match db.concrete_struct_members(pattern.concrete_struct_id)
                    {
                        Ok(member_order) => member_order,
                        Err(_) => return,
                    };
                    for (member, inner_value) in zip(member_order.values(), inner_values) {
                        if let Some((inner_pattern, _)) =
                            pattern.field_patterns.iter().find(|(_, field)| member.id == field.id)
                        {
                            self.destructure_pattern(*inner_pattern, *inner_value);
                        }
                    }
                }
            }
            Pattern::Tuple(pattern) => {
                if let ConstValue::Struct(inner_values, _) = value.long(db) {
                    for (inner_pattern, inner_value) in zip(&pattern.field_patterns, inner_values) {
                        self.destructure_pattern(*inner_pattern, *inner_value);
                    }
                }
            }
            Pattern::FixedSizeArray(pattern) => {
                if let ConstValue::Struct(inner_values, _) = value.long(db) {
                    for (inner_pattern, inner_value) in
                        zip(&pattern.elements_patterns, inner_values)
                    {
                        self.destructure_pattern(*inner_pattern, *inner_value);
                    }
                }
            }
            Pattern::EnumVariant(pattern) => {
                if let ConstValue::Enum(variant, inner_value) = value.long(db)
                    && pattern.variant == *variant
                    && let Some(inner_pattern) = pattern.inner_pattern
                {
                    self.destructure_pattern(inner_pattern, *inner_value);
                }
            }
        }
    }
}

impl<'db, 'r> std::ops::Deref for ConstantEvaluateContext<'db, 'r, '_> {
    type Target = ConstCalcInfo<'db>;
    fn deref(&self) -> &Self::Target {
        self.info
    }
}

/// Helper for the arguments info.
struct NumericArg<'db> {
    /// The arg's integer value.
    v: BigInt,
    /// The arg's type.
    ty: TypeId<'db>,
}
impl<'db> NumericArg<'db> {
    fn try_new(db: &'db dyn Database, arg: ConstValueId<'db>) -> Option<Self> {
        Some(Self { ty: arg.ty(db).ok()?, v: numeric_arg_value(db, arg)? })
    }
}

/// Helper for creating a `NumericArg` value.
/// This includes unwrapping of `NonZero` values and struct of 2 values as a `u256`.
fn numeric_arg_value<'db>(db: &'db dyn Database, value: ConstValueId<'db>) -> Option<BigInt> {
    match value.long(db) {
        ConstValue::Int(value, _) => Some(value.clone()),
        ConstValue::Struct(v, _) => {
            if let [low, high] = &v[..] {
                Some(low.long(db).to_int()? + (high.long(db).to_int()? << 128))
            } else {
                None
            }
        }
        ConstValue::NonZero(const_value) => numeric_arg_value(db, *const_value),
        _ => None,
    }
}

/// Query implementation of [ConstantSemantic::const_calc_info].
fn const_calc_info<'db>(db: &'db dyn Database) -> Arc<ConstCalcInfo<'db>> {
    Arc::new(ConstCalcInfo::new(db))
}

/// Implementation of [ConstantSemantic::const_calc_info].
#[salsa::tracked]
fn const_calc_info_tracked<'db>(db: &'db dyn Database) -> Arc<ConstCalcInfo<'db>> {
    const_calc_info(db)
}

/// Holds static information about extern functions required for const calculations.
#[derive(Debug, PartialEq, Eq, salsa::Update)]
pub struct ConstCalcInfo<'db> {
    /// Traits that are allowed for consts if their impls is in the corelib.
    const_traits: UnorderedHashSet<TraitId<'db>>,
    /// The const value for the unit type `()`.
    unit_const: ConstValueId<'db>,
    /// The const value for `true`.
    true_const: ConstValueId<'db>,
    /// The const value for `false`.
    false_const: ConstValueId<'db>,
    /// The function for panicking with a felt252.
    panic_with_felt252: FunctionId<'db>,
    /// The integer `upcast` style functions.
    pub upcast_fns: UnorderedHashSet<ExternFunctionId<'db>>,
    /// The integer `downcast` style functions, mapping to whether it returns a reversed Option
    /// enum.
    pub downcast_fns: UnorderedHashMap<ExternFunctionId<'db>, bool>,
    /// The `felt252` into `u128` words libfunc.
    pub u128s_from_felt252: ExternFunctionId<'db>,
    /// The `unwrap_non_zero` function.
    unwrap_non_zero: ExternFunctionId<'db>,
    /// The `is_zero` style functions.
    pub nz_fns: UnorderedHashSet<ExternFunctionId<'db>>,
    /// The range of values of a numeric type.
    pub type_value_ranges: UnorderedHashMap<TypeId<'db>, TypeRange>,

    core_info: Arc<CoreInfo<'db>>,
}

impl<'db> std::ops::Deref for ConstCalcInfo<'db> {
    type Target = CoreInfo<'db>;
    fn deref(&self) -> &CoreInfo<'db> {
        &self.core_info
    }
}

impl<'db> ConstCalcInfo<'db> {
    /// Creates a new ConstCalcInfo.
    fn new(db: &'db dyn Database) -> Self {
        let core_info = db.core_info();
        let unit_const = ConstValue::Struct(vec![], unit_ty(db)).intern(db);
        let core = ModuleHelper::core(db);
        let bounded_int = core.submodule("internal").submodule("bounded_int");
        let integer = core.submodule("integer");
        let zeroable = core.submodule("zeroable");
        let starknet = core.submodule("starknet");
        let class_hash_module = starknet.submodule("class_hash");
        let class_hash_ty = class_hash_module.ty("ClassHash", vec![]);
        let contract_address_module = starknet.submodule("contract_address");
        let contract_address_ty = contract_address_module.ty("ContractAddress", vec![]);
        Self {
            const_traits: FromIterator::from_iter([
                core_info.neg_trt,
                core_info.add_trt,
                core_info.sub_trt,
                core_info.mul_trt,
                core_info.div_trt,
                core_info.rem_trt,
                core_info.div_rem_trt,
                core_info.bitand_trt,
                core_info.bitor_trt,
                core_info.bitxor_trt,
                core_info.partialeq_trt,
                core_info.partialord_trt,
                core_info.not_trt,
            ]),
            true_const: ConstValue::Enum(true_variant(db), unit_const).intern(db),
            false_const: ConstValue::Enum(false_variant(db), unit_const).intern(db),
            unit_const,
            panic_with_felt252: core.function_id("panic_with_felt252", vec![]),
            upcast_fns: FromIterator::from_iter([
                bounded_int.extern_function_id("upcast"),
                integer.extern_function_id("u8_to_felt252"),
                integer.extern_function_id("u16_to_felt252"),
                integer.extern_function_id("u32_to_felt252"),
                integer.extern_function_id("u64_to_felt252"),
                integer.extern_function_id("u128_to_felt252"),
                integer.extern_function_id("i8_to_felt252"),
                integer.extern_function_id("i16_to_felt252"),
                integer.extern_function_id("i32_to_felt252"),
                integer.extern_function_id("i64_to_felt252"),
                integer.extern_function_id("i128_to_felt252"),
                class_hash_module.extern_function_id("class_hash_to_felt252"),
                contract_address_module.extern_function_id("contract_address_to_felt252"),
            ]),
            downcast_fns: FromIterator::from_iter([
                (bounded_int.extern_function_id("downcast"), false),
                (bounded_int.extern_function_id("bounded_int_trim_min"), true),
                (bounded_int.extern_function_id("bounded_int_trim_max"), true),
                (integer.extern_function_id("u8_try_from_felt252"), false),
                (integer.extern_function_id("u16_try_from_felt252"), false),
                (integer.extern_function_id("u32_try_from_felt252"), false),
                (integer.extern_function_id("u64_try_from_felt252"), false),
                (integer.extern_function_id("i8_try_from_felt252"), false),
                (integer.extern_function_id("i16_try_from_felt252"), false),
                (integer.extern_function_id("i32_try_from_felt252"), false),
                (integer.extern_function_id("i64_try_from_felt252"), false),
                (integer.extern_function_id("i128_try_from_felt252"), false),
                (class_hash_module.extern_function_id("class_hash_try_from_felt252"), false),
                (
                    contract_address_module.extern_function_id("contract_address_try_from_felt252"),
                    false,
                ),
            ]),
            u128s_from_felt252: integer.extern_function_id("u128s_from_felt252"),
            unwrap_non_zero: zeroable.extern_function_id("unwrap_non_zero"),
            nz_fns: FromIterator::from_iter([
                core.extern_function_id("felt252_is_zero"),
                bounded_int.extern_function_id("bounded_int_is_zero"),
                integer.extern_function_id("u8_is_zero"),
                integer.extern_function_id("u16_is_zero"),
                integer.extern_function_id("u32_is_zero"),
                integer.extern_function_id("u64_is_zero"),
                integer.extern_function_id("u128_is_zero"),
                integer.extern_function_id("u256_is_zero"),
            ]),
            type_value_ranges: FromIterator::from_iter([
                (core_info.u8, TypeRange::new(u8::MIN, u8::MAX)),
                (core_info.u16, TypeRange::new(u16::MIN, u16::MAX)),
                (core_info.u32, TypeRange::new(u32::MIN, u32::MAX)),
                (core_info.u64, TypeRange::new(u64::MIN, u64::MAX)),
                (core_info.u128, TypeRange::new(u128::MIN, u128::MAX)),
                (core_info.u256, TypeRange::new(BigInt::ZERO, BigInt::from(1) << 256)),
                (core_info.i8, TypeRange::new(i8::MIN, i8::MAX)),
                (core_info.i16, TypeRange::new(i16::MIN, i16::MAX)),
                (core_info.i32, TypeRange::new(i32::MIN, i32::MAX)),
                (core_info.i64, TypeRange::new(i64::MIN, i64::MAX)),
                (core_info.i128, TypeRange::new(i128::MIN, i128::MAX)),
                (class_hash_ty, TypeRange::new(BigInt::ZERO, BigInt::from(1) << 251)),
                (contract_address_ty, TypeRange::new(BigInt::ZERO, BigInt::from(1) << 251)),
            ]),
            core_info,
        }
    }
}

/// Trait for constant-related semantic queries.
pub trait ConstantSemantic<'db>: Database {
    /// Returns the semantic diagnostics of a constant definition.
    fn constant_semantic_diagnostics(
        &'db self,
        const_id: ConstantId<'db>,
    ) -> Diagnostics<'db, SemanticDiagnostic<'db>> {
        let db = self.as_dyn_database();
        constant_semantic_data(db, const_id, false)
            .as_ref()
            .map(|data| data.diagnostics.clone())
            .unwrap_or_default()
    }
    /// Returns the semantic data of a constant definition.
    fn constant_semantic_data(&'db self, use_id: ConstantId<'db>) -> Maybe<Constant<'db>> {
        let db = self.as_dyn_database();
        constant_semantic_data(db, use_id, false).maybe_as_ref()?.constant.clone()
    }
    /// Returns the resolver data of a constant definition.
    fn constant_resolver_data(&'db self, use_id: ConstantId<'db>) -> Maybe<Arc<ResolverData<'db>>> {
        let db = self.as_dyn_database();
        Ok(constant_semantic_data(db, use_id, false).maybe_as_ref()?.resolver_data.clone())
    }
    /// Returns the const value of a constant definition.
    fn constant_const_value(&'db self, const_id: ConstantId<'db>) -> Maybe<ConstValueId<'db>> {
        let db = self.as_dyn_database();
        Ok(constant_semantic_data(db, const_id, false).maybe_as_ref()?.const_value)
    }
    /// Returns information required for const calculations.
    fn const_calc_info(&'db self) -> Arc<ConstCalcInfo<'db>> {
        const_calc_info_tracked(self.as_dyn_database())
    }
}
impl<'db, T: Database + ?Sized> ConstantSemantic<'db> for T {}

/// A range of values of a numeric type.
#[derive(Clone, Debug, PartialEq, Eq, salsa::Update)]
pub struct TypeRange {
    /// The minimum value of the range.
    pub min: BigInt,
    /// The maximum value of the range.
    pub max: BigInt,
}
impl TypeRange {
    pub fn new(min: impl Into<BigInt>, max: impl Into<BigInt>) -> Self {
        Self { min: min.into(), max: max.into() }
    }
}