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