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/check_api/src/test/java/com/google/errorprone/fixes/BranchedSuggestedFixesTest.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.fixes; import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.ImmutableList; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Test for BranchSuggestedFixes */ @RunWith(JUnit4.class) public class BranchedSuggestedFixesTest { @Test public void combinesBranchWithFirst() { ImmutableList<SuggestedFix> fixes = BranchedSuggestedFixes.builder() .startWith(SuggestedFix.builder().addImport("A").build()) .then() .addOption(SuggestedFix.builder().addImport("B").build()) .addOption(SuggestedFix.builder().addImport("C").build()) .build() .getFixes(); assertThat(fixes).hasSize(2); assertThat(fixes.get(0).getImportsToAdd()).containsExactly("import A", "import B"); assertThat(fixes.get(1).getImportsToAdd()).containsExactly("import A", "import C"); } @Test public void emptyIfNoProgress() { ImmutableList<SuggestedFix> fixes = BranchedSuggestedFixes.builder() .startWith(SuggestedFix.builder().addImport("A").build()) .then() .then() .build() .getFixes(); assertThat(fixes).isEmpty(); } @Test public void emptyIfResumedProgress() { ImmutableList<SuggestedFix> fixes = BranchedSuggestedFixes.builder() .startWith(SuggestedFix.builder().addImport("A").build()) .then() .then() .addOption(SuggestedFix.builder().addImport("B").build()) .build() .getFixes(); assertThat(fixes).isEmpty(); } }
2,281
31.6
87
java
error-prone
error-prone-master/check_api/src/test/java/com/google/errorprone/fixes/AppliedFixTest.java
/* * Copyright 2011 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.fixes; import static com.google.common.truth.Truth.assertThat; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.sun.source.tree.TreeVisitor; import com.sun.tools.javac.tree.EndPosTable; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.util.Position; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author alexeagle@google.com (Alex Eagle) */ @RunWith(JUnit4.class) public class AppliedFixTest { final EndPosTable endPositions = new EndPosTable() { final Map<JCTree, Integer> map = new HashMap<>(); @Override public void storeEnd(JCTree tree, int endpos) { map.put(tree, endpos); } @Override public int replaceTree(JCTree oldtree, JCTree newtree) { Integer endpos = map.getOrDefault(oldtree, Position.NOPOS); map.put(newtree, endpos); return endpos; } @Override public int getEndPos(JCTree tree) { Integer result = map.getOrDefault(tree, Position.NOPOS); return result; } }; // TODO(b/67738557): consolidate helpers for creating fake trees JCTree node(int startPos, int endPos) { return new JCTree() { @Override public Tag getTag() { throw new UnsupportedOperationException(); } @Override public void accept(Visitor v) { throw new UnsupportedOperationException(); } @Override public <R, D> R accept(TreeVisitor<R, D> v, D d) { throw new UnsupportedOperationException(); } @Override public Kind getKind() { throw new UnsupportedOperationException(); } @Override public int getStartPosition() { return startPos; } @Override public int getEndPosition(EndPosTable endPosTable) { return endPos; } }; } @Test public void shouldApplySingleFixOnALine() { JCTree node = node(11, 14); AppliedFix fix = AppliedFix.fromSource("import org.me.B;", endPositions).apply(SuggestedFix.delete(node)); assertThat(fix.getNewCodeSnippet().toString(), equalTo("import org.B;")); } @Test public void shouldReportOnlyTheChangedLineInNewSnippet() { JCTree node = node(25, 26); AppliedFix fix = AppliedFix.fromSource("public class Foo {\n" + " int 3;\n" + "}", endPositions) .apply( SuggestedFix.builder().prefixWith(node, "three").postfixWith(node, "tres").build()); assertThat(fix.getNewCodeSnippet().toString()).isEqualTo("int three3tres;"); } @Test public void shouldReturnNullOnEmptyFix() { AppliedFix fix = AppliedFix.fromSource("public class Foo {}", endPositions).apply(SuggestedFix.emptyFix()); assertThat(fix).isNull(); } @Test public void shouldReturnNullOnImportOnlyFix() { AppliedFix fix = AppliedFix.fromSource("public class Foo {}", endPositions) .apply(SuggestedFix.builder().addImport("foo.bar.Baz").build()); assertThat(fix).isNull(); } @Test public void shouldThrowExceptionOnIllegalRange() { assertThrows(IllegalArgumentException.class, () -> SuggestedFix.replace(0, -1, "")); assertThrows(IllegalArgumentException.class, () -> SuggestedFix.replace(-1, -1, "")); assertThrows(IllegalArgumentException.class, () -> SuggestedFix.replace(-1, 1, "")); } @Test public void shouldSuggestToRemoveLastLineIfAsked() { JCTree node = node(21, 42); AppliedFix fix = AppliedFix.fromSource("package com.example;\n" + "import java.util.Map;\n", endPositions) .apply(SuggestedFix.delete(node)); assertThat(fix.getNewCodeSnippet().toString(), equalTo("to remove this line")); } @Test public void shouldApplyFixesInReverseOrder() { // Have to use a mock Fix here in order to intentionally return Replacements in wrong order. Set<Replacement> replacements = new LinkedHashSet<>(); replacements.add(Replacement.create(0, 1, "")); replacements.add(Replacement.create(1, 1, "")); Fix mockFix = mock(Fix.class); when(mockFix.getReplacements(any())).thenReturn(replacements); // If the fixes had been applied in the wrong order, this would fail. // But it succeeds, so they were applied in the right order. AppliedFix.fromSource(" ", endPositions).apply(mockFix); } @Test public void shouldThrowIfReplacementOutsideSource() { AppliedFix.Applier applier = AppliedFix.fromSource("Hello", endPositions); SuggestedFix fix = SuggestedFix.replace(0, 6, "World!"); assertThrows(IllegalArgumentException.class, () -> applier.apply(fix)); } }
5,642
30.702247
100
java
error-prone
error-prone-master/check_api/src/test/java/com/google/errorprone/fixes/ReplacementsTest.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.fixes; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import static org.junit.Assert.fail; import com.google.common.base.Function; import com.google.common.collect.Iterables; import com.google.common.collect.Range; import com.google.errorprone.fixes.Replacements.CoalescePolicy; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link Replacements}Test */ @RunWith(JUnit4.class) public class ReplacementsTest { @Test public void duplicate() { Replacements replacements = new Replacements(); replacements.add(Replacement.create(42, 43, "hello")); try { replacements.add(Replacement.create(42, 43, "goodbye")); fail(); } catch (IllegalArgumentException expected) { assertThat(expected).hasMessageThat().contains("conflicts with existing replacement"); } } @Test public void overlap() { Replacements replacements = new Replacements(); Replacement hello = Replacement.create(2, 4, "hello"); Replacement goodbye = Replacement.create(3, 5, "goodbye"); replacements.add(hello); try { replacements.add(goodbye); fail(); } catch (IllegalArgumentException expected) { assertThat(expected) .hasMessageThat() .isEqualTo(String.format("%s overlaps with existing replacements: %s", goodbye, hello)); } } private static final Function<Replacement, Range<Integer>> AS_RANGES = new Function<Replacement, Range<Integer>>() { @Override public Range<Integer> apply(Replacement replacement) { return replacement.range(); } }; @Test public void ascending() { assertThat( Iterables.transform( new Replacements() .add(Replacement.create(0, 0, "hello")) .add(Replacement.create(0, 1, "hello")) .ascending(), AS_RANGES)) .containsExactly(Range.closedOpen(0, 0), Range.closedOpen(0, 1)) .inOrder(); assertThat( Iterables.transform( new Replacements() .add(Replacement.create(0, 1, "hello")) .add(Replacement.create(0, 0, "hello")) .ascending(), AS_RANGES)) .containsExactly(Range.closedOpen(0, 0), Range.closedOpen(0, 1)) .inOrder(); } @Test public void identicalDuplicatesOK() { Replacements replacements = new Replacements(); replacements.add(Replacement.create(42, 43, "hello")); replacements.add(Replacement.create(42, 43, "hello")); } @Test public void coalesceExistingFirst() { // A replacement of an empty region represents an insertion. // Multiple, differing insertions at the same insertion point are allowed, and will be // coalesced into a single Replacement at that insertion point. assertThat( new Replacements() .add(Replacement.create(42, 42, "hello;")) .add(Replacement.create(42, 42, "goodbye;"), CoalescePolicy.EXISTING_FIRST) .descending()) .containsExactly(Replacement.create(42, 42, "hello;goodbye;")); assertThat( new Replacements() .add(Replacement.create(42, 42, "goodbye;")) .add(Replacement.create(42, 42, "hello;"), CoalescePolicy.EXISTING_FIRST) .descending()) .containsExactly(Replacement.create(42, 42, "goodbye;hello;")); } @Test public void coalesceReplacementFirst() { // A replacement of an empty region represents an insertion. // Multiple, differing insertions at the same insertion point are allowed, and will be // coalesced into a single Replacement at that insertion point. assertThat( new Replacements() .add(Replacement.create(42, 42, "hello;")) .add(Replacement.create(42, 42, "goodbye;"), CoalescePolicy.REPLACEMENT_FIRST) .descending()) .contains(Replacement.create(42, 42, "goodbye;hello;")); assertThat( new Replacements() .add(Replacement.create(42, 42, "goodbye;")) .add(Replacement.create(42, 42, "hello;"), CoalescePolicy.REPLACEMENT_FIRST) .descending()) .containsExactly(Replacement.create(42, 42, "hello;goodbye;")); } @Test public void coalesceReject() { assertThrows( IllegalArgumentException.class, () -> new Replacements() .add(Replacement.create(42, 42, "hello;")) .add(Replacement.create(42, 42, "goodbye;"), CoalescePolicy.REJECT) .descending()); } @Test public void multipleInsertionsAreDeduplicated() { assertThat( new Replacements() .add(Replacement.create(42, 42, "@Nullable")) .add(Replacement.create(42, 42, "@Nullable")) .descending()) .containsExactly(Replacement.create(42, 42, "@Nullable")); } @Test public void duplicateInsertionsNotCoalesced() { assertThat( new Replacements() .add(Replacement.create(42, 42, "@Nullable"), CoalescePolicy.REPLACEMENT_FIRST) .add(Replacement.create(42, 42, "@Nullable"), CoalescePolicy.REPLACEMENT_FIRST) .descending()) .containsExactly(Replacement.create(42, 42, "@Nullable")); } @Test public void duplicateInsertionsCanBeKept() { assertThat( new Replacements() .add(Replacement.create(5, 5, "}"), CoalescePolicy.KEEP_ONLY_IDENTICAL_INSERTS) .add(Replacement.create(5, 5, "}"), CoalescePolicy.KEEP_ONLY_IDENTICAL_INSERTS) .descending()) .containsExactly(Replacement.create(5, 5, "}}")); } @Test public void zeroLengthRangeOverlaps() { Replacements replacements = new Replacements(); replacements.add(Replacement.create(1, 1, "Something")); Replacement around = Replacement.create(0, 2, "Around"); assertThrows(IllegalArgumentException.class, () -> replacements.add(around)); } }
6,813
35.438503
98
java
error-prone
error-prone-master/check_api/src/test/java/com/google/errorprone/dataflow/AccessPathStoreTest.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.dataflow; import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.mock; import com.google.errorprone.dataflow.nullnesspropagation.Nullness; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * @author bennostein@google.com (Benno Stein) */ @RunWith(JUnit4.class) public class AccessPathStoreTest { @Test public void leastUpperBoundEmpty() { assertThat(newStore().leastUpperBound(newStore())).isEqualTo(newStore()); } @Test public void buildAndGet() { AccessPathStore.Builder<Nullness> builder = newStore().toBuilder(); AccessPath path1 = mock(AccessPath.class); AccessPath path2 = mock(AccessPath.class); builder.setInformation(path1, Nullness.NULL); builder.setInformation(path2, Nullness.NONNULL); assertThat(builder.build().valueOfAccessPath(path1, Nullness.BOTTOM)).isEqualTo(Nullness.NULL); assertThat(builder.build().valueOfAccessPath(path2, Nullness.BOTTOM)) .isEqualTo(Nullness.NONNULL); assertThat(newStore().heap()).isEmpty(); } private static AccessPathStore<Nullness> newStore() { return AccessPathStore.empty(); } }
1,815
32.62963
99
java
error-prone
error-prone-master/check_api/src/test/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessTest.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.dataflow.nullnesspropagation; import static com.google.common.truth.Truth.assertThat; import static com.google.errorprone.dataflow.nullnesspropagation.Nullness.BOTTOM; import static com.google.errorprone.dataflow.nullnesspropagation.Nullness.NONNULL; import static com.google.errorprone.dataflow.nullnesspropagation.Nullness.NULL; import static com.google.errorprone.dataflow.nullnesspropagation.Nullness.NULLABLE; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for {@link Nullness}. * * @author eaftan@google.com (Eddie Aftandilian) */ @RunWith(JUnit4.class) public class NullnessTest { @Test public void leastUpperBound() { assertThat(NULLABLE.leastUpperBound(NULLABLE)).isEqualTo(NULLABLE); assertThat(NULLABLE.leastUpperBound(NULL)).isEqualTo(NULLABLE); assertThat(NULLABLE.leastUpperBound(NONNULL)).isEqualTo(NULLABLE); assertThat(NULLABLE.leastUpperBound(BOTTOM)).isEqualTo(NULLABLE); assertThat(NULL.leastUpperBound(NULLABLE)).isEqualTo(NULLABLE); assertThat(NULL.leastUpperBound(NULL)).isEqualTo(NULL); assertThat(NULL.leastUpperBound(NONNULL)).isEqualTo(NULLABLE); assertThat(NULL.leastUpperBound(BOTTOM)).isEqualTo(NULL); assertThat(NONNULL.leastUpperBound(NULLABLE)).isEqualTo(NULLABLE); assertThat(NONNULL.leastUpperBound(NULL)).isEqualTo(NULLABLE); assertThat(NONNULL.leastUpperBound(NONNULL)).isEqualTo(NONNULL); assertThat(NONNULL.leastUpperBound(BOTTOM)).isEqualTo(NONNULL); assertThat(BOTTOM.leastUpperBound(NULLABLE)).isEqualTo(NULLABLE); assertThat(BOTTOM.leastUpperBound(NULL)).isEqualTo(NULL); assertThat(BOTTOM.leastUpperBound(NONNULL)).isEqualTo(NONNULL); assertThat(BOTTOM.leastUpperBound(BOTTOM)).isEqualTo(BOTTOM); } @Test public void greatestLowerBound() { assertThat(NULLABLE.greatestLowerBound(NULLABLE)).isEqualTo(NULLABLE); assertThat(NULLABLE.greatestLowerBound(NULL)).isEqualTo(NULL); assertThat(NULLABLE.greatestLowerBound(NONNULL)).isEqualTo(NONNULL); assertThat(NULLABLE.greatestLowerBound(BOTTOM)).isEqualTo(BOTTOM); assertThat(NULL.greatestLowerBound(NULLABLE)).isEqualTo(NULL); assertThat(NULL.greatestLowerBound(NULL)).isEqualTo(NULL); assertThat(NULL.greatestLowerBound(NONNULL)).isEqualTo(BOTTOM); assertThat(NULL.greatestLowerBound(BOTTOM)).isEqualTo(BOTTOM); assertThat(NONNULL.greatestLowerBound(NULLABLE)).isEqualTo(NONNULL); assertThat(NONNULL.greatestLowerBound(NULL)).isEqualTo(BOTTOM); assertThat(NONNULL.greatestLowerBound(NONNULL)).isEqualTo(NONNULL); assertThat(NONNULL.greatestLowerBound(BOTTOM)).isEqualTo(BOTTOM); assertThat(BOTTOM.greatestLowerBound(NULLABLE)).isEqualTo(BOTTOM); assertThat(BOTTOM.greatestLowerBound(NULL)).isEqualTo(BOTTOM); assertThat(BOTTOM.greatestLowerBound(NONNULL)).isEqualTo(BOTTOM); assertThat(BOTTOM.greatestLowerBound(BOTTOM)).isEqualTo(BOTTOM); } @Test public void deducedValueWhenNotEqual() { assertThat(NULLABLE.deducedValueWhenNotEqual()).isEqualTo(NULLABLE); assertThat(NULL.deducedValueWhenNotEqual()).isEqualTo(NONNULL); assertThat(NONNULL.deducedValueWhenNotEqual()).isEqualTo(NULLABLE); assertThat(BOTTOM.deducedValueWhenNotEqual()).isEqualTo(BOTTOM); } }
3,925
42.622222
83
java
error-prone
error-prone-master/check_api/src/test/java/com/google/errorprone/dataflow/nullnesspropagation/NonNullAssumptionsTest.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.dataflow.nullnesspropagation; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import static org.junit.Assert.fail; import com.google.common.collect.ImmutableSet; import com.google.common.testing.ArbitraryInstances; import com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTransfer.MemberName; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Tests to verify assumptions about specific JDK and other methods and fields built into {@link * NullnessPropagationTransfer} by running the referenced methods and reading the referenced fields * where possible/feasible. * * @author kmb@google.com (Kevin Bierhoff) */ // TODO(kmb): Add tests for methods assumed to return non-null values (for all inputs...) @RunWith(JUnit4.class) public class NonNullAssumptionsTest { @Test public void classesWithNonNullStaticFields() throws Exception { for (String classname : NullnessPropagationTransfer.CLASSES_WITH_NON_NULL_CONSTANTS) { int found = 0; Class<?> clazz = loadClass(classname); for (Field field : clazz.getDeclaredFields()) { if (Modifier.isFinal(field.getModifiers()) && Modifier.isStatic(field.getModifiers())) { ++found; field.setAccessible(true); assertWithMessage(field.toString()).that(field.get(null)).isNotNull(); } } assertWithMessage(classname).that(found).isGreaterThan(0); } } @Test public void nullImpliesTrueParameters() throws Exception { for (MemberName member : NullnessPropagationTransfer.NULL_IMPLIES_TRUE_PARAMETERS.keySet()) { ImmutableSet<Integer> nullParameters = NullnessPropagationTransfer.NULL_IMPLIES_TRUE_PARAMETERS.get(member); assertWithMessage(member.clazz + "#" + member.member + "()") .that(nullParameters) .isNotEmpty(); if (member.clazz.startsWith("android.")) { // Can't load Android SDK classes. continue; } int found = 0; for (Method method : loadClass(member.clazz).getMethods()) { if (!method.getName().equals(member.member)) { continue; } ++found; for (int nullParam : nullParameters) { // The following assertion would also fail if method returned something other than boolean assertThat(invokeWithSingleNullArgument(method, nullParam)).isEqualTo(Boolean.TRUE); } } assertWithMessage(member.clazz + "#" + member.member + "()").that(found).isGreaterThan(0); } } @Test public void requiredNonNullParameters() throws Exception { for (MemberName member : NullnessPropagationTransfer.REQUIRED_NON_NULL_PARAMETERS.keySet()) { ImmutableSet<Integer> nonNullParameters = NullnessPropagationTransfer.REQUIRED_NON_NULL_PARAMETERS.get(member); assertWithMessage(member.clazz + "#" + member.member + "()") .that(nonNullParameters) .isNotEmpty(); int found = 0; for (Method method : loadClass(member.clazz).getMethods()) { if (!method.getName().equals(member.member)) { continue; } ++found; for (int nonNullParam : nonNullParameters) { try { invokeWithSingleNullArgument(method, nonNullParam); fail( "InvocationTargetException expected calling " + method + " with null parameter " + nonNullParam); } catch (InvocationTargetException expected) { } } } assertWithMessage(member.clazz + "#" + member.member + "()").that(found).isGreaterThan(0); } } @Test public void equalsParameters() throws Exception { int found = 0; for (Method method : loadClass("java.lang.Object").getMethods()) { if (!method.getName().equals("equals")) { continue; } found++; assertThat(invokeWithSingleNullArgument(method, 0)).isEqualTo(Boolean.FALSE); } assertWithMessage("equals()").that(found).isGreaterThan(0); } private static Object invokeWithSingleNullArgument(Method method, int nullParam) throws IllegalAccessException, InvocationTargetException { Class<?>[] params = method.getParameterTypes(); int nonNullIndex = nullParam < 0 ? params.length + nullParam : nullParam; assertWithMessage(method.toString()).that(nonNullIndex).isLessThan(params.length); Object[] args = new Object[params.length]; for (int i = 0; i < params.length; ++i) { if (i != nonNullIndex) { args[i] = ArbitraryInstances.get(params[i]); } } Object receiver = Modifier.isStatic(method.getModifiers()) ? null : ArbitraryInstances.get(method.getDeclaringClass()); method.setAccessible(true); return method.invoke(receiver, args); } private static Class<?> loadClass(String classname) throws Exception { return Thread.currentThread().getContextClassLoader().loadClass(classname); } }
5,885
36.974194
100
java
error-prone
error-prone-master/check_api/src/test/java/com/google/errorprone/names/NamingConventionsTest.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.names; import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.ImmutableList; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for code in NamingConventions */ @RunWith(JUnit4.class) public class NamingConventionsTest { @Test public void splitToLowercaseTerms_separatesTerms_withLowerCamelCase() { String identifierName = "camelCaseTerm"; ImmutableList<String> terms = NamingConventions.splitToLowercaseTerms(identifierName); assertThat(terms).containsExactly("camel", "case", "term"); } @Test public void splitToLowercaseTerms_separatesTerms_withUpperCamelCase() { String identifierName = "CamelCaseTerm"; ImmutableList<String> terms = NamingConventions.splitToLowercaseTerms(identifierName); assertThat(terms).containsExactly("camel", "case", "term"); } @Test public void splitToLowercaseTerms_separatesTrailingDigits_withoutDelimiter() { String identifierName = "term123"; ImmutableList<String> terms = NamingConventions.splitToLowercaseTerms(identifierName); assertThat(terms).containsExactly("term", "123"); } @Test public void splitToLowercaseTerms_doesntSplit_withIntermediateDigits() { String identifierName = "i8n"; ImmutableList<String> terms = NamingConventions.splitToLowercaseTerms(identifierName); assertThat(terms).containsExactly("i8n"); } @Test public void splitToLowercaseTerms_separatesTerms_withUnderscoreSeparator() { String identifierName = "UNDERSCORE_SEPARATED"; ImmutableList<String> terms = NamingConventions.splitToLowercaseTerms(identifierName); assertThat(terms).containsExactly("underscore", "separated"); } @Test public void splitToLowercaseTerms_findsSingleTerm_withOnlyUnderscore() { String identifierName = "_____"; ImmutableList<String> terms = NamingConventions.splitToLowercaseTerms(identifierName); assertThat(terms).containsExactly("_____"); } @Test public void splitToLowercaseTerms_noEmptyTerm_withTrailingUnderscoreDigit() { String identifierName = "test_1"; ImmutableList<String> terms = NamingConventions.splitToLowercaseTerms(identifierName); assertThat(terms).containsExactly("test", "1"); } @Test public void convertToLowerUnderscore_givesSingleUnderscore_fromSingleUnderscore() { String identifierName = "_"; String lowerUnderscore = NamingConventions.convertToLowerUnderscore(identifierName); assertThat(lowerUnderscore).isEqualTo("_"); } @Test public void convertToLowerUnderscore_separatesTerms_fromCamelCase() { String identifierName = "camelCase"; String lowerUnderscore = NamingConventions.convertToLowerUnderscore(identifierName); assertThat(lowerUnderscore).isEqualTo("camel_case"); } }
3,457
30.153153
90
java
error-prone
error-prone-master/check_api/src/test/java/com/google/errorprone/names/TermEditDistanceTest.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.names; import static com.google.common.truth.Truth.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for TermEditDistance */ @RunWith(JUnit4.class) public class TermEditDistanceTest { @Test public void getNormalizedEditDistance_returnsMatch_withPermutedTerms() { TermEditDistance termEditDistance = new TermEditDistance(); String sourceIdentifier = "fooBarBaz"; String targetIdentifier = "bazFooBar"; double distance = termEditDistance.getNormalizedEditDistance(sourceIdentifier, targetIdentifier); assertThat(distance).isEqualTo(0.0); } @Test public void getNormalizedEditDistance_isSymmetric_withExtraTerm() { TermEditDistance termEditDistance = new TermEditDistance(); String identifier = "fooBarBaz"; String otherIdentifier = "barBaz"; double distanceFwd = termEditDistance.getNormalizedEditDistance(identifier, otherIdentifier); double distanceBwd = termEditDistance.getNormalizedEditDistance(otherIdentifier, identifier); assertThat(distanceFwd).isEqualTo(distanceBwd); } @Test public void getNormalizedEditDistance_returnsNoMatch_withDifferentTerms() { TermEditDistance termEditDistance = new TermEditDistance((s, t) -> s.equals(t) ? 0.0 : 1.0, (s, t) -> 1.0); String sourceIdentifier = "fooBar"; String targetIdentifier = "bazQux"; double distance = termEditDistance.getNormalizedEditDistance(sourceIdentifier, targetIdentifier); assertThat(distance).isEqualTo(1.0); } }
2,197
32.30303
97
java
error-prone
error-prone-master/check_api/src/test/java/com/google/errorprone/names/NeedlemanWunschEditDistanceTest.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.names; import static com.google.common.truth.Truth.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for NeedlemanWunschEditDistance */ @RunWith(JUnit4.class) public class NeedlemanWunschEditDistanceTest { @Test public void needlemanWunschEditDistance_returnsZero_withIdenticalNames() { String identifier = "foo"; double distance = NeedlemanWunschEditDistance.getEditDistance( identifier, identifier, /* caseSensitive= */ false, 1, 1, 10); assertThat(distance).isEqualTo(0.0); } @Test public void needlemanWunschEditDistance_matchesLevenschtein_withHugeGapCost() { String identifier = "fooBar"; String otherIdentifier = "bazQux"; double levenschtein = LevenshteinEditDistance.getEditDistance(identifier, otherIdentifier); double needlemanWunsch = NeedlemanWunschEditDistance.getEditDistance( identifier, otherIdentifier, /* caseSensitive= */ false, 1, 1000, 1000); assertThat(needlemanWunsch).isEqualTo(levenschtein); } @Test public void needlemanWunschEditDistanceWorstCase_matchesLevenschtein_withHugeGapCost() { String identifier = "fooBar"; String otherIdentifier = "bazQux"; double levenschtein = LevenshteinEditDistance.getWorstCaseEditDistance( identifier.length(), otherIdentifier.length()); double needlemanWunsch = NeedlemanWunschEditDistance.getWorstCaseEditDistance( identifier.length(), otherIdentifier.length(), 1, 1000, 1000); assertThat(needlemanWunsch).isEqualTo(levenschtein); } }
2,261
32.264706
95
java
error-prone
error-prone-master/check_api/src/test/java/com/google/errorprone/scanner/ErrorProneInjectorTest.java
/* * Copyright 2023 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 static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.errorprone.ErrorProneFlags; import com.google.errorprone.scanner.ErrorProneInjector.ProvisionException; import javax.inject.Inject; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public final class ErrorProneInjectorTest { @Test public void retrievesPredefinedInstance() { var injector = ErrorProneInjector.create().addBinding(Integer.class, 2); assertThat(injector.getInstance(Integer.class)) .isSameInstanceAs(injector.getInstance(Integer.class)); } @Test public void noConstructor_injectable() { var injector = ErrorProneInjector.create(); var unused = injector.getInstance(NoConstructor.class); } @Test public void injectConstructor_injectable() { var injector = ErrorProneInjector.create(); var unused = injector.getInstance(InjectConstructor.class); } @Test public void bothConstructors_injectable() { var injector = ErrorProneInjector.create().addBinding(Integer.class, 2); var obj = injector.getInstance(InjectConstructorAndZeroArgConstructor.class); assertThat(obj.x).isEqualTo(2); } @Test public void errorProneFlags_favouredOverZeroArg() { var injector = ErrorProneInjector.create().addBinding(ErrorProneFlags.class, ErrorProneFlags.empty()); var obj = injector.getInstance(ErrorProneFlagsAndZeroArgsConstructor.class); assertThat(obj.x).isEqualTo(1); } @Test public void pathInError() { var injector = ErrorProneInjector.create(); var e = assertThrows( ProvisionException.class, () -> injector.getInstance(InjectConstructorAndZeroArgConstructor.class)); assertThat(e).hasMessageThat().contains("Integer <- InjectConstructorAndZeroArgConstructor"); } public static final class NoConstructor {} public static final class InjectConstructor { @Inject InjectConstructor() {} } public static final class InjectConstructorAndZeroArgConstructor { final int x; @Inject InjectConstructorAndZeroArgConstructor(Integer x) { this.x = x; } InjectConstructorAndZeroArgConstructor() { this.x = 0; } } public static final class ErrorProneFlagsAndZeroArgsConstructor { final int x; ErrorProneFlagsAndZeroArgsConstructor() { this.x = 0; } ErrorProneFlagsAndZeroArgsConstructor(ErrorProneFlags flags) { this.x = 1; } } }
3,204
26.62931
97
java
error-prone
error-prone-master/check_api/src/test/java/com/google/errorprone/apply/IdeaImportOrganizerTest.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.apply; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.ImmutableList; import java.util.stream.Stream; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** {@link IdeaImportOrganizer}Test */ @RunWith(JUnit4.class) public class IdeaImportOrganizerTest { private static final ImmutableList<ImportOrganizer.Import> IMPORTS = Stream.of( "import com.android.blah", "import android.foo", "import java.ping", "import javax.pong", "import unknown.fred", "import unknown.barney", "import net.wilma", "import static com.android.blah.blah", "import static android.foo.bar", "import static java.ping.pong", "import static javax.pong.ping", "import static unknown.fred.flintstone", "import static net.wilma.flintstone") .map(ImportOrganizer.Import::importOf) .collect(toImmutableList()); @Test public void staticLastOrdering() { IdeaImportOrganizer organizer = new IdeaImportOrganizer(); ImportOrganizer.OrganizedImports organized = organizer.organizeImports(IMPORTS); assertThat(organized.asImportBlock()) .isEqualTo( "import android.foo;\n" + "import com.android.blah;\n" + "import net.wilma;\n" + "import unknown.barney;\n" + "import unknown.fred;\n" + "\n" + "import javax.pong;\n" + "import java.ping;\n" + "\n" + "import static android.foo.bar;\n" + "import static com.android.blah.blah;\n" + "import static java.ping.pong;\n" + "import static javax.pong.ping;\n" + "import static net.wilma.flintstone;\n" + "import static unknown.fred.flintstone;\n"); } }
2,717
36.232877
84
java
error-prone
error-prone-master/check_api/src/test/java/com/google/errorprone/apply/SourceFileTest.java
/* * Copyright 2011 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.apply; import static com.google.common.truth.Truth.assertThat; import java.util.Arrays; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Unit tests for {@link SourceFile}s. * * @author sjnickerson@google.com (Simon Nickerson) */ @RunWith(JUnit4.class) public class SourceFileTest { private static final String DUMMY_PATH = "java/com/google/foo/bar/FooBar.java"; private static final String SOURCE_TEXT = "// Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do\n" + "// eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut\n" + "// enim ad minim veniam, quis nostrud exercitation ullamco\n" + "// laboris nisi ut aliquip ex ea commodo consequat. Duis aute\n" + "// irure dolor in reprehenderit in voluptate velit esse cillum dolore\n" + "// eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat\n" + "// non proident, sunt in culpa qui officia deserunt mollit anim id\n" + "// est laborum.\n"; private SourceFile sourceFile; @Before public void setUp() { sourceFile = new SourceFile(DUMMY_PATH, SOURCE_TEXT); } @Test public void getSourceText() { assertThat(sourceFile.getSourceText()).isEqualTo(SOURCE_TEXT); } @Test public void getPath() { assertThat(sourceFile.getPath()).isEqualTo(DUMMY_PATH); } @Test public void getLines() { List<String> lines = sourceFile.getLines(); assertThat(lines).hasSize(8); assertThat(lines.get(0)) .isEqualTo("// Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do"); assertThat(lines.get(7)).isEqualTo("// est laborum."); } @Test public void replaceChars() { sourceFile.replaceChars(3, 8, "Sasquatch"); assertThat(sourceFile.getSourceText()).isEqualTo(SOURCE_TEXT.replace("Lorem", "Sasquatch")); assertThat(sourceFile.getLines().get(0)) .isEqualTo("// Sasquatch ipsum dolor sit amet, consectetur adipisicing elit, sed do"); } @Test public void replaceLines() { sourceFile.replaceLines(Arrays.asList("Line1", "Line2")); assertThat(sourceFile.getSourceText()).isEqualTo("Line1\nLine2\n"); } @Test public void replaceLines_numbered() { sourceFile.replaceLines(2, 5, Arrays.asList("cat", "dog")); assertThat(sourceFile.getSourceText()) .isEqualTo( "// Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do\n" + "cat\n" + "dog\n" + "// eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat\n" + "// non proident, sunt in culpa qui officia deserunt mollit anim id\n" + "// est laborum.\n"); } @Test public void getFragmentByChars() { assertThat(sourceFile.getFragmentByChars(3, 8)).isEqualTo("Lorem"); } @Test public void getFragmentByLines() { assertThat(sourceFile.getFragmentByLines(2, 2)) .isEqualTo("// eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut\n"); assertThat(sourceFile.getFragmentByLines(8, 8)).isEqualTo("// est laborum.\n"); assertThat(sourceFile.getFragmentByLines(2, 3)) .isEqualTo( "// eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut\n" + "// enim ad minim veniam, quis nostrud exercitation ullamco\n"); assertThat(sourceFile.getFragmentByLines(1, 8)).isEqualTo(SOURCE_TEXT); } }
4,135
34.350427
96
java
error-prone
error-prone-master/check_api/src/test/java/com/google/errorprone/apply/AndroidImportOrganizerTest.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.apply; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.ImmutableList; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link AndroidImportOrganizer} */ @RunWith(JUnit4.class) public class AndroidImportOrganizerTest { private static final ImmutableList<ImportOrganizer.Import> IMPORTS = ImmutableList.of( "import com.android.blah", "import android.foo", "import java.ping", "import javax.pong", "import unknown.fred", "import unknown.barney", "import net.wilma", "import static com.android.blah.blah", "import static android.foo.bar", "import static java.ping.pong", "import static javax.pong.ping", "import static unknown.fred.flintstone", "import static net.wilma.flintstone") .stream() .map(ImportOrganizer.Import::importOf) .collect(toImmutableList()); @Test public void staticFirstOrdering() { AndroidImportOrganizer organizer = new AndroidImportOrganizer(StaticOrder.STATIC_FIRST); ImportOrganizer.OrganizedImports organized = organizer.organizeImports(IMPORTS); assertThat(organized.asImportBlock()) .isEqualTo( "import static android.foo.bar;\n" + "\n" + "import static com.android.blah.blah;\n" + "\n" + "import static net.wilma.flintstone;\n" + "\n" + "import static unknown.fred.flintstone;\n" + "\n" + "import static java.ping.pong;\n" + "\n" + "import static javax.pong.ping;\n" + "\n" + "import android.foo;\n" + "\n" + "import com.android.blah;\n" + "\n" + "import net.wilma;\n" + "\n" + "import unknown.barney;\n" + "import unknown.fred;\n" + "\n" + "import java.ping;\n" + "\n" + "import javax.pong;\n"); } @Test public void staticLastOrdering() { AndroidImportOrganizer organizer = new AndroidImportOrganizer(StaticOrder.STATIC_LAST); ImportOrganizer.OrganizedImports organized = organizer.organizeImports(IMPORTS); assertThat(organized.asImportBlock()) .isEqualTo( "import android.foo;\n" + "\n" + "import com.android.blah;\n" + "\n" + "import net.wilma;\n" + "\n" + "import unknown.barney;\n" + "import unknown.fred;\n" + "\n" + "import java.ping;\n" + "\n" + "import javax.pong;\n" + "\n" + "import static android.foo.bar;\n" + "\n" + "import static com.android.blah.blah;\n" + "\n" + "import static net.wilma.flintstone;\n" + "\n" + "import static unknown.fred.flintstone;\n" + "\n" + "import static java.ping.pong;\n" + "\n" + "import static javax.pong.ping;\n"); } }
4,138
35.628319
92
java
error-prone
error-prone-master/check_api/src/test/java/com/google/errorprone/apply/BasicImportOrganizerTest.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.apply; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.ImmutableList; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link BasicImportOrganizer} */ @RunWith(JUnit4.class) public class BasicImportOrganizerTest { private static final ImmutableList<ImportOrganizer.Import> IMPORTS = ImmutableList.of( "import com.android.blah", "import android.foo", "import java.ping", "import javax.pong", "import unknown.fred", "import unknown.barney", "import net.wilma", "import static com.android.blah.blah", "import static android.foo.bar", "import static java.ping.pong", "import static javax.pong.ping", "import static unknown.fred.flintstone", "import static net.wilma.flintstone") .stream() .map(ImportOrganizer.Import::importOf) .collect(toImmutableList()); @Test public void staticFirstOrdering() { BasicImportOrganizer organizer = new BasicImportOrganizer(StaticOrder.STATIC_FIRST); ImportOrganizer.OrganizedImports organized = organizer.organizeImports(IMPORTS); assertThat(organized.asImportBlock()) .isEqualTo( "import static android.foo.bar;\n" + "import static com.android.blah.blah;\n" + "import static java.ping.pong;\n" + "import static javax.pong.ping;\n" + "import static net.wilma.flintstone;\n" + "import static unknown.fred.flintstone;\n" + "\n" + "import android.foo;\n" + "import com.android.blah;\n" + "import java.ping;\n" + "import javax.pong;\n" + "import net.wilma;\n" + "import unknown.barney;\n" + "import unknown.fred;\n"); } @Test public void staticLastOrdering() { BasicImportOrganizer organizer = new BasicImportOrganizer(StaticOrder.STATIC_LAST); ImportOrganizer.OrganizedImports organized = organizer.organizeImports(IMPORTS); assertThat(organized.asImportBlock()) .isEqualTo( "import android.foo;\n" + "import com.android.blah;\n" + "import java.ping;\n" + "import javax.pong;\n" + "import net.wilma;\n" + "import unknown.barney;\n" + "import unknown.fred;\n" + "\n" + "import static android.foo.bar;\n" + "import static com.android.blah.blah;\n" + "import static java.ping.pong;\n" + "import static javax.pong.ping;\n" + "import static net.wilma.flintstone;\n" + "import static unknown.fred.flintstone;\n"); } }
3,666
38.430108
88
java
error-prone
error-prone-master/check_api/src/test/java/com/google/errorprone/apply/OrganizedImportsTest.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.apply; import static com.google.common.primitives.Booleans.falseFirst; import static com.google.common.truth.Truth.assertThat; import static java.util.Comparator.comparing; import com.google.common.collect.ImmutableSortedSet; import com.google.errorprone.apply.ImportOrganizer.Import; import java.util.Comparator; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** */ @RunWith(JUnit4.class) public class OrganizedImportsTest { private static final Comparator<Import> IMPORT_COMPARATOR = comparing(Import::isStatic, falseFirst()).thenComparing(Import::getType); @Test public void emptyList() { ImportOrganizer.OrganizedImports organizedImports = new ImportOrganizer.OrganizedImports(); assertThat(organizedImports.asImportBlock()).isEmpty(); } private ImmutableSortedSet<Import> buildSortedImportSet(Import... element) { return ImmutableSortedSet.orderedBy(IMPORT_COMPARATOR).add(element).build(); } @Test public void singleGroup() { Map<String, Set<Import>> groups = new TreeMap<>(); groups.put("first", buildSortedImportSet(Import.importOf("import first"))); ImportOrganizer.OrganizedImports organizedImports = new ImportOrganizer.OrganizedImports().addGroups(groups, groups.keySet()); assertThat(organizedImports.asImportBlock()).isEqualTo("import first;\n"); } @Test public void multipleGroups() { Map<String, Set<Import>> groups = new TreeMap<>(); groups.put("first", buildSortedImportSet(Import.importOf("import first"))); groups.put("second", buildSortedImportSet(Import.importOf("import second"))); ImportOrganizer.OrganizedImports organizedImports = new ImportOrganizer.OrganizedImports().addGroups(groups, groups.keySet()); assertThat(organizedImports.asImportBlock()).isEqualTo("import first;\n\nimport second;\n"); } @Test public void importCount() { Map<String, Set<Import>> groups = new TreeMap<>(); groups.put("first", buildSortedImportSet(Import.importOf("import first"))); groups.put("second", buildSortedImportSet(Import.importOf("import second"))); ImportOrganizer.OrganizedImports organizedImports = new ImportOrganizer.OrganizedImports().addGroups(groups, groups.keySet()); assertThat(organizedImports.getImportCount()).isEqualTo(2); } }
3,045
38.051282
96
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/JavacErrorDescriptionListener.java
/* * Copyright 2011 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 static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableList.toImmutableList; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import com.google.errorprone.fixes.AppliedFix; import com.google.errorprone.fixes.Fix; import com.google.errorprone.matchers.Description; import com.sun.source.tree.Tree.Kind; import com.sun.tools.javac.tree.EndPosTable; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.JCDiagnostic; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import com.sun.tools.javac.util.Log; import java.io.IOException; import java.io.UncheckedIOException; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Function; import javax.tools.JavaFileObject; /** * Making our errors appear to the user and break their build. * * @author alexeagle@google.com (Alex Eagle) */ public class JavacErrorDescriptionListener implements DescriptionListener { private final Log log; private final JavaFileObject sourceFile; private final Function<Fix, AppliedFix> fixToAppliedFix; private final Context context; // When we're trying to refactor using error prone fixes, any error halts compilation of other // files. We set this to true when refactoring so we can log every hit without breaking the // compile. private final boolean dontUseErrors; // The suffix for properties in src/main/resources/com/google/errorprone/errors.properties private static final String MESSAGE_BUNDLE_KEY = "error.prone"; // DiagnosticFlag.MULTIPLE went away in JDK13, so we want to load it if it's available. private static final Supplier<EnumSet<JCDiagnostic.DiagnosticFlag>> diagnosticFlags = Suppliers.memoize( () -> { try { return EnumSet.of(JCDiagnostic.DiagnosticFlag.valueOf("MULTIPLE")); } catch (IllegalArgumentException iae) { // JDK 13 and above return EnumSet.noneOf(JCDiagnostic.DiagnosticFlag.class); } }); private JavacErrorDescriptionListener( Log log, EndPosTable endPositions, JavaFileObject sourceFile, Context context, boolean dontUseErrors) { this.log = log; this.sourceFile = sourceFile; this.context = context; this.dontUseErrors = dontUseErrors; checkNotNull(endPositions); // Optimization for checks that emit the same fix multiple times. Consider a check that renames // all uses of a symbol, and reports the diagnostic on all occurrences of the symbol. This can // be useful in environments where diagnostics are only shown on changed lines, but can lead to // quadratic behaviour during fix application if we're not careful. Map<Fix, AppliedFix> cache = new HashMap<>(); try { CharSequence sourceFileContent = sourceFile.getCharContent(true); AppliedFix.Applier applier = AppliedFix.fromSource(sourceFileContent, endPositions); fixToAppliedFix = fix -> cache.computeIfAbsent(fix, applier::apply); } catch (IOException e) { throw new UncheckedIOException(e); } } @Override public void onDescribed(Description description) { ImmutableList<AppliedFix> appliedFixes = description.fixes.stream() .filter(f -> !shouldSkipImportTreeFix(description.position, f)) .map(fixToAppliedFix) .filter(Objects::nonNull) .collect(toImmutableList()); String message = messageForFixes(description, appliedFixes); // Swap the log's source and the current file's source; then be sure to swap them back later. JavaFileObject originalSource = log.useSource(sourceFile); try { JCDiagnostic.Factory factory = JCDiagnostic.Factory.instance(context); JCDiagnostic.DiagnosticType type = JCDiagnostic.DiagnosticType.ERROR; DiagnosticPosition pos = description.position; switch (description.severity()) { case ERROR: if (dontUseErrors) { type = JCDiagnostic.DiagnosticType.WARNING; } else { type = JCDiagnostic.DiagnosticType.ERROR; } break; case WARNING: type = JCDiagnostic.DiagnosticType.WARNING; break; case SUGGESTION: type = JCDiagnostic.DiagnosticType.NOTE; break; } log.report( factory.create( type, /* lintCategory */ null, diagnosticFlags.get(), log.currentSource(), pos, MESSAGE_BUNDLE_KEY, message)); } finally { if (originalSource != null) { log.useSource(originalSource); } } } // b/79407644: Because AppliedFix doesn't consider imports, just don't display a // suggested fix to an ImportTree when the fix reports imports to remove/add. Imports can still // be fixed if they were specified via SuggestedFix.replace, for example. private static boolean shouldSkipImportTreeFix(DiagnosticPosition position, Fix f) { if (position.getTree() != null && position.getTree().getKind() != Kind.IMPORT) { return false; } return !f.getImportsToAdd().isEmpty() || !f.getImportsToRemove().isEmpty(); } private static String messageForFixes(Description description, List<AppliedFix> appliedFixes) { StringBuilder messageBuilder = new StringBuilder(description.getMessage()); boolean first = true; for (AppliedFix appliedFix : appliedFixes) { if (first) { messageBuilder.append("\nDid you mean "); } else { messageBuilder.append(" or "); } if (appliedFix.isRemoveLine()) { messageBuilder.append("to remove this line"); } else { messageBuilder.append("'").append(appliedFix.getNewCodeSnippet()).append("'"); } first = false; } if (!first) { // appended at least one suggested fix to the message messageBuilder.append("?"); } return messageBuilder.toString(); } static Factory provider(Context context) { return (log, compilation) -> new JavacErrorDescriptionListener( log, compilation.endPositions, compilation.getSourceFile(), context, false); } static Factory providerForRefactoring(Context context) { return (log, compilation) -> new JavacErrorDescriptionListener( log, compilation.endPositions, compilation.getSourceFile(), context, true); } }
7,264
36.838542
99
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/RefactoringCollection.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; import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.file.StandardOpenOption.APPEND; import static java.nio.file.StandardOpenOption.CREATE; import com.google.auto.value.AutoValue; import com.google.common.collect.HashMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.SetMultimap; import com.google.errorprone.ErrorProneOptions.PatchingOptions; import com.google.errorprone.apply.DescriptionBasedDiff; import com.google.errorprone.apply.FileDestination; import com.google.errorprone.apply.FileSource; import com.google.errorprone.apply.FsFileDestination; import com.google.errorprone.apply.FsFileSource; import com.google.errorprone.apply.ImportOrganizer; import com.google.errorprone.apply.PatchFileDestination; import com.google.errorprone.apply.SourceFile; import com.google.errorprone.matchers.Description; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.Log; import java.io.IOException; import java.io.UncheckedIOException; import java.net.URI; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collection; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.logging.Level; import java.util.logging.Logger; /** A container of fixes that have been collected during a single compilation phase. */ class RefactoringCollection implements DescriptionListener.Factory { private static final Logger logger = Logger.getLogger(RefactoringCollection.class.getName()); private final SetMultimap<URI, DelegatingDescriptionListener> foundSources = HashMultimap.create(); private final Path rootPath; private final FileDestination fileDestination; private final Function<URI, RefactoringResult> postProcess; private final DescriptionListener.Factory descriptionsFactory; private final ImportOrganizer importOrganizer; @AutoValue abstract static class RefactoringResult { abstract String message(); abstract RefactoringResultType type(); private static RefactoringResult create(String message, RefactoringResultType type) { return new AutoValue_RefactoringCollection_RefactoringResult(message, type); } } enum RefactoringResultType { NO_CHANGES, CHANGED, } static RefactoringCollection refactor(PatchingOptions patchingOptions, Context context) { Path rootPath = buildRootPath(); FileDestination fileDestination; Function<URI, RefactoringResult> postProcess; if (patchingOptions.inPlace()) { fileDestination = new FsFileDestination(rootPath); postProcess = uri -> RefactoringResult.create( String.format( "Refactoring changes were successfully applied to %s," + " please check the refactored code and recompile.", uri), RefactoringResultType.CHANGED); } else { Path baseDir = rootPath.resolve(patchingOptions.baseDirectory()); Path patchFilePath = baseDir.resolve("error-prone.patch"); PatchFileDestination patchFileDestination = new PatchFileDestination(baseDir, rootPath); postProcess = new Function<URI, RefactoringResult>() { private final AtomicBoolean first = new AtomicBoolean(true); @Override public RefactoringResult apply(URI uri) { try { writePatchFile(first, uri, patchFileDestination, patchFilePath); return RefactoringResult.create( "Changes were written to " + patchFilePath + ". Please inspect the file and apply with: " + "patch -p0 -u -i error-prone.patch", RefactoringResultType.CHANGED); } catch (IOException e) { throw new RuntimeException("Failed to emit patch file!", e); } } }; fileDestination = patchFileDestination; } ImportOrganizer importOrganizer = patchingOptions.importOrganizer(); return new RefactoringCollection( rootPath, fileDestination, postProcess, importOrganizer, context); } private RefactoringCollection( Path rootPath, FileDestination fileDestination, Function<URI, RefactoringResult> postProcess, ImportOrganizer importOrganizer, Context context) { this.rootPath = rootPath; this.fileDestination = fileDestination; this.postProcess = postProcess; this.descriptionsFactory = JavacErrorDescriptionListener.providerForRefactoring(context); this.importOrganizer = importOrganizer; } private static Path buildRootPath() { Path root = Iterables.getFirst(FileSystems.getDefault().getRootDirectories(), null); if (root == null) { throw new RuntimeException("Can't find a root filesystem!"); } return root; } @Override public DescriptionListener getDescriptionListener(Log log, JCCompilationUnit compilation) { URI sourceFile = compilation.getSourceFile().toUri(); DelegatingDescriptionListener delegate = new DelegatingDescriptionListener( descriptionsFactory.getDescriptionListener(log, compilation), DescriptionBasedDiff.createIgnoringOverlaps(compilation, importOrganizer)); foundSources.put(sourceFile, delegate); return delegate; } RefactoringResult applyChanges(URI uri) throws Exception { Collection<DelegatingDescriptionListener> listeners = foundSources.removeAll(uri); if (doApplyProcess(fileDestination, new FsFileSource(rootPath), listeners)) { return postProcess.apply(uri); } return RefactoringResult.create("", RefactoringResultType.NO_CHANGES); } private static void writePatchFile( AtomicBoolean first, URI uri, PatchFileDestination fileDestination, Path patchFilePatch) throws IOException { String patchFile = fileDestination.patchFile(uri); if (patchFile != null) { if (first.compareAndSet(true, false)) { try { Files.deleteIfExists(patchFilePatch); } catch (IOException e) { throw new UncheckedIOException(e); } } Files.createDirectories(patchFilePatch.getParent()); Files.write(patchFilePatch, patchFile.getBytes(UTF_8), APPEND, CREATE); } } private static boolean doApplyProcess( FileDestination fileDestination, FileSource fileSource, Collection<DelegatingDescriptionListener> listeners) { boolean appliedDiff = false; for (DelegatingDescriptionListener listener : listeners) { if (listener.base.isEmpty()) { continue; } try { SourceFile file = fileSource.readFile(listener.base.getRelevantFileName()); listener.base.applyDifferences(file); fileDestination.writeFile(file); appliedDiff = true; } catch (IOException e) { logger.log( Level.WARNING, "Failed to apply diff to file " + listener.base.getRelevantFileName(), e); } } return appliedDiff; } private static final class DelegatingDescriptionListener implements DescriptionListener { final DescriptionBasedDiff base; final DescriptionListener listener; DelegatingDescriptionListener(DescriptionListener listener, DescriptionBasedDiff base) { this.listener = listener; this.base = base; } @Override public void onDescribed(Description description) { listener.onDescribed(description); base.onDescribed(description); } } }
8,352
35.475983
95
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/MaskedClassLoader.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; import static java.nio.charset.StandardCharsets.UTF_8; import com.sun.tools.javac.api.ClientCodeWrapper.Trusted; import com.sun.tools.javac.file.JavacFileManager; import com.sun.tools.javac.util.Context; import java.net.URL; import java.net.URLClassLoader; import javax.tools.JavaFileManager; /** * A classloader that allows plugins to access the Error Prone classes from the compiler classpath. */ // TODO(cushon): consolidate with Bazel's ClassloaderMaskingFileManager public class MaskedClassLoader extends ClassLoader { /** * An alternative to {@link JavacFileManager#preRegister(Context)} that installs a {@link * MaskedClassLoader}. */ public static void preRegisterFileManager(Context context) { context.put( JavaFileManager.class, new Context.Factory<JavaFileManager>() { @Override public JavaFileManager make(Context c) { return new MaskedFileManager(c); } }); } public MaskedClassLoader(ClassLoader parent) { super(parent); } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { if (name.startsWith("com.google.errorprone.") || name.startsWith("org.checkerframework.errorprone.dataflow.")) { return Class.forName(name); } else { throw new ClassNotFoundException(name); } } @Trusted static class MaskedFileManager extends JavacFileManager { public MaskedFileManager(Context context) { super(context, /* register= */ true, UTF_8); } public MaskedFileManager() { this(new Context()); } @Override protected ClassLoader getClassLoader(URL[] urls) { return new URLClassLoader( urls, new MaskedClassLoader(JavacFileManager.class.getClassLoader())); } } }
2,434
29.061728
99
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/InvalidCommandLineOptionException.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; public class InvalidCommandLineOptionException extends RuntimeException { public InvalidCommandLineOptionException(String message) { super(message); } }
803
31.16
75
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/ErrorProneFlags.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 static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static java.util.Arrays.stream; import com.google.common.base.Ascii; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Streams; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.CheckReturnValue; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; /** * Represents an immutable map of Error Prone flags to their set values. * * <p>All get* methods return an {@code Optional<*>} containing the value for the given key, or * empty if the flag is unset. * * <p>To access ErrorProneFlags from a BugChecker class, add a constructor to the class that takes * one parameter of type ErrorProneFlags. * * <p>See <a href="https://errorprone.info/docs/flags">documentation</a> for full syntax * description. */ public final class ErrorProneFlags implements Serializable { public static final String PREFIX = "-XepOpt:"; private final ImmutableMap<String, String> flagsMap; public static ErrorProneFlags empty() { return new ErrorProneFlags(ImmutableMap.of()); } public static ErrorProneFlags fromMap(Map<String, String> flagsMap) { return new ErrorProneFlags(ImmutableMap.copyOf(flagsMap)); } private ErrorProneFlags(ImmutableMap<String, String> flagsMap) { this.flagsMap = flagsMap; } public ImmutableMap<String, String> getFlagsMap() { return ImmutableMap.copyOf(flagsMap); } /** * Gets flag value for the given key as a String, wrapped in an {@link Optional}, which is empty * if the flag is unset. */ public Optional<String> get(String key) { return Optional.ofNullable(flagsMap.get(key)); } /** * Gets the flag value for the given key as a Boolean, wrapped in an {@link Optional}, which is * empty if the flag is unset. * * <p>The value within the {@link Optional} will be {@code true} if the flag's value is "true", * {@code false} for "false", both case insensitive. If the value is neither "true" nor "false", * throws an {@link IllegalArgumentException}. * * <p>Note that any flag set without a value, e.g. {@code -XepOpt:FlagValue}, will be "true". */ public Optional<Boolean> getBoolean(String key) { return this.get(key).map(ErrorProneFlags::parseBoolean); } /** * Gets the flag value for an enum of the given type, wrapped in an {@link Optional}, which is * empty if the flag is unset. */ public <T extends Enum<T>> Optional<T> getEnum(String key, Class<T> clazz) { return this.get(key).map(value -> asEnumValue(key, value, clazz)); } /** * Gets the flag value for a comma-separated set of enums of the given type, wrapped in an {@link * Optional}, which is empty if the flag is unset. If the flag is explicitly set to empty, an * empty set will be returned. */ public <T extends Enum<T>> Optional<ImmutableSet<T>> getEnumSet(String key, Class<T> clazz) { return this.get(key) .map( value -> Streams.stream(Splitter.on(',').omitEmptyStrings().split(value)) .map(v -> asEnumValue(key, v, clazz)) .collect(toImmutableSet())); } private static <T extends Enum<T>> T asEnumValue(String key, String value, Class<T> clazz) { return stream(clazz.getEnumConstants()) .filter(c -> Ascii.equalsIgnoreCase(c.name(), value)) .findFirst() .orElseThrow( () -> new IllegalArgumentException( String.format( "Error Prone flag %s=%s could not be parsed as an enum constant of %s", key, value, clazz))); } private static boolean parseBoolean(String value) { if ("true".equalsIgnoreCase(value)) { return true; } if ("false".equalsIgnoreCase(value)) { return false; } throw new IllegalArgumentException( String.format("Error Prone flag value %s could not be parsed as a boolean.", value)); } /** * Gets the flag value for the given key as an Integer, wrapped in an {@link Optional}, which is * empty if the flag is unset. * * <p>If the flag's value cannot be interpreted as an Integer, throws a {@link * NumberFormatException} (note: float values will *not* be interpreted as integers and will throw * an exception!) */ public Optional<Integer> getInteger(String key) { return this.get(key).map(Integer::valueOf); } /** * Gets the flag value for the given key as a comma-separated {@link List} of Strings, wrapped in * an {@link Optional}, which is empty if the flag is unset. * * <p>(note: empty strings included, e.g. {@code "-XepOpt:List=,1,,2," => ["","1","","2",""]}) */ public Optional<List<String>> getList(String key) { return this.get(key).map(v -> ImmutableList.copyOf(Splitter.on(',').split(v))); } /** * Gets the flag value for the given key as a comma-separated {@link Set} of Strings, wrapped in * an {@link Optional}, which is empty if the flag is unset. * * <p>(note: empty strings included, e.g. {@code "-XepOpt:Set=,1,,1,2," => ["","1","2"]}) */ public Optional<Set<String>> getSet(String key) { return this.get(key).map(v -> ImmutableSet.copyOf(Splitter.on(',').split(v))); } /** Whether this Flags object is empty, i.e. no flags have been set. */ public boolean isEmpty() { return this.flagsMap.isEmpty(); } /** * Returns a new ErrorProneFlags object with the values of two ErrorProneFlags objects added * together. For flags that appear in both instances, the values in {@code other} override {@code * this}. */ @CheckReturnValue public ErrorProneFlags plus(ErrorProneFlags other) { Map<String, String> combinedMaps = new HashMap<>(this.getFlagsMap()); combinedMaps.putAll(other.getFlagsMap()); return ErrorProneFlags.fromMap(combinedMaps); } /** Builder for Error Prone command-line flags object. Parses flags from strings. */ public static class Builder { private final HashMap<String, String> flagsMap = new HashMap<>(); private Builder() {} /** * Given a String custom flag in the format {@code "-XepOpt:FlagName=Value"}, places the flag in * this builder's dictionary, e.g. {@code flagsMap["FlagName"] = "Value"} */ @CanIgnoreReturnValue public Builder parseFlag(String flag) { checkArgument(flag.startsWith(PREFIX)); // Strip prefix String remaining = flag.substring(PREFIX.length()); // Get key and value by splitting on first equals sign. String[] parts = remaining.split("=", 2); String key = parts[0]; String value = parts.length < 2 ? "true" : parts[1]; this.putFlag(key, value); return this; } /** Puts a key-value pair directly in this builder's dictionary. Mostly exists for testing. */ @CanIgnoreReturnValue public Builder putFlag(String key, String value) { flagsMap.put(key, value); return this; } public ErrorProneFlags build() { return fromMap(flagsMap); } } public static Builder builder() { return new Builder(); } }
8,131
34.356522
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/ErrorProneTimings.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; import static com.google.common.collect.ImmutableMap.toImmutableMap; import com.google.common.base.Stopwatch; import com.google.common.collect.ImmutableMap; import com.google.errorprone.matchers.Suppressible; import com.sun.tools.javac.util.Context; import java.time.Duration; import java.util.HashMap; import java.util.Map; /** A collection of timing data for the runtime of individual checks. */ public final class ErrorProneTimings { private static final Context.Key<ErrorProneTimings> timingsKey = new Context.Key<>(); public static ErrorProneTimings instance(Context context) { ErrorProneTimings instance = context.get(timingsKey); if (instance == null) { instance = new ErrorProneTimings(context); } return instance; } private ErrorProneTimings(Context context) { context.put(timingsKey, this); } private final Map<String, Stopwatch> timers = new HashMap<>(); private final Stopwatch initializationTime = Stopwatch.createUnstarted(); /** Creates a timing span for the given {@link Suppressible}. */ public AutoCloseable span(Suppressible suppressible) { String key = suppressible.canonicalName(); Stopwatch sw = timers.computeIfAbsent(key, k -> Stopwatch.createUnstarted()).start(); return () -> sw.stop(); } /** Creates a timing span for initialization. */ public AutoCloseable initializationTimeSpan() { initializationTime.start(); return () -> initializationTime.stop(); } /** Returns the elapsed durations of each timer. */ public ImmutableMap<String, Duration> timings() { return timers.entrySet().stream() .collect(toImmutableMap(e -> e.getKey(), e -> e.getValue().elapsed())); } /** Returns the elapsed initialization time. */ public Duration initializationTime() { return initializationTime.elapsed(); } }
2,472
32.418919
89
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/SubContext.java
/* * Copyright 2013 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 static com.google.common.base.Preconditions.checkNotNull; import com.sun.tools.javac.util.Context; /** * A view on top of a {@code Context} allowing additional modifications to be added without * affecting the underlying {@code Context}. * * @author Louis Wasserman */ public final class SubContext extends Context { private final Context base; public SubContext(Context base) { this.base = checkNotNull(base); } @Override public <T> T get(Key<T> key) { T result = super.get(key); return (result == null) ? base.get(key) : result; } @Override public <T> T get(Class<T> clazz) { T result = super.get(clazz); return (result == null) ? base.get(clazz) : result; } }
1,357
27.291667
91
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/SuppressionInfo.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; import com.google.common.collect.ImmutableSet; import com.google.errorprone.annotations.CheckReturnValue; import com.google.errorprone.annotations.Immutable; import com.google.errorprone.matchers.Suppressible; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.util.SimpleTreeVisitor; import com.sun.tools.javac.code.Attribute; 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.util.Name; import com.sun.tools.javac.util.Pair; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; /** * Immutable container of "suppression signals" - annotations or other information gathered from * source - that can be used to determine if a specific {@link Suppressible} object should be * considered suppressed. * * <p>SuppressionInfo instances are obtained by starting with the {@link #EMPTY} instance, then * getting new instances by calling {@link #withExtendedSuppressions} with symbols discovered as you * descend a program tree. */ @Immutable @CheckReturnValue public class SuppressionInfo { public static final SuppressionInfo EMPTY = new SuppressionInfo(ImmutableSet.of(), ImmutableSet.of(), false); private static final Supplier<Name> ANDROID_SUPPRESS_LINT = VisitorState.memoize(state -> state.getName("android.annotation.SuppressLint")); private static final Supplier<Name> VALUE = VisitorState.memoize(state -> state.getName("value")); private final ImmutableSet<String> suppressWarningsStrings; @SuppressWarnings("Immutable") /* Name is javac's interned version of a string. */ private final ImmutableSet<Name> customSuppressions; private final boolean inGeneratedCode; private SuppressionInfo( Set<String> suppressWarningsStrings, Set<Name> customSuppressions, boolean inGeneratedCode) { this.suppressWarningsStrings = ImmutableSet.copyOf(suppressWarningsStrings); this.customSuppressions = ImmutableSet.copyOf(customSuppressions); this.inGeneratedCode = inGeneratedCode; } private static boolean isGenerated(Symbol sym, VisitorState state) { return !ASTHelpers.getGeneratedBy(sym, state).isEmpty(); } /** * Returns true if this checker should be considered suppressed given the signals present in this * object. * * @param suppressible Holds information about the suppressibilty of a checker * @param suppressedInGeneratedCode true if this checker instance should be considered suppressed */ public SuppressedState suppressedState( Suppressible suppressible, boolean suppressedInGeneratedCode, VisitorState state) { if (inGeneratedCode && suppressedInGeneratedCode) { return SuppressedState.SUPPRESSED; } if (suppressible.supportsSuppressWarnings() && !Collections.disjoint(suppressible.allNames(), suppressWarningsStrings)) { return SuppressedState.SUPPRESSED; } if (suppressible.suppressedByAnyOf(customSuppressions, state)) { return SuppressedState.SUPPRESSED; } return SuppressedState.UNSUPPRESSED; } /** * Generates the {@link SuppressionInfo} for a {@link CompilationUnitTree}. This differs in that * {@code isGenerated} is determined by inspecting the annotations of the outermost class so that * matchers on {@link CompilationUnitTree} will also be suppressed. */ public SuppressionInfo forCompilationUnit(CompilationUnitTree tree, VisitorState state) { AtomicBoolean generated = new AtomicBoolean(false); new SimpleTreeVisitor<Void, Void>() { @Override public Void visitClass(ClassTree node, Void unused) { ClassSymbol symbol = ASTHelpers.getSymbol(node); generated.compareAndSet(false, symbol != null && isGenerated(symbol, state)); return null; } }.visit(tree.getTypeDecls(), null); return new SuppressionInfo(suppressWarningsStrings, customSuppressions, generated.get()); } /** * Returns an instance of {@code SuppressionInfo} that takes into account any suppression signals * present on {@code sym} as well as those already stored in {@code this}. * * <p>Checks suppressions for any {@code @SuppressWarnings}, Android's {@code SuppressLint}, and * custom suppression annotations described by {@code customSuppressionAnnosToLookFor}. * * <p>We do not modify the existing suppression sets, so they can be restored when moving up the * tree. We also avoid copying the suppression sets if the next node to explore does not have any * suppressed warnings or custom suppression annotations. This is the common case. * * @param sym The {@code Symbol} for the AST node currently being scanned * @param state VisitorState for checking the current tree, as well as for getting the {@code * SuppressWarnings symbol type}. */ public SuppressionInfo withExtendedSuppressions( Symbol sym, VisitorState state, Set<? extends Name> customSuppressionAnnosToLookFor) { boolean newInGeneratedCode = inGeneratedCode || isGenerated(sym, state); boolean anyModification = newInGeneratedCode != inGeneratedCode; /* Handle custom suppression annotations. */ Set<Name> lookingFor = new HashSet<>(customSuppressionAnnosToLookFor); lookingFor.removeAll(customSuppressions); Set<Name> newlyPresent = ASTHelpers.annotationsAmong(sym, lookingFor, state); Set<Name> newCustomSuppressions; if (!newlyPresent.isEmpty()) { anyModification = true; newCustomSuppressions = newlyPresent; newCustomSuppressions.addAll(customSuppressions); } else { newCustomSuppressions = customSuppressions; } /* Handle {@code @SuppressWarnings} and {@code @SuppressLint}. */ Name suppressLint = ANDROID_SUPPRESS_LINT.get(state); Name valueName = VALUE.get(state); Set<String> newSuppressions = null; // Iterate over annotations on this symbol, looking for SuppressWarnings for (Attribute.Compound attr : sym.getAnnotationMirrors()) { if ((attr.type.tsym == state.getSymtab().suppressWarningsType.tsym) || attr.type.tsym.getQualifiedName().equals(suppressLint)) { for (Pair<MethodSymbol, Attribute> value : attr.values) { if (value.fst.name.equals(valueName)) { if (value.snd instanceof Attribute.Array) { // SuppressWarnings/SuppressLint take an array for (Attribute suppress : ((Attribute.Array) value.snd).values) { String suppressedWarning = (String) suppress.getValue(); if (!suppressWarningsStrings.contains(suppressedWarning)) { anyModification = true; if (newSuppressions == null) { newSuppressions = new HashSet<>(suppressWarningsStrings); } newSuppressions.add(suppressedWarning); } } } else { throw new RuntimeException( "Expected SuppressWarnings/SuppressLint annotation to take array type"); } } } } } // Since this is invoked every time we descend into a new node, let's save some garbage // by returning the same instance if there were no changes. if (!anyModification) { return this; } if (newSuppressions == null) { newSuppressions = suppressWarningsStrings; } return new SuppressionInfo(newSuppressions, newCustomSuppressions, newInGeneratedCode); } public enum SuppressedState { UNSUPPRESSED, SUPPRESSED } }
8,427
41.781726
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/JavacInvocationInstance.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; import com.sun.tools.javac.util.Context; /** * A token uniquely identifying a single invocation of javac. Any caches which might otherwise * persist indefinitely should be reset if they detect that the JavacInvocationInstance inside their * {@link Context} has changed. The only meaningful way to compare JavacInvocationInstance objects * is by their object identity, as they have no properties. */ public final class JavacInvocationInstance { public static JavacInvocationInstance instance(Context context) { JavacInvocationInstance instance = context.get(JavacInvocationInstance.class); if (instance == null) { instance = new JavacInvocationInstance(); context.put(JavacInvocationInstance.class, instance); } return instance; } private JavacInvocationInstance() {} }
1,450
37.184211
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/StatisticsCollector.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; import com.google.common.collect.HashMultiset; import com.google.common.collect.ImmutableMultiset; import com.google.common.collect.Multiset; /** A collector of counters keyed by strings. */ public interface StatisticsCollector { /** Adds 1 to the counter for {@code key}. */ default void incrementCounter(String key) { incrementCounter(key, 1); } /** Adds {@code count} to the counter for {@code key}. */ void incrementCounter(String key, int count); /** Returns a copy of the counters in this statistics collector. */ ImmutableMultiset<String> counters(); /** Returns a new statistics collector that will successfully count keys added to it. */ static StatisticsCollector createCollector() { return new StatisticsCollector() { private final Multiset<String> strings = HashMultiset.create(); @Override public void incrementCounter(String key, int count) { strings.add(key, count); } @Override public ImmutableMultiset<String> counters() { return ImmutableMultiset.copyOf(strings); } }; } /** * Returns a statistics collector that will ignore any statistics added to it, always returning an * empty result for {@link #counters}. */ static StatisticsCollector createNoOpCollector() { return new StatisticsCollector() { @Override public void incrementCounter(String key, int count) {} @Override public ImmutableMultiset<String> counters() { return ImmutableMultiset.of(); } }; } }
2,180
30.157143
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/BaseErrorProneJavaCompiler.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 static com.google.common.base.StandardSystemProperty.JAVA_SPECIFICATION_VERSION; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.errorprone.RefactoringCollection.RefactoringResult; import com.google.errorprone.scanner.ErrorProneScannerTransformer; import com.google.errorprone.scanner.ScannerSupplier; import com.sun.source.util.JavacTask; import com.sun.source.util.TaskEvent; import com.sun.source.util.TaskEvent.Kind; import com.sun.source.util.TaskListener; import com.sun.tools.javac.api.BasicJavacTask; import com.sun.tools.javac.api.JavacTool; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.JavacMessages; import com.sun.tools.javac.util.Log; import com.sun.tools.javac.util.Log.WriterKind; import com.sun.tools.javac.util.Options; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.nio.charset.Charset; import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import java.util.Set; import javax.annotation.Nullable; import javax.lang.model.SourceVersion; import javax.tools.DiagnosticListener; import javax.tools.JavaCompiler; import javax.tools.JavaCompiler.CompilationTask; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; /** An Error Prone compiler that implements {@link javax.tools.JavaCompiler}. */ public class BaseErrorProneJavaCompiler implements JavaCompiler { private final JavaCompiler javacTool; private final ScannerSupplier scannerSupplier; public BaseErrorProneJavaCompiler(ScannerSupplier scannerSupplier) { this(JavacTool.create(), scannerSupplier); } BaseErrorProneJavaCompiler(JavaCompiler javacTool, ScannerSupplier scannerSupplier) { this.javacTool = javacTool; this.scannerSupplier = scannerSupplier; } @Override public CompilationTask getTask( Writer out, JavaFileManager fileManager, DiagnosticListener<? super JavaFileObject> diagnosticListener, Iterable<String> options, Iterable<String> classes, Iterable<? extends JavaFileObject> compilationUnits) { ErrorProneOptions errorProneOptions = ErrorProneOptions.processArgs(options); List<String> remainingOptions = Arrays.asList(errorProneOptions.getRemainingArgs()); ImmutableList<String> javacOpts = ImmutableList.copyOf(remainingOptions); javacOpts = defaultToLatestSupportedLanguageLevel(javacOpts); javacOpts = setCompilePolicyToByFile(javacOpts); JavacTask task = (JavacTask) javacTool.getTask( out, fileManager, diagnosticListener, javacOpts, classes, compilationUnits); addTaskListener(task, scannerSupplier, errorProneOptions); return task; } static void addTaskListener( JavacTask javacTask, ScannerSupplier scannerSupplier, ErrorProneOptions errorProneOptions) { Context context = ((BasicJavacTask) javacTask).getContext(); checkCompilePolicy(Options.instance(context).get("compilePolicy")); setupMessageBundle(context); RefactoringCollection[] refactoringCollection = {null}; javacTask.addTaskListener( createAnalyzer(scannerSupplier, errorProneOptions, context, refactoringCollection)); if (refactoringCollection[0] != null) { javacTask.addTaskListener(new RefactoringTask(context, refactoringCollection[0])); } } @Override public StandardJavaFileManager getStandardFileManager( DiagnosticListener<? super JavaFileObject> diagnosticListener, Locale locale, Charset charset) { return javacTool.getStandardFileManager(diagnosticListener, locale, charset); } @Override public int isSupportedOption(String option) { int numberOfArgs = javacTool.isSupportedOption(option); if (numberOfArgs != -1) { return numberOfArgs; } return ErrorProneOptions.isSupportedOption(option); } @Override public int run(InputStream in, OutputStream out, OutputStream err, String... arguments) { return javacTool.run(in, out, err, arguments); } @Override public Set<SourceVersion> getSourceVersions() { Set<SourceVersion> filtered = EnumSet.noneOf(SourceVersion.class); for (SourceVersion version : javacTool.getSourceVersions()) { if (version.compareTo(SourceVersion.RELEASE_6) >= 0) { filtered.add(version); } } return filtered; } /** * Default to compiling with the same -source and -target as the host's javac. * * <p>This prevents, e.g., targeting Java 8 by default when using error-prone on JDK7. */ private static ImmutableList<String> defaultToLatestSupportedLanguageLevel( ImmutableList<String> args) { String overrideLanguageLevel; switch (JAVA_SPECIFICATION_VERSION.value()) { case "1.7": overrideLanguageLevel = "7"; break; case "1.8": overrideLanguageLevel = "8"; break; default: return args; } return ImmutableList.<String>builder() .add( // suppress xlint 'options' warnings to avoid diagnostics like: // 'bootstrap class path not set in conjunction with -source 1.7' "-Xlint:-options", "-source", overrideLanguageLevel, "-target", overrideLanguageLevel) .addAll(args) .build(); } /** * Throws InvalidCommandLineOptionException if the {@code -XDcompilePolicy} flag is set to an * unsupported value */ static void checkCompilePolicy(@Nullable String compilePolicy) { if (compilePolicy == null) { throw new InvalidCommandLineOptionException( "The default compilation policy (by-todo) is not supported by Error Prone," + " pass -XDcompilePolicy=simple instead"); } switch (compilePolicy) { case "byfile": case "simple": break; default: throw new InvalidCommandLineOptionException( String.format( "-XDcompilePolicy=%s is not supported by Error Prone," + " pass -XDcompilePolicy=simple instead", compilePolicy)); } } /** * Sets javac's {@code -XDcompilePolicy} flag to ensure that all classes in a file are attributed * before any of them are lowered. Error Prone depends on this behavior when analyzing files that * contain multiple top-level classes. */ private static ImmutableList<String> setCompilePolicyToByFile(ImmutableList<String> args) { for (String arg : args) { if (arg.startsWith("-XDcompilePolicy")) { String value = arg.substring(arg.indexOf('=') + 1); checkCompilePolicy(value); return args; // don't do anything if a valid policy is already set } } return ImmutableList.<String>builder().addAll(args).add("-XDcompilePolicy=simple").build(); } /** Registers our message bundle. */ public static void setupMessageBundle(Context context) { ResourceBundle bundle = ResourceBundle.getBundle("com.google.errorprone.errors"); JavacMessages.instance(context).add(l -> bundle); } static ErrorProneAnalyzer createAnalyzer( ScannerSupplier scannerSupplier, ErrorProneOptions epOptions, Context context, RefactoringCollection[] refactoringCollection) { if (!epOptions.patchingOptions().doRefactor()) { return ErrorProneAnalyzer.createByScanningForPlugins(scannerSupplier, epOptions, context); } refactoringCollection[0] = RefactoringCollection.refactor(epOptions.patchingOptions(), context); // Refaster refactorer or using builtin checks CodeTransformer codeTransformer = epOptions .patchingOptions() .customRefactorer() .or( () -> { ScannerSupplier toUse = ErrorPronePlugins.loadPlugins(scannerSupplier, context) .applyOverrides(epOptions); ImmutableSet<String> namedCheckers = epOptions.patchingOptions().namedCheckers(); if (!namedCheckers.isEmpty()) { toUse = toUse.filter(bci -> namedCheckers.contains(bci.canonicalName())); } return ErrorProneScannerTransformer.create(toUse.get()); }) .get(); return ErrorProneAnalyzer.createWithCustomDescriptionListener( codeTransformer, epOptions, context, refactoringCollection[0]); } static class RefactoringTask implements TaskListener { private final Context context; private final RefactoringCollection refactoringCollection; public RefactoringTask(Context context, RefactoringCollection refactoringCollection) { this.context = context; this.refactoringCollection = refactoringCollection; } @Override public void started(TaskEvent event) {} @Override public void finished(TaskEvent event) { if (event.getKind() != Kind.GENERATE) { return; } RefactoringResult refactoringResult; try { refactoringResult = refactoringCollection.applyChanges(event.getSourceFile().toUri()); } catch (Exception e) { PrintWriter out = Log.instance(context).getWriter(WriterKind.ERROR); out.println(e.getMessage()); out.flush(); return; } if (refactoringResult.type() == RefactoringCollection.RefactoringResultType.CHANGED) { PrintWriter out = Log.instance(context).getWriter(WriterKind.NOTICE); out.println(refactoringResult.message()); out.flush(); } } } }
10,320
35.860714
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/ErrorProneError.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; import com.google.common.base.Strings; import com.google.common.base.Throwables; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.DiagnosticSource; import com.sun.tools.javac.util.JCDiagnostic; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticType; import com.sun.tools.javac.util.Log; import java.lang.reflect.Method; import javax.tools.JavaFileObject; /** * Wraps an unrecoverable error that occurs during analysis with the source position that triggered * the crash. */ public class ErrorProneError extends Error { private final String checkName; private final Throwable cause; private final DiagnosticPosition pos; private final JavaFileObject source; public ErrorProneError( String checkName, Throwable cause, DiagnosticPosition pos, JavaFileObject source) { super( formatMessage(checkName, source, pos, cause), cause, /* enableSuppression= */ true, /* writableStackTrace= */ false); this.checkName = checkName; this.cause = cause; this.pos = pos; this.source = source; } /** * @deprecated prefer {@link #logFatalError(Log, Context)} */ @Deprecated public void logFatalError(Log log) { String version = ErrorProneVersion.loadVersionFromPom().or("unknown version"); JavaFileObject prev = log.currentSourceFile(); try { log.useSource(source); // use reflection since this overload of error doesn't exist in JDK >= 11 Method m = Log.class.getMethod("error", DiagnosticPosition.class, String.class, Object[].class); m.invoke( log, pos, "error.prone.crash", Throwables.getStackTraceAsString(cause), version, checkName); } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } finally { log.useSource(prev); } } public void logFatalError(Log log, Context context) { String version = ErrorProneVersion.loadVersionFromPom().or("unknown version"); JavaFileObject originalSource = log.useSource(source); JCDiagnostic.Factory factory = JCDiagnostic.Factory.instance(context); try { log.report( factory.create( DiagnosticType.ERROR, log.currentSource(), pos, "error.prone.crash", Throwables.getStackTraceAsString(cause), version, checkName)); } finally { log.useSource(originalSource); } } private static String formatMessage( String checkName, JavaFileObject file, DiagnosticPosition pos, Throwable cause) { DiagnosticSource source = new DiagnosticSource(file, /* log= */ null); int column = source.getColumnNumber(pos.getStartPosition(), /* expandTabs= */ true); int line = source.getLineNumber(pos.getStartPosition()); String snippet = source.getLine(pos.getStartPosition()); StringBuilder sb = new StringBuilder(); sb.append( String.format( "\n%s:%d: %s: An exception was thrown by Error Prone: %s\n", source.getFile().getName(), line, checkName, cause.getMessage())); sb.append(snippet).append('\n'); if (column > 0) { sb.append(Strings.repeat(" ", column - 1)); } sb.append("^\n"); return sb.toString(); } public String checkName() { return checkName; } }
4,095
32.57377
99
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/ErrorPronePlugins.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; import static com.google.common.collect.ImmutableList.toImmutableList; import com.google.common.collect.ImmutableList; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.scanner.ScannerSupplier; import com.sun.tools.javac.processing.JavacProcessingEnvironment; import com.sun.tools.javac.util.Context; import java.util.ServiceLoader; import javax.tools.JavaFileManager; import javax.tools.StandardLocation; /** Loads custom Error Prone checks from the annotation processor classpath. */ public final class ErrorPronePlugins { public static ScannerSupplier loadPlugins(ScannerSupplier scannerSupplier, Context context) { JavaFileManager fileManager = context.get(JavaFileManager.class); // Unlike in annotation processor discovery, we never search CLASS_PATH if // ANNOTATION_PROCESSOR_PATH is unavailable. if (!fileManager.hasLocation(StandardLocation.ANNOTATION_PROCESSOR_PATH)) { return scannerSupplier; } // Use the same classloader that Error Prone was loaded from to avoid classloader skew // when using Error Prone plugins together with the Error Prone javac plugin. JavacProcessingEnvironment processingEnvironment = JavacProcessingEnvironment.instance(context); ClassLoader loader = processingEnvironment.getProcessorClassLoader(); ImmutableList<Class<? extends BugChecker>> extraBugCheckers = ServiceLoader.load(BugChecker.class, loader).stream() .map(ServiceLoader.Provider::type) .collect(toImmutableList()); if (extraBugCheckers.isEmpty()) { return scannerSupplier; } return scannerSupplier.plus(ScannerSupplier.fromBugCheckerClasses(extraBugCheckers)); } private ErrorPronePlugins() {} }
2,379
41.5
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/ErrorProneOptions.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.auto.value.AutoValue; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.errorprone.apply.ImportOrganizer; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.nio.file.FileSystems; import java.nio.file.Files; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; /** * Processes command-line options specific to error-prone. * * <p>Documentation for the available flags are available at https://errorprone.infoflags * * @author eaftan@google.com (Eddie Aftandilian) */ public class ErrorProneOptions { private static final String PREFIX = "-Xep"; private static final String SEVERITY_PREFIX = "-Xep:"; private static final String PATCH_CHECKS_PREFIX = "-XepPatchChecks:"; private static final String PATCH_OUTPUT_LOCATION = "-XepPatchLocation:"; private static final String PATCH_IMPORT_ORDER_PREFIX = "-XepPatchImportOrder:"; private static final String EXCLUDED_PATHS_PREFIX = "-XepExcludedPaths:"; private static final String IGNORE_LARGE_CODE_GENERATORS = "-XepIgnoreLargeCodeGenerators:"; private static final String ERRORS_AS_WARNINGS_FLAG = "-XepAllErrorsAsWarnings"; private static final String SUGGESTIONS_AS_WARNINGS_FLAG = "-XepAllSuggestionsAsWarnings"; private static final String ENABLE_ALL_CHECKS = "-XepAllDisabledChecksAsWarnings"; private static final String IGNORE_SUPPRESSION_ANNOTATIONS = "-XepIgnoreSuppressionAnnotations"; private static final String DISABLE_ALL_CHECKS = "-XepDisableAllChecks"; private static final String DISABLE_ALL_WARNINGS = "-XepDisableAllWarnings"; private static final String IGNORE_UNKNOWN_CHECKS_FLAG = "-XepIgnoreUnknownCheckNames"; private static final String DISABLE_WARNINGS_IN_GENERATED_CODE_FLAG = "-XepDisableWarningsInGeneratedCode"; private static final String COMPILING_TEST_ONLY_CODE = "-XepCompilingTestOnlyCode"; private static final String COMPILING_PUBLICLY_VISIBLE_CODE = "-XepCompilingPubliclyVisibleCode"; /** see {@link javax.tools.OptionChecker#isSupportedOption(String)} */ public static int isSupportedOption(String option) { boolean isSupported = option.startsWith(SEVERITY_PREFIX) || option.startsWith(ErrorProneFlags.PREFIX) || option.startsWith(PATCH_OUTPUT_LOCATION) || option.startsWith(PATCH_CHECKS_PREFIX) || option.startsWith(EXCLUDED_PATHS_PREFIX) || option.equals(IGNORE_UNKNOWN_CHECKS_FLAG) || option.equals(DISABLE_WARNINGS_IN_GENERATED_CODE_FLAG) || option.equals(ERRORS_AS_WARNINGS_FLAG) || option.equals(SUGGESTIONS_AS_WARNINGS_FLAG) || option.equals(ENABLE_ALL_CHECKS) || option.equals(DISABLE_ALL_CHECKS) || option.equals(IGNORE_SUPPRESSION_ANNOTATIONS) || option.equals(COMPILING_TEST_ONLY_CODE) || option.equals(COMPILING_PUBLICLY_VISIBLE_CODE) || option.equals(DISABLE_ALL_WARNINGS); return isSupported ? 0 : -1; } public boolean isEnableAllChecksAsWarnings() { return enableAllChecksAsWarnings; } public boolean isDisableAllChecks() { return disableAllChecks; } /** * Severity levels for an error-prone check that define how the check results should be presented. */ public enum Severity { DEFAULT, // whatever is specified in the @BugPattern annotation OFF, WARN, ERROR } @AutoValue abstract static class PatchingOptions { final boolean doRefactor() { return inPlace() || !baseDirectory().isEmpty(); } abstract ImmutableSet<String> namedCheckers(); abstract boolean inPlace(); abstract String baseDirectory(); abstract Optional<Supplier<CodeTransformer>> customRefactorer(); abstract ImportOrganizer importOrganizer(); static Builder builder() { return new AutoValue_ErrorProneOptions_PatchingOptions.Builder() .baseDirectory("") .inPlace(false) .namedCheckers(ImmutableSet.of()) .importOrganizer(ImportOrganizer.STATIC_FIRST_ORGANIZER); } @AutoValue.Builder abstract static class Builder { abstract Builder namedCheckers(ImmutableSet<String> checkers); abstract Builder inPlace(boolean inPlace); abstract Builder baseDirectory(String baseDirectory); abstract Builder customRefactorer(Supplier<CodeTransformer> refactorer); abstract Builder importOrganizer(ImportOrganizer importOrganizer); abstract PatchingOptions autoBuild(); final PatchingOptions build() { PatchingOptions patchingOptions = autoBuild(); // If anything is specified, then (checkers or refaster) and output must be set. if ((!patchingOptions.namedCheckers().isEmpty() || patchingOptions.customRefactorer().isPresent()) ^ patchingOptions.doRefactor()) { throw new InvalidCommandLineOptionException( "-XepPatchChecks and -XepPatchLocation must be specified together"); } return patchingOptions; } } } private final ImmutableList<String> remainingArgs; private final ImmutableMap<String, Severity> severityMap; private final boolean ignoreUnknownChecks; private final boolean disableWarningsInGeneratedCode; private final boolean disableAllWarnings; private final boolean dropErrorsToWarnings; private final boolean suggestionsAsWarnings; private final boolean enableAllChecksAsWarnings; private final boolean disableAllChecks; private final boolean isTestOnlyTarget; private final boolean isPubliclyVisibleTarget; private final ErrorProneFlags flags; private final PatchingOptions patchingOptions; private final Pattern excludedPattern; private final boolean ignoreSuppressionAnnotations; private final boolean ignoreLargeCodeGenerators; private ErrorProneOptions( ImmutableMap<String, Severity> severityMap, ImmutableList<String> remainingArgs, boolean ignoreUnknownChecks, boolean disableWarningsInGeneratedCode, boolean disableAllWarnings, boolean dropErrorsToWarnings, boolean suggestionsAsWarnings, boolean enableAllChecksAsWarnings, boolean disableAllChecks, boolean isTestOnlyTarget, boolean isPubliclyVisibleTarget, ErrorProneFlags flags, PatchingOptions patchingOptions, Pattern excludedPattern, boolean ignoreSuppressionAnnotations, boolean ignoreLargeCodeGenerators) { this.severityMap = severityMap; this.remainingArgs = remainingArgs; this.ignoreUnknownChecks = ignoreUnknownChecks; this.disableWarningsInGeneratedCode = disableWarningsInGeneratedCode; this.disableAllWarnings = disableAllWarnings; this.dropErrorsToWarnings = dropErrorsToWarnings; this.suggestionsAsWarnings = suggestionsAsWarnings; this.enableAllChecksAsWarnings = enableAllChecksAsWarnings; this.disableAllChecks = disableAllChecks; this.isTestOnlyTarget = isTestOnlyTarget; this.isPubliclyVisibleTarget = isPubliclyVisibleTarget; this.flags = flags; this.patchingOptions = patchingOptions; this.excludedPattern = excludedPattern; this.ignoreSuppressionAnnotations = ignoreSuppressionAnnotations; this.ignoreLargeCodeGenerators = ignoreLargeCodeGenerators; } public String[] getRemainingArgs() { return remainingArgs.toArray(new String[remainingArgs.size()]); } public ImmutableMap<String, Severity> getSeverityMap() { return severityMap; } public boolean ignoreUnknownChecks() { return ignoreUnknownChecks; } public boolean disableWarningsInGeneratedCode() { return disableWarningsInGeneratedCode; } public boolean isDisableAllWarnings() { return disableAllWarnings; } public boolean isDropErrorsToWarnings() { return dropErrorsToWarnings; } public boolean isSuggestionsAsWarnings() { return suggestionsAsWarnings; } public boolean isTestOnlyTarget() { return isTestOnlyTarget; } public boolean isPubliclyVisibleTarget() { return isPubliclyVisibleTarget; } public boolean isIgnoreSuppressionAnnotations() { return ignoreSuppressionAnnotations; } public boolean ignoreLargeCodeGenerators() { return ignoreLargeCodeGenerators; } public ErrorProneFlags getFlags() { return flags; } public PatchingOptions patchingOptions() { return patchingOptions; } public Pattern getExcludedPattern() { return excludedPattern; } private static class Builder { private boolean ignoreUnknownChecks = false; private boolean disableAllWarnings = false; private boolean disableWarningsInGeneratedCode = false; private boolean dropErrorsToWarnings = false; private boolean suggestionsAsWarnings = false; private boolean enableAllChecksAsWarnings = false; private boolean disableAllChecks = false; private boolean isTestOnlyTarget = false; private boolean isPubliclyVisibleTarget = false; private boolean ignoreSuppressionAnnotations = false; private boolean ignoreLargeCodeGenerators = true; private final Map<String, Severity> severityMap = new LinkedHashMap<>(); private final ErrorProneFlags.Builder flagsBuilder = ErrorProneFlags.builder(); private final PatchingOptions.Builder patchingOptionsBuilder = PatchingOptions.builder(); private Pattern excludedPattern; private void parseSeverity(String arg) { // Strip prefix String remaining = arg.substring(SEVERITY_PREFIX.length()); // Split on ':' List<String> parts = Splitter.on(':').splitToList(remaining); if (parts.size() > 2 || parts.get(0).isEmpty()) { throw new InvalidCommandLineOptionException("invalid flag: " + arg); } String checkName = parts.get(0); Severity severity; if (parts.size() == 1) { severity = Severity.DEFAULT; } else { // parts.length == 2 try { severity = Severity.valueOf(parts.get(1)); } catch (IllegalArgumentException e) { throw new InvalidCommandLineOptionException("invalid flag: " + arg); } } severityMap.put(checkName, severity); } public void parseFlag(String flag) { flagsBuilder.parseFlag(flag); } public void setIgnoreSuppressionAnnotations(boolean ignoreSuppressionAnnotations) { this.ignoreSuppressionAnnotations = ignoreSuppressionAnnotations; } public void setIgnoreUnknownChecks(boolean ignoreUnknownChecks) { this.ignoreUnknownChecks = ignoreUnknownChecks; } public void setDisableWarningsInGeneratedCode(boolean disableWarningsInGeneratedCode) { this.disableWarningsInGeneratedCode = disableWarningsInGeneratedCode; } public void setDropErrorsToWarnings(boolean dropErrorsToWarnings) { severityMap.entrySet().stream() .filter(e -> e.getValue() == Severity.ERROR) .forEach(e -> e.setValue(Severity.WARN)); this.dropErrorsToWarnings = dropErrorsToWarnings; } public void setSuggestionsAsWarnings(boolean suggestionsAsWarnings) { this.suggestionsAsWarnings = suggestionsAsWarnings; } public void setDisableAllWarnings(boolean disableAllWarnings) { severityMap.entrySet().stream() .filter(e -> e.getValue() == Severity.WARN) .forEach(e -> e.setValue(Severity.OFF)); this.disableAllWarnings = disableAllWarnings; } public void setEnableAllChecksAsWarnings(boolean enableAllChecksAsWarnings) { // Checks manually disabled before this flag are reset to warning-level severityMap.entrySet().stream() .filter(e -> e.getValue() == Severity.OFF) .forEach(e -> e.setValue(Severity.WARN)); this.enableAllChecksAsWarnings = enableAllChecksAsWarnings; } public void setIgnoreLargeCodeGenerators(boolean ignoreLargeCodeGenerators) { this.ignoreLargeCodeGenerators = ignoreLargeCodeGenerators; } public void setDisableAllChecks(boolean disableAllChecks) { // Discard previously set severities so that the DisableAllChecks flag is position sensitive. severityMap.clear(); this.disableAllChecks = disableAllChecks; } public void setTestOnlyTarget(boolean isTestOnlyTarget) { this.isTestOnlyTarget = isTestOnlyTarget; } public void setPubliclyVisibleTarget(boolean isPubliclyVisibleTarget) { this.isPubliclyVisibleTarget = isPubliclyVisibleTarget; } public PatchingOptions.Builder patchingOptionsBuilder() { return patchingOptionsBuilder; } public ErrorProneOptions build(ImmutableList<String> remainingArgs) { return new ErrorProneOptions( ImmutableMap.copyOf(severityMap), remainingArgs, ignoreUnknownChecks, disableWarningsInGeneratedCode, disableAllWarnings, dropErrorsToWarnings, suggestionsAsWarnings, enableAllChecksAsWarnings, disableAllChecks, isTestOnlyTarget, isPubliclyVisibleTarget, flagsBuilder.build(), patchingOptionsBuilder.build(), excludedPattern, ignoreSuppressionAnnotations, ignoreLargeCodeGenerators); } public void setExcludedPattern(Pattern excludedPattern) { this.excludedPattern = excludedPattern; } } private static final ErrorProneOptions EMPTY = new Builder().build(ImmutableList.of()); public static ErrorProneOptions empty() { return EMPTY; } /** * Given a list of command-line arguments, produce the corresponding {@link ErrorProneOptions} * instance. * * @param args command-line arguments * @return an {@link ErrorProneOptions} instance encapsulating the given arguments * @throws InvalidCommandLineOptionException if an error-prone option is invalid */ public static ErrorProneOptions processArgs(Iterable<String> args) { Preconditions.checkNotNull(args); ImmutableList.Builder<String> remainingArgs = ImmutableList.builder(); /* By default, we throw an error when an unknown option is passed in, if for example you * try to disable a check that doesn't match any of the known checks. This catches typos from * the command line. * * You can pass the IGNORE_UNKNOWN_CHECKS_FLAG to opt-out of that checking. This allows you to * use command lines from different versions of error-prone interchangeably. */ Builder builder = new Builder(); for (String arg : args) { switch (arg) { case IGNORE_SUPPRESSION_ANNOTATIONS: builder.setIgnoreSuppressionAnnotations(true); break; case IGNORE_UNKNOWN_CHECKS_FLAG: builder.setIgnoreUnknownChecks(true); break; case DISABLE_WARNINGS_IN_GENERATED_CODE_FLAG: builder.setDisableWarningsInGeneratedCode(true); break; case ERRORS_AS_WARNINGS_FLAG: builder.setDropErrorsToWarnings(true); break; case SUGGESTIONS_AS_WARNINGS_FLAG: builder.setSuggestionsAsWarnings(true); break; case ENABLE_ALL_CHECKS: builder.setEnableAllChecksAsWarnings(true); break; case DISABLE_ALL_CHECKS: builder.setDisableAllChecks(true); break; case COMPILING_TEST_ONLY_CODE: builder.setTestOnlyTarget(true); break; case COMPILING_PUBLICLY_VISIBLE_CODE: builder.setPubliclyVisibleTarget(true); break; case DISABLE_ALL_WARNINGS: builder.setDisableAllWarnings(true); break; default: if (arg.startsWith(SEVERITY_PREFIX)) { builder.parseSeverity(arg); } else if (arg.startsWith(ErrorProneFlags.PREFIX)) { builder.parseFlag(arg); } else if (arg.startsWith(PATCH_OUTPUT_LOCATION)) { String remaining = arg.substring(PATCH_OUTPUT_LOCATION.length()); if (remaining.equals("IN_PLACE")) { builder.patchingOptionsBuilder().inPlace(true); } else { if (remaining.isEmpty()) { throw new InvalidCommandLineOptionException("invalid flag: " + arg); } builder.patchingOptionsBuilder().baseDirectory(remaining); } } else if (arg.startsWith(PATCH_CHECKS_PREFIX)) { String remaining = arg.substring(PATCH_CHECKS_PREFIX.length()); if (remaining.startsWith("refaster:")) { // Refaster rule, load from InputStream at file builder .patchingOptionsBuilder() .customRefactorer( () -> { String path = remaining.substring("refaster:".length()); try (InputStream in = Files.newInputStream(FileSystems.getDefault().getPath(path)); ObjectInputStream ois = new ObjectInputStream(in)) { return (CodeTransformer) ois.readObject(); } catch (IOException | ClassNotFoundException e) { throw new RuntimeException("Can't load Refaster rule from " + path, e); } }); } else { Iterable<String> checks = Splitter.on(',').trimResults().split(remaining); builder.patchingOptionsBuilder().namedCheckers(ImmutableSet.copyOf(checks)); } } else if (arg.startsWith(PATCH_IMPORT_ORDER_PREFIX)) { String remaining = arg.substring(PATCH_IMPORT_ORDER_PREFIX.length()); ImportOrganizer importOrganizer = ImportOrderParser.getImportOrganizer(remaining); builder.patchingOptionsBuilder().importOrganizer(importOrganizer); } else if (arg.startsWith(EXCLUDED_PATHS_PREFIX)) { String pathRegex = arg.substring(EXCLUDED_PATHS_PREFIX.length()); builder.setExcludedPattern(Pattern.compile(pathRegex)); } else { if (arg.startsWith(PREFIX)) { throw new InvalidCommandLineOptionException("invalid flag: " + arg); } remainingArgs.add(arg); } } } return builder.build(remainingArgs.build()); } /** * Given a list of command-line arguments, produce the corresponding {@link ErrorProneOptions} * instance. * * @param args command-line arguments * @return an {@link ErrorProneOptions} instance encapsulating the given arguments * @throws InvalidCommandLineOptionException if an error-prone option is invalid */ public static ErrorProneOptions processArgs(String[] args) { Preconditions.checkNotNull(args); return processArgs(Arrays.asList(args)); } }
19,810
36.807252
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/ErrorProneAnalyzer.java
/* * Copyright 2012 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 static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Throwables.getStackTraceAsString; import static com.google.common.base.Verify.verify; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.scanner.ErrorProneScannerTransformer; import com.google.errorprone.scanner.ScannerSupplier; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.Tree; import com.sun.source.util.TaskEvent; import com.sun.source.util.TaskEvent.Kind; import com.sun.source.util.TaskListener; import com.sun.source.util.TreePath; import com.sun.tools.javac.api.ClientCodeWrapper.Trusted; import com.sun.tools.javac.api.JavacTrees; import com.sun.tools.javac.code.Symbol.CompletionFailure; import com.sun.tools.javac.main.JavaCompiler; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.Log; import com.sun.tools.javac.util.PropagatedException; import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; import javax.tools.JavaFileObject; /** A {@link TaskListener} that runs Error Prone over attributed compilation units. */ @Trusted public class ErrorProneAnalyzer implements TaskListener { // The set of trees that have already been scanned. private final Set<Tree> seen = new HashSet<>(); private final Supplier<CodeTransformer> transformer; private final ErrorProneOptions errorProneOptions; private final Context context; private final DescriptionListener.Factory descriptionListenerFactory; public static ErrorProneAnalyzer createByScanningForPlugins( ScannerSupplier scannerSupplier, ErrorProneOptions errorProneOptions, Context context) { return new ErrorProneAnalyzer( scansPlugins(scannerSupplier, errorProneOptions, context), errorProneOptions, context, JavacErrorDescriptionListener.provider(context)); } private static Supplier<CodeTransformer> scansPlugins( ScannerSupplier scannerSupplier, ErrorProneOptions errorProneOptions, Context context) { return Suppliers.memoize( () -> { // we can't load plugins from the processorpath until the filemanager has been // initialized, so do it lazily ErrorProneTimings timings = ErrorProneTimings.instance(context); try (AutoCloseable unused = timings.initializationTimeSpan()) { return ErrorProneScannerTransformer.create( ErrorPronePlugins.loadPlugins(scannerSupplier, context) .applyOverrides(errorProneOptions) .get()); } catch (InvalidCommandLineOptionException e) { throw new PropagatedException(e); } catch (Exception e) { // for the timing span, should be impossible throw new AssertionError(e); } }); } static ErrorProneAnalyzer createWithCustomDescriptionListener( CodeTransformer codeTransformer, ErrorProneOptions errorProneOptions, Context context, DescriptionListener.Factory descriptionListenerFactory) { return new ErrorProneAnalyzer( Suppliers.ofInstance(codeTransformer), errorProneOptions, context, descriptionListenerFactory); } private ErrorProneAnalyzer( Supplier<CodeTransformer> transformer, ErrorProneOptions errorProneOptions, Context context, DescriptionListener.Factory descriptionListenerFactory) { this.transformer = checkNotNull(transformer); this.errorProneOptions = checkNotNull(errorProneOptions); this.descriptionListenerFactory = checkNotNull(descriptionListenerFactory); Context errorProneContext = new SubContext(context); errorProneContext.put(ErrorProneOptions.class, errorProneOptions); this.context = errorProneContext; } private int errorProneErrors = 0; @Override public void finished(TaskEvent taskEvent) { if (taskEvent.getKind() != Kind.ANALYZE) { return; } if (JavaCompiler.instance(context).errorCount() > errorProneErrors) { return; } TreePath path = JavacTrees.instance(context).getPath(taskEvent.getTypeElement()); if (path == null) { path = new TreePath(taskEvent.getCompilationUnit()); } // Assert that the event is unique and scan the current tree. verify(seen.add(path.getLeaf()), "Duplicate FLOW event for: %s", taskEvent.getTypeElement()); Log log = Log.instance(context); JCCompilationUnit compilation = (JCCompilationUnit) path.getCompilationUnit(); DescriptionListener descriptionListener = descriptionListenerFactory.getDescriptionListener(log, compilation); DescriptionListener countingDescriptionListener = d -> { if (d.severity() == SeverityLevel.ERROR) { errorProneErrors++; } descriptionListener.onDescribed(d); }; JavaFileObject originalSource = log.useSource(compilation.getSourceFile()); try { if (shouldExcludeSourceFile(compilation)) { return; } if (path.getLeaf().getKind() == Tree.Kind.COMPILATION_UNIT) { // We only get TaskEvents for compilation units if they contain no package declarations // (e.g. package-info.java files). In this case it's safe to analyze the // CompilationUnitTree immediately. transformer.get().apply(path, context, countingDescriptionListener); } else if (finishedCompilation(path.getCompilationUnit())) { // Otherwise this TaskEvent is for a ClassTree, and we can scan the whole // CompilationUnitTree once we've seen all the enclosed classes. transformer.get().apply(new TreePath(compilation), context, countingDescriptionListener); } } catch (ErrorProneError e) { e.logFatalError(log, context); // let the exception propagate to javac's main, where it will cause the compilation to // terminate with Result.ABNORMAL throw e; } catch (LinkageError e) { // similar to ErrorProneError String version = ErrorProneVersion.loadVersionFromPom().or("unknown version"); log.error("error.prone.crash", getStackTraceAsString(e), version, "(see stack trace)"); throw e; } catch (CompletionFailure e) { // A CompletionFailure can be triggered when error-prone tries to complete a symbol // that isn't on the compilation classpath. This can occur when a check performs an // instanceof test on a symbol, which requires inspecting the transitive closure of the // symbol's supertypes. If javac didn't need to check the symbol's assignability // then a normal compilation would have succeeded, and no diagnostics will have been // reported yet, but we don't want to crash javac. log.error("proc.cant.access", e.sym, getDetailValue(e), getStackTraceAsString(e)); } finally { log.useSource(originalSource); } } private static Object getDetailValue(CompletionFailure completionFailure) { try { // The return type of getDetailValue() changed from Object to JCDiagnostic in JDK 10, // but the rest of the signature is unchanged between the two versions, // see https://bugs.openjdk.java.net/browse/JDK-817032, return CompletionFailure.class.getMethod("getDetailValue").invoke(completionFailure); } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } } /** Returns true if the given source file should be excluded from analysis. */ private boolean shouldExcludeSourceFile(CompilationUnitTree tree) { Pattern excludedPattern = errorProneOptions.getExcludedPattern(); return excludedPattern != null && excludedPattern.matcher(ASTHelpers.getFileName(tree)).matches(); } /** Returns true if all declarations inside the given compilation unit have been visited. */ private boolean finishedCompilation(CompilationUnitTree tree) { OUTER: for (Tree decl : tree.getTypeDecls()) { switch (decl.getKind()) { case EMPTY_STATEMENT: // ignore ";" at the top level, which counts as an empty type decl continue OUTER; case IMPORT: // The spec disallows mixing imports and empty top-level declarations (";"), but // javac has a bug that causes it to accept empty declarations interspersed with imports: // http://mail.openjdk.java.net/pipermail/compiler-dev/2013-August/006968.html // // Any import declarations after the first semi are incorrectly added to the list // of type declarations, so we have to skip over them here. continue OUTER; default: break; } if (!seen.contains(decl)) { return false; } } return true; } }
9,622
41.768889
99
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/VisitorState.java
/* * Copyright 2011 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 static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.errorprone.util.ASTHelpers.getStartPosition; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultiset; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.SuppressionInfo.SuppressedState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.dataflow.nullnesspropagation.NullnessAnalysis; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Suppressible; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.ErrorProneToken; import com.google.errorprone.util.ErrorProneTokens; import com.sun.source.tree.Tree; import com.sun.source.util.TreePath; import com.sun.tools.javac.code.Kinds.Kind; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.CompletionFailure; import com.sun.tools.javac.code.Symbol.ModuleSymbol; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.ArrayType; import com.sun.tools.javac.code.Type.ClassType; import com.sun.tools.javac.code.Types; import com.sun.tools.javac.comp.Modules; import com.sun.tools.javac.model.JavacElements; import com.sun.tools.javac.parser.Tokens.Token; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.TreeMaker; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.Name; import com.sun.tools.javac.util.Names; import com.sun.tools.javac.util.Options; import java.io.IOException; import java.lang.ref.SoftReference; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import javax.annotation.Nullable; import javax.lang.model.util.Elements; /** * @author alexeagle@google.com (Alex Eagle) */ public class VisitorState { private final SharedState sharedState; public final Context context; private final TreePath path; private final SuppressedState suppressedState; // The default no-op implementation of DescriptionListener. We use this instead of null so callers // of getDescriptionListener() don't have to do null-checking. private static void nullListener(Description description) {} /** * Return a VisitorState that has no Error Prone configuration, and can't report results. * * <p>If using this method, consider moving to using utility methods not needing VisitorSate */ public static VisitorState createForUtilityPurposes(Context context) { return new VisitorState( context, VisitorState::nullListener, ImmutableMap.of(), ErrorProneOptions.empty(), // Can't use this VisitorState to report results, so no-op collector. StatisticsCollector.createNoOpCollector(), null, SuppressedState.UNSUPPRESSED); } /** * Return a VisitorState that has no Error Prone configuration, but can report findings to {@code * listener}. */ public static VisitorState createForCustomFindingCollection( Context context, DescriptionListener listener) { return new VisitorState( context, listener, ImmutableMap.of(), ErrorProneOptions.empty(), StatisticsCollector.createCollector(), null, SuppressedState.UNSUPPRESSED); } /** * Return a VisitorState configured for a new compilation, including Error Prone configuration. */ public static VisitorState createConfiguredForCompilation( Context context, DescriptionListener listener, Map<String, SeverityLevel> severityMap, ErrorProneOptions errorProneOptions) { return new VisitorState( context, listener, severityMap, errorProneOptions, StatisticsCollector.createCollector(), null, SuppressedState.UNSUPPRESSED); } /** * Return a VisitorState that has no Error Prone configuration, and can't report results. * * @deprecated If VisitorState is needed, use {@link #createForUtilityPurposes}, otherwise just * use utility methods in ASTHelpers that don't need VisitorSate. */ @Deprecated public VisitorState(Context context) { this( context, VisitorState::nullListener, ImmutableMap.of(), ErrorProneOptions.empty(), // Can't use this VisitorState to report results, so no-op collector. StatisticsCollector.createNoOpCollector(), null, SuppressedState.UNSUPPRESSED); } /** * Return a VisitorState that has no Error Prone configuration, but can report findings to {@code * listener}. * * @deprecated Use the equivalent factory method {@link #createForCustomFindingCollection}. */ @Deprecated public VisitorState(Context context, DescriptionListener listener) { this( context, listener, ImmutableMap.of(), ErrorProneOptions.empty(), StatisticsCollector.createCollector(), null, SuppressedState.UNSUPPRESSED); } /** * Return a VisitorState configured for a new compilation, including Error Prone configuration. * * @deprecated Use the equivalent factory method {@link #createConfiguredForCompilation}. */ @Deprecated public VisitorState( Context context, DescriptionListener listener, Map<String, SeverityLevel> severityMap, ErrorProneOptions errorProneOptions) { this( context, listener, severityMap, errorProneOptions, StatisticsCollector.createCollector(), null, SuppressedState.UNSUPPRESSED); } /** * The constructor used for brand-new VisitorState objects from outside. It builds a new * SharedState. */ private VisitorState( Context context, DescriptionListener descriptionListener, Map<String, SeverityLevel> severityMap, ErrorProneOptions errorProneOptions, StatisticsCollector statisticsCollector, TreePath path, SuppressedState suppressedState) { this.context = context; this.suppressedState = suppressedState; this.path = path; this.sharedState = new SharedState( context, descriptionListener, statisticsCollector, severityMap, errorProneOptions); } /** * The constructor used for basing a new VisitorState object on an older one. It accepts * parameters only for the things that can change, and reuses its SharedState. */ private VisitorState( Context context, TreePath path, SuppressedState suppressedState, SharedState sharedState) { this.context = context; this.path = path; this.suppressedState = suppressedState; this.sharedState = sharedState; } public VisitorState withPath(TreePath path) { checkNotNull(path); return new VisitorState(context, path, suppressedState, sharedState); } private VisitorState withNoPathForMemoization() { return new VisitorState(context, null, suppressedState, sharedState); } public VisitorState withSuppression(SuppressedState suppressedState) { if (suppressedState == this.suppressedState) { return this; } return new VisitorState(context, path, suppressedState, sharedState); } public TreePath getPath() { if (path == null) { throw new UnsupportedOperationException( "VisitorState.memoize Supplier implementations cannot access the TreePath: The result is" + " cached across multiple CompilationUnitTree instances, which share none of the" + " path. Alternatively, you've managed to call getPath() before the VisitorState's" + " path was initialized."); } return path; } public TreeMaker getTreeMaker() { return sharedState.treeMaker; } public Types getTypes() { return sharedState.types; } public Elements getElements() { return JavacElements.instance(context); } public Symtab getSymtab() { return sharedState.symtab; } public Names getNames() { return sharedState.names; } public NullnessAnalysis getNullnessAnalysis() { return NullnessAnalysis.instance(context); } public ErrorProneOptions errorProneOptions() { return sharedState.errorProneOptions; } public Map<String, SeverityLevel> severityMap() { return sharedState.severityMap; } public void reportMatch(Description description) { checkNotNull(description, "Use Description.NO_MATCH to denote an absent finding."); if (description == Description.NO_MATCH) { return; } // TODO(cushon): creating Descriptions with the default severity and updating them here isn't // ideal (we could forget to do the update), so consider removing severity from Description. // Instead, there could be another method on the listener that took a description and a // (separate) SeverityLevel. Adding the method to the interface would require updating the // existing implementations, though. Wait for default methods? SeverityLevel override = sharedState.severityMap.get(description.checkName); if (override != null) { description = description.applySeverityOverride(override); } sharedState.statisticsCollector.incrementCounter(statsKey(description.checkName + "-findings")); // TODO(glorioso): I believe it is correct to still emit regular findings since the // Scanner configured the visitor state to explicitly scan suppressed nodes, but perhaps // we can add a 'suppressed' field to Description to allow the description listener to bucket // them out. sharedState.descriptionListener.onDescribed(description); } private String statsKey(String key) { return suppressedState == SuppressedState.SUPPRESSED ? key + "-suppressed" : key; } /** * Increment the counter for a combination of {@code bugChecker}'s canonical name and {@code key} * by 1. * * <p>e.g.: a key of {@code foo} becomes {@code FooChecker-foo}. */ public void incrementCounter(BugChecker bugChecker, String key) { incrementCounter(bugChecker, key, 1); } /** * Increment the counter for a combination of {@code bugChecker}'s canonical name and {@code key} * by {@code count}. * * <p>e.g.: a key of {@code foo} becomes {@code FooChecker-foo}. */ public void incrementCounter(BugChecker bugChecker, String key, int count) { sharedState.statisticsCollector.incrementCounter( statsKey(bugChecker.canonicalName() + "-" + key), count); } /** * Returns a copy of all of the counters previously added to this VisitorState with {@link * #incrementCounter}. */ public ImmutableMultiset<String> counters() { return sharedState.statisticsCollector.counters(); } public Name getName(String nameStr) { return getNames().fromString(nameStr); } /** * Given the binary name of a class, returns the {@link Type}. * * <p>Prefer not to use this method for constant strings, or strings otherwise known at compile * time. Instead, save the result of {@link * com.google.errorprone.suppliers.Suppliers#typeFromString} as a class constant, and use its * {@link Supplier#get} method to look up the Type when needed. This lookup will be faster, * improving Error Prone's analysis time. * * <p>If this method returns null, the compiler doesn't have access to this type, which means that * if you are comparing other types to this for equality or the subtype relation, your result * would always be false even if it could create the type. Thus it might be best to bail out early * in your matcher if this method returns null on your type of interest. * * @param typeStr the JLS 13.1 binary name of the class, e.g. {@code "java.util.Map$Entry"} * @return the {@link Type}, or null if it cannot be found */ @Nullable public Type getTypeFromString(String typeStr) { return sharedState .typeCache .computeIfAbsent(typeStr, key -> Optional.ofNullable(getTypeFromStringInternal(key))) .orElse(null); } @Nullable private Type getTypeFromStringInternal(String typeStr) { validateTypeStr(typeStr); Type primitiveOrVoidType = getPrimitiveOrVoidType(typeStr); if (primitiveOrVoidType != null) { return primitiveOrVoidType; } ClassSymbol classSymbol = (ClassSymbol) getSymbolFromString(typeStr); if (classSymbol != null) { return classSymbol.asType(); } // It's possible for the type to exist on the classpath and still for getSymbolFromString to // return null if the type is not referenced in any source file (or by any of the referenced // types' supertypes). Checking for this, however, is prohibitively slow. See b/138753468 return null; } /** * @param symStr the string representation of a symbol * @return the Symbol object, or null if it cannot be found */ // TODO(cushon): deal with binary compat issues and return ClassSymbol @Nullable public Symbol getSymbolFromString(String symStr) { return getSymbolFromName(binaryNameFromClassname(symStr)); } /** * Returns the Name object corresponding to the named class, converting it to binary form along * the way if necessary (i.e., replacing Foo.Bar with Foo$Bar). To get the Name corresponding to * some string that is not a class name, see the more general {@link #getName(String)}. */ public Name binaryNameFromClassname(String className) { return getName(inferBinaryName(className)); } /** * Look up the class symbol for a given Name. * * @param name the name to look up, which must be in binary form (i.e. with $ for nested classes). */ @Nullable public ClassSymbol getSymbolFromName(Name name) { boolean modular = sharedState.modules.getDefaultModule() != getSymtab().noModule; if (!modular) { return getSymbolFromString(getSymtab().noModule, name); } for (ModuleSymbol msym : sharedState.modules.allModules()) { ClassSymbol result = getSymbolFromString(msym, name); if (result != null) { // TODO(cushon): the path where we iterate over all modules is probably slow. // Try to learn some lessons from JDK-8189747, and consider disallowing this case and // requiring users to call the getSymbolFromString(ModuleSymbol, Name) overload instead. return result; } } return null; } @Nullable public ClassSymbol getSymbolFromString(ModuleSymbol msym, Name name) { ClassSymbol result = getSymtab().getClass(msym, name); if (result == null || result.kind == Kind.ERR || !result.exists()) { return null; } try { result.complete(); } catch (CompletionFailure failure) { // Ignoring completion error is problematic in general, but in this case we're ignoring a // completion error for a type that was directly requested, not one that was discovered // during the compilation. return null; } return result; } /** * Given a canonical class name, infers the binary class name using case conventions. For example, * give {@code com.example.Outer.Inner} returns {@code com.example.Outer$Inner}. */ // TODO(cushon): consider migrating call sites to use binary names and removing this code. // (But then we'd probably want error handling for probably-incorrect canonical names, // so it may not end up being a performance win.) @VisibleForTesting static String inferBinaryName(String classname) { int len = classname.length(); checkArgument(!classname.isEmpty(), "class name must be non-empty"); checkArgument(classname.charAt(len - 1) != '.', "invalid class name: %s", classname); int lastPeriod = classname.lastIndexOf('.'); if (lastPeriod == -1) { return classname; // top level class in default package } int secondToLastPeriod = classname.lastIndexOf('.', lastPeriod - 1); if (secondToLastPeriod != -1 && !Character.isUpperCase(classname.charAt(secondToLastPeriod + 1))) { return classname; // top level class } StringBuilder sb = new StringBuilder(len); boolean foundUppercase = false; for (int i = 0; i < len; i++) { char c = classname.charAt(i); foundUppercase = foundUppercase || Character.isUpperCase(c); if (c == '.') { sb.append(foundUppercase ? '$' : '.'); } else { sb.append(c); } } return sb.toString(); } /** Build an instance of a Type. */ public Type getType(Type baseType, boolean isArray, List<Type> typeParams) { boolean isGeneric = typeParams != null && !typeParams.isEmpty(); if (!isArray && !isGeneric) { // Simple type. return baseType; } else if (isArray && !isGeneric) { // Array type, not generic. ClassSymbol arraySymbol = getSymtab().arrayClass; return new ArrayType(baseType, arraySymbol); } else if (!isArray && isGeneric) { // Generic type, not array. com.sun.tools.javac.util.List<Type> typeParamsCopy = com.sun.tools.javac.util.List.from(typeParams); return new ClassType(Type.noType, typeParamsCopy, baseType.tsym); } else { throw new IllegalArgumentException("Unsupported arguments to getType"); } } /** Build an Array Type from another Type */ public Type arrayTypeForType(Type baseType) { return new ArrayType(baseType, getSymtab().arrayClass); } /** * Returns the {@link TreePath} to the nearest tree node of one of the given types. To instead * retrieve the element directly, use {@link #findEnclosing(Class...)}. * * @return the path, or {@code null} if there is no match */ @Nullable @SafeVarargs public final TreePath findPathToEnclosing(Class<? extends Tree>... classes) { TreePath enclosingPath = getPath(); while (enclosingPath != null) { for (Class<? extends Tree> clazz : classes) { if (clazz.isInstance(enclosingPath.getLeaf())) { return enclosingPath; } } enclosingPath = enclosingPath.getParentPath(); } return null; } /** * Find the first enclosing tree node of one of the given types. * * @return the node, or {@code null} if there is no match */ @Nullable @SuppressWarnings("unchecked") // findPathToEnclosing guarantees that the type is from |classes| @SafeVarargs public final <T extends Tree> T findEnclosing(Class<? extends T>... classes) { TreePath pathToEnclosing = findPathToEnclosing(classes); return (pathToEnclosing == null) ? null : (T) pathToEnclosing.getLeaf(); } /** * Gets the current source file. * * @return the source file as a sequence of characters, or null if it is not available */ @Nullable public CharSequence getSourceCode() { try { return getPath().getCompilationUnit().getSourceFile().getCharContent(false); } catch (IOException e) { return null; } } /** * Gets the original source code that represents the given node. * * <p>Note that this may be different from what is returned by calling .toString() on the node. * This returns exactly what is in the source code, whereas .toString() pretty-prints the node * from its AST representation. * * @return the source code that represents the node, or {@code null} if the source code is * unavailable (e.g. for generated or desugared AST nodes) */ @Nullable public String getSourceForNode(Tree tree) { int start = ((JCTree) tree).getStartPosition(); int end = getEndPosition(tree); CharSequence source = getSourceCode(); if (end == -1) { return null; } checkArgument(start >= 0, "invalid start position (%s) for: %s", start, tree); checkArgument(start < end, "invalid source positions (%s, %s) for: %s", start, end, tree); checkArgument(end <= source.length(), "invalid end position (%s) for: %s", end, tree); return source.subSequence(start, end).toString(); } /** * Returns the list of {@link Token}s for the given {@link JCTree}. * * <p>This is moderately expensive (the source of the node has to be re-lexed), so it should only * be used if a fix is already going to be emitted. */ public List<ErrorProneToken> getTokensForNode(Tree tree) { return ErrorProneTokens.getTokens(getSourceForNode(tree), context); } /** * Returns the list of {@link Token}s for the given {@link JCTree}, offset by the start position * of the tree within the overall source. * * <p>This is moderately expensive (the source of the node has to be re-lexed), so it should only * be used if a fix is already going to be emitted. */ public List<ErrorProneToken> getOffsetTokensForNode(Tree tree) { int start = getStartPosition(tree); return ErrorProneTokens.getTokens(getSourceForNode(tree), start, context); } /** * Returns the list of {@link Token}s for source code between the given positions, offset by the * start position. * * <p>This is moderately expensive (the source of the node has to be re-lexed), so it should only * be used if a fix is already going to be emitted. */ public List<ErrorProneToken> getOffsetTokens(int start, int end) { return ErrorProneTokens.getTokens( getSourceCode().subSequence(start, end).toString(), start, context); } /** Returns the end position of the node, or -1 if it is not available. */ public int getEndPosition(Tree node) { JCCompilationUnit compilationUnit = (JCCompilationUnit) getPath().getCompilationUnit(); if (compilationUnit.endPositions == null) { return -1; } return ((JCTree) node).getEndPosition(compilationUnit.endPositions); } /** Validates a type string, ensuring it is not generic and not an array type. */ private static void validateTypeStr(String typeStr) { if (typeStr.contains("[") || typeStr.contains("]")) { throw new IllegalArgumentException( String.format( "Cannot convert array types (%s), please build them using getType()", typeStr)); } if (typeStr.contains("<") || typeStr.contains(">")) { throw new IllegalArgumentException( String.format( "Cannot convert generic types (%s), please build them using getType()", typeStr)); } } /** * Given a string that represents a type, if it's a primitive type (e.g., "int") or "void", return * the corresponding Type, or null otherwise. */ @Nullable private Type getPrimitiveOrVoidType(String typeStr) { switch (typeStr) { case "byte": return getSymtab().byteType; case "short": return getSymtab().shortType; case "int": return getSymtab().intType; case "long": return getSymtab().longType; case "float": return getSymtab().floatType; case "double": return getSymtab().doubleType; case "boolean": return getSymtab().booleanType; case "char": return getSymtab().charType; case "void": return getSymtab().voidType; default: return null; } } /** Returns true if the compilation is targeting Android. */ public boolean isAndroidCompatible() { return Options.instance(context).getBoolean("androidCompatible"); } /** Returns a timing span for the given {@link Suppressible}. */ public AutoCloseable timingSpan(Suppressible suppressible) { return sharedState.timings.span(suppressible); } private static class Cache<T> implements Supplier<T> { private final Supplier<T> impl; /* Uses T instead of Optional<T> because we don't want to cache null results (b/138753468). These inline caches persist between compilation units, and a type that fails to resolve in one may become available in the next; we want to keep looking it up (relying on the per-file cache in typeCache) if we don't have a result. If you want to cache a computation which can return null, wrap it in an Optional at the call site.*/ private SoftReference<T> cache = new SoftReference<>(null); private JavacInvocationInstance provenance; private Cache(Supplier<T> impl) { this.impl = impl; // provenance intentionally left null-initialized } @Override public synchronized T get(VisitorState state) { /* * Don't let callers rely on the TreePath: The Cache is shared across the whole compilation, * not just the current VisitorState's TreePath's CompilationUnit. */ state = state.withNoPathForMemoization(); /* javac is single-threaded, so in principle we don't really need to lock. But in practice it's cheap enough to be worth getting peace of mind that this is always correct. */ T value = cache.get(); if (value == null) { value = impl.get(state); if (value != null) { cache = new SoftReference<>(value); provenance = state.sharedState.javacInvocationInstance; } } else { JavacInvocationInstance current = state.sharedState.javacInvocationInstance; if (provenance != current) { value = impl.get(state); cache = new SoftReference<>(value); provenance = current; } } return value; } } /** * Produces a cache for a function that is expected to return the same result throughout a * compilation, but requires a {@link VisitorState} to compute that result. * * <p><b>Note:</b> Do not use this method for a function that depends on the varying state of a * {@link com.google.errorprone.VisitorState} (e.g. {@link #getPath()}—including the compilation * unit itself!). */ public static <T> Supplier<T> memoize(Supplier<T> f) { return new Cache<>(f); } /** * Instances that every {@link VisitorState} instance can share. * * <p>For the types that are typically stored in {@link Context}, caching the references over * {@code SomeClass.instance(context)} has sizable performance improvements in aggregate. */ private static final class SharedState { private final Modules modules; private final Names names; private final Symtab symtab; private final ErrorProneTimings timings; private final Types types; private final TreeMaker treeMaker; private final JavacInvocationInstance javacInvocationInstance; private final DescriptionListener descriptionListener; private final StatisticsCollector statisticsCollector; private final Map<String, SeverityLevel> severityMap; private final ErrorProneOptions errorProneOptions; // TODO(ronshapiro): should we presize this with a reasonable size? We can check for the // smallest build and see how many types are loaded and use that. Or perhaps a heuristic // based on number of files? private final Map<String, Optional<Type>> typeCache = new HashMap<>(); SharedState( Context context, DescriptionListener descriptionListener, StatisticsCollector statisticsCollector, Map<String, SeverityLevel> severityMap, ErrorProneOptions errorProneOptions) { this.modules = Modules.instance(context); this.names = Names.instance(context); this.symtab = Symtab.instance(context); this.timings = ErrorProneTimings.instance(context); this.types = Types.instance(context); this.treeMaker = TreeMaker.instance(context); this.javacInvocationInstance = JavacInvocationInstance.instance(context); this.descriptionListener = descriptionListener; this.statisticsCollector = statisticsCollector; this.severityMap = severityMap; this.errorProneOptions = errorProneOptions; } } /** * Returns the Java source code for a constant expression representing the given constant value. * Like {@link Elements#getConstantExpression}, but doesn't over-escape single quotes in strings. */ public String getConstantExpression(Object value) { String escaped = getElements().getConstantExpression(value); if (value instanceof String) { // Don't escape single-quotes in string literals StringBuilder sb = new StringBuilder(); for (int i = 0; i < escaped.length(); i++) { char c = escaped.charAt(i); if (c == '\\' && i + 1 < escaped.length()) { char next = escaped.charAt(++i); if (next != '\'') { sb.append(c); } sb.append(next); } else { sb.append(c); } } return sb.toString(); } return escaped; } }
29,493
35.729763
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/ImportOrderParser.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.errorprone.apply.ImportOrganizer; /** Parse import order strings. */ public final class ImportOrderParser { /** * Parse import order string and create appropriate {@link ImportOrganizer}. * * @param importOrder the import order, either static-first or static-last. * @return the {@link ImportOrganizer} */ public static ImportOrganizer getImportOrganizer(String importOrder) { switch (importOrder) { case "static-first": return ImportOrganizer.STATIC_FIRST_ORGANIZER; case "static-last": return ImportOrganizer.STATIC_LAST_ORGANIZER; case "android-static-first": return ImportOrganizer.ANDROID_STATIC_FIRST_ORGANIZER; case "android-static-last": return ImportOrganizer.ANDROID_STATIC_LAST_ORGANIZER; case "idea": return ImportOrganizer.IDEA_ORGANIZER; default: throw new IllegalStateException("Unknown import order: '" + importOrder + "'"); } } private ImportOrderParser() {} }
1,652
33.4375
87
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/CodeTransformer.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.common.collect.ImmutableClassToInstanceMap; import com.sun.source.util.TreePath; import com.sun.tools.javac.util.Context; import java.lang.annotation.Annotation; /** * Interface for a transformation over Java source. * * @author lowasser@google.com (Louis Wasserman) */ public interface CodeTransformer { /** Apply recursively from the leaf node in the given {@link TreePath}. */ void apply(TreePath path, Context context, DescriptionListener listener); /** * Returns a map of annotation data logically applied to this code transformer. * * <p>As an example, if a {@code CodeTransformer} expressed as a Refaster rule had an annotation * applied to it: * * <pre>{@code * @MyCustomAnnotation("value") * public class AnnotatedRefasterRule { * @BeforeTemplate void before(String x) {...} * @AfterTemplate void after(String x) {...} * } * }</pre> * * You could retrieve the value of {@code @MyCustomAnnotation} from this map. */ ImmutableClassToInstanceMap<Annotation> annotations(); }
1,703
32.411765
98
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/DescriptionListener.java
/* * Copyright 2011 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.matchers.Description; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.util.Log; /** * Strategies for reporting results. * * @author alexeagle@google.com (Alex Eagle) */ public interface DescriptionListener { /** Reports a suggested modification to the code. */ void onDescribed(Description description); /** Factory for creating DescriptionListeners while compiling each file. */ interface Factory { DescriptionListener getDescriptionListener(Log log, JCCompilationUnit compilation); } }
1,216
31.026316
87
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/CompositeCodeTransformer.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; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableClassToInstanceMap; import com.google.common.collect.ImmutableList; import com.sun.source.util.TreePath; import com.sun.tools.javac.util.Context; import java.io.Serializable; import java.lang.annotation.Annotation; /** Combines multiple {@code CodeTransformer}s into one. */ @AutoValue public abstract class CompositeCodeTransformer implements CodeTransformer, Serializable { public static CodeTransformer compose(CodeTransformer... transformers) { return compose(ImmutableList.copyOf(transformers)); } public static CodeTransformer compose(Iterable<? extends CodeTransformer> transformers) { return new AutoValue_CompositeCodeTransformer(ImmutableList.copyOf(transformers)); } CompositeCodeTransformer() {} public abstract ImmutableList<CodeTransformer> transformers(); @Override public void apply(TreePath path, Context context, DescriptionListener listener) { for (CodeTransformer transformer : transformers()) { transformer.apply(path, context, listener); } } @Override public ImmutableClassToInstanceMap<Annotation> annotations() { return ImmutableClassToInstanceMap.of(); } }
1,861
33.481481
91
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/ErrorProneVersion.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; import com.google.common.base.Optional; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** The Error Prone version. */ public final class ErrorProneVersion { private static final String PROPERTIES_RESOURCE = "/META-INF/maven/com.google.errorprone/error_prone_core/pom.properties"; /** * Loads the Error Prone version. * * <p>This depends on the Maven build, and will always return {@code Optional.absent()} with other * build systems. */ public static Optional<String> loadVersionFromPom() { try (InputStream stream = ErrorProneVersion.class.getResourceAsStream(PROPERTIES_RESOURCE)) { if (stream == null) { return Optional.absent(); } Properties mavenProperties = new Properties(); mavenProperties.load(stream); return Optional.of(mavenProperties.getProperty("version")); } catch (IOException expected) { return Optional.absent(); } } private ErrorProneVersion() {} }
1,639
31.156863
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/BugCheckerInfo.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; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableSet.toImmutableSet; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.bugpatterns.BugChecker; import java.io.Serializable; import java.lang.annotation.Annotation; import java.lang.reflect.Modifier; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.stream.Stream; import javax.annotation.Nullable; /** * An accessor for information about a single bug checker, including the metadata in the check's * {@code @BugPattern} annotation and the class that implements the check. */ public class BugCheckerInfo implements Serializable { /** The BugChecker class. */ private final Class<? extends BugChecker> checker; /** * The canonical name of this check. Corresponds to the {@code name} attribute from its {@code * BugPattern} annotation. */ private final String canonicalName; /** * Additional identifiers for this check, to be checked for in @SuppressWarnings annotations. * Corresponds to the canonical name plus all {@code altName}s from its {@code BugPattern} * annotation. */ private final ImmutableSet<String> allNames; /** Set of String tags associated with the checker. */ private final ImmutableSet<String> tags; /** * The error message to print in compiler diagnostics when this check triggers. Corresponds to the * {@code summary} attribute from its {@code BugPattern}. */ private final String message; /** The default type of diagnostic (error or warning) to emit when this check triggers. */ private final SeverityLevel defaultSeverity; /** * The link URL to display in the diagnostic message when this check triggers. Computed from the * {@code link} and {@code linkType} attributes from its {@code BugPattern}. May be null if no * link should be displayed. */ private final String linkUrl; private final boolean supportsSuppressWarnings; /** * A set of suppression annotations for this check. Computed from the {@code * suppressionAnnotations} attributes from its {@code BugPattern}. May be empty if there are no * suppression annotations for this check. */ private final Set<Class<? extends Annotation>> customSuppressionAnnotations; /** True if the check can be disabled using command-line flags. */ private final boolean disableable; public static BugCheckerInfo create(Class<? extends BugChecker> checker) { BugPattern pattern = checkNotNull( checker.getAnnotation(BugPattern.class), "BugCheckers must be annotated with @BugPattern"); checkArgument( !(Modifier.isAbstract(checker.getModifiers()) || Modifier.isInterface(checker.getModifiers())), "%s must be a concrete class", checker); try { BugPatternValidator.validate(pattern); } catch (ValidationException e) { throw new IllegalStateException(e); } return new BugCheckerInfo(checker, pattern); } private BugCheckerInfo(Class<? extends BugChecker> checker, BugPattern pattern) { this(canonicalName(checker.getSimpleName(), pattern), checker, pattern); } private BugCheckerInfo( String canonicalName, Class<? extends BugChecker> checker, BugPattern pattern) { this( checker, canonicalName, ImmutableSet.<String>builder().add(canonicalName).add(pattern.altNames()).build(), pattern.summary(), pattern.severity(), createLinkUrl(canonicalName, pattern), Stream.of(pattern.suppressionAnnotations()).anyMatch(a -> isSuppressWarnings(a)), Stream.of(pattern.suppressionAnnotations()) .filter(a -> !isSuppressWarnings(a)) .collect(toImmutableSet()), ImmutableSet.copyOf(pattern.tags()), pattern.disableable()); } private BugCheckerInfo( Class<? extends BugChecker> checker, String canonicalName, ImmutableSet<String> allNames, String message, SeverityLevel defaultSeverity, String linkUrl, boolean supportsSuppressWarnings, Set<Class<? extends Annotation>> customSuppressionAnnotations, ImmutableSet<String> tags, boolean disableable) { this.checker = checker; this.canonicalName = canonicalName; this.allNames = allNames; this.message = message; this.defaultSeverity = defaultSeverity; this.linkUrl = linkUrl; this.supportsSuppressWarnings = supportsSuppressWarnings; this.customSuppressionAnnotations = customSuppressionAnnotations; this.tags = tags; this.disableable = disableable; } private static boolean isSuppressWarnings(Class<? extends Annotation> annotation) { return annotation.getSimpleName().equals("SuppressWarnings"); } /** * @return a BugCheckerInfo with the same information as this class, except that its default * severity is the passed in parameter. If this checker's current defaultSeverity is the same * as the argument, return this. */ public BugCheckerInfo withCustomDefaultSeverity(SeverityLevel defaultSeverity) { if (defaultSeverity == this.defaultSeverity) { return this; } return new BugCheckerInfo( checker, canonicalName, allNames, message, defaultSeverity, linkUrl, supportsSuppressWarnings, customSuppressionAnnotations, tags, disableable); } @Nullable private static String createLinkUrl(String canonicalName, BugPattern pattern) { switch (pattern.linkType()) { case AUTOGENERATED: return String.format("https://errorprone.info/bugpattern/%s", canonicalName); case CUSTOM: // annotation.link() must be provided. if (pattern.link().isEmpty()) { throw new IllegalStateException( "If linkType element of @BugPattern is CUSTOM, " + "a link element must also be provided."); } return pattern.link(); case NONE: return null; } throw new AssertionError( "Unexpected value for linkType element of @BugPattern: " + pattern.linkType()); } public String canonicalName() { return canonicalName; } public static String canonicalName(String className, BugPattern pattern) { if (!pattern.name().isEmpty()) { return pattern.name(); } return className; } public Set<String> allNames() { return allNames; } public String message() { return message; } public SeverityLevel defaultSeverity() { return defaultSeverity; } public SeverityLevel severity(Map<String, SeverityLevel> severities) { return firstNonNull(severities.get(canonicalName), defaultSeverity); } public String linkUrl() { return linkUrl; } public boolean supportsSuppressWarnings() { return supportsSuppressWarnings; } public Set<Class<? extends Annotation>> customSuppressionAnnotations() { return Collections.unmodifiableSet(customSuppressionAnnotations); } public boolean disableable() { return disableable; } public ImmutableSet<String> getTags() { return tags; } public Class<? extends BugChecker> checkerClass() { return checker; } @Override public int hashCode() { return checker.hashCode(); } @Override public boolean equals(Object o) { if (!(o instanceof BugCheckerInfo)) { return false; } return checker.equals(((BugCheckerInfo) o).checker); } @Override public String toString() { return canonicalName; } }
8,442
30.981061
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/AnnotationType.java
/* * Copyright 2011 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.matchers; import com.google.errorprone.VisitorState; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.tree.JCTree; /** * @author eaftan@google.com (Eddie Aftandilian) * @author pepstein@google.com (Peter Epstein) */ public class AnnotationType implements Matcher<AnnotationTree> { private final String annotationClassName; public AnnotationType(String annotationClassName) { this.annotationClassName = annotationClassName; } @Override public boolean matches(AnnotationTree annotationTree, VisitorState state) { Tree type = annotationTree.getAnnotationType(); if (type.getKind() == Tree.Kind.IDENTIFIER && type instanceof JCTree.JCIdent) { JCTree.JCIdent jcIdent = (JCTree.JCIdent) type; return jcIdent.sym.getQualifiedName().contentEquals(annotationClassName); } else if (type.getKind() == Tree.Kind.MEMBER_SELECT && type instanceof JCTree.JCFieldAccess) { JCTree.JCFieldAccess jcFieldAccess = (JCTree.JCFieldAccess) type; return jcFieldAccess.sym.getQualifiedName().contentEquals(annotationClassName); } else { return false; } } }
1,799
35
99
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/HasIdentifier.java
/* * Copyright 2012 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.matchers; import static com.google.common.base.MoreObjects.firstNonNull; import com.google.errorprone.VisitorState; import com.sun.source.tree.ClassTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.Tree; import com.sun.source.util.TreePathScanner; /** * Matches if the given matcher matches all of the identifiers under this syntax tree. * * @author alexloh@google.com (Alex Loh) */ public class HasIdentifier implements Matcher<Tree> { private final Matcher<IdentifierTree> nodeMatcher; public HasIdentifier(Matcher<IdentifierTree> nodeMatcher) { this.nodeMatcher = nodeMatcher; } @Override public boolean matches(Tree tree, VisitorState state) { Boolean matches = new HasIdentifierScanner(state, nodeMatcher).scan(state.getPath(), null); return firstNonNull(matches, false); } /** AST Visitor that matches identifiers in a Tree */ private static class HasIdentifierScanner extends TreePathScanner<Boolean, Void> { private Matcher<IdentifierTree> idMatcher; private VisitorState ancestorState; public HasIdentifierScanner(VisitorState ancestorState, Matcher<IdentifierTree> idMatcher) { this.ancestorState = ancestorState; this.idMatcher = idMatcher; } @Override public Boolean visitIdentifier(IdentifierTree node, Void v) { return idMatcher.matches(node, ancestorState.withPath(getCurrentPath())); } @Override public Boolean reduce(Boolean r1, Boolean r2) { return firstNonNull(r1, false) || firstNonNull(r2, false); } @Override public Boolean visitClass(ClassTree node, Void v) { return firstNonNull(super.visitClass(node, v), false); } } }
2,337
31.027397
96
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/package-info.java
/* * Copyright 2012 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. */ /** * A predicate DSL for matching javac AST nodes. This allows concise, readable declarative code for * describing a match, by composing generic-type-safe matchers on the inspected AST subtree. */ package com.google.errorprone.matchers;
850
37.681818
99
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/AnnotationMatcherUtils.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.matchers; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.Tree; import javax.annotation.Nullable; /** * Utilities for matching annotations. * * @author mwacker@google.com (Mike Wacker) */ public class AnnotationMatcherUtils { /** * Gets the value for an argument, or null if the argument does not exist. * * @param annotationTree the AST node for the annotation * @param name the name of the argument whose value to get * @return the value of the argument, or null if the argument does not exist */ @Nullable public static ExpressionTree getArgument(AnnotationTree annotationTree, String name) { for (ExpressionTree argumentTree : annotationTree.getArguments()) { if (argumentTree.getKind() != Tree.Kind.ASSIGNMENT) { continue; } AssignmentTree assignmentTree = (AssignmentTree) argumentTree; if (!assignmentTree.getVariable().toString().equals(name)) { continue; } ExpressionTree expressionTree = assignmentTree.getExpression(); return expressionTree; } return null; } // Static class. private AnnotationMatcherUtils() {} }
1,880
31.431034
88
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/Matchers.java
/* * Copyright 2011 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.matchers; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Iterables.getLast; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.common.collect.Streams.stream; import static com.google.errorprone.matchers.MethodVisibility.Visibility.PUBLIC; import static com.google.errorprone.suppliers.Suppliers.BOOLEAN_TYPE; import static com.google.errorprone.suppliers.Suppliers.INT_TYPE; import static com.google.errorprone.suppliers.Suppliers.JAVA_LANG_BOOLEAN_TYPE; import static com.google.errorprone.suppliers.Suppliers.STRING_TYPE; import static com.google.errorprone.suppliers.Suppliers.typeFromClass; import static com.google.errorprone.suppliers.Suppliers.typeFromString; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.isSubtype; import static com.google.errorprone.util.ASTHelpers.stripParentheses; import static java.util.Objects.requireNonNull; import static javax.lang.model.element.Modifier.STATIC; import com.google.common.base.VerifyException; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.errorprone.VisitorState; import com.google.errorprone.dataflow.nullnesspropagation.Nullness; import com.google.errorprone.matchers.ChildMultiMatcher.MatchType; import com.google.errorprone.matchers.MethodVisibility.Visibility; import com.google.errorprone.matchers.method.MethodMatchers; import com.google.errorprone.matchers.method.MethodMatchers.AnyMethodMatcher; import com.google.errorprone.matchers.method.MethodMatchers.ConstructorMatcher; import com.google.errorprone.matchers.method.MethodMatchers.InstanceMethodMatcher; import com.google.errorprone.matchers.method.MethodMatchers.StaticMethodMatcher; import com.google.errorprone.predicates.TypePredicate; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.suppliers.Suppliers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.AssertTree; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.BlockTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.ContinueTree; import com.sun.source.tree.EnhancedForLoopTree; import com.sun.source.tree.ExpressionStatementTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.LiteralTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.ReturnTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.SynchronizedTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.TypeCastTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; 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.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.TypeTag; import com.sun.tools.javac.processing.JavacProcessingEnvironment; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.util.Name; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.function.BiPredicate; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Stream; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.element.NestingKind; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; /** * Static factory methods which make the DSL read more fluently. Since matchers are run in a tight * loop during compilation, performance is important. When assembling a matcher from the DSL, it's * best to construct it only once, by saving the resulting matcher as a static variable for example. * * @author alexeagle@google.com (Alex Eagle) */ public class Matchers { private Matchers() {} /** A matcher that matches any AST node. */ public static <T extends Tree> Matcher<T> anything() { return (t, state) -> true; } /** A matcher that matches no AST node. */ public static <T extends Tree> Matcher<T> nothing() { return (t, state) -> false; } /** Matches an AST node iff it does not match the given matcher. */ public static <T extends Tree> Matcher<T> not(Matcher<T> matcher) { return (t, state) -> !matcher.matches(t, state); } /** * Compose several matchers together, such that the composite matches an AST node iff all the * given matchers do. */ @SafeVarargs public static <T extends Tree> Matcher<T> allOf(Matcher<? super T>... matchers) { return (t, state) -> { for (Matcher<? super T> matcher : matchers) { if (!matcher.matches(t, state)) { return false; } } return true; }; } /** * Compose several matchers together, such that the composite matches an AST node iff all the * given matchers do. */ public static <T extends Tree> Matcher<T> allOf(Iterable<? extends Matcher<? super T>> matchers) { return (t, state) -> { for (Matcher<? super T> matcher : matchers) { if (!matcher.matches(t, state)) { return false; } } return true; }; } /** * Compose several matchers together, such that the composite matches an AST node if any of the * given matchers do. */ public static <T extends Tree> Matcher<T> anyOf(Iterable<? extends Matcher<? super T>> matchers) { return (t, state) -> { for (Matcher<? super T> matcher : matchers) { if (matcher.matches(t, state)) { return true; } } return false; }; } @SafeVarargs public static <T extends Tree> Matcher<T> anyOf(Matcher<? super T>... matchers) { // IntelliJ claims it can infer <Matcher<? super T>>, but blaze can't (b/132970194). return anyOf(Arrays.<Matcher<? super T>>asList(matchers)); } /** Matches if an AST node is an instance of the given class. */ public static <T extends Tree> Matcher<T> isInstance(java.lang.Class<?> klass) { return (t, state) -> klass.isInstance(t); } /** Matches an AST node of a given kind, for example, an Annotation or a switch block. */ public static <T extends Tree> Matcher<T> kindIs(Kind kind) { return (tree, state) -> tree.getKind() == kind; } /** Matches an AST node of a given kind, for example, an Annotation or a switch block. */ public static <T extends Tree> Matcher<T> kindAnyOf(Set<Kind> kinds) { return (tree, state) -> kinds.contains(tree.getKind()); } /** Matches an AST node which is the same object reference as the given node. */ public static <T extends Tree> Matcher<T> isSame(Tree t) { return (tree, state) -> tree == t; } /** Matches a static method. */ public static StaticMethodMatcher staticMethod() { return MethodMatchers.staticMethod(); } /** Matches an instance method. */ public static InstanceMethodMatcher instanceMethod() { return MethodMatchers.instanceMethod(); } /** Matches a static or instance method. */ public static AnyMethodMatcher anyMethod() { return MethodMatchers.anyMethod(); } /** Matches a constructor. */ public static ConstructorMatcher constructor() { return MethodMatchers.constructor(); } /** * Match a Tree based solely on the Symbol produced by {@link ASTHelpers#getSymbol(Tree)}. * * <p>If {@code getSymbol} returns {@code null}, the matcher returns false instead of calling * {@code pred}. */ public static <T extends Tree> Matcher<T> symbolMatcher(BiPredicate<Symbol, VisitorState> pred) { return (tree, state) -> { Symbol sym = getSymbol(tree); return sym != null && pred.test(sym, state); }; } /** Matches an AST node that represents a non-static field. */ public static Matcher<ExpressionTree> isInstanceField() { return symbolMatcher( (symbol, state) -> symbol.getKind() == ElementKind.FIELD && !ASTHelpers.isStatic(symbol)); } /** Matches an AST node that represents a local variable or parameter. */ public static Matcher<ExpressionTree> isVariable() { return symbolMatcher( (symbol, state) -> symbol.getKind() == ElementKind.LOCAL_VARIABLE || symbol.getKind() == ElementKind.PARAMETER); } /** * Matches a compound assignment operator AST node which matches a given left-operand matcher, a * given right-operand matcher, and a specific compound assignment operator. * * @param operator Which compound assignment operator to match against. * @param leftOperandMatcher The matcher to apply to the left operand. * @param rightOperandMatcher The matcher to apply to the right operand. */ public static CompoundAssignment compoundAssignment( Kind operator, Matcher<ExpressionTree> leftOperandMatcher, Matcher<ExpressionTree> rightOperandMatcher) { Set<Kind> operators = new HashSet<>(1); operators.add(operator); return new CompoundAssignment(operators, leftOperandMatcher, rightOperandMatcher); } /** * Matches a compound assignment operator AST node which matches a given left-operand matcher, a * given right-operand matcher, and is one of a set of compound assignment operators. Does not * match compound assignment operators. * * @param operators Which compound assignment operators to match against. * @param receiverMatcher The matcher to apply to the receiver. * @param expressionMatcher The matcher to apply to the expression. */ public static CompoundAssignment compoundAssignment( Set<Kind> operators, Matcher<ExpressionTree> receiverMatcher, Matcher<ExpressionTree> expressionMatcher) { return new CompoundAssignment(operators, receiverMatcher, expressionMatcher); } /** * Matches when the receiver of an instance method is the same reference as a particular argument * to the method. For example, receiverSameAsArgument(1) would match {@code obj.method("", obj)} * * @param argNum The number of the argument to compare against (zero-based. */ public static Matcher<? super MethodInvocationTree> receiverSameAsArgument(int argNum) { return (t, state) -> { List<? extends ExpressionTree> args = t.getArguments(); if (args.size() <= argNum) { return false; } ExpressionTree arg = args.get(argNum); JCExpression methodSelect = (JCExpression) t.getMethodSelect(); if (methodSelect instanceof JCFieldAccess) { JCFieldAccess fieldAccess = (JCFieldAccess) methodSelect; return ASTHelpers.sameVariable(fieldAccess.getExpression(), arg); } else if (methodSelect instanceof JCIdent) { // A bare method call: "equals(foo)". Receiver is implicitly "this". return arg.toString().equals("this"); } return false; }; } public static Matcher<MethodInvocationTree> receiverOfInvocation( Matcher<ExpressionTree> expressionTreeMatcher) { return (methodInvocationTree, state) -> { ExpressionTree receiver = ASTHelpers.getReceiver(methodInvocationTree); return receiver != null && expressionTreeMatcher.matches(receiver, state); }; } /** * Matches if the given annotation matcher matches all of or any of the annotations on this tree * node. * * @param matchType Whether to match if the matchers match any of or all of the annotations on * this tree. * @param annotationMatcher The annotation matcher to use. */ public static <T extends Tree> MultiMatcher<T, AnnotationTree> annotations( MatchType matchType, Matcher<AnnotationTree> annotationMatcher) { return new AnnotationMatcher<>(matchType, annotationMatcher); } /** Matches a class in which any of/all of its constructors match the given constructorMatcher. */ public static MultiMatcher<ClassTree, MethodTree> constructor( MatchType matchType, Matcher<MethodTree> constructorMatcher) { return new ConstructorOfClass(matchType, constructorMatcher); } public static Matcher<MethodInvocationTree> argument( int position, Matcher<ExpressionTree> argumentMatcher) { return new MethodInvocationArgument(position, argumentMatcher); } /** Matches if the given matcher matches all of/any of the arguments to this method invocation. */ public static MultiMatcher<MethodInvocationTree, ExpressionTree> hasArguments( MatchType matchType, Matcher<ExpressionTree> argumentMatcher) { return new HasArguments(matchType, argumentMatcher); } /** * Matches an AST node if it is a method invocation and the given matchers match. * * @param methodSelectMatcher matcher identifying the method being called * @param matchType how to match method arguments with {@code methodArgumentMatcher} * @param methodArgumentMatcher matcher applied to each method argument */ public static Matcher<ExpressionTree> methodInvocation( Matcher<ExpressionTree> methodSelectMatcher, MatchType matchType, Matcher<ExpressionTree> methodArgumentMatcher) { return new MethodInvocation(methodSelectMatcher, matchType, methodArgumentMatcher); } /** * Matches an AST node if it is a method invocation and the method select matches {@code * methodSelectMatcher}. Ignores any arguments. */ public static Matcher<ExpressionTree> methodInvocation( Matcher<ExpressionTree> methodSelectMatcher) { return (expressionTree, state) -> { if (!(expressionTree instanceof MethodInvocationTree)) { return false; } MethodInvocationTree tree = (MethodInvocationTree) expressionTree; return methodSelectMatcher.matches(tree.getMethodSelect(), state); }; } public static Matcher<MethodInvocationTree> argumentCount(int argumentCount) { return (t, state) -> t.getArguments().size() == argumentCount; } /** * Matches an AST node if its parent node is matched by the given matcher. For example, {@code * parentNode(kindIs(Kind.RETURN))} would match the {@code this} expression in {@code return * this;} */ public static <T extends Tree> Matcher<T> parentNode(Matcher<Tree> treeMatcher) { return (tree, state) -> { TreePath parent = requireNonNull(state.getPath().getParentPath()); return treeMatcher.matches(parent.getLeaf(), state.withPath(parent)); }; } /** * Matches an AST node if its type is a subtype of the given type. * * @param typeStr a string representation of the type, e.g., "java.util.AbstractList" */ public static <T extends Tree> Matcher<T> isSubtypeOf(String typeStr) { return new IsSubtypeOf<>(typeStr); } /** * Matches an AST node if its type is a subtype of the given type. * * @param type the type to check against */ public static <T extends Tree> Matcher<T> isSubtypeOf(Supplier<Type> type) { return new IsSubtypeOf<>(type); } /** * Matches an AST node if its type is a subtype of the given type. * * @param clazz a class representation of the type, e.g., Action.class. */ public static <T extends Tree> Matcher<T> isSubtypeOf(Class<?> clazz) { return new IsSubtypeOf<>(typeFromClass(clazz)); } /** Matches an AST node if it has the same erased type as the given type. */ public static <T extends Tree> Matcher<T> isSameType(Supplier<Type> type) { return new IsSameType<>(type); } /** Matches an AST node if it has the same erased type as the given type. */ public static <T extends Tree> Matcher<T> isSameType(String typeString) { return new IsSameType<>(typeString); } /** Matches an AST node if it has the same erased type as the given class. */ public static <T extends Tree> Matcher<T> isSameType(Class<?> clazz) { return new IsSameType<>(typeFromClass(clazz)); } /** * Match a Tree based solely on the type produced by {@link ASTHelpers#getType(Tree)}. * * <p>If {@code getType} returns {@code null}, the matcher returns false instead of calling {@code * pred}. */ public static <T extends Tree> Matcher<T> typePredicateMatcher(TypePredicate pred) { return (tree, state) -> { Type type = getType(tree); return type != null && pred.apply(type, state); }; } /** Matches an AST node if its type is an array type. */ public static <T extends Tree> Matcher<T> isArrayType() { return typePredicateMatcher((type, state) -> state.getTypes().isArray(type)); } /** Matches an AST node if its type is a primitive array type. */ public static <T extends Tree> Matcher<T> isPrimitiveArrayType() { return typePredicateMatcher( (type, state) -> state.getTypes().isArray(type) && state.getTypes().elemtype(type).isPrimitive()); } /** Matches an AST node if its type is a primitive type. */ public static <T extends Tree> Matcher<T> isPrimitiveType() { return typePredicateMatcher((type, state) -> type.isPrimitive()); } /** Matches an AST node if its type is either a primitive type or a {@code void} type. */ public static <T extends Tree> Matcher<T> isPrimitiveOrVoidType() { return typePredicateMatcher((type, state) -> type.isPrimitiveOrVoid()); } /** Matches an AST node if its type is a {@code void} type. */ public static <T extends Tree> Matcher<T> isVoidType() { return typePredicateMatcher( (type, state) -> state.getTypes().isSameType(type, state.getSymtab().voidType)); } /** * Matches an AST node if its type is a primitive type, or a boxed version of a primitive type. */ public static <T extends Tree> Matcher<T> isPrimitiveOrBoxedPrimitiveType() { return typePredicateMatcher( (type, state) -> state.getTypes().unboxedTypeOrType(type).isPrimitive()); } /** Matches an AST node if its type is a boxed primitive type. */ public static Matcher<ExpressionTree> isBoxedPrimitiveType() { return typePredicateMatcher( (type, state) -> !state.getTypes().isSameType(state.getTypes().unboxedType(type), Type.noType)); } /** Matches an AST node which is enclosed by a block node that matches the given matcher. */ public static <T extends Tree> Enclosing.Block<T> enclosingBlock(Matcher<BlockTree> matcher) { return new Enclosing.Block<>(matcher); } /** Matches an AST node which is enclosed by a class node that matches the given matcher. */ public static <T extends Tree> Enclosing.Class<T> enclosingClass(Matcher<ClassTree> matcher) { return new Enclosing.Class<>(matcher); } /** Matches an AST node which is enclosed by a method node that matches the given matcher. */ public static <T extends Tree> Enclosing.Method<T> enclosingMethod(Matcher<MethodTree> matcher) { return new Enclosing.Method<>(matcher); } /** * Matches an AST node that is enclosed by some node that matches the given matcher. * * <p>TODO(eaftan): This could be used instead of enclosingBlock and enclosingClass. */ public static Matcher<Tree> enclosingNode(Matcher<Tree> matcher) { return (t, state) -> { TreePath path = state.getPath().getParentPath(); while (path != null) { Tree node = path.getLeaf(); state = state.withPath(path); if (matcher.matches(node, state)) { return true; } path = path.getParentPath(); } return false; }; } private static boolean siblingStatement( int offset, Matcher<StatementTree> matcher, StatementTree statement, VisitorState state) { // TODO(cushon): walking arbitrarily far up to find a block tree often isn't what we want TreePath blockPath = state.findPathToEnclosing(BlockTree.class); if (blockPath == null) { return false; } BlockTree block = (BlockTree) blockPath.getLeaf(); List<? extends StatementTree> statements = block.getStatements(); int idx = statements.indexOf(statement); if (idx == -1) { return false; } idx += offset; if (idx < 0 || idx >= statements.size()) { return false; } StatementTree sibling = statements.get(idx); return matcher.matches(sibling, state.withPath(new TreePath(blockPath, sibling))); } /** * Matches a statement AST node if the following statement in the enclosing block matches the * given matcher. */ public static <T extends StatementTree> Matcher<T> nextStatement(Matcher<StatementTree> matcher) { return (statement, state) -> siblingStatement(/* offset= */ 1, matcher, statement, state); } /** * Matches a statement AST node if the previous statement in the enclosing block matches the given * matcher. */ public static <T extends StatementTree> Matcher<T> previousStatement( Matcher<StatementTree> matcher) { return (statement, state) -> siblingStatement(/* offset= */ -1, matcher, statement, state); } /** Matches a statement AST node if the statement is the last statement in the block. */ public static Matcher<StatementTree> isLastStatementInBlock() { return (statement, state) -> { // TODO(cushon): walking arbitrarily far up to find a block tree often isn't what we want TreePath blockPath = state.findPathToEnclosing(BlockTree.class); if (blockPath == null) { return false; } BlockTree block = (BlockTree) blockPath.getLeaf(); return getLast(block.getStatements()).equals(statement); }; } /** Matches an AST node if it is a null literal. */ public static Matcher<ExpressionTree> nullLiteral() { return (tree, state) -> { return tree.getKind() == Kind.NULL_LITERAL; }; } /** Matches an AST node if it is a literal other than null. */ public static Matcher<ExpressionTree> nonNullLiteral() { return (tree, state) -> { switch (tree.getKind()) { case MEMBER_SELECT: return ((MemberSelectTree) tree).getIdentifier().contentEquals("class"); case INT_LITERAL: case LONG_LITERAL: case FLOAT_LITERAL: case DOUBLE_LITERAL: case BOOLEAN_LITERAL: case CHAR_LITERAL: // fall through case STRING_LITERAL: return true; default: return false; } }; } /** * Matches a Literal AST node if it is a string literal with the given value. For example, {@code * stringLiteral("thing")} matches the literal {@code "thing"} */ public static Matcher<ExpressionTree> stringLiteral(String value) { return new StringLiteral(value); } /** * Matches a Literal AST node if it is a string literal which matches the given {@link Pattern}. * * @see #stringLiteral(String) */ public static Matcher<ExpressionTree> stringLiteral(Pattern pattern) { return new StringLiteral(pattern); } public static Matcher<ExpressionTree> booleanLiteral(boolean value) { return (expressionTree, state) -> expressionTree.getKind() == Kind.BOOLEAN_LITERAL && value == (Boolean) (((LiteralTree) expressionTree).getValue()); } /** * Matches the boolean constant ({@link Boolean#TRUE} or {@link Boolean#FALSE}) corresponding to * the given value. */ public static Matcher<ExpressionTree> booleanConstant(boolean value) { return (expressionTree, state) -> { if (expressionTree instanceof JCFieldAccess) { Symbol symbol = getSymbol(expressionTree); if (ASTHelpers.isStatic(symbol) && state.getTypes().unboxedTypeOrType(symbol.type).getTag() == TypeTag.BOOLEAN) { if (value) { return symbol.getSimpleName().contentEquals("TRUE"); } else { return symbol.getSimpleName().contentEquals("FALSE"); } } } return false; }; } /** * Ignores any number of parenthesis wrapping an expression and then applies the passed matcher to * that expression. For example, the passed matcher would be applied to {@code value} in {@code * (((value)))}. */ public static Matcher<ExpressionTree> ignoreParens(Matcher<ExpressionTree> innerMatcher) { return (tree, state) -> innerMatcher.matches(stripParentheses(tree), state); } public static Matcher<ExpressionTree> intLiteral(int value) { return (tree, state) -> { return tree.getKind() == Kind.INT_LITERAL && value == ((Integer) ((LiteralTree) tree).getValue()); }; } public static Matcher<ExpressionTree> classLiteral(Matcher<? super ExpressionTree> classMatcher) { return (tree, state) -> { if (tree.getKind() == Kind.MEMBER_SELECT) { MemberSelectTree select = (MemberSelectTree) tree; return select.getIdentifier().contentEquals("class") && classMatcher.matches(select.getExpression(), state); } return false; }; } /** * Matches an Annotation AST node if the argument to the annotation with the given name has a * value which matches the given matcher. For example, {@code hasArgumentWithValue("value", * stringLiteral("one"))} matches {@code @Thing("one")} or {@code @Thing({"one", "two"})} or * {@code @Thing(value = "one")} */ public static Matcher<AnnotationTree> hasArgumentWithValue( String argumentName, Matcher<ExpressionTree> valueMatcher) { return new AnnotationHasArgumentWithValue(argumentName, valueMatcher); } /** Matches an Annotation AST node if an argument to the annotation does not exist. */ public static Matcher<AnnotationTree> doesNotHaveArgument(String argumentName) { return new AnnotationDoesNotHaveArgument(argumentName); } public static Matcher<AnnotationTree> isType(String annotationClassName) { return new AnnotationType(annotationClassName); } /** * Matches a {@link MethodInvocation} when the arguments at the two given indices are both the * same variable, as determined by {@link ASTHelpers#sameVariable}. * * @param index1 the index of the first actual parameter to test * @param index2 the index of the second actual parameter to test * @throws IndexOutOfBoundsException if the given indices are invalid */ public static Matcher<? super MethodInvocationTree> sameArgument(int index1, int index2) { return (tree, state) -> { List<? extends ExpressionTree> args = tree.getArguments(); return ASTHelpers.sameVariable(args.get(index1), args.get(index2)); }; } /** * Determines whether an expression has an annotation of the given type. This includes annotations * inherited from superclasses due to @Inherited. * * @param annotationClass the binary class name of the annotation (e.g. * "javax.annotation.Nullable", or "some.package.OuterClassName$InnerClassName") */ public static <T extends Tree> Matcher<T> hasAnnotation(String annotationClass) { Supplier<Set<Name>> name = VisitorState.memoize( state -> ImmutableSet.of(state.binaryNameFromClassname(annotationClass))); return (T tree, VisitorState state) -> !ASTHelpers.annotationsAmong(ASTHelpers.getDeclaredSymbol(tree), name.get(state), state) .isEmpty(); } /** * Determines if an expression has an annotation referred to by the given mirror. Accounts for * binary names and annotations inherited due to @Inherited. * * @param annotationMirror mirror referring to the annotation type */ public static Matcher<Tree> hasAnnotation(TypeMirror annotationMirror) { String annotationName = annotationMirror.toString(); return (Tree tree, VisitorState state) -> { JavacProcessingEnvironment javacEnv = JavacProcessingEnvironment.instance(state.context); TypeElement typeElem = (TypeElement) javacEnv.getTypeUtils().asElement(annotationMirror); String name; if (typeElem != null) { // Get the binary name if possible ($ to separate nested members). See b/36160747 name = javacEnv.getElementUtils().getBinaryName(typeElem).toString(); } else { name = annotationName; } return ASTHelpers.hasAnnotation(ASTHelpers.getDeclaredSymbol(tree), name, state); }; } /** * Determines whether an expression has an annotation with the given simple name. This does not * include annotations inherited from superclasses due to @Inherited. * * @param simpleName the simple name of the annotation (e.g. "Nullable") */ public static <T extends Tree> Matcher<T> hasAnnotationWithSimpleName(String simpleName) { return (tree, state) -> ASTHelpers.hasDirectAnnotationWithSimpleName( ASTHelpers.getDeclaredSymbol(tree), simpleName); } /** * Determines whether an expression refers to a symbol that has an annotation of the given type. * This includes annotations inherited from superclasses due to @Inherited. * * @param annotationClass the binary class name of the annotation (e.g. * "javax.annotation.Nullable", or "some.package.OuterClassName$InnerClassName") */ public static <T extends Tree> Matcher<T> symbolHasAnnotation(String annotationClass) { return symbolMatcher( (symbol, state) -> ASTHelpers.hasAnnotation(symbol, annotationClass, state)); } /** * Determines whether an expression has an annotation of the given class. This includes * annotations inherited from superclasses due to @Inherited. * * @param inputClass The class of the annotation to look for (e.g, Produces.class). */ public static <T extends Tree> Matcher<T> hasAnnotation(Class<? extends Annotation> inputClass) { return (tree, state) -> ASTHelpers.hasAnnotation(ASTHelpers.getDeclaredSymbol(tree), inputClass, state); } /** * Determines whether an expression refers to a symbol that has an annotation of the given type. * This includes annotations inherited from superclasses due to @Inherited. * * @param inputClass The class of the annotation to look for (e.g, Produces.class). */ public static <T extends Tree> Matcher<T> symbolHasAnnotation( Class<? extends Annotation> inputClass) { return (tree, state) -> ASTHelpers.hasAnnotation(getSymbol(tree), inputClass, state); } /** * Matches if a method or any method it overrides has an annotation of the given type. JUnit 4's * {@code @Test}, {@code @Before}, and {@code @After} annotations behave this way. * * @param annotationClass the binary class name of the annotation (e.g. * "javax.annotation.Nullable", or "some.package.OuterClassName$InnerClassName") */ public static Matcher<MethodTree> hasAnnotationOnAnyOverriddenMethod(String annotationClass) { return (tree, state) -> { MethodSymbol methodSym = getSymbol(tree); if (methodSym == null) { return false; } if (ASTHelpers.hasAnnotation(methodSym, annotationClass, state)) { return true; } for (MethodSymbol method : ASTHelpers.findSuperMethods(methodSym, state.getTypes())) { if (ASTHelpers.hasAnnotation(method, annotationClass, state)) { return true; } } return false; }; } /** Matches a method invocation that is known to never return null. */ public static Matcher<ExpressionTree> methodReturnsNonNull() { return anyOf( instanceMethod().onDescendantOf("java.lang.Object").named("toString"), instanceMethod().onExactClass("java.lang.String"), staticMethod().onClass("java.lang.String"), instanceMethod().onExactClass("java.util.StringTokenizer").named("nextToken")); } public static Matcher<MethodTree> methodReturns(Matcher<? super Tree> returnTypeMatcher) { return (methodTree, state) -> { Tree returnTree = methodTree.getReturnType(); // Constructors have no return type. return returnTree != null && returnTypeMatcher.matches(returnTree, state); }; } public static Matcher<MethodTree> methodReturns(Supplier<Type> returnType) { return methodReturns(isSameType(returnType)); } /** Match a method that returns a non-primitive type. */ public static Matcher<MethodTree> methodReturnsNonPrimitiveType() { return methodReturns(not(isPrimitiveOrVoidType())); } /** * Match a method declaration with a specific name. * * @param methodName The name of the method to match, e.g., "equals" */ public static Matcher<MethodTree> methodIsNamed(String methodName) { return (methodTree, state) -> methodTree.getName().contentEquals(methodName); } /** * Match a method declaration that starts with a given string. * * @param prefix The prefix. */ public static Matcher<MethodTree> methodNameStartsWith(String prefix) { return (methodTree, state) -> methodTree.getName().toString().startsWith(prefix); } /** * Match a method declaration with a specific enclosing class and method name. * * @param className The fully-qualified name of the enclosing class, e.g. * "com.google.common.base.Preconditions" * @param methodName The name of the method to match, e.g., "checkNotNull" */ public static Matcher<MethodTree> methodWithClassAndName(String className, String methodName) { return (methodTree, state) -> getSymbol(methodTree).getEnclosingElement().getQualifiedName().contentEquals(className) && methodTree.getName().contentEquals(methodName); } /** * Matches an AST node that represents a method declaration, based on the list of * variableMatchers. Applies the variableMatcher at index n to the parameter at index n and * returns true iff they all match. Returns false if the number of variableMatchers provided does * not match the number of parameters. * * <p>If you pass no variableMatchers, this will match methods with no parameters. * * @param variableMatcher an array of matchers to apply to the parameters of the method */ @SafeVarargs public static Matcher<MethodTree> methodHasParameters(Matcher<VariableTree>... variableMatcher) { return methodHasParameters(ImmutableList.copyOf(variableMatcher)); } /** Matches an AST node that represents a method declaration with no parameters. */ public static Matcher<MethodTree> methodHasNoParameters() { return methodHasParameters(ImmutableList.of()); } /** * Matches an AST node that represents a method declaration, based on the list of * variableMatchers. Applies the variableMatcher at index n to the parameter at index n and * returns true iff they all match. Returns false if the number of variableMatchers provided does * not match the number of parameters. * * <p>If you pass no variableMatchers, this will match methods with no parameters. * * @param variableMatcher a list of matchers to apply to the parameters of the method */ public static Matcher<MethodTree> methodHasParameters( List<Matcher<VariableTree>> variableMatcher) { return (methodTree, state) -> { if (methodTree.getParameters().size() != variableMatcher.size()) { return false; } int paramIndex = 0; for (Matcher<VariableTree> eachVariableMatcher : variableMatcher) { if (!eachVariableMatcher.matches(methodTree.getParameters().get(paramIndex++), state)) { return false; } } return true; }; } /** Matches if the given matcher matches all of/any of the parameters to this method. */ public static MultiMatcher<MethodTree, VariableTree> methodHasParameters( MatchType matchType, Matcher<VariableTree> parameterMatcher) { return new MethodHasParameters(matchType, parameterMatcher); } public static Matcher<MethodTree> methodHasVisibility(Visibility visibility) { return new MethodVisibility(visibility); } public static Matcher<MethodTree> methodIsConstructor() { return (methodTree, state) -> getSymbol(methodTree).isConstructor(); } /** * Matches a constructor declaration in a specific enclosing class. * * @param className The fully-qualified name of the enclosing class, e.g. * "com.google.common.base.Preconditions" */ public static Matcher<MethodTree> constructorOfClass(String className) { return (methodTree, state) -> { Symbol symbol = getSymbol(methodTree); return symbol.getEnclosingElement().getQualifiedName().contentEquals(className) && symbol.isConstructor(); }; } /** * Matches a class in which at least one method matches the given methodMatcher. * * @param methodMatcher A matcher on MethodTrees to run against all methods in this class. * @return True if some method in the class matches the given methodMatcher. */ public static Matcher<ClassTree> hasMethod(Matcher<MethodTree> methodMatcher) { return (t, state) -> { for (Tree member : t.getMembers()) { if (member instanceof MethodTree && methodMatcher.matches((MethodTree) member, state)) { return true; } } return false; }; } /** * Matches on the type of a VariableTree AST node. * * @param treeMatcher A matcher on the type of the variable. */ public static Matcher<VariableTree> variableType(Matcher<Tree> treeMatcher) { return (variableTree, state) -> treeMatcher.matches(variableTree.getType(), state); } /** * Matches on the initializer of a VariableTree AST node. * * @param expressionTreeMatcher A matcher on the initializer of the variable. */ public static Matcher<VariableTree> variableInitializer( Matcher<ExpressionTree> expressionTreeMatcher) { return (variableTree, state) -> { ExpressionTree initializer = variableTree.getInitializer(); return initializer != null && expressionTreeMatcher.matches(initializer, state); }; } /** * Matches if a {@link VariableTree} is a field declaration, as opposed to a local variable, enum * constant, parameter to a method, etc. */ public static Matcher<VariableTree> isField() { return (variableTree, state) -> getSymbol(variableTree).getKind() == ElementKind.FIELD; } /** Matches if a {@link ClassTree} is an enum declaration. */ public static Matcher<ClassTree> isEnum() { return (classTree, state) -> getSymbol(classTree).getKind() == ElementKind.ENUM; } /** * Matches an class based on whether it is nested in another class or method. * * @param kind The kind of nesting to match, eg ANONYMOUS, LOCAL, MEMBER, TOP_LEVEL */ public static Matcher<ClassTree> nestingKind(NestingKind kind) { return (classTree, state) -> kind == getSymbol(classTree).getNestingKind(); } /** * Matches a binary tree if the given matchers match the operands in either order. That is, * returns true if either: matcher1 matches the left operand and matcher2 matches the right * operand or matcher2 matches the left operand and matcher1 matches the right operand */ public static Matcher<BinaryTree> binaryTree( Matcher<ExpressionTree> matcher1, Matcher<ExpressionTree> matcher2) { return (t, state) -> null != ASTHelpers.matchBinaryTree(t, Arrays.asList(matcher1, matcher2), state); } /** * Matches any AST that contains an identifier with a certain property. This matcher can be used, * for instance, to locate identifiers with a certain name or which is defined in a certain class. * * @param nodeMatcher Which identifiers to look for */ public static Matcher<Tree> hasIdentifier(Matcher<IdentifierTree> nodeMatcher) { return new HasIdentifier(nodeMatcher); } /** Returns true if the Tree node has the expected {@code Modifier}. */ public static <T extends Tree> Matcher<T> hasModifier(Modifier modifier) { return (tree, state) -> { Symbol sym = getSymbol(tree); return sym != null && sym.getModifiers().contains(modifier); }; } /** Matches an AST node which is an expression yielding the indicated static field access. */ public static Matcher<ExpressionTree> staticFieldAccess() { return allOf(isStatic(), isSymbol(VarSymbol.class)); } /** Matches an AST node that is static. */ public static <T extends Tree> Matcher<T> isStatic() { return (tree, state) -> { Symbol sym = getSymbol(tree); return sym != null && ASTHelpers.isStatic(sym); }; } /** Matches an AST node that is transient. */ public static <T extends Tree> Matcher<T> isTransient() { return (tree, state) -> getSymbol(tree).getModifiers().contains(Modifier.TRANSIENT); } /** * Matches a {@code throw} statement where the thrown item is matched by the passed {@code * thrownMatcher}. */ public static Matcher<StatementTree> throwStatement( Matcher<? super ExpressionTree> thrownMatcher) { return new Throws(thrownMatcher); } /** * Matches a {@code return} statement where the returned expression is matched by the passed * {@code returnedMatcher}. */ public static Matcher<StatementTree> returnStatement( Matcher<? super ExpressionTree> returnedMatcher) { return new Returns(returnedMatcher); } /** * Matches an {@code assert} statement where the condition is matched by the passed {@code * conditionMatcher}. */ public static Matcher<StatementTree> assertStatement(Matcher<ExpressionTree> conditionMatcher) { return new Asserts(conditionMatcher); } /** Matches a {@code continue} statement. */ public static Matcher<StatementTree> continueStatement() { return (statementTree, state) -> statementTree instanceof ContinueTree; } /** Matches an {@link ExpressionStatementTree} based on its {@link ExpressionTree}. */ public static Matcher<StatementTree> expressionStatement(Matcher<ExpressionTree> matcher) { return (statementTree, state) -> statementTree instanceof ExpressionStatementTree && matcher.matches(((ExpressionStatementTree) statementTree).getExpression(), state); } static Matcher<Tree> isSymbol(java.lang.Class<? extends Symbol> symbolClass) { return new IsSymbol(symbolClass); } /** * Converts the given matcher to one that can be applied to any tree but is only executed when run * on a tree of {@code type} and returns {@code false} for all other tree types. */ public static <S extends T, T extends Tree> Matcher<T> toType( Class<S> type, Matcher<? super S> matcher) { return (tree, state) -> type.isInstance(tree) && matcher.matches(type.cast(tree), state); } /** Matches if this Tree is enclosed by either a synchronized block or a synchronized method. */ public static <T extends Tree> Matcher<T> inSynchronized() { return (tree, state) -> { SynchronizedTree synchronizedTree = ASTHelpers.findEnclosingNode(state.getPath(), SynchronizedTree.class); if (synchronizedTree != null) { return true; } MethodTree methodTree = ASTHelpers.findEnclosingNode(state.getPath(), MethodTree.class); return methodTree != null && methodTree.getModifiers().getFlags().contains(Modifier.SYNCHRONIZED); }; } /** * Matches if this ExpressionTree refers to the same variable as the one passed into the matcher. */ public static Matcher<ExpressionTree> sameVariable(ExpressionTree expr) { return (tree, state) -> ASTHelpers.sameVariable(tree, expr); } /** * Matches if the expression is provably non-null. * * <p>Uses the Checker Framework dataflow implementation to determine nullness. Be careful about * using this in performance-critical code. */ public static Matcher<ExpressionTree> isNonNullUsingDataflow() { return new NullnessMatcher(Nullness.NONNULL); } /** * @deprecated use {@link #isNonNullUsingDataflow} instead. */ @Deprecated public static Matcher<ExpressionTree> isNonNull() { return isNonNullUsingDataflow(); } /** * Matches if the expression is provably null. * * <p>Uses the Checker Framework dataflow implementation to determine nullness. Be careful about * using this in performance-critical code. * * <p>Prefer {@code kindIs(NULL_LITERAL)} unless you really need dataflow. */ public static Matcher<ExpressionTree> isNullUsingDataflow() { return new NullnessMatcher(Nullness.NULL); } /** * @deprecated use {@link #isNullUsingDataflow} instead. */ @Deprecated public static Matcher<ExpressionTree> isNull() { return isNullUsingDataflow(); } /** * Matches an enhanced for loop if all the given matchers match. * * @param variableMatcher The matcher to apply to the variable. * @param expressionMatcher The matcher to apply to the expression. * @param statementMatcher The matcher to apply to the statement. */ public static Matcher<EnhancedForLoopTree> enhancedForLoop( Matcher<VariableTree> variableMatcher, Matcher<ExpressionTree> expressionMatcher, Matcher<StatementTree> statementMatcher) { return (t, state) -> variableMatcher.matches(t.getVariable(), state) && expressionMatcher.matches(t.getExpression(), state) && statementMatcher.matches(t.getStatement(), state); } /** Matches if the given tree is inside a loop. */ public static <T extends Tree> Matcher<T> inLoop() { return (tree, state) -> { TreePath path = state.getPath().getParentPath(); while (path != null) { Tree node = path.getLeaf(); switch (node.getKind()) { case METHOD: case CLASS: return false; case WHILE_LOOP: case FOR_LOOP: case ENHANCED_FOR_LOOP: case DO_WHILE_LOOP: return true; default: // continue below } path = path.getParentPath(); } return false; }; } /** * Matches an assignment operator AST node if both of the given matchers match. * * @param variableMatcher The matcher to apply to the variable. * @param expressionMatcher The matcher to apply to the expression. */ public static Matcher<AssignmentTree> assignment( Matcher<ExpressionTree> variableMatcher, Matcher<? super ExpressionTree> expressionMatcher) { return (t, state) -> variableMatcher.matches(t.getVariable(), state) && expressionMatcher.matches(t.getExpression(), state); } /** * Matches a type cast AST node if both of the given matchers match. * * @param typeMatcher The matcher to apply to the type. * @param expressionMatcher The matcher to apply to the expression. */ public static Matcher<TypeCastTree> typeCast( Matcher<Tree> typeMatcher, Matcher<ExpressionTree> expressionMatcher) { return (t, state) -> typeMatcher.matches(t.getType(), state) && expressionMatcher.matches(t.getExpression(), state); } /** * Matches an assertion AST node if the given matcher matches its condition. * * @param conditionMatcher The matcher to apply to the condition in the assertion, e.g. in "assert * false", the "false" part of the statement */ public static Matcher<AssertTree> assertionWithCondition( Matcher<ExpressionTree> conditionMatcher) { return (tree, state) -> conditionMatcher.matches(tree.getCondition(), state); } /** * Applies the given matcher recursively to all descendants of an AST node, and matches if any * matching descendant node is found. * * @param treeMatcher The matcher to apply recursively to the tree. */ public static Matcher<Tree> contains(Matcher<Tree> treeMatcher) { return new Contains(treeMatcher); } /** * Applies the given matcher recursively to all descendants of an AST node, and matches if any * matching descendant node is found. * * @param clazz The type of node to be matched. * @param treeMatcher The matcher to apply recursively to the tree. */ public static <T extends Tree, V extends Tree> Matcher<T> contains( Class<? extends V> clazz, Matcher<? super V> treeMatcher) { Matcher<Tree> contains = new Contains(toType(clazz, treeMatcher)); return contains::matches; } /** * Matches if the method accepts the given number of arguments. * * @param arity the number of arguments the method should accept */ public static Matcher<MethodTree> methodHasArity(int arity) { return (methodTree, state) -> methodTree.getParameters().size() == arity; } /** * Matches any node that is directly an implementation, but not extension, of the given Class. * * <p>E.x. {@code class C implements I} will match, but {@code class C extends A} will not. * * <p>Additionally, this will only match <i>direct</i> implementations of interfaces. E.g. the * following will not match: * * <p>{@code interface I1 {} interface I2 extends I1 {} class C implements I2 {} ... * isDirectImplementationOf(I1).match(\/*class tree for C*\/); // will not match } */ public static Matcher<ClassTree> isDirectImplementationOf(String clazz) { Matcher<Tree> isProvidedType = isSameType(clazz); return new IsDirectImplementationOf(isProvidedType); } /** Matches any node that is a direct extension of the given class. */ public static Matcher<ClassTree> isExtensionOf(String clazz) { Matcher<Tree> isProvidedType = isSameType(clazz); return new IsExtensionOf(isProvidedType); } @SafeVarargs public static Matcher<Tree> hasAnyAnnotation(Class<? extends Annotation>... annotations) { ArrayList<Matcher<Tree>> matchers = new ArrayList<>(annotations.length); for (Class<? extends Annotation> annotation : annotations) { matchers.add(hasAnnotation(annotation)); } return anyOf(matchers); } public static Matcher<Tree> hasAnyAnnotation(List<? extends TypeMirror> mirrors) { ArrayList<Matcher<Tree>> matchers = new ArrayList<>(mirrors.size()); for (TypeMirror mirror : mirrors) { matchers.add(hasAnnotation(mirror)); } return anyOf(matchers); } private static final ImmutableSet<Kind> DECLARATION = Sets.immutableEnumSet(Kind.LAMBDA_EXPRESSION, Kind.CLASS, Kind.ENUM, Kind.INTERFACE); private static boolean isDeclaration(Kind kind) { return DECLARATION.contains(kind) || kind.name().equals("RECORD"); } public static boolean methodCallInDeclarationOfThrowingRunnable(VisitorState state) { return stream(state.getPath()) // Find the nearest definitional context for this method invocation // (i.e.: the nearest surrounding class or lambda) .filter(t -> isDeclaration(t.getKind())) .findFirst() .map(t -> isThrowingFunctionalInterface(getType(t), state)) .orElseThrow(VerifyException::new); } public static boolean isThrowingFunctionalInterface(Type clazzType, VisitorState state) { return CLASSES_CONSIDERED_THROWING.get(state).stream() .anyMatch(t -> isSubtype(clazzType, t, state)); } /** * {@link FunctionalInterface}s that are generally used as a lambda expression for 'a block of * code that's going to fail', e.g.: * * <p>{@code assertThrows(FooException.class, () -> myCodeThatThrowsAnException()); * errorCollector.checkThrows(FooException.class, () -> myCodeThatThrowsAnException()); } */ // TODO(glorioso): Consider a meta-annotation like @LikelyToThrow instead/in addition? private static final Supplier<ImmutableSet<Type>> CLASSES_CONSIDERED_THROWING = VisitorState.memoize( state -> Stream.of( "org.junit.function.ThrowingRunnable", "org.junit.jupiter.api.function.Executable", "org.assertj.core.api.ThrowableAssert$ThrowingCallable", "com.google.devtools.build.lib.testutil.MoreAsserts$ThrowingRunnable", "com.google.gerrit.testing.GerritJUnit$ThrowingRunnable", "com.google.truth.ExpectFailure.AssertionCallback", "com.google.truth.ExpectFailure.DelegatedAssertionCallback", "com.google.truth.ExpectFailure.StandardSubjectBuilderCallback", "com.google.truth.ExpectFailure.SimpleSubjectBuilderCallback") .map(state::getTypeFromString) .filter(Objects::nonNull) .collect(toImmutableSet())); private static class IsDirectImplementationOf extends ChildMultiMatcher<ClassTree, Tree> { public IsDirectImplementationOf(Matcher<Tree> classMatcher) { super(MatchType.AT_LEAST_ONE, classMatcher); } @Override protected Iterable<? extends Tree> getChildNodes(ClassTree classTree, VisitorState state) { return classTree.getImplementsClause(); } } private static class IsExtensionOf extends ChildMultiMatcher<ClassTree, Tree> { IsExtensionOf(Matcher<Tree> classMatcher) { super(MatchType.AT_LEAST_ONE, classMatcher); } @Override protected Iterable<? extends Tree> getChildNodes(ClassTree classTree, VisitorState state) { List<Tree> matched = new ArrayList<>(); Tree extendsClause = classTree.getExtendsClause(); if (extendsClause != null) { matched.add(extendsClause); } return matched; } } /** Matches an AST node whose compilation unit's package name matches the given predicate. */ public static <T extends Tree> Matcher<T> packageMatches(Predicate<String> predicate) { return (tree, state) -> predicate.test(getPackageFullName(state)); } /** Matches an AST node whose compilation unit's package name matches the given pattern. */ public static <T extends Tree> Matcher<T> packageMatches(Pattern pattern) { return packageMatches(pattern.asPredicate()); } /** Matches an AST node whose compilation unit starts with this prefix. */ public static <T extends Tree> Matcher<T> packageStartsWith(String prefix) { return packageMatches(s -> s.startsWith(prefix)); } private static String getPackageFullName(VisitorState state) { JCCompilationUnit compilationUnit = (JCCompilationUnit) state.getPath().getCompilationUnit(); return compilationUnit.packge.fullname.toString(); } private static final Matcher<ExpressionTree> STATIC_EQUALS = anyOf( allOf( staticMethod() .onClass("android.support.v4.util.ObjectsCompat") .named("equals") .withParameters("java.lang.Object", "java.lang.Object"), Matchers::methodReturnsBoolean), allOf( staticMethod() .onClass("androidx.v4.util.ObjectsCompat") .named("equals") .withParameters("java.lang.Object", "java.lang.Object"), Matchers::methodReturnsBoolean), allOf( staticMethod() .onClass("java.util.Objects") .named("equals") .withParameters("java.lang.Object", "java.lang.Object"), Matchers::methodReturnsBoolean), allOf( staticMethod() .onClass("com.google.common.base.Objects") .named("equal") .withParameters("java.lang.Object", "java.lang.Object"), Matchers::methodReturnsBoolean)); /** * Matches an invocation of a recognized static object equality method such as {@link * java.util.Objects#equals}. These are simple facades to {@link Object#equals} that accept null * for either argument. */ @SuppressWarnings("unchecked") // safe covariant cast public static <T extends ExpressionTree> Matcher<T> staticEqualsInvocation() { return (Matcher<T>) STATIC_EQUALS; } private static final Matcher<ExpressionTree> INSTANCE_EQUALS = allOf( instanceMethod().anyClass().named("equals").withParameters("java.lang.Object"), Matchers::methodReturnsBoolean); private static boolean methodReturnsBoolean(ExpressionTree tree, VisitorState state) { return ASTHelpers.isSameType( getSymbol(tree).type.getReturnType(), state.getSymtab().booleanType, state); } /** Matches calls to the method {@link Object#equals(Object)} or any override of that method. */ @SuppressWarnings("unchecked") // safe covariant cast public static <T extends ExpressionTree> Matcher<T> instanceEqualsInvocation() { return (Matcher<T>) INSTANCE_EQUALS; } public static final Matcher<MethodTree> MAIN_METHOD = allOf( methodHasArity(1), methodHasVisibility(PUBLIC), hasModifier(STATIC), methodReturns(Suppliers.VOID_TYPE), methodIsNamed("main"), methodHasParameters(isSameType(Suppliers.arrayOf(STRING_TYPE)))); private static final Matcher<ExpressionTree> INSTANCE_HASHCODE = allOf(instanceMethod().anyClass().named("hashCode").withNoParameters(), isSameType(INT_TYPE)); /** Matches calls to the method {@link Object#hashCode()} or any override of that method. */ public static Matcher<ExpressionTree> instanceHashCodeInvocation() { return INSTANCE_HASHCODE; } private static final Matcher<ExpressionTree> ASSERT_EQUALS = staticMethod() .onClassAny("org.junit.Assert", "junit.framework.Assert", "junit.framework.TestCase") .named("assertEquals"); /** * Matches calls to the method {@code org.junit.Assert#assertEquals} and corresponding methods in * JUnit 3.x. */ public static Matcher<ExpressionTree> assertEqualsInvocation() { return ASSERT_EQUALS; } private static final Matcher<ExpressionTree> ASSERT_NOT_EQUALS = staticMethod() .onClassAny("org.junit.Assert", "junit.framework.Assert", "junit.framework.TestCase") .named("assertNotEquals"); /** * Matches calls to the method {@code org.junit.Assert#assertNotEquals} and corresponding methods * in JUnit 3.x. */ public static Matcher<ExpressionTree> assertNotEqualsInvocation() { return ASSERT_NOT_EQUALS; } private static final Matcher<MethodTree> EQUALS_DECLARATION = allOf( methodIsNamed("equals"), methodHasVisibility(PUBLIC), methodHasParameters(variableType(isSameType("java.lang.Object"))), anyOf(methodReturns(BOOLEAN_TYPE), methodReturns(JAVA_LANG_BOOLEAN_TYPE))); /** Matches {@link Object#equals} method declaration. */ public static Matcher<MethodTree> equalsMethodDeclaration() { return EQUALS_DECLARATION; } private static final Matcher<MethodTree> TO_STRING_DECLARATION = allOf( methodIsNamed("toString"), methodHasVisibility(PUBLIC), methodHasNoParameters(), methodReturns(STRING_TYPE)); /** Matches {@link Object#toString} method declaration. */ public static Matcher<MethodTree> toStringMethodDeclaration() { return TO_STRING_DECLARATION; } private static final Matcher<MethodTree> HASH_CODE_DECLARATION = allOf( methodIsNamed("hashCode"), methodHasVisibility(PUBLIC), methodHasNoParameters(), methodReturns(INT_TYPE)); /** Matches {@code hashCode} method declaration. */ public static Matcher<MethodTree> hashCodeMethodDeclaration() { return HASH_CODE_DECLARATION; } /** Matcher for the overriding method of 'int java.lang.Comparable.compareTo(T other)' */ private static final Matcher<MethodTree> COMPARABLE_METHOD_MATCHER = allOf( methodIsNamed("compareTo"), methodHasVisibility(PUBLIC), methodReturns(INT_TYPE), methodHasArity(1)); /** Matches {@code compareTo} method declaration. */ public static Matcher<MethodTree> compareToMethodDeclaration() { return COMPARABLE_METHOD_MATCHER; } /** Method signature of serialization methods. */ public static final Matcher<MethodTree> SERIALIZATION_METHODS = allOf( (t, s) -> isSubtype(getSymbol(t).owner.type, s.getSymtab().serializableType, s), anyOf( allOf( methodIsNamed("readObject"), methodHasParameters(isSameType("java.io.ObjectInputStream"))), allOf( methodIsNamed("writeObject"), methodHasParameters(isSameType("java.io.ObjectOutputStream"))), allOf(methodIsNamed("readObjectNoData"), methodReturns(isVoidType())), allOf( methodIsNamed("readResolve"), methodReturns(typeFromString("java.lang.Object"))), allOf( methodIsNamed("writeReplace"), methodReturns(typeFromString("java.lang.Object"))))); public static final Matcher<Tree> IS_INTERFACE = (t, s) -> { Symbol symbol = getSymbol(t); return symbol instanceof ClassSymbol && symbol.isInterface(); }; /** * Matches the {@code Tree} if it returns an expression matching {@code expressionTreeMatcher}. */ public static Matcher<StatementTree> matchExpressionReturn( Matcher<ExpressionTree> expressionTreeMatcher) { return (statement, state) -> { if (!(statement instanceof ReturnTree)) { return false; } ExpressionTree expression = ((ReturnTree) statement).getExpression(); if (expression == null) { return false; } return expressionTreeMatcher.matches(expression, state); }; } /** * Matches a {@link BlockTree} if it single statement block with statement matching {@code * statementMatcher}. */ public static Matcher<BlockTree> matchSingleStatementBlock( Matcher<StatementTree> statementMatcher) { return (blockTree, state) -> { if (blockTree == null) { return false; } List<? extends StatementTree> statements = blockTree.getStatements(); if (statements.size() != 1) { return false; } return statementMatcher.matches(getOnlyElement(statements), state); }; } /** * Returns a matcher for {@link MethodTree} whose implementation contains a single return * statement with expression matching the passed {@code expressionTreeMatcher}. */ public static Matcher<MethodTree> singleStatementReturnMatcher( Matcher<ExpressionTree> expressionTreeMatcher) { Matcher<BlockTree> matcher = matchSingleStatementBlock(matchExpressionReturn(expressionTreeMatcher)); return (methodTree, state) -> { return matcher.matches(methodTree.getBody(), state); }; } }
63,719
38.068056
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/Returns.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.matchers; import com.google.errorprone.VisitorState; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.ReturnTree; import com.sun.source.tree.StatementTree; /** * Matches a {@code return} statement whose returned expression is matched by the given matcher. * * @author schmitt@google.com (Peter Schmitt) */ public class Returns implements Matcher<StatementTree> { private final Matcher<? super ExpressionTree> returnedMatcher; /** * New matcher for a {@code return} statement where the returned expression is matched by the * passed {@code returnedMatcher}. */ public Returns(Matcher<? super ExpressionTree> returnedMatcher) { this.returnedMatcher = returnedMatcher; } @Override public boolean matches(StatementTree expressionTree, VisitorState state) { if (!(expressionTree instanceof ReturnTree)) { return false; } return returnedMatcher.matches(((ReturnTree) expressionTree).getExpression(), state); } }
1,621
31.44
96
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/MethodInvocation.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.matchers; import com.google.errorprone.VisitorState; import com.google.errorprone.matchers.ChildMultiMatcher.MatchType; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; /** * Matches a method invocation based on a matcher for the method select (receiver + method * identifier) and one for the arguments. * * @author schmitt@google.com (Peter Schmitt) */ public class MethodInvocation implements Matcher<ExpressionTree> { private final Matcher<ExpressionTree> methodSelectMatcher; private final MethodArgumentMatcher methodArgumentMatcher; /** * Creates a new matcher for method invocations based on a method select and an argument matcher. * * @param matchType how to apply the argument matcher to the method's arguments */ public MethodInvocation( Matcher<ExpressionTree> methodSelectMatcher, MatchType matchType, Matcher<ExpressionTree> methodArgumentMatcher) { this.methodSelectMatcher = methodSelectMatcher; this.methodArgumentMatcher = new MethodArgumentMatcher(matchType, methodArgumentMatcher); } @Override public boolean matches(ExpressionTree expressionTree, VisitorState state) { if (!(expressionTree instanceof MethodInvocationTree)) { return false; } MethodInvocationTree tree = (MethodInvocationTree) expressionTree; return methodSelectMatcher.matches(tree.getMethodSelect(), state) && methodArgumentMatcher.matches(tree, state); } private static class MethodArgumentMatcher extends ChildMultiMatcher<MethodInvocationTree, ExpressionTree> { public MethodArgumentMatcher(MatchType matchType, Matcher<ExpressionTree> nodeMatcher) { super(matchType, nodeMatcher); } @Override protected Iterable<? extends ExpressionTree> getChildNodes( MethodInvocationTree tree, VisitorState state) { return tree.getArguments(); } } }
2,560
33.608108
99
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/MethodHasParameters.java
/* * Copyright 2012 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.matchers; import com.google.errorprone.VisitorState; import com.sun.source.tree.MethodTree; import com.sun.source.tree.VariableTree; /** * Matches if the given matcher matches all of/any of the parameters to this method. * * @author eaftan@google.com (Eddie Aftandilian) */ public class MethodHasParameters extends ChildMultiMatcher<MethodTree, VariableTree> { public MethodHasParameters(MatchType matchType, Matcher<VariableTree> nodeMatcher) { super(matchType, nodeMatcher); } @Override protected Iterable<? extends VariableTree> getChildNodes( MethodTree methodTree, VisitorState state) { return methodTree.getParameters(); } }
1,302
31.575
86
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/AnnotationHasArgumentWithValue.java
/* * Copyright 2011 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.matchers; import com.google.errorprone.VisitorState; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.NewArrayTree; /** * @author eaftan@google.com (Eddie Aftandilian) * @author pepstein@google.com (Peter Epstein) */ public class AnnotationHasArgumentWithValue implements Matcher<AnnotationTree> { private final String element; private final Matcher<ExpressionTree> valueMatcher; public AnnotationHasArgumentWithValue(String element, Matcher<ExpressionTree> valueMatcher) { this.element = element; this.valueMatcher = valueMatcher; } @Override public boolean matches(AnnotationTree annotationTree, VisitorState state) { ExpressionTree expressionTree = AnnotationMatcherUtils.getArgument(annotationTree, element); if (expressionTree == null) { return false; } expressionTree = ASTHelpers.stripParentheses(expressionTree); if (expressionTree instanceof NewArrayTree) { NewArrayTree arrayTree = (NewArrayTree) expressionTree; for (ExpressionTree elementTree : arrayTree.getInitializers()) { if (valueMatcher.matches(elementTree, state)) { return true; } } return false; } return valueMatcher.matches(expressionTree, state); } }
1,991
31.655738
96
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/MultiMatcher.java
/* * Copyright 2013 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.matchers; import static com.google.common.collect.Iterables.getOnlyElement; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.google.errorprone.VisitorState; import com.sun.source.tree.Tree; import java.util.List; /** * An matcher that applies a single matcher across multiple tree nodes. * * @author eaftan@google.com (Eddie Aftandilian) * @param <T> the type of the node to match on * @param <N> the type of the subnode that the given matcher should match */ public interface MultiMatcher<T extends Tree, N extends Tree> extends Matcher<T> { /** Attempt to match the given node, and return the associated subnodes that matched. */ MultiMatchResult<N> multiMatchResult(T tree, VisitorState vs); /** * A result from the call of {@link MultiMatcher#multiMatchResult(Tree, VisitorState)}, containing * information about whether it matched, and if so, what nodes matched. */ @AutoValue abstract class MultiMatchResult<N extends Tree> { MultiMatchResult() {} /** True if the MultiMatcher matched the nodes expected. */ public abstract boolean matches(); /** * The list of nodes which matched the MultiMatcher's expectations (could be empty if the match * type was ALL and there were no child nodes). Only sensical if {@link #matches()} is true. */ public abstract ImmutableList<N> matchingNodes(); public final N onlyMatchingNode() { return getOnlyElement(matchingNodes()); } static <N extends Tree> MultiMatchResult<N> create(boolean matches, List<N> matchingNodes) { return new AutoValue_MultiMatcher_MultiMatchResult<>( matches, ImmutableList.copyOf(matchingNodes)); } } }
2,369
34.909091
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/WaitMatchers.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.matchers; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.method.MethodMatchers.instanceMethod; import com.sun.source.tree.MethodInvocationTree; import java.util.regex.Pattern; /** Matchers for method invocations related to Object.wait() and Condition.await(); */ public final class WaitMatchers { private static final String OBJECT_FQN = "java.lang.Object"; private static final String CONDITION_FQN = "java.util.concurrent.locks.Condition"; /** Matches any wait/await method. */ public static final Matcher<MethodInvocationTree> waitMethod = anyOf( instanceMethod().onExactClass(OBJECT_FQN).named("wait"), instanceMethod() .onDescendantOf(CONDITION_FQN) .withNameMatching(Pattern.compile("await.*"))); /** Matches wait/await methods that have a timeout. */ public static final Matcher<MethodInvocationTree> waitMethodWithTimeout = anyOf( instanceMethod().onExactClass(OBJECT_FQN).named("wait").withParameters("long"), instanceMethod().onExactClass(OBJECT_FQN).named("wait").withParameters("long", "int"), instanceMethod() .onDescendantOf(CONDITION_FQN) .named("await") .withParameters("long", "java.util.concurrent.TimeUnit"), instanceMethod().onDescendantOf(CONDITION_FQN).named("awaitNanos"), instanceMethod().onDescendantOf(CONDITION_FQN).named("awaitUntil")); private WaitMatchers() {} }
2,164
39.849057
96
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/Suppressible.java
/* * Copyright 2013 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.matchers; import com.google.errorprone.VisitorState; import com.sun.tools.javac.util.Name; import java.lang.annotation.Annotation; import java.util.Set; /** * @author alexeagle@google.com (Alex Eagle) */ public interface Suppressible { /** * Returns all of the name strings that this checker should respect as part of a * {@code @SuppressWarnings} annotation. */ Set<String> allNames(); /** The canonical name of the check. */ String canonicalName(); /** Returns true if this checker can be suppressed using {@code @SuppressWarnings}. */ boolean supportsSuppressWarnings(); /** Returns the custom suppression annotations for this checker, if custom suppression is used. */ Set<Class<? extends Annotation>> customSuppressionAnnotations(); boolean suppressedByAnyOf(Set<Name> annotations, VisitorState s); }
1,480
31.911111
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/HasArguments.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.matchers; import com.google.errorprone.VisitorState; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; /** * Matches if the given matcher matches all of/any of the parameters to this method. * * @author eaftan@google.com (Eddie Aftandilian) */ public class HasArguments extends ChildMultiMatcher<MethodInvocationTree, ExpressionTree> { public HasArguments(MatchType matchType, Matcher<ExpressionTree> nodeMatcher) { super(matchType, nodeMatcher); } @Override protected Iterable<? extends ExpressionTree> getChildNodes( MethodInvocationTree methodInvocationTree, VisitorState state) { return methodInvocationTree.getArguments(); } }
1,345
32.65
91
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/InjectMatchers.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.matchers; 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.enclosingClass; import static com.google.errorprone.matchers.Matchers.hasAnnotation; import static com.google.errorprone.matchers.Matchers.isSubtypeOf; import static com.google.errorprone.matchers.Matchers.isType; import static com.google.errorprone.matchers.Matchers.symbolHasAnnotation; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.Tree; /** Utility constants and matchers related to dependency injection. */ public final class InjectMatchers { public static final Matcher<Tree> INSIDE_GUICE_MODULE = enclosingClass( anyOf( isSubtypeOf("com.google.inject.Module"), isSubtypeOf("com.google.gwt.inject.client.GinModule"))); private InjectMatchers() {} // no instantiation public static final String GUICE_PROVIDES_ANNOTATION = "com.google.inject.Provides"; public static final String DAGGER_PROVIDES_ANNOTATION = "dagger.Provides"; private static final Matcher<Tree> HAS_PROVIDES_ANNOTATION = annotations( AT_LEAST_ONE, anyOf( isType(GUICE_PROVIDES_ANNOTATION), isType(DAGGER_PROVIDES_ANNOTATION), isType("com.google.inject.throwingproviders.CheckedProvides"), isType("com.google.inject.multibindings.ProvidesIntoMap"), isType("com.google.inject.multibindings.ProvidesIntoSet"), isType("com.google.inject.multibindings.ProvidesIntoOptional"), isType("dagger.producers.Produces"))); @SuppressWarnings("unchecked") // Safe contravariant cast public static <T extends Tree> Matcher<T> hasProvidesAnnotation() { return (Matcher<T>) HAS_PROVIDES_ANNOTATION; } public static final String ASSISTED_ANNOTATION = "com.google.inject.assistedinject.Assisted"; public static final String ASSISTED_INJECT_ANNOTATION = "com.google.inject.assistedinject.AssistedInject"; public static final String GUICE_INJECT_ANNOTATION = "com.google.inject.Inject"; public static final String JAVAX_INJECT_ANNOTATION = "javax.inject.Inject"; public static final Matcher<AnnotationTree> IS_APPLICATION_OF_JAVAX_INJECT = new AnnotationType(JAVAX_INJECT_ANNOTATION); public static final Matcher<AnnotationTree> IS_APPLICATION_OF_GUICE_INJECT = new AnnotationType(GUICE_INJECT_ANNOTATION); public static final Matcher<AnnotationTree> IS_APPLICATION_OF_AT_INJECT = anyOf(IS_APPLICATION_OF_JAVAX_INJECT, IS_APPLICATION_OF_GUICE_INJECT); public static final Matcher<Tree> HAS_INJECT_ANNOTATION = anyOf(hasAnnotation(GUICE_INJECT_ANNOTATION), hasAnnotation(JAVAX_INJECT_ANNOTATION)); @SuppressWarnings("unchecked") // Safe contravariant cast public static <T extends Tree> Matcher<T> hasInjectAnnotation() { return (Matcher<T>) HAS_INJECT_ANNOTATION; } public static final String GUICE_SCOPE_ANNOTATION = "com.google.inject.ScopeAnnotation"; public static final String JAVAX_SCOPE_ANNOTATION = "javax.inject.Scope"; public static final Matcher<AnnotationTree> IS_SCOPING_ANNOTATION = anyOf( symbolHasAnnotation(GUICE_SCOPE_ANNOTATION), symbolHasAnnotation(JAVAX_SCOPE_ANNOTATION)); public static final String GUICE_BINDING_ANNOTATION = "com.google.inject.BindingAnnotation"; public static final String JAVAX_QUALIFIER_ANNOTATION = "javax.inject.Qualifier"; public static final Matcher<AnnotationTree> IS_BINDING_ANNOTATION = anyOf( symbolHasAnnotation(JAVAX_QUALIFIER_ANNOTATION), symbolHasAnnotation(GUICE_BINDING_ANNOTATION)); public static final String GUICE_MAP_KEY_ANNOTATION = "com.google.inject.multibindings.MapKey"; public static final String DAGGER_MAP_KEY_ANNOTATION = "dagger.MapKey"; public static final Matcher<ClassTree> IS_DAGGER_COMPONENT = anyOf( hasAnnotation("dagger.Component"), hasAnnotation("dagger.Subcomponent"), hasAnnotation("dagger.producers.ProductionComponent"), hasAnnotation("dagger.producers.ProductionSubcomponent"), hasAnnotation("dagger.hilt.DefineComponent")); public static final Matcher<ClassTree> IS_DAGGER_COMPONENT_OR_MODULE = anyOf(IS_DAGGER_COMPONENT, hasAnnotation("dagger.Module")); }
5,163
44.298246
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/Asserts.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.matchers; import com.google.errorprone.VisitorState; import com.sun.source.tree.AssertTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.StatementTree; /** Matches assert statements which have a condition expression matched by the given matcher. */ public class Asserts implements Matcher<StatementTree> { private final Matcher<ExpressionTree> expressionMatcher; public Asserts(Matcher<ExpressionTree> expressionMatcher) { this.expressionMatcher = expressionMatcher; } @Override public boolean matches(StatementTree statementTree, VisitorState state) { if (!(statementTree instanceof AssertTree)) { return false; } return expressionMatcher.matches(((AssertTree) statementTree).getCondition(), state); } }
1,409
32.571429
96
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/JUnitMatchers.java
/* * Copyright 2013 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.matchers; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.annotations; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.enclosingClass; import static com.google.errorprone.matchers.Matchers.hasAnnotation; import static com.google.errorprone.matchers.Matchers.hasAnnotationOnAnyOverriddenMethod; import static com.google.errorprone.matchers.Matchers.hasAnnotationWithSimpleName; import static com.google.errorprone.matchers.Matchers.hasArgumentWithValue; import static com.google.errorprone.matchers.Matchers.hasMethod; import static com.google.errorprone.matchers.Matchers.hasModifier; import static com.google.errorprone.matchers.Matchers.isSubtypeOf; import static com.google.errorprone.matchers.Matchers.methodHasNoParameters; import static com.google.errorprone.matchers.Matchers.methodHasVisibility; import static com.google.errorprone.matchers.Matchers.methodIsNamed; import static com.google.errorprone.matchers.Matchers.methodNameStartsWith; import static com.google.errorprone.matchers.Matchers.methodReturns; import static com.google.errorprone.matchers.Matchers.nestingKind; import static com.google.errorprone.matchers.Matchers.not; import static com.google.errorprone.suppliers.Suppliers.VOID_TYPE; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.streamSuperMethods; import static javax.lang.model.element.NestingKind.TOP_LEVEL; import com.google.common.collect.ImmutableList; import com.google.errorprone.VisitorState; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.ClassTree; 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.TreeScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.ClassType; import javax.lang.model.element.Modifier; /** * Matchers for code patterns which appear to be JUnit-based tests. * * @author alexeagle@google.com (Alex Eagle) * @author eaftan@google.com (Eddie Aftandillian) */ public final class JUnitMatchers { public static final String JUNIT4_TEST_ANNOTATION = "org.junit.Test"; public static final String JUNIT4_THEORY_ANNOTATION = "org.junit.experimental.theories.Theory"; public static final String JUNIT_BEFORE_ANNOTATION = "org.junit.Before"; public static final String JUNIT_AFTER_ANNOTATION = "org.junit.After"; public static final String JUNIT_BEFORE_CLASS_ANNOTATION = "org.junit.BeforeClass"; public static final String JUNIT_AFTER_CLASS_ANNOTATION = "org.junit.AfterClass"; public static final String JUNIT4_RUN_WITH_ANNOTATION = "org.junit.runner.RunWith"; private static final String JUNIT3_TEST_CASE_CLASS = "junit.framework.TestCase"; private static final String JUNIT4_IGNORE_ANNOTATION = "org.junit.Ignore"; /** * Checks if a method, or any overridden method, is annotated with any annotation from the * org.junit package. */ public static boolean hasJUnitAnnotation(MethodTree tree, VisitorState state) { MethodSymbol methodSym = getSymbol(tree); if (methodSym == null) { return false; } if (hasJUnitAttr(methodSym)) { return true; } return streamSuperMethods(methodSym, state.getTypes()).anyMatch(JUnitMatchers::hasJUnitAttr); } /** Checks if a method symbol has any attribute from the org.junit package. */ private static boolean hasJUnitAttr(MethodSymbol methodSym) { return methodSym.getRawAttributes().stream() .anyMatch(attr -> attr.type.tsym.getQualifiedName().toString().startsWith("org.junit.")); } public static final Matcher<MethodTree> hasJUnit4BeforeAnnotations = anyOf( hasAnnotationOnAnyOverriddenMethod(JUNIT_BEFORE_ANNOTATION), hasAnnotation(JUNIT_BEFORE_CLASS_ANNOTATION)); public static final Matcher<MethodTree> hasJUnit4AfterAnnotations = anyOf( hasAnnotationOnAnyOverriddenMethod(JUNIT_AFTER_ANNOTATION), hasAnnotation(JUNIT_AFTER_CLASS_ANNOTATION)); /** Matches a class that inherits from TestCase. */ public static final Matcher<ClassTree> isTestCaseDescendant = isSubtypeOf(JUNIT3_TEST_CASE_CLASS); /** * Match a class which appears to be missing a @RunWith annotation. * * <p>Matches if: 1) The class does not have a JUnit 4 @RunWith annotation. 2) The class is * concrete. 3) The class is a top-level class. */ public static final Matcher<ClassTree> isConcreteClassWithoutRunWith = allOf( not(hasAnnotation(JUNIT4_RUN_WITH_ANNOTATION)), not(Matchers.<ClassTree>hasModifier(Modifier.ABSTRACT)), nestingKind(TOP_LEVEL)); /** Match a class which has one or more methods with a JUnit 4 @Test annotation. */ public static final Matcher<ClassTree> hasJUnit4TestCases = hasMethod(hasAnnotationOnAnyOverriddenMethod(JUNIT4_TEST_ANNOTATION)); /** * Match a class which appears to be a JUnit 3 test class. * * <p>Matches if: 1) The class does inherit from TestCase. 2) The class does not have a JUnit 4 * {@code @RunWith} annotation nor any methods annotated {@code @Test}. 3) The class is concrete. * 4) This class is a top-level class. */ public static final Matcher<ClassTree> isJUnit3TestClass = allOf(isTestCaseDescendant, isConcreteClassWithoutRunWith, not(hasJUnit4TestCases)); /** * Match a method which appears to be a JUnit 3 test case. * * <p>Matches if: 1) The method's name begins with "test". 2) The method has no parameters. 3) The * method is public. 4) The method returns void */ public static final Matcher<MethodTree> isJunit3TestCase = allOf( methodNameStartsWith("test"), methodHasNoParameters(), Matchers.<MethodTree>hasModifier(Modifier.PUBLIC), methodReturns(VOID_TYPE)); /** Common matcher for possible JUnit setUp/tearDown methods. */ private static final Matcher<MethodTree> looksLikeJUnitSetUpOrTearDown = allOf( methodHasNoParameters(), anyOf( methodHasVisibility(MethodVisibility.Visibility.PUBLIC), methodHasVisibility(MethodVisibility.Visibility.PROTECTED)), not(Matchers.<MethodTree>hasModifier(Modifier.ABSTRACT)), not(Matchers.<MethodTree>hasModifier(Modifier.STATIC)), methodReturns(VOID_TYPE)); /** * Match a method which appears to be a JUnit 3 setUp method * * <p>Matches if: 1) The method is named "setUp" 2) The method has no parameters 3) The method is * a public or protected instance method that is not abstract 4) The method returns void */ public static final Matcher<MethodTree> looksLikeJUnit3SetUp = allOf(methodIsNamed("setUp"), looksLikeJUnitSetUpOrTearDown); /** * Matches a method which appears to be a JUnit4 @Before method. * * <p>Matches if: 1) The method is annotated {@code Before} 2) The method has no parameters 3) The * method is a public or protected instance method that is not abstract 4) The method returns void */ public static final Matcher<MethodTree> looksLikeJUnit4Before = allOf(hasAnnotationWithSimpleName("Before"), looksLikeJUnitSetUpOrTearDown); /** * Match a method which appears to be a JUnit 3 tearDown method * * <p>Matches if: 1) The method is named "tearDown" 2) The method has no parameters 3) The method * is a public or protected instance method that is not abstract 4) The method returns void */ public static final Matcher<MethodTree> looksLikeJUnit3TearDown = allOf(methodIsNamed("tearDown"), looksLikeJUnitSetUpOrTearDown); /** * Matches a method which appears to be a JUnit4 @After method. * * <p>Matches if: 1) The method is annotated {@code After} 2) The method has no parameters 3) The * method is a public or protected instance method that is not abstract 4) The method returns void */ public static final Matcher<MethodTree> looksLikeJUnit4After = allOf(hasAnnotationWithSimpleName("After"), looksLikeJUnitSetUpOrTearDown); /** Matches a method annotated with @Test but not @Ignore. */ public static final Matcher<MethodTree> wouldRunInJUnit4 = allOf( hasAnnotationOnAnyOverriddenMethod(JUNIT4_TEST_ANNOTATION), not(hasAnnotationOnAnyOverriddenMethod(JUNIT4_IGNORE_ANNOTATION))); /** Matches a JUnit 3 or 4 test case. */ public static final Matcher<MethodTree> TEST_CASE = anyOf( isJunit3TestCase, hasAnnotation(JUNIT4_TEST_ANNOTATION), hasAnnotation(JUNIT4_THEORY_ANNOTATION)); /** * A list of test runners that this matcher should look for in the @RunWith annotation. Subclasses * of the test runners are also matched. */ private static final ImmutableList<String> TEST_RUNNERS = ImmutableList.of( "org.mockito.junit.MockitoJUnitRunner", "org.junit.runners.BlockJUnit4ClassRunner"); /** * Matches an argument of type {@code Class<T>}, where T is a subtype of one of the test runners * listed in the TEST_RUNNERS field. * * <p>TODO(eaftan): Support checking for an annotation that tells us whether this test runner * expects tests to be annotated with @Test. */ public static Matcher<ExpressionTree> isJUnit4TestRunnerOfType(Iterable<String> runnerTypes) { return new Matcher<ExpressionTree>() { @Override public boolean matches(ExpressionTree t, VisitorState state) { Type type = ASTHelpers.getType(t); // Expect a class type. if (!(type instanceof ClassType)) { return false; } // Expect one type argument, the type of the JUnit class runner to use. com.sun.tools.javac.util.List<Type> typeArgs = type.getTypeArguments(); if (typeArgs.size() != 1) { return false; } Type runnerType = typeArgs.get(0); for (String testRunner : runnerTypes) { Symbol parent = state.getSymbolFromString(testRunner); if (parent == null) { continue; } if (runnerType.tsym.isSubClass(parent, state.getTypes())) { return true; } } return false; } }; } public static final MultiMatcher<ClassTree, AnnotationTree> hasJUnit4TestRunner = annotations( AT_LEAST_ONE, hasArgumentWithValue("value", isJUnit4TestRunnerOfType(TEST_RUNNERS))); /** * Matches classes which have attributes of only JUnit4 test classes. * * <p>Matches if 1) the class is non-abstract, 2) the class does not inherit from JUnit3 {@code * TestCase}, and 3) the class is annotated with {@code @RunWith} or any method therein is * annotated with {@code @Test}. */ public static final Matcher<ClassTree> isJUnit4TestClass = allOf( not(isTestCaseDescendant), not(enclosingClass(hasModifier(Modifier.ABSTRACT))), anyOf(hasJUnit4TestRunner, hasJUnit4TestCases)); /** * Matches classes which have attributes of both JUnit 3 and 4 classes. * * <p>Matches if the class 1) inherits from JUnit 3 {@code TestCase}, and 2) a) has a JUnit4 test * runner annotation, or b) has any methods annotated {@code @Test}. * * <p>As currently implemented, classes with ambiguous version will match neither {@code * isJUnit4TestClass} nor {@code isJUnit3TestClass}. */ public static final Matcher<ClassTree> isAmbiguousJUnitVersion = allOf(isTestCaseDescendant, anyOf(hasJUnit4TestRunner, hasJUnit4TestCases)); /** Returns true if the tree contains a method invocation that looks like a test assertion. */ public static boolean containsTestMethod(Tree tree) { return firstNonNull( tree.accept( new TreeScanner<Boolean, Void>() { @Override public Boolean visitMethodInvocation(MethodInvocationTree node, Void unused) { String name = getSymbol(node).getSimpleName().toString(); return name.contains("assert") || name.contains("verify") || name.contains("check") || name.contains("fail") || name.contains("expect") || firstNonNull(super.visitMethodInvocation(node, null), false); } @Override public Boolean reduce(Boolean a, Boolean b) { return firstNonNull(a, false) || firstNonNull(b, false); } }, null), false); } private JUnitMatchers() {} }
13,631
42.974194
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/ConstructorOfClass.java
/* * Copyright 2012 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.matchers; import com.google.common.collect.ImmutableList; import com.google.errorprone.VisitorState; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; /** * Applies the given matcher to the constructor(s) of the given class. * * @author eaftan@google.com (Eddie Aftandilian) */ public class ConstructorOfClass extends ChildMultiMatcher<ClassTree, MethodTree> { public ConstructorOfClass(MatchType matchType, Matcher<MethodTree> nodeMatcher) { super(matchType, nodeMatcher); } @Override protected Iterable<? extends MethodTree> getChildNodes(ClassTree classTree, VisitorState state) { ImmutableList.Builder<MethodTree> result = ImmutableList.builder(); // Iterate over members of class (methods and fields). for (Tree member : classTree.getMembers()) { // If this member is a constructor... if (member instanceof MethodTree && ASTHelpers.getSymbol(member).isConstructor()) { result.add((MethodTree) member); } } return result.build(); } }
1,751
34.04
99
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/MethodInvocationArgument.java
/* * Copyright 2012 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.matchers; import com.google.errorprone.VisitorState; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; /** * Applies an Expression matcher to an argument of a MethodInvocation by position. * * @author alexeagle@google.com (Alex Eagle) */ public class MethodInvocationArgument implements Matcher<MethodInvocationTree> { private final int position; private final Matcher<ExpressionTree> argumentMatcher; public MethodInvocationArgument(int position, Matcher<ExpressionTree> argumentMatcher) { this.position = position; this.argumentMatcher = argumentMatcher; } @Override public boolean matches(MethodInvocationTree methodInvocationTree, VisitorState state) { if (methodInvocationTree.getArguments().size() <= position) { return false; } return argumentMatcher.matches(methodInvocationTree.getArguments().get(position), state); } }
1,558
33.644444
93
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/NullnessMatcher.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.matchers; import com.google.errorprone.VisitorState; import com.google.errorprone.dataflow.nullnesspropagation.Nullness; import com.sun.source.tree.ExpressionTree; import com.sun.source.util.TreePath; /** Matches an expression based on the result of the nullness dataflow analysis. */ public class NullnessMatcher implements Matcher<ExpressionTree> { private final Nullness expectedNullnessValue; public NullnessMatcher(Nullness expectedNullnessValue) { this.expectedNullnessValue = expectedNullnessValue; } @Override public boolean matches(ExpressionTree expr, VisitorState state) { TreePath exprPath = new TreePath(state.getPath(), expr); return state.getNullnessAnalysis().getNullness(exprPath, state.context) == expectedNullnessValue; } }
1,418
35.384615
83
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/IsNonNullMatcher.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.matchers; import static com.google.errorprone.matchers.Matchers.isNonNullUsingDataflow; import com.google.errorprone.VisitorState; import com.sun.source.tree.ExpressionTree; /** * Matches expressions that can be statically determined to be non-null. The matcher should have few * if any false positives but has many, many false negatives. */ public final class IsNonNullMatcher implements Matcher<ExpressionTree> { @Override public boolean matches(ExpressionTree tree, VisitorState state) { return isNonNullUsingDataflow().matches(tree, state); } }
1,204
34.441176
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/MethodVisibility.java
/* * Copyright 2012 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.matchers; import static com.google.errorprone.util.ASTHelpers.getSymbol; import com.google.errorprone.VisitorState; import com.sun.source.tree.MethodTree; import java.util.Set; import javax.lang.model.element.Modifier; /** * A matcher for method visibility (public, private, protected, or default). * * @author eaftan@google.com (Eddie Aftandilian) */ public class MethodVisibility implements Matcher<MethodTree> { private final Visibility visibility; public MethodVisibility(Visibility visibility) { this.visibility = visibility; } @Override public boolean matches(MethodTree t, VisitorState state) { Set<Modifier> modifiers = getSymbol(t).getModifiers(); if (visibility == Visibility.DEFAULT) { return !modifiers.contains(Visibility.PUBLIC.toModifier()) && !modifiers.contains(Visibility.PROTECTED.toModifier()) && !modifiers.contains(Visibility.PRIVATE.toModifier()); } else { return modifiers.contains(visibility.toModifier()); } } /** The visibility of a member. */ public enum Visibility { PUBLIC(Modifier.PUBLIC), PROTECTED(Modifier.PROTECTED), DEFAULT(null), PRIVATE(Modifier.PRIVATE); private final Modifier correspondingModifier; Visibility(Modifier correspondingModifier) { this.correspondingModifier = correspondingModifier; } public Modifier toModifier() { return correspondingModifier; } } }
2,077
29.115942
76
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/CompileTimeConstantExpressionMatcher.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.matchers; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.anything; import static com.google.errorprone.matchers.Matchers.nullLiteral; import static com.google.errorprone.matchers.Matchers.staticMethod; import static com.google.errorprone.matchers.Matchers.toType; import static com.google.errorprone.matchers.Matchers.typeCast; import static com.google.errorprone.util.ASTHelpers.constValue; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.isConsideredFinal; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.CompileTimeConstant; import com.google.errorprone.suppliers.Supplier; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.ConditionalExpressionTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.TypeCastTree; import com.sun.source.util.SimpleTreeVisitor; import com.sun.tools.javac.code.Symbol; import javax.lang.model.element.ElementKind; /** * A matcher for compile-time-constant expressions. * * <p>For the purposes of this matcher, a compile-time constant expression is one of the following: * * <ol> * <li>Any expression for which the Java compiler can determine a constant value at compile time. * <li>The expression consisting of the literal {@code null}. * <li>An expression consisting of a single identifier, where the identifier is a formal method * parameter that is declared {@code final} and has the {@link CompileTimeConstant} * annotation. * </ol> */ public class CompileTimeConstantExpressionMatcher implements Matcher<ExpressionTree> { private static final Supplier<Symbol> COMPILE_TIME_CONSTANT_ANNOTATION = VisitorState.memoize(state -> state.getSymbolFromString(CompileTimeConstant.class.getName())); private static final Matcher<ExpressionTree> INSTANCE = anyOf( // TODO(xtof): Consider utilising mdempsky's closed-over-addition matcher // (perhaps extended for other arithmetic operations). new ExpressionWithConstValueMatcher(), nullLiteral(), // Allows passing a null literal to a method with a @CompileTimeConstant parameter // when A) there's an overload of the method that takes a supertype of the parameter's // type and B) the overload with the @CompileTimeConstant parameter specifically needs to // be the overload that is called. toType(TypeCastTree.class, typeCast(anything(), nullLiteral()))); public static Matcher<ExpressionTree> instance() { return INSTANCE; } @Override public boolean matches(ExpressionTree t, VisitorState state) { return INSTANCE.matches(t, state); } private static final Matcher<ExpressionTree> IMMUTABLE_FACTORY = anyOf( staticMethod().onClass("com.google.common.collect.ImmutableList").named("of"), staticMethod().onClass("com.google.common.collect.ImmutableSet").named("of")); /** * A matcher for {@link ExpressionTree}s for which the java compiler can compute a constant value * (except a literal {@code null}). */ private static final class ExpressionWithConstValueMatcher implements Matcher<ExpressionTree> { @Override public boolean matches(ExpressionTree tree, VisitorState state) { return tree.accept( new SimpleTreeVisitor<Boolean, Void>() { @Override public Boolean visitConditionalExpression(ConditionalExpressionTree tree, Void unused) { return tree.getTrueExpression().accept(this, null) && tree.getFalseExpression().accept(this, null); } @Override public Boolean visitMethodInvocation(MethodInvocationTree tree, Void unused) { return IMMUTABLE_FACTORY.matches(tree, state) && tree.getArguments().stream().allMatch(a -> a.accept(this, null)); } @Override public Boolean visitBinary(BinaryTree tree, Void unused) { return defaultAction(tree, null) || (tree.getKind().equals(Kind.PLUS) && tree.getLeftOperand().accept(this, null) && tree.getRightOperand().accept(this, null)); } @Override public Boolean visitParenthesized(ParenthesizedTree tree, Void unused) { return tree.getExpression().accept(this, null); } @Override protected Boolean defaultAction(Tree node, Void unused) { if (constValue(node) != null) { return true; } if (node.getKind() != Tree.Kind.IDENTIFIER) { return false; } Symbol.VarSymbol varSymbol = (Symbol.VarSymbol) getSymbol(node); Symbol owner = varSymbol.owner; ElementKind ownerKind = owner.getKind(); // Check that the identifier is a formal method/constructor parameter, or a class/enum // field. if (ownerKind != ElementKind.METHOD && ownerKind != ElementKind.CONSTRUCTOR && ownerKind != ElementKind.CLASS && ownerKind != ElementKind.ENUM) { return false; } // Check that the symbol is final if (!isConsideredFinal(varSymbol)) { return false; } // Check if the symbol has the @CompileTimeConstant annotation. if (hasCompileTimeConstantAnnotation(state, varSymbol)) { return true; } return false; } }, null); } } public static boolean hasCompileTimeConstantAnnotation(VisitorState state, Symbol symbol) { Symbol annotation = COMPILE_TIME_CONSTANT_ANNOTATION.get(state); // If we can't look up the annotation in the current VisitorState, then presumably it couldn't // be present on a Symbol we're inspecting. return annotation != null && symbol.attribute(annotation) != null; } }
6,998
41.676829
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/AnnotationDoesNotHaveArgument.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.matchers; import com.google.errorprone.VisitorState; import com.sun.source.tree.AnnotationTree; /** * Matches an annotation that does not have a particular argument, possibly because the default * value is being used. * * @author mwacker@google.com (Mike Wacker) */ public class AnnotationDoesNotHaveArgument implements Matcher<AnnotationTree> { private final String name; /** * Creates a new matcher. * * @param name the name of the argument to search for */ public AnnotationDoesNotHaveArgument(String name) { this.name = name; } @Override public boolean matches(AnnotationTree annotationTree, VisitorState state) { return AnnotationMatcherUtils.getArgument(annotationTree, name) == null; } }
1,378
28.978261
95
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/ChildMultiMatcher.java
/* * Copyright 2013 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.matchers; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.ForOverride; import com.sun.source.tree.Tree; import com.sun.source.util.TreePath; import java.util.List; /** * A {@link MultiMatcher} that applies a matcher across multiple children of a single ancestor node. * Configurable to return true if any of, all of, or the last node matches. In the any or last of * cases, provides access to the node that matched. * * @author eaftan@google.com (Eddie Aftandilian) * @param <T> the type of the node to match on * @param <N> the type of the subnode that the given matcher should match */ public abstract class ChildMultiMatcher<T extends Tree, N extends Tree> implements MultiMatcher<T, N> { public enum MatchType { /** * Matches if all of the child elements match the matcher. If the parent element has no child * elements, this matcher returns true. */ ALL, /** * Matches if at least one of the child elements match the matcher. If the parent element has no * child elements, this matcher returns false. */ AT_LEAST_ONE, /** * Matches if the last child element matches the matcher, regardless of whether or not any of * the other child elements would match the matcher. If the parent element has no child * elements, this matcher returns false. */ LAST } @AutoValue abstract static class Matchable<T extends Tree> { public abstract T tree(); public abstract VisitorState state(); public static <T extends Tree> Matchable<T> create(T tree, VisitorState state) { return new AutoValue_ChildMultiMatcher_Matchable<>(tree, state); } } @AutoValue abstract static class MatchResult<T extends Tree> { public abstract ImmutableList<T> matchingNodes(); public abstract boolean matches(); public static <T extends Tree> MatchResult<T> none() { return create(ImmutableList.<T>of(), /* matches= */ false); } public static <T extends Tree> MatchResult<T> match(T matchingNode) { return create(ImmutableList.of(matchingNode), /* matches= */ true); } public static <T extends Tree> MatchResult<T> match(ImmutableList<T> matchingNodes) { return create(matchingNodes, /* matches= */ true); } private static <T extends Tree> MatchResult<T> create(List<T> matchingNode, boolean matches) { return new AutoValue_ChildMultiMatcher_MatchResult<>( ImmutableList.copyOf(matchingNode), matches); } } /** * A matcher that operates over a list of nodes, each of which includes an AST node and a * VisitorState with a TreePath for the given node. */ private abstract static class ListMatcher<N extends Tree> { abstract MatchResult<N> matches(List<Matchable<N>> matchables, Matcher<N> nodeMatcher); public static <N extends Tree> ListMatcher<N> create(MatchType matchType) { switch (matchType) { case ALL: return new AllMatcher<>(); case AT_LEAST_ONE: return new AtLeastOneMatcher<>(); case LAST: return new LastMatcher<>(); } throw new AssertionError("Unexpected match type: " + matchType); } } /** A matcher that returns true if all nodes in the list match. */ private static class AllMatcher<N extends Tree> extends ListMatcher<N> { @Override public MatchResult<N> matches(List<Matchable<N>> matchables, Matcher<N> nodeMatcher) { ImmutableList.Builder<N> matchingTrees = ImmutableList.builder(); for (Matchable<N> matchable : matchables) { if (!nodeMatcher.matches(matchable.tree(), matchable.state())) { return MatchResult.none(); } matchingTrees.add(matchable.tree()); } return MatchResult.match(matchingTrees.build()); } } /** A matcher that returns true if at least one node in the list matches. */ private static class AtLeastOneMatcher<N extends Tree> extends ListMatcher<N> { @Override public MatchResult<N> matches(List<Matchable<N>> matchables, Matcher<N> nodeMatcher) { ImmutableList.Builder<N> matchingTrees = ImmutableList.builder(); for (Matchable<N> matchable : matchables) { if (nodeMatcher.matches(matchable.tree(), matchable.state())) { matchingTrees.add(matchable.tree()); } } ImmutableList<N> allTheTrees = matchingTrees.build(); return allTheTrees.isEmpty() ? MatchResult.<N>none() : MatchResult.match(allTheTrees); } } /** A matcher that returns true if the last node in the list matches. */ private static class LastMatcher<N extends Tree> extends ListMatcher<N> { @Override public MatchResult<N> matches(List<Matchable<N>> matchables, Matcher<N> nodeMatcher) { if (matchables.isEmpty()) { return MatchResult.none(); } Matchable<N> last = Iterables.getLast(matchables); return nodeMatcher.matches(last.tree(), last.state()) ? MatchResult.match(last.tree()) : MatchResult.<N>none(); } } /** The matcher to apply to the subnodes in question. */ protected final Matcher<N> nodeMatcher; private final ListMatcher<N> listMatcher; public ChildMultiMatcher(MatchType matchType, Matcher<N> nodeMatcher) { this.nodeMatcher = nodeMatcher; this.listMatcher = ListMatcher.create(matchType); } @Override public boolean matches(T tree, VisitorState state) { return multiMatchResult(tree, state).matches(); } @Override public MultiMatchResult<N> multiMatchResult(T tree, VisitorState state) { ImmutableList.Builder<Matchable<N>> result = ImmutableList.builder(); for (N subnode : getChildNodes(tree, state)) { TreePath newPath = new TreePath(state.getPath(), subnode); result.add(Matchable.create(subnode, state.withPath(newPath))); } MatchResult<N> matchResult = listMatcher.matches(result.build(), nodeMatcher); return MultiMatchResult.create(matchResult.matches(), matchResult.matchingNodes()); } /** * Returns the set of child nodes to match. The nodes must be immediate children of the current * node to ensure the TreePath calculation is correct. MultiMatchers with other requirements * should not subclass ChildMultiMatcher. */ @ForOverride protected abstract Iterable<? extends N> getChildNodes(T tree, VisitorState state); }
7,146
36.223958
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/Contains.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.matchers; import com.google.errorprone.VisitorState; import com.sun.source.tree.Tree; import com.sun.source.util.TreeScanner; /** * A matcher that recursively inspects a tree, applying the given matcher to all levels of each tree * and returning {@code true} if any match is found. * * <p>This matcher may be slow. Please avoid using it if there is any other way to implement your * check. */ public class Contains implements Matcher<Tree> { private final Matcher<Tree> matcher; public Contains(Matcher<Tree> matcher) { this.matcher = matcher; } @Override public boolean matches(Tree tree, VisitorState state) { FirstMatchingScanner scanner = new FirstMatchingScanner(state); Boolean matchFound = tree.accept(scanner, /* data= */ false); return matchFound != null && matchFound; } private class FirstMatchingScanner extends TreeScanner<Boolean, Boolean> { private final VisitorState state; public FirstMatchingScanner(VisitorState state) { this.state = state; } @Override public Boolean scan(Tree tree, Boolean matchFound) { if (matchFound) { return true; } if (matcher.matches(tree, state)) { return true; } return super.scan(tree, false); } @Override public Boolean reduce(Boolean left, Boolean right) { return (left != null && left) || (right != null && right); } } }
2,052
28.328571
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/IsSubtypeOf.java
/* * Copyright 2013 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.matchers; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.isSubtype; import com.google.errorprone.VisitorState; import com.google.errorprone.suppliers.Supplier; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Type; /** * @author eaftan@google.com (Eddie Aftandilian) */ public class IsSubtypeOf<T extends Tree> extends AbstractTypeMatcher<T> { public IsSubtypeOf(Supplier<Type> typeToCompareSupplier) { super(typeToCompareSupplier); } public IsSubtypeOf(String typeString) { super(typeString); } @Override public boolean matches(T tree, VisitorState state) { return isSubtype(getType(tree), typeToCompareSupplier.get(state), state); } }
1,392
29.955556
77
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/FieldMatchers.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.matchers; import static com.google.errorprone.util.ASTHelpers.isStatic; import com.google.errorprone.VisitorState; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.ImportTree; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import javax.annotation.Nullable; // TODO(glorioso): this likely wants to be a fluent interface like MethodMatchers. // Ex: [staticField()|instanceField()] // .[onClass(String)|onAnyClass|onClassMatching] // .[named(String)|withAnyName|withNameMatching] /** Static utility methods for creating {@link Matcher}s for detecting references to fields. */ public final class FieldMatchers { private FieldMatchers() {} public static Matcher<ExpressionTree> anyFieldInClass(String className) { return new FieldReferenceMatcher() { @Override boolean classIsAppropriate(ClassSymbol classSymbol) { return classSymbol.getQualifiedName().contentEquals(className); } @Override boolean fieldSymbolIsAppropriate(Symbol symbol) { return true; } }; } public static Matcher<ExpressionTree> staticField(String className, String fieldName) { return new FieldReferenceMatcher() { @Override boolean classIsAppropriate(ClassSymbol classSymbol) { return classSymbol.getQualifiedName().contentEquals(className); } @Override boolean fieldSymbolIsAppropriate(Symbol symbol) { return isStatic(symbol) && symbol.getSimpleName().contentEquals(fieldName); } }; } public static Matcher<ExpressionTree> instanceField(String className, String fieldName) { return new FieldReferenceMatcher() { @Override boolean classIsAppropriate(ClassSymbol classSymbol) { return classSymbol.getQualifiedName().contentEquals(className); } @Override boolean fieldSymbolIsAppropriate(Symbol symbol) { return !isStatic(symbol) && symbol.getSimpleName().contentEquals(fieldName); } }; } private abstract static class FieldReferenceMatcher implements Matcher<ExpressionTree> { @Override public boolean matches(ExpressionTree expressionTree, VisitorState state) { return isSymbolFieldInAppropriateClass(ASTHelpers.getSymbol(expressionTree)) // Don't match if this is part of a static import tree, since they will get the finding // on any usage of the field in their source. && ASTHelpers.findEnclosingNode(state.getPath(), ImportTree.class) == null; } private boolean isSymbolFieldInAppropriateClass(@Nullable Symbol symbol) { if (symbol == null) { return false; } return symbol.getKind().isField() && fieldSymbolIsAppropriate(symbol) && classIsAppropriate(symbol.owner.enclClass()); } abstract boolean fieldSymbolIsAppropriate(Symbol symbol); abstract boolean classIsAppropriate(ClassSymbol classSymbol); } }
3,665
34.941176
97
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/IsSameType.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.matchers; import com.google.errorprone.VisitorState; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Type; /** * Matches an AST node if its erased type is the same as the given type, e.g. If the type of the AST * node is {@code HashMap<K,V>} and the given type is {@code HashMap}, then their erased type is the * same. * * @author yanx@google.com (Yan Xie) */ public class IsSameType<T extends Tree> extends AbstractTypeMatcher<T> { public IsSameType(Supplier<Type> typeToCompareSupplier) { super(typeToCompareSupplier); } public IsSameType(String typeString) { super(typeString); } @Override public boolean matches(T tree, VisitorState state) { Type typeToCompare = typeToCompareSupplier.get(state); return ASTHelpers.isSameType(ASTHelpers.getType(tree), typeToCompare, state); } }
1,575
31.833333
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/Enclosing.java
/* * Copyright 2013 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.matchers; import com.google.errorprone.VisitorState; import com.sun.source.tree.BlockTree; import com.sun.source.tree.CaseTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import com.sun.source.util.TreePath; /** * Adapt matchers to match against a parent node of a given type. For example, match a node if the * enclosing class matches a predicate. * * @author alexeagle@google.com (Alex Eagle) */ public class Enclosing { private Enclosing() {} private abstract static class EnclosingMatcher<T extends Tree, U extends Tree> implements Matcher<U> { protected final Matcher<T> matcher; protected final java.lang.Class<T> clazz; protected EnclosingMatcher(Matcher<T> matcher, java.lang.Class<T> clazz) { this.matcher = matcher; this.clazz = clazz; } @Override public boolean matches(U unused, VisitorState state) { TreePath pathToEnclosing = state.findPathToEnclosing(clazz); // No match if there is no enclosing element to match against if (pathToEnclosing == null) { return false; } T enclosing = clazz.cast(pathToEnclosing.getLeaf()); return matcher.matches(enclosing, state.withPath(pathToEnclosing)); } } public static class Block<T extends Tree> extends EnclosingMatcher<BlockTree, T> { public Block(Matcher<BlockTree> matcher) { super(matcher, BlockTree.class); } } public static class Class<T extends Tree> extends EnclosingMatcher<ClassTree, T> { public Class(Matcher<ClassTree> matcher) { super(matcher, ClassTree.class); } } public static class Method<T extends Tree> extends EnclosingMatcher<MethodTree, T> { public Method(Matcher<MethodTree> matcher) { super(matcher, MethodTree.class); } } public static class BlockOrCase<T extends Tree> implements Matcher<T> { private final Matcher<BlockTree> blockTreeMatcher; private final Matcher<CaseTree> caseTreeMatcher; public BlockOrCase(Matcher<BlockTree> blockTreeMatcher, Matcher<CaseTree> caseTreeMatcher) { this.blockTreeMatcher = blockTreeMatcher; this.caseTreeMatcher = caseTreeMatcher; } @Override public boolean matches(T unused, VisitorState state) { TreePath pathToEnclosing = state.findPathToEnclosing(CaseTree.class, BlockTree.class); if (pathToEnclosing == null) { return false; } Tree enclosing = pathToEnclosing.getLeaf(); state = state.withPath(pathToEnclosing); if (enclosing instanceof BlockTree) { return blockTreeMatcher.matches((BlockTree) enclosing, state); } else if (enclosing instanceof CaseTree) { return caseTreeMatcher.matches((CaseTree) enclosing, state); } else { // findEnclosing given two types must return something of one of those types throw new IllegalStateException("enclosing tree not a BlockTree or CaseTree"); } } } }
3,624
33.855769
98
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/Throws.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.matchers; import com.google.errorprone.VisitorState; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.ThrowTree; /** * Matches a {@code throw} statement whose thrown expression is matched by the given matcher. * * @author schmitt@google.com (Peter Schmitt) */ public class Throws implements Matcher<StatementTree> { private final Matcher<? super ExpressionTree> thrownMatcher; /** * New matcher for a {@code throw} statement where the thrown item is matched by the passed {@code * thrownMatcher}. */ public Throws(Matcher<? super ExpressionTree> thrownMatcher) { this.thrownMatcher = thrownMatcher; } @Override public boolean matches(StatementTree expressionTree, VisitorState state) { if (!(expressionTree instanceof ThrowTree)) { return false; } return thrownMatcher.matches(((ThrowTree) expressionTree).getExpression(), state); } }
1,592
30.86
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/Description.java
/* * Copyright 2012 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.matchers; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Strings.isNullOrEmpty; import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.CheckReturnValue; import com.google.errorprone.annotations.RestrictedApi; import com.google.errorprone.fixes.Fix; import com.google.errorprone.fixes.SuggestedFix; import com.sun.source.tree.Tree; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import java.util.List; import java.util.Optional; import javax.annotation.Nullable; /** * Simple data object containing the information captured about an AST match. Can be printed in a * UI, or output in structured format for use by tools. * * @author alexeagle@google.com (Alex Eagle) */ public class Description { /** Describes the sentinel value of the case where the match failed. */ public static final Description NO_MATCH = new Description( null, "<no match>", "<no match>", "<no match>", ImmutableList.<Fix>of(), Optional.of(SUGGESTION)); /** The position of the match. */ public final DiagnosticPosition position; /** The name of the check that produced the match. */ public final String checkName; /** The raw message, not including the check name or the link. */ private final String rawMessage; /** The raw link URL for the check. May be null if there is no link. */ @Nullable private final String linkUrl; /** * A list of fixes to suggest in an error message or use in automated refactoring. Fixes are in * order of decreasing preference, from most preferred to least preferred. */ public final ImmutableList<Fix> fixes; /** Is this a warning, error, etc.? */ private final Optional<BugPattern.SeverityLevel> severity; public BugPattern.SeverityLevel severity() { return severity.get(); } /** * Returns the message to be printed by the compiler when a match is found in interactive use. * Includes the name of the check and a link for more information. */ public String getMessage() { return String.format("[%s] %s", checkName, getMessageWithoutCheckName()); } /** Returns a link associated with this finding or null if there is no link. */ @Nullable public String getLink() { return linkUrl; } /** Returns the raw message, not including a link or check name. */ public String getRawMessage() { return rawMessage; } /** Returns the message, not including the check name but including the link. */ public String getMessageWithoutCheckName() { return linkUrl != null ? String.format("%s\n%s", rawMessage, linkTextForDiagnostic(linkUrl)) : String.format("%s", rawMessage); } private Description( DiagnosticPosition position, String checkName, String rawMessage, @Nullable String linkUrl, List<Fix> fixes, Optional<SeverityLevel> severity) { this.position = position; this.checkName = checkName; this.rawMessage = rawMessage; this.linkUrl = linkUrl; this.fixes = ImmutableList.copyOf(fixes); this.severity = severity; } /** Internal-only. */ @CheckReturnValue public Description applySeverityOverride(SeverityLevel severity) { return new Description( position, checkName, rawMessage, linkUrl, fixes, Optional.of(this.severity.orElse(severity))); } /** * Construct the link text to include in the compiler error message. Returns null if there is no * link. */ @Nullable private static String linkTextForDiagnostic(String linkUrl) { return isNullOrEmpty(linkUrl) ? null : " (see " + linkUrl + ")"; } /** Returns a new builder for {@link Description}s. */ @RestrictedApi( explanation = "Use describeMatch or buildDescription on BugChecker instead.", link = "", allowedOnPath = ".*/java/com/google/devtools/staticanalysis/errorprone/pluggabletype/LatticeAdapter.java" + "|.*/java/com/google/devtools/staticanalysis/errorprone/pluggabletype/LatticeInfo.java" + "|.*/third_party/java_src/error_prone/project/check_api/src/main/java/com/google/errorprone/bugpatterns/BugChecker.java") public static Builder builder(Tree node, String name, @Nullable String link, String message) { return new Builder((DiagnosticPosition) node, name, link, message); } /** Returns a new builder for {@link Description}s. */ @RestrictedApi( explanation = "Use describeMatch or buildDescription on BugChecker instead.", link = "", allowedOnPath = ".*/third_party/java_src/error_prone/project/check_api/src/main/java/com/google/errorprone/bugpatterns/BugChecker.java") public static Builder builder( DiagnosticPosition position, String name, @Nullable String link, String message) { return new Builder(position, name, link, message); } /** Returns a new builder for {@link Description}s. */ @RestrictedApi( explanation = "Use describeMatch or buildDescription on BugChecker instead.", link = "", allowedOnPath = ".*/third_party/java_src/error_prone/project/check_api/src/main/java/com/google/errorprone/bugpatterns/BugChecker.java" + "|.*/third_party/java_src/error_prone/project/core/src/main/java/com/google/errorprone/refaster/RefasterScanner.java") public static Builder builder(JCTree tree, String name, @Nullable String link, String message) { return new Builder(tree, name, link, message); } /** Builder for {@code Description}s. */ public static class Builder { private final DiagnosticPosition position; private final String name; private String linkUrl; private Optional<SeverityLevel> severity = Optional.empty(); private final ImmutableList.Builder<Fix> fixListBuilder = ImmutableList.builder(); private String rawMessage; private Builder( DiagnosticPosition position, String name, @Nullable String linkUrl, String rawMessage) { this.position = Preconditions.checkNotNull(position); this.name = Preconditions.checkNotNull(name); this.linkUrl = linkUrl; this.rawMessage = Preconditions.checkNotNull(rawMessage); } /** * Adds a suggested fix for this {@code Description}. Fixes should be added in order of * decreasing preference. Adding an empty fix is a no-op. * * @param fix a suggested fix for this problem * @throws NullPointerException if {@code fix} is {@code null} */ @CanIgnoreReturnValue public Builder addFix(Fix fix) { checkNotNull(fix, "fix must not be null"); if (!fix.isEmpty()) { fixListBuilder.add(fix); } return this; } /** * Adds a suggested fix for this {@code Description} if {@code fix} is present. Fixes should be * added in order of decreasing preference. Adding an empty fix is a no-op. * * @param fix a suggested fix for this problem * @throws NullPointerException if {@code fix} is {@code null} * @deprecated prefer referring to empty fixes using {@link SuggestedFix#emptyFix()}. */ @CanIgnoreReturnValue @Deprecated public Builder addFix(Optional<? extends Fix> fix) { checkNotNull(fix, "fix must not be null"); fix.ifPresent(this::addFix); return this; } /** * Add each fix in order. * * @param fixes a list of suggested fixes for this problem * @throws NullPointerException if {@code fixes} or any of its elements are {@code null} */ @CanIgnoreReturnValue public Builder addAllFixes(List<? extends Fix> fixes) { checkNotNull(fixes, "fixes must not be null"); for (Fix fix : fixes) { addFix(fix); } return this; } /** * Set a custom error message for this {@code Description}. The custom message will be used * instead of the summary field as the text for the diagnostic message. * * @param message A custom error message without the check name ("[checkname]") or link */ @CanIgnoreReturnValue public Builder setMessage(String message) { checkNotNull(message, "message must not be null"); this.rawMessage = message; return this; } /** * Set a custom link URL. The custom URL will be used instead of the default one which forms * part of the {@code @}BugPattern. */ @CanIgnoreReturnValue public Builder setLinkUrl(String linkUrl) { checkNotNull(linkUrl, "linkUrl must not be null"); this.linkUrl = linkUrl; return this; } @RestrictedApi( explanation = "Prefer to set a single default severity using @BugPattern. Overriding the severity for" + " individual Descriptions causes any command line options to be ignored, which is" + " potentially very confusing.", link = "", allowedOnPath = ".*/third_party/java_src/error_prone/project/check_api/src/main/java/com/google/errorprone/matchers/Description.java$|" + ".*/java/com/google/devtools/javatools/staticanalysis/xlang/java/BugCheckerUsingXlang.java$|" + ".*/java/com/google/devtools/staticanalysis/errorprone/RestrictedInheritanceChecker.java$|" + ".*/java/com/google/devtools/staticanalysis/errorprone/pluggabletype/LatticeAdapter.java$|" + ".*/third_party/java_src/error_prone/project/core/src/main/java/com/google/errorprone/bugpatterns/RestrictedApiChecker.java$|" + ".*/third_party/java_src/error_prone/project/core/src/main/java/com/google/errorprone/refaster/RefasterScanner.java$") @CanIgnoreReturnValue public Builder overrideSeverity(SeverityLevel severity) { checkNotNull(severity, "severity must not be null"); this.severity = Optional.of(severity); return this; } public Description build() { return new Description(position, name, rawMessage, linkUrl, fixListBuilder.build(), severity); } } }
11,053
37.117241
144
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/Matcher.java
/* * Copyright 2011 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.matchers; import com.google.errorprone.VisitorState; import com.sun.source.tree.Tree; import java.io.Serializable; /** * Define a predicate on a {@link Tree}, which also accesses the state of AST traversal. * * @param <T> a javac AST node * @author alexeagle@google.com (Alex Eagle) */ @FunctionalInterface public interface Matcher<T extends Tree> extends Serializable { boolean matches(T t, VisitorState state); }
1,063
31.242424
88
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/CompoundAssignment.java
/* * Copyright 2013 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.matchers; import com.google.common.collect.ImmutableSet; import com.google.errorprone.VisitorState; import com.sun.source.tree.CompoundAssignmentTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.Tree.Kind; import java.util.Set; /** Matcher for a compound-assignment operator expression. */ public class CompoundAssignment implements Matcher<CompoundAssignmentTree> { private static final ImmutableSet<Kind> COMPOUND_ASSIGNMENT_OPERATORS = ImmutableSet.of( Kind.AND_ASSIGNMENT, Kind.DIVIDE_ASSIGNMENT, Kind.LEFT_SHIFT_ASSIGNMENT, Kind.MINUS_ASSIGNMENT, Kind.MULTIPLY_ASSIGNMENT, Kind.OR_ASSIGNMENT, Kind.PLUS_ASSIGNMENT, Kind.REMAINDER_ASSIGNMENT, Kind.RIGHT_SHIFT_ASSIGNMENT, Kind.UNSIGNED_RIGHT_SHIFT_ASSIGNMENT, Kind.XOR_ASSIGNMENT); private final Set<Kind> operators; private final Matcher<ExpressionTree> receiverMatcher; private final Matcher<ExpressionTree> expressionMatcher; /** * Creates a new compound-assignment operator matcher, which matches a compound assignment * expression with one of a set of operators and whose receiver and expression match the given * matchers. * * @param operators The set of matching compound-assignment operators. These are drawn from the * {@link Kind} enum values which link to {@link CompoundAssignmentTree} in their javadoc. * @param receiverMatcher The matcher which must match the receiver which will be assigned to. * @param expressionMatcher The matcher which must match the right-hand expression to the compound * assignment. */ public CompoundAssignment( Set<Kind> operators, Matcher<ExpressionTree> receiverMatcher, Matcher<ExpressionTree> expressionMatcher) { this.operators = validateOperators(operators); if (receiverMatcher == null) { throw new NullPointerException("CompoundAssignment receiver matcher is null"); } if (expressionMatcher == null) { throw new NullPointerException("CompoundAssignment expression matcher is null"); } this.receiverMatcher = receiverMatcher; this.expressionMatcher = expressionMatcher; } @Override public boolean matches(CompoundAssignmentTree compoundAssignmentTree, VisitorState state) { if (!operators.contains(compoundAssignmentTree.getKind())) { return false; } return receiverMatcher.matches(compoundAssignmentTree.getVariable(), state) && expressionMatcher.matches(compoundAssignmentTree.getExpression(), state); } /** * Returns the provided set of operators if they are all compound-assignment operators. Otherwise, * throws an IllegalArgumentException. */ private static Set<Kind> validateOperators(Set<Kind> kinds) { for (Kind kind : kinds) { if (!COMPOUND_ASSIGNMENT_OPERATORS.contains(kind)) { throw new IllegalArgumentException(kind.name() + " is not a compound-assignment operator."); } } return kinds; } }
3,684
37.789474
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/AbstractTypeMatcher.java
/* * Copyright 2013 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.matchers; import static com.google.errorprone.suppliers.Suppliers.typeFromString; import com.google.errorprone.VisitorState; import com.google.errorprone.suppliers.Supplier; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Type; /** Base class for type matchers. */ public abstract class AbstractTypeMatcher<T extends Tree> implements Matcher<T> { protected Supplier<Type> typeToCompareSupplier; public AbstractTypeMatcher(Supplier<Type> typeToCompareSupplier) { this.typeToCompareSupplier = typeToCompareSupplier; } public AbstractTypeMatcher(String typeString) { this(typeFromString(typeString)); } @Override public abstract boolean matches(T tree, VisitorState state); }
1,358
31.357143
81
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/TestNgMatchers.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.matchers; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.streamSuperMethods; import com.google.errorprone.VisitorState; import com.sun.source.tree.ClassTree; import com.sun.source.tree.MethodTree; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; /** * Matchers for code patterns which appear to be TestNG-based tests. * * @author bhagwani@google.com (Sumit Bhagwani) */ public class TestNgMatchers { /** * Checks if a method, or any overridden method, is annotated with any annotation from the * org.testng package. */ public static boolean hasTestNgAnnotation(MethodTree tree, VisitorState state) { MethodSymbol methodSym = getSymbol(tree); if (methodSym == null) { return false; } if (hasTestNgAttr(methodSym)) { return true; } return streamSuperMethods(methodSym, state.getTypes()).anyMatch(TestNgMatchers::hasTestNgAttr); } /** Checks if a class is annotated with any annotation from the org.testng package. */ public static boolean hasTestNgAnnotation(ClassTree tree) { ClassSymbol classSym = getSymbol(tree); return classSym != null && hasTestNgAttr(classSym); } /** Checks if a symbol has any attribute from the org.testng package. */ private static boolean hasTestNgAttr(Symbol methodSym) { return methodSym.getRawAttributes().stream() .anyMatch(attr -> attr.type.tsym.getQualifiedName().toString().startsWith("org.testng.")); } private TestNgMatchers() {} }
2,265
34.40625
99
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/AnnotationMatcher.java
/* * Copyright 2013 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.matchers; import com.google.errorprone.VisitorState; import com.sun.source.tree.AnnotatedTypeTree; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.PackageTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; /** * Matches if the given annotation matcher matches all of or any of the annotations on the tree * node. * * @author eaftan@google.com (Eddie Aftandilian) */ public class AnnotationMatcher<T extends Tree> extends ChildMultiMatcher<T, AnnotationTree> { public AnnotationMatcher(MatchType matchType, Matcher<AnnotationTree> nodeMatcher) { super(matchType, nodeMatcher); } @Override protected Iterable<? extends AnnotationTree> getChildNodes(T tree, VisitorState state) { if (tree instanceof ClassTree) { return ((ClassTree) tree).getModifiers().getAnnotations(); } else if (tree instanceof VariableTree) { return ((VariableTree) tree).getModifiers().getAnnotations(); } else if (tree instanceof MethodTree) { return ((MethodTree) tree).getModifiers().getAnnotations(); } else if (tree instanceof CompilationUnitTree) { return ((CompilationUnitTree) tree).getPackageAnnotations(); } else if (tree instanceof AnnotatedTypeTree) { return ((AnnotatedTypeTree) tree).getAnnotations(); } else if (tree instanceof PackageTree) { return ((PackageTree) tree).getAnnotations(); } else { throw new IllegalArgumentException( "Cannot access annotations from tree of type " + tree.getClass()); } } }
2,313
36.934426
95
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/IsSymbol.java
/* * Copyright 2013 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.matchers; import com.google.errorprone.VisitorState; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Symbol; /** * Matches a symbol with the given symbol as superclass. * * @author cushon@google.com (Liam Miller-Cushon) */ class IsSymbol implements Matcher<Tree> { private final Class<? extends Symbol> symbolClass; public IsSymbol(Class<? extends Symbol> symbolClass) { this.symbolClass = symbolClass; } @Override public boolean matches(Tree item, VisitorState state) { Symbol sym = ASTHelpers.getSymbol(item); return symbolClass.isAssignableFrom(sym.getClass()); } }
1,303
30.047619
75
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/StringLiteral.java
/* * Copyright 2012 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.matchers; import com.google.errorprone.VisitorState; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.LiteralTree; import java.util.function.Predicate; import java.util.regex.Pattern; /** * @author eaftan@google.com (Eddie Aftandilian) * @author pepstein@google.com (Peter Epstein) */ public class StringLiteral implements Matcher<ExpressionTree> { private final Predicate<String> matcher; public StringLiteral(String value) { this.matcher = value::equals; } public StringLiteral(Pattern pattern) { this.matcher = pattern.asPredicate(); } @Override public boolean matches(ExpressionTree expressionTree, VisitorState state) { if (expressionTree instanceof LiteralTree) { LiteralTree literalTree = (LiteralTree) expressionTree; Object actualValue = literalTree.getValue(); return actualValue instanceof String && matcher.test((String) actualValue); } else { return false; } } }
1,605
29.884615
81
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/UnusedReturnValueMatcher.java
/* * Copyright 2012 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.matchers; import static com.google.errorprone.matchers.Matchers.allOf; import static com.google.errorprone.matchers.Matchers.anyOf; import static com.google.errorprone.matchers.Matchers.enclosingMethod; import static com.google.errorprone.matchers.Matchers.enclosingNode; import static com.google.errorprone.matchers.Matchers.expressionStatement; import static com.google.errorprone.matchers.Matchers.instanceMethod; import static com.google.errorprone.matchers.Matchers.isLastStatementInBlock; import static com.google.errorprone.matchers.Matchers.isThrowingFunctionalInterface; import static com.google.errorprone.matchers.Matchers.kindIs; import static com.google.errorprone.matchers.Matchers.methodCallInDeclarationOfThrowingRunnable; import static com.google.errorprone.matchers.Matchers.nextStatement; import static com.google.errorprone.matchers.Matchers.parentNode; import static com.google.errorprone.matchers.Matchers.previousStatement; import static com.google.errorprone.matchers.Matchers.staticMethod; import static com.google.errorprone.util.ASTHelpers.findEnclosingNode; import static com.google.errorprone.util.ASTHelpers.getReceiver; import static com.google.errorprone.util.ASTHelpers.getResultType; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.isVoidType; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.CheckReturnValue; import com.google.errorprone.util.ASTHelpers; import com.google.errorprone.util.MoreAnnotations; import com.sun.source.tree.BlockTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MemberReferenceTree; import com.sun.source.tree.MemberReferenceTree.ReferenceMode; import com.sun.source.tree.MethodTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.MethodType; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; import java.util.stream.Stream; import javax.lang.model.type.TypeKind; /** * Matches expressions that invoke or reference a non-void method or constructor and which do not * use their return value and are not in a context where non-use of the return value is allowed. */ @CheckReturnValue public final class UnusedReturnValueMatcher implements Matcher<ExpressionTree> { private static final ImmutableMap<AllowReason, Matcher<ExpressionTree>> ALLOW_MATCHERS = ImmutableMap.of( AllowReason.MOCKING_CALL, UnusedReturnValueMatcher::mockitoInvocation, AllowReason.EXCEPTION_TESTING, UnusedReturnValueMatcher::exceptionTesting, AllowReason.RETURNS_JAVA_LANG_VOID, UnusedReturnValueMatcher::returnsJavaLangVoid); private static final ImmutableSet<AllowReason> DISALLOW_EXCEPTION_TESTING = Sets.immutableEnumSet( Sets.filter(ALLOW_MATCHERS.keySet(), k -> !k.equals(AllowReason.EXCEPTION_TESTING))); /** Gets an instance of this matcher. */ public static UnusedReturnValueMatcher get(boolean allowInExceptionThrowers) { return new UnusedReturnValueMatcher( allowInExceptionThrowers ? ALLOW_MATCHERS.keySet() : DISALLOW_EXCEPTION_TESTING); } private final ImmutableSet<AllowReason> validAllowReasons; private UnusedReturnValueMatcher(ImmutableSet<AllowReason> validAllowReasons) { this.validAllowReasons = validAllowReasons; } @Override public boolean matches(ExpressionTree tree, VisitorState state) { return isReturnValueUnused(tree, state) && !isAllowed(tree, state); } private static boolean isVoidMethod(MethodSymbol symbol) { return !symbol.isConstructor() && isVoid(symbol.getReturnType()); } private static boolean isVoid(Type type) { return type.getKind() == TypeKind.VOID; } private static boolean implementsVoidMethod(ExpressionTree tree, VisitorState state) { return isVoid(state.getTypes().findDescriptorType(getType(tree)).getReturnType()); } /** * Returns {@code true} if and only if the given {@code tree} is an invocation of or reference to * a constructor or non-{@code void} method for which the return value is considered unused. */ public static boolean isReturnValueUnused(ExpressionTree tree, VisitorState state) { Symbol sym = getSymbol(tree); if (!(sym instanceof MethodSymbol) || isVoidMethod((MethodSymbol) sym)) { return false; } if (tree instanceof MemberReferenceTree) { // Runnable r = foo::getBar; return implementsVoidMethod(tree, state); } Tree parent = state.getPath().getParentPath().getLeaf(); return parent instanceof LambdaExpressionTree // Runnable r = () -> foo.getBar(); ? implementsVoidMethod((LambdaExpressionTree) parent, state) // foo.getBar(); : parent.getKind() == Kind.EXPRESSION_STATEMENT; } /** * Returns {@code true} if the given expression is allowed to have an unused return value based on * its context. */ public boolean isAllowed(ExpressionTree tree, VisitorState state) { return getAllowReasons(tree, state).findAny().isPresent(); } /** * Returns a stream of reasons the given expression is allowed to have an unused return value * based on its context. */ public Stream<AllowReason> getAllowReasons(ExpressionTree tree, VisitorState state) { return validAllowReasons.stream() .filter(reason -> ALLOW_MATCHERS.get(reason).matches(tree, state)); } private static boolean returnsJavaLangVoid(ExpressionTree tree, VisitorState state) { return tree instanceof MemberReferenceTree ? returnsJavaLangVoid((MemberReferenceTree) tree, state) : isVoidType(getResultType(tree), state); } private static boolean returnsJavaLangVoid(MemberReferenceTree tree, VisitorState state) { if (tree.getMode() == ReferenceMode.NEW) { // constructors can't return java.lang.Void return false; } // We need to do this to get the correct return type for things like future::get when future // is a Future<Void>. // - The Type of the method reference is the functional interface type it's implementing. // - The Symbol is the declared method symbol, i.e. V get(). // So we resolve the symbol (V get()) as a member of the qualifier type (Future<Void>) to get // the method type (Void get()) and then look at the return type of that. Type type = state.getTypes().memberType(getType(tree.getQualifierExpression()), getSymbol(tree)); // TODO(cgdecker): There are probably other types than MethodType that we could resolve here return type instanceof MethodType && isVoidType(type.getReturnType(), state); } private static boolean exceptionTesting(ExpressionTree tree, VisitorState state) { return tree instanceof MemberReferenceTree ? isThrowingFunctionalInterface(getType(tree), state) : expectedExceptionTest(state); } private static final Matcher<ExpressionTree> FAIL_METHOD = anyOf( instanceMethod().onDescendantOf("com.google.common.truth.AbstractVerb").named("fail"), instanceMethod() .onDescendantOf("com.google.common.truth.StandardSubjectBuilder") .named("fail"), staticMethod().onClass("org.junit.Assert").named("fail"), staticMethod().onClass("junit.framework.Assert").named("fail"), staticMethod().onClass("junit.framework.TestCase").named("fail")); private static final Matcher<StatementTree> EXPECTED_EXCEPTION_MATCHER = anyOf( // expectedException.expect(Foo.class); me(); allOf( isLastStatementInBlock(), previousStatement( expressionStatement( anyOf(instanceMethod().onExactClass("org.junit.rules.ExpectedException"))))), // try { me(); fail(); } catch (Throwable t) {} allOf(enclosingNode(kindIs(Kind.TRY)), nextStatement(expressionStatement(FAIL_METHOD))), // assertThrows(Throwable.class, () => { me(); }) allOf( anyOf(isLastStatementInBlock(), parentNode(kindIs(Kind.LAMBDA_EXPRESSION))), // Within the context of a ThrowingRunnable/Executable: (t, s) -> methodCallInDeclarationOfThrowingRunnable(s)), // @Test(expected = FooException.class) void bah() { me(); } allOf( UnusedReturnValueMatcher::isOnlyStatementInBlock, enclosingMethod(UnusedReturnValueMatcher::isTestExpectedExceptionMethod))); private static boolean isTestExpectedExceptionMethod(MethodTree tree, VisitorState state) { if (!JUnitMatchers.wouldRunInJUnit4.matches(tree, state)) { return false; } return getSymbol(tree).getAnnotationMirrors().stream() .filter(am -> am.type.tsym.getQualifiedName().contentEquals("org.junit.Test")) .findFirst() .flatMap(testAm -> MoreAnnotations.getAnnotationValue(testAm, "expected")) .flatMap(MoreAnnotations::asTypeValue) .filter(tv -> !tv.toString().equals("org.junit.Test.None")) .isPresent(); } private static boolean isOnlyStatementInBlock(StatementTree t, VisitorState s) { BlockTree parentBlock = ASTHelpers.findEnclosingNode(s.getPath(), BlockTree.class); return parentBlock != null && parentBlock.getStatements().size() == 1 && parentBlock.getStatements().get(0) == t; } /** Allow return values to be ignored in tests that expect an exception to be thrown. */ public static boolean expectedExceptionTest(VisitorState state) { // Allow unused return values in tests that check for thrown exceptions, e.g.: // // try { // Foo.newFoo(-1); // fail(); // } catch (IllegalArgumentException expected) { // } // StatementTree statement = findEnclosingNode(state.getPath(), StatementTree.class); return statement != null && EXPECTED_EXCEPTION_MATCHER.matches(statement, state); } private static final Matcher<ExpressionTree> MOCKITO_MATCHER = anyOf( staticMethod().onClass("org.mockito.Mockito").named("verify"), instanceMethod().onDescendantOf("org.mockito.stubbing.Stubber").named("when"), instanceMethod().onDescendantOf("org.mockito.InOrder").named("verify")); /** * Don't match the method that is invoked through {@code Mockito.verify(t)} or {@code * doReturn(val).when(t)}. */ public static boolean mockitoInvocation(Tree tree, VisitorState state) { if (!(tree instanceof JCMethodInvocation)) { return false; } JCMethodInvocation invocation = (JCMethodInvocation) tree; if (!(invocation.getMethodSelect() instanceof JCFieldAccess)) { return false; } ExpressionTree receiver = getReceiver(invocation); return MOCKITO_MATCHER.matches(receiver, state); } /** * Enumeration of known reasons that an unused return value may be allowed because of the context * in which the method is used. Suppression is not considered here; these are reasons that don't * have anything to do with specific checkers. */ public enum AllowReason { /** * The context is one in which the method is probably being called to test for an exception it * throws. */ EXCEPTION_TESTING, /** The context is a mocking call such as in {@code verify(foo).getBar();}. */ MOCKING_CALL, /** The method returns {@code java.lang.Void} at this use-site. */ RETURNS_JAVA_LANG_VOID, /** The method is a known Builder setter method (that always returns "this"). */ KNOWN_BUILDER_SETTER, } }
12,705
43.118056
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/method/MethodMatcherImpl.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.matchers.method; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.errorprone.VisitorState; import com.google.errorprone.matchers.method.MethodMatchers.AnyMethodMatcher; import com.google.errorprone.matchers.method.MethodMatchers.ConstructorClassMatcher; import com.google.errorprone.matchers.method.MethodMatchers.ConstructorMatcher; import com.google.errorprone.matchers.method.MethodMatchers.InstanceMethodMatcher; import com.google.errorprone.matchers.method.MethodMatchers.MethodClassMatcher; import com.google.errorprone.matchers.method.MethodMatchers.MethodNameMatcher; import com.google.errorprone.matchers.method.MethodMatchers.MethodSignatureMatcher; import com.google.errorprone.matchers.method.MethodMatchers.ParameterMatcher; import com.google.errorprone.matchers.method.MethodMatchers.StaticMethodMatcher; import com.google.errorprone.predicates.TypePredicate; import com.google.errorprone.predicates.TypePredicates; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.suppliers.Suppliers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.tools.javac.code.Type; import java.util.Iterator; import java.util.List; import java.util.function.Predicate; import java.util.regex.Pattern; final class MethodMatcherImpl implements InstanceMethodMatcher, StaticMethodMatcher, AnyMethodMatcher, MethodClassMatcher, MethodSignatureMatcher, MethodNameMatcher, ConstructorMatcher, ConstructorClassMatcher, ParameterMatcher { /** * The fluent API methods in this class build up a list of constraints, which can either be used * as a predicate (by calling {@link #matches(MatchState, VisitorState)} on each Constraint in the * list), or exported as a rule set for {@link MethodInvocationMatcher#compile(Iterable)}. */ private interface Constraint { /** Tests whether this Constraint is satisfied with the method invocation we're checking. */ boolean matches(MatchState m, VisitorState s); } static final AnyMethodMatcher ANY_METHOD = new MethodMatcherImpl( BaseMethodMatcher.METHOD, ImmutableList.of( (m, s) -> { // Handled by base matcher. return true; })); static final ConstructorMatcher CONSTRUCTOR = new MethodMatcherImpl(BaseMethodMatcher.CONSTRUCTOR, ImmutableList.of((m, s) -> true)); static final StaticMethodMatcher STATIC_METHOD = new MethodMatcherImpl( BaseMethodMatcher.METHOD, ImmutableList.of((m, s) -> m.sym().isStatic())); static final InstanceMethodMatcher INSTANCE_METHOD = new MethodMatcherImpl( BaseMethodMatcher.METHOD, ImmutableList.of((m, s) -> !m.sym().isStatic())); private final BaseMethodMatcher baseMatcher; private final ImmutableList<Constraint> constraints; // All constructors private: only static final instances are legal starting points for chains. private MethodMatcherImpl(BaseMethodMatcher baseMatcher, ImmutableList<Constraint> matchers) { this.baseMatcher = baseMatcher; this.constraints = matchers; } private MethodMatcherImpl append(Constraint c) { return new MethodMatcherImpl( baseMatcher, ImmutableList.<Constraint>builder().addAll(this.constraints).add(c).build()); } @Override public boolean matches(ExpressionTree tree, VisitorState state) { MatchState method = baseMatcher.match(tree); if (method == null) { return false; } for (Constraint constraint : constraints) { if (!constraint.matches(method, state)) { return false; } } return true; } @Override public MethodClassMatcher onClass(TypePredicate predicate) { return append((m, s) -> predicate.apply(m.ownerType(), s)); } @Override public MethodClassMatcher onClass(String className) { TypePredicate pred = TypePredicates.isExactType(className); return append((m, s) -> pred.apply(m.ownerType(), s)); } @Override public MethodClassMatcher onClass(Supplier<Type> classType) { return onClass(TypePredicates.isExactType(classType)); } @Override public MethodClassMatcher onClassAny(Iterable<String> classNames) { TypePredicate pred = TypePredicates.isExactTypeAny(classNames); return append((m, s) -> pred.apply(m.ownerType(), s)); } @Override public MethodClassMatcher onClassAny(String... classNames) { return onClassAny(ImmutableList.copyOf(classNames)); } @Override public MethodClassMatcher onExactClass(String className) { return onClass(className); } @Override public MethodClassMatcher onExactClass(Supplier<Type> classType) { return onClass(classType); } @Override public MethodClassMatcher onExactClassAny(Iterable<String> classTypes) { return onClassAny(classTypes); } @Override public MethodClassMatcher onExactClassAny(String... classTypes) { return onClassAny(classTypes); } @Override public MethodClassMatcher onDescendantOf(String className) { TypePredicate pred = TypePredicates.isDescendantOf(className); return append((m, s) -> pred.apply(m.ownerType(), s)); } @Override public MethodClassMatcher onDescendantOf(Supplier<Type> classType) { return onClass(TypePredicates.isDescendantOf(classType)); } @Override public MethodClassMatcher onDescendantOfAny(String... classTypes) { return onDescendantOfAny(ImmutableList.copyOf(classTypes)); } @Override public MethodClassMatcher onDescendantOfAny(Iterable<String> classTypes) { TypePredicate pred = TypePredicates.isDescendantOfAny(classTypes); return append((m, s) -> pred.apply(m.ownerType(), s)); } @Override public MethodClassMatcher anyClass() { return this; } @Override public MethodNameMatcher named(String name) { checkArgument( !name.contains("(") && !name.contains(")"), "method name (%s) cannot contain parentheses; use \"foo\" instead of \"foo()\"", name); return append((m, s) -> m.sym().getSimpleName().contentEquals(name)); } @Override public MethodNameMatcher namedAnyOf(String... names) { return namedAnyOf(ImmutableSet.copyOf(names)); } @Override public MethodNameMatcher namedAnyOf(Iterable<String> names) { ImmutableSet<String> expected = ImmutableSet.copyOf(names); return append((m, s) -> expected.contains(m.sym().getSimpleName().toString())); } @Override public MethodNameMatcher withAnyName() { return this; } private MethodNameMatcher stringConstraint(Predicate<String> constraint) { return append((m, s) -> constraint.test(m.sym().getSimpleName().toString())); } @Override public MethodNameMatcher withNameMatching(Pattern pattern) { return stringConstraint(s -> pattern.matcher(s).matches()); } @Override public MethodSignatureMatcher withSignature(String signature) { // TODO(cushon): build a way to match signatures (including varargs ones!) that doesn't // rely on MethodSymbol#toString(). return append( (m, s) -> m.sym().getSimpleName().contentEquals(signature) || m.sym().toString().equals(signature)); } @Override public ParameterMatcher withNoParameters() { return withParameters(ImmutableList.of()); } @Override public ParameterMatcher withParameters(String first, String... rest) { return withParameters(Lists.asList(first, rest)); } @Override public ParameterMatcher withParameters(Iterable<String> expected) { return withParametersOfType(Suppliers.fromStrings(expected)); } @Override public ParameterMatcher withParametersOfType(Iterable<Supplier<Type>> expected) { return append( (method, state) -> { List<Type> actual = method.paramTypes(); if (actual.size() != Iterables.size(expected)) { return false; } Iterator<Type> ax = actual.iterator(); Iterator<Supplier<Type>> bx = expected.iterator(); while (ax.hasNext()) { if (!ASTHelpers.isSameType(ax.next(), bx.next().get(state), state)) { return false; } } return true; }); } @Override public ConstructorClassMatcher forClass(TypePredicate predicate) { return append((m, s) -> predicate.apply(m.ownerType(), s)); } @Override public ConstructorClassMatcher forClass(String className) { return append((m, s) -> m.ownerType().asElement().getQualifiedName().contentEquals(className)); } @Override public ConstructorClassMatcher forClass(Supplier<Type> classType) { return forClass(TypePredicates.isExactType(classType)); } }
9,580
33.217857
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/method/BaseMethodMatcher.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.matchers.method; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import org.checkerframework.checker.nullness.qual.Nullable; interface BaseMethodMatcher { @Nullable MatchState match(ExpressionTree tree); BaseMethodMatcher METHOD = tree -> { Symbol sym = ASTHelpers.getSymbol(tree); if (!(sym instanceof MethodSymbol)) { return null; } if (tree instanceof NewClassTree) { // Don't match constructors as they are neither static nor instance methods. return null; } if (tree instanceof MethodInvocationTree) { tree = ((MethodInvocationTree) tree).getMethodSelect(); } return MethodMatchState.create(tree, (MethodSymbol) sym); }; BaseMethodMatcher CONSTRUCTOR = tree -> { switch (tree.getKind()) { case NEW_CLASS: case METHOD_INVOCATION: case MEMBER_REFERENCE: break; default: return null; } Symbol sym = ASTHelpers.getSymbol(tree); if (!(sym instanceof MethodSymbol)) { return null; } MethodSymbol method = (MethodSymbol) sym; if (!method.isConstructor()) { return null; } return ConstructorMatchState.create(method); }; }
2,176
31.984848
86
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/method/ConstructorMatchState.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.matchers.method; import com.google.auto.value.AutoValue; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Type; /** The state that is propagated across a match operation for constructors. */ @AutoValue public abstract class ConstructorMatchState implements MatchState { /** The type of the class in which a member method or constructor is declared. */ @Override public Type ownerType() { return sym().owner.type; } /** The method being matched. */ @Override public abstract MethodSymbol sym(); static MatchState create(MethodSymbol methodSymbol) { return new AutoValue_ConstructorMatchState(methodSymbol); } }
1,314
32.717949
83
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/method/MatchState.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.matchers.method; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Type; import java.util.List; /** The state that is propagated across a match operation. */ public interface MatchState { /** The type of the class in which a member method or constructor is declared. */ Type ownerType(); /** The method being matched. */ MethodSymbol sym(); /** The method's formal parameter types. */ default List<Type> paramTypes() { return sym().type.getParameterTypes(); } }
1,158
31.194444
83
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/method/MethodMatchers.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.matchers.method; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.predicates.TypePredicate; import com.google.errorprone.suppliers.Supplier; import com.sun.source.tree.ExpressionTree; import com.sun.tools.javac.code.Type; import java.util.regex.Pattern; public final class MethodMatchers { /** * @deprecated use {@code Matcher<ExpressionTree>} instead of referring directly to this type. */ @Deprecated public interface MethodMatcher extends Matcher<ExpressionTree> {} // Language definition for fluent method matchers. /** * @deprecated use {@code Matcher<ExpressionTree>} instead of referring directly to this type. */ @Deprecated public interface InstanceMethodMatcher extends MethodMatcher { /** Match on types that satisfy the given predicate. */ MethodClassMatcher onClass(TypePredicate predicate); /** Match on types with the given fully-qualified name. (e.g. {@code java.lang.String}) */ MethodClassMatcher onExactClass(String className); /** Match on the given type exactly. */ MethodClassMatcher onExactClass(Supplier<Type> classType); /** Match on types that are exactly the same as any of the given types. */ MethodClassMatcher onExactClassAny(Iterable<String> classTypes); /** Match on types that are exactly the same as any of the given types. */ MethodClassMatcher onExactClassAny(String... classTypes); /** Match on descendants of the given fully-qualified type name. */ MethodClassMatcher onDescendantOf(String className); /** Match on descendants of the given type. */ MethodClassMatcher onDescendantOf(Supplier<Type> classType); /** Match on types that are descendants of any of the given types. */ MethodClassMatcher onDescendantOfAny(String... classTypes); /** Match on types that are descendants of any of the given types. */ MethodClassMatcher onDescendantOfAny(Iterable<String> classTypes); /** Match on any class. */ MethodClassMatcher anyClass(); } /** * @deprecated use {@code Matcher<ExpressionTree>} instead of referring directly to this type. */ @Deprecated public interface StaticMethodMatcher extends MethodMatcher { /** Match on types that satisfy the given predicate. */ MethodClassMatcher onClass(TypePredicate predicate); /** Match on types with the given fully-qualified name. (e.g. {@code java.lang.String}) */ MethodClassMatcher onClass(String className); /** Match on the given type exactly. */ MethodClassMatcher onClass(Supplier<Type> classType); /** Match on types that are equal to any of the given types. */ MethodClassMatcher onClassAny(Iterable<String> classNames); /** Match on types that are equal to any of the given types. */ MethodClassMatcher onClassAny(String... classNames); /** Match on descendants of the given fully-qualified type name. */ MethodClassMatcher onDescendantOf(String className); /** Match on descendants of the given type. */ MethodClassMatcher onDescendantOf(Supplier<Type> classType); /** Match on types that are descendants of any of the given types. */ MethodClassMatcher onDescendantOfAny(String... classTypes); /** Match on types that are descendants of any of the given types. */ MethodClassMatcher onDescendantOfAny(Iterable<String> classTypes); /** Match on any class. */ MethodClassMatcher anyClass(); } /** * @deprecated use {@code Matcher<ExpressionTree>} instead of referring directly to this type. */ @Deprecated public interface AnyMethodMatcher extends MethodMatcher { /** Match the given type exactly. */ MethodClassMatcher onClass(TypePredicate predicate); /** Match on types with the given fully-qualified name. (e.g. {@code java.lang.String}) */ MethodClassMatcher onClass(String className); /** Match on descendants of the given fully-qualified type name. */ MethodClassMatcher onDescendantOf(String className); /** Match on descendants of the given type. */ MethodClassMatcher onDescendantOf(Supplier<Type> classType); /** Match on types that are descendants of any of the given types. */ MethodClassMatcher onDescendantOfAny(String... classTypes); /** Match on types that are descendants of any of the given types. */ MethodClassMatcher onDescendantOfAny(Iterable<String> classTypes); /** Match on any class. */ MethodClassMatcher anyClass(); } /** * @deprecated use {@code Matcher<ExpressionTree>} instead of referring directly to this type. */ @Deprecated public interface MethodClassMatcher extends MethodMatcher { /** Match methods with the given name. (e.g. {@code toString}) */ MethodNameMatcher named(String name); /** Match methods with any of the given names. */ MethodNameMatcher namedAnyOf(String... names); /** Match methods with any of the given names. */ MethodNameMatcher namedAnyOf(Iterable<String> names); /** Match methods with any name. */ MethodNameMatcher withAnyName(); /** Match methods with a name that matches the given regular expression. */ MethodNameMatcher withNameMatching(Pattern pattern); /** * Match methods with the given signature. The implementation uses javac internals to * pretty-print the signatures, and the signature format is not well-specified. This matcher * should be used with caution. * * <p>Example: {@code format(java.lang.String,java.lang.Object...)} */ MethodSignatureMatcher withSignature(String signature); } /** * @deprecated use {@code Matcher<ExpressionTree>} instead of referring directly to this type. */ @Deprecated public interface MethodSignatureMatcher extends MethodMatcher {} /** * @deprecated use {@code Matcher<ExpressionTree>} instead of referring directly to this type. */ @Deprecated public interface MethodNameMatcher extends MethodMatcher { /** Match methods with no formal parameters. */ ParameterMatcher withNoParameters(); /** Match methods whose formal parameters have the given types. */ ParameterMatcher withParameters(String first, String... rest); /** Match methods whose formal parameters have the given types. */ ParameterMatcher withParameters(Iterable<String> parameters); /** Match constructors whose formal parameters have the given types. */ ParameterMatcher withParametersOfType(Iterable<Supplier<Type>> parameters); } /** * @deprecated use {@code Matcher<ExpressionTree>} instead of referring directly to this type. */ @Deprecated public interface ConstructorMatcher extends MethodMatcher { /** Match on types that satisfy the given predicate. */ ConstructorClassMatcher forClass(TypePredicate predicate); /** Match on the given type exactly. */ ConstructorClassMatcher forClass(String className); /** Match on the given type exactly. */ ConstructorClassMatcher forClass(Supplier<Type> classType); } /** * @deprecated use {@code Matcher<ExpressionTree>} instead of referring directly to this type. */ @Deprecated public interface ConstructorClassMatcher extends MethodMatcher { /** Match constructors with no formal parameters. */ ParameterMatcher withNoParameters(); /** Match constructors whose formal parameters have the given types. */ ParameterMatcher withParameters(String first, String... rest); /** Match constructors whose formal parameters have the given types. */ ParameterMatcher withParameters(Iterable<String> parameters); /** Match constructors whose formal parameters have the given types. */ ParameterMatcher withParametersOfType(Iterable<Supplier<Type>> parameters); } /** * @deprecated use {@code Matcher<ExpressionTree>} instead of referring directly to this type. */ @Deprecated public interface ParameterMatcher extends MethodMatcher {} // Method matcher factories public static StaticMethodMatcher staticMethod() { return MethodMatcherImpl.STATIC_METHOD; } public static InstanceMethodMatcher instanceMethod() { return MethodMatcherImpl.INSTANCE_METHOD; } public static AnyMethodMatcher anyMethod() { return MethodMatcherImpl.ANY_METHOD; } public static ConstructorMatcher constructor() { return MethodMatcherImpl.CONSTRUCTOR; } private MethodMatchers() {} }
9,042
35.46371
96
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/method/MethodMatchState.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.matchers.method; import com.google.auto.value.AutoValue; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Type; /** The state that is propagated across a match operation for methods. */ @AutoValue abstract class MethodMatchState implements MatchState { /** The type of the class in which a member method or constructor is declared. */ abstract ExpressionTree tree(); @Override public Type ownerType() { // TODO(cushon): should this be the symbol's owner type, not the receiver's owner type? return ASTHelpers.getReceiverType(tree()); } /** The method being matched. */ @Override public abstract MethodSymbol sym(); static MatchState create(ExpressionTree tree, MethodSymbol methodSymbol) { return new AutoValue_MethodMatchState(tree, methodSymbol); } }
1,554
33.555556
91
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/matchers/method/MethodInvocationMatcher.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.matchers.method; import com.google.auto.value.AutoValue; import com.google.common.base.Preconditions; import com.google.common.collect.HashBasedTable; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimaps; import com.google.common.collect.SetMultimap; import com.google.common.collect.Table; import com.google.errorprone.VisitorState; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ExpressionTree; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Type; import java.util.ArrayDeque; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.BiPredicate; import javax.annotation.Nullable; import javax.lang.model.element.ElementKind; /** * The machinery and type definitions necessary to model and compile a single efficient matcher out * of a list of {@link com.google.errorprone.matchers.method.MethodMatchers.MethodMatcher}s. */ public class MethodInvocationMatcher { static final class Context { final MethodSymbol sym; final ExpressionTree tree; Context(MethodSymbol sym, ExpressionTree tree) { this.sym = sym; this.tree = tree; } public static Optional<Context> create(ExpressionTree tree) { Symbol sym = ASTHelpers.getSymbol(tree); if (!(sym instanceof MethodSymbol)) { return Optional.empty(); } return Optional.of(new Context((MethodSymbol) sym, tree)); } } /** * The kinds of things that count as a method invocation. * * <p><strong>This is part of the low-level API for constructing Rule objects dynamically. * Consider using the fluent API from MethodMatcher, and the associated helpers in Matchers, when * possible.</strong> */ public enum MethodKind { STATIC, INSTANCE, CONSTRUCTOR } /** * The kinds of properties a matcher can match against. * * <p><strong>This is part of the low-level API for constructing Rule objects dynamically. * Consider using the fluent API from MethodMatcher, and the associated helpers in Matchers, when * possible.</strong> * * <p><em>The order of these enum constants is important</em>: it's the order in which we will * search the graph (because we iterate over values() to decide what order to check predicates). * Therefore, prefer putting first those properties which are cheap to check, or which will often * result in a failure to match (so we can prune the search space). */ public enum TokenType { KIND { @Override MethodKind extract(Context ctx, VisitorState s) { return ctx.sym.getKind() == ElementKind.CONSTRUCTOR ? MethodKind.CONSTRUCTOR : ctx.sym.isStatic() ? MethodKind.STATIC : MethodKind.INSTANCE; } }, METHOD_NAME { @Override String extract(Context ctx, VisitorState s) { return ctx.sym.getSimpleName().toString(); } }, PARAMETER_TYPES { @Override ImmutableList<String> extract(Context ctx, VisitorState s) { return ctx.sym.getParameters().stream() .map(param -> param.type.tsym.getQualifiedName().toString()) .collect(ImmutableList.toImmutableList()); } }, DEFINED_IN { @Override String extract(Context ctx, VisitorState s) { return ctx.sym.owner.getQualifiedName().toString(); } }, RECEIVER_TYPE { @Override String extract(Context ctx, VisitorState s) { return ASTHelpers.getReceiverType(ctx.tree).tsym.getQualifiedName().toString(); } }, RECEIVER_SUPERTYPE { @Override Type extract(Context ctx, VisitorState s) { return ASTHelpers.getReceiverType(ctx.tree).tsym.type; } }; abstract Object extract(Context ctx, VisitorState s); } /** * A specific value for a property that a method invocation can have. * * <p><strong>This is part of the low-level API for constructing Rule objects dynamically. * Consider using the fluent API from MethodMatcher, and the associated helpers in Matchers, when * possible. Do not create your own implementations of this interface.</strong> */ public interface Token { /** The category of properties that this value falls into. */ TokenType type(); /** * The value to compare with {@link TokenType#extract(Context, VisitorState)} to determine * whether this property matches. */ Object comparisonKey(); /** A token limiting the {@link Kind} of invocation to match. */ @AutoValue abstract class Kind implements Token { public abstract MethodKind kind(); public static Kind create(MethodKind kind) { return new AutoValue_MethodInvocationMatcher_Token_Kind(kind); } @Override public MethodKind comparisonKey() { return kind(); } @Override public TokenType type() { return TokenType.KIND; } } /** A token limiting the name of the method being invoked. */ @AutoValue abstract class MethodName implements Token { public abstract String methodName(); @Override public Object comparisonKey() { return methodName(); } @Override public TokenType type() { return TokenType.METHOD_NAME; } public static MethodName create(String methodName) { return new AutoValue_MethodInvocationMatcher_Token_MethodName(methodName); } } /** A token limiting the types of the formal parameters of the method being invoked. */ @AutoValue abstract class ParameterTypes implements Token { public abstract ImmutableList<String> parameterTypes(); @Override public TokenType type() { return TokenType.PARAMETER_TYPES; } @Override public Object comparisonKey() { return parameterTypes(); } public static ParameterTypes create(ImmutableList<String> types) { return new AutoValue_MethodInvocationMatcher_Token_ParameterTypes(types); } } /** A token specifying the class or interface in which the invoked method was defined. */ @AutoValue abstract class DefinedIn implements Token { public abstract String owner(); public static DefinedIn create(String owner) { return new AutoValue_MethodInvocationMatcher_Token_DefinedIn(owner); } @Override public TokenType type() { return TokenType.DEFINED_IN; } @Override public Object comparisonKey() { return owner(); } } /** * A token specifying the exact type of the object on which the method is being invoked (or the * class in which it is defined, for static methods). */ @AutoValue abstract class ReceiverType implements Token { public abstract String receiverType(); public static ReceiverType create(String receiverType) { return new AutoValue_MethodInvocationMatcher_Token_ReceiverType(receiverType); } @Override public Object comparisonKey() { return receiverType(); } @Override public TokenType type() { return TokenType.RECEIVER_TYPE; } } /** * A token specifying that the class of the object on which the method is being invoked must be * a subtype of another type. */ @AutoValue abstract class ReceiverSupertype implements Token { public abstract String receiverSupertype(); @Override public TokenType type() { return TokenType.RECEIVER_SUPERTYPE; } public static ReceiverSupertype create(String receiverSupertype) { return new AutoValue_MethodInvocationMatcher_Token_ReceiverSupertype(receiverSupertype); } @Override public Object comparisonKey() { // Can't do a key-based lookup for a supertype, but it's still useful to be able to put // these things in a map for iterating them. return receiverSupertype(); } } } /** * A rule describing a set of constraints for a method invocation. For each TokenType, a Rule * specifies 0 or more Tokens describing what values are allowed for that type. * * <p><strong>This is part of the low-level API for constructing Rule objects dynamically. * Consider using the fluent API from MethodMatcher, and the associated helpers in Matchers, when * possible.</strong> */ @AutoValue public abstract static class Rule { /** Builds a Rule object from a map. */ public static Rule create(ImmutableMap<TokenType, ? extends Set<Token>> required) { return new AutoValue_MethodInvocationMatcher_Rule(required); } // An absent token means to allow any value for this token type public abstract ImmutableMap<TokenType, ? extends Set<Token>> required(); } /** A Node is just a type synonym for Object - it's just a unique pointer. */ private static class Node {} /** * A map describing where to look next based on the current token, and a default if none match. */ private static class NodeWithDefault { private final Set<Node> states; @Nullable final Set<Node> def; final SetMultimap<Token, Node> mapping; NodeWithDefault(Set<Node> states, Set<Node> def, SetMultimap<Token, Node> mapping) { this.states = states; this.def = def; this.mapping = mapping; } } /** Shared by all compiled graphs, because it has no varying properties. */ private static final Node ACCEPT = new Node(); /** Converts a DFA produced by {@link #compile(Iterable)} into a Matcher based on map lookups. */ private static final class GraphMatcher { static Matcher<ExpressionTree> from( Map<Set<Node>, NodeWithDefault> mappings, NodeWithDefault root) { BiPredicate<Context, VisitorState> pred = traverse(mappings, root); return (tree, state) -> { Optional<Context> ctx = Context.create(tree); // Could be ctx.map(...).orElse(false), but why pay to box the Boolean? return ctx.isPresent() && pred.test(ctx.get(), state); }; } private static BiPredicate<Context, VisitorState> traverse( Map<Set<Node>, NodeWithDefault> mappings, NodeWithDefault root) { if (root.states.contains(ACCEPT)) { // If there was any path from the root to the accept node, the predicate matched. return (ctx, state) -> true; } SetMultimap<Token, Node> children = root.mapping; if (children.isEmpty()) { Preconditions.checkArgument(root.def != null, "Found node with no mappings and no default"); // Since this node is only a default, we don't have to bother checking its token type at // all, and can just return the next matcher we "would have" unconditionally delegated to. return traverse(mappings, mappings.get(root.def)); } ImmutableSet<TokenType> tokenTypes = children.keySet().stream().map(Token::type).collect(ImmutableSet.toImmutableSet()); Preconditions.checkArgument( tokenTypes.size() == 1, "Found mismatched token types in node with mappings %s", children); // We have a valid input. Translate each of its children into a Predicate, and return a new // Predicate that delegates appropriately depending on context TokenType type = tokenTypes.iterator().next(); // safe since the set is a singleton. BiPredicate<Context, VisitorState> defaultBehavior; if (root.def == null) { defaultBehavior = (ctx, state) -> false; } else { defaultBehavior = traverse(mappings, mappings.get(root.def)); } Map<Object, BiPredicate<Context, VisitorState>> lookup = new HashMap<>(); @SuppressWarnings("UnstableApiUsage") Set<Map.Entry<Token, Set<Node>>> entries = Multimaps.asMap(children).entrySet(); // Would be cleaner as a stream collecting into a map, but the cost of that stream operation // is non-negligible and DFA compilation needs to be faster. for (Map.Entry<Token, Set<Node>> entry : entries) { lookup.put( entry.getKey().comparisonKey(), traverse(mappings, mappings.get(entry.getValue()))); } switch (type) { case RECEIVER_SUPERTYPE: return (ctx, state) -> { Type receiverType = (Type) TokenType.RECEIVER_SUPERTYPE.extract(ctx, state); // Have to iterate here because subclassing can't be checked by lookup. for (Map.Entry<Object, BiPredicate<Context, VisitorState>> child : lookup.entrySet()) { if (ASTHelpers.isSubtype( receiverType, state.getTypeFromString((String) child.getKey()), state)) { return child.getValue().test(ctx, state); } } return defaultBehavior.test(ctx, state); }; default: return (ctx, state) -> { // All other token types can be checked via a map lookup. Object lookupKey = type.extract(ctx, state); BiPredicate<Context, VisitorState> child = lookup.get(lookupKey); if (child != null) { return child.test(ctx, state); } return defaultBehavior.test(ctx, state); }; } } } /** * Constructs a Matcher that matches for method invocations (including constructor invocations) * satisfying at least one of the given Rule specifications. For an easy way to create such Rules, * see the factories in {@link com.google.errorprone.matchers.Matchers} returning subtypes of * {@link com.google.errorprone.matchers.method.MethodMatchers.MethodMatcher}. */ public static Matcher<ExpressionTree> compile(Iterable<Rule> rules) { // A set of Rule objects represents a predicate stated in disjunctive normal form, where the // atoms are equality tests on parts of a MethodSymbol allowed by TokenType and Token classes. // // We optimize for frequent evaluation of this predicate by first compiling it into a graph // where each node has a single outgoing edge for each relevant token, so that each token // comparison is just a lookup in a map of edges, instead of a linear scan over N rules. // The final graph will have one root state, and one accept state; if we reach the accept, we // say the predicate matches, and if we ever find no matching edge from the current node, we say // the predicate fails to match. To construct this graph optimally, we start with an NFA with // one path from the root to accept per rule; and then apply a modified version of the power-set // construction to reduce it to an equivalent DFA. Table<Node, Optional<Token>, Node> nfa = HashBasedTable.create(); ImmutableSet.Builder<Node> rootsBuilder = ImmutableSet.builder(); for (Rule rule : rules) { ImmutableMap<TokenType, ? extends Set<Token>> required = rule.required(); int numTokens = required.size(); if (numTokens == 0) { // Forget this whole graph business if one of the alternatives is "anything". This isn't // just an optimization: it simplifies building the graph if we know no rules are empty. return (tree, state) -> true; } Node root = new Node(); rootsBuilder.add(root); Node src = root; int tokensHandled = 0; for (TokenType type : TokenType.values()) { Optional<Set<Token>> labels = Optional.ofNullable(required.get(type)); if (labels.isPresent()) { tokensHandled++; } boolean lastToken = tokensHandled == numTokens; Node dst = lastToken ? ACCEPT : new Node(); if (labels.isPresent()) { for (Token label : labels.get()) { nfa.put(src, Optional.of(label), dst); } } else { nfa.put(src, Optional.empty(), dst); } if (lastToken) { break; // No transitions out of the accept state. } src = dst; } } ImmutableSet<Node> roots = rootsBuilder.build(); // TODO(amalloy): When converting to a DFA, we could use the information that there is // exactly one accept state // (and no transitions out of that accept state) to help us prune unnecessary identical states // from the graph. Instead of starting from the root and proceeding forwards, we could start // from the // accept state and proceed backwards through the graph. If we ever have two nodes with exactly // the same set of outgoing edges, we could replace them with a single node. Map<Set<Node>, NodeWithDefault> mappings = new HashMap<>(); ArrayDeque<Set<Node>> open = new ArrayDeque<>(); open.add(roots); while (!open.isEmpty()) { Set<Node> curr = open.removeFirst(); Set<Node> acceptsAny = new HashSet<>(); SetMultimap<Token, Node> destinations = HashMultimap.create(); // First collect all the nodes that accept any token at all for (Node node : curr) { for (Map.Entry<Optional<Token>, Node> entry : nfa.row(node).entrySet()) { if (!entry.getKey().isPresent()) { acceptsAny.add(entry.getValue()); } } } // Then collect the pickier nodes that want a specific token. Now instead of going to that // specific node, that token takes us to the union of that node and all "any" nodes. for (Node node : curr) { for (Map.Entry<Optional<Token>, Node> entry : nfa.row(node).entrySet()) { entry .getKey() .ifPresent( label -> { destinations.put(label, entry.getValue()); destinations.putAll(label, acceptsAny); }); } } mappings.put( curr, new NodeWithDefault(curr, acceptsAny.isEmpty() ? null : acceptsAny, destinations)); if (!acceptsAny.isEmpty()) { open.addLast(acceptsAny); } // asMap has been @Beta and unmodified for 6 years. I'll take my chances. If it changes, we // can just reimplement this simple helper. @SuppressWarnings("UnstableApiUsage") Collection<Set<Node>> values = Multimaps.asMap(destinations).values(); open.addAll(values); } // At this point, mappings has all the information we need, but it's burdened with a bunch of // now-unnecessary Set<Node> objects for its map keys. We want to replace those with something // lightweight, and convert the indirect references through mappings to a direct pointer lookup. return GraphMatcher.from(mappings, mappings.get(roots)); } private MethodInvocationMatcher() {} }
19,686
36.427757
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/util/package-info.java
/* * Copyright 2012 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. */ /** Utility code. */ package com.google.errorprone.util;
666
34.105263
75
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/util/ErrorProneScope.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.util; import static com.google.common.base.Preconditions.checkState; import com.sun.tools.javac.code.Scope; import com.sun.tools.javac.code.Scope.LookupKind; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.util.Name; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Arrays; import java.util.function.Predicate; import org.checkerframework.checker.nullness.qual.Nullable; /** A compatibility wrapper around {@code com.sun.tools.javac.util.Filter} */ public final class ErrorProneScope { @SuppressWarnings("unchecked") // reflection public Iterable<Symbol> getSymbolsByName(Name name, Predicate<Symbol> predicate) { return (Iterable<Symbol>) invoke(getSymbolsByName, name, maybeAsFilter(predicate)); } @SuppressWarnings("unchecked") // reflection public Iterable<Symbol> getSymbolsByName( Name name, Predicate<Symbol> predicate, LookupKind lookupKind) { return (Iterable<Symbol>) invoke(getSymbolsByNameLookupKind, name, maybeAsFilter(predicate), lookupKind); } @SuppressWarnings("unchecked") // reflection public Iterable<Symbol> getSymbols(Predicate<Symbol> predicate) { return (Iterable<Symbol>) invoke(getSymbols, maybeAsFilter(predicate)); } @SuppressWarnings("unchecked") // reflection public Iterable<Symbol> getSymbols(Predicate<Symbol> predicate, LookupKind lookupKind) { return (Iterable<Symbol>) invoke(getSymbolsLookupKind, maybeAsFilter(predicate), lookupKind); } public boolean anyMatch(Predicate<Symbol> predicate) { return (boolean) invoke(anyMatch, maybeAsFilter(predicate)); } private static final Class<?> FILTER_CLASS = getFilterClass(); private static @Nullable Class<?> getFilterClass() { if (RuntimeVersion.isAtLeast17()) { return null; } try { return Class.forName("com.sun.tools.javac.util.Filter"); } catch (ClassNotFoundException e) { throw new LinkageError(e.getMessage(), e); } } private static final Method anyMatch = getImpl("anyMatch", Predicate.class); private static final Method getSymbolsByName = getImpl("getSymbolsByName", Name.class, Predicate.class); private static final Method getSymbolsByNameLookupKind = getImpl("getSymbolsByName", Name.class, Predicate.class, LookupKind.class); private static final Method getSymbols = getImpl("getSymbols", Predicate.class); private static final Method getSymbolsLookupKind = getImpl("getSymbols", Predicate.class, LookupKind.class); private static Method getImpl(String name, Class<?>... parameters) { return FILTER_CLASS != null ? getMethodOrDie( Scope.class, name, Arrays.stream(parameters) .map(p -> p.equals(Predicate.class) ? FILTER_CLASS : p) .toArray(Class<?>[]::new)) : getMethodOrDie(Scope.class, name, parameters); } private final Scope scope; ErrorProneScope(Scope scope) { this.scope = scope; } private Object invoke(Method method, Object... args) { try { return method.invoke(scope, args); } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } } private Object maybeAsFilter(Predicate<Symbol> predicate) { if (FILTER_CLASS == null) { return predicate; } return Proxy.newProxyInstance( getClass().getClassLoader(), new Class<?>[] {FILTER_CLASS}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) { checkState(method.getName().equals("accepts")); return predicate.test((Symbol) args[0]); } }); } private static Method getMethodOrDie(Class<?> clazz, String name, Class<?>... parameters) { try { return clazz.getMethod(name, parameters); } catch (NoSuchMethodException e) { throw new LinkageError(e.getMessage(), e); } } }
4,652
33.213235
97
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/util/FindIdentifiers.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.util; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.errorprone.util.ASTHelpers.isConsideredFinal; import static com.google.errorprone.util.ASTHelpers.isStatic; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.errorprone.VisitorState; import com.sun.source.tree.BlockTree; import com.sun.source.tree.CatchTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.EnhancedForLoopTree; import com.sun.source.tree.ForLoopTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.ImportTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewClassTree; 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 com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Kinds.KindSelector; import com.sun.tools.javac.code.Scope; import com.sun.tools.javac.code.Scope.WriteableScope; 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.Symbol.PackageSymbol; import com.sun.tools.javac.code.Symbol.TypeSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.ClassType; import com.sun.tools.javac.comp.AttrContext; import com.sun.tools.javac.comp.Enter; import com.sun.tools.javac.comp.Env; import com.sun.tools.javac.comp.MemberEnter; import com.sun.tools.javac.comp.Resolve; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import com.sun.tools.javac.util.Name; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.function.BiPredicate; import java.util.stream.StreamSupport; import javax.annotation.Nullable; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; /** A helper class to find all identifiers in scope at a given program point. */ public final class FindIdentifiers { /** Finds a variable declaration with the given name that is in scope at the current location. */ public static Symbol findIdent(String name, VisitorState state) { return findIdent(name, state, KindSelector.VAR); } /** Finds a declaration with the given name and type that is in scope at the current location. */ @Nullable public static Symbol findIdent(String name, VisitorState state, KindSelector kind) { ClassType enclosingClass = ASTHelpers.getType(getEnclosingClass(state.getPath())); Env<AttrContext> env; if (enclosingClass == null || enclosingClass.tsym == null) { env = Enter.instance(state.context) .getTopLevelEnv((JCCompilationUnit) state.getPath().getCompilationUnit()); } else { env = Enter.instance(state.context).getClassEnv(enclosingClass.tsym); MethodTree enclosingMethod = state.findEnclosing(MethodTree.class); if (enclosingMethod != null) { env = MemberEnter.instance(state.context).getMethodEnv((JCMethodDecl) enclosingMethod, env); } } try { Symbol result = findIdent(name, state, kind, env); return result.exists() ? result : null; } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } } // Signature was changed in Java 13: https://bugs.openjdk.java.net/browse/JDK-8223305 private static Symbol findIdent( String name, VisitorState state, KindSelector kind, Env<AttrContext> env) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (RuntimeVersion.isAtLeast13()) { Method method = Resolve.class.getDeclaredMethod( "findIdent", DiagnosticPosition.class, Env.class, Name.class, KindSelector.class); method.setAccessible(true); return (Symbol) method.invoke(Resolve.instance(state.context), null, env, state.getName(name), kind); } Method method = Resolve.class.getDeclaredMethod("findIdent", Env.class, Name.class, KindSelector.class); method.setAccessible(true); return (Symbol) method.invoke(Resolve.instance(state.context), env, state.getName(name), kind); } @Nullable private static ClassTree getEnclosingClass(TreePath treePath) { if (treePath.getLeaf() instanceof ClassTree) { return (ClassTree) treePath.getLeaf(); } while (true) { TreePath parent = treePath.getParentPath(); if (parent == null) { return null; } Tree leaf = parent.getLeaf(); if (leaf instanceof ClassTree && ((ClassTree) leaf).getMembers().contains(treePath.getLeaf())) { return (ClassTree) leaf; } treePath = parent; } } /** * Finds the set of all bare variable identifiers in scope at the current location. Identifiers * are ordered by ascending distance/scope count from the current location to match shadowing * rules. That is, if two variables with the same simple names appear in the set, the one that * appears first in iteration order is the one you get if you use the bare name in the source * code. * * <p>We do not report variables that would require a qualified access. We also do not handle * wildcard imports. */ public static ImmutableSet<VarSymbol> findAllIdents(VisitorState state) { ImmutableSet.Builder<VarSymbol> result = new ImmutableSet.Builder<>(); Tree prev = state.getPath().getLeaf(); for (Tree curr : state.getPath().getParentPath()) { switch (curr.getKind()) { case BLOCK: for (StatementTree stmt : ((BlockTree) curr).getStatements()) { if (stmt.equals(prev)) { break; } addIfVariable(stmt, result); } break; case LAMBDA_EXPRESSION: for (VariableTree param : ((LambdaExpressionTree) curr).getParameters()) { result.add(ASTHelpers.getSymbol(param)); } break; case METHOD: for (VariableTree param : ((MethodTree) curr).getParameters()) { result.add(ASTHelpers.getSymbol(param)); } break; case CATCH: result.add(ASTHelpers.getSymbol(((CatchTree) curr).getParameter())); break; case CLASS: case INTERFACE: case ENUM: case ANNOTATION_TYPE: // Collect fields declared in this class. If we are in a field initializer, only // include fields declared before this one. JLS 8.3.3 allows forward references if the // field is referred to by qualified name, but we don't support that. for (Tree member : ((ClassTree) curr).getMembers()) { if (member.equals(prev)) { break; } addIfVariable(member, result); } // Collect inherited fields. Type classType = ASTHelpers.getType(curr); List<Type> classTypeClosure = state.getTypes().closure(classType); List<Type> superTypes = classTypeClosure.size() <= 1 ? Collections.emptyList() : classTypeClosure.subList(1, classTypeClosure.size()); for (Type type : superTypes) { Scope scope = type.tsym.members(); ImmutableList.Builder<VarSymbol> varsList = ImmutableList.builder(); for (Symbol var : ASTHelpers.scope(scope).getSymbols(VarSymbol.class::isInstance)) { varsList.add((VarSymbol) var); } result.addAll(varsList.build().reverse()); } break; case FOR_LOOP: addAllIfVariable(((ForLoopTree) curr).getInitializer(), result); break; case ENHANCED_FOR_LOOP: result.add(ASTHelpers.getSymbol(((EnhancedForLoopTree) curr).getVariable())); break; case TRY: TryTree tryTree = (TryTree) curr; boolean inResources = false; for (Tree resource : tryTree.getResources()) { if (resource.equals(prev)) { inResources = true; break; } } if (inResources) { // Case 1: we're in one of the resource declarations for (Tree resource : tryTree.getResources()) { if (resource.equals(prev)) { break; } addIfVariable(resource, result); } } else if (tryTree.getBlock().equals(prev)) { // Case 2: We're in the block (not a catch or finally) addAllIfVariable(tryTree.getResources(), result); } break; case COMPILATION_UNIT: for (ImportTree importTree : ((CompilationUnitTree) curr).getImports()) { if (importTree.isStatic() && importTree.getQualifiedIdentifier().getKind() == Kind.MEMBER_SELECT) { MemberSelectTree memberSelectTree = (MemberSelectTree) importTree.getQualifiedIdentifier(); Scope scope = state .getTypes() .membersClosure( ASTHelpers.getType(memberSelectTree.getExpression()), /* skipInterface= */ false); for (Symbol var : ASTHelpers.scope(scope) .getSymbols( sym -> sym instanceof VarSymbol && sym.getSimpleName() .equals(memberSelectTree.getIdentifier()))) { result.add((VarSymbol) var); } } } break; default: // other node types don't introduce variables break; } prev = curr; } return result.build().stream() .filter(variable -> isVisible(variable, state.getPath())) .collect(toImmutableSet()); } /** * Finds all variable declarations which are unused at this point in the AST (i.e. they might be * used further on). */ public static ImmutableSet<VarSymbol> findUnusedIdentifiers(VisitorState state) { ImmutableSet.Builder<VarSymbol> definedVariables = ImmutableSet.builder(); ImmutableSet.Builder<Symbol> usedSymbols = ImmutableSet.builder(); Tree prev = state.getPath().getLeaf(); for (Tree curr : state.getPath().getParentPath()) { createFindIdentifiersScanner(usedSymbols, prev).scan(curr, null); switch (curr.getKind()) { case BLOCK: // If we see a block then walk over each statement to see if it defines a variable for (StatementTree statement : ((BlockTree) curr).getStatements()) { if (statement.equals(prev)) { // break if we see the tree we have just processed so that we only consider things // declared/used before us in the tree break; } addIfVariable(statement, definedVariables); } break; case FOR_LOOP: ForLoopTree forLoop = (ForLoopTree) curr; forLoop.getInitializer().stream().forEach(t -> addIfVariable(t, definedVariables)); break; case ENHANCED_FOR_LOOP: EnhancedForLoopTree enhancedFor = (EnhancedForLoopTree) curr; addIfVariable(enhancedFor.getVariable(), definedVariables); break; default: break; } prev = curr; } return ImmutableSet.copyOf(Sets.difference(definedVariables.build(), usedSymbols.build())); } /** Find the set of all identifiers referenced within this Tree */ public static ImmutableSet<Symbol> findReferencedIdentifiers(Tree tree) { ImmutableSet.Builder<Symbol> builder = ImmutableSet.builder(); createFindIdentifiersScanner(builder, null).scan(tree, null); return builder.build(); } /** Finds all the visible fields declared or inherited in the target class */ public static ImmutableList<VarSymbol> findAllFields(Type classType, VisitorState state) { return state.getTypes().closure(classType).stream() .flatMap( type -> { TypeSymbol tsym = type.tsym; if (tsym == null) { return ImmutableList.<VarSymbol>of().stream(); } WriteableScope scope = tsym.members(); if (scope == null) { return ImmutableList.<VarSymbol>of().stream(); } return ImmutableList.copyOf( ASTHelpers.scope(scope).getSymbols(VarSymbol.class::isInstance)) .reverse() .stream() .map(v -> (VarSymbol) v) .filter(v -> isVisible(v, state.getPath())); }) .collect(toImmutableList()); } /** * Finds all identifiers in a tree. Takes an optional stop point as its argument: the depth-first * walk will stop if this node is encountered. */ private static TreeScanner<Void, Void> createFindIdentifiersScanner( ImmutableSet.Builder<Symbol> builder, @Nullable Tree stoppingPoint) { return new TreeScanner<Void, Void>() { @Override public Void scan(Tree tree, Void unused) { return Objects.equals(stoppingPoint, tree) ? null : super.scan(tree, unused); } @Override public Void scan(Iterable<? extends Tree> iterable, Void unused) { if (stoppingPoint != null && iterable != null) { ImmutableList.Builder<Tree> builder = ImmutableList.builder(); for (Tree t : iterable) { if (stoppingPoint.equals(t)) { break; } builder.add(t); } iterable = builder.build(); } return super.scan(iterable, unused); } @Override public Void visitIdentifier(IdentifierTree identifierTree, Void unused) { Symbol symbol = ASTHelpers.getSymbol(identifierTree); if (symbol != null) { builder.add(symbol); } return null; } }; } private static boolean isVisible(VarSymbol var, TreePath path) { switch (var.getKind()) { case ENUM_CONSTANT: case FIELD: ImmutableList<ClassSymbol> enclosingClasses = StreamSupport.stream(path.spliterator(), false) .filter(ClassTree.class::isInstance) .map(ClassTree.class::cast) .map(ASTHelpers::getSymbol) .collect(toImmutableList()); if (!var.isStatic()) { // Instance fields are not visible if we are in a static context... if (inStaticContext(path)) { return false; } // ... or if we're in a static nested class and the instance fields are declared outside // the enclosing static nested class (JLS 8.5.1). if (lowerThan( path, (curr, unused) -> { Symbol sym = ASTHelpers.getSymbol(curr); return sym != null && isStatic(sym); }, (curr, unused) -> curr instanceof ClassTree && ASTHelpers.getSymbol(curr).equals(var.owner))) { return false; } } // If we're lexically enclosed by the same class that defined var, we can access private // fields (JLS 6.6.1). if (enclosingClasses.contains(ASTHelpers.enclosingClass(var))) { return true; } PackageSymbol enclosingPackage = ((JCCompilationUnit) path.getCompilationUnit()).packge; Set<Modifier> modifiers = var.getModifiers(); // If we're in the same package where var was defined, we can access package-private fields // (JLS 6.6.1). if (Objects.equals(enclosingPackage, ASTHelpers.enclosingPackage(var))) { return !modifiers.contains(Modifier.PRIVATE); } // Otherwise we can only access public and protected fields (JLS 6.6.1, plus the fact // that the only enum constants and fields usable by simple name are either defined // in the enclosing class or a superclass). return modifiers.contains(Modifier.PUBLIC) || modifiers.contains(Modifier.PROTECTED); case PARAMETER: case LOCAL_VARIABLE: // If we are in an anonymous inner class, lambda, or local class, any local variable or // method parameter we access that is defined outside the anonymous class/lambda must be // final or effectively final (JLS 8.1.3). if (lowerThan( path, (curr, parent) -> curr.getKind() == Kind.LAMBDA_EXPRESSION || (curr.getKind() == Kind.NEW_CLASS && ((NewClassTree) curr).getClassBody() != null) || (curr.getKind() == Kind.CLASS && parent.getKind() == Kind.BLOCK), (curr, unused) -> Objects.equals(var.owner, ASTHelpers.getSymbol(curr)))) { if (!isConsideredFinal(var)) { return false; } } return true; case EXCEPTION_PARAMETER: case RESOURCE_VARIABLE: return true; default: throw new IllegalArgumentException("Unexpected variable type: " + var.getKind()); } } /** Returns true iff the leaf node of the {@code path} occurs in a JLS 8.3.1 static context. */ private static boolean inStaticContext(TreePath path) { ClassSymbol enclosingClass = ASTHelpers.getSymbol(ASTHelpers.findEnclosingNode(path, ClassTree.class)); ClassSymbol directSuperClass = (ClassSymbol) enclosingClass.getSuperclass().tsym; Tree prev = path.getLeaf(); path = path.getParentPath(); for (Tree tree : path) { switch (tree.getKind()) { case METHOD: return isStatic(ASTHelpers.getSymbol(tree)); case BLOCK: // static initializer if (((BlockTree) tree).isStatic()) { return true; } break; case VARIABLE: // variable initializer of static variable VariableTree variableTree = (VariableTree) tree; VarSymbol variableSym = ASTHelpers.getSymbol(variableTree); if (variableSym.getKind() == ElementKind.FIELD) { return Objects.equals(variableTree.getInitializer(), prev) && variableSym.isStatic(); } break; case METHOD_INVOCATION: // JLS 8.8.7.1 explicit constructor invocation MethodSymbol methodSym = ASTHelpers.getSymbol((MethodInvocationTree) tree); if (methodSym.isConstructor() && (Objects.equals(methodSym.owner, enclosingClass) || Objects.equals(methodSym.owner, directSuperClass))) { return true; } break; default: break; } prev = tree; } return false; } private static void addIfVariable(Tree tree, ImmutableSet.Builder<VarSymbol> setBuilder) { if (tree.getKind() == Kind.VARIABLE) { setBuilder.add(ASTHelpers.getSymbol((VariableTree) tree)); } } private static void addAllIfVariable( List<? extends Tree> list, ImmutableSet.Builder<VarSymbol> setBuilder) { for (Tree tree : list) { addIfVariable(tree, setBuilder); } } /** * Walks up the given {@code path} and returns true iff the first node matching {@code predicate1} * occurs lower in the AST than the first node node matching {@code predicate2}. Returns false if * no node matches {@code predicate1} or if no node matches {@code predicate2}. * * @param predicate1 A {@link BiPredicate} that accepts the current node and its parent * @param predicate2 A {@link BiPredicate} that accepts the current node and its parent */ private static boolean lowerThan( TreePath path, BiPredicate<Tree, Tree> predicate1, BiPredicate<Tree, Tree> predicate2) { int index1 = -1; int index2 = -1; int count = 0; path = path.getParentPath(); while (path != null) { Tree curr = path.getLeaf(); TreePath parentPath = path.getParentPath(); if (index1 < 0 && predicate1.test(curr, parentPath == null ? null : parentPath.getLeaf())) { index1 = count; } if (index2 < 0 && predicate2.test(curr, parentPath == null ? null : parentPath.getLeaf())) { index2 = count; } if (index1 >= 0 && index2 >= 0) { break; } path = parentPath; count++; } return (index1 >= 0) && (index1 < index2); } private FindIdentifiers() {} }
21,932
38.805808
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/util/RuntimeVersion.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.util; /** * JDK runtime version utilities. * * <p>These methods are generally used when deciding which method to call reflectively. Bug checkers * that rely on support for specific source code constructs should consult {@link SourceVersion} * instead. * * @see SourceVersion */ public final class RuntimeVersion { private static final int FEATURE = Runtime.version().feature(); /** Returns true if the current runtime is JDK 12 or newer. */ public static boolean isAtLeast12() { return FEATURE >= 12; } /** Returns true if the current runtime is JDK 13 or newer. */ public static boolean isAtLeast13() { return FEATURE >= 13; } /** Returns true if the current runtime is JDK 14 or newer. */ public static boolean isAtLeast14() { return FEATURE >= 14; } /** Returns true if the current runtime is JDK 15 or newer. */ public static boolean isAtLeast15() { return FEATURE >= 15; } /** Returns true if the current runtime is JDK 16 or newer. */ public static boolean isAtLeast16() { return FEATURE >= 16; } /** Returns true if the current runtime is JDK 17 or newer. */ public static boolean isAtLeast17() { return FEATURE >= 17; } /** Returns true if the current runtime is JDK 18 or newer. */ public static boolean isAtLeast18() { return FEATURE >= 18; } /** Returns true if the current runtime is JDK 19 or newer. */ public static boolean isAtLeast19() { return FEATURE >= 19; } /** Returns true if the current runtime is JDK 20 or newer. */ public static boolean isAtLeast20() { return FEATURE >= 20; } /** Returns true if the current runtime is JDK 21 or newer. */ public static boolean isAtLeast21() { return FEATURE >= 21; } /** * Returns the latest {@code --release} version. * * <p>Prefer the {@code isAtLeast} methods for assumption checks in tests. */ public static int release() { return FEATURE; } private RuntimeVersion() {} }
2,624
27.225806
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/util/SideEffectAnalysis.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.util; import com.sun.source.tree.CompoundAssignmentTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.UnaryTree; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.tree.JCTree.JCUnary; /** * This class is responsible for analyzing an expression and telling if the expression can have side * effects. This class is used by calling the static {@link #hasSideEffect(ExpressionTree)} method. * * <p>A side-effect is what that would change the state of the program. Here are examples of * expressions that could possibly change the state of a program. * * <ul> * <li>Any function call: toString(), hashCode(), setX(value), etc. * <li>Unary expression: i += 1, i++, --j * <li>New expression: new SomeClass() * </ul> * * <p>Everything besides the above examples is considered side-effect free. * * <p>The analysis in this class initially assumes that the expression is side-effect free and then * tries to prove it wrong. */ public final class SideEffectAnalysis extends TreeScanner<Void, Void> { private boolean hasSideEffect = false; private SideEffectAnalysis() {} /** * Tries to establish whether {@code expression} is side-effect free. The heuristics here are very * conservative. */ public static boolean hasSideEffect(ExpressionTree expression) { if (expression == null) { return false; } SideEffectAnalysis analyzer = new SideEffectAnalysis(); expression.accept(analyzer, null); return analyzer.hasSideEffect; } @Override public Void visitCompoundAssignment(CompoundAssignmentTree tree, Void unused) { hasSideEffect = true; return null; } @Override public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) { hasSideEffect = true; return null; } @Override public Void visitNewClass(NewClassTree tree, Void unused) { hasSideEffect = true; return null; } @Override public Void visitUnary(UnaryTree tree, Void unused) { JCUnary unary = (JCUnary) tree; switch (unary.getKind()) { case PREFIX_DECREMENT: case PREFIX_INCREMENT: case POSTFIX_DECREMENT: case POSTFIX_INCREMENT: hasSideEffect = true; break; default: break; } return super.visitUnary(tree, unused); } }
3,043
29.747475
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/util/Visibility.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.util; import static com.google.errorprone.util.ASTHelpers.enclosingClass; import static com.google.errorprone.util.ASTHelpers.enclosingPackage; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.google.errorprone.util.ASTHelpers.getType; import static com.google.errorprone.util.ASTHelpers.isStatic; import com.google.errorprone.VisitorState; import com.sun.source.tree.ClassTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MemberReferenceTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.NewClassTree; 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.PackageSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import java.util.Set; import javax.lang.model.element.Modifier; /** * Describes visibilities available via VisibleForTesting annotations, and provides methods to * establish whether a given {@link Tree} should be visible. */ public enum Visibility implements Comparable<Visibility> { // In order of ascending visibility. NONE { @Override public boolean shouldBeVisible(Tree tree, VisitorState state) { return false; } @Override public boolean shouldBeVisible(Symbol symbol, VisitorState state) { return false; } @Override public String description() { return "not be used"; } }, PRIVATE { @Override public boolean shouldBeVisible(Tree tree, VisitorState state) { return shouldBeVisible(getSymbol(tree), state); } @Override public boolean shouldBeVisible(Symbol symbol, VisitorState state) { Symbol outermostClass = null; for (Tree parent : state.getPath()) { if (parent instanceof ClassTree) { outermostClass = getSymbol(parent); } } return outermostClass == null || ASTHelpers.outermostClass(symbol).equals(outermostClass); } @Override public String description() { return "private visibility"; } }, PACKAGE_PRIVATE { @Override public boolean shouldBeVisible(Tree tree, VisitorState state) { return PACKAGE_PRIVATE.shouldBeVisible(getSymbol(tree), state); } @Override public boolean shouldBeVisible(Symbol symbol, VisitorState state) { JCCompilationUnit compilationUnit = (JCCompilationUnit) state.getPath().getCompilationUnit(); PackageSymbol packge = compilationUnit.packge; // TODO(ghm): Should we handle the default (unnamed) package here? return enclosingPackage(symbol).equals(packge); } @Override public String description() { return "default (package private) visibility"; } }, PROTECTED { // Rules https://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6.2 @Override public boolean shouldBeVisible(Tree tree, VisitorState state) { if (PACKAGE_PRIVATE.shouldBeVisible(tree, state)) { return true; } Symbol symbol = getSymbol(tree); ClassTree classTree = ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class); if (isStatic(symbol)) { if (classTree == null) { return false; } return hasEnclosingClassExtending(enclosingClass(symbol).type, state, classTree); } // Anonymous subclasses will match on the synthetic constructor. if (tree instanceof NewClassTree) { return false; } if (!(tree instanceof ExpressionTree)) { return hasEnclosingClassExtending(enclosingClass(symbol).type, state, classTree); } if (tree instanceof MemberSelectTree && ((MemberSelectTree) tree).getIdentifier().contentEquals("super")) { // Allow qualified super calls. return true; } if (tree instanceof MemberSelectTree || tree instanceof MemberReferenceTree) { ExpressionTree receiver = ASTHelpers.getReceiver((ExpressionTree) tree); return receiver.toString().equals("super") || hasEnclosingClassOfSuperType(getType(receiver), state, classTree); } // If there's no receiver, we must be accessing it via an implicit "this", or we're // using unqualified "super". return true; } @Override public boolean shouldBeVisible(Symbol symbol, VisitorState state) { if (PACKAGE_PRIVATE.shouldBeVisible(symbol, state)) { return true; } ClassTree classTree = ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class); return classTree != null && hasEnclosingClassExtending(enclosingClass(symbol).type, state, classTree); } private boolean hasEnclosingClassOfSuperType( Type type, VisitorState state, ClassTree classTree) { for (ClassSymbol encl = getSymbol(classTree); encl != null; encl = enclosingClass(encl)) { if (encl.isStatic()) { break; } if (ASTHelpers.isSubtype(type, encl.type, state)) { return true; } } return false; } private boolean hasEnclosingClassExtending(Type type, VisitorState state, ClassTree classTree) { for (ClassSymbol encl = getSymbol(classTree); encl != null; encl = enclosingClass(encl)) { if (encl.isStatic()) { break; } if (ASTHelpers.isSubtype(encl.type, type, state)) { return true; } } return false; } @Override public String description() { return "protected visibility"; } }, PUBLIC { @Override public boolean shouldBeVisible(Tree tree, VisitorState state) { return true; } @Override public boolean shouldBeVisible(Symbol symbol, VisitorState state) { return true; } @Override public String description() { return "public visibility"; } }; /** * Whether {@code tree} should be visible from the path in {@code state} assuming we're in prod * code. */ public abstract boolean shouldBeVisible(Tree tree, VisitorState state); /** * Whether {@code symbol} should be visible from the path in {@code state} assuming we're in prod * code. */ public abstract boolean shouldBeVisible(Symbol symbol, VisitorState state); public static Visibility fromModifiers(Set<Modifier> modifiers) { if (modifiers.contains(Modifier.PRIVATE)) { return Visibility.PRIVATE; } if (modifiers.contains(Modifier.PUBLIC)) { return Visibility.PUBLIC; } if (modifiers.contains(Modifier.PROTECTED)) { return Visibility.PROTECTED; } return Visibility.PACKAGE_PRIVATE; } public boolean isAtLeastAsRestrictiveAs(Visibility visibility) { return compareTo(visibility) <= 0; } public boolean isMoreVisibleThan(Visibility visibility) { return compareTo(visibility) > 0; } /** * A fragment describing this visibility, to fit in a phrase like "restricted to [...]". * * <p>This is complicated by {@code NONE}, which doesn't describe a Java visibility. */ public abstract String description(); }
7,789
31.869198
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/util/SourceVersion.java
/* * Copyright 2023 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.util; import com.sun.tools.javac.code.Source; import com.sun.tools.javac.util.Context; /** * JDK source version utilities. * * @see RuntimeVersion */ public final class SourceVersion { /** Returns true if the compiler source version level supports switch expressions. */ public static boolean supportsSwitchExpressions(Context context) { return sourceIsAtLeast(context, 14); } /** Returns true if the compiler source version level supports text blocks. */ public static boolean supportsTextBlocks(Context context) { return sourceIsAtLeast(context, 15); } /** Returns true if the compiler source version level supports effectively final. */ public static boolean supportsEffectivelyFinal(Context context) { return sourceIsAtLeast(context, 8); } private static boolean sourceIsAtLeast(Context context, int version) { Source lowerBound = Source.lookup(Integer.toString(version)); return lowerBound != null && Source.instance(context).compareTo(lowerBound) >= 0; } private SourceVersion() {} }
1,683
32.68
87
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/util/Regexes.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.util; import com.google.common.base.CharMatcher; import com.google.common.collect.ImmutableMap; import java.util.Optional; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** Utilities for checks that work with regexes. */ public final class Regexes { /** * A map of regex constructs to escape characters we can translate to a literal. Note that '\b' * doesn't appear here because '\b' in a regex means wordbreak and '\b' a as literal means * backspace. */ private static final ImmutableMap<Character, Character> REGEXCHAR_TO_LITERALCHAR = new ImmutableMap.Builder<Character, Character>() .put('t', '\t') .put('n', '\n') .put('f', '\f') .put('r', '\r') .buildOrThrow(); private static final CharMatcher UNESCAPED_CONSTRUCT = CharMatcher.anyOf("[].^$?*+{}()|"); /** * If the given regexes matches exactly one string, returns that string. Otherwise returns {@code * null}. This can be used to identify arguments to e.g. {@code String.replaceAll} that don't need * to be regexes. */ public static Optional<String> convertRegexToLiteral(String s) { try { Pattern.compile(s); } catch (PatternSyntaxException e) { /* The string is a malformed regular expression which will throw an error at runtime. We will * preserve this behavior by not rewriting it. */ return Optional.empty(); } boolean inQuote = false; StringBuilder result = new StringBuilder(); int length = s.length(); for (int i = 0; i < length; ++i) { char current = s.charAt(i); if (!inQuote && UNESCAPED_CONSTRUCT.matches(current)) { /* If we see an unescaped regular expression control character then we can't match this as a * string-literal so give up */ return Optional.empty(); } else if (current == '\\') { /* There should be a character following the backslash. No need to check for string length * since we have already ascertained we have a well formed regex */ char escaped = s.charAt(++i); if (escaped == 'Q') { inQuote = true; } else if (escaped == 'E') { inQuote = false; } else { /* If not starting or ending a quotation (\Q...\E) backslashes can only be used to write * escaped constructs or to quote characters that would otherwise be interpreted as * unescaped constructs. * * If they are escaping a construct we can write as a literal string (i.e. one of \t \n * \f \r or \\) then we convert to a literal character. * * If they are escaping an unescaped construct we convert to the relevant character * * Everything else we can't represent in a literal string */ Character controlChar = REGEXCHAR_TO_LITERALCHAR.get(escaped); if (controlChar != null) { result.append(controlChar); } else if (escaped == '\\') { result.append('\\'); } else if (UNESCAPED_CONSTRUCT.matches(escaped)) { result.append(escaped); } else { return Optional.empty(); } } } else { /* Otherwise we have a literal character to match so keep going */ result.append(current); } } return Optional.of(result.toString()); } private Regexes() {} }
4,114
36.072072
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/util/ErrorProneTokens.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.util; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.collect.ImmutableList; import com.sun.tools.javac.parser.JavaTokenizer; import com.sun.tools.javac.parser.Scanner; import com.sun.tools.javac.parser.ScannerFactory; import com.sun.tools.javac.parser.Tokens.Comment; import com.sun.tools.javac.parser.Tokens.Comment.CommentStyle; import com.sun.tools.javac.parser.Tokens.TokenKind; import com.sun.tools.javac.parser.UnicodeReader; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.Position.LineMap; /** A utility for tokenizing and preserving comments. */ public class ErrorProneTokens { private final int offset; private final CommentSavingTokenizer commentSavingTokenizer; private final ScannerFactory scannerFactory; public ErrorProneTokens(String source, Context context) { this(source, 0, context); } public ErrorProneTokens(String source, int offset, Context context) { this.offset = offset; scannerFactory = ScannerFactory.instance(context); char[] buffer = source == null ? new char[] {} : source.toCharArray(); commentSavingTokenizer = new CommentSavingTokenizer(scannerFactory, buffer, buffer.length); } public LineMap getLineMap() { return commentSavingTokenizer.getLineMap(); } public ImmutableList<ErrorProneToken> getTokens() { Scanner scanner = new AccessibleScanner(scannerFactory, commentSavingTokenizer); ImmutableList.Builder<ErrorProneToken> tokens = ImmutableList.builder(); do { scanner.nextToken(); tokens.add(new ErrorProneToken(scanner.token(), offset)); } while (scanner.token().kind != TokenKind.EOF); return tokens.build(); } /** Returns the tokens for the given source text, including comments. */ public static ImmutableList<ErrorProneToken> getTokens(String source, Context context) { return getTokens(source, 0, context); } /** * Returns the tokens for the given source text, including comments, indicating the offset of the * source within the overall file. */ public static ImmutableList<ErrorProneToken> getTokens( String source, int offset, Context context) { return new ErrorProneTokens(source, offset, context).getTokens(); } /** A {@link JavaTokenizer} that saves comments. */ static class CommentSavingTokenizer extends JavaTokenizer { CommentSavingTokenizer(ScannerFactory fac, char[] buffer, int length) { super(fac, buffer, length); } @Override protected Comment processComment(int pos, int endPos, CommentStyle style) { char[] buf = getRawCharactersReflectively(pos, endPos); return new CommentWithTextAndPosition( pos, endPos, new AccessibleReader(fac, buf, buf.length), style); } private char[] getRawCharactersReflectively(int beginIndex, int endIndex) { Object instance; try { instance = JavaTokenizer.class.getDeclaredField("reader").get(this); } catch (ReflectiveOperationException e) { instance = this; } try { return (char[]) instance .getClass() .getMethod("getRawCharacters", int.class, int.class) .invoke(instance, beginIndex, endIndex); } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } } } /** A {@link Comment} that saves its text and start position. */ static class CommentWithTextAndPosition implements Comment { private final int pos; private final int endPos; private final AccessibleReader reader; private final CommentStyle style; private String text = null; public CommentWithTextAndPosition( int pos, int endPos, AccessibleReader reader, CommentStyle style) { this.pos = pos; this.endPos = endPos; this.reader = reader; this.style = style; } public int getPos() { return pos; } public int getEndPos() { return endPos; } /** * Returns the source position of the character at index {@code index} in the comment text. * * <p>The handling of javadoc comments in javac has more logic to skip over leading whitespace * and '*' characters when indexing into doc comments, but we don't need any of that. */ @Override public int getSourcePos(int index) { checkArgument( 0 <= index && index < (endPos - pos), "Expected %s in the range [0, %s)", index, endPos - pos); return pos + index; } @Override public CommentStyle getStyle() { return style; } @Override public String getText() { String text = this.text; if (text == null) { this.text = text = new String(reader.getRawCharacters()); } return text; } /** * We don't care about {@code @deprecated} javadoc tags (see the DepAnn check). * * @return false */ @Override public boolean isDeprecated() { return false; } @Override public String toString() { return String.format("Comment: '%s'", getText()); } } // Scanner(ScannerFactory, JavaTokenizer) is package-private static class AccessibleScanner extends Scanner { protected AccessibleScanner(ScannerFactory fac, JavaTokenizer tokenizer) { super(fac, tokenizer); } } // UnicodeReader(ScannerFactory, char[], int) is package-private static class AccessibleReader extends UnicodeReader { protected AccessibleReader(ScannerFactory fac, char[] buffer, int length) { super(fac, buffer, length); } } }
6,282
31.220513
99
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/util/Commented.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.util; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.sun.source.tree.Tree; import com.sun.tools.javac.parser.Tokens.Comment; /** Class to hold AST nodes annotated with the comments that are associated with them */ @AutoValue public abstract class Commented<T extends Tree> { /** Identifies the position of a comment relative to the associated treenode. */ public enum Position { BEFORE, AFTER, ANY } public abstract T tree(); public abstract ImmutableList<Comment> beforeComments(); public abstract ImmutableList<Comment> afterComments(); static <T extends Tree> Builder<T> builder() { return new AutoValue_Commented.Builder<T>(); } @AutoValue.Builder abstract static class Builder<T extends Tree> { abstract Builder<T> setTree(T tree); protected abstract ImmutableList.Builder<Comment> beforeCommentsBuilder(); protected abstract ImmutableList.Builder<Comment> afterCommentsBuilder(); @CanIgnoreReturnValue Builder<T> addComment( Comment comment, int nodePosition, int tokenizingOffset, Position position) { OffsetComment offsetComment = new OffsetComment(comment, tokenizingOffset); if (comment.getSourcePos(0) < nodePosition) { if (position.equals(Position.BEFORE) || position.equals(Position.ANY)) { beforeCommentsBuilder().add(offsetComment); } } else { if (position.equals(Position.AFTER) || position.equals(Position.ANY)) { afterCommentsBuilder().add(offsetComment); } } return this; } @CanIgnoreReturnValue Builder<T> addAllComment( Iterable<? extends Comment> comments, int nodePosition, int tokenizingOffset, Position position) { for (Comment comment : comments) { addComment(comment, nodePosition, tokenizingOffset, position); } return this; } abstract Commented<T> build(); } }
2,685
29.873563
88
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/util/SourceCodeEscapers.java
/* * Copyright (C) 2009 The Guava 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.util; import com.google.common.collect.ImmutableMap; import com.google.common.escape.ArrayBasedCharEscaper; import com.google.common.escape.CharEscaper; import com.google.common.escape.Escaper; import java.util.Map; /** * A factory for Escaper instances used to escape strings for safe use in Java. * * <p>This is a subset of source code escapers that are in the process of being open-sources as part * of guava, see: https://github.com/google/guava/issues/1620 */ // TODO(cushon): migrate to the guava version once it is open-sourced, and delete this public final class SourceCodeEscapers { private SourceCodeEscapers() {} // For each xxxEscaper() method, please add links to external reference pages // that are considered authoritative for the behavior of that escaper. // From: http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters private static final char PRINTABLE_ASCII_MIN = 0x20; // ' ' private static final char PRINTABLE_ASCII_MAX = 0x7E; // '~' private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray(); /** * Returns an {@link Escaper} instance that escapes special characters in a string so it can * safely be included in either a Java character literal or string literal. This is the preferred * way to escape Java characters for use in String or character literals. * * <p>See: <a href= "http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#101089" * >The Java Language Specification</a> for more details. */ public static CharEscaper javaCharEscaper() { return JAVA_CHAR_ESCAPER; } private static final CharEscaper JAVA_CHAR_ESCAPER = new JavaCharEscaper( ImmutableMap.of( '\b', "\\b", '\f', "\\f", '\n', "\\n", '\r', "\\r", '\t', "\\t", '\"', "\\\"", '\\', "\\\\", '\'', "\\'")); // This escaper does not produce octal escape sequences. See: // http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#101089 // "Octal escapes are provided for compatibility with C, but can express // only Unicode values \u0000 through \u00FF, so Unicode escapes are // usually preferred." private static class JavaCharEscaper extends ArrayBasedCharEscaper { JavaCharEscaper(Map<Character, String> replacements) { super(replacements, PRINTABLE_ASCII_MIN, PRINTABLE_ASCII_MAX); } @Override protected char[] escapeUnsafe(char c) { return asUnicodeHexEscape(c); } } // Helper for common case of escaping a single char. private static char[] asUnicodeHexEscape(char c) { // Equivalent to String.format("\\u%04x", (int)c); char[] r = new char[6]; r[0] = '\\'; r[1] = 'u'; r[5] = HEX_DIGITS[c & 0xF]; c >>>= 4; r[4] = HEX_DIGITS[c & 0xF]; c >>>= 4; r[3] = HEX_DIGITS[c & 0xF]; c >>>= 4; r[2] = HEX_DIGITS[c & 0xF]; return r; } }
3,601
35.02
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/util/Comments.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.util; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.errorprone.util.ASTHelpers.getStartPosition; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.CharMatcher; import com.google.common.collect.ImmutableList; import com.google.common.collect.Range; import com.google.common.collect.TreeRangeSet; import com.google.errorprone.VisitorState; import com.google.errorprone.util.Commented.Position; import com.google.errorprone.util.ErrorProneTokens.CommentWithTextAndPosition; import com.sun.source.tree.BlockTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree; import com.sun.source.util.TreePath; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.parser.Tokens.Comment; import com.sun.tools.javac.parser.Tokens.TokenKind; import com.sun.tools.javac.util.Position.LineMap; import java.util.Iterator; import java.util.List; import java.util.Optional; /** * Utilities for attaching comments to relevant AST nodes * * @author andrewrice@google.com (Andrew Rice) */ public final class Comments { /** * Attach comments to nodes on arguments of constructor calls. Calls such as {@code new Test( * param1 /* c1 *&#47;, /* c2 *&#47; param2)} will attach the comment c1 to {@code param1} and the * comment c2 to {@code param2}. * * <p>Warning: this is expensive to compute as it involves re-tokenizing the source for this node. * * <p>Currently this method will only tokenize the source code of the method call itself. However, * the source positions in the returned {@code Comment} objects are adjusted so that they are * relative to the whole file. */ public static ImmutableList<Commented<ExpressionTree>> findCommentsForArguments( NewClassTree newClassTree, VisitorState state) { int startPosition = getStartPosition(newClassTree); return findCommentsForArguments( newClassTree, newClassTree.getArguments(), startPosition, state); } /** * Attach comments to nodes on arguments of method calls. Calls such as {@code test(param1 /* c1 * *&#47;, /* c2 *&#47; param2)} will attach the comment c1 to {@code param1} and the comment c2 * to {@code param2}. * * <p>Warning: this is expensive to compute as it involves re-tokenizing the source for this node * * <p>Currently this method will only tokenize the source code of the method call itself. However, * the source positions in the returned {@code Comment} objects are adjusted so that they are * relative to the whole file. */ public static ImmutableList<Commented<ExpressionTree>> findCommentsForArguments( MethodInvocationTree methodInvocationTree, VisitorState state) { int startPosition = state.getEndPosition(methodInvocationTree.getMethodSelect()); return findCommentsForArguments( methodInvocationTree, methodInvocationTree.getArguments(), startPosition, state); } /** * Extract the text body from a comment. * * <p>This currently includes asterisks that start lines in the body of block comments. Do not * rely on this behaviour. * * <p>TODO(andrewrice) Update this method to handle block comments properly if we find the need */ public static String getTextFromComment(Comment comment) { switch (comment.getStyle()) { case BLOCK: return comment.getText().replaceAll("^\\s*/\\*\\s*(.*?)\\s*\\*/\\s*", "$1"); case LINE: return comment.getText().replaceAll("^\\s*//\\s*", ""); case JAVADOC: return comment.getText().replaceAll("^\\s*/\\*\\*\\s*(.*?)\\s*\\*/\\s*", "$1"); } throw new AssertionError(comment.getStyle()); } private static ImmutableList<Commented<ExpressionTree>> findCommentsForArguments( Tree tree, List<? extends ExpressionTree> arguments, int invocationStart, VisitorState state) { if (arguments.isEmpty()) { return ImmutableList.of(); } CharSequence sourceCode = state.getSourceCode(); Optional<Integer> endPosition = computeEndPosition(tree, sourceCode, state); if (!endPosition.isPresent()) { return noComments(arguments); } CharSequence source = sourceCode.subSequence(invocationStart, endPosition.get()); if (CharMatcher.is('/').matchesNoneOf(source)) { return noComments(arguments); } // The token position of the end of the method invocation int invocationEnd = state.getEndPosition(tree) - invocationStart; // Ignore comments nested inside arguments. TreeRangeSet<Integer> exclude = TreeRangeSet.create(); arguments.forEach( arg -> exclude.add( Range.closed( getStartPosition(arg) - invocationStart, state.getEndPosition(arg) - invocationStart))); ErrorProneTokens errorProneTokens = new ErrorProneTokens(source.toString(), state.context); ImmutableList<ErrorProneToken> tokens = errorProneTokens.getTokens(); LineMap lineMap = errorProneTokens.getLineMap(); ArgumentTracker argumentTracker = new ArgumentTracker(arguments, invocationStart, state, lineMap); TokenTracker tokenTracker = new TokenTracker(lineMap); argumentTracker.advance(); for (ErrorProneToken token : tokens) { tokenTracker.advance(token); if (tokenTracker.atStartOfLine() && !tokenTracker.wasPreviousLineEmpty()) { // if the token is at the start of a line it could still have a comment attached which was // on the previous line for (Comment c : token.comments()) { if (!(c instanceof CommentWithTextAndPosition)) { continue; } CommentWithTextAndPosition comment = (CommentWithTextAndPosition) c; int commentStart = comment.getPos(); int commentEnd = comment.getEndPos(); if (exclude.intersects(Range.closedOpen(commentStart, commentEnd))) { continue; } if (tokenTracker.isCommentOnPreviousLine(c) && token.pos() <= argumentTracker.currentArgumentStartPosition && argumentTracker.isPreviousArgumentOnPreviousLine()) { // token was on the previous line so therefore we should add it to the previous comment // unless the previous argument was not on the previous line with it argumentTracker.addCommentToPreviousArgument(c, Position.ANY); } else { // if the comment comes after the end of the invocation and it's not on the same line // as the final argument then we need to ignore it if (commentStart <= invocationEnd || lineMap.getLineNumber(commentStart) <= lineMap.getLineNumber(argumentTracker.currentArgumentEndPosition)) { argumentTracker.addCommentToCurrentArgument(c, Position.ANY); } } } } else { // we add all the before-comments from the first token of the argument // we add all the after-comments from the last token of the argument if (token.pos() == argumentTracker.currentArgumentStartPosition) { argumentTracker.addAllCommentsToCurrentArgument(token.comments(), Position.BEFORE); } if (token.endPos() > argumentTracker.currentArgumentEndPosition) { argumentTracker.addAllCommentsToCurrentArgument(token.comments(), Position.AFTER); } } if (token.pos() >= argumentTracker.currentArgumentEndPosition) { // We are between arguments so wait for a (lexed) comma to delimit them if (token.kind() == TokenKind.COMMA) { if (!argumentTracker.hasMoreArguments()) { break; } argumentTracker.advance(); } } } return argumentTracker.build(); } private static ImmutableList<Commented<ExpressionTree>> noComments( List<? extends ExpressionTree> arguments) { return arguments.stream() .map(a -> Commented.<ExpressionTree>builder().setTree(a).build()) .collect(toImmutableList()); } /** * Finds the end position of this MethodInvocationTree. This is complicated by the fact that * sometimes a comment will fall outside of the bounds of the tree. * * <p>For example: * * <pre> * test(arg1, // comment1 * arg2); // comment2 * int i; * </pre> * * In this case {@code comment2} lies beyond the end of the invocation tree. In order to get the * comment we need the tokenizer to lex the token which follows the invocation ({@code int} in the * example). * * <p>We over-approximate this end position by looking for the next node in the AST and using the * end position of this node. * * <p>As a heuristic we first scan for any {@code /} characters on the same line as the end of the * method invocation. If we don't find any then we use the end of the method invocation as the end * position. * * @return the end position of the tree or Optional.empty if we are unable to calculate it */ @VisibleForTesting static Optional<Integer> computeEndPosition( Tree methodInvocationTree, CharSequence sourceCode, VisitorState state) { int invocationEnd = state.getEndPosition(methodInvocationTree); if (invocationEnd == -1) { return Optional.empty(); } // Finding a good end position is expensive so first check whether we have any comment at // the end of our line. If we don't then we can just use the end of the methodInvocationTree int nextNewLine = CharMatcher.is('\n').indexIn(sourceCode, invocationEnd); if (nextNewLine == -1) { return Optional.of(invocationEnd); } if (CharMatcher.is('/').matchesNoneOf(sourceCode.subSequence(invocationEnd, nextNewLine))) { return Optional.of(invocationEnd); } int nextNodeEnd = state.getEndPosition(getNextNodeOrParent(methodInvocationTree, state)); if (nextNodeEnd == -1) { return Optional.of(invocationEnd); } MethodScanner scanner = new MethodScanner(invocationEnd, nextNodeEnd); scanner.scan(state.getPath().getParentPath().getLeaf(), null); return Optional.of( scanner.startOfNextMethodInvocation == -1 ? nextNodeEnd : scanner.startOfNextMethodInvocation); } static class MethodScanner extends TreeScanner<Void, Void> { public int startOfNextMethodInvocation = -1; int invocationEnd; int nextNodeEnd; MethodScanner(int invocationEnd, int nextNodeEnd) { this.invocationEnd = invocationEnd; this.nextNodeEnd = nextNodeEnd; } @Override public Void visitMethodInvocation(MethodInvocationTree methodInvocationTree, Void unused) { int start = ASTHelpers.getStartPosition(methodInvocationTree); if (invocationEnd < start && start < nextNodeEnd && (start < startOfNextMethodInvocation || startOfNextMethodInvocation == -1)) { startOfNextMethodInvocation = start; } return super.visitMethodInvocation(methodInvocationTree, null); } } /** * Find the node which (approximately) follows this one in the tree. This works by walking upwards * to find enclosing block (or class) and then looking for the node after the subtree we walked. * If our subtree is the last of the block then we return the node for the block instead, if we * can't find a suitable block we return the parent node. */ private static Tree getNextNodeOrParent(Tree current, VisitorState state) { Tree predecessorNode = current; TreePath enclosingPath = state.getPath(); while (enclosingPath != null && !(enclosingPath.getLeaf() instanceof BlockTree) && !(enclosingPath.getLeaf() instanceof ClassTree)) { predecessorNode = enclosingPath.getLeaf(); enclosingPath = enclosingPath.getParentPath(); } if (enclosingPath == null) { return state.getPath().getParentPath().getLeaf(); } Tree parent = enclosingPath.getLeaf(); if (parent instanceof BlockTree) { return after(predecessorNode, ((BlockTree) parent).getStatements(), parent); } else if (parent instanceof ClassTree) { return after(predecessorNode, ((ClassTree) parent).getMembers(), parent); } return parent; } /** * Find the element in the iterable following the target * * @param target is the element to search for * @param iterable is the iterable to search * @param defaultValue will be returned if there is no item following the searched for item * @return the item following {@code target} or {@code defaultValue} if not found */ private static <T> T after(T target, Iterable<? extends T> iterable, T defaultValue) { Iterator<? extends T> iterator = iterable.iterator(); while (iterator.hasNext()) { if (iterator.next().equals(target)) { break; } } if (iterator.hasNext()) { return iterator.next(); } return defaultValue; } /** This class is used to keep track of state between lines of code when consuming tokens */ private static class TokenTracker { private final LineMap lineMap; private int tokensOnCurrentLine = 0; private int currentLineNumber = -1; private boolean previousLineEmpty = true; TokenTracker(LineMap lineMap) { this.lineMap = lineMap; } void advance(ErrorProneToken token) { int line = lineMap.getLineNumber(token.pos()); if (line != currentLineNumber) { currentLineNumber = line; previousLineEmpty = tokensOnCurrentLine == 0; tokensOnCurrentLine = 0; } else { tokensOnCurrentLine++; } } boolean isCommentOnPreviousLine(Comment c) { int tokenLine = lineMap.getLineNumber(c.getSourcePos(0)); return tokenLine == currentLineNumber - 1; } boolean atStartOfLine() { return tokensOnCurrentLine == 0; } boolean wasPreviousLineEmpty() { return previousLineEmpty; } } /** * This class is used to keep track of the arguments we are processing. It keeps a window of the * current and previous argument as builders so that more comments can be added to them as we find * them. When we advance everything is shuffled down: the builder for the previous argument is * built and put in the final results list, the builder for the current argument is moved to * previous and a new builder is made for the next argument. We also track the positions of the * current and previous argument so that we know whether a comment occurred before or after it */ private static class ArgumentTracker { private final VisitorState state; private final Iterator<? extends ExpressionTree> argumentsIterator; private final int offset; private final LineMap lineMap; private Commented.Builder<ExpressionTree> currentCommentedResultBuilder = null; private Commented.Builder<ExpressionTree> previousCommentedResultBuilder = null; private final ImmutableList.Builder<Commented<ExpressionTree>> resultBuilder = ImmutableList.builder(); private int currentArgumentStartPosition = -1; private int currentArgumentEndPosition = -1; private int previousArgumentEndPosition = -1; ArgumentTracker( Iterable<? extends ExpressionTree> arguments, int offset, VisitorState state, LineMap lineMap) { this.state = state; this.offset = offset; this.argumentsIterator = arguments.iterator(); this.lineMap = lineMap; } void advance() { ExpressionTree nextArgument = argumentsIterator.next(); currentArgumentEndPosition = state.getEndPosition(nextArgument) - offset; previousArgumentEndPosition = currentArgumentStartPosition; currentArgumentStartPosition = getStartPosition(nextArgument) - offset; if (previousCommentedResultBuilder != null) { resultBuilder.add(previousCommentedResultBuilder.build()); } previousCommentedResultBuilder = currentCommentedResultBuilder; currentCommentedResultBuilder = Commented.<ExpressionTree>builder().setTree(nextArgument); } /** Returns the final result. The object should not be used after calling this method */ ImmutableList<Commented<ExpressionTree>> build() { if (previousCommentedResultBuilder != null) { resultBuilder.add(previousCommentedResultBuilder.build()); } if (currentCommentedResultBuilder != null) { resultBuilder.add(currentCommentedResultBuilder.build()); } return resultBuilder.build(); } boolean isPreviousArgumentOnPreviousLine() { return lineMap.getLineNumber(previousArgumentEndPosition) == lineMap.getLineNumber(currentArgumentStartPosition) - 1; } void addCommentToPreviousArgument(Comment c, Position position) { previousCommentedResultBuilder.addComment(c, previousArgumentEndPosition, offset, position); } void addCommentToCurrentArgument(Comment c, Position position) { currentCommentedResultBuilder.addComment(c, currentArgumentStartPosition, offset, position); } void addAllCommentsToCurrentArgument(Iterable<Comment> comments, Position position) { currentCommentedResultBuilder.addAllComment( comments, currentArgumentStartPosition, offset, position); } boolean hasMoreArguments() { return argumentsIterator.hasNext(); } } private Comments() {} }
18,277
37.889362
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
/* * Copyright 2012 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.util; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Verify.verify; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Streams.stream; import static com.google.errorprone.matchers.JUnitMatchers.JUNIT4_RUN_WITH_ANNOTATION; import static com.google.errorprone.matchers.Matchers.isSubtypeOf; import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toCollection; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.google.auto.value.AutoValue; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.CharMatcher; import com.google.common.collect.AbstractIterator; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.SetMultimap; import com.google.common.collect.Sets; import com.google.common.collect.Streams; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.InlineMe; import com.google.errorprone.dataflow.nullnesspropagation.Nullness; import com.google.errorprone.dataflow.nullnesspropagation.NullnessAnalysis; import com.google.errorprone.matchers.JUnitMatchers; import com.google.errorprone.matchers.Matcher; import com.google.errorprone.matchers.TestNgMatchers; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.suppliers.Suppliers; import com.sun.source.tree.AnnotatedTypeTree; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.ArrayAccessTree; import com.sun.source.tree.AssertTree; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.CaseTree; import com.sun.source.tree.CatchTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.CompoundAssignmentTree; import com.sun.source.tree.ConditionalExpressionTree; import com.sun.source.tree.DoWhileLoopTree; import com.sun.source.tree.EnhancedForLoopTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.ForLoopTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.IfTree; import com.sun.source.tree.InstanceOfTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.LiteralTree; import com.sun.source.tree.MemberReferenceTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.ModifiersTree; import com.sun.source.tree.ModuleTree; import com.sun.source.tree.NewArrayTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.PackageTree; import com.sun.source.tree.ParameterizedTypeTree; import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.ReturnTree; import com.sun.source.tree.SwitchTree; import com.sun.source.tree.SynchronizedTree; import com.sun.source.tree.ThrowTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.TryTree; import com.sun.source.tree.TypeCastTree; import com.sun.source.tree.TypeParameterTree; import com.sun.source.tree.UnaryTree; import com.sun.source.tree.VariableTree; import com.sun.source.tree.WhileLoopTree; import com.sun.source.util.SimpleTreeVisitor; import com.sun.source.util.TreePath; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.api.JavacTrees; import com.sun.tools.javac.code.Attribute; import com.sun.tools.javac.code.Attribute.Compound; import com.sun.tools.javac.code.Attribute.TypeCompound; import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Scope; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.CompletionFailure; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.PackageSymbol; import com.sun.tools.javac.code.Symbol.TypeSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.ClassType; import com.sun.tools.javac.code.Type.TypeVar; import com.sun.tools.javac.code.Type.UnionClassType; import com.sun.tools.javac.code.Type.WildcardType; import com.sun.tools.javac.code.TypeAnnotations; import com.sun.tools.javac.code.TypeAnnotations.AnnotationType; import com.sun.tools.javac.code.TypeTag; import com.sun.tools.javac.code.Types; import com.sun.tools.javac.comp.Enter; import com.sun.tools.javac.comp.Resolve; import com.sun.tools.javac.parser.JavaTokenizer; import com.sun.tools.javac.parser.ScannerFactory; import com.sun.tools.javac.parser.Tokens.Token; import com.sun.tools.javac.parser.Tokens.TokenKind; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCAnnotatedType; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCClassDecl; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCLiteral; import com.sun.tools.javac.tree.JCTree.JCMemberReference; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; import com.sun.tools.javac.tree.JCTree.JCNewClass; import com.sun.tools.javac.tree.JCTree.JCPackageDecl; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.FatalError; import com.sun.tools.javac.util.Log; import com.sun.tools.javac.util.Log.DeferredDiagnosticHandler; import com.sun.tools.javac.util.Name; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.net.JarURLConnection; import java.net.URI; import java.nio.CharBuffer; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Deque; import java.util.EnumSet; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Stream; import javax.annotation.Nullable; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.type.TypeKind; /** This class contains utility methods to work with the javac AST. */ public class ASTHelpers { /** * Determines whether two expressions refer to the same variable. Note that returning false * doesn't necessarily mean the expressions do *not* refer to the same field. We don't attempt to * do any complex analysis here, just catch the obvious cases. */ public static boolean sameVariable(ExpressionTree expr1, ExpressionTree expr2) { requireNonNull(expr1); requireNonNull(expr2); // Throw up our hands if we're not comparing identifiers and/or field accesses. if ((expr1.getKind() != Kind.IDENTIFIER && expr1.getKind() != Kind.MEMBER_SELECT) || (expr2.getKind() != Kind.IDENTIFIER && expr2.getKind() != Kind.MEMBER_SELECT)) { return false; } Symbol sym1 = getSymbol(expr1); Symbol sym2 = getSymbol(expr2); if (sym1 == null) { throw new IllegalStateException("Couldn't get symbol for " + expr1); } else if (sym2 == null) { throw new IllegalStateException("Couldn't get symbol for " + expr2); } if (expr1.getKind() == Kind.IDENTIFIER && expr2.getKind() == Kind.IDENTIFIER) { // foo == foo? return sym1.equals(sym2); } else if (expr1.getKind() == Kind.MEMBER_SELECT && expr2.getKind() == Kind.MEMBER_SELECT) { // foo.baz.bar == foo.baz.bar? return sym1.equals(sym2) && sameVariable(((JCFieldAccess) expr1).selected, ((JCFieldAccess) expr2).selected); } else { // this.foo == foo? ExpressionTree selected; if (expr1.getKind() == Kind.IDENTIFIER) { selected = ((JCFieldAccess) expr2).selected; } else { selected = ((JCFieldAccess) expr1).selected; } // TODO(eaftan): really shouldn't be relying on .toString() return selected.toString().equals("this") && sym1.equals(sym2); } } /** * Gets the symbol declared by a tree. Returns null if {@code tree} does not declare a symbol or * is null. */ @Nullable public static Symbol getDeclaredSymbol(Tree tree) { if (tree instanceof PackageTree) { return getSymbol((PackageTree) tree); } if (tree instanceof TypeParameterTree) { Type type = ((JCTypeParameter) tree).type; return type == null ? null : type.tsym; } if (tree instanceof ClassTree) { return getSymbol((ClassTree) tree); } if (tree instanceof MethodTree) { return getSymbol((MethodTree) tree); } if (tree instanceof VariableTree) { return getSymbol((VariableTree) tree); } return null; } /** * Gets the symbol for a tree. Returns null if this tree does not have a symbol because it is of * the wrong type, if {@code tree} is null, or if the symbol cannot be found due to a compilation * error. */ @Nullable public static Symbol getSymbol(Tree tree) { if (tree instanceof AnnotationTree) { return getSymbol(((AnnotationTree) tree).getAnnotationType()); } if (tree instanceof JCFieldAccess) { return ((JCFieldAccess) tree).sym; } if (tree instanceof JCIdent) { return ((JCIdent) tree).sym; } if (tree instanceof JCMethodInvocation) { return ASTHelpers.getSymbol((MethodInvocationTree) tree); } if (tree instanceof JCNewClass) { return ASTHelpers.getSymbol((NewClassTree) tree); } if (tree instanceof MemberReferenceTree) { return ((JCMemberReference) tree).sym; } if (tree instanceof JCAnnotatedType) { return getSymbol(((JCAnnotatedType) tree).underlyingType); } if (tree instanceof ParameterizedTypeTree) { return getSymbol(((ParameterizedTypeTree) tree).getType()); } if (tree instanceof ClassTree) { return getSymbol((ClassTree) tree); } return getDeclaredSymbol(tree); } /** Gets the symbol for a class. */ public static ClassSymbol getSymbol(ClassTree tree) { return checkNotNull(((JCClassDecl) tree).sym, "%s had a null ClassSymbol", tree); } /** Gets the symbol for a package. */ public static PackageSymbol getSymbol(PackageTree tree) { return checkNotNull(((JCPackageDecl) tree).packge, "%s had a null PackageSymbol", tree); } /** Gets the symbol for a method. */ public static MethodSymbol getSymbol(MethodTree tree) { return checkNotNull(((JCMethodDecl) tree).sym, "%s had a null MethodSymbol", tree); } /** Gets the method symbol for a new class. */ public static MethodSymbol getSymbol(NewClassTree tree) { Symbol sym = ((JCNewClass) tree).constructor; if (!(sym instanceof MethodSymbol)) { // Defensive. Would only occur if there are errors in the AST. throw new IllegalArgumentException(tree.toString()); } return (MethodSymbol) sym; } /** Gets the symbol for a variable. */ public static VarSymbol getSymbol(VariableTree tree) { return checkNotNull(((JCVariableDecl) tree).sym, "%s had a null VariableTree", tree); } /** Gets the symbol for a method invocation. */ public static MethodSymbol getSymbol(MethodInvocationTree tree) { Symbol sym = ASTHelpers.getSymbol(tree.getMethodSelect()); if (!(sym instanceof MethodSymbol)) { // Defensive. Would only occur if there are errors in the AST. throw new IllegalArgumentException(tree.toString()); } return (MethodSymbol) sym; } /** Gets the symbol for a member reference. */ public static MethodSymbol getSymbol(MemberReferenceTree tree) { Symbol sym = ((JCMemberReference) tree).sym; if (!(sym instanceof MethodSymbol)) { // Defensive. Would only occur if there are errors in the AST. throw new IllegalArgumentException(tree.toString()); } return (MethodSymbol) sym; } /** * Returns whether this symbol is safe to remove. That is, if it cannot be accessed from outside * its own compilation unit. * * <p>For variables this just means that one of the enclosing elements is private; for methods, it * also means that this symbol is not an override. */ public static boolean canBeRemoved(Symbol symbol, VisitorState state) { if (symbol instanceof MethodSymbol && !findSuperMethods((MethodSymbol) symbol, state.getTypes()).isEmpty()) { return false; } return isEffectivelyPrivate(symbol); } /** See {@link #canBeRemoved(Symbol, VisitorState)}. */ public static boolean canBeRemoved(VarSymbol symbol) { return isEffectivelyPrivate(symbol); } /** See {@link #canBeRemoved(Symbol, VisitorState)}. */ public static boolean canBeRemoved(ClassSymbol symbol) { return isEffectivelyPrivate(symbol); } /** Returns whether this symbol or any of its owners are private. */ public static boolean isEffectivelyPrivate(Symbol symbol) { return enclosingElements(symbol).anyMatch(Symbol::isPrivate); } /** Checks whether an expression requires parentheses. */ public static boolean requiresParentheses(ExpressionTree expression, VisitorState state) { switch (expression.getKind()) { case IDENTIFIER: case MEMBER_SELECT: case METHOD_INVOCATION: case ARRAY_ACCESS: case PARENTHESIZED: case NEW_CLASS: case MEMBER_REFERENCE: return false; case LAMBDA_EXPRESSION: // Parenthesizing e.g. `x -> (y -> z)` is unnecessary but helpful Tree parent = state.getPath().getParentPath().getLeaf(); return parent.getKind().equals(Kind.LAMBDA_EXPRESSION) && stripParentheses(((LambdaExpressionTree) parent).getBody()).equals(expression); default: // continue below } if (expression instanceof LiteralTree) { if (!isSameType(getType(expression), state.getSymtab().stringType, state)) { return false; } // TODO(b/112139121): work around for javac's too-early constant string folding return state.getOffsetTokensForNode(expression).stream() .anyMatch(t -> t.kind() == TokenKind.PLUS); } if (expression instanceof UnaryTree) { Tree parent = state.getPath().getParentPath().getLeaf(); if (!(parent instanceof MemberSelectTree)) { return false; } // eg. (i++).toString(); return stripParentheses(((MemberSelectTree) parent).getExpression()).equals(expression); } return true; } /** Removes any enclosing parentheses from the tree. */ public static Tree stripParentheses(Tree tree) { return tree instanceof ExpressionTree ? stripParentheses((ExpressionTree) tree) : tree; } /** Given an ExpressionTree, removes any enclosing parentheses. */ public static ExpressionTree stripParentheses(ExpressionTree tree) { while (tree instanceof ParenthesizedTree) { tree = ((ParenthesizedTree) tree).getExpression(); } return tree; } /** * Given a TreePath, finds the first enclosing node of the given type and returns the path from * the enclosing node to the top-level {@code CompilationUnitTree}. */ public static <T> TreePath findPathFromEnclosingNodeToTopLevel(TreePath path, Class<T> klass) { if (path != null) { do { path = path.getParentPath(); } while (path != null && !klass.isInstance(path.getLeaf())); } return path; } /** * Returns a stream of the owner hierarchy starting from {@code sym}, as described by {@link * Symbol#owner}. Returns {@code sym} itself first, followed by its owners, closest first, up to * the owning package and possibly module. */ public static Stream<Symbol> enclosingElements(Symbol sym) { return Stream.iterate(sym, Symbol::getEnclosingElement).takeWhile(s -> s != null); } /** * Given a TreePath, walks up the tree until it finds a node of the given type. Returns null if no * such node is found. */ @Nullable public static <T> T findEnclosingNode(TreePath path, Class<T> klass) { path = findPathFromEnclosingNodeToTopLevel(path, klass); return (path == null) ? null : klass.cast(path.getLeaf()); } /** Finds the enclosing {@link MethodTree}. Returns {@code null} if no such node found. */ @Nullable public static MethodTree findEnclosingMethod(VisitorState state) { for (Tree parent : state.getPath()) { switch (parent.getKind()) { case METHOD: return (MethodTree) parent; case CLASS: case LAMBDA_EXPRESSION: return null; default: // fall out } } return null; } /** * Find the root assignable expression of a chain of field accesses. If there is no root (i.e, a * bare method call or a static method call), return null. * * <p>Examples: * * <pre>{@code * a.trim().intern() ==> a * a.b.trim().intern() ==> a.b * this.intValue.foo() ==> this.intValue * this.foo() ==> this * intern() ==> null * String.format() ==> null * java.lang.String.format() ==> null * }</pre> */ @Nullable public static ExpressionTree getRootAssignable(MethodInvocationTree methodInvocationTree) { if (!(methodInvocationTree instanceof JCMethodInvocation)) { throw new IllegalArgumentException( "Expected type to be JCMethodInvocation, but was " + methodInvocationTree.getClass()); } // Check for bare method call, e.g. intern(). if (((JCMethodInvocation) methodInvocationTree).getMethodSelect() instanceof JCIdent) { return null; } // Unwrap the field accesses until you get to an identifier. ExpressionTree expr = methodInvocationTree; while (expr instanceof JCMethodInvocation) { expr = ((JCMethodInvocation) expr).getMethodSelect(); if (expr instanceof JCFieldAccess) { expr = ((JCFieldAccess) expr).getExpression(); } } // We only want assignable identifiers. Symbol sym = getSymbol(expr); if (sym instanceof VarSymbol) { return expr; } return null; } /** * Gives the return type of an ExpressionTree that represents a method select. * * <p>TODO(eaftan): Are there other places this could be used? */ public static Type getReturnType(ExpressionTree expressionTree) { if (expressionTree instanceof JCFieldAccess) { JCFieldAccess methodCall = (JCFieldAccess) expressionTree; return methodCall.type.getReturnType(); } else if (expressionTree instanceof JCIdent) { JCIdent methodCall = (JCIdent) expressionTree; return methodCall.type.getReturnType(); } else if (expressionTree instanceof JCMethodInvocation) { return getReturnType(((JCMethodInvocation) expressionTree).getMethodSelect()); } else if (expressionTree instanceof JCMemberReference) { return ((JCMemberReference) expressionTree).sym.type.getReturnType(); } throw new IllegalArgumentException("Expected a JCFieldAccess or JCIdent"); } /** * Returns the type that this expression tree will evaluate to. If it's a literal, an identifier, * or a member select this is the actual type, if it's a method invocation then it's the return * type of the method (after instantiating generic types), if it's a constructor then it's the * type of the returned class. * * <p>TODO(andrewrice) consider replacing {@code getReturnType} with this method * * @param expressionTree the tree to evaluate * @return the result type of this tree or null if unable to resolve it */ @Nullable public static Type getResultType(ExpressionTree expressionTree) { Type type = ASTHelpers.getType(expressionTree); return type == null ? null : Optional.ofNullable(type.getReturnType()).orElse(type); } /** * Returns the type of a receiver of a method call expression. Precondition: the expressionTree * corresponds to a method call. * * <p>Examples: * * <pre>{@code * a.b.foo() ==> type of a.b * a.bar().foo() ==> type of a.bar() * this.foo() ==> type of this * foo() ==> type of this * TheClass.aStaticMethod() ==> TheClass * aStaticMethod() ==> type of class in which method is defined * }</pre> */ public static Type getReceiverType(ExpressionTree expressionTree) { if (expressionTree instanceof JCFieldAccess) { JCFieldAccess methodSelectFieldAccess = (JCFieldAccess) expressionTree; return methodSelectFieldAccess.selected.type; } else if (expressionTree instanceof JCIdent) { JCIdent methodCall = (JCIdent) expressionTree; return methodCall.sym.owner.type; } else if (expressionTree instanceof JCMethodInvocation) { return getReceiverType(((JCMethodInvocation) expressionTree).getMethodSelect()); } else if (expressionTree instanceof JCMemberReference) { return ((JCMemberReference) expressionTree).getQualifierExpression().type; } throw new IllegalArgumentException( "Expected a JCFieldAccess or JCIdent from expression " + expressionTree); } /** * Returns the receiver of an expression. * * <p>Examples: * * <pre>{@code * a.foo() ==> a * a.b.foo() ==> a.b * a.bar().foo() ==> a.bar() * a.b.c ==> a.b * a.b().c ==> a.b() * this.foo() ==> this * foo() ==> null * TheClass.aStaticMethod() ==> TheClass * aStaticMethod() ==> null * aStaticallyImportedMethod() ==> null * }</pre> */ @Nullable public static ExpressionTree getReceiver(ExpressionTree expressionTree) { if (expressionTree instanceof MethodInvocationTree) { ExpressionTree methodSelect = ((MethodInvocationTree) expressionTree).getMethodSelect(); if (methodSelect instanceof IdentifierTree) { return null; } return getReceiver(methodSelect); } else if (expressionTree instanceof MemberSelectTree) { return ((MemberSelectTree) expressionTree).getExpression(); } else if (expressionTree instanceof MemberReferenceTree) { return ((MemberReferenceTree) expressionTree).getQualifierExpression(); } else { throw new IllegalStateException( String.format( "Expected expression '%s' to be a method invocation or field access, but was %s", expressionTree, expressionTree.getKind())); } } /** * Returns a {@link Stream} of {@link ExpressionTree}s resulting from calling {@link * #getReceiver(ExpressionTree)} repeatedly until no receiver exists. * * <p>For example, give {@code foo().bar().baz()}, returns a stream of {@code [foo().bar(), * foo()]}. * * <p>This can be more convenient than manually traversing up a tree, as it handles the * termination condition automatically. Typical uses cases would include traversing fluent call * chains. */ public static Stream<ExpressionTree> streamReceivers(ExpressionTree tree) { return stream( new AbstractIterator<ExpressionTree>() { private ExpressionTree current = tree; @Override protected ExpressionTree computeNext() { if (current instanceof MethodInvocationTree || current instanceof MemberSelectTree || current instanceof MemberReferenceTree) { current = getReceiver(current); return current == null ? endOfData() : current; } return endOfData(); } }); } /** * Given a BinaryTree to match against and a list of two matchers, applies the matchers to the * operands in both orders. If both matchers match, returns a list with the operand that matched * each matcher in the corresponding position. * * @param tree a BinaryTree AST node * @param matchers a list of matchers * @param state the VisitorState * @return a list of matched operands, or null if at least one did not match */ @Nullable public static List<ExpressionTree> matchBinaryTree( BinaryTree tree, List<Matcher<ExpressionTree>> matchers, VisitorState state) { ExpressionTree leftOperand = tree.getLeftOperand(); ExpressionTree rightOperand = tree.getRightOperand(); if (matchers.get(0).matches(leftOperand, state) && matchers.get(1).matches(rightOperand, state)) { return Arrays.asList(leftOperand, rightOperand); } else if (matchers.get(0).matches(rightOperand, state) && matchers.get(1).matches(leftOperand, state)) { return Arrays.asList(rightOperand, leftOperand); } return null; } /** * Returns the method tree that matches the given symbol within the compilation unit, or null if * none was found. */ @Nullable public static MethodTree findMethod(MethodSymbol symbol, VisitorState state) { return JavacTrees.instance(state.context).getTree(symbol); } /** * Returns the class tree that matches the given symbol within the compilation unit, or null if * none was found. */ @Nullable public static ClassTree findClass(ClassSymbol symbol, VisitorState state) { return JavacTrees.instance(state.context).getTree(symbol); } // TODO(ghm): Using a comparison of tsym here appears to be a behaviour change. @SuppressWarnings("TypeEquals") @Nullable public static MethodSymbol findSuperMethodInType( MethodSymbol methodSymbol, Type superType, Types types) { if (methodSymbol.isStatic() || superType.equals(methodSymbol.owner.type)) { return null; } Scope scope = superType.tsym.members(); for (Symbol sym : scope.getSymbolsByName(methodSymbol.name)) { if (sym != null && !isStatic(sym) && ((sym.flags() & Flags.SYNTHETIC) == 0) && methodSymbol.overrides( sym, (TypeSymbol) methodSymbol.owner, types, /* checkResult= */ true)) { return (MethodSymbol) sym; } } return null; } /** * Finds supermethods of {@code methodSymbol}, not including {@code methodSymbol} itself, and * including interfaces. */ public static Set<MethodSymbol> findSuperMethods(MethodSymbol methodSymbol, Types types) { return findSuperMethods(methodSymbol, types, /* skipInterfaces= */ false) .collect(toCollection(LinkedHashSet::new)); } /** See {@link #findSuperMethods(MethodSymbol, Types)}. */ public static Stream<MethodSymbol> streamSuperMethods(MethodSymbol methodSymbol, Types types) { return findSuperMethods(methodSymbol, types, /* skipInterfaces= */ false); } private static Stream<MethodSymbol> findSuperMethods( MethodSymbol methodSymbol, Types types, boolean skipInterfaces) { TypeSymbol owner = (TypeSymbol) methodSymbol.owner; Stream<Type> typeStream = types.closure(owner.type).stream(); if (skipInterfaces) { typeStream = typeStream.filter(type -> !type.isInterface()); } return typeStream .map(type -> findSuperMethodInType(methodSymbol, type, types)) .filter(Objects::nonNull); } /** * Finds (if it exists) first (in the class hierarchy) non-interface super method of given {@code * method}. */ public static Optional<MethodSymbol> findSuperMethod(MethodSymbol methodSymbol, Types types) { return findSuperMethods(methodSymbol, types, /* skipInterfaces= */ true).findFirst(); } /** * Finds all methods in any superclass of {@code startClass} with a certain {@code name} that * match the given {@code predicate}. * * @return The (possibly empty) list of methods in any superclass that match {@code predicate} and * have the given {@code name}. Results are returned least-abstract first, i.e., starting in * the {@code startClass} itself, progressing through its superclasses, and finally interfaces * in an unspecified order. */ public static Stream<MethodSymbol> matchingMethods( Name name, Predicate<MethodSymbol> predicate, Type startClass, Types types) { Predicate<Symbol> matchesMethodPredicate = sym -> sym instanceof MethodSymbol && predicate.test((MethodSymbol) sym); // Iterate over all classes and interfaces that startClass inherits from. return types.closure(startClass).stream() .flatMap( (Type superClass) -> { // Iterate over all the methods declared in superClass. TypeSymbol superClassSymbol = superClass.tsym; Scope superClassSymbols = superClassSymbol.members(); if (superClassSymbols == null) { // Can be null if superClass is a type variable return Stream.empty(); } return stream( scope(superClassSymbols) .getSymbolsByName(name, matchesMethodPredicate, NON_RECURSIVE)) // By definition of the filter, we know that the symbol is a MethodSymbol. .map(symbol -> (MethodSymbol) symbol); }); } /** * Finds all methods in any superclass of {@code startClass} with a certain {@code name} that * match the given {@code predicate}. * * @return The (possibly empty) set of methods in any superclass that match {@code predicate} and * have the given {@code name}. The set's iteration order will be the same as the order * documented in {@link #matchingMethods(Name, java.util.function.Predicate, Type, Types)}. */ public static ImmutableSet<MethodSymbol> findMatchingMethods( Name name, Predicate<MethodSymbol> predicate, Type startClass, Types types) { return matchingMethods(name, predicate, startClass, types).collect(toImmutableSet()); } /** * Determines whether a method can be overridden. * * @return true if the method can be overridden. */ public static boolean methodCanBeOverridden(MethodSymbol methodSymbol) { if (methodSymbol.getModifiers().contains(Modifier.ABSTRACT)) { return true; } if (methodSymbol.isStatic() || methodSymbol.isPrivate() || isFinal(methodSymbol) || methodSymbol.isConstructor()) { return false; } ClassSymbol classSymbol = (ClassSymbol) methodSymbol.owner; return !isFinal(classSymbol) && !classSymbol.isAnonymous(); } private static boolean isFinal(Symbol symbol) { return (symbol.flags() & Flags.FINAL) == Flags.FINAL; } /** * Flag for record types, canonical record constructors and type members that are part of a * record's state vector. Can be replaced by {@code com.sun.tools.javac.code.Flags.RECORD} once * the minimum JDK version is 14. */ private static final long RECORD_FLAG = 1L << 61; /** * Returns whether the given {@link Symbol} is a record, a record's canonical constructor or a * member that is part of a record's state vector. */ public static boolean isRecord(Symbol symbol) { return (symbol.flags() & RECORD_FLAG) == RECORD_FLAG; } /** * Determines whether a symbol has an annotation of the given type. This includes annotations * inherited from superclasses due to {@code @Inherited}. * * @param annotationClass the binary class name of the annotation (e.g. * "javax.annotation.Nullable", or "some.package.OuterClassName$InnerClassName") * @return true if the symbol is annotated with given type. */ public static boolean hasAnnotation(Symbol sym, String annotationClass, VisitorState state) { if (sym == null) { return false; } // TODO(amalloy): unify with hasAnnotation(Symbol, Name, VisitorState) // normalize to non-binary names annotationClass = annotationClass.replace('$', '.'); Name annotationName = state.getName(annotationClass); if (hasAttribute(sym, annotationName)) { return true; } if (sym instanceof ClassSymbol && isInherited(state, annotationClass)) { do { if (hasAttribute(sym, annotationName)) { return true; } sym = ((ClassSymbol) sym).getSuperclass().tsym; } while (sym instanceof ClassSymbol); } return false; } /** * Check for the presence of an annotation, considering annotation inheritance. * * @return true if the symbol is annotated with given type. * @deprecated prefer {@link #hasAnnotation(Symbol, String, VisitorState)} to avoid needing a * runtime dependency on the annotation class, and to prevent issues if there is skew between * the definition of the annotation on the runtime and compile-time classpaths */ @InlineMe( replacement = "ASTHelpers.hasAnnotation(sym, annotationClass.getName(), state)", imports = {"com.google.errorprone.util.ASTHelpers"}) @Deprecated public static boolean hasAnnotation( Symbol sym, Class<? extends Annotation> annotationClass, VisitorState state) { return hasAnnotation(sym, annotationClass.getName(), state); } /** * Check for the presence of an annotation, considering annotation inheritance. * * @param annotationClass the binary class name of the annotation (e.g. * "javax.annotation.Nullable", or "some.package.OuterClassName$InnerClassName") * @return true if the tree is annotated with given type. */ public static boolean hasAnnotation(Tree tree, String annotationClass, VisitorState state) { Symbol sym = getDeclaredSymbol(tree); return hasAnnotation(sym, annotationClass, state); } /** * Check for the presence of an annotation, considering annotation inheritance. * * @return true if the tree is annotated with given type. * @deprecated prefer {@link #hasAnnotation(Symbol, String, VisitorState)} to avoid needing a * runtime dependency on the annotation class, and to prevent issues if there is skew between * the definition of the annotation on the runtime and compile-time classpaths */ @InlineMe( replacement = "ASTHelpers.hasAnnotation(tree, annotationClass.getName(), state)", imports = {"com.google.errorprone.util.ASTHelpers"}) @Deprecated public static boolean hasAnnotation( Tree tree, Class<? extends Annotation> annotationClass, VisitorState state) { return hasAnnotation(tree, annotationClass.getName(), state); } private static final Supplier<Cache<Name, Boolean>> inheritedAnnotationCache = VisitorState.memoize(unusedState -> Caffeine.newBuilder().maximumSize(1000).build()); @SuppressWarnings("ConstantConditions") // IntelliJ worries unboxing our Boolean may throw NPE. private static boolean isInherited(VisitorState state, Name annotationName) { return inheritedAnnotationCache .get(state) .get( annotationName, name -> { Symbol annotationSym = state.getSymbolFromName(annotationName); if (annotationSym == null) { return false; } try { annotationSym.complete(); } catch (CompletionFailure e) { /* @Inherited won't work if the annotation isn't on the classpath, but we can still check if it's present directly */ } Symbol inheritedSym = state.getSymtab().inheritedType.tsym; return annotationSym.attribute(inheritedSym) != null; }); } private static boolean isInherited(VisitorState state, String annotationName) { return isInherited(state, state.binaryNameFromClassname(annotationName)); } private static boolean hasAttribute(Symbol sym, Name annotationName) { for (Compound a : sym.getRawAttributes()) { if (a.type.tsym.getQualifiedName().equals(annotationName)) { return true; } } return false; } /** * Determines which of a set of annotations are present on a symbol. * * @param sym The symbol to inspect for annotations * @param annotationClasses The annotations of interest to look for, Each name must be in binary * form, e.g. "com.google.Foo$Bar", not "com.google.Foo.Bar". * @return A possibly-empty set of annotations present on the queried element. */ public static Set<Name> annotationsAmong( Symbol sym, Set<? extends Name> annotationClasses, VisitorState state) { if (sym == null) { return ImmutableSet.of(); } Set<Name> result = directAnnotationsAmong(sym, annotationClasses); if (!(sym instanceof ClassSymbol)) { return result; } Set<Name> possibleInherited = new HashSet<>(); for (Name a : annotationClasses) { if (!result.contains(a) && isInherited(state, a)) { possibleInherited.add(a); } } sym = ((ClassSymbol) sym).getSuperclass().tsym; while (sym instanceof ClassSymbol && !possibleInherited.isEmpty()) { for (Name local : directAnnotationsAmong(sym, possibleInherited)) { result.add(local); possibleInherited.remove(local); } sym = ((ClassSymbol) sym).getSuperclass().tsym; } return result; } /** * Explicitly returns a modifiable {@code Set<Name>}, so that annotationsAmong can futz with it to * add inherited annotations. */ private static Set<Name> directAnnotationsAmong( Symbol sym, Set<? extends Name> binaryAnnotationNames) { Set<Name> result = new HashSet<>(); for (Compound a : sym.getRawAttributes()) { Name annoName = a.type.tsym.flatName(); if (binaryAnnotationNames.contains(annoName)) { result.add(annoName); } } return result; } /** * Check for the presence of an annotation with a specific simple name directly on this symbol. * Does *not* consider annotation inheritance. * * @param sym the symbol to check for the presence of the annotation * @param simpleName the simple name of the annotation to look for, e.g. "Nullable" or * "CheckReturnValue" */ public static boolean hasDirectAnnotationWithSimpleName(Symbol sym, String simpleName) { for (AnnotationMirror annotation : sym.getAnnotationMirrors()) { if (annotation.getAnnotationType().asElement().getSimpleName().contentEquals(simpleName)) { return true; } } return false; } /** * Check for the presence of an annotation with a specific simple name directly on this symbol. * Does *not* consider annotation inheritance. * * @param tree the tree to check for the presence of the annotation * @param simpleName the simple name of the annotation to look for, e.g. "Nullable" or * "CheckReturnValue" */ public static boolean hasDirectAnnotationWithSimpleName(Tree tree, String simpleName) { return hasDirectAnnotationWithSimpleName(getDeclaredSymbol(tree), simpleName); } /** * Returns true if any of the given tree is a declaration annotated with an annotation with the * simple name {@code @UsedReflectively} or {@code @Keep}, or any annotations meta-annotated with * an annotation with that simple name. * * <p>This indicates the annotated element is used (e.g. by reflection, or referenced by generated * code) and should not be removed. */ public static boolean shouldKeep(Tree tree) { ModifiersTree modifiers = getModifiers(tree); if (modifiers == null) { return false; } for (AnnotationTree annotation : modifiers.getAnnotations()) { Type annotationType = getType(annotation); if (annotationType == null) { continue; } TypeSymbol tsym = annotationType.tsym; if (tsym.getSimpleName().contentEquals(USED_REFLECTIVELY) || tsym.getSimpleName().contentEquals(KEEP)) { return true; } if (ANNOTATIONS_CONSIDERED_KEEP.contains(tsym.getQualifiedName().toString())) { return true; } if (hasDirectAnnotationWithSimpleName(tsym, USED_REFLECTIVELY) || hasDirectAnnotationWithSimpleName(tsym, KEEP)) { return true; } } return false; } /** * Additional annotations which can't be annotated with {@code @Keep}, but should be treated as * though they are. */ private static final ImmutableSet<String> ANNOTATIONS_CONSIDERED_KEEP = ImmutableSet.of( "org.apache.beam.sdk.transforms.DoFn.ProcessElement", "org.junit.jupiter.api.Nested"); private static final String USED_REFLECTIVELY = "UsedReflectively"; private static final String KEEP = "Keep"; /** * Retrieves an annotation, considering annotation inheritance. * * @deprecated If {@code annotationClass} contains a member that is a {@code Class} or an array of * them, attempting to access that member from the Error Prone checker code will result in a * runtime exception. Instead, operate on {@code sym.getAnnotationMirrors()} to * meta-syntactically inspect the annotation. */ @Nullable @Deprecated public static <T extends Annotation> T getAnnotation(Tree tree, Class<T> annotationClass) { Symbol sym = getSymbol(tree); return sym == null ? null : getAnnotation(sym, annotationClass); } /** * Retrieves an annotation, considering annotation inheritance. * * @deprecated If {@code annotationClass} contains a member that is a {@code Class} or an array of * them, attempting to access that member from the Error Prone checker code will result in a * runtime exception. Instead, operate on {@code sym.getAnnotationMirrors()} to * meta-syntactically inspect the annotation. */ @Nullable @Deprecated @SuppressWarnings("deprecation") public static <T extends Annotation> T getAnnotation(Symbol sym, Class<T> annotationClass) { return sym == null ? null : sym.getAnnotation(annotationClass); } /** * @return all values of the given enum type, in declaration order. */ public static LinkedHashSet<String> enumValues(TypeSymbol enumType) { if (enumType.getKind() != ElementKind.ENUM) { throw new IllegalStateException(); } Scope scope = enumType.members(); Deque<String> values = new ArrayDeque<>(); for (Symbol sym : scope.getSymbols()) { if (sym instanceof VarSymbol) { VarSymbol var = (VarSymbol) sym; if ((var.flags() & Flags.ENUM) != 0) { /* * Javac gives us the members backwards, apparently. It's worth making an effort to * preserve declaration order because it's useful for diagnostics (e.g. in {@link * MissingCasesInEnumSwitch}). */ values.push(sym.name.toString()); } } } return new LinkedHashSet<>(values); } /** Returns true if the given tree is a generated constructor. */ public static boolean isGeneratedConstructor(MethodTree tree) { if (!(tree instanceof JCMethodDecl)) { return false; } return (((JCMethodDecl) tree).mods.flags & Flags.GENERATEDCONSTR) == Flags.GENERATEDCONSTR; } /** Returns the list of all constructors defined in the class (including generated ones). */ public static List<MethodTree> getConstructors(ClassTree classTree) { List<MethodTree> constructors = new ArrayList<>(); for (Tree member : classTree.getMembers()) { if (member instanceof MethodTree) { MethodTree methodTree = (MethodTree) member; if (getSymbol(methodTree).isConstructor()) { constructors.add(methodTree); } } } return constructors; } /** * A wrapper for {@link Symbol#getEnclosedElements} to avoid binary compatibility issues for * covariant overrides in subtypes of {@link Symbol}. */ public static List<Symbol> getEnclosedElements(Symbol symbol) { return symbol.getEnclosedElements(); } /** Returns the list of all constructors defined in the class. */ public static ImmutableList<MethodSymbol> getConstructors(ClassSymbol classSymbol) { return getEnclosedElements(classSymbol).stream() .filter(Symbol::isConstructor) .map(e -> (MethodSymbol) e) .collect(toImmutableList()); } /** * Returns the {@code Type} of the given tree, or {@code null} if the type could not be * determined. */ @Nullable public static Type getType(@Nullable Tree tree) { return tree instanceof JCTree ? ((JCTree) tree).type : null; } /** * Returns the {@code ClassType} for the given type {@code ClassTree} or {@code null} if the type * could not be determined. */ @Nullable public static ClassType getType(@Nullable ClassTree tree) { Type type = getType((Tree) tree); return type instanceof ClassType ? (ClassType) type : null; } @Nullable public static String getAnnotationName(AnnotationTree tree) { Symbol sym = getSymbol(tree); return sym == null ? null : sym.name.toString(); } /** Returns the erasure of the given type tree, i.e. {@code List} for {@code List<Foo>}. */ public static Tree getErasedTypeTree(Tree tree) { return tree.accept( new SimpleTreeVisitor<Tree, Void>() { @Override public Tree visitIdentifier(IdentifierTree tree, Void unused) { return tree; } @Override public Tree visitParameterizedType(ParameterizedTypeTree tree, Void unused) { return tree.getType(); } }, null); } /** Return the enclosing {@code ClassSymbol} of the given symbol, or {@code null}. */ @Nullable public static ClassSymbol enclosingClass(Symbol sym) { // sym.owner is null in the case of module symbols. return sym.owner == null ? null : sym.owner.enclClass(); } /** * Return the enclosing {@code PackageSymbol} of the given symbol, or {@code null}. * * <p>Prefer this to {@link Symbol#packge}, which throws a {@link NullPointerException} for * symbols that are not contained by a package: https://bugs.openjdk.java.net/browse/JDK-8231911 */ @Nullable public static PackageSymbol enclosingPackage(Symbol sym) { Symbol curr = sym; while (curr != null) { if (curr.getKind().equals(ElementKind.PACKAGE)) { return (PackageSymbol) curr; } curr = curr.owner; } return null; } /** Return true if the given symbol is defined in the current package. */ public static boolean inSamePackage(Symbol targetSymbol, VisitorState state) { JCCompilationUnit compilationUnit = (JCCompilationUnit) state.getPath().getCompilationUnit(); PackageSymbol usePackage = compilationUnit.packge; PackageSymbol targetPackage = enclosingPackage(targetSymbol); return targetPackage != null && usePackage != null && targetPackage.getQualifiedName().equals(usePackage.getQualifiedName()); } /** * Returns the {@link Nullness} for an expression as determined by the nullness dataflow analysis. */ public static Nullness getNullnessValue( ExpressionTree expr, VisitorState state, NullnessAnalysis nullnessAnalysis) { TreePath pathToExpr = new TreePath(state.getPath(), expr); return nullnessAnalysis.getNullness(pathToExpr, state.context); } /** Returns the compile-time constant value of a tree if it has one, or {@code null}. */ @Nullable public static Object constValue(Tree tree) { if (tree == null) { return null; } tree = stripParentheses(tree); Type type = ASTHelpers.getType(tree); Object value; if (tree instanceof JCLiteral) { value = ((JCLiteral) tree).value; } else if (type != null) { value = type.constValue(); } else { return null; } if (type.hasTag(TypeTag.BOOLEAN) && value instanceof Integer) { return ((Integer) value) == 1; } return value; } /** Returns the compile-time constant value of a tree if it is of type clazz, or {@code null}. */ @Nullable public static <T> T constValue(Tree tree, Class<? extends T> clazz) { Object value = constValue(tree); return clazz.isInstance(value) ? clazz.cast(value) : null; } /** Return true if the given type is 'void' or 'Void'. */ public static boolean isVoidType(Type type, VisitorState state) { if (type == null) { return false; } return type.getKind() == TypeKind.VOID || state.getTypes().isSameType(Suppliers.JAVA_LANG_VOID_TYPE.get(state), type); } private static final ImmutableSet<TypeTag> SUBTYPE_UNDEFINED = Sets.immutableEnumSet( TypeTag.METHOD, TypeTag.PACKAGE, TypeTag.UNKNOWN, TypeTag.ERROR, TypeTag.FORALL); /** Returns true if {@code erasure(s) <: erasure(t)}. */ public static boolean isSubtype(Type s, Type t, VisitorState state) { if (s == null || t == null) { return false; } if (SUBTYPE_UNDEFINED.contains(s.getTag()) || SUBTYPE_UNDEFINED.contains(t.getTag())) { return false; } Types types = state.getTypes(); return types.isSubtype(types.erasure(s), types.erasure(t)); } /** * Returns true if {@code t} is a subtype of Throwable but not a subtype of RuntimeException or * Error. */ public static boolean isCheckedExceptionType(Type t, VisitorState state) { Symtab symtab = state.getSymtab(); return isSubtype(t, symtab.throwableType, state) && !isSubtype(t, symtab.runtimeExceptionType, state) && !isSubtype(t, symtab.errorType, state); } /** Returns true if {@code erasure(s)} is castable to {@code erasure(t)}. */ public static boolean isCastable(Type s, Type t, VisitorState state) { if (s == null || t == null) { return false; } Types types = state.getTypes(); return types.isCastable(types.erasure(s), types.erasure(t)); } /** Returns true if {@code erasure(s) == erasure(t)}. */ public static boolean isSameType(Type s, Type t, VisitorState state) { if (s == null || t == null) { return false; } Types types = state.getTypes(); return types.isSameType(types.erasure(s), types.erasure(t)); } /** Returns the modifiers tree of the given class, method, or variable declaration. */ @Nullable public static ModifiersTree getModifiers(Tree tree) { if (tree instanceof ClassTree) { return ((ClassTree) tree).getModifiers(); } if (tree instanceof MethodTree) { return ((MethodTree) tree).getModifiers(); } if (tree instanceof VariableTree) { return ((VariableTree) tree).getModifiers(); } if (tree instanceof ModifiersTree) { return (ModifiersTree) tree; } return null; } /** Returns the annotations of the given tree, or an empty list. */ public static List<? extends AnnotationTree> getAnnotations(Tree tree) { if (tree instanceof TypeParameterTree) { return ((TypeParameterTree) tree).getAnnotations(); } if (tree instanceof ModuleTree) { return ((ModuleTree) tree).getAnnotations(); } if (tree instanceof PackageTree) { return ((PackageTree) tree).getAnnotations(); } if (tree instanceof NewArrayTree) { return ((NewArrayTree) tree).getAnnotations(); } if (tree instanceof AnnotatedTypeTree) { return ((AnnotatedTypeTree) tree).getAnnotations(); } if (tree instanceof ModifiersTree) { return ((ModifiersTree) tree).getAnnotations(); } ModifiersTree modifiersTree = getModifiers(tree); return modifiersTree == null ? ImmutableList.of() : modifiersTree.getAnnotations(); } /** * Returns the upper bound of a type if it has one, or the type itself if not. Correctly handles * wildcards and capture variables. */ public static Type getUpperBound(Type type, Types types) { if (type.hasTag(TypeTag.WILDCARD)) { return types.wildUpperBound(type); } if (type.hasTag(TypeTag.TYPEVAR) && ((TypeVar) type).isCaptured()) { return types.cvarUpperBound(type); } if (type.getUpperBound() != null) { return type.getUpperBound(); } // concrete type, e.g. java.lang.String, or a case we haven't considered return type; } /** * Returns true if the leaf node in the {@link TreePath} from {@code state} sits somewhere * underneath a class or method that is marked as JUnit 3 or 4 test code. */ public static boolean isJUnitTestCode(VisitorState state) { for (Tree ancestor : state.getPath()) { if (ancestor instanceof MethodTree && JUnitMatchers.hasJUnitAnnotation((MethodTree) ancestor, state)) { return true; } if (ancestor instanceof ClassTree && (JUnitMatchers.isTestCaseDescendant.matches((ClassTree) ancestor, state) || hasAnnotation(getSymbol(ancestor), JUNIT4_RUN_WITH_ANNOTATION, state))) { return true; } } return false; } /** * Returns true if the leaf node in the {@link TreePath} from {@code state} sits somewhere * underneath a class or method that is marked as TestNG test code. */ public static boolean isTestNgTestCode(VisitorState state) { for (Tree ancestor : state.getPath()) { if (ancestor instanceof MethodTree && TestNgMatchers.hasTestNgAnnotation((MethodTree) ancestor, state)) { return true; } if (ancestor instanceof ClassTree && TestNgMatchers.hasTestNgAnnotation((ClassTree) ancestor)) { return true; } } return false; } /** Returns an {@link AnnotationTree} with the given simple name, or {@code null}. */ @Nullable public static AnnotationTree getAnnotationWithSimpleName( List<? extends AnnotationTree> annotations, String name) { for (AnnotationTree annotation : annotations) { if (hasSimpleName(annotation, name)) { return annotation; } } return null; } /** * Returns a list of {@link AnnotationTree} with the given simple name. This is useful for {@link * java.lang.annotation.Repeatable} annotations */ public static List<AnnotationTree> getAnnotationsWithSimpleName( List<? extends AnnotationTree> annotations, String name) { List<AnnotationTree> matches = new ArrayList<>(); for (AnnotationTree annotation : annotations) { if (hasSimpleName(annotation, name)) { matches.add(annotation); } } return matches; } private static boolean hasSimpleName(AnnotationTree annotation, String name) { Tree annotationType = annotation.getAnnotationType(); javax.lang.model.element.Name simpleName; if (annotationType instanceof IdentifierTree) { simpleName = ((IdentifierTree) annotationType).getName(); } else if (annotationType instanceof MemberSelectTree) { simpleName = ((MemberSelectTree) annotationType).getIdentifier(); } else { return false; } return simpleName.contentEquals(name); } /** * Returns whether {@code anno} corresponds to a type annotation, or {@code null} if it could not * be determined. */ @Nullable public static AnnotationType getAnnotationType( AnnotationTree anno, @Nullable Symbol target, VisitorState state) { if (target == null) { return null; } Symbol annoSymbol = getSymbol(anno); if (annoSymbol == null) { return null; } Compound compound = target.attribute(annoSymbol); if (compound == null) { for (TypeCompound typeCompound : target.getRawTypeAttributes()) { if (typeCompound.type.tsym.equals(annoSymbol)) { compound = typeCompound; break; } } } if (compound == null) { return null; } return annotationTargetType(TypeAnnotations.instance(state.context), anno, compound, target); } private static AnnotationType annotationTargetType( TypeAnnotations typeAnnotations, AnnotationTree tree, Compound compound, @Nullable Symbol target) { try { try { // the JCTree argument was added in JDK 21 return (AnnotationType) TypeAnnotations.class .getMethod("annotationTargetType", JCTree.class, Compound.class, Symbol.class) .invoke(typeAnnotations, tree, compound, target); } catch (NoSuchMethodException e1) { return (AnnotationType) TypeAnnotations.class .getMethod("annotationTargetType", Compound.class, Symbol.class) .invoke(typeAnnotations, compound, target); } } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } } /** * Extract the filename from a {@link CompilationUnitTree}, with special handling for jar files. * The return value is normalized to always use '/' to separate elements of the path and to always * have a leading '/'. */ @Nullable public static String getFileName(CompilationUnitTree tree) { return getFileNameFromUri(tree.getSourceFile().toUri()); } private static final CharMatcher BACKSLASH_MATCHER = CharMatcher.is('\\'); /** * Extract the filename from the URI, with special handling for jar files. The return value is * normalized to always use '/' to separate elements of the path and to always have a leading '/'. */ @Nullable public static String getFileNameFromUri(URI uri) { if (!uri.getScheme().equals("jar")) { return uri.getPath(); } try { String jarEntryFileName = ((JarURLConnection) uri.toURL().openConnection()).getEntryName(); // It's possible (though it violates the zip file spec) for paths to zip file entries to use // '\' as the separator. Normalize to use '/'. jarEntryFileName = BACKSLASH_MATCHER.replaceFrom(jarEntryFileName, '/'); if (!jarEntryFileName.startsWith("/")) { jarEntryFileName = "/" + jarEntryFileName; } return jarEntryFileName; } catch (IOException e) { return null; } } /** * Given a Type ({@code base}), find the method named {@code name}, with the appropriate {@code * argTypes} and {@code tyargTypes} and return its MethodSymbol. * * <p>Ex: * * <pre>{@code * ..... * class A {} * class B { * public int hashCode() { return 42; } * } * ..... * * MethodSymbol meth = ASTHelpers.resolveExistingMethod( * state, * symbol, * state.getName("hashCode"), * ImmutableList.<Type>of(), * ImmutableList.<Type>of()); * }</pre> * * {@code meth} could be different MethodSymbol's depending on whether {@code symbol} represented * {@code B} or {@code A}. (B's hashCode method or Object#hashCode). * * @return a MethodSymbol representing the method symbol resolved from the context of this type, * or {@code null} if the method could not be resolved. */ @Nullable public static MethodSymbol resolveExistingMethod( VisitorState state, TypeSymbol base, Name name, Iterable<Type> argTypes, Iterable<Type> tyargTypes) { Resolve resolve = Resolve.instance(state.context); Enter enter = Enter.instance(state.context); Log log = Log.instance(state.context); DeferredDiagnosticHandler handler = new DeferredDiagnosticHandler(log); try { return resolve.resolveInternalMethod( /*pos*/ null, enter.getEnv(base), base.type, name, com.sun.tools.javac.util.List.from(argTypes), com.sun.tools.javac.util.List.from(tyargTypes)); } catch (FatalError e) { // the method could not be resolved return null; } finally { log.popDiagnosticHandler(handler); } } /** * Returns the value of the {@code @Generated} annotation on enclosing classes, if present. * * <p>Although {@code @Generated} can be applied to non-class program elements, there are no known * cases of that happening, so it isn't supported here. */ public static ImmutableSet<String> getGeneratedBy(VisitorState state) { return stream(state.getPath()) .filter(ClassTree.class::isInstance) .flatMap(enclosing -> getGeneratedBy(getSymbol(enclosing), state).stream()) .collect(toImmutableSet()); } /** * Returns the values of the given symbol's {@code Generated} annotations, if present. If the * annotation doesn't have {@code values} set, returns the string name of the annotation itself. */ public static ImmutableSet<String> getGeneratedBy(Symbol symbol, VisitorState state) { checkNotNull(symbol); return symbol.getRawAttributes().stream() .filter(attribute -> attribute.type.tsym.getSimpleName().contentEquals("Generated")) .flatMap(ASTHelpers::generatedValues) .collect(toImmutableSet()); } private static Stream<String> generatedValues(Attribute.Compound attribute) { return attribute.getElementValues().entrySet().stream() .filter(e -> e.getKey().getSimpleName().contentEquals("value")) .findFirst() .map(e -> MoreAnnotations.asStrings(e.getValue())) .orElseGet(() -> Stream.of(attribute.type.tsym.getQualifiedName().toString())); } public static boolean isSuper(Tree tree) { switch (tree.getKind()) { case IDENTIFIER: return ((IdentifierTree) tree).getName().contentEquals("super"); case MEMBER_SELECT: return ((MemberSelectTree) tree).getIdentifier().contentEquals("super"); default: return false; } } /** * Attempts to detect whether we're in a static-initializer-like context: that includes direct * assignments to static fields, assignments to enum fields, being contained within an expression * which is ultimately assigned to a static field. * * <p>This is very much a heuristic, and not fool-proof. */ public static boolean isInStaticInitializer(VisitorState state) { return stream(state.getPath()) .anyMatch( tree -> (tree instanceof VariableTree && variableIsStaticFinal((VarSymbol) getSymbol(tree))) || (tree instanceof AssignmentTree && getSymbol(((AssignmentTree) tree).getVariable()) instanceof VarSymbol && variableIsStaticFinal( (VarSymbol) getSymbol(((AssignmentTree) tree).getVariable())))); } /** * Whether the variable is (or should be regarded as) static final. * * <p>We regard instance fields within enums as "static final", as they will only have a finite * number of instances tied to an (effectively) static final enum value. */ public static boolean variableIsStaticFinal(VarSymbol var) { return (var.isStatic() || var.owner.isEnum()) && var.getModifiers().contains(Modifier.FINAL); } /** An expression's target type, see {@link #targetType}. */ @AutoValue public abstract static class TargetType { public abstract Type type(); public abstract TreePath path(); static TargetType create(Type type, TreePath path) { return new AutoValue_ASTHelpers_TargetType(type, path); } } /** * Implementation of unary numeric promotion rules. * * <p><a href="https://docs.oracle.com/javase/specs/jls/se9/html/jls-5.html#jls-5.6.1">JLS * §5.6.1</a> */ @Nullable private static Type unaryNumericPromotion(Type type, VisitorState state) { Type unboxed = unboxAndEnsureNumeric(type, state); switch (unboxed.getTag()) { case BYTE: case SHORT: case CHAR: return state.getSymtab().intType; case INT: case LONG: case FLOAT: case DOUBLE: return unboxed; default: throw new AssertionError("Should not reach here: " + type); } } /** * Implementation of binary numeric promotion rules. * * <p><a href="https://docs.oracle.com/javase/specs/jls/se9/html/jls-5.html#jls-5.6.2">JLS * §5.6.2</a> */ @Nullable private static Type binaryNumericPromotion(Type leftType, Type rightType, VisitorState state) { Type unboxedLeft = unboxAndEnsureNumeric(leftType, state); Type unboxedRight = unboxAndEnsureNumeric(rightType, state); Set<TypeTag> tags = EnumSet.of(unboxedLeft.getTag(), unboxedRight.getTag()); if (tags.contains(TypeTag.DOUBLE)) { return state.getSymtab().doubleType; } else if (tags.contains(TypeTag.FLOAT)) { return state.getSymtab().floatType; } else if (tags.contains(TypeTag.LONG)) { return state.getSymtab().longType; } else { return state.getSymtab().intType; } } private static Type unboxAndEnsureNumeric(Type type, VisitorState state) { Type unboxed = state.getTypes().unboxedTypeOrType(type); checkArgument(unboxed.isNumeric(), "[%s] is not numeric", type); return unboxed; } /** * Returns the target type of the tree at the given {@link VisitorState}'s path, or else {@code * null}. * * <p>For example, the target type of an assignment expression is the variable's type, and the * target type of a return statement is the enclosing method's type. */ @Nullable public static TargetType targetType(VisitorState state) { if (!canHaveTargetType(state.getPath().getLeaf())) { return null; } ExpressionTree current; TreePath parent = state.getPath(); do { current = (ExpressionTree) parent.getLeaf(); parent = parent.getParentPath(); } while (parent != null && parent.getLeaf().getKind() == Kind.PARENTHESIZED); if (parent == null) { return null; } Type type = new TargetTypeVisitor(current, state, parent).visit(parent.getLeaf(), null); if (type == null) { Tree actualTree = null; if (YIELD_TREE != null && YIELD_TREE.isAssignableFrom(parent.getLeaf().getClass())) { actualTree = parent.getParentPath().getParentPath().getParentPath().getLeaf(); } else if (CONSTANT_CASE_LABEL_TREE != null && CONSTANT_CASE_LABEL_TREE.isAssignableFrom(parent.getLeaf().getClass())) { actualTree = parent.getParentPath().getParentPath().getLeaf(); } type = getType(TargetTypeVisitor.getSwitchExpression(actualTree)); if (type == null) { return null; } } return TargetType.create(type, parent); } @Nullable private static final Class<?> CONSTANT_CASE_LABEL_TREE = constantCaseLabelTree(); @Nullable private static final Class<?> YIELD_TREE = yieldTree(); @Nullable private static Class<?> constantCaseLabelTree() { try { return Class.forName("com.sun.source.tree.ConstantCaseLabelTree"); } catch (ClassNotFoundException e) { return null; } } @Nullable private static Class<?> yieldTree() { try { return Class.forName("com.sun.source.tree.YieldTree"); } catch (ClassNotFoundException e) { return null; } } private static boolean canHaveTargetType(Tree tree) { // Anything that isn't an expression can't have a target type. if (!(tree instanceof ExpressionTree)) { return false; } switch (tree.getKind()) { case IDENTIFIER: case MEMBER_SELECT: if (!(ASTHelpers.getSymbol(tree) instanceof VarSymbol)) { // If we're selecting other than a member (e.g. a type or a method) then this doesn't // have a target type. return false; } break; case PRIMITIVE_TYPE: case ARRAY_TYPE: case PARAMETERIZED_TYPE: case EXTENDS_WILDCARD: case SUPER_WILDCARD: case UNBOUNDED_WILDCARD: case ANNOTATED_TYPE: case INTERSECTION_TYPE: case TYPE_ANNOTATION: // These are all things that only appear in type uses, so they can't have a target type. return false; case ANNOTATION: // Annotations can only appear on elements which don't have target types. return false; default: // Continue. } return true; } @VisibleForTesting static class TargetTypeVisitor extends SimpleTreeVisitor<Type, Void> { private final VisitorState state; private final TreePath parent; private final ExpressionTree current; private TargetTypeVisitor(ExpressionTree current, VisitorState state, TreePath parent) { this.current = current; this.state = state; this.parent = parent; } @Nullable @Override public Type visitArrayAccess(ArrayAccessTree node, Void unused) { if (current.equals(node.getIndex())) { return state.getSymtab().intType; } else { return getType(node.getExpression()); } } @Override public Type visitAssert(AssertTree node, Void unused) { return current.equals(node.getCondition()) ? state.getSymtab().booleanType : state.getSymtab().stringType; } @Nullable @Override public Type visitAssignment(AssignmentTree tree, Void unused) { return getType(tree.getVariable()); } @Override public Type visitAnnotation(AnnotationTree tree, Void unused) { return null; } @Nullable @Override public Type visitCase(CaseTree tree, Void unused) { Tree switchTree = parent.getParentPath().getLeaf(); return getType(getSwitchExpression(switchTree)); } @Nullable private static ExpressionTree getSwitchExpression(@Nullable Tree tree) { if (tree == null) { return null; } if (tree instanceof SwitchTree) { return ((SwitchTree) tree).getExpression(); } // Reflection is required for JDK < 12 try { Class<?> switchExpression = Class.forName("com.sun.source.tree.SwitchExpressionTree"); Class<?> clazz = tree.getClass(); if (switchExpression.isAssignableFrom(clazz)) { try { Method method = clazz.getMethod("getExpression"); return (ExpressionTree) method.invoke(tree); } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } } } catch (ClassNotFoundException e) { // continue below } return null; } @Override public Type visitClass(ClassTree node, Void unused) { return null; } @Nullable @Override public Type visitCompoundAssignment(CompoundAssignmentTree tree, Void unused) { Type variableType = getType(tree.getVariable()); Type expressionType = getType(tree.getExpression()); Types types = state.getTypes(); switch (tree.getKind()) { case LEFT_SHIFT_ASSIGNMENT: case RIGHT_SHIFT_ASSIGNMENT: case UNSIGNED_RIGHT_SHIFT_ASSIGNMENT: // Shift operators perform *unary* numeric promotion on the operands, separately. if (tree.getExpression().equals(current)) { return unaryNumericPromotion(expressionType, state); } break; case PLUS_ASSIGNMENT: Type stringType = state.getSymtab().stringType; if (types.isSuperType(variableType, stringType)) { return stringType; } break; default: // Fall though. } // If we've got to here, we can only have boolean or numeric operands // (because the only compound assignment operator for String is +=). // These operands will necessarily be unboxed (and, if numeric, undergo binary numeric // promotion), even if the resulting expression is of boxed type. As such, report the unboxed // type. return types.unboxedTypeOrType(variableType).getTag() == TypeTag.BOOLEAN ? state.getSymtab().booleanType : binaryNumericPromotion(variableType, expressionType, state); } @Override public Type visitEnhancedForLoop(EnhancedForLoopTree node, Void unused) { Type variableType = ASTHelpers.getType(node.getVariable()); if (state.getTypes().isArray(ASTHelpers.getType(node.getExpression()))) { // For iterating an array, the target type is LoopVariableType[]. return state.getType(variableType, true, ImmutableList.of()); } // For iterating an iterable, the target type is Iterable<? extends LoopVariableType>. variableType = state.getTypes().boxedTypeOrType(variableType); return state.getType( state.getSymtab().iterableType, false, ImmutableList.of(new WildcardType(variableType, BoundKind.EXTENDS, variableType.tsym))); } @Override public Type visitInstanceOf(InstanceOfTree node, Void unused) { return state.getSymtab().objectType; } @Override public Type visitLambdaExpression(LambdaExpressionTree lambdaExpressionTree, Void unused) { return state.getTypes().findDescriptorType(getType(lambdaExpressionTree)).getReturnType(); } @Override public Type visitMethod(MethodTree node, Void unused) { return null; } @Override public Type visitParenthesized(ParenthesizedTree node, Void unused) { return visit(node.getExpression(), unused); } @Nullable @Override public Type visitReturn(ReturnTree tree, Void unused) { for (TreePath path = parent; path != null; path = path.getParentPath()) { Tree enclosing = path.getLeaf(); switch (enclosing.getKind()) { case METHOD: return getType(((MethodTree) enclosing).getReturnType()); case LAMBDA_EXPRESSION: return visitLambdaExpression((LambdaExpressionTree) enclosing, null); default: // fall out } } throw new AssertionError("return not enclosed by method or lambda"); } @Nullable @Override public Type visitSynchronized(SynchronizedTree node, Void unused) { // The null occurs if you've asked for the type of the parentheses around the expression. return Objects.equals(current, node.getExpression()) ? state.getSymtab().objectType : null; } @Override public Type visitThrow(ThrowTree node, Void unused) { return ASTHelpers.getType(current); } @Override public Type visitTypeCast(TypeCastTree node, Void unused) { return getType(node.getType()); } @Nullable @Override public Type visitVariable(VariableTree tree, Void unused) { return getType(tree.getType()); } @Nullable @Override public Type visitUnary(UnaryTree tree, Void unused) { return getType(tree); } @Nullable @Override public Type visitBinary(BinaryTree tree, Void unused) { Type leftType = checkNotNull(getType(tree.getLeftOperand())); Type rightType = checkNotNull(getType(tree.getRightOperand())); switch (tree.getKind()) { // The addition and subtraction operators for numeric types + and - (§15.18.2) case PLUS: // If either operand is of string type, string concatenation is performed. Type stringType = state.getSymtab().stringType; if (isSameType(stringType, leftType, state) || isSameType(stringType, rightType, state)) { return stringType; } // Fall through. case MINUS: // The multiplicative operators *, /, and % (§15.17) case MULTIPLY: case DIVIDE: case REMAINDER: // The numerical comparison operators <, <=, >, and >= (§15.20.1) case LESS_THAN: case LESS_THAN_EQUAL: case GREATER_THAN: case GREATER_THAN_EQUAL: // The integer bitwise operators &, ^, and | case AND: case XOR: case OR: if (typeIsBoolean(state.getTypes().unboxedTypeOrType(leftType)) && typeIsBoolean(state.getTypes().unboxedTypeOrType(rightType))) { return state.getSymtab().booleanType; } return binaryNumericPromotion(leftType, rightType, state); case EQUAL_TO: case NOT_EQUAL_TO: return handleEqualityOperator(tree, leftType, rightType); case LEFT_SHIFT: case RIGHT_SHIFT: case UNSIGNED_RIGHT_SHIFT: // Shift operators perform *unary* numeric promotion on the operands, separately. return unaryNumericPromotion(getType(current), state); default: return getType(tree); } } @Nullable private Type handleEqualityOperator(BinaryTree tree, Type leftType, Type rightType) { Type unboxedLeft = checkNotNull(state.getTypes().unboxedTypeOrType(leftType)); Type unboxedRight = checkNotNull(state.getTypes().unboxedTypeOrType(rightType)); // If the operands of an equality operator are both of numeric type, or one is of numeric // type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is // performed on the operands (§5.6.2). if ((leftType.isNumeric() && rightType.isNumeric()) || (leftType.isNumeric() != rightType.isNumeric() && (unboxedLeft.isNumeric() || unboxedRight.isNumeric()))) { // https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.21.1 // Numerical equality. return binaryNumericPromotion(unboxedLeft, unboxedRight, state); } // If the operands of an equality operator are both of type boolean, or if one operand is // of type boolean and the other is of type Boolean, then the operation is boolean // equality. boolean leftIsBoolean = typeIsBoolean(leftType); boolean rightIsBoolean = typeIsBoolean(rightType); if ((leftIsBoolean && rightIsBoolean) || (leftIsBoolean != rightIsBoolean && (typeIsBoolean(unboxedLeft) || typeIsBoolean(unboxedRight)))) { return state.getSymtab().booleanType; } // If the operands of an equality operator are both of either reference type or the null // type, then the operation is object equality. return tree.getLeftOperand().equals(current) ? leftType : rightType; } private static boolean typeIsBoolean(Type type) { return type.getTag() == TypeTag.BOOLEAN; } @Nullable @Override public Type visitConditionalExpression(ConditionalExpressionTree tree, Void unused) { return tree.getCondition().equals(current) ? state.getSymtab().booleanType : getType(tree); } @Override public Type visitNewClass(NewClassTree tree, Void unused) { if (Objects.equals(current, tree.getEnclosingExpression())) { return ASTHelpers.getSymbol(tree.getIdentifier()).owner.type; } return visitMethodInvocationOrNewClass( tree.getArguments(), ASTHelpers.getSymbol(tree), ((JCNewClass) tree).constructorType); } @Override public Type visitMethodInvocation(MethodInvocationTree tree, Void unused) { return visitMethodInvocationOrNewClass( tree.getArguments(), ASTHelpers.getSymbol(tree), ((JCMethodInvocation) tree).meth.type); } @Nullable private Type visitMethodInvocationOrNewClass( List<? extends ExpressionTree> arguments, MethodSymbol sym, Type type) { int idx = arguments.indexOf(current); if (idx == -1) { return null; } if (type.getParameterTypes().size() <= idx) { if (!sym.isVarArgs()) { if ((sym.flags() & Flags.HYPOTHETICAL) != 0) { // HYPOTHETICAL is also used for signature-polymorphic methods return null; } throw new IllegalStateException( String.format( "saw %d formal parameters and %d actual parameters on non-varargs method %s\n", type.getParameterTypes().size(), arguments.size(), sym)); } idx = type.getParameterTypes().size() - 1; } Type argType = type.getParameterTypes().get(idx); if (sym.isVarArgs() && idx == type.getParameterTypes().size() - 1) { argType = state.getTypes().elemtype(argType); } return argType; } @Override public Type visitIf(IfTree tree, Void unused) { return getConditionType(tree.getCondition()); } @Override public Type visitWhileLoop(WhileLoopTree tree, Void unused) { return getConditionType(tree.getCondition()); } @Override public Type visitDoWhileLoop(DoWhileLoopTree tree, Void unused) { return getConditionType(tree.getCondition()); } @Override public Type visitForLoop(ForLoopTree tree, Void unused) { return getConditionType(tree.getCondition()); } @Nullable @Override public Type visitSwitch(SwitchTree node, Void unused) { if (current == node.getExpression()) { return state.getTypes().unboxedTypeOrType(getType(current)); } else { return null; } } @Nullable @Override public Type visitNewArray(NewArrayTree node, Void unused) { if (Objects.equals(node.getType(), current)) { return null; } if (node.getDimensions().contains(current)) { return state.getSymtab().intType; } if (node.getInitializers() != null && node.getInitializers().contains(current)) { return state.getTypes().elemtype(ASTHelpers.getType(node)); } return null; } @Nullable @Override public Type visitMemberSelect(MemberSelectTree node, Void unused) { if (current.equals(node.getExpression())) { return ASTHelpers.getType(node.getExpression()); } return null; } @Override public Type visitMemberReference(MemberReferenceTree node, Void unused) { return state.getTypes().findDescriptorType(getType(node)).getReturnType(); } @Nullable private Type getConditionType(Tree condition) { if (condition != null && condition.equals(current)) { return state.getSymtab().booleanType; } return null; } } /** * Returns declaration annotations of the given symbol, as well as 'top-level' type annotations, * including : * * <ul> * <li>Type annotations of the return type of a method. * <li>Type annotations on the type of a formal parameter or field. * </ul> * * <p>One might expect this to be equivalent to information returned by {@link * Type#getAnnotationMirrors}, but javac doesn't associate type annotation information with types * for symbols completed from class files, so that approach doesn't work across compilation * boundaries. */ public static Stream<Attribute.Compound> getDeclarationAndTypeAttributes(Symbol sym) { return MoreAnnotations.getDeclarationAndTypeAttributes(sym); } /** * Return a mirror of this annotation. * * @return an {@code AnnotationMirror} for the annotation represented by {@code annotationTree}. */ public static AnnotationMirror getAnnotationMirror(AnnotationTree annotationTree) { return ((JCAnnotation) annotationTree).attribute; } /** Returns whether the given {@code tree} contains any comments in its source. */ public static boolean containsComments(Tree tree, VisitorState state) { return state.getOffsetTokensForNode(tree).stream().anyMatch(t -> !t.comments().isEmpty()); } /** * Returns the outermost enclosing owning class, or {@code null}. Doesn't crash on symbols that * aren't containing in a package, unlike {@link Symbol#outermostClass} (see b/123431414). */ // TODO(b/123431414): fix javac and use Symbol.outermostClass insteads @Nullable public static ClassSymbol outermostClass(Symbol symbol) { ClassSymbol curr = symbol.enclClass(); while (curr != null && curr.owner != null) { ClassSymbol encl = curr.owner.enclClass(); if (encl == null) { break; } curr = encl; } return curr; } /** Returns whether {@code symbol} is final or effectively final. */ public static boolean isConsideredFinal(Symbol symbol) { return (symbol.flags() & (Flags.FINAL | Flags.EFFECTIVELY_FINAL)) != 0; } /** Returns the exceptions thrown by {@code tree}. */ public static ImmutableSet<Type> getThrownExceptions(Tree tree, VisitorState state) { ScanThrownTypes scanner = new ScanThrownTypes(state); scanner.scan(tree, null); return ImmutableSet.copyOf(scanner.getThrownTypes()); } /** Scanner for determining what types are thrown by a tree. */ public static final class ScanThrownTypes extends TreeScanner<Void, Void> { ArrayDeque<Set<Type>> thrownTypes = new ArrayDeque<>(); SetMultimap<VarSymbol, Type> thrownTypesByVariable = HashMultimap.create(); private final VisitorState state; private final Types types; public ScanThrownTypes(VisitorState state) { this.state = state; this.types = state.getTypes(); thrownTypes.push(new HashSet<>()); } public Set<Type> getThrownTypes() { return thrownTypes.peek(); } @Override public Void visitMethodInvocation(MethodInvocationTree invocation, Void unused) { Type type = getType(invocation.getMethodSelect()); if (type != null) { getThrownTypes().addAll(type.getThrownTypes()); } return super.visitMethodInvocation(invocation, null); } @Override public Void visitTry(TryTree tree, Void unused) { thrownTypes.push(new HashSet<>()); scanResources(tree); scan(tree.getBlock(), null); // Make two passes over the `catch` blocks: once to remove caught exceptions, and once to // add thrown ones. We can't do this in one step as an exception could be caught but later // thrown. for (CatchTree catchTree : tree.getCatches()) { Type type = getType(catchTree.getParameter()); Set<Type> caughtTypes = new HashSet<>(); Set<Type> capturedTypes = new HashSet<>(); for (Type unionMember : extractTypes(type)) { for (Type thrownType : getThrownTypes()) { // If the thrown type is a subtype of the caught type, we caught it, and it doesn't flow // through to any subsequent catches. if (types.isSubtype(thrownType, unionMember)) { caughtTypes.add(thrownType); capturedTypes.add(thrownType); } // If our caught type is a subtype of a thrown type, we caught something, but didn't // remove it from the list of things the try {} block throws. if (types.isSubtype(unionMember, thrownType)) { capturedTypes.add(unionMember); } } } getThrownTypes().removeAll(caughtTypes); thrownTypesByVariable.putAll(getSymbol(catchTree.getParameter()), capturedTypes); } for (CatchTree catchTree : tree.getCatches()) { scan(catchTree.getBlock(), null); } scan(tree.getFinallyBlock(), null); Set<Type> fromBlock = thrownTypes.pop(); getThrownTypes().addAll(fromBlock); return null; } public void scanResources(TryTree tree) { for (Tree resource : tree.getResources()) { Symbol symbol = getType(resource).tsym; if (symbol instanceof ClassSymbol) { getCloseMethod((ClassSymbol) symbol, state) .ifPresent(methodSymbol -> getThrownTypes().addAll(methodSymbol.getThrownTypes())); } } scan(tree.getResources(), null); } @Override public Void visitThrow(ThrowTree tree, Void unused) { if (tree.getExpression() instanceof IdentifierTree) { Symbol symbol = getSymbol(tree.getExpression()); if (thrownTypesByVariable.containsKey(symbol)) { getThrownTypes().addAll(thrownTypesByVariable.get((VarSymbol) symbol)); return super.visitThrow(tree, null); } } getThrownTypes().addAll(extractTypes(getType(tree.getExpression()))); return super.visitThrow(tree, null); } @Override public Void visitNewClass(NewClassTree tree, Void unused) { getThrownTypes().addAll(getSymbol(tree).getThrownTypes()); return super.visitNewClass(tree, null); } @Override public Void visitVariable(VariableTree tree, Void unused) { return super.visitVariable(tree, null); } // We don't need to account for anything thrown by declarations. @Override public Void visitLambdaExpression(LambdaExpressionTree tree, Void unused) { return null; } @Override public Void visitClass(ClassTree tree, Void unused) { return null; } @Override public Void visitMethod(MethodTree tree, Void unused) { return null; } private static final Supplier<Type> AUTOCLOSEABLE = Suppliers.typeFromString("java.lang.AutoCloseable"); private static final Supplier<Name> CLOSE = VisitorState.memoize(state -> state.getName("close")); private static Optional<MethodSymbol> getCloseMethod(ClassSymbol symbol, VisitorState state) { Types types = state.getTypes(); if (!types.isAssignable(symbol.type, AUTOCLOSEABLE.get(state))) { return Optional.empty(); } Type voidType = state.getSymtab().voidType; Optional<MethodSymbol> declaredCloseMethod = ASTHelpers.matchingMethods( CLOSE.get(state), s -> !s.isConstructor() && s.params.isEmpty() && types.isSameType(s.getReturnType(), voidType), symbol.type, types) .findFirst(); verify( declaredCloseMethod.isPresent(), "%s implements AutoCloseable but no method named close() exists, even inherited", symbol); return declaredCloseMethod; } private static ImmutableList<Type> extractTypes(@Nullable Type type) { if (type == null) { return ImmutableList.of(); } if (type.isUnion()) { UnionClassType unionType = (UnionClassType) type; return ImmutableList.copyOf(unionType.getAlternativeTypes()); } return ImmutableList.of(type); } } /** Returns the start position of the node. */ public static int getStartPosition(Tree tree) { return ((JCTree) tree).getStartPosition(); } /** Returns a no arg private constructor for the {@link ClassTree}. */ public static String createPrivateConstructor(ClassTree classTree) { return "private " + classTree.getSimpleName() + "() {}"; } private static final Matcher<Tree> IS_BUGCHECKER = isSubtypeOf("com.google.errorprone.bugpatterns.BugChecker"); /** Returns {@code true} if the code is in a BugChecker class. */ public static boolean isBugCheckerCode(VisitorState state) { for (Tree ancestor : state.getPath()) { if (IS_BUGCHECKER.matches(ancestor, state)) { return true; } } return false; } private static final Method IS_LOCAL = getIsLocal(); private static Method getIsLocal() { try { return Symbol.class.getMethod("isLocal"); } catch (NoSuchMethodException e) { // continue below } try { return Symbol.class.getMethod("isDirectlyOrIndirectlyLocal"); } catch (NoSuchMethodException e) { throw new LinkageError(e.getMessage(), e); } } /** * Returns true if the symbol is directly or indirectly local to a method or variable initializer; * see {@code Symbol#isLocal} or {@code Symbol#isDirectlyOrIndirectlyLocal}. */ public static boolean isLocal(Symbol symbol) { try { return (boolean) IS_LOCAL.invoke(symbol); } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } } /** Returns true if the symbol is static. Returns {@code false} for module symbols. */ @SuppressWarnings("ASTHelpersSuggestions") public static boolean isStatic(Symbol symbol) { switch (symbol.getKind()) { case MODULE: return false; default: return symbol.isStatic(); } } /** * Returns true if the given method symbol is public (both the method and the enclosing class) and * does <i>not</i> have a super-method (i.e., it is not an {@code @Override}). * * <p>This method is useful (in part) for determining whether to suggest API improvements or not. */ public static boolean methodIsPublicAndNotAnOverride(MethodSymbol method, VisitorState state) { // don't match non-public APIs Symbol symbol = method; while (symbol != null && !(symbol instanceof PackageSymbol)) { if (!symbol.getModifiers().contains(Modifier.PUBLIC)) { return false; } symbol = symbol.owner; } // don't match overrides (even "effective overrides") if (!findSuperMethods(method, state.getTypes()).isEmpty()) { return false; } return true; } /** * Returns true if the given method symbol is abstract. * * <p><b>Note:</b> this API does not consider interface {@code default} methods to be abstract. */ public static boolean isAbstract(MethodSymbol method) { return method.getModifiers().contains(Modifier.ABSTRACT); } /** Returns a compatibility adapter around {@link Scope}. */ public static ErrorProneScope scope(Scope scope) { return new ErrorProneScope(scope); } public static EnumSet<Flags.Flag> asFlagSet(long flags) { flags &= ~(Flags.ANONCONSTR_BASED | POTENTIALLY_AMBIGUOUS); return Flags.asFlagSet(flags); } // Removed in JDK 21 by JDK-8026369 public static final long POTENTIALLY_AMBIGUOUS = 1L << 48; /** Returns true if the given source code contains comments. */ public static boolean stringContainsComments(CharSequence source, Context context) { JavaTokenizer tokenizer = new JavaTokenizer(ScannerFactory.instance(context), CharBuffer.wrap(source)) {}; for (Token token = tokenizer.readToken(); token.kind != TokenKind.EOF; token = tokenizer.readToken()) { if (token.comments != null && !token.comments.isEmpty()) { return true; } } return false; } /** * Returns the mapping between type variables and their instantiations in the given type. For * example, the instantiation of {@code Map<K, V>} as {@code Map<String, Integer>} would be * represented as a {@code TypeSubstitution} from {@code [K, V]} to {@code [String, Integer]}. */ public static ImmutableListMultimap<Symbol.TypeVariableSymbol, Type> getTypeSubstitution( Type type, Symbol sym) { ImmutableListMultimap.Builder<Symbol.TypeVariableSymbol, Type> result = ImmutableListMultimap.builder(); class Visitor extends Types.DefaultTypeVisitor<Void, Type> { @Override public Void visitMethodType(Type.MethodType t, Type other) { scan(t.getParameterTypes(), other.getParameterTypes()); scan(t.getThrownTypes(), other.getThrownTypes()); scan(t.getReturnType(), other.getReturnType()); return null; } @Override public Void visitClassType(ClassType t, Type other) { scan(t.getTypeArguments(), other.getTypeArguments()); return null; } @Override public Void visitTypeVar(TypeVar t, Type other) { result.put((Symbol.TypeVariableSymbol) t.asElement(), other); return null; } @Override public Void visitForAll(Type.ForAll t, Type other) { scan(t.getParameterTypes(), other.getParameterTypes()); scan(t.getThrownTypes(), other.getThrownTypes()); scan(t.getReturnType(), other.getReturnType()); return null; } @Override public Void visitWildcardType(WildcardType t, Type type) { if (type instanceof WildcardType) { WildcardType other = (WildcardType) type; scan(t.getExtendsBound(), other.getExtendsBound()); scan(t.getSuperBound(), other.getSuperBound()); } return null; } @Override public Void visitType(Type t, Type other) { return null; } private void scan(Collection<Type> from, Collection<Type> to) { Streams.forEachPair(from.stream(), to.stream(), this::scan); } private void scan(Type from, Type to) { if (from != null) { from.accept(this, to); } } } sym.asType().accept(new Visitor(), type); return result.build(); } /** Returns {@code true} if this is a `var` or a lambda parameter that has no explicit type. */ public static boolean hasNoExplicitType(VariableTree tree, VisitorState state) { /* * We detect the absence of an explicit type by looking for an absent start position for the * type tree. * * Note that the .isImplicitlyTyped() method on JCVariableDecl returns the wrong answer after * type attribution has occurred. */ return getStartPosition(tree.getType()) == -1; } /** Returns {@code true} if this symbol was declared in Kotlin source. */ public static boolean isKotlin(Symbol symbol, VisitorState state) { return hasAnnotation(symbol.enclClass(), "kotlin.Metadata", state); } /** * Returns whether {@code existingMethod} has an overload (or "nearly" an overload) with the given * {@code targetMethodName}, and only a single parameter of type {@code onlyParameterType}. */ public static boolean hasOverloadWithOnlyOneParameter( MethodSymbol existingMethod, Name targetMethodName, Type onlyParameterType, VisitorState state) { @Nullable MethodTree t = state.findEnclosing(MethodTree.class); @Nullable MethodSymbol enclosingMethod = t == null ? null : getSymbol(t); return hasMatchingMethods( targetMethodName, input -> !input.equals(existingMethod) // Make sure we're not currently *inside* that overload, to avoid // creating an infinite loop. && !input.equals(enclosingMethod) && (enclosingMethod == null || !enclosingMethod.overrides( input, (TypeSymbol) input.owner, state.getTypes(), true)) && input.isStatic() == existingMethod.isStatic() && input.getParameters().size() == 1 && isSameType(input.getParameters().get(0).asType(), onlyParameterType, state) && isSameType(input.getReturnType(), existingMethod.getReturnType(), state), enclosingClass(existingMethod).asType(), state.getTypes()); } // Adapted from findMatchingMethods(); but this short-circuits private static boolean hasMatchingMethods( Name name, Predicate<MethodSymbol> predicate, Type startClass, Types types) { Predicate<Symbol> matchesMethodPredicate = sym -> sym instanceof MethodSymbol && predicate.test((MethodSymbol) sym); // Iterate over all classes and interfaces that startClass inherits from. for (Type superClass : types.closure(startClass)) { // Iterate over all the methods declared in superClass. TypeSymbol superClassSymbol = superClass.tsym; Scope superClassSymbols = superClassSymbol.members(); if (superClassSymbols != null) { // Can be null if superClass is a type variable if (!Iterables.isEmpty( scope(superClassSymbols) .getSymbolsByName(name, matchesMethodPredicate, NON_RECURSIVE))) { return true; } } } return false; } private ASTHelpers() {} }
100,388
35.934879
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/util/OffsetComment.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.util; import com.sun.tools.javac.parser.Tokens.Comment; /** Wraps a {@link Comment} to allow an offset source position to be reported. */ final class OffsetComment implements Comment { private final Comment wrapped; private final int offset; OffsetComment(Comment wrapped, int offset) { this.wrapped = wrapped; this.offset = offset; } @Override public String getText() { return wrapped.getText(); } @Override public int getSourcePos(int i) { return wrapped.getSourcePos(i) + offset; } @Override public CommentStyle getStyle() { return wrapped.getStyle(); } @Override public boolean isDeprecated() { return false; } }
1,320
24.403846
81
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/util/Reachability.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.util; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.collect.Iterables.getLast; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static java.util.Objects.requireNonNull; import com.sun.source.tree.AssertTree; import com.sun.source.tree.BlockTree; import com.sun.source.tree.BreakTree; import com.sun.source.tree.CaseTree; import com.sun.source.tree.CatchTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.ContinueTree; import com.sun.source.tree.DoWhileLoopTree; import com.sun.source.tree.EmptyStatementTree; import com.sun.source.tree.EnhancedForLoopTree; import com.sun.source.tree.ExpressionStatementTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.ForLoopTree; import com.sun.source.tree.IfTree; import com.sun.source.tree.LabeledStatementTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.ReturnTree; import com.sun.source.tree.StatementTree; import com.sun.source.tree.SwitchTree; import com.sun.source.tree.SynchronizedTree; import com.sun.source.tree.ThrowTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TryTree; import com.sun.source.tree.VariableTree; import com.sun.source.tree.WhileLoopTree; import com.sun.source.util.SimpleTreeVisitor; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.tree.JCTree; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; /** An implementation of JLS 14.21 reachability. */ public class Reachability { /** * Returns true if the given statement can complete normally, as defined by JLS 14.21. * * <p>An exception is made for {@code System.exit}, which cannot complete normally in practice. */ public static boolean canCompleteNormally(StatementTree statement) { return statement.accept(new CanCompleteNormallyVisitor(), null); } /** * Returns true if the given case tree can complete normally, as defined by JLS 14.21. * * <p>An exception is made for {@code System.exit}, which cannot complete normally in practice. */ public static boolean canCompleteNormally(CaseTree caseTree) { List<? extends StatementTree> statements = caseTree.getStatements(); if (statements.isEmpty()) { return true; } // We only care whether the last statement completes; javac would have already // reported an error if that statement wasn't reachable, and the answer is // independent of any preceding statements. // TODO(cushon): This isn't really making an exception for System.exit in the prior statements. return canCompleteNormally(getLast(statements)); } private static class CanCompleteNormallyVisitor extends SimpleTreeVisitor<Boolean, Void> { /** Trees that are the target of a reachable break statement. */ private final Set<Tree> breaks = new HashSet<>(); /** Trees that are the target of a reachable continue statement. */ private final Set<Tree> continues = new HashSet<>(); boolean scan(List<? extends StatementTree> trees) { boolean completes = true; for (StatementTree tree : trees) { completes = scan(tree); } return completes; } private boolean scan(Tree tree) { return tree.accept(this, null); } /* A break statement cannot complete normally. */ @Override public Boolean visitBreak(BreakTree tree, Void unused) { breaks.add(skipLabel(requireNonNull(((JCTree.JCBreak) tree).target))); return false; } /* A continue statement cannot complete normally. */ @Override public Boolean visitContinue(ContinueTree tree, Void unused) { continues.add(skipLabel(requireNonNull(((JCTree.JCContinue) tree).target))); return false; } private static Tree skipLabel(JCTree tree) { return tree.hasTag(JCTree.Tag.LABELLED) ? ((JCTree.JCLabeledStatement) tree).body : tree; } @Override public Boolean visitBlock(BlockTree tree, Void unused) { return scan(tree.getStatements()); } /* A local class declaration statement can complete normally iff it is reachable. */ @Override public Boolean visitClass(ClassTree tree, Void unused) { return true; } /* A local variable declaration statement can complete normally iff it is reachable. */ @Override public Boolean visitVariable(VariableTree tree, Void unused) { return true; } /* An empty statement can complete normally iff it is reachable. */ @Override public Boolean visitEmptyStatement(EmptyStatementTree tree, Void unused) { return true; } @Override public Boolean visitLabeledStatement(LabeledStatementTree tree, Void unused) { // break/continue targets have already been resolved by javac, so // there's nothing to do here return scan(tree.getStatement()); } /* An expression statement can complete normally iff it is reachable. */ @Override public Boolean visitExpressionStatement(ExpressionStatementTree tree, Void unused) { if (isSystemExit(tree.getExpression())) { // The spec doesn't have any special handling for {@code System.exit}, but in practice it // cannot complete normally return false; } return true; } private static boolean isSystemExit(ExpressionTree expression) { if (!(expression instanceof MethodInvocationTree)) { return false; } MethodSymbol sym = getSymbol((MethodInvocationTree) expression); return sym.owner.getQualifiedName().contentEquals("java.lang.System") && sym.getSimpleName().contentEquals("exit"); } /* * An if-then statement can complete normally iff it is reachable. * * The then-statement is reachable iff the if-then statement is reachable. * An if-then-else statement can complete normally iff the then-statement * can complete normally or the else-statement can complete normally. * * The then-statement is reachable iff the if-then-else statement is * reachable. * * The else-statement is reachable iff the if-then-else statement is * reachable. */ @Override public Boolean visitIf(IfTree tree, Void unused) { boolean thenCompletes = scan(tree.getThenStatement()); boolean elseCompletes = tree.getElseStatement() == null || scan(tree.getElseStatement()); return thenCompletes || elseCompletes; } /* An assert statement can complete normally iff it is reachable. */ @Override public Boolean visitAssert(AssertTree tree, Void unused) { return true; } /* * A switch statement can complete normally iff at least one of the * following is true: * * 1) The switch block is empty or contains only switch labels. * 2) The last statement in the switch block can complete normally. * 3) There is at least one switch label after the last switch block * statement group. * 4) The switch block does not contain a default label. * 5) There is a reachable break statement that exits the switch statement. * * A switch block is reachable iff its switch statement is reachable. * * A statement in a switch block is reachable iff its switch statement is * reachable and at least one of the following is true: * * - It bears a case or default label. * * - There is a statement preceding it in the switch block and that * preceding statement can complete normally. */ @Override public Boolean visitSwitch(SwitchTree tree, Void unused) { // (1) if (tree.getCases().stream().allMatch(c -> c.getStatements().isEmpty())) { return true; } // (2) boolean lastCompletes = true; for (CaseTree c : tree.getCases()) { lastCompletes = scan(c.getStatements()); } if (lastCompletes) { return true; } // (3) if (getLast(tree.getCases()).getStatements().isEmpty()) { return true; } // (4) if (tree.getCases().stream().noneMatch(c -> c.getExpression() == null)) { return true; } // (5) if (breaks.contains(tree)) { return true; } return false; } /* * A while statement can complete normally iff at least one of the * following is true: * * 1) The while statement is reachable and the condition expression is not * a constant expression (§15.28) with value true. * 2) There is a reachable break statement that exits the while statement. * * The contained statement is reachable iff the while statement is * reachable and the condition expression is not a constant expression * whose value is false. */ @Override public Boolean visitWhileLoop(WhileLoopTree tree, Void unused) { Boolean condValue = ASTHelpers.constValue(tree.getCondition(), Boolean.class); if (!Objects.equals(condValue, false)) { scan(tree.getStatement()); } // (1) if (!Objects.equals(condValue, true)) { return true; } // (2) if (breaks.contains(tree)) { return true; } return false; } /* * A do statement can complete normally iff at least one of the following * is true: * * 1) The contained statement can complete normally and the condition * expression is not a constant expression (§15.28) with value true. * * 2) The do statement contains a reachable continue statement with no * label, and the do statement is the innermost while, do, or for * statement that contains that continue statement, and the continue * statement continues that do statement, and the condition expression * is not a constant expression with value true. * * 3) The do statement contains a reachable continue statement with a * label L, and the do statement has label L, and the continue * statement continues that do statement, and the condition expression * is not a constant expression with value true. * * 4) There is a reachable break statement that exits the do statement. * * The contained statement is reachable iff the do statement is reachable. */ @Override public Boolean visitDoWhileLoop(DoWhileLoopTree that, Void unused) { boolean completes = scan(that.getStatement()); boolean conditionIsAlwaysTrue = firstNonNull(ASTHelpers.constValue(that.getCondition(), Boolean.class), false); // (1) if (completes && !conditionIsAlwaysTrue) { return true; } // (2) or (3) if (continues.contains(that) && !conditionIsAlwaysTrue) { return true; } // (4) if (breaks.contains(that)) { return true; } return false; } /* * A basic for statement can complete normally iff at least one of the * following is true: * * 1) The for statement is reachable, there is a condition expression, and * the condition expression is not a constant expression (§15.28) with * value true. * * 2) There is a reachable break statement that exits the for statement. * * The contained statement is reachable iff the for statement is reachable * and the condition expression is not a constant expression whose value is * false. */ @Override public Boolean visitForLoop(ForLoopTree that, Void unused) { Boolean condValue = ASTHelpers.constValue(that.getCondition(), Boolean.class); if (!Objects.equals(condValue, false)) { scan(that.getStatement()); } // (1) if (that.getCondition() != null && !Objects.equals(condValue, true)) { return true; } // (2) if (breaks.contains(that)) { return true; } return false; } /* An enhanced for statement can complete normally iff it is reachable. */ @Override public Boolean visitEnhancedForLoop(EnhancedForLoopTree that, Void unused) { scan(that.getStatement()); return true; } /* A return statement cannot complete normally. */ @Override public Boolean visitReturn(ReturnTree tree, Void unused) { return false; } /* A throw statement cannot complete normally. */ @Override public Boolean visitThrow(ThrowTree tree, Void unused) { return false; } /* * A synchronized statement can complete normally iff the contained * statement can complete normally. * * The contained statement is reachable iff the synchronized statement * is reachable. */ @Override public Boolean visitSynchronized(SynchronizedTree tree, Void unused) { return scan(tree.getBlock()); } /* * A try statement can complete normally iff both of the following are true: * * 1) The try block can complete normally or any catch block can complete * normally. * * 2) If the try statement has a finally block, then the finally block can * complete normally. */ @Override public Boolean visitTry(TryTree that, Void unused) { boolean completes = scan(that.getBlock()); // assume all catch blocks are reachable; javac has already rejected unreachable // checked exception handlers for (CatchTree catchTree : that.getCatches()) { completes |= scan(catchTree.getBlock()); } if (that.getFinallyBlock() != null && !scan(that.getFinallyBlock())) { completes = false; } return completes; } } }
14,399
34.380835
99
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/util/MoreAnnotations.java
/* * Copyright 2012 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.util; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toList; import com.google.common.base.MoreObjects; import com.google.common.collect.Streams; import com.sun.tools.javac.code.Attribute; import com.sun.tools.javac.code.Attribute.Compound; import com.sun.tools.javac.code.Attribute.TypeCompound; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.TargetType; import com.sun.tools.javac.code.TypeAnnotationPosition; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; import java.util.stream.Stream; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.SimpleAnnotationValueVisitor8; /** Annotation-related utilities. */ public final class MoreAnnotations { /** * Returns declaration annotations of the given symbol, as well as 'top-level' type annotations, * including : * * <ul> * <li>Type annotations of the return type of a method. * <li>Type annotations on the type of a formal parameter or field. * </ul> * * <p>One might expect this to be equivalent to information returned by {@link * com.sun.tools.javac.code.Type#getAnnotationMirrors}, but javac doesn't associate type * annotation information with types for symbols completed from class files, so that approach * doesn't work across compilation boundaries. */ public static Stream<Compound> getDeclarationAndTypeAttributes(Symbol sym) { return Streams.concat(sym.getRawAttributes().stream(), getTopLevelTypeAttributes(sym)) .collect( groupingBy(c -> c.type.asElement().getQualifiedName(), LinkedHashMap::new, toList())) .values() .stream() .map(c -> c.get(0)); } /** * Returns "top-level" type annotations of the given symbol, including: * * <ul> * <li>Type annotations of the return type of a method. * <li>Type annotations on the type of a formal parameter or field. * </ul> * * <p>These annotations are not always included in those returned by {@link * com.sun.tools.javac.code.Type#getAnnotationMirrors} because javac doesn't associate type * annotation information with types for symbols completed from class files. These type * annotations won't be included when the symbol is not in the current compilation. */ public static Stream<TypeCompound> getTopLevelTypeAttributes(Symbol sym) { Symbol typeAnnotationOwner; switch (sym.getKind()) { case PARAMETER: typeAnnotationOwner = sym.owner; break; default: typeAnnotationOwner = sym; } return typeAnnotationOwner.getRawTypeAttributes().stream() .filter(anno -> isAnnotationOnType(sym, anno.position)); } private static boolean isAnnotationOnType(Symbol sym, TypeAnnotationPosition position) { if (!position.location.isEmpty()) { return false; } switch (sym.getKind()) { case LOCAL_VARIABLE: return position.type == TargetType.LOCAL_VARIABLE; case FIELD: return position.type == TargetType.FIELD; case CONSTRUCTOR: case METHOD: return position.type == TargetType.METHOD_RETURN; case PARAMETER: switch (position.type) { case METHOD_FORMAL_PARAMETER: return ((MethodSymbol) sym.owner).getParameters().indexOf(sym) == position.parameter_index; default: return false; } case CLASS: // There are no type annotations on the top-level type of the class being declared, only // on other types in the signature (e.g. `class Foo extends Bar<@A Baz> {}`). return false; default: throw new AssertionError( "unsupported element kind in MoreAnnotation#isAnnotationOnType: " + sym.getKind()); } } /** * Returns the value of the annotation element-value pair with the given name if it is explicitly * set. */ public static Optional<Attribute> getValue(Attribute.Compound attribute, String name) { return attribute.getElementValues().entrySet().stream() .filter(e -> e.getKey().getSimpleName().contentEquals(name)) .map(Map.Entry::getValue) .findFirst(); } /** * Returns the value of the annotation element-value pair with the given name if it is explicitly * set. */ public static Optional<AnnotationValue> getAnnotationValue( Attribute.Compound attribute, String name) { return getValue(attribute, name).map(a -> a); } /** Converts the given attribute to an integer value. */ public static Optional<Integer> asIntegerValue(AnnotationValue a) { class Visitor extends SimpleAnnotationValueVisitor8<Integer, Void> { @Override public Integer visitInt(int i, Void unused) { return i; } } return Optional.ofNullable(a.accept(new Visitor(), null)); } /** Converts the given attribute to an string value. */ public static Optional<String> asStringValue(AnnotationValue a) { class Visitor extends SimpleAnnotationValueVisitor8<String, Void> { @Override public String visitString(String s, Void unused) { return s; } } return Optional.ofNullable(a.accept(new Visitor(), null)); } /** Converts the given attribute to an enum value. */ public static <T extends Enum<T>> Optional<T> asEnumValue(Class<T> clazz, AnnotationValue a) { class Visitor extends SimpleAnnotationValueVisitor8<T, Void> { @Override public T visitEnumConstant(VariableElement c, Void unused) { return Enum.valueOf(clazz, c.getSimpleName().toString()); } } return Optional.ofNullable(a.accept(new Visitor(), null)); } /** Converts the given attribute to an enum value. */ public static Optional<TypeMirror> asTypeValue(AnnotationValue a) { class Visitor extends SimpleAnnotationValueVisitor8<TypeMirror, Void> { @Override public TypeMirror visitType(TypeMirror t, Void unused) { return t; } } return Optional.ofNullable(a.accept(new Visitor(), null)); } /** Converts the given annotation value to one or more strings. */ public static Stream<String> asStrings(AnnotationValue v) { return MoreObjects.firstNonNull( v.accept( new SimpleAnnotationValueVisitor8<Stream<String>, Void>() { @Override public Stream<String> visitString(String s, Void unused) { return Stream.of(s); } @Override public Stream<String> visitArray(List<? extends AnnotationValue> list, Void unused) { return list.stream().flatMap(a -> a.accept(this, null)).filter(x -> x != null); } }, null), Stream.empty()); } /** Converts the given annotation value to one or more annotations. */ public static Stream<TypeMirror> asTypes(AnnotationValue v) { return asArray(v, MoreAnnotations::asTypeValue); } private static <T> Stream<T> asArray( AnnotationValue v, Function<AnnotationValue, Optional<T>> mapper) { class Visitor extends SimpleAnnotationValueVisitor8<Stream<T>, Void> { @Override public Stream<T> visitArray(List<? extends AnnotationValue> vals, Void unused) { return vals.stream().map(mapper).flatMap(Streams::stream); } } return MoreObjects.firstNonNull(v.accept(new Visitor(), null), Stream.of()); } private MoreAnnotations() {} }
8,348
35.458515
99
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/util/ErrorProneToken.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.util; import static java.util.stream.Collectors.toList; import com.google.common.collect.Lists; import com.sun.tools.javac.parser.Tokens.Comment; import com.sun.tools.javac.parser.Tokens.Token; import com.sun.tools.javac.parser.Tokens.TokenKind; import com.sun.tools.javac.util.Name; import java.util.Collections; import java.util.List; /** Wraps a javac {@link Token} to return comments in declaration order. */ public class ErrorProneToken { private final int offset; private final Token token; ErrorProneToken(Token token, int offset) { this.token = token; this.offset = offset; } public TokenKind kind() { return token.kind; } public int pos() { return offset + token.pos; } public int endPos() { return offset + token.endPos; } public List<Comment> comments() { // javac stores the comments in reverse declaration order because appending to linked // lists is expensive if (token.comments == null) { return Collections.emptyList(); } if (offset == 0) { return Lists.reverse(token.comments); } return Lists.reverse( token.comments.stream().map(c -> new OffsetComment(c, offset)).collect(toList())); } public boolean hasName() { // the subclasses of Token jealously guard their secrets; // inspect class names to figure out which hazzers are supported by a given token return token.getClass().getSimpleName().contentEquals("NamedToken"); } public boolean hasStringVal() { String name = token.getClass().getSimpleName(); return name.contentEquals("StringToken") || name.contentEquals("NumericToken"); } public boolean hasRadix() { return token.getClass().getSimpleName().contentEquals("NumericToken"); } public Name name() { return token.name(); } public String stringVal() { return token.stringVal(); } public int radix() { return token.radix(); } @Override public String toString() { return token.toString(); } }
2,633
26.4375
90
java