cairo_lang_semantic/
diagnostic.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
use std::fmt::Display;

use cairo_lang_debug::DebugWithDb;
use cairo_lang_defs::diagnostic_utils::StableLocation;
use cairo_lang_defs::ids::{
    EnumId, FunctionTitleId, ImplDefId, ImplFunctionId, ModuleId, ModuleItemId,
    NamedLanguageElementId, StructId, TopLevelLanguageElementId, TraitFunctionId, TraitId,
    TraitImplId, UseId,
};
use cairo_lang_defs::plugin::PluginDiagnostic;
use cairo_lang_diagnostics::{
    DiagnosticAdded, DiagnosticEntry, DiagnosticLocation, DiagnosticsBuilder, ErrorCode, Severity,
    error_code,
};
use cairo_lang_filesystem::db::Edition;
use cairo_lang_syntax as syntax;
use itertools::Itertools;
use smol_str::SmolStr;
use syntax::node::ids::SyntaxStablePtrId;

use crate::corelib::LiteralError;
use crate::db::SemanticGroup;
use crate::expr::inference::InferenceError;
use crate::items::feature_kind::FeatureMarkerDiagnostic;
use crate::items::trt::ConcreteTraitTypeId;
use crate::resolve::{ResolvedConcreteItem, ResolvedGenericItem};
use crate::types::peel_snapshots;
use crate::{ConcreteTraitId, semantic};

#[cfg(test)]
#[path = "diagnostic_test.rs"]
mod test;

pub type SemanticDiagnostics = DiagnosticsBuilder<SemanticDiagnostic>;
pub trait SemanticDiagnosticsBuilder {
    /// Report a diagnostic in the location of the given ptr.
    fn report(
        &mut self,
        stable_ptr: impl Into<SyntaxStablePtrId>,
        kind: SemanticDiagnosticKind,
    ) -> DiagnosticAdded;
    /// Report a diagnostic in the location after the given ptr (with width 0).
    fn report_after(
        &mut self,
        stable_ptr: impl Into<SyntaxStablePtrId>,
        kind: SemanticDiagnosticKind,
    ) -> DiagnosticAdded;
}
impl SemanticDiagnosticsBuilder for SemanticDiagnostics {
    fn report(
        &mut self,
        stable_ptr: impl Into<SyntaxStablePtrId>,
        kind: SemanticDiagnosticKind,
    ) -> DiagnosticAdded {
        self.add(SemanticDiagnostic::new(StableLocation::new(stable_ptr.into()), kind))
    }
    fn report_after(
        &mut self,
        stable_ptr: impl Into<SyntaxStablePtrId>,
        kind: SemanticDiagnosticKind,
    ) -> DiagnosticAdded {
        self.add(SemanticDiagnostic::new_after(StableLocation::new(stable_ptr.into()), kind))
    }
}

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct SemanticDiagnostic {
    pub stable_location: StableLocation,
    pub kind: SemanticDiagnosticKind,
    /// true if the diagnostic should be reported *after* the given location. Normally false, in
    /// which case the diagnostic points to the given location (as-is).
    pub after: bool,
}
impl SemanticDiagnostic {
    /// Create a diagnostic in the given location.
    pub fn new(stable_location: StableLocation, kind: SemanticDiagnosticKind) -> Self {
        SemanticDiagnostic { stable_location, kind, after: false }
    }
    /// Create a diagnostic in the location after the given location (with width 0).
    pub fn new_after(stable_location: StableLocation, kind: SemanticDiagnosticKind) -> Self {
        SemanticDiagnostic { stable_location, kind, after: true }
    }
}
impl DiagnosticEntry for SemanticDiagnostic {
    type DbType = dyn SemanticGroup;

