cairo_lang_semantic/resolve/
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
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
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
use std::iter::Peekable;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};

use cairo_lang_defs::ids::{
    GenericKind, GenericParamId, GenericTypeId, ImplDefId, LanguageElementId, LookupItemId,
    ModuleFileId, ModuleId, TraitId, TraitItemId,
};
use cairo_lang_diagnostics::Maybe;
use cairo_lang_filesystem::db::{CORELIB_CRATE_NAME, CrateSettings};
use cairo_lang_filesystem::ids::{CrateId, CrateLongId};
use cairo_lang_proc_macros::DebugWithDb;
use cairo_lang_syntax as syntax;
use cairo_lang_syntax::node::helpers::PathSegmentEx;
use cairo_lang_syntax::node::ids::SyntaxStablePtrId;
use cairo_lang_syntax::node::{Terminal, TypedSyntaxNode, ast};
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::{Intern, LookupIntern, extract_matches, require, try_extract_matches};
pub use item::{ResolvedConcreteItem, ResolvedGenericItem};
use itertools::Itertools;
use smol_str::SmolStr;
use syntax::node::TypedStablePtr;
use syntax::node::db::SyntaxGroup;
use syntax::node::helpers::QueryAttrs;

use crate::corelib::{core_submodule, get_submodule};
use crate::db::SemanticGroup;
use crate::diagnostic::SemanticDiagnosticKind::{self, *};
use crate::diagnostic::{NotFoundItemType, SemanticDiagnostics, SemanticDiagnosticsBuilder};
use crate::expr::compute::{
    ComputationContext, ContextFunction, Environment, compute_expr_semantic,
    get_statement_item_by_name,
};
use crate::expr::inference::canonic::ResultNoErrEx;
use crate::expr::inference::conform::InferenceConform;
use crate::expr::inference::infers::InferenceEmbeddings;
use crate::expr::inference::{Inference, InferenceData, InferenceId};
use crate::items::constant::{ConstValue, ImplConstantId, resolve_const_expr_and_evaluate};
use crate::items::enm::SemanticEnumEx;
use crate::items::feature_kind::{FeatureConfig, FeatureKind, extract_feature_config};
use crate::items::functions::{GenericFunctionId, ImplGenericFunctionId};
use crate::items::generics::generic_params_to_args;
use crate::items::imp::{
    ConcreteImplId, ConcreteImplLongId, ImplImplId, ImplLongId, ImplLookupContext,
};
use crate::items::module::ModuleItemInfo;
use crate::items::trt::{
    ConcreteTraitConstantLongId, ConcreteTraitGenericFunctionLongId, ConcreteTraitId,
    ConcreteTraitImplLongId, ConcreteTraitLongId, ConcreteTraitTypeId,
};
use crate::items::{TraitOrImplContext, visibility};
use crate::substitution::{GenericSubstitution, SemanticRewriter, SubstitutionRewriter};
use crate::types::{ImplTypeId, are_coupons_enabled, resolve_type};
use crate::{
    ConcreteFunction, ConcreteTypeId, ExprId, FunctionId, FunctionLongId, GenericArgumentId,
    GenericParam, Member, Mutability, TypeId, TypeLongId,
};

#[cfg(test)]
mod test;

mod item;

// Remove when these are added as actual keywords.
pub const SELF_TYPE_KW: &str = "Self";
pub const SUPER_KW: &str = "super";
pub const CRATE_KW: &str = "crate";

/// Lookback maps for item resolving. Can be used to quickly check what is the semantic resolution
/// of any path segment.
#[derive(Clone, Default, Debug, PartialEq, Eq, DebugWithDb)]
#[debug_db(dyn SemanticGroup + 'static)]
pub struct ResolvedItems {
    pub concrete: UnorderedHashMap<ast::TerminalIdentifierPtr, ResolvedConcreteItem>,
    pub generic: UnorderedHashMap<ast::TerminalIdentifierPtr, ResolvedGenericItem>,
}
impl ResolvedItems {
    // Relates a path segment to a ResolvedConcreteItem, and adds to a resolved_items map. This will
    // be used in "Go to definition".
    pub fn mark_concrete(
        &mut self,
        db: &dyn SemanticGroup,
        segment: &syntax::node::ast::PathSegment,
        resolved_item: ResolvedConcreteItem,
    ) -> ResolvedConcreteItem {
        let identifier = segment.identifier_ast(db.upcast());
        if let Some(generic_item) = resolved_item.generic(db) {
            // Mark the generic item as well, for language server resolved_items.
            self.generic.insert(identifier.stable_ptr(), generic_item);
        }
        self.concrete.insert(identifier.stable_ptr(), resolved_item.clone());
        resolved_item
    }
    // Relates a path segment to a ResolvedGenericItem, and adds to a resolved_items map. This will
    // be used in "Go to definition".
    pub fn mark_generic(
        &mut self,
        db: &dyn SemanticGroup,
        segment: &syntax::node::ast::PathSegment,
        resolved_item: ResolvedGenericItem,
    ) -> ResolvedGenericItem {
        let identifier = segment.identifier_ast(db.upcast());
        self.generic.insert(identifier.stable_ptr(), resolved_item.clone());
        resolved_item
    }
}

/// The enriched members of a type, including direct members of structs, as well as members of
/// targets of `Deref` and `DerefMut` of the type.
#[derive(Debug, PartialEq, Eq, DebugWithDb, Clone)]
#[debug_db(dyn SemanticGroup + 'static)]
pub struct EnrichedMembers {
    /// A map from member names to their semantic representation and the number of deref operations
    /// needed to access them.
    pub members: OrderedHashMap<SmolStr, (Member, usize)>,
    /// The sequence of deref functions needed to access the members.
    pub deref_functions: Vec<(FunctionId, Mutability)>,
    /// The tail of deref chain explored so far. The search for additional members will continue
    /// from this point.
    /// Useful for partial computation of enriching members where a member was already previously
    /// found.
    pub exploration_tail: Option<ExprId>,
}
impl EnrichedMembers {
    /// Returns `EnrichedTypeMemberAccess` for a single member if exists.
    pub fn get_member(&self, name: &str) -> Option<EnrichedTypeMemberAccess> {
        let (member, n_derefs) = self.members.get(name)?;
        Some(EnrichedTypeMemberAccess {
            member: member.clone(),
            deref_functions: self.deref_functions[..*n_derefs].to_vec(),
        })
    }
}

/// The enriched member of a type, including the member itself and the deref functions needed to
/// access it.
pub struct EnrichedTypeMemberAccess {
    /// The member itself.
    pub member: Member,
    /// The sequence of deref functions needed to access the member.
    pub deref_functions: Vec<(FunctionId, Mutability)>,
}

#[derive(Debug, PartialEq, Eq, DebugWithDb)]
#[debug_db(dyn SemanticGroup + 'static)]
pub struct ResolverData {
    /// Current module in which to resolve the path.
    pub module_file_id: ModuleFileId,
    /// Named generic parameters accessible to the resolver.
    generic_param_by_name: OrderedHashMap<SmolStr, GenericParamId>,
    /// All generic parameters accessible to the resolver.
    pub generic_params: Vec<GenericParamId>,
    /// The enriched members per type and its mutability in the resolver context.
    pub type_enriched_members: OrderedHashMap<(TypeId, bool), EnrichedMembers>,
    /// Lookback map for resolved identifiers in path. Used in "Go to definition".
    pub resolved_items: ResolvedItems,
    /// Inference data for the resolver.
    pub inference_data: InferenceData,
    /// The trait/impl context the resolver is currently in. Used to resolve "Self::" paths.
    pub trait_or_impl_ctx: TraitOrImplContext,
    /// The configuration of allowed features.
    pub feature_config: FeatureConfig,
    /// The set of used items in the current context.
    pub used_items: OrderedHashSet<LookupItemId>,
}
impl ResolverData {
    pub fn new(module_file_id: ModuleFileId, inference_id: InferenceId) -> Self {
        Self {
            module_file_id,
            generic_param_by_name: Default::default(),
            generic_params: Default::default(),
            type_enriched_members: Default::default(),
            resolved_items: Default::default(),
            inference_data: InferenceData::new(inference_id),
            trait_or_impl_ctx: TraitOrImplContext::None,
            feature_config: Default::default(),
            used_items: Default::default(),
        }
    }
    pub fn clone_with_inference_id(
        &self,
        db: &dyn SemanticGroup,
        inference_id: InferenceId,
    ) -> Self {
        Self {
            module_file_id: self.module_file_id,
            generic_param_by_name: self.generic_param_by_name.clone(),
            generic_params: self.generic_params.clone(),
            type_enriched_members: self.type_enriched_members.clone(),
            resolved_items: self.resolved_items.clone(),
            inference_data: self.inference_data.clone_with_inference_id(db, inference_id),
            trait_or_impl_ctx: self.trait_or_impl_ctx,
            feature_config: self.feature_config.clone(),
            used_items: self.used_items.clone(),
        }
    }
}

