-
Notifications
You must be signed in to change notification settings - Fork 380
/
RsDiagnostic.kt
1782 lines (1599 loc) · 63 KB
/
RsDiagnostic.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.utils
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.util.InspectionMessage
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.util.NlsContexts.Tooltip
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.text.StringUtil.pluralize
import com.intellij.psi.PsiElement
import com.intellij.util.ThreeState
import com.intellij.xml.util.XmlStringUtil.escapeString
import org.rust.cargo.project.workspace.PackageOrigin
import org.rust.cargo.toolchain.RustChannel
import org.rust.cargo.toolchain.impl.RustcVersion
import org.rust.ide.annotator.RsAnnotationHolder
import org.rust.ide.annotator.RsErrorAnnotator
import org.rust.ide.annotator.fixes.*
import org.rust.ide.inspections.RsExperimentalChecksInspection
import org.rust.ide.inspections.RsProblemsHolder
import org.rust.ide.inspections.RsTypeCheckInspection
import org.rust.ide.inspections.RsWrongAssocTypeArgumentsInspection
import org.rust.ide.inspections.fixes.*
import org.rust.ide.presentation.render
import org.rust.ide.presentation.renderInsertionSafe
import org.rust.ide.presentation.shortPresentableText
import org.rust.ide.refactoring.implementMembers.ImplementMembersFix
import org.rust.ide.utils.checkMatch.Pattern
import org.rust.ide.utils.import.RsImportHelper.getTypeReferencesInfoFromTys
import org.rust.lang.core.*
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.resolve.ImplLookup
import org.rust.lang.core.resolve.KnownItems
import org.rust.lang.core.resolve.Namespace
import org.rust.lang.core.types.*
import org.rust.lang.core.types.infer.*
import org.rust.lang.core.types.ty.*
import org.rust.lang.utils.RsErrorCode.*
import org.rust.lang.utils.Severity.*
import org.rust.stdext.buildList
import org.rust.stdext.buildMap
private val REF_STR_TY = TyReference(TyStr.INSTANCE, Mutability.IMMUTABLE)
private val MUT_REF_STR_TY = TyReference(TyStr.INSTANCE, Mutability.MUTABLE)
sealed class RsDiagnostic(
val element: PsiElement,
val endElement: PsiElement? = null,
val inspectionClass: Class<*> = RsErrorAnnotator::class.java
) {
abstract fun prepare(): PreparedAnnotation
class TypeError(
element: PsiElement,
private val expectedTy: Ty,
private val actualTy: Ty
) : RsDiagnostic(element, inspectionClass = RsTypeCheckInspection::class.java), TypeFoldable<TypeError> {
private val description: String? = if (expectedTy.hasTyInfer || actualTy.hasTyInfer) {
// if types contain infer types, they will be replaced with more specific (e.g. `{integer}` with `i32`)
// so we capture string representation of types right here
expectedFound(element, expectedTy, actualTy)
} else {
null
}
override fun prepare(): PreparedAnnotation {
return PreparedAnnotation(
ERROR,
E0308,
"mismatched types",
description ?: expectedFound(element, expectedTy, actualTy),
fixes = buildList {
if (element is RsElement) {
if (element is RsExpr) {
addAll(createExprQuickFixes(element))
}
val retFix = ChangeReturnTypeFix.createIfCompatible(element, actualTy)
if (retFix != null) {
add(retFix)
}
}
val parent = element.parent
if (parent is RsLetDecl && parent.typeReference != null) {
val pat = parent.pat
if (pat is RsPatIdent &&
!actualTy.containsTyOfClass(TyUnknown::class.java, TyAnon::class.java)) {
val text = "Change type of `${pat.patBinding.identifier.text ?: "?"}` to `${actualTy.renderInsertionSafe()}`"
add(ConvertLetDeclTypeFix(parent, text, actualTy))
}
}
}
)
}
private fun createExprQuickFixes(element: RsExpr): List<LocalQuickFix> {
return buildList {
if (expectedTy is TyNumeric && isActualTyNumeric()) {
add(AddAsTyFix(element, expectedTy))
} else {
val (lookup, items) = element.implLookupAndKnownItems
if (isFromActualImplForExpected(items, lookup)) {
add(ConvertToTyUsingFromTraitFix(element, expectedTy))
} else { // only check TryFrom if From is not available
val resultErrTy = errTyOfTryFromActualImplForTy(expectedTy, items, lookup)
if (resultErrTy != null) {
add(ConvertToTyUsingTryFromTraitAndUnpackFix(element, expectedTy, resultErrTy))
}
}
// currently it's possible to have `impl FromStr` independently form `impl<'a> From<&'a str>` or
// `impl<'a> TryFrom<&'a str>`, so check for FromStr even if From or TryFrom is available
val resultFromStrErrTy = ifActualIsStrGetErrTyOfFromStrImplForTy(expectedTy, items, lookup)
if (resultFromStrErrTy != null) {
add(ConvertToTyUsingFromStrAndUnpackFix(element, expectedTy, resultFromStrErrTy))
}
if (isToOwnedImplWithExpectedForActual(items, lookup)) {
add(ConvertToOwnedTyFix(element, expectedTy))
}
val stringTy = items.String.asTy()
if (expectedTy.isEquivalentTo(stringTy)
&& (isToStringImplForActual(items, lookup) || isActualTyNumeric())) {
add(ConvertToStringFix(element))
} else if (expectedTy is TyReference) {
if (expectedTy.mutability == Mutability.IMMUTABLE) {
if (isTraitWithTySubstImplForActual(lookup, items.Borrow, expectedTy)) {
add(ConvertToBorrowedTyFix(element, expectedTy))
}
if (isTraitWithTySubstImplForActual(lookup, items.AsRef, expectedTy)) {
add(ConvertToRefTyFix(element, expectedTy))
}
} else if (expectedTy.mutability == Mutability.MUTABLE) {
if (actualTy is TyReference && actualTy.mutability == Mutability.IMMUTABLE) {
add(ChangeRefToMutableFix(element))
}
if (element.isMutable && lookup.coercionSequence(actualTy).all { it !is TyReference || it.mutability.isMut }) {
if (isTraitWithTySubstImplForActual(lookup, items.BorrowMut, expectedTy)) {
add(ConvertToBorrowedTyWithMutFix(element, expectedTy))
}
if (isTraitWithTySubstImplForActual(lookup, items.AsMut, expectedTy)) {
add(ConvertToMutTyFix(element, expectedTy))
}
}
}
} else if (expectedTy is TyAdt && expectedTy.item == items.Result) {
val (expOkTy, expErrTy) = expectedTy.typeArguments
if (expErrTy.isEquivalentTo(errTyOfTryFromActualImplForTy(expOkTy, items, lookup))) {
add(ConvertToTyUsingTryFromTraitFix(element, expOkTy))
}
if (expErrTy.isEquivalentTo(ifActualIsStrGetErrTyOfFromStrImplForTy(expOkTy, items, lookup))) {
add(ConvertToTyUsingFromStrFix(element, expOkTy))
}
}
if (actualTy.isEquivalentTo(stringTy)) {
if (expectedTy.isEquivalentTo(REF_STR_TY)) {
add(ConvertToImmutableStrFix(element))
} else if (expectedTy.isEquivalentTo(MUT_REF_STR_TY)) {
add(ConvertToMutStrFix(element))
}
}
val derefsRefsToExpected = derefRefPathFromActualToExpected(lookup, element)
if (derefsRefsToExpected != null) {
add(ConvertToTyWithDerefsRefsFix(element, expectedTy, derefsRefsToExpected))
}
}
}
}
private fun isActualTyNumeric() = actualTy is TyNumeric || actualTy is TyInfer.IntVar || actualTy is TyInfer.FloatVar
private fun isFromActualImplForExpected(items: KnownItems, lookup: ImplLookup): Boolean {
val fromTrait = items.From ?: return false
return lookup.canSelect(TraitRef(expectedTy, fromTrait.withSubst(actualTy)))
}
private fun errTyOfTryFromActualImplForTy(ty: Ty, items: KnownItems, lookup: ImplLookup): Ty? {
val fromTrait = items.TryFrom ?: return null
val result = lookup.selectProjectionStrict(TraitRef(ty, fromTrait.withSubst(actualTy)),
fromTrait.associatedTypesTransitively.find { it.name == "Error" } ?: return null)
return result.ok()?.value
}
private fun ifActualIsStrGetErrTyOfFromStrImplForTy(ty: Ty, items: KnownItems, lookup: ImplLookup): Ty? {
if (lookup.coercionSequence(actualTy).lastOrNull() !is TyStr) return null
val fromStr = items.FromStr ?: return null
val result = lookup.selectProjectionStrict(
TraitRef(ty, BoundElement(fromStr)),
fromStr.findAssociatedType("Err") ?: return null
)
return result.ok()?.value
}
private fun isToOwnedImplWithExpectedForActual(items: KnownItems, lookup: ImplLookup): Boolean {
val toOwnedTrait = items.ToOwned ?: return false
val result = lookup.selectProjectionStrictWithDeref(
TraitRef(actualTy, BoundElement(toOwnedTrait)),
toOwnedTrait.findAssociatedType("Owned") ?: return false
)
return expectedTy.isEquivalentTo(result.ok()?.value)
}
private fun isToStringImplForActual(items: KnownItems, lookup: ImplLookup): Boolean {
val toStringTrait = items.ToString ?: return false
return lookup.canSelectWithDeref(TraitRef(actualTy, BoundElement(toStringTrait)))
}
private fun isTraitWithTySubstImplForActual(lookup: ImplLookup, trait: RsTraitItem?, ty: TyReference): Boolean =
trait != null && lookup.canSelectWithDeref(TraitRef(actualTy, trait.withSubst(ty.referenced)))
private fun expectedFound(element: PsiElement, expectedTy: Ty, actualTy: Ty): String {
val useQualifiedName = getConflictingNames(element, expectedTy, actualTy)
return "expected `${expectedTy.rendered(useQualifiedName)}`, found `${actualTy.rendered(useQualifiedName)}`"
}
/**
* Try to find a "path" from [actualTy] to [expectedTy] through dereferences and references.
*
* The method works by getting coercion sequence of types for the [actualTy] and sequence of the types that can
* lead to [expectedTy] by adding references. The "expected sequence" is represented by a list of references'
* mutabilities, and a map from the type X to the index i in the list such that if we apply the references from
* 0 (inclusive) to i (exclusive) we will get [expectedTy]. For example for [expectedTy] = `&mut&i32` we will
* have: [mutable, immutable] and {&mut&i32 -> 0, &i32 -> 1, i32 -> 2}. Then, using those data structures, we
* try to find a first type X of the "actual" sequence that is also in the "expected" sequence, and a number of
* dereferences to get from [actualTy] to X and references to get from X to [expectedTy]. Finally we try to
* check if applying the references would agree with the expression's mutability.
*/
private fun derefRefPathFromActualToExpected(lookup: ImplLookup, element: RsElement): DerefRefPath? {
// get all the types that can lead to `expectedTy` by adding references to them
val expectedRefSeq: MutableList<Mutability> = mutableListOf()
val tyToExpectedRefSeq: Map<Ty, Int> = buildMap {
put(expectedTy, 0)
var ty = expectedTy
var i = 1
while (ty is TyReference) {
expectedRefSeq.add(ty.mutability)
ty = ty.referenced
put(ty, i++)
}
}
// get all the types we can get by dereferencing `actualTy`
val actualCoercionSeq = lookup.coercionSequence(actualTy).toList()
var refSeqEnd: Int? = null
// for the first type X in the "actual sequence" that is also in the "expected sequence"; get the number of
// dereferences we need to apply to get to X from `actualTy` and number of references to get to `expectedTy`
val derefs = actualCoercionSeq.indexOfFirst { refSeqEnd = tyToExpectedRefSeq[it]; refSeqEnd != null }
val refs = expectedRefSeq.subList(0, refSeqEnd ?: return null)
// check that mutability of references would not contradict the `element`
val isSuitableMutability = refs.isEmpty() ||
!refs.last().isMut ||
element is RsExpr &&
element.isMutable &&
// covers cases like `let mut x: &T = ...`
actualCoercionSeq.subList(0, derefs + 1).all {
it !is TyReference || it.mutability.isMut
}
if (!isSuitableMutability) return null
return DerefRefPath(derefs, refs)
}
override fun superFoldWith(folder: TypeFolder): TypeError =
TypeError(element, expectedTy.foldWith(folder), actualTy.foldWith(folder))
override fun superVisitWith(visitor: TypeVisitor): Boolean =
expectedTy.visitWith(visitor) || actualTy.visitWith(visitor)
}
class DerefError(
element: PsiElement,
val ty: Ty
) : RsDiagnostic(element, inspectionClass = RsExperimentalChecksInspection::class.java) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0614,
"type ${ty.rendered(getConflictingNames(element, ty))} cannot be dereferenced"
)
}
class AccessError(
element: PsiElement,
private val errorCode: RsErrorCode,
private val itemType: String,
private val fix: MakePublicFix?
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
errorCode,
"$itemType `${element.text}` is private",
fixes = listOfNotNull(fix)
)
}
class StructFieldAccessError(
element: PsiElement,
private val fieldName: String,
private val structName: String,
private val fix: MakePublicFix?
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
if (element.parent is RsStructLiteralField) E0451 else E0616,
"Field `$fieldName` of struct `$structName` is private",
fixes = listOfNotNull(fix)
)
}
class UnsafeError(
element: RsExpr,
private val message: String
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0133,
message,
fixes = listOfNotNull(SurroundWithUnsafeFix(element as RsExpr), AddUnsafeFix.create(element))
)
}
class TypePlaceholderForbiddenError(
element: PsiElement
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0121,
"The type placeholder `_` is not allowed within types on item signatures"
)
}
class ImplDropForNonAdtError(
element: PsiElement
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0120,
"Drop can be only implemented by structs and enums"
)
}
class SelfInStaticMethodError(
element: PsiElement,
private val function: RsFunction
) : RsDiagnostic(element) {
override fun prepare(): PreparedAnnotation {
val fixes = mutableListOf<LocalQuickFix>()
if (function.owner.isImplOrTrait) fixes.add(AddSelfFix(function))
return PreparedAnnotation(
ERROR,
E0424,
"The self keyword was used in a static method",
fixes = fixes
)
}
}
class UnnecessaryVisibilityQualifierError(
element: RsVis
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0449,
"Unnecessary visibility qualifier",
fixes = listOf(RemoveElementFix(element, "visibility qualifier"))
)
}
class UnsafeNegativeImplementationError(
element: PsiElement
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0198,
"Negative implementations are not unsafe"
)
}
class UnsafeTraitImplError(
element: PsiElement,
private val traitName: String
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0199,
errorText()
)
private fun errorText(): String {
return "Implementing the trait `$traitName` is not unsafe"
}
}
class TraitMissingUnsafeImplError(
element: PsiElement,
private val traitName: String
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0200,
errorText(),
fixes = listOfNotNull(AddUnsafeFix.create(element))
)
private fun errorText(): String {
return "The trait `$traitName` requires an `unsafe impl` declaration"
}
}
class IncorrectlyPlacedInlineAttr(
element: PsiElement,
private val attr: RsAttr
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0518,
"Attribute should be applied to function or closure",
fixes = listOf(RemoveAttrFix(attr))
)
}
class TraitMissingUnsafeImplAttributeError(
element: PsiElement,
private val attrRequiringUnsafeImpl: String
) : RsDiagnostic(element) {
override fun prepare(): PreparedAnnotation = PreparedAnnotation(
ERROR,
E0569,
errorText()
)
private fun errorText(): String {
return "Requires an `unsafe impl` declaration due to `#[$attrRequiringUnsafeImpl]` attribute"
}
}
class UnknownMethodInTraitError(
element: PsiElement,
private val member: RsAbstractable,
private val traitName: String
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0407,
errorText()
)
private fun errorText(): String {
return "Method `${member.name}` is not a member of trait `$traitName`"
}
}
class ImplBothCopyAndDropError(
element: PsiElement
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0184,
"Cannot implement both Copy and Drop"
)
}
class DeclMissingFromTraitError(
element: PsiElement,
private val fn: RsFunction,
private val selfParameter: RsSelfParameter
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0185,
errorText()
)
private fun errorText(): String {
return "Method `${fn.name}` has a `${selfParameter.canonicalDecl}` declaration in the impl, but not in the trait"
}
}
class DeclMissingFromImplError(
element: PsiElement,
private val fn: RsFunction,
private val selfParameter: RsSelfParameter?
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0186,
errorText()
)
private fun errorText(): String {
return "Method `${fn.name}` has a `${selfParameter?.canonicalDecl}` declaration in the trait, but not in the impl"
}
}
class ExplicitCallToDrop(
element: PsiElement
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0040,
errorText(),
fixes = listOf(ReplaceWithStdMemDropFix(element.parent)) // e.parent: fn's name -> RsMethodCall or RsCallExpr
)
private fun errorText(): String {
return "Explicit calls to `drop` are forbidden. Use `std::mem::drop` instead"
}
}
class TraitParamCountMismatchError(
element: PsiElement,
private val fn: RsFunction,
private val traitName: String,
private val paramsCount: Int,
private val superParamsCount: Int
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0050,
errorText()
)
private fun errorText(): String {
return "Method `${fn.name}` has $paramsCount ${pluralize("parameter", paramsCount)} but the declaration in trait `$traitName` has $superParamsCount"
}
}
class CastAsBoolError(val castExpr: RsCastExpr) : RsDiagnostic(castExpr) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0054,
"It is not allowed to cast to a bool.",
fixes = listOfNotNull(CompareWithZeroFix.createIfCompatible(castExpr))
)
}
class ConstItemReferToStaticError(element: RsElement, val constContext: RsConstContextKind) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0013,
when (constContext) {
is RsConstContextKind.Constant -> "Const `${constContext.psi.name.orEmpty()}` cannot refer to static " +
"`${element.text}`"
is RsConstContextKind.ConstFn -> "Constant function `${constContext.psi.name.orEmpty()}` cannot refer " +
"to static `${element.text}`"
is RsConstContextKind.EnumVariantDiscriminant -> "Enum variant `${constContext.psi.name.orEmpty()}`'s " +
"discriminant value cannot refer to static `${element.text}`"
RsConstContextKind.ArraySize -> "Array size cannot refer to static `${element.text}`"
RsConstContextKind.ConstGenericArgument -> "Const generic argument cannot refer to static " +
"`${element.text}`"
}
)
}
class IncorrectFunctionArgumentCountError(
element: PsiElement,
private val expectedCount: Int,
private val realCount: Int,
private val functionType: FunctionType = FunctionType.FUNCTION,
private val fixes: List<LocalQuickFix> = emptyList(),
private val textAttributes: TextAttributesKey? = null
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
functionType.errorCode,
errorText(),
fixes = fixes,
textAttributes = textAttributes
)
private fun errorText(): String {
return "This function takes${if (functionType.variadic) " at least" else ""}" +
" $expectedCount ${pluralize("parameter", expectedCount)}" +
" but $realCount ${pluralize("parameter", realCount)}" +
" ${if (realCount == 1) "was" else "were"} supplied"
}
enum class FunctionType(val variadic: Boolean, val errorCode: RsErrorCode) {
VARIADIC_FUNCTION(true, E0060),
FUNCTION(false, E0061),
CLOSURE(false, E0057)
}
}
class ReturnMustHaveValueError(
element: PsiElement
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0069,
"`return;` in a function whose return type is not `()`"
)
}
class DuplicateEnumDiscriminant(
variant: RsEnumVariant,
private val id: Long
) : RsDiagnostic(variant.variantDiscriminant?.expr ?: variant) {
override fun prepare(): PreparedAnnotation = PreparedAnnotation(
ERROR,
E0081,
"Discriminant value `$id` already exists"
)
}
class ReprForEmptyEnumError(
val attr: RsAttr,
element: PsiElement = attr.metaItem.path?.referenceNameElement ?: attr.metaItem
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0084,
"Enum with no variants can't have `repr` attribute",
fixes = listOf(RemoveAttrFix(attr))
)
}
class DuplicateFieldError(
element: PsiElement,
private val fieldName: String
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0124,
errorText()
)
private fun errorText(): String {
return "Field `$fieldName` is already declared"
}
}
sealed class InvalidStartAttrError(
element: PsiElement
) : RsDiagnostic(element) {
class ReturnMismatch(element: PsiElement) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0132,
"Functions with a `start` attribute must return `isize`"
)
}
class InvalidOwner(element: PsiElement) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0132,
"Start attribute can be placed only on functions"
)
}
class InvalidParam(
element: PsiElement,
private val num: Int = -1
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0132,
"Functions with a `start` attribute must have " + when (num) {
0 -> "`isize` as first parameter"
1 -> "`*const *const u8` as second parameter"
else -> "the following signature: `fn(isize, *const *const u8) -> isize`"
}
)
}
}
class DuplicateEnumVariantError(
element: PsiElement,
private val fieldName: String
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0428,
errorText()
)
private fun errorText(): String {
return "Enum variant `$fieldName` is already declared"
}
}
class ReservedLifetimeNameError(
element: PsiElement,
private val lifetimeName: String
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0262,
errorText()
)
private fun errorText(): String {
return "`$lifetimeName` is a reserved lifetime name"
}
}
class DuplicateLifetimeError(
element: PsiElement,
private val fieldName: String
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0263,
errorText()
)
private fun errorText(): String {
return "Lifetime name `$fieldName` declared twice in the same scope"
}
}
class LoopOnlyKeywordUsedInClosureError(
element: PsiElement
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0267,
"`${element.text}` cannot be used in closures, only inside `loop` and `while` blocks"
)
}
class LoopOnlyKeywordUsedOutsideOfLoopError(
element: PsiElement
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0268,
"`${element.text}` may only be used inside `loop` and `while` blocks"
)
}
class DuplicateBindingError(
element: PsiElement,
private val fieldName: String
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0415,
errorText()
)
private fun errorText(): String {
return "Identifier `$fieldName` is bound more than once in this parameter list"
}
}
class RepeatedIdentifierInPattern(
repeatedIdentifier: RsPatBinding,
private val name: String
) : RsDiagnostic(repeatedIdentifier) {
override fun prepare(): PreparedAnnotation {
return PreparedAnnotation(
ERROR,
E0416,
"Identifier `$name` is bound more than once in the same pattern"
)
}
}
class DuplicateTypeParameterError(
element: PsiElement,
private val fieldName: String
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0403,
errorText()
)
private fun errorText(): String {
return "The name `$fieldName` is already used for a type parameter in this type parameter list"
}
}
class NotTraitError(
element: PsiElement,
private val found: RsItemElement
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0404,
errorText()
)
private fun errorText(): String {
val itemKind = found.itemKindName
val name = found.name
return "Expected trait, found $itemKind `$name`"
}
}
class DuplicateAssociatedItemError(
element: PsiElement,
private val fieldName: String
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0201,
errorText()
)
private fun errorText(): String {
return "Duplicate definitions with name `$fieldName`"
}
}
/**
* [E0428] - item vs item
* [E0255] - item vs import
* [E0260] - item vs extern crate
* [E0252] - import vs import
* [E0254] - import vs extern crate
* [E0259] - extern crate vs extern crate
*/
class DuplicateDefinitionError private constructor(
element: PsiElement,
private val itemType: String,
private val itemName: String,
private val scopeType: String,
private val errorCode: RsErrorCode,
) : RsDiagnostic(element) {
constructor(
element: PsiElement,
itemNamespace: Namespace,
itemName: String,
scope: PsiElement,
errorCode: RsErrorCode,
) : this(element, itemNamespace.itemName, itemName, scope.formatScope(), errorCode)
override fun prepare() = PreparedAnnotation(ERROR, errorCode, errorText())
private fun errorText(): String = when {
element.ancestorOrSelf<RsUseSpeck>() != null ->
"A second item with name `$itemName` imported. Try to use an alias."
errorCode == E0259 ->
"A second extern crate with name `$itemName` imported"
else ->
"A $itemType named `$itemName` has already been defined in this $scopeType"
}
companion object {
private fun PsiElement.formatScope(): String =
when (this) {
is RsBlock -> "block"
is RsMod, is RsForeignModItem -> "module"
is RsTraitItem -> "trait"
else -> "scope"
}
}
}
class ImplSizedError(
element: PsiElement
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0322,
"Explicit impls for the `Sized` trait are not permitted"
)
}
class ImplUnsizeError(
element: PsiElement
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0328,
"Explicit impls for the `Unsize` trait are not permitted"
)
}
class ConstTraitFnError(
element: PsiElement
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0379,
"Trait functions cannot be declared const"
)
}
class UndeclaredLabelError(
element: RsMandatoryReferenceElement
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0426,
errorText()
)
private fun errorText(): String {
return "Use of undeclared label `${element.text}`"
}
}
class UndeclaredLifetimeError(
val lifetime: RsLifetime
) : RsDiagnostic(lifetime) {
override fun prepare(): PreparedAnnotation {
return PreparedAnnotation(
ERROR,
E0261,
errorText(),
fixes = listOfNotNull(CreateLifetimeParameterFromUsageFix.tryCreate(lifetime))
)
}
private fun errorText(): String {
return "Use of undeclared lifetime name `${element.text}`"
}
}
class InBandAndExplicitLifetimesError(
val lifetime: RsLifetime
) : RsDiagnostic(lifetime) {
override fun prepare(): PreparedAnnotation {
return PreparedAnnotation(
ERROR,
E0688,
errorText(),
fixes = listOfNotNull(CreateLifetimeParameterFromUsageFix.tryCreate(lifetime))
)
}
private fun errorText(): String = "Cannot mix in-band and explicit lifetime definitions"
}
class TraitItemsMissingImplError(
startElement: PsiElement,
endElement: PsiElement,
private val missing: String,
private val impl: RsImplItem
) : RsDiagnostic(startElement, endElement) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0046,
errorText(),
fixes = listOf(ImplementMembersFix(impl))
)
private fun errorText(): String {
return "Not all trait items implemented, missing: $missing"
}
}
class CrateNotFoundError(
startElement: PsiElement,
private val crateName: String
) : RsDiagnostic(startElement) {
override fun prepare() = PreparedAnnotation(
UNKNOWN_SYMBOL,
E0463,
errorText()
)
private fun errorText(): String {
return "Can't find crate for `$crateName`"
}
}
class SizedTraitIsNotImplemented(
element: RsTypeReference,
private val ty: Ty
) : RsDiagnostic(element) {
override fun prepare() = PreparedAnnotation(
ERROR,
E0277,
header = "the trait bound `$ty: std::marker::Sized` is not satisfied",
description = "`$ty` does not have a constant size known at compile-time",
fixes = listOf(ConvertToReferenceFix(element), ConvertToBoxFix(element))
)
}
class SuperTraitIsNotImplemented(
element: RsTraitRef,
type: Ty,
private val missingTrait: String
) : RsDiagnostic(element) {
private val typeText = type.shortPresentableText
override fun prepare() = PreparedAnnotation(
ERROR,
E0277,
header = "the trait bound `$typeText: $missingTrait` is not satisfied",
description = "the trait `$missingTrait` is not implemented for `$typeText`"
)
}
class ExperimentalFeature(
element: PsiElement,