Java Code Examples for com.google.errorprone.matchers.Description#Builder

The following examples show how to use com.google.errorprone.matchers.Description#Builder . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: XPFlagCleaner.java    From piranha with Apache License 2.0 6 votes vote down vote up
private Description updateCode(
    Value v, ExpressionTree tree, ExpressionTree expr, VisitorState state) {
  boolean update = false;
  String replacementString = "";

  if (v.equals(Value.TRUE)) {
    update = true;
    replacementString = TRUE;
  } else if (v.equals(Value.FALSE)) {
    update = true;
    replacementString = FALSE;
  }

  if (update) {
    Description.Builder builder = buildDescription(tree);
    SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
    fixBuilder.replace(expr, replacementString);
    decrementAllSymbolUsages(expr, state, fixBuilder);
    builder.addFix(fixBuilder.build());
    endPos = state.getEndPosition(expr);
    return builder.build();
  }
  return Description.NO_MATCH;
}
 
Example 2
Source File: XPFlagCleaner.java    From piranha with Apache License 2.0 6 votes vote down vote up
@Override
public Description matchExpressionStatement(ExpressionStatementTree tree, VisitorState state) {
  if (overLaps(tree, state)) {
    return Description.NO_MATCH;
  }

  if (tree.getExpression().getKind().equals(Kind.METHOD_INVOCATION)) {
    MethodInvocationTree mit = (MethodInvocationTree) tree.getExpression();
    API api = getXPAPI(mit);
    if (api.equals(API.DELETE_METHOD)) {
      Description.Builder builder = buildDescription(tree);
      SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
      fixBuilder.delete(tree);
      decrementAllSymbolUsages(tree, state, fixBuilder);
      builder.addFix(fixBuilder.build());
      endPos = state.getEndPosition(tree);
      return builder.build();
    }
  }
  return Description.NO_MATCH;
}
 
Example 3
Source File: NullAway.java    From NullAway with MIT License 6 votes vote down vote up
@SuppressWarnings("unused")
private Description.Builder changeReturnNullabilityFix(
    Tree suggestTree, Description.Builder builder, VisitorState state) {
  if (suggestTree.getKind() != Tree.Kind.METHOD) {
    throw new RuntimeException("This should be a MethodTree");
  }
  SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
  MethodTree methodTree = (MethodTree) suggestTree;
  int countNullableAnnotations = 0;
  for (AnnotationTree annotationTree : methodTree.getModifiers().getAnnotations()) {
    if (state.getSourceForNode(annotationTree.getAnnotationType()).endsWith("Nullable")) {
      fixBuilder.delete(annotationTree);
      countNullableAnnotations += 1;
    }
  }
  assert countNullableAnnotations > 1;
  return builder.addFix(fixBuilder.build());
}
 
Example 4
Source File: ErrorBuilder.java    From NullAway with MIT License 6 votes vote down vote up
/**
 * create an error description for a nullability warning
 *
 * @param errorMessage the error message object.
 * @param suggestTree the location at which a fix suggestion should be made
 * @param descriptionBuilder the description builder for the error.
 * @param state the visitor state (used for e.g. suppression finding).
 * @return the error description
 */
public Description createErrorDescription(
    ErrorMessage errorMessage,
    @Nullable Tree suggestTree,
    Description.Builder descriptionBuilder,
    VisitorState state) {
  Description.Builder builder = descriptionBuilder.setMessage(errorMessage.message);
  if (errorMessage.messageType.equals(GET_ON_EMPTY_OPTIONAL)
      && hasPathSuppression(state.getPath(), OPTIONAL_CHECK_NAME)) {
    return Description.NO_MATCH;
  }

  if (config.suggestSuppressions() && suggestTree != null) {
    builder = addSuggestedSuppression(errorMessage, suggestTree, builder);
  }
  // #letbuildersbuild
  return builder.build();
}
 
Example 5
Source File: ErrorBuilder.java    From NullAway with MIT License 6 votes vote down vote up
private Description.Builder removeCastToNonNullFix(
    Tree suggestTree, Description.Builder builder) {
  assert suggestTree.getKind() == Tree.Kind.METHOD_INVOCATION;
  final MethodInvocationTree invTree = (MethodInvocationTree) suggestTree;
  final Symbol.MethodSymbol methodSymbol = ASTHelpers.getSymbol(invTree);
  final String qualifiedName =
      ASTHelpers.enclosingClass(methodSymbol) + "." + methodSymbol.getSimpleName().toString();
  if (!qualifiedName.equals(config.getCastToNonNullMethod())) {
    throw new RuntimeException("suggestTree should point to the castToNonNull invocation.");
  }
  // Remove the call to castToNonNull:
  final SuggestedFix fix =
      SuggestedFix.builder()
          .replace(suggestTree, invTree.getArguments().get(0).toString())
          .build();
  return builder.addFix(fix);
}
 