/// Resolves paths semantically.
pub struct Resolver<'db> {
    db: &'db dyn SemanticGroup,
    pub data: ResolverData,
    pub owning_crate_id: CrateId,
    pub settings: CrateSettings,
}
impl Deref for Resolver<'_> {
    type Target = ResolverData;

    fn deref(&self) -> &Self::Target {
        &self.data
    }
}
impl DerefMut for Resolver<'_> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.data
    }
}
impl Resolver<'_> {
    /// Extracts the allowed node from the syntax, and sets it as the allowed features of the
    /// resolver.
    pub fn set_feature_config(
        &mut self,
        element_id: &impl LanguageElementId,
        syntax: &impl QueryAttrs,
        diagnostics: &mut SemanticDiagnostics,
    ) {
        self.feature_config =
            extract_feature_config(self.db.upcast(), element_id, syntax, diagnostics);
    }
}

/// A trait for things that can be interpreted as a path of segments.
pub trait AsSegments {
    fn to_segments(self, db: &dyn SyntaxGroup) -> Vec<ast::PathSegment>;
}
impl AsSegments for &ast::ExprPath {
    fn to_segments(self, db: &dyn SyntaxGroup) -> Vec<ast::PathSegment> {
        self.elements(db)
    }
}
impl AsSegments for Vec<ast::PathSegment> {
    fn to_segments(self, _: &dyn SyntaxGroup) -> Vec<ast::PathSegment> {
        self
    }
}

impl<'db> Resolver<'db> {
    pub fn new(
        db: &'db dyn SemanticGroup,
        module_file_id: ModuleFileId,
        inference_id: InferenceId,
    ) -> Self {
        Self::with_data(db, ResolverData::new(module_file_id, inference_id))
    }

    pub fn with_data(db: &'db dyn SemanticGroup, data: ResolverData) -> Self {
        let owning_crate_id = data.module_file_id.0.owning_crate(db.upcast());
        let settings = db.crate_config(owning_crate_id).map(|c| c.settings).unwrap_or_default();
        Self { owning_crate_id, settings, db, data }
    }