    fn format(&self, db: &Self::DbType) -> String {
        match &self.kind {
            SemanticDiagnosticKind::ModuleFileNotFound(path) => {
                format!("Module file not found. Expected path: {path}")
            }
            SemanticDiagnosticKind::Unsupported => "Unsupported feature.".into(),
            SemanticDiagnosticKind::UnknownLiteral => "Unknown literal.".into(),
            SemanticDiagnosticKind::UnknownBinaryOperator => "Unknown binary operator.".into(),
            SemanticDiagnosticKind::UnknownTrait => "Unknown trait.".into(),
            SemanticDiagnosticKind::UnknownImpl => "Unknown impl.".into(),
            SemanticDiagnosticKind::UnexpectedElement { expected, actual } => {
                let expected_str = expected.iter().map(|kind| kind.to_string()).join(" or ");
                format!("Expected {expected_str}, found {actual}.")
            }
            SemanticDiagnosticKind::UnknownType => "Unknown type.".into(),
            SemanticDiagnosticKind::UnknownEnum => "Unknown enum.".into(),
            SemanticDiagnosticKind::LiteralError(literal_error) => literal_error.format(db),
            SemanticDiagnosticKind::NotAVariant => {
                "Not a variant. Use the full name Enum::Variant.".into()
            }
            SemanticDiagnosticKind::NotAStruct => "Not a struct.".into(),
            SemanticDiagnosticKind::NotAType => "Not a type.".into(),
            SemanticDiagnosticKind::NotATrait => "Not a trait.".into(),
            SemanticDiagnosticKind::NotAnImpl => "Not an impl.".into(),
            SemanticDiagnosticKind::ImplItemNotInTrait {
                impl_def_id,
                impl_item_name,
                trait_id,
                item_kind,
            } => {
                let defs_db = db.upcast();
                format!(
                    "Impl item {item_kind} `{}::{}` is not a member of trait `{}`.",
                    impl_def_id.name(defs_db),
                    impl_item_name,
                    trait_id.name(defs_db)
                )
            }
            SemanticDiagnosticKind::ImplicitImplNotInferred {
                trait_impl_id,
                concrete_trait_id,
            } => {
                let defs_db = db.upcast();
                format!(
                    "Cannot infer implicit impl `{}.`\nCould not find implementation of trait \
                     `{:?}`",
                    trait_impl_id.name(defs_db),
                    concrete_trait_id.debug(db)
                )
            }
            SemanticDiagnosticKind::GenericsNotSupportedInItem { scope, item_kind } => {
                format!("Generic parameters are not supported in {scope} item {item_kind}.")
            }
            SemanticDiagnosticKind::UnexpectedGenericArgs => "Unexpected generic arguments".into(),
            SemanticDiagnosticKind::UnknownMember => "Unknown member.".into(),
            SemanticDiagnosticKind::MemberSpecifiedMoreThanOnce => {
                "Member specified more than once.".into()
            }
            SemanticDiagnosticKind::ConstCycle => {
                "Cycle detected while resolving 'const' items.".into()
            }
            SemanticDiagnosticKind::UseCycle => {
                "Cycle detected while resolving 'use' items.".into()
            }
            SemanticDiagnosticKind::TypeAliasCycle => {
                "Cycle detected while resolving type-alias/impl-type items.".into()
            }
            SemanticDiagnosticKind::ImplAliasCycle => {
                "Cycle detected while resolving 'impls alias' items.".into()
            }
            SemanticDiagnosticKind::ImplRequirementCycle => {
                "Cycle detected while resolving generic param. Try specifying the generic impl \
                 parameter explicitly to break the cycle."
                    .into()
            }
            SemanticDiagnosticKind::MissingMember(member_name) => {
                format!(r#"Missing member "{member_name}"."#)
            }
            SemanticDiagnosticKind::WrongNumberOfParameters {
                impl_def_id,
                impl_function_id,
                trait_id,
                expected,
                actual,
            } => {
                let defs_db = db.upcast();
                let function_name = impl_function_id.name(defs_db);
                format!(
                    "The number of parameters in the impl function `{}::{}` is incompatible with \
                     `{}::{}`. Expected: {}, actual: {}.",
                    impl_def_id.name(defs_db),
                    function_name,
                    trait_id.name(defs_db),
                    function_name,
                    expected,
                    actual,
                )
            }
            SemanticDiagnosticKind::WrongNumberOfArguments { expected, actual } => {
                format!("Wrong number of arguments. Expected {expected}, found: {actual}")
            }
            SemanticDiagnosticKind::WrongParameterType {
                impl_def_id,
                impl_function_id,
                trait_id,
                expected_ty,
                actual_ty,
            } => {
                let defs_db = db.upcast();
                let function_name = impl_function_id.name(defs_db);
                format!(
                    "Parameter type of impl function `{}::{}` is incompatible with `{}::{}`. \
                     Expected: `{}`, actual: `{}`.",
                    impl_def_id.name(defs_db),
                    function_name,
                    trait_id.name(defs_db),
                    function_name,
                    expected_ty.format(db),
                    actual_ty.format(db)
                )
            }
            SemanticDiagnosticKind::VariantCtorNotImmutable => {
                "Variant constructor argument must be immutable.".to_string()
            }
            SemanticDiagnosticKind::TraitParamMutable { trait_id, function_id } => {
                let defs_db = db.upcast();
                format!(
                    "Parameter of trait function `{}::{}` can't be defined as mutable.",
                    trait_id.name(defs_db),
                    function_id.name(defs_db),
                )
            }
            SemanticDiagnosticKind::ParameterShouldBeReference {
                impl_def_id,
                impl_function_id,
                trait_id,
            } => {
                let defs_db = db.upcast();
                let function_name = impl_function_id.name(defs_db);
                format!(
                    "Parameter of impl function {}::{} is incompatible with {}::{}. It should be \
                     a reference.",
                    impl_def_id.name(defs_db),
                    function_name,
                    trait_id.name(defs_db),
                    function_name,
                )
            }
            SemanticDiagnosticKind::ParameterShouldNotBeReference {
                impl_def_id,
                impl_function_id,
                trait_id,
            } => {
                let defs_db = db.upcast();
                let function_name = impl_function_id.name(defs_db);
                format!(
                    "Parameter of impl function {}::{} is incompatible with {}::{}. It should not \
                     be a reference.",
                    impl_def_id.name(defs_db),
                    function_name,
                    trait_id.name(defs_db),
                    function_name,
                )
            }
            SemanticDiagnosticKind::WrongParameterName {
                impl_def_id,
                impl_function_id,
                trait_id,
                expected_name,
            } => {
                let defs_db = db.upcast();
                let function_name = impl_function_id.name(defs_db);
                format!(
                    "Parameter name of impl function {}::{function_name} is incompatible with \
                     {}::{function_name} parameter `{expected_name}`.",
                    impl_def_id.name(defs_db),
                    trait_id.name(defs_db),
                )
            }
            SemanticDiagnosticKind::WrongType { expected_ty, actual_ty } => {
                format!(
                    r#"Expected type "{}", found: "{}"."#,
                    expected_ty.format(db),
                    actual_ty.format(db)
                )
            }
            SemanticDiagnosticKind::InconsistentBinding => "variable is bound inconsistently \
                                                            across alternatives separated by `|` \
                                                            bound in different ways"
                .into(),
            SemanticDiagnosticKind::WrongArgumentType { expected_ty, actual_ty } => {
                let diagnostic_prefix = format!(
                    r#"Unexpected argument type. Expected: "{}", found: "{}"."#,
                    expected_ty.format(db),
                    actual_ty.format(db)
                );
                if (expected_ty.is_fully_concrete(db) && actual_ty.is_fully_concrete(db))
                    || peel_snapshots(db, *expected_ty).0 == peel_snapshots(db, *actual_ty).0
                {
                    diagnostic_prefix
                } else {
                    format!(
                        "{}\nIt is possible that the type inference failed because the types \
                         differ in the number of snapshots.\nConsider adding or removing \
                         snapshots.",
                        diagnostic_prefix
                    )
                }
            }
            SemanticDiagnosticKind::WrongReturnType { expected_ty, actual_ty } => {
                format!(
                    r#"Unexpected return type. Expected: "{}", found: "{}"."#,
                    expected_ty.format(db),
                    actual_ty.format(db)
                )
            }
            SemanticDiagnosticKind::WrongExprType { expected_ty, actual_ty } => {
                format!(
                    r#"Unexpected expression type. Expected: "{}", found: "{}"."#,
                    expected_ty.format(db),
                    actual_ty.format(db)
                )
            }
            SemanticDiagnosticKind::WrongNumberOfGenericParamsForImplFunction {
                expected,
                actual,
            } => {
                format!(
                    "Wrong number of generic parameters for impl function. Expected: {}, found: \
                     {}.",
                    expected, actual
                )
            }
            SemanticDiagnosticKind::WrongReturnTypeForImpl {
                impl_def_id,
                impl_function_id,
                trait_id,
                expected_ty,
                actual_ty,
            } => {
                let defs_db = db.upcast();
                let function_name = impl_function_id.name(defs_db);
                format!(
                    "Return type of impl function `{}::{}` is incompatible with `{}::{}`. \
                     Expected: `{}`, actual: `{}`.",
                    impl_def_id.name(defs_db),
                    function_name,
                    trait_id.name(defs_db),
                    function_name,
                    expected_ty.format(db),
                    actual_ty.format(db)
                )
            }
            SemanticDiagnosticKind::AmbiguousTrait { trait_function_id0, trait_function_id1 } => {
                format!(
                    "Ambiguous method call. More than one applicable trait function with a \
                     suitable self type was found: {} and {}. Consider adding type annotations or \
                     explicitly refer to the impl function.",
                    trait_function_id0.full_path(db.upcast()),
                    trait_function_id1.full_path(db.upcast())
                )
            }
            SemanticDiagnosticKind::VariableNotFound(name) => {
                format!(r#"Variable "{name}" not found."#)
            }
            SemanticDiagnosticKind::MissingVariableInPattern => {
                "Missing variable in pattern.".into()
            }
            SemanticDiagnosticKind::StructMemberRedefinition { struct_id, member_name } => {
                format!(
                    r#"Redefinition of member "{member_name}" on struct "{}"."#,
                    struct_id.full_path(db.upcast())
                )
            }
            SemanticDiagnosticKind::EnumVariantRedefinition { enum_id, variant_name } => {
                format!(
                    r#"Redefinition of variant "{variant_name}" on enum "{}"."#,
                    enum_id.full_path(db.upcast())
                )
            }
            SemanticDiagnosticKind::InfiniteSizeType(ty) => {
                format!(r#"Recursive type "{}" has infinite size."#, ty.format(db))
            }
            SemanticDiagnosticKind::ArrayOfZeroSizedElements(ty) => {
                format!(r#"Cannot have array of type "{}" that is zero sized."#, ty.format(db))
            }
            SemanticDiagnosticKind::ParamNameRedefinition { function_title_id, param_name } => {
                format!(
                    r#"Redefinition of parameter name "{param_name}"{}"#,
                    function_title_id
                        .map(|function_title_id| format!(
                            r#" in function "{}"."#,
                            function_title_id.full_path(db.upcast())
                        ))
                        .unwrap_or(".".into()),
                )
            }
            SemanticDiagnosticKind::ConditionNotBool(condition_ty) => {
                format!(r#"Condition has type "{}", expected bool."#, condition_ty.format(db))
            }
            SemanticDiagnosticKind::IncompatibleArms {
                multi_arm_expr_kind: incompatibility_kind,
                pending_ty: first_ty,
                different_ty,
            } => {
                let prefix = match incompatibility_kind {
                    MultiArmExprKind::Match => "Match arms have incompatible types",
                    MultiArmExprKind::If => "If blocks have incompatible types",
                    MultiArmExprKind::Loop => "Loop has incompatible return types",
                };
                format!(r#"{prefix}: "{}" and "{}""#, first_ty.format(db), different_ty.format(db))
            }
            SemanticDiagnosticKind::LogicalOperatorNotAllowedInIfLet => {
                "Logical operator not allowed in if-let.".into()
            }
            SemanticDiagnosticKind::LogicalOperatorNotAllowedInWhileLet => {
                "Logical operator not allowed in while-let.".into()
            }
            SemanticDiagnosticKind::TypeHasNoMembers { ty, member_name: _ } => {
                format!(r#"Type "{}" has no members."#, ty.format(db))
            }
            SemanticDiagnosticKind::NoSuchStructMember { struct_id, member_name } => {
                format!(
                    r#"Struct "{}" has no member "{member_name}""#,
                    struct_id.full_path(db.upcast())
                )
            }
            SemanticDiagnosticKind::NoSuchTypeMember { ty, member_name } => {
                format!(r#"Type "{}" has no member "{member_name}""#, ty.format(db))
            }
            SemanticDiagnosticKind::MemberNotVisible(member_name) => {
                format!(r#"Member "{member_name}" is not visible in this context."#)
            }
            SemanticDiagnosticKind::NoSuchVariant { enum_id, variant_name } => {
                format!(
                    r#"Enum "{}" has no variant "{variant_name}""#,
                    enum_id.full_path(db.upcast())
                )
            }
            SemanticDiagnosticKind::ReturnTypeNotErrorPropagateType => {
                "`?` can only be used in a function with `Option` or `Result` return type.".into()
            }
            SemanticDiagnosticKind::IncompatibleErrorPropagateType { return_ty, err_ty } => {
                format!(
                    r#"Return type "{}" does not wrap error "{}""#,
                    return_ty.format(db),
                    err_ty.format(db)
                )
            }
            SemanticDiagnosticKind::ErrorPropagateOnNonErrorType(ty) => {
                format!(r#"Type "{}" can not error propagate"#, ty.format(db))
            }
            SemanticDiagnosticKind::UnhandledMustUseType(ty) => {
                format!(r#"Unhandled `#[must_use]` type `{}`"#, ty.format(db))
            }
            SemanticDiagnosticKind::UnhandledMustUseFunction => {
                "Unhandled `#[must_use]` function.".into()
            }
            SemanticDiagnosticKind::UnstableFeature { feature_name, note } => {
                format!(
                    "Usage of unstable feature `{feature_name}` with no \
                     `#[feature({feature_name})]` attribute.{}",
                    note.as_ref().map(|note| format!(" Note: {}", note)).unwrap_or_default()
                )
            }
            SemanticDiagnosticKind::DeprecatedFeature { feature_name, note } => {
                format!(
                    "Usage of deprecated feature `{feature_name}` with no \
                     `#[feature({feature_name})]` attribute.{}",
                    note.as_ref().map(|note| format!(" Note: {}", note)).unwrap_or_default()
                )
            }
            SemanticDiagnosticKind::InternalFeature { feature_name, note } => {
                format!(
                    "Usage of internal feature `{feature_name}` with no \
                     `#[feature({feature_name})]` attribute.{}",
                    note.as_ref().map(|note| format!(" Note: {}", note)).unwrap_or_default()
                )
            }
            SemanticDiagnosticKind::FeatureMarkerDiagnostic(diagnostic) => match diagnostic {
                FeatureMarkerDiagnostic::MultipleMarkers => {
                    "Multiple feature marker attributes.".into()
                }
                FeatureMarkerDiagnostic::MissingAllowFeature => {
                    "Missing `feature` arg for feature marker attribute.".into()
                }
                FeatureMarkerDiagnostic::UnsupportedArgument => {
                    "Unsupported argument for feature marker attribute.".into()
                }
                FeatureMarkerDiagnostic::DuplicatedArgument => {
                    "Duplicated argument for feature marker attribute.".into()
                }
            },
            SemanticDiagnosticKind::UnusedVariable => {
                "Unused variable. Consider ignoring by prefixing with `_`.".into()
            }
            SemanticDiagnosticKind::UnusedConstant => {
                "Unused constant. Consider ignoring by prefixing with `_`.".into()
            }
            SemanticDiagnosticKind::MultipleConstantDefinition(constant_name) => {
                format!(r#"Multiple definitions of constant "{}"."#, constant_name)
            }
            SemanticDiagnosticKind::UnusedUse => "Unused use.".into(),
            SemanticDiagnosticKind::MultipleDefinitionforBinding(identifier_name) => {
                format!(
                    r#"Multiple definitions of identifier '{}' as constant and variable."#,
                    identifier_name
                )
            }
            SemanticDiagnosticKind::MultipleGenericItemDefinition(type_name) => {
                format!(r#"Multiple definitions of an item "{}"."#, type_name)
            }
            SemanticDiagnosticKind::UnsupportedUseItemInStatement => {
                "Unsupported use item in statement.".into()
            }
            SemanticDiagnosticKind::InvalidMemberExpression => "Invalid member expression.".into(),
            SemanticDiagnosticKind::InvalidPath => "Invalid path.".into(),
            SemanticDiagnosticKind::RefArgNotAVariable => "ref argument must be a variable.".into(),
            SemanticDiagnosticKind::RefArgNotMutable => {
                "ref argument must be a mutable variable.".into()
            }
            SemanticDiagnosticKind::RefArgNotExplicit => {
                "ref argument must be passed with a preceding 'ref'.".into()
            }
            SemanticDiagnosticKind::ImmutableArgWithModifiers => {
                "Argument to immutable parameter cannot have modifiers.".into()
            }
            SemanticDiagnosticKind::AssignmentToImmutableVar => {
                "Cannot assign to an immutable variable.".into()
            }
            SemanticDiagnosticKind::InvalidLhsForAssignment => {
                "Invalid left-hand side of assignment.".into()
            }
            SemanticDiagnosticKind::PathNotFound(item_type) => match item_type {
                NotFoundItemType::Identifier => "Identifier not found.".into(),
                NotFoundItemType::Function => "Function not found.".into(),
                NotFoundItemType::Type => "Type not found.".into(),
                NotFoundItemType::Trait => "Trait not found.".into(),
                NotFoundItemType::Impl => "Impl not found.".into(),
            },
            SemanticDiagnosticKind::AmbiguousPath(module_items) => {
                format!(
                    "Ambiguous path. Multiple matching items: {}",
                    module_items
                        .iter()
                        .map(|item| format!("`{}`", item.full_path(db.upcast())))
                        .join(", ")
                )
            }
            SemanticDiagnosticKind::UseStarEmptyPath => {
                "`*` in `use` items is not allowed for empty path.".into()
            }
            SemanticDiagnosticKind::GlobalUsesNotSupportedInEdition(edition) => {
                format!("Global `use` item is not supported in `{edition:?}` edition.")
            }
            SemanticDiagnosticKind::TraitInTraitMustBeExplicit => {
                "In a trait, paths of the same trait must be fully explicit. Either use `Self` if \
                 this is the intention, or explicitly specify all the generic arguments."
                    .to_string()
            }
            SemanticDiagnosticKind::ImplInImplMustBeExplicit => {
                "In an impl, paths of the same impl must be fully explicit. Either use `Self` if \
                 this is the intention, or explicitly specify all the generic arguments."
                    .to_string()
            }
            SemanticDiagnosticKind::TraitItemForbiddenInTheTrait => {
                "In a trait, paths of the same trait are not allowed. Did you mean to use `Self::`?"
                    .to_string()
            }
            SemanticDiagnosticKind::TraitItemForbiddenInItsImpl => "In an impl, paths of the \
                                                                    impl's trait are not allowed. \
                                                                    Did you mean to use `Self::`?"
                .to_string(),
            SemanticDiagnosticKind::ImplItemForbiddenInTheImpl => {
                "In an impl, paths of the same impl are not allowed. Did you mean to use `Self::`?"
                    .to_string()
            }
            SemanticDiagnosticKind::SuperUsedInRootModule => {
                "'super' cannot be used for the crate's root module.".into()
            }
            SemanticDiagnosticKind::ItemNotVisible(item_id, containing_modules) => {
                format!(
                    "Item `{}` is not visible in this context{}.",
                    item_id.full_path(db.upcast()),
                    if containing_modules.is_empty() {
                        "".to_string()
                    } else if let [module_id] = &containing_modules[..] {
                        format!(" through module `{}`", module_id.full_path(db.upcast()))
                    } else {
                        format!(
                            " through any of the modules: {}",
                            containing_modules
                                .iter()
                                .map(|module_id| format!("`{}`", module_id.full_path(db.upcast())))
                                .join(", ")
                        )
                    }
                )
            }
            SemanticDiagnosticKind::UnusedImport(use_id) => {
                format!("Unused import: `{}`", use_id.full_path(db.upcast()))
            }
            SemanticDiagnosticKind::UnexpectedEnumPattern(ty) => {
                format!(r#"Unexpected type for enum pattern. "{}" is not an enum."#, ty.format(db),)
            }
            SemanticDiagnosticKind::UnexpectedStructPattern(ty) => {
                format!(
                    r#"Unexpected type for struct pattern. "{}" is not a struct."#,
                    ty.format(db),
                )
            }
            SemanticDiagnosticKind::UnexpectedTuplePattern(ty) => {
                format!(r#"Unexpected type for tuple pattern. "{}" is not a tuple."#, ty.format(db),)
            }
            SemanticDiagnosticKind::UnexpectedFixedSizeArrayPattern(ty) => {
                format!(
                    "Unexpected type for fixed size array pattern. \"{}\" is not a fixed size \
                     array.",
                    ty.format(db),
                )
            }
            SemanticDiagnosticKind::WrongNumberOfTupleElements { expected, actual } => format!(
                r#"Wrong number of tuple elements in pattern. Expected: {}. Got: {}."#,
                expected, actual
            ),
            SemanticDiagnosticKind::WrongNumberOfFixedSizeArrayElements { expected, actual } => {
                format!(
                    "Wrong number of fixed size array elements in pattern. Expected: {}. Got: {}.",
                    expected, actual
                )
            }
            SemanticDiagnosticKind::WrongEnum { expected_enum, actual_enum } => {
                format!(
                    r#"Wrong enum in pattern. Expected: "{}". Got: "{}"."#,
                    expected_enum.full_path(db.upcast()),
                    actual_enum.full_path(db.upcast())
                )
            }
            SemanticDiagnosticKind::RedundantModifier { current_modifier, previous_modifier } => {
                format!(
                    "`{current_modifier}` modifier was specified after another modifier \
                     (`{previous_modifier}`). Only a single modifier is allowed."
                )
            }
            SemanticDiagnosticKind::ReferenceLocalVariable => {
                "`ref` is only allowed for function parameters, not for local variables."
                    .to_string()
            }
            SemanticDiagnosticKind::InvalidCopyTraitImpl(inference_error) => {
                format!("Invalid copy trait implementation, {}", inference_error.format(db))
            }
            SemanticDiagnosticKind::InvalidDropTraitImpl(inference_error) => {
                format!("Invalid drop trait implementation, {}", inference_error.format(db))
            }
            SemanticDiagnosticKind::InvalidImplItem(item_kw) => {
                format!("`{item_kw}` is not allowed inside impl.")
            }
            SemanticDiagnosticKind::MissingItemsInImpl(item_names) => {
                format!(
                    "Not all trait items are implemented. Missing: {}.",
                    item_names.iter().map(|name| format!("'{name}'")).join(", ")
                )
            }
            SemanticDiagnosticKind::PassPanicAsNopanic { impl_function_id, trait_id } => {
                let name = impl_function_id.name(db.upcast());
                let trait_name = trait_id.name(db.upcast());
                format!(
                    "The signature of function `{name}` is incompatible with trait \
                     `{trait_name}`. The trait function is declared as nopanic."
                )
            }
            SemanticDiagnosticKind::PanicableFromNonPanicable => {
                "Function is declared as nopanic but calls a function that may panic.".into()
            }
            SemanticDiagnosticKind::PanicableExternFunction => {
                "An extern function must be marked as nopanic.".into()
            }
            SemanticDiagnosticKind::PluginDiagnostic(diagnostic) => {
                format!("Plugin diagnostic: {}", diagnostic.message)
            }
            SemanticDiagnosticKind::NameDefinedMultipleTimes(name) => {
                format!("The name `{name}` is defined multiple times.")
            }
            SemanticDiagnosticKind::NonPrivateUseStar => {
                "`pub` not supported for global `use`.".into()
            }
            SemanticDiagnosticKind::NamedArgumentsAreNotSupported => {
                "Named arguments are not supported in this context.".into()
            }
            SemanticDiagnosticKind::UnnamedArgumentFollowsNamed => {
                "Unnamed arguments cannot follow named arguments.".into()
            }
            SemanticDiagnosticKind::NamedArgumentMismatch { expected, found } => {
                format!("Unexpected argument name. Expected: '{expected}', found '{found}'.")
            }
            SemanticDiagnosticKind::UnsupportedOutsideOfFunction(feature_name) => {
                let feature_name_str = match feature_name {
                    UnsupportedOutsideOfFunctionFeatureName::ReturnStatement => "Return statement",
                    UnsupportedOutsideOfFunctionFeatureName::ErrorPropagate => "The '?' operator",
                };
                format!("{feature_name_str} is not supported outside of functions.")
            }
            SemanticDiagnosticKind::UnsupportedConstant => {
                "This expression is not supported as constant.".into()
            }
            SemanticDiagnosticKind::DivisionByZero => "Division by zero.".into(),
            SemanticDiagnosticKind::ExternTypeWithImplGenericsNotSupported => {
                "Extern types with impl generics are not supported.".into()
            }
            SemanticDiagnosticKind::MissingSemicolon => "Missing semicolon".into(),
            SemanticDiagnosticKind::TraitMismatch { expected_trt, actual_trt } => {
                format!(
                    "Expected an impl of `{:?}`. Got an impl of `{:?}`.",
                    expected_trt.debug(db),
                    actual_trt.debug(db),
                )
            }
            SemanticDiagnosticKind::InternalInferenceError(err) => err.format(db),
            SemanticDiagnosticKind::DesnapNonSnapshot => {
                "Desnap operator can only be applied on snapshots".into()
            }
            SemanticDiagnosticKind::NoImplementationOfIndexOperator { ty, inference_errors } => {
                if inference_errors.is_empty() {
                    format!(
                        "Type `{}` does not implement the `Index` trait nor the `IndexView` trait.",
                        ty.format(db)
                    )
                } else {
                    format!(
                        "Type `{}` could not be indexed.\n{}",
                        ty.format(db),
                        inference_errors.format(db)
                    )
                }
            }
            SemanticDiagnosticKind::MultipleImplementationOfIndexOperator(ty) => {
                format!(
                    r#"Type "{}" implements both the "Index" trait and the "IndexView" trait."#,
                    ty.format(db)
                )
            }

            SemanticDiagnosticKind::UnsupportedInlineArguments => {
                "Unsupported `inline` arguments.".into()
            }
            SemanticDiagnosticKind::RedundantInlineAttribute => {
                "Redundant `inline` attribute.".into()
            }
            SemanticDiagnosticKind::InlineAttrForExternFunctionNotAllowed => {
                "`inline` attribute is not allowed for extern functions.".into()
            }
            SemanticDiagnosticKind::InlineAlwaysWithImplGenericArgNotAllowed => {
                "`#[inline(always)]` is not allowed for functions with impl generic parameters."
                    .into()
            }
            SemanticDiagnosticKind::CannotCallMethod { ty, method_name, inference_errors } => {
                if inference_errors.is_empty() {
                    format!(
                        "Method `{}` not found on type `{}`. Did you import the correct trait and \
                         impl?",
                        method_name,
                        ty.format(db)
                    )
                } else {
                    format!(
                        "Method `{}` could not be called on type `{}`.\n{}",
                        method_name,
                        ty.format(db),
                        inference_errors.format(db)
                    )
                }
            }
            SemanticDiagnosticKind::TailExpressionNotAllowedInLoop => {
                "Tail expression not allowed in a `loop` block.".into()
            }
            SemanticDiagnosticKind::ContinueOnlyAllowedInsideALoop => {
                "`continue` only allowed inside a `loop`.".into()
            }
            SemanticDiagnosticKind::BreakOnlyAllowedInsideALoop => {
                "`break` only allowed inside a `loop`.".into()
            }
            SemanticDiagnosticKind::BreakWithValueOnlyAllowedInsideALoop => {
                "Can only break with a value inside a `loop`.".into()
            }
            SemanticDiagnosticKind::ReturnNotAllowedInsideALoop => {
                "`return` not allowed inside a `loop`.".into()
            }
            SemanticDiagnosticKind::ErrorPropagateNotAllowedInsideALoop => {
                "`?` not allowed inside a `loop`.".into()
            }
            SemanticDiagnosticKind::ConstGenericParamNotSupported => {
                "Const generic args are not allowed in this context.".into()
            }
            SemanticDiagnosticKind::NegativeImplsNotEnabled => {
                "Negative impls are not enabled in the current crate.".into()
            }
            SemanticDiagnosticKind::NegativeImplsOnlyOnImpls => {
                "Negative impls supported only in impl definitions.".into()
            }
            SemanticDiagnosticKind::ImplicitPrecedenceAttrForExternFunctionNotAllowed => {
                "`implicit_precedence` attribute is not allowed for extern functions.".into()
            }
            SemanticDiagnosticKind::RedundantImplicitPrecedenceAttribute => {
                "Redundant `implicit_precedence` attribute.".into()
            }
            SemanticDiagnosticKind::UnsupportedImplicitPrecedenceArguments => {
                "Unsupported `implicit_precedence` arguments.".into()
            }
            SemanticDiagnosticKind::UnsupportedFeatureAttrArguments => {
                "`feature` attribute argument should be a single string.".into()
            }
            SemanticDiagnosticKind::UnsupportedAllowAttrArguments => {
                // TODO(orizi): Add information about the allowed arguments.
                "`allow` attribute argument not supported.".into()
            }
            SemanticDiagnosticKind::UnsupportedPubArgument => "Unsupported `pub` argument.".into(),
            SemanticDiagnosticKind::UnknownStatementAttribute => {
                "Unknown statement attribute.".into()
            }
            SemanticDiagnosticKind::InlineMacroNotFound(macro_name) => {
                format!("Inline macro `{}` not found.", macro_name)
            }
            SemanticDiagnosticKind::InlineMacroFailed(macro_name) => {
                format!("Inline macro `{}` failed.", macro_name)
            }
            SemanticDiagnosticKind::UnknownGenericParam(name) => {
                format!("Unknown generic parameter `{}`.", name)
            }
            SemanticDiagnosticKind::PositionalGenericAfterNamed => {
                "Positional generic parameters must come before named generic parameters.".into()
            }
            SemanticDiagnosticKind::GenericArgDuplicate(name) => {
                format!("Generic argument `{}` is specified more than once.", name)
            }
            SemanticDiagnosticKind::TooManyGenericArguments { expected, actual } => {
                format!("Expected {} generic arguments, found {}.", expected, actual)
            }
            SemanticDiagnosticKind::GenericArgOutOfOrder(name) => {
                format!("Generic argument `{}` is out of order.", name)
            }
            SemanticDiagnosticKind::ArgPassedToNegativeImpl => {
                "Only `_` is valid as a negative impl argument.".into()
            }
            SemanticDiagnosticKind::CouponForExternFunctionNotAllowed => {
                "Coupon cannot be used with extern functions.".into()
            }
            SemanticDiagnosticKind::CouponArgumentNoModifiers => {
                "The __coupon__ argument cannot have modifiers.".into()
            }
            SemanticDiagnosticKind::CouponsDisabled => {
                "Coupons are disabled in the current crate.\nYou can enable them by enabling the \
                 coupons experimental feature in the crate config."
                    .into()
            }
            SemanticDiagnosticKind::StructBaseStructExpressionNotLast => {
                "The base struct must always be the last argument.".into()
            }
            SemanticDiagnosticKind::StructBaseStructExpressionNoEffect => {
                "Base struct has no effect, all the fields in the struct have already been \
                 specified."
                    .into()
            }
            SemanticDiagnosticKind::FixedSizeArrayTypeNonSingleType => {
                "Fixed size array type must have exactly one type.".into()
            }
            SemanticDiagnosticKind::FixedSizeArrayTypeEmptySize => {
                "Fixed size array type must have a size clause.".into()
            }
            SemanticDiagnosticKind::FixedSizeArrayNonNumericSize => {
                "Fixed size array type must have a positive integer size.".into()
            }
            SemanticDiagnosticKind::FixedSizeArrayNonSingleValue => {
                "Fixed size array with defined size must have exactly one value.".into()
            }
            SemanticDiagnosticKind::FixedSizeArraySizeTooBig => {
                "Fixed size array size must be smaller than 2^15.".into()
            }
            SemanticDiagnosticKind::SelfNotSupportedInContext => {
                "`Self` is not supported in this context.".into()
            }
            SemanticDiagnosticKind::SelfMustBeFirst => {
                "`Self` can only be the first segment of a path.".into()
            }
            SemanticDiagnosticKind::CannotCreateInstancesOfPhantomTypes => {
                "Can not create instances of phantom types.".into()
            }
            SemanticDiagnosticKind::NonPhantomTypeContainingPhantomType => {
                "Non-phantom type containing phantom type.".into()
            }
            SemanticDiagnosticKind::DerefCycle { deref_chain } => {
                format!("Deref impls cycle detected:\n{}", deref_chain)
            }
            SemanticDiagnosticKind::NoImplementationOfTrait {
                ty,
                trait_name,
                inference_errors,
            } => {
                if inference_errors.is_empty() {
                    format!(
                        "Implementation of trait `{}` not found on type `{}`. Did you import the \
                         correct trait and impl?",
                        trait_name,
                        ty.format(db)
                    )
                } else {
                    format!(
                        "Could not find implementation of trait `{}` on type `{}`.\n{}",
                        trait_name,
                        ty.format(db),
                        inference_errors.format(db)
                    )
                }
            }
            SemanticDiagnosticKind::CallExpressionRequiresFunction { ty, inference_errors } => {
                if inference_errors.is_empty() {
                    format!("Call expression requires a function, found `{}`.", ty.format(db))
                } else {
                    format!(
                        "Call expression requires a function, found `{}`.\n{}",
                        ty.format(db),
                        inference_errors.format(db)
                    )
                }
            }
            SemanticDiagnosticKind::CompilerTraitReImplementation { trait_id } => {
                format!("Trait `{}` should not be re-implemented.", trait_id.full_path(db.upcast()))
            }
            SemanticDiagnosticKind::ClosureInGlobalScope => {
                "Closures are not allowed in this context.".into()
            }
            SemanticDiagnosticKind::MaybeMissingColonColon => "Are you missing a `::`?.".into(),
            SemanticDiagnosticKind::CallingShadowedFunction { shadowed_function_name } => {
                format!("Function `{}` is shadowed by a local variable.", shadowed_function_name)
            }
            SemanticDiagnosticKind::RefClosureArgument => {
                "Arguments to closure functions cannot be references".into()
            }
            SemanticDiagnosticKind::MutableCapturedVariable => {
                "Capture of mutable variables in a closure is not supported".into()
            }
            SemanticDiagnosticKind::NonTraitTypeConstrained { identifier, concrete_trait_id } => {
                format!(
                    "associated type `{}` not found for `{}`",
                    identifier,
                    concrete_trait_id.full_path(db)
                )
            }
            SemanticDiagnosticKind::DuplicateTypeConstraint {
                concrete_trait_type_id: trait_type_id,
            } => {
                format!(
                    "the value of the associated type `{}` in trait `{}` is already specified",
                    trait_type_id.trait_type(db).name(db.upcast()),
                    trait_type_id.concrete_trait(db).full_path(db)
                )
            }
            SemanticDiagnosticKind::TypeConstraintsSyntaxNotEnabled => {
                "Type constraints syntax is not enabled in the current crate.".into()
            }
        }
    }

    fn location(&self, db: &Self::DbType) -> DiagnosticLocation {
        let mut location = self.stable_location.diagnostic_location(db.upcast());
        if self.after {
            location = location.after();
        }
        location
    }

    fn severity(&self) -> Severity {
        match &self.kind {
            SemanticDiagnosticKind::UnusedVariable
            | SemanticDiagnosticKind::UnhandledMustUseType { .. }
            | SemanticDiagnosticKind::UnhandledMustUseFunction
            | SemanticDiagnosticKind::TraitInTraitMustBeExplicit
            | SemanticDiagnosticKind::ImplInImplMustBeExplicit
            | SemanticDiagnosticKind::TraitItemForbiddenInTheTrait
            | SemanticDiagnosticKind::TraitItemForbiddenInItsImpl
            | SemanticDiagnosticKind::ImplItemForbiddenInTheImpl
            | SemanticDiagnosticKind::UnstableFeature { .. }
            | SemanticDiagnosticKind::DeprecatedFeature { .. }
            | SemanticDiagnosticKind::UnusedImport { .. }
            | SemanticDiagnosticKind::CallingShadowedFunction { .. }
            | SemanticDiagnosticKind::UnusedConstant
            | SemanticDiagnosticKind::UnusedUse => Severity::Warning,
            SemanticDiagnosticKind::PluginDiagnostic(diag) => diag.severity,
            _ => Severity::Error,
        }
    }

    fn error_code(&self) -> Option<ErrorCode> {
        self.kind.error_code()
    }

    fn is_same_kind(&self, other: &Self) -> bool {
        other.kind == self.kind
    }
}

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum SemanticDiagnosticKind {
    ModuleFileNotFound(String),
    Unsupported,
    UnknownLiteral,
    UnknownBinaryOperator,
    UnknownTrait,
    UnknownImpl,
    UnexpectedElement {
        expected: Vec<ElementKind>,
        actual: ElementKind,
    },
    UnknownType,
    UnknownEnum,
    LiteralError(LiteralError),
    NotAVariant,
    NotAStruct,
    NotAType,
    NotATrait,
    NotAnImpl,
    ImplItemNotInTrait {
        impl_def_id: ImplDefId,
        impl_item_name: SmolStr,
        trait_id: TraitId,
        item_kind: String,
    },
    ImplicitImplNotInferred {
        trait_impl_id: TraitImplId,
        concrete_trait_id: ConcreteTraitId,
    },
    GenericsNotSupportedInItem {
        scope: String,
        item_kind: String,
    },
    UnexpectedGenericArgs,
    UnknownMember,
    CannotCreateInstancesOfPhantomTypes,
    NonPhantomTypeContainingPhantomType,
    MemberSpecifiedMoreThanOnce,
    StructBaseStructExpressionNotLast,
    StructBaseStructExpressionNoEffect,
    ConstCycle,
    UseCycle,
    TypeAliasCycle,
    ImplAliasCycle,
    ImplRequirementCycle,
    MissingMember(SmolStr),
    WrongNumberOfParameters {
        impl_def_id: ImplDefId,
        impl_function_id: ImplFunctionId,
        trait_id: TraitId,
        expected: usize,
        actual: usize,
    },
    WrongNumberOfArguments {
        expected: usize,
        actual: usize,
    },
    WrongParameterType {
        impl_def_id: ImplDefId,
        impl_function_id: ImplFunctionId,
        trait_id: TraitId,
        expected_ty: semantic::TypeId,
        actual_ty: semantic::TypeId,
    },
    VariantCtorNotImmutable,
    TraitParamMutable {
        trait_id: TraitId,
        function_id: TraitFunctionId,
    },
    ParameterShouldBeReference {
        impl_def_id: ImplDefId,
        impl_function_id: ImplFunctionId,
        trait_id: TraitId,
    },
    ParameterShouldNotBeReference {
        impl_def_id: ImplDefId,
        impl_function_id: ImplFunctionId,
        trait_id: TraitId,
    },
    WrongParameterName {
        impl_def_id: ImplDefId,
        impl_function_id: ImplFunctionId,
        trait_id: TraitId,
        expected_name: SmolStr,
    },
    WrongType {
        expected_ty: semantic::TypeId,
        actual_ty: semantic::TypeId,
    },
    InconsistentBinding,
    WrongArgumentType {
        expected_ty: semantic::TypeId,
        actual_ty: semantic::TypeId,
    },
    WrongReturnType {
        expected_ty: semantic::TypeId,
        actual_ty: semantic::TypeId,
    },
    WrongExprType {
        expected_ty: semantic::TypeId,
        actual_ty: semantic::TypeId,
    },
    WrongNumberOfGenericParamsForImplFunction {
        expected: usize,
        actual: usize,
    },
    WrongReturnTypeForImpl {
        impl_def_id: ImplDefId,
        impl_function_id: ImplFunctionId,
        trait_id: TraitId,
        expected_ty: semantic::TypeId,
        actual_ty: semantic::TypeId,
    },
    AmbiguousTrait {
        trait_function_id0: TraitFunctionId,
        trait_function_id1: TraitFunctionId,
    },
    VariableNotFound(SmolStr),
    MissingVariableInPattern,
    StructMemberRedefinition {
        struct_id: StructId,
        member_name: SmolStr,
    },
    EnumVariantRedefinition {
        enum_id: EnumId,
        variant_name: SmolStr,
    },
    InfiniteSizeType(semantic::TypeId),
    ArrayOfZeroSizedElements(semantic::TypeId),
    ParamNameRedefinition {
        function_title_id: Option<FunctionTitleId>,
        param_name: SmolStr,
    },
    ConditionNotBool(semantic::TypeId),
    IncompatibleArms {
        multi_arm_expr_kind: MultiArmExprKind,
        pending_ty: semantic::TypeId,
        different_ty: semantic::TypeId,
    },
    LogicalOperatorNotAllowedInIfLet,
    LogicalOperatorNotAllowedInWhileLet,
    TypeHasNoMembers {
        ty: semantic::TypeId,
        member_name: SmolStr,
    },
    CannotCallMethod {
        ty: semantic::TypeId,
        method_name: SmolStr,
        inference_errors: TraitInferenceErrors,
    },
    NoSuchStructMember {
        struct_id: StructId,
        member_name: SmolStr,
    },
    NoSuchTypeMember {
        ty: semantic::TypeId,
        member_name: SmolStr,
    },
    MemberNotVisible(SmolStr),
    NoSuchVariant {
        enum_id: EnumId,
        variant_name: SmolStr,
    },
    ReturnTypeNotErrorPropagateType,
    IncompatibleErrorPropagateType {
        return_ty: semantic::TypeId,
        err_ty: semantic::TypeId,
    },
    ErrorPropagateOnNonErrorType(semantic::TypeId),
    UnhandledMustUseType(semantic::TypeId),
    UnstableFeature {
        feature_name: SmolStr,
        note: Option<SmolStr>,
    },
    DeprecatedFeature {
        feature_name: SmolStr,
        note: Option<SmolStr>,
    },
    InternalFeature {
        feature_name: SmolStr,
        note: Option<SmolStr>,
    },
    FeatureMarkerDiagnostic(FeatureMarkerDiagnostic),
    UnhandledMustUseFunction,
    UnusedVariable,
    UnusedConstant,
    UnusedUse,
    MultipleConstantDefinition(SmolStr),
    MultipleDefinitionforBinding(SmolStr),
    MultipleGenericItemDefinition(SmolStr),
    UnsupportedUseItemInStatement,
    ConstGenericParamNotSupported,
    NegativeImplsNotEnabled,
    NegativeImplsOnlyOnImpls,
    RefArgNotAVariable,
    RefArgNotMutable,
    RefArgNotExplicit,
    ImmutableArgWithModifiers,
    AssignmentToImmutableVar,
    InvalidLhsForAssignment,
    InvalidMemberExpression,
    InvalidPath,
    PathNotFound(NotFoundItemType),
    AmbiguousPath(Vec<ModuleItemId>),
    UseStarEmptyPath,
    GlobalUsesNotSupportedInEdition(Edition),
    TraitInTraitMustBeExplicit,
    ImplInImplMustBeExplicit,
    TraitItemForbiddenInTheTrait,
    TraitItemForbiddenInItsImpl,
    ImplItemForbiddenInTheImpl,
    SuperUsedInRootModule,
    ItemNotVisible(ModuleItemId, Vec<ModuleId>),
    UnusedImport(UseId),
    RedundantModifier {
        current_modifier: SmolStr,
        previous_modifier: SmolStr,
    },
    ReferenceLocalVariable,
    UnexpectedEnumPattern(semantic::TypeId),
    UnexpectedStructPattern(semantic::TypeId),
    UnexpectedTuplePattern(semantic::TypeId),
    UnexpectedFixedSizeArrayPattern(semantic::TypeId),
    WrongNumberOfTupleElements {
        expected: usize,
        actual: usize,
    },
    WrongNumberOfFixedSizeArrayElements {
        expected: usize,
        actual: usize,
    },
    WrongEnum {
        expected_enum: EnumId,
        actual_enum: EnumId,
    },
    InvalidCopyTraitImpl(InferenceError),
    InvalidDropTraitImpl(InferenceError),
    InvalidImplItem(SmolStr),
    MissingItemsInImpl(Vec<SmolStr>),
    PassPanicAsNopanic {
        impl_function_id: ImplFunctionId,
        trait_id: TraitId,
    },
    PanicableFromNonPanicable,
    PanicableExternFunction,
    PluginDiagnostic(PluginDiagnostic),
    NameDefinedMultipleTimes(SmolStr),
    NonPrivateUseStar,
    NamedArgumentsAreNotSupported,
    ArgPassedToNegativeImpl,
    UnnamedArgumentFollowsNamed,
    NamedArgumentMismatch {
        expected: SmolStr,
        found: SmolStr,
    },
    UnsupportedOutsideOfFunction(UnsupportedOutsideOfFunctionFeatureName),
    UnsupportedConstant,
    DivisionByZero,
    ExternTypeWithImplGenericsNotSupported,
    MissingSemicolon,
    TraitMismatch {
        expected_trt: semantic::ConcreteTraitId,
        actual_trt: semantic::ConcreteTraitId,
    },
    DesnapNonSnapshot,
    InternalInferenceError(InferenceError),
    NoImplementationOfIndexOperator {
        ty: semantic::TypeId,
        inference_errors: TraitInferenceErrors,
    },
    NoImplementationOfTrait {
        ty: semantic::TypeId,
        trait_name: SmolStr,
        inference_errors: TraitInferenceErrors,
    },
    CallExpressionRequiresFunction {
        ty: semantic::TypeId,
        inference_errors: TraitInferenceErrors,
    },
    MultipleImplementationOfIndexOperator(semantic::TypeId),

    UnsupportedInlineArguments,
    RedundantInlineAttribute,
    InlineAttrForExternFunctionNotAllowed,
    InlineAlwaysWithImplGenericArgNotAllowed,
    TailExpressionNotAllowedInLoop,
    ContinueOnlyAllowedInsideALoop,
    BreakOnlyAllowedInsideALoop,
    BreakWithValueOnlyAllowedInsideALoop,
    ReturnNotAllowedInsideALoop,
    ErrorPropagateNotAllowedInsideALoop,
    ImplicitPrecedenceAttrForExternFunctionNotAllowed,
    RedundantImplicitPrecedenceAttribute,
    UnsupportedImplicitPrecedenceArguments,
    UnsupportedFeatureAttrArguments,
    UnsupportedAllowAttrArguments,
    UnsupportedPubArgument,
    UnknownStatementAttribute,
    InlineMacroNotFound(SmolStr),
    InlineMacroFailed(SmolStr),
    UnknownGenericParam(SmolStr),
    PositionalGenericAfterNamed,
    GenericArgDuplicate(SmolStr),
    TooManyGenericArguments {
        expected: usize,
        actual: usize,
    },
    GenericArgOutOfOrder(SmolStr),
    CouponForExternFunctionNotAllowed,
    CouponArgumentNoModifiers,
    /// Coupons are disabled in the current crate.
    CouponsDisabled,
    FixedSizeArrayTypeNonSingleType,
    FixedSizeArrayTypeEmptySize,
    FixedSizeArrayNonNumericSize,
    FixedSizeArrayNonSingleValue,
    FixedSizeArraySizeTooBig,
    SelfNotSupportedInContext,
    SelfMustBeFirst,
    DerefCycle {
        deref_chain: String,
    },
    CompilerTraitReImplementation {
        trait_id: TraitId,
    },
    ClosureInGlobalScope,
    MaybeMissingColonColon,
    CallingShadowedFunction {
        shadowed_function_name: SmolStr,
    },
    RefClosureArgument,
    MutableCapturedVariable,
    NonTraitTypeConstrained {
        identifier: SmolStr,
        concrete_trait_id: ConcreteTraitId,
    },
    DuplicateTypeConstraint {
        concrete_trait_type_id: ConcreteTraitTypeId,
    },
    TypeConstraintsSyntaxNotEnabled,
}

/// The kind of an expression with multiple possible return types.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum MultiArmExprKind {
    If,
    Match,
    Loop,
}

impl SemanticDiagnosticKind {
    pub fn error_code(&self) -> Option<ErrorCode> {
        Some(match &self {
            Self::UnusedVariable => error_code!(E0001),
            Self::CannotCallMethod { .. } => {
                error_code!(E0002)
            }
            Self::MissingMember(_) => error_code!(E0003),
            _ => return None,
        })
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum NotFoundItemType {
    Identifier,
    Function,
    Type,
    Trait,
    Impl,
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum UnsupportedOutsideOfFunctionFeatureName {
    ReturnStatement,
    ErrorPropagate,
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ElementKind {
    Constant,
    Variable,
    Module,
    Function,
    TraitFunction,
    Type,
    Variant,
    Trait,
    Impl,
}
impl From<&ResolvedConcreteItem> for ElementKind {
    fn from(val: &ResolvedConcreteItem) -> Self {
        match val {
            ResolvedConcreteItem::Constant(_) => ElementKind::Constant,
            ResolvedConcreteItem::Module(_) => ElementKind::Module,
            ResolvedConcreteItem::Function(_) => ElementKind::Function,
            ResolvedConcreteItem::TraitFunction(_) => ElementKind::TraitFunction,
            ResolvedConcreteItem::Type(_) => ElementKind::Type,
            ResolvedConcreteItem::Variant(_) => ElementKind::Variant,
            ResolvedConcreteItem::Trait(_) => ElementKind::Trait,
            ResolvedConcreteItem::Impl(_) => ElementKind::Impl,
        }
    }
}
impl From<&ResolvedGenericItem> for ElementKind {
    fn from(val: &ResolvedGenericItem) -> Self {
        match val {
            ResolvedGenericItem::GenericConstant(_) => ElementKind::Constant,
            ResolvedGenericItem::Module(_) => ElementKind::Module,
            ResolvedGenericItem::GenericFunction(_) => ElementKind::Function,
            ResolvedGenericItem::TraitFunction(_) => ElementKind::TraitFunction,
            ResolvedGenericItem::GenericType(_) | ResolvedGenericItem::GenericTypeAlias(_) => {
                ElementKind::Type
            }
            ResolvedGenericItem::Variant(_) => ElementKind::Variant,
            ResolvedGenericItem::Trait(_) => ElementKind::Trait,
            ResolvedGenericItem::Impl(_) | ResolvedGenericItem::GenericImplAlias(_) => {
                ElementKind::Impl
            }
            ResolvedGenericItem::Variable(_) => ElementKind::Variable,
        }
    }
}
impl Display for ElementKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let res = match self {
            ElementKind::Constant => "constant",
            ElementKind::Variable => "variable",
            ElementKind::Module => "module",
            ElementKind::Function => "function",
            ElementKind::TraitFunction => "function",
            ElementKind::Type => "type",
            ElementKind::Variant => "variant",
            ElementKind::Trait => "trait",
            ElementKind::Impl => "impl",
        };
        write!(f, "{res}")
    }
}

/// A list of trait functions and the inference errors that occurred while trying to infer them.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct TraitInferenceErrors {
    pub traits_and_errors: Vec<(TraitFunctionId, InferenceError)>,
}
impl TraitInferenceErrors {
    /// Is the error list empty.
    fn is_empty(&self) -> bool {
        self.traits_and_errors.is_empty()
    }
    /// Format the list of errors.
    fn format(&self, db: &(dyn SemanticGroup + 'static)) -> String {
        self.traits_and_errors
            .iter()
            .map(|(trait_function_id, inference_error)| {
                format!(
                    "Candidate `{}` inference failed with: {}",
                    trait_function_id.full_path(db.upcast()),
                    inference_error.format(db)
                )
            })
            .join("\n")
    }
}