Example 6
Source File: XPFlagCleaner.java    From piranha with Apache License 2.0 5 votes vote down vote up
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
  if (overLaps(tree, state)) {
    return Description.NO_MATCH;
  }
  ExpressionTree et = tree.getExpression();
  if (et != null && et.getKind().equals(Kind.BOOLEAN_LITERAL)) {
    return Description.NO_MATCH;
  }

  Value x = evalExpr(et, state);
  boolean update = false;
  String replacementString = EMPTY;

  if (x.equals(Value.TRUE)) {
    update = true;
    replacementString = TRUE;
  } else if (x.equals(Value.FALSE)) {
    update = true;
    replacementString = FALSE;
  }

  if (update) {
    Description.Builder builder = buildDescription(tree);
    SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
    fixBuilder.replace(et, replacementString);
    decrementAllSymbolUsages(et, state, fixBuilder);
    builder.addFix(fixBuilder.build());
    endPos = state.getEndPosition(tree);
    return builder.build();
  }
  return Description.NO_MATCH;
}
 
Example 7
Source File: XPFlagCleaner.java    From piranha with Apache License 2.0 5 votes vote down vote up
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {

  for (String name : handledAnnotations) {
    AnnotationTree at =
        ASTHelpers.getAnnotationWithSimpleName(tree.getModifiers().getAnnotations(), name);

    if (at != null) {
      for (ExpressionTree et : at.getArguments()) {
        if (et.getKind() == Kind.ASSIGNMENT) {
          AssignmentTree assn = (AssignmentTree) et;
          if (ASTHelpers.getSymbol(assn.getExpression())
              .getQualifiedName()
              .toString()
              .endsWith(xpFlagName)) {
            Description.Builder builder = buildDescription(tree);
            SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
            if (isTreated) {
              fixBuilder.delete(at);
              decrementAllSymbolUsages(at, state, fixBuilder);
            } else {
              fixBuilder.delete(tree);
              decrementAllSymbolUsages(tree, state, fixBuilder);
            }
            builder.addFix(fixBuilder.build());
            return builder.build();
          }
        }
      }
    }
  }

  return Description.NO_MATCH;
}
 
Example 8
Source File: XPFlagCleaner.java    From piranha with Apache License 2.0 5 votes vote down vote up
@Override
public Description matchConditionalExpression(
    ConditionalExpressionTree tree, VisitorState state) {
  if (overLaps(tree, state)) {
    return Description.NO_MATCH;
  }
  ExpressionTree et = tree.getCondition();
  Value x = evalExpr(et, state);
  String replacementString = EMPTY;

  boolean update = false;
  ExpressionTree removedBranch = null;
  if (x.equals(Value.TRUE)) {
    update = true;
    replacementString = state.getSourceForNode(tree.getTrueExpression());
    removedBranch = tree.getFalseExpression();
  } else if (x.equals(Value.FALSE)) {
    update = true;
    replacementString = state.getSourceForNode(tree.getFalseExpression());
    removedBranch = tree.getTrueExpression();
  }

  if (update) {
    Preconditions.checkNotNull(removedBranch, "update => removedBranch != null here.");
    Description.Builder builder = buildDescription(tree);
    SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
    fixBuilder.replace(tree, stripBraces(replacementString));
    decrementAllSymbolUsages(et, state, fixBuilder);
    decrementAllSymbolUsages(removedBranch, state, fixBuilder);
    builder.addFix(fixBuilder.build());
    endPos = state.getEndPosition(tree);
    return builder.build();
  }
  return Description.NO_MATCH;
}
 
Example 9
Source File: ErrorBuilder.java    From NullAway with MIT License 5 votes vote down vote up
private Description.Builder addSuggestedSuppression(
    ErrorMessage errorMessage, Tree suggestTree, Description.Builder builder) {
  switch (errorMessage.messageType) {
    case DEREFERENCE_NULLABLE:
    case RETURN_NULLABLE:
    case PASS_NULLABLE:
    case ASSIGN_FIELD_NULLABLE:
    case SWITCH_EXPRESSION_NULLABLE:
      if (config.getCastToNonNullMethod() != null) {
        builder = addCastToNonNullFix(suggestTree, builder);
      } else {
        builder = addSuppressWarningsFix(suggestTree, builder, suppressionName);
      }
      break;
    case CAST_TO_NONNULL_ARG_NONNULL:
      builder = removeCastToNonNullFix(suggestTree, builder);
      break;
    case WRONG_OVERRIDE_RETURN:
      builder = addSuppressWarningsFix(suggestTree, builder, suppressionName);
      break;
    case WRONG_OVERRIDE_PARAM:
      builder = addSuppressWarningsFix(suggestTree, builder, suppressionName);
      break;
    case METHOD_NO_INIT:
    case FIELD_NO_INIT:
      builder = addSuppressWarningsFix(suggestTree, builder, INITIALIZATION_CHECK_NAME);
      break;
    case ANNOTATION_VALUE_INVALID:
      break;
    default:
      builder = addSuppressWarningsFix(suggestTree, builder, suppressionName);
  }
  return builder;
}
 
