repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/SamePackageImportsTemplate.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.common.collect.ImmutableMap; import com.google.errorprone.refaster.ImportPolicy; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; import com.google.errorprone.refaster.annotation.UseImportPolicy; /** Sample template generating references to nested classes in java.util. */ public class SamePackageImportsTemplate<K, V> { @BeforeTemplate ImmutableMap.Builder<K, V> builderFactory() { return ImmutableMap.builder(); } @AfterTemplate @UseImportPolicy(ImportPolicy.IMPORT_CLASS_DIRECTLY) ImmutableMap.Builder<K, V> builderConstructor() { return new ImmutableMap.Builder<>(); } }
1,363
34.894737
76
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/SuppressWarningsTemplate.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; /** Sample template for exercising {@code @SuppressWarnings} handling. */ public class SuppressWarningsTemplate { @BeforeTemplate int abs(int x) { return x < 0 ? -x : x; } @AfterTemplate int math(int x) { return Math.abs(x); } }
1,046
29.794118
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/TypeArgumentsMethodInvocationTemplate.java
/* * Copyright 2022 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; /** Sample template for introducing type arguments on a method invocation in an @AfterTemplate. */ public class TypeArgumentsMethodInvocationTemplate<T> { @BeforeTemplate Future<T> before(ExecutorService executorService, Callable<T> callable) { return executorService.submit(callable); } @AfterTemplate Future<T> after(ExecutorService executorService, Callable<T> callable) { return executorService.<T>submit(callable); } }
1,360
35.783784
98
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/TryTemplate.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.common.base.MoreObjects; import com.google.common.primitives.Ints; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; /** * Example Refaster template matching a {@code try} statement. * * @author lowasser@google.com (Louis Wasserman) */ public class TryTemplate { @BeforeTemplate void tryParseInt(int result, String str, int defaultValue) { try { result = Integer.parseInt(str); } catch (NumberFormatException e) { result = defaultValue; } } @AfterTemplate void oneLiner(int result, String str, int defaultValue) { result = MoreObjects.firstNonNull(Ints.tryParse(str), defaultValue); } }
1,396
30.75
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/ImportClassDirectlyTemplate.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.ImportPolicy; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; import com.google.errorprone.refaster.annotation.UseImportPolicy; import java.util.Map; /** * Test for an {@code ImportPolicy} importing nested classes directly. * * @author Louis Wasserman */ public class ImportClassDirectlyTemplate<K, V> { @BeforeTemplate void forEachKeys(Map<K, V> map) { for (K k : map.keySet()) { System.out.println(k + " " + map.get(k)); } } @AfterTemplate @UseImportPolicy(ImportPolicy.IMPORT_CLASS_DIRECTLY) void forEachEntries(Map<K, V> map) { for (Map.Entry<K, V> entry : map.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } } }
1,479
31.173913
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/ArrayTemplate.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; import java.util.List; /** * Example Refaster template using array syntax. * * @author mdempsky@google.com (Matthew Dempsky) */ public class ArrayTemplate { @BeforeTemplate public String before(List<String> e, int i) { return e.get(i); } @AfterTemplate public String after(List<String> e, int i) { return e.toArray(new String[0])[i]; } }
1,151
30.135135
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/AnonymousClassTemplate.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; import com.google.errorprone.refaster.annotation.OfKind; import com.sun.source.tree.Tree.Kind; import java.util.AbstractList; import java.util.Collections; import java.util.List; /** * Example template using an anonymous class, demonstrating that methods may be matched in any * order. * * @author lowasser@google.com (Louis Wasserman) */ public class AnonymousClassTemplate { @BeforeTemplate List<Integer> anonymousAbstractList(@OfKind(Kind.INT_LITERAL) final int value, final int size) { return new AbstractList<Integer>() { @Override public Integer get(int index) { return value; } @Override public int size() { return size; } @Override public Integer set(int index, Integer element) { throw new UnsupportedOperationException(); } }; } @AfterTemplate List<Integer> nCopies(final int value, final int size) { return Collections.nCopies(size, value); } }
1,755
29.275862
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/PlaceholderAllowedVarsTemplate.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; import com.google.errorprone.refaster.annotation.Placeholder; public abstract class PlaceholderAllowedVarsTemplate { @Placeholder abstract boolean condition(); @Placeholder abstract void beforeBody(); @Placeholder abstract String concatBody(); @BeforeTemplate void before(String str) { if (condition()) { beforeBody(); str += concatBody(); } } @AfterTemplate void after(String str) { System.out.println("found match: " + str); } }
1,271
27.909091
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/UnnecessaryLambdaParens.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; public class UnnecessaryLambdaParens<T> { @BeforeTemplate Optional<T> last(Stream<T> stream) { return stream.map((x) -> x).collect(Collectors.reducing((a, b) -> b)); } @AfterTemplate Optional<T> reduce(Stream<T> stream) { return stream.map((x) -> x).reduce((a, b) -> b); } }
1,187
32
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/AutoboxingTemplate.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Refaster rule demonstrating that autoboxing is applied when matching templates. * * @author lowasser@google.com (Louis Wasserman) */ public class AutoboxingTemplate { @BeforeTemplate public <E> List<E> singletonList(E e) { return Collections.singletonList(e); } @AfterTemplate public <E> List<E> asList(E e) { return Arrays.asList(e); } }
1,236
30.717949
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/StaticImportClassTokenTemplate.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.ImportPolicy; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; import com.google.errorprone.refaster.annotation.UseImportPolicy; /** Sample template generating references to nested classes in java.util. */ public class StaticImportClassTokenTemplate { @BeforeTemplate boolean isString(Object o) { return o instanceof String; } @AfterTemplate @UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS) boolean isStringViaClass(Object o) { return Boolean.valueOf(String.class.isInstance(o)); } }
1,295
34.027027
76
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/InferLambdaType.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; public class InferLambdaType<T> { @BeforeTemplate Optional<T> last(Stream<T> stream) { return stream.collect(Collectors.reducing((a, b) -> b)); } @AfterTemplate Optional<T> reduce(Stream<T> stream) { return stream.reduce((T a, T b) -> b); } }
1,155
31.111111
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/VariableDeclTemplate.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; /** * Sample Refaster rule matching a variable declaration. * * @author lowasser@google.com (Louis Wasserman) */ public class VariableDeclTemplate { @SuppressWarnings("unused") @BeforeTemplate public void valueOf(String str) { int x = Integer.valueOf(str); } @SuppressWarnings("unused") @AfterTemplate public void parse(String str) { int x = Integer.parseInt(str); } }
1,194
28.875
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/MayOptionallyUseTemplate.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata.template; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; import com.google.errorprone.refaster.annotation.MayOptionallyUse; import com.google.errorprone.refaster.annotation.Placeholder; import java.io.UnsupportedEncodingException; /** * Template demonstrating the use of the @MayOptionallyUse annotation. * * @author lowasser@google.com (Louis Wasserman) */ public abstract class MayOptionallyUseTemplate { @Placeholder abstract void useString(String str); @Placeholder abstract void handleException(@MayOptionallyUse Exception e); @BeforeTemplate public void tryCatch(byte[] bytes) { try { useString(new String(bytes, "UTF-8")); } catch (UnsupportedEncodingException e) { handleException(e); } } @AfterTemplate public void safe(byte[] bytes) { useString(new String(bytes, UTF_8)); } }
1,636
29.886792
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/TryMultiCatchTemplate.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; /** * Example Refaster template matching a {@code try} statement with unioned catch types. * * @author lowasser@google.com (Louis Wasserman) */ public class TryMultiCatchTemplate { @BeforeTemplate <T> void before(T result, Class<T> clazz) { try { result = clazz.newInstance(); } catch (IllegalAccessException | InstantiationException | SecurityException e) { e.printStackTrace(); } } @AfterTemplate <T> void after(T result, Class<T> clazz) { try { result = clazz.newInstance(); } catch (ReflectiveOperationException | SecurityException e) { e.printStackTrace(); } } }
1,429
30.086957
87
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/AnyOfTemplate.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.Refaster; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; /** * Example refactoring using {@code Refaster.anyOf}. * * @author lowasser@google.com (Louis Wasserman) */ public class AnyOfTemplate { @BeforeTemplate boolean signumIsZero(double d) { return Refaster.anyOf(Math.signum(d) == 0.0, 0.0 == Math.signum(d)); } @AfterTemplate boolean isZero(double d) { return d == 0.0; } }
1,182
30.972973
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/IfTemplate.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; /** * Sample Refaster template using {@code if} syntax. * * @author lowasser@google.com (Louis Wasserman) */ public class IfTemplate<T> { @BeforeTemplate public void ifBefore(boolean cond, T x, T y, T z) { if (cond) { x = y; } else { x = z; } } @AfterTemplate public void conditional(boolean cond, T x, T y, T z) { x = (cond) ? y : z; } }
1,172
28.325
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/PlaceholderAllowsIdentityTemplate.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; import com.google.errorprone.refaster.annotation.Placeholder; import java.util.Collection; import java.util.Iterator; /** * Test case demonstrating use of Refaster placeholder methods. * * @author lowasser@google.com (Louis Wasserman) */ public abstract class PlaceholderAllowsIdentityTemplate { @BeforeTemplate <E> void iteratorRemoveIf(Collection<E> collection) { Iterator<E> iterator = collection.iterator(); while (iterator.hasNext()) { if (someBooleanCondition(iterator.next())) { iterator.remove(); } } } @AfterTemplate <E> void iterablesRemoveIf(Collection<E> collection) { Iterables.removeIf( collection, new Predicate<E>() { @Override public boolean apply(E input) { return someBooleanCondition(input); } }); } @Placeholder(allowsIdentity = true) abstract <E> boolean someBooleanCondition(E e); }
1,811
30.241379
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/PrecedenceSensitiveTemplate.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; import java.util.Objects; /** * Example Refaster template that may require outputs to be parenthesized even if the input was not. * * @author mdempsky@google.com (Matthew Dempsky) */ public class PrecedenceSensitiveTemplate { @BeforeTemplate public boolean before(Object a, Object b) { return Objects.equals(a, b); } @AfterTemplate public boolean after(Object a, Object b) { return a == b; } }
1,207
31.648649
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/IsInstanceTemplate.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.Refaster; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; /** * Example template using {@link Refaster#isInstance} in the {@code @AfterTemplate}. * * @author lowasser@google.com (Louis Wasserman) */ public class IsInstanceTemplate { @BeforeTemplate boolean isString(Object o) { return String.class.isInstance(o); } @AfterTemplate boolean instanceOfString(Object o) { return Refaster.<String>isInstance(o); } }
1,213
31.810811
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/NestedClassTemplate.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; import java.util.concurrent.locks.AbstractQueuedSynchronizer; import java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject; /** * Example template that returns an instance of a nested class. * * @author cpovirk@google.com (Chris Povirk) */ public class NestedClassTemplate { @BeforeTemplate public ConditionObject before(AbstractQueuedSynchronizer sync) { return sync.new ConditionObject(); } @AfterTemplate public ConditionObject after(AbstractQueuedSynchronizer sync) { return null; } }
1,318
33.710526
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/WildcardUnificationTemplate.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.common.truth.IterableSubject; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; import java.util.Collection; /** * Tests for {@code UFreeIdent} accepting two references to the same wildcard. * * @author Kurt Alfred Kluever */ public class WildcardUnificationTemplate { @BeforeTemplate static void containsAllOf(IterableSubject subject, Collection<?> expected) { subject.hasSize(expected.size()); subject.containsAtLeastElementsIn(expected); } @AfterTemplate static void containsExactly(IterableSubject subject, Collection<?> expected) { subject.containsExactlyElementsIn(expected); } }
1,379
32.658537
80
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/BinaryTemplate.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; /** * Example template using binary expressions. * * @author lowasser@google.com (Louis Wasserman) */ public class BinaryTemplate { @BeforeTemplate public int divide(int a, int b) { return (a + b) / 2; } @AfterTemplate public int shift(int a, int b) { return (a + b) >> 1; } }
1,098
27.921053
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/MultipleReferencesToIdentifierTemplate.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; /** * Refaster template referring to a single identifier multiple times. * * @author lowasser@google.com (Louis Wasserman) */ public class MultipleReferencesToIdentifierTemplate { @BeforeTemplate public boolean orSelf(boolean a) { return a || a; } @AfterTemplate public boolean identity(boolean a) { return a; } }
1,127
30.333333
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/DiamondTemplate.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** Tests that BeforeTemplates using diamond syntax match whether diamond is used or not. */ public class DiamondTemplate { @BeforeTemplate <T> List<T> linkedList() { return new LinkedList<>(); } @AfterTemplate <T> List<T> arrayList() { return new ArrayList<>(); } }
1,156
32.057143
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/LambdaImplicitType.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; public class LambdaImplicitType<T> { @BeforeTemplate Optional<T> last(Stream<T> stream) { return stream.collect(Collectors.reducing((a, b) -> b)); } @AfterTemplate Optional<T> reduce(Stream<T> stream) { return stream.reduce((a, b) -> b); } }
1,154
31.083333
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/VoidExpressionPlaceholderTemplate.java
/* * Copyright 2022 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; import com.google.errorprone.refaster.annotation.Placeholder; import java.util.Collection; /** Test case with a void placeholder method that is used as an expression. */ public abstract class VoidExpressionPlaceholderTemplate<T> { @Placeholder abstract void consume(T t); @BeforeTemplate void before(Collection<T> collection) { collection.stream().forEach(x -> consume(x)); } @AfterTemplate void after(Collection<T> collection) { collection.forEach(x -> consume(x)); } }
1,293
32.179487
78
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/NonJdkTypeTemplate.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata.template; import static com.google.common.collect.ImmutableList.toImmutableList; import com.google.common.collect.ImmutableList; import com.google.errorprone.refaster.ImportPolicy; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; import com.google.errorprone.refaster.annotation.UseImportPolicy; import java.util.stream.Stream; /** Example template that uses a non-JDK type. */ public class NonJdkTypeTemplate<T> { @BeforeTemplate public ImmutableList<T> before(Stream<T> stream) { return ImmutableList.copyOf(stream.iterator()); } @AfterTemplate @UseImportPolicy(ImportPolicy.STATIC_IMPORT_ALWAYS) public ImmutableList<T> after(Stream<T> stream) { return stream.collect(toImmutableList()); } }
1,448
36.153846
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/EmitCommentTemplate.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.Refaster; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; public class EmitCommentTemplate { @BeforeTemplate void before(String str) { System.out.println(str); } @AfterTemplate void after(String str) { Refaster.emitComment("comment"); System.out.println(str); } }
1,066
32.34375
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/template/GenericPlaceholderTemplate.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata.template; import com.google.common.base.Joiner; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; import com.google.errorprone.refaster.annotation.Placeholder; import java.util.ArrayList; import java.util.List; /** Example template using a placeholder with generics to be inferred. */ public abstract class GenericPlaceholderTemplate<E> { @Placeholder abstract E generate(); @BeforeTemplate void before(int n) { for (int i = 0; i < n; i++) { System.out.println(generate()); // E can only be inferred by looking at the actual type here } } @AfterTemplate void after(int n) { List<E> list = new ArrayList<>(); for (int i = 0; i < n; i++) { list.add(generate()); } System.out.println(Joiner.on('\n').join(list)); } }
1,496
32.266667
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/WildcardTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata; import java.util.Collections; import java.util.List; /** * Test input for {@code WildcardTemplate}. * * @author lowasser@google.com (Louis Wasserman) */ public class WildcardTemplateExample { public void example() { List<?> myList = Collections.emptyList(); System.out.println(myList); } }
957
29.903226
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/SamePackageImportsTemplateExample.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; /** * Test data for {@code SamePackageImportsTemplate}. */ public class SamePackageImportsTemplateExample { public void example() { ImmutableMap.Builder<String, Integer> builder = ImmutableMap.builder(); System.out.println(builder.buildOrThrow()); } }
909
31.5
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/TryTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; /** * Test input for {@code TryTemplate}. * * @author lowasser@google.com */ public class TryTemplateExample { int foo(String str) { int result; try { result = Integer.parseInt(str); } catch (NumberFormatException tolerated) { result = 0; } return result; } }
958
26.4
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/TopLevelTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; import java.util.logging.Logger; /** * Test data for {@code TopLevelTemplate}. */ public class TopLevelTemplateExample { private static final Logger logger = Logger.getAnonymousLogger("foobar"); }
859
30.851852
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/NestedClassTemplateExample.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; import java.util.concurrent.locks.AbstractQueuedSynchronizer; import java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject; /** * Sample data for {@code NestedClassTemplate}. * * @author cpovirk@google.com (Chris Povirk) */ public class NestedClassTemplateExample { ConditionObject example(AbstractQueuedSynchronizer sync) { return sync.new ConditionObject(); } }
1,050
31.84375
77
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/VarargTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; /** * Test case for {@code VarargTemplate}. * * @author juanch@google.com (Juan Chen) */ public class VarargTemplateExample { public String foo0() { return String.format("first: %s, second: %s"); } public String foo0_empty() { return String.format("first: %s, second: %s", new Object[]{}); } public String foo1() { return String.format("first: %s, second: %s", new Object[]{"first"}); } public String foo2() { return String.format("first: %s, second: %s", new Object[]{"first", "second"}); } public String foo3() { return String.format("first: %s, second: %s", new Object[]{"first", "second", "third"}); } }
1,315
27.608696
92
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/PrecedenceSensitiveTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata; import java.util.Objects; /** * Test data for {@code PrecedenceSensitiveTemplate}. * * @author mdempsky@google.com (Matthew Dempsky) */ public class PrecedenceSensitiveTemplateExample { public void foo(String a, String b) { if (Objects.equals(a, b)) { System.out.println("same"); } if (!Objects.equals(a, b)) { System.out.println("different"); } } }
1,037
28.657143
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/ExplicitTypesPreservedTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; import java.util.LinkedList; import java.util.Map.Entry; /** * Sample data for {@code ExplicitTypesPreservedTemplate}. * * @author lowasser@google.com (Louis Wasserman) */ public class ExplicitTypesPreservedTemplateExample { public void example() { // positive examples System.out.println(new LinkedList<String>()); System.out.println(new LinkedList<Entry<String, Integer>>()); // negative examples System.out.println(new LinkedList<String>() {{ add("foo"); }}); } }
1,164
29.657895
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/IsInstanceTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata; /** * Test input for {@code IsInstanceTemplate}. * * @author lowasser@google.com (Louis Wasserman) */ public class IsInstanceTemplateExample { public void foo() { System.out.println(String.class.isInstance("foo")); } }
880
31.62963
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/ParenthesesOptionalTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata; /** * Test input for {@code ParenthesesOptionalTemplate}. * * @author lowasser@google.com (Louis Wasserman) */ public class ParenthesesOptionalTemplateExample { public void example(int x) { System.out.println(x * 5 + 5); } }
886
31.851852
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/AssertTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; /** * Test data for {@code AssertTemplate}. */ public class AssertTemplateExample { public void example(String s) { assert !s.isEmpty() : s + " must not be empty"; assert !s.isEmpty(); System.out.println(s); } }
887
29.62069
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/AnonymousClassTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata; import java.util.AbstractList; /** * Test data for {@code AnonymousClassTemplate}. * * @author lowasser@google.com (Louis Wasserman) */ public class AnonymousClassTemplateExample { public void sameOrderNoVariableConflicts() { System.out.println(new AbstractList<Integer>() { @Override public Integer get(int index) { return 17; } @Override public int size() { return 5; } @Override public Integer set(int i, Integer element) { throw new UnsupportedOperationException(); } }); } public void sameOrderVariableConflicts() { System.out.println(new AbstractList<Integer>() { @Override public Integer get(int i) { return 17; } @Override public int size() { return 5; } @Override public Integer set(int i, Integer element) { throw new UnsupportedOperationException(); } }); } public void differentOrderNoVariableConflicts() { System.out.println(new AbstractList<Integer>() { @Override public Integer get(int index) { return 17; } @Override public Integer set(int i, Integer element) { throw new UnsupportedOperationException(); } @Override public int size() { return 5; } }); } public void differentOrderVariableConflicts() { System.out.println(new AbstractList<Integer>() { @Override public Integer get(int i) { return 17; } @Override public Integer set(int i, Integer element) { throw new UnsupportedOperationException(); } @Override public int size() { return 5; } }); } public void fewerMethods() { System.out.println(new AbstractList<Integer>() { @Override public Integer get(int index) { return 17; } @Override public int size() { return 5; } }); } public void moreMethods() { System.out.println(new AbstractList<Integer>() { @Override public Integer get(int index) { return 17; } @Override public Integer set(int index, Integer element) { throw new UnsupportedOperationException(); } @Override public int size() { return 5; } @Override public void clear() { throw new UnsupportedOperationException(); } }); } }
3,124
21.482014
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/ImplicitTypesInlinedTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata; import static java.util.Collections.emptyList; import java.util.Collections; import java.util.List; /** * Test data for {@code ImplicitTypesInlinedTemplate}. * * @author lowasser@google.com (Louis Wasserman) */ public class ImplicitTypesInlinedTemplateExample { @SuppressWarnings("unused") public void foo() { List<String> stringList = Collections.emptyList(); List<Double> doubleList = emptyList(); List<Integer> intList = Collections.synchronizedList(Collections.<Integer>emptyList()); } }
1,165
32.314286
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/IfTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata; import java.util.Comparator; /** * Test data for {@code IfTemplate}. * * @author lowasser@google.com (Louis Wasserman) */ public class IfTemplateExample { public String example() { String foo; if (Math.random() < 0.5) { foo = "bar"; } else { foo = "baz"; } Comparator<String> comparator; if (true) { comparator = new Comparator<String>() { @Override public int compare(String a, String b) { return a.length() - b.length(); } }; } else { comparator = String.CASE_INSENSITIVE_ORDER; } System.out.println(comparator); return foo; } }
1,293
26.531915
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/MayOptionallyUseTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; import java.io.UnsupportedEncodingException; /** * Test data for {@code MayOptionallyUseTemplate}. * * @author lowasser@google.com (Louis Wasserman) */ public class MayOptionallyUseTemplateExample { public void example1() { try { System.out.println(new String(new byte[0], "UTF-8")); } catch (UnsupportedEncodingException e) { } } public void example2() { try { System.out.println(new String(new byte[0], "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }
1,199
28.268293
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/InferredThisTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; /** * Test data for {@code InferredThisTemplate}. * * @author lowasser@google.com (Louis Wasserman) */ public class InferredThisTemplateExample { public void example() { new Thread() { @Override public void run() { this.setName(this.getName()); setName(getName()); } }.start(); } }
990
27.314286
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/BinaryTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; import java.util.Random; /** * Test input for {@code BinaryTemplate}. * * @author lowasser@google.com (Louis Wasserman) */ class BinaryTemplateExample { public void example(int x, int y) { // positive examples System.out.println((0xFF + 5) / 2); System.out.println((x + y) / 2 + 20); System.err.println((y + new Random().nextInt()) / 2); // negative examples System.out.println((x + y /* signed division */) / 2 + 20); System.out.println(x + y / 2); System.out.println((x - y) / 2); System.out.println((x * y) / 2); System.out.println((x + y) / 3); System.out.println((x + 5L) / 2); } }
1,298
30.682927
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/EmitCommentBeforeTemplateExample.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata; public class EmitCommentBeforeTemplateExample { public void example() { System.out.println("foobar".length()); } }
772
34.136364
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/StaticImportClassTokenTemplateExample.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; /** Test data for {@code StaticImportClassTokenTemplate}. */ public class StaticImportClassTokenTemplateExample { public void example() { boolean eq = "a" instanceof String; } }
843
32.76
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/AnyOfTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata; /** * Test input for {@code AnyOfTemplate} refactoring. * * @author lowasser@google.com (Louis Wasserman) */ public class AnyOfTemplateExample { public void foo(double d) { if (Math.signum(d) == 0.0) { System.out.println("zero"); } if (0.0 == Math.signum(d)) { System.out.println("also zero"); } } }
986
29.84375
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/ArrayTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata; import java.util.Arrays; import java.util.List; /** * Test data for {@code ArrayTemplate}. * * @author mdempsky@google.com (Matthew Dempsky) */ public class ArrayTemplateExample { public void foo() { List<String> list = Arrays.asList("foo", "bar"); System.out.println(list.get(1)); } }
953
29.774194
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/ImportClassDirectlyTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; import java.util.Map; /** * Test input for {@code ImportClassDirectlyTemplate}. * * @author Louis Wasserman */ public class ImportClassDirectlyTemplateExample { public void example(Map<String, Integer> map) { for (String str : map.keySet()) { System.out.println(str + " " + map.get(str)); } } }
976
27.735294
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/LambdaImplicitTypeExample.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; import java.util.Arrays; import java.util.stream.Collectors; public class LambdaImplicitTypeExample { public void example() { System.out.println( Arrays.asList("foo", "bar").stream().collect(Collectors.reducing((a, b) -> b))); } }
905
31.357143
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/AsVarargsTemplateExample.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; import java.util.stream.IntStream; import java.util.stream.Stream; /** * Test data for AsVarargsTemplate. * * @author Louis Wasserman */ public class AsVarargsTemplateExample { public void example() { System.out.println( Stream.of(IntStream.of(1), IntStream.of(2)).flatMap(s -> s.boxed()).mapToInt(i -> i).sum()); // unchanged, it's not using the varargs overload System.out.println( Stream.of(IntStream.of(1)).flatMap(s -> s.boxed()).mapToInt(i -> i).sum()); } }
1,163
30.459459
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/NonJdkTypeTemplateExample.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; import com.google.common.collect.ImmutableList; import java.util.stream.Stream; /** Test data for {@code NonJdkTypeTemplate}. */ public class NonJdkTypeTemplateExample { ImmutableList<Integer> example() { return ImmutableList.copyOf(Stream.of(1).iterator()); } }
929
32.214286
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/LabelTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; import java.math.BigInteger; /** * Test data for {@code LabelTemplate}. * * @author lowasser@google.com (Louis Wasserman) */ public class LabelTemplateExample { public void example(BigInteger[] array) { StringBuilder builder = new StringBuilder("["); for (int i = 0; i < array.length; i++) { builder.append(array[i]); if (i == array.length - 1) { break; } builder.append(','); } join: for (int i = 0; i < array.length; i++) { builder.append(array[i]); if (i == array.length - 1) { break join; } builder.append(','); } join: for (int i = 0; i < array.length; i++) { builder.append(array[i]); if (i == array.length - 1) { continue join; } builder.append(','); } System.out.println(builder); } }
1,488
27.09434
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/DiamondTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata; import java.util.LinkedList; import java.util.List; /** * Test data for {@code DiamondTemplate}. */ public class DiamondTemplateExample { public void example() { List<Integer> explicit = new LinkedList<Integer>(); List<Integer> diamond = new LinkedList<>(); @SuppressWarnings("rawtypes") List<Integer> raw = new LinkedList(); System.out.println(explicit + " " + diamond + " " + raw); } }
1,064
32.28125
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/EmitCommentTemplateExample.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata; public class EmitCommentTemplateExample { public void example() { System.out.println("foobar"); } }
757
33.454545
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/ReturnPlaceholderTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata; import com.google.common.collect.Ordering; /** * Test data for {@code ReturnPlaceholderTemplate}. * * @author lowasser@google.com (Louis Wasserman) */ public class ReturnPlaceholderTemplateExample { public static final Ordering<String> LENGTH_THEN_LOWER_CASE_ONE_LINE = new Ordering<String>() { @Override public int compare(String left, String right) { int lengthCmp = Integer.compare(left.length(), right.length()); if (lengthCmp != 0) { return lengthCmp; } return left.toLowerCase().compareTo(right.toLowerCase()); } }; public static final Ordering<String> LENGTH_THEN_LOWER_CASE_MULTI_LINE = new Ordering<String>() { @Override public int compare(String left, String right) { int lengthCmp = Integer.compare(left.length(), right.length()); if (lengthCmp != 0) { return lengthCmp; } String leftLower = left.toLowerCase(); String rightLower = right.toLowerCase(); return leftLower.compareTo(rightLower); } }; }
1,676
33.22449
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/InferLambdaBodyTypeExample.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; import java.util.Collection; /** Sample data for InferLambdaBodyType. */ public class InferLambdaBodyTypeExample { static void example(Collection<Integer> collection) { for (Integer i : collection) { System.out.println(i); } for (Integer i : collection) { int j = i + 1; System.out.println(j); } } }
996
29.212121
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/BlockPlaceholderTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; import com.google.common.io.ByteStreams; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; /** * Test data for {@code BlockPlaceholderTemplate}. */ public class BlockPlaceholderTemplateExample { public void positiveExample1() throws IOException { InputStream stream = new FileInputStream("foo.bar"); try { System.out.println(ByteStreams.toByteArray(stream).length); } finally { stream.close(); } } public void positiveExample2() throws IOException { InputStream stream = new FileInputStream("foo.bar"); try { int count = 0; while (true) { int b = stream.read(); if (b == -1) { break; } count++; } System.out.println(count); } finally { stream.close(); } } public void negativeExample1() throws IOException { // modifies placeholder parameter InputStream stream = null; try { stream = new FileInputStream("foo.bar"); System.out.println(ByteStreams.toByteArray(stream).length); } finally { stream.close(); } } public void negativeExample2() throws IOException { // changes control flow for (int i = 0; i < 10; i++) { InputStream stream = new FileInputStream("foo.bar"); try { System.out.println(ByteStreams.toByteArray(stream).length); break; } finally { stream.close(); } } } }
2,106
26.723684
87
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/TwoLinesToOneTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata; import java.util.Random; /** * Test data for {@code TwoLinesTemplate}. * * @author lowasser@google.com (Louis Wasserman) */ public class TwoLinesToOneTemplateExample { public int example() { Random rng = new Random(); int x = rng.nextInt(); x = x + rng.nextInt(); x = x + 20; x = x + 5; x = x + rng.nextInt(30); x = x + 20; // comments should block matching x = x + rng.nextInt(); return x; } }
1,093
27.789474
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/VariableDeclTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; /** * Test data for {@code VariableDeclTemplate}. * * @author lowasser@google.com (Louis Wasserman) */ public class VariableDeclTemplateExample { @SuppressWarnings("unused") public void example() { int a = Integer.valueOf("3"); Integer b = Integer.valueOf("3"); final int c = Integer.valueOf("3"); } }
982
29.71875
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/InferLambdaTypeExample.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; import java.util.Arrays; import java.util.stream.Collectors; public class InferLambdaTypeExample { public void example() { System.out.println( Arrays.asList("foo", "bar") .stream() .collect(Collectors.reducing((String a, String b) -> b))); System.out.println( Arrays.asList("foo", "bar").stream().collect(Collectors.reducing((a, b) -> b))); } }
1,055
32
88
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/TryMultiCatchTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; /** * Test data for {@code TryMultiCatchTemplate}. * * @author lowasser@google.com (Louis Wasserman) */ public class TryMultiCatchTemplateExample { public void foo() { String str = null; try { str = String.class.newInstance(); } catch (IllegalAccessException | InstantiationException | SecurityException tolerated) { tolerated.printStackTrace(); } System.out.println(str); } }
1,075
29.742857
93
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/PlaceholderAllowedVarsTemplateExample.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata; public class PlaceholderAllowedVarsTemplateExample { public void shouldMatch() { String accum = "foo"; if (!"foo".equals("bar")) { System.out.println("in if"); accum += "bar"; } System.out.println("foo"); } public void shouldNotMatch() { String accum = "foo"; if (!"foo".equals("bar")) { System.out.println(accum); accum += "bar"; } System.out.println("foo"); } }
1,078
28.972222
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/PlaceholderTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; import java.util.Iterator; import java.util.List; /** * Test data for {@code PlaceholderTemplate}. */ public class PlaceholderTemplateExample { public void positiveExample(List<Integer> list) { Iterator<Integer> itr = list.iterator(); while (itr.hasNext()) { if (itr.next() < 0) { itr.remove(); } } } public void negativeIdentityExample(List<Boolean> list) { Iterator<Boolean> itr = list.iterator(); while (itr.hasNext()) { if (itr.next()) { itr.remove(); } } } public void refersToForbiddenVariable(List<Integer> list) { Iterator<Integer> itr = list.iterator(); while (itr.hasNext()) { if (itr.next() < list.size()) { itr.remove(); } } } }
1,413
25.679245
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/GenericPlaceholderTemplateExample.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata; import java.util.UUID; /** * Example usage of {@code GenericPlaceholderTemplate}. */ public class GenericPlaceholderTemplateExample { public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.println(UUID.randomUUID()); } } }
921
30.793103
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/VoidExpressionPlaceholderTemplateExample.java
/* * Copyright 2022 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; import java.util.List; /** Test data for {@code VoidExpressionPlaceholderTemplate}. */ public class VoidExpressionPlaceholderTemplateExample { public static void foo(String s) { s.length(); } public void positiveExample(List<String> list) { list.stream().forEach(x -> foo(x)); } }
956
29.870968
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/AutoboxingTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata; import java.util.Collections; /** * Test data for {@code AutoboxingTemplate}. * * @author lowasser@google.com (Louis Wasserman) */ public class AutoboxingTemplateExample { public void foo() { System.out.println(Collections.singletonList(5)); } }
908
30.344828
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/TypeArgumentsMethodInvocationTemplateExample.java
/* * Copyright 2022 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** Test data for {@code TypeArgumentsMethodInvocationTemplate}. */ public class TypeArgumentsMethodInvocationTemplateExample { public Future<Object> example() { ExecutorService executorService = Executors.newSingleThreadExecutor(); return executorService.submit(() -> new Object()); } }
1,070
37.25
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/MultiBoundTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; import java.nio.CharBuffer; /** * Test data for {@code MultiBoundTemplate}. */ public class MultiBoundTemplateExample { public void example() { System.out.println(new StringBuilder("foo")); System.out.println(CharBuffer.wrap("foo")); } }
910
29.366667
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/MultipleReferencesToIdentifierTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata; /** * Example input for {@code MultipleReferencesToIdentifierTemplate}. * * @author lowasser@google.com (Louis Wasserman) */ public class MultipleReferencesToIdentifierTemplateExample { public void example(int x, int y, String text) { // positive examples System.out.println(true || true); System.out.println((x == y) || (x == y)); System.out.println(text.contains("棒球場") || text.contains("棒球場")); // negative examples System.out.println((x == y) || (y == x)); } }
1,147
34.875
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/SuppressWarningsTemplateExample.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; /** Test data for {@code SuppressWarningsTemplate}. */ public class SuppressWarningsTemplateExample { @SuppressWarnings("SuppressWarningsTemplate") public int abs1(int x) { return x < 0 ? -x : x; } @SuppressWarnings("SuppressWarningsTemplate") static class Inner { public int abs2(int x) { return x < 0 ? -x : x; } } public int abs3(int x) { @SuppressWarnings("SuppressWarningsTemplate") int r = x < 0 ? -x : x; return r; } public int abs4(int x) { return x < 0 ? -x : x; } }
1,190
26.697674
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/StaticFieldTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata; import java.util.Collections; import java.util.List; /** * Test data for {@code StaticFieldTemplate}. * * @author mdempsky@google.com (Matthew Dempsky) */ public class StaticFieldTemplateExample { public void foo() { @SuppressWarnings("unchecked") List<Integer> list = Collections.EMPTY_LIST; System.out.println(list); } }
993
30.0625
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/IfFallthroughTemplateExample.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; import com.google.common.collect.Ordering; import java.util.Comparator; /** * Test data for {@code IfFallthroughTemplate}. */ public class IfFallthroughTemplateExample { public Comparator<String> example1() { return new Comparator<String>() { @Override public int compare(String o1, String o2) { if (o1 == null && o2 == null) { return 0; } if (o1 == null) { return -1; } if (o2 == null) { return 1; } return Ordering.natural().compare(o1, o2); } }; } public Comparator<String> example2() { return new Comparator<String>() { @Override public int compare(String o1, String o2) { if (o1 == null && o2 == null) { return 0; } if (o1 == null) { return -1; } if (o2 != null) { return Ordering.natural().compare(o1, o2); } return 1; } }; } }
1,627
25.258065
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/UnnecessaryLambdaParensExample.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; import java.util.Arrays; import java.util.stream.Collectors; public class UnnecessaryLambdaParensExample { public void example() { System.out.println(Arrays.asList("foo", "bar").stream().map((x) -> x).collect(Collectors.reducing((a, b) -> b))); } }
915
32.925926
117
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/MethodInvocationTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * Example input for {@code MethodInvocationTemplate}. * * @author lowasser@google.com (Louis Wasserman) */ public class MethodInvocationTemplateExample { public void example(MessageDigest digest, String string) throws NoSuchAlgorithmException { // positive examples MessageDigest.getInstance("MD5").digest("foo".getBytes()); digest.digest("foo".getBytes()); MessageDigest.getInstance("SHA1").digest(string.getBytes()); digest.digest((string + 90).getBytes()); // negative examples System.out.println("foo".getBytes()); } }
1,305
33.368421
92
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/OneLineToTwoTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata; import java.util.Random; /** * Test data for {@code OneLineToTwoTemplate}. * * @author lowasser@google.com (Louis Wasserman) */ public class OneLineToTwoTemplateExample { public int example() { Random rng = new Random(); int x = rng.nextInt(); x = x + rng.nextInt() + 20; x = x + 5 + rng.nextInt(30); return x; } }
994
29.151515
100
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/PlaceholderAllowsIdentityTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; import java.util.Iterator; import java.util.List; /** * Test data for {@code PlaceholderTemplate}. */ public class PlaceholderAllowsIdentityTemplateExample { public void positiveExample(List<Integer> list) { Iterator<Integer> itr = list.iterator(); while (itr.hasNext()) { if (itr.next() < 0) { itr.remove(); } } } public void positiveIdentityExample(List<Boolean> list) { Iterator<Boolean> itr = list.iterator(); while (itr.hasNext()) { if (itr.next()) { itr.remove(); } } } public void refersToForbiddenVariable(List<Integer> list) { Iterator<Integer> itr = list.iterator(); while (itr.hasNext()) { if (itr.next() < list.size()) { itr.remove(); } } } }
1,427
25.943396
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/LiteralTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; import java.nio.charset.Charset; /** * Test data for {@code LiteralTemplate}. * * @author lowasser@google.com (Louis Wasserman) */ public class LiteralTemplateExample { public void example() { System.out.println(new String(new byte[0], Charset.forName("UTF-8"))); } }
939
29.322581
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/WildcardUnificationTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.refaster.testdata; import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.ImmutableList; /** * Test data for {@code WildcardUnificationTemplate}. * * @author kak@google.com (Kurt Kluever) */ public class WildcardUnificationTemplateExample { public void example() { ImmutableList<String> actual = ImmutableList.of("kurt", "kluever"); ImmutableList<String> expected = ImmutableList.of("kluever", "kurt"); assertThat(actual).hasSize(expected.size()); assertThat(actual).containsAtLeastElementsIn(expected); } }
1,207
32.555556
75
java
error-prone
error-prone-master/core/src/test/java/com/google/errorprone/refaster/testdata/input/ComparisonChainTemplateExample.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.refaster.testdata; /** * Test data for {@code ComparisonChainTemplate}. */ public class ComparisonChainTemplateExample { public int compare(String a, String b) { int cmp = Integer.valueOf(a.length()).compareTo(Integer.valueOf(b.length())); if (cmp == 0) { return a.compareTo(b); } else { return cmp; } } }
970
31.366667
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/ErrorProneJavaCompiler.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone; import com.google.errorprone.scanner.BuiltInCheckerSuppliers; import com.google.errorprone.scanner.ScannerSupplier; import com.sun.tools.javac.api.JavacTool; import javax.tools.JavaCompiler; /** * An Error Prone compiler that implements {@link javax.tools.JavaCompiler}. * * <p>Runs all built-in checks by default. * * @author nik */ public class ErrorProneJavaCompiler extends BaseErrorProneJavaCompiler { public ErrorProneJavaCompiler() { this(JavacTool.create()); } ErrorProneJavaCompiler(JavaCompiler javacTool) { super(javacTool, BuiltInCheckerSuppliers.defaultChecks()); } public ErrorProneJavaCompiler(ScannerSupplier scannerSupplier) { super(JavacTool.create(), scannerSupplier); } }
1,367
29.4
76
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/ErrorProneJavacPlugin.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone; import com.google.auto.service.AutoService; import com.google.errorprone.scanner.BuiltInCheckerSuppliers; import com.sun.source.util.JavacTask; import com.sun.source.util.Plugin; /** A javac {@link Plugin} that runs Error Prone. */ @AutoService(Plugin.class) public class ErrorProneJavacPlugin implements Plugin { @Override public String getName() { return "ErrorProne"; } @Override public void init(JavacTask javacTask, String... args) { BaseErrorProneJavaCompiler.addTaskListener( javacTask, BuiltInCheckerSuppliers.defaultChecks(), ErrorProneOptions.processArgs(args)); } }
1,248
31.868421
97
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/scanner/BuiltInCheckerSuppliers.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.scanner; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Streams; import com.google.errorprone.BugCheckerInfo; import com.google.errorprone.bugpatterns.ASTHelpersSuggestions; import com.google.errorprone.bugpatterns.AlreadyChecked; import com.google.errorprone.bugpatterns.AlwaysThrows; import com.google.errorprone.bugpatterns.AmbiguousMethodReference; import com.google.errorprone.bugpatterns.AnnotateFormatMethod; import com.google.errorprone.bugpatterns.AnnotationMirrorToString; import com.google.errorprone.bugpatterns.AnnotationPosition; import com.google.errorprone.bugpatterns.AnnotationValueToString; import com.google.errorprone.bugpatterns.ArrayAsKeyOfSetOrMap; import com.google.errorprone.bugpatterns.ArrayEquals; import com.google.errorprone.bugpatterns.ArrayFillIncompatibleType; import com.google.errorprone.bugpatterns.ArrayHashCode; import com.google.errorprone.bugpatterns.ArrayToString; import com.google.errorprone.bugpatterns.ArraysAsListPrimitiveArray; import com.google.errorprone.bugpatterns.AssertFalse; import com.google.errorprone.bugpatterns.AssertThrowsMultipleStatements; import com.google.errorprone.bugpatterns.AssertionFailureIgnored; import com.google.errorprone.bugpatterns.AsyncCallableReturnsNull; import com.google.errorprone.bugpatterns.AsyncFunctionReturnsNull; import com.google.errorprone.bugpatterns.AttemptedNegativeZero; import com.google.errorprone.bugpatterns.AutoValueBuilderDefaultsInConstructor; import com.google.errorprone.bugpatterns.AutoValueFinalMethods; import com.google.errorprone.bugpatterns.AutoValueImmutableFields; import com.google.errorprone.bugpatterns.AutoValueSubclassLeaked; import com.google.errorprone.bugpatterns.AvoidObjectArrays; import com.google.errorprone.bugpatterns.BadAnnotationImplementation; import com.google.errorprone.bugpatterns.BadComparable; import com.google.errorprone.bugpatterns.BadImport; import com.google.errorprone.bugpatterns.BadInstanceof; import com.google.errorprone.bugpatterns.BadShiftAmount; import com.google.errorprone.bugpatterns.BanClassLoader; import com.google.errorprone.bugpatterns.BanJNDI; import com.google.errorprone.bugpatterns.BanSerializableRead; import com.google.errorprone.bugpatterns.BareDotMetacharacter; import com.google.errorprone.bugpatterns.BigDecimalEquals; import com.google.errorprone.bugpatterns.BigDecimalLiteralDouble; import com.google.errorprone.bugpatterns.BooleanParameter; import com.google.errorprone.bugpatterns.BoxedPrimitiveConstructor; import com.google.errorprone.bugpatterns.BoxedPrimitiveEquality; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugPatternNaming; import com.google.errorprone.bugpatterns.ByteBufferBackingArray; import com.google.errorprone.bugpatterns.CacheLoaderNull; import com.google.errorprone.bugpatterns.CannotMockFinalClass; import com.google.errorprone.bugpatterns.CannotMockMethod; import com.google.errorprone.bugpatterns.CanonicalDuration; import com.google.errorprone.bugpatterns.CatchAndPrintStackTrace; import com.google.errorprone.bugpatterns.CatchFail; import com.google.errorprone.bugpatterns.CatchingUnchecked; import com.google.errorprone.bugpatterns.ChainedAssertionLosesContext; import com.google.errorprone.bugpatterns.ChainingConstructorIgnoresParameter; import com.google.errorprone.bugpatterns.CharacterGetNumericValue; import com.google.errorprone.bugpatterns.CheckNotNullMultipleTimes; import com.google.errorprone.bugpatterns.CheckReturnValue; import com.google.errorprone.bugpatterns.CheckedExceptionNotThrown; import com.google.errorprone.bugpatterns.ClassCanBeStatic; import com.google.errorprone.bugpatterns.ClassName; import com.google.errorprone.bugpatterns.ClassNamedLikeTypeParameter; import com.google.errorprone.bugpatterns.ClassNewInstance; import com.google.errorprone.bugpatterns.CollectionToArraySafeParameter; import com.google.errorprone.bugpatterns.CollectorShouldNotUseState; import com.google.errorprone.bugpatterns.ComparableAndComparator; import com.google.errorprone.bugpatterns.ComparableType; import com.google.errorprone.bugpatterns.CompareToZero; import com.google.errorprone.bugpatterns.ComparingThisWithNull; import com.google.errorprone.bugpatterns.ComparisonContractViolated; import com.google.errorprone.bugpatterns.ComparisonOutOfRange; import com.google.errorprone.bugpatterns.CompileTimeConstantChecker; import com.google.errorprone.bugpatterns.ComplexBooleanConstant; import com.google.errorprone.bugpatterns.ComputeIfAbsentAmbiguousReference; import com.google.errorprone.bugpatterns.ConditionalExpressionNumericPromotion; import com.google.errorprone.bugpatterns.ConstantField; import com.google.errorprone.bugpatterns.ConstantOverflow; import com.google.errorprone.bugpatterns.ConstantPatternCompile; import com.google.errorprone.bugpatterns.DangerousLiteralNullChecker; import com.google.errorprone.bugpatterns.DateFormatConstant; import com.google.errorprone.bugpatterns.DeadException; import com.google.errorprone.bugpatterns.DeadThread; import com.google.errorprone.bugpatterns.DeduplicateConstants; import com.google.errorprone.bugpatterns.DefaultCharset; import com.google.errorprone.bugpatterns.DefaultPackage; import com.google.errorprone.bugpatterns.DepAnn; import com.google.errorprone.bugpatterns.DeprecatedVariable; import com.google.errorprone.bugpatterns.DifferentNameButSame; import com.google.errorprone.bugpatterns.DirectInvocationOnMock; import com.google.errorprone.bugpatterns.DiscardedPostfixExpression; import com.google.errorprone.bugpatterns.DistinctVarargsChecker; import com.google.errorprone.bugpatterns.DoNotCallChecker; import com.google.errorprone.bugpatterns.DoNotCallSuggester; import com.google.errorprone.bugpatterns.DoNotClaimAnnotations; import com.google.errorprone.bugpatterns.DoNotMockAutoValue; import com.google.errorprone.bugpatterns.DoNotMockChecker; import com.google.errorprone.bugpatterns.DoNotUseRuleChain; import com.google.errorprone.bugpatterns.DoubleBraceInitialization; import com.google.errorprone.bugpatterns.DuplicateMapKeys; import com.google.errorprone.bugpatterns.EmptyCatch; import com.google.errorprone.bugpatterns.EmptyIfStatement; import com.google.errorprone.bugpatterns.EmptyTopLevelDeclaration; import com.google.errorprone.bugpatterns.EqualsGetClass; import com.google.errorprone.bugpatterns.EqualsHashCode; import com.google.errorprone.bugpatterns.EqualsIncompatibleType; import com.google.errorprone.bugpatterns.EqualsNaN; import com.google.errorprone.bugpatterns.EqualsNull; import com.google.errorprone.bugpatterns.EqualsReference; import com.google.errorprone.bugpatterns.EqualsUnsafeCast; import com.google.errorprone.bugpatterns.EqualsUsingHashCode; import com.google.errorprone.bugpatterns.EqualsWrongThing; import com.google.errorprone.bugpatterns.ErroneousBitwiseExpression; import com.google.errorprone.bugpatterns.ErroneousThreadPoolConstructorChecker; import com.google.errorprone.bugpatterns.ExpectedExceptionChecker; import com.google.errorprone.bugpatterns.ExtendingJUnitAssert; import com.google.errorprone.bugpatterns.ExtendsAutoValue; import com.google.errorprone.bugpatterns.FallThrough; import com.google.errorprone.bugpatterns.FieldCanBeFinal; import com.google.errorprone.bugpatterns.FieldCanBeLocal; import com.google.errorprone.bugpatterns.FieldCanBeStatic; import com.google.errorprone.bugpatterns.Finalize; import com.google.errorprone.bugpatterns.Finally; import com.google.errorprone.bugpatterns.FloatCast; import com.google.errorprone.bugpatterns.FloatingPointAssertionWithinEpsilon; import com.google.errorprone.bugpatterns.FloatingPointLiteralPrecision; import com.google.errorprone.bugpatterns.ForEachIterable; import com.google.errorprone.bugpatterns.ForOverrideChecker; import com.google.errorprone.bugpatterns.FunctionalInterfaceClash; import com.google.errorprone.bugpatterns.FunctionalInterfaceMethodChanged; import com.google.errorprone.bugpatterns.FutureReturnValueIgnored; import com.google.errorprone.bugpatterns.FuturesGetCheckedIllegalExceptionType; import com.google.errorprone.bugpatterns.FuzzyEqualsShouldNotBeUsedInEqualsMethod; import com.google.errorprone.bugpatterns.GetClassOnAnnotation; import com.google.errorprone.bugpatterns.GetClassOnClass; import com.google.errorprone.bugpatterns.GetClassOnEnum; import com.google.errorprone.bugpatterns.HashtableContains; import com.google.errorprone.bugpatterns.HidingField; import com.google.errorprone.bugpatterns.ICCProfileGetInstance; import com.google.errorprone.bugpatterns.IdentityBinaryExpression; import com.google.errorprone.bugpatterns.IdentityHashMapBoxing; import com.google.errorprone.bugpatterns.IdentityHashMapUsage; import com.google.errorprone.bugpatterns.IgnoredPureGetter; import com.google.errorprone.bugpatterns.ImmutableMemberCollection; import com.google.errorprone.bugpatterns.ImmutableSetForContains; import com.google.errorprone.bugpatterns.ImplementAssertionWithChaining; import com.google.errorprone.bugpatterns.ImpossibleNullComparison; import com.google.errorprone.bugpatterns.Incomparable; import com.google.errorprone.bugpatterns.IncompatibleModifiersChecker; import com.google.errorprone.bugpatterns.InconsistentCapitalization; import com.google.errorprone.bugpatterns.InconsistentHashCode; import com.google.errorprone.bugpatterns.IncorrectMainMethod; import com.google.errorprone.bugpatterns.IncrementInForLoopAndHeader; import com.google.errorprone.bugpatterns.IndexOfChar; import com.google.errorprone.bugpatterns.InexactVarargsConditional; import com.google.errorprone.bugpatterns.InfiniteRecursion; import com.google.errorprone.bugpatterns.InitializeInline; import com.google.errorprone.bugpatterns.InjectOnBugCheckers; import com.google.errorprone.bugpatterns.InlineTrivialConstant; import com.google.errorprone.bugpatterns.InputStreamSlowMultibyteRead; import com.google.errorprone.bugpatterns.InsecureCipherMode; import com.google.errorprone.bugpatterns.InstanceOfAndCastMatchWrongType; import com.google.errorprone.bugpatterns.IntLongMath; import com.google.errorprone.bugpatterns.InterfaceWithOnlyStatics; import com.google.errorprone.bugpatterns.InterruptedExceptionSwallowed; import com.google.errorprone.bugpatterns.Interruption; import com.google.errorprone.bugpatterns.InvalidPatternSyntax; import com.google.errorprone.bugpatterns.InvalidTimeZoneID; import com.google.errorprone.bugpatterns.InvalidZoneId; import com.google.errorprone.bugpatterns.IsInstanceIncompatibleType; import com.google.errorprone.bugpatterns.IsInstanceOfClass; import com.google.errorprone.bugpatterns.IterableAndIterator; import com.google.errorprone.bugpatterns.IterablePathParameter; import com.google.errorprone.bugpatterns.JUnit3FloatingPointComparisonWithoutDelta; import com.google.errorprone.bugpatterns.JUnit3TestNotRun; import com.google.errorprone.bugpatterns.JUnit4ClassAnnotationNonStatic; import com.google.errorprone.bugpatterns.JUnit4ClassUsedInJUnit3; import com.google.errorprone.bugpatterns.JUnit4SetUpNotRun; import com.google.errorprone.bugpatterns.JUnit4TearDownNotRun; import com.google.errorprone.bugpatterns.JUnit4TestNotRun; import com.google.errorprone.bugpatterns.JUnit4TestsNotRunWithinEnclosed; import com.google.errorprone.bugpatterns.JUnitAmbiguousTestClass; import com.google.errorprone.bugpatterns.JUnitAssertSameCheck; import com.google.errorprone.bugpatterns.JUnitParameterMethodNotFound; import com.google.errorprone.bugpatterns.JavaLangClash; import com.google.errorprone.bugpatterns.JavaUtilDateChecker; import com.google.errorprone.bugpatterns.JdkObsolete; import com.google.errorprone.bugpatterns.LabelledBreakTarget; import com.google.errorprone.bugpatterns.LambdaFunctionalInterface; import com.google.errorprone.bugpatterns.LenientFormatStringValidation; import com.google.errorprone.bugpatterns.LiteByteStringUtf8; import com.google.errorprone.bugpatterns.LiteEnumValueOf; import com.google.errorprone.bugpatterns.LiteProtoToString; import com.google.errorprone.bugpatterns.LockNotBeforeTry; import com.google.errorprone.bugpatterns.LockOnBoxedPrimitive; import com.google.errorprone.bugpatterns.LockOnNonEnclosingClassLiteral; import com.google.errorprone.bugpatterns.LogicalAssignment; import com.google.errorprone.bugpatterns.LongDoubleConversion; import com.google.errorprone.bugpatterns.LongFloatConversion; import com.google.errorprone.bugpatterns.LongLiteralLowerCaseSuffix; import com.google.errorprone.bugpatterns.LoopConditionChecker; import com.google.errorprone.bugpatterns.LoopOverCharArray; import com.google.errorprone.bugpatterns.LossyPrimitiveCompare; import com.google.errorprone.bugpatterns.MathAbsoluteNegative; import com.google.errorprone.bugpatterns.MathRoundIntLong; import com.google.errorprone.bugpatterns.MemberName; import com.google.errorprone.bugpatterns.MemoizeConstantVisitorStateLookups; import com.google.errorprone.bugpatterns.MethodCanBeStatic; import com.google.errorprone.bugpatterns.MissingBraces; import com.google.errorprone.bugpatterns.MissingCasesInEnumSwitch; import com.google.errorprone.bugpatterns.MissingDefault; import com.google.errorprone.bugpatterns.MissingFail; import com.google.errorprone.bugpatterns.MissingImplementsComparable; import com.google.errorprone.bugpatterns.MissingOverride; import com.google.errorprone.bugpatterns.MissingRefasterAnnotation; import com.google.errorprone.bugpatterns.MissingSuperCall; import com.google.errorprone.bugpatterns.MissingTestCall; import com.google.errorprone.bugpatterns.MisusedDayOfYear; import com.google.errorprone.bugpatterns.MisusedWeekYear; import com.google.errorprone.bugpatterns.MixedArrayDimensions; import com.google.errorprone.bugpatterns.MixedDescriptors; import com.google.errorprone.bugpatterns.MixedMutabilityReturnType; import com.google.errorprone.bugpatterns.MockNotUsedInProduction; import com.google.errorprone.bugpatterns.MockitoUsage; import com.google.errorprone.bugpatterns.ModifiedButNotUsed; import com.google.errorprone.bugpatterns.ModifyCollectionInEnhancedForLoop; import com.google.errorprone.bugpatterns.ModifySourceCollectionInStream; import com.google.errorprone.bugpatterns.ModifyingCollectionWithItself; import com.google.errorprone.bugpatterns.MultiVariableDeclaration; import com.google.errorprone.bugpatterns.MultipleParallelOrSequentialCalls; import com.google.errorprone.bugpatterns.MultipleTopLevelClasses; import com.google.errorprone.bugpatterns.MultipleUnaryOperatorsInMethodCall; import com.google.errorprone.bugpatterns.MustBeClosedChecker; import com.google.errorprone.bugpatterns.MutablePublicArray; import com.google.errorprone.bugpatterns.NCopiesOfChar; import com.google.errorprone.bugpatterns.NamedLikeContextualKeyword; import com.google.errorprone.bugpatterns.NarrowCalculation; import com.google.errorprone.bugpatterns.NarrowingCompoundAssignment; import com.google.errorprone.bugpatterns.NegativeCharLiteral; import com.google.errorprone.bugpatterns.NestedInstanceOfConditions; import com.google.errorprone.bugpatterns.NewFileSystem; import com.google.errorprone.bugpatterns.NoAllocationChecker; import com.google.errorprone.bugpatterns.NonApiType; import com.google.errorprone.bugpatterns.NonAtomicVolatileUpdate; import com.google.errorprone.bugpatterns.NonCanonicalStaticImport; import com.google.errorprone.bugpatterns.NonCanonicalStaticMemberImport; import com.google.errorprone.bugpatterns.NonCanonicalType; import com.google.errorprone.bugpatterns.NonFinalCompileTimeConstant; import com.google.errorprone.bugpatterns.NonOverridingEquals; import com.google.errorprone.bugpatterns.NonRuntimeAnnotation; import com.google.errorprone.bugpatterns.NullOptional; import com.google.errorprone.bugpatterns.NullTernary; import com.google.errorprone.bugpatterns.NullableConstructor; import com.google.errorprone.bugpatterns.NullableOnContainingClass; import com.google.errorprone.bugpatterns.NullablePrimitive; import com.google.errorprone.bugpatterns.NullablePrimitiveArray; import com.google.errorprone.bugpatterns.NullableVoid; import com.google.errorprone.bugpatterns.ObjectEqualsForPrimitives; import com.google.errorprone.bugpatterns.ObjectToString; import com.google.errorprone.bugpatterns.ObjectsHashCodePrimitive; import com.google.errorprone.bugpatterns.OperatorPrecedence; import com.google.errorprone.bugpatterns.OptionalEquality; import com.google.errorprone.bugpatterns.OptionalMapToOptional; import com.google.errorprone.bugpatterns.OptionalMapUnusedValue; import com.google.errorprone.bugpatterns.OptionalNotPresent; import com.google.errorprone.bugpatterns.OptionalOfRedundantMethod; import com.google.errorprone.bugpatterns.OrphanedFormatString; import com.google.errorprone.bugpatterns.OutlineNone; import com.google.errorprone.bugpatterns.OverrideThrowableToString; import com.google.errorprone.bugpatterns.Overrides; import com.google.errorprone.bugpatterns.PackageInfo; import com.google.errorprone.bugpatterns.PackageLocation; import com.google.errorprone.bugpatterns.ParameterComment; import com.google.errorprone.bugpatterns.ParameterName; import com.google.errorprone.bugpatterns.ParametersButNotParameterized; import com.google.errorprone.bugpatterns.PreconditionsCheckNotNullRepeated; import com.google.errorprone.bugpatterns.PreconditionsInvalidPlaceholder; import com.google.errorprone.bugpatterns.PreferredInterfaceType; import com.google.errorprone.bugpatterns.PrimitiveArrayPassedToVarargsMethod; import com.google.errorprone.bugpatterns.PrimitiveAtomicReference; import com.google.errorprone.bugpatterns.PrivateConstructorForUtilityClass; import com.google.errorprone.bugpatterns.PrivateSecurityContractProtoAccess; import com.google.errorprone.bugpatterns.ProtectedMembersInFinalClass; import com.google.errorprone.bugpatterns.ProtoBuilderReturnValueIgnored; import com.google.errorprone.bugpatterns.ProtoRedundantSet; import com.google.errorprone.bugpatterns.ProtoStringFieldReferenceEquality; import com.google.errorprone.bugpatterns.ProtoTruthMixedDescriptors; import com.google.errorprone.bugpatterns.ProtocolBufferOrdinal; import com.google.errorprone.bugpatterns.PublicApiNamedStreamShouldReturnStream; import com.google.errorprone.bugpatterns.RandomCast; import com.google.errorprone.bugpatterns.RandomModInteger; import com.google.errorprone.bugpatterns.ReachabilityFenceUsage; import com.google.errorprone.bugpatterns.RedundantOverride; import com.google.errorprone.bugpatterns.RedundantThrows; import com.google.errorprone.bugpatterns.ReferenceEquality; import com.google.errorprone.bugpatterns.RemoveUnusedImports; import com.google.errorprone.bugpatterns.RequiredModifiersChecker; import com.google.errorprone.bugpatterns.RestrictedApiChecker; import com.google.errorprone.bugpatterns.RethrowReflectiveOperationExceptionAsLinkageError; import com.google.errorprone.bugpatterns.ReturnValueIgnored; import com.google.errorprone.bugpatterns.ReturnsNullCollection; import com.google.errorprone.bugpatterns.RobolectricShadowDirectlyOn; import com.google.errorprone.bugpatterns.RxReturnValueIgnored; import com.google.errorprone.bugpatterns.SameNameButDifferent; import com.google.errorprone.bugpatterns.SelfAlwaysReturnsThis; import com.google.errorprone.bugpatterns.SelfAssignment; import com.google.errorprone.bugpatterns.SelfComparison; import com.google.errorprone.bugpatterns.SelfEquals; import com.google.errorprone.bugpatterns.ShortCircuitBoolean; import com.google.errorprone.bugpatterns.ShouldHaveEvenArgs; import com.google.errorprone.bugpatterns.SizeGreaterThanOrEqualsZero; import com.google.errorprone.bugpatterns.StatementSwitchToExpressionSwitch; import com.google.errorprone.bugpatterns.StaticAssignmentInConstructor; import com.google.errorprone.bugpatterns.StaticAssignmentOfThrowable; import com.google.errorprone.bugpatterns.StaticMockMember; import com.google.errorprone.bugpatterns.StaticQualifiedUsingExpression; import com.google.errorprone.bugpatterns.StreamResourceLeak; import com.google.errorprone.bugpatterns.StreamToIterable; import com.google.errorprone.bugpatterns.StreamToString; import com.google.errorprone.bugpatterns.StringBuilderInitWithChar; import com.google.errorprone.bugpatterns.StringCaseLocaleUsage; import com.google.errorprone.bugpatterns.StringSplitter; import com.google.errorprone.bugpatterns.StronglyTypeByteString; import com.google.errorprone.bugpatterns.SubstringOfZero; import com.google.errorprone.bugpatterns.SuppressWarningsDeprecated; import com.google.errorprone.bugpatterns.SuppressWarningsWithoutExplanation; import com.google.errorprone.bugpatterns.SwigMemoryLeak; import com.google.errorprone.bugpatterns.SwitchDefault; import com.google.errorprone.bugpatterns.SymbolToString; import com.google.errorprone.bugpatterns.SystemExitOutsideMain; import com.google.errorprone.bugpatterns.SystemOut; import com.google.errorprone.bugpatterns.TestExceptionChecker; import com.google.errorprone.bugpatterns.TestParametersNotInitialized; import com.google.errorprone.bugpatterns.TheoryButNoTheories; import com.google.errorprone.bugpatterns.ThreadJoinLoop; import com.google.errorprone.bugpatterns.ThreadLocalUsage; import com.google.errorprone.bugpatterns.ThreeLetterTimeZoneID; import com.google.errorprone.bugpatterns.ThrowIfUncheckedKnownChecked; import com.google.errorprone.bugpatterns.ThrowNull; import com.google.errorprone.bugpatterns.ThrowSpecificExceptions; import com.google.errorprone.bugpatterns.ThrowsUncheckedException; import com.google.errorprone.bugpatterns.ToStringReturnsNull; import com.google.errorprone.bugpatterns.TooManyParameters; import com.google.errorprone.bugpatterns.TransientMisuse; import com.google.errorprone.bugpatterns.TreeToString; import com.google.errorprone.bugpatterns.TruthAssertExpected; import com.google.errorprone.bugpatterns.TruthConstantAsserts; import com.google.errorprone.bugpatterns.TruthGetOrDefault; import com.google.errorprone.bugpatterns.TruthSelfEquals; import com.google.errorprone.bugpatterns.TryFailRefactoring; import com.google.errorprone.bugpatterns.TryFailThrowable; import com.google.errorprone.bugpatterns.TryWithResourcesVariable; import com.google.errorprone.bugpatterns.TypeEqualsChecker; import com.google.errorprone.bugpatterns.TypeNameShadowing; import com.google.errorprone.bugpatterns.TypeParameterNaming; import com.google.errorprone.bugpatterns.TypeParameterQualifier; import com.google.errorprone.bugpatterns.TypeParameterShadowing; import com.google.errorprone.bugpatterns.TypeParameterUnusedInFormals; import com.google.errorprone.bugpatterns.TypeToString; import com.google.errorprone.bugpatterns.URLEqualsHashCode; import com.google.errorprone.bugpatterns.UndefinedEquals; import com.google.errorprone.bugpatterns.UngroupedOverloads; import com.google.errorprone.bugpatterns.UnicodeDirectionalityCharacters; import com.google.errorprone.bugpatterns.UnicodeEscape; import com.google.errorprone.bugpatterns.UnicodeInCode; import com.google.errorprone.bugpatterns.UnnecessarilyFullyQualified; import com.google.errorprone.bugpatterns.UnnecessarilyVisible; import com.google.errorprone.bugpatterns.UnnecessaryAnonymousClass; import com.google.errorprone.bugpatterns.UnnecessaryAssignment; import com.google.errorprone.bugpatterns.UnnecessaryBoxedAssignment; import com.google.errorprone.bugpatterns.UnnecessaryBoxedVariable; import com.google.errorprone.bugpatterns.UnnecessaryDefaultInEnumSwitch; import com.google.errorprone.bugpatterns.UnnecessaryFinal; import com.google.errorprone.bugpatterns.UnnecessaryLambda; import com.google.errorprone.bugpatterns.UnnecessaryLongToIntConversion; import com.google.errorprone.bugpatterns.UnnecessaryMethodInvocationMatcher; import com.google.errorprone.bugpatterns.UnnecessaryMethodReference; import com.google.errorprone.bugpatterns.UnnecessaryOptionalGet; import com.google.errorprone.bugpatterns.UnnecessaryParentheses; import com.google.errorprone.bugpatterns.UnnecessarySetDefault; import com.google.errorprone.bugpatterns.UnnecessaryStaticImport; import com.google.errorprone.bugpatterns.UnnecessaryStringBuilder; import com.google.errorprone.bugpatterns.UnnecessaryTestMethodPrefix; import com.google.errorprone.bugpatterns.UnnecessaryTypeArgument; import com.google.errorprone.bugpatterns.UnsafeFinalization; import com.google.errorprone.bugpatterns.UnsafeLocaleUsage; import com.google.errorprone.bugpatterns.UnsafeReflectiveConstructionCast; import com.google.errorprone.bugpatterns.UnsynchronizedOverridesSynchronized; import com.google.errorprone.bugpatterns.UnusedAnonymousClass; import com.google.errorprone.bugpatterns.UnusedCollectionModifiedInPlace; import com.google.errorprone.bugpatterns.UnusedException; import com.google.errorprone.bugpatterns.UnusedLabel; import com.google.errorprone.bugpatterns.UnusedMethod; import com.google.errorprone.bugpatterns.UnusedNestedClass; import com.google.errorprone.bugpatterns.UnusedTypeParameter; import com.google.errorprone.bugpatterns.UnusedVariable; import com.google.errorprone.bugpatterns.UseCorrectAssertInTests; import com.google.errorprone.bugpatterns.UseEnumSwitch; import com.google.errorprone.bugpatterns.VarChecker; import com.google.errorprone.bugpatterns.VarTypeName; import com.google.errorprone.bugpatterns.VariableNameSameAsType; import com.google.errorprone.bugpatterns.Varifier; import com.google.errorprone.bugpatterns.WaitNotInLoop; import com.google.errorprone.bugpatterns.WildcardImport; import com.google.errorprone.bugpatterns.WithSignatureDiscouraged; import com.google.errorprone.bugpatterns.WrongOneof; import com.google.errorprone.bugpatterns.XorPower; import com.google.errorprone.bugpatterns.YodaCondition; import com.google.errorprone.bugpatterns.android.BinderIdentityRestoredDangerously; import com.google.errorprone.bugpatterns.android.BundleDeserializationCast; import com.google.errorprone.bugpatterns.android.FragmentInjection; import com.google.errorprone.bugpatterns.android.FragmentNotInstantiable; import com.google.errorprone.bugpatterns.android.HardCodedSdCardPath; import com.google.errorprone.bugpatterns.android.IsLoggableTagLength; import com.google.errorprone.bugpatterns.android.MislabeledAndroidString; import com.google.errorprone.bugpatterns.android.ParcelableCreator; import com.google.errorprone.bugpatterns.android.RectIntersectReturnValueIgnored; import com.google.errorprone.bugpatterns.android.StaticOrDefaultInterfaceMethod; import com.google.errorprone.bugpatterns.android.WakelockReleasedDangerously; import com.google.errorprone.bugpatterns.apidiff.AndroidJdkLibsChecker; import com.google.errorprone.bugpatterns.apidiff.Java7ApiChecker; import com.google.errorprone.bugpatterns.apidiff.Java8ApiChecker; import com.google.errorprone.bugpatterns.argumentselectiondefects.ArgumentSelectionDefectChecker; import com.google.errorprone.bugpatterns.argumentselectiondefects.AssertEqualsArgumentOrderChecker; import com.google.errorprone.bugpatterns.argumentselectiondefects.AutoValueConstructorOrderChecker; import com.google.errorprone.bugpatterns.checkreturnvalue.BuilderReturnThis; import com.google.errorprone.bugpatterns.checkreturnvalue.CanIgnoreReturnValueSuggester; import com.google.errorprone.bugpatterns.checkreturnvalue.NoCanIgnoreReturnValueOnClasses; import com.google.errorprone.bugpatterns.checkreturnvalue.UnnecessarilyUsedValue; import com.google.errorprone.bugpatterns.checkreturnvalue.UsingJsr305CheckReturnValue; import com.google.errorprone.bugpatterns.collectionincompatibletype.CollectionIncompatibleType; import com.google.errorprone.bugpatterns.collectionincompatibletype.CollectionUndefinedEquality; import com.google.errorprone.bugpatterns.collectionincompatibletype.CompatibleWithMisuse; import com.google.errorprone.bugpatterns.collectionincompatibletype.IncompatibleArgumentType; import com.google.errorprone.bugpatterns.collectionincompatibletype.TruthIncompatibleType; import com.google.errorprone.bugpatterns.flogger.FloggerArgumentToString; import com.google.errorprone.bugpatterns.flogger.FloggerFormatString; import com.google.errorprone.bugpatterns.flogger.FloggerLogString; import com.google.errorprone.bugpatterns.flogger.FloggerLogVarargs; import com.google.errorprone.bugpatterns.flogger.FloggerLogWithCause; import com.google.errorprone.bugpatterns.flogger.FloggerMessageFormat; import com.google.errorprone.bugpatterns.flogger.FloggerRedundantIsEnabled; import com.google.errorprone.bugpatterns.flogger.FloggerRequiredModifiers; import com.google.errorprone.bugpatterns.flogger.FloggerSplitLogStatement; import com.google.errorprone.bugpatterns.flogger.FloggerStringConcatenation; import com.google.errorprone.bugpatterns.flogger.FloggerWithCause; import com.google.errorprone.bugpatterns.flogger.FloggerWithoutCause; import com.google.errorprone.bugpatterns.formatstring.FormatString; import com.google.errorprone.bugpatterns.formatstring.FormatStringAnnotationChecker; import com.google.errorprone.bugpatterns.formatstring.InlineFormatString; import com.google.errorprone.bugpatterns.inject.AssistedInjectAndInjectOnConstructors; import com.google.errorprone.bugpatterns.inject.AssistedInjectAndInjectOnSameConstructor; import com.google.errorprone.bugpatterns.inject.AutoFactoryAtInject; import com.google.errorprone.bugpatterns.inject.CloseableProvides; import com.google.errorprone.bugpatterns.inject.InjectOnConstructorOfAbstractClass; import com.google.errorprone.bugpatterns.inject.InjectOnMemberAndConstructor; import com.google.errorprone.bugpatterns.inject.InjectedConstructorAnnotations; import com.google.errorprone.bugpatterns.inject.InvalidTargetingOnScopingAnnotation; import com.google.errorprone.bugpatterns.inject.JavaxInjectOnAbstractMethod; import com.google.errorprone.bugpatterns.inject.JavaxInjectOnFinalField; import com.google.errorprone.bugpatterns.inject.MisplacedScopeAnnotations; import com.google.errorprone.bugpatterns.inject.MoreThanOneInjectableConstructor; import com.google.errorprone.bugpatterns.inject.MoreThanOneQualifier; import com.google.errorprone.bugpatterns.inject.MoreThanOneScopeAnnotationOnClass; import com.google.errorprone.bugpatterns.inject.OverlappingQualifierAndScopeAnnotation; import com.google.errorprone.bugpatterns.inject.QualifierOrScopeOnInjectMethod; import com.google.errorprone.bugpatterns.inject.QualifierWithTypeUse; import com.google.errorprone.bugpatterns.inject.ScopeAnnotationOnInterfaceOrAbstractClass; import com.google.errorprone.bugpatterns.inject.ScopeOrQualifierAnnotationRetention; import com.google.errorprone.bugpatterns.inject.dagger.AndroidInjectionBeforeSuper; import com.google.errorprone.bugpatterns.inject.dagger.EmptySetMultibindingContributions; import com.google.errorprone.bugpatterns.inject.dagger.PrivateConstructorForNoninstantiableModule; import com.google.errorprone.bugpatterns.inject.dagger.ProvidesNull; import com.google.errorprone.bugpatterns.inject.dagger.RefersToDaggerCodegen; import com.google.errorprone.bugpatterns.inject.dagger.ScopeOnModule; import com.google.errorprone.bugpatterns.inject.dagger.UseBinds; import com.google.errorprone.bugpatterns.inject.guice.AssistedInjectScoping; import com.google.errorprone.bugpatterns.inject.guice.AssistedParameters; import com.google.errorprone.bugpatterns.inject.guice.BindingToUnqualifiedCommonType; import com.google.errorprone.bugpatterns.inject.guice.InjectOnFinalField; import com.google.errorprone.bugpatterns.inject.guice.OverridesGuiceInjectableMethod; import com.google.errorprone.bugpatterns.inject.guice.OverridesJavaxInjectableMethod; import com.google.errorprone.bugpatterns.inject.guice.ProvidesMethodOutsideOfModule; import com.google.errorprone.bugpatterns.inlineme.Inliner; import com.google.errorprone.bugpatterns.inlineme.Suggester; import com.google.errorprone.bugpatterns.inlineme.Validator; import com.google.errorprone.bugpatterns.javadoc.AlmostJavadoc; import com.google.errorprone.bugpatterns.javadoc.EmptyBlockTag; import com.google.errorprone.bugpatterns.javadoc.EscapedEntity; import com.google.errorprone.bugpatterns.javadoc.InheritDoc; import com.google.errorprone.bugpatterns.javadoc.InvalidBlockTag; import com.google.errorprone.bugpatterns.javadoc.InvalidInlineTag; import com.google.errorprone.bugpatterns.javadoc.InvalidLink; import com.google.errorprone.bugpatterns.javadoc.InvalidParam; import com.google.errorprone.bugpatterns.javadoc.InvalidThrows; import com.google.errorprone.bugpatterns.javadoc.InvalidThrowsLink; import com.google.errorprone.bugpatterns.javadoc.MalformedInlineTag; import com.google.errorprone.bugpatterns.javadoc.MissingSummary; import com.google.errorprone.bugpatterns.javadoc.NotJavadoc; import com.google.errorprone.bugpatterns.javadoc.ReturnFromVoid; import com.google.errorprone.bugpatterns.javadoc.UnescapedEntity; import com.google.errorprone.bugpatterns.javadoc.UnrecognisedJavadocTag; import com.google.errorprone.bugpatterns.javadoc.UrlInSee; import com.google.errorprone.bugpatterns.nullness.DereferenceWithNullBranch; import com.google.errorprone.bugpatterns.nullness.EqualsBrokenForNull; import com.google.errorprone.bugpatterns.nullness.EqualsMissingNullable; import com.google.errorprone.bugpatterns.nullness.ExtendsObject; import com.google.errorprone.bugpatterns.nullness.FieldMissingNullable; import com.google.errorprone.bugpatterns.nullness.NullArgumentForNonNullParameter; import com.google.errorprone.bugpatterns.nullness.ParameterMissingNullable; import com.google.errorprone.bugpatterns.nullness.ReturnMissingNullable; import com.google.errorprone.bugpatterns.nullness.UnnecessaryCheckNotNull; import com.google.errorprone.bugpatterns.nullness.UnsafeWildcard; import com.google.errorprone.bugpatterns.nullness.VoidMissingNullable; import com.google.errorprone.bugpatterns.overloading.InconsistentOverloads; import com.google.errorprone.bugpatterns.threadsafety.DoubleCheckedLocking; import com.google.errorprone.bugpatterns.threadsafety.GuardedByChecker; import com.google.errorprone.bugpatterns.threadsafety.ImmutableAnnotationChecker; import com.google.errorprone.bugpatterns.threadsafety.ImmutableChecker; import com.google.errorprone.bugpatterns.threadsafety.ImmutableEnumChecker; import com.google.errorprone.bugpatterns.threadsafety.ImmutableRefactoring; import com.google.errorprone.bugpatterns.threadsafety.StaticGuardedByInstance; import com.google.errorprone.bugpatterns.threadsafety.SynchronizeOnNonFinalField; import com.google.errorprone.bugpatterns.threadsafety.ThreadPriorityCheck; import com.google.errorprone.bugpatterns.time.DateChecker; import com.google.errorprone.bugpatterns.time.DurationFrom; import com.google.errorprone.bugpatterns.time.DurationGetTemporalUnit; import com.google.errorprone.bugpatterns.time.DurationTemporalUnit; import com.google.errorprone.bugpatterns.time.DurationToLongTimeUnit; import com.google.errorprone.bugpatterns.time.FromTemporalAccessor; import com.google.errorprone.bugpatterns.time.InstantTemporalUnit; import com.google.errorprone.bugpatterns.time.InvalidJavaTimeConstant; import com.google.errorprone.bugpatterns.time.JavaDurationGetSecondsGetNano; import com.google.errorprone.bugpatterns.time.JavaDurationWithNanos; import com.google.errorprone.bugpatterns.time.JavaDurationWithSeconds; import com.google.errorprone.bugpatterns.time.JavaInstantGetSecondsGetNano; import com.google.errorprone.bugpatterns.time.JavaLocalDateTimeGetNano; import com.google.errorprone.bugpatterns.time.JavaLocalTimeGetNano; import com.google.errorprone.bugpatterns.time.JavaPeriodGetDays; import com.google.errorprone.bugpatterns.time.JavaTimeDefaultTimeZone; import com.google.errorprone.bugpatterns.time.JodaConstructors; import com.google.errorprone.bugpatterns.time.JodaDateTimeConstants; import com.google.errorprone.bugpatterns.time.JodaDurationWithMillis; import com.google.errorprone.bugpatterns.time.JodaInstantWithMillis; import com.google.errorprone.bugpatterns.time.JodaNewPeriod; import com.google.errorprone.bugpatterns.time.JodaPlusMinusLong; import com.google.errorprone.bugpatterns.time.JodaTimeConverterManager; import com.google.errorprone.bugpatterns.time.JodaToSelf; import com.google.errorprone.bugpatterns.time.JodaWithDurationAddedLong; import com.google.errorprone.bugpatterns.time.LocalDateTemporalAmount; import com.google.errorprone.bugpatterns.time.PeriodFrom; import com.google.errorprone.bugpatterns.time.PeriodGetTemporalUnit; import com.google.errorprone.bugpatterns.time.PeriodTimeMath; import com.google.errorprone.bugpatterns.time.PreferJavaTimeOverload; import com.google.errorprone.bugpatterns.time.ProtoDurationGetSecondsGetNano; import com.google.errorprone.bugpatterns.time.ProtoTimestampGetSecondsGetNano; import com.google.errorprone.bugpatterns.time.StronglyTypeTime; import com.google.errorprone.bugpatterns.time.TemporalAccessorGetChronoField; import com.google.errorprone.bugpatterns.time.TimeUnitConversionChecker; import com.google.errorprone.bugpatterns.time.TimeUnitMismatch; import com.google.errorprone.bugpatterns.time.ZoneIdOfZ; import java.util.Arrays; /** * Static helper class that provides {@link ScannerSupplier}s and {@link BugChecker}s for the * built-in Error Prone checks, as opposed to plugin checks or checks used in tests. */ public class BuiltInCheckerSuppliers { @SafeVarargs public static ImmutableSet<BugCheckerInfo> getSuppliers(Class<? extends BugChecker>... checkers) { return getSuppliers(Arrays.asList(checkers)); } public static ImmutableSet<BugCheckerInfo> getSuppliers( Iterable<Class<? extends BugChecker>> checkers) { return Streams.stream(checkers) .map(BugCheckerInfo::create) .collect(ImmutableSet.toImmutableSet()); } /** Returns a {@link ScannerSupplier} with all {@link BugChecker}s in Error Prone. */ public static ScannerSupplier allChecks() { return ScannerSupplier.fromBugCheckerInfos( Iterables.concat(ENABLED_ERRORS, ENABLED_WARNINGS, DISABLED_CHECKS)); } /** * Returns a {@link ScannerSupplier} with the {@link BugChecker}s that are in the ENABLED lists. */ public static ScannerSupplier defaultChecks() { return allChecks() .filter(Predicates.or(Predicates.in(ENABLED_ERRORS), Predicates.in(ENABLED_WARNINGS))); } /** * Returns a {@link ScannerSupplier} with the {@link BugChecker}s that are in the ENABLED_ERRORS * list. */ public static ScannerSupplier errorChecks() { return allChecks().filter(Predicates.in(ENABLED_ERRORS)); } /** * Returns a {@link ScannerSupplier} with the {@link BugChecker}s that are in the ENABLED_WARNINGS * list. */ public static ScannerSupplier warningChecks() { return allChecks().filter(Predicates.in(ENABLED_WARNINGS)); } /** A list of all checks with severity ERROR that are on by default. */ public static final ImmutableSet<BugCheckerInfo> ENABLED_ERRORS = getSuppliers( // keep-sorted start AlwaysThrows.class, AndroidInjectionBeforeSuper.class, ArrayEquals.class, ArrayFillIncompatibleType.class, ArrayHashCode.class, ArrayToString.class, ArraysAsListPrimitiveArray.class, AssistedInjectScoping.class, AssistedParameters.class, AsyncCallableReturnsNull.class, AsyncFunctionReturnsNull.class, AutoValueBuilderDefaultsInConstructor.class, AutoValueConstructorOrderChecker.class, BadAnnotationImplementation.class, BadShiftAmount.class, BanJNDI.class, BoxedPrimitiveEquality.class, BundleDeserializationCast.class, ChainingConstructorIgnoresParameter.class, CheckNotNullMultipleTimes.class, CheckReturnValue.class, CollectionIncompatibleType.class, CollectionToArraySafeParameter.class, ComparableType.class, ComparingThisWithNull.class, ComparisonOutOfRange.class, CompatibleWithMisuse.class, CompileTimeConstantChecker.class, ComputeIfAbsentAmbiguousReference.class, ConditionalExpressionNumericPromotion.class, ConstantOverflow.class, DangerousLiteralNullChecker.class, DeadException.class, DeadThread.class, DereferenceWithNullBranch.class, DiscardedPostfixExpression.class, DoNotCallChecker.class, DoNotMockChecker.class, DoubleBraceInitialization.class, DuplicateMapKeys.class, DurationFrom.class, DurationGetTemporalUnit.class, DurationTemporalUnit.class, DurationToLongTimeUnit.class, EqualsHashCode.class, EqualsNaN.class, EqualsNull.class, EqualsReference.class, EqualsWrongThing.class, FloggerFormatString.class, FloggerLogString.class, FloggerLogVarargs.class, FloggerSplitLogStatement.class, ForOverrideChecker.class, FormatString.class, FormatStringAnnotationChecker.class, FromTemporalAccessor.class, FunctionalInterfaceMethodChanged.class, FuturesGetCheckedIllegalExceptionType.class, FuzzyEqualsShouldNotBeUsedInEqualsMethod.class, GetClassOnAnnotation.class, GetClassOnClass.class, GuardedByChecker.class, HashtableContains.class, IdentityBinaryExpression.class, IdentityHashMapBoxing.class, ImmutableChecker.class, ImpossibleNullComparison.class, Incomparable.class, IncompatibleArgumentType.class, IncompatibleModifiersChecker.class, IndexOfChar.class, InexactVarargsConditional.class, InfiniteRecursion.class, InjectOnFinalField.class, InjectOnMemberAndConstructor.class, InstantTemporalUnit.class, InvalidJavaTimeConstant.class, InvalidPatternSyntax.class, InvalidTimeZoneID.class, InvalidZoneId.class, IsInstanceIncompatibleType.class, IsInstanceOfClass.class, IsLoggableTagLength.class, JUnit3TestNotRun.class, JUnit4ClassAnnotationNonStatic.class, JUnit4SetUpNotRun.class, JUnit4TearDownNotRun.class, JUnit4TestNotRun.class, JUnit4TestsNotRunWithinEnclosed.class, JUnitAssertSameCheck.class, JUnitParameterMethodNotFound.class, JavaxInjectOnAbstractMethod.class, JodaToSelf.class, LenientFormatStringValidation.class, LiteByteStringUtf8.class, LocalDateTemporalAmount.class, LockOnBoxedPrimitive.class, LoopConditionChecker.class, LossyPrimitiveCompare.class, MathRoundIntLong.class, MislabeledAndroidString.class, MisplacedScopeAnnotations.class, MissingSuperCall.class, MissingTestCall.class, MisusedDayOfYear.class, MisusedWeekYear.class, MixedDescriptors.class, MockitoUsage.class, ModifyingCollectionWithItself.class, MoreThanOneInjectableConstructor.class, MoreThanOneScopeAnnotationOnClass.class, MustBeClosedChecker.class, NCopiesOfChar.class, NoCanIgnoreReturnValueOnClasses.class, NonCanonicalStaticImport.class, NonFinalCompileTimeConstant.class, NonRuntimeAnnotation.class, NullArgumentForNonNullParameter.class, NullTernary.class, NullableOnContainingClass.class, OptionalEquality.class, OptionalMapUnusedValue.class, OptionalOfRedundantMethod.class, OverlappingQualifierAndScopeAnnotation.class, OverridesJavaxInjectableMethod.class, PackageInfo.class, ParametersButNotParameterized.class, ParcelableCreator.class, PeriodFrom.class, PeriodGetTemporalUnit.class, PeriodTimeMath.class, PreconditionsInvalidPlaceholder.class, PrivateSecurityContractProtoAccess.class, ProtoBuilderReturnValueIgnored.class, ProtoStringFieldReferenceEquality.class, ProtoTruthMixedDescriptors.class, ProtocolBufferOrdinal.class, ProvidesMethodOutsideOfModule.class, ProvidesNull.class, RandomCast.class, RandomModInteger.class, RectIntersectReturnValueIgnored.class, RequiredModifiersChecker.class, RestrictedApiChecker.class, ReturnValueIgnored.class, SelfAssignment.class, SelfComparison.class, SelfEquals.class, ShouldHaveEvenArgs.class, SizeGreaterThanOrEqualsZero.class, StreamToString.class, StringBuilderInitWithChar.class, SubstringOfZero.class, SuppressWarningsDeprecated.class, TemporalAccessorGetChronoField.class, TestParametersNotInitialized.class, TheoryButNoTheories.class, ThrowIfUncheckedKnownChecked.class, ThrowNull.class, TreeToString.class, TruthSelfEquals.class, TryFailThrowable.class, TypeParameterQualifier.class, UnicodeDirectionalityCharacters.class, UnicodeInCode.class, UnnecessaryCheckNotNull.class, UnnecessaryTypeArgument.class, UnsafeWildcard.class, UnusedAnonymousClass.class, UnusedCollectionModifiedInPlace.class, Validator.class, VarTypeName.class, WrongOneof.class, XorPower.class, ZoneIdOfZ.class // keep-sorted end ); /** A list of all checks with severity WARNING that are on by default. */ public static final ImmutableSet<BugCheckerInfo> ENABLED_WARNINGS = getSuppliers( // keep-sorted start ASTHelpersSuggestions.class, AlmostJavadoc.class, AlreadyChecked.class, AmbiguousMethodReference.class, AnnotateFormatMethod.class, ArgumentSelectionDefectChecker.class, ArrayAsKeyOfSetOrMap.class, AssertEqualsArgumentOrderChecker.class, AssertThrowsMultipleStatements.class, AssertionFailureIgnored.class, AssistedInjectAndInjectOnSameConstructor.class, AttemptedNegativeZero.class, AutoValueFinalMethods.class, AutoValueImmutableFields.class, AutoValueSubclassLeaked.class, BadComparable.class, BadImport.class, BadInstanceof.class, BareDotMetacharacter.class, BigDecimalEquals.class, BigDecimalLiteralDouble.class, BoxedPrimitiveConstructor.class, BugPatternNaming.class, ByteBufferBackingArray.class, CacheLoaderNull.class, CanonicalDuration.class, CatchAndPrintStackTrace.class, CatchFail.class, ChainedAssertionLosesContext.class, CharacterGetNumericValue.class, ClassCanBeStatic.class, ClassNewInstance.class, CloseableProvides.class, CollectionUndefinedEquality.class, CollectorShouldNotUseState.class, ComparableAndComparator.class, CompareToZero.class, ComplexBooleanConstant.class, DateChecker.class, DateFormatConstant.class, DefaultCharset.class, DefaultPackage.class, DeprecatedVariable.class, DirectInvocationOnMock.class, DistinctVarargsChecker.class, DoNotCallSuggester.class, DoNotClaimAnnotations.class, DoNotMockAutoValue.class, DoubleCheckedLocking.class, EmptyBlockTag.class, EmptyCatch.class, EmptySetMultibindingContributions.class, EmptyTopLevelDeclaration.class, EqualsGetClass.class, EqualsIncompatibleType.class, EqualsUnsafeCast.class, EqualsUsingHashCode.class, ErroneousBitwiseExpression.class, ErroneousThreadPoolConstructorChecker.class, EscapedEntity.class, ExtendingJUnitAssert.class, ExtendsObject.class, FallThrough.class, Finalize.class, Finally.class, FloatCast.class, FloatingPointAssertionWithinEpsilon.class, FloatingPointLiteralPrecision.class, FloggerArgumentToString.class, FloggerStringConcatenation.class, FragmentInjection.class, FragmentNotInstantiable.class, FutureReturnValueIgnored.class, GetClassOnEnum.class, HidingField.class, ICCProfileGetInstance.class, IdentityHashMapUsage.class, IgnoredPureGetter.class, ImmutableAnnotationChecker.class, ImmutableEnumChecker.class, InconsistentCapitalization.class, InconsistentHashCode.class, IncorrectMainMethod.class, IncrementInForLoopAndHeader.class, InheritDoc.class, InjectOnBugCheckers.class, InjectOnConstructorOfAbstractClass.class, InjectedConstructorAnnotations.class, InlineFormatString.class, InlineTrivialConstant.class, Inliner.class, InputStreamSlowMultibyteRead.class, InstanceOfAndCastMatchWrongType.class, IntLongMath.class, InvalidBlockTag.class, InvalidInlineTag.class, InvalidLink.class, InvalidParam.class, InvalidTargetingOnScopingAnnotation.class, InvalidThrows.class, InvalidThrowsLink.class, IterableAndIterator.class, JUnit3FloatingPointComparisonWithoutDelta.class, JUnit4ClassUsedInJUnit3.class, JUnitAmbiguousTestClass.class, JavaDurationGetSecondsGetNano.class, JavaDurationWithNanos.class, JavaDurationWithSeconds.class, JavaInstantGetSecondsGetNano.class, JavaLangClash.class, JavaLocalDateTimeGetNano.class, JavaLocalTimeGetNano.class, JavaPeriodGetDays.class, JavaTimeDefaultTimeZone.class, JavaUtilDateChecker.class, JavaxInjectOnFinalField.class, JdkObsolete.class, JodaConstructors.class, JodaDateTimeConstants.class, JodaDurationWithMillis.class, JodaInstantWithMillis.class, JodaNewPeriod.class, JodaPlusMinusLong.class, JodaTimeConverterManager.class, JodaWithDurationAddedLong.class, LabelledBreakTarget.class, LiteEnumValueOf.class, LiteProtoToString.class, LockNotBeforeTry.class, LockOnNonEnclosingClassLiteral.class, LogicalAssignment.class, LongDoubleConversion.class, LongFloatConversion.class, LoopOverCharArray.class, MalformedInlineTag.class, MathAbsoluteNegative.class, MemoizeConstantVisitorStateLookups.class, MissingCasesInEnumSwitch.class, MissingFail.class, MissingImplementsComparable.class, MissingOverride.class, MissingRefasterAnnotation.class, MissingSummary.class, MixedMutabilityReturnType.class, MockNotUsedInProduction.class, ModifiedButNotUsed.class, ModifyCollectionInEnhancedForLoop.class, ModifySourceCollectionInStream.class, MultipleParallelOrSequentialCalls.class, MultipleUnaryOperatorsInMethodCall.class, MutablePublicArray.class, NamedLikeContextualKeyword.class, NarrowCalculation.class, NarrowingCompoundAssignment.class, NegativeCharLiteral.class, NestedInstanceOfConditions.class, NewFileSystem.class, NonApiType.class, NonAtomicVolatileUpdate.class, NonCanonicalType.class, NonOverridingEquals.class, NotJavadoc.class, NullOptional.class, NullableConstructor.class, NullablePrimitive.class, NullablePrimitiveArray.class, NullableVoid.class, ObjectEqualsForPrimitives.class, ObjectToString.class, ObjectsHashCodePrimitive.class, OperatorPrecedence.class, OptionalMapToOptional.class, OptionalNotPresent.class, OrphanedFormatString.class, OutlineNone.class, OverrideThrowableToString.class, Overrides.class, OverridesGuiceInjectableMethod.class, ParameterName.class, PreconditionsCheckNotNullRepeated.class, PrimitiveAtomicReference.class, ProtectedMembersInFinalClass.class, ProtoDurationGetSecondsGetNano.class, ProtoRedundantSet.class, ProtoTimestampGetSecondsGetNano.class, QualifierOrScopeOnInjectMethod.class, ReachabilityFenceUsage.class, ReferenceEquality.class, RethrowReflectiveOperationExceptionAsLinkageError.class, ReturnFromVoid.class, RobolectricShadowDirectlyOn.class, RxReturnValueIgnored.class, SameNameButDifferent.class, ScopeAnnotationOnInterfaceOrAbstractClass.class, SelfAlwaysReturnsThis.class, ShortCircuitBoolean.class, StaticAssignmentInConstructor.class, StaticAssignmentOfThrowable.class, StaticGuardedByInstance.class, StaticMockMember.class, StreamResourceLeak.class, StreamToIterable.class, StringCaseLocaleUsage.class, StringSplitter.class, Suggester.class, SwigMemoryLeak.class, SynchronizeOnNonFinalField.class, ThreadJoinLoop.class, ThreadLocalUsage.class, ThreadPriorityCheck.class, ThreeLetterTimeZoneID.class, TimeUnitConversionChecker.class, ToStringReturnsNull.class, TruthAssertExpected.class, TruthConstantAsserts.class, TruthGetOrDefault.class, TruthIncompatibleType.class, TypeEqualsChecker.class, TypeNameShadowing.class, TypeParameterShadowing.class, TypeParameterUnusedInFormals.class, URLEqualsHashCode.class, UndefinedEquals.class, UnicodeEscape.class, UnnecessaryAssignment.class, UnnecessaryLambda.class, UnnecessaryLongToIntConversion.class, UnnecessaryMethodInvocationMatcher.class, UnnecessaryMethodReference.class, UnnecessaryParentheses.class, UnnecessaryStringBuilder.class, UnrecognisedJavadocTag.class, UnsafeFinalization.class, UnsafeReflectiveConstructionCast.class, UnsynchronizedOverridesSynchronized.class, UnusedLabel.class, UnusedMethod.class, UnusedNestedClass.class, UnusedTypeParameter.class, UnusedVariable.class, UseBinds.class, VariableNameSameAsType.class, WaitNotInLoop.class, WakelockReleasedDangerously.class, WithSignatureDiscouraged.class // keep-sorted end ); /** A list of all checks that are off by default. */ public static final ImmutableSet<BugCheckerInfo> DISABLED_CHECKS = getSuppliers( // keep-sorted start AndroidJdkLibsChecker.class, AnnotationMirrorToString.class, AnnotationPosition.class, AnnotationValueToString.class, AssertFalse.class, AssistedInjectAndInjectOnConstructors.class, AutoFactoryAtInject.class, AvoidObjectArrays.class, BanClassLoader.class, BanSerializableRead.class, BinderIdentityRestoredDangerously.class, // TODO: enable this by default. BindingToUnqualifiedCommonType.class, BooleanParameter.class, BuilderReturnThis.class, CanIgnoreReturnValueSuggester.class, CannotMockFinalClass.class, CannotMockMethod.class, CatchingUnchecked.class, CheckedExceptionNotThrown.class, ClassName.class, ClassNamedLikeTypeParameter.class, ComparisonContractViolated.class, ConstantField.class, ConstantPatternCompile.class, DeduplicateConstants.class, DepAnn.class, DifferentNameButSame.class, DoNotUseRuleChain.class, EmptyIfStatement.class, EqualsBrokenForNull.class, EqualsMissingNullable.class, ExpectedExceptionChecker.class, ExtendsAutoValue.class, FieldCanBeFinal.class, FieldCanBeLocal.class, FieldCanBeStatic.class, FieldMissingNullable.class, FloggerLogWithCause.class, FloggerMessageFormat.class, FloggerRedundantIsEnabled.class, FloggerRequiredModifiers.class, FloggerWithCause.class, FloggerWithoutCause.class, ForEachIterable.class, FunctionalInterfaceClash.class, HardCodedSdCardPath.class, ImmutableMemberCollection.class, ImmutableRefactoring.class, ImmutableSetForContains.class, ImplementAssertionWithChaining.class, InconsistentOverloads.class, InitializeInline.class, InsecureCipherMode.class, InterfaceWithOnlyStatics.class, InterruptedExceptionSwallowed.class, Interruption.class, IterablePathParameter.class, Java7ApiChecker.class, Java8ApiChecker.class, LambdaFunctionalInterface.class, LongLiteralLowerCaseSuffix.class, MemberName.class, MethodCanBeStatic.class, MissingBraces.class, MissingDefault.class, MixedArrayDimensions.class, MoreThanOneQualifier.class, MultiVariableDeclaration.class, MultipleTopLevelClasses.class, NoAllocationChecker.class, NonCanonicalStaticMemberImport.class, PackageLocation.class, ParameterComment.class, ParameterMissingNullable.class, PreferJavaTimeOverload.class, PreferredInterfaceType.class, PrimitiveArrayPassedToVarargsMethod.class, PrivateConstructorForNoninstantiableModule.class, PrivateConstructorForUtilityClass.class, PublicApiNamedStreamShouldReturnStream.class, QualifierWithTypeUse.class, RedundantOverride.class, RedundantThrows.class, RefersToDaggerCodegen.class, RemoveUnusedImports.class, ReturnMissingNullable.class, ReturnsNullCollection.class, ScopeOnModule.class, ScopeOrQualifierAnnotationRetention.class, StatementSwitchToExpressionSwitch.class, StaticOrDefaultInterfaceMethod.class, StaticQualifiedUsingExpression.class, StronglyTypeByteString.class, StronglyTypeTime.class, SuppressWarningsWithoutExplanation.class, SwitchDefault.class, SymbolToString.class, SystemExitOutsideMain.class, SystemOut.class, TestExceptionChecker.class, ThrowSpecificExceptions.class, ThrowsUncheckedException.class, TimeUnitMismatch.class, TooManyParameters.class, TransientMisuse.class, TryFailRefactoring.class, TryWithResourcesVariable.class, TypeParameterNaming.class, TypeToString.class, UnescapedEntity.class, // TODO(b/263817298): re-enable UngroupedOverloads.class, UnnecessarilyFullyQualified.class, UnnecessarilyUsedValue.class, UnnecessarilyVisible.class, UnnecessaryAnonymousClass.class, UnnecessaryBoxedAssignment.class, UnnecessaryBoxedVariable.class, UnnecessaryDefaultInEnumSwitch.class, UnnecessaryFinal.class, UnnecessaryOptionalGet.class, UnnecessarySetDefault.class, UnnecessaryStaticImport.class, UnnecessaryTestMethodPrefix.class, UnsafeLocaleUsage.class, UnusedException.class, UrlInSee.class, UseCorrectAssertInTests.class, UseEnumSwitch.class, UsingJsr305CheckReturnValue.class, VarChecker.class, Varifier.class, VoidMissingNullable.class, WildcardImport.class, YodaCondition.class // keep-sorted end ); // May not be instantiated private BuiltInCheckerSuppliers() {} }
61,594
49.989238
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/TheoryButNoTheories.java
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.JUnitMatchers.hasJUnit4TestRunner; import static com.google.errorprone.matchers.JUnitMatchers.isJUnit4TestRunnerOfType; import static com.google.errorprone.matchers.Matchers.annotations; import static com.google.errorprone.matchers.Matchers.hasArgumentWithValue; import static com.google.errorprone.util.ASTHelpers.annotationsAmong; import static com.google.errorprone.util.ASTHelpers.getAnnotationWithSimpleName; import static com.google.errorprone.util.ASTHelpers.getSymbol; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.MultiMatcher; import com.google.errorprone.suppliers.Supplier; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.util.Name; import java.util.stream.Stream; /** Flags uses of {@code @Theory} (and others) in non-{@code Theories}-run tests. */ @BugPattern( summary = "This test has members annotated with @Theory, @DataPoint, or @DataPoints but is using the" + " default JUnit4 runner.", severity = ERROR) public final class TheoryButNoTheories extends BugChecker implements ClassTreeMatcher { private static final String THEORIES = "org.junit.experimental.theories.Theories"; private static final Supplier<ImmutableSet<Name>> TYPES = VisitorState.memoize( s -> Stream.of( "org.junit.experimental.theories.Theory", "org.junit.experimental.theories.DataPoint", "org.junit.experimental.theories.DataPoints") .map(s::getName) .collect(toImmutableSet())); private static final MultiMatcher<Tree, AnnotationTree> USING_THEORIES_RUNNER = annotations( AT_LEAST_ONE, hasArgumentWithValue("value", isJUnit4TestRunnerOfType(ImmutableSet.of(THEORIES)))); @Override public Description matchClass(ClassTree tree, VisitorState state) { if (!hasJUnit4TestRunner.matches(tree, state)) { return NO_MATCH; } if (USING_THEORIES_RUNNER.matches(tree, state)) { return NO_MATCH; } if (tree.getMembers().stream() .allMatch(m -> annotationsAmong(getSymbol(m), TYPES.get(state), state).isEmpty())) { return NO_MATCH; } AnnotationTree annotation = getAnnotationWithSimpleName(tree.getModifiers().getAnnotations(), "RunWith"); SuggestedFix.Builder fix = SuggestedFix.builder(); fix.replace( annotation, String.format("@RunWith(%s.class)", SuggestedFixes.qualifyType(state, fix, THEORIES))); return describeMatch(tree, fix.build()); } }
3,946
42.373626
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/LoopConditionChecker.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Description.NO_MATCH; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.DoWhileLoopTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.ForLoopTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.WhileLoopTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.CompoundAssignmentTree; import com.sun.source.tree.DoWhileLoopTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.ForLoopTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.LiteralTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.Tree; import com.sun.source.tree.UnaryTree; import com.sun.source.tree.WhileLoopTree; import com.sun.source.util.SimpleTreeVisitor; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern(summary = "Loop condition is never modified in loop body.", severity = ERROR) public class LoopConditionChecker extends BugChecker implements ForLoopTreeMatcher, DoWhileLoopTreeMatcher, WhileLoopTreeMatcher { @Override public Description matchDoWhileLoop(DoWhileLoopTree tree, VisitorState state) { return check(tree.getCondition(), ImmutableList.of(tree.getCondition(), tree.getStatement())); } @Override public Description matchForLoop(ForLoopTree tree, VisitorState state) { if (tree.getCondition() == null) { return NO_MATCH; } return check( tree.getCondition(), ImmutableList.<Tree>builder() .add(tree.getCondition()) .add(tree.getStatement()) .addAll(tree.getUpdate()) .build()); } @Override public Description matchWhileLoop(WhileLoopTree tree, VisitorState state) { return check(tree.getCondition(), ImmutableList.of(tree.getCondition(), tree.getStatement())); } private Description check(ExpressionTree condition, ImmutableList<Tree> loopBodyTrees) { ImmutableSet<Symbol.VarSymbol> conditionVars = LoopConditionVisitor.scan(condition); if (conditionVars.isEmpty()) { return NO_MATCH; } for (Tree tree : loopBodyTrees) { if (UpdateScanner.scan(tree, conditionVars)) { return NO_MATCH; } } return buildDescription(condition) .setMessage( String.format( "condition variable(s) never modified in loop body: %s", Joiner.on(", ").join(conditionVars))) .build(); } /** Scan for loop conditions that are determined entirely by the state of local variables. */ private static class LoopConditionVisitor extends SimpleTreeVisitor<Boolean, Void> { static ImmutableSet<Symbol.VarSymbol> scan(Tree tree) { ImmutableSet.Builder<Symbol.VarSymbol> conditionVars = ImmutableSet.builder(); if (!firstNonNull(tree.accept(new LoopConditionVisitor(conditionVars), null), false)) { return ImmutableSet.of(); } return conditionVars.build(); } private final ImmutableSet.Builder<Symbol.VarSymbol> conditionVars; public LoopConditionVisitor(ImmutableSet.Builder<Symbol.VarSymbol> conditionVars) { this.conditionVars = conditionVars; } @Override public Boolean visitIdentifier(IdentifierTree tree, Void unused) { Symbol sym = ASTHelpers.getSymbol(tree); if (sym instanceof Symbol.VarSymbol) { switch (sym.getKind()) { case LOCAL_VARIABLE: case PARAMETER: conditionVars.add((Symbol.VarSymbol) sym); return true; default: // fall out } } return false; } @Override public Boolean visitLiteral(LiteralTree tree, Void unused) { return true; } @Override public Boolean visitUnary(UnaryTree node, Void unused) { return node.getExpression().accept(this, null); } @Override public Boolean visitBinary(BinaryTree node, Void unused) { return firstNonNull(node.getLeftOperand().accept(this, null), false) && firstNonNull(node.getRightOperand().accept(this, null), false); } } /** Scan for updates to the given variables. */ private static class UpdateScanner extends TreeScanner<Void, Void> { public static boolean scan(Tree tree, ImmutableSet<Symbol.VarSymbol> variables) { UpdateScanner scanner = new UpdateScanner(variables); tree.accept(scanner, null); return scanner.modified; } private boolean modified = false; private final ImmutableSet<Symbol.VarSymbol> variables; public UpdateScanner(ImmutableSet<Symbol.VarSymbol> variables) { this.variables = variables; } @Override public Void visitUnary(UnaryTree tree, Void unused) { switch (tree.getKind()) { case POSTFIX_INCREMENT: case PREFIX_INCREMENT: case POSTFIX_DECREMENT: case PREFIX_DECREMENT: check(tree.getExpression()); break; default: // fall out } return super.visitUnary(tree, unused); } @Override public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) { check(ASTHelpers.getReceiver(tree)); return super.visitMethodInvocation(tree, unused); } @Override public Void visitAssignment(AssignmentTree tree, Void unused) { check(tree.getVariable()); return super.visitAssignment(tree, unused); } @Override public Void visitCompoundAssignment(CompoundAssignmentTree tree, Void unused) { check(tree.getVariable()); return super.visitCompoundAssignment(tree, unused); } private void check(ExpressionTree expression) { Symbol sym = ASTHelpers.getSymbol(expression); modified |= variables.contains(sym); } } }
6,995
34.155779
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/OverrideThrowableToString.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import com.google.common.collect.ImmutableList; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matchers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; /** * Warns against overriding toString() in a Throwable class and suggests getMessage() * * @author mariasam@google.com (Maria Sam) */ @BugPattern( summary = "To return a custom message with a Throwable class, one should " + "override getMessage() instead of toString().", severity = WARNING) public final class OverrideThrowableToString extends BugChecker implements ClassTreeMatcher { @Override public Description matchClass(ClassTree classTree, VisitorState state) { if (!ASTHelpers.isSubtype( ASTHelpers.getType(classTree), state.getSymtab().throwableType, state)) { return Description.NO_MATCH; } ImmutableList<MethodTree> methods = classTree.getMembers().stream() .filter(m -> m instanceof MethodTree) .map(m -> (MethodTree) m) .collect(toImmutableList()); if (methods.stream().anyMatch(m -> m.getName().contentEquals("getMessage"))) { return Description.NO_MATCH; } return methods.stream() .filter(m -> Matchers.toStringMethodDeclaration().matches(m, state)) .findFirst() .map(m -> describeMatch(m, SuggestedFixes.renameMethod(m, "getMessage", state))) .orElse(Description.NO_MATCH); } }
2,526
37.287879
93
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ChainedAssertionLosesContext.java
/* * Copyright 2019 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.bugpatterns.ImplementAssertionWithChaining.makeCheckDescription; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.instanceMethod; import static com.google.errorprone.matchers.Matchers.staticMethod; import static com.google.errorprone.util.ASTHelpers.getDeclaredSymbol; import static com.google.errorprone.util.ASTHelpers.getEnclosedElements; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.isSubtype; import static com.sun.source.tree.Tree.Kind.CLASS; import static com.sun.source.tree.Tree.Kind.METHOD_INVOCATION; import static java.lang.String.format; import static java.util.stream.Stream.concat; import static javax.lang.model.element.Modifier.STATIC; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.FormatMethod; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.suppliers.Supplier; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import com.sun.source.util.TreePath; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Type; import javax.annotation.Nullable; /** * Identifies calls to {@code assertThat} and similar methods inside the implementation of a {@code * Subject} assertion method. These calls should instead use {@code check(...)}. * * <pre>{@code * // Before: * public void hasFoo() { * assertThat(actual().foo()).isEqualTo(expected); * } * * // After: * public void hasFoo() { * check("foo()").that(actual().foo()).isEqualTo(expected); * } * }</pre> */ @BugPattern( summary = "Inside a Subject, use check(...) instead of assert*() to preserve user-supplied messages" + " and other settings.", severity = WARNING) public final class ChainedAssertionLosesContext extends BugChecker implements MethodInvocationTreeMatcher { @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!inInstanceMethodOfSubjectImplementation(state)) { return NO_MATCH; } if (STANDARD_ASSERT_THAT.matches(tree, state)) { String checkDescription = makeCheckDescription(getOnlyElement(tree.getArguments()), state); if (checkDescription == null) { // TODO(cpovirk): Generate a suggested fix without a check description. return NO_MATCH; } return replace(tree.getMethodSelect(), "check(%s).that", checkDescription); } else if (ANY_ASSERT_THAT.matches(tree, state)) { FactoryMethodName factory = tryFindFactory(tree, state); if (factory == null) { // TODO(cpovirk): Generate a warning that instructs the user to find or expose a factory. return NO_MATCH; } if (tree.getArguments().size() != 1) { // TODO(cpovirk): Generate a suggested fix without a check description. return NO_MATCH; } String checkDescription = makeCheckDescription(getOnlyElement(tree.getArguments()), state); if (checkDescription == null) { // TODO(cpovirk): Generate a suggested fix without a check description. return NO_MATCH; } return describeMatch( tree, SuggestedFix.builder() .addStaticImport(factory.clazz() + "." + factory.method()) .replace( tree.getMethodSelect(), format("check(%s).about(%s()).that", checkDescription, factory.method())) .build()); } else if (ASSERT_ABOUT.matches(tree, state)) { String checkDescription = findThatCallAndMakeCheckDescription(state); if (checkDescription == null) { // TODO(cpovirk): Generate a suggested fix without a check description. return NO_MATCH; } return replace(tree.getMethodSelect(), "check(%s).about", checkDescription); } else if (ASSERT_WITH_MESSAGE.matches(tree, state)) { String checkDescription = findThatCallAndMakeCheckDescription(state); if (checkDescription == null) { // TODO(cpovirk): Generate a suggested fix without a check description. return NO_MATCH; } return replace(tree.getMethodSelect(), "check(%s).withMessage", checkDescription); } else if (ASSERT.matches(tree, state)) { String checkDescription = findThatCallAndMakeCheckDescription(state); if (checkDescription == null) { // TODO(cpovirk): Generate a suggested fix without a check description. return NO_MATCH; } return replace(tree, "check(%s)", checkDescription); } else { /* * TODO(cpovirk): If it's an assertThat method other than Truth.assertThat, then find the * appropriate Subject.Factory, and generate check().about(...).that(...). */ return NO_MATCH; } } /** * Starting from a {@code VisitorState} pointing at part of a fluent assertion statement (like * {@code check()} or {@code assertWithMessage()}, walks up the tree and returns the subsequent * call to {@code that(...)}. * * <p>Often, the call is made directly on the result of the given tree -- like when the input is * {@code check()}, which is part of the expression {@code check().that(...)}. But sometimes there * is an intervening call to {@code withMessage}, {@code about}, or both. */ @Nullable static MethodInvocationTree findThatCall(VisitorState state) { TreePath path = state.getPath(); /* * Each iteration walks 1 method call up the tree, but it's actually 2 steps in the tree because * there's a MethodSelectTree between each pair of MethodInvocationTrees. */ while (true) { path = path.getParentPath().getParentPath(); Tree leaf = path.getLeaf(); if (leaf.getKind() != METHOD_INVOCATION) { return null; } MethodInvocationTree maybeThatCall = (MethodInvocationTree) leaf; if (WITH_MESSAGE_OR_ABOUT.matches(maybeThatCall, state)) { continue; } else if (SUBJECT_BUILDER_THAT.matches(maybeThatCall, state)) { return maybeThatCall; } else { return null; } } } @FormatMethod private Description replace(Tree tree, String format, Object... args) { return describeMatch(tree, SuggestedFix.replace(tree, String.format(format, args))); } @AutoValue abstract static class FactoryMethodName { static FactoryMethodName create(String clazz, String method) { return new AutoValue_ChainedAssertionLosesContext_FactoryMethodName(clazz, method); } @Nullable static FactoryMethodName tryCreate(MethodSymbol symbol) { return symbol.params.isEmpty() ? create(symbol.owner.getQualifiedName().toString(), symbol.getSimpleName().toString()) : null; } abstract String clazz(); abstract String method(); } @Nullable private static FactoryMethodName tryFindFactory( MethodInvocationTree assertThatCall, VisitorState state) { MethodSymbol assertThatSymbol = getSymbol(assertThatCall); /* * First, a special case for ProtoTruth.protos(). Usually the main case below finds it OK, but * sometimes it misses it, I believe because it can't decide between that and * IterableOfProtosSubject.iterableOfMessages. */ if (assertThatSymbol.owner.getQualifiedName().contentEquals(PROTO_TRUTH_CLASS)) { return FactoryMethodName.create(PROTO_TRUTH_CLASS, "protos"); } ImmutableSet<MethodSymbol> factories = concat( // The class that assertThat is declared in: getEnclosedElements(assertThatSymbol.owner).stream(), // The Subject class (possibly the same; if so, toImmutableSet() will deduplicate): getEnclosedElements(assertThatSymbol.getReturnType().asElement()).stream()) .filter(s -> s instanceof MethodSymbol) .map(s -> (MethodSymbol) s) .filter( s -> returns(s, SUBJECT_FACTORY_CLASS, state) || returns(s, CUSTOM_SUBJECT_BUILDER_FACTORY_CLASS, state)) .collect(toImmutableSet()); return factories.size() == 1 ? FactoryMethodName.tryCreate(getOnlyElement(factories)) : null; // TODO(cpovirk): If multiple factories exist, try filtering to visible ones only. } private static boolean returns(MethodSymbol symbol, String returnType, VisitorState state) { return isSubtype(symbol.getReturnType(), state.getTypeFromString(returnType), state); } private static boolean inInstanceMethodOfSubjectImplementation(VisitorState state) { /* * All the checks here are mostly a no-op because, in static methods or methods outside Subject, * makeCheckDescription will fail to find a call to actual(), so the check won't fire. But they * set up for a future in which we issue a warning even if we can't produce a check description * for the suggested fix automatically. */ TreePath pathToEnclosingMethod = state.findPathToEnclosing(MethodTree.class); if (pathToEnclosingMethod == null) { return false; } MethodTree enclosingMethod = (MethodTree) pathToEnclosingMethod.getLeaf(); if (enclosingMethod.getModifiers().getFlags().contains(STATIC)) { return false; } Tree enclosingClass = pathToEnclosingMethod.getParentPath().getLeaf(); if (enclosingClass == null || enclosingClass.getKind() != CLASS) { return false; } /* * TODO(cpovirk): Ideally we'd also recognize types nested inside Subject implementations, like * IterableSubject.UsingCorrespondence. */ return isSubtype( getDeclaredSymbol(enclosingClass).type, COM_GOOGLE_COMMON_TRUTH_SUBJECT.get(state), state); } @Nullable private static String findThatCallAndMakeCheckDescription(VisitorState state) { MethodInvocationTree thatCall = findThatCall(state); if (thatCall == null) { return null; } return makeCheckDescription(getOnlyElement(thatCall.getArguments()), state); } private static final String TRUTH_CLASS = "com.google.common.truth.Truth"; private static final String PROTO_TRUTH_CLASS = "com.google.common.truth.extensions.proto.ProtoTruth"; private static final String SUBJECT_CLASS = "com.google.common.truth.Subject"; private static final String SUBJECT_FACTORY_CLASS = "com.google.common.truth.Subject.Factory"; private static final String CUSTOM_SUBJECT_BUILDER_FACTORY_CLASS = "com.google.common.truth.CustomSubjectBuilder.Factory"; private static final Matcher<ExpressionTree> STANDARD_ASSERT_THAT = staticMethod().onClass(TRUTH_CLASS).named("assertThat"); private static final Matcher<ExpressionTree> ANY_ASSERT_THAT = staticMethod().anyClass().named("assertThat"); private static final Matcher<ExpressionTree> ASSERT_ABOUT = staticMethod().onClass(TRUTH_CLASS).named("assertAbout"); private static final Matcher<ExpressionTree> ASSERT_WITH_MESSAGE = staticMethod().onClass(TRUTH_CLASS).named("assertWithMessage"); private static final Matcher<ExpressionTree> ASSERT = staticMethod().onClass(TRUTH_CLASS).named("assert_"); private static final Matcher<ExpressionTree> SUBJECT_BUILDER_THAT = anyOf( instanceMethod() .onDescendantOf("com.google.common.truth.CustomSubjectBuilder") .named("that"), instanceMethod() .onDescendantOf("com.google.common.truth.SimpleSubjectBuilder") .named("that"), instanceMethod() .onDescendantOf("com.google.common.truth.StandardSubjectBuilder") .named("that")); private static final Matcher<ExpressionTree> WITH_MESSAGE_OR_ABOUT = instanceMethod() .onDescendantOf("com.google.common.truth.StandardSubjectBuilder") .namedAnyOf("withMessage", "about"); private static final Supplier<Type> COM_GOOGLE_COMMON_TRUTH_SUBJECT = VisitorState.memoize(state -> state.getTypeFromString(SUBJECT_CLASS)); }
13,430
42.466019
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/RestrictedApiChecker.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.streamSuperMethods; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.RestrictedApi; import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MemberReferenceTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.Matchers; import com.google.errorprone.util.ASTHelpers; import com.google.errorprone.util.MoreAnnotations; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.MemberReferenceTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Attribute; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.TypeSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Types; import com.sun.tools.javac.model.AnnotationProxyMaker; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import java.util.List; import java.util.Optional; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import java.util.stream.Stream; import javax.annotation.Nullable; /** Check for non-allowlisted callers to RestrictedApiChecker. */ @BugPattern( name = "RestrictedApi", summary = "Check for non-allowlisted callers to RestrictedApiChecker.", severity = SeverityLevel.ERROR) public class RestrictedApiChecker extends BugChecker implements MethodInvocationTreeMatcher, NewClassTreeMatcher, AnnotationTreeMatcher, MemberReferenceTreeMatcher { /** * Validates a {@code @RestrictedApi} annotation and that the declared restriction makes sense. * * <p>The other match functions in this class check the <em>usages</em> of a restricted API. */ @Override public Description matchAnnotation(AnnotationTree tree, VisitorState state) { // TODO(bangert): Validate all the fields if (!getSymbol(tree).getQualifiedName().contentEquals(RestrictedApi.class.getName())) { return NO_MATCH; } // TODO(bangert): make a more elegant API to get the annotation within an annotation tree. // Maybe find the declared object and get annotations on that... Attribute.Compound restrictedApi = (Attribute.Compound) ASTHelpers.getAnnotationMirror(tree); if (restrictedApi == null) { return NO_MATCH; } return NO_MATCH; } private static final ImmutableSet<String> ALLOWLIST_ANNOTATION_NAMES = ImmutableSet.of("allowlistAnnotations", "allowlistWithWarningAnnotations"); private static Tree getAnnotationArgumentTree(AnnotationTree tree, String name) { return tree.getArguments().stream() .filter(arg -> arg.getKind().equals(Tree.Kind.ASSIGNMENT)) .map(arg -> (AssignmentTree) arg) .filter(arg -> isVariableTreeWithName(arg, name)) .map(AssignmentTree::getExpression) .findFirst() .orElse(tree); } private static boolean isVariableTreeWithName(AssignmentTree tree, String name) { ExpressionTree variable = tree.getVariable(); return variable instanceof IdentifierTree && ((IdentifierTree) variable).getName().contentEquals(name); } @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { return checkMethodUse(getSymbol(tree), tree, state); } @Override public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) { return checkMethodUse(getSymbol(tree), tree, state); } /** * Returns the constructor type for the supplied constructor symbol of an anonymous class object * that can be matched with a corresponding constructor in its direct superclass. If the anonymous * object creation expression is qualified, i.e., is of the form {@code enclosingExpression.new * identifier (arguments)} the constructor type includes an implicit first parameter with type * matching enclosingExpression. In such a case a matching constructor type is created by dropping * this implicit parameter. */ private static Type dropImplicitEnclosingInstanceParameter( NewClassTree tree, VisitorState state, MethodSymbol anonymousClassConstructor) { Type type = anonymousClassConstructor.asType(); if (!hasEnclosingExpression(tree)) { // fast path return type; } com.sun.tools.javac.util.List<Type> params = type.getParameterTypes(); params = firstNonNull(params.tail, com.sun.tools.javac.util.List.nil()); return state.getTypes().createMethodTypeWithParameters(type, params); } private static boolean hasEnclosingExpression(NewClassTree tree) { if (tree.getEnclosingExpression() != null) { return true; } List<? extends ExpressionTree> arguments = tree.getArguments(); return !arguments.isEmpty() && ((JCTree) arguments.get(0)).hasTag(JCTree.Tag.NULLCHK); } private static MethodSymbol superclassConstructorSymbol(NewClassTree tree, VisitorState state) { MethodSymbol constructor = getSymbol(tree); Types types = state.getTypes(); TypeSymbol superclass = types.supertype(constructor.enclClass().asType()).asElement(); Type anonymousClassType = constructor.enclClass().asType(); Type matchingConstructorType = dropImplicitEnclosingInstanceParameter(tree, state, constructor); return (MethodSymbol) getOnlyElement( ASTHelpers.scope(superclass.members()) .getSymbols( member -> member.isConstructor() && types.hasSameArgs( member.asMemberOf(anonymousClassType, types).asType(), matchingConstructorType))); } @Override public Description matchNewClass(NewClassTree tree, VisitorState state) { if (tree.getClassBody() != null) { return checkMethodUse(superclassConstructorSymbol(tree, state), tree, state); } else { return checkRestriction(getRestrictedApiAnnotation(getSymbol(tree), state), tree, state); } } private Description checkMethodUse( MethodSymbol method, ExpressionTree where, VisitorState state) { Attribute.Compound annotation = getRestrictedApiAnnotation(method, state); if (annotation != null) { return checkRestriction(annotation, where, state); } // Try each super method for @RestrictedApi return streamSuperMethods(method, state.getTypes()) .filter((t) -> ASTHelpers.hasAnnotation(t, RestrictedApi.class, state)) .findFirst() .map( superWithRestrictedApi -> checkRestriction( getRestrictedApiAnnotation(superWithRestrictedApi, state), where, state)) .orElse(NO_MATCH); } @Nullable private static Attribute.Compound getRestrictedApiAnnotation(Symbol sym, VisitorState state) { if (sym == null) { return null; } return sym.attribute(state.getSymbolFromString(RestrictedApi.class.getName())); } private Description checkRestriction( @Nullable Attribute.Compound attribute, Tree where, VisitorState state) { if (attribute == null) { return NO_MATCH; } RestrictedApi restriction = AnnotationProxyMaker.generateAnnotation(attribute, RestrictedApi.class); if (restriction == null) { return NO_MATCH; } if (!restriction.allowedOnPath().isEmpty()) { JCCompilationUnit compilationUnit = (JCCompilationUnit) state.getPath().getCompilationUnit(); String path = compilationUnit.getSourceFile().toUri().toString(); try { if (Pattern.matches(restriction.allowedOnPath(), path)) { return NO_MATCH; } } catch (PatternSyntaxException e) { throw new IllegalArgumentException( String.format( "Invalid regex for RestrictedApi annotation of %s", state.getSourceForNode(where)), e); } } boolean warn = Matchers.enclosingNode(shouldAllowWithWarning(attribute)).matches(where, state); boolean allow = Matchers.enclosingNode(shouldAllow(attribute)).matches(where, state); if (warn && allow) { // TODO(bangert): Clarify this message if possible. var descriptionBuilder = buildDescription(where) .setMessage( "The Restricted API (" + restriction.explanation() + ") call here is both allowlisted-as-warning and " + "silently allowlisted. " + "Please remove one of the conflicting suppression annotations."); if (!restriction.link().isEmpty()) { descriptionBuilder.setLinkUrl(restriction.link()); } return descriptionBuilder.build(); } if (allow) { return NO_MATCH; } SeverityLevel level = warn ? SeverityLevel.WARNING : SeverityLevel.ERROR; Description.Builder description = buildDescription(where).setMessage(restriction.explanation()).overrideSeverity(level); return description.build(); } // TODO(bangert): Memoize these if necessary. private static Matcher<Tree> shouldAllow(Attribute.Compound api) { Optional<Attribute> allowlistAnnotations = MoreAnnotations.getValue(api, "allowlistAnnotations"); // TODO(b/178905039): remove handling of legacy names if (!allowlistAnnotations.isPresent()) { allowlistAnnotations = MoreAnnotations.getValue(api, "whitelistAnnotations"); } return Matchers.hasAnyAnnotation( allowlistAnnotations .map(MoreAnnotations::asTypes) .orElse(Stream.empty()) .collect(toImmutableList())); } private static Matcher<Tree> shouldAllowWithWarning(Attribute.Compound api) { Optional<Attribute> allowlistWithWarningAnnotations = MoreAnnotations.getValue(api, "allowlistWithWarningAnnotations"); // TODO(b/178905039): remove handling of legacy names if (!allowlistWithWarningAnnotations.isPresent()) { allowlistWithWarningAnnotations = MoreAnnotations.getValue(api, "whitelistWithWarningAnnotations"); } return Matchers.hasAnyAnnotation( allowlistWithWarningAnnotations .map(MoreAnnotations::asTypes) .orElse(Stream.empty()) .collect(toImmutableList())); } }
11,972
40.572917
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MultipleTopLevelClasses.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.LinkType.CUSTOM; import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION; import static com.google.errorprone.matchers.Description.NO_MATCH; import com.google.common.base.Joiner; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.StandardTags; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher; import com.google.errorprone.matchers.Description; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.Tree; import java.util.ArrayList; import java.util.List; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( altNames = {"TopLevel"}, summary = "Source files should not contain multiple top-level class declarations", severity = SUGGESTION, documentSuppression = false, linkType = CUSTOM, tags = StandardTags.STYLE, link = "https://google.github.io/styleguide/javaguide.html#s3.4.1-one-top-level-class") public final class MultipleTopLevelClasses extends BugChecker implements CompilationUnitTreeMatcher { @Override public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) { List<String> names = new ArrayList<>(); for (Tree member : tree.getTypeDecls()) { if (member instanceof ClassTree) { ClassTree classMember = (ClassTree) member; switch (classMember.getKind()) { case CLASS: case INTERFACE: case ANNOTATION_TYPE: case ENUM: if (isSuppressed(classMember, state)) { // If any top-level classes have @SuppressWarnings("TopLevel"), ignore // this compilation unit. We can't rely on the normal suppression // mechanism because the only enclosing element is the package declaration, // and @SuppressWarnings can't be applied to packages. return NO_MATCH; } names.add(classMember.getSimpleName().toString()); break; default: break; } } } if (names.size() <= 1) { // this can happen with multiple type declarations if some of them are // empty (e.g. ";" at the top level counts as an empty type decl) return NO_MATCH; } String message = String.format( "Expected at most one top-level class declaration, instead found: %s", Joiner.on(", ").join(names)); for (Tree typeDecl : tree.getTypeDecls()) { state.reportMatch(buildDescription(typeDecl).setMessage(message).build()); } return NO_MATCH; } }
3,399
38.08046
91
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/ImmutableSetForContains.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.hasAnnotationWithSimpleName; import static com.google.errorprone.matchers.Matchers.hasModifier; import static com.google.errorprone.matchers.Matchers.instanceMethod; import static com.google.errorprone.matchers.Matchers.isSameType; import static com.google.errorprone.matchers.Matchers.isStatic; import static com.google.errorprone.matchers.Matchers.staticMethod; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.shouldKeep; import static com.google.errorprone.util.ASTHelpers.streamReceivers; import static java.util.stream.Collectors.toMap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.ParameterizedTypeTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol; import java.util.Map; import java.util.Optional; import java.util.stream.Stream; import javax.lang.model.element.Modifier; /** * Refactoring to suggest using {@code private static final} {@link ImmutableSet} over {@link * ImmutableList} when using only contains, containsAll and isEmpty. */ @BugPattern( summary = "This private static ImmutableList is only used for contains, containsAll or isEmpty" + " checks; prefer ImmutableSet.", severity = SUGGESTION) public final class ImmutableSetForContains extends BugChecker implements ClassTreeMatcher { private static final Matcher<Tree> PRIVATE_STATIC_IMMUTABLE_LIST_MATCHER = allOf( isStatic(), hasModifier(Modifier.PRIVATE), hasModifier(Modifier.FINAL), isSameType(ImmutableList.class)); private static final Matcher<Tree> EXCLUSIONS = anyOf( (t, s) -> shouldKeep(t), hasAnnotationWithSimpleName("Bind"), hasAnnotationWithSimpleName("Inject")); private static final Matcher<ExpressionTree> IMMUTABLE_LIST_FACTORIES = staticMethod().onClass(ImmutableList.class.getName()).namedAnyOf("of", "copyOf"); private static final Matcher<ExpressionTree> IMMUTABLE_LIST_BUILD = instanceMethod().onExactClass(ImmutableList.Builder.class.getName()).namedAnyOf("build"); private static final Matcher<ExpressionTree> IMMUTABLE_COLLECTION = instanceMethod().onExactClass(Stream.class.getName()).named("collect"); private static final Matcher<ExpressionTree> IMMUTABLE_BUILDER_METHODS = instanceMethod() .onExactClass(ImmutableList.Builder.class.getName()) .namedAnyOf("add", "addAll"); @Override public Description matchClass(ClassTree tree, VisitorState state) { ImmutableSet<VariableTree> immutableListVar = tree.getMembers().stream() .filter(member -> member.getKind().equals(Kind.VARIABLE)) .map(VariableTree.class::cast) // TODO(ashishkedia) : Expand to non-static vars with simple init in constructors. .filter( member -> PRIVATE_STATIC_IMMUTABLE_LIST_MATCHER.matches(member, state) && !EXCLUSIONS.matches(member, state)) .collect(toImmutableSet()); if (immutableListVar.isEmpty()) { return Description.NO_MATCH; } ImmutableVarUsageScanner usageScanner = new ImmutableVarUsageScanner(immutableListVar); // Scan entire compilation unit since private static vars of nested classes may be referred in // parent class. TreePath cuPath = state.findPathToEnclosing(CompilationUnitTree.class); usageScanner.scan(cuPath.getLeaf(), state.withPath(cuPath)); SuggestedFix.Builder fix = SuggestedFix.builder(); Optional<VariableTree> firstReplacement = Optional.empty(); for (VariableTree var : immutableListVar) { if (isSuppressed(var, state)) { continue; } if (!usageScanner.disallowedVarUsages.get(getSymbol(var))) { firstReplacement = Optional.of(var); fix.merge(convertListToSetInit(var, state)); } } if (!firstReplacement.isPresent()) { return Description.NO_MATCH; } return describeMatch(firstReplacement.get(), fix.build()); } private static SuggestedFix convertListToSetInit(VariableTree var, VisitorState state) { SuggestedFix.Builder fix = SuggestedFix.builder() .addImport(ImmutableSet.class.getName()) .replace(stripParameters(var.getType()), "ImmutableSet"); if (IMMUTABLE_LIST_FACTORIES.matches(var.getInitializer(), state)) { fix.replace(getReceiver(var.getInitializer()), "ImmutableSet"); return fix.build(); } if (IMMUTABLE_COLLECTION.matches(var.getInitializer(), state)) { fix.addStaticImport("com.google.common.collect.ImmutableSet.toImmutableSet") .replace( getOnlyElement(((MethodInvocationTree) var.getInitializer()).getArguments()), "toImmutableSet()"); return fix.build(); } if (IMMUTABLE_LIST_BUILD.matches(var.getInitializer(), state)) { Optional<ExpressionTree> rootExpr = getRootMethod((MethodInvocationTree) var.getInitializer(), state); if (rootExpr.isPresent()) { if (rootExpr.get().getKind().equals(Kind.METHOD_INVOCATION)) { MethodInvocationTree methodTree = (MethodInvocationTree) rootExpr.get(); fix.replace(getReceiver(methodTree), "ImmutableSet"); return fix.build(); } if (rootExpr.get().getKind().equals(Kind.NEW_CLASS)) { NewClassTree ctorTree = (NewClassTree) rootExpr.get(); fix.replace(stripParameters(ctorTree.getIdentifier()), "ImmutableSet.Builder"); } return fix.build(); } } return fix.replace( var.getInitializer(), "ImmutableSet.copyOf(" + state.getSourceForNode(var.getInitializer()) + ")") .build(); } private static Tree stripParameters(Tree tree) { return tree.getKind().equals(Kind.PARAMETERIZED_TYPE) ? ((ParameterizedTypeTree) tree).getType() : tree; } private static Optional<ExpressionTree> getRootMethod( MethodInvocationTree methodInvocationTree, VisitorState state) { return streamReceivers(methodInvocationTree) .filter(t -> !IMMUTABLE_BUILDER_METHODS.matches(t, state)) .findFirst(); } // Scans the tree for all usages of immutable list vars and determines if any usage will prevent // us from turning ImmutableList into ImmutableSet. private static final class ImmutableVarUsageScanner extends TreeScanner<Void, VisitorState> { private static final Matcher<ExpressionTree> ALLOWED_FUNCTIONS_ON_LIST = instanceMethod() .onExactClass(ImmutableList.class.getName()) .namedAnyOf("contains", "containsAll", "isEmpty"); // For each ImmutableList usage var, we will keep a map indicating if the var has been used in a // way that would prevent us from making it a set. private final Map<Symbol, Boolean> disallowedVarUsages; private ImmutableVarUsageScanner(ImmutableSet<VariableTree> immutableListVar) { this.disallowedVarUsages = immutableListVar.stream() .map(ASTHelpers::getSymbol) .collect(toMap(x -> x, x -> Boolean.FALSE)); } @Override public Void visitMethodInvocation( MethodInvocationTree methodInvocationTree, VisitorState state) { methodInvocationTree.getArguments().forEach(tree -> scan(tree, state)); methodInvocationTree.getTypeArguments().forEach(tree -> scan(tree, state)); if (!allowedFuncOnImmutableVar(methodInvocationTree, state)) { scan(methodInvocationTree.getMethodSelect(), state); } return null; } private boolean allowedFuncOnImmutableVar(MethodInvocationTree methodTree, VisitorState state) { ExpressionTree receiver = getReceiver(methodTree); if (receiver == null) { return false; } if (!disallowedVarUsages.containsKey(getSymbol(receiver))) { // Not a function invocation on any of the candidate immutable list vars. return false; } return ALLOWED_FUNCTIONS_ON_LIST.matches(methodTree, state); } @Override public Void visitIdentifier(IdentifierTree identifierTree, VisitorState visitorState) { recordDisallowedUsage(getSymbol(identifierTree)); return super.visitIdentifier(identifierTree, visitorState); } @Override public Void visitMemberSelect(MemberSelectTree memberSelectTree, VisitorState visitorState) { recordDisallowedUsage(getSymbol(memberSelectTree)); return super.visitMemberSelect(memberSelectTree, visitorState); } private void recordDisallowedUsage(Symbol symbol) { disallowedVarUsages.computeIfPresent(symbol, (sym, oldVal) -> Boolean.TRUE); } } }
10,691
42.287449
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/TestExceptionChecker.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.collect.Iterables.getLast; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.fixes.SuggestedFixes.qualifyType; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.getStartPosition; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.JUnitMatchers; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionStatementTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCAssign; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.Tag; import java.util.Collection; import java.util.List; import javax.annotation.Nullable; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Using @Test(expected=...) is discouraged, since the test will pass if *any* statement in" + " the test method throws the expected exception", severity = WARNING) public class TestExceptionChecker extends BugChecker implements MethodTreeMatcher { @Override public Description matchMethod(MethodTree tree, VisitorState state) { if (tree.getBody() == null) { return NO_MATCH; } SuggestedFix.Builder baseFixBuilder = SuggestedFix.builder(); JCExpression expectedException = deleteExpectedException( baseFixBuilder, ((JCMethodDecl) tree).getModifiers().getAnnotations(), state); SuggestedFix baseFix = baseFixBuilder.build(); if (expectedException == null) { return NO_MATCH; } return handleStatements(tree, state, expectedException, baseFix); } /** * Handle a method annotated with {@code @Test(expected=...}. * * @param tree the method * @param state the visitor state * @param expectedException the type of expected exception * @param baseFix the base fix */ private Description handleStatements( MethodTree tree, VisitorState state, JCExpression expectedException, SuggestedFix baseFix) { return describeMatch( tree, buildFix( state, SuggestedFix.builder().merge(baseFix), expectedException, tree.getBody().getStatements())); } private static SuggestedFix buildFix( VisitorState state, SuggestedFix.Builder fix, JCExpression expectedException, Collection<? extends StatementTree> statements) { if (statements.isEmpty()) { return fix.build(); } fix.addStaticImport("org.junit.Assert.assertThrows"); StringBuilder prefix = new StringBuilder(); prefix.append( String.format("assertThrows(%s, () -> ", state.getSourceForNode(expectedException))); StatementTree last = getLast(statements); if (last instanceof ExpressionStatementTree) { ExpressionTree expression = ((ExpressionStatementTree) last).getExpression(); fix.prefixWith(expression, prefix.toString()); fix.postfixWith(expression, ")"); } else { prefix.append(" {"); fix.prefixWith(last, prefix.toString()); fix.postfixWith(last, "});"); } return fix.build(); } /** * Searches the annotation list for {@code @Test(expected=...)}. If found, deletes the exception * attribute from the annotation, and returns its value. */ @Nullable private static JCExpression deleteExpectedException( SuggestedFix.Builder fix, List<JCAnnotation> annotations, VisitorState state) { Type testAnnotation = ORG_JUNIT_TEST.get(state); for (JCAnnotation annotationTree : annotations) { if (!ASTHelpers.isSameType(testAnnotation, annotationTree.type, state)) { continue; } com.sun.tools.javac.util.List<JCExpression> arguments = annotationTree.getArguments(); for (JCExpression arg : arguments) { if (!arg.hasTag(Tag.ASSIGN)) { continue; } JCAssign assign = (JCAssign) arg; if (assign.lhs.hasTag(Tag.IDENT) && ((JCIdent) assign.lhs).getName().contentEquals("expected")) { if (arguments.size() == 1) { fix.replace( annotationTree, "@" + qualifyType(state, fix, JUnitMatchers.JUNIT4_TEST_ANNOTATION)); } else { removeFromList(fix, state, arguments, assign); } return assign.rhs; } } } return null; } /** Deletes an entry and its delimiter from a list. */ private static void removeFromList( SuggestedFix.Builder fix, VisitorState state, List<? extends Tree> arguments, Tree tree) { int idx = arguments.indexOf(tree); if (idx == arguments.size() - 1) { fix.replace( state.getEndPosition(arguments.get(arguments.size() - 1)), state.getEndPosition(tree), ""); } else { fix.replace(getStartPosition(tree), getStartPosition(arguments.get(idx + 1)), ""); } } private static final Supplier<Type> ORG_JUNIT_TEST = VisitorState.memoize(state -> state.getTypeFromString(JUnitMatchers.JUNIT4_TEST_ANNOTATION)); }
6,407
37.142857
99
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/LiteByteStringUtf8.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.instanceMethod; import static com.google.errorprone.matchers.Matchers.receiverOfInvocation; import static com.google.errorprone.matchers.Matchers.toType; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.MethodInvocationTree; /** * @author glorioso@google.com (Nick Glorioso) */ @BugPattern( summary = "This pattern will silently corrupt certain byte sequences from the serialized protocol " + "message. Use ByteString or byte[] directly", severity = ERROR) public class LiteByteStringUtf8 extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<MethodInvocationTree> BYTE_STRING_UTF_8 = allOf( instanceMethod().onDescendantOf("com.google.protobuf.ByteString").named("toStringUtf8"), receiverOfInvocation( toType( MethodInvocationTree.class, instanceMethod() .onDescendantOf("com.google.protobuf.MessageLite") .named("toByteString")))); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { return BYTE_STRING_UTF_8.matches(tree, state) ? describeMatch(tree) : Description.NO_MATCH; } }
2,307
40.214286
98
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AmbiguousMethodReference.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.getType; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toCollection; import com.google.common.collect.Streams; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.Signatures; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Types; import java.util.ArrayList; import java.util.List; import java.util.Map; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern(summary = "Method reference is ambiguous", severity = WARNING) public class AmbiguousMethodReference extends BugChecker implements ClassTreeMatcher { @Override public Description matchClass(ClassTree tree, VisitorState state) { ClassSymbol origin = getSymbol(tree); Types types = state.getTypes(); Iterable<Symbol> members = types.membersClosure(getType(tree), /* skipInterface= */ false).getSymbols(); // collect declared and inherited methods, grouped by reference descriptor Map<String, List<MethodSymbol>> methods = Streams.stream(members) .filter(MethodSymbol.class::isInstance) .map(MethodSymbol.class::cast) .filter(m -> m.isConstructor() || m.owner.equals(origin)) .collect( groupingBy(m -> methodReferenceDescriptor(types, m), toCollection(ArrayList::new))); // look for groups of ambiguous method references for (Tree member : tree.getMembers()) { if (!(member instanceof MethodTree)) { continue; } MethodSymbol msym = getSymbol((MethodTree) member); if (isSuppressed(msym, state)) { continue; } List<MethodSymbol> clash = methods.remove(methodReferenceDescriptor(types, msym)); if (clash == null) { continue; } // If the clashing group has 1 or 0 non-private methods, method references outside the file // are unambiguous. int nonPrivateMethodCount = 0; for (MethodSymbol method : clash) { if (!method.isPrivate()) { nonPrivateMethodCount++; } } if (nonPrivateMethodCount < 2) { continue; } clash.remove(msym); // ignore overridden inherited methods and hidden interface methods clash.removeIf(m -> types.isSubSignature(msym.type, m.type)); if (clash.isEmpty()) { continue; } String message = String.format( "This method's reference is ambiguous, its name and functional interface type" + " are the same as: %s", clash.stream() .map(m -> Signatures.prettyMethodSignature(origin, m)) .collect(joining(", "))); state.reportMatch(buildDescription(member).setMessage(message).build()); } return NO_MATCH; } /** Returns a string descriptor of a method's reference type. */ private static String methodReferenceDescriptor(Types types, MethodSymbol sym) { StringBuilder sb = new StringBuilder(); sb.append(sym.getSimpleName()).append('('); if (!sym.isStatic()) { sb.append(Signatures.descriptor(sym.owner.type, types)); } sym.params().stream().map(p -> Signatures.descriptor(p.type, types)).forEachOrdered(sb::append); sb.append(")"); return sb.toString(); } }
4,661
38.508475
100
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/MissingRefasterAnnotation.java
/* * Copyright 2022 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.BugPattern.StandardTags.LIKELY_ERROR; import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE; import static com.google.errorprone.matchers.Matchers.annotations; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.isType; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.MultiMatcher; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "The Refaster template contains a method without any Refaster annotations", severity = WARNING, tags = LIKELY_ERROR) public final class MissingRefasterAnnotation extends BugChecker implements ClassTreeMatcher { private static final MultiMatcher<Tree, AnnotationTree> HAS_REFASTER_ANNOTATION = annotations( AT_LEAST_ONE, anyOf( isType("com.google.errorprone.refaster.annotation.Placeholder"), isType("com.google.errorprone.refaster.annotation.BeforeTemplate"), isType("com.google.errorprone.refaster.annotation.AfterTemplate"))); @Override public Description matchClass(ClassTree tree, VisitorState state) { long methodTypeCount = tree.getMembers().stream() .filter(member -> member.getKind() == Tree.Kind.METHOD) .map(MethodTree.class::cast) .filter(method -> !ASTHelpers.isGeneratedConstructor(method)) .map(method -> HAS_REFASTER_ANNOTATION.matches(method, state)) .distinct() .count(); return methodTypeCount < 2 ? Description.NO_MATCH : describeMatch(tree); } }
2,790
41.938462
93
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/NegativeCharLiteral.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.isSameType; import static com.google.errorprone.matchers.Matchers.kindIs; import static com.google.errorprone.matchers.Matchers.typeCast; import static com.sun.source.tree.Tree.Kind.INT_LITERAL; import static com.sun.source.tree.Tree.Kind.LONG_LITERAL; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.TypeCastTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Matcher; import com.sun.source.tree.LiteralTree; import com.sun.source.tree.TypeCastTree; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Casting a negative signed literal to an (unsigned) char might be misleading.", severity = WARNING) public class NegativeCharLiteral extends BugChecker implements TypeCastTreeMatcher { private static final Matcher<TypeCastTree> isIntegralLiteralCastToChar = typeCast(isSameType("char"), anyOf(kindIs(LONG_LITERAL), kindIs(INT_LITERAL))); @Override public Description matchTypeCast(TypeCastTree tree, VisitorState state) { if (!isIntegralLiteralCastToChar.matches(tree, state)) { return NO_MATCH; } long literalValue = ((Number) ((LiteralTree) tree.getExpression()).getValue()).longValue(); if (literalValue >= 0) { return NO_MATCH; } char castResult = (char) literalValue; String replacement; if (castResult == Character.MAX_VALUE) { replacement = "Character.MAX_VALUE"; } else { replacement = String.format("Character.MAX_VALUE - %s", Character.MAX_VALUE - castResult); } return describeMatch(tree, SuggestedFix.builder().replace(tree, replacement).build()); } }
2,717
39.567164
96
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/LongFloatConversion.java
/* * Copyright 2020 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.google.errorprone.matchers.Description.NO_MATCH; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.targetType; import com.google.errorprone.BugPattern; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.util.TreePath; import javax.lang.model.type.TypeKind; /** A {@link BugChecker}; see the associated {@link BugPattern} annotation for details. */ @BugPattern( summary = "Conversion from long to float may lose precision; use an explicit cast to float if this" + " was intentional", severity = WARNING) public class LongFloatConversion extends BugChecker implements MethodInvocationTreeMatcher { @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { for (ExpressionTree arg : tree.getArguments()) { if (!getType(arg).getKind().equals(TypeKind.LONG)) { continue; } ASTHelpers.TargetType targetType = targetType(state.withPath(new TreePath(state.getPath(), arg))); if (targetType == null) { continue; } if (targetType.type().getKind().equals(TypeKind.FLOAT)) { state.reportMatch(describeMatch(arg, SuggestedFix.prefixWith(arg, "(float) "))); } } return NO_MATCH; } }
2,373
37.918033
97
java
error-prone
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/AssertThrowsUtils.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.collect.Iterables.getLast; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.util.ASTHelpers.getStartPosition; import static java.util.stream.Collectors.joining; import com.google.common.collect.Iterables; import com.google.errorprone.VisitorState; import com.google.errorprone.fixes.Fix; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.CatchTree; import com.sun.source.tree.ExpressionStatementTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.TryTree; import java.util.List; import java.util.Optional; /** * Utility methods for refactoring try-fail pattern to assertThrows, which is preferred. Used by * {@link TryFailRefactoring} and {@link MissingFail}. */ public final class AssertThrowsUtils { /** * Transforms a try-catch block in the try-fail pattern into a call to JUnit's {@code * assertThrows}, inserting the behavior of the {@code try} block into a lambda parameter, and * assigning the expected exception to a variable, if it is used within the {@code catch} block. * For example: * * <pre> * try { * foo(); * fail(); * } catch (MyException expected) { * assertThat(expected).isEqualTo(other); * } * </pre> * * becomes * * <pre> * {@code MyException expected = assertThrows(MyException.class, () -> foo());} * assertThat(expected).isEqualTo(other); * </pre> * * @param tryTree the tree representing the try-catch block to be refactored. * @param throwingStatements the list of statements in the {@code throw} clause, <b>excluding</b> * the fail statement. * @param state current visitor state (for source positions). * @return an {@link Optional} containing a {@link Fix} that replaces {@code tryTree} with an * equivalent {@code assertThrows}, if possible. Returns an {@code Optional.empty()} if a fix * could not be constructed for the given code (e.g. multi-catch). */ public static Optional<Fix> tryFailToAssertThrows( TryTree tryTree, List<? extends StatementTree> throwingStatements, Optional<Tree> failureMessage, VisitorState state) { List<? extends CatchTree> catchTrees = tryTree.getCatches(); if (catchTrees.size() != 1) { return Optional.empty(); } CatchTree catchTree = Iterables.getOnlyElement(catchTrees); SuggestedFix.Builder fix = SuggestedFix.builder(); StringBuilder fixPrefix = new StringBuilder(); String fixSuffix = ""; if (throwingStatements.isEmpty()) { return Optional.empty(); } List<? extends StatementTree> catchStatements = catchTree.getBlock().getStatements(); fix.addStaticImport("org.junit.Assert.assertThrows"); List<? extends Tree> resources = tryTree.getResources(); if (!resources.isEmpty()) { fixPrefix.append( resources.stream().map(state::getSourceForNode).collect(joining("\n", "try (", ") {\n"))); fixSuffix = "\n}"; } if (!catchStatements.isEmpty()) { // TODO(cushon): pick a fresh name for the variable, if necessary fixPrefix.append(String.format("%s = ", state.getSourceForNode(catchTree.getParameter()))); } fixPrefix.append( String.format( "assertThrows(%s%s.class, () -> ", failureMessage // Supplying a constant string adds little value, since a failure here always means // the same thing: the method just called wasn't expected to complete normally, but // it did. .filter(t -> ASTHelpers.constValue(t, String.class) == null) .map(t -> state.getSourceForNode(t) + ", ") .orElse(""), state.getSourceForNode(catchTree.getParameter().getType()))); boolean useExpressionLambda = throwingStatements.size() == 1 && getOnlyElement(throwingStatements).getKind() == Kind.EXPRESSION_STATEMENT; if (!useExpressionLambda) { fixPrefix.append("{"); } fix.replace( getStartPosition(tryTree), getStartPosition(throwingStatements.iterator().next()), fixPrefix.toString()); if (useExpressionLambda) { fix.postfixWith( ((ExpressionStatementTree) throwingStatements.iterator().next()).getExpression(), ")"); } else { fix.postfixWith(getLast(throwingStatements), "});"); } if (catchStatements.isEmpty()) { fix.replace( state.getEndPosition(getLast(throwingStatements)), state.getEndPosition(tryTree), fixSuffix); } else { fix.replace( /* startPos= */ state.getEndPosition(getLast(throwingStatements)), /* endPos= */ getStartPosition(catchStatements.get(0)), "\n"); fix.replace( state.getEndPosition(getLast(catchStatements)), state.getEndPosition(tryTree), fixSuffix); } return Optional.of(fix.build()); } private AssertThrowsUtils() {} }
5,790
38.394558
100
java