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/refaster/UParens.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.util.ASTHelpers.stripParentheses;
import com.google.auto.value.AutoValue;
import com.sun.source.tree.ParenthesizedTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCParens;
/**
* {@link UTree} version of {@link ParenthesizedTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UParens extends UExpression implements ParenthesizedTree {
public static UParens create(UExpression expression) {
return new AutoValue_UParens(expression);
}
@Override
public abstract UExpression getExpression();
@Override
protected Choice<Unifier> defaultAction(Tree tree, Unifier unifier) {
return getExpression().unify(stripParentheses(tree), unifier);
}
@Override
public Kind getKind() {
return Kind.PARENTHESIZED;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitParenthesized(this, data);
}
@Override
public JCParens inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner.maker().Parens(getExpression().inline(inliner));
}
@Override
public UExpression negate() {
return create(getExpression().negate());
}
}
| 1,918
| 28.075758
| 81
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UMethodType.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.unifyList;
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.MethodType;
import java.util.List;
import javax.annotation.Nullable;
/**
* A {@code UType} representation of a {@link MethodType}. This can be used to e.g. disambiguate
* method overloads.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
public abstract class UMethodType extends UType {
public static UMethodType create(UType returnType, UType... parameterTypes) {
return create(returnType, ImmutableList.copyOf(parameterTypes));
}
public static UMethodType create(UType returnType, List<UType> parameterTypes) {
return new AutoValue_UMethodType(returnType, ImmutableList.copyOf(parameterTypes));
}
public abstract UType getReturnType();
public abstract ImmutableList<UType> getParameterTypes();
@Override
@Nullable
public Choice<Unifier> visitMethodType(MethodType methodTy, @Nullable Unifier unifier) {
// Don't unify the return type, which doesn't matter in overload resolution.
return unifyList(unifier, getParameterTypes(), methodTy.getParameterTypes());
}
@Override
public MethodType inline(Inliner inliner) throws CouldNotResolveImportException {
return new MethodType(
inliner.<Type>inlineList(getParameterTypes()),
getReturnType().inline(inliner),
com.sun.tools.javac.util.List.<Type>nil(),
inliner.symtab().methodClass);
}
}
| 2,217
| 33.123077
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/USynchronized.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.SynchronizedTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCSynchronized;
/**
* {@link UTree} representation of a {@link SynchronizedTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class USynchronized extends USimpleStatement implements SynchronizedTree {
public static USynchronized create(UExpression expression, UBlock block) {
return new AutoValue_USynchronized(expression, block);
}
@Override
public abstract UExpression getExpression();
@Override
public abstract UBlock getBlock();
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitSynchronized(this, data);
}
@Override
public Kind getKind() {
return Kind.SYNCHRONIZED;
}
@Override
public JCSynchronized inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.Synchronized(getExpression().inline(inliner), getBlock().inline(inliner));
}
@Override
public Choice<Unifier> visitSynchronized(SynchronizedTree synced, Unifier unifier) {
return getExpression()
.unify(synced.getExpression(), unifier)
.thenChoose(unifications(getBlock(), synced.getBlock()));
}
}
| 2,039
| 29.447761
| 87
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/PlaceholderVerificationVisitor.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.MoreObjects.firstNonNull;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
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.tree.JCTree.JCExpression;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* Cheap visitor to verify that a tree or set of trees could conceivably match a placeholder, by
* potentially matching at least all of the required expressions, and not matching forbidden
* expressions, i.e. other variables known to Refaster.
*
* @author lowasser@google.com (Louis Wasserman)
*/
final class PlaceholderVerificationVisitor extends TreeScanner<Boolean, Unifier> {
private final List<UExpression> unmatched;
private final ImmutableList<UExpression> allowed;
/**
* @param required UExpressions that must potentially match at least one expression in the tested
* code.
* @param allowed UExpressions that are explicitly allowed, and excepted from the ban on
* references to known variables
*/
PlaceholderVerificationVisitor(
Collection<? extends UExpression> required, Collection<? extends UExpression> allowed) {
this.unmatched = new LinkedList<>(required);
this.allowed = ImmutableList.copyOf(allowed);
Preconditions.checkArgument(this.allowed.containsAll(unmatched), "allowed");
}
public boolean allRequiredMatched() {
return unmatched.isEmpty();
}
private boolean couldUnify(UExpression expr, Tree tree, Unifier unifier) {
return expr.unify(tree, unifier.fork()).first().isPresent();
}
@Override
public Boolean scan(Tree node, Unifier unifier) {
Iterator<UExpression> iterator = unmatched.iterator();
while (iterator.hasNext()) {
if (couldUnify(iterator.next(), node, unifier)) {
iterator.remove();
return true;
}
}
for (UExpression expr : allowed) {
if (couldUnify(expr, node, unifier)) {
return true;
}
}
if (node instanceof JCExpression) {
JCExpression expr = (JCExpression) node;
for (UFreeIdent.Key key :
Iterables.filter(unifier.getBindings().keySet(), UFreeIdent.Key.class)) {
JCExpression keyBinding = unifier.getBinding(key);
if (PlaceholderUnificationVisitor.equivalentExprs(unifier, expr, keyBinding)) {
return false;
}
}
}
return firstNonNull(super.scan(node, unifier), true);
}
@Override
public Boolean visitIdentifier(IdentifierTree node, Unifier unifier) {
for (LocalVarBinding localBinding :
Iterables.filter(unifier.getBindings().values(), LocalVarBinding.class)) {
if (localBinding.getSymbol().equals(ASTHelpers.getSymbol(node))) {
return false;
}
}
return true;
}
@Override
public Boolean reduce(Boolean r1, Boolean r2) {
return firstNonNull(r1, true) && firstNonNull(r2, true);
}
}
| 3,769
| 34.233645
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/Bindings.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.base.MoreObjects;
import com.google.common.base.Objects;
import com.google.common.collect.ForwardingMap;
import com.google.common.collect.Maps;
import com.google.common.reflect.TypeToken;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A type-safe map from objects of type {@code Bindings.Key<V>}, which consist of a {@code String}
* key and a {@code Bindings.Key} subclass, to values of type {@code V}.
*
* @author Louis Wasserman
*/
public class Bindings extends ForwardingMap<Bindings.Key<?>, Object> {
/**
* A key type for a {@code Binding}. Users must subclass {@code Key} with a specific literal
* {@code V} type.
*/
public abstract static class Key<V> {
private final String identifier;
protected Key(String identifier) {
this.identifier = checkNotNull(identifier);
}
public String getIdentifier() {
return identifier;
}
TypeToken<V> getValueType() {
return new TypeToken<V>(getClass()) {};
}
@Override
public int hashCode() {
return Objects.hashCode(getClass(), identifier);
}
@Override
@SuppressWarnings("EqualsGetClass")
public boolean equals(@Nullable Object obj) {
// explicitly call getClass so that objects of different subclasses return false.
if (obj != null && this.getClass() == obj.getClass()) {
Key<?> key = (Key<?>) obj;
return identifier.equals(key.identifier);
}
return false;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this).add("identifier", identifier).toString();
}
}
private final Map<Key<?>, Object> contents;
public static Bindings create() {
return new Bindings();
}
public static <V> Bindings create(Key<V> key, V value) {
Bindings result = create();
result.putBinding(key, value);
return result;
}
public static <V1, V2> Bindings create(Key<V1> key1, V1 value1, Key<V2> key2, V2 value2) {
Bindings result = create();
result.putBinding(key1, value1);
result.putBinding(key2, value2);
return result;
}
public static Bindings create(Bindings bindings) {
return new Bindings(bindings);
}
private Bindings() {
this(new HashMap<>());
}
Bindings(Bindings bindings) {
this(Maps.newHashMap(bindings.contents));
}
private Bindings(Map<Key<?>, Object> contents) {
this.contents = contents;
}
@Override
protected Map<Key<?>, Object> delegate() {
return contents;
}
@SuppressWarnings("unchecked")
public <V> V getBinding(Key<V> key) {
checkNotNull(key);
return (V) super.get(key);
}
@SuppressWarnings("unchecked")
public <V> V putBinding(Key<V> key, V value) {
checkNotNull(value);
return (V) super.put(key, value);
}
@CanIgnoreReturnValue
@Nullable
@Override
public Object put(Key<?> key, Object value) {
checkNotNull(key, "key");
checkNotNull(value, "value");
return super.put(key, key.getValueType().getRawType().cast(value));
}
@Override
public void putAll(Map<? extends Key<?>, ? extends Object> map) {
standardPutAll(map);
}
public Bindings unmodifiable() {
return new Bindings(Collections.unmodifiableMap(contents));
}
}
| 4,085
| 26.24
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UBreak.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.errorprone.util.RuntimeVersion;
import com.sun.source.tree.BreakTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCBreak;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.Name;
import java.util.Objects;
import javax.annotation.Nullable;
/**
* {@code UTree} representation of {@code BreakTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
final class UBreak extends USimpleStatement implements BreakTree {
private final StringName label;
UBreak(StringName label) {
this.label = label;
}
static UBreak create(@Nullable CharSequence label) {
return new UBreak((label == null) ? null : StringName.of(label));
}
// TODO(b/176098078): Add @Override once compiling JDK 12+
@Nullable
public ExpressionTree getValue() {
return null;
}
@Override
@Nullable
public StringName getLabel() {
return label;
}
@Override
public Kind getKind() {
return Kind.BREAK;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitBreak(this, data);
}
private ULabeledStatement.Key key() {
return new ULabeledStatement.Key(getLabel());
}
@Override
public JCBreak inline(Inliner inliner) {
return makeBreak(ULabeledStatement.inlineLabel(getLabel(), inliner), inliner);
}
private static JCBreak makeBreak(Name label, Inliner inliner) {
try {
if (RuntimeVersion.isAtLeast12()) {
return (JCBreak)
TreeMaker.class
.getMethod("Break", JCExpression.class)
.invoke(inliner.maker(), inliner.maker().Ident(label));
} else {
return (JCBreak)
TreeMaker.class.getMethod("Break", Name.class).invoke(inliner.maker(), label);
}
} catch (ReflectiveOperationException e) {
throw new LinkageError(e.getMessage(), e);
}
}
@Override
public Choice<Unifier> visitBreak(BreakTree node, Unifier unifier) {
if (getLabel() == null) {
return Choice.condition(node.getLabel() == null, unifier);
} else {
CharSequence boundName = unifier.getBinding(key());
return Choice.condition(
boundName != null && node.getLabel().contentEquals(boundName), unifier);
}
}
@Override
public int hashCode() {
return Objects.hashCode(label);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof UBreak)) {
return false;
}
UBreak other = (UBreak) obj;
return Objects.equals(label, other.label);
}
}
| 3,301
| 26.747899
| 90
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UForLoop.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.ForLoopTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCExpressionStatement;
import com.sun.tools.javac.tree.JCTree.JCForLoop;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import javax.annotation.Nullable;
/**
* {@link UTree} representation of a {@link ForLoopTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UForLoop extends USimpleStatement implements ForLoopTree {
public static UForLoop create(
Iterable<? extends UStatement> initializer,
@Nullable UExpression condition,
Iterable<? extends UExpressionStatement> update,
UStatement statement) {
return new AutoValue_UForLoop(
ImmutableList.copyOf(initializer),
condition,
ImmutableList.copyOf(update),
(USimpleStatement) statement);
}
@Override
public abstract ImmutableList<UStatement> getInitializer();
@Override
@Nullable
public abstract UExpression getCondition();
@Override
public abstract ImmutableList<UExpressionStatement> getUpdate();
@Override
public abstract USimpleStatement getStatement();
@Override
@Nullable
public Choice<Unifier> visitForLoop(ForLoopTree loop, @Nullable Unifier unifier) {
return UBlock.unifyStatementList(getInitializer(), loop.getInitializer(), unifier)
.thenChoose(unifications(getCondition(), loop.getCondition()))
.thenChoose(unifications(getUpdate(), loop.getUpdate()))
.thenChoose(unifications(getStatement(), loop.getStatement()));
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitForLoop(this, data);
}
@Override
public Kind getKind() {
return Kind.FOR_LOOP;
}
@Override
public JCForLoop inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.ForLoop(
UBlock.inlineStatementList(getInitializer(), inliner),
(getCondition() == null) ? null : getCondition().inline(inliner),
com.sun.tools.javac.util.List.convert(
JCExpressionStatement.class, inliner.<JCStatement>inlineList(getUpdate())),
getStatement().inline(inliner));
}
}
| 3,053
| 31.489362
| 91
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/PlaceholderUnificationVisitor.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.checkState;
import com.google.auto.value.AutoValue;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.errorprone.refaster.PlaceholderUnificationVisitor.State;
import com.google.errorprone.refaster.UPlaceholderExpression.PlaceholderParamIdent;
import com.google.errorprone.util.ASTHelpers;
import com.google.errorprone.util.RuntimeVersion;
import com.sun.source.tree.ArrayAccessTree;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.CatchTree;
import com.sun.source.tree.CompoundAssignmentTree;
import com.sun.source.tree.ConditionalExpressionTree;
import com.sun.source.tree.DoWhileLoopTree;
import com.sun.source.tree.EnhancedForLoopTree;
import com.sun.source.tree.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.LabeledStatementTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.NewArrayTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.ParenthesizedTree;
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.TreeVisitor;
import com.sun.source.tree.TryTree;
import com.sun.source.tree.TypeCastTree;
import com.sun.source.tree.UnaryTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.tree.WhileLoopTree;
import com.sun.source.util.SimpleTreeVisitor;
import com.sun.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.JCBlock;
import com.sun.tools.javac.tree.JCTree.JCCase;
import com.sun.tools.javac.tree.JCTree.JCCatch;
import com.sun.tools.javac.tree.JCTree.JCConditional;
import com.sun.tools.javac.tree.JCTree.JCDoWhileLoop;
import com.sun.tools.javac.tree.JCTree.JCEnhancedForLoop;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCExpressionStatement;
import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
import com.sun.tools.javac.tree.JCTree.JCForLoop;
import com.sun.tools.javac.tree.JCTree.JCIf;
import com.sun.tools.javac.tree.JCTree.JCInstanceOf;
import com.sun.tools.javac.tree.JCTree.JCLabeledStatement;
import com.sun.tools.javac.tree.JCTree.JCLambda;
import com.sun.tools.javac.tree.JCTree.JCMemberReference;
import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
import com.sun.tools.javac.tree.JCTree.JCModifiers;
import com.sun.tools.javac.tree.JCTree.JCNewArray;
import com.sun.tools.javac.tree.JCTree.JCNewClass;
import com.sun.tools.javac.tree.JCTree.JCParens;
import com.sun.tools.javac.tree.JCTree.JCReturn;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.tree.JCTree.JCSwitch;
import com.sun.tools.javac.tree.JCTree.JCSynchronized;
import com.sun.tools.javac.tree.JCTree.JCThrow;
import com.sun.tools.javac.tree.JCTree.JCTry;
import com.sun.tools.javac.tree.JCTree.JCTypeCast;
import com.sun.tools.javac.tree.JCTree.JCUnary;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.tree.JCTree.JCWhileLoop;
import com.sun.tools.javac.tree.JCTree.Tag;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.Name;
import java.util.EnumSet;
import java.util.Map;
import java.util.function.BiFunction;
import javax.annotation.Nullable;
/**
* Given a tree as input, returns all the ways this placeholder invocation could be matched with
* that tree, represented as States, containing the {@code Unifier}, the list of all parameters of
* the placeholder method that were unified with subtrees of the given tree, and a {@code
* JCExpression} representing the implementation of the placeholder method, with references to the
* placeholder parameters replaced with a corresponding {@code PlaceholderParamIdent}.
*/
@AutoValue
abstract class PlaceholderUnificationVisitor
extends SimpleTreeVisitor<Choice<? extends State<? extends JCTree>>, State<?>> {
/**
* Represents the state of a placeholder unification in progress, including the current unifier
* state, the parameters of the placeholder method that have been bound, and a result used to
* store additional state.
*/
@AutoValue
abstract static class State<R> {
static <R> State<R> create(
List<UVariableDecl> seenParameters, Unifier unifier, @Nullable R result) {
return new AutoValue_PlaceholderUnificationVisitor_State<>(seenParameters, unifier, result);
}
public abstract List<UVariableDecl> seenParameters();
public abstract Unifier unifier();
@Nullable
public abstract R result();
public <R2> State<R2> withResult(R2 result) {
return create(seenParameters(), unifier(), result);
}
public State<R> fork() {
return create(seenParameters(), unifier().fork(), result());
}
}
public static PlaceholderUnificationVisitor create(
TreeMaker maker, Map<UVariableDecl, UExpression> arguments) {
return new AutoValue_PlaceholderUnificationVisitor(maker, ImmutableMap.copyOf(arguments));
}
abstract TreeMaker maker();
abstract ImmutableMap<UVariableDecl, UExpression> arguments();
/**
* Returns all the ways this tree might be unified with the arguments to this placeholder
* invocation. That is, if the placeholder invocation looks like {@code placeholder(arg1, arg2,
* ...)}, then the {@code Choice} will contain any ways this tree can be unified with {@code
* arg1}, {@code arg2}, or the other arguments.
*/
Choice<State<PlaceholderParamIdent>> tryBindArguments(ExpressionTree node, State<?> state) {
return Choice.from(arguments().entrySet())
.thenChoose(
(Map.Entry<UVariableDecl, UExpression> entry) ->
unifyParam(entry.getKey(), entry.getValue(), node, state.fork()));
}
private Choice<State<PlaceholderParamIdent>> unifyParam(
UVariableDecl placeholderParam,
UExpression placeholderArg,
ExpressionTree toUnify,
State<?> state) {
return placeholderArg
.unify(toUnify, state.unifier())
.transform(
(Unifier unifier) ->
State.create(
state.seenParameters().prepend(placeholderParam),
unifier,
new PlaceholderParamIdent(placeholderParam, unifier.getContext())));
}
public Choice<? extends State<? extends JCTree>> unify(@Nullable Tree node, State<?> state) {
if (node instanceof ExpressionTree) {
return unifyExpression((ExpressionTree) node, state);
} else if (node == null) {
return Choice.of(state.<JCTree>withResult(null));
} else {
return node.accept(this, state);
}
}
public Choice<State<List<JCTree>>> unify(
@Nullable Iterable<? extends Tree> nodes, State<?> state) {
if (nodes == null) {
return Choice.of(state.<List<JCTree>>withResult(null));
}
Choice<State<List<JCTree>>> choice = Choice.of(state.withResult(List.<JCTree>nil()));
for (Tree node : nodes) {
choice =
choice.thenChoose(
(State<List<JCTree>> s) ->
unify(node, s)
.transform(
treeState ->
treeState.withResult(s.result().prepend(treeState.result()))));
}
return choice.transform(s -> s.withResult(s.result().reverse()));
}
static boolean equivalentExprs(Unifier unifier, JCExpression expr1, JCExpression expr2) {
return expr1.type != null
&& expr2.type != null
&& Types.instance(unifier.getContext()).isSameType(expr2.type, expr1.type)
&& expr2.toString().equals(expr1.toString());
}
/**
* Verifies that the given tree does not directly conflict with an already-bound {@code
* UFreeIdent} or {@code ULocalVarIdent}.
*/
static final TreeVisitor<Boolean, Unifier> FORBIDDEN_REFERENCE_VISITOR =
new SimpleTreeVisitor<Boolean, Unifier>() {
@Override
protected Boolean defaultAction(Tree node, Unifier unifier) {
if (!(node instanceof JCExpression)) {
return false;
}
JCExpression expr = (JCExpression) node;
for (UFreeIdent.Key key :
Iterables.filter(unifier.getBindings().keySet(), UFreeIdent.Key.class)) {
JCExpression keyBinding = unifier.getBinding(key);
if (equivalentExprs(unifier, expr, keyBinding)) {
return true;
}
}
return false;
}
@Override
public Boolean visitIdentifier(IdentifierTree node, Unifier unifier) {
for (LocalVarBinding localBinding :
Iterables.filter(unifier.getBindings().values(), LocalVarBinding.class)) {
if (localBinding.getSymbol().equals(ASTHelpers.getSymbol(node))) {
return true;
}
}
return defaultAction(node, unifier);
}
};
/**
* Returns all the ways this placeholder invocation might unify with the specified tree: either by
* unifying the entire tree with an argument to the placeholder invocation, or by recursing on the
* subtrees.
*/
@SuppressWarnings("unchecked")
public Choice<? extends State<? extends JCExpression>> unifyExpression(
@Nullable ExpressionTree node, State<?> state) {
if (node == null) {
return Choice.of(state.<JCExpression>withResult(null));
}
Choice<? extends State<? extends JCExpression>> tryBindArguments =
tryBindArguments(node, state);
if (!node.accept(FORBIDDEN_REFERENCE_VISITOR, state.unifier())) {
return tryBindArguments.or((Choice) node.accept(this, state));
} else {
return tryBindArguments;
}
}
/**
* Returns all the ways this placeholder invocation might unify with the specified list of trees.
*/
public Choice<State<List<JCExpression>>> unifyExpressions(
@Nullable Iterable<? extends ExpressionTree> nodes, State<?> state) {
return unify(nodes, state)
.transform(s -> s.withResult(List.convert(JCExpression.class, s.result())));
}
@SuppressWarnings("unchecked")
public Choice<? extends State<? extends JCStatement>> unifyStatement(
@Nullable StatementTree node, State<?> state) {
return (Choice<? extends State<? extends JCStatement>>) unify(node, state);
}
public Choice<State<List<JCStatement>>> unifyStatements(
@Nullable Iterable<? extends StatementTree> nodes, State<?> state) {
return chooseSubtrees(
state, s -> unify(nodes, s), stmts -> List.convert(JCStatement.class, stmts));
}
@Override
protected Choice<State<JCTree>> defaultAction(Tree node, State<?> state) {
return Choice.of(state.withResult((JCTree) node));
}
/**
* This method, and its overloads, take
*
* <ol>
* <li>an initial state
* <li>functions that, given one state, return a branch choosing a subtree
* <li>a function that takes pieces of a tree type and recomposes them
* </ol>
*/
private static <T, R> Choice<State<R>> chooseSubtrees(
State<?> state,
Function<State<?>, Choice<? extends State<? extends T>>> choice1,
Function<T, R> finalizer) {
return choice1.apply(state).transform(s -> s.withResult(finalizer.apply(s.result())));
}
private static <T1, T2, R> Choice<State<R>> chooseSubtrees(
State<?> state,
Function<State<?>, Choice<? extends State<? extends T1>>> choice1,
Function<State<?>, Choice<? extends State<? extends T2>>> choice2,
BiFunction<T1, T2, R> finalizer) {
return choice1
.apply(state)
.thenChoose(
s1 ->
choice2
.apply(s1)
.transform(s2 -> s2.withResult(finalizer.apply(s1.result(), s2.result()))));
}
@FunctionalInterface
private interface TriFunction<T1, T2, T3, R> {
R apply(T1 t1, T2 t2, T3 t3);
}
private static <T1, T2, T3, R> Choice<State<R>> chooseSubtrees(
State<?> state,
Function<State<?>, Choice<? extends State<? extends T1>>> choice1,
Function<State<?>, Choice<? extends State<? extends T2>>> choice2,
Function<State<?>, Choice<? extends State<? extends T3>>> choice3,
TriFunction<T1, T2, T3, R> finalizer) {
return choice1
.apply(state)
.thenChoose(
s1 ->
choice2
.apply(s1)
.thenChoose(
s2 ->
choice3
.apply(s2)
.transform(
s3 ->
s3.withResult(
finalizer.apply(
s1.result(), s2.result(), s3.result())))));
}
@FunctionalInterface
private interface QuadFunction<T1, T2, T3, T4, R> {
R apply(T1 t1, T2 t2, T3 t3, T4 t4);
}
private static <T1, T2, T3, T4, R> Choice<State<R>> chooseSubtrees(
State<?> state,
Function<State<?>, Choice<? extends State<? extends T1>>> choice1,
Function<State<?>, Choice<? extends State<? extends T2>>> choice2,
Function<State<?>, Choice<? extends State<? extends T3>>> choice3,
Function<State<?>, Choice<? extends State<? extends T4>>> choice4,
QuadFunction<T1, T2, T3, T4, R> finalizer) {
return choice1
.apply(state)
.thenChoose(
s1 ->
choice2
.apply(s1)
.thenChoose(
s2 ->
choice3
.apply(s2)
.thenChoose(
s3 ->
choice4
.apply(s3)
.transform(
s4 ->
s4.withResult(
finalizer.apply(
s1.result(),
s2.result(),
s3.result(),
s4.result()))))));
}
@Override
public Choice<State<JCArrayAccess>> visitArrayAccess(ArrayAccessTree node, State<?> state) {
return chooseSubtrees(
state,
s -> unifyExpression(node.getExpression(), s),
s -> unifyExpression(node.getIndex(), s),
maker()::Indexed);
}
@Override
public Choice<State<JCBinary>> visitBinary(BinaryTree node, State<?> state) {
Tag tag = ((JCBinary) node).getTag();
return chooseSubtrees(
state,
s -> unifyExpression(node.getLeftOperand(), s),
s -> unifyExpression(node.getRightOperand(), s),
(l, r) -> maker().Binary(tag, l, r));
}
@Override
public Choice<State<JCMethodInvocation>> visitMethodInvocation(
MethodInvocationTree node, State<?> state) {
return chooseSubtrees(
state,
s -> unifyExpression(node.getMethodSelect(), s),
s -> unifyExpressions(node.getArguments(), s),
(select, args) -> maker().Apply(null, select, args));
}
@Override
public Choice<State<JCFieldAccess>> visitMemberSelect(MemberSelectTree node, State<?> state) {
return chooseSubtrees(
state,
s -> unifyExpression(node.getExpression(), s),
expr -> maker().Select(expr, (Name) node.getIdentifier()));
}
@Override
public Choice<State<JCParens>> visitParenthesized(ParenthesizedTree node, State<?> state) {
return chooseSubtrees(state, s -> unifyExpression(node.getExpression(), s), maker()::Parens);
}
private static final ImmutableSet<Tag> MUTATING_UNARY_TAGS =
ImmutableSet.copyOf(EnumSet.of(Tag.PREINC, Tag.PREDEC, Tag.POSTINC, Tag.POSTDEC));
@Override
public Choice<State<JCUnary>> visitUnary(UnaryTree node, State<?> state) {
Tag tag = ((JCUnary) node).getTag();
return chooseSubtrees(
state, s -> unifyExpression(node.getExpression(), s), expr -> maker().Unary(tag, expr))
.condition(
s ->
!MUTATING_UNARY_TAGS.contains(tag)
|| !(s.result().getExpression() instanceof PlaceholderParamIdent));
}
@Override
public Choice<State<JCTypeCast>> visitTypeCast(TypeCastTree node, State<?> state) {
return chooseSubtrees(
state,
s -> unifyExpression(node.getExpression(), s),
expr -> maker().TypeCast((JCTree) node.getType(), expr));
}
@Override
public Choice<State<JCInstanceOf>> visitInstanceOf(InstanceOfTree node, State<?> state) {
return chooseSubtrees(
state,
s -> unifyExpression(node.getExpression(), s),
expr -> maker().TypeTest(expr, (JCTree) node.getType()));
}
@Override
public Choice<State<JCNewClass>> visitNewClass(NewClassTree node, State<?> state) {
if (node.getEnclosingExpression() != null
|| (node.getTypeArguments() != null && !node.getTypeArguments().isEmpty())
|| node.getClassBody() != null) {
return Choice.none();
}
return chooseSubtrees(
state,
s -> unifyExpression(node.getIdentifier(), s),
s -> unifyExpressions(node.getArguments(), s),
(ident, args) -> maker().NewClass(null, null, ident, args, null));
}
@Override
public Choice<State<JCNewArray>> visitNewArray(NewArrayTree node, State<?> state) {
return chooseSubtrees(
state,
s -> unifyExpressions(node.getDimensions(), s),
s -> unifyExpressions(node.getInitializers(), s),
(dims, inits) -> maker().NewArray((JCExpression) node.getType(), dims, inits));
}
@Override
public Choice<State<JCConditional>> visitConditionalExpression(
ConditionalExpressionTree node, State<?> state) {
return chooseSubtrees(
state,
s -> unifyExpression(node.getCondition(), s),
s -> unifyExpression(node.getTrueExpression(), s),
s -> unifyExpression(node.getFalseExpression(), s),
maker()::Conditional);
}
@Override
public Choice<State<JCAssign>> visitAssignment(AssignmentTree node, State<?> state) {
return chooseSubtrees(
state,
s -> unifyExpression(node.getVariable(), s),
s -> unifyExpression(node.getExpression(), s),
maker()::Assign)
.condition(s -> !(s.result().getVariable() instanceof PlaceholderParamIdent));
}
@Override
public Choice<State<JCAssignOp>> visitCompoundAssignment(
CompoundAssignmentTree node, State<?> state) {
return chooseSubtrees(
state,
s -> unifyExpression(node.getVariable(), s),
s -> unifyExpression(node.getExpression(), s),
(variable, expr) -> maker().Assignop(((JCAssignOp) node).getTag(), variable, expr))
.condition(assignOp -> !(assignOp.result().getVariable() instanceof PlaceholderParamIdent));
}
@Override
public Choice<State<JCExpressionStatement>> visitExpressionStatement(
ExpressionStatementTree node, State<?> state) {
return chooseSubtrees(state, s -> unifyExpression(node.getExpression(), s), maker()::Exec);
}
@Override
public Choice<State<JCBlock>> visitBlock(BlockTree node, State<?> state) {
return chooseSubtrees(
state, s -> unifyStatements(node.getStatements(), s), stmts -> maker().Block(0, stmts));
}
@Override
public Choice<State<JCThrow>> visitThrow(ThrowTree node, State<?> state) {
return chooseSubtrees(state, s -> unifyExpression(node.getExpression(), s), maker()::Throw);
}
@Override
public Choice<State<JCEnhancedForLoop>> visitEnhancedForLoop(
EnhancedForLoopTree node, State<?> state) {
return chooseSubtrees(
state,
s -> unifyExpression(node.getExpression(), s),
s -> unifyStatement(node.getStatement(), s),
(expr, stmt) ->
UEnhancedForLoop.makeForeachLoop(
maker(), (JCVariableDecl) node.getVariable(), expr, stmt));
}
@Override
public Choice<State<JCIf>> visitIf(IfTree node, State<?> state) {
return chooseSubtrees(
state,
s -> unifyExpression(node.getCondition(), s),
s -> unifyStatement(node.getThenStatement(), s),
s -> unifyStatement(node.getElseStatement(), s),
maker()::If);
}
@Override
public Choice<State<JCDoWhileLoop>> visitDoWhileLoop(DoWhileLoopTree node, State<?> state) {
return chooseSubtrees(
state,
s -> unifyStatement(node.getStatement(), s),
s -> unifyExpression(node.getCondition(), s),
maker()::DoLoop);
}
@Override
public Choice<State<JCForLoop>> visitForLoop(ForLoopTree node, State<?> state) {
return chooseSubtrees(
state,
s -> unifyStatements(node.getInitializer(), s),
s -> unifyExpression(node.getCondition(), s),
s -> unifyStatements(node.getUpdate(), s),
s -> unifyStatement(node.getStatement(), s),
(inits, cond, update, stmt) ->
maker().ForLoop(inits, cond, List.convert(JCExpressionStatement.class, update), stmt));
}
@Override
public Choice<State<JCLabeledStatement>> visitLabeledStatement(
LabeledStatementTree node, State<?> state) {
return chooseSubtrees(
state,
s -> unifyStatement(node.getStatement(), s),
stmt -> maker().Labelled((Name) node.getLabel(), stmt));
}
@Override
public Choice<State<JCVariableDecl>> visitVariable(VariableTree node, State<?> state) {
return chooseSubtrees(
state,
s -> unifyExpression(node.getInitializer(), s),
init ->
maker()
.VarDef(
(JCModifiers) node.getModifiers(),
(Name) node.getName(),
(JCExpression) node.getType(),
init));
}
@Override
public Choice<State<JCWhileLoop>> visitWhileLoop(WhileLoopTree node, State<?> state) {
return chooseSubtrees(
state,
s -> unifyExpression(node.getCondition(), s),
s -> unifyStatement(node.getStatement(), s),
maker()::WhileLoop);
}
@Override
public Choice<State<JCSynchronized>> visitSynchronized(SynchronizedTree node, State<?> state) {
return chooseSubtrees(
state,
s -> unifyExpression(node.getExpression(), s),
s -> unifyStatement(node.getBlock(), s),
(expr, block) -> maker().Synchronized(expr, (JCBlock) block));
}
@Override
public Choice<State<JCReturn>> visitReturn(ReturnTree node, State<?> state) {
return chooseSubtrees(state, s -> unifyExpression(node.getExpression(), s), maker()::Return);
}
@Override
public Choice<State<JCTry>> visitTry(TryTree node, State<?> state) {
return chooseSubtrees(
state,
s -> unify(node.getResources(), s),
s -> unifyStatement(node.getBlock(), s),
s -> unify(node.getCatches(), s),
s -> unifyStatement(node.getFinallyBlock(), s),
(resources, block, catches, finallyBlock) ->
maker()
.Try(
resources,
(JCBlock) block,
List.convert(JCCatch.class, catches),
(JCBlock) finallyBlock));
}
@Override
public Choice<State<JCCatch>> visitCatch(CatchTree node, State<?> state) {
return chooseSubtrees(
state,
s -> unifyStatement(node.getBlock(), s),
block -> maker().Catch((JCVariableDecl) node.getParameter(), (JCBlock) block));
}
@Override
public Choice<State<JCSwitch>> visitSwitch(SwitchTree node, State<?> state) {
return chooseSubtrees(
state,
s -> unifyExpression(node.getExpression(), s),
s -> unify(node.getCases(), s),
(expr, cases) -> maker().Switch(expr, List.convert(JCCase.class, cases)));
}
@Override
public Choice<State<JCCase>> visitCase(CaseTree node, State<?> state) {
return chooseSubtrees(
state, s -> unifyStatements(node.getStatements(), s), stmts -> makeCase(node, stmts));
}
private JCCase makeCase(CaseTree node, List<JCStatement> stmts) {
try {
if (RuntimeVersion.isAtLeast12()) {
Enum<?> caseKind = (Enum) CaseTree.class.getMethod("getCaseKind").invoke(node);
checkState(
caseKind.name().contentEquals("STATEMENT"),
"expression switches are not supported yet");
return (JCCase)
TreeMaker.class
.getMethod(
"Case",
Class.forName("com.sun.source.tree.CaseTree$CaseKind"),
List.class,
List.class,
JCTree.class)
.invoke(
maker(),
caseKind,
RuntimeVersion.isAtLeast17()
? CaseTree.class.getMethod("getLabels").invoke(node)
: List.of((JCExpression) node.getExpression()),
stmts,
/* body */ null);
} else {
return (JCCase)
TreeMaker.class
.getMethod("Case", JCExpression.class, List.class)
.invoke(maker(), node.getExpression(), stmts);
}
} catch (ReflectiveOperationException e) {
throw new LinkageError(e.getMessage(), e);
}
}
@Override
public Choice<State<JCLambda>> visitLambdaExpression(LambdaExpressionTree node, State<?> state) {
return chooseSubtrees(
state,
s -> unify(node.getBody(), s),
body ->
maker()
.Lambda(
List.convert(
JCVariableDecl.class, (List<? extends VariableTree>) node.getParameters()),
body));
}
@Override
public Choice<State<JCMemberReference>> visitMemberReference(
MemberReferenceTree node, State<?> state) {
return chooseSubtrees(
state,
s -> unifyExpression(node.getQualifierExpression(), s),
expr ->
maker()
.Reference(
node.getMode(),
(Name) node.getName(),
expr,
List.convert(
JCExpression.class,
(List<? extends ExpressionTree>) node.getTypeArguments())));
}
}
| 28,077
| 37.253406
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/RefasterRuleBuilderScanner.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 static java.util.logging.Level.FINE;
import com.google.common.collect.ImmutableClassToInstanceMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Ordering;
import com.google.errorprone.CodeTransformer;
import com.google.errorprone.SubContext;
import com.google.errorprone.VisitorState;
import com.google.errorprone.refaster.annotation.AfterTemplate;
import com.google.errorprone.refaster.annotation.AllowCodeBetweenLines;
import com.google.errorprone.refaster.annotation.AlsoNegation;
import com.google.errorprone.refaster.annotation.BeforeTemplate;
import com.google.errorprone.refaster.annotation.Placeholder;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.SimpleTreeVisitor;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.util.Context;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import javax.lang.model.element.Modifier;
/**
* Scanner implementation to extract a single Refaster rule from a {@code ClassTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
public final class RefasterRuleBuilderScanner extends SimpleTreeVisitor<Void, Void> {
private static final Logger logger =
Logger.getLogger(RefasterRuleBuilderScanner.class.toString());
static final Context.Key<Map<MethodSymbol, PlaceholderMethod>> PLACEHOLDER_METHODS_KEY =
new Context.Key<>();
private final Context context;
private final Map<MethodSymbol, PlaceholderMethod> placeholderMethods;
private final List<Template<?>> beforeTemplates;
private final List<Template<?>> afterTemplates;
private RefasterRuleBuilderScanner(Context context) {
this.context = new SubContext(context);
if (context.get(PLACEHOLDER_METHODS_KEY) == null) {
this.placeholderMethods = new HashMap<>();
context.put(PLACEHOLDER_METHODS_KEY, placeholderMethods);
} else {
this.placeholderMethods = context.get(PLACEHOLDER_METHODS_KEY);
}
this.beforeTemplates = new ArrayList<>();
this.afterTemplates = new ArrayList<>();
}
public static Collection<? extends CodeTransformer> extractRules(
ClassTree tree, Context context) {
ClassSymbol sym = ASTHelpers.getSymbol(tree);
RefasterRuleBuilderScanner scanner = new RefasterRuleBuilderScanner(context);
// visit abstract methods first
ImmutableList<MethodTree> methods =
new Ordering<MethodTree>() {
@Override
public int compare(MethodTree l, MethodTree r) {
return Boolean.compare(
l.getModifiers().getFlags().contains(Modifier.ABSTRACT),
r.getModifiers().getFlags().contains(Modifier.ABSTRACT));
}
}.reverse().immutableSortedCopy(Iterables.filter(tree.getMembers(), MethodTree.class));
scanner.visit(methods, null);
UTemplater templater = new UTemplater(context);
List<UType> types = templater.templateTypes(sym.type.getTypeArguments());
return scanner.createMatchers(
Iterables.filter(types, UTypeVar.class),
sym.getQualifiedName().toString(),
UTemplater.annotationMap(sym));
}
@Override
public Void visitMethod(MethodTree tree, Void v) {
try {
VisitorState state = new VisitorState(context);
logger.log(FINE, "Discovered method with name {0}", tree.getName());
if (ASTHelpers.hasAnnotation(tree, Placeholder.class, state)) {
checkArgument(
tree.getModifiers().getFlags().contains(Modifier.ABSTRACT),
"@Placeholder methods are expected to be abstract");
UTemplater templater = new UTemplater(context);
ImmutableMap.Builder<UVariableDecl, ImmutableClassToInstanceMap<Annotation>> params =
ImmutableMap.builder();
for (VariableTree param : tree.getParameters()) {
params.put(
templater.visitVariable(param, null),
UTemplater.annotationMap(ASTHelpers.getSymbol(param)));
}
MethodSymbol sym = ASTHelpers.getSymbol(tree);
placeholderMethods.put(
sym,
PlaceholderMethod.create(
tree.getName(),
templater.template(sym.getReturnType()),
params.buildOrThrow(),
UTemplater.annotationMap(sym)));
} else if (ASTHelpers.hasAnnotation(tree, BeforeTemplate.class, state)) {
checkState(afterTemplates.isEmpty(), "BeforeTemplate must come before AfterTemplate");
Template<?> template = UTemplater.createTemplate(context, tree);
beforeTemplates.add(template);
if (template instanceof BlockTemplate) {
context.put(UTemplater.REQUIRE_BLOCK_KEY, /* data= */ true);
}
} else if (ASTHelpers.hasAnnotation(tree, AfterTemplate.class, state)) {
afterTemplates.add(UTemplater.createTemplate(context, tree));
} else if (tree.getModifiers().getFlags().contains(Modifier.ABSTRACT)) {
throw new IllegalArgumentException(
"Placeholder methods must have @Placeholder, but abstract method does not: " + tree);
}
return null;
} catch (RuntimeException t) {
throw new RuntimeException("Error analysing: " + tree.getName(), t);
}
}
private ImmutableList<? extends CodeTransformer> createMatchers(
Iterable<UTypeVar> typeVars,
String qualifiedTemplateClass,
ImmutableClassToInstanceMap<Annotation> annotationMap) {
if (beforeTemplates.isEmpty() && afterTemplates.isEmpty()) {
// there's no template here
return ImmutableList.of();
} else {
if (annotationMap.containsKey(AllowCodeBetweenLines.class)) {
List<UBlank> blanks = new ArrayList<>();
for (int i = 0; i < beforeTemplates.size(); i++) {
if (beforeTemplates.get(i) instanceof ExpressionTemplate) {
throw new IllegalArgumentException(
"@AllowCodeBetweenLines may not be specified for expression templates.");
}
BlockTemplate before = (BlockTemplate) beforeTemplates.get(i);
List<UStatement> stmtsWithBlanks = new ArrayList<>();
for (UStatement stmt : before.templateStatements()) {
if (!stmtsWithBlanks.isEmpty()) {
UBlank blank = UBlank.create();
blanks.add(blank);
stmtsWithBlanks.add(blank);
}
stmtsWithBlanks.add(stmt);
}
beforeTemplates.set(i, before.withStatements(stmtsWithBlanks));
}
for (int i = 0; i < afterTemplates.size(); i++) {
BlockTemplate afterBlock = (BlockTemplate) afterTemplates.get(i);
afterTemplates.set(
i,
afterBlock.withStatements(Iterables.concat(blanks, afterBlock.templateStatements())));
}
}
RefasterRule<?, ?> rule =
RefasterRule.create(
qualifiedTemplateClass, typeVars, beforeTemplates, afterTemplates, annotationMap);
List<ExpressionTemplate> negatedAfterTemplates = new ArrayList<>();
for (Template<?> afterTemplate : afterTemplates) {
if (afterTemplate.annotations().containsKey(AlsoNegation.class)) {
negatedAfterTemplates.add(((ExpressionTemplate) afterTemplate).negation());
}
}
if (!negatedAfterTemplates.isEmpty()) {
List<ExpressionTemplate> negatedBeforeTemplates = new ArrayList<>();
for (Template<?> beforeTemplate : beforeTemplates) {
negatedBeforeTemplates.add(((ExpressionTemplate) beforeTemplate).negation());
}
RefasterRule<?, ?> negation =
RefasterRule.create(
qualifiedTemplateClass,
typeVars,
negatedBeforeTemplates,
negatedAfterTemplates,
annotationMap);
return ImmutableList.of(rule, negation);
}
return ImmutableList.of(rule);
}
}
}
| 9,060
| 41.341121
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UIntersectionClassType.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 static com.sun.tools.javac.code.Flags.COMPOUND;
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.ClassType;
import com.sun.tools.javac.code.Type.IntersectionClassType;
/**
* {@code UType} representation of an {@code IntersectionClassType}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
public abstract class UIntersectionClassType extends UType {
static UIntersectionClassType create(Iterable<? extends UType> bounds) {
return new AutoValue_UIntersectionClassType(ImmutableList.copyOf(bounds));
}
abstract ImmutableList<UType> bounds();
@Override
public IntersectionClassType inline(Inliner inliner) throws CouldNotResolveImportException {
return new IntersectionClassType(
inliner.inlineList(bounds()),
new ClassSymbol(COMPOUND, inliner.asName("intersection"), inliner.symtab().noSymbol),
false);
}
@Override
public Choice<Unifier> visitClassType(ClassType t, Unifier unifier) {
if (t instanceof IntersectionClassType) {
IntersectionClassType intersection = (IntersectionClassType) t;
return unifyList(unifier, bounds(), intersection.getComponents());
}
return Choice.none();
}
}
| 2,029
| 34
| 94
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/Template.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 java.util.logging.Level.FINE;
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.common.collect.Iterables;
import com.google.common.collect.Ordering;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.refaster.PlaceholderMethod.PlaceholderExpressionKey;
import com.google.errorprone.refaster.UTypeVar.TypeWithExpression;
import com.google.errorprone.refaster.annotation.NoAutoboxing;
import com.sun.source.tree.Tree.Kind;
import com.sun.tools.javac.code.Kinds.KindSelector;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.ForAll;
import com.sun.tools.javac.code.Type.MethodType;
import com.sun.tools.javac.code.TypeTag;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.comp.Attr;
import com.sun.tools.javac.comp.AttrContext;
import com.sun.tools.javac.comp.Enter;
import com.sun.tools.javac.comp.Env;
import com.sun.tools.javac.comp.Resolve;
import com.sun.tools.javac.tree.EndPosTable;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCAnnotation;
import com.sun.tools.javac.tree.JCTree.JCCatch;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCExpressionStatement;
import com.sun.tools.javac.tree.JCTree.JCLambda;
import com.sun.tools.javac.tree.JCTree.JCLiteral;
import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
import com.sun.tools.javac.tree.JCTree.JCTry;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.tree.Pretty;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.JCDiagnostic;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import com.sun.tools.javac.util.Log;
import com.sun.tools.javac.util.Position;
import com.sun.tools.javac.util.Warner;
import java.io.IOException;
import java.io.Serializable;
import java.io.UncheckedIOException;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Abstract superclass for templates that can be used to search and replace in a Java syntax tree.
*
* @author lowasser@google.com (Louis Wasserman)
* @param <M> Type of a match for this template.
*/
public abstract class Template<M extends TemplateMatch> implements Serializable {
private static final Logger logger = Logger.getLogger(Template.class.toString());
public abstract ImmutableClassToInstanceMap<Annotation> annotations();
public abstract ImmutableList<UTypeVar> templateTypeVariables();
public abstract ImmutableMap<String, UType> expressionArgumentTypes();
public abstract Iterable<M> match(JCTree tree, Context context);
public abstract Fix replace(M match);
Iterable<UTypeVar> typeVariables(Context context) {
ImmutableList<UTypeVar> ruleTypeVars = context.get(RefasterRule.RULE_TYPE_VARS);
return Iterables.concat(
(ruleTypeVars == null) ? ImmutableList.<UTypeVar>of() : ruleTypeVars,
templateTypeVariables());
}
boolean autoboxing() {
return !annotations().containsKey(NoAutoboxing.class);
}
/**
* Returns a list of the expected types to be matched. This consists of the argument types from
* the @BeforeTemplate method, concatenated with the return types of expression placeholders,
* sorted by the name of the placeholder method.
*
* @throws CouldNotResolveImportException if a referenced type could not be resolved
*/
protected List<Type> expectedTypes(Inliner inliner) throws CouldNotResolveImportException {
ArrayList<Type> result = new ArrayList<>();
ImmutableList<UType> types = expressionArgumentTypes().values().asList();
ImmutableList<String> argNames = expressionArgumentTypes().keySet().asList();
for (int i = 0; i < argNames.size(); i++) {
String argName = argNames.get(i);
Optional<JCExpression> singleBinding =
inliner.getOptionalBinding(new UFreeIdent.Key(argName));
if (!singleBinding.isPresent()) {
Optional<java.util.List<JCExpression>> exprs =
inliner.getOptionalBinding(new URepeated.Key(argName));
if (!exprs.isPresent() || exprs.get().isEmpty()) {
// It is a repeated template variable and matches no expressions.
continue;
}
}
result.add(types.get(i).inline(inliner));
}
for (PlaceholderExpressionKey key :
Ordering.natural()
.immutableSortedCopy(
Iterables.filter(inliner.bindings.keySet(), PlaceholderExpressionKey.class))) {
Type type = key.method.returnType().inline(inliner);
// Skip void placeholder expressions, because
// a) if the expected type is void, any actual type is acceptable
// b) these types are used as the argument types in a synthetic MethodType, and method
// argument types cannot be void
if (!type.getTag().equals(TypeTag.VOID)) {
result.add(type);
}
}
return List.from(result);
}
/**
* Returns a list of the actual types to be matched. This consists of the types of the expressions
* bound to the @BeforeTemplate method parameters, concatenated with the types of the expressions
* bound to expression placeholders, sorted by the name of the placeholder method.
*/
protected List<Type> actualTypes(Inliner inliner) throws CouldNotResolveImportException {
ArrayList<Type> result = new ArrayList<>();
ImmutableList<String> argNames = expressionArgumentTypes().keySet().asList();
for (int i = 0; i < expressionArgumentTypes().size(); i++) {
String argName = argNames.get(i);
Optional<JCExpression> singleBinding =
inliner.getOptionalBinding(new UFreeIdent.Key(argName));
if (singleBinding.isPresent()) {
result.add(singleBinding.get().type);
} else {
Optional<java.util.List<JCExpression>> exprs =
inliner.getOptionalBinding(new URepeated.Key(argName));
if (exprs.isPresent() && !exprs.get().isEmpty()) {
Type[] exprTys = new Type[exprs.get().size()];
for (int j = 0; j < exprs.get().size(); j++) {
exprTys[j] = exprs.get().get(j).type;
}
// Get the least upper bound of the types of all expressions that the argument matches.
// In the special case where exprs is empty, returns the "bottom" type, which is a
// subtype of everything.
result.add(inliner.types().lub(List.from(exprTys)));
}
}
}
for (PlaceholderExpressionKey key :
Ordering.natural()
.immutableSortedCopy(
Iterables.filter(inliner.bindings.keySet(), PlaceholderExpressionKey.class))) {
Type keyType = key.method.returnType().inline(inliner);
// See comment in `expectedTypes` for why we skip void placeholder keys.
if (!keyType.getTag().equals(TypeTag.VOID)) {
result.add(inliner.getBinding(key).type);
}
}
return List.from(result);
}
@Nullable
protected Optional<Unifier> typecheck(
Unifier unifier,
Inliner inliner,
Warner warner,
List<Type> expectedTypes,
List<Type> actualTypes) {
try {
ImmutableList<UTypeVar> freeTypeVars = freeTypeVars(unifier);
infer(
warner,
inliner,
inliner.<Type>inlineList(freeTypeVars),
expectedTypes,
inliner.symtab().voidType,
actualTypes);
for (UTypeVar var : freeTypeVars) {
Type instantiationForVar =
infer(
warner,
inliner,
inliner.<Type>inlineList(freeTypeVars),
expectedTypes,
var.inline(inliner),
actualTypes);
unifier.putBinding(
var.key(), TypeWithExpression.create(instantiationForVar.getReturnType()));
}
if (!checkBounds(unifier, inliner, warner)) {
return Optional.absent();
}
return Optional.of(unifier);
} catch (CouldNotResolveImportException e) {
logger.log(FINE, "Failure to resolve an import", e);
return Optional.absent();
} catch (InferException e) {
logger.log(FINE, "No valid instantiation found: " + e.getMessage());
return Optional.absent();
}
}
private boolean checkBounds(Unifier unifier, Inliner inliner, Warner warner)
throws CouldNotResolveImportException {
Types types = unifier.types();
ListBuffer<Type> varsBuffer = new ListBuffer<>();
ListBuffer<Type> bindingsBuffer = new ListBuffer<>();
for (UTypeVar typeVar : typeVariables(unifier.getContext())) {
varsBuffer.add(inliner.inlineAsVar(typeVar));
bindingsBuffer.add(unifier.getBinding(typeVar.key()).type());
}
List<Type> vars = varsBuffer.toList();
List<Type> bindings = bindingsBuffer.toList();
for (UTypeVar typeVar : typeVariables(unifier.getContext())) {
List<Type> bounds = types.getBounds(inliner.inlineAsVar(typeVar));
bounds = types.subst(bounds, vars, bindings);
if (!types.isSubtypeUnchecked(unifier.getBinding(typeVar.key()).type(), bounds, warner)) {
logger.log(
FINE,
String.format("%s is not a subtype of %s", inliner.getBinding(typeVar.key()), bounds));
return false;
}
}
return true;
}
protected static Pretty pretty(Context context, Writer writer) {
JCCompilationUnit unit = context.get(JCCompilationUnit.class);
try {
String unitContents = unit.getSourceFile().getCharContent(false).toString();
return new Pretty(writer, true) {
{
// Work-around for b/22196513
width = 0;
}
@Override
public void visitAnnotation(JCAnnotation anno) {
if (anno.getArguments().isEmpty()) {
try {
print("@");
printExpr(anno.annotationType);
} catch (IOException e) {
// the supertype swallows exceptions too
throw new RuntimeException(e);
}
} else {
super.visitAnnotation(anno);
}
}
@Override
public void printExpr(JCTree tree, int prec) throws IOException {
EndPosTable endPositions = unit.endPositions;
/*
* Modifiers, and specifically flags like final, appear to just need weird special
* handling.
*
* Note: we can't use {@code TreeInfo.getEndPos()} or {@code JCTree.getEndPosition()}
* here, because they will return the end position of an enclosing AST node for trees
* whose real end positions aren't stored.
*/
int endPos = endPositions.getEndPos(tree);
boolean hasRealEndPosition = endPos != Position.NOPOS;
if (tree.getKind() != Kind.MODIFIERS && hasRealEndPosition) {
writer.append(unitContents.substring(tree.getStartPosition(), endPos));
} else {
super.printExpr(tree, prec);
}
}
@Override
public void visitApply(JCMethodInvocation tree) {
JCExpression select = tree.getMethodSelect();
if (select != null && select.toString().equals("Refaster.emitCommentBefore")) {
String commentLiteral = (String) ((JCLiteral) tree.getArguments().get(0)).getValue();
JCExpression expr = tree.getArguments().get(1);
try {
print("/* " + commentLiteral + " */ ");
} catch (IOException e) {
throw new RuntimeException(e);
}
expr.accept(this);
} else {
super.visitApply(tree);
}
}
@Override
public void printStat(JCTree tree) throws IOException {
if (tree instanceof JCExpressionStatement
&& ((JCExpressionStatement) tree).getExpression() instanceof JCMethodInvocation) {
JCMethodInvocation invocation =
(JCMethodInvocation) ((JCExpressionStatement) tree).getExpression();
JCExpression select = invocation.getMethodSelect();
if (select != null && select.toString().equals("Refaster.emitComment")) {
String commentLiteral =
(String) ((JCLiteral) invocation.getArguments().get(0)).getValue();
print("// " + commentLiteral);
return;
}
}
super.printStat(tree);
}
// Don't print parentheses around single lambda parameters without an explicit type.
@Override
public void visitLambda(JCLambda lambda) {
try {
boolean exactlyOneParamWithNoType =
lambda.params.size() == 1 && lambda.params.get(0).vartype == null;
if (!exactlyOneParamWithNoType) {
print("(");
}
boolean first = true;
for (JCVariableDecl param : lambda.params) {
if (!first) {
print(",");
}
if (param.vartype != null) {
if (!first) {
print(" ");
}
print(param.vartype + " ");
}
print(param.name);
first = false;
}
if (!exactlyOneParamWithNoType) {
print(")");
}
print("->");
printExpr(lambda.body);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public void visitTry(JCTry tree) {
if (tree.getResources().isEmpty()) {
super.visitTry(tree);
return;
}
try {
print("try (");
boolean first = true;
for (JCTree resource : tree.getResources()) {
if (!first) {
print(";");
println();
}
printExpr(resource);
first = false;
}
print(")");
printStat(tree.body);
for (JCCatch catchStmt : tree.getCatches()) {
printStat(catchStmt);
}
if (tree.getFinallyBlock() != null) {
print(" finally ");
printStat(tree.getFinallyBlock());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
};
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static class InferException extends Exception {
final Collection<JCDiagnostic> diagnostics;
public InferException(Collection<JCDiagnostic> diagnostics) {
this.diagnostics = diagnostics;
}
@Override
public String getMessage() {
return "Inference failed with the following error(s): " + diagnostics;
}
}
/**
* Returns the inferred method type of the template based on the given actual argument types.
*
* @throws InferException if no instances of the specified type variables would allow the {@code
* actualArgTypes} to match the {@code expectedArgTypes}
*/
private Type infer(
Warner warner,
Inliner inliner,
List<Type> freeTypeVariables,
List<Type> expectedArgTypes,
Type returnType,
List<Type> actualArgTypes)
throws InferException {
Symtab symtab = inliner.symtab();
Type methodType =
new MethodType(expectedArgTypes, returnType, List.<Type>nil(), symtab.methodClass);
if (!freeTypeVariables.isEmpty()) {
methodType = new ForAll(freeTypeVariables, methodType);
}
Enter enter = inliner.enter();
MethodSymbol methodSymbol =
new MethodSymbol(0, inliner.asName("__m__"), methodType, symtab.unknownSymbol);
Type site = symtab.methodClass.type;
Env<AttrContext> env =
enter.getTopLevelEnv(TreeMaker.instance(inliner.getContext()).TopLevel(List.<JCTree>nil()));
// Set up the resolution phase:
try {
Field field = AttrContext.class.getDeclaredField("pendingResolutionPhase");
field.setAccessible(true);
field.set(env.info, newMethodResolutionPhase(autoboxing()));
} catch (ReflectiveOperationException e) {
throw new LinkageError(e.getMessage(), e);
}
Object resultInfo;
try {
Class<?> resultInfoClass = Class.forName("com.sun.tools.javac.comp.Attr$ResultInfo");
Constructor<?> resultInfoCtor =
resultInfoClass.getDeclaredConstructor(Attr.class, KindSelector.class, Type.class);
resultInfoCtor.setAccessible(true);
resultInfo =
resultInfoCtor.newInstance(
Attr.instance(inliner.getContext()), KindSelector.PCK, Type.noType);
} catch (ReflectiveOperationException e) {
throw new LinkageError(e.getMessage(), e);
}
// Type inference sometimes produces diagnostics, so we need to catch them to avoid interfering
// with the enclosing compilation.
Log.DeferredDiagnosticHandler handler =
new Log.DeferredDiagnosticHandler(Log.instance(inliner.getContext()));
try {
MethodType result =
callCheckMethod(warner, inliner, resultInfo, actualArgTypes, methodSymbol, site, env);
if (!handler.getDiagnostics().isEmpty()) {
throw new InferException(handler.getDiagnostics());
}
return result;
} finally {
Log.instance(inliner.getContext()).popDiagnosticHandler(handler);
}
}
/** Reflectively instantiate the package-private {@code MethodResolutionPhase} enum. */
@Nullable
private static Object newMethodResolutionPhase(boolean autoboxing) {
for (Class<?> c : Resolve.class.getDeclaredClasses()) {
if (!c.getName().equals("com.sun.tools.javac.comp.Resolve$MethodResolutionPhase")) {
continue;
}
for (Object e : c.getEnumConstants()) {
if (e.toString().equals(autoboxing ? "BOX" : "BASIC")) {
return e;
}
}
}
return null;
}
/**
* Reflectively invoke Resolve.checkMethod(), which despite being package-private is apparently
* the only useful entry-point into javac8's type inference implementation.
*/
private MethodType callCheckMethod(
Warner warner,
Inliner inliner,
Object resultInfo,
List<Type> actualArgTypes,
MethodSymbol methodSymbol,
Type site,
Env<AttrContext> env)
throws InferException {
try {
Method checkMethod;
checkMethod =
Resolve.class.getDeclaredMethod(
"checkMethod",
Env.class,
Type.class,
Symbol.class,
Class.forName(
"com.sun.tools.javac.comp.Attr$ResultInfo"), // ResultInfo is package-private
List.class,
List.class,
Warner.class);
checkMethod.setAccessible(true);
return (MethodType)
checkMethod.invoke(
Resolve.instance(inliner.getContext()),
env,
site,
methodSymbol,
resultInfo,
actualArgTypes,
/* freeTypeVariables */ List.<Type>nil(),
warner);
} catch (InvocationTargetException e) {
if (e.getCause() instanceof Resolve.InapplicableMethodException) {
throw new InferException(
ImmutableList.of(
((Resolve.InapplicableMethodException) e.getTargetException()).getDiagnostic()));
}
throw new LinkageError(e.getMessage(), e.getCause());
} catch (ReflectiveOperationException e) {
throw new LinkageError(e.getMessage(), e);
}
}
/**
* Returns a list of the elements of {@code typeVariables} that are <em>not</em> bound in the
* specified {@link Unifier}.
*/
private ImmutableList<UTypeVar> freeTypeVars(Unifier unifier) {
ImmutableList.Builder<UTypeVar> builder = ImmutableList.builder();
for (UTypeVar var : typeVariables(unifier.getContext())) {
if (unifier.getBinding(var.key()) == null) {
builder.add(var);
}
}
return builder.build();
}
protected static Fix addImports(Inliner inliner, SuggestedFix.Builder fix) {
for (String importToAdd : inliner.getImportsToAdd()) {
fix.addImport(importToAdd);
}
for (String staticImportToAdd : inliner.getStaticImportsToAdd()) {
fix.addStaticImport(staticImportToAdd);
}
return fix.build();
}
}
| 21,736
| 36.413081
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UBlank.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.MoreObjects.firstNonNull;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ContiguousSet;
import com.google.common.collect.DiscreteDomain;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Range;
import com.google.errorprone.refaster.UStatement.UnifierWithUnconsumedStatements;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TreeVisitor;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.util.ListBuffer;
import java.util.List;
import java.util.UUID;
/** Equivalent to a no-arg block placeholder invocation. */
@AutoValue
abstract class UBlank implements UStatement {
static UBlank create() {
return new AutoValue_UBlank(UUID.randomUUID());
}
abstract UUID unique();
Key key() {
return new Key(unique());
}
static class Key extends Bindings.Key<List<? extends StatementTree>> {
Key(UUID k) {
super(k.toString());
}
}
private static final TreeScanner<Boolean, Unifier> FORBIDDEN_REFERENCE_SCANNER =
new TreeScanner<Boolean, Unifier>() {
@Override
public Boolean reduce(Boolean l, Boolean r) {
return firstNonNull(l, false) || firstNonNull(r, false);
}
@Override
public Boolean scan(Tree t, Unifier unifier) {
if (t != null) {
Boolean forbidden =
t.accept(PlaceholderUnificationVisitor.FORBIDDEN_REFERENCE_VISITOR, unifier);
return firstNonNull(forbidden, false) || firstNonNull(super.scan(t, unifier), false);
}
return false;
}
};
@Override
public Tree.Kind getKind() {
return Kind.OTHER;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitOther(this, data);
}
@Override
public Choice<UnifierWithUnconsumedStatements> apply(UnifierWithUnconsumedStatements state) {
int goodIndex = 0;
while (goodIndex < state.unconsumedStatements().size()) {
StatementTree stmt = state.unconsumedStatements().get(goodIndex);
// If the statement refers to bound variables or might exit, stop consuming statements.
if (firstNonNull(FORBIDDEN_REFERENCE_SCANNER.scan(stmt, state.unifier()), false)
|| ControlFlowVisitor.INSTANCE.visitStatement(stmt)
!= ControlFlowVisitor.Result.NEVER_EXITS) {
break;
} else {
goodIndex++;
}
}
ImmutableSortedSet<Integer> breakPoints =
ContiguousSet.create(Range.closed(0, goodIndex), DiscreteDomain.integers());
return Choice.from(breakPoints)
.transform(
(Integer k) -> {
Unifier unifier = state.unifier().fork();
unifier.putBinding(key(), state.unconsumedStatements().subList(0, k));
ImmutableList<? extends StatementTree> remaining =
state.unconsumedStatements().subList(k, state.unconsumedStatements().size());
return UnifierWithUnconsumedStatements.create(unifier, remaining);
});
}
@Override
public com.sun.tools.javac.util.List<JCStatement> inlineStatements(Inliner inliner) {
ListBuffer<JCStatement> buffer = new ListBuffer<>();
for (StatementTree stmt :
inliner.getOptionalBinding(key()).or(ImmutableList.<StatementTree>of())) {
buffer.add((JCStatement) stmt);
}
return buffer.toList();
}
}
| 4,225
| 33.92562
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UTypeVarIdent.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.refaster.UTypeVar.TypeWithExpression;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TreeVisitor;
import com.sun.source.util.SimpleTreeVisitor;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import javax.annotation.Nullable;
import javax.lang.model.element.ElementKind;
/**
* Identifier for a type variable in an AST; this is a syntactic representation of a {@link
* UTypeVar}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UTypeVarIdent extends UIdent {
private static final TreeVisitor<Boolean, Void> QUALIFIED_FROM_PACKAGE =
new SimpleTreeVisitor<Boolean, Void>(false) {
@Override
public Boolean visitMemberSelect(MemberSelectTree node, Void p) {
return node.getExpression().accept(this, null);
}
@Override
public Boolean visitIdentifier(IdentifierTree node, Void p) {
return ASTHelpers.getSymbol(node) != null
&& ASTHelpers.getSymbol(node).getKind() == ElementKind.PACKAGE;
}
};
public static UTypeVarIdent create(CharSequence name) {
return new AutoValue_UTypeVarIdent(StringName.of(name));
}
@Override
public abstract StringName getName();
UTypeVar.Key key() {
return new UTypeVar.Key(getName());
}
@Override
public JCExpression inline(Inliner inliner) {
return inliner.getBinding(key()).inline(inliner);
}
@Override
protected Choice<Unifier> defaultAction(Tree target, Unifier unifier) {
JCExpression expr = (JCExpression) target;
Type targetType = expr.type;
if (targetType == null) {
return Choice.none();
}
@Nullable TypeWithExpression boundType = unifier.getBinding(key());
if (boundType == null) {
unifier.putBinding(
key(),
expr.accept(QUALIFIED_FROM_PACKAGE, null)
? TypeWithExpression.create(
targetType) /* use the ImportPolicy to refer to this type */
: TypeWithExpression.create(targetType, expr));
return Choice.of(unifier);
} else if (unifier.types().isSameType(targetType, boundType.type())) {
return Choice.of(unifier);
}
return Choice.none();
}
}
| 3,082
| 32.150538
| 91
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UArrayAccess.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.ArrayAccessTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCArrayAccess;
/**
* {@link UTree} version of {@link ArrayAccessTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UArrayAccess extends UExpression implements ArrayAccessTree {
public static UArrayAccess create(UExpression arrayExpr, UExpression indexExpr) {
return new AutoValue_UArrayAccess(arrayExpr, indexExpr);
}
@Override
public abstract UExpression getExpression();
@Override
public abstract UExpression getIndex();
@Override
public Choice<Unifier> visitArrayAccess(ArrayAccessTree arrayAccess, Unifier unifier) {
return getExpression()
.unify(arrayAccess.getExpression(), unifier)
.thenChoose(unifications(getIndex(), arrayAccess.getIndex()));
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitArrayAccess(this, data);
}
@Override
public Kind getKind() {
return Kind.ARRAY_ACCESS;
}
@Override
public JCArrayAccess inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner.maker().Indexed(getExpression().inline(inliner), getIndex().inline(inliner));
}
}
| 2,022
| 30.123077
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UWhileLoop.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.WhileLoopTree;
import com.sun.tools.javac.tree.JCTree.JCWhileLoop;
/**
* A {@link UTree} representation of a {@link WhileLoopTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UWhileLoop extends USimpleStatement implements WhileLoopTree {
public static UWhileLoop create(UExpression condition, UStatement body) {
return new AutoValue_UWhileLoop(condition, (USimpleStatement) body);
}
@Override
public abstract UExpression getCondition();
@Override
public abstract USimpleStatement getStatement();
@Override
public JCWhileLoop inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.WhileLoop(getCondition().inline(inliner), getStatement().inline(inliner));
}
@Override
public Choice<Unifier> visitWhileLoop(WhileLoopTree loop, Unifier unifier) {
return getCondition()
.unify(loop.getCondition(), unifier)
.thenChoose(unifications(getStatement(), loop.getStatement()));
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitWhileLoop(this, data);
}
@Override
public Kind getKind() {
return Kind.WHILE_LOOP;
}
}
| 2,038
| 29.432836
| 84
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UEnhancedForLoop.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.VerifyException;
import com.sun.source.tree.EnhancedForLoopTree;
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.JCEnhancedForLoop;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
import com.sun.tools.javac.tree.TreeMaker;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* A {@link UTree} representation of a {@link EnhancedForLoopTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UEnhancedForLoop extends USimpleStatement implements EnhancedForLoopTree {
private static final long serialVersionUID = 0;
public static UEnhancedForLoop create(
UVariableDecl variable, UExpression elements, UStatement statement) {
// On JDK 20 and above the `EnhancedForLoopTree` interface contains a additional method
// `getDeclarationKind()`, referencing a type not available prior to JDK 20. AutoValue
// generates a corresponding field and accessor for this property. Here we find and invoke the
// generated constructor with the appropriate arguments, depending on context.
// See https://github.com/openjdk/jdk20/commit/2cb64a75578ccc15a1dfc8c2843aa11d05ca8aa7.
// TODO: Simplify this logic once JDK 19 and older are no longer supported.
return isCompiledWithJdk20Plus()
? createJdk20PlusEnhancedForLoop(variable, elements, statement)
: createPreJdk20EnhancedForLoop(variable, elements, statement);
}
private static boolean isCompiledWithJdk20Plus() {
return Arrays.stream(AutoValue_UEnhancedForLoop.class.getDeclaredMethods())
.anyMatch(m -> "getDeclarationKind".equals(m.getName()));
}
private static UEnhancedForLoop createPreJdk20EnhancedForLoop(
UVariableDecl variable, UExpression elements, UStatement statement) {
try {
return AutoValue_UEnhancedForLoop.class
.getDeclaredConstructor(UVariableDecl.class, UExpression.class, USimpleStatement.class)
.newInstance(variable, elements, statement);
} catch (ReflectiveOperationException e) {
throw new LinkageError(e.getMessage(), e);
}
}
private static UEnhancedForLoop createJdk20PlusEnhancedForLoop(
UVariableDecl variable, UExpression elements, UStatement statement) {
Object declarationKind = getVariableDeclarationKind();
try {
return AutoValue_UEnhancedForLoop.class
.getDeclaredConstructor(
declarationKind.getClass(),
UVariableDecl.class,
UExpression.class,
USimpleStatement.class)
.newInstance(declarationKind, variable, elements, statement);
} catch (ReflectiveOperationException e) {
throw new LinkageError(e.getMessage(), e);
}
}
private static Object getVariableDeclarationKind() {
Class<?> declarationKind;
try {
declarationKind = Class.forName("com.sun.source.tree.EnhancedForLoopTree$DeclarationKind");
} catch (ClassNotFoundException e) {
throw new VerifyException("Cannot load `EnhancedForLoopTree.DeclarationKind` enum", e);
}
return Arrays.stream(declarationKind.getEnumConstants())
.filter(v -> "VARIABLE".equals(v.toString()))
.findFirst()
.orElseThrow(
() ->
new VerifyException(
"Enum value `EnhancedForLoopTree.DeclarationKind.VARIABLE` not found"));
}
@Override
public abstract UVariableDecl getVariable();
@Override
public abstract UExpression getExpression();
@Override
public abstract USimpleStatement getStatement();
// TODO(cushon): support record patterns in enhanced for
public Tree getVariableOrRecordPattern() {
return getVariable();
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitEnhancedForLoop(this, data);
}
@Override
public Kind getKind() {
return Kind.ENHANCED_FOR_LOOP;
}
@Override
public JCEnhancedForLoop inline(Inliner inliner) throws CouldNotResolveImportException {
return makeForeachLoop(
inliner.maker(),
getVariable().inline(inliner),
getExpression().inline(inliner),
getStatement().inline(inliner));
}
private static final Method treeMakerForeachLoopMethod = treeMakerForeachLoopMethod();
private static Method treeMakerForeachLoopMethod() {
try {
return TreeMaker.class.getMethod(
"ForeachLoop", JCTree.class, JCExpression.class, JCStatement.class);
} catch (ReflectiveOperationException e1) {
try {
return TreeMaker.class.getMethod(
"ForeachLoop", JCVariableDecl.class, JCExpression.class, JCStatement.class);
} catch (ReflectiveOperationException e2) {
e2.addSuppressed(e1);
throw new LinkageError(e2.getMessage(), e2);
}
}
}
static JCEnhancedForLoop makeForeachLoop(
TreeMaker maker, JCVariableDecl variable, JCExpression expression, JCStatement statement) {
try {
return (JCEnhancedForLoop)
treeMakerForeachLoopMethod.invoke(maker, variable, expression, statement);
} catch (ReflectiveOperationException e) {
throw new LinkageError(e.getMessage(), e);
}
}
@Override
public Choice<Unifier> visitEnhancedForLoop(EnhancedForLoopTree loop, Unifier unifier) {
return getVariable()
.unify(loop.getVariable(), unifier)
.thenChoose(unifications(getExpression(), loop.getExpression()))
.thenChoose(unifications(getStatement(), loop.getStatement()));
}
}
| 6,460
| 36.132184
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/USkip.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.EmptyStatementTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCSkip;
/**
* A {@link UTree} representation of an {@link EmptyStatementTree}
*
* @author lowasser@google.com (Louis Wasserman)
*/
final class USkip extends USimpleStatement implements EmptyStatementTree {
public static final USkip INSTANCE = new USkip();
private USkip() {}
Object readResolve() {
return INSTANCE;
}
@Override
public JCSkip inline(Inliner inliner) {
return inliner.maker().Skip();
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitEmptyStatement(this, data);
}
@Override
public Kind getKind() {
return Kind.EMPTY_STATEMENT;
}
@Override
public Choice<Unifier> visitEmptyStatement(EmptyStatementTree node, Unifier unifier) {
return Choice.of(unifier);
}
@Override
public String toString() {
return "USkip{}";
}
}
| 1,618
| 25.112903
| 88
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/Inliner.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.common.base.Optional;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.errorprone.SubContext;
import com.google.errorprone.refaster.UTypeVar.TypeWithExpression;
import com.google.errorprone.util.ASTHelpers;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.TypeSymbol;
import com.sun.tools.javac.code.Symbol.TypeVariableSymbol;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.ArrayType;
import com.sun.tools.javac.code.Type.ClassType;
import com.sun.tools.javac.code.Type.TypeVar;
import com.sun.tools.javac.code.Type.WildcardType;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.comp.Enter;
import com.sun.tools.javac.comp.Infer;
import com.sun.tools.javac.main.JavaCompiler;
import com.sun.tools.javac.tree.JCTree.JCExpression;
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.ListBuffer;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Names;
import java.util.Map;
import java.util.Set;
/**
* A context representing all the dependencies necessary to reconstruct a pretty-printable source
* tree from a {@code UTree} based on a set of substitutions.
*
* @author Louis Wasserman
*/
public final class Inliner {
private final Context context;
private final Set<String> importsToAdd;
private final Set<String> staticImportsToAdd;
public final Bindings bindings;
private final Map<String, TypeVar> typeVarCache;
public Inliner(Context context, Bindings bindings) {
this.context = new SubContext(context);
this.bindings = new Bindings(bindings).unmodifiable();
this.importsToAdd = Sets.newHashSet();
this.staticImportsToAdd = Sets.newHashSet();
this.typeVarCache = Maps.newHashMap();
}
public void addImport(String qualifiedImport) {
if (!qualifiedImport.startsWith("java.lang")) {
importsToAdd.add(qualifiedImport);
}
}
public void addStaticImport(String qualifiedImport) {
staticImportsToAdd.add(qualifiedImport);
}
public ClassSymbol resolveClass(CharSequence qualifiedClass)
throws CouldNotResolveImportException {
try {
Symbol symbol =
JavaCompiler.instance(context).resolveBinaryNameOrIdent(qualifiedClass.toString());
if (symbol.equals(symtab().errSymbol) || !(symbol instanceof ClassSymbol)) {
throw new CouldNotResolveImportException(qualifiedClass);
} else {
return (ClassSymbol) symbol;
}
} catch (NullPointerException e) {
throw new CouldNotResolveImportException(qualifiedClass);
}
}
public Context getContext() {
return context;
}
public Types types() {
return Types.instance(context);
}
public Symtab symtab() {
return Symtab.instance(context);
}
public Enter enter() {
return Enter.instance(context);
}
public Names names() {
return Names.instance(context);
}
public TreeMaker maker() {
return TreeMaker.instance(context);
}
public Infer infer() {
return Infer.instance(context);
}
public ImportPolicy importPolicy() {
return ImportPolicy.instance(context);
}
public Name asName(CharSequence str) {
return names().fromString(str.toString());
}
private static final Types.SimpleVisitor<JCExpression, Inliner> INLINE_AS_TREE =
new Types.SimpleVisitor<JCExpression, Inliner>() {
@Override
public JCExpression visitType(Type t, Inliner inliner) {
return inliner.maker().Type(t);
}
@Override
public JCExpression visitClassType(ClassType type, Inliner inliner) {
ClassSymbol classSym = (ClassSymbol) type.tsym;
JCExpression classExpr =
inliner
.importPolicy()
.classReference(
inliner,
ASTHelpers.outermostClass(classSym).getQualifiedName().toString(),
classSym.getQualifiedName().toString());
List<JCExpression> argExprs = List.nil();
for (Type argType : type.getTypeArguments()) {
argExprs = argExprs.append(visit(argType, inliner));
}
return argExprs.isEmpty() ? classExpr : inliner.maker().TypeApply(classExpr, argExprs);
}
@Override
public JCExpression visitWildcardType(WildcardType type, Inliner inliner) {
TreeMaker maker = inliner.maker();
return maker.Wildcard(maker.TypeBoundKind(type.kind), visit(type.type, inliner));
}
@Override
public JCExpression visitArrayType(ArrayType type, Inliner inliner) {
return inliner.maker().TypeArray(visit(type.getComponentType(), inliner));
}
};
/** Inlines the syntax tree representing the specified type. */
public JCExpression inlineAsTree(Type type) {
return INLINE_AS_TREE.visit(type, this);
}
public <V> V getBinding(Bindings.Key<V> key) {
V value = bindings.getBinding(key);
if (value == null) {
throw new IllegalStateException("No binding for " + key);
}
return value;
}
public <V> Optional<V> getOptionalBinding(Bindings.Key<V> key) {
return Optional.fromNullable(bindings.getBinding(key));
}
public <R> com.sun.tools.javac.util.List<R> inlineList(
Iterable<? extends Inlineable<? extends R>> elements) throws CouldNotResolveImportException {
ListBuffer<R> result = new ListBuffer<>();
for (Inlineable<? extends R> e : elements) {
if (e instanceof URepeated) {
// URepeated is bound to a list of expressions.
URepeated repeated = (URepeated) e;
for (JCExpression expr : getBinding(repeated.key())) {
@SuppressWarnings("unchecked")
// URepeated is an Inlineable<JCExpression>, so if e is also an Inlineable<? extends R>,
// then R must be ? super JCExpression.
R r = (R) expr;
result.append(r);
}
} else {
result.append(e.inline(this));
}
}
return result.toList();
}
public ImmutableSet<String> getImportsToAdd() {
return ImmutableSet.copyOf(importsToAdd);
}
public ImmutableSet<String> getStaticImportsToAdd() {
return ImmutableSet.copyOf(staticImportsToAdd);
}
public TypeVar inlineAsVar(UTypeVar var) throws CouldNotResolveImportException {
/*
* In order to handle recursively bounded type variables without a stack overflow,
* we first cache a type var with no bounds, then we inline the bounds.
*/
TypeVar typeVar = typeVarCache.get(var.getName());
if (typeVar != null) {
return typeVar;
}
Name name = asName(var.getName());
TypeSymbol sym = new TypeVariableSymbol(0, name, null, symtab().noSymbol);
typeVar = new TypeVar(sym, /* bound= */ null, /* lower= */ symtab().botType);
sym.type = typeVar;
typeVarCache.put(var.getName(), typeVar);
// Any recursive uses of var will point to the same TypeVar object generated above.
typeVar.setUpperBound(var.getUpperBound().inline(this));
typeVar.lower = var.getLowerBound().inline(this);
return typeVar;
}
Type inlineTypeVar(UTypeVar var) throws CouldNotResolveImportException {
Optional<TypeWithExpression> typeVarBinding = getOptionalBinding(var.key());
if (typeVarBinding.isPresent()) {
return typeVarBinding.get().type();
} else {
return inlineAsVar(var);
}
}
}
| 8,312
| 33.069672
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/RefasterSuppressionHelper.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.refaster;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.SuppressionInfo;
import com.google.errorprone.VisitorState;
import com.google.errorprone.matchers.Suppressible;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Name;
import java.lang.annotation.Annotation;
import java.util.Set;
/** Helpers for handling suppression annotations in refaster. */
final class RefasterSuppressionHelper {
/**
* Returns true if the given rule is suppressed on the given tree.
*
* <p>Unlike Error Prone, which scans the compilation unit once for all checks, refaster scans the
* compilation unit separately for each check. This simplifies suppression handling, since we can
* just stop recursively scanning as soon as a suppression is found for the current refaster rule.
*/
static boolean suppressed(RefasterRule<?, ?> rule, Tree tree, Context context) {
VisitorState state = VisitorState.createForUtilityPurposes(context);
Symbol sym = ASTHelpers.getDeclaredSymbol(tree);
if (sym == null) {
return false;
}
return SuppressionInfo.EMPTY
.withExtendedSuppressions(
sym, state, /* customSuppressionAnnosToLookFor= */ ImmutableSet.of())
.suppressedState(
new RefasterSuppressible(rule), /* suppressedInGeneratedCode= */ false, state)
.equals(SuppressionInfo.SuppressedState.SUPPRESSED);
}
/** Adapts a {@link RefasterRule<?, ?>} into a {@link Suppressible}. */
private static class RefasterSuppressible implements Suppressible {
private final RefasterRule<?, ?> rule;
RefasterSuppressible(RefasterRule<?, ?> rule) {
this.rule = rule;
}
@Override
public Set<String> allNames() {
return ImmutableSet.of(canonicalName());
}
@Override
public String canonicalName() {
return rule.simpleTemplateName();
}
@Override
public boolean supportsSuppressWarnings() {
return true;
}
@Override
public Set<Class<? extends Annotation>> customSuppressionAnnotations() {
return ImmutableSet.of();
}
@Override
public boolean suppressedByAnyOf(Set<Name> annotations, VisitorState s) {
// no custom suppression annotations
return false;
}
}
private RefasterSuppressionHelper() {}
}
| 3,084
| 32.172043
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UAssignOp.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.CompoundAssignmentTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.JCTree.JCAssignOp;
/**
* {@link UTree} representation of a {@link CompoundAssignmentTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UAssignOp extends UExpression implements CompoundAssignmentTree {
private static final ImmutableBiMap<Kind, JCTree.Tag> TAG =
ImmutableBiMap.<Kind, JCTree.Tag>builder()
.put(Kind.PLUS_ASSIGNMENT, JCTree.Tag.PLUS_ASG)
.put(Kind.MINUS_ASSIGNMENT, JCTree.Tag.MINUS_ASG)
.put(Kind.MULTIPLY_ASSIGNMENT, JCTree.Tag.MUL_ASG)
.put(Kind.DIVIDE_ASSIGNMENT, JCTree.Tag.DIV_ASG)
.put(Kind.REMAINDER_ASSIGNMENT, JCTree.Tag.MOD_ASG)
.put(Kind.LEFT_SHIFT_ASSIGNMENT, JCTree.Tag.SL_ASG)
.put(Kind.RIGHT_SHIFT_ASSIGNMENT, JCTree.Tag.SR_ASG)
.put(Kind.UNSIGNED_RIGHT_SHIFT_ASSIGNMENT, JCTree.Tag.USR_ASG)
.put(Kind.OR_ASSIGNMENT, JCTree.Tag.BITOR_ASG)
.put(Kind.AND_ASSIGNMENT, JCTree.Tag.BITAND_ASG)
.put(Kind.XOR_ASSIGNMENT, JCTree.Tag.BITXOR_ASG)
.buildOrThrow();
public static UAssignOp create(UExpression variable, Kind operator, UExpression expression) {
checkArgument(
TAG.containsKey(operator),
"Tree kind %s does not represent a compound assignment operator",
operator);
return new AutoValue_UAssignOp(variable, operator, expression);
}
@Override
public abstract UExpression getVariable();
@Override
public abstract Kind getKind();
@Override
public abstract UExpression getExpression();
@Override
public JCAssignOp inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.Assignop(
TAG.get(getKind()), getVariable().inline(inliner), getExpression().inline(inliner));
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitCompoundAssignment(this, data);
}
// TODO(lowasser): consider matching x = x ? y as well as x ?= y
@Override
public Choice<Unifier> visitCompoundAssignment(CompoundAssignmentTree assignOp, Unifier unifier) {
return Choice.condition(getKind() == assignOp.getKind(), unifier)
.thenChoose(unifications(getVariable(), assignOp.getVariable()))
.thenChoose(unifications(getExpression(), assignOp.getExpression()));
}
}
| 3,364
| 36.388889
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UIdent.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.IdentifierTree;
import com.sun.source.tree.TreeVisitor;
/**
* Abstract supertype for {@link UTree} identifiers.
*
* @author lowasser@google.com (Louis Wasserman)
*/
abstract class UIdent extends UExpression implements IdentifierTree {
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitIdentifier(this, data);
}
@Override
public Kind getKind() {
return Kind.IDENTIFIER;
}
}
| 1,114
| 28.342105
| 75
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UContinue.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.ContinueTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCContinue;
import javax.annotation.Nullable;
/**
* {@code UTree} representation of {@code ContinueTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UContinue extends USimpleStatement implements ContinueTree {
static UContinue create(@Nullable CharSequence label) {
return new AutoValue_UContinue((label == null) ? null : StringName.of(label));
}
@Override
@Nullable
public abstract StringName getLabel();
@Override
public Kind getKind() {
return Kind.CONTINUE;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitContinue(this, data);
}
private ULabeledStatement.Key key() {
return new ULabeledStatement.Key(getLabel());
}
@Override
public JCContinue inline(Inliner inliner) {
return inliner.maker().Continue(ULabeledStatement.inlineLabel(getLabel(), inliner));
}
@Override
public Choice<Unifier> visitContinue(ContinueTree node, Unifier unifier) {
if (getLabel() == null) {
return Choice.condition(node.getLabel() == null, unifier);
} else {
CharSequence boundName = unifier.getBinding(key());
return Choice.condition(
boundName != null && node.getLabel().contentEquals(boundName), unifier);
}
}
}
| 2,093
| 28.914286
| 88
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/Unifiable.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 java.io.Serializable;
/**
* A serializable representation of a template that can be matched against a target of type {@code
* T}.
*
* @author Louis Wasserman
*/
public interface Unifiable<T> extends Serializable {
/**
* Returns all valid unification paths (if any) from this {@code Unifier} that unify this with
* {@code target}.
*/
Choice<Unifier> unify(T target, Unifier unifier);
}
| 1,059
| 30.176471
| 98
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UMemberReference.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.collect.ImmutableList;
import com.sun.source.tree.MemberReferenceTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCMemberReference;
import javax.annotation.Nullable;
/**
* {@code UTree} representation of a {@code MemberReferenceTree}
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UMemberReference extends UExpression implements MemberReferenceTree {
public static UMemberReference create(
ReferenceMode mode,
UExpression qualifierExpression,
CharSequence name,
@Nullable Iterable<? extends UExpression> typeArguments) {
return new AutoValue_UMemberReference(
mode,
qualifierExpression,
StringName.of(name),
(typeArguments == null) ? null : ImmutableList.copyOf(typeArguments));
}
@Override
public Kind getKind() {
return Kind.MEMBER_REFERENCE;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitMemberReference(this, data);
}
@Override
public Choice<Unifier> visitMemberReference(MemberReferenceTree node, Unifier unifier) {
return Choice.condition(getMode() == node.getMode(), unifier)
.thenChoose(unifications(getQualifierExpression(), node.getQualifierExpression()))
.thenChoose(unifications(getName(), node.getName()))
.thenChoose(unifications(getTypeArguments(), node.getTypeArguments()));
}
@Override
public JCMemberReference inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner
.maker()
.Reference(
getMode(),
getName().inline(inliner),
getQualifierExpression().inline(inliner),
(getTypeArguments() == null) ? null : inliner.inlineList(getTypeArguments()));
}
@Override
public abstract ReferenceMode getMode();
@Override
public abstract UExpression getQualifierExpression();
@Override
public abstract StringName getName();
@Override
@Nullable
public abstract ImmutableList<UExpression> getTypeArguments();
}
| 2,856
| 31.101124
| 90
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UMemberSelect.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.errorprone.util.ASTHelpers;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.tree.JCTree.JCExpression;
/**
* {@link UTree} version of {@link MemberSelectTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
public abstract class UMemberSelect extends UExpression implements MemberSelectTree {
/**
* Use of this string as an expression in a member select will cause this method select to be
* inlined as an identifier. I.e., "".foo will be inlined as foo.
*/
public static final String CONVERT_TO_IDENT = "";
public static UMemberSelect create(UExpression expression, CharSequence identifier, UType type) {
return new AutoValue_UMemberSelect(expression, StringName.of(identifier), type);
}
@Override
public abstract UExpression getExpression();
@Override
public abstract StringName getIdentifier();
abstract UType type();
@Override
public Choice<Unifier> visitMemberSelect(MemberSelectTree fieldAccess, Unifier unifier) {
if (ASTHelpers.getSymbol(fieldAccess) != null) {
return getIdentifier()
.unify(fieldAccess.getIdentifier(), unifier)
.thenChoose(unifications(getExpression(), fieldAccess.getExpression()))
.thenChoose(unifications(type(), ASTHelpers.getSymbol(fieldAccess).asType()));
}
return Choice.none();
}
@Override
public Choice<Unifier> visitIdentifier(IdentifierTree ident, Unifier unifier) {
Symbol sym = ASTHelpers.getSymbol(ident);
if (sym != null && sym.owner.type != null) {
JCExpression thisIdent = unifier.thisExpression(sym.owner.type);
return getIdentifier()
.unify(ident.getName(), unifier)
.thenChoose(unifications(getExpression(), thisIdent))
.thenChoose(unifications(type(), sym.asType()));
}
return Choice.none();
}
@Override
public Kind getKind() {
return Kind.MEMBER_SELECT;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitMemberSelect(this, data);
}
@Override
public JCExpression inline(Inliner inliner) throws CouldNotResolveImportException {
JCExpression expression = getExpression().inline(inliner);
if (expression.toString().equals(CONVERT_TO_IDENT)) {
return inliner.maker().Ident(getIdentifier().inline(inliner));
}
// TODO(lowasser): consider inlining this.foo() as foo()
return inliner.maker().Select(getExpression().inline(inliner), getIdentifier().inline(inliner));
}
}
| 3,405
| 33.755102
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/Inlineable.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;
/**
* A type that can be inlined given an {@code Inliner} context.
*
* @param <T> The type that this inlines to.
* @author Louis Wasserman
*/
interface Inlineable<T> {
T inline(Inliner inliner) throws CouldNotResolveImportException;
}
| 890
| 30.821429
| 75
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/PlaceholderMethod.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.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.ClassToInstanceMap;
import com.google.common.collect.ImmutableClassToInstanceMap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.errorprone.VisitorState;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.refaster.UPlaceholderExpression.PlaceholderParamIdent;
import com.google.errorprone.refaster.annotation.Matches;
import com.google.errorprone.refaster.annotation.MayOptionallyUse;
import com.google.errorprone.refaster.annotation.NotMatches;
import com.google.errorprone.refaster.annotation.OfKind;
import com.google.errorprone.refaster.annotation.Placeholder;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.util.List;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.Set;
/**
* Representation of a {@code Refaster} placeholder method, which can represent an arbitrary
* operation on a specific set of expressions.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class PlaceholderMethod implements Serializable {
static PlaceholderMethod create(
CharSequence name,
UType returnType,
ImmutableMap<UVariableDecl, ImmutableClassToInstanceMap<Annotation>> parameters,
ClassToInstanceMap<Annotation> annotations) {
boolean allowsIdentity = annotations.getInstance(Placeholder.class).allowsIdentity();
Class<? extends Matcher<? super ExpressionTree>> matchesClass =
annotations.containsKey(Matches.class)
? UTemplater.getValue(annotations.getInstance(Matches.class))
: null;
Class<? extends Matcher<? super ExpressionTree>> notMatchesClass =
annotations.containsKey(NotMatches.class)
? UTemplater.getValue(annotations.getInstance(NotMatches.class))
: null;
Predicate<Tree.Kind> allowedKinds =
annotations.containsKey(OfKind.class)
? Predicates.<Tree.Kind>in(Arrays.asList(annotations.getInstance(OfKind.class).value()))
: Predicates.<Tree.Kind>alwaysTrue();
class PlaceholderMatcher implements Matcher<ExpressionTree> {
@Override
public boolean matches(ExpressionTree t, VisitorState state) {
try {
return (allowsIdentity || !(t instanceof PlaceholderParamIdent))
&& (matchesClass == null || matchesClass.newInstance().matches(t, state))
&& (notMatchesClass == null || !notMatchesClass.newInstance().matches(t, state))
&& allowedKinds.apply(t.getKind());
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
}
}
return new AutoValue_PlaceholderMethod(
StringName.of(name),
returnType,
parameters,
new PlaceholderMatcher(),
ImmutableClassToInstanceMap.<Annotation, Annotation>copyOf(annotations));
}
abstract StringName name();
abstract UType returnType();
abstract ImmutableMap<UVariableDecl, ImmutableClassToInstanceMap<Annotation>>
annotatedParameters();
abstract Matcher<ExpressionTree> matcher();
abstract ImmutableClassToInstanceMap<Annotation> annotations();
ImmutableSet<UVariableDecl> parameters() {
return annotatedParameters().keySet();
}
/** Parameters which must be referenced in any tree matched to this placeholder. */
Set<UVariableDecl> requiredParameters() {
return Maps.filterValues(
annotatedParameters(),
(ImmutableClassToInstanceMap<Annotation> annotations) ->
!annotations.containsKey(MayOptionallyUse.class))
.keySet();
}
PlaceholderExpressionKey exprKey() {
return new PlaceholderExpressionKey(name().contents(), this);
}
PlaceholderBlockKey blockKey() {
return new PlaceholderBlockKey(name().contents(), this);
}
static final class PlaceholderExpressionKey extends Bindings.Key<JCExpression>
implements Comparable<PlaceholderExpressionKey> {
final PlaceholderMethod method;
private PlaceholderExpressionKey(String str, PlaceholderMethod method) {
super(str);
this.method = method;
}
@Override
public int compareTo(PlaceholderExpressionKey o) {
return getIdentifier().compareTo(o.getIdentifier());
}
}
static final class PlaceholderBlockKey extends Bindings.Key<List<JCStatement>> {
final PlaceholderMethod method;
private PlaceholderBlockKey(String str, PlaceholderMethod method) {
super(str);
this.method = method;
}
}
}
| 5,535
| 36.659864
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UInstanceOf.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.InstanceOfTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCInstanceOf;
import java.lang.reflect.Proxy;
import javax.annotation.Nullable;
/**
* {@link UTree} representation of a {@link InstanceOfTree}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UInstanceOf extends UExpression {
public static UInstanceOf create(UExpression expression, UTree<?> type) {
return new AutoValue_UInstanceOf(expression, type);
}
public abstract UExpression getExpression();
public abstract UTree<?> getType();
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
InstanceOfTree proxy =
(InstanceOfTree)
Proxy.newProxyInstance(
getClass().getClassLoader(),
new Class<?>[] {InstanceOfTree.class},
(unused, method, args) -> {
switch (method.getName()) {
case "getPattern":
// TODO(cushon): support refaster template matching on instanceof patterns
return null;
case "getExpression":
return getExpression();
case "getType":
return getType();
default:
try {
return method.invoke(UInstanceOf.this, args);
} catch (IllegalArgumentException e) {
throw new LinkageError(method.getName(), e);
}
}
});
return visitor.visitInstanceOf(proxy, data);
}
@Override
public Kind getKind() {
return Kind.INSTANCE_OF;
}
@Override
public JCInstanceOf inline(Inliner inliner) throws CouldNotResolveImportException {
return inliner.maker().TypeTest(getExpression().inline(inliner), getType().inline(inliner));
}
@Override
@Nullable
public Choice<Unifier> visitInstanceOf(InstanceOfTree instanceOf, @Nullable Unifier unifier) {
return getExpression()
.unify(instanceOf.getExpression(), unifier)
.thenChoose(unifications(getType(), instanceOf.getType()));
}
}
| 2,972
| 32.784091
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/UPlaceholderStatement.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.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.google.errorprone.refaster.PlaceholderUnificationVisitor.State;
import com.google.errorprone.refaster.UPlaceholderExpression.UncheckedCouldNotResolveImportException;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.tree.JCTree.JCStatement;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.List;
/**
* A representation of a block placeholder.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@AutoValue
abstract class UPlaceholderStatement implements UStatement {
static UPlaceholderStatement create(
PlaceholderMethod placeholder,
Iterable<? extends UExpression> arguments,
ControlFlowVisitor.Result implementationFlow) {
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_UPlaceholderStatement(
placeholder, builder.buildOrThrow(), implementationFlow);
}
abstract PlaceholderMethod placeholder();
abstract ImmutableMap<UVariableDecl, UExpression> arguments();
abstract ControlFlowVisitor.Result implementationFlow();
@Override
public Kind getKind() {
return Kind.OTHER;
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
return visitor.visitOther(this, data);
}
@AutoValue
abstract static class ConsumptionState {
static ConsumptionState empty() {
return new AutoValue_UPlaceholderStatement_ConsumptionState(0, List.<JCStatement>nil());
}
abstract int consumedStatements();
abstract List<JCStatement> placeholderImplInReverseOrder();
ConsumptionState consume(JCStatement impl) {
return new AutoValue_UPlaceholderStatement_ConsumptionState(
consumedStatements() + 1, placeholderImplInReverseOrder().prepend(impl));
}
}
public boolean reverify(Unifier unifier) {
return MoreObjects.firstNonNull(
new PlaceholderVerificationVisitor(
Collections2.transform(
placeholder().requiredParameters(), Functions.forMap(arguments())),
arguments().values())
.scan(unifier.getBinding(placeholder().blockKey()), unifier),
true);
}
@Override
public Choice<UnifierWithUnconsumedStatements> apply(UnifierWithUnconsumedStatements initState) {
PlaceholderUnificationVisitor visitor =
PlaceholderUnificationVisitor.create(
TreeMaker.instance(initState.unifier().getContext()), arguments());
PlaceholderVerificationVisitor verification =
new PlaceholderVerificationVisitor(
Collections2.transform(
placeholder().requiredParameters(), Functions.forMap(arguments())),
arguments().values());
// The choices where we might conceivably have a completed placeholder match.
Choice<State<ConsumptionState>> realOptions = Choice.none();
// The choice of consumption states to this point in the block.
Choice<State<ConsumptionState>> choiceToHere =
Choice.of(
State.create(List.<UVariableDecl>nil(), initState.unifier(), ConsumptionState.empty()));
if (verification.allRequiredMatched()) {
realOptions = choiceToHere.or(realOptions);
}
for (StatementTree targetStatement : initState.unconsumedStatements()) {
if (!verification.scan(targetStatement, initState.unifier())) {
break; // we saw a variable that's not allowed to be referenced
}
// Consume another statement, or if that fails, fall back to the previous choices...
choiceToHere =
choiceToHere.thenChoose(
(State<ConsumptionState> consumptionState) ->
visitor
.unifyStatement(targetStatement, consumptionState)
.transform(
(State<? extends JCStatement> stmtState) ->
stmtState.withResult(
consumptionState.result().consume(stmtState.result()))));
if (verification.allRequiredMatched()) {
realOptions = choiceToHere.or(realOptions);
}
}
return realOptions.thenOption(
(State<ConsumptionState> consumptionState) -> {
if (ImmutableSet.copyOf(consumptionState.seenParameters())
.containsAll(placeholder().requiredParameters())) {
Unifier resultUnifier = consumptionState.unifier().fork();
int nConsumedStatements = consumptionState.result().consumedStatements();
ImmutableList<? extends StatementTree> remainingStatements =
initState
.unconsumedStatements()
.subList(nConsumedStatements, initState.unconsumedStatements().size());
UnifierWithUnconsumedStatements result =
UnifierWithUnconsumedStatements.create(resultUnifier, remainingStatements);
List<JCStatement> impl =
consumptionState.result().placeholderImplInReverseOrder().reverse();
ControlFlowVisitor.Result implFlow = ControlFlowVisitor.INSTANCE.visitStatements(impl);
if (implFlow == implementationFlow()) {
List<JCStatement> prevBinding = resultUnifier.getBinding(placeholder().blockKey());
if (prevBinding != null && prevBinding.toString().equals(impl.toString())) {
return Optional.of(result);
} else if (prevBinding == null) {
resultUnifier.putBinding(placeholder().blockKey(), impl);
return Optional.of(result);
}
}
}
return Optional.absent();
});
}
@Override
public List<JCStatement> inlineStatements(Inliner inliner) throws CouldNotResolveImportException {
try {
Optional<List<JCStatement>> binding = inliner.getOptionalBinding(placeholder().blockKey());
// If a placeholder was used as an expression binding in the @BeforeTemplate,
// and as a bare statement or as a return in the @AfterTemplate, we may need to convert.
Optional<JCExpression> exprBinding = inliner.getOptionalBinding(placeholder().exprKey());
binding =
binding.or(
exprBinding.transform(
(JCExpression expr) -> {
switch (implementationFlow()) {
case NEVER_EXITS:
return List.of(inliner.maker().Exec(expr));
case ALWAYS_RETURNS:
return List.of(inliner.maker().Return(expr));
default:
throw new AssertionError();
}
}));
return UPlaceholderExpression.copier(arguments(), inliner).copy(binding.get(), inliner);
} catch (UncheckedCouldNotResolveImportException e) {
throw e.getCause();
}
}
}
| 8,217
| 40.928571
| 101
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/annotation/Placeholder.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.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation to indicate a placeholder method.
*
* <p>A placeholder method is an abstract method in a Refaster template class which can represent an
* arbitrary expression (if the return type is nonvoid), or zero or more statements (if the return
* type is void), in terms of its arguments. For example,
*
* <pre>{@code
* abstract class ComputeIfAbsent<K, V> {
* @Placeholder abstract V computeValue(K key);
*
* @BeforeTemplate void getOrCompute(Map<K, V> map, K key) {
* V value = map.get(key);
* if (value == null) {
* map.put(key, value = computeValue(key));
* }
* }
*
* @AfterTemplate void computeIfAbsent(Map<K, V> map, K key) {
* V value = map.computeIfAbsent(key, (K k) -> computeValue(k));
* }
* }
* }</pre>
*
* <p>Here, {@code computeValue} represents an arbitrary expression in terms of {@code key}, and the
* {@code @AfterTemplate} rewrites that same expression in terms of the parameter of a lambda
* expression.
*
* <p>For a multi-line example, consider
*
* <pre>{@code
* abstract class TryWithResources<T extends AutoCloseable> {
* @Placeholder abstract T open();
* @Placeholder void process(T resource);
*
* @BeforeTemplate void tryFinallyClose() {
* T resource = open();
* try {
* process(resource);
* } finally {
* resource.close();
* }
* }
*
* @AfterTemplate void tryWithResource() {
* try (T resource = open()) {
* process(resource);
* }
* }
* }
* }</pre>
*
* <p>Here, {@code process} is any block, though it must refer to {@code resource} in some way; it
* is not permitted to reassign the contents of {@code resource}.
*
* <p>Placeholder methods are not permitted to refer to any local variables or parameters of the
* {@code @BeforeTemplate} that are not passed to them as arguments. Additionally, they
* <em>must</em> contain references to all arguments that <em>are</em> passed to them -- except
* those corresponding to parameters annotated with {@link MayOptionallyUse}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Placeholder {
// TODO(lowasser): consider putting forbiddenKinds here as an annotation parameter
/**
* Identifies whether the placeholder is allowed to match an expression which simply returns one
* of the placeholder arguments unchanged.
*/
boolean allowsIdentity() default false;
}
| 3,288
| 33.621053
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/annotation/RequiredAnnotation.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.annotation;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates that an annotation requires the presence of another annotation. Only checked on
* Refaster templates at runtime.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@Target(ElementType.ANNOTATION_TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequiredAnnotation {
Class<? extends Annotation>[] value() default {};
}
| 1,214
| 32.75
| 92
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/annotation/AlsoNegation.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.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates that Refaster should, additionally, refactor the negation of this rule and its
* corresponding before templates. For example, given a {@code BeforeTemplate} with the code {@code
* str.length() == 0} and an {@code @AfterTemplate @AlsoNegation} with the code {@code
* str.isEmpty()}, Refaster would also rewrite {@code str.length() != 0} as {@code !str.isEmpty()}.
*
* <p>If this annotation is applied, all {@code BeforeTemplate} and {@code AfterTemplate} templates
* must be expression templates with boolean return type.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
@RequiredAnnotation(AfterTemplate.class)
public @interface AlsoNegation {}
| 1,507
| 39.756757
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/annotation/Matches.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.annotation;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ExpressionTree;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Specify an error-prone {@link Matcher} to further restrict what expressions are matched by the
* annotated parameter.
*
* <p><b>Note:</b> The {@code @Matches} annotation should <b>only</b> go on the
* {@code @BeforeTemplate}. For example:
*
* <pre>{@code
* class SingletonList {
* @BeforeTemplate
* public <E> List<E> before(@Matches(IsNonNullMatcher.class) E e) {
* return Collections.singletonList(e);
* }
*
* @AfterTemplate
* public <E> List<E> after(E e) {
* return ImmutableList.of(e);
* }
* }
* }</pre>
*/
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.SOURCE)
public @interface Matches {
Class<? extends Matcher<? super ExpressionTree>> value();
}
| 1,647
| 30.692308
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/annotation/UseImportPolicy.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.annotation;
import com.google.errorprone.refaster.ImportPolicy;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation to indicate which import policy to use.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
@RequiredAnnotation(AfterTemplate.class)
public @interface UseImportPolicy {
ImportPolicy value();
}
| 1,153
| 31.055556
| 75
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/annotation/BeforeTemplate.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.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Desired "before" version of a refactoring. Corresponds to a matching method annotated with {@link
* AfterTemplate}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface BeforeTemplate {}
| 1,100
| 32.363636
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/annotation/AllowCodeBetweenLines.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.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation on a Refaster rule to allow code between every pair of consecutive top-level
* statements in @BeforeTemplates that do not refer to variables Refaster knows about and do not
* break or return, and moves that code to the beginning of the @AfterTemplate.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface AllowCodeBetweenLines {}
| 1,253
| 35.882353
| 96
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/annotation/RequiredAnnotationProcessor.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.annotation;
import com.google.auto.common.AnnotationMirrors;
import com.google.errorprone.annotations.FormatMethod;
import com.google.errorprone.annotations.FormatString;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.SimpleAnnotationValueVisitor7;
import javax.tools.Diagnostic.Kind;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Enforces {@code @RequiredAnnotation} as an annotation processor.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@SupportedAnnotationTypes("*")
public final class RequiredAnnotationProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (annotations.isEmpty()) {
return false;
}
validateElements(roundEnv.getRootElements());
return false;
}
private @Nullable AnnotationMirror getAnnotationMirror(
Element element, TypeMirror annotationType) {
for (AnnotationMirror mirror : element.getAnnotationMirrors()) {
if (processingEnv.getTypeUtils().isSameType(mirror.getAnnotationType(), annotationType)) {
return mirror;
}
}
return null;
}
private @Nullable AnnotationValue getAnnotationValue(AnnotationMirror mirror, String key) {
for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
mirror.getElementValues().entrySet()) {
if (entry.getKey().getSimpleName().contentEquals(key)) {
return entry.getValue();
}
}
return null;
}
private void validateElements(Iterable<? extends Element> elements) {
for (Element element : elements) {
validateElement(element);
}
}
private void validateElement(Element element) {
TypeMirror requiredAnnotationTypeMirror =
processingEnv.getElementUtils().getTypeElement(RequiredAnnotation.class.getName()).asType();
for (AnnotationMirror annotation :
processingEnv.getElementUtils().getAllAnnotationMirrors(element)) {
AnnotationMirror requiredAnnotationMirror =
getAnnotationMirror(
annotation.getAnnotationType().asElement(), requiredAnnotationTypeMirror);
if (requiredAnnotationMirror == null) {
continue;
}
AnnotationValue value = getAnnotationValue(requiredAnnotationMirror, "value");
if (value == null) {
continue;
}
new SimpleAnnotationValueVisitor7<Void, Void>() {
@Override
public Void visitType(TypeMirror t, Void p) {
if (getAnnotationMirror(element, t) == null) {
printError(
element,
annotation,
"Annotation %s on %s also requires %s",
AnnotationMirrors.toString(annotation),
element,
t);
}
return null;
}
@Override
public Void visitArray(List<? extends AnnotationValue> vals, Void p) {
for (AnnotationValue val : vals) {
visit(val);
}
return null;
}
}.visit(value);
}
validateElements(element.getEnclosedElements());
}
@FormatMethod
private void printError(
Element element, AnnotationMirror annotation, @FormatString String message, Object... args) {
processingEnv
.getMessager()
.printMessage(Kind.ERROR, String.format(message, args), element, annotation);
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latest();
}
}
| 4,679
| 33.411765
| 100
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/annotation/NotMatches.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.annotation;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ExpressionTree;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Specify an error-prone {@link Matcher} to further restrict what expressions are matched by the
* annotated parameter.
*/
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.SOURCE)
public @interface NotMatches {
Class<? extends Matcher<? super ExpressionTree>> value();
}
| 1,222
| 33.942857
| 97
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/annotation/OfKind.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.annotation;
import com.sun.source.tree.Tree.Kind;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation to specify what tree kinds are allowed or disallowed to match a given expression.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.SOURCE)
public @interface OfKind {
Kind[] value();
}
| 1,128
| 31.257143
| 95
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/annotation/AfterTemplate.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.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Desired "after" version of a refactoring. Corresponds to a matching method annotated with {@link
* BeforeTemplate}.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface AfterTemplate {}
| 1,099
| 32.333333
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/annotation/Repeated.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.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* An annotation for repeated Refaster template variables.
*
* <p>A template variable with annotation @Repeated matches zero or more occurrences of expression.
* This is often used for varargs.
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.SOURCE)
public @interface Repeated {}
| 1,122
| 33.030303
| 99
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/annotation/NoAutoboxing.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.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates that a Refaster rule should not allow autoboxing when it is typechecking a match.
*
* @author lowasser@google.com (Louis Wasserman)
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
@RequiredAnnotation(BeforeTemplate.class)
public @interface NoAutoboxing {}
| 1,115
| 32.818182
| 94
|
java
|
error-prone
|
error-prone-master/core/src/main/java/com/google/errorprone/refaster/annotation/MayOptionallyUse.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.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates that a parameter to a placeholder method is not required to be used in the
* placeholder's implementation. For example, the pattern
*
* <pre>{@code
* abstract class Utf8Bytes {
* @Placeholder abstract void handleException(
* @MayOptionallyUse UnsupportedEncodingException e);
* @Placeholder abstract void useString(String str);
* @BeforeTemplate void before(byte[] array) {
* try {
* useString(new String(array, "UTF_8"));
* } catch (UnsupportedEncodingException e) {
* handleException(e);
* }
* }
* @AfterTemplate void after(byte[] array) {
* useString(new String(array, StandardCharsets.UTF_8));
* }
* }
* }</pre>
*
* would match even if the catch statement were empty, or didn't refer to e.
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.SOURCE)
public @interface MayOptionallyUse {}
| 1,702
| 32.392157
| 87
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/RequiredModifiers.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation declaring that the target annotation requires all the specified modifiers. For
* example, an annotation declared as:
*
* <pre>{@code
* @RequiredModifiers(modifier = Modifier.PUBLIC)
* @interface MyAnnotation {}
* }</pre>
*
* <p>will be considered illegal when used on non-public elements such as:
*
* <pre>{@code
* @MyAnnotation void foo() {}
* }</pre>
*
* @author benyu@google.com (Jige Yu)
*/
@Documented
@Retention(RetentionPolicy.CLASS) // Element's source might not be available during analysis
@Target(ElementType.ANNOTATION_TYPE)
public @interface RequiredModifiers {
/**
* @deprecated use {@link #modifier} instead
*/
@Deprecated
javax.lang.model.element.Modifier[] value() default {};
/**
* The required modifiers. The annotated element is illegal if any one or more of these modifiers
* are absent.
*
* <p>Empty array has the same effect as not applying this annotation at all; duplicates are
* allowed but have no effect.
*/
Modifier[] modifier() default {};
}
| 1,896
| 29.596774
| 99
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/SuppressPackageLocation.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates that the PackageLocation warning should be suppressed for this package.
*
* <p>The standard {@link SuppressWarnings} annotation cannot be applied to packages, so we must use
* a custom suppression annotation for this check.
*/
@Target(ElementType.PACKAGE)
@Retention(RetentionPolicy.CLASS)
public @interface SuppressPackageLocation {}
| 1,171
| 34.515152
| 100
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/Var.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.annotations;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.LOCAL_VARIABLE;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* The parameter or local variable to which this annotation is applied is non-final.
*
* <p>Most references are never modified, and accidentally modifying a reference is a potential
* source of bugs. To prevent accidental modifications, the accompanying Error Prone <a
* href="https://errorprone.info/bugpattern/Var">check</a> prevents parameters and local variables
* from being modified unless they are explicitly annotated with @Var.
*
* <p>Since Java 8 can infer whether a local variable or parameter is effectively {@code final}, and
* {@code @Var} makes it clear whether any variable is non- {@code final}, explicitly marking local
* variables and parameters as {@code final} is discouraged.
*
* <p>The annotation can also be applied to fields, to indicate that the field is deliberately
* non-final.
*/
@Target({FIELD, PARAMETER, LOCAL_VARIABLE})
@Retention(RUNTIME)
@IncompatibleModifiers(modifier = {Modifier.FINAL})
public @interface Var {}
| 1,933
| 41.043478
| 100
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/Immutable.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.annotations;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* The class to which this annotation is applied is immutable.
*
* <p>An object is immutable if its state cannot be observed to change after construction. Immutable
* objects are inherently thread-safe.
*
* <p>A class is immutable if all instances of that class are immutable. The immutability of a class
* can only be fully guaranteed if the class is final, otherwise one must ensure all subclasses are
* also immutable.
*
* <p>A conservative definition of object immutability is:
*
* <ul>
* <li>All fields are final;
* <li>All reference fields are of immutable type, or null;
* <li>It is <em>properly constructed</em> (the {@code this} reference does not escape the
* constructor).
* </ul>
*
* <p>The requirement that all reference fields be immutable ensures <em>deep</em> immutability,
* meaning all contained state is also immutable. A weaker property, common with container classes,
* is <em>shallow</em> immutability, which allows some of the object's fields to point to mutable
* objects. One example of shallow immutability is guava's ImmutableList, which may contain mutable
* elements.
*
* <p>It is possible to implement immutable classes with some internal mutable state, as long as
* callers can never observe changes to that state. For example, some state may be lazily
* initialized to improve performance.
*
* <p>It is also technically possible to have an immutable object with non-final fields (see the
* implementation of {@link String#hashCode()} for an example), but doing this correctly requires
* subtle reasoning about safe data races and deep knowledge of the Java Memory Model.
*
* <p>Use of this annotation is validated by <a
* href="https://errorprone.info/bugpattern/Immutable">Error Prone's immutability analysis</a>,
* which ensures that all {@code @Immutable}-annotated classes are deeply immutable according to the
* conservative definition above. Non-final classes may be annotated with {@code @Immutable}, and
* any code compiled by Error Prone will be checked to ensure that no mutable subtypes of
* {@code @Immutable}-annotated classes exist.
*
* <p>For more information about immutability, see:
*
* <ul>
* <li>Java Concurrency in Practice §3.4
* <li>Effective Java 3rd Edition §17
* </ul>
*/
@Documented
@Target(TYPE)
@Retention(RUNTIME)
@Inherited
public @interface Immutable {
/**
* When annotating a generic type as immutable, {@code containerOf} specifies which type
* parameters must be instantiated with immutable types for the container to be deeply immutable.
*/
String[] containerOf() default {};
}
| 3,545
| 40.717647
| 100
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/NoAllocation.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.annotations;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Documented;
import java.lang.annotation.Target;
/**
* Annotation for method declarations, which denotes that this method will not cause allocations
* that are visible from source code. Compilers or runtimes can still introduce opportunities for
* allocation to occur that might result in garbage collection.
*
* <p>Be careful using this annotation. It should be used sparingly, typically only for methods
* called within inner loops or user interface event handlers. Misuse will likely lead to decreased
* performance and significantly more complex code.
*/
@Documented
@Target(METHOD)
public @interface NoAllocation {}
| 1,366
| 36.972222
| 99
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/CanIgnoreReturnValue.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.annotations;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.CLASS;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Indicates that the return value of the annotated API is ignorable.
*
* <p>This is the opposite of {@link CheckReturnValue}. It can be used inside classes or packages
* annotated with {@code @CheckReturnValue} to exempt specific APIs from the default.
*/
@Documented
// Note: annotating a type with @CanIgnoreReturnValue is discouraged (and banned inside of Google)
@Target({METHOD, CONSTRUCTOR, TYPE})
@Retention(CLASS)
public @interface CanIgnoreReturnValue {}
| 1,469
| 36.692308
| 98
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/CompileTimeConstant.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.annotations;
import static java.lang.annotation.RetentionPolicy.CLASS;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Annotation for method parameter and class field declarations, which denotes that corresponding
* actual values must be compile-time constant expressions.
*
* <p>When the formal parameter of a method or constructor is annotated with the {@link
* CompileTimeConstant} type annotation, the corresponding actual parameter must be an expression
* that satisfies one of the following conditions:
*
* <ol>
* <li>The expression is one for which the Java compiler can determine a constant value at compile
* time, or
* <li>the expression consists of the literal {@code null}, or
* <li>the expression consists of a single identifier, where the identifier is a formal method
* parameter or class field that is declared {@code final} and has the {@link
* CompileTimeConstant} annotation.
* </ol>
*
* <p>This constraint on call sites of methods or constructors that have one or more formal
* parameters with this annotation is enforced by <a href="https://errorprone.info">error-prone</a>.
*
* <p>For example, the following code snippet is legal:
*
* <pre>{@code
* public class C {
* private static final String S = "Hello";
* void m(@CompileTimeConstant final String s) { }
* void n(@CompileTimeConstant final String t) {
* m(S + " World!");
* m(null);
* m(t);
* }
* }
* }</pre>
*
* <p>In contrast, the following is illegal:
*
* <pre>{@code
* public class C {
* void m(@CompileTimeConstant final String s) { }
* void n(String t) {
* m(t);
* }
* }
* }</pre>
*
* <p>When a class field is annotated with the {@link CompileTimeConstant} type annotation, the
* field must also be declared to be {@code final}, and the corresponding initialised value must be
* an expression that satisfies one of the following conditions:
*
* <ol>
* <li>The expression is one for which the Java compiler can determine a constant value at compile
* time, or
* <li>the expression consists of the literal {@code null}, or
* <li>the expression consists of a single identifier, where the identifier is a formal method
* parameter or class field that is declared {@code final} and has the {@link
* CompileTimeConstant} annotation.
* </ol>
*
* <p>This constraint on fields with this annotation is enforced by <a
* href="https://errorprone.info">error-prone</a>.
*
* <p>For example, the following code snippet is legal:
*
* <pre>{@code
* public class C {
* \@CompileTimeConstant final String S;
* public C(@CompileTimeConstant String s) {
* this.S = s;
* }
* void m(@CompileTimeConstant final String s) { }
* void n() {
* m(S);
* }
* }
* }</pre>
*
* <p>In contrast, the following are illegal:
*
* <pre>{@code
* public class C {
* \@CompileTimeConstant String S;
* public C(@CompileTimeConstant String s) {
* this.S = s;
* }
* void m(@CompileTimeConstant final String s) { }
* void n() {
* m(S);
* }
* }
* }</pre>
*
* <pre>{@code
* public class C {
* \@CompileTimeConstant final String S;
* public C(String s) {
* this.S = s;
* }
* }
* }</pre>
*
* <p>Compile-time constant values are implicitly under the control of the trust domain of the
* application whose source code they are part of. Hence, this annotation is useful to constrain the
* use of APIs that may only be safely called with values that are under application control.
*
* <p>The current implementation of the @CompileTimeConstant checker cannot reason about more
* complex scenarios, for example, returning compile-time-constant values from a method, or storing
* compile-time-constant values in a collection. APIs will typically accommodate such use cases via
* domain-specific types that capture domain-specific aspects of trustworthiness that arise from
* values being under application control.
*/
@Documented
@Retention(CLASS)
@Target({ElementType.PARAMETER, ElementType.FIELD})
public @interface CompileTimeConstant {}
| 4,859
| 33.714286
| 100
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/RestrictedApi.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.annotations;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
// TODO(b/157082874): Allow restricting entire classes.
/**
* Restrict this method to callsites with a allowlist annotation.
*
* <p>Callers that are not allowlisted will cause a configurable compiler diagnostic. Allowlisting
* can either allow the call outright, or make the compiler emit a warning when the API is called.
* Paths matching a regular expression, e.g. unit tests, can also be excluded.
*
* <p>The following example shows a hypothetical, potentially unsafe {@code Foo.bar} method. It is
* marked with the {@code @RestrictedApi} annotations such that callers annotated with
* {@code @LegacyUnsafeFooBar} raise a warning, whereas the {@code @ReviewedFooBar} annotation
* silently allows the call.
*
* <p>The {@code @LegacyUnsafeFooBar} annotation can be used to allow existing call sites until they
* are refactored, while prohibiting new call-sites. Call-sites determined to be acceptable, for
* example through code review, could be marked {@code @ReviewedFooBar}.
*
* <pre>{@code
* public @interface LegacyUnsafeFooBar{}
*
* public @interface ReviewedFooBar{
* public string reviewer();
* public string comments();
* }
*
* public class Foo {
* @RestrictedApi(
* explanation="You could shoot yourself in the foot with Foo.bar if you aren't careful",
* link="http://edsger.dijkstra/foo_bar_consider_harmful.html",
* allowedOnPath="testsuite/.*", // Unsafe behavior in tests is ok.
* allowlistAnnotations = {ReviewedFooBar.class},
* allowlistWithWarningAnnotations = {LegacyUnsafeFooBar.class})
* public void bar() {
* if (complicatedCondition) {
* shoot_your_foot();
* } else {
* solve_your_problem();
* }
* }
* boolean complicatedCondition = true;
*
* @ReviewedFooBar(
* reviewer="bangert",
* comments="Makes sure complicatedCondition isn't true, so bar is safe!"
* )
* public void safeBar() {
* if (!complicatedCondition) {
* bar();
* }
* }
*
* @LegacyUnsafeFooBar
* public void someOldCode() {
* // ...
* bar()
* // ...
* }
* }
* }</pre>
*/
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
public @interface RestrictedApi {
/** Explanation why the API is restricted, to be inserted into the compiler output. */
String explanation();
/** Optional link explaining why the API is restricted. */
String link() default "";
/**
* Allow the restricted API on paths matching this regular expression.
*
* <p>Leave empty (the default) to enforce the API restrictions on all paths.
*/
String allowedOnPath() default "";
/** Allow calls to the restricted API in methods or classes with this annotation. */
Class<? extends Annotation>[] allowlistAnnotations() default {};
/**
* Emit warnings, not errors, on calls to the restricted API for callers with this annotation.
*
* <p>This should only be used if callers should aggressively move away from this API (or change
* to a allowlist annotation after review). Too many warnings will lead to ALL warnings being
* ignored, so tread very carefully.
*/
Class<? extends Annotation>[] allowlistWithWarningAnnotations() default {};
}
| 3,996
| 35.336364
| 100
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/FormatString.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.annotations;
import static java.lang.annotation.RetentionPolicy.CLASS;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Annotation for method parameter declarations which denotes that actual parameters will be used as
* a format string in printf-style formatting.
*
* <p>This is an optional annotation used along with the {@link FormatMethod} annotation to denote
* which parameter in a format method is the format string. All parameters after the format string
* are assumed to be printf-style arguments for the format string. For example, the following
* snippet declares that {@code logMessage} will be used as a format string with {@code args} passed
* as arguments to the format string:
*
* <pre>
* public class Foo {
* @FormatMethod void doBarAndLogFailure(@FormatString String logMessage,
* Object... args) {...}
* }</pre>
*
* <p>See {@link FormatMethod} for more information.
*/
@Documented
@Retention(CLASS)
@Target({ElementType.PARAMETER})
public @interface FormatString {}
| 1,774
| 35.979167
| 100
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/DoNotMock.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.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation representing a type that should not be mocked.
*
* <p>When marking a type {@code @DoNotMock}, you should always point to alternative testing
* solutions such as standard fakes or other testing utilities.
*
* <p>Mockito tests can enforce this annotation by using a custom MockMaker which intercepts
* creation of mocks.
*/
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
public @interface DoNotMock {
/**
* The reason why the annotated type should not be mocked.
*
* <p>This should suggest alternative APIs to use for testing objects of this type.
*/
String value() default "Create a real instance instead";
}
| 1,612
| 33.319149
| 92
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/IncompatibleModifiers.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation declaring that the target annotation is incompatible with any one of the provided
* modifiers. For example, an annotation declared as:
*
* <pre>{@code
* @IncompatibleModifiers(modifier = Modifier.PUBLIC)
* @interface MyAnnotation {}
* </pre>
*
* <p>will be considered illegal when used as:
*
* <pre>
* @MyAnnotation public void foo() {}
* }</pre>
*
* @author benyu@google.com (Jige Yu)
*/
@Documented
@Retention(RetentionPolicy.CLASS) // Element's source might not be available during analysis
@Target(ElementType.ANNOTATION_TYPE)
public @interface IncompatibleModifiers {
/**
* @deprecated use {@link #modifier} instead
*/
@Deprecated
javax.lang.model.element.Modifier[] value() default {};
/**
* The incompatible modifiers. The annotated element is illegal with the presence of any one or
* more of these modifiers.
*
* <p>Empty array has the same effect as not applying this annotation at all; duplicates are
* allowed but have no effect.
*/
Modifier[] modifier() default {};
}
| 1,905
| 29.741935
| 97
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/CheckReturnValue.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.annotations;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PACKAGE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Indicates that the return value of the annotated method must be used. An error is triggered when
* one of these methods is called but the result is not used.
*
* <p>{@code @CheckReturnValue} may be applied to a class or package to indicate that all methods in
* that class (including indirectly; that is, methods of inner classes within the annotated class)
* or package must have their return values used. For convenience, we provide an annotation, {@link
* CanIgnoreReturnValue}, to exempt specific methods or classes from this behavior.
*/
@Documented
@Target({METHOD, CONSTRUCTOR, TYPE, PACKAGE})
@Retention(RUNTIME)
public @interface CheckReturnValue {}
| 1,727
| 40.142857
| 100
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/DoNotCall.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.annotations;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.CLASS;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.List;
/**
* Indicates that the annotated method should not be called under any normal circumstances, yet is
* either <i>impossible</i> to remove, or <i>should not</i> ever be removed. Example:
*
* <pre>{@code
* public class ImmutableList<E> implements List<E> {
* @DoNotCall("guaranteed to throw an exception")
* @Override public add(E e) {
* throw new UnsupportedOperationException();
* }
* }
* }</pre>
*
* By the demands of the {@code List} interface, this method can never be removed. However, since it
* should always throw an exception, there can be no valid reason to call it except in the rarest of
* circumstances. Although this information can only benefit users who have a reference of type
* {@code ImmutableList} (not {@link List}), it's a good start.
*
* <p>If the typical caller's best remedy is to "inline" the method, {@link InlineMe} is probably a
* better option; read there for more information. Using both annotations together is probably
* unnecessary.
*
* <p><b>Note on testing:</b> A {@code @DoNotCall} method should still have unit tests.
*
* <h2>{@code @DoNotCall} and deprecation</h2>
*
* <p>Deprecation may feel inappropriate or misleading in cases where there is no intention to ever
* remove the method. It might create the impression of a "blemish" on your API; something that
* should be fixed. Moreover, it's generally hard to enforce deprecation warnings as strongly as a
* {@code @DoNotCall} violation should be.
*
* <p>But, when choosing the {@code @DoNotCall} option, consider adding {@link Deprecated} as well
* anyway, so that any tools that don't support {@code @DoNotCall} can still do something reasonable
* to discourage usage. This practice does have some cost; for example, suppression would require
* {@code @SuppressWarnings({"DoNotCall", "deprecation"})}.
*
* <h2>Tool support</h2>
*
* Error Prone supports this annotation via its <a
* href="https://errorprone.info/bugpattern/DoNotCall">DoNotCall</a> pattern.
*/
@Retention(CLASS)
@Target(METHOD)
public @interface DoNotCall {
/** An optional explanation of why the method should not be called. */
String value() default "";
}
| 3,040
| 40.094595
| 100
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/OverridingMethodsMustInvokeSuper.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.annotations;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.CLASS;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Indicates that any concrete method that overrides the annotated method, directly or indirectly,
* must invoke {@code super.theAnnotatedMethod(...)} at some point. This does not necessarily
* require an <i>unconditional</i> call; any matching call appearing directly within the method body
* (not inside an intervening class or lambda expression) is acceptable.
*
* <p>If the overriding method is itself overridable, applying this annotation to that method is
* technically redundant, but may be helpful to readers.
*
* <p><b>Preferred:</b> usually, a better solution is to make the method {@code final}, and have its
* implementation delegate to a second concrete method which <i>is</i> overridable (or to a function
* object which subclasses can specify). "Mandatory" statements remain in the final method while
* "optional" code moves out. This is the only way to make sure the statements will be executed
* unconditionally.
*/
@Documented
@Target(METHOD)
@Retention(CLASS)
public @interface OverridingMethodsMustInvokeSuper {}
| 1,932
| 42.931818
| 100
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/CompatibleWith.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.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Collection;
/**
* Declares that a parameter to a method must be "compatible with" one of the type parameters in the
* method's enclosing class, or on the method itself. "Compatible with" means that there can exist a
* "reference casting conversion" from one type to the other (JLS 5.5.1).
*
* <p>For example, {@link Collection#contains} would be annotated as follows:
*
* <pre>{@code
* interface Collection<E> {
* boolean contains(@CompatibleWith("E") Object o);
* }
* }</pre>
*
* <p>To indicate that invocations of {@link Collection#contains} must be passed an argument whose
* type is compatible with the generic type argument of the Collection instance:
*
* <pre>{@code
* Collection<String> stringCollection = ...;
* boolean shouldBeFalse = stringCollection.contains(42); // BUG! int isn't compatible with String
* }</pre>
*
* <p>Note: currently, this annotation can't be used if the method overrides another method that has
* {@code @CompatibleWith} already present.
*/
@Documented
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.PARAMETER)
public @interface CompatibleWith {
String value();
}
| 2,003
| 34.785714
| 100
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/ForOverride.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.annotations;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.CLASS;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Indicates that the annotated method is provided only to be overridden: it should not be
* <i>invoked</i> from outside its declaring source file (as if it is {@code private}), and
* overriding methods should not be directly invoked at all. Such a method represents a contract
* between a class and its <i>subclasses</i> only, and is not to be considered part of the
* <i>caller</i>-facing API of either class.
*
* <p>The annotated method must have protected or package-private visibility, and must not be {@code
* static}, {@code final} or declared in a {@code final} class. Overriding methods must have either
* protected or package-private visibility, although their effective visibility is actually "none".
*/
@Documented
@IncompatibleModifiers(
modifier = {Modifier.PUBLIC, Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL})
@Retention(CLASS) // Parent source might not be available while compiling subclass
@Target(METHOD)
public @interface ForOverride {}
| 1,864
| 42.372093
| 100
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/ThreadSafe.java
|
/*
* Copyright 2023 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.annotations;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* This annotation indicates that the class/interface it is applied to is thread safe
*
* <p>An object is thread safe if no sequences of accesses (like reads and writes to public fields
* or calls to public methods) may put the object into an invalid state, or cause it to violate its
* contract, regardless of the interleaving of those actions at runtime.
*
* <p>This annotation has two related-but-distinct purposes:
*
* <ul>
* <li>For humans: it indicates that the class/interface (and subclasses) is thread-safe
* <li>For machines: it causes the annotated class/interface -- and all of its subtypes -- to be
* validated by the {@code com.google.errorprone.bugpatterns.threadsafety.ThreadSafeChecker}
* {@code BugChecker}.
* </ul>
*
* Note that passing the checks performed by the {@code ThreadSafeChecker} is neither necessary nor
* sufficient to guarantee the thread safety of a class. In fact, it is not possible to determine
* thread safety through static code analysis alone, and the goal of {@code ThreadSafeChecker} is to
* steer the code towards using standard thread-safe patterns, and then to assist the developer in
* avoiding common mistakes. It is not meant as a substitute for diligent code review by a
* knowledgeable developer.
*
* <p>Also note that the only easy way to guarantee thread-safety of a class is to make it
* immutable, and you should do that whenever possible (or at the least, make as much of the class
* be immutable). Otherwise, writing a thread-safe class is inherently tricky and error prone, and
* keeping it thread-safe is even more so.
*
* <p>The remainder of this javadoc describes the heuristics enforced by {@code ThreadSafeChecker}
* and the related {@code com.google.errorprone.bugpatterns.threadsafety.GuardedByChecker} and
* {@code com.google.errorprone.bugpatterns.threadsafety.ImmutableChecker} on which the former
* relies.
*
* <p>The {@code ThreadSafeChecker} heuristics enforce that every field meets at least one of these
* requirements:
*
* <ul>
* <li>It is both {@code final} and its type is deemed inherently deeply thread-safe; and/or
* <li>it is annotated with either {@link com.google.errorprone.annotations.concurrent.GuardedBy}
* (some other annotations named {@code GuardedBy} also work, though this the preferred);
* </ul>
*
* Below, more details about what is meant by "deemed inherently deeply thread-safe" are presented,
* and, afterwards, more about {@code GuardedBy}.
*
* <p>A type is deemed inherently deeply thread-safe if it meets two requirements. The first
* requirement is that it meets at least one of these four conditions:
*
* <ul>
* <li>it is listed as a well-known immutable type in {@code
* com.google.errorprone.bugpatterns.threadsafety.WellKnownMutability} (e.g. a field of type
* {@link String}); and/or
* <li>it is listed as a well-known thread-safe type in {@code
* com.google.errorprone.bugpatterns.threadsafety.WellKnownThreadSafety} (e.g. a field of type
* {@link java.util.concurrent.atomic.AtomicBoolean}); and/or
* <li>it is annotated with {@link Immutable}; and/or
* <li>it is annotated with {@link ThreadSafe}.
* </ul>
*
* <p>This first requirement means the type is at least inherently shallowly thread-safe.
*
* <p>Fields annotated with {@code javax.annotation.concurrent.GuardedBy} are likely the meat of a
* mutable thread-safe class: these are things that need to be mutated, but should be done so in a
* safe manner -- i.e., (most likely) in critical sections of code that protect their access by
* means of a lock. See more information in that annotation's javadoc.
*
* <p>As stated before, the heuristics above are not sufficient to guarantee the thread safety of a
* class. Also as stated before, thread-safety is tricky, and requires diligent analysis by skilled
* people. That said, we provide here a few examples of common examples of ways to break these
* heuristics, so as to help you avoid them:
*
* <ul>
* <li>a non-private {@code @GuardedBy} field -- i.e.if a non-private {@code @GuardedBy} field is
* accessed outside the class, the code that enforces {@code @GuardedBy} will not prevent
* unprotected access and/or modifications to the field;
* <li>indirect access to the field. There are several ways in which code may access the objects
* stored in the field indirectly (i.e. not directly referencing the field). In all these
* cases, {@code @GuardedBy} offers no enforcement. Here's some examples:
* <ul>
* <li>if the {@code @GuardedBy} field instance is part of an object by a method (e.g. a
* simple getter method or constructor parameter);
* <li>if a method takes an out-parameter and the method calls a method in that
* out-parameter passing the instance of the {@code @GuardedBy} field, and that instance
* is stored in the out-parameter (i.e. a simple setter method);
* </ul>
* <li>methods that perform multiple operations -- e.g., if a class {@code Foo} contains a {@code
* AtomicInteger} (which is an inherently deeply thread-safe data structure), the following
* code makes this class not thread-safe:
* <pre>{@code
* private void incrementMyAtomicInteger() {
* myAtomicInteger.set(myAtomicInteger.get() + 1);
* }
*
* }</pre>
* </ul>
*
* Also see https://errorprone.info/bugpattern/ThreadSafe
*/
// TODO(b/112275411): when fixed, delete the comment above about non-private fields
@Target({TYPE})
@Retention(RUNTIME)
// Note: besides abiding by the standard behavior of `@Inherited`, the behavior enforced by
// the static analysis effectively applies not only to classes that extend a class annotated with
// @ThreadSafe but *also* applies to classes that implement an annotated interface. This is because
// a class that implements an interface annotated with `@ThreadSafe` either: a. is anonymous, in
// which case the static analysis is implemented to run against it; or b. it is not anonymous, in
// which case the static analysis enforces that the class _also_ have an `@ThreadSafe` annotation.
@Inherited
@Documented
public @interface ThreadSafe {}
| 7,174
| 51.372263
| 100
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/MustBeClosed.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.annotations;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Documented;
import java.lang.annotation.Target;
/**
* Annotation for constructors of AutoCloseables or methods that return an AutoCloseable and require
* that the resource is closed.
*
* <p>This is enforced by checking that invocations occur within the resource variable initializer
* of a try-with-resources statement, which guarantees that the resource is always closed. The
* analysis may be improved in the future to recognize other patterns where the resource will always
* be closed.
*
* <p>Note that Android SDK versions prior to 19 do not support try-with-resources, so the
* annotation should be avoided on APIs that may be used on Android, unless desugaring is used.
*/
@Documented
@Target({CONSTRUCTOR, METHOD})
public @interface MustBeClosed {}
| 1,566
| 38.175
| 100
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/InlineMe.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.annotations;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Documented;
import java.lang.annotation.Target;
/**
* Indicates that callers of this API should be inlined. That is, this API is trivially expressible
* in terms of another API, for example a method that just calls another method.
*/
@Documented
@Target({METHOD, CONSTRUCTOR})
public @interface InlineMe {
/**
* What the caller should be replaced with. Local parameter names can be used in the replacement
* string. If you are invoking an instance method or constructor, you must include the implicit
* {@code this} in the replacement body. If you are invoking a static method, you must include the
* implicit {@code ClassName} in the replacement body.
*/
String replacement();
/** The new imports to (optionally) add to the caller. */
String[] imports() default {};
/** The new static imports to (optionally) add to the caller. */
String[] staticImports() default {};
}
| 1,701
| 36
| 100
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/Keep.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.annotations;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Indicates that the annotated element should not be removed, and that its visibility, modifiers,
* type, and name should not be modified.
*
* <p>For example, program elements that are referenced via reflection may be annotated to prevent
* them from being removed by static analysis that detects dead code.
*
* <p>If this annotates another annotation type, any member annotated with that annotation type
* should also be kept.
*/
@Documented
@Target({ANNOTATION_TYPE, CONSTRUCTOR, FIELD, METHOD, TYPE})
@Retention(RUNTIME)
public @interface Keep {}
| 1,678
| 38.046512
| 98
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/InlineMeValidationDisabled.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.annotations;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Target;
/**
* An annotation that disables validation of the {@link InlineMe} annotation's correctness (i.e.:
* that it accurately represents an inlining of the annotated method).
*/
@Target({METHOD, CONSTRUCTOR})
public @interface InlineMeValidationDisabled {
/**
* An explanation as to why the validation is disabled (e.g.: moving from a constructor to a
* static factory method that delegates to this constructor, which is behavior-perserving, but
* isn't strictly an inlining).
*/
String value();
}
| 1,319
| 34.675676
| 97
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/FormatMethod.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.annotations;
import static java.lang.annotation.RetentionPolicy.CLASS;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Annotation for a method that takes a printf-style format string as an argument followed by
* arguments for that format string.
*
* <p>This annotation is used in conjunction with {@link FormatString} to denote a method that takes
* a printf-style format string and its format arguments. In any method annotated as {@code
* FormatMethod} without a {@link FormatString} parameter, the first {@code String} parameter is
* assumed to be the format string. For example, the following two methods are equivalent:
*
* <pre>
* @FormatMethod void log(Locale l, @FormatString String logMessage, Object... args) {}
* @FormatMethod void log(Locale l, String logMessage, Object... args) {}
* </pre>
*
* <p>Using {@link FormatMethod} on a method header will ensure the following for the parameters
* passed to the method:
*
* <ol>
* <li>A format string is either:
* <ul>
* <li>A compile time constant value (see {@link CompileTimeConstant} for more info).
* <p>The following example is valid:
* <pre>
* public class Foo {
* static final String staticFinalLogMessage = "foo";
* @FormatMethod void log(@FormatString String format, Object... args) {}
* void validLogs() {
* log("String literal");
* log(staticFinalLogMessage);
* }
* }</pre>
* <p>However the following would be invalid:
* <pre>
* public class Foo{
* @FormatMethod void log(@FormatString String format, Object... args) {}
* void invalidLog(String notCompileTimeConstant) {
* log(notCompileTimeConstant);
* }
* }</pre>
* <li>An effectively final variable that was assigned to a compile time constant value.
* This is to permit the following common case:
* <pre>
* String format = "Some long format string: %s";
* log(format, arg);
* </pre>
* <li>Another {@link FormatString} annotated parameter. Ex:
* <pre>
* public class Foo {
* static final String staticFinalLogMessage = "foo";
* @FormatMethod void log(@FormatString String format, Object... args) {}
* @FormatMethod void validLog(@FormatString String format, Object... args) {
* log(format, args);
* }
* }</pre>
* </ul>
* <li>The format string will be valid for the input format arguments. In the case that the actual
* format string parameter has a compile time constant value, this will compare the actual
* format string value to the types of the passed in format arguments to ensure validity. In
* the case that the actual format string parameter is a parameter that was annotated {@link
* FormatString} itself, this will ensure that the types of the arguments passed to the callee
* match the types of the arguments in the caller.
* </ol>
*/
@Documented
@Retention(CLASS)
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
public @interface FormatMethod {}
| 3,851
| 40.419355
| 100
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/Modifier.java
|
/*
* Copyright 2021 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.annotations;
/**
* Modifiers in the Java language, as specified in:
*
* <ul>
* <li>https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#jls-8.1.1
* <li>https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#jls-8.3.1
* <li>https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#jls-8.4.3
* <li>https://docs.oracle.com/javase/specs/jls/se11/html/jls-9.html#jls-9.4
* </ul>
*/
public enum Modifier {
PUBLIC,
PROTECTED,
PRIVATE,
ABSTRACT,
DEFAULT,
STATIC,
FINAL,
TRANSIENT,
VOLATILE,
SYNCHRONIZED,
NATIVE,
STRICTFP
}
| 1,218
| 27.348837
| 80
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/concurrent/LazyInit.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.annotations.concurrent;
import com.google.errorprone.annotations.IncompatibleModifiers;
import com.google.errorprone.annotations.Modifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Use this annotation on any static or field that will be initialized lazily, where races yield no
* semantic difference in the code (as, for example, is the case with {@link String#hashCode}). Note
* that lazily initializing a non-volatile field is hard to do correctly, and one should rarely use
* this. It should also only be done by developers who clearly understand the potential issues, and
* then, always using the pattern as presented in the {@code getData} method of this sample code
* below:
*
* <pre>{@code
* private final String source;
* @LazyInit private String data;
*
* public String getData() {
* String local = data;
* if (local == null) {
* data = local = expensiveCalculation(source);
* }
* return local;
* }
*
* private static String expensiveCalculation(String string) {
* return string.replaceAll(" ", "_");
* }
* }</pre>
*
* <p>The need for using the {@code local} variable is detailed in
* http://jeremymanson.blogspot.com/2008/12/benign-data-races-in-java.html (see, particularly, the
* part after "Now, let's break the code").
*
* <p>Also note that {@code LazyInit} must not be used on 64-bit primitives ({@code long}s and
* {@code double}s), because the Java Language Specification does not guarantee that writing to
* these is atomic. Furthermore, when used for non-primitives, the non-primitive must be either
* truly immutable or at least thread safe (in the Java memory model sense). And callers must
* accommodate the fact that different calls to something like the above getData() method may return
* different (though identically computed) objects, with different identityHashCode() values. Again,
* unless you really understand this <b>and</b> you really need the performance benefits of
* introducing the data race, do not use this construct.
*/
@IncompatibleModifiers(modifier = {Modifier.FINAL})
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface LazyInit {}
| 2,924
| 42.656716
| 100
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/concurrent/UnlockMethod.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.annotations.concurrent;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.CLASS;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* The method to which this annotation is applied releases one or more locks. The caller must hold
* the locks when the function is entered, and will not hold them when it completes.
*
* <p>This annotation does not apply to built-in (synchronization) locks, which cannot be released
* without being acquired in the same method.
*
* <p>The arguments determine which locks the annotated method releases:
*
* <ul>
* <li><code>field-name</code>: The lock is referenced by the final instance field specified by
* <em>field-name</em>.
* <li><code>class-name.this.field-name</code>: For inner classes, it may be necessary to
* disambiguate 'this'; the <em>class-name.this</em> designation allows you to specify which
* 'this' reference is intended.
* <li><code>class-name.field-name</code>: The lock is referenced by the static final field
* specified by <em>class-name.field-name</em>.
* <li><code>method-name()</code>: The lock object is returned by calling the named nullary
* method.
* </ul>
*
* @deprecated the correctness of this annotation is not enforced; it will soon be removed.
*/
@Target(METHOD)
@Retention(CLASS)
@Deprecated
public @interface UnlockMethod {
String[] value();
}
| 2,103
| 37.962963
| 98
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/concurrent/LockMethod.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.annotations.concurrent;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.CLASS;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* The method to which this annotation is applied acquires one or more locks. The caller will hold
* the locks when the function finishes execution.
*
* <p>This annotation does not apply to built-in (synchronization) locks, which cannot be acquired
* without being released in the same method.
*
* <p>The arguments determine which locks the annotated method acquires:
*
* <ul>
* <li><code>field-name</code>: The lock is referenced by the final instance field specified by
* <em>field-name</em>.
* <li><code>class-name.this.field-name</code>: For inner classes, it may be necessary to
* disambiguate 'this'; the <em>class-name.this</em> designation allows you to specify which
* 'this' reference is intended.
* <li><code>class-name.field-name</code>: The lock is referenced by the static final field
* specified by <em>class-name.field-name</em>.
* <li><code>method-name()</code>: The lock object is returned by calling the named nullary
* method.
* </ul>
*
* @deprecated the correctness of this annotation is not enforced; it will soon be removed.
*/
@Target(METHOD)
@Retention(CLASS)
@Deprecated
public @interface LockMethod {
String[] value();
}
| 2,067
| 37.296296
| 98
|
java
|
error-prone
|
error-prone-master/annotations/src/main/java/com/google/errorprone/annotations/concurrent/GuardedBy.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.annotations.concurrent;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.CLASS;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/** Indicates that the annotated element should be used only while holding the specified lock. */
@Target({FIELD, METHOD})
@Retention(CLASS)
public @interface GuardedBy {
/**
* The lock that should be held, specified in the format given in <a
* href="https://errorprone.info/bugpattern/GuardedBy">the documentation for the corresponding
* Error Prone check</a>.
*/
String value();
}
| 1,306
| 35.305556
| 97
|
java
|
error-prone
|
error-prone-master/docgen_processor/src/main/java/com/google/errorprone/DocGenProcessor.java
|
/*
* Copyright 2011 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.auto.service.AutoService;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.FileObject;
import javax.tools.StandardLocation;
/**
* Annotation processor which visits all classes that have a {@code BugPattern} annotation, and
* writes a tab-delimited text file dumping the data found.
*
* @author eaftan@google.com (Eddie Aftandilian)
* @author alexeagle@google.com (Alex Eagle)
*/
@AutoService(Processor.class)
@SupportedAnnotationTypes("com.google.errorprone.BugPattern")
public class DocGenProcessor extends AbstractProcessor {
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latest();
}
private final Gson gson = new Gson();
private PrintWriter pw;
/** {@inheritDoc} */
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
try {
FileObject manifest =
processingEnv
.getFiler()
.createResource(StandardLocation.SOURCE_OUTPUT, "", "bugPatterns.txt");
pw = new PrintWriter(new OutputStreamWriter(manifest.openOutputStream(), UTF_8), true);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/** {@inheritDoc} */
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for (Element element : roundEnv.getElementsAnnotatedWith(BugPattern.class)) {
gson.toJson(BugPatternInstance.fromElement(element), pw);
pw.println();
}
if (roundEnv.processingOver()) {
// this was the last round, do cleanup
cleanup();
}
return false;
}
/** Perform cleanup after last round of annotation processing. */
private void cleanup() {
pw.close();
}
}
| 2,963
| 30.870968
| 95
|
java
|
error-prone
|
error-prone-master/docgen_processor/src/main/java/com/google/errorprone/BugPatternInstance.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import com.google.common.base.Preconditions;
import com.google.errorprone.BugPattern.SeverityLevel;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
/** A serialization-friendly POJO of the information in a {@link BugPattern}. */
public final class BugPatternInstance {
public String className;
public String name;
public String summary;
public String explanation;
public String[] altNames;
public String category;
public String[] tags;
public SeverityLevel severity;
public String[] suppressionAnnotations;
public boolean documentSuppression = true;
public static BugPatternInstance fromElement(Element element) {
BugPatternInstance instance = new BugPatternInstance();
instance.className = element.toString();
BugPattern annotation = element.getAnnotation(BugPattern.class);
instance.name =
annotation.name().isEmpty() ? element.getSimpleName().toString() : annotation.name();
instance.altNames = annotation.altNames();
instance.tags = annotation.tags();
instance.severity = annotation.severity();
instance.summary = annotation.summary();
instance.explanation = annotation.explanation();
instance.documentSuppression = annotation.documentSuppression();
Map<String, Object> keyValues = getAnnotation(element, BugPattern.class.getName());
Object suppression = keyValues.get("suppressionAnnotations");
if (suppression == null) {
instance.suppressionAnnotations = new String[] {SuppressWarnings.class.getName()};
} else {
Preconditions.checkState(suppression instanceof List);
@SuppressWarnings("unchecked") // Always List<? extends AnnotationValue>, see above.
List<? extends AnnotationValue> resultList = (List<? extends AnnotationValue>) suppression;
instance.suppressionAnnotations =
resultList.stream().map(AnnotationValue::toString).toArray(String[]::new);
}
return instance;
}
private static Map<String, Object> getAnnotation(Element element, String name) {
for (AnnotationMirror mirror : element.getAnnotationMirrors()) {
if (mirror.getAnnotationType().toString().equals(name)) {
return annotationKeyValues(mirror);
}
}
throw new IllegalArgumentException(String.format("%s has no annotation %s", element, name));
}
private static Map<String, Object> annotationKeyValues(AnnotationMirror mirror) {
Map<String, Object> result = new LinkedHashMap<>();
for (ExecutableElement key : mirror.getElementValues().keySet()) {
result.put(key.getSimpleName().toString(), mirror.getElementValues().get(key).getValue());
}
return result;
}
}
| 3,500
| 38.337079
| 97
|
java
|
error-prone
|
error-prone-master/test_helpers/src/test/java/com/google/errorprone/BugCheckerRefactoringTestHelperTest.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static com.google.common.truth.Truth.assertThat;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.fail;
import com.google.errorprone.BugCheckerRefactoringTestHelper.TestMode;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.ReturnTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ReturnTree;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link BugCheckerRefactoringTestHelper}. */
@RunWith(JUnit4.class)
public class BugCheckerRefactoringTestHelperTest {
private BugCheckerRefactoringTestHelper helper;
@Before
public void setUp() {
helper = BugCheckerRefactoringTestHelper.newInstance(ReturnNullRefactoring.class, getClass());
}
@Test
public void noMatch() {
helper
.addInputLines("in/Test.java", "public class Test {}")
.addOutputLines("out/Test.java", "public class Test {}")
.doTest();
}
@Test
public void replace() {
helper
.addInputLines(
"in/Test.java",
"public class Test {",
" public Object foo() {",
" Integer i = 1 + 2;",
" return i;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"public class Test {",
" public Object foo() {",
" Integer i = 1 + 2;",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void replaceFail() {
assertThrows(
AssertionError.class,
() ->
helper
.addInputLines(
"in/Test.java",
"public class Test {",
" public Object foo() {",
" Integer i = 1 + 2;",
" return i;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"public class Test {",
" public Object foo() {",
" Integer i = 1 + 2;",
" return i;",
" }",
"}")
.doTest());
}
@Test
public void replaceTextMatch() {
helper
.addInputLines(
"in/Test.java",
"public class Test {",
" public Object foo() {",
" Integer i = 1 + 2;",
" return i;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"public class Test {",
" public Object foo() {",
" Integer i = 1 + 2;",
" return null;",
" }",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void ignoreWhitespace() {
helper
.addInputLines(
"in/Test.java",
"public class Test {",
" public Object foo() { Integer i = 2 + 1; return i; }",
"}")
.addOutputLines(
"out/Test.java",
"public class Test {",
" public Object foo() {",
" Integer i = 2 + 1;",
" return null;",
" }",
"}")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void replaceTextMatchFail() {
assertThrows(
AssertionError.class,
() ->
helper
.addInputLines(
"in/Test.java",
"public class Test {",
" public Object foo() {",
" Integer i = 1 + 2;",
" return i;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"public class Test {",
" public Object foo() {",
" Integer i = 2 + 1;",
" return null;",
" }",
"}")
.doTest(TestMode.TEXT_MATCH));
}
@Test
public void compilationErrorFail() {
try {
helper
.addInputLines("syntax_error.java", "public clazz Bar { ! this should fail }")
.expectUnchanged()
.doTest();
} catch (AssertionError e) {
assertThat(e).hasMessageThat().contains("compilation failed unexpectedly");
return;
}
fail("compilation succeeded unexpectedly");
}
@Test
public void annotationFullName() {
BugCheckerRefactoringTestHelper.newInstance(RemoveAnnotationRefactoring.class, getClass())
.addInputLines("bar/Foo.java", "package bar;", "public @interface Foo {", "};")
.expectUnchanged()
.addInputLines("foo/Bar.java", "import bar.Foo;", "public @Foo class Bar {", "}")
.addOutputLines("out/foo/Bar.java", "import bar.Foo;", "public class Bar {", "}")
.doTest(TestMode.TEXT_MATCH);
}
/** Mock {@link BugChecker} for testing only. */
@BugPattern(
summary = "Mock refactoring that replaces all returns with 'return null;' statement.",
explanation = "For test purposes only.",
severity = SUGGESTION)
public static class ReturnNullRefactoring extends BugChecker implements ReturnTreeMatcher {
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
return describeMatch(tree, SuggestedFix.replace(tree, "return null;"));
}
}
/** Mock {@link BugChecker} for testing only. */
@BugPattern(
summary = "Mock refactoring that removes all annotations declared in package bar ",
explanation = "For test purposes only.",
severity = SUGGESTION)
public static class RemoveAnnotationRefactoring extends BugChecker
implements AnnotationTreeMatcher {
@Override
public Description matchAnnotation(AnnotationTree tree, VisitorState state) {
if (ASTHelpers.getType(tree).asElement().toString().startsWith("bar.")) {
return describeMatch(tree, SuggestedFix.replace(tree, ""));
}
return Description.NO_MATCH;
}
}
@Test
public void compilationError() {
try {
helper
.addInputLines("Test.java", "public class Test extends NoSuch {}")
.expectUnchanged()
.doTest();
} catch (AssertionError e) {
assertThat(e).hasMessageThat().contains("error: cannot find symbol");
return;
}
fail("compilation succeeded unexpectedly");
}
@Test
public void staticLastImportOrder() {
BugCheckerRefactoringTestHelper.newInstance(ImportArrayList.class, getClass())
.setImportOrder("static-last")
.addInputLines("pkg/A.java", "import static java.lang.Math.min;", "class A {", "}")
.addOutputLines(
"out/pkg/A.java",
"import java.util.ArrayList;",
"",
"import static java.lang.Math.min;",
"class A {",
"}")
.doTest(TestMode.TEXT_MATCH);
}
/** Mock {@link BugChecker} for testing only. */
@BugPattern(
summary = "Mock refactoring that imports an ArrayList",
explanation = "For test purposes only.",
severity = SUGGESTION)
public static class ImportArrayList extends BugChecker implements CompilationUnitTreeMatcher {
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
SuggestedFix fix = SuggestedFix.builder().addImport("java.util.ArrayList").build();
return describeMatch(tree, fix);
}
}
@Test
public void onlyCallDoTestOnce() {
helper.addInputLines("Test.java", "public class Test {}").expectUnchanged().doTest();
IllegalStateException expected =
assertThrows(IllegalStateException.class, () -> helper.doTest());
assertThat(expected).hasMessageThat().contains("doTest");
}
}
| 8,985
| 31.557971
| 98
|
java
|
error-prone
|
error-prone-master/test_helpers/src/test/java/com/google/errorprone/CompilationTestHelperTest.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static com.google.common.truth.Truth.assertThat;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static org.junit.Assert.assertThrows;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.ReturnTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ReturnTree;
import com.sun.tools.javac.main.Main.Result;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link CompilationTestHelper}. */
@RunWith(JUnit4.class)
public class CompilationTestHelperTest {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(ReturnTreeChecker.class, getClass());
@Test
public void fileWithNoBugMarkersAndNoErrorsShouldPass() {
compilationHelper.addSourceLines("Test.java", "public class Test {}").doTest();
}
@Test
public void fileWithNoBugMarkersAndErrorFails() {
AssertionError expected =
assertThrows(
AssertionError.class,
() ->
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" public boolean doIt() {",
" return true;",
" }",
"}")
.doTest());
assertThat(expected).hasMessageThat().contains("Saw unexpected error on line 3");
}
@Test
public void fileWithBugMarkerAndNoErrorsFails() {
AssertionError expected =
assertThrows(
AssertionError.class,
() ->
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" // BUG: Diagnostic contains:",
" public void doIt() {}",
"}")
.doTest());
assertThat(expected).hasMessageThat().contains("Did not see an error on line 3");
}
@Test
public void fileWithBugMatcherAndNoErrorsFails() {
AssertionError expected =
assertThrows(
AssertionError.class,
() ->
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" // BUG: Diagnostic matches: X",
" public void doIt() {}",
"}")
.expectErrorMessage("X", Predicates.containsPattern(""))
.doTest());
assertThat(expected).hasMessageThat().contains("Did not see an error on line 3");
}
@Test
public void fileWithBugMarkerAndMatchingErrorSucceeds() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" public boolean doIt() {",
" // BUG: Diagnostic contains: Method may return normally",
" return true;",
" }",
"}")
.doTest();
}
@Test
public void fileWithBugMatcherAndMatchingErrorSucceeds() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" public boolean doIt() {",
" // BUG: Diagnostic matches: X",
" return true;",
" }",
"}")
.expectErrorMessage("X", Predicates.containsPattern("Method may return normally"))
.doTest();
}
@Test
public void fileWithBugMarkerAndErrorOnWrongLineFails() {
AssertionError expected =
assertThrows(
AssertionError.class,
() ->
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" // BUG: Diagnostic contains:",
" public boolean doIt() {",
" return true;",
" }",
"}")
.doTest());
assertThat(expected).hasMessageThat().contains("Did not see an error on line 3");
}
@Test
public void fileWithBugMatcherAndErrorOnWrongLineFails() {
AssertionError expected =
assertThrows(
AssertionError.class,
() ->
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" // BUG: Diagnostic matches: X",
" public boolean doIt() {",
" return true;",
" }",
"}")
.expectErrorMessage("X", Predicates.containsPattern(""))
.doTest());
assertThat(expected).hasMessageThat().contains("Did not see an error on line 3");
}
@Test
public void fileWithMultipleBugMarkersAndMatchingErrorsSucceeds() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" public boolean doIt() {",
" // BUG: Diagnostic contains: Method may return normally",
" return true;",
" }",
" public String doItAgain() {",
" // BUG: Diagnostic contains: Method may return normally",
" return null;",
" }",
"}")
.doTest();
}
@Test
public void fileWithMultipleSameBugMatchersAndMatchingErrorsSucceeds() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" public boolean doIt() {",
" // BUG: Diagnostic matches: X",
" return true;",
" }",
" public String doItAgain() {",
" // BUG: Diagnostic matches: X",
" return null;",
" }",
"}")
.expectErrorMessage("X", Predicates.containsPattern("Method may return normally"))
.doTest();
}
@Test
public void fileWithMultipleDifferentBugMatchersAndMatchingErrorsSucceeds() {
compilationHelper
.addSourceLines(
"Test.java",
"public class Test {",
" public boolean doIt() {",
" // BUG: Diagnostic matches: X",
" return true;",
" }",
" public String doItAgain() {",
" // BUG: Diagnostic matches: Y",
" return null;",
" }",
"}")
.expectErrorMessage("X", Predicates.containsPattern("Method may return normally"))
.expectErrorMessage("Y", Predicates.containsPattern("Method may return normally"))
.doTest();
}
@Test
public void fileWithSyntaxErrorFails() {
AssertionError expected =
assertThrows(
AssertionError.class,
() ->
compilationHelper
.addSourceLines(
"Test.java",
"class Test {",
" void m() {",
" // BUG: Diagnostic contains:",
// There's a syntax error on this line, but it shouldn't register as an
// Error Prone diagnostic
" return}",
"}")
.doTest());
assertThat(expected).hasMessageThat().contains("error: illegal start of expression");
}
@Test
public void expectedResultMatchesActualResultSucceeds() {
compilationHelper
.expectResult(Result.OK)
.addSourceLines("Test.java", "public class Test {}")
.doTest();
}
@Test
public void expectedResultDiffersFromActualResultFails() {
AssertionError expected =
assertThrows(
AssertionError.class,
() ->
compilationHelper
.expectResult(Result.ERROR)
.addSourceLines("Test.java", "public class Test {}")
.doTest());
assertThat(expected).hasMessageThat().contains("Expected compilation result ERROR, but was OK");
}
@Test
public void expectNoDiagnoticsAndNoDiagnosticsProducedSucceeds() {
compilationHelper
.expectNoDiagnostics()
.addSourceLines("Test.java", "// BUG: Diagnostic contains:", "public class Test {}")
.doTest();
}
@Test
public void expectNoDiagnoticsAndNoDiagnosticsProducedSucceedsWithMatches() {
compilationHelper
.expectNoDiagnostics()
.addSourceLines("Test.java", "// BUG: Diagnostic matches: X", "public class Test {}")
.expectErrorMessage("X", Predicates.containsPattern(""))
.doTest();
}
@Test
public void expectNoDiagnoticsButDiagnosticsProducedFails() {
AssertionError expected =
assertThrows(
AssertionError.class,
() ->
compilationHelper
.expectNoDiagnostics()
.addSourceLines(
"Test.java",
"public class Test {",
" public boolean doIt() {",
" // BUG: Diagnostic contains:",
" return true;",
" }",
"}")
.doTest());
assertThat(expected).hasMessageThat().contains("Expected no diagnostics produced, but found 1");
}
@Test
public void expectNoDiagnoticsButDiagnosticsProducedFailsWithMatches() {
AssertionError expected =
assertThrows(
AssertionError.class,
() ->
compilationHelper
.expectNoDiagnostics()
.addSourceLines(
"Test.java",
"public class Test {",
" public boolean doIt() {",
" // BUG: Diagnostic matches: X",
" return true;",
" }",
"}")
.expectErrorMessage("X", Predicates.containsPattern(""))
.doTest());
assertThat(expected).hasMessageThat().contains("Expected no diagnostics produced, but found 1");
}
@Test
public void failureWithErrorAndNoDiagnosticFails() {
InvalidCommandLineOptionException expected =
assertThrows(
InvalidCommandLineOptionException.class,
() ->
compilationHelper
.expectNoDiagnostics()
.addSourceLines("Test.java", "public class Test {}")
.setArgs(
ImmutableList.of("-Xep:ReturnTreeChecker:Squirrels")) // Bad flag crashes.
.doTest());
assertThat(expected)
.hasMessageThat()
.contains("invalid flag: -Xep:ReturnTreeChecker:Squirrels");
}
@Test
public void commandLineArgToDisableCheckWorks() {
compilationHelper
.setArgs(ImmutableList.of("-Xep:ReturnTreeChecker:OFF"))
.expectNoDiagnostics()
.addSourceLines(
"Test.java",
"public class Test {",
" public boolean doIt() {",
" // BUG: Diagnostic contains:",
" return true;",
" }",
"}")
.doTest();
}
@Test
public void missingExpectErrorFails() {
AssertionError expected =
assertThrows(
AssertionError.class,
() ->
compilationHelper
.addSourceLines(
"Test.java", " // BUG: Diagnostic matches: X", "public class Test {}")
.doTest());
assertThat(expected).hasMessageThat().contains("No expected error message with key [X]");
}
@BugPattern(
summary = "Method may return normally.",
explanation = "Consider mutating some global state instead.",
severity = ERROR)
public static class ReturnTreeChecker extends BugChecker implements ReturnTreeMatcher {
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
return describeMatch(tree);
}
}
@Test
public void unexpectedDiagnosticOnFirstLine() {
AssertionError expected =
assertThrows(
AssertionError.class,
() ->
CompilationTestHelper.newInstance(PackageTreeChecker.class, getClass())
.addSourceLines("test/Test.java", "package test;", "public class Test {}")
.doTest());
assertThat(expected).hasMessageThat().contains("Package declaration found");
}
@BugPattern(
summary = "Package declaration found",
explanation = "Prefer to use the default package for everything.",
severity = ERROR)
public static class PackageTreeChecker extends BugChecker implements CompilationUnitTreeMatcher {
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
if (tree.getPackage() != null) {
return describeMatch(tree.getPackage());
}
return NO_MATCH;
}
}
/** Test classes used for withClassPath tests */
public static class WithClassPath extends WithClassPathSuper {}
public static class WithClassPathSuper {}
@Test
public void withClassPath_success() {
compilationHelper
.addSourceLines(
"Test.java",
"import " + WithClassPath.class.getCanonicalName() + ";",
"class Test extends WithClassPath {}")
.withClasspath(
CompilationTestHelperTest.class, WithClassPath.class, WithClassPathSuper.class)
.doTest();
}
@Test
public void withClassPath_failure() {
// disable checkWellFormed
compilationHelper
.addSourceLines(
"Test.java",
"import " + WithClassPath.class.getCanonicalName() + ";",
"// BUG: Diagnostic contains: cannot access "
+ WithClassPathSuper.class.getCanonicalName(),
"class Test extends WithClassPath {}")
.withClasspath(CompilationTestHelperTest.class, WithClassPath.class)
.matchAllDiagnostics()
.expectResult(Result.ERROR)
.doTest();
}
@Test
public void onlyCallDoTestOnce() {
compilationHelper.addSourceLines("Test.java", "public class Test {}").doTest();
IllegalStateException expected =
assertThrows(IllegalStateException.class, () -> compilationHelper.doTest());
assertThat(expected).hasMessageThat().contains("doTest");
}
@Test
public void assertionErrors_causeTestFailures() {
var compilationTestHelper =
CompilationTestHelper.newInstance(AssertionFailingChecker.class, getClass())
.addSourceLines("test/Test.java", "package test;", "public class Test {}");
AssertionError expected =
assertThrows(AssertionError.class, () -> compilationTestHelper.doTest());
assertThat(expected)
.hasMessageThat()
.contains("An unhandled exception was thrown by the Error Prone static analysis plugin");
}
/** A BugPattern that always throws. */
@BugPattern(summary = "A really broken checker.", severity = ERROR)
public static class AssertionFailingChecker extends BugChecker
implements CompilationUnitTreeMatcher {
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
throw new AssertionError();
}
}
}
| 16,541
| 34.04661
| 100
|
java
|
error-prone
|
error-prone-master/test_helpers/src/main/java/com/google/errorprone/FileManagers.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static com.google.common.base.StandardSystemProperty.JAVA_CLASS_PATH;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Streams.stream;
import static java.lang.ThreadLocal.withInitial;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.stream;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.jimfs.Jimfs;
import com.sun.tools.javac.file.CacheFSInfo;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.util.Context;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.tools.StandardLocation;
/**
* Manages {@link JavacFileManager}s for use in Error Prone's test.
*
* <p>The file manager does some expensive IO to process the platform and user classpaths, so we
* re-use the same filemanager instance across multiple tests to re-use that work.
*/
public final class FileManagers {
// The file manager isn't thread-safe, so keep one instance per thread instead of using static
// state, in case this is accessed from multiple threads.
private static final ThreadLocal<JavacFileManager> FILE_MANAGER =
withInitial(FileManagers::createFileManager);
private static final ThreadLocal<FileSystem> FILE_SYSTEM = withInitial(Jimfs::newFileSystem);
private static JavacFileManager createFileManager() {
Context context = new Context();
// Install the non-default caching version of FSInfo, which caches the result of filesystem
// calls to files on the classpath.
CacheFSInfo.preRegister(context);
return new JavacFileManager(context, /* register= */ false, UTF_8);
}
/** Returns a {@link JavacFileManager} for use in compiler-based tests. */
public static JavacFileManager testFileManager() {
JavacFileManager fileManager = FILE_MANAGER.get();
// Explicitly set the class path to the ambient runtime's classpath. This is the default
// behaviour, but re-doing it for each test avoids issues when tests are executed in different
// classloaders observed with IntelliJ and maven.
setLocation(fileManager, systemClassPath(), StandardLocation.CLASS_PATH);
// Set the output directories (for compiled classes and generated sources) to an in-memory
// temporary directory, to avoid successful compilations trying to write their output to
// local disk wherever the test is executing.
Path tempDirectory;
try {
tempDirectory =
Files.createTempDirectory(FILE_SYSTEM.get().getRootDirectories().iterator().next(), "");
} catch (IOException e) {
throw new UncheckedIOException(e);
}
stream(StandardLocation.values())
.filter(StandardLocation::isOutputLocation)
.forEach(
outputLocation ->
setLocation(fileManager, ImmutableList.of(tempDirectory), outputLocation));
return fileManager;
}
/** Returns the current runtime's classpath. */
private static ImmutableList<Path> systemClassPath() {
// splitToStream isn't available if Android guava is on the classpath
return stream(Splitter.on(File.pathSeparatorChar).split(JAVA_CLASS_PATH.value()))
.map(Paths::get)
.collect(toImmutableList());
}
private static void setLocation(
JavacFileManager fileManager, ImmutableList<Path> collect, StandardLocation classPath) {
// Calling `setLocationFromPaths` on trusted inputs should never fail, so rethrow the
// specified `IOException` as unchecked so we can call it in lambdas.
try {
fileManager.setLocationFromPaths(classPath, collect);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private FileManagers() {}
}
| 4,555
| 39.318584
| 98
|
java
|
error-prone
|
error-prone-master/test_helpers/src/main/java/com/google/errorprone/BugCheckerRefactoringTestHelper.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static com.google.common.collect.Streams.stream;
import static com.google.common.truth.Truth.assertAbout;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.errorprone.FileObjects.forResource;
import static com.google.errorprone.FileObjects.forSourceLines;
import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;
import static org.junit.Assert.fail;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableBiMap;
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.Iterators;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.CheckReturnValue;
import com.google.errorprone.apply.DescriptionBasedDiff;
import com.google.errorprone.apply.ImportOrganizer;
import com.google.errorprone.apply.SourceFile;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.fixes.Fix;
import com.google.errorprone.scanner.ErrorProneScanner;
import com.google.errorprone.scanner.ErrorProneScannerTransformer;
import com.google.errorprone.scanner.Scanner;
import com.google.errorprone.scanner.ScannerSupplier;
import com.google.googlejavaformat.java.Formatter;
import com.google.googlejavaformat.java.FormatterException;
import com.google.testing.compile.JavaFileObjects;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.util.TreePath;
import com.sun.tools.javac.api.JavacTaskImpl;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.main.JavaCompiler;
import com.sun.tools.javac.tree.JCTree.JCClassDecl;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.util.Context;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UncheckedIOException;
import java.net.URI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaFileObject;
/**
* Compare a file transformed as suggested by {@link BugChecker} to an expected source.
*
* <p>Inputs are a {@link BugChecker} instance, input file and expected file.
*
* @author kurs@google.com (Jan Kurs)
*/
@CheckReturnValue
public class BugCheckerRefactoringTestHelper {
/** Test mode for matching refactored source against expected source. */
public enum TestMode {
TEXT_MATCH {
@Override
void verifyMatch(JavaFileObject refactoredSource, JavaFileObject expectedSource)
throws IOException {
assertThat(maybeFormat(refactoredSource.getCharContent(false).toString()))
.isEqualTo(maybeFormat(expectedSource.getCharContent(false).toString()));
}
private String maybeFormat(String input) {
try {
return new Formatter().formatSource(input);
} catch (FormatterException e) {
return input;
}
}
},
AST_MATCH {
@Override
void verifyMatch(JavaFileObject refactoredSource, JavaFileObject expectedSource) {
assertAbout(javaSource()).that(refactoredSource).parsesAs(expectedSource);
}
};
abstract void verifyMatch(JavaFileObject refactoredSource, JavaFileObject expectedSource)
throws IOException;
}
/**
* For checks that provide multiple possible fixes, chooses the one that will be applied for the
* test.
*/
public interface FixChooser {
Fix choose(List<Fix> fixes);
}
/** Predefined FixChoosers for selecting a fix by its position in the list */
public enum FixChoosers implements FixChooser {
FIRST {
@Override
public Fix choose(List<Fix> fixes) {
return fixes.get(0);
}
},
SECOND {
@Override
public Fix choose(List<Fix> fixes) {
return fixes.get(1);
}
},
THIRD {
@Override
public Fix choose(List<Fix> fixes) {
return fixes.get(2);
}
},
FOURTH {
@Override
public Fix choose(List<Fix> fixes) {
return fixes.get(3);
}
}
}
private final Map<JavaFileObject, JavaFileObject> sources = new HashMap<>();
private final Class<?> clazz;
private final ScannerSupplier scannerSupplier;
private FixChooser fixChooser = FixChoosers.FIRST;
private ImmutableList<String> options = ImmutableList.of();
private boolean allowBreakingChanges = false;
private String importOrder = "static-first";
private boolean run = false;
private BugCheckerRefactoringTestHelper(Class<?> clazz, ScannerSupplier scannerSupplier) {
this.clazz = clazz;
this.scannerSupplier = scannerSupplier;
}
/**
* @deprecated prefer {@link #newInstance(Class, Class)}
*/
@Deprecated
public static BugCheckerRefactoringTestHelper newInstance(
BugChecker refactoringBugChecker, Class<?> clazz) {
return new BugCheckerRefactoringTestHelper(
clazz, new OverrideIgnoringScannerSupplier(new ErrorProneScanner(refactoringBugChecker)));
}
/**
* Returns a new {@link CompilationTestHelper}.
*
* @param scannerSupplier the {@link ScannerSupplier} to test
* @param clazz the class to use to locate file resources
*/
public static BugCheckerRefactoringTestHelper newInstance(
ScannerSupplier scannerSupplier, Class<?> clazz) {
return new BugCheckerRefactoringTestHelper(clazz, scannerSupplier);
}
public static BugCheckerRefactoringTestHelper newInstance(
Class<? extends BugChecker> checkerClass, Class<?> clazz) {
return new BugCheckerRefactoringTestHelper(
clazz, ScannerSupplier.fromBugCheckerClasses(checkerClass));
}
public BugCheckerRefactoringTestHelper.ExpectOutput addInput(String inputFilename) {
return new ExpectOutput(forResource(clazz, inputFilename));
}
public BugCheckerRefactoringTestHelper.ExpectOutput addInputLines(String path, String... input) {
return new ExpectOutput(forSourceLines(path, input));
}
@CanIgnoreReturnValue
public BugCheckerRefactoringTestHelper setFixChooser(FixChooser chooser) {
this.fixChooser = chooser;
return this;
}
@CanIgnoreReturnValue
public BugCheckerRefactoringTestHelper addModules(String... modules) {
return setArgs(
Arrays.stream(modules)
.map(m -> String.format("--add-exports=%s=ALL-UNNAMED", m))
.collect(toImmutableList()));
}
@CanIgnoreReturnValue
public BugCheckerRefactoringTestHelper setArgs(ImmutableList<String> args) {
checkState(options.isEmpty());
this.options = args;
return this;
}
@CanIgnoreReturnValue
public BugCheckerRefactoringTestHelper setArgs(String... args) {
this.options = ImmutableList.copyOf(args);
return this;
}
/** If set, fixes that produce output that doesn't compile are allowed. Off by default. */
@CanIgnoreReturnValue
public BugCheckerRefactoringTestHelper allowBreakingChanges() {
allowBreakingChanges = true;
return this;
}
@CanIgnoreReturnValue
public BugCheckerRefactoringTestHelper setImportOrder(String importOrder) {
this.importOrder = importOrder;
return this;
}
public void doTest() {
this.doTest(TestMode.AST_MATCH);
}
public void doTest(TestMode testMode) {
checkState(!run, "doTest should only be called once");
this.run = true;
for (Map.Entry<JavaFileObject, JavaFileObject> entry : sources.entrySet()) {
try {
runTestOnPair(entry.getKey(), entry.getValue(), testMode);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
@CanIgnoreReturnValue
private BugCheckerRefactoringTestHelper addInputAndOutput(
JavaFileObject input, JavaFileObject output) {
sources.put(input, output);
return this;
}
private void runTestOnPair(JavaFileObject input, JavaFileObject output, TestMode testMode)
throws IOException {
Context context = new Context();
JCCompilationUnit tree = doCompile(input, sources.keySet(), context);
JavaFileObject transformed = applyDiff(input, context, tree);
closeCompiler(context);
testMode.verifyMatch(transformed, output);
if (!allowBreakingChanges) {
Context anotherContext = new Context();
doCompile(output, sources.values(), anotherContext);
closeCompiler(anotherContext);
}
}
@CanIgnoreReturnValue
private JCCompilationUnit doCompile(
JavaFileObject input, Iterable<JavaFileObject> files, Context context) throws IOException {
JavacTool tool = JavacTool.create();
DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<>();
ErrorProneOptions errorProneOptions;
try {
errorProneOptions = ErrorProneOptions.processArgs(options);
} catch (InvalidCommandLineOptionException e) {
throw new IllegalArgumentException("Exception during argument processing: " + e);
}
context.put(ErrorProneOptions.class, errorProneOptions);
StringWriter out = new StringWriter();
JavacTaskImpl task =
(JavacTaskImpl)
tool.getTask(
new PrintWriter(out, true),
FileManagers.testFileManager(),
diagnosticsCollector,
ImmutableList.copyOf(errorProneOptions.getRemainingArgs()),
/* classes= */ null,
files,
context);
Iterable<? extends CompilationUnitTree> trees = task.parse();
task.analyze();
ImmutableMap<URI, ? extends CompilationUnitTree> byUri =
stream(trees).collect(toImmutableMap(t -> t.getSourceFile().toUri(), t -> t));
URI inputUri = input.toUri();
assertWithMessage(out + Joiner.on('\n').join(diagnosticsCollector.getDiagnostics()))
.that(byUri)
.containsKey(inputUri);
JCCompilationUnit tree = (JCCompilationUnit) byUri.get(inputUri);
Iterable<Diagnostic<? extends JavaFileObject>> errorDiagnostics =
Iterables.filter(
diagnosticsCollector.getDiagnostics(), d -> d.getKind() == Diagnostic.Kind.ERROR);
if (!Iterables.isEmpty(errorDiagnostics)) {
fail("compilation failed unexpectedly: " + errorDiagnostics);
}
return tree;
}
private JavaFileObject applyDiff(
JavaFileObject sourceFileObject, Context context, JCCompilationUnit tree) throws IOException {
ImportOrganizer importOrganizer = ImportOrderParser.getImportOrganizer(importOrder);
DescriptionBasedDiff diff = DescriptionBasedDiff.create(tree, importOrganizer);
ErrorProneOptions errorProneOptions = context.get(ErrorProneOptions.class);
ErrorProneScannerTransformer.create(scannerSupplier.applyOverrides(errorProneOptions).get())
.apply(
new TreePath(tree),
context,
description -> {
if (!description.fixes.isEmpty()) {
diff.handleFix(fixChooser.choose(description.fixes));
}
});
SourceFile sourceFile = SourceFile.create(sourceFileObject);
diff.applyDifferences(sourceFile);
JavaFileObject transformed =
JavaFileObjects.forSourceString(getFullyQualifiedName(tree), sourceFile.getSourceText());
return transformed;
}
private static String getFullyQualifiedName(JCCompilationUnit tree) {
Iterator<JCClassDecl> types =
Iterables.filter(tree.getTypeDecls(), JCClassDecl.class).iterator();
if (types.hasNext()) {
return Iterators.getOnlyElement(types).sym.getQualifiedName().toString();
}
// Fallback: if no class is declared, then assume we're looking at a `package-info.java`..
if (tree.getPackage() != null) {
return tree.getPackage().packge.package_info.toString();
}
// ..or a `module-info.java`.
return tree.getModuleDecl().sym.getQualifiedName().toString();
}
/** To assert the proper {@code .addInput().addOutput()} chain. */
public class ExpectOutput {
private final JavaFileObject input;
private ExpectOutput(JavaFileObject input) {
this.input = input;
}
public BugCheckerRefactoringTestHelper addOutputLines(String path, String... output) {
return addInputAndOutput(input, forSourceLines(path, output));
}
public BugCheckerRefactoringTestHelper addOutput(String outputFilename) {
return addInputAndOutput(input, forResource(clazz, outputFilename));
}
public BugCheckerRefactoringTestHelper expectUnchanged() {
return addInputAndOutput(input, input);
}
}
private static void closeCompiler(Context context) {
JavaCompiler compiler = context.get(JavaCompiler.compilerKey);
if (compiler != null) {
compiler.close();
}
}
/**
* Wraps a {@code InstanceReturningScannerSupplier}, but silently skips {@link #applyOverrides}
* instead of throwing {@code UOE}.
*/
private static class OverrideIgnoringScannerSupplier extends ScannerSupplier {
private final ScannerSupplier delegate;
public OverrideIgnoringScannerSupplier(ErrorProneScanner scanner) {
delegate = ScannerSupplier.fromScanner(scanner);
}
@Override
public Scanner get() {
return delegate.get();
}
@Override
public ScannerSupplier applyOverrides(ErrorProneOptions errorProneOptions) {
return this;
}
@Override
public ImmutableBiMap<String, BugCheckerInfo> getAllChecks() {
throw new UnsupportedOperationException();
}
@Override
public ImmutableSet<BugCheckerInfo> getEnabledChecks() {
throw new UnsupportedOperationException();
}
@Override
public ImmutableMap<String, SeverityLevel> severities() {
throw new UnsupportedOperationException();
}
@Override
protected ImmutableSet<String> disabled() {
throw new UnsupportedOperationException();
}
@Override
public ErrorProneFlags getFlags() {
throw new UnsupportedOperationException();
}
}
}
| 15,023
| 33.777778
| 100
|
java
|
error-prone
|
error-prone-master/test_helpers/src/main/java/com/google/errorprone/DiagnosticTestHelper.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static com.google.common.truth.Truth.assertWithMessage;
import static java.util.Locale.ENGLISH;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.Assert.fail;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import com.google.common.io.CharSource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticListener;
import javax.tools.JavaFileObject;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeDiagnosingMatcher;
/**
* Utility class for tests which need to assert on the diagnostics produced during compilation.
*
* @author alexeagle@google.com (Alex Eagle)
*/
public class DiagnosticTestHelper {
// When testing a single error-prone check, the name of the check. Used to validate diagnostics.
// Null if not testing a single error-prone check.
private final String checkName;
private final Map<String, Predicate<? super String>> expectedErrorMsgs = new HashMap<>();
/** Construct a {@link DiagnosticTestHelper} not associated with a specific check. */
public DiagnosticTestHelper() {
this(null);
}
/** Construct a {@link DiagnosticTestHelper} for a check with the given name. */
public DiagnosticTestHelper(String checkName) {
this.checkName = checkName;
}
public final ClearableDiagnosticCollector<JavaFileObject> collector =
new ClearableDiagnosticCollector<>();
public static Matcher<Diagnostic<? extends JavaFileObject>> suggestsRemovalOfLine(
URI fileUri, int line) {
return allOf(
diagnosticOnLine(fileUri, line), diagnosticMessage(containsString("remove this line")));
}
public List<Diagnostic<? extends JavaFileObject>> getDiagnostics() {
return collector.getDiagnostics();
}
public void clearDiagnostics() {
collector.clear();
}
public String describe() {
StringBuilder stringBuilder = new StringBuilder().append("Diagnostics:\n");
for (Diagnostic<? extends JavaFileObject> diagnostic : getDiagnostics()) {
stringBuilder
.append(" [")
.append(diagnostic.getLineNumber())
.append(":")
.append(diagnostic.getColumnNumber())
.append("]\t");
stringBuilder.append(diagnostic.getMessage(Locale.getDefault()).replace("\n", "\\n"));
stringBuilder.append("\n");
}
return stringBuilder.toString();
}
public static Matcher<Diagnostic<? extends JavaFileObject>> diagnosticLineAndColumn(
long line, long column) {
return new TypeSafeDiagnosingMatcher<Diagnostic<? extends JavaFileObject>>() {
@Override
protected boolean matchesSafely(
Diagnostic<? extends JavaFileObject> item, Description mismatchDescription) {
if (item.getLineNumber() != line) {
mismatchDescription
.appendText("diagnostic not on line ")
.appendValue(item.getLineNumber());
return false;
}
if (item.getColumnNumber() != column) {
mismatchDescription
.appendText("diagnostic not on column ")
.appendValue(item.getColumnNumber());
return false;
}
return true;
}
@Override
public void describeTo(Description description) {
description
.appendText("a diagnostic on line:column ")
.appendValue(line)
.appendText(":")
.appendValue(column);
}
};
}
public static Matcher<Diagnostic<? extends JavaFileObject>> diagnosticOnLine(
URI fileUri, long line) {
return new TypeSafeDiagnosingMatcher<Diagnostic<? extends JavaFileObject>>() {
@Override
public boolean matchesSafely(
Diagnostic<? extends JavaFileObject> item, Description mismatchDescription) {
if (item.getSource() == null) {
mismatchDescription
.appendText("diagnostic not attached to a file: ")
.appendValue(item.getMessage(ENGLISH));
return false;
}
if (!item.getSource().toUri().equals(fileUri)) {
mismatchDescription.appendText("diagnostic not in file ").appendValue(fileUri);
return false;
}
if (item.getLineNumber() != line) {
mismatchDescription
.appendText("diagnostic not on line ")
.appendValue(item.getLineNumber());
return false;
}
return true;
}
@Override
public void describeTo(Description description) {
description.appendText("a diagnostic on line ").appendValue(line);
}
};
}
public static Matcher<Diagnostic<? extends JavaFileObject>> diagnosticOnLine(
URI fileUri, long line, Predicate<? super String> matcher) {
return new TypeSafeDiagnosingMatcher<Diagnostic<? extends JavaFileObject>>() {
@Override
public boolean matchesSafely(
Diagnostic<? extends JavaFileObject> item, Description mismatchDescription) {
if (item.getSource() == null) {
mismatchDescription
.appendText("diagnostic not attached to a file: ")
.appendValue(item.getMessage(ENGLISH));
return false;
}
if (!item.getSource().toUri().equals(fileUri)) {
mismatchDescription.appendText("diagnostic not in file ").appendValue(fileUri);
return false;
}
if (item.getLineNumber() != line) {
mismatchDescription
.appendText("diagnostic not on line ")
.appendValue(item.getLineNumber());
return false;
}
if (!matcher.test(item.getMessage(Locale.getDefault()))) {
mismatchDescription.appendText("diagnostic does not match ").appendValue(matcher);
return false;
}
return true;
}
@Override
public void describeTo(Description description) {
description
.appendText("a diagnostic on line ")
.appendValue(line)
.appendText(" that matches \n")
.appendValue(matcher)
.appendText("\n");
}
};
}
public static Matcher<Diagnostic<? extends JavaFileObject>> diagnosticMessage(
Matcher<String> matcher) {
return new TypeSafeDiagnosingMatcher<Diagnostic<? extends JavaFileObject>>() {
@Override
public boolean matchesSafely(
Diagnostic<? extends JavaFileObject> item, Description mismatchDescription) {
if (!matcher.matches(item.getMessage(Locale.getDefault()))) {
mismatchDescription
.appendText("diagnostic message does not match ")
.appendDescriptionOf(matcher);
return false;
}
return true;
}
@Override
public void describeTo(Description description) {
description.appendText("a diagnostic with message ").appendDescriptionOf(matcher);
}
};
}
/**
* Comment that marks a bug on the next line in a test file. For example, "// BUG: Diagnostic
* contains: foo.bar()", where "foo.bar()" is a string that should be in the diagnostic for the
* line. Multiple expected strings may be separated by newlines, e.g. // BUG: Diagnostic contains:
* foo.bar() // bar.baz() // baz.foo()
*/
private static final String BUG_MARKER_COMMENT_INLINE = "// BUG: Diagnostic contains:";
private static final String BUG_MARKER_COMMENT_LOOKUP = "// BUG: Diagnostic matches:";
private final Set<String> usedLookupKeys = new HashSet<>();
enum LookForCheckNameInDiagnostic {
YES,
NO;
}
/**
* Expects an error message matching {@code matcher} at the line below a comment matching the key.
* For example, given the source
*
* <pre>
* // BUG: Diagnostic matches: X
* a = b + c;
* </pre>
*
* ... you can use {@code expectErrorMessage("X", Predicates.containsPattern("Can't add b to
* c"));}
*
* <p>Error message keys that don't match any diagnostics will cause test to fail.
*/
public void expectErrorMessage(String key, Predicate<? super String> matcher) {
expectedErrorMsgs.put(key, matcher);
}
/**
* Asserts that the diagnostics contain a diagnostic on each line of the source file that matches
* our bug marker pattern. Parses the bug marker pattern for the specific string to look for in
* the diagnostic.
*
* @param source File in which to find matching lines
*/
public void assertHasDiagnosticOnAllMatchingLines(
JavaFileObject source, LookForCheckNameInDiagnostic lookForCheckNameInDiagnostic)
throws IOException {
List<Diagnostic<? extends JavaFileObject>> diagnostics = getDiagnostics();
LineNumberReader reader =
new LineNumberReader(CharSource.wrap(source.getCharContent(false)).openStream());
do {
String line = reader.readLine();
if (line == null) {
break;
}
List<Predicate<? super String>> predicates = null;
if (line.contains(BUG_MARKER_COMMENT_INLINE)) {
// Diagnostic must contain all patterns from the bug marker comment.
List<String> patterns = extractPatterns(line, reader, BUG_MARKER_COMMENT_INLINE);
predicates = new ArrayList<>(patterns.size());
for (String pattern : patterns) {
predicates.add(new SimpleStringContains(pattern));
}
} else if (line.contains(BUG_MARKER_COMMENT_LOOKUP)) {
int markerLineNumber = reader.getLineNumber();
List<String> lookupKeys = extractPatterns(line, reader, BUG_MARKER_COMMENT_LOOKUP);
predicates = new ArrayList<>(lookupKeys.size());
for (String lookupKey : lookupKeys) {
assertWithMessage(
"No expected error message with key [%s] as expected from line [%s] "
+ "with diagnostic [%s]",
lookupKey, markerLineNumber, line.trim())
.that(expectedErrorMsgs.containsKey(lookupKey))
.isTrue();
predicates.add(expectedErrorMsgs.get(lookupKey));
usedLookupKeys.add(lookupKey);
}
}
if (predicates != null) {
int lineNumber = reader.getLineNumber();
for (Predicate<? super String> predicate : predicates) {
Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> patternMatcher =
hasItem(diagnosticOnLine(source.toUri(), lineNumber, predicate));
assertWithMessage(
"Did not see an error on line %s matching %s. %s",
lineNumber, predicate, allErrors(diagnostics))
.that(patternMatcher.matches(diagnostics))
.isTrue();
}
if (checkName != null && lookForCheckNameInDiagnostic == LookForCheckNameInDiagnostic.YES) {
// Diagnostic must contain check name.
Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> checkNameMatcher =
hasItem(
diagnosticOnLine(
source.toUri(), lineNumber, new SimpleStringContains("[" + checkName + "]")));
assertWithMessage(
"Did not see an error on line %s containing [%s]. %s",
lineNumber, checkName, allErrors(diagnostics))
.that(checkNameMatcher.matches(diagnostics))
.isTrue();
}
} else {
int lineNumber = reader.getLineNumber();
Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher =
hasItem(diagnosticOnLine(source.toUri(), lineNumber));
if (matcher.matches(diagnostics)) {
fail("Saw unexpected error on line " + lineNumber + ". " + allErrors(diagnostics));
}
}
} while (true);
reader.close();
}
private static String allErrors(List<Diagnostic<? extends JavaFileObject>> diagnostics) {
if (diagnostics.isEmpty()) {
return "There were no errors.";
}
return "All errors:\n"
+ diagnostics.stream().map(Object::toString).collect(Collectors.joining("\n\n"));
}
/** Returns the lookup keys that weren't used. */
public Set<String> getUnusedLookupKeys() {
return Sets.difference(expectedErrorMsgs.keySet(), usedLookupKeys);
}
/**
* Extracts the patterns from a bug marker comment.
*
* @param line The first line of the bug marker comment
* @param reader A reader for the test file
* @param matchString The bug marker comment match string.
* @return A list of patterns that the diagnostic is expected to contain
*/
private static List<String> extractPatterns(
String line, BufferedReader reader, String matchString) throws IOException {
int bugMarkerIndex = line.indexOf(matchString);
if (bugMarkerIndex < 0) {
throw new IllegalArgumentException("Line must contain bug marker prefix");
}
List<String> result = new ArrayList<>();
String restOfLine = line.substring(bugMarkerIndex + matchString.length()).trim();
result.add(restOfLine);
line = reader.readLine().trim();
while (line.startsWith("//")) {
restOfLine = line.substring(2).trim();
result.add(restOfLine);
line = reader.readLine().trim();
}
return result;
}
private static class SimpleStringContains implements Predicate<String> {
private final String pattern;
SimpleStringContains(String pattern) {
this.pattern = pattern;
}
@Override
public boolean test(String input) {
return input.contains(pattern);
}
@Override
public String toString() {
return pattern;
}
}
private static class ClearableDiagnosticCollector<S> implements DiagnosticListener<S> {
private final List<Diagnostic<? extends S>> diagnostics = new ArrayList<>();
@Override
public void report(Diagnostic<? extends S> diagnostic) {
diagnostics.add(diagnostic);
}
public List<Diagnostic<? extends S>> getDiagnostics() {
return ImmutableList.copyOf(diagnostics);
}
public void clear() {
diagnostics.clear();
}
}
}
| 15,111
| 34.144186
| 100
|
java
|
error-prone
|
error-prone-master/test_helpers/src/main/java/com/google/errorprone/FileObjects.java
|
/*
* Copyright 2020 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.stream;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.io.ByteStreams;
import com.google.errorprone.annotations.MustBeClosed;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.net.URI;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import javax.tools.SimpleJavaFileObject;
/** Factories for in-memory {@link JavaFileObject}s, for testing. */
public final class FileObjects {
/** Loads resources of the provided class into {@link JavaFileObject}s. */
public static ImmutableList<JavaFileObject> forResources(Class<?> clazz, String... fileNames) {
return stream(fileNames)
.map(fileName -> forResource(clazz, fileName))
.collect(toImmutableList());
}
/** Loads a resource of the provided class into a {@link JavaFileObject}. */
public static JavaFileObject forResource(Class<?> clazz, String resourceName) {
URI uri =
URI.create(
"file:///" + clazz.getPackage().getName().replace('.', '/') + "/" + resourceName);
String content;
try (InputStream inputStream = findResource(clazz, resourceName)) {
content = new String(ByteStreams.toByteArray(inputStream), UTF_8);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return new SimpleJavaFileObject(uri, Kind.SOURCE) {
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
return content;
}
};
}
// TODO(b/176096448): the testdata/ fallback is a hack, fix affected tests and remove it
@MustBeClosed
private static InputStream findResource(Class<?> clazz, String name) {
InputStream is = clazz.getResourceAsStream(name);
if (is != null) {
return is;
}
is = clazz.getResourceAsStream("testdata/" + name);
if (is != null) {
return is;
}
throw new AssertionError("could not find resource: " + name + " for: " + clazz);
}
/** Creates a {@link JavaFileObject} with the given name and content. */
public static JavaFileObject forSourceLines(String path, String... lines) {
return new SimpleJavaFileObject(URI.create("file:///" + path), Kind.SOURCE) {
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return Joiner.on('\n').join(lines) + "\n";
}
};
}
private FileObjects() {}
}
| 3,258
| 35.211111
| 97
|
java
|
error-prone
|
error-prone-master/test_helpers/src/main/java/com/google/errorprone/CompilationTestHelper.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.errorprone.BugCheckerInfo.canonicalName;
import static com.google.errorprone.FileObjects.forResource;
import static com.google.errorprone.FileObjects.forSourceLines;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.asList;
import static java.util.Arrays.stream;
import static org.junit.Assert.fail;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.io.ByteStreams;
import com.google.errorprone.DiagnosticTestHelper.LookForCheckNameInDiagnostic;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.CheckReturnValue;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.scanner.ScannerSupplier;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.main.Main.Result;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import javax.annotation.Nullable;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
/** Helps test Error Prone bug checkers and compilations. */
@CheckReturnValue
public class CompilationTestHelper {
private static final ImmutableList<String> DEFAULT_ARGS =
ImmutableList.of(
"-encoding",
"UTF-8",
// print stack traces for completion failures
"-XDdev",
"-parameters",
"-XDcompilePolicy=simple",
// Don't limit errors/warnings for tests to the default of 100
"-Xmaxerrs",
"500",
"-Xmaxwarns",
"500");
private final DiagnosticTestHelper diagnosticHelper;
private final BaseErrorProneJavaCompiler compiler;
private final ByteArrayOutputStream outputStream;
private final Class<?> clazz;
private final List<JavaFileObject> sources = new ArrayList<>();
private ImmutableList<String> extraArgs = ImmutableList.of();
@Nullable private ImmutableList<Class<?>> overrideClasspath;
private boolean expectNoDiagnostics = false;
private Optional<Result> expectedResult = Optional.empty();
private LookForCheckNameInDiagnostic lookForCheckNameInDiagnostic =
LookForCheckNameInDiagnostic.YES;
private boolean run = false;
private CompilationTestHelper(ScannerSupplier scannerSupplier, String checkName, Class<?> clazz) {
this.clazz = clazz;
this.diagnosticHelper = new DiagnosticTestHelper(checkName);
this.outputStream = new ByteArrayOutputStream();
this.compiler = new BaseErrorProneJavaCompiler(JavacTool.create(), scannerSupplier);
}
/**
* Returns a new {@link CompilationTestHelper}.
*
* @param scannerSupplier the {@link ScannerSupplier} to test
* @param clazz the class to use to locate file resources
*/
public static CompilationTestHelper newInstance(ScannerSupplier scannerSupplier, Class<?> clazz) {
return new CompilationTestHelper(scannerSupplier, null, clazz);
}
/**
* Returns a new {@link CompilationTestHelper}.
*
* @param checker the {@link BugChecker} to test
* @param clazz the class to use to locate file resources
*/
public static CompilationTestHelper newInstance(
Class<? extends BugChecker> checker, Class<?> clazz) {
ScannerSupplier scannerSupplier = ScannerSupplier.fromBugCheckerClasses(checker);
String checkName =
canonicalName(checker.getSimpleName(), checker.getAnnotation(BugPattern.class));
return new CompilationTestHelper(scannerSupplier, checkName, clazz);
}
/**
* Pass -proc:none unless annotation processing is explicitly enabled, to avoid picking up
* annotation processors via service loading.
*/
// TODO(cushon): test compilations should be isolated so they can't pick things up from the
// ambient classpath.
static List<String> disableImplicitProcessing(List<String> args) {
if (args.contains("-processor") || args.contains("-processorpath")) {
return args;
}
return ImmutableList.<String>builder().addAll(args).add("-proc:none").build();
}
/**
* Creates a list of arguments to pass to the compiler. Uses DEFAULT_ARGS as the base and appends
* the overridden classpath, if provided, and any extraArgs that were provided.
*/
private static ImmutableList<String> buildArguments(
@Nullable List<Class<?>> overrideClasspath, List<String> extraArgs) {
ImmutableList.Builder<String> result = ImmutableList.<String>builder().addAll(DEFAULT_ARGS);
getOverrideClasspath(overrideClasspath)
.ifPresent((Path jar) -> result.add("-cp").add(jar.toString()));
return result.addAll(disableImplicitProcessing(extraArgs)).build();
}
private static Optional<Path> getOverrideClasspath(@Nullable List<Class<?>> overrideClasspath) {
if (overrideClasspath == null) {
return Optional.empty();
}
try {
Path tempJarFile = Files.createTempFile(/* prefix= */ null, /* suffix= */ ".jar");
try (OutputStream os = Files.newOutputStream(tempJarFile);
JarOutputStream jos = new JarOutputStream(os)) {
for (Class<?> clazz : overrideClasspath) {
String entryPath = clazz.getName().replace('.', '/') + ".class";
jos.putNextEntry(new JarEntry(entryPath));
try (InputStream is = clazz.getClassLoader().getResourceAsStream(entryPath)) {
ByteStreams.copy(is, jos);
}
}
}
return Optional.of(tempJarFile);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/**
* Adds a source file to the test compilation, from the string content of the file.
*
* <p>The diagnostics expected from compiling the file are inferred from the file contents. For
* each line of the test file that contains the bug marker pattern "// BUG: Diagnostic contains:
* foo", we expect to see a diagnostic on that line containing "foo". For each line of the test
* file that does <i>not</i> contain the bug marker pattern, we expect no diagnostic to be
* generated. You can also use "// BUG: Diagnostic matches: X" in tandem with {@code
* expectErrorMessage("X", "foo")} to allow you to programmatically construct the error message.
*
* @param path a path for the source file
* @param lines the content of the source file
*/
// TODO(eaftan): We could eliminate this path parameter and just infer the path from the
// package and class name
@CanIgnoreReturnValue
public CompilationTestHelper addSourceLines(String path, String... lines) {
this.sources.add(forSourceLines(path, lines));
return this;
}
/**
* Adds a source file to the test compilation, from an existing resource file.
*
* <p>See {@link #addSourceLines} for how expected diagnostics should be specified.
*
* <p>For most uses, {@link #addSourceLines} is preferred. Using separate source files to denote
* positive/negative examples tends to bloat individual tests. Prefer writing smaller tests using
* {@link #addSourceLines} which test a single behaviour in isolation.
*
* @param path the path to the source file
*/
@CanIgnoreReturnValue
public CompilationTestHelper addSourceFile(String path) {
this.sources.add(forResource(clazz, path));
return this;
}
/**
* Sets the classpath for the test compilation, overriding the default of using the runtime
* classpath of the test execution. This is useful to verify correct behavior when the classpath
* is incomplete.
*
* @param classes the class(es) to use as the classpath
*/
@CanIgnoreReturnValue
public CompilationTestHelper withClasspath(Class<?>... classes) {
this.overrideClasspath = ImmutableList.copyOf(classes);
return this;
}
@CanIgnoreReturnValue
public CompilationTestHelper addModules(String... modules) {
return setArgs(
stream(modules)
.map(m -> String.format("--add-exports=%s=ALL-UNNAMED", m))
.collect(toImmutableList()));
}
/**
* Sets custom command-line arguments for the compilation. These will be appended to the default
* compilation arguments.
*/
@CanIgnoreReturnValue
public CompilationTestHelper setArgs(String... args) {
return setArgs(asList(args));
}
/**
* Sets custom command-line arguments for the compilation. These will be appended to the default
* compilation arguments.
*/
@CanIgnoreReturnValue
public CompilationTestHelper setArgs(List<String> args) {
checkState(
extraArgs.isEmpty(),
"Extra args already set: old value: %s, new value: %s",
extraArgs,
args);
this.extraArgs = ImmutableList.copyOf(args);
return this;
}
/**
* Tells the compilation helper to expect that no diagnostics will be generated, even if the
* source file contains bug markers. Useful for testing that a check is actually disabled when the
* proper command-line argument is passed.
*/
@CanIgnoreReturnValue
public CompilationTestHelper expectNoDiagnostics() {
this.expectNoDiagnostics = true;
return this;
}
/**
* By default, the compilation helper will only inspect diagnostics generated by the check being
* tested. This behaviour can be disabled to test the interaction between Error Prone checks and
* javac diagnostics.
*/
@CanIgnoreReturnValue
public CompilationTestHelper matchAllDiagnostics() {
this.lookForCheckNameInDiagnostic = LookForCheckNameInDiagnostic.NO;
return this;
}
/**
* Tells the compilation helper to expect a specific result from the compilation, e.g. success or
* failure.
*/
@CanIgnoreReturnValue
public CompilationTestHelper expectResult(Result result) {
expectedResult = Optional.of(result);
return this;
}
/**
* Expects an error message matching {@code matcher} at the line below a comment matching the key.
* For example, given the source
*
* <pre>
* // BUG: Diagnostic matches: X
* a = b + c;
* </pre>
*
* ... you can use {@code expectErrorMessage("X", Predicates.containsPattern("Can't add b to
* c"));}
*
* <p>Error message keys that don't match any diagnostics will cause test to fail.
*/
@CanIgnoreReturnValue
public CompilationTestHelper expectErrorMessage(String key, Predicate<? super String> matcher) {
diagnosticHelper.expectErrorMessage(key, matcher);
return this;
}
/** Performs a compilation and checks that the diagnostics and result match the expectations. */
public void doTest() {
checkState(!sources.isEmpty(), "No source files to compile");
checkState(!run, "doTest should only be called once");
this.run = true;
Result result = compile();
for (Diagnostic<? extends JavaFileObject> diagnostic : diagnosticHelper.getDiagnostics()) {
if (diagnostic.getCode().contains("error.prone.crash")) {
fail(diagnostic.getMessage(Locale.ENGLISH));
}
}
if (expectNoDiagnostics) {
List<Diagnostic<? extends JavaFileObject>> diagnostics = diagnosticHelper.getDiagnostics();
assertWithMessage(
String.format(
"Expected no diagnostics produced, but found %d: %s",
diagnostics.size(), diagnostics))
.that(diagnostics.size())
.isEqualTo(0);
assertWithMessage(
String.format(
"Expected compilation result to be "
+ expectedResult.orElse(Result.OK)
+ ", but was %s. No diagnostics were emitted."
+ " OutputStream from Compiler follows.\n\n%s",
result,
outputStream))
.that(result)
.isEqualTo(expectedResult.orElse(Result.OK));
} else {
for (JavaFileObject source : sources) {
try {
diagnosticHelper.assertHasDiagnosticOnAllMatchingLines(
source, lookForCheckNameInDiagnostic);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
assertWithMessage("Unused error keys: " + diagnosticHelper.getUnusedLookupKeys())
.that(diagnosticHelper.getUnusedLookupKeys().isEmpty())
.isTrue();
}
expectedResult.ifPresent(
expected ->
assertWithMessage(
String.format(
"Expected compilation result %s, but was %s\n%s\n%s",
expected,
result,
Joiner.on('\n').join(diagnosticHelper.getDiagnostics()),
outputStream))
.that(result)
.isEqualTo(expected));
}
private Result compile() {
List<String> processedArgs = buildArguments(overrideClasspath, extraArgs);
return compiler
.getTask(
new PrintWriter(
new BufferedWriter(new OutputStreamWriter(outputStream, UTF_8)),
/* autoFlush= */ true),
FileManagers.testFileManager(),
diagnosticHelper.collector,
/* options= */ ImmutableList.copyOf(processedArgs),
/* classes= */ ImmutableList.of(),
sources)
.call()
? Result.OK
: Result.ERROR;
}
}
| 14,512
| 37.39418
| 100
|
java
|
error-prone
|
error-prone-master/docgen/src/test/java/com/google/errorprone/BugPatternFileGeneratorTest.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.io.CharStreams;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.gson.Gson;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class BugPatternFileGeneratorTest {
@Rule public TemporaryFolder tmpfolder = new TemporaryFolder();
private Path wikiDir;
private Path explanationDirBase;
@Before
public void setUp() throws Exception {
wikiDir = tmpfolder.newFolder("wiki").toPath();
explanationDirBase = tmpfolder.newFolder("explanations").toPath();
}
private static BugPatternInstance deadExceptionTestInfo() {
BugPatternInstance instance = new BugPatternInstance();
instance.className = "com.google.errorprone.bugpatterns.DeadException";
instance.name = "DeadException";
instance.summary = "Exception created but not thrown";
instance.explanation =
"The exception is created with new, but is not thrown, and the reference is lost.";
instance.altNames = new String[] {"ThrowableInstanceNeverThrown"};
instance.tags = new String[] {"LikelyError"};
instance.severity = SeverityLevel.ERROR;
instance.suppressionAnnotations = new String[] {"java.lang.SuppressWarnings.class"};
return instance;
}
private static final String BUGPATTERN_LINE;
static {
BugPatternInstance instance = deadExceptionTestInfo();
BUGPATTERN_LINE = new Gson().toJson(instance);
}
private static final String BUGPATTERN_LINE_SIDECAR;
static {
BugPatternInstance instance = deadExceptionTestInfo();
instance.explanation = "";
BUGPATTERN_LINE_SIDECAR = new Gson().toJson(instance);
}
// Assert that the generator produces the same output it did before.
// This is brittle, but you can open the golden file
// src/test/resources/com/google/errorprone/DeadException.md
// in the same Jekyll environment you use for prod, and verify it looks good.
@Test
public void regressionTest_frontmatter_pygments() throws Exception {
BugPatternFileGenerator generator =
new BugPatternFileGenerator(
wikiDir, explanationDirBase, true, null, input -> input.severity);
generator.processLine(BUGPATTERN_LINE);
String expected =
CharStreams.toString(
new InputStreamReader(
getClass().getResourceAsStream("testdata/DeadException_frontmatter_pygments.md"),
UTF_8));
String actual =
CharStreams.toString(Files.newBufferedReader(wikiDir.resolve("DeadException.md"), UTF_8));
assertThat(actual.trim()).isEqualTo(expected.trim());
}
@Test
public void regressionTest_nofrontmatter_gfm() throws Exception {
BugPatternFileGenerator generator =
new BugPatternFileGenerator(
wikiDir, explanationDirBase, false, null, input -> input.severity);
generator.processLine(BUGPATTERN_LINE);
String expected =
CharStreams.toString(
new InputStreamReader(
getClass().getResourceAsStream("testdata/DeadException_nofrontmatter_gfm.md"),
UTF_8));
String actual = new String(Files.readAllBytes(wikiDir.resolve("DeadException.md")), UTF_8);
assertThat(actual.trim()).isEqualTo(expected.trim());
}
@Test
public void regressionTest_sidecar() throws Exception {
BugPatternFileGenerator generator =
new BugPatternFileGenerator(
wikiDir, explanationDirBase, false, null, input -> input.severity);
Files.write(
explanationDirBase.resolve("DeadException.md"),
Arrays.asList(
"The exception is created with new, but is not thrown, and the reference is lost."),
UTF_8);
generator.processLine(BUGPATTERN_LINE_SIDECAR);
String expected =
CharStreams.toString(
new InputStreamReader(
getClass().getResourceAsStream("testdata/DeadException_nofrontmatter_gfm.md"),
UTF_8));
String actual = new String(Files.readAllBytes(wikiDir.resolve("DeadException.md")), UTF_8);
assertThat(actual.trim()).isEqualTo(expected.trim());
}
@Test
public void escapeAngleBracketsInSummary() throws Exception {
// Create a BugPattern with angle brackets in the summary
BugPatternInstance instance = new BugPatternInstance();
instance.className = "com.google.errorprone.bugpatterns.DontDoThis";
instance.name = "DontDoThis";
instance.summary = "Don't do this; do List<Foo> instead";
instance.explanation = "This is a bad idea, you want `List<Foo>` instead";
instance.altNames = new String[0];
instance.tags = new String[] {"LikelyError"};
instance.severity = SeverityLevel.ERROR;
instance.suppressionAnnotations = new String[] {"java.lang.SuppressWarnings.class"};
// Write markdown file
BugPatternFileGenerator generator =
new BugPatternFileGenerator(
wikiDir, explanationDirBase, false, null, input -> input.severity);
generator.processLine(new Gson().toJson(instance));
String expected =
CharStreams.toString(
new InputStreamReader(
getClass().getResourceAsStream("testdata/DontDoThis_nofrontmatter_gfm.md"), UTF_8));
String actual = new String(Files.readAllBytes(wikiDir.resolve("DontDoThis.md")), UTF_8);
assertThat(actual.trim()).isEqualTo(expected.trim());
}
}
| 6,316
| 38.48125
| 100
|
java
|
error-prone
|
error-prone-master/docgen/src/test/java/com/google/errorprone/BugPatternIndexWriterTest.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableSet;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.DocGenTool.Target;
import java.io.StringWriter;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class BugPatternIndexWriterTest {
@Test
public void dumpInternal() throws Exception {
StringWriter writer = new StringWriter();
BugPatternInstance pattern1 = new BugPatternInstance();
pattern1.severity = SeverityLevel.ERROR;
pattern1.name = "BugPatternA";
pattern1.summary = "Here's the \"interesting\" summary";
BugPatternInstance pattern2 = new BugPatternInstance();
pattern2.severity = SeverityLevel.ERROR;
pattern2.name = "BugPatternB";
pattern2.summary = "{summary2}";
BugPatternInstance pattern3 = new BugPatternInstance();
pattern3.severity = SeverityLevel.ERROR;
pattern3.name = "BugPatternC";
pattern3.summary = "mature";
new BugPatternIndexWriter()
.dump(
Arrays.asList(pattern3, pattern2, pattern1),
writer,
Target.INTERNAL,
ImmutableSet.of("BugPatternC"));
assertThat(writer.toString())
.isEqualTo(
"# Bug patterns\n\n"
+ "[TOC]\n\n"
+ "This list is auto-generated from our sources. Each bug pattern includes code\n"
+ "examples of both positive and negative cases; these examples are used in our\n"
+ "regression test suite.\n"
+ "\n"
+ "Patterns which are marked __Experimental__ will not be evaluated against your\n"
+ "code, unless you specifically configure Error Prone. The default checks are\n"
+ "marked __On by default__, and each release promotes some experimental checks\n"
+ "after we've vetted them against Google's codebase.\n"
+ "\n"
+ "## On by default : ERROR\n"
+ "\n"
+ "__[BugPatternC](bugpattern/BugPatternC.md)__ \\\n"
+ "mature\n"
+ "\n"
+ "## Experimental : ERROR\n"
+ "\n"
+ "__[BugPatternA](bugpattern/BugPatternA.md)__ \\\n"
+ "Here's the "interesting" summary\n"
+ "\n"
+ "__[BugPatternB](bugpattern/BugPatternB.md)__ \\\n"
+ "{summary2}\n"
+ "\n");
}
@Test
public void dumpExternal() throws Exception {
StringWriter writer = new StringWriter();
BugPatternInstance pattern1 = new BugPatternInstance();
pattern1.severity = SeverityLevel.ERROR;
pattern1.name = "BugPatternA";
pattern1.summary = "Here's the \"interesting\" summary";
BugPatternInstance pattern2 = new BugPatternInstance();
pattern2.severity = SeverityLevel.ERROR;
pattern2.name = "BugPatternB";
pattern2.summary = "{summary2}";
BugPatternInstance pattern3 = new BugPatternInstance();
pattern3.severity = SeverityLevel.ERROR;
pattern3.name = "BugPatternC";
pattern3.summary = "mature";
new BugPatternIndexWriter()
.dump(
Arrays.asList(pattern3, pattern2, pattern1),
writer,
Target.EXTERNAL,
ImmutableSet.of("BugPatternC"));
assertThat(writer.toString())
.isEqualTo(
"---\n"
+ "title: Bug Patterns\n"
+ "layout: bugpatterns\n"
+ "---\n\n\n"
+ "# Bug patterns\n"
+ "\n"
+ "This list is auto-generated from our sources. Each bug pattern includes code\n"
+ "examples of both positive and negative cases; these examples are used in our\n"
+ "regression test suite.\n"
+ "\n"
+ "Patterns which are marked __Experimental__ will not be evaluated against your\n"
+ "code, unless you specifically configure Error Prone. The default checks are\n"
+ "marked __On by default__, and each release promotes some experimental checks\n"
+ "after we've vetted them against Google's codebase.\n"
+ "\n"
+ "## On by default : ERROR\n"
+ "\n"
+ "__[BugPatternC](bugpattern/BugPatternC)__<br>\n"
+ "mature\n"
+ "\n"
+ "## Experimental : ERROR\n"
+ "\n"
+ "__[BugPatternA](bugpattern/BugPatternA)__<br>\n"
+ "Here's the "interesting" summary\n"
+ "\n"
+ "__[BugPatternB](bugpattern/BugPatternB)__<br>\n"
+ "{summary2}\n"
+ "\n");
}
}
| 5,557
| 37.867133
| 99
|
java
|
error-prone
|
error-prone-master/docgen/src/main/java/com/google/errorprone/BugPatternFileGenerator.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.LineProcessor;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.representer.Representer;
/**
* Reads each line of the bugpatterns.txt tab-delimited data file, and generates a GitHub Jekyll
* page for each one.
*
* @author alexeagle@google.com (Alex Eagle)
*/
class BugPatternFileGenerator implements LineProcessor<List<BugPatternInstance>> {
private final Path outputDir;
private final Path explanationDir;
private final List<BugPatternInstance> result;
private final Function<BugPatternInstance, SeverityLevel> severityRemapper;
/** Controls whether yaml front-matter is generated. */
private final boolean generateFrontMatter;
/** The base url for links to bugpatterns. */
@Nullable private final String baseUrl;
public BugPatternFileGenerator(
Path bugpatternDir,
Path explanationDir,
boolean generateFrontMatter,
String baseUrl,
Function<BugPatternInstance, SeverityLevel> severityRemapper) {
this.outputDir = bugpatternDir;
this.explanationDir = explanationDir;
this.severityRemapper = severityRemapper;
this.generateFrontMatter = generateFrontMatter;
this.baseUrl = baseUrl;
result = new ArrayList<>();
}
@Override
public boolean processLine(String line) throws IOException {
BugPatternInstance pattern = new Gson().fromJson(line, BugPatternInstance.class);
pattern.severity = severityRemapper.apply(pattern);
result.add(pattern);
// replace spaces in filename with underscores
Path checkPath = Paths.get(pattern.name.replace(' ', '_') + ".md");
try (Writer writer = Files.newBufferedWriter(outputDir.resolve(checkPath), UTF_8)) {
// load side-car explanation file, if it exists
Path sidecarExplanation = explanationDir.resolve(checkPath);
if (Files.exists(sidecarExplanation)) {
if (!pattern.explanation.isEmpty()) {
throw new AssertionError(
String.format(
"%s specifies an explanation via @BugPattern and side-car", pattern.name));
}
pattern.explanation = new String(Files.readAllBytes(sidecarExplanation), UTF_8).trim();
}
// Construct an appropriate page for this {@code BugPattern}. Include altNames if
// there are any, and explain the correct way to suppress.
ImmutableMap.Builder<String, Object> templateData =
ImmutableMap.<String, Object>builder()
.put("tags", Joiner.on(", ").join(pattern.tags))
.put("severity", pattern.severity)
.put("name", pattern.name)
.put("className", pattern.className)
.put("summary", pattern.summary.trim())
.put("altNames", Joiner.on(", ").join(pattern.altNames))
.put("explanation", pattern.explanation.trim());
if (baseUrl != null) {
templateData.put("baseUrl", baseUrl);
}
if (generateFrontMatter) {
ImmutableMap<String, String> frontmatterData =
ImmutableMap.<String, String>builder()
.put("title", pattern.name)
.put("summary", pattern.summary)
.put("layout", "bugpattern")
.put("tags", Joiner.on(", ").join(pattern.tags))
.put("severity", pattern.severity.toString())
.buildOrThrow();
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml =
new Yaml(
new SafeConstructor(new LoaderOptions()),
new Representer(new DumperOptions()),
options);
Writer yamlWriter = new StringWriter();
yamlWriter.write("---\n");
yaml.dump(frontmatterData, yamlWriter);
yamlWriter.write("---\n");
templateData.put("frontmatter", yamlWriter.toString());
}
if (pattern.documentSuppression) {
String suppressionString;
if (pattern.suppressionAnnotations.length == 0) {
suppressionString = "This check may not be suppressed.";
} else {
suppressionString =
pattern.suppressionAnnotations.length == 1
? "Suppress false positives by adding the suppression annotation %s to the "
+ "enclosing element."
: "Suppress false positives by adding one of these suppression annotations to "
+ "the enclosing element: %s";
suppressionString =
String.format(
suppressionString,
Arrays.stream(pattern.suppressionAnnotations)
.map((String anno) -> standardizeAnnotation(anno, pattern.name))
.collect(Collectors.joining(", ")));
}
templateData.put("suppression", suppressionString);
}
MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache = mf.compile("com/google/errorprone/resources/bugpattern.mustache");
mustache.execute(writer, templateData.buildOrThrow());
}
return true;
}
private String standardizeAnnotation(String fullAnnotationName, String patternName) {
String annotationName =
fullAnnotationName.endsWith(".class")
? fullAnnotationName.substring(0, fullAnnotationName.length() - ".class".length())
: fullAnnotationName;
if (annotationName.equals(SuppressWarnings.class.getName())) {
annotationName = SuppressWarnings.class.getSimpleName() + "(\"" + patternName + "\")";
}
return "`@" + annotationName + "`";
}
@Override
public List<BugPatternInstance> getResult() {
return result;
}
}
| 7,191
| 37.459893
| 97
|
java
|
error-prone
|
error-prone-master/docgen/src/main/java/com/google/errorprone/BugPatternIndexWriter.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.primitives.Booleans.trueFirst;
import static java.util.Comparator.comparing;
import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.SortedSetMultimap;
import com.google.common.collect.TreeMultimap;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.DocGenTool.Target;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
/**
* @author alexeagle@google.com (Alex Eagle)
*/
public class BugPatternIndexWriter {
@AutoValue
abstract static class IndexEntry {
abstract boolean onByDefault();
abstract SeverityLevel severity();
static IndexEntry create(boolean onByDefault, SeverityLevel severity) {
return new AutoValue_BugPatternIndexWriter_IndexEntry(onByDefault, severity);
}
String asCategoryHeader() {
return (onByDefault() ? "On by default" : "Experimental") + " : " + severity();
}
}
@AutoValue
abstract static class MiniDescription {
abstract String name();
abstract String summary();
static MiniDescription create(BugPatternInstance bugPattern) {
return new AutoValue_BugPatternIndexWriter_MiniDescription(
bugPattern.name, bugPattern.summary);
}
}
void dump(
Collection<BugPatternInstance> patterns, Writer w, Target target, Set<String> enabledChecks)
throws IOException {
// (Default, Severity) -> [Pattern...]
SortedSetMultimap<IndexEntry, MiniDescription> sorted =
TreeMultimap.create(
comparing(IndexEntry::onByDefault, trueFirst()).thenComparing(IndexEntry::severity),
Comparator.comparing(MiniDescription::name));
for (BugPatternInstance pattern : patterns) {
sorted.put(
IndexEntry.create(enabledChecks.contains(pattern.name), pattern.severity),
MiniDescription.create(pattern));
}
Map<String, Object> templateData = new HashMap<>();
ImmutableList<Map<String, Object>> bugpatternData =
Multimaps.asMap(sorted).entrySet().stream()
.map(
e ->
ImmutableMap.of(
"category", e.getKey().asCategoryHeader(), "checks", e.getValue()))
.collect(toImmutableList());
templateData.put("bugpatterns", bugpatternData);
if (target == Target.EXTERNAL) {
ImmutableMap<String, String> frontmatterData =
ImmutableMap.<String, String>builder()
.put("title", "Bug Patterns")
.put("layout", "bugpatterns")
.buildOrThrow();
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(options);
Writer yamlWriter = new StringWriter();
yamlWriter.write("---\n");
yaml.dump(frontmatterData, yamlWriter);
yamlWriter.write("---\n");
templateData.put("frontmatter", yamlWriter.toString());
MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache =
mf.compile("com/google/errorprone/resources/bugpatterns_external.mustache");
mustache.execute(w, templateData);
} else {
MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache =
mf.compile("com/google/errorprone/resources/bugpatterns_internal.mustache");
mustache.execute(w, templateData);
}
}
}
| 4,590
| 34.315385
| 98
|
java
|
error-prone
|
error-prone-master/docgen/src/main/java/com/google/errorprone/DocGenTool.java
|
/*
* Copyright 2015 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.io.Files.asCharSource;
import static com.google.errorprone.scanner.BuiltInCheckerSuppliers.ENABLED_ERRORS;
import static com.google.errorprone.scanner.BuiltInCheckerSuppliers.ENABLED_WARNINGS;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.beust.jcommander.IStringConverter;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.google.common.base.Ascii;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.StreamSupport;
/**
* Utility main which consumes the same tab-delimited text file and generates GitHub pages for the
* BugPatterns.
*/
public final class DocGenTool {
@Parameters(separators = "=")
static class Options {
@Parameter(names = "-bug_patterns", description = "Path to bugPatterns.txt", required = true)
private String bugPatterns;
@Parameter(
names = "-explanations",
description = "Path to side-car explanations",
required = true)
private String explanations;
@Parameter(names = "-docs_repository", description = "Path to docs repository", required = true)
private String docsRepository;
@Parameter(
names = "-target",
description = "Whether to target the internal or external site",
converter = TargetEnumConverter.class,
required = true)
private Target target;
@Parameter(
names = "-base_url",
description = "The base url for links to bugpatterns",
arity = 1)
private String baseUrl = null;
}
enum Target {
INTERNAL,
EXTERNAL
}
public static class TargetEnumConverter implements IStringConverter<Target> {
@Override
public Target convert(String arg) {
return Target.valueOf(Ascii.toUpperCase(arg));
}
}
public static void main(String[] args) throws IOException {
Options options = new Options();
new JCommander(options).parse(args);
Path bugPatterns = Paths.get(options.bugPatterns);
if (!Files.exists(bugPatterns)) {
usage("Cannot find bugPatterns file: " + options.bugPatterns);
}
Path explanationDir = Paths.get(options.explanations);
if (!Files.exists(explanationDir)) {
usage("Cannot find explanations dir: " + options.explanations);
}
Path wikiDir = Paths.get(options.docsRepository);
Files.createDirectories(wikiDir);
Path bugpatternDir = wikiDir.resolve("bugpattern");
if (!Files.exists(bugpatternDir)) {
Files.createDirectories(bugpatternDir);
}
Files.createDirectories(wikiDir.resolve("_data"));
BugPatternFileGenerator generator =
new BugPatternFileGenerator(
bugpatternDir,
explanationDir,
options.target == Target.EXTERNAL,
options.baseUrl,
input -> input.severity);
try (Writer w =
Files.newBufferedWriter(wikiDir.resolve("bugpatterns.md"), StandardCharsets.UTF_8)) {
List<BugPatternInstance> patterns =
asCharSource(bugPatterns.toFile(), UTF_8).readLines(generator);
new BugPatternIndexWriter().dump(patterns, w, options.target, enabledCheckNames());
}
}
private static ImmutableSet<String> enabledCheckNames() {
return StreamSupport.stream(
Iterables.concat(ENABLED_ERRORS, ENABLED_WARNINGS).spliterator(), false)
.map(BugCheckerInfo::canonicalName)
.collect(toImmutableSet());
}
private static void usage(String err) {
System.err.println(err);
System.exit(1);
}
private DocGenTool() {}
}
| 4,540
| 32.637037
| 100
|
java
|
error-prone
|
error-prone-master/type_annotations/src/main/java/com/google/errorprone/annotations/ImmutableTypeParameter.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.annotations;
import static java.lang.annotation.ElementType.TYPE_PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* The type parameter to which this annotation is applied should only be instantiated with immutable
* types.
*
* <p>For a definition of immutability and of the semantics enforced by Error Prone, see {@link
* Immutable}.
*/
@Documented
@Target(TYPE_PARAMETER)
@Retention(RUNTIME)
public @interface ImmutableTypeParameter {}
| 1,225
| 33.055556
| 100
|
java
|
error-prone
|
error-prone-master/annotation/src/test/java/com/google/errorprone/BugPatternValidatorTest.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import com.google.errorprone.BugPattern.LinkType;
import com.google.errorprone.BugPattern.SeverityLevel;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author eaftan@google.com (Eddie Aftandilian)
*/
@RunWith(JUnit4.class)
public class BugPatternValidatorTest {
private @interface CustomSuppressionAnnotation {}
private @interface CustomSuppressionAnnotation2 {}
@Test
public void basicBugPattern() throws Exception {
@BugPattern(
name = "BasicBugPattern",
summary = "Simplest possible BugPattern",
explanation = "Simplest possible BugPattern ",
severity = SeverityLevel.ERROR)
final class BugPatternTestClass {}
BugPattern annotation = BugPatternTestClass.class.getAnnotation(BugPattern.class);
BugPatternValidator.validate(annotation);
}
@Test
public void linkTypeNoneAndNoLink() throws Exception {
@BugPattern(
name = "LinkTypeNoneAndNoLink",
summary = "linkType none and no link",
explanation = "linkType none and no link",
severity = SeverityLevel.ERROR,
linkType = LinkType.NONE)
final class BugPatternTestClass {}
BugPattern annotation = BugPatternTestClass.class.getAnnotation(BugPattern.class);
BugPatternValidator.validate(annotation);
}
@Test
public void linkTypeNoneButIncludesLink() {
@BugPattern(
name = "LinkTypeNoneButIncludesLink",
summary = "linkType none but includes link",
explanation = "linkType none but includes link",
severity = SeverityLevel.ERROR,
linkType = LinkType.NONE,
link = "http://foo")
final class BugPatternTestClass {}
BugPattern annotation = BugPatternTestClass.class.getAnnotation(BugPattern.class);
assertThrows(ValidationException.class, () -> BugPatternValidator.validate(annotation));
}
@Test
public void linkTypeCustomAndIncludesLink() throws Exception {
@BugPattern(
name = "LinkTypeCustomAndIncludesLink",
summary = "linkType custom and includes link",
explanation = "linkType custom and includes link",
severity = SeverityLevel.ERROR,
linkType = LinkType.CUSTOM,
link = "http://foo")
final class BugPatternTestClass {}
BugPattern annotation = BugPatternTestClass.class.getAnnotation(BugPattern.class);
BugPatternValidator.validate(annotation);
}
@Test
public void linkTypeCustomButNoLink() {
@BugPattern(
name = "LinkTypeCustomButNoLink",
summary = "linkType custom but no link",
explanation = "linkType custom but no link",
severity = SeverityLevel.ERROR,
linkType = LinkType.CUSTOM)
final class BugPatternTestClass {}
BugPattern annotation = BugPatternTestClass.class.getAnnotation(BugPattern.class);
assertThrows(ValidationException.class, () -> BugPatternValidator.validate(annotation));
}
@Test
public void unsuppressible() throws Exception {
@BugPattern(
name = "Unsuppressible",
summary = "An unsuppressible BugPattern",
explanation = "An unsuppressible BugPattern",
severity = SeverityLevel.ERROR,
suppressionAnnotations = {},
disableable = false)
final class BugPatternTestClass {}
BugPattern annotation = BugPatternTestClass.class.getAnnotation(BugPattern.class);
BugPatternValidator.validate(annotation);
}
@Test
public void customSuppressionAnnotation() throws Exception {
@BugPattern(
name = "customSuppressionAnnotation",
summary = "Uses a custom suppression annotation",
explanation = "Uses a custom suppression annotation",
severity = SeverityLevel.ERROR,
suppressionAnnotations = CustomSuppressionAnnotation.class)
final class BugPatternTestClass {}
BugPattern annotation = BugPatternTestClass.class.getAnnotation(BugPattern.class);
BugPatternValidator.validate(annotation);
}
@Test
public void multipleCustomSuppressionAnnotations() throws Exception {
@BugPattern(
name = "customSuppressionAnnotation",
summary = "Uses multiple custom suppression annotations",
explanation = "Uses multiple custom suppression annotations",
severity = SeverityLevel.ERROR,
suppressionAnnotations = {
CustomSuppressionAnnotation.class,
CustomSuppressionAnnotation2.class
})
final class BugPatternTestClass {}
BugPattern annotation = BugPatternTestClass.class.getAnnotation(BugPattern.class);
BugPatternValidator.validate(annotation);
}
@Test
public void suppressionAnnotationsIncludesSuppressWarnings() throws Exception {
@BugPattern(
name = "customSuppressionAnnotationButSuppressWarnings",
summary = "Specifies multiple custom suppression annotations including @SuppressWarnings",
explanation =
"Specifies multiple custom suppression annotations including @SuppressWarnings",
severity = SeverityLevel.ERROR,
suppressionAnnotations = {CustomSuppressionAnnotation.class, SuppressWarnings.class})
final class BugPatternTestClass {}
BugPattern annotation = BugPatternTestClass.class.getAnnotation(BugPattern.class);
BugPatternValidator.validate(annotation);
}
@Test
public void spacesInNameNotAllowed() {
@BugPattern(
name = "name with spaces",
summary = "Has a name with spaces",
severity = SeverityLevel.ERROR)
final class BugPatternTestClass {}
BugPattern annotation = BugPatternTestClass.class.getAnnotation(BugPattern.class);
ValidationException e =
assertThrows(ValidationException.class, () -> BugPatternValidator.validate(annotation));
assertThat(e).hasMessageThat().contains("Name must not contain whitespace");
}
}
| 6,563
| 34.673913
| 98
|
java
|
error-prone
|
error-prone-master/annotation/src/main/java/com/google/errorprone/BugPatternValidator.java
|
/*
* Copyright 2013 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import com.google.common.base.CharMatcher;
/**
* Validates an {@code @BugPattern} annotation for wellformedness.
*
* @author eaftan@google.com (Eddie Aftandilian)
*/
public final class BugPatternValidator {
public static void validate(BugPattern pattern) throws ValidationException {
if (pattern == null) {
throw new ValidationException("No @BugPattern provided");
}
// name must not contain spaces
if (CharMatcher.whitespace().matchesAnyOf(pattern.name())) {
throw new ValidationException("Name must not contain whitespace: " + pattern.name());
}
// linkType must be consistent with link element.
switch (pattern.linkType()) {
case CUSTOM:
if (pattern.link().isEmpty()) {
throw new ValidationException("Expected a custom link but none was provided");
}
break;
case AUTOGENERATED:
case NONE:
if (!pattern.link().isEmpty()) {
throw new ValidationException("Expected no custom link but found: " + pattern.link());
}
break;
}
}
private BugPatternValidator() {}
}
| 1,746
| 30.196429
| 96
|
java
|
error-prone
|
error-prone-master/annotation/src/main/java/com/google/errorprone/BugPattern.java
|
/*
* Copyright 2011 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
/**
* Describes a bug pattern detected by error-prone. Used to generate compiler error messages, for
* {@code @}SuppressWarnings, and to generate the documentation that we host on our web site.
*
* @author eaftan@google.com (Eddie Aftandilian)
*/
@Retention(RUNTIME)
public @interface BugPattern {
/** A collection of standardized tags that can be applied to BugPatterns. */
final class StandardTags {
private StandardTags() {}
/**
* This check, for reasons of backwards compatibility or difficulty in cleaning up, should be
* considered very likely to represent a real error in the vast majority ({@code >99.9%}) of
* cases, but couldn't otherwise be turned on as an ERROR.
*
* <p>Systems trying to determine the set of likely errors from a collection of BugPatterns
* should act as if any BugPattern with {@link #severity()} of {@link SeverityLevel#ERROR} also
* has this tag.
*/
public static final String LIKELY_ERROR = "LikelyError";
/**
* This check detects a coding pattern that is valid within the Java language and doesn't
* represent a runtime defect, but is otherwise discouraged for reasons of consistency within a
* project or ease of understanding by other programmers.
*
* <p>Checks using this tag should limit their replacements to those that don't change the
* behavior of the code (for example: adding clarifying parentheses, reordering modifiers in a
* single declaration, removing implicit modifiers like {@code public} for members in an {@code
* interface}).
*/
public static final String STYLE = "Style";
/**
* This check detects a potential performance issue, where an easily-identifiable replacement
* for the code being made will always result in a net positive performance improvement.
*/
public static final String PERFORMANCE = "Performance";
/**
* This check detects code that may technically be working within a limited domain, but is
* fragile, or violates generally-accepted assumptions of behavior.
*
* <p>Examples: DefaultCharset, where code implicitly uses the JVM default charset, will work in
* circumstances where data being fed to the system happens to be compatible with the Charset,
* but breaks down if fed data outside.
*/
public static final String FRAGILE_CODE = "FragileCode";
/**
* This check points out potential issues when operating in a concurrent context
*
* <p>The code may work fine when accessed by 1 thread at a time, but may have some unintended
* behavior when running in multiple threads.
*/
public static final String CONCURRENCY = "Concurrency";
/**
* This check points out a coding pattern that, while functional, has an easier-to-read or
* faster alternative.
*/
public static final String SIMPLIFICATION = "Simplification";
/** This check performs a refactoring, for example migrating to a new version of an API. */
public static final String REFACTORING = "Refactoring";
}
/**
* A unique identifier for this bug, used for @SuppressWarnings and in the compiler error message.
*
* <p>If this is not specified (or specified as an empty string), the class name of the check will
* be used instead.
*/
String name() default "";
/** Alternate identifiers for this bug, which may also be used in @SuppressWarnings. */
String[] altNames() default {};
/** The type of link to generate in the compiler error message. */
LinkType linkType() default LinkType.AUTOGENERATED;
/** The link URL to use if linkType() is LinkType.CUSTOM. */
String link() default "";
/** The type of link to generate in the compiler error message. */
enum LinkType {
/** Link to autogenerated documentation, hosted on the error-prone web site. */
AUTOGENERATED,
/** Custom string. */
CUSTOM,
/** No link should be displayed. */
NONE
}
/**
* A list of Stringly-typed tags to apply to this check. These tags can be consumed by tools
* aggregating Error Prone checks (for example: a git pre-commit hook could clean up Java source
* by finding any checks tagged "Style", run an Error Prone compile over the code with those
* checks enabled, collect the fixes suggested and apply them).
*
* <p>To allow for sharing of tags across systems, a number of standard tags are available as
* static constants in {@link StandardTags}. It is strongly encouraged to extract any custom tags
* used in annotation property to constants that are shared by your codebase.
*/
String[] tags() default {};
/**
* A short summary of the problem that this checker detects. Used for the default compiler error
* message and for the short description in the generated docs. Should not end with a period, to
* match javac warning/error style.
*
* <p>Markdown syntax is not allowed for this element.
*/
String summary();
/**
* A longer explanation of the problem that this checker detects. Used as the main content in the
* generated documentation for this checker.
*
* <p>Markdown syntax is allowed for this element.
*/
String explanation() default "";
SeverityLevel severity();
/** The severity of the diagnostic. */
enum SeverityLevel {
ERROR,
WARNING,
/** Note that this level generally disables the bug checker. */
SUGGESTION,
}
/** True if the check can be disabled using command-line flags. */
boolean disableable() default true;
/**
* A set of annotation types that can be used to suppress the check.
*
* <p>Includes only {@link SuppressWarnings} by default.
*
* <p>To make a check unsuppressible, set {@code suppressionAnnotations} to empty. Note that
* unsuppressible checks may still be disabled using command line flags (see {@link
* #disableable}).
*/
Class<? extends Annotation>[] suppressionAnnotations() default SuppressWarnings.class;
/**
* Generate an explanation of how to suppress the check.
*
* <p>This should only be disabled if the check has a non-standard suppression mechanism that
* requires additional explanation. For example, {@link SuppressWarnings} cannot be applied to
* packages, so checks that operate at the package level need special treatment.
*/
boolean documentSuppression() default true;
/**
* @deprecated this is a no-op that will be removed in the future
*/
@Deprecated
boolean generateExamplesFromTestCases() default true;
}
| 7,340
| 37.84127
| 100
|
java
|
error-prone
|
error-prone-master/annotation/src/main/java/com/google/errorprone/ValidationException.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;
/**
* An exception that indicates that BugPattern validation failed.
*
* @author eaftan@google.com (Eddie Aftandilian)
*/
public class ValidationException extends Exception {
public ValidationException(String message) {
super(message);
}
}
| 893
| 29.827586
| 75
|
java
|
error-prone
|
error-prone-master/refaster/src/main/java/com/google/errorprone/refaster/RefasterRuleCompilerAnalyzer.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.refaster;
import com.google.errorprone.CodeTransformer;
import com.google.errorprone.CompositeCodeTransformer;
import com.sun.source.tree.ClassTree;
import com.sun.source.util.TaskEvent;
import com.sun.source.util.TaskEvent.Kind;
import com.sun.source.util.TaskListener;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.api.JavacTrees;
import com.sun.tools.javac.main.JavaCompiler;
import com.sun.tools.javac.util.Context;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/**
* TaskListener that receives compilation of a Refaster rule class and outputs a serialized analyzer
* to the specified path.
*/
public class RefasterRuleCompilerAnalyzer implements TaskListener {
private final Context context;
private final Path destinationPath;
RefasterRuleCompilerAnalyzer(Context context, Path destinationPath) {
this.context = context;
this.destinationPath = destinationPath;
}
@Override
public void finished(TaskEvent taskEvent) {
if (taskEvent.getKind() != Kind.ANALYZE) {
return;
}
if (JavaCompiler.instance(context).errorCount() > 0) {
return;
}
ClassTree tree = JavacTrees.instance(context).getTree(taskEvent.getTypeElement());
if (tree == null) {
return;
}
List<CodeTransformer> rules = new ArrayList<>();
new TreeScanner<Void, Context>() {
@Override
public Void visitClass(ClassTree node, Context context) {
rules.addAll(RefasterRuleBuilderScanner.extractRules(node, context));
return super.visitClass(node, context);
}
}.scan(tree, context);
if (rules.isEmpty()) {
throw new IllegalArgumentException("Did not find any Refaster templates");
}
try (ObjectOutputStream output =
new ObjectOutputStream(Files.newOutputStream(destinationPath))) {
output.writeObject(CompositeCodeTransformer.compose(rules));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| 2,704
| 33.679487
| 100
|
java
|
error-prone
|
error-prone-master/refaster/src/main/java/com/google/errorprone/refaster/RefasterRuleCompiler.java
|
/*
* Copyright 2016 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.errorprone.refaster;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.auto.service.AutoService;
import com.sun.source.util.JavacTask;
import com.sun.source.util.Plugin;
import com.sun.tools.javac.api.BasicJavacTask;
import java.nio.file.FileSystems;
import java.util.Arrays;
import java.util.Iterator;
/**
* A javac plugin that compiles Refaster rules to a {@code .analyzer} file.
*
* @author lowasser@google.com
*/
@AutoService(Plugin.class)
public class RefasterRuleCompiler implements Plugin {
@Override
public String getName() {
return "RefasterRuleCompiler";
}
@Override
public void init(JavacTask javacTask, String... args) {
Iterator<String> itr = Arrays.asList(args).iterator();
String path = null;
while (itr.hasNext()) {
if (itr.next().equals("--out")) {
path = itr.next();
break;
}
}
checkArgument(path != null, "No --out specified");
javacTask.addTaskListener(
new RefasterRuleCompilerAnalyzer(
((BasicJavacTask) javacTask).getContext(), FileSystems.getDefault().getPath(path)));
}
}
| 1,746
| 30.196429
| 100
|
java
|
error-prone
|
error-prone-master/check_api/src/test/java/com/google/errorprone/ErrorProneOptionsTest.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.errorprone.ErrorProneOptions.Severity;
import com.google.errorprone.apply.ImportOrganizer;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for {@code ErrorProneOptions}.
*
* @author eaftan@google.com (Eddie Aftandilian)
*/
@RunWith(JUnit4.class)
public class ErrorProneOptionsTest {
@Test
public void nonErrorProneFlagsPlacedInRemainingArgs() {
String[] args = {"-nonErrorProneFlag", "value"};
ErrorProneOptions options = ErrorProneOptions.processArgs(args);
assertThat(options.getRemainingArgs()).isEqualTo(args);
}
@Test
public void malformedOptionThrowsProperException() {
List<String> badArgs =
Arrays.asList(
"-Xep:Foo:WARN:jfkdlsdf", // too many parts
"-Xep:", // no check name
"-Xep:Foo:FJDKFJSD"); // nonexistent severity level
badArgs.forEach(
arg -> {
InvalidCommandLineOptionException expected =
assertThrows(
InvalidCommandLineOptionException.class,
() -> ErrorProneOptions.processArgs(Arrays.asList(arg)));
assertThat(expected).hasMessageThat().contains("invalid flag");
});
}
@Test
public void handlesErrorProneSeverityFlags() {
String[] args1 = {"-Xep:Check1"};
ErrorProneOptions options = ErrorProneOptions.processArgs(args1);
ImmutableMap<String, Severity> expectedSeverityMap =
ImmutableMap.of("Check1", Severity.DEFAULT);
assertThat(options.getSeverityMap()).isEqualTo(expectedSeverityMap);
String[] args2 = {"-Xep:Check1", "-Xep:Check2:OFF", "-Xep:Check3:WARN"};
options = ErrorProneOptions.processArgs(args2);
expectedSeverityMap =
ImmutableMap.<String, Severity>builder()
.put("Check1", Severity.DEFAULT)
.put("Check2", Severity.OFF)
.put("Check3", Severity.WARN)
.buildOrThrow();
assertThat(options.getSeverityMap()).isEqualTo(expectedSeverityMap);
}
@Test
public void handlesErrorProneCustomFlags() {
String[] args = {"-XepOpt:Flag1", "-XepOpt:Flag2=Value2", "-XepOpt:Flag3=a,b,c"};
ErrorProneOptions options = ErrorProneOptions.processArgs(args);
ImmutableMap<String, String> expectedFlagsMap =
ImmutableMap.<String, String>builder()
.put("Flag1", "true")
.put("Flag2", "Value2")
.put("Flag3", "a,b,c")
.buildOrThrow();
assertThat(options.getFlags().getFlagsMap()).isEqualTo(expectedFlagsMap);
}
@Test
public void combineErrorProneFlagsWithNonErrorProneFlags() {
String[] args = {
"-classpath",
"/this/is/classpath",
"-verbose",
"-Xep:Check1:WARN",
"-XepOpt:Check1:Flag1=Value1",
"-Xep:Check2:ERROR"
};
ErrorProneOptions options = ErrorProneOptions.processArgs(args);
String[] expectedRemainingArgs = {"-classpath", "/this/is/classpath", "-verbose"};
assertThat(options.getRemainingArgs()).isEqualTo(expectedRemainingArgs);
ImmutableMap<String, Severity> expectedSeverityMap =
ImmutableMap.<String, Severity>builder()
.put("Check1", Severity.WARN)
.put("Check2", Severity.ERROR)
.buildOrThrow();
assertThat(options.getSeverityMap()).isEqualTo(expectedSeverityMap);
ImmutableMap<String, String> expectedFlagsMap = ImmutableMap.of("Check1:Flag1", "Value1");
assertThat(options.getFlags().getFlagsMap()).containsExactlyEntriesIn(expectedFlagsMap);
}
@Test
public void lastSeverityFlagWins() {
String[] args = {"-Xep:Check1:ERROR", "-Xep:Check1:OFF"};
ErrorProneOptions options = ErrorProneOptions.processArgs(args);
ImmutableMap<String, Severity> expectedSeverityMap = ImmutableMap.of("Check1", Severity.OFF);
assertThat(options.getSeverityMap()).isEqualTo(expectedSeverityMap);
}
@Test
public void lastCustomFlagWins() {
String[] args = {"-XepOpt:Flag1=First", "-XepOpt:Flag1=Second"};
ErrorProneOptions options = ErrorProneOptions.processArgs(args);
ImmutableMap<String, String> expectedFlagsMap = ImmutableMap.of("Flag1", "Second");
assertThat(options.getFlags().getFlagsMap()).containsExactlyEntriesIn(expectedFlagsMap);
}
@Test
public void recognizesAllChecksAsWarnings() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepAllDisabledChecksAsWarnings"});
assertThat(options.isEnableAllChecksAsWarnings()).isTrue();
}
@Test
public void recognizesDemoteErrorToWarning() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepAllErrorsAsWarnings"});
assertThat(options.isDropErrorsToWarnings()).isTrue();
}
@Test
public void recognizesAllSuggestionsAsWarnings() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepAllSuggestionsAsWarnings"});
assertThat(options.isSuggestionsAsWarnings()).isTrue();
}
@Test
public void recognizesDisableAllChecks() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepDisableAllChecks"});
assertThat(options.isDisableAllChecks()).isTrue();
}
@Test
public void recognizesCompilingTestOnlyCode() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepCompilingTestOnlyCode"});
assertThat(options.isTestOnlyTarget()).isTrue();
}
@Test
public void recognizesCompilingPubliclyVisibleCode() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepCompilingPubliclyVisibleCode"});
assertThat(options.isPubliclyVisibleTarget()).isTrue();
}
@Test
public void recognizesDisableAllWarnings() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepDisableAllWarnings"});
assertThat(options.isDisableAllWarnings()).isTrue();
}
@Test
public void recognizesVisitSuppressedCode() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepIgnoreSuppressionAnnotations"});
assertThat(options.isIgnoreSuppressionAnnotations()).isTrue();
}
@Test
public void recognizesExcludedPaths() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(
new String[] {"-XepExcludedPaths:(.*/)?(build/generated|other_output)/.*\\.java"});
Pattern excludedPattern = options.getExcludedPattern();
assertThat(excludedPattern).isNotNull();
assertThat(excludedPattern.matcher("fizz/build/generated/Gen.java").matches()).isTrue();
assertThat(excludedPattern.matcher("fizz/bazz/generated/Gen.java").matches()).isFalse();
assertThat(excludedPattern.matcher("fizz/abuild/generated/Gen.java").matches()).isFalse();
assertThat(excludedPattern.matcher("other_output/Gen.java").matches()).isTrue();
assertThat(excludedPattern.matcher("foo/other_output/subdir/Gen.java").matches()).isTrue();
assertThat(excludedPattern.matcher("foo/other_output/subdir/Gen.cpp").matches()).isFalse();
}
@Test
public void recognizesPatch() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(
new String[] {"-XepPatchLocation:IN_PLACE", "-XepPatchChecks:FooBar,MissingOverride"});
assertThat(options.patchingOptions().doRefactor()).isTrue();
assertThat(options.patchingOptions().inPlace()).isTrue();
assertThat(options.patchingOptions().namedCheckers())
.containsExactly("MissingOverride", "FooBar");
assertThat(options.patchingOptions().customRefactorer()).isAbsent();
options =
ErrorProneOptions.processArgs(
new String[] {
"-XepPatchLocation:/some/base/dir", "-XepPatchChecks:FooBar,MissingOverride"
});
assertThat(options.patchingOptions().doRefactor()).isTrue();
assertThat(options.patchingOptions().inPlace()).isFalse();
assertThat(options.patchingOptions().baseDirectory()).isEqualTo("/some/base/dir");
assertThat(options.patchingOptions().namedCheckers())
.containsExactly("MissingOverride", "FooBar");
assertThat(options.patchingOptions().customRefactorer()).isAbsent();
options = ErrorProneOptions.processArgs(new String[] {});
assertThat(options.patchingOptions().doRefactor()).isFalse();
}
@Test
public void throwsExceptionWithBadPatchArgs() {
assertThrows(
InvalidCommandLineOptionException.class,
() -> ErrorProneOptions.processArgs(new String[] {"-XepPatchLocation:IN_PLACE"}));
assertThrows(
InvalidCommandLineOptionException.class,
() ->
ErrorProneOptions.processArgs(new String[] {"-XepPatchChecks:FooBar,MissingOverride"}));
}
@Test
public void recognizesRefaster() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(
new String[] {"-XepPatchChecks:refaster:/foo/bar", "-XepPatchLocation:IN_PLACE"});
assertThat(options.patchingOptions().doRefactor()).isTrue();
assertThat(options.patchingOptions().inPlace()).isTrue();
assertThat(options.patchingOptions().customRefactorer()).isPresent();
}
@Test
public void importOrder_staticFirst() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepPatchImportOrder:static-first"});
assertThat(options.patchingOptions().importOrganizer())
.isSameInstanceAs(ImportOrganizer.STATIC_FIRST_ORGANIZER);
}
@Test
public void importOrder_staticLast() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepPatchImportOrder:static-last"});
assertThat(options.patchingOptions().importOrganizer())
.isSameInstanceAs(ImportOrganizer.STATIC_LAST_ORGANIZER);
}
@Test
public void importOrder_androidStaticFirst() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepPatchImportOrder:android-static-first"});
assertThat(options.patchingOptions().importOrganizer())
.isSameInstanceAs(ImportOrganizer.ANDROID_STATIC_FIRST_ORGANIZER);
}
@Test
public void importOrder_androidStaticLast() {
ErrorProneOptions options =
ErrorProneOptions.processArgs(new String[] {"-XepPatchImportOrder:android-static-last"});
assertThat(options.patchingOptions().importOrganizer())
.isSameInstanceAs(ImportOrganizer.ANDROID_STATIC_LAST_ORGANIZER);
}
@Test
public void noSuchXepFlag() {
assertThrows(
InvalidCommandLineOptionException.class,
() -> ErrorProneOptions.processArgs(new String[] {"-XepNoSuchFlag"}));
}
@Test
public void severityOrder() {
for (Collection<String> permutation :
Collections2.permutations(ImmutableList.of("A", "B", "C"))) {
ImmutableMap<String, Severity> severityMap =
permutation.stream().collect(toImmutableMap(x -> x, x -> Severity.ERROR));
ErrorProneOptions options =
ErrorProneOptions.processArgs(
permutation.stream()
.map(x -> String.format("-Xep:%s:ERROR", x))
.collect(toImmutableList()));
assertThat(options.getSeverityMap()).containsExactlyEntriesIn(severityMap).inOrder();
}
}
}
| 12,309
| 38.203822
| 100
|
java
|
error-prone
|
error-prone-master/check_api/src/test/java/com/google/errorprone/ErrorProneFlagsTest.java
|
/*
* Copyright 2017 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import static org.junit.Assert.assertThrows;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests of internal methods and flag parsing for new-style Error Prone command-line flags. */
@RunWith(JUnit4.class)
public final class ErrorProneFlagsTest {
@Test
public void parseAndGetStringValue() {
ErrorProneFlags flags =
ErrorProneFlags.builder()
.parseFlag("-XepOpt:SomeArg=SomeValue")
.parseFlag("-XepOpt:Other:Arg:More:Parts=Long")
.parseFlag("-XepOpt:EmptyArg=")
.build();
assertThat(flags.get("SomeArg")).hasValue("SomeValue");
assertThat(flags.get("Other:Arg:More:Parts")).hasValue("Long");
assertThat(flags.get("EmptyArg")).hasValue("");
assertThat(flags.get("absent")).isEmpty();
}
@Test
public void parseAndGetBoolean() {
ErrorProneFlags flags =
ErrorProneFlags.builder()
// Boolean parsing should ignore case.
.parseFlag("-XepOpt:Arg1=tRuE")
.parseFlag("-XepOpt:Arg2=FaLsE")
.parseFlag("-XepOpt:Arg3=yes")
.build();
assertThat(flags.getBoolean("Arg1")).hasValue(true);
assertThat(flags.getBoolean("Arg2")).hasValue(false);
assertThrows(IllegalArgumentException.class, () -> flags.getBoolean("Arg3"));
assertThat(flags.getBoolean("absent")).isEmpty();
}
@Test
public void parseAndGetImplicitTrue() {
ErrorProneFlags flags = ErrorProneFlags.builder().parseFlag("-XepOpt:SomeArg").build();
assertThat(flags.getBoolean("SomeArg")).hasValue(true);
}
@Test
public void parseAndGetInteger() {
ErrorProneFlags flags =
ErrorProneFlags.builder()
.parseFlag("-XepOpt:Arg1=10")
.parseFlag("-XepOpt:Arg2=20.6")
.parseFlag("-XepOpt:Arg3=thirty")
.build();
assertThat(flags.getInteger("Arg1")).hasValue(10);
assertThrows(NumberFormatException.class, () -> flags.getInteger("Arg2"));
assertThrows(NumberFormatException.class, () -> flags.getInteger("Arg3"));
assertThat(flags.getInteger("absent")).isEmpty();
}
@Test
public void parseAndGetList() {
ErrorProneFlags flags =
ErrorProneFlags.builder()
.parseFlag("-XepOpt:ArgA=1,2,3")
.parseFlag("-XepOpt:ArgB=4,")
.parseFlag("-XepOpt:ArgC=5,,,6")
.parseFlag("-XepOpt:ArgD=7")
.parseFlag("-XepOpt:ArgE=")
.build();
assertThat(flags.getList("ArgA")).hasValue(ImmutableList.of("1", "2", "3"));
assertThat(flags.getList("ArgB")).hasValue(ImmutableList.of("4", ""));
assertThat(flags.getList("ArgC")).hasValue(ImmutableList.of("5", "", "", "6"));
assertThat(flags.getList("ArgD")).hasValue(ImmutableList.of("7"));
assertThat(flags.getList("ArgE")).hasValue(ImmutableList.of(""));
assertThat(flags.getList("absent")).isEmpty();
}
@Test
public void plus_secondShouldOverwriteFirst() {
ErrorProneFlags flags1 =
ErrorProneFlags.builder().putFlag("a", "FIRST_A").putFlag("b", "FIRST_B").build();
ErrorProneFlags flags2 =
ErrorProneFlags.builder().putFlag("b", "b2").putFlag("c", "c2").build();
ImmutableMap<String, String> expectedCombinedMap =
ImmutableMap.<String, String>builder()
.put("a", "FIRST_A")
.put("b", "b2")
.put("c", "c2")
.buildOrThrow();
ImmutableMap<String, String> actualCombinedMap = flags1.plus(flags2).getFlagsMap();
assertThat(actualCombinedMap).containsExactlyEntriesIn(expectedCombinedMap);
}
@Test
public void empty() {
ErrorProneFlags emptyFlags = ErrorProneFlags.empty();
assertThat(emptyFlags.isEmpty()).isTrue();
assertThat(emptyFlags.getFlagsMap().isEmpty()).isTrue();
ErrorProneFlags nonEmptyFlags = ErrorProneFlags.fromMap(ImmutableMap.of("a", "b"));
assertThat(nonEmptyFlags.isEmpty()).isFalse();
assertThat(nonEmptyFlags.getFlagsMap().isEmpty()).isFalse();
}
/** An enum for testing. */
public enum Colour {
RED,
YELLOW,
GREEN
}
@Test
public void enumFlags() {
ErrorProneFlags flags =
ErrorProneFlags.builder()
.parseFlag("-XepOpt:Colour=RED")
.parseFlag("-XepOpt:Colours=YELLOW,GREEN")
.parseFlag("-XepOpt:CaseInsensitiveColours=yellow,green")
.parseFlag("-XepOpt:EmptyColours=")
.build();
assertThat(flags.getEnum("Colour", Colour.class)).hasValue(Colour.RED);
assertThat(flags.getEnumSet("Colours", Colour.class))
.hasValue(ImmutableSet.of(Colour.YELLOW, Colour.GREEN));
assertThat(flags.getEnumSet("CaseInsensitiveColours", Colour.class))
.hasValue(ImmutableSet.of(Colour.YELLOW, Colour.GREEN));
assertThat(flags.getEnumSet("EmptyColours", Colour.class)).hasValue(ImmutableSet.of());
assertThat(flags.getEnumSet("NoSuchColours", Colour.class)).isEmpty();
}
@Test
public void invalidEnumFlags() {
ErrorProneFlags flags =
ErrorProneFlags.builder()
.parseFlag("-XepOpt:Colour=NOSUCH")
.parseFlag("-XepOpt:Colours=YELLOW,NOSUCH")
.build();
assertThrows(IllegalArgumentException.class, () -> flags.getEnum("Colour", Colour.class));
assertThrows(IllegalArgumentException.class, () -> flags.getEnumSet("Colours", Colour.class));
}
}
| 6,258
| 36.479042
| 98
|
java
|
error-prone
|
error-prone-master/check_api/src/test/java/com/google/errorprone/matchers/DescriptionTest.java
|
/*
* Copyright 2014 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import static com.google.common.truth.Truth.assertThat;
import static com.google.errorprone.BugPattern.LinkType.CUSTOM;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import com.google.errorprone.BugPattern;
import com.google.errorprone.bugpatterns.BugChecker;
import com.sun.source.tree.Tree;
import com.sun.source.tree.TreeVisitor;
import com.sun.tools.javac.tree.EndPosTable;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author cushon@google.com (Liam Miller-Cushon)
*/
@RunWith(JUnit4.class)
public class DescriptionTest {
private static class MockTree implements Tree, DiagnosticPosition {
@Override
public <R, D> R accept(TreeVisitor<R, D> arg0, D arg1) {
return null;
}
@Override
public Kind getKind() {
return null;
}
@Override
public JCTree getTree() {
throw new UnsupportedOperationException();
}
@Override
public int getStartPosition() {
throw new UnsupportedOperationException();
}
@Override
public int getPreferredPosition() {
throw new UnsupportedOperationException();
}
@Override
public int getEndPosition(EndPosTable endPosTable) {
throw new UnsupportedOperationException();
}
}
@BugPattern(
name = "DeadException",
summary = "Exception created but not thrown",
explanation = "",
severity = ERROR)
public static class MyChecker extends BugChecker {
Description getDescription() {
return describeMatch((Tree) new MockTree());
}
}
private static final String URL = " (see https://errorprone.info/bugpattern/DeadException)";
@Test
public void descriptionFromBugPattern() {
Description description = new MyChecker().getDescription();
assertThat(description.checkName).isEqualTo("DeadException");
assertThat(description.getMessageWithoutCheckName())
.isEqualTo("Exception created but not thrown\n" + URL);
assertThat(description.getMessage())
.isEqualTo("[DeadException] Exception created but not thrown\n" + URL);
}
@Test
public void customDescription() {
Description description =
new MyChecker()
.buildDescription((DiagnosticPosition) new MockTree())
.setMessage("custom message")
.build();
assertThat(description.checkName).isEqualTo("DeadException");
assertThat(description.getMessageWithoutCheckName()).isEqualTo("custom message\n" + URL);
assertThat(description.getMessage()).isEqualTo("[DeadException] custom message\n" + URL);
}
@BugPattern(
summary = "Exception created but not thrown",
explanation = "",
severity = ERROR,
linkType = CUSTOM,
link = "https://www.google.com/")
public static class CustomLinkChecker extends BugChecker {
Description getDescription() {
return describeMatch((Tree) new MockTree());
}
}
@Test
public void customLink() {
Description description =
new CustomLinkChecker()
.buildDescription((DiagnosticPosition) new MockTree())
.setMessage("custom message")
.build();
assertThat(description.getMessage())
.isEqualTo("[CustomLinkChecker] custom message\n (see https://www.google.com/)");
}
@Test
public void customLinkOverride() {
Description description =
new CustomLinkChecker()
.buildDescription((DiagnosticPosition) new MockTree())
.setMessage("custom message")
.setLinkUrl("http://foo")
.build();
assertThat(description.getMessage()).contains("http://foo");
}
}
| 4,406
| 30.255319
| 95
|
java
|
error-prone
|
error-prone-master/check_api/src/test/java/com/google/errorprone/matchers/StringLiteralTest.java
|
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.matchers;
import static com.google.common.truth.Truth.assertThat;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.TreeVisitor;
import javax.lang.model.element.Name;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* @author alexeagle@google.com (Alex Eagle)
*/
@RunWith(JUnit4.class)
public class StringLiteralTest {
@Test
public void matches() {
// TODO(b/67738557): consolidate helpers for creating fake trees
LiteralTree tree =
new LiteralTree() {
@Override
public Kind getKind() {
throw new UnsupportedOperationException();
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
throw new UnsupportedOperationException();
}
@Override
public Object getValue() {
return "a string literal";
}
};
assertThat(new StringLiteral("a string literal").matches(tree, null)).isTrue();
}
@Test
public void notMatches() {
// TODO(b/67738557): consolidate helpers for creating fake trees
LiteralTree tree =
new LiteralTree() {
@Override
public Kind getKind() {
throw new UnsupportedOperationException();
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
throw new UnsupportedOperationException();
}
@Override
public Object getValue() {
return "a string literal";
}
};
assertThat(new StringLiteral("different string").matches(tree, null)).isFalse();
IdentifierTree idTree =
new IdentifierTree() {
@Override
public Name getName() {
return null;
}
@Override
public Kind getKind() {
throw new UnsupportedOperationException();
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
throw new UnsupportedOperationException();
}
};
assertThat(new StringLiteral("test").matches(idTree, null)).isFalse();
// TODO(b/67738557): consolidate helpers for creating fake trees
LiteralTree intTree =
new LiteralTree() {
@Override
public Object getValue() {
return 5;
}
@Override
public Kind getKind() {
throw new UnsupportedOperationException();
}
@Override
public <R, D> R accept(TreeVisitor<R, D> visitor, D data) {
throw new UnsupportedOperationException();
}
};
assertThat(new StringLiteral("test").matches(intTree, null)).isFalse();
}
}
| 3,457
| 27.578512
| 84
|
java
|
error-prone
|
error-prone-master/check_api/src/test/java/com/google/errorprone/util/RegexesTest.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.util;
import static com.google.common.truth.Truth8.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link Regexes}Test */
@RunWith(JUnit4.class)
public final class RegexesTest {
@Test
public void positive() {
assertThat(Regexes.convertRegexToLiteral("hello")).hasValue("hello");
assertThat(Regexes.convertRegexToLiteral("\\t\\n\\f\\r")).hasValue("\t\n\f\r");
assertThat(Regexes.convertRegexToLiteral("\\Q.\\E")).hasValue(".");
}
@Test
public void negative() {
assertThat(Regexes.convertRegexToLiteral("[a-z]+")).isEmpty();
}
}
| 1,256
| 29.658537
| 83
|
java
|
error-prone
|
error-prone-master/check_api/src/test/java/com/google/errorprone/util/InheritedAnnotation.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.util;
import java.lang.annotation.Inherited;
@Inherited
public @interface InheritedAnnotation {}
| 738
| 31.130435
| 75
|
java
|
error-prone
|
error-prone-master/check_api/src/test/java/com/google/errorprone/util/SourceVersionTest.java
|
/*
* Copyright 2023 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.util;
import static com.google.common.truth.Truth.assertThat;
import com.sun.tools.javac.main.Option;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Options;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class SourceVersionTest {
@Test
public void supportsSwitchExpressions_notSupported() {
Context context = contextWithSourceVersion("13");
assertThat(SourceVersion.supportsSwitchExpressions(context)).isFalse();
}
@Test
public void supportsSwitchExpressions_conditionallySupported() {
Context context = contextWithSourceVersion("14");
assertThat(SourceVersion.supportsSwitchExpressions(context))
.isEqualTo(RuntimeVersion.isAtLeast14());
}
@Test
public void supportsTextBlocks_notSupported() {
Context context = contextWithSourceVersion("14");
assertThat(SourceVersion.supportsTextBlocks(context)).isFalse();
}
@Test
public void supportsTextBlocks_conditionallySupported() {
Context context = contextWithSourceVersion("15");
assertThat(SourceVersion.supportsTextBlocks(context)).isEqualTo(RuntimeVersion.isAtLeast15());
}
private static Context contextWithSourceVersion(String versionString) {
Context context = new Context();
Options options = Options.instance(context);
options.put(Option.SOURCE, versionString);
return context;
}
}
| 2,070
| 29.910448
| 98
|
java
|
error-prone
|
error-prone-master/check_api/src/test/java/com/google/errorprone/util/SignaturesTest.java
|
/*
* Copyright 2019 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.util;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.collect.ImmutableList;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import com.sun.source.tree.NewClassTree;
import com.sun.source.util.JavacTask;
import com.sun.source.util.TaskEvent;
import com.sun.source.util.TaskEvent.Kind;
import com.sun.source.util.TaskListener;
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.util.Context;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** {@link Signatures}Test */
@RunWith(JUnit4.class)
public class SignaturesTest {
@Test
public void prettyMethodSignature() throws Exception {
FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix());
Path source = fileSystem.getPath("Test.java");
Files.write(
source,
ImmutableList.of(
"class Test {", //
" void f() {",
" new Test();",
" new Test() {};",
" }",
"}"),
UTF_8);
JavacFileManager fileManager = new JavacFileManager(new Context(), false, UTF_8);
List<String> signatures = new ArrayList<>();
JavacTask task =
JavacTool.create()
.getTask(
/* out= */ null,
fileManager,
/* diagnosticListener= */ null,
/* options= */ ImmutableList.of(),
/* classes= */ ImmutableList.of(),
fileManager.getJavaFileObjects(source));
task.addTaskListener(
new TaskListener() {
@Override
public void finished(TaskEvent e) {
if (e.getKind() != Kind.ANALYZE) {
return;
}
new TreePathScanner<Void, Void>() {
@Override
public Void visitNewClass(NewClassTree node, Void unused) {
signatures.add(
Signatures.prettyMethodSignature(
(ClassSymbol) e.getTypeElement(), ASTHelpers.getSymbol(node)));
return super.visitNewClass(node, null);
}
}.scan(e.getCompilationUnit(), null);
}
});
assertThat(task.call()).isTrue();
assertThat(signatures).containsExactly("Test()", "Test()");
}
}
| 3,308
| 33.831579
| 87
|
java
|
error-prone
|
error-prone-master/check_api/src/test/java/com/google/errorprone/util/testdata/TargetTypeTest.java
|
/*
* Copyright 2018 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.util.testdata;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
abstract class TargetTypeTest {
void unary() {
System.out.println(
// BUG: Diagnostic contains: boolean
!detectWrappedBoolean());
System.out.println(
// BUG: Diagnostic contains: boolean
!detectPrimitiveBoolean());
System.out.println(
// BUG: Diagnostic contains: int
~detectPrimitiveInt());
System.out.println(
// BUG: Diagnostic contains: int
~detectWrappedInteger());
System.out.println(
// BUG: Diagnostic contains: int
~detectPrimitiveByte());
}
void binary(boolean b) {
// BUG: Diagnostic contains: int
long a1 = detectPrimitiveInt() + 20;
// BUG: Diagnostic contains: int
long a2 = detectWrappedInteger() - 20;
// BUG: Diagnostic contains: long
long a3 = detectPrimitiveInt() + 20L;
// BUG: Diagnostic contains: long
long a4 = detectWrappedInteger() - 20L;
// BUG: Diagnostic contains: boolean
boolean b1 = detectPrimitiveBoolean() & b;
// BUG: Diagnostic contains: boolean
boolean b2 = b || detectWrappedBoolean();
// BUG: Diagnostic contains: java.lang.String
String s1 = detectString() + "";
// BUG: Diagnostic contains: java.lang.String
String s2 = null + detectString();
// BUG: Diagnostic contains: java.lang.String
String s3 = 0 + detectString();
// BUG: Diagnostic contains: java.lang.String
boolean eq1 = detectString() == "";
// BUG: Diagnostic contains: java.lang.String
boolean eq2 = null != detectString();
// BUG: Diagnostic contains: int
boolean eq3 = detectPrimitiveInt() == 0;
// BUG: Diagnostic contains: int
boolean eq4 = 0 == detectWrappedInteger();
}
void binary_shift() {
// The shift operator is unusual in terms of binary operators, in that the operands undergo
// unary numeric promotion separately.
// BUG: Diagnostic contains: int
System.out.println(detectPrimitiveInt() << 1L);
// BUG: Diagnostic contains: int
System.out.println(1L << detectPrimitiveInt());
int i = 1;
// BUG: Diagnostic contains: int
i >>>= detectPrimitiveInt();
// BUG: Diagnostic contains: int
i >>>= detectWrappedInteger();
long a = 1;
// BUG: Diagnostic contains: int
a <<= detectPrimitiveInt();
// BUG: Diagnostic contains: int
a >>>= detectWrappedInteger();
// BUG: Diagnostic contains: int
a >>= detectWrappedInteger();
}
void conditional_condition() {
// BUG: Diagnostic contains: boolean
System.out.println(detectPrimitiveBoolean() ? "" : "");
// BUG: Diagnostic contains: boolean
System.out.println(detectWrappedBoolean() ? "" : "");
}
void conditional_trueExpression(boolean b) {
// BUG: Diagnostic contains: int
System.out.println(b ? detectWrappedInteger() : 0);
}
void conditional_trueExpression_noUnboxing(boolean b) {
// BUG: Diagnostic contains: java.lang.Integer
System.out.println(b ? detectWrappedInteger() : Integer.valueOf(0));
}
void conditional_conditionalInCondition(boolean b1, boolean b2) {
// BUG: Diagnostic contains: long
System.out.println(((detectPrimitiveInt() != 0L) ? b1 : b2) ? "" : "");
}
void ifStatement() {
if (
// BUG: Diagnostic contains: boolean
detectPrimitiveBoolean()) {}
if (
// BUG: Diagnostic contains: boolean
detectWrappedBoolean()) {}
}
void ifElseStatement() {
if (true) {
} else if (
// BUG: Diagnostic contains: boolean
detectPrimitiveBoolean()) {
}
if (true) {
} else if (
// BUG: Diagnostic contains: boolean
detectWrappedBoolean()) {
}
}
void whileLoop() {
while (
// BUG: Diagnostic contains: boolean
detectPrimitiveBoolean()) {}
while (
// BUG: Diagnostic contains: boolean
detectWrappedBoolean()) {}
}
void doWhileLoop() {
do {} while (
// BUG: Diagnostic contains: boolean
detectPrimitiveBoolean());
do {} while (
// BUG: Diagnostic contains: boolean
detectWrappedBoolean());
}
void forLoop() {
for (;
// BUG: Diagnostic contains: boolean
detectPrimitiveBoolean(); ) {}
for (;
// BUG: Diagnostic contains: boolean
detectWrappedBoolean(); ) {}
}
void typesOfDetectMethods() {
// BUG: Diagnostic contains: byte
byte primitiveByte = detectPrimitiveByte();
// BUG: Diagnostic contains: boolean
boolean primitiveBoolean = detectPrimitiveBoolean();
// BUG: Diagnostic contains: int
int primitiveInt = detectPrimitiveInt();
// BUG: Diagnostic contains: java.lang.Boolean
Boolean wrappedBoolean = detectWrappedBoolean();
// BUG: Diagnostic contains: java.lang.Integer
Integer wrappedInteger = detectWrappedInteger();
}
void arrayAccess(String[] s) {
// BUG: Diagnostic contains: int
System.out.println(s[detectPrimitiveInt()]);
// BUG: Diagnostic contains: int
System.out.println(s[detectWrappedInteger()]);
// BUG: Diagnostic contains: java.lang.String[]
System.out.println(detectStringArray()[0]);
}
void switchStatement() {
// BUG: Diagnostic contains: int
switch (detectPrimitiveInt()) {
}
// BUG: Diagnostic contains: int
switch (detectWrappedInteger()) {
}
// BUG: Diagnostic contains: java.lang.String
switch (detectString()) {
}
// BUG: Diagnostic contains: com.google.errorprone.util.testdata.TargetTypeTest.ThisEnum
switch (detectThisEnum()) {
}
}
int[] array_intInPrimitiveIntArray() {
// BUG: Diagnostic contains: int
int[] array = {detectPrimitiveInt()};
// BUG: Diagnostic contains: int
return new int[] {detectPrimitiveInt()};
}
int[][] array_intInPrimitiveIntArray2D() {
// BUG: Diagnostic contains: int
int[][] array = {{detectPrimitiveInt()}};
// BUG: Diagnostic contains: int
return new int[][] {{detectPrimitiveInt()}};
}
int[][][] array_byteInPrimitiveIntArray3D() {
// BUG: Diagnostic contains: int
int[][][] array = {{{detectPrimitiveByte()}}};
// BUG: Diagnostic contains: int
return new int[][][] {{{detectPrimitiveByte()}}};
}
int[] array_byteInPrimitiveIntArray() {
// BUG: Diagnostic contains: int
int[] array = {detectPrimitiveByte()};
// BUG: Diagnostic contains: int
return new int[] {detectPrimitiveByte()};
}
Integer[] array_intInWrappedIntegerArray() {
// BUG: Diagnostic contains: java.lang.Integer
Integer[] array = {detectPrimitiveInt()};
// BUG: Diagnostic contains: java.lang.Integer
return new Integer[] {detectPrimitiveInt()};
}
Integer[] array_integerInWrappedIntegerArray() {
// BUG: Diagnostic contains: java.lang.Integer
Integer[] array = {detectWrappedInteger()};
// BUG: Diagnostic contains: java.lang.Integer
return new Integer[] {detectWrappedInteger()};
}
int[] array_integerInPrimitiveIntArray() {
// BUG: Diagnostic contains: int
int[] array = {detectWrappedInteger()};
// BUG: Diagnostic contains: int
return new int[] {detectWrappedInteger()};
}
Integer[][] array_integerInWrappedIntegerArray2D() {
// BUG: Diagnostic contains: java.lang.Integer
Integer[][] array = {{detectWrappedInteger()}};
// BUG: Diagnostic contains: java.lang.Integer
return new Integer[][] {{detectWrappedInteger()}};
}
Integer[][][] array_integerInWrappedIntegerArray3D() {
// BUG: Diagnostic contains: java.lang.Integer
Integer[][][] array = {{{detectWrappedInteger()}}};
// BUG: Diagnostic contains: java.lang.Integer
return new Integer[][][] {{{detectWrappedInteger()}}};
}
Serializable[] array_integerInSerializableArray() {
// BUG: Diagnostic contains: java.io.Serializable
Serializable[] array = {detectWrappedInteger()};
// BUG: Diagnostic contains: java.io.Serializable
return new Serializable[] {detectWrappedInteger()};
}
Object[][][] array_integerInObjectArray3D() {
// BUG: Diagnostic contains: java.lang.Object
Object[][][] array = {{{detectWrappedInteger()}}};
// BUG: Diagnostic contains: java.lang.Object
return new Object[][][] {{{detectWrappedInteger()}}};
}
Object[][] array_integerArrayInObjectArray() {
// BUG: Diagnostic contains: java.lang.Integer
Object[][] array = {new Integer[] {detectPrimitiveInt()}};
// BUG: Diagnostic contains: java.lang.Integer
return new Object[][] {new Integer[] {detectPrimitiveInt()}};
}
Object[][] array_arrayHiddenInsideObjectArray() {
// BUG: Diagnostic contains: java.lang.Integer
Object[][] array = {{new Integer[] {detectPrimitiveInt()}}};
// BUG: Diagnostic contains: java.lang.Integer
return new Object[][] {{new Integer[] {detectPrimitiveInt()}}};
}
Integer[][] array_primitiveByteInDimensions() {
// BUG: Diagnostic contains: int
return new Integer[detectPrimitiveByte()][];
}
String[][] array_wrappedIntegerInDimensions() {
// BUG: Diagnostic contains: int
return new String[detectWrappedInteger()][];
}
String[][] array_initializeWithArray() {
// BUG: Diagnostic contains: java.lang.String[]
String[][] s = {detectStringArray()};
return s;
}
String methodChain() {
// BUG: Diagnostic contains: java.lang.Boolean
Boolean b = TargetTypeTest.detectWrappedBoolean();
// BUG: Diagnostic contains: java.lang.Integer
return detectWrappedInteger().toString();
}
void compoundAssignment_numeric(Integer i, int j, Long k) {
// BUG: Diagnostic contains: int
i /= detectWrappedInteger();
// BUG: Diagnostic contains: int
i *= (detectWrappedInteger());
// BUG: Diagnostic contains: int
j -= detectWrappedInteger();
// BUG: Diagnostic contains: long
k /= detectWrappedInteger();
}
void compoundAssignment_string(String s, Object o) {
// BUG: Diagnostic contains: java.lang.String
s += detectWrappedInteger();
// BUG: Diagnostic contains: java.lang.String
s += detectPrimitiveInt();
// BUG: Diagnostic contains: java.lang.String
o += detectString();
}
void compoundAssignment_boolean(boolean b) {
// BUG: Diagnostic contains: boolean
b &= detectWrappedBoolean();
// BUG: Diagnostic contains: boolean
b |= detectPrimitiveBoolean();
}
void concatenation(String s, Object a) {
// BUG: Diagnostic contains: java.lang.String
a = s + detectWrappedInteger();
// BUG: Diagnostic contains: java.lang.String
a = s + detectPrimitiveByte();
// BUG: Diagnostic contains: java.lang.String
a = s + detectVoid();
// BUG: Diagnostic contains: java.lang.String
a = s + detectStringArray();
}
abstract <T> T id(T t);
abstract <T> List<T> list(List<T> t);
void generic() {
// BUG: Diagnostic contains: java.lang.String
String s = id(detectString());
// BUG: Diagnostic contains: java.lang.Integer
int i = id(detectPrimitiveInt());
// BUG: Diagnostic contains: java.util.List<java.lang.String>
List<String> y = id(detectStringList());
// BUG: Diagnostic contains: java.lang.Integer
Integer z = id(detectPrimitiveInt());
}
void typeCast() {
// BUG: Diagnostic contains: int
long a = (int) detectPrimitiveByte();
// BUG: Diagnostic contains: java.lang.Object
String s = (String) (Object) detectString();
}
void enhancedForLoop() {
// BUG: Diagnostic contains: java.lang.String[]
for (String s : detectStringArray()) {}
// BUG: Diagnostic contains: java.lang.Object[]
for (Object s : detectStringArray()) {}
// BUG: Diagnostic contains: int[]
for (int i : detectPrimitiveIntArray()) {}
// BUG: Diagnostic contains: long[]
for (long i : detectPrimitiveIntArray()) {}
// BUG: Diagnostic contains: java.lang.Integer[]
for (Integer i : detectPrimitiveIntArray()) {}
// BUG: Diagnostic contains: java.lang.Object[]
for (Object i : detectPrimitiveIntArray()) {}
// BUG: Diagnostic contains: java.lang.Iterable<? extends java.lang.String>
for (String s : detectStringList()) {}
// BUG: Diagnostic contains: java.lang.Iterable<? extends java.lang.Object>
for (Object s : detectStringList()) {}
// BUG: Diagnostic contains: java.lang.Iterable<? extends java.lang.Integer>
for (int s : detectIntegerList()) {}
}
void testAssert() {
// BUG: Diagnostic contains: boolean
assert detectPrimitiveBoolean();
// BUG: Diagnostic contains: boolean
assert detectWrappedBoolean();
// BUG: Diagnostic contains: boolean
assert detectPrimitiveBoolean() : "";
// BUG: Diagnostic contains: java.lang.String
assert false : detectString();
// BUG: Diagnostic contains: java.lang.String
assert false : detectPrimitiveInt();
}
void testSwitch(int anInt, String aString) {
final int detectInt = 0;
switch (anInt) {
// BUG: Diagnostic contains: int
case detectInt:
break;
}
final byte detectByte = 0;
switch (anInt) {
// BUG: Diagnostic contains: int
case detectByte:
break;
}
final String detectString = "";
switch (aString) {
// BUG: Diagnostic contains: java.lang.String
case detectString:
break;
}
}
void instanceOf() {
// BUG: Diagnostic contains: java.lang.Object
if (detectString() instanceof String) {}
// BUG: Diagnostic contains: java.lang.Object
if (detectStringList() instanceof Serializable) {}
}
void testSynchronized() {
// BUG: Diagnostic contains: java.lang.Object
synchronized (detectString()) {
}
}
void testThrow() throws IOException {
if (System.currentTimeMillis() > 0) {
// BUG: Diagnostic contains: java.lang.IllegalArgumentException
throw detectIllegalArgumentException();
}
if (System.currentTimeMillis() > 0) {
// BUG: Diagnostic contains: java.io.IOException
throw detectIoException();
}
}
void newClass() {
// BUG: Diagnostic contains: java.lang.String
new IllegalArgumentException(detectString());
// BUG: Diagnostic contains: HasInner
detectHasInner().new Inner();
// BUG: Diagnostic contains: HasInner
detectDifferentName().new Inner();
}
// Helper methods that we can search for.
static byte detectPrimitiveByte() {
return 0;
}
static boolean detectPrimitiveBoolean() {
return true;
}
static int detectPrimitiveInt() {
return 0;
}
static int[] detectPrimitiveIntArray() {
return new int[0];
}
static Boolean detectWrappedBoolean() {
return true;
}
static Integer detectWrappedInteger() {
return 0;
}
static String detectString() {
return "";
}
static String[] detectStringArray() {
return new String[] {};
}
static ThisEnum detectThisEnum() {
return null;
}
static Void detectVoid() {
return null;
}
static List<String> detectStringList() {
return null;
}
static List<Integer> detectIntegerList() {
return null;
}
static IllegalArgumentException detectIllegalArgumentException() {
return null;
}
static IOException detectIoException() {
return null;
}
static HasInner detectHasInner() {
return null;
}
static DifferentName detectDifferentName() {
return null;
}
enum ThisEnum {}
class HasInner {
class Inner {}
}
// Not called the obvious "ExtendsHasInner" in order to avoid erroneously matching the "HasInner"
// part of it.
class DifferentName extends HasInner {}
}
| 16,238
| 27.38986
| 99
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.