    pub fn inference(&mut self) -> Inference<'_> {
        self.data.inference_data.inference(self.db)
    }

    /// Adds a generic param to an existing resolver.
    /// This is required since a resolver needs to exist before resolving the generic params,
    /// and thus, they are added to the Resolver only after they are resolved.
    pub fn add_generic_param(&mut self, generic_param_id: GenericParamId) {
        self.generic_params.push(generic_param_id);
        let db = self.db.upcast();
        if let Some(name) = generic_param_id.name(db) {
            self.generic_param_by_name.insert(name, generic_param_id);
        }
    }

    /// Resolves an item, given a path.
    /// Guaranteed to result in at most one diagnostic.
    fn resolve_path_inner<ResolvedItem: Clone>(
        &mut self,
        diagnostics: &mut SemanticDiagnostics,
        path: impl AsSegments,
        item_type: NotFoundItemType,
        statement_env: Option<&mut Environment>,
        mut callbacks: ResolvePathInnerCallbacks<
            ResolvedItem,
            impl FnMut(
                &mut Resolver<'_>,
                &mut SemanticDiagnostics,
                &mut Peekable<std::slice::Iter<'_, ast::PathSegment>>,
                Option<&mut Environment>,
            ) -> Maybe<ResolvedItem>,
            impl FnMut(
                &mut Resolver<'_>,
                &mut SemanticDiagnostics,
                &ResolvedItem,
                &ast::PathSegment,
                NotFoundItemType,
            ) -> Maybe<ResolvedItem>,
            impl FnMut(&mut SemanticDiagnostics, &ast::PathSegment) -> Maybe<()>,
            impl FnMut(
                &mut ResolvedItems,
                &dyn SemanticGroup,
                &syntax::node::ast::PathSegment,
                ResolvedItem,
            ),
        >,
    ) -> Maybe<ResolvedItem> {
        let db = self.db;
        let syntax_db = db.upcast();
        let elements_vec = path.to_segments(syntax_db);
        let mut segments = elements_vec.iter().peekable();

        // Find where the first segment lies in.
        let mut item: ResolvedItem = (callbacks.resolve_path_first_segment)(
            self,
            diagnostics,
            &mut segments,
            statement_env,
        )?;

        // Follow modules.
        while let Some(segment) = segments.next() {
            (callbacks.validate_segment)(diagnostics, segment)?;

            // If this is not the last segment, set the expected type to
            // [NotFoundItemType::Identifier].
            let cur_item_type =
                if segments.peek().is_some() { NotFoundItemType::Identifier } else { item_type };
            // `?` is ok here as the rest of the segments have no meaning if the current one can't
            // be resolved.
            item = (callbacks.resolve_path_next_segment)(
                self,
                diagnostics,
                &item,
                segment,
                cur_item_type,
            )?;
            (callbacks.mark)(&mut self.resolved_items, db, segment, item.clone());
        }
        Ok(item)
    }

    /// Resolves a concrete item, given a path.
    /// Guaranteed to result in at most one diagnostic.
    /// Item not inside a statement.
    pub fn resolve_concrete_path(
        &mut self,
        diagnostics: &mut SemanticDiagnostics,
        path: impl AsSegments,
        item_type: NotFoundItemType,
    ) -> Maybe<ResolvedConcreteItem> {
        self.resolve_concrete_path_ex(diagnostics, path, item_type, None)
    }

    /// Resolves a concrete item, given a path.
    /// Guaranteed to result in at most one diagnostic.
    pub fn resolve_concrete_path_ex(
        &mut self,
        diagnostics: &mut SemanticDiagnostics,
        path: impl AsSegments,
        item_type: NotFoundItemType,
        statement_env: Option<&mut Environment>,
    ) -> Maybe<ResolvedConcreteItem> {
        self.resolve_path_inner::<ResolvedConcreteItem>(
            diagnostics,
            path,
            item_type,
            statement_env,
            ResolvePathInnerCallbacks {
                resolved_item_type: PhantomData,
                resolve_path_first_segment: |resolver, diagnostics, segments, statement_env| {
                    resolver.resolve_concrete_path_first_segment(
                        diagnostics,
                        segments,
                        statement_env,
                    )
                },
                resolve_path_next_segment: |resolver, diagnostics, item, segment, item_type| {
                    resolver.resolve_path_next_segment_concrete(
                        diagnostics,
                        item,
                        segment,
                        item_type,
                    )
                },
                validate_segment: |_, _| Ok(()),
                mark: |resolved_items, db, segment, item| {
                    resolved_items.mark_concrete(db, segment, item.clone());
                },
            },
        )
    }

    /// Resolves the first segment of a concrete path.
    fn resolve_concrete_path_first_segment(
        &mut self,
        diagnostics: &mut SemanticDiagnostics,
        segments: &mut Peekable<std::slice::Iter<'_, ast::PathSegment>>,
        statement_env: Option<&mut Environment>,
    ) -> Maybe<ResolvedConcreteItem> {
        if let Some(base_module) = self.try_handle_super_segments(diagnostics, segments) {
            return Ok(ResolvedConcreteItem::Module(base_module?));
        }

        let db = self.db;
        let syntax_db = db.upcast();
        Ok(match segments.peek().unwrap() {
            syntax::node::ast::PathSegment::WithGenericArgs(generic_segment) => {
                let identifier = generic_segment.ident(syntax_db);
                // Identifier with generic args cannot be a local item.
                match self.determine_base(&identifier, statement_env) {
                    ResolvedBase::Module(module_id) => ResolvedConcreteItem::Module(module_id),
                    ResolvedBase::Crate(_) => {
                        // Crates do not have generics.
                        return Err(diagnostics.report(
                            &generic_segment.generic_args(syntax_db),
                            UnexpectedGenericArgs,
                        ));
                    }
                    ResolvedBase::StatementEnvironment(generic_item) => {
                        let segment = segments.next().unwrap();
                        self.specialize_generic_statement_arg(
                            segment,
                            diagnostics,
                            &identifier,
                            generic_item,
                            segment.generic_args(syntax_db),
                        )
                    }
                }
            }
            syntax::node::ast::PathSegment::Simple(simple_segment) => {
                let identifier = simple_segment.ident(syntax_db);

                if let Some(resolved_item) =
                    resolve_self_segment(db, diagnostics, &identifier, &self.data.trait_or_impl_ctx)
                {
                    // The first segment is `Self`. Consume it and return.
                    segments.next().unwrap();
                    return resolved_item;
                }

                if let Some(local_item) = self.determine_base_item_in_local_scope(&identifier) {
                    self.resolved_items.mark_concrete(db, segments.next().unwrap(), local_item)
                } else {
                    match self.determine_base(&identifier, statement_env) {
                        // This item lies inside a module.
                        ResolvedBase::Module(module_id) => ResolvedConcreteItem::Module(module_id),
                        ResolvedBase::Crate(crate_id) => self.resolved_items.mark_concrete(
                            db,
                            segments.next().unwrap(),
                            ResolvedConcreteItem::Module(ModuleId::CrateRoot(crate_id)),
                        ),
                        ResolvedBase::StatementEnvironment(generic_item) => {
                            let segment = segments.next().unwrap();
                            self.specialize_generic_statement_arg(
                                segment,
                                diagnostics,
                                &identifier,
                                generic_item,
                                segment.generic_args(syntax_db),
                            )
                        }
                    }
                }
            }
        })
    }

    /// Resolves a generic item, given a path.
    /// Guaranteed to result in at most one diagnostic.
    pub fn resolve_generic_path(
        &mut self,
        diagnostics: &mut SemanticDiagnostics,
        path: impl AsSegments,
        item_type: NotFoundItemType,
        statement_env: Option<&mut Environment>,
    ) -> Maybe<ResolvedGenericItem> {
        self.resolve_generic_path_inner(diagnostics, path, item_type, false, statement_env)
    }
    /// Resolves a generic item, given a concrete item path, while ignoring the generic args.
    /// Guaranteed to result in at most one diagnostic.
    pub fn resolve_generic_path_with_args(
        &mut self,
        diagnostics: &mut SemanticDiagnostics,
        path: impl AsSegments,
        item_type: NotFoundItemType,
        statement_env: Option<&mut Environment>,
    ) -> Maybe<ResolvedGenericItem> {
        self.resolve_generic_path_inner(diagnostics, path, item_type, true, statement_env)
    }

    /// Resolves a generic item, given a path.
    /// Guaranteed to result in at most one diagnostic.
    /// If `allow_generic_args` is true a path with generic args will be processed, but the generic
    /// params will be ignored.
    fn resolve_generic_path_inner(
        &mut self,
        diagnostics: &mut SemanticDiagnostics,
        path: impl AsSegments,
        item_type: NotFoundItemType,
        allow_generic_args: bool,
        statement_env: Option<&mut Environment>,
    ) -> Maybe<ResolvedGenericItem> {
        let validate_segment =
            |diagnostics: &mut SemanticDiagnostics, segment: &ast::PathSegment| match segment {
                ast::PathSegment::WithGenericArgs(generic_args) if !allow_generic_args => {
                    Err(diagnostics.report(generic_args, UnexpectedGenericArgs))
                }
                _ => Ok(()),
            };
        self.resolve_path_inner::<ResolvedGenericItem>(
            diagnostics,
            path,
            item_type,
            statement_env,
            ResolvePathInnerCallbacks {
                resolved_item_type: PhantomData,
                resolve_path_first_segment: |resolver, diagnostics, segments, statement_env| {
                    resolver.resolve_generic_path_first_segment(
                        diagnostics,
                        segments,
                        allow_generic_args,
                        statement_env,
                    )
                },
                resolve_path_next_segment: |resolver, diagnostics, item, segment, item_type| {
                    let identifier = segment.identifier_ast(self.db.upcast());
                    resolver.resolve_path_next_segment_generic(
                        diagnostics,
                        item,
                        &identifier,
                        item_type,
                    )
                },
                validate_segment,
                mark: |resolved_items, db, segment, item| {
                    resolved_items.mark_generic(db, segment, item.clone());
                },
            },
        )
    }

    /// Resolves the first segment of a generic path.
    /// If `allow_generic_args` is true the generic args will be ignored.
    fn resolve_generic_path_first_segment(
        &mut self,
        diagnostics: &mut SemanticDiagnostics,
        segments: &mut Peekable<std::slice::Iter<'_, ast::PathSegment>>,
        allow_generic_args: bool,
        statement_env: Option<&mut Environment>,
    ) -> Maybe<ResolvedGenericItem> {
        if let Some(base_module) = self.try_handle_super_segments(diagnostics, segments) {
            return Ok(ResolvedGenericItem::Module(base_module?));
        }
        let db = self.db;
        let syntax_db = db.upcast();
        Ok(match segments.peek().unwrap() {
            syntax::node::ast::PathSegment::WithGenericArgs(generic_segment) => {
                if !allow_generic_args {
                    return Err(diagnostics
                        .report(&generic_segment.generic_args(syntax_db), UnexpectedGenericArgs));
                }
                let identifier = generic_segment.ident(syntax_db);
                // Identifier with generic args cannot be a local item.
                match self.determine_base(&identifier, statement_env) {
                    ResolvedBase::Module(module_id) => ResolvedGenericItem::Module(module_id),
                    ResolvedBase::Crate(_) => {
                        // Crates do not have generics.
                        return Err(diagnostics.report(
                            &generic_segment.generic_args(syntax_db),
                            UnexpectedGenericArgs,
                        ));
                    }
                    ResolvedBase::StatementEnvironment(generic_item) => generic_item,
                }
            }
            syntax::node::ast::PathSegment::Simple(simple_segment) => {
                let identifier = simple_segment.ident(syntax_db);
                match self.determine_base(&identifier, statement_env) {
                    // This item lies inside a module.
                    ResolvedBase::Module(module_id) => ResolvedGenericItem::Module(module_id),
                    ResolvedBase::Crate(crate_id) => self.resolved_items.mark_generic(
                        db,
                        segments.next().unwrap(),
                        ResolvedGenericItem::Module(ModuleId::CrateRoot(crate_id)),
                    ),
                    ResolvedBase::StatementEnvironment(generic_item) => {
                        segments.next();
                        generic_item
                    }
                }
            }
        })
    }

    /// Handles `super::` initial segments, by removing them, and returning the valid module if
    /// exists. If there's none - returns None.
    /// If there are, but that's an invalid path, adds to diagnostics and returns `Some(Err)`.
    fn try_handle_super_segments(
        &self,
        diagnostics: &mut SemanticDiagnostics,
        segments: &mut Peekable<std::slice::Iter<'_, ast::PathSegment>>,
    ) -> Option<Maybe<ModuleId>> {
        let syntax_db = self.db.upcast();
        let mut module_id = self.module_file_id.0;
        for segment in segments.peeking_take_while(|segment| match segment {
            ast::PathSegment::WithGenericArgs(_) => false,
            ast::PathSegment::Simple(simple) => simple.ident(syntax_db).text(syntax_db) == SUPER_KW,
        }) {
            module_id = match module_id {
                ModuleId::CrateRoot(_) => {
                    return Some(Err(diagnostics.report(segment, SuperUsedInRootModule)));
                }
                ModuleId::Submodule(submodule_id) => submodule_id.parent_module(self.db.upcast()),
            };
        }
        (module_id != self.module_file_id.0).then_some(Ok(module_id))
    }

    /// Given the current resolved item, resolves the next segment.
    fn resolve_path_next_segment_concrete(
        &mut self,
        diagnostics: &mut SemanticDiagnostics,
        containing_item: &ResolvedConcreteItem,
        segment: &ast::PathSegment,
        item_type: NotFoundItemType,
    ) -> Maybe<ResolvedConcreteItem> {
        let syntax_db = self.db.upcast();
        let identifier = &segment.identifier_ast(syntax_db);
        let generic_args_syntax = segment.generic_args(syntax_db);

        let ident = identifier.text(syntax_db);

        if identifier.text(syntax_db) == SELF_TYPE_KW {
            return Err(diagnostics.report(identifier, SelfMustBeFirst));
        }

        match containing_item {
            ResolvedConcreteItem::Module(module_id) => {
                // Prefix `super` segments should be removed earlier. Middle `super` segments are
                // not allowed.
                if ident == SUPER_KW {
                    return Err(diagnostics.report(identifier, InvalidPath));
                }
                let segment_stable_ptr = segment.stable_ptr().untyped();

                let inner_item_info = self
                    .db
                    .module_item_info_by_name(*module_id, ident)?
                    .ok_or_else(|| diagnostics.report(identifier, PathNotFound(item_type)))?;

                self.validate_item_usability(diagnostics, *module_id, identifier, &inner_item_info);
                self.data.used_items.insert(LookupItemId::ModuleItem(inner_item_info.item_id));
                let inner_generic_item =
                    ResolvedGenericItem::from_module_item(self.db, inner_item_info.item_id)?;
                let specialized_item = self.specialize_generic_module_item(
                    diagnostics,
                    identifier,
                    inner_generic_item,
                    generic_args_syntax.clone(),
                )?;
                self.warn_same_impl_trait(
                    diagnostics,
                    &specialized_item,
                    &generic_args_syntax.unwrap_or_default(),
                    segment_stable_ptr,
                );
                Ok(specialized_item)
            }
            ResolvedConcreteItem::Type(ty) => {
                if let TypeLongId::Concrete(ConcreteTypeId::Enum(concrete_enum_id)) =
                    ty.lookup_intern(self.db)
                {
                    let enum_id = concrete_enum_id.enum_id(self.db);
                    let variants = self
                        .db
                        .enum_variants(enum_id)
                        .map_err(|_| diagnostics.report(identifier, UnknownEnum))?;
                    let variant_id = variants.get(&ident).ok_or_else(|| {
                        diagnostics
                            .report(identifier, NoSuchVariant { enum_id, variant_name: ident })
                    })?;
                    let variant = self.db.variant_semantic(enum_id, *variant_id)?;
                    let concrete_variant =
                        self.db.concrete_enum_variant(concrete_enum_id, &variant)?;
                    Ok(ResolvedConcreteItem::Variant(concrete_variant))
                } else {
                    Err(diagnostics.report(identifier, InvalidPath))
                }
            }
            ResolvedConcreteItem::Trait(concrete_trait_id) => {
                // Find the relevant function in the trait.
                let long_trait_id = concrete_trait_id.lookup_intern(self.db);
                let trait_id = long_trait_id.trait_id;

                let Some(trait_item_id) = self.db.trait_item_by_name(trait_id, ident)? else {
                    return Err(diagnostics.report(identifier, InvalidPath));
                };
                self.data.used_items.insert(LookupItemId::TraitItem(trait_item_id));

                match trait_item_id {
                    TraitItemId::Function(trait_function_id) => {
                        let concrete_trait_function = ConcreteTraitGenericFunctionLongId::new(
                            self.db,
                            *concrete_trait_id,
                            trait_function_id,
                        )
                        .intern(self.db);
                        let identifier_stable_ptr = identifier.stable_ptr().untyped();
                        if let TraitOrImplContext::Trait(ctx_trait_id) = &self.trait_or_impl_ctx {
                            if trait_id == *ctx_trait_id {
                                return Ok(ResolvedConcreteItem::Function(
                                    self.specialize_function(
                                        diagnostics,
                                        identifier_stable_ptr,
                                        GenericFunctionId::Trait(concrete_trait_function),
                                        &generic_args_syntax.unwrap_or_default(),
                                    )?,
                                ));
                            }
                        }
                        let impl_lookup_context = self.impl_lookup_context();
                        let generic_function = self.inference().infer_trait_generic_function(
                            concrete_trait_function,
                            &impl_lookup_context,
                            Some(identifier_stable_ptr),
                        );

                        Ok(ResolvedConcreteItem::Function(self.specialize_function(
                            diagnostics,
                            identifier_stable_ptr,
                            generic_function,
                            &generic_args_syntax.unwrap_or_default(),
                        )?))
                    }
                    TraitItemId::Type(trait_type_id) => {
                        if let TraitOrImplContext::Trait(ctx_trait_id) = &self.trait_or_impl_ctx {
                            if trait_id == *ctx_trait_id {
                                return Ok(ResolvedConcreteItem::Type(
                                    TypeLongId::TraitType(trait_type_id).intern(self.db),
                                ));
                            }
                        }
                        let concrete_trait_type =
                            ConcreteTraitTypeId::new(self.db, *concrete_trait_id, trait_type_id);

                        let impl_lookup_context = self.impl_lookup_context();
                        let identifier_stable_ptr = identifier.stable_ptr().untyped();
                        let ty = self.inference().infer_trait_type(
                            concrete_trait_type,
                            &impl_lookup_context,
                            Some(identifier_stable_ptr),
                        );
                        Ok(ResolvedConcreteItem::Type(self.inference().rewrite(ty).no_err()))
                    }
                    TraitItemId::Constant(trait_constant_id) => {
                        let concrete_trait_constant = ConcreteTraitConstantLongId::new(
                            self.db,
                            *concrete_trait_id,
                            trait_constant_id,
                        )
                        .intern(self.db);

                        if let TraitOrImplContext::Trait(ctx_trait_id) = &self.trait_or_impl_ctx {
                            if trait_id == *ctx_trait_id {
                                return Ok(ResolvedConcreteItem::Constant(
                                    ConstValue::TraitConstant(trait_constant_id).intern(self.db),
                                ));
                            }
                        }

                        let impl_lookup_context = self.impl_lookup_context();
                        let identifier_stable_ptr = identifier.stable_ptr().untyped();
                        let imp_constant_id = self.inference().infer_trait_constant(
                            concrete_trait_constant,
                            &impl_lookup_context,
                            Some(identifier_stable_ptr),
                        );
                        // Make sure the inference is solved for successful impl lookup
                        // Ignore the result of the `solve()` call - the error, if any, will be
                        // reported later.
                        self.inference().solve().ok();

                        Ok(ResolvedConcreteItem::Constant(
                            ConstValue::ImplConstant(imp_constant_id).intern(self.db),
                        ))
                    }
                    TraitItemId::Impl(trait_impl_id) => {
                        let concrete_trait_impl = ConcreteTraitImplLongId::new(
                            self.db,
                            *concrete_trait_id,
                            trait_impl_id,
                        )
                        .intern(self.db);

                        if let TraitOrImplContext::Trait(ctx_trait_id) = &self.trait_or_impl_ctx {
                            if trait_id == *ctx_trait_id {
                                return Ok(ResolvedConcreteItem::Impl(
                                    ImplLongId::TraitImpl(trait_impl_id).intern(self.db),
                                ));
                            }
                        }

                        let impl_lookup_context = self.impl_lookup_context();
                        let identifier_stable_ptr = identifier.stable_ptr().untyped();
                        let impl_impl_id = self.inference().infer_trait_impl(
                            concrete_trait_impl,
                            &impl_lookup_context,
                            Some(identifier_stable_ptr),
                        );
                        // Make sure the inference is solved for successful impl lookup
                        // Ignore the result of the `solve()` call - the error, if any, will be
                        // reported later.
                        self.inference().solve().ok();

                        Ok(ResolvedConcreteItem::Impl(
                            ImplLongId::ImplImpl(impl_impl_id).intern(self.db),
                        ))
                    }
                }
            }
            ResolvedConcreteItem::Impl(impl_id) => {
                let concrete_trait_id = self.db.impl_concrete_trait(*impl_id)?;
                let trait_id = concrete_trait_id.trait_id(self.db);
                let Some(trait_item_id) = self.db.trait_item_by_name(trait_id, ident)? else {
                    return Err(diagnostics.report(identifier, InvalidPath));
                };
                self.data.used_items.insert(LookupItemId::TraitItem(trait_item_id));

                match trait_item_id {
                    TraitItemId::Function(trait_function_id) => {
                        let generic_function_id = GenericFunctionId::Impl(ImplGenericFunctionId {
                            impl_id: *impl_id,
                            function: trait_function_id,
                        });

                        Ok(ResolvedConcreteItem::Function(self.specialize_function(
                            diagnostics,
                            identifier.stable_ptr().untyped(),
                            generic_function_id,
                            &generic_args_syntax.unwrap_or_default(),
                        )?))
                    }
                    TraitItemId::Type(trait_type_id) => {
                        let impl_type_id = ImplTypeId::new(*impl_id, trait_type_id, self.db);
                        let ty = self
                            .inference()
                            .reduce_impl_ty(impl_type_id)
                            .unwrap_or_else(|_| TypeLongId::ImplType(impl_type_id).intern(self.db));
                        Ok(ResolvedConcreteItem::Type(ty))
                    }
                    TraitItemId::Constant(trait_constant_id) => {
                        let impl_constant_id =
                            ImplConstantId::new(*impl_id, trait_constant_id, self.db);

                        let constant =
                            self.inference().reduce_impl_constant(impl_constant_id).unwrap_or_else(
                                |_| ConstValue::ImplConstant(impl_constant_id).intern(self.db),
                            );

                        Ok(ResolvedConcreteItem::Constant(constant))
                    }
                    TraitItemId::Impl(trait_impl_id) => {
                        let impl_impl_id = ImplImplId::new(*impl_id, trait_impl_id, self.db);
                        let imp = self
                            .inference()
                            .reduce_impl_impl(impl_impl_id)
                            .unwrap_or_else(|_| ImplLongId::ImplImpl(impl_impl_id).intern(self.db));

                        Ok(ResolvedConcreteItem::Impl(imp))
                    }
                }
            }
            ResolvedConcreteItem::Function(function_id) if ident == "Coupon" => {
                if !are_coupons_enabled(self.db, self.module_file_id) {
                    diagnostics.report(identifier, CouponsDisabled);
                }
                if matches!(
                    function_id.get_concrete(self.db).generic_function,
                    GenericFunctionId::Extern(_)
                ) {
                    return Err(diagnostics.report(identifier, CouponForExternFunctionNotAllowed));
                }
                Ok(ResolvedConcreteItem::Type(TypeLongId::Coupon(*function_id).intern(self.db)))
            }
            _ => Err(diagnostics.report(identifier, InvalidPath)),
        }
    }

    /// Specializes a ResolvedGenericItem that came from a ModuleItem.
    fn specialize_generic_module_item(
        &mut self,
        diagnostics: &mut SemanticDiagnostics,
        identifier: &syntax::node::ast::TerminalIdentifier,
        generic_item: ResolvedGenericItem,
        generic_args_syntax: Option<Vec<ast::GenericArg>>,
    ) -> Maybe<ResolvedConcreteItem> {
        Ok(match generic_item {
            ResolvedGenericItem::GenericConstant(id) => {
                ResolvedConcreteItem::Constant(self.db.constant_const_value(id)?)
            }
            ResolvedGenericItem::Module(module_id) => {
                if generic_args_syntax.is_some() {
                    return Err(diagnostics.report(identifier, UnexpectedGenericArgs));
                }
                ResolvedConcreteItem::Module(module_id)
            }
            ResolvedGenericItem::GenericFunction(generic_function) => {
                ResolvedConcreteItem::Function(self.specialize_function(
                    diagnostics,
                    identifier.stable_ptr().untyped(),
                    generic_function,
                    &generic_args_syntax.unwrap_or_default(),
                )?)
            }
            ResolvedGenericItem::GenericType(generic_type) => {
                ResolvedConcreteItem::Type(self.specialize_type(
                    diagnostics,
                    identifier.stable_ptr().untyped(),
                    generic_type,
                    &generic_args_syntax.unwrap_or_default(),
                )?)
            }
            ResolvedGenericItem::GenericTypeAlias(module_type_alias_id) => {
                let ty = self.db.module_type_alias_resolved_type(module_type_alias_id)?;
                let generic_params =
                    self.db.module_type_alias_generic_params(module_type_alias_id)?;
                let generic_args = self.resolve_generic_args(
                    diagnostics,
                    &generic_params,
                    &generic_args_syntax.unwrap_or_default(),
                    identifier.stable_ptr().untyped(),
                )?;
                let substitution = GenericSubstitution::new(&generic_params, &generic_args);
                let ty = SubstitutionRewriter { db: self.db, substitution: &substitution }
                    .rewrite(ty)?;
                ResolvedConcreteItem::Type(ty)
            }
            ResolvedGenericItem::GenericImplAlias(impl_alias_id) => {
                let impl_id = self.db.impl_alias_resolved_impl(impl_alias_id)?;
                let generic_params = self.db.impl_alias_generic_params(impl_alias_id)?;
                let generic_args = self.resolve_generic_args(
                    diagnostics,
                    &generic_params,
                    &generic_args_syntax.unwrap_or_default(),
                    identifier.stable_ptr().untyped(),
                )?;
                let substitution = GenericSubstitution::new(&generic_params, &generic_args);
                let impl_id = SubstitutionRewriter { db: self.db, substitution: &substitution }
                    .rewrite(impl_id)?;
                ResolvedConcreteItem::Impl(impl_id)
            }
            ResolvedGenericItem::Trait(trait_id) => {
                ResolvedConcreteItem::Trait(self.specialize_trait(
                    diagnostics,
                    identifier.stable_ptr().untyped(),
                    trait_id,
                    &generic_args_syntax.unwrap_or_default(),
                )?)
            }
            ResolvedGenericItem::Impl(impl_def_id) => ResolvedConcreteItem::Impl(
                ImplLongId::Concrete(self.specialize_impl(
                    diagnostics,
                    identifier.stable_ptr().untyped(),
                    impl_def_id,
                    &generic_args_syntax.unwrap_or_default(),
                )?)
                .intern(self.db),
            ),
            ResolvedGenericItem::Variant(_) => panic!("Variant is not a module item."),
            ResolvedGenericItem::TraitFunction(_) => panic!("TraitFunction is not a module item."),
            ResolvedGenericItem::Variable(_) => panic!("Variable is not a module item."),
        })
    }

    /// Given the current resolved item, resolves the next segment.
    fn resolve_path_next_segment_generic(
        &mut self,
        diagnostics: &mut SemanticDiagnostics,
        containing_item: &ResolvedGenericItem,
        identifier: &ast::TerminalIdentifier,
        item_type: NotFoundItemType,
    ) -> Maybe<ResolvedGenericItem> {
        let syntax_db = self.db.upcast();
        let ident = identifier.text(syntax_db);
        match containing_item {
            ResolvedGenericItem::Module(module_id) => {
                let inner_item_info = self
                    .db
                    .module_item_info_by_name(*module_id, ident)?
                    .ok_or_else(|| diagnostics.report(identifier, PathNotFound(item_type)))?;
                self.validate_item_usability(diagnostics, *module_id, identifier, &inner_item_info);
                self.data.used_items.insert(LookupItemId::ModuleItem(inner_item_info.item_id));
                ResolvedGenericItem::from_module_item(self.db, inner_item_info.item_id)
            }
            ResolvedGenericItem::GenericType(GenericTypeId::Enum(enum_id)) => {
                let variants = self.db.enum_variants(*enum_id)?;
                let variant_id = variants.get(&ident).ok_or_else(|| {
                    diagnostics.report(identifier, NoSuchVariant {
                        enum_id: *enum_id,
                        variant_name: ident,
                    })
                })?;
                let variant = self.db.variant_semantic(*enum_id, *variant_id)?;
                Ok(ResolvedGenericItem::Variant(variant))
            }
            _ => Err(diagnostics.report(identifier, InvalidPath)),
        }
    }

    /// Determines whether the first identifier of a path is a local item.
    fn determine_base_item_in_local_scope(
        &mut self,
        identifier: &ast::TerminalIdentifier,
    ) -> Option<ResolvedConcreteItem> {
        let syntax_db = self.db.upcast();
        let ident = identifier.text(syntax_db);

        // If a generic param with this name is found, use it.
        if let Some(generic_param_id) = self.data.generic_param_by_name.get(&ident) {
            let item = match generic_param_id.kind(self.db.upcast()) {
                GenericKind::Type => ResolvedConcreteItem::Type(
                    TypeLongId::GenericParameter(*generic_param_id).intern(self.db),
                ),
                GenericKind::Const => ResolvedConcreteItem::Constant(
                    ConstValue::Generic(*generic_param_id).intern(self.db),
                ),
                GenericKind::Impl => ResolvedConcreteItem::Impl(
                    ImplLongId::GenericParameter(*generic_param_id).intern(self.db),
                ),
                GenericKind::NegImpl => return None,
            };
            return Some(item);
        }
        // TODO(spapini): Resolve local variables.

        None
    }

    /// Determines the base module or crate for the path resolving. Looks only in non-local scope
    /// (i.e. current module, or crates).
    fn determine_base(
        &mut self,
        identifier: &ast::TerminalIdentifier,
        statement_env: Option<&mut Environment>,
    ) -> ResolvedBase {
        let syntax_db = self.db.upcast();
        let ident = identifier.text(syntax_db);

        if let Some(env) = statement_env {
            if let Some(inner_generic_arg) = get_statement_item_by_name(env, &ident) {
                return ResolvedBase::StatementEnvironment(inner_generic_arg);
            }
        }

        // If an item with this name is found inside the current module, use the current module.
        if let Ok(Some(_)) = self.db.module_item_by_name(self.module_file_id.0, ident.clone()) {
            return ResolvedBase::Module(self.module_file_id.0);
        }

        // If the first element is `crate`, use the crate's root module as the base module.
        if ident == CRATE_KW {
            return ResolvedBase::Crate(self.owning_crate_id);
        }
        // If the first segment is a name of a crate, use the crate's root module as the base
        // module.
        if let Some(dep) = self.settings.dependencies.get(ident.as_str()) {
            return ResolvedBase::Crate(
                CrateLongId::Real { name: ident, discriminator: dep.discriminator.clone() }
                    .intern(self.db),
            );
        }
        // If the first segment is `core` - and it was not overridden by a dependency - using it.
        if ident == CORELIB_CRATE_NAME {
            return ResolvedBase::Crate(CrateId::core(self.db));
        }
        ResolvedBase::Module(self.prelude_submodule())
    }

    /// Returns the crate's `prelude` submodule.
    pub fn prelude_submodule(&self) -> ModuleId {
        let prelude_submodule_name = self.settings.edition.prelude_submodule_name();
        let core_prelude_submodule = core_submodule(self.db, "prelude");
        get_submodule(self.db, core_prelude_submodule, prelude_submodule_name).unwrap_or_else(
            || {
                panic!(
                    "expected prelude submodule `{prelude_submodule_name}` not found in \
                     `core::prelude`."
                )
            },
        )
    }

    /// Specializes a trait.
    fn specialize_trait(
        &mut self,
        diagnostics: &mut SemanticDiagnostics,
        stable_ptr: SyntaxStablePtrId,
        trait_id: TraitId,
        generic_args: &[ast::GenericArg],
    ) -> Maybe<ConcreteTraitId> {
        // TODO(lior): Should we report diagnostic if `trait_generic_params` failed?
        let generic_params = self
            .db
            .trait_generic_params(trait_id)
            .map_err(|_| diagnostics.report(stable_ptr, UnknownTrait))?;
        let generic_args =
            self.resolve_generic_args(diagnostics, &generic_params, generic_args, stable_ptr)?;

        Ok(ConcreteTraitLongId { trait_id, generic_args }.intern(self.db))
    }

    /// Specializes an impl.
    fn specialize_impl(
        &mut self,
        diagnostics: &mut SemanticDiagnostics,
        stable_ptr: SyntaxStablePtrId,
        impl_def_id: ImplDefId,
        generic_args: &[ast::GenericArg],
    ) -> Maybe<ConcreteImplId> {
        // TODO(lior): Should we report diagnostic if `impl_def_generic_params` failed?
        let generic_params = self
            .db
            .impl_def_generic_params(impl_def_id)
            .map_err(|_| diagnostics.report(stable_ptr, UnknownImpl))?;
        let generic_args =
            self.resolve_generic_args(diagnostics, &generic_params, generic_args, stable_ptr)?;

        Ok(ConcreteImplLongId { impl_def_id, generic_args }.intern(self.db))
    }

    /// Specializes a generic function.
    pub fn specialize_function(
        &mut self,
        diagnostics: &mut SemanticDiagnostics,
        stable_ptr: SyntaxStablePtrId,
        generic_function: GenericFunctionId,
        generic_args: &[ast::GenericArg],
    ) -> Maybe<FunctionId> {
        // TODO(lior): Should we report diagnostic if `impl_def_generic_params` failed?
        let generic_params: Vec<_> = generic_function.generic_params(self.db)?;
        let generic_args =
            self.resolve_generic_args(diagnostics, &generic_params, generic_args, stable_ptr)?;

        Ok(FunctionLongId { function: ConcreteFunction { generic_function, generic_args } }
            .intern(self.db))
    }

    /// Specializes a generic type.
    pub fn specialize_type(
        &mut self,
        diagnostics: &mut SemanticDiagnostics,
        stable_ptr: SyntaxStablePtrId,
        generic_type: GenericTypeId,
        generic_args: &[ast::GenericArg],
    ) -> Maybe<TypeId> {
        let generic_params = self
            .db
            .generic_type_generic_params(generic_type)
            .map_err(|_| diagnostics.report(stable_ptr, UnknownType))?;
        let generic_args =
            self.resolve_generic_args(diagnostics, &generic_params, generic_args, stable_ptr)?;

        Ok(TypeLongId::Concrete(ConcreteTypeId::new(self.db, generic_type, generic_args))
            .intern(self.db))
    }

    pub fn impl_lookup_context(&self) -> ImplLookupContext {
        let mut lookup_context =
            ImplLookupContext::new(self.module_file_id.0, self.generic_params.clone());

        if let TraitOrImplContext::Impl(impl_def_id) = &self.trait_or_impl_ctx {
            let Ok(generic_params) = self.db.impl_def_generic_params(*impl_def_id) else {
                return lookup_context;
            };
            let generic_args = generic_params_to_args(generic_params.as_slice(), self.db);
            let impl_id: ConcreteImplId =
                ConcreteImplLongId { impl_def_id: *impl_def_id, generic_args }.intern(self.db);
            lookup_context.insert_impl(ImplLongId::Concrete(impl_id).intern(self.db));
        }
        lookup_context
    }

    /// Resolves generic arguments.
    /// For each generic argument, if the syntax is provided, it will be resolved by the inference.
    /// Otherwise, resolved by type.
    pub fn resolve_generic_args(
        &mut self,
        diagnostics: &mut SemanticDiagnostics,
        generic_params: &[GenericParam],
        generic_args_syntax: &[ast::GenericArg],
        stable_ptr: SyntaxStablePtrId,
    ) -> Maybe<Vec<GenericArgumentId>> {
        let mut substitution = GenericSubstitution::default();
        let mut resolved_args = vec![];
        let arg_syntax_per_param =
            self.get_arg_syntax_per_param(diagnostics, generic_params, generic_args_syntax)?;

        for generic_param in generic_params.iter() {
            let generic_param = SubstitutionRewriter { db: self.db, substitution: &substitution }
                .rewrite(*generic_param)?;
            let generic_arg = self.resolve_generic_arg(
                generic_param,
                arg_syntax_per_param
                    .get(&generic_param.id())
                    .and_then(|arg_syntax| {
                        if let ast::GenericArgValue::Expr(expr) = arg_syntax {
                            Some(expr.expr(self.db.upcast()))
                        } else {
                            None
                        }
                    })
                    .as_ref(),
                stable_ptr,
                diagnostics,
            )?;
            resolved_args.push(generic_arg);
            substitution.insert(generic_param.id(), generic_arg);
        }

        Ok(resolved_args)
    }

    /// Returns a map of generic param id -> its assigned arg syntax.
    fn get_arg_syntax_per_param(
        &self,
        diagnostics: &mut SemanticDiagnostics,
        generic_params: &[GenericParam],
        generic_args_syntax: &[ast::GenericArg],
    ) -> Maybe<UnorderedHashMap<GenericParamId, ast::GenericArgValue>> {
        let syntax_db = self.db.upcast();
        let mut arg_syntax_per_param =
            UnorderedHashMap::<GenericParamId, ast::GenericArgValue>::default();
        let mut last_named_arg_index = None;
        let generic_param_by_name = generic_params
            .iter()
            .enumerate()
            .filter_map(|(i, param)| Some((param.id().name(self.db.upcast())?, (i, param.id()))))
            .collect::<UnorderedHashMap<_, _>>();
        for (idx, generic_arg_syntax) in generic_args_syntax.iter().enumerate() {
            match generic_arg_syntax {
                ast::GenericArg::Named(arg_syntax) => {
                    let name = arg_syntax.name(syntax_db).text(syntax_db);
                    let Some((index, generic_param_id)) = generic_param_by_name.get(&name) else {
                        return Err(diagnostics.report(arg_syntax, UnknownGenericParam(name)));
                    };
                    if let Some(prev_index) = last_named_arg_index {
                        if prev_index > index {
                            return Err(diagnostics.report(arg_syntax, GenericArgOutOfOrder(name)));
                        }
                    }
                    last_named_arg_index = Some(index);
                    if arg_syntax_per_param
                        .insert(*generic_param_id, arg_syntax.value(syntax_db))
                        .is_some()
                    {
                        return Err(diagnostics.report(arg_syntax, GenericArgDuplicate(name)));
                    }
                }
                ast::GenericArg::Unnamed(arg_syntax) => {
                    if last_named_arg_index.is_some() {
                        return Err(diagnostics.report(arg_syntax, PositionalGenericAfterNamed));
                    }
                    let generic_param = generic_params.get(idx).ok_or_else(|| {
                        diagnostics.report(arg_syntax, TooManyGenericArguments {
                            expected: generic_params.len(),
                            actual: generic_args_syntax.len(),
                        })
                    })?;
                    assert_eq!(
                        arg_syntax_per_param
                            .insert(generic_param.id(), arg_syntax.value(syntax_db)),
                        None,
                        "Unexpected duplication in ordered params."
                    );
                }
            }
        }
        Ok(arg_syntax_per_param)
    }

    /// Resolves a generic argument.
    /// If no syntax Expr is provided, inference will be used.
    /// If a syntax Expr is provided, it will be resolved by type.
    fn resolve_generic_arg(
        &mut self,
        generic_param: GenericParam,
        generic_arg_syntax_opt: Option<&ast::Expr>,
        stable_ptr: SyntaxStablePtrId,
        diagnostics: &mut SemanticDiagnostics,
    ) -> Result<GenericArgumentId, cairo_lang_diagnostics::DiagnosticAdded> {
        let Some(generic_arg_syntax) = generic_arg_syntax_opt else {
            let lookup_context = self.impl_lookup_context();
            let inference = &mut self.data.inference_data.inference(self.db);
            return inference
                .infer_generic_arg(&generic_param, lookup_context, Some(stable_ptr))
                .map_err(|err_set| {
                    inference.report_on_pending_error(err_set, diagnostics, stable_ptr)
                });
        };
        Ok(match generic_param {
            GenericParam::Type(_) => {
                let ty = resolve_type(self.db, diagnostics, self, generic_arg_syntax);
                GenericArgumentId::Type(ty)
            }
            GenericParam::Const(const_param) => {
                // TODO(spapini): Currently no bound checks are performed. Move literal validation
                // to inference finalization and use inference here. This will become more relevant
                // when we support constant expressions, which need inference.
                let environment = Environment::empty();

                // Using the resolver's data in the constant computation context, so impl vars are
                // added to the correct inference.
                let mut resolver_data =
                    ResolverData::new(self.module_file_id, self.inference_data.inference_id);
                std::mem::swap(&mut self.data, &mut resolver_data);

                let mut ctx = ComputationContext::new(
                    self.db,
                    diagnostics,
                    Resolver::with_data(self.db, resolver_data),
                    None,
                    environment,
                    ContextFunction::Global,
                );
                let value = compute_expr_semantic(&mut ctx, generic_arg_syntax);

                let const_value = resolve_const_expr_and_evaluate(
                    self.db,
                    &mut ctx,
                    &value,
                    generic_arg_syntax.stable_ptr().untyped(),
                    const_param.ty,
                );

                // Update `self` data with const_eval_resolver's data.
                std::mem::swap(&mut ctx.resolver.data, &mut self.data);

                GenericArgumentId::Constant(const_value.intern(self.db))
            }

            GenericParam::Impl(param) => {
                let expr_path = try_extract_matches!(generic_arg_syntax, ast::Expr::Path)
                    .ok_or_else(|| diagnostics.report(generic_arg_syntax, UnknownImpl))?;
                let resolved_impl = try_extract_matches!(
                    self.resolve_concrete_path(diagnostics, expr_path, NotFoundItemType::Impl)?,
                    ResolvedConcreteItem::Impl
                )
                .ok_or_else(|| diagnostics.report(generic_arg_syntax, UnknownImpl))?;
                let impl_def_concrete_trait = self.db.impl_concrete_trait(resolved_impl)?;
                let expected_concrete_trait = param.concrete_trait?;
                if let Err(err_set) = self
                    .inference()
                    .conform_traits(impl_def_concrete_trait, expected_concrete_trait)
                {
                    let diag_added = diagnostics.report(generic_arg_syntax, TraitMismatch {
                        expected_trt: expected_concrete_trait,
                        actual_trt: impl_def_concrete_trait,
                    });
                    self.inference().consume_reported_error(err_set, diag_added);
                }
                GenericArgumentId::Impl(resolved_impl)
            }
            GenericParam::NegImpl(_) => {
                return Err(diagnostics.report(generic_arg_syntax, ArgPassedToNegativeImpl));
            }
        })
    }
    /// Should visibility checks not actually happen for lookups in this module.
    // TODO(orizi): Remove this check when performing a major Cairo update.
    pub fn ignore_visibility_checks(&self, module_id: ModuleId) -> bool {
        let module_crate = module_id.owning_crate(self.db.upcast());
        let module_edition =
            self.db.crate_config(module_crate).map(|c| c.settings.edition).unwrap_or_default();
        module_edition.ignore_visibility()
            || self.settings.edition.ignore_visibility() && module_crate == self.db.core_crate()
    }

    /// Validates that an item is usable from the current module or adds a diagnostic.
    /// This includes visibility checks and feature checks.
    fn validate_item_usability(
        &self,
        diagnostics: &mut SemanticDiagnostics,
        containing_module_id: ModuleId,
        identifier: &ast::TerminalIdentifier,
        item_info: &ModuleItemInfo,
    ) {
        let db = self.db.upcast();
        if !self.ignore_visibility_checks(containing_module_id) {
            let user_module = self.module_file_id.0;
            if !visibility::peek_visible_in(
                db,
                item_info.visibility,
                containing_module_id,
                user_module,
            ) {
                diagnostics.report(identifier, ItemNotVisible(item_info.item_id));
            }
        }
        match &item_info.feature_kind {
            FeatureKind::Unstable { feature, note }
                if !self.data.feature_config.allowed_features.contains(feature) =>
            {
                diagnostics.report(identifier, UnstableFeature {
                    feature_name: feature.clone(),
                    note: note.clone(),
                });
            }
            FeatureKind::Deprecated { feature, note }
                if !self.data.feature_config.allow_deprecated
                    && !self.data.feature_config.allowed_features.contains(feature) =>
            {
                diagnostics.report(identifier, DeprecatedFeature {
                    feature_name: feature.clone(),
                    note: note.clone(),
                });
            }
            FeatureKind::Internal { feature, note }
                if !self.data.feature_config.allowed_features.contains(feature) =>
            {
                diagnostics.report(identifier, InternalFeature {
                    feature_name: feature.clone(),
                    note: note.clone(),
                });
            }
            _ => {}
        }
    }

    // TODO(yuval): on a breaking version change, consider changing warnings to errors.
    /// Warns about the use of a trait in a path inside the same trait or an impl of it, and the use
    /// of an impl in a path inside the same impl.
    /// That is, warns about using the actual path equivalent to `Self`, where `Self` can be used.
    fn warn_same_impl_trait(
        &mut self,
        diagnostics: &mut SemanticDiagnostics,
        specialized_item: &ResolvedConcreteItem,
        generic_args_syntax_slice: &[ast::GenericArg],
        segment_stable_ptr: SyntaxStablePtrId,
    ) {
        match *specialized_item {
            ResolvedConcreteItem::Trait(current_segment_concrete_trait) => {
                match self.trait_or_impl_ctx {
                    TraitOrImplContext::None => {}
                    TraitOrImplContext::Trait(ctx_trait) => {
                        self.warn_trait_in_same_trait(
                            diagnostics,
                            current_segment_concrete_trait.trait_id(self.db),
                            generic_args_syntax_slice,
                            ctx_trait,
                            segment_stable_ptr,
                        )
                        .ok();
                    }
                    TraitOrImplContext::Impl(ctx_impl_def_id) => {
                        self.warn_trait_in_its_impl(
                            diagnostics,
                            current_segment_concrete_trait,
                            ctx_impl_def_id,
                            segment_stable_ptr,
                        )
                        .ok();
                    }
                };
            }
            ResolvedConcreteItem::Impl(current_segment_impl_id) => {
                if let TraitOrImplContext::Impl(ctx_impl) = self.trait_or_impl_ctx {
                    // A ResolvedConcreteItem::Impl returned by
                    // `specialize_generic_module_item` must be ImplLongId::Concrete.
                    let current_segment_concrete_impl_id = extract_matches!(
                        current_segment_impl_id.lookup_intern(self.db),
                        ImplLongId::Concrete
                    );
                    self.warn_impl_in_same_impl(
                        diagnostics,
                        current_segment_concrete_impl_id.impl_def_id(self.db),
                        generic_args_syntax_slice,
                        ctx_impl,
                        segment_stable_ptr,
                    )
                    .ok();
                }
            }
            _ => {}
        };
    }

    /// Raises a warning diagnostic (and returns an error) if the segment describes an impl in the
    /// context of that impl (that is, could be expressed as `Self`).
    fn warn_impl_in_same_impl(
        &mut self,
        diagnostics: &mut SemanticDiagnostics,
        current_segment_impl_def_id: ImplDefId,
        current_segment_generic_args: &[ast::GenericArg],
        ctx_impl: ImplDefId,
        segment_stable_ptr: SyntaxStablePtrId,
    ) -> Maybe<()> {
        if current_segment_impl_def_id != ctx_impl {
            return Ok(());
        }

        let generic_params = self.db.impl_def_generic_params(ctx_impl)?;
        self.compare_segment_args_to_params(
            diagnostics,
            current_segment_generic_args,
            generic_params,
            segment_stable_ptr,
            ImplInImplMustBeExplicit,
            ImplItemForbiddenInTheImpl,
        )
    }

    /// Raises a warning diagnostic (and returns an error) if the segment is of a concrete trait in
    /// the context of an impl of that concrete trait (that is, could be expressed as `Self`).
    fn warn_trait_in_its_impl(
        &mut self,
        diagnostics: &mut SemanticDiagnostics,
        current_segment_concrete_trait_id: ConcreteTraitId,
        impl_ctx: ImplDefId,
        segment_stable_ptr: SyntaxStablePtrId,
    ) -> Maybe<()> {
        let ctx_impl_trait = self.db.impl_def_trait(impl_ctx)?;
        if current_segment_concrete_trait_id.trait_id(self.db) != ctx_impl_trait {
            return Ok(());
        }

        let ctx_impl_concrete_trait = self.db.impl_def_concrete_trait(impl_ctx)?;
        if ctx_impl_concrete_trait.generic_args(self.db)
            == current_segment_concrete_trait_id.generic_args(self.db)
        {
            return Err(diagnostics.report(segment_stable_ptr, TraitItemForbiddenInItsImpl));
        }
        Ok(())
    }

    /// Raises a warning diagnostic (and returns an error) if the segment describes a trait in the
    /// context of that trait (that is, could be expressed as `Self`).
    fn warn_trait_in_same_trait(
        &mut self,
        diagnostics: &mut SemanticDiagnostics,
        current_segment_trait_id: TraitId,
        current_segment_generic_args: &[ast::GenericArg],
        ctx_trait: TraitId,
        segment_stable_ptr: SyntaxStablePtrId,
    ) -> Maybe<()> {
        if current_segment_trait_id != ctx_trait {
            return Ok(());
        }

        let generic_params = self.db.trait_generic_params(ctx_trait)?;
        self.compare_segment_args_to_params(
            diagnostics,
            current_segment_generic_args,
            generic_params,
            segment_stable_ptr,
            TraitInTraitMustBeExplicit,
            TraitItemForbiddenInTheTrait,
        )
    }

    /// Check if the given generic arguments exactly match the given generic parameters.
    /// This is used to check if a path segment is forbidden in the context of the item referred to
    /// by the segment.
    ///
    /// Fails if not all arguments are explicitly specified or if they are all specified and exactly
    /// the same as the parameters.
    fn compare_segment_args_to_params(
        &mut self,
        diagnostics: &mut SemanticDiagnostics,
        current_segment_generic_args: &[ast::GenericArg],
        generic_params: Vec<GenericParam>,
        segment_stable_ptr: SyntaxStablePtrId,
        must_be_explicit_error: SemanticDiagnosticKind,
        item_forbidden_in_itself_explicit_error: SemanticDiagnosticKind,
    ) -> Maybe<()> {
        // This assumes the current segment item and the context items are equal. In this specific
        // case we disallow implicit arguments.
        if current_segment_generic_args.len() < generic_params.len() {
            return Err(diagnostics.report(segment_stable_ptr, must_be_explicit_error));
        }
        let resolved_args = self.resolve_generic_args(
            diagnostics,
            &generic_params,
            current_segment_generic_args,
            segment_stable_ptr,
        )?;

        if generic_params
            .iter()
            .zip_eq(resolved_args.iter())
            .all(|(gparam, garg)| gparam.as_arg(self.db) == *garg)
        {
            return Err(
                diagnostics.report(segment_stable_ptr, item_forbidden_in_itself_explicit_error)
            );
        }
        Ok(())
    }

    /// Specializes a ResolvedGenericItem that came from a Statement Environment.
    fn specialize_generic_statement_arg(
        &mut self,
        segment: &ast::PathSegment,
        diagnostics: &mut SemanticDiagnostics,
        identifier: &ast::TerminalIdentifier,
        inner_generic_item: ResolvedGenericItem,
        generic_args_syntax: Option<Vec<ast::GenericArg>>,
    ) -> ResolvedConcreteItem {
        let segment_stable_ptr = segment.stable_ptr().untyped();
        let specialized_item = self
            .specialize_generic_module_item(
                diagnostics,
                identifier,
                inner_generic_item.clone(),
                generic_args_syntax.clone(),
            )
            .unwrap();
        self.warn_same_impl_trait(
            diagnostics,
            &specialized_item,
            &generic_args_syntax.unwrap_or_default(),
            segment_stable_ptr,
        );
        specialized_item
    }
}

