本文整理汇总了Java中com.google.errorprone.VisitorState.getSourceForNode方法的典型用法代码示例。如果您正苦于以下问题:Java VisitorState.getSourceForNode方法的具体用法?Java VisitorState.getSourceForNode怎么用?Java VisitorState.getSourceForNode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.google.errorprone.VisitorState
的用法示例。
在下文中一共展示了VisitorState.getSourceForNode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: matchMethodInvocation
import com.google.errorprone.VisitorState; //导入方法依赖的package包/类
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
if (!matcher.matches(tree, state)) {
return Description.NO_MATCH;
}
Description.Builder description = buildDescription(tree);
MethodSymbol sym = ASTHelpers.getSymbol(tree);
if (sym != null) {
description.setMessage(String.format(MESSAGE_TEMPLATE, sym));
}
// If this looks like the "Wait until a condition becomes true" case from the wiki content,
// rewrite the enclosing if to a while. Other fixes are too complicated to construct
// mechanically, so we provide detailed instructions in the wiki content.
if (!waitMethodWithTimeout.matches(tree, state)) {
JCIf enclosingIf = ASTHelpers.findEnclosingNode(state.getPath().getParentPath(), JCIf.class);
if (enclosingIf != null && enclosingIf.getElseStatement() == null) {
CharSequence ifSource = state.getSourceForNode(enclosingIf);
if (ifSource == null) {
// Source isn't available, so we can't construct a fix
return description.build();
}
String replacement = ifSource.toString().replaceFirst("if", "while");
return description.addFix(SuggestedFix.replace(enclosingIf, replacement)).build();
}
}
return description.build();
}
示例2: rewriteCompoundAssignment
import com.google.errorprone.VisitorState; //导入方法依赖的package包/类
/** Desugars a compound assignment, making the cast explicit. */
private static Optional<Fix> rewriteCompoundAssignment(
CompoundAssignmentTree tree, VisitorState state) {
CharSequence var = state.getSourceForNode(tree.getVariable());
CharSequence expr = state.getSourceForNode(tree.getExpression());
if (var == null || expr == null) {
return Optional.absent();
}
switch (tree.getKind()) {
case RIGHT_SHIFT_ASSIGNMENT:
// narrowing the result of a signed right shift does not lose information
return Optional.absent();
default:
break;
}
Kind regularAssignmentKind = regularAssignmentFromCompound(tree.getKind());
String op = assignmentToString(regularAssignmentKind);
// Add parens to the rhs if necessary to preserve the current precedence
// e.g. 's -= 1 - 2' -> 's = s - (1 - 2)'
if (tree.getExpression() instanceof JCBinary) {
Kind rhsKind = tree.getExpression().getKind();
if (!OperatorPrecedence.from(rhsKind)
.isHigher(OperatorPrecedence.from(regularAssignmentKind))) {
expr = String.format("(%s)", expr);
}
}
// e.g. 's *= 42' -> 's = (short) (s * 42)'
String castType = getType(tree.getVariable()).toString();
String replacement = String.format("%s = (%s) (%s %s %s)", var, castType, var, op, expr);
return Optional.of(SuggestedFix.replace(tree, replacement));
}
示例3: getMessageOrFormat
import com.google.errorprone.VisitorState; //导入方法依赖的package包/类
private static String getMessageOrFormat(MethodInvocationTree tree, VisitorState state) {
if (tree.getArguments().size() > 1) {
return "String.format("
+ state
.getSourceCode()
.subSequence(
((JCTree) tree.getArguments().get(0)).getStartPosition(),
state.getEndPosition(Iterables.getLast(tree.getArguments())))
+ ")";
}
return state.getSourceForNode(getOnlyElement(tree.getArguments()));
}
示例4: matchClass
import com.google.errorprone.VisitorState; //导入方法依赖的package包/类
@Override
public Description matchClass(ClassTree classTree, VisitorState visitorState) {
Symbol throwableClass = visitorState.getSymbolFromString("java.lang.Throwable");
if (Objects.equals(ASTHelpers.getSymbol(classTree.getExtendsClause()), throwableClass)) {
Optional<? extends Tree> methodTree =
classTree
.getMembers()
.stream()
.filter(
m ->
m instanceof MethodTree
&& ((MethodTree) m).getName().contentEquals("toString"))
.findFirst();
if (methodTree.isPresent()) {
SuggestedFix.Builder builder = SuggestedFix.builder();
MethodTree tree = (MethodTree) methodTree.get();
if (!tree.getParameters().isEmpty()) {
return Description.NO_MATCH;
}
String newTree =
tree.getModifiers().toString().replaceAll("@Override[(][)]", "@Override")
+ "String getMessage()\n"
+ visitorState.getSourceForNode(tree.getBody());
builder.replace(tree, newTree);
return describeMatch(classTree, builder.build());
}
}
return Description.NO_MATCH;
}
示例5: buildFix
import com.google.errorprone.VisitorState; //导入方法依赖的package包/类
/**
* Create fixes for invalid assertions.
*
* <ul>
* <li>Rewrite `verify(mock.bar())` to `verify(mock).bar()`
* <li>Rewrite `verify(mock.bar(), times(N))` to `verify(mock, times(N)).bar()`
* <li>Rewrite `verify(mock, never())` to `verifyZeroInteractions(mock)`
* <li>Finally, offer to delete the mock statement.
* </ul>
*/
private void buildFix(
Description.Builder builder, MethodInvocationTree tree, VisitorState state) {
MethodInvocationTree mockitoCall = tree;
List<? extends ExpressionTree> args = mockitoCall.getArguments();
Tree mock = mockitoCall.getArguments().get(0);
boolean isVerify = ASTHelpers.getSymbol(tree).getSimpleName().contentEquals("verify");
if (isVerify && mock.getKind() == Kind.METHOD_INVOCATION) {
MethodInvocationTree invocation = (MethodInvocationTree) mock;
String verify = state.getSourceForNode(mockitoCall.getMethodSelect());
String receiver = state.getSourceForNode(ASTHelpers.getReceiver(invocation));
String mode = args.size() > 1 ? ", " + state.getSourceForNode(args.get(1)) : "";
String call = state.getSourceForNode(invocation).substring(receiver.length());
builder.addFix(
SuggestedFix.replace(tree, String.format("%s(%s%s)%s", verify, receiver, mode, call)));
}
if (isVerify && args.size() > 1 && NEVER_METHOD.matches(args.get(1), state)) {
// TODO(cushon): handle times(0) the same as never()
builder.addFix(
SuggestedFix.builder()
.addStaticImport("org.mockito.Mockito.verifyZeroInteractions")
.replace(tree, String.format("verifyZeroInteractions(%s)", mock))
.build());
}
// Always suggest the naive semantics-preserving option, which is just to
// delete the assertion:
Tree parent = state.getPath().getParentPath().getLeaf();
if (parent.getKind() == Kind.EXPRESSION_STATEMENT) {
// delete entire expression statement
builder.addFix(SuggestedFix.delete(parent));
} else {
builder.addFix(SuggestedFix.delete(tree));
}
}
示例6: replaceMethodName
import com.google.errorprone.VisitorState; //导入方法依赖的package包/类
private Fix replaceMethodName(MethodInvocationTree tree, VisitorState state, String newName) {
String source = state.getSourceForNode((JCTree) tree.getMethodSelect());
int idx = source.lastIndexOf("contains");
String replacement =
source.substring(0, idx) + newName + source.substring(idx + "contains".length());
Fix fix = SuggestedFix.replace(tree.getMethodSelect(), replacement);
return fix;
}
示例7: removeEqualsFromComparison
import com.google.errorprone.VisitorState; //导入方法依赖的package包/类
private Description removeEqualsFromComparison(
BinaryTree tree, VisitorState state, ExpressionType expressionType) {
String replacement =
expressionType == ExpressionType.GREATER_THAN_EQUAL
? state.getSourceForNode((JCTree) tree.getLeftOperand()) + " > 0"
: "0 < " + state.getSourceForNode((JCTree) tree.getRightOperand());
return describeMatch(tree, SuggestedFix.replace(tree, replacement));
}
示例8: getMessageSnippet
import com.google.errorprone.VisitorState; //导入方法依赖的package包/类
private static String getMessageSnippet(
StatementTree failStatement, VisitorState state, HasOtherParameters hasOtherParameters) {
ExpressionTree expression = ((ExpressionStatementTree) failStatement).getExpression();
MethodSymbol sym = (MethodSymbol) getSymbol(expression);
String tail = hasOtherParameters == HasOtherParameters.TRUE ? ", " : "";
// The above casts were checked earlier by failOrAssert.
return hasInitialStringParameter(sym, state)
? state.getSourceForNode(((MethodInvocationTree) expression).getArguments().get(0)) + tail
: "";
}
示例9: toFile
import com.google.errorprone.VisitorState; //导入方法依赖的package包/类
/** Converts a {@code String} to a {@code File}. */
private Object toFile(VisitorState state, Tree fileArg, SuggestedFix.Builder fix) {
Type type = ASTHelpers.getType(fileArg);
if (ASTHelpers.isSubtype(type, state.getSymtab().stringType, state)) {
fix.addImport("java.io.File");
return String.format("new File(%s)", state.getSourceForNode(fileArg));
} else if (ASTHelpers.isSubtype(type, state.getTypeFromString("java.io.File"), state)) {
return state.getSourceForNode(fileArg);
} else {
throw new AssertionError("unexpected type: " + type);
}
}
示例10: classify
import com.google.errorprone.VisitorState; //导入方法依赖的package包/类
static Operand classify(JCTree tree, VisitorState state) {
CharSequence source = state.getSourceForNode(tree);
if (tree instanceof MethodInvocationTree) {
// expr.getClass() -> "expr"
MethodInvocationTree receiverInvocation = (MethodInvocationTree) tree;
MethodSymbol sym = ASTHelpers.getSymbol(receiverInvocation);
if (sym != null) {
if (sym.getSimpleName().contentEquals("getClass") && sym.params().isEmpty()) {
if (receiverInvocation.getMethodSelect() instanceof IdentifierTree) {
// unqualified `getClass()`
return Operand.create(Kind.EXPR, state.getSourceForNode(tree), source);
}
return Operand.create(
Kind.GET_CLASS,
state.getSourceForNode((JCTree) ASTHelpers.getReceiver(receiverInvocation)),
source);
}
}
} else if (tree instanceof MemberSelectTree) {
// Foo.class -> "Foo"
MemberSelectTree select = (MemberSelectTree) tree;
if (select.getIdentifier().contentEquals("class")) {
return Operand.create(
Kind.LITERAL, state.getSourceForNode((JCTree) select.getExpression()), source);
}
}
return Operand.create(Kind.EXPR, source, source);
}
示例11: normalizedSourceForExpression
import com.google.errorprone.VisitorState; //导入方法依赖的package包/类
private static String normalizedSourceForExpression(JCExpression expression, VisitorState state) {
return state.getSourceForNode(TreeInfo.skipParens(expression));
}
示例12: convertToString
import com.google.errorprone.VisitorState; //导入方法依赖的package包/类
private static String convertToString(ExpressionTree detail, VisitorState state) {
return state.getSourceForNode(detail)
+ (ASTHelpers.isSameType(ASTHelpers.getType(detail), state.getSymtab().stringType, state)
? ""
: ".toString()");
}
示例13: matchMethod
import com.google.errorprone.VisitorState; //导入方法依赖的package包/类
@Override
public Description matchMethod(MethodTree methodTree, VisitorState state) {
MethodSymbol methodSymbol = (MethodSymbol) ASTHelpers.getSymbol(methodTree);
boolean isVarargs = (methodSymbol.flags() & Flags.VARARGS) != 0;
Set<MethodSymbol> superMethods = ASTHelpers.findSuperMethods(methodSymbol, state.getTypes());
// If there are no super methods, we're fine:
if (superMethods.isEmpty()) {
return Description.NO_MATCH;
}
Iterator<MethodSymbol> superMethodsIterator = superMethods.iterator();
boolean areSupersVarargs = superMethodsIterator.next().isVarArgs();
while (superMethodsIterator.hasNext()) {
if (areSupersVarargs != superMethodsIterator.next().isVarArgs()) {
// The super methods are inconsistent (some are varargs, some are not varargs). Then the
// current method is inconsistent with some of its supermethods, so report a match.
return describeMatch(methodTree, new SuggestedFix());
}
}
// The current method is consistent with all of its supermethods:
if (isVarargs == areSupersVarargs) {
return Description.NO_MATCH;
}
// The current method is inconsistent with all of its supermethods, so flip the varargs-ness
// of the current method.
List<? extends VariableTree> parameterTree = methodTree.getParameters();
Tree paramType = parameterTree.get(parameterTree.size() - 1).getType();
CharSequence paramTypeSource = state.getSourceForNode((JCTree) paramType);
if (paramTypeSource == null) {
// No fix if we don't have tree end positions.
return describeMatch(methodTree, new SuggestedFix());
}
Fix fix = new SuggestedFix();
if (isVarargs) {
fix = new SuggestedFix().replace(paramType, "[]", paramTypeSource.length() - 3, 0);
} else {
// There may be a comment that includes a '[' character between the open and closed
// brackets of the array type. If so, we don't return a fix.
int arrayOpenIndex = paramTypeSource.length() - 2;
while (paramTypeSource.charAt(arrayOpenIndex) == ' ') {
arrayOpenIndex--;
}
if (paramTypeSource.charAt(arrayOpenIndex) == '[') {
fix = new SuggestedFix().replace(paramType, "...", arrayOpenIndex, 0);
}
}
return describeMatch(methodTree, fix);
}
示例14: createDescription
import com.google.errorprone.VisitorState; //导入方法依赖的package包/类
public Description createDescription(
ExpressionTree tree, ExpressionTree arg, VisitorState state, boolean suggestIntegral) {
String literal = state.getSourceForNode(arg);
if (literal == null) {
return describeMatch(tree);
}
// BigDecimal doesn't seem to support underscores or terminal Ds in its string parsing
literal = literal.replaceAll("[_dD]", "");
BigDecimal intendedValue = new BigDecimal(literal);
Optional<BigInteger> integralValue = asBigInteger(intendedValue);
Description.Builder description = buildDescription(tree);
if (suggestIntegral && integralValue.isPresent() && isWithinLongRange(integralValue.get())) {
long longValue = integralValue.get().longValue();
String suggestedString;
switch (Ints.saturatedCast(longValue)) {
case 0:
suggestedString = "BigDecimal.ZERO";
break;
case 1:
suggestedString = "BigDecimal.ONE";
break;
case 10:
suggestedString = "BigDecimal.TEN";
break;
default:
suggestedString = "new BigDecimal(" + longValue + "L)";
}
description.addFix(
SuggestedFix.builder()
.addImport("java.math.BigDecimal")
.replace(tree, suggestedString)
.build());
}
description.addFix(
SuggestedFix.builder()
.addImport("java.math.BigDecimal")
.replace(tree, "new BigDecimal(\"" + literal + "\")")
.build());
return description.build();
}
示例15: matchBinary
import com.google.errorprone.VisitorState; //导入方法依赖的package包/类
@Override
public Description matchBinary(BinaryTree tree, VisitorState state) {
if (constValue(tree.getLeftOperand()) != null) {
switch (tree.getKind()) {
case LEFT_SHIFT: // bit field initialization, e.g. `1 << 1`, `1 << 2`, ...
case DIVIDE: // aspect ratios, e.g. `1.0f / 1.0f`, `2.0f / 3.0f`, ...
case MINUS: // character arithmetic, e.g. `'A' - 'A'`, `'B' - 'A'`, ...
return NO_MATCH;
default: // fall out
}
}
String replacement;
switch (tree.getKind()) {
case DIVIDE:
replacement = "1";
break;
case MINUS:
case REMAINDER:
replacement = "0";
break;
case GREATER_THAN_EQUAL:
case LESS_THAN_EQUAL:
case EQUAL_TO:
if (ASSERTION.matches(state.getPath().getParentPath().getLeaf(), state)) {
return NO_MATCH;
}
replacement = "true";
break;
case LESS_THAN:
case GREATER_THAN:
case NOT_EQUAL_TO:
case XOR:
if (ASSERTION.matches(state.getPath().getParentPath().getLeaf(), state)) {
return NO_MATCH;
}
replacement = "false";
break;
case AND:
case OR:
case CONDITIONAL_AND:
case CONDITIONAL_OR:
replacement = state.getSourceForNode(tree.getLeftOperand());
break;
case LEFT_SHIFT:
case RIGHT_SHIFT:
case UNSIGNED_RIGHT_SHIFT:
replacement = null; // ¯\_(ツ)_/¯
break;
case MULTIPLY:
case PLUS:
default:
return NO_MATCH;
}
if (!tree.getLeftOperand().toString().equals(tree.getRightOperand().toString())) {
return NO_MATCH;
}
switch (tree.getKind()) {
case EQUAL_TO:
replacement = isNanReplacement(tree, state).orElse(replacement);
break;
case NOT_EQUAL_TO:
replacement = isNanReplacement(tree, state).map(r -> "!" + r).orElse(replacement);
break;
default: // fall out
}
Description.Builder description = buildDescription(tree);
if (replacement != null) {
description.setMessage(
String.format(
"A binary expression where both operands are the same is usually incorrect;"
+ " the value of this expression is equivalent to `%s`.",
replacement));
}
return description.build();
}