Example 10
Source File: ErrorBuilder.java    From NullAway with MIT License 5 votes vote down vote up
/**
 * create an error description for a generalized @Nullable value to @NonNull location assignment.
 *
 * <p>This includes: field assignments, method arguments and method returns
 *
 * @param errorMessage the error message object.
 * @param suggestTreeIfCastToNonNull the location at which a fix suggestion should be made if a
 *     castToNonNull method is available (usually the expression to cast)
 * @param descriptionBuilder the description builder for the error.
 * @param state the visitor state for the location which triggered the error (i.e. for suppression
 *     finding)
 * @return the error description.
 */
Description createErrorDescriptionForNullAssignment(
    ErrorMessage errorMessage,
    @Nullable Tree suggestTreeIfCastToNonNull,
    Description.Builder descriptionBuilder,
    VisitorState state) {
  if (config.getCastToNonNullMethod() != null) {
    return createErrorDescription(
        errorMessage, suggestTreeIfCastToNonNull, descriptionBuilder, state);
  } else {
    return createErrorDescription(
        errorMessage, suppressibleNode(state.getPath()), descriptionBuilder, state);
  }
}
 
Example 11
Source File: ErrorBuilder.java    From NullAway with MIT License 5 votes vote down vote up
void reportInitErrorOnField(Symbol symbol, VisitorState state, Description.Builder builder) {
  if (symbolHasSuppressWarningsAnnotation(symbol, INITIALIZATION_CHECK_NAME)) {
    return;
  }
  Tree tree = getTreesInstance(state).getTree(symbol);

  String fieldName = symbol.toString();

  if (symbol.enclClass().getNestingKind().isNested()) {
    String flatName = symbol.enclClass().flatName().toString();
    int index = flatName.lastIndexOf(".") + 1;
    fieldName = flatName.substring(index) + "." + fieldName;
  }

  if (symbol.isStatic()) {
    state.reportMatch(
        createErrorDescription(
            new ErrorMessage(
                FIELD_NO_INIT, "@NonNull static field " + fieldName + " not initialized"),
            tree,
            builder,
            state));
  } else {
    state.reportMatch(
        createErrorDescription(
            new ErrorMessage(FIELD_NO_INIT, "@NonNull field " + fieldName + " not initialized"),
            tree,
            builder,
            state));
  }
}
 
Example 12
Source File: ErrorBuilder.java    From NullAway with MIT License 5 votes vote down vote up
private Description.Builder addCastToNonNullFix(Tree suggestTree, Description.Builder builder) {
  final String fullMethodName = config.getCastToNonNullMethod();
  assert fullMethodName != null;
  // Add a call to castToNonNull around suggestTree:
  final String[] parts = fullMethodName.split("\\.");
  final String shortMethodName = parts[parts.length - 1];
  final String replacement = shortMethodName + "(" + suggestTree.toString() + ")";
  final SuggestedFix fix =
      SuggestedFix.builder()
          .replace(suggestTree, replacement)
          .addStaticImport(fullMethodName) // ensure castToNonNull static import
          .build();
  return builder.addFix(fix);
}
 
Example 13
Source File: ErrorBuilder.java    From NullAway with MIT License 5 votes vote down vote up
void reportInitializerError(
    Symbol.MethodSymbol methodSymbol,
    String message,
    VisitorState state,
    Description.Builder descriptionBuilder) {
  if (symbolHasSuppressWarningsAnnotation(methodSymbol, INITIALIZATION_CHECK_NAME)) {
    return;
  }
  Tree methodTree = getTreesInstance(state).getTree(methodSymbol);
  state.reportMatch(
      createErrorDescription(
          new ErrorMessage(METHOD_NO_INIT, message), methodTree, descriptionBuilder, state));
}
 
Example 14
Source File: NullAway.java    From NullAway with MIT License 4 votes vote down vote up
@SuppressWarnings("unused")
private Description.Builder changeParamNullabilityFix(
    Tree suggestTree, Description.Builder builder) {
  return builder.addFix(SuggestedFix.prefixWith(suggestTree, "@Nullable "));
}
 
