repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnConstructorOfAbstractClass.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.inject;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.fixes.SuggestedFix.delete;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.InjectMatchers.GUICE_INJECT_ANNOTATION;
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.hasModifier;
import static com.google.errorprone.matchers.Matchers.isType;
import static com.google.errorprone.matchers.Matchers.methodIsConstructor;
import static javax.lang.model.element.Modifier.ABSTRACT;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.InjectMatchers;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.MultiMatcher;
import com.google.errorprone.matchers.MultiMatcher.MultiMatchResult;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.MethodTree;
/**
* @author glorioso@google.com (Nick Glorioso)
*/
@BugPattern(
summary =
"Constructors on abstract classes are never directly @Inject'ed, only the constructors"
+ " of their subclasses can be @Inject'ed.",
severity = WARNING)
public class InjectOnConstructorOfAbstractClass extends BugChecker implements MethodTreeMatcher {
private static final MultiMatcher<MethodTree, AnnotationTree> INJECT_FINDER =
annotations(
AT_LEAST_ONE,
anyOf(isType(InjectMatchers.JAVAX_INJECT_ANNOTATION), isType(GUICE_INJECT_ANNOTATION)));
private static final Matcher<MethodTree> TO_MATCH =
allOf(methodIsConstructor(), enclosingClass(hasModifier(ABSTRACT)));
@Override
public Description matchMethod(MethodTree methodTree, VisitorState state) {
if (TO_MATCH.matches(methodTree, state)) {
MultiMatchResult<AnnotationTree> injectAnnotations =
INJECT_FINDER.multiMatchResult(methodTree, state);
if (injectAnnotations.matches()) {
AnnotationTree injectAnnotation = injectAnnotations.matchingNodes().get(0);
return describeMatch(injectAnnotation, delete(injectAnnotation));
}
}
return Description.NO_MATCH;
}
}
| 3,271
| 42.626667
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/MoreThanOneScopeAnnotationOnClass.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.bugpatterns.inject;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.InjectMatchers.IS_DAGGER_COMPONENT;
import static com.google.errorprone.matchers.InjectMatchers.IS_SCOPING_ANNOTATION;
import static com.google.errorprone.matchers.Matchers.annotations;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.MultiMatcher;
import com.google.errorprone.matchers.MultiMatcher.MultiMatchResult;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.Tree;
import java.util.List;
/**
* This checker matches if a class has more than one annotation that is a scope annotation(that is,
* the annotation is either annotated with Guice's {@code @ScopeAnnotation} or Javax's
* {@code @Scope}).
*
* @author sgoldfeder@google.com (Steven Goldfeder)
*/
@BugPattern(
name = "InjectMoreThanOneScopeAnnotationOnClass",
altNames = "MoreThanOneScopeAnnotationOnClass",
summary = "A class can be annotated with at most one scope annotation.",
severity = ERROR)
public class MoreThanOneScopeAnnotationOnClass extends BugChecker implements ClassTreeMatcher {
private static final MultiMatcher<Tree, AnnotationTree> SCOPE_ANNOTATION_MATCHER =
annotations(AT_LEAST_ONE, IS_SCOPING_ANNOTATION);
@Override
public final Description matchClass(ClassTree classTree, VisitorState state) {
MultiMatchResult<AnnotationTree> scopeAnnotationResult =
SCOPE_ANNOTATION_MATCHER.multiMatchResult(classTree, state);
if (scopeAnnotationResult.matches() && !IS_DAGGER_COMPONENT.matches(classTree, state)) {
ImmutableList<AnnotationTree> scopeAnnotations = scopeAnnotationResult.matchingNodes();
if (scopeAnnotations.size() > 1) {
return buildDescription(classTree)
.setMessage(
"This class is annotated with more than one scope annotation: "
+ annotationDebugString(scopeAnnotations)
+ ". However, classes can only have one scope annotation applied to them. "
+ "Please remove all but one of them.")
.build();
}
}
return Description.NO_MATCH;
}
private static String annotationDebugString(List<AnnotationTree> scopeAnnotations) {
return Joiner.on(", ").join(scopeAnnotations);
}
}
| 3,412
| 42.202532
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/JavaxInjectOnFinalField.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.bugpatterns.inject;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.bugpatterns.inject.ElementPredicates.isFinalField;
import static com.google.errorprone.matchers.InjectMatchers.IS_APPLICATION_OF_JAVAX_INJECT;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.AnnotationTree;
/**
* @author sgoldfeder@google.com (Steven Goldfeder)
*/
@BugPattern(summary = "@javax.inject.Inject cannot be put on a final field.", severity = WARNING)
public class JavaxInjectOnFinalField extends BugChecker implements AnnotationTreeMatcher {
@Override
public Description matchAnnotation(AnnotationTree annotationTree, VisitorState state) {
if (IS_APPLICATION_OF_JAVAX_INJECT.matches(annotationTree, state)) {
if (isFinalField(getSymbol(state.getPath().getParentPath().getParentPath().getLeaf()))) {
return describeMatch(annotationTree, SuggestedFix.delete(annotationTree));
}
}
return Description.NO_MATCH;
}
}
| 1,986
| 40.395833
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/InjectOnMemberAndConstructor.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.inject;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.InjectMatchers.hasInjectAnnotation;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.constructor;
import static com.google.errorprone.matchers.Matchers.isField;
import static com.google.errorprone.util.ASTHelpers.isStatic;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.InjectMatchers;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symbol;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.lang.model.element.ElementKind;
/**
* Checks if class constructor and members are both annotated as @Inject.
*
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(
summary =
"Members shouldn't be annotated with @Inject if constructor is already annotated @Inject",
severity = ERROR)
public class InjectOnMemberAndConstructor extends BugChecker implements ClassTreeMatcher {
private static final Matcher<ClassTree> HAS_CONSTRUCTORS_WITH_INJECT =
constructor(AT_LEAST_ONE, hasInjectAnnotation());
private static final Matcher<VariableTree> INSTANCE_FIELD_WITH_INJECT =
allOf(isField(), hasInjectAnnotation());
@Override
public final Description matchClass(ClassTree classTree, VisitorState state) {
if (!HAS_CONSTRUCTORS_WITH_INJECT.matches(classTree, state)) {
return Description.NO_MATCH;
}
List<MethodTree> ctors = ASTHelpers.getConstructors(classTree);
ImmutableList<MethodTree> ctorsWithInject =
ctors.stream()
.filter(c -> hasInjectAnnotation().matches(c, state))
.collect(toImmutableList());
if (ctorsWithInject.size() != 1) {
// Injection frameworks don't support multiple @Inject ctors.
// There is already an ERROR check for it.
// http://errorprone.info/bugpattern/MoreThanOneInjectableConstructor
return Description.NO_MATCH;
}
// collect the assignments in ctor
Set<Symbol> variablesAssigned = new HashSet<>();
new TreeScanner<Void, Void>() {
@Override
public Void visitAssignment(AssignmentTree tree, Void unused) {
Symbol symbol = ASTHelpers.getSymbol(tree.getVariable());
// check if it is instance field.
if (symbol != null && symbol.getKind() == ElementKind.FIELD && !isStatic(symbol)) {
variablesAssigned.add(symbol);
}
return super.visitAssignment(tree, null);
}
}.scan(getOnlyElement(ctorsWithInject), null);
SuggestedFix.Builder fix = SuggestedFix.builder();
VariableTree variableTreeFirstMatch = null;
for (Tree member : classTree.getMembers()) {
if (!(member instanceof VariableTree)) {
continue;
}
VariableTree variableTree = (VariableTree) member;
if (!INSTANCE_FIELD_WITH_INJECT.matches(variableTree, state)) {
continue;
}
if (!variablesAssigned.contains(ASTHelpers.getSymbol(variableTree))) {
continue;
}
variableTreeFirstMatch = variableTree;
removeInjectAnnotationFromVariable(variableTree, state).ifPresent(fix::merge);
}
if (variableTreeFirstMatch == null) {
return Description.NO_MATCH;
}
if (fix.isEmpty()) {
return describeMatch(variableTreeFirstMatch);
}
return describeMatch(variableTreeFirstMatch, fix.build());
}
private static Optional<SuggestedFix> removeInjectAnnotationFromVariable(
VariableTree variableTree, VisitorState state) {
for (AnnotationTree annotation : variableTree.getModifiers().getAnnotations()) {
if (InjectMatchers.IS_APPLICATION_OF_AT_INJECT.matches(annotation, state)) {
return Optional.of(SuggestedFix.replace(annotation, ""));
}
}
return Optional.empty();
}
}
| 5,438
| 38.413043
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/AssistedInjectAndInjectOnConstructors.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.bugpatterns.inject;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.InjectMatchers.ASSISTED_INJECT_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.hasInjectAnnotation;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.constructor;
import static com.google.errorprone.matchers.Matchers.hasAnnotation;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ClassTree;
/**
* @author sgoldfeder@google.com (Steven Goldfeder)
*/
@BugPattern(
summary =
"@AssistedInject and @Inject should not be used on different constructors in the same"
+ " class.",
severity = WARNING)
public class AssistedInjectAndInjectOnConstructors extends BugChecker implements ClassTreeMatcher {
/**
* Matches if a class has a constructor that is annotated with @Inject and a constructor annotated
* with @AssistedInject.
*/
private static final Matcher<ClassTree> HAS_CONSTRUCTORS_WITH_INJECT_AND_ASSISTED_INJECT =
allOf(
constructor(AT_LEAST_ONE, hasInjectAnnotation()),
constructor(AT_LEAST_ONE, hasAnnotation(ASSISTED_INJECT_ANNOTATION)));
@Override
public final Description matchClass(ClassTree classTree, VisitorState state) {
if (HAS_CONSTRUCTORS_WITH_INJECT_AND_ASSISTED_INJECT.matches(classTree, state)) {
return describeMatch(classTree);
}
return Description.NO_MATCH;
}
}
| 2,512
| 38.888889
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/ScopeAnnotationOnInterfaceOrAbstractClass.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.bugpatterns.inject;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.InjectMatchers.GUICE_SCOPE_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.IS_DAGGER_COMPONENT;
import static com.google.errorprone.matchers.InjectMatchers.JAVAX_SCOPE_ANNOTATION;
import static com.google.errorprone.matchers.Matchers.symbolHasAnnotation;
import static javax.lang.model.element.Modifier.ABSTRACT;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Flags;
/**
* @author sgoldfeder@google.com (Steven Goldfeder)
*/
@BugPattern(
name = "InjectScopeAnnotationOnInterfaceOrAbstractClass",
summary = "Scope annotation on an interface or abstract class is not allowed",
severity = WARNING)
public class ScopeAnnotationOnInterfaceOrAbstractClass extends BugChecker
implements AnnotationTreeMatcher {
/**
* Matches annotations that are themselves annotated with {@code @ScopeAnnotation(Guice)} or
* {@code @Scope(Javax)}.
*/
private static final Matcher<AnnotationTree> SCOPE_ANNOTATION_MATCHER =
Matchers.<AnnotationTree>anyOf(
symbolHasAnnotation(GUICE_SCOPE_ANNOTATION), symbolHasAnnotation(JAVAX_SCOPE_ANNOTATION));
private static final Matcher<ClassTree> INTERFACE_AND_ABSTRACT_TYPE_MATCHER =
new Matcher<ClassTree>() {
@Override
public boolean matches(ClassTree classTree, VisitorState state) {
return classTree.getModifiers().getFlags().contains(ABSTRACT)
|| (ASTHelpers.getSymbol(classTree).flags() & Flags.INTERFACE) != 0;
}
};
@Override
public final Description matchAnnotation(AnnotationTree annotationTree, VisitorState state) {
Tree modified = getCurrentlyAnnotatedNode(state);
if (SCOPE_ANNOTATION_MATCHER.matches(annotationTree, state)
&& modified instanceof ClassTree
&& !IS_DAGGER_COMPONENT.matches((ClassTree) modified, state)
&& INTERFACE_AND_ABSTRACT_TYPE_MATCHER.matches((ClassTree) modified, state)) {
return describeMatch(annotationTree, SuggestedFix.delete(annotationTree));
}
return Description.NO_MATCH;
}
private static Tree getCurrentlyAnnotatedNode(VisitorState state) {
return state.getPath().getParentPath().getParentPath().getLeaf();
}
}
| 3,499
| 41.168675
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/CloseableProvides.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.inject;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.methodReturns;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.InjectMatchers;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.sun.source.tree.MethodTree;
/**
* @author bhagwani@google.com (Sumit Bhagwani)
*/
@BugPattern(
summary = "Providing Closeable resources makes their lifecycle unclear",
severity = WARNING)
public class CloseableProvides extends BugChecker implements MethodTreeMatcher {
private static final Matcher<MethodTree> CLOSEABLE_PROVIDES_MATCHER =
allOf(
InjectMatchers.hasProvidesAnnotation(),
methodReturns(Matchers.isSubtypeOf("java.io.Closeable")));
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
if (!CLOSEABLE_PROVIDES_MATCHER.matches(tree, state)) {
return Description.NO_MATCH;
}
return describeMatch(tree);
}
}
| 1,989
| 35.851852
| 80
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/MoreThanOneQualifier.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.bugpatterns.inject;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.InjectMatchers.GUICE_BINDING_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.JAVAX_QUALIFIER_ANNOTATION;
import static com.google.errorprone.matchers.Matchers.symbolHasAnnotation;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ModifiersTree;
import java.util.List;
/**
* @author sgoldfeder@google.com (Steven Goldfeder)
*/
@BugPattern(
name = "InjectMoreThanOneQualifier",
summary = "Using more than one qualifier annotation on the same element is not allowed.",
severity = ERROR)
public class MoreThanOneQualifier extends BugChecker implements AnnotationTreeMatcher {
private static final Matcher<AnnotationTree> QUALIFIER_ANNOTATION_MATCHER =
Matchers.anyOf(
symbolHasAnnotation(GUICE_BINDING_ANNOTATION),
symbolHasAnnotation(JAVAX_QUALIFIER_ANNOTATION));
@Override
public Description matchAnnotation(AnnotationTree annotationTree, VisitorState state) {
int numberOfQualifiers = 0;
if (QUALIFIER_ANNOTATION_MATCHER.matches(annotationTree, state)) {
for (AnnotationTree t : getSiblingAnnotations(state)) {
if (QUALIFIER_ANNOTATION_MATCHER.matches(t, state)) {
numberOfQualifiers++;
}
}
}
if (numberOfQualifiers > 1) {
return describeMatch(annotationTree, SuggestedFix.delete(annotationTree));
}
return Description.NO_MATCH;
}
private static List<? extends AnnotationTree> getSiblingAnnotations(VisitorState state) {
return ((ModifiersTree) state.getPath().getParentPath().getLeaf()).getAnnotations();
}
}
| 2,762
| 38.471429
| 93
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/InvalidTargetingOnScopingAnnotation.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.bugpatterns.inject;
import static com.google.common.collect.Sets.immutableEnumSet;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.InjectMatchers.GUICE_SCOPE_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.JAVAX_SCOPE_ANNOTATION;
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.hasAnnotation;
import static com.google.errorprone.matchers.Matchers.isType;
import static com.google.errorprone.matchers.Matchers.kindIs;
import static com.google.errorprone.util.ASTHelpers.getAnnotation;
import static com.sun.source.tree.Tree.Kind.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.MultiMatcher;
import com.google.errorprone.matchers.MultiMatcher.MultiMatchResult;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ClassTree;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Set;
/**
* @author sgoldfeder@google.com (Steven Goldfeder)
*/
@BugPattern(
name = "InjectInvalidTargetingOnScopingAnnotation",
summary = "A scoping annotation's Target should include TYPE and METHOD.",
severity = WARNING)
public class InvalidTargetingOnScopingAnnotation extends BugChecker implements ClassTreeMatcher {
private static final String TARGET_ANNOTATION = "java.lang.annotation.Target";
private static final MultiMatcher<ClassTree, AnnotationTree> HAS_TARGET_ANNOTATION =
annotations(AT_LEAST_ONE, isType(TARGET_ANNOTATION));
private static final Matcher<ClassTree> ANNOTATION_WITH_SCOPE_AND_TARGET =
allOf(
kindIs(ANNOTATION_TYPE),
anyOf(hasAnnotation(GUICE_SCOPE_ANNOTATION), hasAnnotation(JAVAX_SCOPE_ANNOTATION)));
private static final ImmutableSet<ElementType> REQUIRED_ELEMENT_TYPES =
immutableEnumSet(TYPE, METHOD);
@Override
public final Description matchClass(ClassTree classTree, VisitorState state) {
if (ANNOTATION_WITH_SCOPE_AND_TARGET.matches(classTree, state)) {
MultiMatchResult<AnnotationTree> targetAnnotation =
HAS_TARGET_ANNOTATION.multiMatchResult(classTree, state);
if (targetAnnotation.matches()) {
AnnotationTree targetTree = targetAnnotation.onlyMatchingNode();
Target target = getAnnotation(classTree, Target.class);
if (target != null
&& // Unlikely to occur, but just in case Target isn't on the classpath.
!Arrays.asList(target.value()).containsAll(REQUIRED_ELEMENT_TYPES)) {
return describeMatch(targetTree, replaceTargetAnnotation(target, targetTree));
}
}
}
return Description.NO_MATCH;
}
/**
* Rewrite the annotation with static imports, adding TYPE and METHOD to the @Target annotation
* value (and reordering them to their declaration order in ElementType).
*/
private static Fix replaceTargetAnnotation(
Target annotation, AnnotationTree targetAnnotationTree) {
Set<ElementType> types = EnumSet.copyOf(REQUIRED_ELEMENT_TYPES);
types.addAll(Arrays.asList(annotation.value()));
return replaceTargetAnnotation(targetAnnotationTree, types);
}
static Fix replaceTargetAnnotation(AnnotationTree targetAnnotationTree, Set<ElementType> types) {
SuggestedFix.Builder builder =
SuggestedFix.builder()
.replace(targetAnnotationTree, "@Target({" + Joiner.on(", ").join(types) + "})");
for (ElementType type : types) {
builder.addStaticImport("java.lang.annotation.ElementType." + type);
}
return builder.build();
}
}
| 5,099
| 42.589744
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/OverlappingQualifierAndScopeAnnotation.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.bugpatterns.inject;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.InjectMatchers.GUICE_BINDING_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.GUICE_SCOPE_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.JAVAX_QUALIFIER_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.JAVAX_SCOPE_ANNOTATION;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.hasAnnotation;
import static com.google.errorprone.matchers.Matchers.kindIs;
import static com.sun.source.tree.Tree.Kind.ANNOTATION_TYPE;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ClassTree;
/**
* @author sgoldfeder@google.com (Steven Goldfeder)
*/
@BugPattern(
summary =
"Annotations cannot be both Scope annotations and Qualifier annotations: this causes "
+ "confusion when trying to use them.",
severity = ERROR)
public class OverlappingQualifierAndScopeAnnotation extends BugChecker implements ClassTreeMatcher {
private static final Matcher<ClassTree> ANNOTATION_WITH_BOTH_TYPES =
allOf(
kindIs(ANNOTATION_TYPE),
anyOf(hasAnnotation(GUICE_BINDING_ANNOTATION), hasAnnotation(JAVAX_QUALIFIER_ANNOTATION)),
anyOf(hasAnnotation(GUICE_SCOPE_ANNOTATION), hasAnnotation(JAVAX_SCOPE_ANNOTATION)));
@Override
public final Description matchClass(ClassTree classTree, VisitorState state) {
return ANNOTATION_WITH_BOTH_TYPES.matches(classTree, state)
? describeMatch(classTree)
: Description.NO_MATCH;
}
}
| 2,633
| 42.9
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/QualifierOrScopeOnInjectMethod.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.inject;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.InjectMatchers.IS_APPLICATION_OF_AT_INJECT;
import static com.google.errorprone.matchers.InjectMatchers.IS_BINDING_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.IS_SCOPING_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.hasProvidesAnnotation;
import static com.google.errorprone.matchers.Matchers.annotations;
import static com.google.errorprone.matchers.Matchers.anyOf;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.MultiMatcher;
import com.google.errorprone.matchers.MultiMatcher.MultiMatchResult;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
import java.util.ArrayList;
import java.util.List;
/**
* @author Nick Glorioso (glorioso@google.com)
*/
@BugPattern(
summary =
"Qualifiers/Scope annotations on @Inject methods don't have any effect."
+ " Move the qualifier annotation to the binding location.",
severity = SeverityLevel.WARNING,
tags = StandardTags.LIKELY_ERROR)
public class QualifierOrScopeOnInjectMethod extends BugChecker implements MethodTreeMatcher {
private static final MultiMatcher<MethodTree, AnnotationTree> QUALIFIER_ANNOTATION_FINDER =
annotations(AT_LEAST_ONE, anyOf(IS_BINDING_ANNOTATION, IS_SCOPING_ANNOTATION));
private static final MultiMatcher<MethodTree, AnnotationTree> HAS_INJECT =
annotations(AT_LEAST_ONE, IS_APPLICATION_OF_AT_INJECT);
private static final Matcher<MethodTree> PROVIDES_METHOD = hasProvidesAnnotation();
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
MultiMatchResult<AnnotationTree> qualifierAnnotations =
QUALIFIER_ANNOTATION_FINDER.multiMatchResult(tree, state);
MultiMatchResult<AnnotationTree> injectAnnotations = HAS_INJECT.multiMatchResult(tree, state);
if (!(qualifierAnnotations.matches() && injectAnnotations.matches())) {
return Description.NO_MATCH;
}
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
ImmutableList<AnnotationTree> matchingAnnotations = qualifierAnnotations.matchingNodes();
// If we're looking at an @Inject constructor, move the scope annotation to the class instead,
// and delete all of the other qualifiers
if (ASTHelpers.getSymbol(tree).isConstructor()) {
List<AnnotationTree> scopes = new ArrayList<>();
List<AnnotationTree> qualifiers = new ArrayList<>();
for (AnnotationTree annoTree : matchingAnnotations) {
(IS_SCOPING_ANNOTATION.matches(annoTree, state) ? scopes : qualifiers).add(annoTree);
}
ClassTree outerClass = ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class);
scopes.forEach(
a -> {
fixBuilder.delete(a);
fixBuilder.prefixWith(outerClass, state.getSourceForNode(a) + " ");
});
deleteAll(qualifiers, fixBuilder);
return describeMatch(tree, fixBuilder.build());
}
// If it has a "@Provides" annotation as well as an @Inject annotation, removing the @Inject
// should be semantics-preserving (since Modules aren't generally themselves @Injected).
if (PROVIDES_METHOD.matches(tree, state)) {
deleteAll(injectAnnotations.matchingNodes(), fixBuilder);
return describeMatch(injectAnnotations.matchingNodes().get(0), fixBuilder.build());
}
// Don't know what else to do here, deleting is the no-op change.
deleteAll(matchingAnnotations, fixBuilder);
return describeMatch(matchingAnnotations.get(0), fixBuilder.build());
}
private static void deleteAll(List<AnnotationTree> scopes, SuggestedFix.Builder fixBuilder) {
scopes.forEach(fixBuilder::delete);
}
}
| 5,041
| 44.017857
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/JavaxInjectOnAbstractMethod.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.bugpatterns.inject;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.fixes.SuggestedFix.delete;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.InjectMatchers.IS_APPLICATION_OF_JAVAX_INJECT;
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.hasModifier;
import static javax.lang.model.element.Modifier.ABSTRACT;
import static javax.lang.model.element.Modifier.DEFAULT;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.MultiMatcher;
import com.google.errorprone.matchers.MultiMatcher.MultiMatchResult;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.MethodTree;
/**
* @author sgoldfeder@google.com (Steven Goldfeder)
*/
@BugPattern(
summary = "Abstract and default methods are not injectable with javax.inject.Inject",
severity = ERROR)
public class JavaxInjectOnAbstractMethod extends BugChecker implements MethodTreeMatcher {
private static final MultiMatcher<MethodTree, AnnotationTree> INJECT_FINDER =
annotations(AT_LEAST_ONE, IS_APPLICATION_OF_JAVAX_INJECT);
private static final Matcher<MethodTree> ABSTRACT_OR_DEFAULT_METHOD_WITH_INJECT =
allOf(anyOf(hasModifier(ABSTRACT), hasModifier(DEFAULT)));
@Override
public Description matchMethod(MethodTree methodTree, VisitorState state) {
if (ABSTRACT_OR_DEFAULT_METHOD_WITH_INJECT.matches(methodTree, state)) {
MultiMatchResult<AnnotationTree> injectAnnotations =
INJECT_FINDER.multiMatchResult(methodTree, state);
if (injectAnnotations.matches()) {
AnnotationTree injectAnnotation = injectAnnotations.onlyMatchingNode();
return describeMatch(injectAnnotation, delete(injectAnnotation));
}
}
return Description.NO_MATCH;
}
}
| 2,959
| 43.179104
| 91
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/QualifierWithTypeUse.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.inject;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
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.hasAnnotation;
import static com.google.errorprone.matchers.Matchers.isType;
import static com.google.errorprone.matchers.Matchers.kindIs;
import static com.sun.source.tree.Tree.Kind.ANNOTATION_TYPE;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.InjectMatchers;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.MultiMatcher;
import com.google.errorprone.matchers.MultiMatcher.MultiMatchResult;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ClassTree;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Set;
/**
* @author glorioso@google.com (Nick Glorioso)
*/
@BugPattern(
summary =
"Injection frameworks currently don't understand Qualifiers in TYPE_PARAMETER or"
+ " TYPE_USE contexts.",
severity = WARNING,
tags = StandardTags.FRAGILE_CODE)
public class QualifierWithTypeUse extends BugChecker implements ClassTreeMatcher {
private static final MultiMatcher<ClassTree, AnnotationTree> HAS_TARGET_ANNOTATION =
annotations(AT_LEAST_ONE, isType("java.lang.annotation.Target"));
private static final Matcher<ClassTree> IS_QUALIFIER_WITH_TARGET =
allOf(
kindIs(ANNOTATION_TYPE),
anyOf(
hasAnnotation(InjectMatchers.JAVAX_QUALIFIER_ANNOTATION),
hasAnnotation(InjectMatchers.GUICE_BINDING_ANNOTATION)));
private static final ImmutableSet<ElementType> FORBIDDEN_ELEMENT_TYPES =
ImmutableSet.of(ElementType.TYPE_PARAMETER, ElementType.TYPE_USE);
@Override
public Description matchClass(ClassTree tree, VisitorState state) {
if (IS_QUALIFIER_WITH_TARGET.matches(tree, state)) {
MultiMatchResult<AnnotationTree> targetAnnotation =
HAS_TARGET_ANNOTATION.multiMatchResult(tree, state);
if (targetAnnotation.matches()) {
AnnotationTree annotationTree = targetAnnotation.onlyMatchingNode();
Target target = ASTHelpers.getAnnotation(tree, Target.class);
if (hasTypeUseOrTypeParameter(target)) {
return describeMatch(annotationTree, removeTypeUse(target, annotationTree));
}
}
}
return Description.NO_MATCH;
}
private static boolean hasTypeUseOrTypeParameter(Target targetAnnotation) {
// Should only be in cases where Target is not in the classpath
return targetAnnotation != null
&& !Collections.disjoint(FORBIDDEN_ELEMENT_TYPES, Arrays.asList(targetAnnotation.value()));
}
private static Fix removeTypeUse(Target targetAnnotation, AnnotationTree tree) {
Set<ElementType> elements = EnumSet.copyOf(Arrays.asList(targetAnnotation.value()));
elements.removeAll(FORBIDDEN_ELEMENT_TYPES);
if (elements.isEmpty()) {
return SuggestedFix.delete(tree);
}
return InvalidTargetingOnScopingAnnotation.replaceTargetAnnotation(tree, elements);
}
}
| 4,505
| 41.11215
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/dagger/ScopeOnModule.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.inject.dagger;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.hasAnnotation;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ClassTree;
import com.sun.tools.javac.code.Symbol;
import java.util.ArrayList;
import java.util.List;
/** Migrate users who use JSR 330 scopes on Dagger modules. */
@BugPattern(
summary = "Scopes on modules have no function and will soon be an error.",
severity = SUGGESTION)
public final class ScopeOnModule extends BugChecker implements ClassTreeMatcher {
@Override
public Description matchClass(ClassTree classTree, VisitorState state) {
if (!DaggerAnnotations.isAnyModule().matches(classTree, state)) {
return Description.NO_MATCH;
}
List<SuggestedFix> fixes = new ArrayList<>();
for (AnnotationTree annotation : classTree.getModifiers().getAnnotations()) {
Symbol annotationType = getSymbol(annotation.getAnnotationType());
if (hasAnnotation(annotationType, "javax.inject.Scope", state)) {
fixes.add(SuggestedFix.delete(annotation));
}
}
if (fixes.isEmpty()) {
return Description.NO_MATCH;
}
return buildDescription(classTree).addAllFixes(fixes).build();
}
}
| 2,299
| 37.333333
| 81
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/dagger/package-info.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.
*/
/** Bug patterns related to <a href="https://dagger.dev/">Dagger</a>. */
package com.google.errorprone.bugpatterns.inject.dagger;
| 739
| 37.947368
| 75
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/dagger/PrivateConstructorForNoninstantiableModule.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.inject.dagger;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.bugpatterns.inject.dagger.DaggerAnnotations.isBindingDeclarationMethod;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.isStatic;
import static com.google.errorprone.util.ASTHelpers.createPrivateConstructor;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.isGeneratedConstructor;
import static com.sun.source.tree.Tree.Kind.CLASS;
import static com.sun.source.tree.Tree.Kind.METHOD;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import java.util.function.Predicate;
/**
* @author gak@google.com (Gregory Kick)
*/
@BugPattern(
summary = "Add a private constructor to modules that will not be instantiated by Dagger.",
severity = SUGGESTION)
public class PrivateConstructorForNoninstantiableModule extends BugChecker
implements ClassTreeMatcher {
@Override
public Description matchClass(ClassTree classTree, VisitorState state) {
if (!DaggerAnnotations.isAnyModule().matches(classTree, state)) {
return NO_MATCH;
}
// if a module is declared as an interface, skip it
if (!classTree.getKind().equals(CLASS)) {
return NO_MATCH;
}
ImmutableList<Tree> nonSyntheticMembers =
classTree.getMembers().stream()
.filter(
tree ->
!(tree.getKind().equals(METHOD) && isGeneratedConstructor((MethodTree) tree)))
.collect(toImmutableList());
// ignore empty modules
if (nonSyntheticMembers.isEmpty()) {
return NO_MATCH;
}
if (nonSyntheticMembers.stream().anyMatch(tree -> getSymbol(tree).isConstructor())) {
return NO_MATCH;
}
boolean hasBindingDeclarationMethods =
nonSyntheticMembers.stream()
.anyMatch(matcherAsPredicate(isBindingDeclarationMethod(), state));
if (hasBindingDeclarationMethods) {
return describeMatch(classTree, addPrivateConstructor(classTree, state));
}
boolean allStaticMembers =
nonSyntheticMembers.stream().allMatch(matcherAsPredicate(isStatic(), state));
if (allStaticMembers) {
return describeMatch(classTree, addPrivateConstructor(classTree, state));
}
return NO_MATCH;
}
private static Fix addPrivateConstructor(ClassTree classTree, VisitorState state) {
return SuggestedFixes.addMembers(classTree, state, createPrivateConstructor(classTree));
}
private static <T extends Tree> Predicate<T> matcherAsPredicate(
Matcher<? super T> matcher, VisitorState state) {
return t -> matcher.matches(t, state);
}
}
| 3,968
| 36.8
| 107
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/dagger/UseBinds.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.inject.dagger;
import static com.google.common.base.Preconditions.checkState;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.bugpatterns.inject.dagger.DaggerAnnotations.ELEMENTS_INTO_SET_CLASS_NAME;
import static com.google.errorprone.bugpatterns.inject.dagger.DaggerAnnotations.INTO_MAP_CLASS_NAME;
import static com.google.errorprone.bugpatterns.inject.dagger.DaggerAnnotations.INTO_SET_CLASS_NAME;
import static com.google.errorprone.bugpatterns.inject.dagger.DaggerAnnotations.PRODUCES_CLASS_NAME;
import static com.google.errorprone.bugpatterns.inject.dagger.DaggerAnnotations.PROVIDES_CLASS_NAME;
import static com.google.errorprone.bugpatterns.inject.dagger.DaggerAnnotations.isBindingMethod;
import static com.google.errorprone.bugpatterns.inject.dagger.Util.IS_DAGGER_2_MODULE;
import static com.google.errorprone.bugpatterns.inject.dagger.Util.makeConcreteClassAbstract;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.sun.source.tree.Tree.Kind.ASSIGNMENT;
import static com.sun.source.tree.Tree.Kind.RETURN;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ModifiersTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.util.Name;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.lang.model.element.Modifier;
@BugPattern(
summary = "@Binds is a more efficient and declarative mechanism for delegating a binding.",
severity = WARNING)
public class UseBinds extends BugChecker implements MethodTreeMatcher {
private static final Matcher<MethodTree> SIMPLE_METHOD =
new Matcher<MethodTree>() {
@Override
public boolean matches(MethodTree t, VisitorState state) {
List<? extends VariableTree> parameters = t.getParameters();
if (parameters.size() != 1) {
return false;
}
VariableTree onlyParameter = Iterables.getOnlyElement(parameters);
BlockTree body = t.getBody();
if (body == null) {
return false;
}
List<? extends StatementTree> statements = body.getStatements();
if (statements.size() != 1) {
return false;
}
StatementTree onlyStatement = Iterables.getOnlyElement(statements);
if (!onlyStatement.getKind().equals(RETURN)) {
return false;
}
Symbol returnedSymbol = getSymbol(((ReturnTree) onlyStatement).getExpression());
if (returnedSymbol == null) {
return false;
}
return getSymbol(onlyParameter).equals(returnedSymbol);
}
};
private static final Matcher<MethodTree> CAN_BE_A_BINDS_METHOD =
allOf(isBindingMethod(), SIMPLE_METHOD);
@Override
public Description matchMethod(MethodTree method, VisitorState state) {
if (!CAN_BE_A_BINDS_METHOD.matches(method, state)) {
return NO_MATCH;
}
ClassTree enclosingClass = ASTHelpers.findEnclosingNode(state.getPath(), ClassTree.class);
// Dagger 1 modules don't support @Binds.
if (!IS_DAGGER_2_MODULE.matches(enclosingClass, state)) {
return NO_MATCH;
}
if (enclosingClass.getExtendsClause() != null) {
return fixByDelegating();
}
for (Tree member : enclosingClass.getMembers()) {
if (member.getKind().equals(Tree.Kind.METHOD) && !getSymbol(member).isConstructor()) {
MethodTree siblingMethod = (MethodTree) member;
Set<Modifier> siblingFlags = siblingMethod.getModifiers().getFlags();
if (!(siblingFlags.contains(Modifier.STATIC) || siblingFlags.contains(Modifier.ABSTRACT))
&& !CAN_BE_A_BINDS_METHOD.matches(siblingMethod, state)) {
return fixByDelegating();
}
}
}
return fixByModifyingMethod(state, enclosingClass, method);
}
private Description fixByModifyingMethod(
VisitorState state, ClassTree enclosingClass, MethodTree method) {
return describeMatch(
method,
SuggestedFix.builder()
.addImport("dagger.Binds")
.merge(convertMethodToBinds(method, enclosingClass, state))
.merge(makeConcreteClassAbstract(enclosingClass, state))
.build());
}
private static SuggestedFix.Builder convertMethodToBinds(
MethodTree method, ClassTree enclosingClass, VisitorState state) {
SuggestedFix.Builder fix = SuggestedFix.builder();
ModifiersTree modifiers = method.getModifiers();
ImmutableList.Builder<String> modifierStringsBuilder =
ImmutableList.<String>builder().add("@Binds");
for (AnnotationTree annotation : modifiers.getAnnotations()) {
Name annotationQualifiedName = getSymbol(annotation).getQualifiedName();
if (annotationQualifiedName.contentEquals(PROVIDES_CLASS_NAME)
|| annotationQualifiedName.contentEquals(PRODUCES_CLASS_NAME)) {
List<? extends ExpressionTree> arguments = annotation.getArguments();
if (!arguments.isEmpty()) {
ExpressionTree argument = Iterables.getOnlyElement(arguments);
checkState(argument.getKind().equals(ASSIGNMENT));
AssignmentTree assignment = (AssignmentTree) argument;
checkState(getSymbol(assignment.getVariable()).getSimpleName().contentEquals("type"));
String typeName = getSymbol(assignment.getExpression()).getSimpleName().toString();
switch (typeName) {
case "SET":
modifierStringsBuilder.add("@IntoSet");
fix.addImport(INTO_SET_CLASS_NAME);
break;
case "SET_VALUES":
modifierStringsBuilder.add("@ElementsIntoSet");
fix.addImport(ELEMENTS_INTO_SET_CLASS_NAME);
break;
case "MAP":
modifierStringsBuilder.add("@IntoMap");
fix.addImport(INTO_MAP_CLASS_NAME);
break;
default:
throw new AssertionError("Unknown type name: " + typeName);
}
}
} else {
modifierStringsBuilder.add(state.getSourceForNode(annotation));
}
}
Set<Modifier> methodFlags = new HashSet<>(modifiers.getFlags());
methodFlags.remove(Modifier.STATIC);
methodFlags.remove(Modifier.FINAL);
if (!enclosingClass.getKind().equals(Kind.INTERFACE)) {
methodFlags.add(Modifier.ABSTRACT);
}
for (Modifier flag : methodFlags) {
modifierStringsBuilder.add(flag.toString());
}
fix.replace(modifiers, Joiner.on(' ').join(modifierStringsBuilder.build()));
fix.replace(method.getBody(), ";");
return fix;
}
private static Description fixByDelegating() {
// TODO(gak): add a suggested fix by which we make a nested abstract module that we can include
return NO_MATCH;
}
}
| 8,531
| 40.417476
| 109
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/dagger/ProvidesNull.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.inject.dagger;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ReturnTreeMatcher;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.CatchTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
/**
* Bug checker for null-returning methods annotated with {@code @Provides} but not
* {@code @Nullable}.
*/
@BugPattern(
name = "DaggerProvidesNull",
summary = "Dagger @Provides methods may not return null unless annotated with @Nullable",
severity = ERROR)
public class ProvidesNull extends BugChecker implements ReturnTreeMatcher {
/**
* Matches explicit "return null" statements in methods annotated with {@code @Provides} but not
* {@code @Nullable}. Suggests either annotating the method with {@code @Nullable} or throwing a
* {@link RuntimeException} instead.
*/
// TODO(eaftan): Use nullness dataflow analysis when it's ready
@Override
public Description matchReturn(ReturnTree returnTree, VisitorState state) {
ExpressionTree returnExpression = returnTree.getExpression();
if (returnExpression == null || returnExpression.getKind() != Kind.NULL_LITERAL) {
return Description.NO_MATCH;
}
TreePath path = state.getPath();
MethodTree enclosingMethod = null;
while (true) {
if (path == null || path.getLeaf() instanceof LambdaExpressionTree) {
return Description.NO_MATCH;
} else if (path.getLeaf() instanceof MethodTree) {
enclosingMethod = (MethodTree) path.getLeaf();
break;
} else {
path = path.getParentPath();
}
}
MethodSymbol enclosingMethodSym = ASTHelpers.getSymbol(enclosingMethod);
// Method is not annotated as Provides -> No match
if (!ASTHelpers.hasAnnotation(enclosingMethodSym, "dagger.Provides", state)) {
return Description.NO_MATCH;
}
// Method is annotated as Nullable -> No match
if (ASTHelpers.hasDirectAnnotationWithSimpleName(enclosingMethodSym, "Nullable")) {
return Description.NO_MATCH;
}
// Type-use annotations do *NOT* work with Dagger. See b/117251022
// You must use *any* non-type-use Nullable annotation.
Fix addNullableFix =
SuggestedFix.builder()
.prefixWith(enclosingMethod, "@Nullable\n")
.addImport("javax.annotation.Nullable")
.build();
CatchTree enclosingCatch = ASTHelpers.findEnclosingNode(state.getPath(), CatchTree.class);
if (enclosingCatch == null) {
// If not in a catch block, suggest adding @Nullable first, then throwing an exception.
Fix throwRuntimeExceptionFix =
SuggestedFix.replace(returnTree, "throw new RuntimeException();");
return buildDescription(returnTree)
.addFix(addNullableFix)
.addFix(throwRuntimeExceptionFix)
.build();
} else {
// If in a catch block, suggest throwing an exception first, then adding @Nullable.
String replacement =
String.format("throw new RuntimeException(%s);", enclosingCatch.getParameter().getName());
Fix throwRuntimeExceptionFix = SuggestedFix.replace(returnTree, replacement);
return buildDescription(returnTree)
.addFix(throwRuntimeExceptionFix)
.addFix(addNullableFix)
.build();
}
}
}
| 4,520
| 39.00885
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/dagger/AndroidInjectionBeforeSuper.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.inject.dagger;
import static com.google.common.base.Predicates.notNull;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.enclosingClass;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.isSameType;
import static com.google.errorprone.matchers.Matchers.isSubtypeOf;
import static com.google.errorprone.matchers.Matchers.methodHasParameters;
import static com.google.errorprone.matchers.Matchers.methodIsNamed;
import static com.google.errorprone.matchers.Matchers.staticMethod;
import static com.google.errorprone.matchers.Matchers.variableType;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.SimpleTreeVisitor;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* @author Ron Shapiro
*/
@BugPattern(
summary =
"AndroidInjection.inject() should always be invoked before calling super.lifecycleMethod()",
severity = ERROR)
public final class AndroidInjectionBeforeSuper extends BugChecker implements MethodTreeMatcher {
private enum MatchType {
ACTIVITY(
"android.app.Activity",
"onCreate",
ImmutableList.of(variableType(isSameType("android.os.Bundle"))),
"dagger.android.AndroidInjection"),
FRAMEWORK_FRAGMENT(
"android.app.Fragment",
"onAttach",
ImmutableList.of(variableType(isSameType("android.content.Context"))),
"dagger.android.AndroidInjection"),
FRAMEWORK_FRAGMENT_PRE_API23(
"android.app.Fragment",
"onAttach",
ImmutableList.of(variableType(isSameType("android.app.Activity"))),
"dagger.android.AndroidInjection"),
SUPPORT_FRAGMENT(
"android.support.v4.app.Fragment",
"onAttach",
ImmutableList.of(variableType(isSameType("android.content.Context"))),
"dagger.android.support.AndroidSupportInjection"),
SUPPORT_FRAGMENT_PRE_API23(
"android.support.v4.app.Fragment",
"onAttach",
ImmutableList.of(variableType(isSameType("android.app.Activity"))),
"dagger.android.support.AndroidSupportInjection"),
SERVICE(
"android.app.Service", "onCreate", ImmutableList.of(), "dagger.android.AndroidInjection"),
;
private final String lifecycleMethod;
private final Matcher<MethodTree> methodMatcher;
private final Matcher<ExpressionTree> methodInvocationMatcher;
private final Matcher<ExpressionTree> injectMethodMatcher;
MatchType(
String componentType,
String lifecycleMethod,
ImmutableList<Matcher<VariableTree>> lifecycleMethodParameters,
String staticMethodClass) {
this.lifecycleMethod = lifecycleMethod;
methodMatcher =
allOf(
methodIsNamed(lifecycleMethod),
methodHasParameters(lifecycleMethodParameters),
enclosingClass(isSubtypeOf(componentType)));
methodInvocationMatcher =
instanceMethod().onDescendantOf(componentType).named(lifecycleMethod);
injectMethodMatcher =
staticMethod().onClass(staticMethodClass).named("inject").withParameters(componentType);
}
}
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
for (MatchType matchType : MatchType.values()) {
if (matchType.methodMatcher.matches(tree, state)) {
return tree.accept(new LifecycleMethodVisitor(matchType, state), null);
}
}
return Description.NO_MATCH;
}
private final class LifecycleMethodVisitor extends SimpleTreeVisitor<Description, Void> {
private final MatchType matchType;
private final VisitorState state;
LifecycleMethodVisitor(MatchType matchType, VisitorState state) {
this.matchType = matchType;
this.state = state;
}
private boolean foundSuper = false;
@Override
public @Nullable Description visitMethodInvocation(MethodInvocationTree node, Void unused) {
if (foundSuper && matchType.injectMethodMatcher.matches(node, state)) {
return buildDescription(node)
.setMessage(
String.format(
"AndroidInjection.inject() should always be invoked before calling super.%s()",
matchType.lifecycleMethod))
.build();
} else if (matchType.methodInvocationMatcher.matches(node, state)) {
foundSuper = true;
}
return null;
}
@Override
public Description visitMethod(MethodTree node, Void unused) {
BlockTree methodBody = node.getBody();
if (methodBody == null) {
return Description.NO_MATCH;
}
return methodBody.getStatements().stream()
.map(tree -> tree.accept(this, null))
.filter(notNull())
.findFirst()
.orElse(Description.NO_MATCH);
}
@Override
public Description visitExpressionStatement(ExpressionStatementTree node, Void unused) {
return node.getExpression().accept(this, null);
}
}
}
| 6,348
| 37.478788
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/dagger/RefersToDaggerCodegen.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.inject.dagger;
import static com.google.errorprone.util.ASTHelpers.enclosingPackage;
import static com.google.errorprone.util.ASTHelpers.getGeneratedBy;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Type;
/**
* Checks that the only code that refers to Dagger generated code is other Dagger generated code.
*/
@BugPattern(
summary = "Don't refer to Dagger's internal or generated code",
severity = SeverityLevel.ERROR)
public final class RefersToDaggerCodegen extends BugChecker implements MethodInvocationTreeMatcher {
private static final ImmutableSet<String> DAGGER_INTERNAL_PACKAGES =
ImmutableSet.of(
"dagger.internal",
"dagger.producers.internal",
"dagger.producers.monitoring.internal",
"dagger.android.internal");
private static final ImmutableSet<String> GENERATED_BASE_TYPES =
ImmutableSet.of("dagger.internal.Factory", "dagger.producers.internal.AbstractProducer");
/**
* Dagger 1 does not add an @Generated annotation, but it's code should still be able to refer to
* {@code dagger.internal} APIs.
*/
private static final ImmutableSet<String> DAGGER_1_GENERATED_BASE_TYPES =
ImmutableSet.of("dagger.internal.Binding", "dagger.internal.ModuleAdapter");
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
MethodSymbol method = getSymbol(tree);
ClassSymbol rootClassOfMethod = ASTHelpers.outermostClass(method);
if (!isGeneratedFactoryType(rootClassOfMethod, state)
&& !isMembersInjectionInvocation(method, state)
&& !isDaggerInternalClass(rootClassOfMethod)) {
return Description.NO_MATCH;
}
if (isAllowedToReferenceDaggerInternals(state)) {
return Description.NO_MATCH;
}
return describeMatch(tree);
}
private static boolean isMembersInjectionInvocation(MethodSymbol method, VisitorState state) {
if (method.getSimpleName().contentEquals("injectMembers")) {
return false;
}
return isGeneratedBaseType(ASTHelpers.outermostClass(method), state, "dagger.MembersInjector");
}
// TODO(ronshapiro): if we ever start emitting an annotation that has class retention, use that
// instead of checking for subtypes of generated code
private static boolean isGeneratedFactoryType(ClassSymbol symbol, VisitorState state) {
// TODO(ronshapiro): check annotation creators, inaccessible map key proxies, or inaccessible
// module constructor proxies?
return GENERATED_BASE_TYPES.stream()
.anyMatch(baseType -> isGeneratedBaseType(symbol, state, baseType));
}
private static boolean isGeneratedBaseType(
ClassSymbol symbol, VisitorState state, String baseTypeName) {
Type baseType = state.getTypeFromString(baseTypeName);
return ASTHelpers.isSubtype(symbol.asType(), baseType, state);
}
private static boolean isDaggerInternalClass(ClassSymbol symbol) {
return DAGGER_INTERNAL_PACKAGES.contains(
enclosingPackage(symbol).getQualifiedName().toString());
}
private static boolean isAllowedToReferenceDaggerInternals(VisitorState state) {
ClassSymbol rootCallingClass =
ASTHelpers.outermostClass(getSymbol(state.findEnclosing(ClassTree.class)));
if (rootCallingClass.getQualifiedName().toString().startsWith("dagger.")) {
return true;
}
ImmutableSet<String> generatedBy = getGeneratedBy(rootCallingClass, state);
if (!generatedBy.isEmpty()) {
return generatedBy.contains("dagger.internal.codegen.ComponentProcessor");
}
if (DAGGER_1_GENERATED_BASE_TYPES.stream()
.anyMatch(dagger1Type -> isGeneratedBaseType(rootCallingClass, state, dagger1Type))) {
return true;
} else if (isGeneratedBaseType(rootCallingClass, state, "dagger.MembersInjector")
&& rootCallingClass.getSimpleName().toString().contains("$$ParentAdapter")) {
return true;
}
return false;
}
}
| 5,242
| 40.283465
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/dagger/EmptySetMultibindingContributions.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.inject.dagger;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.hasAnnotation;
import static com.google.errorprone.matchers.Matchers.hasArgumentWithValue;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Sets;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.matchers.method.MethodMatchers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.code.Flags.Flag;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.tree.JCTree.JCModifiers;
import com.sun.tools.javac.util.Name;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/**
* @author gak@google.com (Gregory Kick)
*/
@BugPattern(
summary =
"@Multibinds is a more efficient and declarative mechanism for ensuring that a set"
+ " multibinding is present in the graph.",
severity = WARNING)
public final class EmptySetMultibindingContributions extends BugChecker
implements MethodTreeMatcher {
private static final Matcher<AnnotationTree> HAS_DAGGER_ONE_MODULE_ARGUMENT =
anyOf(
hasArgumentWithValue("injects", Matchers.<ExpressionTree>anything()),
hasArgumentWithValue("staticInjections", Matchers.<ExpressionTree>anything()),
hasArgumentWithValue("overrides", Matchers.<ExpressionTree>anything()),
hasArgumentWithValue("addsTo", Matchers.<ExpressionTree>anything()),
hasArgumentWithValue("complete", Matchers.<ExpressionTree>anything()),
hasArgumentWithValue("library", Matchers.<ExpressionTree>anything()));
/** We're just not going to worry about Collections.EMPTY_SET. */
private static final Matcher<ExpressionTree> COLLECTIONS_EMPTY_SET =
MethodMatchers.staticMethod().onClass(Collections.class.getCanonicalName()).named("emptySet");
private static final Matcher<ExpressionTree> IMMUTABLE_SETS_OF =
MethodMatchers.staticMethod()
.onClassAny(
ImmutableSet.class.getCanonicalName(), ImmutableSortedSet.class.getCanonicalName())
.named("of")
.withNoParameters();
private static final Matcher<ExpressionTree> SET_CONSTRUCTORS =
anyOf(
noArgSetConstructor(HashSet.class),
noArgSetConstructor(LinkedHashSet.class),
noArgSetConstructor(TreeSet.class));
@SuppressWarnings("rawtypes")
private static Matcher<ExpressionTree> noArgSetConstructor(Class<? extends Set> setClass) {
return MethodMatchers.constructor().forClass(setClass.getCanonicalName()).withNoParameters();
}
private static final Matcher<ExpressionTree> SET_FACTORY_METHODS =
anyOf(
setFactory("newHashSet"),
setFactory("newLinkedHashSet"),
setFactory("newConcurrentHashSet"));
private static Matcher<ExpressionTree> setFactory(String factoryName) {
return MethodMatchers.staticMethod()
.onClass(Sets.class.getCanonicalName())
.named(factoryName)
.withNoParameters();
}
private static final Matcher<ExpressionTree> ENUM_SET_NONE_OF =
MethodMatchers.staticMethod().onClass(EnumSet.class.getCanonicalName()).named("noneOf");
private static final Matcher<ExpressionTree> EMPTY_SET =
anyOf(
COLLECTIONS_EMPTY_SET,
IMMUTABLE_SETS_OF,
SET_CONSTRUCTORS,
SET_FACTORY_METHODS,
ENUM_SET_NONE_OF);
private static final Matcher<MethodTree> DIRECTLY_RETURNS_EMPTY_SET =
Matchers.singleStatementReturnMatcher(EMPTY_SET);
private static final Matcher<MethodTree> RETURNS_EMPTY_SET =
new Matcher<MethodTree>() {
@Override
public boolean matches(MethodTree method, VisitorState state) {
List<? extends VariableTree> parameters = method.getParameters();
if (!parameters.isEmpty()) {
return false;
}
return DIRECTLY_RETURNS_EMPTY_SET.matches(method, state);
}
};
private static final Matcher<Tree> ANNOTATED_WITH_PRODUCES_OR_PROVIDES =
anyOf(hasAnnotation("dagger.Provides"), hasAnnotation("dagger.producers.Produces"));
private static final Matcher<MethodTree> CAN_BE_A_MULTIBINDS_METHOD =
allOf(
ANNOTATED_WITH_PRODUCES_OR_PROVIDES,
hasAnnotation("dagger.multibindings.ElementsIntoSet"),
RETURNS_EMPTY_SET);
@Override
public Description matchMethod(MethodTree method, VisitorState state) {
if (!CAN_BE_A_MULTIBINDS_METHOD.matches(method, state)) {
return NO_MATCH;
}
JCClassDecl enclosingClass = ASTHelpers.findEnclosingNode(state.getPath(), JCClassDecl.class);
// Check to see if this is in a Dagger 1 module b/c it doesn't support @Multibinds
for (JCAnnotation annotation : enclosingClass.getModifiers().getAnnotations()) {
if (ASTHelpers.getSymbol(annotation.getAnnotationType())
.getQualifiedName()
.contentEquals("dagger.Module")
&& HAS_DAGGER_ONE_MODULE_ARGUMENT.matches(annotation, state)) {
return NO_MATCH;
}
}
return fixByModifyingMethod(state, enclosingClass, method);
}
private Description fixByModifyingMethod(
VisitorState state, JCClassDecl enclosingClass, MethodTree method) {
JCModifiers methodModifiers = ((JCMethodDecl) method).getModifiers();
String replacementModifiersString = createReplacementMethodModifiers(state, methodModifiers);
JCModifiers enclosingClassModifiers = enclosingClass.getModifiers();
String enclosingClassReplacementModifiersString =
createReplacementClassModifiers(state, enclosingClassModifiers);
SuggestedFix.Builder fixBuilder =
SuggestedFix.builder()
.addImport("dagger.multibindings.Multibinds")
.replace(methodModifiers, replacementModifiersString)
.replace(method.getBody(), ";");
fixBuilder =
(enclosingClassModifiers.pos == -1)
? fixBuilder.prefixWith(enclosingClass, enclosingClassReplacementModifiersString)
: fixBuilder.replace(enclosingClassModifiers, enclosingClassReplacementModifiersString);
return describeMatch(method, fixBuilder.build());
}
private static String createReplacementMethodModifiers(
VisitorState state, JCModifiers modifiers) {
ImmutableList.Builder<String> modifierStringsBuilder =
ImmutableList.<String>builder().add("@Multibinds");
for (JCAnnotation annotation : modifiers.annotations) {
Name annotationQualifiedName = ASTHelpers.getSymbol(annotation).getQualifiedName();
if (!(annotationQualifiedName.contentEquals("dagger.Provides")
|| annotationQualifiedName.contentEquals("dagger.producers.Produces")
|| annotationQualifiedName.contentEquals("dagger.multibindings.ElementsIntoSet"))) {
modifierStringsBuilder.add(state.getSourceForNode(annotation));
}
}
EnumSet<Flag> methodFlags = ASTHelpers.asFlagSet(modifiers.flags);
methodFlags.remove(Flags.Flag.STATIC);
methodFlags.remove(Flags.Flag.FINAL);
methodFlags.add(Flags.Flag.ABSTRACT);
for (Flag flag : methodFlags) {
modifierStringsBuilder.add(flag.toString());
}
return Joiner.on(' ').join(modifierStringsBuilder.build());
}
private static String createReplacementClassModifiers(
VisitorState state, JCModifiers enclosingClassModifiers) {
ImmutableList.Builder<String> classModifierStringsBuilder = ImmutableList.builder();
for (JCAnnotation annotation : enclosingClassModifiers.annotations) {
classModifierStringsBuilder.add(state.getSourceForNode(annotation));
}
EnumSet<Flag> classFlags = ASTHelpers.asFlagSet(enclosingClassModifiers.flags);
classFlags.remove(Flags.Flag.FINAL);
classFlags.add(Flags.Flag.ABSTRACT);
for (Flag flag : classFlags) {
classModifierStringsBuilder.add(flag.toString());
}
return Joiner.on(' ').join(classModifierStringsBuilder.build());
}
}
| 9,808
| 40.740426
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/dagger/DaggerAnnotations.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.inject.dagger;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.hasAnnotation;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.Tree;
/** A utility class for static analysis having to do with Dagger annotations. */
public final class DaggerAnnotations {
// Dagger types
static final String BINDS_CLASS_NAME = "dagger.Binds";
static final String PROVIDES_CLASS_NAME = "dagger.Provides";
static final String MODULE_CLASS_NAME = "dagger.Module";
static final String MULTIBINDS_CLASS_NAME = "dagger.multibindings.Multibinds";
// Dagger Producers types
static final String PRODUCES_CLASS_NAME = "dagger.producers.Produces";
static final String PRODUCER_MODULE_CLASS_NAME = "dagger.producers.ProducerModule";
// Multibinding types
static final String INTO_SET_CLASS_NAME = "dagger.multibindings.IntoSet";
static final String ELEMENTS_INTO_SET_CLASS_NAME = "dagger.multibindings.ElementsIntoSet";
static final String INTO_MAP_CLASS_NAME = "dagger.multibindings.IntoMap";
private static final Matcher<Tree> ANY_MODULE =
anyOf(hasAnnotation(MODULE_CLASS_NAME), hasAnnotation(PRODUCER_MODULE_CLASS_NAME));
private static final Matcher<Tree> BINDING_METHOD =
anyOf(hasAnnotation(PROVIDES_CLASS_NAME), hasAnnotation(PRODUCES_CLASS_NAME));
private static final Matcher<Tree> BINDING_DECLARATION_METHOD =
anyOf(hasAnnotation(BINDS_CLASS_NAME), hasAnnotation(MULTIBINDS_CLASS_NAME));
// Common Matchers
public static Matcher<Tree> isAnyModule() {
return ANY_MODULE;
}
static Matcher<Tree> isBindingMethod() {
return BINDING_METHOD;
}
static Matcher<Tree> isBindingDeclarationMethod() {
return BINDING_DECLARATION_METHOD;
}
private DaggerAnnotations() {}
}
| 2,471
| 36.454545
| 92
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/dagger/Util.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.inject.dagger;
import static com.google.common.collect.Iterables.transform;
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.constructor;
import static com.google.errorprone.matchers.Matchers.hasAnnotation;
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.isType;
import static com.google.errorprone.matchers.Matchers.kindIs;
import static com.google.errorprone.matchers.Matchers.not;
import static com.google.errorprone.util.ASTHelpers.createPrivateConstructor;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.ASTHelpers.isGeneratedConstructor;
import static com.sun.source.tree.Tree.Kind.INTERFACE;
import static com.sun.source.tree.Tree.Kind.METHOD;
import static java.util.Arrays.asList;
import static javax.lang.model.element.Modifier.ABSTRACT;
import static javax.lang.model.element.Modifier.FINAL;
import static javax.lang.model.element.Modifier.STATIC;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.VisitorState;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.matchers.MultiMatcher;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.tree.JCTree.JCModifiers;
import java.util.EnumSet;
import java.util.Set;
import javax.lang.model.element.Modifier;
/** Matchers and utilities useful to Dagger bug checkers. */
final class Util {
private Util() {}
static final Matcher<Tree> ANNOTATED_WITH_PRODUCES_OR_PROVIDES =
anyOf(hasAnnotation("dagger.Provides"), hasAnnotation("dagger.producers.Produces"));
static final Matcher<Tree> ANNOTATED_WITH_MULTIBINDING_ANNOTATION =
anyOf(
hasAnnotation("dagger.multibindings.IntoSet"),
hasAnnotation("dagger.multibindings.ElementsIntoSet"),
hasAnnotation("dagger.multibindings.IntoMap"));
/**
* Matches Dagger 2 {@linkplain dagger.Module modules} and {@linkplain
* dagger.producers.ProducersModule producer modules}.
*/
static final Matcher<Tree> IS_DAGGER_2_MODULE =
annotations(
AT_LEAST_ONE,
anyOf(
allOf(
isType("dagger.Module"),
not(
hasAnyParameter(
"injects",
"staticInjections",
"overrides",
"addsTo",
"complete",
"library"))),
isType("dagger.producers.ProducerModule")));
/** Matches an annotation that has an argument for at least one of the given parameters. */
private static Matcher<AnnotationTree> hasAnyParameter(String... parameters) {
return anyOf(
transform(
asList(parameters),
new Function<String, Matcher<AnnotationTree>>() {
@Override
public Matcher<AnnotationTree> apply(String parameter) {
return hasArgumentWithValue(parameter, Matchers.<ExpressionTree>anything());
}
}));
}
private static final Matcher<ClassTree> CLASS_EXTENDS_NOTHING =
new Matcher<ClassTree>() {
@Override
public boolean matches(ClassTree t, VisitorState state) {
return t.getExtendsClause() == null;
}
};
/**
* Matches Dagger 2 {@linkplain dagger.Module modules} and {@linkplain
* dagger.producers.ProducersModule producer modules} that could contain abstract binding methods.
*
* <ul>
* <li>an interface or a class with no superclass
* <li>no instance {@link dagger.Provides} or {@link dagger.producers.Produces} methods
* </ul>
*/
static final Matcher<ClassTree> CAN_HAVE_ABSTRACT_BINDING_METHODS =
allOf(
IS_DAGGER_2_MODULE,
anyOf(kindIs(INTERFACE), CLASS_EXTENDS_NOTHING),
not(
hasMethod(
Matchers.<MethodTree>allOf(
ANNOTATED_WITH_PRODUCES_OR_PROVIDES, not(hasModifier(STATIC))))));
/** Returns the annotation on {@code classTree} whose type's FQCN is {@code annotationName}. */
static Optional<AnnotationTree> findAnnotation(String annotationName, ClassTree classTree) {
for (AnnotationTree annotationTree : classTree.getModifiers().getAnnotations()) {
ClassSymbol annotationClass = (ClassSymbol) getSymbol(annotationTree.getAnnotationType());
if (annotationClass.fullname.contentEquals(annotationName)) {
return Optional.of(annotationTree);
}
}
return Optional.absent();
}
private static final MultiMatcher<ClassTree, MethodTree> HAS_GENERATED_CONSTRUCTOR =
constructor(
AT_LEAST_ONE,
new Matcher<MethodTree>() {
@Override
public boolean matches(MethodTree t, VisitorState state) {
return isGeneratedConstructor(t);
}
});
/**
* Returns a fix that changes a concrete class to an abstract class.
*
* <ul>
* <li>Removes {@code final} if it was there.
* <li>Adds {@code abstract} if it wasn't there.
* <li>Adds a private empty constructor if the class was {@code final} and had only a default
* constructor.
* </ul>
*/
static SuggestedFix.Builder makeConcreteClassAbstract(ClassTree classTree, VisitorState state) {
Set<Modifier> flags = EnumSet.noneOf(Modifier.class);
flags.addAll(classTree.getModifiers().getFlags());
boolean wasFinal = flags.remove(FINAL);
boolean wasAbstract = !flags.add(ABSTRACT);
if (classTree.getKind().equals(INTERFACE) || (!wasFinal && wasAbstract)) {
return SuggestedFix.builder(); // no-op
}
ImmutableList.Builder<Object> modifiers = ImmutableList.builder();
for (AnnotationTree annotation : classTree.getModifiers().getAnnotations()) {
modifiers.add(state.getSourceForNode(annotation));
}
modifiers.addAll(flags);
SuggestedFix.Builder makeAbstract = SuggestedFix.builder();
if (((JCModifiers) classTree.getModifiers()).pos == -1) {
makeAbstract.prefixWith(classTree, Joiner.on(' ').join(modifiers.build()));
} else {
makeAbstract.replace(classTree.getModifiers(), Joiner.on(' ').join(modifiers.build()));
}
if (wasFinal && HAS_GENERATED_CONSTRUCTOR.matches(classTree, state)) {
makeAbstract.merge(addPrivateConstructor(classTree));
}
return makeAbstract;
}
// TODO(dpb): Account for indentation level.
private static SuggestedFix.Builder addPrivateConstructor(ClassTree classTree) {
SuggestedFix.Builder fix = SuggestedFix.builder();
String indent = " ";
for (Tree member : classTree.getMembers()) {
if (member.getKind().equals(METHOD) && !isGeneratedConstructor((MethodTree) member)) {
fix.prefixWith(
member, indent + createPrivateConstructor(classTree) + " // no instances\n" + indent);
break;
}
if (!member.getKind().equals(METHOD)) {
indent = "";
}
}
return fix;
}
}
| 8,532
| 39.633333
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/guice/package-info.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.
*/
/** Bug patterns related to <a href="https://github.com/google/guice">Guice</a>. */
package com.google.errorprone.bugpatterns.inject.guice;
| 749
| 38.473684
| 83
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/guice/BindingToUnqualifiedCommonType.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.bugpatterns.inject.guice;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.InjectMatchers.GUICE_PROVIDES_ANNOTATION;
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.classLiteral;
import static com.google.errorprone.matchers.Matchers.instanceMethod;
import static com.google.errorprone.matchers.Matchers.isPrimitiveOrBoxedPrimitiveType;
import static com.google.errorprone.matchers.Matchers.isSameType;
import static com.google.errorprone.matchers.Matchers.isType;
import static com.google.errorprone.matchers.Matchers.methodInvocation;
import static com.google.errorprone.matchers.Matchers.methodReturns;
import static com.google.errorprone.matchers.Matchers.not;
import static com.google.errorprone.matchers.Matchers.receiverOfInvocation;
import static com.google.errorprone.matchers.Matchers.symbolHasAnnotation;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.matchers.ChildMultiMatcher.MatchType;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.InjectMatchers;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.MonthDay;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.time.Period;
import java.time.Year;
import java.time.YearMonth;
import java.time.ZonedDateTime;
/**
* @author glorioso@google.com (Nick Glorioso)
*/
@BugPattern(
summary =
"This code declares a binding for a common value type without a Qualifier annotation.",
severity = WARNING)
public class BindingToUnqualifiedCommonType extends BugChecker
implements MethodTreeMatcher, MethodInvocationTreeMatcher {
private static final Matcher<Tree> IS_SIMPLE_TYPE =
anyOf(
isPrimitiveOrBoxedPrimitiveType(),
// java.time types
isSameType(DayOfWeek.class),
isSameType(Duration.class),
isSameType(Instant.class),
isSameType(LocalDate.class),
isSameType(LocalDateTime.class),
isSameType(LocalTime.class),
isSameType(Month.class),
isSameType(MonthDay.class),
isSameType(OffsetDateTime.class),
isSameType(OffsetTime.class),
isSameType(Period.class),
isSameType(Year.class),
isSameType(YearMonth.class),
isSameType(ZonedDateTime.class),
// other common JDK types
isSameType(String.class),
isSameType(BigDecimal.class));
private static final Matcher<MethodTree> PROVIDES_UNQUALIFIED_CONSTANT =
allOf(
annotations(AT_LEAST_ONE, isType(GUICE_PROVIDES_ANNOTATION)),
not(
annotations(
AT_LEAST_ONE,
Matchers.<AnnotationTree>anyOf(
symbolHasAnnotation(InjectMatchers.GUICE_BINDING_ANNOTATION),
symbolHasAnnotation(InjectMatchers.JAVAX_QUALIFIER_ANNOTATION)))),
methodReturns(IS_SIMPLE_TYPE));
private static final Matcher<MethodInvocationTree> BIND_TO_UNQUALIFIED_CONSTANT =
allOf(
instanceMethod()
.onDescendantOf("com.google.inject.binder.LinkedBindingBuilder")
.namedAnyOf("to", "toInstance", "toProvider", "toConstructor"),
receiverOfInvocation(
methodInvocation(
anyOf(
instanceMethod()
.onDescendantOf("com.google.inject.AbstractModule")
.withSignature("<T>bind(java.lang.Class<T>)"),
instanceMethod()
.onDescendantOf("com.google.inject.Binder")
.withSignature("<T>bind(java.lang.Class<T>)")),
MatchType.ALL,
classLiteral(IS_SIMPLE_TYPE))));
@Override
public Description matchMethod(MethodTree method, VisitorState state) {
if (PROVIDES_UNQUALIFIED_CONSTANT.matches(method, state)
&& !ASTHelpers.isJUnitTestCode(state)) {
return describeMatch(method);
}
return Description.NO_MATCH;
}
@Override
public Description matchMethodInvocation(
MethodInvocationTree methodInvocation, VisitorState state) {
if (BIND_TO_UNQUALIFIED_CONSTANT.matches(methodInvocation, state)
&& !ASTHelpers.isJUnitTestCode(state)) {
return describeMatch(methodInvocation);
}
return Description.NO_MATCH;
}
}
| 6,046
| 40.993056
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/guice/InjectOnFinalField.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.bugpatterns.inject.guice;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.InjectMatchers.GUICE_INJECT_ANNOTATION;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.hasAnnotation;
import static com.google.errorprone.matchers.Matchers.hasModifier;
import static com.google.errorprone.matchers.Matchers.isField;
import static javax.lang.model.element.Modifier.FINAL;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.fixes.SuggestedFixes;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.VariableTree;
/**
* @author sgoldfeder@google.com (Steven Goldfeder)
*/
@BugPattern(
name = "GuiceInjectOnFinalField",
summary =
"Although Guice allows injecting final fields, doing so is disallowed because the injected "
+ "value may not be visible to other threads.",
severity = ERROR)
public class InjectOnFinalField extends BugChecker implements VariableTreeMatcher {
private static final Matcher<VariableTree> FINAL_FIELD_WITH_GUICE_INJECT =
allOf(isField(), hasModifier(FINAL), hasAnnotation(GUICE_INJECT_ANNOTATION));
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
if (FINAL_FIELD_WITH_GUICE_INJECT.matches(tree, state)) {
return describeMatch(
tree, SuggestedFixes.removeModifiers(tree, state, FINAL).orElse(SuggestedFix.emptyFix()));
}
return Description.NO_MATCH;
}
}
| 2,454
| 41.327586
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/guice/AssistedParameters.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.bugpatterns.inject.guice;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.InjectMatchers.ASSISTED_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.ASSISTED_INJECT_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.hasInjectAnnotation;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.hasAnnotation;
import static com.google.errorprone.matchers.Matchers.methodHasParameters;
import static com.google.errorprone.matchers.Matchers.methodIsConstructor;
import com.google.auto.common.MoreElements;
import com.google.auto.value.AutoValue;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.matchers.ChildMultiMatcher.MatchType;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.google.errorprone.matchers.MultiMatcher;
import com.google.errorprone.matchers.MultiMatcher.MultiMatchResult;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.code.Attribute;
import com.sun.tools.javac.code.Attribute.Compound;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* @author sgoldfeder@google.com (Steven Goldfeder)
*/
@BugPattern(
name = "GuiceAssistedParameters",
summary =
"A constructor cannot have two @Assisted parameters of the same type unless they are "
+ "disambiguated with named @Assisted annotations.",
severity = ERROR)
public class AssistedParameters extends BugChecker implements MethodTreeMatcher {
private static final Matcher<MethodTree> IS_CONSTRUCTOR_WITH_INJECT_OR_ASSISTED =
allOf(
methodIsConstructor(),
anyOf(hasInjectAnnotation(), hasAnnotation(ASSISTED_INJECT_ANNOTATION)));
private static final MultiMatcher<MethodTree, VariableTree> ASSISTED_PARAMETER_MATCHER =
methodHasParameters(MatchType.AT_LEAST_ONE, Matchers.hasAnnotation(ASSISTED_ANNOTATION));
@Override
public final Description matchMethod(MethodTree constructor, VisitorState state) {
if (!IS_CONSTRUCTOR_WITH_INJECT_OR_ASSISTED.matches(constructor, state)) {
return Description.NO_MATCH;
}
// Gather @Assisted parameters, partition by type
MultiMatchResult<VariableTree> assistedParameters =
ASSISTED_PARAMETER_MATCHER.multiMatchResult(constructor, state);
if (!assistedParameters.matches()) {
return Description.NO_MATCH;
}
Multimap<Type, VariableTree> parametersByType =
partitionParametersByType(assistedParameters.matchingNodes(), state);
// If there's more than one parameter with the same type, they could conflict unless their
// @Assisted values are different.
List<ConflictResult> conflicts = new ArrayList<>();
for (Map.Entry<Type, Collection<VariableTree>> typeAndParameters :
parametersByType.asMap().entrySet()) {
Collection<VariableTree> parametersForThisType = typeAndParameters.getValue();
if (parametersForThisType.size() < 2) {
continue;
}
// Gather the @Assisted value from each parameter. If any value is repeated amongst the
// parameters in this type, it's a compile error.
ImmutableListMultimap<String, VariableTree> keyForAssistedVariable =
Multimaps.index(parametersForThisType, AssistedParameters::valueFromAssistedAnnotation);
for (Map.Entry<String, List<VariableTree>> assistedValueToParameters :
Multimaps.asMap(keyForAssistedVariable).entrySet()) {
if (assistedValueToParameters.getValue().size() > 1) {
conflicts.add(
ConflictResult.create(
typeAndParameters.getKey(),
assistedValueToParameters.getKey(),
ImmutableList.copyOf(assistedValueToParameters.getValue())));
}
}
}
if (conflicts.isEmpty()) {
return Description.NO_MATCH;
}
return buildDescription(constructor).setMessage(buildErrorMessage(conflicts)).build();
}
private static String valueFromAssistedAnnotation(VariableTree variableTree) {
for (Compound c : ASTHelpers.getSymbol(variableTree).getAnnotationMirrors()) {
if (MoreElements.asType(c.getAnnotationType().asElement())
.getQualifiedName()
.contentEquals(ASSISTED_ANNOTATION)) {
// Assisted only has 'value', and value can only contain 1 element.
Collection<Attribute> valueEntries = c.getElementValues().values();
if (!valueEntries.isEmpty()) {
return Iterables.getOnlyElement(valueEntries).getValue().toString();
}
}
}
return "";
}
private static String buildErrorMessage(List<ConflictResult> conflicts) {
StringBuilder sb =
new StringBuilder(
" Assisted parameters of the same type need to have distinct values for the @Assisted"
+ " annotation. There are conflicts between the annotations on this constructor:");
for (ConflictResult conflict : conflicts) {
sb.append("\n").append(conflict.type());
if (!conflict.value().isEmpty()) {
sb.append(", @Assisted(\"").append(conflict.value()).append("\")");
}
sb.append(": ");
List<String> simpleParameterNames =
Lists.transform(conflict.parameters(), t -> t.getName().toString());
Joiner.on(", ").appendTo(sb, simpleParameterNames);
}
return sb.toString();
}
@AutoValue
abstract static class ConflictResult {
abstract Type type();
abstract String value();
abstract ImmutableList<VariableTree> parameters();
static ConflictResult create(Type t, String v, ImmutableList<VariableTree> p) {
return new AutoValue_AssistedParameters_ConflictResult(t, v, p);
}
}
// Since Type doesn't have strong equality semantics, we have to use Types.isSameType to
// determine which parameters are conflicting with each other.
private static ListMultimap<Type, VariableTree> partitionParametersByType(
List<VariableTree> parameters, VisitorState state) {
Types types = state.getTypes();
ListMultimap<Type, VariableTree> multimap = LinkedListMultimap.create();
variables:
for (VariableTree node : parameters) {
// Normalize Integer => int
Type type = types.unboxedTypeOrType(ASTHelpers.getType(node));
for (Type existingType : multimap.keySet()) {
if (types.isSameType(existingType, type)) {
multimap.put(existingType, node);
continue variables;
}
}
// A new type for the map.
multimap.put(type, node);
}
return multimap;
}
}
| 8,202
| 39.014634
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/guice/OverridesGuiceInjectableMethod.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.bugpatterns.inject.guice;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.InjectMatchers.GUICE_INJECT_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.JAVAX_INJECT_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.hasInjectAnnotation;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.MethodTree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
/**
* This checker matches methods that 1) are not themselves annotated with @Inject (neither
* javax.inject.Inject nor com.google.inject.Inject) 2) descend from a method that is annotated
* with @com.google.inject.Inject
*
* @author sgoldfeder@google.com (Steven Goldfeder)
*/
@BugPattern(
summary =
"This method is not annotated with @Inject, but it overrides a "
+ "method that is annotated with @com.google.inject.Inject. Guice will inject this "
+ "method, and it is recommended to annotate it explicitly.",
severity = WARNING)
public class OverridesGuiceInjectableMethod extends BugChecker implements MethodTreeMatcher {
@Override
public Description matchMethod(MethodTree methodTree, VisitorState state) {
// if method is itself annotated with @Inject or it has no ancestor methods, return NO_MATCH;
if (!hasInjectAnnotation().matches(methodTree, state)) {
MethodSymbol method = ASTHelpers.getSymbol(methodTree);
for (MethodSymbol superMethod : ASTHelpers.findSuperMethods(method, state.getTypes())) {
if (ASTHelpers.hasAnnotation(superMethod, GUICE_INJECT_ANNOTATION, state)) {
return buildDescription(methodTree)
.addFix(
SuggestedFix.builder()
.addImport(JAVAX_INJECT_ANNOTATION)
.prefixWith(methodTree, "@Inject\n")
.build())
.setMessage(
String.format(
"This method is not annotated with @Inject, but overrides the method in %s "
+ "that is annotated with @com.google.inject.Inject. Guice will inject "
+ "this method, and it is recommended to annotate it explicitly.",
ASTHelpers.enclosingClass(superMethod).getQualifiedName()))
.build();
}
}
}
return Description.NO_MATCH;
}
}
| 3,379
| 44.066667
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/guice/ProvidesMethodOutsideOfModule.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.bugpatterns.inject.guice;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.InjectMatchers.GUICE_PROVIDES_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.INSIDE_GUICE_MODULE;
import static com.google.errorprone.matchers.Matchers.allOf;
import static com.google.errorprone.matchers.Matchers.isType;
import static com.google.errorprone.matchers.Matchers.not;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.AnnotationTree;
/**
* @author glorioso@google.com (Nick Glorioso)
*/
@BugPattern(
summary = "@Provides methods need to be declared in a Module to have any effect.",
severity = ERROR)
public class ProvidesMethodOutsideOfModule extends BugChecker implements AnnotationTreeMatcher {
private static final Matcher<AnnotationTree> PROVIDES_ANNOTATION_ON_METHOD_OUTSIDE_OF_MODULE =
allOf(isType(GUICE_PROVIDES_ANNOTATION), not(INSIDE_GUICE_MODULE));
@Override
public Description matchAnnotation(AnnotationTree annotation, VisitorState state) {
if (PROVIDES_ANNOTATION_ON_METHOD_OUTSIDE_OF_MODULE.matches(annotation, state)) {
return describeMatch(annotation, SuggestedFix.delete(annotation));
}
return Description.NO_MATCH;
}
}
| 2,227
| 41.846154
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/guice/AssistedInjectScoping.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.bugpatterns.inject.guice;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.InjectMatchers.ASSISTED_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.ASSISTED_INJECT_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.GUICE_SCOPE_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.JAVAX_SCOPE_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.hasInjectAnnotation;
import static com.google.errorprone.matchers.Matchers.annotations;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.constructor;
import static com.google.errorprone.matchers.Matchers.hasAnnotation;
import static com.google.errorprone.matchers.Matchers.methodHasParameters;
import static com.google.errorprone.matchers.Matchers.symbolHasAnnotation;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.MultiMatcher;
import com.google.errorprone.matchers.MultiMatcher.MultiMatchResult;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
/**
* This checker matches iff *both* of the following conditions are true: 1) The class is assisted:
* a) If there is a constructor that is annotated with @Inject and that constructor has at least one
* parameter that is annotated with @Assisted. b) If there is no @Inject constructor and at least
* one constructor is annotated with {@code @AssistedInject}. 2) There is an annotation on the
* class, and the annotation is itself annotated with {@code @ScopeAnnotation}.
*
* @author eaftan@google.com (Eddie Aftandilian)
*/
@BugPattern(
name = "GuiceAssistedInjectScoping",
summary = "Scope annotation on implementation class of AssistedInject factory is not allowed",
severity = ERROR)
public class AssistedInjectScoping extends BugChecker implements ClassTreeMatcher {
/** Matches classes that have an annotation that itself is annotated with @ScopeAnnotation. */
private static final MultiMatcher<ClassTree, AnnotationTree> CLASS_TO_SCOPE_ANNOTATIONS =
annotations(
AT_LEAST_ONE,
anyOf(
symbolHasAnnotation(GUICE_SCOPE_ANNOTATION),
symbolHasAnnotation(JAVAX_SCOPE_ANNOTATION)));
/** Matches if any constructor of a class is annotated with an @Inject annotation. */
private static final MultiMatcher<ClassTree, MethodTree> CLASS_TO_INJECTED_CONSTRUCTORS =
constructor(AT_LEAST_ONE, hasInjectAnnotation());
/**
* Matches if: 1) If there is a constructor that is annotated with @Inject and that constructor
* has at least one parameter that is annotated with @Assisted. 2) If there is no @Inject
* constructor and at least one constructor is annotated with @AssistedInject.
*/
private static final Matcher<ClassTree> HAS_ASSISTED_CONSTRUCTOR =
new Matcher<ClassTree>() {
@Override
public boolean matches(ClassTree classTree, VisitorState state) {
MultiMatchResult<MethodTree> injectedConstructors =
CLASS_TO_INJECTED_CONSTRUCTORS.multiMatchResult(classTree, state);
if (injectedConstructors.matches()) {
// Check constructor with @Inject annotation for parameter with @Assisted annotation.
return methodHasParameters(AT_LEAST_ONE, hasAnnotation(ASSISTED_ANNOTATION))
.matches(injectedConstructors.matchingNodes().get(0), state);
}
return constructor(AT_LEAST_ONE, hasAnnotation(ASSISTED_INJECT_ANNOTATION))
.matches(classTree, state);
}
};
@Override
public final Description matchClass(ClassTree classTree, VisitorState state) {
MultiMatchResult<AnnotationTree> hasScopeAnnotations =
CLASS_TO_SCOPE_ANNOTATIONS.multiMatchResult(classTree, state);
if (!hasScopeAnnotations.matches() || !HAS_ASSISTED_CONSTRUCTOR.matches(classTree, state)) {
return Description.NO_MATCH;
}
AnnotationTree annotationWithScopeAnnotation = hasScopeAnnotations.matchingNodes().get(0);
if (annotationWithScopeAnnotation == null) {
throw new IllegalStateException(
"Expected to find an annotation that was annotated with @ScopeAnnotation");
}
return describeMatch(
annotationWithScopeAnnotation, SuggestedFix.delete(annotationWithScopeAnnotation));
}
}
| 5,506
| 47.734513
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/bugpatterns/inject/guice/OverridesJavaxInjectableMethod.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.bugpatterns.inject.guice;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.InjectMatchers.GUICE_INJECT_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.JAVAX_INJECT_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.hasInjectAnnotation;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.MethodTree;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
/**
* This checker matches methods that 1) are not themselves annotated with @Inject 2) descend from a
* method that is annotated with @javax.inject.Inject 3) do not descent from a method that is
* annotated with @com.google.inject.Inject
*
* @author sgoldfeder@google.com (Steven Goldfeder)
*/
@BugPattern(
summary =
"This method is not annotated with @Inject, but it overrides a method that is "
+ " annotated with @javax.inject.Inject. The method will not be Injected.",
severity = ERROR)
public class OverridesJavaxInjectableMethod extends BugChecker implements MethodTreeMatcher {
@Override
public Description matchMethod(MethodTree methodTree, VisitorState state) {
// if method is itself annotated with @Inject or it has no ancestor methods, return NO_MATCH;
if (hasInjectAnnotation().matches(methodTree, state)) {
return Description.NO_MATCH;
}
boolean foundJavaxInject = false;
for (MethodSymbol superMethod :
ASTHelpers.findSuperMethods(ASTHelpers.getSymbol(methodTree), state.getTypes())) {
// With a Guice annotation, Guice will still inject the subclass-overridden method.
if (ASTHelpers.hasAnnotation(superMethod, GUICE_INJECT_ANNOTATION, state)) {
return Description.NO_MATCH;
}
// is not necessarily a match even if we find javax Inject on an ancestor
// since a higher up ancestor may have @com.google.inject.Inject
foundJavaxInject |= ASTHelpers.hasAnnotation(superMethod, JAVAX_INJECT_ANNOTATION, state);
}
if (foundJavaxInject) {
return describeMatch(
methodTree,
SuggestedFix.builder()
.addImport(JAVAX_INJECT_ANNOTATION)
.prefixWith(methodTree, "@Inject\n")
.build());
}
return Description.NO_MATCH;
}
}
| 3,266
| 39.8375
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/URepeated.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.refaster;
import com.google.auto.value.AutoValue;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import java.util.List;
import javax.annotation.Nullable;
/** A variable that can match a sequence of expressions. */
@AutoValue
abstract class URepeated extends UExpression {
public static URepeated create(CharSequence identifier, UExpression expression) {
return new AutoValue_URepeated(identifier.toString(), expression);
}
abstract String identifier();
abstract UExpression expression();
@Override
@Nullable
protected Choice<Unifier> defaultAction(Tree node, @Nullable Unifier unifier) {
return expression().unify(node, unifier);
}
@Override
public JCExpression inline(Inliner inliner) throws CouldNotResolveImportException {
throw new UnsupportedOperationException(
"@Repeated variables should be inlined inside method invocations or newArray");
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return expression().accept(visitor, data);
}
@Override
public Kind getKind() {
return Kind.OTHER;
}
/** Gets the binding of the underlying identifier in the unifier. */
@Nullable
public JCExpression getUnderlyingBinding(Unifier unifier) {
return (unifier == null) ? null : unifier.getBinding(new UFreeIdent.Key(identifier()));
}
public Key key() {
return new Key(identifier());
}
/** A key for a variable with count constraints. It maps to a list of expressions in a binding. */
public static final class Key extends Bindings.Key<List<JCExpression>> {
public Key(String name) {
super(name);
}
}
}
| 2,345
| 29.868421
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UReturn.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.refaster;
import static com.google.errorprone.refaster.Unifier.unifyNullable;
import com.google.auto.value.AutoValue;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCReturn;
import javax.annotation.Nullable;
/**
* {@link UTree} representation of a {@link ReturnTree}.
*
* @author lowasser@google.com
*/
@AutoValue
public abstract class UReturn extends USimpleStatement implements ReturnTree {
public static UReturn create(UExpression expression) {
return new AutoValue_UReturn(expression);
}
@Override
@Nullable
public abstract UExpression getExpression();
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitReturn(this, data);
}
@Override
public Kind getKind() {
return Kind.RETURN;
}
@Override
public JCReturn inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner.maker().Return(getExpression().inline(inliner));
}
@Override
@Nullable
public Choice<Unifier> visitReturn(ReturnTree ret, @Nullable Unifier unifier) {
return unifyNullable(unifier, getExpression(), ret.getExpression());
}
}
| 1,831
| 28.079365
| 81
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UExpressionStatement.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.refaster;
import com.google.auto.value.AutoValue;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCExpressionStatement;
import javax.annotation.Nullable;
/**
* {@link UTree} representation of a {@link ExpressionStatementTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UExpressionStatement extends USimpleStatement implements ExpressionStatementTree {
public static UExpressionStatement create(UExpression expression) {
return new AutoValue_UExpressionStatement(expression);
}
@Override
public abstract UExpression getExpression();
@Override
@Nullable
public Choice<Unifier> visitExpressionStatement(
ExpressionStatementTree expressionStatement, @Nullable Unifier unifier) {
return getExpression().unify(expressionStatement.getExpression(), unifier);
}
@Override
public JCExpressionStatement inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner.maker().Exec(getExpression().inline(inliner));
}
@Override
public Kind getKind() {
return Kind.EXPRESSION_STATEMENT;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitExpressionStatement(this, data);
}
}
| 1,946
| 30.918033
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UTry.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.refaster;
import static com.google.errorprone.refaster.Unifier.unifications;
import static com.google.errorprone.refaster.Unifier.unifyList;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.sun.source.tree.TreeVisitor;
import com.sun.source.tree.TryTree;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCBlock;
import com.sun.tools.javac.tree.JCTree.JCTry;
import javax.annotation.Nullable;
/**
* {@code UTree} representation of a {@code TryTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UTry extends USimpleStatement implements TryTree {
static UTry create(
Iterable<? extends UTree<?>> resources,
UBlock block,
Iterable<UCatch> catches,
@Nullable UBlock finallyBlock) {
return new AutoValue_UTry(
ImmutableList.copyOf(resources), block, ImmutableList.copyOf(catches), finallyBlock);
}
@Override
public abstract ImmutableList<UTree<?>> getResources();
@Override
public abstract UBlock getBlock();
@Override
public abstract ImmutableList<UCatch> getCatches();
@Override
@Nullable
public abstract UBlock getFinallyBlock();
@Override
public Kind getKind() {
return Kind.TRY;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitTry(this, data);
}
@Override
public JCTry inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.Try(
inliner.<JCTree>inlineList(getResources()),
getBlock().inline(inliner),
inliner.inlineList(getCatches()),
inlineFinallyBlock(inliner));
}
/** Skips the finally block if the result would be empty. */
@Nullable
private JCBlock inlineFinallyBlock(Inliner inliner) throws CouldNotResolveImportException {
if (getFinallyBlock() != null) {
JCBlock block = getFinallyBlock().inline(inliner);
if (!block.getStatements().isEmpty()) {
return block;
}
}
return null;
}
@Override
@Nullable
public Choice<Unifier> visitTry(TryTree node, @Nullable Unifier unifier) {
return unifyList(unifier, getResources(), node.getResources())
.thenChoose(unifications(getBlock(), node.getBlock()))
.thenChoose(unifications(getCatches(), node.getCatches()))
.thenChoose(unifications(getFinallyBlock(), node.getFinallyBlock()));
}
}
| 3,105
| 30.06
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/RefasterRule.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.refaster;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import com.google.auto.value.AutoValue;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Ascii;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableClassToInstanceMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.errorprone.CodeTransformer;
import com.google.errorprone.DescriptionListener;
import com.google.errorprone.SubContext;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.code.Symbol.PackageSymbol;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.util.Context;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import javax.tools.JavaFileManager;
/**
* A representation of an entire Refaster rule, corresponding to a class with @BeforeTemplates
* and @AfterTemplates.
*
* @author lowasser@google.com (Louis Wasserman)
* @param <M> The type of a match.
* @param <T> The type of the template used to find matches and generate replacements.
*/
@AutoValue
public abstract class RefasterRule<M extends TemplateMatch, T extends Template<M>>
implements CodeTransformer, Serializable {
public static RefasterRule<?, ?> create(
String qualifiedTemplateClass,
Collection<? extends Template<?>> beforeTemplates,
Collection<? extends Template<?>> afterTemplates) {
return create(
qualifiedTemplateClass,
ImmutableList.<UTypeVar>of(),
beforeTemplates,
afterTemplates,
ImmutableClassToInstanceMap.of());
}
public static RefasterRule<?, ?> create(
String qualifiedTemplateClass,
Iterable<UTypeVar> typeVariables,
Collection<? extends Template<?>> beforeTemplates,
Collection<? extends Template<?>> afterTemplates,
ImmutableClassToInstanceMap<Annotation> annotations) {
checkState(
!beforeTemplates.isEmpty(),
"No @BeforeTemplate was found in the specified class: %s",
qualifiedTemplateClass);
Class<?> templateType = beforeTemplates.iterator().next().getClass();
for (Template<?> beforeTemplate : beforeTemplates) {
checkState(
beforeTemplate.getClass().equals(templateType),
"Expected all templates to be of type %s but found template of type %s in %s",
templateType,
beforeTemplate.getClass(),
qualifiedTemplateClass);
}
for (Template<?> afterTemplate : afterTemplates) {
Set<String> missingArguments =
Sets.difference(
afterTemplate.expressionArgumentTypes().keySet(),
beforeTemplates.stream()
.<Set<String>>map(t -> t.expressionArgumentTypes().keySet())
.reduce(Sets::intersection)
.get());
checkArgument(
missingArguments.isEmpty(),
"@AfterTemplate of %s defines arguments that are not present in all @BeforeTemplate"
+ " methods: %s",
qualifiedTemplateClass,
missingArguments);
checkState(
afterTemplate.getClass().equals(templateType),
"Expected all templates to be of type %s but found template of type %s in %s",
templateType,
afterTemplate.getClass(),
qualifiedTemplateClass);
}
@SuppressWarnings({"unchecked", "rawtypes"})
RefasterRule<?, ?> result =
new AutoValue_RefasterRule(
qualifiedTemplateClass,
ImmutableList.copyOf(typeVariables),
ImmutableList.copyOf(beforeTemplates),
ImmutableList.copyOf(afterTemplates),
annotations);
return result;
}
RefasterRule() {}
abstract String qualifiedTemplateClass();
abstract ImmutableList<UTypeVar> typeVariables();
abstract ImmutableList<T> beforeTemplates();
abstract ImmutableList<T> afterTemplates();
@Override
public abstract ImmutableClassToInstanceMap<Annotation> annotations();
@Override
public void apply(TreePath path, Context context, DescriptionListener listener) {
RefasterScanner.create(this, listener)
.scan(
path.getLeaf(), prepareContext(context, (JCCompilationUnit) path.getCompilationUnit()));
}
boolean rejectMatchesWithComments() {
return true; // TODO(lowasser): worth making configurable?
}
static final Context.Key<ImmutableList<UTypeVar>> RULE_TYPE_VARS = new Context.Key<>();
private Context prepareContext(Context baseContext, JCCompilationUnit compilationUnit) {
Context context = new SubContext(baseContext);
if (context.get(JavaFileManager.class) == null) {
JavacFileManager.preRegister(context);
}
context.put(JCCompilationUnit.class, compilationUnit);
context.put(PackageSymbol.class, compilationUnit.packge);
context.put(RULE_TYPE_VARS, typeVariables());
return context;
}
@VisibleForTesting
static String fromSecondLevel(String qualifiedTemplateClass) {
List<String> path = Splitter.on('.').splitToList(qualifiedTemplateClass);
for (int topLevel = 0; topLevel < path.size() - 1; topLevel++) {
if (Ascii.isUpperCase(path.get(topLevel).charAt(0))) {
return Joiner.on('_').join(path.subList(topLevel + 1, path.size()));
}
}
return Iterables.getLast(path);
}
String simpleTemplateName() {
return fromSecondLevel(qualifiedTemplateClass());
}
@Override
public final String toString() {
return simpleTemplateName();
}
}
| 6,455
| 34.866667
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UModifiers.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.refaster;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.sun.source.tree.ModifiersTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.code.Flags;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCModifiers;
import com.sun.tools.javac.util.List;
import java.util.Set;
import javax.lang.model.element.Modifier;
/**
* {@code UTree} representation of a {@code ModifiersTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UModifiers extends UTree<JCModifiers> implements ModifiersTree {
public static UModifiers create(long flagBits, UAnnotation... annotations) {
return create(flagBits, ImmutableList.copyOf(annotations));
}
public static UModifiers create(long flagBits, Iterable<? extends UAnnotation> annotations) {
return new AutoValue_UModifiers(flagBits, ImmutableList.copyOf(annotations));
}
abstract long flagBits();
@Override
public abstract ImmutableList<UAnnotation> getAnnotations();
@Override
public JCModifiers inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.Modifiers(
flagBits(), List.convert(JCAnnotation.class, inliner.inlineList(getAnnotations())));
}
@Override
public Choice<Unifier> visitModifiers(ModifiersTree modifier, Unifier unifier) {
return Choice.condition(getFlags().equals(modifier.getFlags()), unifier);
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitModifiers(this, data);
}
@Override
public Kind getKind() {
return Kind.MODIFIERS;
}
@Override
public Set<Modifier> getFlags() {
return Flags.asModifierSet(flagBits());
}
}
| 2,439
| 30.282051
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UIntersectionType.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.refaster;
import static com.google.errorprone.refaster.Unifier.unifyList;
import com.google.auto.value.AutoValue;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.sun.source.tree.IntersectionTypeTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCTypeIntersection;
/**
* {@code UTree} representation of an {@code IntersectionTypeTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UIntersectionType extends UExpression implements IntersectionTypeTree {
@VisibleForTesting
static UIntersectionType create(UExpression... bounds) {
return create(ImmutableList.copyOf(bounds));
}
static UIntersectionType create(Iterable<? extends UExpression> bounds) {
return new AutoValue_UIntersectionType(ImmutableList.copyOf(bounds));
}
@Override
public abstract ImmutableList<UExpression> getBounds();
@Override
public JCTypeIntersection inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner.maker().TypeIntersection(inliner.inlineList(getBounds()));
}
@Override
public Kind getKind() {
return Kind.INTERSECTION_TYPE;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitIntersectionType(this, data);
}
@Override
public Choice<Unifier> visitIntersectionType(IntersectionTypeTree node, Unifier unifier) {
return unifyList(unifier, getBounds(), node.getBounds());
}
}
| 2,163
| 31.298507
| 92
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UTemplater.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.refaster;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.errorprone.util.ASTHelpers.isStatic;
import com.google.common.collect.ImmutableClassToInstanceMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.reflect.TypeToken;
import com.google.errorprone.SubContext;
import com.google.errorprone.VisitorState;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.refaster.annotation.Matches;
import com.google.errorprone.refaster.annotation.NotMatches;
import com.google.errorprone.refaster.annotation.OfKind;
import com.google.errorprone.refaster.annotation.Repeated;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotatedTypeTree;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ArrayAccessTree;
import com.sun.source.tree.ArrayTypeTree;
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.BreakTree;
import com.sun.source.tree.CatchTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompoundAssignmentTree;
import com.sun.source.tree.ConditionalExpressionTree;
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.IdentifierTree;
import com.sun.source.tree.IfTree;
import com.sun.source.tree.InstanceOfTree;
import com.sun.source.tree.IntersectionTypeTree;
import com.sun.source.tree.LabeledStatementTree;
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.NewArrayTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.ParameterizedTypeTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.tree.PrimitiveTypeTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.StatementTree;
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.UnionTypeTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.tree.WhileLoopTree;
import com.sun.source.tree.WildcardTree;
import com.sun.source.util.SimpleTreeVisitor;
import com.sun.tools.javac.code.Attribute.Compound;
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.TypeSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
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.Type.ForAll;
import com.sun.tools.javac.code.Type.IntersectionClassType;
import com.sun.tools.javac.code.Type.MethodType;
import com.sun.tools.javac.code.Type.TypeVar;
import com.sun.tools.javac.code.Type.WildcardType;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.model.AnnotationProxyMaker;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCLambda;
import com.sun.tools.javac.tree.JCTree.JCModifiers;
import com.sun.tools.javac.tree.JCTree.JCPrimitiveTypeTree;
import com.sun.tools.javac.util.Context;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.MirroredTypeException;
/**
* Converts a type-checked syntax tree to a portable {@code UTree} template.
*
* @author lowasser@google.com (Louis Wasserman)
*/
public class UTemplater extends SimpleTreeVisitor<Tree, Void> {
/**
* Context key to indicate that templates should be treated as BlockTemplates, regardless of their
* structure.
*/
public static final Context.Key<Boolean> REQUIRE_BLOCK_KEY = new Context.Key<>();
/**
* Returns a template based on a method. One-line methods starting with a {@code return} statement
* are guessed to be expression templates, and all other methods are guessed to be block
* templates.
*/
public static Template<?> createTemplate(Context context, MethodTree decl) {
MethodSymbol declSym = ASTHelpers.getSymbol(decl);
ImmutableClassToInstanceMap<Annotation> annotations = UTemplater.annotationMap(declSym);
ImmutableMap<String, VarSymbol> freeExpressionVars = freeExpressionVariables(decl);
Context subContext = new SubContext(context);
UTemplater templater = new UTemplater(freeExpressionVars, subContext);
ImmutableMap<String, UType> expressionVarTypes =
ImmutableMap.copyOf(
Maps.transformValues(
freeExpressionVars, (VarSymbol sym) -> templater.template(sym.type)));
UType genericType = templater.template(declSym.type);
ImmutableList<UTypeVar> typeParameters;
UMethodType methodType;
if (genericType instanceof UForAll) {
UForAll forAllType = (UForAll) genericType;
typeParameters = forAllType.getTypeVars();
methodType = (UMethodType) forAllType.getQuantifiedType();
} else if (genericType instanceof UMethodType) {
typeParameters = ImmutableList.of();
methodType = (UMethodType) genericType;
} else {
throw new IllegalArgumentException(
"Expected genericType to be either a ForAll or a UMethodType, but was " + genericType);
}
List<? extends StatementTree> bodyStatements = decl.getBody().getStatements();
if (bodyStatements.size() == 1
&& Iterables.getOnlyElement(bodyStatements).getKind() == Kind.RETURN
&& context.get(REQUIRE_BLOCK_KEY) == null) {
ExpressionTree expression =
((ReturnTree) Iterables.getOnlyElement(bodyStatements)).getExpression();
return ExpressionTemplate.create(
annotations,
typeParameters,
expressionVarTypes,
templater.template(expression),
methodType.getReturnType());
} else {
List<UStatement> templateStatements = new ArrayList<>();
for (StatementTree statement : bodyStatements) {
templateStatements.add(templater.template(statement));
}
return BlockTemplate.create(
annotations, typeParameters, expressionVarTypes, templateStatements);
}
}
public static ImmutableMap<String, VarSymbol> freeExpressionVariables(
MethodTree templateMethodDecl) {
ImmutableMap.Builder<String, VarSymbol> builder = ImmutableMap.builder();
for (VariableTree param : templateMethodDecl.getParameters()) {
builder.put(param.getName().toString(), ASTHelpers.getSymbol(param));
}
return builder.buildOrThrow();
}
private final ImmutableMap<String, VarSymbol> freeVariables;
private final Context context;
public UTemplater(Map<String, VarSymbol> freeVariables, Context context) {
this.freeVariables = ImmutableMap.copyOf(freeVariables);
this.context = context;
}
UTemplater(Context context) {
this(ImmutableMap.<String, VarSymbol>of(), context);
}
public Tree template(Tree tree) {
return tree.accept(this, null);
}
@Nullable
private ImmutableList<Tree> templateTrees(@Nullable Iterable<? extends Tree> trees) {
if (trees == null) {
return null;
}
ImmutableList.Builder<Tree> builder = ImmutableList.builder();
for (Tree tree : trees) {
builder.add(template(tree));
}
return builder.build();
}
private static <T> ImmutableList<T> cast(Iterable<?> elements, Class<T> clazz) {
ImmutableList.Builder<T> builder = ImmutableList.builder();
for (Object element : elements) {
builder.add(clazz.cast(element));
}
return builder.build();
}
@Override
public UMethodDecl visitMethod(MethodTree decl, Void v) {
return UMethodDecl.create(
visitModifiers(decl.getModifiers(), null),
decl.getName(),
templateType(decl.getReturnType()),
cast(templateStatements(decl.getParameters()), UVariableDecl.class),
templateExpressions(decl.getThrows()),
(UBlock) template(decl.getBody()));
}
@Override
public UModifiers visitModifiers(ModifiersTree modifiers, Void v) {
return UModifiers.create(
((JCModifiers) modifiers).flags,
cast(templateExpressions(modifiers.getAnnotations()), UAnnotation.class));
}
public UExpression template(ExpressionTree tree) {
return (UExpression) tree.accept(this, null);
}
@Nullable
private ImmutableList<UExpression> templateExpressions(
@Nullable Iterable<? extends ExpressionTree> expressions) {
if (expressions == null) {
return null;
}
ImmutableList.Builder<UExpression> builder = ImmutableList.builder();
for (ExpressionTree expression : expressions) {
builder.add(template(expression));
}
return builder.build();
}
public UExpression templateType(Tree tree) {
checkArgument(
tree instanceof ExpressionTree,
"Trees representing types are expected to implement ExpressionTree, but %s does not",
tree);
return template((ExpressionTree) tree);
}
@Nullable
private ImmutableList<UExpression> templateTypeExpressions(
@Nullable Iterable<? extends Tree> types) {
if (types == null) {
return null;
}
ImmutableList.Builder<UExpression> builder = ImmutableList.builder();
for (Tree type : types) {
builder.add(templateType(type));
}
return builder.build();
}
@Override
public UInstanceOf visitInstanceOf(InstanceOfTree tree, Void v) {
return UInstanceOf.create(template(tree.getExpression()), templateType(tree.getType()));
}
@Override
public UPrimitiveTypeTree visitPrimitiveType(PrimitiveTypeTree tree, Void v) {
return UPrimitiveTypeTree.create(((JCPrimitiveTypeTree) tree).typetag);
}
@Override
public ULiteral visitLiteral(LiteralTree tree, Void v) {
return ULiteral.create(tree.getKind(), tree.getValue());
}
@Override
public UParens visitParenthesized(ParenthesizedTree tree, Void v) {
return UParens.create(template(tree.getExpression()));
}
@Override
public UAssign visitAssignment(AssignmentTree tree, Void v) {
return UAssign.create(template(tree.getVariable()), template(tree.getExpression()));
}
@Override
public UArrayAccess visitArrayAccess(ArrayAccessTree tree, Void v) {
return UArrayAccess.create(template(tree.getExpression()), template(tree.getIndex()));
}
@Override
public UAnnotation visitAnnotation(AnnotationTree tree, Void v) {
return UAnnotation.create(
templateType(tree.getAnnotationType()), templateExpressions(tree.getArguments()));
}
@Override
public UAnnotatedType visitAnnotatedType(AnnotatedTypeTree tree, Void v) {
return UAnnotatedType.create(
cast(templateExpressions(tree.getAnnotations()), UAnnotation.class),
template(tree.getUnderlyingType()));
}
@Override
public UExpression visitMemberSelect(MemberSelectTree tree, Void v) {
Symbol sym = ASTHelpers.getSymbol(tree);
if (sym instanceof ClassSymbol) {
return UClassIdent.create((ClassSymbol) sym);
} else if (isStatic(sym)) {
ExpressionTree selected = tree.getExpression();
checkState(
ASTHelpers.getSymbol(selected) instanceof ClassSymbol,
"Refaster cannot match static methods used on instances");
return staticMember(sym);
}
return UMemberSelect.create(
template(tree.getExpression()), tree.getIdentifier(), template(sym.type));
}
private UStaticIdent staticMember(Symbol symbol) {
return UStaticIdent.create(
(ClassSymbol) symbol.getEnclosingElement(),
symbol.getSimpleName(),
template(symbol.asType()));
}
private static final UStaticIdent ANY_OF;
private static final UStaticIdent IS_INSTANCE;
private static final UStaticIdent CLAZZ;
private static final UStaticIdent NEW_ARRAY;
private static final UStaticIdent ENUM_VALUE_OF;
private static final UStaticIdent AS_VARARGS;
static {
UTypeVar tVar = UTypeVar.create("T");
ANY_OF =
UStaticIdent.create(
Refaster.class.getCanonicalName(),
"anyOf",
UForAll.create(
ImmutableList.of(tVar), UMethodType.create(tVar, UArrayType.create(tVar))));
IS_INSTANCE =
UStaticIdent.create(
Refaster.class.getCanonicalName(),
"isInstance",
UForAll.create(
ImmutableList.of(tVar),
UMethodType.create(
UPrimitiveType.BOOLEAN, UClassType.create(Object.class.getCanonicalName()))));
CLAZZ =
UStaticIdent.create(
Refaster.class.getCanonicalName(),
"clazz",
UForAll.create(
ImmutableList.of(tVar),
UMethodType.create(UClassType.create(Class.class.getCanonicalName(), tVar))));
NEW_ARRAY =
UStaticIdent.create(
Refaster.class.getCanonicalName(),
"newArray",
UForAll.create(
ImmutableList.of(tVar),
UMethodType.create(UArrayType.create(tVar), UPrimitiveType.INT)));
UTypeVar eVar =
UTypeVar.create(
"E", UClassType.create(Enum.class.getCanonicalName(), UTypeVar.create("E")));
ENUM_VALUE_OF =
UStaticIdent.create(
Refaster.class.getCanonicalName(),
"enumValueOf",
UForAll.create(
ImmutableList.of(eVar),
UMethodType.create(eVar, UClassType.create(String.class.getCanonicalName()))));
AS_VARARGS =
UStaticIdent.create(
Refaster.class.getCanonicalName(),
"asVarargs",
UForAll.create(
ImmutableList.of(tVar), UMethodType.create(UArrayType.create(tVar), tVar)));
}
private static Tree getSingleExplicitTypeArgument(MethodInvocationTree tree) {
if (tree.getTypeArguments().isEmpty()) {
throw new IllegalArgumentException(
"Methods in the Refaster class must be invoked with "
+ "an explicit type parameter; for example, 'Refaster.<T>isInstance(o)'.");
}
return Iterables.getOnlyElement(tree.getTypeArguments());
}
static <T, U extends Unifiable<? super T>> boolean anyMatch(
U toUnify, T target, Unifier unifier) {
return toUnify.unify(target, unifier).first().isPresent();
}
@Override
public UExpression visitMethodInvocation(MethodInvocationTree tree, Void v) {
if (anyMatch(ANY_OF, tree.getMethodSelect(), new Unifier(context))) {
return UAnyOf.create(templateExpressions(tree.getArguments()));
} else if (anyMatch(IS_INSTANCE, tree.getMethodSelect(), new Unifier(context))) {
return UInstanceOf.create(
template(Iterables.getOnlyElement(tree.getArguments())),
templateType(getSingleExplicitTypeArgument(tree)));
} else if (anyMatch(CLAZZ, tree.getMethodSelect(), new Unifier(context))) {
Tree typeArg = getSingleExplicitTypeArgument(tree);
return UMemberSelect.create(
templateType(typeArg),
"class",
UClassType.create("java.lang.Class", template(((JCTree) typeArg).type)));
} else if (anyMatch(NEW_ARRAY, tree.getMethodSelect(), new Unifier(context))) {
Tree typeArg = getSingleExplicitTypeArgument(tree);
ExpressionTree lengthArg = Iterables.getOnlyElement(tree.getArguments());
return UNewArray.create(templateType(typeArg), ImmutableList.of(template(lengthArg)), null);
} else if (anyMatch(ENUM_VALUE_OF, tree.getMethodSelect(), new Unifier(context))) {
Tree typeArg = getSingleExplicitTypeArgument(tree);
ExpressionTree strArg = Iterables.getOnlyElement(tree.getArguments());
return UMethodInvocation.create(
UMemberSelect.create(
templateType(typeArg),
"valueOf",
UMethodType.create(
template(((JCTree) typeArg).type), UClassType.create("java.lang.String"))),
template(strArg));
} else if (anyMatch(AS_VARARGS, tree.getMethodSelect(), new Unifier(context))) {
ExpressionTree arg = Iterables.getOnlyElement(tree.getArguments());
checkArgument(
ASTHelpers.hasAnnotation(
ASTHelpers.getSymbol(arg), Repeated.class, new VisitorState(context)));
return template(arg);
}
Map<MethodSymbol, PlaceholderMethod> placeholderMethods =
context.get(RefasterRuleBuilderScanner.PLACEHOLDER_METHODS_KEY);
if (placeholderMethods != null && placeholderMethods.containsKey(ASTHelpers.getSymbol(tree))) {
return UPlaceholderExpression.create(
placeholderMethods.get(ASTHelpers.getSymbol(tree)),
templateExpressions(tree.getArguments()));
} else {
return UMethodInvocation.create(
templateTypeExpressions(tree.getTypeArguments()),
template(tree.getMethodSelect()),
templateExpressions(tree.getArguments()));
}
}
@Override
public UBinary visitBinary(BinaryTree tree, Void v) {
return UBinary.create(
tree.getKind(), template(tree.getLeftOperand()), template(tree.getRightOperand()));
}
@Override
public UAssignOp visitCompoundAssignment(CompoundAssignmentTree tree, Void v) {
return UAssignOp.create(
template(tree.getVariable()), tree.getKind(), template(tree.getExpression()));
}
@Override
public UUnary visitUnary(UnaryTree tree, Void v) {
return UUnary.create(tree.getKind(), template(tree.getExpression()));
}
@Override
public UExpression visitConditionalExpression(ConditionalExpressionTree tree, Void v) {
return UConditional.create(
template(tree.getCondition()),
template(tree.getTrueExpression()),
template(tree.getFalseExpression()));
}
@Override
public UNewArray visitNewArray(NewArrayTree tree, Void v) {
return UNewArray.create(
(UExpression) template(tree.getType()),
templateExpressions(tree.getDimensions()),
templateExpressions(tree.getInitializers()));
}
@Override
public UNewClass visitNewClass(NewClassTree tree, Void v) {
return UNewClass.create(
tree.getEnclosingExpression() == null ? null : template(tree.getEnclosingExpression()),
templateTypeExpressions(tree.getTypeArguments()),
template(tree.getIdentifier()),
templateExpressions(tree.getArguments()),
(tree.getClassBody() == null) ? null : visitClass(tree.getClassBody(), null));
}
@Override
public UClassDecl visitClass(ClassTree tree, Void v) {
ImmutableList.Builder<UMethodDecl> decls = ImmutableList.builder();
for (MethodTree decl : Iterables.filter(tree.getMembers(), MethodTree.class)) {
if (ASTHelpers.isGeneratedConstructor(decl)) {
// skip synthetic constructors
continue;
}
decls.add(visitMethod(decl, null));
}
return UClassDecl.create(decls.build());
}
@Override
public UArrayTypeTree visitArrayType(ArrayTypeTree tree, Void v) {
return UArrayTypeTree.create(templateType(tree.getType()));
}
@Override
public UTypeApply visitParameterizedType(ParameterizedTypeTree tree, Void v) {
return UTypeApply.create(
templateType(tree.getType()), templateTypeExpressions(tree.getTypeArguments()));
}
@Override
public UUnionType visitUnionType(UnionTypeTree tree, Void v) {
return UUnionType.create(templateTypeExpressions(tree.getTypeAlternatives()));
}
@Override
public UWildcard visitWildcard(WildcardTree tree, Void v) {
return UWildcard.create(
tree.getKind(), (tree.getBound() == null) ? null : templateType(tree.getBound()));
}
@Override
public UIntersectionType visitIntersectionType(IntersectionTypeTree tree, Void v) {
return UIntersectionType.create(templateTypeExpressions(tree.getBounds()));
}
@Override
public UTypeParameter visitTypeParameter(TypeParameterTree tree, Void v) {
return UTypeParameter.create(
tree.getName(),
templateTypeExpressions(tree.getBounds()),
cast(templateExpressions(tree.getAnnotations()), UAnnotation.class));
}
@Override
public UTypeCast visitTypeCast(TypeCastTree tree, Void v) {
return UTypeCast.create(templateType(tree.getType()), template(tree.getExpression()));
}
@Override
public ULambda visitLambdaExpression(LambdaExpressionTree tree, Void v) {
return ULambda.create(
((JCLambda) tree).paramKind,
cast(templateStatements(tree.getParameters()), UVariableDecl.class),
(UTree<?>) template(tree.getBody()));
}
@Override
public UMemberReference visitMemberReference(MemberReferenceTree tree, Void v) {
return UMemberReference.create(
tree.getMode(),
template(tree.getQualifierExpression()),
tree.getName(),
(tree.getTypeArguments() == null) ? null : templateExpressions(tree.getTypeArguments()));
}
@Override
public UExpression visitIdentifier(IdentifierTree tree, Void v) {
Symbol sym = ASTHelpers.getSymbol(tree);
if (sym instanceof ClassSymbol) {
return UClassIdent.create((ClassSymbol) sym);
} else if (sym != null && isStatic(sym)) {
return staticMember(sym);
} else if (freeVariables.containsKey(tree.getName().toString())) {
VarSymbol symbol = freeVariables.get(tree.getName().toString());
checkState(symbol == sym);
UExpression ident = UFreeIdent.create(tree.getName());
Matches matches = ASTHelpers.getAnnotation(symbol, Matches.class);
if (matches != null) {
ident = UMatches.create(getValue(matches), /* positive= */ true, ident);
}
NotMatches notMatches = ASTHelpers.getAnnotation(symbol, NotMatches.class);
if (notMatches != null) {
ident = UMatches.create(getValue(notMatches), /* positive= */ false, ident);
}
OfKind hasKind = ASTHelpers.getAnnotation(symbol, OfKind.class);
if (hasKind != null) {
EnumSet<Kind> allowed = EnumSet.copyOf(Arrays.asList(hasKind.value()));
ident = UOfKind.create(ident, ImmutableSet.copyOf(allowed));
}
// @Repeated annotations need to be checked last.
Repeated repeated = ASTHelpers.getAnnotation(symbol, Repeated.class);
if (repeated != null) {
ident = URepeated.create(tree.getName(), ident);
}
return ident;
}
if (sym == null) {
return UTypeVarIdent.create(tree.getName());
}
switch (sym.getKind()) {
case TYPE_PARAMETER:
return UTypeVarIdent.create(tree.getName());
default:
return ULocalVarIdent.create(tree.getName());
}
}
/**
* Returns the {@link Class} instance for the {@link Matcher} associated with the provided {@link
* Matches} annotation. This roundabout solution is recommended and explained by {@link
* Element#getAnnotation(Class)}.
*/
static Class<? extends Matcher<? super ExpressionTree>> getValue(Matches matches) {
String name;
try {
matches.value();
throw new RuntimeException("unreachable");
} catch (MirroredTypeException e) {
DeclaredType type = (DeclaredType) e.getTypeMirror();
name = ((TypeElement) type.asElement()).getQualifiedName().toString();
}
try {
return asSubclass(Class.forName(name), new TypeToken<Matcher<? super ExpressionTree>>() {});
} catch (ClassNotFoundException | ClassCastException e) {
throw new RuntimeException(e);
}
}
/**
* Returns the {@link Class} instance for the {@link Matcher} associated with the provided {@link
* NotMatches} annotation. This roundabout solution is recommended and explained by {@link
* Element#getAnnotation(Class)}.
*/
static Class<? extends Matcher<? super ExpressionTree>> getValue(NotMatches matches) {
String name;
try {
matches.value();
throw new RuntimeException("unreachable");
} catch (MirroredTypeException e) {
DeclaredType type = (DeclaredType) e.getTypeMirror();
name = ((TypeElement) type.asElement()).getQualifiedName().toString();
}
try {
return asSubclass(Class.forName(name), new TypeToken<Matcher<? super ExpressionTree>>() {});
} catch (ClassNotFoundException | ClassCastException e) {
throw new RuntimeException(e);
}
}
/**
* Similar to {@link Class#asSubclass(Class)}, but it accepts a {@link TypeToken} so it handles
* generics better.
*/
@SuppressWarnings("unchecked")
private static <T> Class<? extends T> asSubclass(Class<?> klass, TypeToken<T> token) {
if (!token.isSupertypeOf(klass)) {
throw new ClassCastException(klass + " is not assignable to " + token);
}
return (Class<? extends T>) klass;
}
public UStatement template(StatementTree tree) {
return (UStatement) tree.accept(this, null);
}
@Nullable
private ImmutableList<UStatement> templateStatements(
@Nullable List<? extends StatementTree> statements) {
if (statements == null) {
return null;
}
ImmutableList.Builder<UStatement> builder = ImmutableList.builder();
for (StatementTree statement : statements) {
builder.add(template(statement));
}
return builder.build();
}
@Override
public UTry visitTry(TryTree tree, Void v) {
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableList<UTree<?>> resources =
cast(templateTrees(tree.getResources()), (Class<UTree<?>>) (Class) UTree.class);
UBlock block = visitBlock(tree.getBlock(), null);
ImmutableList.Builder<UCatch> catchesBuilder = ImmutableList.builder();
for (CatchTree catchTree : tree.getCatches()) {
catchesBuilder.add(visitCatch(catchTree, null));
}
UBlock finallyBlock =
(tree.getFinallyBlock() == null) ? null : visitBlock(tree.getFinallyBlock(), null);
return UTry.create(resources, block, catchesBuilder.build(), finallyBlock);
}
@Override
public UCatch visitCatch(CatchTree tree, Void v) {
return UCatch.create(
visitVariable(tree.getParameter(), null), visitBlock(tree.getBlock(), null));
}
@Nullable
private PlaceholderMethod placeholder(@Nullable ExpressionTree expr) {
Map<MethodSymbol, PlaceholderMethod> placeholderMethods =
context.get(RefasterRuleBuilderScanner.PLACEHOLDER_METHODS_KEY);
return (placeholderMethods != null && expr != null)
? placeholderMethods.get(ASTHelpers.getSymbol(expr))
: null;
}
@Override
public UStatement visitExpressionStatement(ExpressionStatementTree tree, Void v) {
PlaceholderMethod placeholderMethod = placeholder(tree.getExpression());
if (placeholderMethod != null && placeholderMethod.returnType().equals(UPrimitiveType.VOID)) {
MethodInvocationTree invocation = (MethodInvocationTree) tree.getExpression();
return UPlaceholderStatement.create(
placeholderMethod,
templateExpressions(invocation.getArguments()),
ControlFlowVisitor.Result.NEVER_EXITS);
}
return UExpressionStatement.create(template(tree.getExpression()));
}
@Override
public UStatement visitReturn(ReturnTree tree, Void v) {
PlaceholderMethod placeholderMethod = placeholder(tree.getExpression());
if (placeholderMethod != null) {
MethodInvocationTree invocation = (MethodInvocationTree) tree.getExpression();
return UPlaceholderStatement.create(
placeholderMethod,
templateExpressions(invocation.getArguments()),
ControlFlowVisitor.Result.ALWAYS_RETURNS);
}
return UReturn.create((tree.getExpression() == null) ? null : template(tree.getExpression()));
}
@Override
public UWhileLoop visitWhileLoop(WhileLoopTree tree, Void v) {
return UWhileLoop.create(template(tree.getCondition()), template(tree.getStatement()));
}
@Override
public UVariableDecl visitVariable(VariableTree tree, Void v) {
return UVariableDecl.create(
tree.getName(),
templateType(tree.getType()),
(tree.getInitializer() == null) ? null : template(tree.getInitializer()));
}
@Override
public USkip visitEmptyStatement(EmptyStatementTree tree, Void v) {
return USkip.INSTANCE;
}
@Override
public UForLoop visitForLoop(ForLoopTree tree, Void v) {
return UForLoop.create(
templateStatements(tree.getInitializer()),
(tree.getCondition() == null) ? null : template(tree.getCondition()),
cast(templateStatements(tree.getUpdate()), UExpressionStatement.class),
template(tree.getStatement()));
}
@Override
public ULabeledStatement visitLabeledStatement(LabeledStatementTree tree, Void v) {
return ULabeledStatement.create(tree.getLabel(), template(tree.getStatement()));
}
@Override
public UBreak visitBreak(BreakTree tree, Void v) {
return UBreak.create(tree.getLabel());
}
@Override
public UContinue visitContinue(ContinueTree tree, Void v) {
return UContinue.create(tree.getLabel());
}
@Override
public UBlock visitBlock(BlockTree tree, Void v) {
return UBlock.create(templateStatements(tree.getStatements()));
}
@Override
public UThrow visitThrow(ThrowTree tree, Void v) {
return UThrow.create(template(tree.getExpression()));
}
@Override
public UDoWhileLoop visitDoWhileLoop(DoWhileLoopTree tree, Void v) {
return UDoWhileLoop.create(template(tree.getStatement()), template(tree.getCondition()));
}
@Override
public UEnhancedForLoop visitEnhancedForLoop(EnhancedForLoopTree tree, Void v) {
return UEnhancedForLoop.create(
visitVariable(tree.getVariable(), null),
template(tree.getExpression()),
template(tree.getStatement()));
}
@Override
public USynchronized visitSynchronized(SynchronizedTree tree, Void v) {
return USynchronized.create(template(tree.getExpression()), visitBlock(tree.getBlock(), null));
}
@Override
public UIf visitIf(IfTree tree, Void v) {
return UIf.create(
template(tree.getCondition()),
template(tree.getThenStatement()),
(tree.getElseStatement() == null) ? null : template(tree.getElseStatement()));
}
@Override
public UAssert visitAssert(AssertTree tree, Void v) {
return UAssert.create(
template(tree.getCondition()),
(tree.getDetail() == null) ? null : template(tree.getDetail()));
}
@Override
protected UTree<?> defaultAction(Tree tree, Void v) {
throw new IllegalArgumentException(
"Refaster does not currently support syntax " + tree.getClass());
}
public UType template(Type type) {
return type.accept(typeTemplater, null);
}
List<UType> templateTypes(Iterable<? extends Type> types) {
ImmutableList.Builder<UType> builder = ImmutableList.builder();
for (Type ty : types) {
builder.add(template(ty));
}
return builder.build();
}
private final Type.Visitor<UType, Void> typeTemplater =
new Types.SimpleVisitor<UType, Void>() {
private final Map<TypeSymbol, UTypeVar> typeVariables = new HashMap<>();
@Override
public UType visitType(Type type, Void v) {
if (UPrimitiveType.isDeFactoPrimitive(type.getKind())) {
return UPrimitiveType.create(type.getKind());
} else {
throw new IllegalArgumentException(
"Refaster does not currently support syntax " + type.getKind());
}
}
@Override
public UArrayType visitArrayType(ArrayType type, Void v) {
return UArrayType.create(type.getComponentType().accept(this, null));
}
@Override
public UMethodType visitMethodType(MethodType type, Void v) {
return UMethodType.create(
type.getReturnType().accept(this, null), templateTypes(type.getParameterTypes()));
}
@Override
public UType visitClassType(ClassType type, Void v) {
if (type instanceof IntersectionClassType) {
return UIntersectionClassType.create(
templateTypes(((IntersectionClassType) type).getComponents()));
}
return UClassType.create(
type.tsym.getQualifiedName().toString(), templateTypes(type.getTypeArguments()));
}
@Override
public UWildcardType visitWildcardType(WildcardType type, Void v) {
return UWildcardType.create(type.kind, type.type.accept(this, null));
}
@Override
public UTypeVar visitTypeVar(TypeVar type, Void v) {
/*
* In order to handle recursively bounded type variables without a stack overflow, we first
* cache a type var with no bounds, then we template the bounds.
*/
TypeSymbol tsym = type.asElement();
if (typeVariables.containsKey(tsym)) {
return typeVariables.get(tsym);
}
UTypeVar var = UTypeVar.create(tsym.getSimpleName().toString());
typeVariables.put(
tsym, var); // so the type variable can be used recursively in the bounds
var.setLowerBound(type.getLowerBound().accept(this, null));
var.setUpperBound(type.getUpperBound().accept(this, null));
return var;
}
@Override
public UForAll visitForAll(ForAll type, Void v) {
ImmutableList<UTypeVar> vars =
cast(templateTypes(type.getTypeVariables()), UTypeVar.class);
return UForAll.create(vars, type.qtype.accept(this, null));
}
};
@SuppressWarnings("unchecked")
public static ImmutableClassToInstanceMap<Annotation> annotationMap(Symbol symbol) {
ImmutableClassToInstanceMap.Builder<Annotation> builder = ImmutableClassToInstanceMap.builder();
for (Compound compound : symbol.getAnnotationMirrors()) {
String annotationClassName =
classNameFrom((TypeElement) compound.getAnnotationType().asElement());
try {
Class<? extends Annotation> annotationClazz =
Class.forName(annotationClassName).asSubclass(Annotation.class);
builder.put(
(Class) annotationClazz,
AnnotationProxyMaker.generateAnnotation(compound, annotationClazz));
} catch (ClassNotFoundException e) {
String friendlyMessage =
"Tried to instantiate an instance of the annotation "
+ annotationClassName
+ " while processing "
+ symbol.getSimpleName()
+ ", but the annotation class file was not present on the classpath.";
throw new LinkageError(friendlyMessage, e);
}
}
return builder.build();
}
// Class.forName() needs nested classes as "foo.Bar$Baz$Quux", not "foo.Bar.Baz.Quux"
// (which is what getQualifiedName() returns).
private static String classNameFrom(TypeElement type) {
// Get the full type name (e.g. "foo.Bar.Baz.Quux") before walking up the hierarchy.
String typeName = type.getQualifiedName().toString();
// Find outermost enclosing type (e.g. "foo.Bar" in our example), possibly several levels up.
// Packages enclose types, so we cannot just wait until we hit null.
while (type.getEnclosingElement().getKind() == ElementKind.CLASS) {
type = (TypeElement) type.getEnclosingElement();
}
// Start with outermost class name and append remainder of full type name with '.' -> '$'
String className = type.getQualifiedName().toString();
return className + typeName.substring(className.length()).replace('.', '$');
}
}
| 37,250
| 37.562112
| 101
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UBlock.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.refaster;
import com.google.auto.value.AutoValue;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCBlock;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.util.ListBuffer;
import java.util.List;
/**
* {@link UTree} representation of a {@link BlockTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UBlock extends USimpleStatement implements BlockTree {
public static UBlock create(List<UStatement> statements) {
return new AutoValue_UBlock(ImmutableList.copyOf(statements));
}
public static UBlock create(UStatement... statements) {
return create(ImmutableList.copyOf(statements));
}
@Override
public abstract ImmutableList<UStatement> getStatements();
static Choice<Unifier> unifyStatementList(
Iterable<? extends UStatement> statements,
Iterable<? extends StatementTree> targets,
Unifier unifier) {
Choice<UnifierWithUnconsumedStatements> choice =
Choice.of(UnifierWithUnconsumedStatements.create(unifier, ImmutableList.copyOf(targets)));
for (UStatement statement : statements) {
choice = choice.thenChoose(statement);
}
return choice.thenOption(
(UnifierWithUnconsumedStatements state) ->
state.unconsumedStatements().isEmpty()
? Optional.of(state.unifier())
: Optional.<Unifier>absent());
}
static com.sun.tools.javac.util.List<JCStatement> inlineStatementList(
Iterable<? extends UStatement> statements, Inliner inliner)
throws CouldNotResolveImportException {
ListBuffer<JCStatement> buffer = new ListBuffer<>();
for (UStatement statement : statements) {
buffer.appendList(statement.inlineStatements(inliner));
}
return buffer.toList();
}
@Override
public Choice<Unifier> visitBlock(BlockTree block, Unifier unifier) {
return unifyStatementList(getStatements(), block.getStatements(), unifier);
}
@Override
public JCBlock inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner.maker().Block(0, inlineStatementList(getStatements(), inliner));
}
@Override
public Kind getKind() {
return Kind.BLOCK;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitBlock(this, data);
}
@Override
public boolean isStatic() {
return false;
}
}
| 3,226
| 31.59596
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UWildcardType.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.refaster;
import static com.google.errorprone.refaster.Unifier.unifications;
import com.google.auto.value.AutoValue;
import com.sun.tools.javac.code.BoundKind;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.WildcardType;
/**
* {@link UType} version of {@link WildcardType}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UWildcardType extends UType {
public static UWildcardType create(BoundKind boundKind, UType bound) {
return new AutoValue_UWildcardType(boundKind, bound);
}
/** This corresponds to a plain ? wildcard. */
public static UWildcardType create() {
return create(BoundKind.UNBOUND, UClassType.create("java.lang.Object"));
}
abstract BoundKind boundKind();
abstract UType bound();
@Override
public Choice<Unifier> visitWildcardType(WildcardType wildcard, Unifier unifier) {
return Choice.condition(boundKind().equals(wildcard.kind), unifier)
.thenChoose(unifications(bound(), wildcard.type));
}
@Override
public Type inline(Inliner inliner) throws CouldNotResolveImportException {
return new WildcardType(bound().inline(inliner), boundKind(), inliner.symtab().boundClass);
}
}
| 1,850
| 31.473684
| 95
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UIf.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.refaster;
import com.google.auto.value.AutoValue;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.errorprone.refaster.ControlFlowVisitor.Result;
import com.sun.source.tree.IfTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.util.List;
import javax.annotation.Nullable;
/**
* {@link UTree} representation of an {@link IfTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UIf implements UStatement, IfTree {
public static UIf create(
UExpression condition, UStatement thenStatement, UStatement elseStatement) {
return new AutoValue_UIf(condition, thenStatement, elseStatement);
}
@Override
public abstract UExpression getCondition();
@Override
public abstract UStatement getThenStatement();
@Override
@Nullable
public abstract UStatement getElseStatement();
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitIf(this, data);
}
@Override
public Kind getKind() {
return Kind.IF;
}
private static Function<Unifier, Choice<Unifier>> unifyUStatementWithSingleStatement(
@Nullable UStatement toUnify, @Nullable StatementTree target) {
return (Unifier unifier) -> {
if (toUnify == null) {
return (target == null) ? Choice.of(unifier) : Choice.<Unifier>none();
}
List<StatementTree> list = (target == null) ? List.<StatementTree>nil() : List.of(target);
return toUnify
.apply(UnifierWithUnconsumedStatements.create(unifier, list))
.condition(s -> s.unconsumedStatements().isEmpty())
.transform(UnifierWithUnconsumedStatements::unifier);
};
}
@Override
@Nullable
public Choice<UnifierWithUnconsumedStatements> apply(UnifierWithUnconsumedStatements state) {
ImmutableList<? extends StatementTree> unconsumedStatements = state.unconsumedStatements();
if (unconsumedStatements.isEmpty()) {
return Choice.none();
}
ImmutableList<? extends StatementTree> unconsumedStatementsTail =
unconsumedStatements.subList(1, unconsumedStatements.size());
StatementTree firstStatement = unconsumedStatements.get(0);
if (firstStatement.getKind() != Kind.IF) {
return Choice.none();
}
IfTree ifTree = (IfTree) firstStatement;
Unifier unifier = state.unifier();
Choice<UnifierWithUnconsumedStatements> forwardMatch =
getCondition()
.unify(ifTree.getCondition(), unifier.fork())
.thenChoose(
unifyUStatementWithSingleStatement(getThenStatement(), ifTree.getThenStatement()))
.thenChoose(
unifierAfterThen -> {
if (getElseStatement() != null
&& ifTree.getElseStatement() == null
&& ControlFlowVisitor.INSTANCE.visitStatement(ifTree.getThenStatement())
== Result.ALWAYS_RETURNS) {
Choice<UnifierWithUnconsumedStatements> result =
getElseStatement()
.apply(
UnifierWithUnconsumedStatements.create(
unifierAfterThen.fork(), unconsumedStatementsTail));
if (getElseStatement() instanceof UBlock) {
Choice<UnifierWithUnconsumedStatements> alternative =
Choice.of(
UnifierWithUnconsumedStatements.create(
unifierAfterThen.fork(), unconsumedStatementsTail));
for (UStatement stmt : ((UBlock) getElseStatement()).getStatements()) {
alternative = alternative.thenChoose(stmt);
}
result = result.or(alternative);
}
return result;
} else {
return unifyUStatementWithSingleStatement(
getElseStatement(), ifTree.getElseStatement())
.apply(unifierAfterThen)
.transform(
unifierAfterElse ->
UnifierWithUnconsumedStatements.create(
unifierAfterElse, unconsumedStatementsTail));
}
});
Choice<UnifierWithUnconsumedStatements> backwardMatch =
getCondition()
.negate()
.unify(ifTree.getCondition(), unifier.fork())
.thenChoose(
unifierAfterCond -> {
if (getElseStatement() == null) {
return Choice.none();
}
return getElseStatement()
.apply(
UnifierWithUnconsumedStatements.create(
unifierAfterCond, List.of(ifTree.getThenStatement())))
.thenOption(
(UnifierWithUnconsumedStatements stateAfterThen) ->
stateAfterThen.unconsumedStatements().isEmpty()
? Optional.of(stateAfterThen.unifier())
: Optional.<Unifier>absent());
})
.thenChoose(
unifierAfterThen -> {
if (ifTree.getElseStatement() == null
&& ControlFlowVisitor.INSTANCE.visitStatement(ifTree.getThenStatement())
== Result.ALWAYS_RETURNS) {
Choice<UnifierWithUnconsumedStatements> result =
getThenStatement()
.apply(
UnifierWithUnconsumedStatements.create(
unifierAfterThen.fork(), unconsumedStatementsTail));
if (getThenStatement() instanceof UBlock) {
Choice<UnifierWithUnconsumedStatements> alternative =
Choice.of(
UnifierWithUnconsumedStatements.create(
unifierAfterThen.fork(), unconsumedStatementsTail));
for (UStatement stmt : ((UBlock) getThenStatement()).getStatements()) {
alternative = alternative.thenChoose(stmt);
}
result = result.or(alternative);
}
return result;
} else {
return unifyUStatementWithSingleStatement(
getThenStatement(), ifTree.getElseStatement())
.apply(unifierAfterThen)
.transform(
unifierAfterElse ->
UnifierWithUnconsumedStatements.create(
unifierAfterElse, unconsumedStatementsTail));
}
});
return forwardMatch.or(backwardMatch);
}
@Override
public List<JCStatement> inlineStatements(Inliner inliner) throws CouldNotResolveImportException {
return List.<JCStatement>of(
inliner
.maker()
.If(
getCondition().inline(inliner),
Iterables.getOnlyElement(getThenStatement().inlineStatements(inliner)),
(getElseStatement() == null)
? null
: Iterables.getOnlyElement(getElseStatement().inlineStatements(inliner))));
}
}
| 8,394
| 41.831633
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/CouldNotResolveImportException.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.refaster;
/**
* Exception thrown when a class symbol could not be resolved by the compiler.
*
* @author Louis Wasserman
*/
public class CouldNotResolveImportException extends Exception {
public CouldNotResolveImportException(CharSequence message) {
super(message.toString());
}
}
| 930
| 31.103448
| 78
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UNewClass.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.refaster;
import static com.google.errorprone.refaster.Unifier.unifications;
import static com.google.errorprone.refaster.Unifier.unifyNullable;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCNewClass;
import java.util.List;
import javax.annotation.Nullable;
/**
* {@link UTree} version of {@link NewClassTree}, which represents a constructor invocation.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UNewClass extends UExpression implements NewClassTree {
public static UNewClass create(
UExpression enclosingExpression,
List<? extends UExpression> typeArguments,
UExpression identifier,
List<UExpression> arguments,
@Nullable UClassDecl classBody) {
return new AutoValue_UNewClass(
enclosingExpression,
ImmutableList.copyOf(typeArguments),
identifier,
ImmutableList.copyOf(arguments),
classBody);
}
public static UNewClass create(
List<? extends UExpression> typeArguments, UExpression identifier, UExpression... arguments) {
return create(null, typeArguments, identifier, ImmutableList.copyOf(arguments), null);
}
public static UNewClass create(UExpression identifier, UExpression... arguments) {
return create(ImmutableList.<UExpression>of(), identifier, arguments);
}
@Override
@Nullable
public abstract UExpression getEnclosingExpression();
/**
* Note: these are not the type arguments to the class, but to the constructor, for those
* extremely rare constructors that look like e.g. {@code <E> Foo(E e)}, where the type parameter
* is for the constructor alone and not the class.
*/
@Override
public abstract ImmutableList<UExpression> getTypeArguments();
@Override
public abstract UExpression getIdentifier();
@Override
public abstract ImmutableList<UExpression> getArguments();
@Override
@Nullable
public abstract UClassDecl getClassBody();
@Override
@Nullable
public Choice<Unifier> visitNewClass(NewClassTree newClass, @Nullable Unifier unifier) {
return unifyNullable(unifier, getEnclosingExpression(), newClass.getEnclosingExpression())
.thenChoose(unifications(getTypeArguments(), newClass.getTypeArguments()))
.thenChoose(unifications(getIdentifier(), newClass.getIdentifier()))
.thenChoose(unifications(getClassBody(), newClass.getClassBody()))
.thenChoose(
unifications(getArguments(), newClass.getArguments(), /* allowVarargs= */ true));
}
@Override
public Kind getKind() {
return Kind.NEW_CLASS;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitNewClass(this, data);
}
@Override
public JCNewClass inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.NewClass(
(getEnclosingExpression() == null) ? null : getEnclosingExpression().inline(inliner),
inliner.<JCExpression>inlineList(getTypeArguments()),
getIdentifier().inline(inliner),
inliner.<JCExpression>inlineList(getArguments()),
(getClassBody() == null) ? null : getClassBody().inline(inliner));
}
}
| 4,057
| 33.683761
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/Choice.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.refaster;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.ForOverride;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
/**
* A representation of a choice with zero or more options, which may be evaluated lazily or
* strictly.
*
* <p>This resembles the list monad in Haskell.
*
* @author lowasser@google.com (Louis Wasserman)
*/
public abstract class Choice<T> {
/*
* This is currently implemented in terms of Iterators, but this may change in future, e.g. to a
* Stream-based implementation.
*
* Special-casing operations for Choice.none and Choice.single, which are by far the most common
* cases, avoids overly nested results.
*/
private static final Choice<Object> NONE =
new Choice<Object>() {
@Override
protected Iterator<Object> iterator() {
return Collections.emptyIterator();
}
@Override
public <R> Choice<R> thenChoose(Function<? super Object, Choice<R>> function) {
checkNotNull(function);
return none();
}
@Override
public <R> Choice<R> thenOption(Function<? super Object, Optional<R>> function) {
checkNotNull(function);
return none();
}
@Override
public <R> Choice<R> transform(Function<? super Object, R> function) {
checkNotNull(function);
return none();
}
@Override
public Choice<Object> or(Choice<Object> other) {
return checkNotNull(other);
}
@CanIgnoreReturnValue
@Override
public Choice<Object> condition(Predicate<? super Object> predicate) {
checkNotNull(predicate);
return this;
}
@Override
public String toString() {
return "Choice.NONE";
}
};
/** The empty {@code Choice}. */
@SuppressWarnings("unchecked")
public static <T> Choice<T> none() {
return (Choice) NONE;
}
/** Returns a {@code Choice} with only one option, {@code t}. */
public static <T> Choice<T> of(T t) {
checkNotNull(t);
return new Choice<T>() {
@Override
protected Iterator<T> iterator() {
return Iterators.singletonIterator(t);
}
@Override
public Optional<T> first() {
return Optional.of(t);
}
@Override
public Choice<T> condition(Predicate<? super T> predicate) {
return predicate.apply(t) ? this : Choice.<T>none();
}
@Override
public <R> Choice<R> thenChoose(Function<? super T, Choice<R>> function) {
return function.apply(t);
}
@Override
public <R> Choice<R> thenOption(Function<? super T, Optional<R>> function) {
return fromOptional(function.apply(t));
}
@Override
public <R> Choice<R> transform(Function<? super T, R> function) {
return of(function.apply(t));
}
@Override
public String toString() {
return String.format("Choice.of(%s)", t);
}
};
}
/**
* Returns a {@code Choice} with {@code t} as an option if {@code condition}, and no options
* otherwise.
*/
public static <T> Choice<T> condition(boolean condition, T t) {
return condition ? of(t) : Choice.<T>none();
}
/**
* Returns a choice of the optional value, if it is present, or the empty choice if it is absent.
*/
public static <T> Choice<T> fromOptional(Optional<T> optional) {
return optional.isPresent() ? of(optional.get()) : Choice.<T>none();
}
public static <T> Choice<T> from(Collection<T> choices) {
switch (choices.size()) {
case 0:
return none();
case 1:
return of(Iterables.getOnlyElement(choices));
default:
return new Choice<T>() {
@Override
protected Iterator<T> iterator() {
return choices.iterator();
}
@Override
public String toString() {
return String.format("Choice.from(%s)", choices);
}
};
}
}
/** Returns a choice between any of the options from any of the specified choices. */
public static <T> Choice<T> any(Collection<Choice<T>> choices) {
return from(choices).thenChoose(Functions.<Choice<T>>identity());
}
private Choice() {}
@VisibleForTesting
Iterable<T> asIterable() {
return this::iterator;
}
// Currently, this is implemented with an Iterator, but that may change in future!
@ForOverride
protected abstract Iterator<T> iterator();
@Override
public String toString() {
return Iterables.toString(asIterable());
}
/** Returns the first valid option from this {@code Choice}. */
public Optional<T> first() {
Iterator<T> itr = iterator();
return itr.hasNext() ? Optional.of(itr.next()) : Optional.<T>absent();
}
/**
* Returns all the choices obtained by choosing from this {@code Choice} and then choosing from
* the {@code Choice} yielded by this function on the result.
*
* <p>The function may be applied lazily or immediately, at the discretion of the implementation.
*
* <p>This is the monadic bind for {@code Choice}.
*/
public <R> Choice<R> thenChoose(Function<? super T, Choice<R>> function) {
checkNotNull(function);
if (Thread.interrupted()) {
throw new RuntimeException(new InterruptedException());
}
Choice<T> thisChoice = this;
return new Choice<R>() {
@Override
protected Iterator<R> iterator() {
if (Thread.interrupted()) {
throw new RuntimeException(new InterruptedException());
}
return Iterators.concat(
Iterators.transform(thisChoice.iterator(), (T t) -> function.apply(t).iterator()));
}
};
}
/**
* Returns all the choices obtained by choosing from this {@code Choice} and yielding a present
* {@code Optional}.
*
* <p>The function may be applied lazily or immediately, at the discretion of the implementation.
*/
public <R> Choice<R> thenOption(Function<? super T, Optional<R>> function) {
checkNotNull(function);
Choice<T> thisChoice = this;
return new Choice<R>() {
@Override
protected Iterator<R> iterator() {
return Optional.presentInstances(Iterables.transform(thisChoice.asIterable(), function))
.iterator();
}
};
}
/** Maps the choices with the specified function. */
public <R> Choice<R> transform(Function<? super T, R> function) {
checkNotNull(function);
Choice<T> thisChoice = this;
return new Choice<R>() {
@Override
protected Iterator<R> iterator() {
return Iterators.transform(thisChoice.iterator(), function);
}
};
}
/** Returns a choice of the options from this {@code Choice} or from {@code other}. */
public Choice<T> or(Choice<T> other) {
checkNotNull(other);
if (other == none()) {
return this;
} else {
Choice<T> thisChoice = this;
return new Choice<T>() {
@Override
protected Iterator<T> iterator() {
return Iterators.concat(thisChoice.iterator(), other.iterator());
}
@Override
public String toString() {
return String.format("%s.or(%s)", thisChoice, other);
}
};
}
}
/** Returns this choice if {@code condition}, otherwise the empty choice. */
public Choice<T> condition(boolean condition) {
return condition ? this : Choice.<T>none();
}
/** Filters the choices to those that satisfy the provided {@code Predicate}. */
public Choice<T> condition(Predicate<? super T> predicate) {
checkNotNull(predicate);
Choice<T> thisChoice = this;
return new Choice<T>() {
@Override
protected Iterator<T> iterator() {
return Iterators.filter(thisChoice.iterator(), predicate);
}
@Override
public String toString() {
return String.format("%s.condition(%s)", thisChoice, predicate);
}
};
}
}
| 9,064
| 28.819079
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UTree.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.refaster;
import com.sun.source.tree.Tree;
import com.sun.source.util.SimpleTreeVisitor;
import com.sun.tools.javac.tree.JCTree;
import javax.annotation.Nullable;
/**
* A serializable representation of a template syntax tree which can be unified with a target AST
* and inlined based on a set of substitutions.
*
* @param <T> The type this tree inlines to.
* @author Louis Wasserman (lowasser@google.com)
*/
public abstract class UTree<T extends JCTree> extends SimpleTreeVisitor<Choice<Unifier>, Unifier>
implements Unifiable<Tree>, Inlineable<T>, Tree {
@Override
public Choice<Unifier> unify(@Nullable Tree target, Unifier unifier) {
return (target != null) ? target.accept(this, unifier) : Choice.<Unifier>none();
}
@Override
protected Choice<Unifier> defaultAction(Tree node, Unifier unifier) {
return Choice.none();
}
}
| 1,496
| 33.813953
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/Refaster.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.refaster;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
/**
* Static utilities to indicate special handling in Refaster templates.
*
* @author lowasser@google.com (Louis Wasserman)
*/
public class Refaster {
private Refaster() {}
/**
* Indicates that Refaster should treat this {@code @Repeated} argument specifically as a varargs
* argument.
*
* <p>For example, you might write
*
* <pre>{@code
* @BeforeTemplate void something(@Repeated T arg) {
* Stream.of(asVarargs(arg)); // doesn't use the Stream.of(T) overload, but Stream.of(T...)
* }
* }</pre>
*/
public static <T> T[] asVarargs(T arg) {
throw new UnsupportedOperationException();
}
/**
* Indicates that Refaster should attempt to match a target expression against each of the
* specified template expressions, in order, and succeed at the first match.
*
* <p>This method should only be used in Refaster templates, but should never actually be run.
*
* <p>For example, instead of writing
*
* <pre>{@code
* @BeforeTemplate <E> List<E> copyOfSingleton(E element) {
* return ImmutableList.copyOf(Collections.singletonList(element));
* }
* @BeforeTemplate <E> List<E> copyOfArrayList(E element) {
* return ImmutableList.copyOf(Lists.newArrayList(element));
* }
* }</pre>
*
* <p>one could alternately write
*
* <pre>{@code
* @BeforeTemplate <E> List<E> singleton(E element) {
* return ImmutableList.copyOf(Refaster.anyOf(
* Collections.singletonList(element),
* Lists.newArrayList(element)));
* }
* }</pre>
*/
@SafeVarargs
@CanIgnoreReturnValue
public static <T> T anyOf(T... expressions) {
throw new UnsupportedOperationException();
}
/**
* This is a placeholder for the Java instanceof operator that can be used with Refaster type
* variables. The type argument must always be specified explicitly, e.g. {@code
* Refaster.<String>isInstance(o)}.
*
* <p>For example, instead of writing the broken
*
* <pre>{@code
* @AfterTemplate <T> boolean instanceOf(Object o) {
* return o instanceof T; // you want to match this, but it won't compile
* }
* }</pre>
*
* <p>you would instead write
*
* <pre>{@code
* @AfterTemplate <T> boolean instanceOf(Object o) {
* return Refaster.<T>isInstance(o); // generates the replacement "o instanceof T"
* }
* }</pre>
*
* @throws IllegalArgumentException if T is not specified explicitly.
*/
public static <T> boolean isInstance(Object o) {
// real code wouldn't have an unused type parameter (T) or an unused argument (o)
throw new UnsupportedOperationException(o.toString());
}
/**
* This is a placeholder for {@code new T[size]}. The type argument must always be specified
* explicitly, e.g. {@code Refaster.<String>newArray(10)}.
*
* <p>For example, instead of writing the broken
*
* <pre>{@code
* @AfterTemplate <T> T[] newTArray(int size) {
* return new T[size]; // you want to generate this code, but it won't compile
* }
* }</pre>
*
* <p>you would instead write
*
* <pre>{@code
* @AfterTemplate <T> T[] newTArray(int size) {
* return Refaster.<T>newArray(size);
* }
* }</pre>
*
* @throws IllegalArgumentException if T is not specified explicitly.
*/
public static <T> T[] newArray(int size) {
throw new UnsupportedOperationException(Integer.toString(size));
}
/**
* This is a placeholder for the expression T.class. The type argument must always be specified
* explicitly, e.g. {@code Refaster.<String>clazz()}.
*
* <p>For example, instead of writing the broken
*
* <pre>{@code
* @AfterTemplate <T> T[] getEnumConstants() {
* return T.class.getEnumConstants(); // you want to inline this, but it won't compile
* }
* }</pre>
*
* you would instead write
*
* <pre>{@code
* @AfterTemplate <T> T[] getEnumConstants() {
* return Refaster.<T>clazz().getEnumConstants();
* }
* }</pre>
*
* @throws IllegalArgumentException if T is not specified explicitly.
*/
public static <T> Class<T> clazz() {
throw new UnsupportedOperationException();
}
/**
* This is a placeholder for the expression E.valueOf(string). The type argument must always be
* specified explicitly, e.g. {@code Refaster.<RoundingMode>valueOf(string)}.
*
* <p>For example, instead of writing the broken
*
* <pre>{@code
* @BeforeTemplate <E extends Enum<E>> E valueOf(String str) {
* return E.valueOf(str);
* }
* }</pre>
*
* <p>you would instead write
*
* <pre>{@code
* @BeforeTemplate <E extends Enum<E>> E valueOf(String str) {
* return Refaster.<E>enumValueOf(str);
* }
* }</pre>
*
* @throws IllegalArgumentException if E is not specified explicitly.
*/
public static <E extends Enum<E>> E enumValueOf(String string) {
throw new UnsupportedOperationException();
}
/**
* This is a special method to emit a comment before an expression. The comment argument must
* always be a string literal. This method cannot be static imported.
*
* <p>For example, instead of writing
*
* <pre>{@code
* @AfterTemplate int lengthWithComment(String str) {
* return /* comment \*\/ str.length();
* }
* }</pre>
*
* <p>you would instead write
*
* <pre>{@code
* @AfterTemplate int lengthWithComment(String str) {
* return Refaster.emitCommentBefore("comment", str.length());
* }
* }</pre>
*/
public static <T> T emitCommentBefore(String literal, T expression) {
throw new UnsupportedOperationException();
}
/**
* This is a special method to emit a one-line comment. The comment argument must always be a
* string literal. This method cannot be static imported.
*
* <p>For example, instead of writing
*
* <pre>{@code
* @AfterTemplate void printWithComment(String str) {
* // comment
* System.out.println(str);
* }
* }</pre>
*
* <p>you would instead write
*
* <pre>{@code
* @AfterTemplate void printWithComment(String str) {
* Refaster.emitComment("comment");
* System.out.println(str);
* }
* }</pre>
*/
public static void emitComment(String literal) {
throw new UnsupportedOperationException();
}
}
| 7,012
| 28.970085
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UArrayTypeTree.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.refaster;
import com.google.auto.value.AutoValue;
import com.sun.source.tree.ArrayTypeTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCArrayTypeTree;
import javax.annotation.Nullable;
/**
* {@link UTree} version of {@link ArrayTypeTree}. This is the AST representation of {@link
* UArrayType}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UArrayTypeTree extends UExpression implements ArrayTypeTree {
public static UArrayTypeTree create(UExpression elementType) {
return new AutoValue_UArrayTypeTree(elementType);
}
@Override
public abstract UExpression getType();
@Override
@Nullable
public Choice<Unifier> visitArrayType(ArrayTypeTree tree, @Nullable Unifier unifier) {
return getType().unify(tree.getType(), unifier);
}
@Override
public Kind getKind() {
return Kind.ARRAY_TYPE;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitArrayType(this, data);
}
@Override
public JCArrayTypeTree inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner.maker().TypeArray(getType().inline(inliner));
}
}
| 1,835
| 29.098361
| 91
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UFreeIdent.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.refaster;
import com.google.auto.value.AutoValue;
import com.google.common.collect.Iterables;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.util.Names;
import javax.annotation.Nullable;
/**
* Free identifier that can be bound to any expression of the appropriate type.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
public abstract class UFreeIdent extends UIdent {
static class Key extends Bindings.Key<JCExpression> {
Key(CharSequence name) {
super(name.toString());
}
}
public static UFreeIdent create(CharSequence identifier) {
return new AutoValue_UFreeIdent(StringName.of(identifier));
}
@Override
public abstract StringName getName();
public Key key() {
return new Key(getName());
}
@Override
public JCExpression inline(Inliner inliner) {
return inliner.getBinding(key());
}
private static boolean trueOrNull(@Nullable Boolean condition) {
return condition == null || condition;
}
@Override
public Choice<Unifier> visitIdentifier(IdentifierTree node, Unifier unifier) {
Names names = Names.instance(unifier.getContext());
return node.getName().equals(names._super)
? Choice.<Unifier>none()
: defaultAction(node, unifier);
}
@Override
protected Choice<Unifier> defaultAction(Tree target, Unifier unifier) {
if (target instanceof JCExpression) {
JCExpression expression = (JCExpression) target;
JCExpression currentBinding = unifier.getBinding(key());
// Check that the expression does not reference any template-local variables.
boolean isGood =
trueOrNull(
new TreeScanner<Boolean, Void>() {
@Override
public Boolean reduce(@Nullable Boolean left, @Nullable Boolean right) {
return trueOrNull(left) && trueOrNull(right);
}
@Override
public Boolean visitIdentifier(IdentifierTree ident, Void v) {
Symbol identSym = ASTHelpers.getSymbol(ident);
for (ULocalVarIdent.Key key :
Iterables.filter(unifier.getBindings().keySet(), ULocalVarIdent.Key.class)) {
if (identSym == unifier.getBinding(key).getSymbol()) {
return false;
}
}
return true;
}
}.scan(expression, null));
if (!isGood) {
return Choice.none();
} else if (currentBinding == null) {
unifier.putBinding(key(), expression);
return Choice.of(unifier);
} else if (currentBinding.toString().equals(expression.toString())) {
// TODO(lowasser): try checking types here in a way that doesn't reject
// different wildcard captures
// If it's the same code, treat it as the same expression.
return Choice.of(unifier);
}
}
return Choice.none();
}
}
| 3,824
| 32.552632
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UType.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.refaster;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import javax.annotation.Nullable;
/**
* A serializable representation of a type template, used for enforcing type constraints on target
* ASTs.
*
* @author Louis Wasserman
*/
public abstract class UType extends Types.SimpleVisitor<Choice<Unifier>, Unifier>
implements Unifiable<Type>, Inlineable<Type> {
@Override
@Nullable
public Choice<Unifier> visitType(Type t, @Nullable Unifier unifier) {
return Choice.none();
}
@Override
public final Choice<Unifier> unify(Type target, Unifier unifier) {
return (target != null) ? target.accept(this, unifier) : Choice.<Unifier>none();
}
}
| 1,339
| 30.162791
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/BlockTemplateMatch.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.refaster;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCBlock;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import java.io.IOException;
/**
* A representation of a match against a {@code BlockTemplate}. The "location" is the first
* statement of the match.
*
* @author lowasser@google.com (Louis Wasserman)
*/
class BlockTemplateMatch extends TemplateMatch {
private final ImmutableList<JCStatement> statements;
public BlockTemplateMatch(JCBlock block, Unifier unifier, int start, int end) {
super(checkNotNull(block).getStatements().get(start), unifier);
this.statements = ImmutableList.copyOf(block.getStatements().subList(start, end));
}
public ImmutableList<JCStatement> getStatements() {
return statements;
}
@Override
public String getRange(JCCompilationUnit unit) {
try {
CharSequence sequence = unit.getSourceFile().getCharContent(true);
JCTree firstStatement = statements.get(0);
JCTree lastStatement = Iterables.getLast(statements);
return sequence
.subSequence(
firstStatement.getStartPosition(), lastStatement.getEndPosition(unit.endPositions))
.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| 2,142
| 33.564516
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/Unifier.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.refaster;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.errorprone.SubContext;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.Context;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
/**
* A mutable representation of an attempt to match a template source tree against a target source
* tree.
*
* @author Louis Wasserman
*/
public final class Unifier {
private final Bindings bindings;
private final Context context;
public Unifier(Context context) {
this.bindings = Bindings.create();
this.context = checkNotNull(context);
}
private Unifier(Context context, Bindings bindings) {
this.context = new SubContext(context);
this.bindings = Bindings.create(bindings);
}
/**
* Returns a {@code Unifier} containing all the bindings from this {@code Unifier}, but which can
* succeed or fail independently of this {@code Unifier}.
*/
public Unifier fork() {
return new Unifier(context, bindings);
}
public Types types() {
return Types.instance(context);
}
public JCExpression thisExpression(Type type) {
return TreeMaker.instance(context).This(type);
}
public Inliner createInliner() {
return new Inliner(context, bindings);
}
@Nullable
public <V> V getBinding(Bindings.Key<V> key) {
return bindings.getBinding(key);
}
public <V> V putBinding(Bindings.Key<V> key, V value) {
checkArgument(!bindings.containsKey(key), "Cannot bind %s more than once", key);
return bindings.putBinding(key, value);
}
public <V> V replaceBinding(Bindings.Key<V> key, V value) {
checkArgument(bindings.containsKey(key), "Binding for %s does not exist", key);
return bindings.putBinding(key, value);
}
public void clearBinding(Bindings.Key<?> key) {
bindings.remove(key);
}
public Bindings getBindings() {
return bindings.unmodifiable();
}
public Context getContext() {
return context;
}
@Override
public String toString() {
return "Unifier{" + bindings + "}";
}
public static <T, U extends Unifiable<? super T>> Function<Unifier, Choice<Unifier>> unifications(
@Nullable U unifiable, @Nullable T target) {
return (Unifier unifier) -> unifyNullable(unifier, unifiable, target);
}
public static <T, U extends Unifiable<? super T>> Choice<Unifier> unifyNullable(
Unifier unifier, @Nullable U unifiable, @Nullable T target) {
if (target == null && unifiable == null) {
return Choice.of(unifier);
} else if (target == null || unifiable == null) {
return Choice.none();
} else {
return unifiable.unify(target, unifier);
}
}
public static <T, U extends Unifiable<? super T>> Function<Unifier, Choice<Unifier>> unifications(
@Nullable List<U> toUnify, @Nullable List<? extends T> targets) {
return unifications(toUnify, targets, /* allowVarargs= */ false);
}
public static <T, U extends Unifiable<? super T>> Function<Unifier, Choice<Unifier>> unifications(
@Nullable List<U> toUnify, @Nullable List<? extends T> targets, boolean allowVarargs) {
return (Unifier unifier) -> unifyList(unifier, toUnify, targets, allowVarargs);
}
/**
* Returns all successful unification paths from the specified {@code Unifier} unifying the
* specified lists, disallowing varargs.
*/
public static <T, U extends Unifiable<? super T>> Choice<Unifier> unifyList(
Unifier unifier, @Nullable List<U> toUnify, @Nullable List<? extends T> targets) {
return unifyList(unifier, toUnify, targets, /* allowVarargs= */ false);
}
/**
* Returns all successful unification paths from the specified {@code Unifier} unifying the
* specified lists, allowing varargs if and only if {@code allowVarargs} is true.
*/
public static <T, U extends Unifiable<? super T>> Choice<Unifier> unifyList(
Unifier unifier,
@Nullable List<U> toUnify,
@Nullable List<? extends T> targets,
boolean allowVarargs) {
if (toUnify == null && targets == null) {
return Choice.of(unifier);
} else if (toUnify == null
|| targets == null
|| (allowVarargs
? toUnify.size() - 1 > targets.size()
: toUnify.size() != targets.size())) {
return Choice.none();
}
Choice<Unifier> choice = Choice.of(unifier);
int index;
for (index = 0; index < toUnify.size(); index++) {
U toUnifyNext = toUnify.get(index);
if (allowVarargs && toUnifyNext instanceof URepeated) {
URepeated repeated = (URepeated) toUnifyNext;
int startIndex = index;
return choice
.condition(index + 1 == toUnify.size())
.thenOption(
new Function<Unifier, Optional<Unifier>>() {
@Override
public Optional<Unifier> apply(Unifier unifier) {
List<JCExpression> expressions = new ArrayList<>();
for (int j = startIndex; j < targets.size(); j++) {
Optional<Unifier> forked =
repeated.unify((JCTree) targets.get(j), unifier.fork()).first();
if (!forked.isPresent()) {
return Optional.absent();
}
JCExpression boundExpr = repeated.getUnderlyingBinding(forked.get());
if (boundExpr == null) {
return Optional.absent();
}
expressions.add(boundExpr);
}
unifier.putBinding(repeated.key(), expressions);
return Optional.of(unifier);
}
});
}
if (index >= targets.size()) {
return Choice.none();
}
choice = choice.thenChoose(unifications(toUnifyNext, targets.get(index)));
}
if (index < targets.size()) {
return Choice.none();
}
return choice;
}
}
| 6,960
| 33.631841
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UForAll.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.refaster;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.ForAll;
import com.sun.tools.javac.code.Types;
import java.util.List;
/**
* {@link UType} version of {@link ForAll}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
public abstract class UForAll extends UType {
public static UForAll create(List<UTypeVar> typeVars, UType quantifiedType) {
return new AutoValue_UForAll(ImmutableList.copyOf(typeVars), quantifiedType);
}
public abstract ImmutableList<UTypeVar> getTypeVars();
public abstract UType getQuantifiedType();
@Override
public Choice<Unifier> visitForAll(ForAll target, Unifier unifier) {
Types types = unifier.types();
try {
Type myType = inline(new Inliner(unifier.getContext(), Bindings.create()));
return Choice.condition(
types.overrideEquivalent(types.erasure(myType), types.erasure(target)), unifier);
} catch (CouldNotResolveImportException e) {
return Choice.none();
}
}
@Override
public Type inline(Inliner inliner) throws CouldNotResolveImportException {
return new ForAll(inliner.<Type>inlineList(getTypeVars()), getQuantifiedType().inline(inliner));
}
}
| 1,932
| 32.327586
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UAssign.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.refaster;
import static com.google.errorprone.refaster.Unifier.unifications;
import com.google.auto.value.AutoValue;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCAssign;
/**
* {@link UTree} representation of a {@link AssignmentTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UAssign extends UExpression implements AssignmentTree {
public static UAssign create(UExpression variable, UExpression expression) {
return new AutoValue_UAssign(variable, expression);
}
@Override
public abstract UExpression getVariable();
@Override
public abstract UExpression getExpression();
@Override
public JCAssign inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner.maker().Assign(getVariable().inline(inliner), getExpression().inline(inliner));
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitAssignment(this, data);
}
@Override
public Kind getKind() {
return Kind.ASSIGNMENT;
}
@Override
public Choice<Unifier> visitAssignment(AssignmentTree assign, Unifier unifier) {
return getVariable()
.unify(assign.getVariable(), unifier)
.thenChoose(unifications(getExpression(), assign.getExpression()));
}
}
| 1,994
| 29.692308
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/ExpressionTemplateMatch.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.refaster;
import com.sun.tools.javac.tree.JCTree.JCExpression;
/**
* A complete representation of a match against an {@code ExpressionTemplate}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
class ExpressionTemplateMatch extends TemplateMatch {
public ExpressionTemplateMatch(JCExpression location, Unifier unifier) {
super(location, unifier);
}
@Override
public JCExpression getLocation() {
return (JCExpression) super.getLocation();
}
}
| 1,109
| 29
| 78
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/LocalVarBinding.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.refaster;
import com.google.auto.value.AutoValue;
import com.sun.source.tree.ModifiersTree;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.util.Name;
/**
* Binding for a local variable in a template.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
public abstract class LocalVarBinding {
public static LocalVarBinding create(VarSymbol symbol, ModifiersTree modifiers) {
return new AutoValue_LocalVarBinding(symbol, modifiers);
}
public abstract VarSymbol getSymbol();
public abstract ModifiersTree getModifiers();
public Name getName() {
return getSymbol().getSimpleName();
}
@Override
public final String toString() {
return getSymbol().getSimpleName().toString();
}
}
| 1,393
| 28.041667
| 83
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UAnnotation.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.refaster;
import static com.google.errorprone.refaster.Unifier.unifications;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import java.util.List;
import javax.annotation.Nullable;
/**
* {@link UTree} version of {@link AnnotationTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UAnnotation extends UExpression implements AnnotationTree {
public static UAnnotation create(UTree<?> annotationType, List<UExpression> arguments) {
return new AutoValue_UAnnotation(annotationType, ImmutableList.copyOf(arguments));
}
public static UAnnotation create(UTree<?> annotationType, UExpression... arguments) {
return create(annotationType, ImmutableList.copyOf(arguments));
}
@Override
public abstract UTree<?> getAnnotationType();
@Override
public abstract ImmutableList<UExpression> getArguments();
@Override
@Nullable
public Choice<Unifier> visitAnnotation(AnnotationTree annotation, Unifier unifier) {
return getAnnotationType()
.unify(annotation.getAnnotationType(), unifier)
.thenChoose(unifications(getArguments(), annotation.getArguments()));
}
@Override
public Kind getKind() {
return Kind.ANNOTATION;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitAnnotation(this, data);
}
@Override
public JCAnnotation inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.Annotation(
getAnnotationType().inline(inliner), inliner.<JCExpression>inlineList(getArguments()));
}
}
| 2,468
| 31.064935
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/USimpleStatement.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.refaster;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.sun.source.tree.StatementTree;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.util.List;
/**
* A {@code UStatement} that matches exactly one statement, and inlines to exactly one statement.
*
* @author lowasser@google.com (Louis Wasserman)
*/
abstract class USimpleStatement extends UTree<JCStatement> implements UStatement {
@Override
public List<JCStatement> inlineStatements(Inliner inliner) throws CouldNotResolveImportException {
return List.of(inline(inliner));
}
private static Function<Unifier, UnifierWithUnconsumedStatements> withUnconsumed(
java.util.List<? extends StatementTree> statements) {
return (Unifier unifier) -> UnifierWithUnconsumedStatements.create(unifier, statements);
}
@Override
public Choice<UnifierWithUnconsumedStatements> apply(UnifierWithUnconsumedStatements state) {
ImmutableList<? extends StatementTree> unconsumedStatements = state.unconsumedStatements();
if (unconsumedStatements.isEmpty()) {
return Choice.none();
}
java.util.List<? extends StatementTree> remainingStatements =
unconsumedStatements.subList(1, unconsumedStatements.size());
return unify(unconsumedStatements.get(0), state.unifier())
.transform(withUnconsumed(remainingStatements));
}
}
| 2,050
| 36.981481
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UBinary.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.refaster;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.errorprone.refaster.Unifier.unifications;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableBiMap;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCBinary;
/**
* {@link UTree} version of {@link BinaryTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UBinary extends UExpression implements BinaryTree {
static final ImmutableBiMap<Kind, JCTree.Tag> OP_CODES =
new ImmutableBiMap.Builder<Kind, JCTree.Tag>()
.put(Kind.PLUS, JCTree.Tag.PLUS)
.put(Kind.MINUS, JCTree.Tag.MINUS)
.put(Kind.MULTIPLY, JCTree.Tag.MUL)
.put(Kind.DIVIDE, JCTree.Tag.DIV)
.put(Kind.REMAINDER, JCTree.Tag.MOD)
.put(Kind.LEFT_SHIFT, JCTree.Tag.SL)
.put(Kind.RIGHT_SHIFT, JCTree.Tag.SR)
.put(Kind.UNSIGNED_RIGHT_SHIFT, JCTree.Tag.USR)
.put(Kind.OR, JCTree.Tag.BITOR)
.put(Kind.AND, JCTree.Tag.BITAND)
.put(Kind.XOR, JCTree.Tag.BITXOR)
.put(Kind.CONDITIONAL_AND, JCTree.Tag.AND)
.put(Kind.CONDITIONAL_OR, JCTree.Tag.OR)
.put(Kind.LESS_THAN, JCTree.Tag.LT)
.put(Kind.LESS_THAN_EQUAL, JCTree.Tag.LE)
.put(Kind.GREATER_THAN, JCTree.Tag.GT)
.put(Kind.GREATER_THAN_EQUAL, JCTree.Tag.GE)
.put(Kind.EQUAL_TO, JCTree.Tag.EQ)
.put(Kind.NOT_EQUAL_TO, JCTree.Tag.NE)
.buildOrThrow();
static final ImmutableBiMap<Kind, Kind> NEGATION =
new ImmutableBiMap.Builder<Kind, Kind>()
.put(Kind.LESS_THAN, Kind.GREATER_THAN_EQUAL)
.put(Kind.LESS_THAN_EQUAL, Kind.GREATER_THAN)
.put(Kind.GREATER_THAN, Kind.LESS_THAN_EQUAL)
.put(Kind.GREATER_THAN_EQUAL, Kind.LESS_THAN)
.put(Kind.EQUAL_TO, Kind.NOT_EQUAL_TO)
.put(Kind.NOT_EQUAL_TO, Kind.EQUAL_TO)
.buildOrThrow();
static final ImmutableBiMap<Kind, Kind> DEMORGAN =
new ImmutableBiMap.Builder<Kind, Kind>()
.put(Kind.CONDITIONAL_AND, Kind.CONDITIONAL_OR)
.put(Kind.CONDITIONAL_OR, Kind.CONDITIONAL_AND)
.put(Kind.AND, Kind.OR)
.put(Kind.OR, Kind.AND)
.buildOrThrow();
public static UBinary create(Kind binaryOp, UExpression lhs, UExpression rhs) {
checkArgument(
OP_CODES.containsKey(binaryOp), "%s is not a supported binary operation", binaryOp);
return new AutoValue_UBinary(binaryOp, lhs, rhs);
}
@Override
public abstract Kind getKind();
@Override
public abstract UExpression getLeftOperand();
@Override
public abstract UExpression getRightOperand();
@Override
public Choice<Unifier> visitBinary(BinaryTree binary, Unifier unifier) {
return Choice.condition(getKind().equals(binary.getKind()), unifier)
.thenChoose(unifications(getLeftOperand(), binary.getLeftOperand()))
.thenChoose(unifications(getRightOperand(), binary.getRightOperand()));
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitBinary(this, data);
}
@Override
public JCBinary inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.Binary(
OP_CODES.get(getKind()),
getLeftOperand().inline(inliner),
getRightOperand().inline(inliner));
}
@Override
public UExpression negate() {
if (NEGATION.containsKey(getKind())) {
return UBinary.create(NEGATION.get(getKind()), getLeftOperand(), getRightOperand());
} else if (DEMORGAN.containsKey(getKind())) {
return UBinary.create(
DEMORGAN.get(getKind()), getLeftOperand().negate(), getRightOperand().negate());
} else {
return super.negate();
}
}
}
| 4,589
| 35.428571
| 92
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UAnnotatedType.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.refaster;
import static com.google.errorprone.refaster.Unifier.unifications;
import static com.google.errorprone.refaster.Unifier.unifyList;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.sun.source.tree.AnnotatedTypeTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCAnnotatedType;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.util.List;
/**
* {@code UTree} representation of an {@code AnnotatedTypeTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UAnnotatedType extends UExpression implements AnnotatedTypeTree {
public static UAnnotatedType create(Iterable<UAnnotation> annotations, UExpression type) {
return new AutoValue_UAnnotatedType(ImmutableList.copyOf(annotations), type);
}
@Override
public Kind getKind() {
return Kind.ANNOTATED_TYPE;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitAnnotatedType(this, data);
}
@Override
public Choice<Unifier> visitAnnotatedType(AnnotatedTypeTree node, Unifier unifier) {
return unifyList(unifier, getAnnotations(), node.getAnnotations())
.thenChoose(unifications(getUnderlyingType(), node.getUnderlyingType()));
}
@Override
public JCAnnotatedType inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.AnnotatedType(
List.convert(JCAnnotation.class, inliner.inlineList(getAnnotations())),
getUnderlyingType().inline(inliner));
}
@Override
public abstract ImmutableList<UAnnotation> getAnnotations();
@Override
public abstract UExpression getUnderlyingType();
}
| 2,402
| 32.375
| 92
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UUnary.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.refaster;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.errorprone.refaster.Unifier.unifications;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableBiMap;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.ConditionalExpressionTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TreeVisitor;
import com.sun.source.tree.UnaryTree;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCConditional;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.TreeCopier;
import com.sun.tools.javac.tree.TreeMaker;
import javax.annotation.Nullable;
/**
* {@link UTree} version of {@link UnaryTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UUnary extends UExpression implements UnaryTree {
private static final ImmutableBiMap<Kind, JCTree.Tag> UNARY_OP_CODES =
new ImmutableBiMap.Builder<Kind, JCTree.Tag>()
.put(Kind.PREFIX_INCREMENT, JCTree.Tag.PREINC)
.put(Kind.PREFIX_DECREMENT, JCTree.Tag.PREDEC)
.put(Kind.POSTFIX_INCREMENT, JCTree.Tag.POSTINC)
.put(Kind.POSTFIX_DECREMENT, JCTree.Tag.POSTDEC)
.put(Kind.UNARY_PLUS, JCTree.Tag.POS)
.put(Kind.UNARY_MINUS, JCTree.Tag.NEG)
.put(Kind.BITWISE_COMPLEMENT, JCTree.Tag.COMPL)
.put(Kind.LOGICAL_COMPLEMENT, JCTree.Tag.NOT)
.buildOrThrow();
public static UUnary create(Kind unaryOp, UExpression expression) {
checkArgument(
UNARY_OP_CODES.containsKey(unaryOp), "%s is not a recognized unary operation", unaryOp);
return new AutoValue_UUnary(unaryOp, expression);
}
@Override
public abstract Kind getKind();
@Override
public abstract UExpression getExpression();
@Override
@Nullable
public Choice<Unifier> visitUnary(UnaryTree unary, @Nullable Unifier unifier) {
return Choice.condition(getKind().equals(unary.getKind()), unifier)
.thenChoose(
unifications(getExpression(), ASTHelpers.stripParentheses(unary.getExpression())));
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitUnary(this, data);
}
@Override
public JCExpression inline(Inliner inliner) throws CouldNotResolveImportException {
JCExpression expr = getExpression().inline(inliner);
TreeMaker maker = inliner.maker();
if (getKind() == Kind.LOGICAL_COMPLEMENT) {
return new TreeCopier<Void>(maker) {
@SuppressWarnings("unchecked")
// essentially depends on T being a superclass of JCExpression
@Override
public <T extends JCTree> T copy(T t, Void v) {
if (t instanceof BinaryTree
|| t instanceof UnaryTree
|| t instanceof ConditionalExpressionTree) {
return super.copy(t, v);
} else {
return (T) defaultNegation(t);
}
}
public JCExpression defaultNegation(Tree expr) {
return maker.Unary(JCTree.Tag.NOT, (JCExpression) expr);
}
@Override
public JCExpression visitBinary(BinaryTree tree, Void v) {
if (UBinary.DEMORGAN.containsKey(tree.getKind())) {
JCExpression negLeft = copy((JCExpression) tree.getLeftOperand());
JCExpression negRight = copy((JCExpression) tree.getRightOperand());
return maker.Binary(
UBinary.OP_CODES.get(UBinary.DEMORGAN.get(tree.getKind())), negLeft, negRight);
} else if (UBinary.NEGATION.containsKey(tree.getKind())) {
JCExpression left = (JCExpression) tree.getLeftOperand();
JCExpression right = (JCExpression) tree.getRightOperand();
return maker.Binary(
UBinary.OP_CODES.get(UBinary.NEGATION.get(tree.getKind())), left, right);
} else {
return defaultNegation(tree);
}
}
@Override
public JCExpression visitUnary(UnaryTree tree, Void v) {
if (tree.getKind() == Kind.LOGICAL_COMPLEMENT) {
return (JCExpression) tree.getExpression();
} else {
return defaultNegation(tree);
}
}
@Override
public JCConditional visitConditionalExpression(ConditionalExpressionTree tree, Void v) {
return maker.Conditional(
(JCExpression) tree.getCondition(),
copy((JCExpression) tree.getTrueExpression()),
copy((JCExpression) tree.getFalseExpression()));
}
}.copy(expr);
} else {
return inliner.maker().Unary(UNARY_OP_CODES.get(getKind()), getExpression().inline(inliner));
}
}
@Override
public UExpression negate() {
return (getKind() == Kind.LOGICAL_COMPLEMENT) ? getExpression() : super.negate();
}
}
| 5,559
| 36.567568
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UTypeVar.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.refaster;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.auto.value.AutoValue;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.TypeVar;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import javax.annotation.Nullable;
/**
* {@link UType} version of {@link TypeVar}.
*
* @author Louis Wasserman
*/
public class UTypeVar extends UType {
// This can't be @AutoValue'd, since the fields are mutable.
/** Bindings key linked to a {@code UTypeVar}. */
public static final class Key extends Bindings.Key<TypeWithExpression> {
public Key(CharSequence name) {
super(name.toString());
}
}
/** Tuple of an expression with an associated type. */
@AutoValue
public abstract static class TypeWithExpression implements Inlineable<JCExpression> {
public static TypeWithExpression create(Type type, JCExpression expression) {
return new AutoValue_UTypeVar_TypeWithExpression(type, checkNotNull(expression));
}
public static TypeWithExpression create(Type type) {
return new AutoValue_UTypeVar_TypeWithExpression(type, null);
}
public abstract Type type();
@Nullable
abstract JCExpression expression();
@Override
public JCExpression inline(Inliner inliner) {
return (expression() == null) ? inliner.inlineAsTree(type()) : expression();
}
@Override
public final String toString() {
return type().toString();
}
}
public static UTypeVar create(String name, UType lowerBound, UType upperBound) {
return new UTypeVar(name, lowerBound, upperBound);
}
public static UTypeVar create(String name, UType upperBound) {
return create(name, UPrimitiveType.NULL, upperBound);
}
public static UTypeVar create(String name) {
return create(name, UClassType.create("java.lang.Object"));
}
private final String name;
private UType lowerBound;
private UType upperBound;
private UTypeVar(String name, UType lowerBound, UType upperBound) {
this.name = checkNotNull(name);
this.lowerBound = checkNotNull(lowerBound);
this.upperBound = checkNotNull(upperBound);
}
@Override
public Choice<Unifier> visitType(Type target, Unifier unifier) {
// This is only called when we're trying to unify overloads, in which case
// type variables don't matter.
return Choice.condition(!target.isPrimitive(), unifier);
}
public Key key() {
return new Key(name);
}
public String getName() {
return name;
}
public UType getLowerBound() {
return lowerBound;
}
public UType getUpperBound() {
return upperBound;
}
/**
* @param lowerBound the lowerBound to set
*/
public void setLowerBound(UType lowerBound) {
this.lowerBound = checkNotNull(lowerBound);
}
/**
* @param upperBound the upperBound to set
*/
public void setUpperBound(UType upperBound) {
this.upperBound = checkNotNull(upperBound);
}
@Override
public Type inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner.inlineTypeVar(this);
}
@Override
public int hashCode() {
return Objects.hashCode(name);
}
@Override
public boolean equals(@Nullable Object obj) {
if (this == obj) {
return true;
} else if (obj instanceof UTypeVar) {
UTypeVar typeVar = (UTypeVar) obj;
return name.equals(typeVar.name)
&& lowerBound.equals(typeVar.lowerBound)
&& upperBound.equals(typeVar.upperBound);
}
return false;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this).add("name", name).toString();
}
}
| 4,371
| 26.670886
| 87
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UThrow.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.refaster;
import com.google.auto.value.AutoValue;
import com.sun.source.tree.ThrowTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCThrow;
import javax.annotation.Nullable;
/**
* {@link UTree} representation of a {@link ThrowTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UThrow extends USimpleStatement implements ThrowTree {
public static UThrow create(UExpression expression) {
return new AutoValue_UThrow(expression);
}
@Override
public abstract UExpression getExpression();
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitThrow(this, data);
}
@Override
public Kind getKind() {
return Kind.THROW;
}
@Override
@Nullable
public Choice<Unifier> visitThrow(ThrowTree throwStmt, @Nullable Unifier unifier) {
return getExpression().unify(throwStmt.getExpression(), unifier);
}
@Override
public JCThrow inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner.maker().Throw(getExpression().inline(inliner));
}
}
| 1,751
| 28.2
| 85
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UPrimitiveType.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.refaster;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableSet;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import javax.lang.model.type.TypeKind;
/**
* {@code UType} representation of primitive {@code Type} instances, specifically including the void
* type and the null type.
*
* @author Louis Wasserman
*/
@AutoValue
abstract class UPrimitiveType extends UType {
public static UPrimitiveType create(TypeKind typeKind) {
checkArgument(
isDeFactoPrimitive(typeKind), "Non-primitive type %s passed to UPrimitiveType", typeKind);
return new AutoValue_UPrimitiveType(typeKind);
}
public abstract TypeKind getKind();
private static final ImmutableSet<TypeKind> HONORARY_PRIMITIVES =
ImmutableSet.of(TypeKind.VOID, TypeKind.NULL);
public static final UPrimitiveType BYTE = create(TypeKind.BYTE);
public static final UPrimitiveType SHORT = create(TypeKind.SHORT);
public static final UPrimitiveType INT = create(TypeKind.INT);
public static final UPrimitiveType LONG = create(TypeKind.LONG);
public static final UPrimitiveType FLOAT = create(TypeKind.FLOAT);
public static final UPrimitiveType DOUBLE = create(TypeKind.DOUBLE);
public static final UPrimitiveType BOOLEAN = create(TypeKind.BOOLEAN);
public static final UPrimitiveType CHAR = create(TypeKind.CHAR);
public static final UPrimitiveType NULL = create(TypeKind.NULL);
public static final UPrimitiveType VOID = create(TypeKind.VOID);
public static boolean isDeFactoPrimitive(TypeKind kind) {
return kind.isPrimitive() || HONORARY_PRIMITIVES.contains(kind);
}
@Override
public Choice<Unifier> visitType(Type target, Unifier unifier) {
return Choice.condition(getKind().equals(target.getKind()), unifier);
}
@Override
public Type inline(Inliner inliner) {
Symtab symtab = inliner.symtab();
switch (getKind()) {
case BYTE:
return symtab.byteType;
case SHORT:
return symtab.shortType;
case INT:
return symtab.intType;
case LONG:
return symtab.longType;
case FLOAT:
return symtab.floatType;
case DOUBLE:
return symtab.doubleType;
case BOOLEAN:
return symtab.booleanType;
case CHAR:
return symtab.charType;
case VOID:
return symtab.voidType;
case NULL:
return symtab.botType;
default:
throw new AssertionError();
}
}
}
| 3,192
| 32.260417
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/StringName.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.refaster;
import com.google.auto.value.AutoValue;
import javax.annotation.Nullable;
import javax.lang.model.element.Name;
/**
* A simple wrapper to view a {@code String} as a {@code Name}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
public abstract class StringName
implements Name, Unifiable<Name>, Inlineable<com.sun.tools.javac.util.Name> {
public static StringName of(CharSequence contents) {
return new AutoValue_StringName(contents.toString());
}
abstract String contents();
@Override
public final String toString() {
return contents();
}
@Override
public int length() {
return contents().length();
}
@Override
public char charAt(int index) {
return contents().charAt(index);
}
@Override
public CharSequence subSequence(int beginIndex, int endIndex) {
return contents().subSequence(beginIndex, endIndex);
}
@Override
public boolean contentEquals(@Nullable CharSequence cs) {
return cs != null && contents().contentEquals(cs);
}
@Override
public Choice<Unifier> unify(@Nullable Name target, Unifier unifier) {
return Choice.condition(contentEquals(target), unifier);
}
@Override
public com.sun.tools.javac.util.Name inline(Inliner inliner) {
return inliner.asName(contents());
}
}
| 1,941
| 25.972222
| 81
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/RefasterScanner.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.refaster;
import static com.google.errorprone.util.ASTHelpers.stringContainsComments;
import com.google.auto.value.AutoValue;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.DescriptionListener;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.DoWhileLoopTree;
import com.sun.source.tree.IfTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.tree.SynchronizedTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.tree.WhileLoopTree;
import com.sun.source.util.SimpleTreeVisitor;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.ListBuffer;
/**
* Scanner that outputs suggested fixes generated by a {@code RefasterMatcher}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class RefasterScanner<M extends TemplateMatch, T extends Template<M>>
extends TreeScanner<Void, Context> {
static <M extends TemplateMatch, T extends Template<M>> RefasterScanner<M, T> create(
RefasterRule<M, T> rule, DescriptionListener listener) {
return new AutoValue_RefasterScanner<>(rule, listener);
}
abstract RefasterRule<M, T> rule();
abstract DescriptionListener listener();
@Override
public Void visitClass(ClassTree node, Context context) {
if (isSuppressed(node, context)) {
return null;
}
Symbol sym = ASTHelpers.getSymbol(node);
if (sym == null || !sym.getQualifiedName().contentEquals(rule().qualifiedTemplateClass())) {
ListBuffer<JCStatement> statements = new ListBuffer<>();
for (Tree tree : node.getMembers()) {
if (tree instanceof JCStatement) {
statements.append((JCStatement) tree);
} else {
tree.accept(this, context);
}
}
scan(TreeMaker.instance(context).Block(0, statements.toList()), context);
}
return null;
}
@Override
public Void visitMethod(MethodTree node, Context context) {
if (isSuppressed(node, context)) {
return null;
}
return super.visitMethod(node, context);
}
@Override
public Void visitVariable(VariableTree node, Context context) {
if (isSuppressed(node, context)) {
return null;
}
return super.visitVariable(node, context);
}
@Override
public Void scan(Tree tree, Context context) {
if (tree == null) {
return null;
}
JCCompilationUnit compilationUnit = context.get(JCCompilationUnit.class);
for (T beforeTemplate : rule().beforeTemplates()) {
matchLoop:
for (M match : beforeTemplate.match((JCTree) tree, context)) {
if (rule().rejectMatchesWithComments()) {
String matchContents = match.getRange(compilationUnit);
if (stringContainsComments(matchContents, context)) {
continue matchLoop;
}
}
Description.Builder builder =
Description.builder(match.getLocation(), rule().qualifiedTemplateClass(), "", "")
.overrideSeverity(SeverityLevel.WARNING);
if (rule().afterTemplates().isEmpty()) {
builder.addFix(SuggestedFix.prefixWith(match.getLocation(), "/* match found */ "));
} else {
for (T afterTemplate : rule().afterTemplates()) {
builder.addFix(afterTemplate.replace(match));
}
}
listener().onDescribed(builder.build());
}
}
return super.scan(tree, context);
}
private static final SimpleTreeVisitor<Tree, Void> SKIP_PARENS =
new SimpleTreeVisitor<Tree, Void>() {
@Override
public Tree visitParenthesized(ParenthesizedTree node, Void v) {
return node.getExpression().accept(this, null);
}
@Override
protected Tree defaultAction(Tree node, Void v) {
return node;
}
};
/*
* Matching on the parentheses surrounding the condition of an if, while, or do-while
* is nonsensical, as those parentheses are obligatory and should never be changed.
*/
@Override
public Void visitDoWhileLoop(DoWhileLoopTree node, Context context) {
scan(node.getStatement(), context);
scan(SKIP_PARENS.visit(node.getCondition(), null), context);
return null;
}
@Override
public Void visitWhileLoop(WhileLoopTree node, Context context) {
scan(SKIP_PARENS.visit(node.getCondition(), null), context);
scan(node.getStatement(), context);
return null;
}
@Override
public Void visitSynchronized(SynchronizedTree node, Context context) {
scan(SKIP_PARENS.visit(node.getExpression(), null), context);
scan(node.getBlock(), context);
return null;
}
@Override
public Void visitIf(IfTree node, Context context) {
scan(SKIP_PARENS.visit(node.getCondition(), null), context);
scan(node.getThenStatement(), context);
scan(node.getElseStatement(), context);
return null;
}
private boolean isSuppressed(Tree node, Context context) {
return RefasterSuppressionHelper.suppressed(rule(), node, context);
}
}
| 6,139
| 32.736264
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UTypeCast.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.refaster;
import static com.google.errorprone.refaster.Unifier.unifications;
import com.google.auto.value.AutoValue;
import com.sun.source.tree.TreeVisitor;
import com.sun.source.tree.TypeCastTree;
import com.sun.tools.javac.tree.JCTree.JCTypeCast;
/**
* {@link UTree} version of {@link TypeCastTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UTypeCast extends UExpression implements TypeCastTree {
public static UTypeCast create(UTree<?> type, UExpression expression) {
return new AutoValue_UTypeCast(type, expression);
}
@Override
public abstract UTree<?> getType();
@Override
public abstract UExpression getExpression();
@Override
public Choice<Unifier> visitTypeCast(TypeCastTree cast, Unifier unifier) {
return getType()
.unify(cast.getType(), unifier)
.thenChoose(unifications(getExpression(), cast.getExpression()));
}
@Override
public Kind getKind() {
return Kind.TYPE_CAST;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitTypeCast(this, data);
}
@Override
public JCTypeCast inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner.maker().TypeCast(getType().inline(inliner), getExpression().inline(inliner));
}
}
| 1,948
| 28.984615
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/ULiteral.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.refaster;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableBiMap;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.code.TypeTag;
import com.sun.tools.javac.tree.JCTree.JCLiteral;
import java.util.Objects;
import javax.annotation.Nullable;
/**
* {@link UTree} version of {@link LiteralTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
public abstract class ULiteral extends UExpression implements LiteralTree {
public static ULiteral nullLit() {
return create(Kind.NULL_LITERAL, null);
}
public static ULiteral intLit(int value) {
return create(Kind.INT_LITERAL, value);
}
public static ULiteral longLit(long value) {
return create(Kind.LONG_LITERAL, value);
}
public static ULiteral floatLit(float value) {
return create(Kind.FLOAT_LITERAL, value);
}
public static ULiteral doubleLit(double value) {
return create(Kind.DOUBLE_LITERAL, value);
}
public static ULiteral booleanLit(boolean value) {
return create(Kind.BOOLEAN_LITERAL, value);
}
public static ULiteral charLit(char value) {
return create(Kind.CHAR_LITERAL, value);
}
public static ULiteral stringLit(String value) {
return create(Kind.STRING_LITERAL, value);
}
private static final ImmutableBiMap<Kind, TypeTag> LIT_KIND_TAG =
new ImmutableBiMap.Builder<Kind, TypeTag>()
.put(Kind.INT_LITERAL, TypeTag.INT)
.put(Kind.LONG_LITERAL, TypeTag.LONG)
.put(Kind.FLOAT_LITERAL, TypeTag.FLOAT)
.put(Kind.DOUBLE_LITERAL, TypeTag.DOUBLE)
.put(Kind.CHAR_LITERAL, TypeTag.CHAR)
.put(Kind.BOOLEAN_LITERAL, TypeTag.BOOLEAN)
.put(Kind.NULL_LITERAL, TypeTag.BOT)
.put(Kind.STRING_LITERAL, TypeTag.CLASS)
.buildOrThrow();
public static ULiteral create(Kind kind, Object value) {
checkArgument(LIT_KIND_TAG.containsKey(kind), "%s is not a literal kind", kind);
return new AutoValue_ULiteral(kind, value);
}
@Override
public abstract Kind getKind();
@Override
@Nullable
public abstract Object getValue();
private static boolean integral(@Nullable Object o) {
return o instanceof Integer || o instanceof Long;
}
private static boolean match(@Nullable Object a, @Nullable Object b) {
if (a instanceof Number && b instanceof Number) {
return (integral(a) && integral(b))
? ((Number) a).longValue() == ((Number) b).longValue()
: Double.compare(((Number) a).doubleValue(), ((Number) b).doubleValue()) == 0;
} else {
return Objects.equals(a, b);
}
}
@Override
public Choice<Unifier> visitLiteral(LiteralTree literal, Unifier unifier) {
return Choice.condition(match(getValue(), literal.getValue()), unifier);
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitLiteral(this, data);
}
@Override
public JCLiteral inline(Inliner inliner) {
Object value = this.getValue();
switch (getKind()) {
case CHAR_LITERAL:
// Why do they do it like this? I wish I knew.
value = (int) ((Character) value).charValue();
break;
case BOOLEAN_LITERAL:
value = ((Boolean) value) ? 1 : 0;
break;
default:
// do nothing
}
return inliner.maker().Literal(LIT_KIND_TAG.get(getKind()), value);
}
@Override
public UExpression negate() {
checkState(getKind() == Kind.BOOLEAN_LITERAL, "Cannot negate a non-Boolean literal");
return booleanLit(!((Boolean) getValue()));
}
}
| 4,386
| 29.894366
| 89
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UMethodInvocation.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.refaster;
import static com.google.errorprone.refaster.Unifier.unifications;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
import java.util.List;
import javax.annotation.Nullable;
/**
* {@link UTree} version of {@link MethodInvocationTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
public abstract class UMethodInvocation extends UExpression implements MethodInvocationTree {
public static UMethodInvocation create(
List<? extends UExpression> typeArguments,
UExpression methodSelect,
List<UExpression> arguments) {
return new AutoValue_UMethodInvocation(
ImmutableList.copyOf(typeArguments), methodSelect, ImmutableList.copyOf(arguments));
}
public static UMethodInvocation create(
List<? extends UExpression> typeArguments,
UExpression methodSelect,
UExpression... arguments) {
return create(typeArguments, methodSelect, ImmutableList.copyOf(arguments));
}
public static UMethodInvocation create(UExpression methodSelect, UExpression... arguments) {
return create(ImmutableList.of(), methodSelect, ImmutableList.copyOf(arguments));
}
@Override
public abstract ImmutableList<UExpression> getTypeArguments();
@Override
public abstract UExpression getMethodSelect();
@Override
public abstract ImmutableList<UExpression> getArguments();
@Override
@Nullable
public Choice<Unifier> visitMethodInvocation(
MethodInvocationTree methodInvocation, @Nullable Unifier unifier) {
return getMethodSelect()
.unify(methodInvocation.getMethodSelect(), unifier)
.thenChoose(
unifications(
getArguments(), methodInvocation.getArguments(), /* allowVarargs= */ true));
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitMethodInvocation(this, data);
}
@Override
public Kind getKind() {
return Kind.METHOD_INVOCATION;
}
@Override
public JCMethodInvocation inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.Apply(
inliner.<JCExpression>inlineList(getTypeArguments()),
getMethodSelect().inline(inliner),
inliner.<JCExpression>inlineList(getArguments()));
}
}
| 3,160
| 31.927083
| 94
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UStatement.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.refaster;
import com.google.auto.value.AutoValue;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.refaster.UStatement.UnifierWithUnconsumedStatements;
import com.sun.source.tree.StatementTree;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import java.io.Serializable;
import java.util.List;
/**
* {@link UTree} representation of a {@link StatementTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
public interface UStatement
extends Serializable,
StatementTree,
Function<UnifierWithUnconsumedStatements, Choice<UnifierWithUnconsumedStatements>> {
/** Tuple of a Unifier and a list of statements that are still waiting to be matched. */
@AutoValue
abstract class UnifierWithUnconsumedStatements {
public static UnifierWithUnconsumedStatements create(
Unifier unifier, List<? extends StatementTree> unconsumedStatements) {
return new AutoValue_UStatement_UnifierWithUnconsumedStatements(
unifier, ImmutableList.copyOf(unconsumedStatements));
}
public abstract Unifier unifier();
public abstract ImmutableList<? extends StatementTree> unconsumedStatements();
}
com.sun.tools.javac.util.List<JCStatement> inlineStatements(Inliner inliner)
throws CouldNotResolveImportException;
}
| 1,975
| 37
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/ImportPolicy.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.refaster;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Streams;
import com.sun.tools.javac.code.Symbol.PackageSymbol;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCImport;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.Context;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
/**
* Policy specifying when and how to import classes when inlining types.
*
* @author Louis Wasserman
*/
public enum ImportPolicy {
// TODO(lowasser): add support for other policies, like "explicitly qualify everything"
/**
* Import the outermost class and explicitly qualify references below that. For example, to
* reference {@code com.google.Foo.Bar}, we import {@code com.google.Foo} and explicitly qualify
* {@code Foo.Bar}.
*/
IMPORT_TOP_LEVEL {
@Override
public JCExpression classReference(
Inliner inliner, CharSequence topLevelClazz, CharSequence fullyQualifiedClazz) {
if (Refaster.class.getName().contentEquals(fullyQualifiedClazz)) {
// Special handling to ensure that the pretty-printer always recognizes Refaster references
return inliner.maker().Ident(inliner.asName("Refaster"));
}
ImmutableSet<String> allImports = getAllImports(inliner, WhichImports.NON_STATIC);
/*
* Check if topLevelClazz or fullyQualifiedClazz is already imported.
* If fullyQualifiedClazz is imported, return the class name.
* If topLevelClazz is imported, return the name from the top level class to the class name.
* If there are imports whose names conflict with topLevelClazz, return fully qualified name.
* Otherwise, import toplevelClazz, and return the name from the top level class
* to the class name.
*/
checkArgument(
topLevelClazz.length() > 0 && fullyQualifiedClazz.length() > 0,
"either topLevelClass (%s) or fullyQualifiedClazz (%s) is null or empty",
topLevelClazz,
fullyQualifiedClazz);
List<String> topLevelPath = Splitter.on('.').splitToList(topLevelClazz);
String topClazz = Iterables.getLast(topLevelPath);
List<String> qualifiedPath = Splitter.on('.').splitToList(fullyQualifiedClazz);
boolean importTopLevelClazz = false;
boolean conflictTopLevelClazz = false;
for (String importName : allImports) {
if (importName.contentEquals(fullyQualifiedClazz)) {
// fullyQualifiedClazz already imported
return makeSelectExpression(inliner, qualifiedPath, qualifiedPath.size() - 1);
}
importTopLevelClazz |= importName.contentEquals(topLevelClazz);
if (!importTopLevelClazz) {
conflictTopLevelClazz |=
topClazz.equals(Iterables.getLast(Splitter.on('.').split(importName)));
}
}
if (importTopLevelClazz) {
return makeSelectExpression(inliner, qualifiedPath, topLevelPath.size() - 1);
} else if (conflictTopLevelClazz) {
return makeSelectExpression(inliner, qualifiedPath, 0);
}
// No conflicts
String packge = Joiner.on('.').join(topLevelPath.subList(0, topLevelPath.size() - 1));
PackageSymbol currentPackage = inliner.getContext().get(PackageSymbol.class);
if (currentPackage == null || !currentPackage.getQualifiedName().contentEquals(packge)) {
// don't import classes from the same package as the class we're refactoring
inliner.addImport(topLevelClazz.toString());
}
return makeSelectExpression(inliner, qualifiedPath, topLevelPath.size() - 1);
}
@Override
public JCExpression staticReference(
Inliner inliner,
CharSequence topLevelClazz,
CharSequence fullyQualifiedClazz,
CharSequence member) {
return inliner
.maker()
.Select(
classReference(inliner, topLevelClazz, fullyQualifiedClazz), inliner.asName(member));
}
private JCExpression makeSelectExpression(
Inliner inliner, List<String> qualifiedPath, int start) {
Iterator<String> selects = qualifiedPath.listIterator(start);
TreeMaker maker = inliner.maker();
JCExpression select = maker.Ident(inliner.asName(selects.next()));
while (selects.hasNext()) {
select = maker.Select(select, inliner.asName(selects.next()));
}
return select;
}
},
/** Import nested classes directly, and qualify static references from the class level. */
IMPORT_CLASS_DIRECTLY {
@Override
public JCExpression classReference(
Inliner inliner, CharSequence topLevelClazz, CharSequence fullyQualifiedClazz) {
if (Refaster.class.getName().contentEquals(fullyQualifiedClazz)) {
// Special handling to ensure that the pretty-printer always recognizes Refaster references
return inliner.maker().Ident(inliner.asName("Refaster"));
}
String packge = topLevelClazz.toString();
int lastDot = packge.lastIndexOf('.');
packge = (lastDot >= 0) ? packge.substring(0, lastDot) : "";
PackageSymbol currentPackage = inliner.getContext().get(PackageSymbol.class);
if (currentPackage == null
|| !currentPackage.getQualifiedName().contentEquals(packge)
|| !topLevelClazz.toString().contentEquals(fullyQualifiedClazz)) {
// don't import classes from the same package as the class we're refactoring
inliner.addImport(fullyQualifiedClazz.toString());
}
String simpleName = fullyQualifiedClazz.toString();
simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1);
return inliner.maker().Ident(inliner.asName(simpleName));
}
@Override
public JCExpression staticReference(
Inliner inliner,
CharSequence topLevelClazz,
CharSequence fullyQualifiedClazz,
CharSequence member) {
if (Refaster.class.getName().contentEquals(topLevelClazz)) {
// Special handling to ensure that the pretty-printer always recognizes Refaster references
return inliner
.maker()
.Select(inliner.maker().Ident(inliner.asName("Refaster")), inliner.asName(member));
}
return inliner
.maker()
.Select(
classReference(inliner, topLevelClazz, fullyQualifiedClazz), inliner.asName(member));
}
},
/**
* When inlining static methods, always static import the method. Non-static references to classes
* are imported from the top level as in {@code IMPORT_TOP_LEVEL}.
*/
STATIC_IMPORT_ALWAYS {
@Override
public JCExpression classReference(
Inliner inliner, CharSequence topLevelClazz, CharSequence fullyQualifiedClazz) {
return IMPORT_TOP_LEVEL.classReference(inliner, topLevelClazz, fullyQualifiedClazz);
}
@Override
public JCExpression staticReference(
Inliner inliner,
CharSequence topLevelClazz,
CharSequence fullyQualifiedClazz,
CharSequence member) {
if (Refaster.class.getName().contentEquals(topLevelClazz)) {
// Special handling to ensure that the pretty-printer always recognizes Refaster references
return inliner
.maker()
.Select(inliner.maker().Ident(inliner.asName("Refaster")), inliner.asName(member));
}
// Foo.class tokens are considered static members :(.
if (member.toString().equals("class")) {
return IMPORT_TOP_LEVEL.staticReference(
inliner, topLevelClazz, fullyQualifiedClazz, member);
}
// Check to see if the reference is already static-imported.
String importableName = fullyQualifiedClazz + "." + member;
if (!getAllImports(inliner, WhichImports.STATIC).contains(importableName)) {
inliner.addStaticImport(importableName);
}
return inliner.maker().Ident(inliner.asName(member));
}
};
public static void bind(Context context, ImportPolicy policy) {
context.put(ImportPolicy.class, checkNotNull(policy));
}
public static ImportPolicy instance(Context context) {
ImportPolicy result = context.get(ImportPolicy.class);
checkState(result != null, "No ImportPolicy bound in this context");
return result;
}
public abstract JCExpression classReference(
Inliner inliner, CharSequence topLevelClazz, CharSequence fullyQualifiedClazz);
public abstract JCExpression staticReference(
Inliner inliner,
CharSequence topLevelClazz,
CharSequence fullyQualifiedClazz,
CharSequence member);
private enum WhichImports {
STATIC {
@Override
Stream<String> getExistingImports(Inliner inliner) {
return inliner.getStaticImportsToAdd().stream();
}
@Override
boolean existingImportMatches(JCImport jcImport) {
return jcImport.isStatic();
}
},
NON_STATIC {
@Override
Stream<String> getExistingImports(Inliner inliner) {
return inliner.getImportsToAdd().stream();
}
@Override
boolean existingImportMatches(JCImport jcImport) {
// An inner type can be imported non-statically or statically
return true;
}
};
abstract Stream<String> getExistingImports(Inliner inliner);
abstract boolean existingImportMatches(JCImport jcImport);
}
/**
* Returns the set of imports that already exist of the import type (both in the source file and
* in the pending list of imports to add).
*/
private static ImmutableSet<String> getAllImports(Inliner inliner, WhichImports whichImports) {
return Streams.concat(
whichImports.getExistingImports(inliner),
Optional.ofNullable(inliner.getContext())
.map(c -> c.get(JCCompilationUnit.class))
.map(JCCompilationUnit::getImports)
.map(Collection::stream)
.orElse(Stream.of())
.filter(whichImports::existingImportMatches)
.map(imp -> getQualifiedIdentifier(imp).toString()))
.collect(toImmutableSet());
}
private static JCTree getQualifiedIdentifier(JCImport i) {
try {
return (JCTree) JCImport.class.getMethod("getQualifiedIdentifier").invoke(i);
} catch (ReflectiveOperationException e) {
throw new LinkageError(e.getMessage(), e);
}
}
}
| 11,567
| 39.589474
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UClassDecl.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.refaster;
import com.google.auto.value.AutoValue;
import com.google.common.base.Function;
import com.google.common.collect.ContiguousSet;
import com.google.common.collect.DiscreteDomain;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Range;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ModifiersTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TreeVisitor;
import com.sun.source.tree.TypeParameterTree;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.util.List;
import javax.lang.model.element.Name;
/**
* {@code UTree} representation of a {@code ClassTree} for anonymous inner class matching.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UClassDecl extends USimpleStatement implements ClassTree {
public static UClassDecl create(UMethodDecl... members) {
return create(ImmutableList.copyOf(members));
}
public static UClassDecl create(Iterable<UMethodDecl> members) {
return new AutoValue_UClassDecl(ImmutableList.copyOf(members));
}
@AutoValue
abstract static class UnifierWithRemainingMembers {
static UnifierWithRemainingMembers create(
Unifier unifier, Iterable<UMethodDecl> remainingMembers) {
return new AutoValue_UClassDecl_UnifierWithRemainingMembers(
unifier, ImmutableList.copyOf(remainingMembers));
}
abstract Unifier unifier();
abstract ImmutableList<UMethodDecl> remainingMembers();
static Function<Unifier, UnifierWithRemainingMembers> withRemaining(
Iterable<UMethodDecl> remainingMembers) {
return (Unifier unifier) -> create(unifier, remainingMembers);
}
}
private static Function<UnifierWithRemainingMembers, Choice<UnifierWithRemainingMembers>> match(
Tree tree) {
return (UnifierWithRemainingMembers state) -> {
ImmutableList<UMethodDecl> currentMembers = state.remainingMembers();
Choice<Integer> methodChoice =
Choice.from(
ContiguousSet.create(
Range.closedOpen(0, currentMembers.size()), DiscreteDomain.integers()));
return methodChoice.thenChoose(
(Integer i) -> {
ImmutableList<UMethodDecl> remainingMembers =
ImmutableList.<UMethodDecl>builder()
.addAll(currentMembers.subList(0, i))
.addAll(currentMembers.subList(i + 1, currentMembers.size()))
.build();
UMethodDecl chosenMethod = currentMembers.get(i);
Unifier unifier = state.unifier().fork();
/*
* If multiple methods use the same parameter name, preserve the last parameter
* name from the target code. For example, given a @BeforeTemplate with
*
* int get(int index) {...}
* int set(int index, int value) {...}
*
* and target code with the lines
*
* int get(int i) {...}
* int set(int j) {...}
*
* then use "j" in place of index in the @AfterTemplates.
*/
for (UVariableDecl param : chosenMethod.getParameters()) {
unifier.clearBinding(param.key());
}
return chosenMethod
.unify(tree, unifier)
.transform(UnifierWithRemainingMembers.withRemaining(remainingMembers));
});
};
}
@Override
public Choice<Unifier> visitClass(ClassTree node, Unifier unifier) {
Choice<UnifierWithRemainingMembers> path =
Choice.of(UnifierWithRemainingMembers.create(unifier, getMembers()));
for (Tree targetMember : node.getMembers()) {
if (targetMember instanceof MethodTree
&& ASTHelpers.isGeneratedConstructor((MethodTree) targetMember)) {
// skip synthetic constructors
continue;
}
path = path.thenChoose(match(targetMember));
}
return path.condition(s -> s.remainingMembers().isEmpty())
.transform(UnifierWithRemainingMembers::unifier);
}
@Override
public JCClassDecl inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.AnonymousClassDef(
inliner.maker().Modifiers(0L),
List.convert(JCTree.class, inliner.inlineList(getMembers())));
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitClass(this, data);
}
@Override
public Kind getKind() {
return Kind.CLASS;
}
@Override
public UTree<?> getExtendsClause() {
return null;
}
@Override
public ImmutableList<UTree<?>> getImplementsClause() {
return ImmutableList.of();
}
@Override
public abstract ImmutableList<UMethodDecl> getMembers();
@Override
public ModifiersTree getModifiers() {
return null;
}
@Override
public Name getSimpleName() {
return null;
}
@Override
public ImmutableList<TypeParameterTree> getTypeParameters() {
return ImmutableList.of();
}
}
| 5,845
| 32.597701
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UOfKind.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.refaster;
import static com.google.errorprone.refaster.Unifier.unifications;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableSet;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import java.util.Set;
import javax.annotation.Nullable;
/**
* {@code UExpression} imposing a restriction on the kind of the matched expression.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UOfKind extends UExpression {
public static UOfKind create(UExpression expression, Set<Kind> allowed) {
return new AutoValue_UOfKind(expression, ImmutableSet.copyOf(allowed));
}
abstract UExpression expression();
abstract ImmutableSet<Kind> allowed();
@Override
public JCExpression inline(Inliner inliner) throws CouldNotResolveImportException {
return expression().inline(inliner);
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return expression().accept(visitor, data);
}
@Override
public Kind getKind() {
return expression().getKind();
}
@Override
@Nullable
protected Choice<Unifier> defaultAction(Tree tree, @Nullable Unifier unifier) {
return Choice.condition(allowed().contains(tree.getKind()), unifier)
.thenChoose(unifications(expression(), tree));
}
}
| 2,012
| 29.5
| 85
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UAnyOf.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.refaster;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCExpression;
/**
* {@code UExpression} allowing a match against any of a list of expressions.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
public abstract class UAnyOf extends UExpression {
public static UAnyOf create(UExpression... expressions) {
return create(ImmutableList.copyOf(expressions));
}
public static UAnyOf create(Iterable<? extends UExpression> expressions) {
return new AutoValue_UAnyOf(ImmutableList.copyOf(expressions));
}
abstract ImmutableList<UExpression> expressions();
@Override
public UExpression negate() {
ImmutableList.Builder<UExpression> negations = ImmutableList.builder();
for (UExpression expression : expressions()) {
negations.add(expression.negate());
}
return create(negations.build());
}
@Override
protected Choice<Unifier> defaultAction(Tree tree, Unifier unifier) {
return Choice.from(expressions())
.thenChoose(
(UExpression expression) ->
expression.unify(ASTHelpers.stripParentheses(tree), unifier.fork()));
}
@Override
public JCExpression inline(Inliner inliner) throws CouldNotResolveImportException {
throw new UnsupportedOperationException("anyOf should not appear in an @AfterTemplate");
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return expressions().get(0).accept(visitor, data);
}
@Override
public Kind getKind() {
return Kind.OTHER;
}
}
| 2,365
| 30.546667
| 92
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UTypeApply.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.refaster;
import static com.google.errorprone.refaster.Unifier.unifications;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.sun.source.tree.ParameterizedTypeTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCTypeApply;
import java.util.List;
import javax.annotation.Nullable;
/**
* {@link UTree} version of {@link ParameterizedTypeTree}. This is the AST version of {@link
* UClassType}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UTypeApply extends UExpression implements ParameterizedTypeTree {
public static UTypeApply create(UExpression type, List<UExpression> typeArguments) {
return new AutoValue_UTypeApply(type, ImmutableList.copyOf(typeArguments));
}
public static UTypeApply create(UExpression type, UExpression... typeArguments) {
return create(type, ImmutableList.copyOf(typeArguments));
}
public static UTypeApply create(String type, UExpression... typeArguments) {
return create(UClassIdent.create(type), typeArguments);
}
@Override
public abstract UExpression getType();
@Override
public abstract ImmutableList<UExpression> getTypeArguments();
@Override
@Nullable
public Choice<Unifier> visitParameterizedType(
ParameterizedTypeTree typeApply, @Nullable Unifier unifier) {
Choice<Unifier> choice = getType().unify(typeApply.getType(), unifier);
if (getTypeArguments().isEmpty()) {
// the template uses diamond syntax; accept anything except raw
return choice.condition(typeApply.getTypeArguments() != null);
} else {
return choice.thenChoose(unifications(getTypeArguments(), typeApply.getTypeArguments()));
}
}
@Override
public Kind getKind() {
return Kind.PARAMETERIZED_TYPE;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitParameterizedType(this, data);
}
@Override
public JCTypeApply inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.TypeApply(getType().inline(inliner), inliner.<JCExpression>inlineList(getTypeArguments()));
}
}
| 2,886
| 32.569767
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UNewArray.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.refaster;
import static com.google.errorprone.refaster.Unifier.unifications;
import static com.google.errorprone.refaster.Unifier.unifyNullable;
import com.google.auto.value.AutoValue;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.NewArrayTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCNewArray;
import java.util.List;
import javax.annotation.Nullable;
/** {@link UTree} version of {@link NewArrayTree}, which represents an array instantiation. */
@AutoValue
abstract class UNewArray extends UExpression implements NewArrayTree {
public static UNewArray create(
UExpression type,
List<? extends UExpression> dimensions,
List<? extends UExpression> initializers) {
return new AutoValue_UNewArray(
type,
dimensions != null ? ImmutableList.copyOf(dimensions) : null,
initializers != null ? ImmutableList.copyOf(initializers) : null);
}
@Nullable
@Override
public abstract UExpression getType();
@Nullable
@Override
public abstract ImmutableList<UExpression> getDimensions();
@Nullable
@Override
public abstract ImmutableList<UExpression> getInitializers();
@Override
@Nullable
public Choice<Unifier> visitNewArray(NewArrayTree newArray, @Nullable Unifier unifier) {
boolean hasRepeated =
getInitializers() != null
&& Iterables.any(getInitializers(), Predicates.instanceOf(URepeated.class));
return unifyNullable(unifier, getType(), newArray.getType())
.thenChoose(unifications(getDimensions(), newArray.getDimensions()))
.thenChoose(unifications(getInitializers(), newArray.getInitializers(), hasRepeated));
}
@Override
public Kind getKind() {
return Kind.NEW_ARRAY;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitNewArray(this, data);
}
@Override
public JCNewArray inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.NewArray(
(getType() == null) ? null : getType().inline(inliner),
(getDimensions() == null) ? null : inliner.<JCExpression>inlineList(getDimensions()),
(getInitializers() == null)
? null
: inliner.<JCExpression>inlineList(getInitializers()));
}
@Override
public List<? extends AnnotationTree> getAnnotations() {
return ImmutableList.of();
}
@Override
public List<? extends List<? extends AnnotationTree>> getDimAnnotations() {
return ImmutableList.of();
}
}
| 3,410
| 32.116505
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/ControlFlowVisitor.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.refaster;
import static com.google.errorprone.refaster.ControlFlowVisitor.Result.ALWAYS_RETURNS;
import static com.google.errorprone.refaster.ControlFlowVisitor.Result.MAY_BREAK_OR_RETURN;
import static com.google.errorprone.refaster.ControlFlowVisitor.Result.NEVER_EXITS;
import com.google.errorprone.refaster.ControlFlowVisitor.BreakContext;
import com.google.errorprone.refaster.ControlFlowVisitor.Result;
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.ContinueTree;
import com.sun.source.tree.DoWhileLoopTree;
import com.sun.source.tree.EnhancedForLoopTree;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.ForLoopTree;
import com.sun.source.tree.IfTree;
import com.sun.source.tree.LabeledStatementTree;
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.WhileLoopTree;
import com.sun.source.util.SimpleTreeVisitor;
import java.util.HashSet;
import java.util.Set;
import javax.lang.model.element.Name;
/**
* Analyzes a series of statements to determine whether they don't, sometimes, or never return.
*
* @author lowasser@google.com (Louis Wasserman)
*/
public class ControlFlowVisitor extends SimpleTreeVisitor<Result, BreakContext> {
public static final ControlFlowVisitor INSTANCE = new ControlFlowVisitor();
/**
* The state of whether a sequence of statements may return, break out of the visited statements,
* or neither.
*/
public enum Result {
NEVER_EXITS {
@Override
Result or(Result other) {
switch (other) {
case MAY_BREAK_OR_RETURN:
case NEVER_EXITS:
return other;
default:
return MAY_RETURN;
}
}
@Override
Result then(Result other) {
return other;
}
},
MAY_BREAK_OR_RETURN {
@Override
Result or(Result other) {
return MAY_BREAK_OR_RETURN;
}
@Override
Result then(Result other) {
return MAY_BREAK_OR_RETURN;
}
},
MAY_RETURN {
@Override
Result or(Result other) {
return (other == MAY_BREAK_OR_RETURN) ? MAY_BREAK_OR_RETURN : MAY_RETURN;
}
@Override
Result then(Result other) {
switch (other) {
case MAY_BREAK_OR_RETURN:
case ALWAYS_RETURNS:
return other;
default:
return MAY_RETURN;
}
}
},
ALWAYS_RETURNS {
@Override
Result or(Result other) {
switch (other) {
case MAY_BREAK_OR_RETURN:
case ALWAYS_RETURNS:
return other;
default:
return MAY_RETURN;
}
}
@Override
Result then(Result other) {
return ALWAYS_RETURNS;
}
};
abstract Result or(Result other);
abstract Result then(Result other);
}
static class BreakContext {
final Set<Name> internalLabels;
int loopDepth;
private BreakContext() {
this.internalLabels = new HashSet<>();
this.loopDepth = 0;
}
void enter(Name label) {
internalLabels.add(label);
}
void exit(Name label) {
internalLabels.remove(label);
}
}
private ControlFlowVisitor() {}
public Result visitStatement(StatementTree node) {
return node.accept(this, new BreakContext());
}
public Result visitStatements(Iterable<? extends StatementTree> nodes) {
return visitStatements(nodes, new BreakContext());
}
private Result visitStatements(Iterable<? extends StatementTree> nodes, BreakContext cxt) {
Result result = NEVER_EXITS;
for (StatementTree node : nodes) {
result = result.then(node.accept(this, cxt));
}
return result;
}
@Override
protected Result defaultAction(Tree node, BreakContext cxt) {
return NEVER_EXITS;
}
@Override
public Result visitBlock(BlockTree node, BreakContext cxt) {
return visitStatements(node.getStatements(), cxt);
}
@Override
public Result visitDoWhileLoop(DoWhileLoopTree node, BreakContext cxt) {
cxt.loopDepth++;
try {
return node.getStatement().accept(this, cxt).or(NEVER_EXITS);
} finally {
cxt.loopDepth--;
}
}
@Override
public Result visitWhileLoop(WhileLoopTree node, BreakContext cxt) {
cxt.loopDepth++;
try {
return node.getStatement().accept(this, cxt).or(NEVER_EXITS);
} finally {
cxt.loopDepth--;
}
}
@Override
public Result visitForLoop(ForLoopTree node, BreakContext cxt) {
cxt.loopDepth++;
try {
return node.getStatement().accept(this, cxt).or(NEVER_EXITS);
} finally {
cxt.loopDepth--;
}
}
@Override
public Result visitEnhancedForLoop(EnhancedForLoopTree node, BreakContext cxt) {
cxt.loopDepth++;
try {
return node.getStatement().accept(this, cxt).or(NEVER_EXITS);
} finally {
cxt.loopDepth--;
}
}
@Override
public Result visitSwitch(SwitchTree node, BreakContext cxt) {
Result result = null;
boolean seenDefault = false;
cxt.loopDepth++;
try {
for (CaseTree caseTree : node.getCases()) {
if (caseTree.getExpression() == null) {
seenDefault = true;
}
if (result == null) {
result = caseTree.accept(this, cxt);
} else {
result = result.or(caseTree.accept(this, cxt));
}
}
if (!seenDefault) {
result = result.or(NEVER_EXITS);
}
return result;
} finally {
cxt.loopDepth--;
}
}
@Override
public Result visitCase(CaseTree node, BreakContext cxt) {
return visitStatements(node.getStatements(), cxt);
}
@Override
public Result visitSynchronized(SynchronizedTree node, BreakContext cxt) {
return node.getBlock().accept(this, cxt);
}
@Override
public Result visitTry(TryTree node, BreakContext cxt) {
Result result = node.getBlock().accept(this, cxt);
for (CatchTree catchTree : node.getCatches()) {
result = result.or(catchTree.accept(this, cxt));
}
if (node.getFinallyBlock() != null) {
result = result.then(node.getFinallyBlock().accept(this, cxt));
}
return result;
}
@Override
public Result visitCatch(CatchTree node, BreakContext cxt) {
return node.getBlock().accept(this, cxt);
}
@Override
public Result visitIf(IfTree node, BreakContext cxt) {
Result thenResult = node.getThenStatement().accept(this, cxt);
Result elseResult =
(node.getElseStatement() == null) ? NEVER_EXITS : node.getElseStatement().accept(this, cxt);
return thenResult.or(elseResult);
}
@Override
public Result visitExpressionStatement(ExpressionStatementTree node, BreakContext cxt) {
return NEVER_EXITS;
}
@Override
public Result visitLabeledStatement(LabeledStatementTree node, BreakContext cxt) {
cxt.enter(node.getLabel());
try {
return node.getStatement().accept(this, cxt);
} finally {
cxt.exit(node.getLabel());
}
}
@Override
public Result visitBreak(BreakTree node, BreakContext cxt) {
if (cxt.internalLabels.contains(node.getLabel())
|| (node.getLabel() == null && cxt.loopDepth > 0)) {
return NEVER_EXITS;
} else {
return MAY_BREAK_OR_RETURN;
}
}
@Override
public Result visitContinue(ContinueTree node, BreakContext cxt) {
if (cxt.internalLabels.contains(node.getLabel())
|| (node.getLabel() == null && cxt.loopDepth > 0)) {
return NEVER_EXITS;
} else {
return MAY_BREAK_OR_RETURN;
}
}
@Override
public Result visitReturn(ReturnTree node, BreakContext cxt) {
return ALWAYS_RETURNS;
}
@Override
public Result visitThrow(ThrowTree node, BreakContext cxt) {
return ALWAYS_RETURNS;
}
}
| 8,719
| 25.996904
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UPrimitiveTypeTree.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.refaster;
import com.google.auto.value.AutoValue;
import com.sun.source.tree.PrimitiveTypeTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.code.TypeTag;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import javax.lang.model.type.TypeKind;
/**
* {@link UTree} version of {@link UPrimitiveTypeTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UPrimitiveTypeTree extends UExpression implements PrimitiveTypeTree {
public static UPrimitiveTypeTree create(TypeTag tag) {
return new AutoValue_UPrimitiveTypeTree(tag);
}
abstract TypeTag typeTag();
public static final UPrimitiveTypeTree BYTE = create(TypeTag.BYTE);
public static final UPrimitiveTypeTree SHORT = create(TypeTag.SHORT);
public static final UPrimitiveTypeTree INT = create(TypeTag.INT);
public static final UPrimitiveTypeTree LONG = create(TypeTag.LONG);
public static final UPrimitiveTypeTree FLOAT = create(TypeTag.FLOAT);
public static final UPrimitiveTypeTree DOUBLE = create(TypeTag.DOUBLE);
public static final UPrimitiveTypeTree BOOLEAN = create(TypeTag.BOOLEAN);
public static final UPrimitiveTypeTree CHAR = create(TypeTag.CHAR);
public static final UPrimitiveTypeTree NULL = create(TypeTag.BOT);
public static final UPrimitiveTypeTree VOID = create(TypeTag.VOID);
@Override
public Choice<Unifier> visitPrimitiveType(PrimitiveTypeTree tree, Unifier unifier) {
return Choice.condition(getPrimitiveTypeKind().equals(tree.getPrimitiveTypeKind()), unifier);
}
@Override
public Kind getKind() {
return Kind.PRIMITIVE_TYPE;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitPrimitiveType(this, data);
}
@Override
public TypeKind getPrimitiveTypeKind() {
return typeTag().getPrimitiveTypeKind();
}
@Override
public JCExpression inline(Inliner inliner) {
return inliner.maker().TypeIdent(typeTag());
}
}
| 2,603
| 33.263158
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UCatch.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.refaster;
import static com.google.errorprone.refaster.Unifier.unifications;
import com.google.auto.value.AutoValue;
import com.sun.source.tree.CatchTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCCatch;
import javax.annotation.Nullable;
/**
* {@code UTree} representation of a {@code CatchTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UCatch extends UTree<JCCatch> implements CatchTree {
static UCatch create(UVariableDecl parameter, UBlock block) {
return new AutoValue_UCatch(parameter, block);
}
@Override
public abstract UVariableDecl getParameter();
@Override
public abstract UBlock getBlock();
@Override
public Kind getKind() {
return Kind.CATCH;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitCatch(this, data);
}
@Override
public JCCatch inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner.maker().Catch(getParameter().inline(inliner), getBlock().inline(inliner));
}
@Override
@Nullable
public Choice<Unifier> visitCatch(CatchTree node, @Nullable Unifier unifier) {
return getParameter()
.unify(node.getParameter(), unifier)
.thenChoose(unifications(getBlock(), node.getBlock()));
}
}
| 1,969
| 28.402985
| 93
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/ULambda.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.refaster;
import static com.google.errorprone.refaster.Unifier.unifications;
import static com.google.errorprone.refaster.Unifier.unifyList;
import com.google.auto.value.AutoValue;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCExpressionStatement;
import com.sun.tools.javac.tree.JCTree.JCLambda;
import com.sun.tools.javac.tree.JCTree.JCLambda.ParameterKind;
import com.sun.tools.javac.tree.JCTree.JCReturn;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
/**
* {@code UTree} representation of a {@code LambdaExpressionTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class ULambda extends UExpression implements LambdaExpressionTree {
public static ULambda create(
ParameterKind parameterKind, Iterable<UVariableDecl> parameters, UTree<?> body) {
return new AutoValue_ULambda(parameterKind, ImmutableList.copyOf(parameters), body);
}
@Override
public Kind getKind() {
return Kind.LAMBDA_EXPRESSION;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitLambdaExpression(this, data);
}
@Override
public Choice<Unifier> visitLambdaExpression(LambdaExpressionTree node, Unifier unifier) {
return unifyList(unifier, getParameters(), node.getParameters())
.thenChoose(unifications(getBody(), node.getBody()));
}
@Override
public JCLambda inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner.maker().Lambda(inlineParams(inliner), inlineBody(inliner));
}
public List<JCVariableDecl> inlineParams(Inliner inliner) throws CouldNotResolveImportException {
if (parameterKind() == ParameterKind.EXPLICIT) {
return List.convert(JCVariableDecl.class, inliner.inlineList(getParameters()));
}
ListBuffer<JCVariableDecl> params = new ListBuffer<>();
for (UVariableDecl param : getParameters()) {
params.add(param.inlineImplicitType(inliner));
}
return params.toList();
}
JCTree inlineBody(Inliner inliner) throws CouldNotResolveImportException {
if (getBody() instanceof UPlaceholderExpression) {
UPlaceholderExpression body = (UPlaceholderExpression) getBody();
Optional<List<JCStatement>> blockBinding =
inliner.getOptionalBinding(body.placeholder().blockKey());
if (blockBinding.isPresent()) {
// this lambda is of the form args -> blockPlaceholder();
List<JCStatement> blockInlined =
UPlaceholderExpression.copier(body.arguments(), inliner)
.copy(blockBinding.get(), inliner);
if (blockInlined.size() == 1) {
if (blockInlined.get(0) instanceof JCReturn) {
return ((JCReturn) blockInlined.get(0)).getExpression();
} else if (blockInlined.get(0) instanceof JCExpressionStatement) {
return ((JCExpressionStatement) blockInlined.get(0)).getExpression();
}
}
return inliner.maker().Block(0, blockInlined);
}
}
return getBody().inline(inliner);
}
abstract ParameterKind parameterKind();
@Override
public abstract ImmutableList<UVariableDecl> getParameters();
@Override
public abstract UTree<?> getBody();
@Override
public BodyKind getBodyKind() {
return getBody().getKind() == Kind.BLOCK ? BodyKind.STATEMENT : BodyKind.EXPRESSION;
}
}
| 4,315
| 35.888889
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/ULocalVarIdent.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.refaster;
import com.google.auto.value.AutoValue;
import com.google.common.base.Optional;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.IdentifierTree;
import com.sun.tools.javac.tree.JCTree.JCIdent;
import java.util.Objects;
/**
* Identifier corresponding to a template local variable.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class ULocalVarIdent extends UIdent {
/** A key in a {@code Bindings} associated with a local variable of the specified name. */
static final class Key extends Bindings.Key<LocalVarBinding> {
Key(CharSequence name) {
super(name.toString());
}
}
public static ULocalVarIdent create(CharSequence identifier) {
return new AutoValue_ULocalVarIdent(StringName.of(identifier));
}
@Override
public abstract StringName getName();
private Key key() {
return new Key(getName());
}
@Override
public Choice<Unifier> visitIdentifier(IdentifierTree ident, Unifier unifier) {
LocalVarBinding binding = unifier.getBinding(key());
return Choice.condition(
binding != null && Objects.equals(ASTHelpers.getSymbol(ident), binding.getSymbol()),
unifier);
}
@Override
public JCIdent inline(Inliner inliner) throws CouldNotResolveImportException {
Optional<LocalVarBinding> binding = inliner.getOptionalBinding(key());
return inliner
.maker()
.Ident(binding.isPresent() ? binding.get().getName() : getName().inline(inliner));
}
}
| 2,142
| 30.985075
| 92
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UUnionType.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.refaster;
import static com.google.errorprone.refaster.Unifier.unifyList;
import com.google.auto.value.AutoValue;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.sun.source.tree.TreeVisitor;
import com.sun.source.tree.UnionTypeTree;
import com.sun.tools.javac.tree.JCTree.JCTypeUnion;
/**
* {@code UTree} representation of {@code UnionTypeTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UUnionType extends UExpression implements UnionTypeTree {
@VisibleForTesting
static UUnionType create(UExpression... typeAlternatives) {
return create(ImmutableList.copyOf(typeAlternatives));
}
static UUnionType create(Iterable<? extends UExpression> typeAlternatives) {
return new AutoValue_UUnionType(ImmutableList.copyOf(typeAlternatives));
}
@Override
public abstract ImmutableList<UExpression> getTypeAlternatives();
@Override
public Kind getKind() {
return Kind.UNION_TYPE;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitUnionType(this, data);
}
@Override
public JCTypeUnion inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner.maker().TypeUnion(inliner.inlineList(getTypeAlternatives()));
}
@Override
public Choice<Unifier> visitUnionType(UnionTypeTree node, Unifier unifier) {
return unifyList(unifier, getTypeAlternatives(), node.getTypeAlternatives());
}
}
| 2,142
| 30.985075
| 84
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UTypeParameter.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.refaster;
import static com.google.errorprone.refaster.Unifier.unifications;
import com.google.auto.value.AutoValue;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.sun.source.tree.TreeVisitor;
import com.sun.source.tree.TypeParameterTree;
import com.sun.tools.javac.tree.JCTree.JCTypeParameter;
import javax.annotation.Nullable;
/**
* {@code UTree} representation of a {@code TypeParameterTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UTypeParameter extends UTree<JCTypeParameter> implements TypeParameterTree {
@VisibleForTesting
static UTypeParameter create(CharSequence name, UExpression... bounds) {
return create(name, ImmutableList.copyOf(bounds), ImmutableList.<UAnnotation>of());
}
static UTypeParameter create(
CharSequence name,
Iterable<? extends UExpression> bounds,
Iterable<? extends UAnnotation> annotations) {
return new AutoValue_UTypeParameter(
StringName.of(name), ImmutableList.copyOf(bounds), ImmutableList.copyOf(annotations));
}
@Override
public abstract StringName getName();
@Override
public abstract ImmutableList<UExpression> getBounds();
@Override
public abstract ImmutableList<UAnnotation> getAnnotations();
@Override
public Kind getKind() {
return Kind.TYPE_PARAMETER;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitTypeParameter(this, data);
}
@Override
public JCTypeParameter inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.TypeParameter(getName().inline(inliner), inliner.inlineList(getBounds()));
}
@Override
@Nullable
public Choice<Unifier> visitTypeParameter(TypeParameterTree node, @Nullable Unifier unifier) {
return getName()
.unify(node.getName(), unifier)
.thenChoose(unifications(getBounds(), node.getBounds()))
.thenChoose(unifications(getAnnotations(), node.getAnnotations()));
}
}
| 2,710
| 31.27381
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UConditional.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.refaster;
import static com.google.errorprone.refaster.Unifier.unifications;
import com.google.auto.value.AutoValue;
import com.sun.source.tree.ConditionalExpressionTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCConditional;
import javax.annotation.Nullable;
/**
* {@link UTree} version of {@link ConditionalExpressionTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UConditional extends UExpression implements ConditionalExpressionTree {
public static UConditional create(
UExpression conditionExpr, UExpression trueExpr, UExpression falseExpr) {
return new AutoValue_UConditional(conditionExpr, trueExpr, falseExpr);
}
@Override
public abstract UExpression getCondition();
@Override
public abstract UExpression getTrueExpression();
@Override
public abstract UExpression getFalseExpression();
@Override
@Nullable
public Choice<Unifier> visitConditionalExpression(
ConditionalExpressionTree conditional, Unifier unifier) {
return getCondition()
.unify(conditional.getCondition(), unifier.fork())
.thenChoose(unifications(getTrueExpression(), conditional.getTrueExpression()))
.thenChoose(unifications(getFalseExpression(), conditional.getFalseExpression()))
.or(
getCondition()
.negate()
.unify(conditional.getCondition(), unifier.fork())
.thenChoose(unifications(getFalseExpression(), conditional.getTrueExpression()))
.thenChoose(unifications(getTrueExpression(), conditional.getFalseExpression())));
}
@Override
public Kind getKind() {
return Kind.CONDITIONAL_EXPRESSION;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitConditionalExpression(this, data);
}
@Override
public JCConditional inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.Conditional(
getCondition().inline(inliner),
getTrueExpression().inline(inliner),
getFalseExpression().inline(inliner));
}
}
| 2,811
| 32.47619
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UAssert.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.refaster;
import static com.google.errorprone.refaster.Unifier.unifications;
import com.google.auto.value.AutoValue;
import com.sun.source.tree.AssertTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import javax.annotation.Nullable;
/**
* {@code UTree} representation of an assertion.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UAssert extends USimpleStatement implements AssertTree {
static UAssert create(UExpression condition, @Nullable UExpression detail) {
return new AutoValue_UAssert(condition, detail);
}
@Override
public Kind getKind() {
return Kind.ASSERT;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitAssert(this, data);
}
@Override
public abstract UExpression getCondition();
@Override
@Nullable
public abstract UExpression getDetail();
@Override
public Choice<Unifier> visitAssert(AssertTree node, Unifier unifier) {
return getCondition()
.unify(node.getCondition(), unifier)
.thenChoose(unifications(getDetail(), node.getDetail()));
}
@Override
public JCStatement inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.Assert(
getCondition().inline(inliner),
(getDetail() == null) ? null : getDetail().inline(inliner));
}
}
| 2,069
| 27.75
| 84
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UDoWhileLoop.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.refaster;
import static com.google.errorprone.refaster.Unifier.unifications;
import com.google.auto.value.AutoValue;
import com.sun.source.tree.DoWhileLoopTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCDoWhileLoop;
import javax.annotation.Nullable;
/**
* A {@link UTree} representation of a {@link DoWhileLoopTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UDoWhileLoop extends USimpleStatement implements DoWhileLoopTree {
public static UDoWhileLoop create(UStatement body, UExpression condition) {
return new AutoValue_UDoWhileLoop((USimpleStatement) body, condition);
}
@Override
public abstract USimpleStatement getStatement();
@Override
public abstract UExpression getCondition();
@Override
@Nullable
public Choice<Unifier> visitDoWhileLoop(DoWhileLoopTree loop, @Nullable Unifier unifier) {
return getStatement()
.unify(loop.getStatement(), unifier)
.thenChoose(unifications(getCondition(), loop.getCondition()));
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitDoWhileLoop(this, data);
}
@Override
public Kind getKind() {
return Kind.DO_WHILE_LOOP;
}
@Override
public JCDoWhileLoop inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner.maker().DoLoop(getStatement().inline(inliner), getCondition().inline(inliner));
}
}
| 2,098
| 30.328358
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/ULabeledStatement.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.refaster;
import com.google.auto.value.AutoValue;
import com.sun.source.tree.LabeledStatementTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCLabeledStatement;
import com.sun.tools.javac.util.Name;
import javax.annotation.Nullable;
/**
* {@code UTree} representation of a {@code LabeledStatementTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class ULabeledStatement extends USimpleStatement implements LabeledStatementTree {
static ULabeledStatement create(CharSequence label, UStatement statement) {
return new AutoValue_ULabeledStatement(StringName.of(label), (USimpleStatement) statement);
}
static class Key extends Bindings.Key<CharSequence> {
Key(CharSequence identifier) {
super(identifier.toString());
}
}
/**
* Returns either the {@code Name} bound to the specified label, or a {@code Name} representing
* the original label if none is already bound.
*/
@Nullable
static Name inlineLabel(@Nullable CharSequence label, Inliner inliner) {
return (label == null)
? null
: inliner.asName(inliner.getOptionalBinding(new Key(label)).or(label));
}
@Override
public abstract StringName getLabel();
@Override
public abstract USimpleStatement getStatement();
@Override
public Kind getKind() {
return Kind.LABELED_STATEMENT;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitLabeledStatement(this, data);
}
private Key key() {
return new Key(getLabel());
}
@Override
public JCLabeledStatement inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.Labelled(inlineLabel(getLabel(), inliner), getStatement().inline(inliner));
}
@Override
public Choice<Unifier> visitLabeledStatement(LabeledStatementTree node, Unifier unifier) {
unifier.putBinding(key(), node.getLabel());
return getStatement().unify(node.getStatement(), unifier);
}
}
| 2,670
| 29.701149
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UWildcard.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.refaster;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.errorprone.refaster.Unifier.unifications;
import com.google.auto.value.AutoValue;
import com.google.common.collect.EnumBiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.Maps;
import com.sun.source.tree.TreeVisitor;
import com.sun.source.tree.WildcardTree;
import com.sun.tools.javac.code.BoundKind;
import com.sun.tools.javac.tree.JCTree.JCWildcard;
import javax.annotation.Nullable;
/**
* {@code UTree} representation of a {@code WildcardTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UWildcard extends UExpression implements WildcardTree {
private static final ImmutableBiMap<Kind, BoundKind> BOUND_KINDS;
static {
EnumBiMap<Kind, BoundKind> validKinds = EnumBiMap.create(Kind.class, BoundKind.class);
validKinds.put(Kind.UNBOUNDED_WILDCARD, BoundKind.UNBOUND);
validKinds.put(Kind.EXTENDS_WILDCARD, BoundKind.EXTENDS);
validKinds.put(Kind.SUPER_WILDCARD, BoundKind.SUPER);
BOUND_KINDS = ImmutableBiMap.copyOf(Maps.unmodifiableBiMap(validKinds));
}
static UWildcard create(Kind kind, @Nullable UTree<?> bound) {
checkArgument(BOUND_KINDS.containsKey(kind));
// verify bound is null iff kind is UNBOUNDED_WILDCARD
checkArgument((bound == null) == (kind == Kind.UNBOUNDED_WILDCARD));
return new AutoValue_UWildcard(kind, bound);
}
@Override
public abstract Kind getKind();
@Override
@Nullable
public abstract UTree<?> getBound();
@Override
public JCWildcard inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.Wildcard(
inliner.maker().TypeBoundKind(BOUND_KINDS.get(getKind())),
(getBound() == null) ? null : getBound().inline(inliner));
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitWildcard(this, data);
}
@Override
public Choice<Unifier> visitWildcard(WildcardTree node, Unifier unifier) {
return Choice.condition(getKind() == node.getKind(), unifier)
.thenChoose(unifications(getBound(), node.getBound()));
}
}
| 2,862
| 33.493976
| 90
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/BlockTemplate.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.refaster;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.logging.Level.SEVERE;
import com.google.auto.value.AutoValue;
import com.google.common.base.CharMatcher;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableClassToInstanceMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.refaster.UStatement.UnifierWithUnconsumedStatements;
import com.google.errorprone.refaster.annotation.UseImportPolicy;
import com.sun.source.tree.StatementTree;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCBlock;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Warner;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.annotation.Annotation;
import java.util.Map;
import java.util.logging.Logger;
/**
* Template representing a sequence of consecutive statements.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
public abstract class BlockTemplate extends Template<BlockTemplateMatch> {
private static final Logger logger = Logger.getLogger(BlockTemplate.class.toString());
public static BlockTemplate create(UStatement... templateStatements) {
return create(ImmutableMap.<String, UType>of(), templateStatements);
}
public static BlockTemplate create(
Map<String, ? extends UType> expressionArgumentTypes, UStatement... templateStatements) {
return create(ImmutableList.<UTypeVar>of(), expressionArgumentTypes, templateStatements);
}
public static BlockTemplate create(
Iterable<UTypeVar> typeVariables,
Map<String, ? extends UType> expressionArgumentTypes,
UStatement... templateStatements) {
return create(
ImmutableClassToInstanceMap.of(),
typeVariables,
expressionArgumentTypes,
ImmutableList.copyOf(templateStatements));
}
public static BlockTemplate create(
ImmutableClassToInstanceMap<Annotation> annotations,
Iterable<UTypeVar> typeVariables,
Map<String, ? extends UType> expressionArgumentTypes,
Iterable<? extends UStatement> templateStatements) {
return new AutoValue_BlockTemplate(
annotations,
ImmutableList.copyOf(typeVariables),
ImmutableMap.copyOf(expressionArgumentTypes),
ImmutableList.copyOf(templateStatements));
}
public BlockTemplate withStatements(Iterable<? extends UStatement> templateStatements) {
return create(
annotations(), templateTypeVariables(), expressionArgumentTypes(), templateStatements);
}
abstract ImmutableList<UStatement> templateStatements();
/**
* If the tree is a {@link JCBlock}, returns a list of disjoint matches corresponding to the exact
* list of template statements found consecutively; otherwise, returns an empty list.
*/
@Override
public Iterable<BlockTemplateMatch> match(JCTree tree, Context context) {
// TODO(lowasser): consider nonconsecutive matches?
if (tree instanceof JCBlock) {
JCBlock block = (JCBlock) tree;
ImmutableList<JCStatement> targetStatements = ImmutableList.copyOf(block.getStatements());
return matchesStartingAnywhere(block, 0, targetStatements, context)
.first()
.or(List.<BlockTemplateMatch>nil());
}
return ImmutableList.of();
}
private Choice<List<BlockTemplateMatch>> matchesStartingAtBeginning(
JCBlock block,
int offset,
ImmutableList<? extends StatementTree> statements,
Context context) {
if (statements.isEmpty()) {
return Choice.none();
}
JCStatement firstStatement = (JCStatement) statements.get(0);
Choice<UnifierWithUnconsumedStatements> choice =
Choice.of(UnifierWithUnconsumedStatements.create(new Unifier(context), statements));
for (UStatement templateStatement : templateStatements()) {
choice = choice.thenChoose(templateStatement);
}
return choice.thenChoose(
(UnifierWithUnconsumedStatements state) -> {
Unifier unifier = state.unifier();
Inliner inliner = unifier.createInliner();
try {
Optional<Unifier> checkedUnifier =
typecheck(
unifier,
inliner,
new Warner(firstStatement),
expectedTypes(inliner),
actualTypes(inliner));
if (checkedUnifier.isPresent()) {
int consumedStatements = statements.size() - state.unconsumedStatements().size();
BlockTemplateMatch match =
new BlockTemplateMatch(
block, checkedUnifier.get(), offset, offset + consumedStatements);
boolean verified =
ExpressionTemplate.trueOrNull(
ExpressionTemplate.PLACEHOLDER_VERIFIER.scan(
templateStatements(), checkedUnifier.get()));
if (!verified) {
return Choice.none();
}
return matchesStartingAnywhere(
block,
offset + consumedStatements,
statements.subList(consumedStatements, statements.size()),
context)
.transform(list -> list.prepend(match));
}
} catch (CouldNotResolveImportException e) {
// fall through
}
return Choice.none();
});
}
private Choice<List<BlockTemplateMatch>> matchesStartingAnywhere(
JCBlock block,
int offset,
ImmutableList<? extends StatementTree> statements,
Context context) {
Choice<List<BlockTemplateMatch>> choice = Choice.none();
for (int i = 0; i < statements.size(); i++) {
choice =
choice.or(
matchesStartingAtBeginning(
block, offset + i, statements.subList(i, statements.size()), context));
}
return choice.or(Choice.of(List.<BlockTemplateMatch>nil()));
}
/** Returns a {@code String} representation of a statement, including semicolon. */
private static String printStatement(Context context, JCStatement statement) {
StringWriter writer = new StringWriter();
try {
pretty(context, writer).printStat(statement);
} catch (IOException e) {
throw new AssertionError("StringWriter cannot throw IOExceptions", e);
}
return writer.toString();
}
/**
* Returns a {@code String} representation of a sequence of statements, with semicolons and
* newlines.
*/
private static String printStatements(Context context, Iterable<JCStatement> statements) {
StringWriter writer = new StringWriter();
try {
pretty(context, writer).printStats(com.sun.tools.javac.util.List.from(statements));
} catch (IOException e) {
throw new AssertionError("StringWriter cannot throw IOExceptions", e);
}
return writer.toString();
}
@Override
public Fix replace(BlockTemplateMatch match) {
checkNotNull(match);
SuggestedFix.Builder fix = SuggestedFix.builder();
Inliner inliner = match.createInliner();
Context context = inliner.getContext();
if (annotations().containsKey(UseImportPolicy.class)) {
ImportPolicy.bind(context, annotations().getInstance(UseImportPolicy.class).value());
} else {
ImportPolicy.bind(context, ImportPolicy.IMPORT_TOP_LEVEL);
}
ImmutableList<JCStatement> targetStatements = match.getStatements();
try {
ImmutableList.Builder<JCStatement> inlinedStatementsBuilder = ImmutableList.builder();
for (UStatement statement : templateStatements()) {
inlinedStatementsBuilder.addAll(statement.inlineStatements(inliner));
}
ImmutableList<JCStatement> inlinedStatements = inlinedStatementsBuilder.build();
int nInlined = inlinedStatements.size();
int nTargets = targetStatements.size();
if (nInlined <= nTargets) {
for (int i = 0; i < nInlined; i++) {
fix.replace(targetStatements.get(i), printStatement(context, inlinedStatements.get(i)));
}
for (int i = nInlined; i < nTargets; i++) {
fix.delete(targetStatements.get(i));
}
} else {
for (int i = 0; i < nTargets - 1; i++) {
fix.replace(targetStatements.get(i), printStatement(context, inlinedStatements.get(i)));
}
int last = nTargets - 1;
ImmutableList<JCStatement> remainingInlined = inlinedStatements.subList(last, nInlined);
fix.replace(
targetStatements.get(last),
CharMatcher.whitespace().trimTrailingFrom(printStatements(context, remainingInlined)));
}
} catch (CouldNotResolveImportException e) {
logger.log(SEVERE, "Failure to resolve import in replacement", e);
}
return addImports(inliner, fix);
}
}
| 9,713
| 38.975309
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UStaticIdent.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.refaster;
import static com.google.errorprone.refaster.Unifier.unifications;
import com.google.auto.value.AutoValue;
import com.google.errorprone.util.ASTHelpers;
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.tree.JCTree.JCExpression;
/**
* Identifier representing a static member (field, method, etc.) on a class.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
public abstract class UStaticIdent extends UIdent {
public static UStaticIdent create(UClassIdent classIdent, CharSequence member, UType memberType) {
return new AutoValue_UStaticIdent(classIdent, StringName.of(member), memberType);
}
public static UStaticIdent create(String qualifiedClass, CharSequence member, UType memberType) {
return create(UClassIdent.create(qualifiedClass), member, memberType);
}
public static UStaticIdent create(ClassSymbol classSym, CharSequence member, UType memberType) {
return create(UClassIdent.create(classSym), member, memberType);
}
abstract UClassIdent classIdent();
@Override
public abstract StringName getName();
abstract UType memberType();
@Override
public JCExpression inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.importPolicy()
.staticReference(
inliner, classIdent().getTopLevelClass(), classIdent().getName(), getName());
}
@Override
protected Choice<Unifier> defaultAction(Tree node, Unifier unifier) {
Symbol symbol = ASTHelpers.getSymbol(node);
if (symbol != null) {
return classIdent()
.unify(symbol.getEnclosingElement(), unifier)
.thenChoose(unifications(getName(), symbol.getSimpleName()))
.thenChoose(unifications(memberType(), symbol.asType()));
}
return Choice.none();
}
}
| 2,528
| 33.175676
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UVariableDecl.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.refaster;
import static com.google.errorprone.refaster.Unifier.unifications;
import com.google.auto.value.AutoValue;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.ModifiersTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.tree.JCTree.JCModifiers;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.Name;
import javax.annotation.Nullable;
/**
* A {@link UTree} representation of a local variable declaration.
*
* <p>A {@code UVariableDecl} can be unified with any variable declaration which has a matching type
* and initializer. Annotations and modifiers are preserved for the corresponding replacement, as
* well as the variable name. {@link ULocalVarIdent} instances are used to represent references to
* local variables.
*
* <p>As a result, we can modify variable declarations and initializations in target code while
* preserving variable names and other contextual information.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
public abstract class UVariableDecl extends USimpleStatement implements VariableTree {
public static UVariableDecl create(
CharSequence identifier, UExpression type, @Nullable UExpression initializer) {
return new AutoValue_UVariableDecl(StringName.of(identifier), type, initializer);
}
public static UVariableDecl create(CharSequence identifier, UExpression type) {
return create(identifier, type, null);
}
@Override
public abstract StringName getName();
@Override
public abstract UExpression getType();
@Override
@Nullable
public abstract UExpression getInitializer();
ULocalVarIdent.Key key() {
return new ULocalVarIdent.Key(getName());
}
@Override
public Choice<Unifier> visitVariable(VariableTree decl, Unifier unifier) {
return Choice.condition(unifier.getBinding(key()) == null, unifier)
.thenChoose(unifications(getType(), decl.getType()))
.thenChoose(unifications(getInitializer(), decl.getInitializer()))
.transform(
new Function<Unifier, Unifier>() {
@Override
public Unifier apply(Unifier unifier) {
unifier.putBinding(
key(), LocalVarBinding.create(ASTHelpers.getSymbol(decl), decl.getModifiers()));
return unifier;
}
});
}
@Override
public JCVariableDecl inline(Inliner inliner) throws CouldNotResolveImportException {
return inline(getType(), inliner);
}
public JCVariableDecl inlineImplicitType(Inliner inliner) throws CouldNotResolveImportException {
return inline(null, inliner);
}
private JCVariableDecl inline(@Nullable UExpression type, Inliner inliner)
throws CouldNotResolveImportException {
Optional<LocalVarBinding> binding = inliner.getOptionalBinding(key());
JCModifiers modifiers;
Name name;
TreeMaker maker = inliner.maker();
if (binding.isPresent()) {
modifiers = (JCModifiers) binding.get().getModifiers();
name = binding.get().getName();
} else {
modifiers = maker.Modifiers(0L);
name = getName().inline(inliner);
}
return maker.VarDef(
modifiers,
name,
(type == null) ? null : type.inline(inliner),
(getInitializer() == null) ? null : getInitializer().inline(inliner));
}
@Override
public Kind getKind() {
return Kind.VARIABLE;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitVariable(this, data);
}
@Override
public ModifiersTree getModifiers() {
return null;
}
@Override
public ExpressionTree getNameExpression() {
return null;
}
}
| 4,569
| 31.877698
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UArrayType.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.refaster;
import com.google.auto.value.AutoValue;
import com.sun.tools.javac.code.Type.ArrayType;
import javax.annotation.Nullable;
/**
* {@link UType} version of {@link ArrayType}, which represents a type {@code T[]} based on the type
* {@code T}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UArrayType extends UType {
public static UArrayType create(UType componentType) {
return new AutoValue_UArrayType(componentType);
}
abstract UType componentType();
@Override
@Nullable
public Choice<Unifier> visitArrayType(ArrayType arrayType, @Nullable Unifier unifier) {
return componentType().unify(arrayType.getComponentType(), unifier);
}
@Override
public ArrayType inline(Inliner inliner) throws CouldNotResolveImportException {
return new ArrayType(componentType().inline(inliner), inliner.symtab().arrayClass);
}
}
| 1,529
| 30.875
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UMatches.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.refaster;
import com.google.auto.value.AutoValue;
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.source.tree.Tree;
import com.sun.source.tree.TreeVisitor;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.util.Context;
import javax.annotation.Nullable;
/**
* {@code UMatches} allows conditionally matching a {@code UExpression} predicated by an error-prone
* {@code Matcher}.
*/
@AutoValue
abstract class UMatches extends UExpression {
public static UMatches create(
Class<? extends Matcher<? super ExpressionTree>> matcherClass,
boolean positive,
UExpression expression) {
// Verify that we can instantiate the Matcher
makeMatcher(matcherClass);
return new AutoValue_UMatches(positive, matcherClass, expression);
}
abstract boolean positive();
abstract Class<? extends Matcher<? super ExpressionTree>> matcherClass();
abstract UExpression expression();
@Override
@Nullable
protected Choice<Unifier> defaultAction(Tree target, @Nullable Unifier unifier) {
Tree exprTarget = ASTHelpers.stripParentheses(target);
return expression()
.unify(exprTarget, unifier)
.condition((Unifier success) -> matches(exprTarget, success) == positive());
}
@Override
public JCExpression inline(Inliner inliner) throws CouldNotResolveImportException {
throw new UnsupportedOperationException("@Matches should not appear in an @AfterTemplate");
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return expression().accept(visitor, data);
}
@Override
public Kind getKind() {
return Kind.OTHER;
}
private transient Matcher<? super ExpressionTree> matcher;
private boolean matches(Tree target, Unifier unifier) {
if (matcher == null) {
matcher = makeMatcher(matcherClass());
}
return target instanceof ExpressionTree
&& matcher.matches((ExpressionTree) target, makeVisitorState(target, unifier));
}
static <T> T makeMatcher(Class<T> klass) {
try {
return klass.newInstance();
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
static VisitorState makeVisitorState(Tree target, Unifier unifier) {
Context context = unifier.getContext();
VisitorState state = new VisitorState(context);
TreePath path = TreePath.getPath(context.get(JCCompilationUnit.class), target);
if (path != null) {
state = state.withPath(path);
}
return state;
}
}
| 3,381
| 30.90566
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UMethodDecl.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.refaster;
import static com.google.errorprone.refaster.Unifier.unifications;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.source.tree.TypeParameterTree;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.tree.JCTree.JCTypeParameter;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.util.List;
import javax.annotation.Nullable;
/**
* {@code UTree} representation of a {@code MethodTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UMethodDecl extends UTree<JCMethodDecl> implements MethodTree {
public static UMethodDecl create(
UModifiers modifiers,
CharSequence name,
UExpression returnType,
Iterable<UVariableDecl> parameters,
Iterable<UExpression> thrown,
UBlock body) {
return new AutoValue_UMethodDecl(
modifiers,
StringName.of(name),
returnType,
ImmutableList.copyOf(parameters),
ImmutableList.copyOf(thrown),
body);
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitMethod(this, data);
}
@Override
public Kind getKind() {
return Kind.METHOD;
}
@Override
@Nullable
public Choice<Unifier> visitMethod(MethodTree decl, @Nullable Unifier unifier) {
return getName()
.unify(decl.getName(), unifier)
.thenChoose(unifications(getReturnType(), decl.getReturnType()))
.thenChoose(unifications(getParameters(), decl.getParameters()))
.thenChoose(unifications(getThrows(), decl.getThrows()))
.thenChoose(unifications(getBody(), decl.getBody()));
}
@Override
public JCMethodDecl inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.MethodDef(
getModifiers().inline(inliner),
getName().inline(inliner),
getReturnType().inline(inliner),
List.<JCTypeParameter>nil(),
List.convert(JCVariableDecl.class, inliner.inlineList(getParameters())),
inliner.<JCExpression>inlineList(getThrows()),
getBody().inline(inliner),
null);
}
@Override
public abstract UModifiers getModifiers();
@Override
public abstract StringName getName();
@Override
public abstract UExpression getReturnType();
@Override
public abstract ImmutableList<UVariableDecl> getParameters();
@Override
public abstract ImmutableList<UExpression> getThrows();
@Override
public abstract UBlock getBody();
@Override
public UTree<?> getDefaultValue() {
return null;
}
@Override
public ImmutableList<? extends TypeParameterTree> getTypeParameters() {
return ImmutableList.of();
}
@Override
public VariableTree getReceiverParameter() {
return null;
}
}
| 3,701
| 28.380952
| 85
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UExpression.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.refaster;
import com.sun.source.tree.ExpressionTree;
import com.sun.tools.javac.tree.JCTree.JCExpression;
/**
* {@link UTree} version of {@link ExpressionTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
public abstract class UExpression extends UTree<JCExpression> implements ExpressionTree {
public UExpression negate() {
return UUnary.create(Kind.LOGICAL_COMPLEMENT, this);
}
}
| 1,034
| 33.5
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/TemplateMatch.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.refaster;
import static com.google.common.base.Preconditions.checkNotNull;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import java.io.IOException;
/**
* Abstract type representing a match against a {@code Template}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
public abstract class TemplateMatch {
private final JCTree location;
private final Unifier unifier;
public TemplateMatch(JCTree location, Unifier unifier) {
this.location = checkNotNull(location);
this.unifier = checkNotNull(unifier);
}
public JCTree getLocation() {
return location;
}
public Unifier getUnifier() {
return unifier;
}
public Inliner createInliner() {
return unifier.createInliner();
}
public String getRange(JCCompilationUnit unit) {
try {
CharSequence sequence = unit.getSourceFile().getCharContent(true);
return sequence
.subSequence(location.getStartPosition(), location.getEndPosition(unit.endPositions))
.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| 1,767
| 27.516129
| 95
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UClassType.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.refaster;
import static com.google.errorprone.refaster.Unifier.unifications;
import static com.sun.tools.javac.code.Flags.STATIC;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.ClassType;
import java.util.List;
/**
* A representation of a type with optional generic parameters.
*
* @author Louis Wasserman
*/
@AutoValue
public abstract class UClassType extends UType {
public static UClassType create(CharSequence fullyQualifiedClass, List<UType> typeArguments) {
return new AutoValue_UClassType(
StringName.of(fullyQualifiedClass), ImmutableList.copyOf(typeArguments));
}
public static UClassType create(String fullyQualifiedClass, UType... typeArguments) {
return create(fullyQualifiedClass, ImmutableList.copyOf(typeArguments));
}
abstract StringName fullyQualifiedClass();
abstract ImmutableList<UType> typeArguments();
@Override
public Choice<Unifier> visitClassType(ClassType classType, Unifier unifier) {
return fullyQualifiedClass()
.unify(classType.tsym.getQualifiedName(), unifier)
.thenChoose(unifications(typeArguments(), classType.getTypeArguments()));
}
@Override
public ClassType inline(Inliner inliner) throws CouldNotResolveImportException {
ClassSymbol classSymbol = inliner.resolveClass(fullyQualifiedClass());
boolean isNonStaticInnerClass =
classSymbol.owner instanceof ClassSymbol && (classSymbol.flags() & STATIC) == 0;
Type owner = isNonStaticInnerClass ? classSymbol.owner.type : Type.noType;
return new ClassType(owner, inliner.<Type>inlineList(typeArguments()), classSymbol);
}
}
| 2,408
| 36.061538
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UPlaceholderExpression.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.refaster;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.auto.value.AutoValue;
import com.google.common.base.Functions;
import com.google.common.base.MoreObjects;
import com.google.common.base.Optional;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCIdent;
import com.sun.tools.javac.tree.TreeCopier;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Names;
import java.util.Map;
/**
* {@code UTree} representation of an invocation of a placeholder method.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
public abstract class UPlaceholderExpression extends UExpression {
static UPlaceholderExpression create(
PlaceholderMethod placeholder, Iterable<? extends UExpression> arguments) {
ImmutableList<UVariableDecl> placeholderParams = placeholder.parameters().asList();
ImmutableList<UExpression> argumentsList = ImmutableList.copyOf(arguments);
ImmutableMap.Builder<UVariableDecl, UExpression> builder = ImmutableMap.builder();
for (int i = 0; i < placeholderParams.size(); i++) {
builder.put(placeholderParams.get(i), argumentsList.get(i));
}
return new AutoValue_UPlaceholderExpression(placeholder, builder.buildOrThrow());
}
abstract PlaceholderMethod placeholder();
abstract ImmutableMap<UVariableDecl, UExpression> arguments();
public static final class PlaceholderParamIdent extends JCIdent {
final UVariableDecl param;
PlaceholderParamIdent(UVariableDecl param, Context context) {
super(Names.instance(context).fromString(param.getName().contents()), null);
this.param = checkNotNull(param);
}
}
static class UncheckedCouldNotResolveImportException extends RuntimeException {
UncheckedCouldNotResolveImportException(CouldNotResolveImportException e) {
super(e);
}
@Override
public synchronized CouldNotResolveImportException getCause() {
return (CouldNotResolveImportException) super.getCause();
}
}
static TreeCopier<Inliner> copier(Map<UVariableDecl, UExpression> arguments, Inliner inliner) {
return new TreeCopier<Inliner>(inliner.maker()) {
@Override
public <T extends JCTree> T copy(T tree, Inliner inliner) {
if (tree == null) {
return null;
}
T result = super.copy(tree, inliner);
if (result.toString().equals(tree.toString())) {
return tree;
} else {
return result;
}
}
@Override
public JCTree visitIdentifier(IdentifierTree node, Inliner inliner) {
if (node instanceof PlaceholderParamIdent) {
try {
return arguments.get(((PlaceholderParamIdent) node).param).inline(inliner);
} catch (CouldNotResolveImportException e) {
throw new UncheckedCouldNotResolveImportException(e);
}
} else {
return super.visitIdentifier(node, inliner);
}
}
};
}
@Override
public JCExpression inline(Inliner inliner) throws CouldNotResolveImportException {
/*
* Copy the original source bound to the placeholder, except anywhere we matched a placeholder
* parameter, replace that with the corresponding expression in this invocation.
*/
try {
return copier(arguments(), inliner)
.copy(inliner.getBinding(placeholder().exprKey()), inliner);
} catch (UncheckedCouldNotResolveImportException e) {
throw e.getCause();
}
}
@Override
public Kind getKind() {
return Kind.OTHER;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitOther(this, data);
}
public boolean reverify(Unifier unifier) {
return MoreObjects.firstNonNull(
new PlaceholderVerificationVisitor(
Collections2.transform(
placeholder().requiredParameters(), Functions.forMap(arguments())),
arguments().values())
.scan(unifier.getBinding(placeholder().exprKey()), unifier),
true);
}
@Override
protected Choice<Unifier> defaultAction(Tree node, Unifier unifier) {
// for now we only match JCExpressions
if (!(node instanceof JCExpression)) {
return Choice.none();
}
JCExpression expr = (JCExpression) node;
PlaceholderVerificationVisitor verification =
new PlaceholderVerificationVisitor(
Collections2.transform(
placeholder().requiredParameters(), Functions.forMap(arguments())),
arguments().values());
if (!verification.scan(node, unifier) || !verification.allRequiredMatched()) {
return Choice.none();
}
/*
* We copy the tree with a TreeCopier, replacing matches for the parameters with
* PlaceholderParamIdents, and updating unifierHolder as we unify things, including forbidding
* references to local variables, etc.
*/
Choice<? extends PlaceholderUnificationVisitor.State<? extends JCExpression>> states =
PlaceholderUnificationVisitor.create(TreeMaker.instance(unifier.getContext()), arguments())
.unifyExpression(
expr,
PlaceholderUnificationVisitor.State.create(
List.<UVariableDecl>nil(), unifier, null));
return states.thenOption(
(PlaceholderUnificationVisitor.State<? extends JCExpression> state) -> {
if (ImmutableSet.copyOf(state.seenParameters())
.containsAll(placeholder().requiredParameters())) {
Unifier resultUnifier = state.unifier();
JCExpression prevBinding = resultUnifier.getBinding(placeholder().exprKey());
if (prevBinding != null) {
return prevBinding.toString().equals(state.result().toString())
? Optional.of(resultUnifier)
: Optional.<Unifier>absent();
}
JCExpression result = state.result();
if (!placeholder()
.matcher()
.matches(result, UMatches.makeVisitorState(expr, resultUnifier))) {
return Optional.absent();
}
result.type = expr.type;
resultUnifier.putBinding(placeholder().exprKey(), result);
return Optional.of(resultUnifier);
} else {
return Optional.absent();
}
});
}
}
| 7,480
| 36.218905
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UClassIdent.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.refaster;
import com.google.auto.value.AutoValue;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.errorprone.util.ASTHelpers;
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.tree.JCTree.JCExpression;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
/**
* Identifier for a class type.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UClassIdent extends UIdent {
@VisibleForTesting
public static UClassIdent create(String qualifiedName) {
List<String> topLevelPath = new ArrayList<>();
for (String component : Splitter.on('.').split(qualifiedName)) {
topLevelPath.add(component);
if (Character.isUpperCase(component.charAt(0))) {
break;
}
}
return create(Joiner.on('.').join(topLevelPath), qualifiedName);
}
public static UClassIdent create(ClassSymbol sym) {
return create(ASTHelpers.outermostClass(sym).getQualifiedName(), sym.getQualifiedName());
}
private static UClassIdent create(CharSequence topLevelClass, CharSequence name) {
return new AutoValue_UClassIdent(topLevelClass.toString(), StringName.of(name));
}
public abstract String getTopLevelClass();
@Override
public abstract StringName getName();
public ClassSymbol resolve(Inliner inliner) throws CouldNotResolveImportException {
return inliner.resolveClass(getName());
}
@Override
public JCExpression inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner.importPolicy().classReference(inliner, getTopLevelClass(), getName());
}
@Override
@Nullable
protected Choice<Unifier> defaultAction(Tree tree, @Nullable Unifier unifier) {
return unify(ASTHelpers.getSymbol(tree), unifier);
}
@Nullable
public Choice<Unifier> unify(@Nullable Symbol symbol, Unifier unifier) {
return symbol != null
? getName().unify(symbol.getQualifiedName(), unifier)
: Choice.<Unifier>none();
}
}
| 2,809
| 31.674419
| 93
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/ExpressionTemplate.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.refaster;
import static com.google.common.base.Preconditions.checkState;
import static java.util.logging.Level.FINE;
import static java.util.logging.Level.SEVERE;
import com.google.auto.value.AutoValue;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableClassToInstanceMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.refaster.annotation.AlsoNegation;
import com.google.errorprone.refaster.annotation.UseImportPolicy;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.api.JavacTrees;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.TypeTag;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCArrayAccess;
import com.sun.tools.javac.tree.JCTree.JCAssign;
import com.sun.tools.javac.tree.JCTree.JCAssignOp;
import com.sun.tools.javac.tree.JCTree.JCBinary;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.tree.JCTree.JCConditional;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
import com.sun.tools.javac.tree.JCTree.JCInstanceOf;
import com.sun.tools.javac.tree.JCTree.JCTypeCast;
import com.sun.tools.javac.tree.JCTree.JCUnary;
import com.sun.tools.javac.tree.TreeInfo;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Warner;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.annotation.Annotation;
import java.util.Map;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Implementation of a template to match and replace an expression anywhere in an AST.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
public abstract class ExpressionTemplate extends Template<ExpressionTemplateMatch>
implements Unifiable<JCExpression> {
private static final Logger logger = Logger.getLogger(ExpressionTemplate.class.toString());
public static ExpressionTemplate create(UExpression expression, UType returnType) {
return create(ImmutableMap.<String, UType>of(), expression, returnType);
}
public static ExpressionTemplate create(
Map<String, ? extends UType> expressionArgumentTypes,
UExpression expression,
UType returnType) {
return create(
ImmutableClassToInstanceMap.of(),
ImmutableList.<UTypeVar>of(),
expressionArgumentTypes,
expression,
returnType);
}
public static ExpressionTemplate create(
ImmutableClassToInstanceMap<Annotation> annotations,
Iterable<UTypeVar> typeVariables,
Map<String, ? extends UType> expressionArgumentTypes,
UExpression expression,
UType returnType) {
return new AutoValue_ExpressionTemplate(
annotations,
ImmutableList.copyOf(typeVariables),
ImmutableMap.copyOf(expressionArgumentTypes),
expression,
returnType);
}
abstract UExpression expression();
abstract UType returnType();
public boolean generateNegation() {
return annotations().containsKey(AlsoNegation.class);
}
public ExpressionTemplate negation() {
checkState(
returnType().equals(UPrimitiveType.BOOLEAN),
"Return type must be boolean to generate negation, but was %s",
returnType());
return create(
annotations(),
templateTypeVariables(),
expressionArgumentTypes(),
expression().negate(),
returnType());
}
/** Returns the matches of this template against the specified target AST. */
@Override
public Iterable<ExpressionTemplateMatch> match(JCTree target, Context context) {
if (target instanceof JCExpression) {
JCExpression targetExpr = (JCExpression) target;
Optional<Unifier> unifier = unify(targetExpr, new Unifier(context)).first();
if (unifier.isPresent()) {
return ImmutableList.of(new ExpressionTemplateMatch(targetExpr, unifier.get()));
}
}
return ImmutableList.of();
}
static boolean trueOrNull(@Nullable Boolean b) {
return b == null || b;
}
/**
* Placeholders' verification step only checks that they use variables that haven't *yet* been
* matched to another local variable. This scanner reruns the verification step for the whole
* tree, returning false if a violation was found, and true or null otherwise.
*/
static final TreeScanner<Boolean, Unifier> PLACEHOLDER_VERIFIER =
new TreeScanner<Boolean, Unifier>() {
@Override
public Boolean reduce(Boolean a, Boolean b) {
return trueOrNull(a) && trueOrNull(b);
}
@Override
public Boolean visitOther(Tree t, Unifier u) {
if (t instanceof UPlaceholderExpression) {
return ((UPlaceholderExpression) t).reverify(u);
} else if (t instanceof UPlaceholderStatement) {
return ((UPlaceholderStatement) t).reverify(u);
} else {
return super.visitOther(t, u);
}
}
};
@Override
public Choice<Unifier> unify(JCExpression target, Unifier unifier) {
return expression()
.unify(target, unifier)
.condition(u -> trueOrNull(PLACEHOLDER_VERIFIER.scan(expression(), u)))
.thenOption(
new Function<Unifier, Optional<Unifier>>() {
@Override
public Optional<Unifier> apply(Unifier unifier) {
Inliner inliner = unifier.createInliner();
try {
List<Type> expectedTypes = expectedTypes(inliner);
List<Type> actualTypes = actualTypes(inliner);
/*
* TODO(cushon): the following is not true in javac8, which can apply target-typing to
* nested method invocations.
*
* The Java compiler's type inference doesn't directly take into account the expected
* return type, so we test the return type by treating the expected return type as an
* extra method argument, and the actual type of the return expression as its actual
* value.
*/
if (target.type.getTag() != TypeTag.VOID) {
expectedTypes = expectedTypes.prepend(returnType().inline(inliner));
Type ty = target.type;
// Java 8 types conditional expressions by taking the *widest* possible type
// they could be allowed, instead of the narrowest, where Refaster really wants
// the narrowest type possible. We reconstruct that by taking the lub of the
// types from each branch.
if (target.getKind() == Kind.CONDITIONAL_EXPRESSION) {
JCConditional cond = (JCConditional) target;
Type trueTy = cond.truepart.type;
Type falseTy = cond.falsepart.type;
if (trueTy.getTag() == TypeTag.BOT) {
ty = falseTy;
} else if (falseTy.getTag() == TypeTag.BOT) {
ty = trueTy;
} else {
ty = Types.instance(unifier.getContext()).lub(trueTy, falseTy);
}
}
actualTypes = actualTypes.prepend(ty);
}
return typecheck(
unifier, inliner, new Warner(target), expectedTypes, actualTypes);
} catch (CouldNotResolveImportException e) {
logger.log(FINE, "Failure to resolve import", e);
return Optional.absent();
}
}
});
}
/**
* Generates a {@link SuggestedFix} replacing the specified match (usually of another template)
* with this template.
*/
@Override
public Fix replace(ExpressionTemplateMatch match) {
Inliner inliner = match.createInliner();
Context context = inliner.getContext();
if (annotations().containsKey(UseImportPolicy.class)) {
ImportPolicy.bind(context, annotations().getInstance(UseImportPolicy.class).value());
} else {
ImportPolicy.bind(context, ImportPolicy.IMPORT_TOP_LEVEL);
}
int prec = getPrecedence(match.getLocation(), context);
SuggestedFix.Builder fix = SuggestedFix.builder();
try {
StringWriter writer = new StringWriter();
pretty(inliner.getContext(), writer).printExpr(expression().inline(inliner), prec);
fix.replace(match.getLocation(), writer.toString());
} catch (CouldNotResolveImportException e) {
logger.log(SEVERE, "Failure to resolve in replacement", e);
} catch (IOException e) {
throw new RuntimeException(e);
}
return addImports(inliner, fix);
}
/**
* Returns the precedence level appropriate for unambiguously printing leaf as a subexpression of
* its parent.
*/
private static int getPrecedence(JCTree leaf, Context context) {
JCCompilationUnit comp = context.get(JCCompilationUnit.class);
JCTree parent =
(JCTree) JavacTrees.instance(context).getPath(comp, leaf).getParentPath().getLeaf();
// In general, this should match the logic in com.sun.tools.javac.tree.Pretty.
//
// TODO(mdempsky): There are probably cases where we could omit parentheses
// by tweaking the returned precedence, but they need careful review.
// For example, consider a template to replace "add(a, b)" with "a + b",
// which applied to "x + add(y, z)" would result in "x + (y + z)".
// In most cases, we'd likely prefer "x + y + z" instead, but those aren't
// always equivalent: "0L + (Integer.MIN_VALUE + Integer.MIN_VALUE)" yields
// a different value than "0L + Integer.MIN_VALUE + Integer.MIN_VALUE" due
// to integer promotion rules.
if (parent instanceof JCConditional) {
// This intentionally differs from Pretty, because Pretty appears buggy:
// http://mail.openjdk.java.net/pipermail/compiler-dev/2013-September/007303.html
JCConditional conditional = (JCConditional) parent;
return TreeInfo.condPrec + ((conditional.cond == leaf) ? 1 : 0);
} else if (parent instanceof JCAssign) {
JCAssign assign = (JCAssign) parent;
return TreeInfo.assignPrec + ((assign.lhs == leaf) ? 1 : 0);
} else if (parent instanceof JCAssignOp) {
JCAssignOp assignOp = (JCAssignOp) parent;
return TreeInfo.assignopPrec + ((assignOp.lhs == leaf) ? 1 : 0);
} else if (parent instanceof JCUnary) {
return TreeInfo.opPrec(parent.getTag());
} else if (parent instanceof JCBinary) {
JCBinary binary = (JCBinary) parent;
return TreeInfo.opPrec(parent.getTag()) + ((binary.rhs == leaf) ? 1 : 0);
} else if (parent instanceof JCTypeCast) {
JCTypeCast typeCast = (JCTypeCast) parent;
return (typeCast.expr == leaf) ? TreeInfo.prefixPrec : TreeInfo.noPrec;
} else if (parent instanceof JCInstanceOf) {
JCInstanceOf instanceOf = (JCInstanceOf) parent;
return TreeInfo.ordPrec + ((instanceOf.getType() == leaf) ? 1 : 0);
} else if (parent instanceof JCArrayAccess) {
JCArrayAccess arrayAccess = (JCArrayAccess) parent;
return (arrayAccess.indexed == leaf) ? TreeInfo.postfixPrec : TreeInfo.noPrec;
} else if (parent instanceof JCFieldAccess) {
JCFieldAccess fieldAccess = (JCFieldAccess) parent;
return (fieldAccess.selected == leaf) ? TreeInfo.postfixPrec : TreeInfo.noPrec;
} else {
return TreeInfo.noPrec;
}
}
}
| 12,551
| 40.979933
| 104
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.