Class BugChecker

java.lang.Object
com.google.errorprone.bugpatterns.BugChecker
All Implemented Interfaces:
Suppressible, Serializable
Direct Known Subclasses:
AbstractAsKeyOfSetOrMap, AbstractLockMethodChecker, AbstractMockChecker, AbstractMustBeClosedChecker, AbstractReferenceEquality, AbstractReturnValueIgnored, AbstractToString, AlmostJavadoc, AmbiguousMethodReference, AndroidInjectionBeforeSuper, AnnotateFormatMethod, AnnotationPosition, ApiDiffChecker, ArgumentSelectionDefectChecker, ArrayEquals, ArrayFillIncompatibleType, ArrayHashCode, ArraysAsListPrimitiveArray, AssertEqualsArgumentOrderChecker, AssertFalse, AssertionFailureIgnored, AssertThrowsMultipleStatements, AssignmentToMock, AssistedInjectAndInjectOnConstructors, AssistedInjectAndInjectOnSameConstructor, AssistedInjectScoping, AssistedParameters, AsyncCallableReturnsNull, AsyncFunctionReturnsNull, AutoFactoryAtInject, AutoValueConstructorOrderChecker, AutoValueFinalMethods, AutoValueImmutableFields, AutoValueSubclassLeaked, BadAnnotationImplementation, BadComparable, BadImport, BadInstanceof, BadShiftAmount, BigDecimalEquals, BigDecimalLiteralDouble, BinderIdentityRestoredDangerously, BindingToUnqualifiedCommonType, BooleanParameter, BoxedPrimitiveConstructor, BundleDeserializationCast, ByteBufferBackingArray, CacheLoaderNull, CannotMockFinalClass, CanonicalDuration, CatchAndPrintStackTrace, CatchFail, CatchingUnchecked, ChainedAssertionLosesContext, ChainingConstructorIgnoresParameter, CheckedExceptionNotThrown, CheckNotNullMultipleTimes, ClassCanBeStatic, ClassName, ClassNamedLikeTypeParameter, ClassNewInstance, CloseableProvides, CollectionIncompatibleType, CollectionToArraySafeParameter, CollectionUndefinedEquality, CollectorShouldNotUseState, ComparableAndComparator, ComparableType, CompareToZero, ComparingThisWithNull, ComparisonContractViolated, ComparisonOutOfRange, CompatibleWithMisuse, CompileTimeConstantChecker, ComplexBooleanConstant, ComputeIfAbsentAmbiguousReference, ConditionalExpressionNumericPromotion, ConstantField, ConstantOverflow, ConstantPatternCompile, DateChecker, DateFormatConstant, DeadException, DeadThread, DeduplicateConstants, DefaultCharset, DefaultPackage, DepAnn, DescribeMatch, DifferentNameButSame, DiscardedPostfixExpression, DivZero, DoNotCallChecker, DoNotCallSuggester, DoubleBraceInitialization, DoubleCheckedLocking, DuplicateMapKeys, DurationFrom, DurationGetTemporalUnit, DurationTemporalUnit, DurationToLongTimeUnit, EmptyBlockTag, EmptyCatch, EmptyIfStatement, EmptySetMultibindingContributions, EmptyTopLevelDeclaration, EqualsBrokenForNull, EqualsGetClass, EqualsHashCode, EqualsIncompatibleType, EqualsNaN, EqualsReference, EqualsUnsafeCast, EqualsUsingHashCode, EqualsWrongThing, EscapedEntity, ExpectedExceptionChecker, ExtendingJUnitAssert, ExtendsAutoValue, FallThrough, FieldCanBeFinal, FieldCanBeLocal, FieldCanBeStatic, Finally, FloatCast, FloatingPointAssertionWithinEpsilon, FloatingPointLiteralPrecision, ForEachIterable, FormatString, FormatStringAnnotationChecker, ForOverrideChecker, FragmentInjection, FragmentNotInstantiable, FromTemporalAccessor, FunctionalInterfaceClash, FunctionalInterfaceMethodChanged, FuturesGetCheckedIllegalExceptionType, FuzzyEqualsShouldNotBeUsedInEqualsMethod, GetClassOnAnnotation, GetClassOnClass, GetClassOnEnum, GuardedByChecker, HardCodedSdCardPath, HashCodeToString, HashtableContains, HidingField, IdentityBinaryExpression, IdentityHashMapBoxing, IdentityHashMapUsage, ImmutableAnnotationChecker, ImmutableChecker, ImmutableEnumChecker, ImmutableModification, ImmutableRefactoring, ImplementAssertionWithChaining, Incomparable, IncompatibleArgumentType, IncompatibleModifiersChecker, InconsistentCapitalization, InconsistentHashCode, InconsistentOverloads, IncrementInForLoopAndHeader, IndexOfChar, InexactVarargsConditional, InfiniteRecursion, InheritDoc, InitializeInline, InjectedConstructorAnnotations, InjectOnConstructorOfAbstractClass, InjectOnFinalField, InjectOnMemberAndConstructor, InlineFormatString, InputStreamSlowMultibyteRead, InsecureCipherMode, InstanceOfAndCastMatchWrongType, InstantTemporalUnit, InterfaceWithOnlyStatics, InterruptedExceptionSwallowed, IntLongMath, InvalidBlockTag, InvalidInlineTag, InvalidJavaTimeConstant, InvalidLink, InvalidParam, InvalidPatternSyntax, InvalidTargetingOnScopingAnnotation, InvalidThrows, InvalidThrowsLink, InvalidTimeZoneID, InvalidZoneId, IsInstanceIncompatibleType, IsInstanceOfClass, IsLoggableTagLength, IterableAndIterator, IterablePathParameter, JavaDurationGetSecondsGetNano, JavaDurationWithNanos, JavaDurationWithSeconds, JavaInstantGetSecondsGetNano, JavaLangClash, JavaLocalDateTimeGetNano, JavaLocalTimeGetNano, JavaPeriodGetDays, JavaTimeDefaultTimeZone, JavaUtilDateChecker, JavaxInjectOnAbstractMethod, JavaxInjectOnFinalField, JdkObsolete, JMockTestWithoutRunWithOrRuleAnnotation, JodaDurationConstructor, JodaDurationWithMillis, JodaInstantWithMillis, JodaNewPeriod, JodaPlusMinusLong, JodaTimeConverterManager, JodaToSelf, JodaWithDurationAddedLong, JUnit3FloatingPointComparisonWithoutDelta, JUnit3TestNotRun, JUnit4ClassAnnotationNonStatic, JUnit4ClassUsedInJUnit3, JUnit4SetUpNotRun, JUnit4TearDownNotRun, JUnit4TestNotRun, JUnitAmbiguousTestClass, JUnitAssertSameCheck, LambdaFunctionalInterface, LiteByteStringUtf8, LiteEnumValueOf, LocalDateTemporalAmount, LockNotBeforeTry, LockOnBoxedPrimitive, LogicalAssignment, LongLiteralLowerCaseSuffix, LoopConditionChecker, LossyPrimitiveCompare, MathAbsoluteRandom, MathRoundIntLong, MemberName, MethodCanBeStatic, MislabeledAndroidString, MissingCasesInEnumSwitch, MissingDefault, MissingFail, MissingOverride, MissingSummary, MissingSuperCall, MissingTestCall, MisusedDateFormat, MixedArrayDimensions, MixedDescriptors, MixedMutabilityReturnType, MockitoUsage, ModifiedButNotUsed, ModifyCollectionInEnhancedForLoop, ModifyingCollectionWithItself, ModifySourceCollectionInStream, MoreThanOneInjectableConstructor, MoreThanOneQualifier, MoreThanOneScopeAnnotationOnClass, MultipleParallelOrSequentialCalls, MultipleTopLevelClasses, MultipleUnaryOperatorsInMethodCall, MultiVariableDeclaration, MutableConstantField, MutableMethodReturnType, MutablePublicArray, NarrowingCompoundAssignment, NCopiesOfChar, NestedInstanceOfConditions, NoAllocationChecker, NoFunctionalReturnType, NonAtomicVolatileUpdate, NonCanonicalStaticImport, NonCanonicalStaticMemberImport, NonCanonicalType, NonFinalCompileTimeConstant, NonOverridingEquals, NonRuntimeAnnotation, NullableConstructor, NullablePrimitive, NullableVoid, NullOptional, NullTernary, ObjectsHashCodePrimitive, OperatorPrecedence, OptionalMapToOptional, OptionalNotPresent, OrphanedFormatString, OutlineNone, OverlappingQualifierAndScopeAnnotation, Overrides, OverridesGuiceInjectableMethod, OverridesJavaxInjectableMethod, OverrideThrowableToString, PackageInfo, PackageLocation, ParameterComment, ParameterName, ParameterNotNullable, ParametersButNotParameterized, ParcelableCreator, PeriodFrom, PeriodGetTemporalUnit, PeriodTimeMath, PreconditionsCheckNotNullRepeated, PreconditionsInvalidPlaceholder, PreferJavaTimeOverload, PrimitiveArrayPassedToVarargsMethod, PrimitiveAtomicReference, PrivateConstructorForNoninstantiableModule, PrivateConstructorForUtilityClass, PrivateSecurityContractProtoAccess, ProtectedMembersInFinalClass, ProtocolBufferOrdinal, ProtoDurationGetSecondsGetNano, ProtoFieldNullComparison, ProtoRedundantSet, ProtoStringFieldReferenceEquality, ProtoTimestampGetSecondsGetNano, ProtoTruthMixedDescriptors, ProvidesMethodOutsideOfModule, ProvidesNull, PublicConstructorForAbstractClass, QualifierOrScopeOnInjectMethod, QualifierWithTypeUse, RandomCast, RandomModInteger, ReachabilityFenceUsage, RedundantCondition, RedundantOverride, RedundantThrows, RefersToDaggerCodegen, RemoveUnusedImports, RequiredModifiersChecker, RestrictedApiChecker, ReturnFromVoid, SameNameButDifferent, ScopeAnnotationOnInterfaceOrAbstractClass, ScopeOnModule, ScopeOrQualifierAnnotationRetention, SelfAssignment, SelfComparison, SelfEquals, ShortCircuitBoolean, ShouldHaveEvenArgs, SizeGreaterThanOrEqualsZero, StaticAssignmentInConstructor, StaticGuardedByInstance, StaticMockMember, StaticOrDefaultInterfaceMethod, StaticQualifiedUsingExpression, StreamToIterable, StringBuilderInitWithChar, StringSplitter, StronglyTypeTime, SubstringOfZero, SuppressWarningsDeprecated, SuppressWarningsWithoutExplanation, SwigMemoryLeak, SwitchDefault, SynchronizeOnNonFinalField, SystemExitOutsideMain, TemporalAccessorGetChronoField, TestExceptionChecker, TheoryButNoTheories, ThreadJoinLoop, ThreadLocalUsage, ThreadPriorityCheck, ThreeLetterTimeZoneID, ThrowIfUncheckedKnownChecked, ThrowNull, ThrowSpecificExceptions, ThrowsUncheckedException, TimeUnitConversionChecker, TimeUnitMismatch, ToStringReturnsNull, TransientMisuse, TruthAssertExpected, TruthConstantAsserts, TruthGetOrDefault, TruthIncompatibleType, TruthSelfEquals, TryFailRefactoring, TryFailThrowable, TypeEqualsChecker, TypeNameShadowing, TypeParameterNaming, TypeParameterQualifier, TypeParameterShadowing, TypeParameterUnusedInFormals, UndefinedEquals, UnescapedEntity, UngroupedOverloads, UnnecessarilyFullyQualified, UnnecessarilyVisible, UnnecessaryAnonymousClass, UnnecessaryBoxedAssignment, UnnecessaryBoxedVariable, UnnecessaryCheckNotNull, UnnecessaryDefaultInEnumSwitch, UnnecessaryLambda, UnnecessaryMethodInvocationMatcher, UnnecessaryParentheses, UnnecessarySetDefault, UnnecessaryStaticImport, UnnecessaryTypeArgument, UnsafeFinalization, UnsafeLocaleUsage, UnsafeReflectiveConstructionCast, UnsynchronizedOverridesSynchronized, UnusedAnonymousClass, UnusedCollectionModifiedInPlace, UnusedException, UnusedMethod, UnusedNestedClass, UnusedVariable, URLEqualsHashCode, UrlInSee, UseBinds, UseCorrectAssertInTests, UseTimeInScope, VarChecker, VariableNameSameAsType, VarTypeName, WaitNotInLoop, WakelockReleasedDangerously, WildcardImport, WithSignatureDiscouraged, WrongOneof, WrongParameterPackage, XorPower