/// Resolves the segment if it's `Self`. Returns the Some(ResolvedConcreteItem) or Some(Err) if
/// segment == `Self` or None otherwise.
fn resolve_self_segment(
    db: &dyn SemanticGroup,
    diagnostics: &mut SemanticDiagnostics,
    identifier: &ast::TerminalIdentifier,
    trait_or_impl_ctx: &TraitOrImplContext,
) -> Option<Maybe<ResolvedConcreteItem>> {
    require(identifier.text(db.upcast()) == SELF_TYPE_KW)?;
    Some(resolve_actual_self_segment(db, diagnostics, identifier, trait_or_impl_ctx))
}

/// Resolves the `Self` segment given that it's actually `Self`.
fn resolve_actual_self_segment(
    db: &dyn SemanticGroup,
    diagnostics: &mut SemanticDiagnostics,
    identifier: &ast::TerminalIdentifier,
    trait_or_impl_ctx: &TraitOrImplContext,
) -> Maybe<ResolvedConcreteItem> {
    match trait_or_impl_ctx {
        TraitOrImplContext::None => Err(diagnostics.report(identifier, SelfNotSupportedInContext)),
        TraitOrImplContext::Trait(trait_id) => {
            let generic_parameters = db.trait_generic_params(*trait_id)?;
            let concrete_trait_id = ConcreteTraitLongId {
                trait_id: *trait_id,
                generic_args: generic_params_to_args(&generic_parameters, db),
            }
            .intern(db);
            Ok(ResolvedConcreteItem::Trait(concrete_trait_id))
        }
        TraitOrImplContext::Impl(impl_def_id) => {
            let generic_parameters = db.impl_def_generic_params(*impl_def_id)?;
            let impl_id = ImplLongId::Concrete(
                ConcreteImplLongId {
                    impl_def_id: *impl_def_id,
                    generic_args: generic_params_to_args(&generic_parameters, db),
                }
                .intern(db),
            );
            Ok(ResolvedConcreteItem::Impl(impl_id.intern(db)))
        }
    }
}

