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