public abstract class BugChecker
extends Object
implements Suppressible, Serializable
A base class for implementing bug checkers. The BugChecker supplies a Scanner implementation for this checker, making it easy to use a single checker. Subclasses should also implement one or more of the *Matcher interfaces in this class to declare which tree node types to match against.
Author:
Colin Decker, Eddie Aftandilian (eaftan@google.com)
See Also:
Serialized Form
  • Constructor Details

    • BugChecker

      public BugChecker()
  • Method Details

    • describeMatch

      @CheckReturnValue protected Description describeMatch​(com.sun.source.tree.Tree node, Fix fix)
      Helper to create a Description for the common case where there is a fix.
    • describeMatch

      @CheckReturnValue protected Description describeMatch​(com.sun.tools.javac.tree.JCTree node, Fix fix)
      Helper to create a Description for the common case where there is a fix.
    • describeMatch

      @CheckReturnValue protected Description describeMatch​(com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition position, Fix fix)
      Helper to create a Description for the common case where there is a fix.
    • describeMatch

      @CheckReturnValue protected Description describeMatch​(com.sun.source.tree.Tree node)
      Helper to create a Description for the common case where there is no fix.
    • describeMatch

      @CheckReturnValue protected Description describeMatch​(com.sun.source.tree.Tree node, Optional<? extends Fix> fix)
      Helper to create a Description for the common case where there is an Optional fix.
    • describeMatch

      @CheckReturnValue protected Description describeMatch​(com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition position, Optional<? extends Fix> fix)
      Helper to create a Description for the common case where there is an Optional fix.
    • buildDescription

      @CheckReturnValue public Description.Builder buildDescription​(com.sun.source.tree.Tree node)
      Returns a Description builder, which allows you to customize the diagnostic with a custom message or multiple fixes.
    • buildDescription

      @CheckReturnValue public Description.Builder buildDescription​(com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition position)
      Returns a Description builder, which allows you to customize the diagnostic with a custom message or multiple fixes.
    • buildDescription

      @CheckReturnValue public Description.Builder buildDescription​(com.sun.tools.javac.tree.JCTree tree)
      Returns a Description builder, which allows you to customize the diagnostic with a custom message or multiple fixes.
    • canonicalName

      public String canonicalName()
      Description copied from interface: Suppressible
      The canonical name of the check.
      Specified by:
      canonicalName in interface Suppressible
    • allNames

      public Set<String> allNames()
      Description copied from interface: Suppressible
      Returns all of the name strings that this checker should respect as part of a @SuppressWarnings annotation.
      Specified by:
      allNames in interface Suppressible
    • message

      public String message()
    • defaultSeverity

      public BugPattern.SeverityLevel defaultSeverity()
    • severity

      public BugPattern.SeverityLevel severity​(Map<String,​BugPattern.SeverityLevel> severities)
    • linkUrl

      public String linkUrl()
    • supportsSuppressWarnings

      public boolean supportsSuppressWarnings()
      Description copied from interface: Suppressible
      Returns true if this checker can be suppressed using @SuppressWarnings.
      Specified by:
      supportsSuppressWarnings in interface Suppressible
    • disableable

      public boolean disableable()
    • customSuppressionAnnotations

      public Set<Class<? extends Annotation>> customSuppressionAnnotations()
      Description copied from interface: Suppressible
      Returns the custom suppression annotations for this checker, if custom suppression is used.
      Specified by:
      customSuppressionAnnotations in interface Suppressible
    • suppressedByAnyOf

      public boolean suppressedByAnyOf​(Set<com.sun.tools.javac.util.Name> annotations, VisitorState s)
      Specified by:
      suppressedByAnyOf in interface Suppressible
    • isSuppressed

      public boolean isSuppressed​(com.sun.source.tree.Tree tree)
      Returns true if the given tree is annotated with a @SuppressWarnings that disables this bug checker.
    • isSuppressed

      public boolean isSuppressed​(com.sun.tools.javac.code.Symbol symbol)
      Returns true if the given symbol is annotated with a @SuppressWarnings that disables this bug checker.
    • equals

      public boolean equals​(Object obj)
      Overrides:
      equals in class Object
    • hashCode

      public int hashCode()
      Overrides:
      hashCode in class Object