/// The base module or crate for the path resolving.
enum ResolvedBase {
    /// The base module is a module.
    Module(ModuleId),
    /// The base module is a crate.
    Crate(CrateId),
    /// The base module to address is the statement
    StatementEnvironment(ResolvedGenericItem),
}

/// The callbacks to be used by `resolve_path_inner`.
struct ResolvePathInnerCallbacks<ResolvedItem, ResolveFirst, ResolveNext, Validate, Mark>
where
    ResolveFirst: FnMut(
        &mut Resolver<'_>,
        &mut SemanticDiagnostics,
        &mut Peekable<std::slice::Iter<'_, ast::PathSegment>>,
        Option<&mut Environment>,
    ) -> Maybe<ResolvedItem>,
    ResolveNext: FnMut(
        &mut Resolver<'_>,
        &mut SemanticDiagnostics,
        &ResolvedItem,
        &ast::PathSegment,
        NotFoundItemType,
    ) -> Maybe<ResolvedItem>,
    Validate: FnMut(&mut SemanticDiagnostics, &ast::PathSegment) -> Maybe<()>,
    Mark: FnMut(
        &mut ResolvedItems,
        &dyn SemanticGroup,
        &syntax::node::ast::PathSegment,
        ResolvedItem,
    ),
{
    /// Type for the resolved item pointed by the path segments.
    resolved_item_type: PhantomData<ResolvedItem>,
    /// Resolves the first segment of a path.
    resolve_path_first_segment: ResolveFirst,
    /// Given the current resolved item, resolves the next segment.
    resolve_path_next_segment: ResolveNext,
    /// An additional validation to perform for each segment. If it fails, the whole resolution
    /// fails.
    validate_segment: Validate,
    mark: Mark,
}