1# python3 2# Copyright (C) 2019 The Android Open Source Project 3# 4# Licensed under the Apache License, Version 2.0 (the "License"); 5# you may not use this file except in compliance with the License. 6# You may obtain a copy of the License at 7# 8# http://www.apache.org/licenses/LICENSE-2.0 9# 10# Unless required by applicable law or agreed to in writing, software 11# distributed under the License is distributed on an "AS IS" BASIS, 12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13# See the License for the specific language governing permissions and 14# limitations under the License. 15 16"""Warning patterns for Java compiler tools.""" 17 18# No need of doc strings for trivial small functions. 19# pylint:disable=missing-function-docstring 20 21# pylint:disable=relative-beyond-top-level 22from .cpp_warn_patterns import compile_patterns 23from .severity import Severity 24 25 26def java_warn(severity, description, pattern_list): 27 return { 28 'category': 'Java', 29 'severity': severity, 30 'description': 'Java: ' + description, 31 'patterns': pattern_list 32 } 33 34 35def java_high(description, pattern_list): 36 return java_warn(Severity.HIGH, description, pattern_list) 37 38 39def java_medium(description, pattern_list): 40 return java_warn(Severity.MEDIUM, description, pattern_list) 41 42 43def warn_with_name(name, severity, description=None): 44 if description is None: 45 description = name 46 return java_warn(severity, description, 47 [r'.*\.java:.*: warning: .+ \[' + name + r'\]$', 48 r'.*\.java:.*: warning: \[' + name + r'\] .+']) 49 50 51def high(name, description=None): 52 return warn_with_name(name, Severity.HIGH, description) 53 54 55def medium(name, description=None): 56 return warn_with_name(name, Severity.MEDIUM, description) 57 58 59def low(name, description=None): 60 return warn_with_name(name, Severity.LOW, description) 61 62 63warn_patterns = [ 64 # pylint does not recognize g-inconsistent-quotes 65 # pylint:disable=line-too-long,bad-option-value,g-inconsistent-quotes 66 # Warnings from Javac 67 java_medium('Use of deprecated', 68 [r'.*: warning: \[deprecation\] .+', 69 r'.*: warning: \[removal\] .+ has been deprecated and marked for removal$']), 70 java_medium('Incompatible SDK implementation', 71 [r'.*\.java:.*: warning: @Implementation .+ has .+ not .+ as in the SDK ']), 72 medium('unchecked', 'Unchecked conversion'), 73 java_medium('No annotation method', 74 [r'.*\.class\): warning: Cannot find annotation method .+ in']), 75 java_medium('No class/method in SDK ...', 76 [r'.*\.java:.*: warning: No such (class|method) .* for SDK']), 77 java_medium('Unknown enum constant', 78 [r'unknown_source_file: warning: unknown enum constant .+']), 79 # Warnings generated by Error Prone 80 java_medium('Non-ascii characters used, but ascii encoding specified', 81 [r".*: warning: unmappable character for encoding ascii"]), 82 java_medium('Non-varargs call of varargs method with inexact argument type for last parameter', 83 [r".*: warning: non-varargs call of varargs method with inexact argument type for last parameter"]), 84 java_medium('Unchecked method invocation', 85 [r".*: warning: \[unchecked\] unchecked method invocation: .+ in class .+"]), 86 java_medium('Unchecked conversion', 87 [r".*: warning: \[unchecked\] unchecked conversion"]), 88 java_medium('_ used as an identifier', 89 [r".*: warning: '_' used as an identifier"]), 90 java_medium('hidden superclass', 91 [r".*: warning: .* stripped of .* superclass .* \[HiddenSuperclass\]"]), 92 java_high('Use of internal proprietary API', 93 [r".*: warning: .* is internal proprietary API and may be removed"]), 94 low('BooleanParameter', 95 'Use parameter comments to document ambiguous literals'), 96 low('ClassNamedLikeTypeParameter', 97 'This class\'s name looks like a Type Parameter.'), 98 low('ConstantField', 99 'Field name is CONSTANT_CASE, but field is not static and final'), 100 low('EmptySetMultibindingContributions', 101 '@Multibinds is a more efficient and declarative mechanism for ensuring that a set multibinding is present in the graph.'), 102 low('ExpectedExceptionRefactoring', 103 'Prefer assertThrows to ExpectedException'), 104 low('FieldCanBeFinal', 105 'This field is only assigned during initialization; consider making it final'), 106 low('FieldMissingNullable', 107 'Fields that can be null should be annotated @Nullable'), 108 low('ImmutableRefactoring', 109 'Refactors uses of the JSR 305 @Immutable to Error Prone\'s annotation'), 110 low('LambdaFunctionalInterface', 111 u'Use Java\'s utility functional interfaces instead of Function\u003cA, B> for primitive types.'), 112 low('MethodCanBeStatic', 113 'A private method that does not reference the enclosing instance can be static'), 114 low('MixedArrayDimensions', 115 'C-style array declarations should not be used'), 116 low('MultiVariableDeclaration', 117 'Variable declarations should declare only one variable'), 118 low('MultipleTopLevelClasses', 119 'Source files should not contain multiple top-level class declarations'), 120 low('MultipleUnaryOperatorsInMethodCall', 121 'Avoid having multiple unary operators acting on the same variable in a method call'), 122 low('OnNameExpected', 123 'OnNameExpected naming style'), 124 low('PackageLocation', 125 'Package names should match the directory they are declared in'), 126 low('ParameterComment', 127 'Non-standard parameter comment; prefer `/* paramName= */ arg`'), 128 low('ParameterNotNullable', 129 'Method parameters that aren\'t checked for null shouldn\'t be annotated @Nullable'), 130 low('PrivateConstructorForNoninstantiableModule', 131 'Add a private constructor to modules that will not be instantiated by Dagger.'), 132 low('PrivateConstructorForUtilityClass', 133 'Utility classes (only static members) are not designed to be instantiated and should be made noninstantiable with a default constructor.'), 134 low('RemoveUnusedImports', 135 'Unused imports'), 136 low('ReturnMissingNullable', 137 'Methods that can return null should be annotated @Nullable'), 138 low('ScopeOnModule', 139 'Scopes on modules have no function and will soon be an error.'), 140 low('SwitchDefault', 141 'The default case of a switch should appear at the end of the last statement group'), 142 low('TestExceptionRefactoring', 143 'Prefer assertThrows to @Test(expected=...)'), 144 low('ThrowsUncheckedException', 145 'Unchecked exceptions do not need to be declared in the method signature.'), 146 low('TryFailRefactoring', 147 'Prefer assertThrows to try/fail'), 148 low('TypeParameterNaming', 149 'Type parameters must be a single letter with an optional numeric suffix, or an UpperCamelCase name followed by the letter \'T\'.'), 150 low('UngroupedOverloads', 151 'Constructors and methods with the same name should appear sequentially with no other code in between. Please re-order or re-name methods.'), 152 low('UnnecessarySetDefault', 153 'Unnecessary call to NullPointerTester#setDefault'), 154 low('UnnecessaryStaticImport', 155 'Using static imports for types is unnecessary'), 156 low('UseBinds', 157 '@Binds is a more efficient and declarative mechanism for delegating a binding.'), 158 low('WildcardImport', 159 'Wildcard imports, static or otherwise, should not be used'), 160 medium('AcronymName', 161 'AcronymName'), 162 medium('AmbiguousMethodReference', 163 'Method reference is ambiguous'), 164 medium('AnnotateFormatMethod', 165 'This method passes a pair of parameters through to String.format, but the enclosing method wasn\'t annotated @FormatMethod. Doing so gives compile-time rather than run-time protection against malformed format strings.'), 166 medium('AnnotationPosition', 167 'Annotations should be positioned after Javadocs, but before modifiers..'), 168 medium('ArgumentSelectionDefectChecker', 169 'Arguments are in the wrong order or could be commented for clarity.'), 170 medium('ArrayAsKeyOfSetOrMap', 171 'Arrays do not override equals() or hashCode, so comparisons will be done on reference equality only. If neither deduplication nor lookup are needed, consider using a List instead. Otherwise, use IdentityHashMap/Set, a Map from a library that handles object arrays, or an Iterable/List of pairs.'), 172 medium('AssertEqualsArgumentOrderChecker', 173 'Arguments are swapped in assertEquals-like call'), 174 medium('AssertFalse', 175 'Assertions may be disabled at runtime and do not guarantee that execution will halt here; consider throwing an exception instead'), 176 medium('AssertThrowsMultipleStatements', 177 'The lambda passed to assertThrows should contain exactly one statement'), 178 medium('AssertionFailureIgnored', 179 'This assertion throws an AssertionError if it fails, which will be caught by an enclosing try block.'), 180 medium('AssistedInjectAndInjectOnConstructors', 181 '@AssistedInject and @Inject should not be used on different constructors in the same class.'), 182 medium('AutoValueFinalMethods', 183 'Make toString(), hashCode() and equals() final in AutoValue classes, so it is clear to readers that AutoValue is not overriding them'), 184 medium('BadAnnotationImplementation', 185 'Classes that implement Annotation must override equals and hashCode. Consider using AutoAnnotation instead of implementing Annotation by hand.'), 186 medium('BadComparable', 187 'Possible sign flip from narrowing conversion'), 188 medium('BadImport', 189 'Importing nested classes/static methods/static fields with commonly-used names can make code harder to read, because it may not be clear from the context exactly which type is being referred to. Qualifying the name with that of the containing class can make the code clearer.'), 190 medium('BadInstanceof', 191 'instanceof used in a way that is equivalent to a null check.'), 192 medium('BigDecimalEquals', 193 'BigDecimal#equals has surprising behavior: it also compares scale.'), 194 medium('BigDecimalLiteralDouble', 195 'new BigDecimal(double) loses precision in this case.'), 196 medium('BinderIdentityRestoredDangerously', 197 'A call to Binder.clearCallingIdentity() should be followed by Binder.restoreCallingIdentity() in a finally block. Otherwise the wrong Binder identity may be used by subsequent code.'), 198 medium('BindingToUnqualifiedCommonType', 199 'This code declares a binding for a common value type without a Qualifier annotation.'), 200 medium('BoxedPrimitiveConstructor', 201 'valueOf or autoboxing provides better time and space performance'), 202 medium('ByteBufferBackingArray', 203 'ByteBuffer.array() shouldn\'t be called unless ByteBuffer.arrayOffset() is used or if the ByteBuffer was initialized using ByteBuffer.wrap() or ByteBuffer.allocate().'), 204 medium('CannotMockFinalClass', 205 'Mockito cannot mock final classes'), 206 medium('CanonicalDuration', 207 'Duration can be expressed more clearly with different units'), 208 medium('CatchAndPrintStackTrace', 209 'Logging or rethrowing exceptions should usually be preferred to catching and calling printStackTrace'), 210 medium('CatchFail', 211 'Ignoring exceptions and calling fail() is unnecessary, and makes test output less useful'), 212 medium('ChangedAbstract', 213 'Method has changed \'abstract\' qualifier'), 214 medium('ClassCanBeStatic', 215 'Inner class is non-static but does not reference enclosing class'), 216 medium('ClassNewInstance', 217 'Class.newInstance() bypasses exception checking; prefer getDeclaredConstructor().newInstance()'), 218 medium('CloseableProvides', 219 'Providing Closeable resources makes their lifecycle unclear'), 220 medium('CollectionToArraySafeParameter', 221 'The type of the array parameter of Collection.toArray needs to be compatible with the array type'), 222 medium('CollectorShouldNotUseState', 223 'Collector.of() should not use state'), 224 medium('ComparableAndComparator', 225 'Class should not implement both `Comparable` and `Comparator`'), 226 medium('ConstructorInvokesOverridable', 227 'Constructors should not invoke overridable methods.'), 228 medium('ConstructorLeaksThis', 229 'Constructors should not pass the \'this\' reference out in method invocations, since the object may not be fully constructed.'), 230 medium('DateFormatConstant', 231 'DateFormat is not thread-safe, and should not be used as a constant field.'), 232 medium('DefaultCharset', 233 'Implicit use of the platform default charset, which can result in differing behaviour between JVM executions or incorrect behavior if the encoding of the data source doesn\'t match expectations.'), 234 medium('DeprecatedThreadMethods', 235 'Avoid deprecated Thread methods; read the method\'s javadoc for details.'), 236 medium('DoubleBraceInitialization', 237 'Prefer collection factory methods or builders to the double-brace initialization pattern.'), 238 medium('DoubleCheckedLocking', 239 'Double-checked locking on non-volatile fields is unsafe'), 240 medium('EmptyTopLevelDeclaration', 241 'Empty top-level type declaration'), 242 medium('EqualsBrokenForNull', 243 'equals() implementation may throw NullPointerException when given null'), 244 medium('EqualsGetClass', 245 'Overriding Object#equals in a non-final class by using getClass rather than instanceof breaks substitutability of subclasses.'), 246 medium('EqualsHashCode', 247 'Classes that override equals should also override hashCode.'), 248 medium('EqualsIncompatibleType', 249 'An equality test between objects with incompatible types always returns false'), 250 medium('EqualsUnsafeCast', 251 'The contract of #equals states that it should return false for incompatible types, while this implementation may throw ClassCastException.'), 252 medium('EqualsUsingHashCode', 253 'Implementing #equals by just comparing hashCodes is fragile. Hashes collide frequently, and this will lead to false positives in #equals.'), 254 medium('ExpectedExceptionChecker', 255 'Calls to ExpectedException#expect should always be followed by exactly one statement.'), 256 medium('ExtendingJUnitAssert', 257 'When only using JUnit Assert\'s static methods, you should import statically instead of extending.'), 258 medium('FallThrough', 259 'Switch case may fall through'), 260 medium('Finally', 261 'If you return or throw from a finally, then values returned or thrown from the try-catch block will be ignored. Consider using try-with-resources instead.'), 262 medium('FloatCast', 263 'Use parentheses to make the precedence explicit'), 264 medium('FloatingPointAssertionWithinEpsilon', 265 'This fuzzy equality check is using a tolerance less than the gap to the next number. You may want a less restrictive tolerance, or to assert equality.'), 266 medium('FloatingPointLiteralPrecision', 267 'Floating point literal loses precision'), 268 medium('FragmentInjection', 269 'Classes extending PreferenceActivity must implement isValidFragment such that it does not unconditionally return true to prevent vulnerability to fragment injection attacks.'), 270 medium('FragmentNotInstantiable', 271 'Subclasses of Fragment must be instantiable via Class#newInstance(): the class must be public, static and have a public nullary constructor'), 272 medium('FunctionalInterfaceClash', 273 'Overloads will be ambiguous when passing lambda arguments'), 274 medium('FutureReturnValueIgnored', 275 'Return value of methods returning Future must be checked. Ignoring returned Futures suppresses exceptions thrown from the code that completes the Future.'), 276 medium('GetClassOnEnum', 277 'Calling getClass() on an enum may return a subclass of the enum type'), 278 medium('HardCodedSdCardPath', 279 'Hardcoded reference to /sdcard'), 280 medium('HidingField', 281 'Hiding fields of superclasses may cause confusion and errors'), 282 medium('ImmutableAnnotationChecker', 283 'Annotations should always be immutable'), 284 medium('ImmutableEnumChecker', 285 'Enums should always be immutable'), 286 medium('IncompatibleModifiers', 287 'This annotation has incompatible modifiers as specified by its @IncompatibleModifiers annotation'), 288 medium('InconsistentCapitalization', 289 'It is confusing to have a field and a parameter under the same scope that differ only in capitalization.'), 290 medium('InconsistentHashCode', 291 'Including fields in hashCode which are not compared in equals violates the contract of hashCode.'), 292 medium('InconsistentOverloads', 293 'The ordering of parameters in overloaded methods should be as consistent as possible (when viewed from left to right)'), 294 medium('IncrementInForLoopAndHeader', 295 'This for loop increments the same variable in the header and in the body'), 296 medium('InjectOnConstructorOfAbstractClass', 297 'Constructors on abstract classes are never directly @Injected, only the constructors of their subclasses can be @Inject\'ed.'), 298 medium('InputStreamSlowMultibyteRead', 299 'Please also override int read(byte[], int, int), otherwise multi-byte reads from this input stream are likely to be slow.'), 300 medium('InstanceOfAndCastMatchWrongType', 301 'Casting inside an if block should be plausibly consistent with the instanceof type'), 302 medium('IntLongMath', 303 'Expression of type int may overflow before being assigned to a long'), 304 medium('IntentBuilderName', 305 'IntentBuilderName'), 306 medium('InvalidParam', 307 'This @param tag doesn\'t refer to a parameter of the method.'), 308 medium('InvalidTag', 309 'This tag is invalid.'), 310 medium('InvalidThrows', 311 'The documented method doesn\'t actually throw this checked exception.'), 312 medium('IterableAndIterator', 313 'Class should not implement both `Iterable` and `Iterator`'), 314 medium('JUnit3FloatingPointComparisonWithoutDelta', 315 'Floating-point comparison without error tolerance'), 316 medium('JUnit4ClassUsedInJUnit3', 317 'Some JUnit4 construct cannot be used in a JUnit3 context. Convert your class to JUnit4 style to use them.'), 318 medium('JUnitAmbiguousTestClass', 319 'Test class inherits from JUnit 3\'s TestCase but has JUnit 4 @Test annotations.'), 320 medium('JavaLangClash', 321 'Never reuse class names from java.lang'), 322 medium('JdkObsolete', 323 'Suggests alternatives to obsolete JDK classes.'), 324 medium('LockNotBeforeTry', 325 'Calls to Lock#lock should be immediately followed by a try block which releases the lock.'), 326 medium('LogicalAssignment', 327 'Assignment where a boolean expression was expected; use == if this assignment wasn\'t expected or add parentheses for clarity.'), 328 medium('MathAbsoluteRandom', 329 'Math.abs does not always give a positive result. Please consider other methods for positive random numbers.'), 330 medium('MissingCasesInEnumSwitch', 331 'Switches on enum types should either handle all values, or have a default case.'), 332 medium('MissingDefault', 333 'The Google Java Style Guide requires that each switch statement includes a default statement group, even if it contains no code. (This requirement is lifted for any switch statement that covers all values of an enum.)'), 334 medium('MissingFail', 335 'Not calling fail() when expecting an exception masks bugs'), 336 medium('MissingOverride', 337 'method overrides method in supertype; expected @Override'), 338 medium('ModifiedButNotUsed', 339 'A collection or proto builder was created, but its values were never accessed.'), 340 medium('ModifyCollectionInEnhancedForLoop', 341 'Modifying a collection while iterating over it in a loop may cause a ConcurrentModificationException to be thrown.'), 342 medium('MultipleParallelOrSequentialCalls', 343 'Multiple calls to either parallel or sequential are unnecessary and cause confusion.'), 344 medium('MutableConstantField', 345 'Constant field declarations should use the immutable type (such as ImmutableList) instead of the general collection interface type (such as List)'), 346 medium('MutableMethodReturnType', 347 'Method return type should use the immutable type (such as ImmutableList) instead of the general collection interface type (such as List)'), 348 medium('NarrowingCompoundAssignment', 349 'Compound assignments may hide dangerous casts'), 350 medium('NestedInstanceOfConditions', 351 'Nested instanceOf conditions of disjoint types create blocks of code that never execute'), 352 medium('NoFunctionalReturnType', 353 'Instead of returning a functional type, return the actual type that the returned function would return and use lambdas at use site.'), 354 medium('NonAtomicVolatileUpdate', 355 'This update of a volatile variable is non-atomic'), 356 medium('NonCanonicalStaticMemberImport', 357 'Static import of member uses non-canonical name'), 358 medium('NonOverridingEquals', 359 'equals method doesn\'t override Object.equals'), 360 medium('NotCloseable', 361 'Not closeable'), 362 medium('NullableCollection', 363 'Method should not return a nullable collection'), 364 medium('NullableConstructor', 365 'Constructors should not be annotated with @Nullable since they cannot return null'), 366 medium('NullableDereference', 367 'Dereference of possibly-null value'), 368 medium('NullablePrimitive', 369 '@Nullable should not be used for primitive types since they cannot be null'), 370 medium('NullableVoid', 371 'void-returning methods should not be annotated with @Nullable, since they cannot return null'), 372 medium('ObjectToString', 373 'Calling toString on Objects that don\'t override toString() doesn\'t provide useful information'), 374 medium('ObjectsHashCodePrimitive', 375 'Objects.hashCode(Object o) should not be passed a primitive value'), 376 medium('OperatorPrecedence', 377 'Use grouping parenthesis to make the operator precedence explicit'), 378 medium('OptionalNotPresent', 379 'One should not call optional.get() inside an if statement that checks !optional.isPresent'), 380 medium('OrphanedFormatString', 381 'String literal contains format specifiers, but is not passed to a format method'), 382 medium('OverrideThrowableToString', 383 'To return a custom message with a Throwable class, one should override getMessage() instead of toString() for Throwable.'), 384 medium('Overrides', 385 'Varargs doesn\'t agree for overridden method'), 386 medium('OverridesGuiceInjectableMethod', 387 'This method is not annotated with @Inject, but it overrides a method that is annotated with @com.google.inject.Inject. Guice will inject this method, and it is recommended to annotate it explicitly.'), 388 medium('ParameterName', 389 'Detects `/* name= */`-style comments on actual parameters where the name doesn\'t match the formal parameter'), 390 medium('PreconditionsInvalidPlaceholder', 391 'Preconditions only accepts the %s placeholder in error message strings'), 392 medium('PrimitiveArrayPassedToVarargsMethod', 393 'Passing a primitive array to a varargs method is usually wrong'), 394 medium('ProtoRedundantSet', 395 'A field on a protocol buffer was set twice in the same chained expression.'), 396 medium('ProtosAsKeyOfSetOrMap', 397 'Protos should not be used as a key to a map, in a set, or in a contains method on a descendant of a collection. Protos have non deterministic ordering and proto equality is deep, which is a performance issue.'), 398 medium('ProvidesFix', 399 'BugChecker has incorrect ProvidesFix tag, please update'), 400 medium('QualifierOrScopeOnInjectMethod', 401 'Qualifiers/Scope annotations on @Inject methods don\'t have any effect. Move the qualifier annotation to the binding location.'), 402 medium('QualifierWithTypeUse', 403 'Injection frameworks currently don\'t understand Qualifiers in TYPE_PARAMETER or TYPE_USE contexts.'), 404 medium('ReachabilityFenceUsage', 405 'reachabilityFence should always be called inside a finally block'), 406 medium('RedundantThrows', 407 'Thrown exception is a subtype of another'), 408 medium('ReferenceEquality', 409 'Comparison using reference equality instead of value equality'), 410 medium('RequiredModifiers', 411 'This annotation is missing required modifiers as specified by its @RequiredModifiers annotation'), 412 medium('ReturnFromVoid', 413 'Void methods should not have a @return tag.'), 414 medium('SamShouldBeLast', 415 'SAM-compatible parameters should be last'), 416 medium('ShortCircuitBoolean', 417 u'Prefer the short-circuiting boolean operators \u0026\u0026 and || to \u0026 and |.'), 418 medium('StaticGuardedByInstance', 419 'Writes to static fields should not be guarded by instance locks'), 420 medium('StaticQualifiedUsingExpression', 421 'A static variable or method should be qualified with a class name, not expression'), 422 medium('StreamResourceLeak', 423 'Streams that encapsulate a closeable resource should be closed using try-with-resources'), 424 medium('StringEquality', 425 'String comparison using reference equality instead of value equality'), 426 medium('StringSplitter', 427 'String.split(String) has surprising behavior'), 428 medium('SwigMemoryLeak', 429 'SWIG generated code that can\'t call a C++ destructor will leak memory'), 430 medium('SynchronizeOnNonFinalField', 431 'Synchronizing on non-final fields is not safe: if the field is ever updated, different threads may end up locking on different objects.'), 432 medium('SystemExitOutsideMain', 433 'Code that contains System.exit() is untestable.'), 434 medium('TestExceptionChecker', 435 'Using @Test(expected=...) is discouraged, since the test will pass if *any* statement in the test method throws the expected exception'), 436 medium('ThreadJoinLoop', 437 'Thread.join needs to be surrounded by a loop until it succeeds, as in Uninterruptibles.joinUninterruptibly.'), 438 medium('ThreadLocalUsage', 439 'ThreadLocals should be stored in static fields'), 440 medium('ThreadPriorityCheck', 441 'Relying on the thread scheduler is discouraged; see Effective Java Item 72 (2nd edition) / 84 (3rd edition).'), 442 medium('ThreeLetterTimeZoneID', 443 'Three-letter time zone identifiers are deprecated, may be ambiguous, and might not do what you intend; the full IANA time zone ID should be used instead.'), 444 medium('ToStringReturnsNull', 445 'An implementation of Object.toString() should never return null.'), 446 medium('TruthAssertExpected', 447 'The actual and expected values appear to be swapped, which results in poor assertion failure messages. The actual value should come first.'), 448 medium('TruthConstantAsserts', 449 'Truth Library assert is called on a constant.'), 450 medium('TruthIncompatibleType', 451 'Argument is not compatible with the subject\'s type.'), 452 medium('TypeNameShadowing', 453 'Type parameter declaration shadows another named type'), 454 medium('TypeParameterShadowing', 455 'Type parameter declaration overrides another type parameter already declared'), 456 medium('TypeParameterUnusedInFormals', 457 'Declaring a type parameter that is only used in the return type is a misuse of generics: operations on the type parameter are unchecked, it hides unsafe casts at invocations of the method, and it interacts badly with method overload resolution.'), 458 medium('URLEqualsHashCode', 459 'Avoid hash-based containers of java.net.URL--the containers rely on equals() and hashCode(), which cause java.net.URL to make blocking internet connections.'), 460 medium('UndefinedEquals', 461 'Collection, Iterable, Multimap, and Queue do not have well-defined equals behavior'), 462 medium('UnnecessaryDefaultInEnumSwitch', 463 'Switch handles all enum values: an explicit default case is unnecessary and defeats error checking for non-exhaustive switches.'), 464 medium('UnnecessaryParentheses', 465 'Unnecessary use of grouping parentheses'), 466 medium('UnsafeFinalization', 467 'Finalizer may run before native code finishes execution'), 468 medium('UnsafeReflectiveConstructionCast', 469 'Prefer `asSubclass` instead of casting the result of `newInstance`, to detect classes of incorrect type before invoking their constructors.This way, if the class is of the incorrect type,it will throw an exception before invoking its constructor.'), 470 medium('UnsynchronizedOverridesSynchronized', 471 'Unsynchronized method overrides a synchronized method.'), 472 medium('Unused', 473 'Unused.'), 474 medium('UnusedException', 475 'This catch block catches an exception and re-throws another, but swallows the caught exception rather than setting it as a cause. This can make debugging harder.'), 476 medium('UseCorrectAssertInTests', 477 'Java assert is used in test. For testing purposes Assert.* matchers should be used.'), 478 medium('UserHandle', 479 'UserHandle'), 480 medium('UserHandleName', 481 'UserHandleName'), 482 medium('Var', 483 'Non-constant variable missing @Var annotation'), 484 medium('VariableNameSameAsType', 485 'variableName and type with the same name would refer to the static field instead of the class'), 486 medium('WaitNotInLoop', 487 'Because of spurious wakeups, Object.wait() and Condition.await() must always be called in a loop'), 488 medium('WakelockReleasedDangerously', 489 'A wakelock acquired with a timeout may be released by the system before calling `release`, even after checking `isHeld()`. If so, it will throw a RuntimeException. Please wrap in a try/catch block.'), 490 java_medium('Found raw type', 491 [r'.*\.java:.*: warning: \[rawtypes\] found raw type']), 492 java_medium('Redundant cast', 493 [r'.*\.java:.*: warning: \[cast\] redundant cast to']), 494 java_medium('Static method should be qualified', 495 [r'.*\.java:.*: warning: \[static\] static method should be qualified']), 496 medium('AbstractInner'), 497 medium('BothPackageInfoAndHtml'), 498 medium('BuilderSetStyle'), 499 medium('CallbackName'), 500 medium('ExecutorRegistration'), 501 medium('HiddenTypeParameter'), 502 medium('JavaApiUsedByMainlineModule'), 503 medium('ListenerLast'), 504 medium('MinMaxConstant'), 505 medium('MissingBuildMethod'), 506 medium('MissingGetterMatchingBuilder'), 507 medium('NoByteOrShort'), 508 medium('OverlappingConstants'), 509 medium('SetterReturnsThis'), 510 medium('StaticFinalBuilder'), 511 medium('StreamFiles'), 512 medium('Typo'), 513 medium('UseIcu'), 514 medium('fallthrough'), 515 medium('overrides'), 516 medium('serial'), 517 medium('try'), 518 high('AndroidInjectionBeforeSuper', 519 'AndroidInjection.inject() should always be invoked before calling super.lifecycleMethod()'), 520 high('AndroidJdkLibsChecker', 521 'Use of class, field, or method that is not compatible with legacy Android devices'), 522 high('ArrayEquals', 523 'Reference equality used to compare arrays'), 524 high('ArrayFillIncompatibleType', 525 'Arrays.fill(Object[], Object) called with incompatible types.'), 526 high('ArrayHashCode', 527 'hashcode method on array does not hash array contents'), 528 high('ArrayReturn', 529 'ArrayReturn'), 530 high('ArrayToString', 531 'Calling toString on an array does not provide useful information'), 532 high('ArraysAsListPrimitiveArray', 533 'Arrays.asList does not autobox primitive arrays, as one might expect.'), 534 high('AssistedInjectAndInjectOnSameConstructor', 535 '@AssistedInject and @Inject cannot be used on the same constructor.'), 536 high('AsyncCallableReturnsNull', 537 'AsyncCallable should not return a null Future, only a Future whose result is null.'), 538 high('AsyncFunctionReturnsNull', 539 'AsyncFunction should not return a null Future, only a Future whose result is null.'), 540 high('AutoFactoryAtInject', 541 '@AutoFactory and @Inject should not be used in the same type.'), 542 high('AutoValueConstructorOrderChecker', 543 'Arguments to AutoValue constructor are in the wrong order'), 544 high('BadShiftAmount', 545 'Shift by an amount that is out of range'), 546 high('BundleDeserializationCast', 547 'Object serialized in Bundle may have been flattened to base type.'), 548 high('ChainingConstructorIgnoresParameter', 549 'The called constructor accepts a parameter with the same name and type as one of its caller\'s parameters, but its caller doesn\'t pass that parameter to it. It\'s likely that it was intended to.'), 550 high('CheckReturnValue', 551 'Ignored return value of method that is annotated with @CheckReturnValue'), 552 high('ClassName', 553 'The source file name should match the name of the top-level class it contains'), 554 high('CollectionIncompatibleType', 555 'Incompatible type as argument to Object-accepting Java collections method'), 556 high('ComparableType', 557 u'Implementing \'Comparable\u003cT>\' where T is not compatible with the implementing class.'), 558 high('ComparingThisWithNull', 559 'this == null is always false, this != null is always true'), 560 high('ComparisonContractViolated', 561 'This comparison method violates the contract'), 562 high('ComparisonOutOfRange', 563 'Comparison to value that is out of range for the compared type'), 564 high('CompatibleWithAnnotationMisuse', 565 '@CompatibleWith\'s value is not a type argument.'), 566 high('CompileTimeConstant', 567 'Non-compile-time constant expression passed to parameter with @CompileTimeConstant type annotation.'), 568 high('ComplexBooleanConstant', 569 'Non-trivial compile time constant boolean expressions shouldn\'t be used.'), 570 high('ConditionalExpressionNumericPromotion', 571 'A conditional expression with numeric operands of differing types will perform binary numeric promotion of the operands; when these operands are of reference types, the expression\'s result may not be of the expected type.'), 572 high('ConstantOverflow', 573 'Compile-time constant expression overflows'), 574 high('DaggerProvidesNull', 575 'Dagger @Provides methods may not return null unless annotated with @Nullable'), 576 high('DeadException', 577 'Exception created but not thrown'), 578 high('DeadThread', 579 'Thread created but not started'), 580 java_high('Deprecated item is not annotated with @Deprecated', 581 [r".*\.java:.*: warning: \[.*\] .+ is not annotated with @Deprecated$"]), 582 high('DivZero', 583 'Division by integer literal zero'), 584 high('DoNotCall', 585 'This method should not be called.'), 586 high('EmptyIf', 587 'Empty statement after if'), 588 high('EqualsNaN', 589 '== NaN always returns false; use the isNaN methods instead'), 590 high('EqualsReference', 591 '== must be used in equals method to check equality to itself or an infinite loop will occur.'), 592 high('EqualsWrongThing', 593 'Comparing different pairs of fields/getters in an equals implementation is probably a mistake.'), 594 high('ForOverride', 595 'Method annotated @ForOverride must be protected or package-private and only invoked from declaring class, or from an override of the method'), 596 high('FormatString', 597 'Invalid printf-style format string'), 598 high('FormatStringAnnotation', 599 'Invalid format string passed to formatting method.'), 600 high('FunctionalInterfaceMethodChanged', 601 'Casting a lambda to this @FunctionalInterface can cause a behavior change from casting to a functional superinterface, which is surprising to users. Prefer decorator methods to this surprising behavior.'), 602 high('FuturesGetCheckedIllegalExceptionType', 603 'Futures.getChecked requires a checked exception type with a standard constructor.'), 604 high('FuzzyEqualsShouldNotBeUsedInEqualsMethod', 605 'DoubleMath.fuzzyEquals should never be used in an Object.equals() method'), 606 high('GetClassOnAnnotation', 607 'Calling getClass() on an annotation may return a proxy class'), 608 high('GetClassOnClass', 609 'Calling getClass() on an object of type Class returns the Class object for java.lang.Class; you probably meant to operate on the object directly'), 610 high('GuardedBy', 611 'Checks for unguarded accesses to fields and methods with @GuardedBy annotations'), 612 high('GuiceAssistedInjectScoping', 613 'Scope annotation on implementation class of AssistedInject factory is not allowed'), 614 high('GuiceAssistedParameters', 615 'A constructor cannot have two @Assisted parameters of the same type unless they are disambiguated with named @Assisted annotations.'), 616 high('GuiceInjectOnFinalField', 617 'Although Guice allows injecting final fields, doing so is disallowed because the injected value may not be visible to other threads.'), 618 high('HashtableContains', 619 'contains() is a legacy method that is equivalent to containsValue()'), 620 high('IdentityBinaryExpression', 621 'A binary expression where both operands are the same is usually incorrect.'), 622 high('Immutable', 623 'Type declaration annotated with @Immutable is not immutable'), 624 high('ImmutableModification', 625 'Modifying an immutable collection is guaranteed to throw an exception and leave the collection unmodified'), 626 high('IncompatibleArgumentType', 627 'Passing argument to a generic method with an incompatible type.'), 628 high('IndexOfChar', 629 'The first argument to indexOf is a Unicode code point, and the second is the index to start the search from'), 630 high('InexactVarargsConditional', 631 'Conditional expression in varargs call contains array and non-array arguments'), 632 high('InfiniteRecursion', 633 'This method always recurses, and will cause a StackOverflowError'), 634 high('InjectInvalidTargetingOnScopingAnnotation', 635 'A scoping annotation\'s Target should include TYPE and METHOD.'), 636 high('InjectMoreThanOneQualifier', 637 'Using more than one qualifier annotation on the same element is not allowed.'), 638 high('InjectMoreThanOneScopeAnnotationOnClass', 639 'A class can be annotated with at most one scope annotation.'), 640 high('InjectOnMemberAndConstructor', 641 'Members shouldn\'t be annotated with @Inject if constructor is already annotated @Inject'), 642 high('InjectScopeAnnotationOnInterfaceOrAbstractClass', 643 'Scope annotation on an interface or abstact class is not allowed'), 644 high('InjectScopeOrQualifierAnnotationRetention', 645 'Scoping and qualifier annotations must have runtime retention.'), 646 high('InjectedConstructorAnnotations', 647 'Injected constructors cannot be optional nor have binding annotations'), 648 high('InsecureCryptoUsage', 649 'A standard cryptographic operation is used in a mode that is prone to vulnerabilities'), 650 high('InvalidPatternSyntax', 651 'Invalid syntax used for a regular expression'), 652 high('InvalidTimeZoneID', 653 'Invalid time zone identifier. TimeZone.getTimeZone(String) will silently return GMT instead of the time zone you intended.'), 654 high('IsInstanceOfClass', 655 'The argument to Class#isInstance(Object) should not be a Class'), 656 high('IsLoggableTagLength', 657 'Log tag too long, cannot exceed 23 characters.'), 658 high('IterablePathParameter', 659 u'Path implements Iterable\u003cPath>; prefer Collection\u003cPath> for clarity'), 660 high('JMockTestWithoutRunWithOrRuleAnnotation', 661 'jMock tests must have a @RunWith(JMock.class) annotation, or the Mockery field must have a @Rule JUnit annotation'), 662 high('JUnit3TestNotRun', 663 'Test method will not be run; please correct method signature (Should be public, non-static, and method name should begin with "test").'), 664 high('JUnit4ClassAnnotationNonStatic', 665 'This method should be static'), 666 high('JUnit4SetUpNotRun', 667 'setUp() method will not be run; please add JUnit\'s @Before annotation'), 668 high('JUnit4TearDownNotRun', 669 'tearDown() method will not be run; please add JUnit\'s @After annotation'), 670 high('JUnit4TestNotRun', 671 'This looks like a test method but is not run; please add @Test and @Ignore, or, if this is a helper method, reduce its visibility.'), 672 high('JUnitAssertSameCheck', 673 'An object is tested for reference equality to itself using JUnit library.'), 674 high('Java7ApiChecker', 675 'Use of class, field, or method that is not compatible with JDK 7'), 676 high('JavaxInjectOnAbstractMethod', 677 'Abstract and default methods are not injectable with javax.inject.Inject'), 678 high('JavaxInjectOnFinalField', 679 '@javax.inject.Inject cannot be put on a final field.'), 680 high('LiteByteStringUtf8', 681 'This pattern will silently corrupt certain byte sequences from the serialized protocol message. Use ByteString or byte[] directly'), 682 high('LockMethodChecker', 683 'This method does not acquire the locks specified by its @LockMethod annotation'), 684 high('LongLiteralLowerCaseSuffix', 685 'Prefer \'L\' to \'l\' for the suffix to long literals'), 686 high('LoopConditionChecker', 687 'Loop condition is never modified in loop body.'), 688 high('MathRoundIntLong', 689 'Math.round(Integer) results in truncation'), 690 high('MislabeledAndroidString', 691 'Certain resources in `android.R.string` have names that do not match their content'), 692 high('MissingSuperCall', 693 'Overriding method is missing a call to overridden super method'), 694 high('MissingTestCall', 695 'A terminating method call is required for a test helper to have any effect.'), 696 high('MisusedWeekYear', 697 'Use of "YYYY" (week year) in a date pattern without "ww" (week in year). You probably meant to use "yyyy" (year) instead.'), 698 high('MockitoCast', 699 'A bug in Mockito will cause this test to fail at runtime with a ClassCastException'), 700 high('MockitoUsage', 701 'Missing method call for verify(mock) here'), 702 high('ModifyingCollectionWithItself', 703 'Using a collection function with itself as the argument.'), 704 high('MoreThanOneInjectableConstructor', 705 'This class has more than one @Inject-annotated constructor. Please remove the @Inject annotation from all but one of them.'), 706 high('MustBeClosedChecker', 707 'The result of this method must be closed.'), 708 high('NCopiesOfChar', 709 'The first argument to nCopies is the number of copies, and the second is the item to copy'), 710 high('NoAllocation', 711 '@NoAllocation was specified on this method, but something was found that would trigger an allocation'), 712 high('NonCanonicalStaticImport', 713 'Static import of type uses non-canonical name'), 714 high('NonFinalCompileTimeConstant', 715 '@CompileTimeConstant parameters should be final or effectively final'), 716 high('NonRuntimeAnnotation', 717 'Calling getAnnotation on an annotation that is not retained at runtime.'), 718 high('NullTernary', 719 'This conditional expression may evaluate to null, which will result in an NPE when the result is unboxed.'), 720 high('NumericEquality', 721 'Numeric comparison using reference equality instead of value equality'), 722 high('OptionalEquality', 723 'Comparison using reference equality instead of value equality'), 724 high('OverlappingQualifierAndScopeAnnotation', 725 'Annotations cannot be both Scope annotations and Qualifier annotations: this causes confusion when trying to use them.'), 726 high('OverridesJavaxInjectableMethod', 727 'This method is not annotated with @Inject, but it overrides a method that is annotated with @javax.inject.Inject. The method will not be Injected.'), 728 high('PackageInfo', 729 'Declaring types inside package-info.java files is very bad form'), 730 high('ParameterPackage', 731 'Method parameter has wrong package'), 732 high('ParcelableCreator', 733 'Detects classes which implement Parcelable but don\'t have CREATOR'), 734 high('PreconditionsCheckNotNull', 735 'Literal passed as first argument to Preconditions.checkNotNull() can never be null'), 736 high('PreconditionsCheckNotNullPrimitive', 737 'First argument to `Preconditions.checkNotNull()` is a primitive rather than an object reference'), 738 high('PredicateIncompatibleType', 739 'Using ::equals or ::isInstance as an incompatible Predicate; the predicate will always return false'), 740 high('PrivateSecurityContractProtoAccess', 741 'Access to a private protocol buffer field is forbidden. This protocol buffer carries a security contract, and can only be created using an approved library. Direct access to the fields is forbidden.'), 742 high('ProtoFieldNullComparison', 743 'Protobuf fields cannot be null.'), 744 high('ProtoStringFieldReferenceEquality', 745 'Comparing protobuf fields of type String using reference equality'), 746 high('ProtocolBufferOrdinal', 747 'To get the tag number of a protocol buffer enum, use getNumber() instead.'), 748 high('ProvidesMethodOutsideOfModule', 749 '@Provides methods need to be declared in a Module to have any effect.'), 750 high('RandomCast', 751 'Casting a random number in the range [0.0, 1.0) to an integer or long always results in 0.'), 752 high('RandomModInteger', 753 'Use Random.nextInt(int). Random.nextInt() % n can have negative results'), 754 high('RectIntersectReturnValueIgnored', 755 'Return value of android.graphics.Rect.intersect() must be checked'), 756 high('RestrictTo', 757 'Use of method or class annotated with @RestrictTo'), 758 high('RestrictedApiChecker', 759 ' Check for non-whitelisted callers to RestrictedApiChecker.'), 760 high('ReturnValueIgnored', 761 'Return value of this method must be used'), 762 high('SelfAssignment', 763 'Variable assigned to itself'), 764 high('SelfComparison', 765 'An object is compared to itself'), 766 high('SelfEquals', 767 'Testing an object for equality with itself will always be true.'), 768 high('ShouldHaveEvenArgs', 769 'This method must be called with an even number of arguments.'), 770 high('SizeGreaterThanOrEqualsZero', 771 'Comparison of a size >= 0 is always true, did you intend to check for non-emptiness?'), 772 high('StaticOrDefaultInterfaceMethod', 773 'Static and default interface methods are not natively supported on older Android devices. '), 774 high('StreamToString', 775 'Calling toString on a Stream does not provide useful information'), 776 high('StringBuilderInitWithChar', 777 'StringBuilder does not have a char constructor; this invokes the int constructor.'), 778 high('SubstringOfZero', 779 'String.substring(0) returns the original String'), 780 high('SuppressWarningsDeprecated', 781 'Suppressing "deprecated" is probably a typo for "deprecation"'), 782 high('ThrowIfUncheckedKnownChecked', 783 'throwIfUnchecked(knownCheckedException) is a no-op.'), 784 high('ThrowNull', 785 'Throwing \'null\' always results in a NullPointerException being thrown.'), 786 high('TruthSelfEquals', 787 'isEqualTo should not be used to test an object for equality with itself; the assertion will never fail.'), 788 high('TryFailThrowable', 789 'Catching Throwable/Error masks failures from fail() or assert*() in the try block'), 790 high('TypeParameterQualifier', 791 'Type parameter used as type qualifier'), 792 high('UnlockMethod', 793 'This method does not acquire the locks specified by its @UnlockMethod annotation'), 794 high('UnnecessaryTypeArgument', 795 'Non-generic methods should not be invoked with type arguments'), 796 high('UnusedAnonymousClass', 797 'Instance created but never used'), 798 high('UnusedCollectionModifiedInPlace', 799 'Collection is modified in place, but the result is not used'), 800 high('VarTypeName', 801 '`var` should not be used as a type name.'), 802 803 # Other javac tool warnings 804 java_medium('addNdkApiCoverage failed to getPackage', 805 [r".*: warning: addNdkApiCoverage failed to getPackage"]), 806 java_medium('bad path element', 807 [r".*: warning: \[path\] bad path element .*\.jar"]), 808 java_medium('Supported version from annotation processor', 809 [r".*: warning: Supported source version .+ from annotation processor"]), 810 java_medium('Schema export directory is not provided', 811 [r".*\.(java|kt):.*: warning: Schema export directory is not provided"]), 812] 813 814compile_patterns(warn_patterns) 815