Example 15
Source File: ErrorBuilder.java    From NullAway with MIT License 4 votes vote down vote up
Description.Builder addSuppressWarningsFix(
    Tree suggestTree, Description.Builder builder, String suppressionName) {
  SuppressWarnings extantSuppressWarnings = null;
  Symbol treeSymbol = ASTHelpers.getSymbol(suggestTree);
  if (treeSymbol != null) {
    extantSuppressWarnings = treeSymbol.getAnnotation(SuppressWarnings.class);
  }
  SuggestedFix fix;
  if (extantSuppressWarnings == null) {
    fix =
        SuggestedFix.prefixWith(
            suggestTree,
            "@SuppressWarnings(\""
                + suppressionName
                + "\") "
                + config.getAutofixSuppressionComment());
  } else {
    // need to update the existing list of warnings
    final List<String> suppressions = Lists.newArrayList(extantSuppressWarnings.value());
    suppressions.add(suppressionName);
    // find the existing annotation, so we can replace it
    final ModifiersTree modifiers =
        (suggestTree instanceof MethodTree)
            ? ((MethodTree) suggestTree).getModifiers()
            : ((VariableTree) suggestTree).getModifiers();
    final List<? extends AnnotationTree> annotations = modifiers.getAnnotations();
    // noinspection ConstantConditions
    com.google.common.base.Optional<? extends AnnotationTree> suppressWarningsAnnot =
        Iterables.tryFind(
            annotations,
            annot -> annot.getAnnotationType().toString().endsWith("SuppressWarnings"));
    if (!suppressWarningsAnnot.isPresent()) {
      throw new AssertionError("something went horribly wrong");
    }
    final String replacement =
        "@SuppressWarnings({"
            + Joiner.on(',').join(Iterables.transform(suppressions, s -> '"' + s + '"'))
            + "}) "
            + config.getAutofixSuppressionComment();
    fix = SuggestedFix.replace(suppressWarningsAnnot.get(), replacement);
  }
  return builder.addFix(fix);
}
 
Example 16
Source File: XPFlagCleaner.java    From piranha with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("TreeToString")
@Override
public Description matchBinary(BinaryTree tree, VisitorState state) {
  if (overLaps(tree, state)) {
    return Description.NO_MATCH;
  }

  Value x = evalExpr(tree, state);
  Description d = updateCode(x, tree, tree, state);
  if (!d.equals(Description.NO_MATCH)) {
    return d;
  }

  ExpressionTree deletedSubTree = null;
  ExpressionTree remainingSubTree = null;
  Value l = evalExpr(tree.getLeftOperand(), state);
  Value r = evalExpr(tree.getRightOperand(), state);
  if (tree.getKind().equals(Kind.CONDITIONAL_AND)) {
    if (l.equals(Value.TRUE)) {
      deletedSubTree = tree.getLeftOperand();
      remainingSubTree = tree.getRightOperand();
    } else if (r.equals(Value.TRUE)) {
      deletedSubTree = tree.getRightOperand();
      remainingSubTree = tree.getLeftOperand();
    }
  } else if (tree.getKind().equals(Kind.CONDITIONAL_OR)) {
    if (l.equals(Value.FALSE)) {
      deletedSubTree = tree.getLeftOperand();
      remainingSubTree = tree.getRightOperand();
    } else if (r.equals(Value.FALSE)) {
      deletedSubTree = tree.getRightOperand();
      remainingSubTree = tree.getLeftOperand();
    }
  }

  if (deletedSubTree != null) {
    Preconditions.checkNotNull(
        remainingSubTree, "deletedSubTree != null => remainingSubTree !=null here.");
    Description.Builder builder = buildDescription(tree);
    SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
    fixBuilder.replace(tree, remainingSubTree.toString());
    decrementAllSymbolUsages(deletedSubTree, state, fixBuilder);
    builder.addFix(fixBuilder.build());

    endPos = state.getEndPosition(tree);
    return builder.build();
  }

  return Description.NO_MATCH;
}
 
Example 17
Source File: ErrorBuilder.java    From NullAway with MIT License 2 votes vote down vote up
/**
 * create an error description for a nullability warning
 *
 * @param errorMessage the error message object.
 * @param descriptionBuilder the description builder for the error.
 * @param state the visitor state (used for e.g. suppression finding).
 * @return the error description
 */
Description createErrorDescription(
    ErrorMessage errorMessage, Description.Builder descriptionBuilder, VisitorState state) {
  Tree enclosingSuppressTree = suppressibleNode(state.getPath());
  return createErrorDescription(errorMessage, enclosingSuppressTree, descriptionBuilder, state);
}