com.google.errorprone.matchers.Description Java Examples

The following examples show how to use com.google.errorprone.matchers.Description. 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: 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 #2
Source File: XPFlagCleaner.java    From piranha with Apache License 2.0 6 votes vote down vote up
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
  Symbol sym = FindIdentifiers.findIdent(xpFlagName, state);
  // Check if this is the flag definition and remove it.
  if (sym != null && sym.isEnum() && sym.equals(ASTHelpers.getSymbol(tree))) {
    xpSym = sym;
    // Remove the flag symbol. This only works because the error prone patch is applied once
    // after all files have been analyzed, otherwise targets that use the flag but haven't been
    // cleaned up would be broken. We use replace with a position adjustment, to get rid of the
    // trailing "," if present on the parent.
    String enumAsStr = state.getSourceForNode(state.getPath().getParentPath().getLeaf());
    String varAsStrWithComma = tree.getName().toString() + ",";
    if (enumAsStr.contains(varAsStrWithComma)) {
      return buildDescription(tree).addFix(SuggestedFix.replace(tree, "", 0, 1)).build();
    } else {
      // Fallback for single/last enum variable detection
      return buildDescription(tree).addFix(SuggestedFix.delete(tree)).build();
    }
  } else if (sym == null
      && tree != null
      && ASTHelpers.getSymbol(tree) != null
      && xpFlagName.equals(ASTHelpers.getSymbol(tree).getConstantValue())) {
    return buildDescription(tree).addFix(SuggestedFix.delete(tree)).build();
  }
  return Description.NO_MATCH;
}
 
Example #3
Source File: NullAway.java    From NullAway with MIT License 6 votes vote down vote up
private Description checkReturnExpression(
    Tree tree, ExpressionTree retExpr, Symbol.MethodSymbol methodSymbol, VisitorState state) {
  Type returnType = methodSymbol.getReturnType();
  if (returnType.isPrimitive()) {
    // check for unboxing
    return doUnboxingCheck(state, retExpr);
  }
  if (returnType.toString().equals("java.lang.Void")) {
    return Description.NO_MATCH;
  }
  if (NullabilityUtil.isUnannotated(methodSymbol, config)
      || Nullness.hasNullableAnnotation(methodSymbol, config)) {
    return Description.NO_MATCH;
  }
  if (mayBeNullExpr(state, retExpr)) {
    final ErrorMessage errorMessage =
        new ErrorMessage(
            MessageTypes.RETURN_NULLABLE,
            "returning @Nullable expression from method with @NonNull return type");

    return errorBuilder.createErrorDescriptionForNullAssignment(
        errorMessage, retExpr, buildDescription(tree), state);
  }
  return Description.NO_MATCH;
}
 
Example #4
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 #5
Source File: NullAway.java    From NullAway with MIT License 6 votes vote down vote up
@Override
public Description matchSwitch(SwitchTree tree, VisitorState state) {
  if (!matchWithinClass) {
    return Description.NO_MATCH;
  }

  ExpressionTree switchExpression = tree.getExpression();
  if (switchExpression instanceof ParenthesizedTree) {
    switchExpression = ((ParenthesizedTree) switchExpression).getExpression();
  }

  if (mayBeNullExpr(state, switchExpression)) {
    final String message =
        "switch expression " + state.getSourceForNode(switchExpression) + " is @Nullable";
    ErrorMessage errorMessage =
        new ErrorMessage(MessageTypes.SWITCH_EXPRESSION_NULLABLE, message);

    return errorBuilder.createErrorDescription(
        errorMessage, switchExpression, buildDescription(switchExpression), state);
  }

  return Description.NO_MATCH;
}
 
Example #6
Source File: AnnotationChecker.java    From grpc-java-api-checker with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the description if tree is annotated.
 */
private Description match(Tree tree, VisitorState state) {
  Symbol symbol = ASTHelpers.getSymbol(tree);
  if (symbol == null) {
    return NO_MATCH;
  }
  AnnotationMirror annotation = findAnnotatedApi(symbol);
  if (annotation == null) {
    return NO_MATCH;
  }
  if (requireAnnotationOnMethodHierarchy && symbol instanceof MethodSymbol) {
    Set<MethodSymbol> superMethods =
            ASTHelpers.findSuperMethods((MethodSymbol) symbol, state.getTypes());
    for (MethodSymbol superMethod : superMethods) {
      AnnotationMirror superAnnotation = findAnnotatedApi(superMethod);
      if (superAnnotation == null) {
        return NO_MATCH;
      }
    }
  }
  return describe(tree, annotation);
}
 
Example #7
Source File: NullAway.java    From NullAway with MIT License 6 votes vote down vote up
private Description checkPossibleUninitFieldRead(
    ExpressionTree tree,
    VisitorState state,
    Symbol symbol,
    TreePath path,
    TreePath enclosingBlockPath) {
  if (!fieldInitializedByPreviousInitializer(symbol, enclosingBlockPath, state)
      && !fieldAlwaysInitializedBeforeRead(symbol, path, state, enclosingBlockPath)) {
    ErrorMessage errorMessage =
        new ErrorMessage(
            MessageTypes.NONNULL_FIELD_READ_BEFORE_INIT,
            "read of @NonNull field " + symbol + " before initialization");
    return errorBuilder.createErrorDescription(errorMessage, buildDescription(tree), state);
  } else {
    return Description.NO_MATCH;
  }
}
 
Example #8
Source File: NullAway.java    From NullAway with MIT License 6 votes vote down vote up
@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
  if (!matchWithinClass) {
    return Description.NO_MATCH;
  }
  // if the method is overriding some other method,
  // check that nullability annotations are consistent with
  // overridden method (if overridden method is in an annotated
  // package)
  Symbol.MethodSymbol methodSymbol = ASTHelpers.getSymbol(tree);
  handler.onMatchMethod(this, tree, state, methodSymbol);
  boolean isOverriding = ASTHelpers.hasAnnotation(methodSymbol, Override.class, state);
  boolean exhaustiveOverride = config.exhaustiveOverride();
  if (isOverriding || !exhaustiveOverride) {
    Symbol.MethodSymbol closestOverriddenMethod =
        getClosestOverriddenMethod(methodSymbol, state.getTypes());
    if (closestOverriddenMethod != null) {
      return checkOverriding(closestOverriddenMethod, methodSymbol, null, state);
    }
  }
  return Description.NO_MATCH;
}
 
Example #9
Source File: NullAway.java    From NullAway with MIT License 6 votes vote down vote up
@Override
public Description matchMemberSelect(MemberSelectTree tree, VisitorState state) {
  if (!matchWithinClass) {
    return Description.NO_MATCH;
  }
  Symbol symbol = ASTHelpers.getSymbol(tree);
  // some checks for cases where we know it is not
  // a null dereference
  if (symbol == null || symbol.getSimpleName().toString().equals("class") || symbol.isEnum()) {
    return Description.NO_MATCH;
  }

  Description badDeref = matchDereference(tree.getExpression(), tree, state);
  if (!badDeref.equals(Description.NO_MATCH)) {
    return badDeref;
  }
  // if we're accessing a field of this, make sure we're not reading the field before init
  if (tree.getExpression() instanceof IdentifierTree
      && ((IdentifierTree) tree.getExpression()).getName().toString().equals("this")) {
    return checkForReadBeforeInit(tree, state);
  }
  return Description.NO_MATCH;
}
 
Example #10
Source File: XPFlagCleaner.java    From piranha with Apache License 2.0 6 votes vote down vote up
@Override
public Description matchClass(ClassTree classTree, VisitorState visitorState) {
  Symbol.ClassSymbol classSymbol = ASTHelpers.getSymbol(classTree);
  if (classSymbol.getKind().equals(ElementKind.ENUM) && isTreatmentGroupEnum(classSymbol)) {
    treatmentGroupsEnum = classSymbol.fullname.toString();
    if (classSymbol.getNestingKind().isNested()) {
      return buildDescription(classTree).addFix(SuggestedFix.delete(classTree)).build();
    } else {
      String emptyEnum =
          PiranhaUtils.DELETE_REQUEST_COMMENT
              + "enum "
              + classSymbol.getSimpleName().toString()
              + " { }";
      return buildDescription(classTree)
          .addFix(SuggestedFix.replace(classTree, emptyEnum))
          .build();
    }
  }
  return Description.NO_MATCH;
}
 
Example #11
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 #12
Source File: XPFlagCleaner.java    From piranha with Apache License 2.0 6 votes vote down vote up
@Override
public Description matchCompilationUnit(
    CompilationUnitTree compilationUnitTree, VisitorState visitorState) {
  if (!initialized && !disabled) {
    Preconditions.checkNotNull(
        flags,
        "The configuration-aware constructor should have been called at this point, and flags set to "
            + "a non-null value.");
    try {
      init(flags);
    } catch (PiranhaConfigurationException pe) {
      disabled = true;
    }
  }
  if (countsCollected) {
    // Clear out this info
    countsCollected = false;
    usageCounts = null;
    deletedUsages = null;
  }
  cuPath = visitorState.getPath();
  return Description.NO_MATCH;
}
 
Example #13
Source File: ProtobufCheck.java    From startup-os with Apache License 2.0 6 votes vote down vote up
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {

  // check whether it's a newBuilder() method of any protobuf-generated message class
  if (NEW_BUILDER.matches(tree, state)) {
    // find next method invocation in chain (on obj.method1().method2() it would return method2)
    ExpressionTree methodInvocation =
        ASTHelpers.findEnclosingNode(state.getPath(), MethodInvocationTree.class);
    // next invoked message is a build() method of any protobuf-generated message builder class
    if (BUILDER_BUILD.matches(methodInvocation, state)) {

      // select "newBuilder().build()" part of tree
      int start = state.getEndPosition(tree) - "newBuilder()".length();
      int end = state.getEndPosition(methodInvocation);

      // suggest to replace it with "getDefaultInstance()"
      return describeMatch(
          methodInvocation,
          SuggestedFix.builder().replace(start, end, "getDefaultInstance()").build());
    }
  }
  return NO_MATCH;
}
 
Example #14
Source File: NullAway.java    From NullAway with MIT License 6 votes vote down vote up
@Override
public Description matchBinary(BinaryTree tree, VisitorState state) {
  if (!matchWithinClass) {
    return Description.NO_MATCH;
  }
  ExpressionTree leftOperand = tree.getLeftOperand();
  ExpressionTree rightOperand = tree.getRightOperand();
  Type leftType = ASTHelpers.getType(leftOperand);
  Type rightType = ASTHelpers.getType(rightOperand);
  if (leftType == null || rightType == null) {
    throw new RuntimeException();
  }
  if (leftType.isPrimitive() && !rightType.isPrimitive()) {
    return doUnboxingCheck(state, rightOperand);
  }
  if (rightType.isPrimitive() && !leftType.isPrimitive()) {
    return doUnboxingCheck(state, leftOperand);
  }
  return Description.NO_MATCH;
}
 
Example #15
Source File: DescriptionBasedDiffTest.java    From Refaster with Apache License 2.0 6 votes vote down vote up
@Test
public void addImport() {
  DescriptionBasedDiff diff = DescriptionBasedDiff.create(compilationUnit);
  diff.onDescribed(new Description(null, "message", 
      SuggestedFix.builder().addImport("com.google.foo.Bar").build(),
      SeverityLevel.NOT_A_PROBLEM));
  diff.applyDifferences(sourceFile);
  assertThat(sourceFile.getLines()).iteratesAs(
      "package foo.bar;",
      "",
      "import com.google.foo.Bar;",
      "class Foo {",
      "  public static void main(String[] args) {",
      "    System.out.println(\"foo\");",
      "  }", 
      "}");
}
 
Example #16
Source File: DescriptionBasedDiffTest.java    From Refaster with Apache License 2.0 6 votes vote down vote up
@Test
public void twoDiffsWithImport() {
  DescriptionBasedDiff diff = DescriptionBasedDiff.create(compilationUnit);
  diff.onDescribed(new Description(null, "message", 
      SuggestedFix.builder()
          .replace(83, 86, "longer")
          .replace(96, 99, "bar")
          .addImport("com.google.foo.Bar")
          .build(),
      SeverityLevel.NOT_A_PROBLEM));
  diff.applyDifferences(sourceFile);
  assertThat(sourceFile.getLines()).iteratesAs(
      "package foo.bar;",
      "",
      "import com.google.foo.Bar;",
      "class Foo {",
      "  public static void main(String[] args) {",
      "    System.longer.println(\"bar\");",
      "  }", 
      "}");
}
 
Example #17
Source File: NullAway.java    From NullAway with MIT License 6 votes vote down vote up
@Override
public Description matchNewClass(NewClassTree tree, VisitorState state) {
  if (!matchWithinClass) {
    return Description.NO_MATCH;
  }
  Symbol.MethodSymbol methodSymbol = ASTHelpers.getSymbol(tree);
  if (methodSymbol == null) {
    throw new RuntimeException("not expecting unresolved method here");
  }
  List<? extends ExpressionTree> actualParams = tree.getArguments();
  if (tree.getClassBody() != null && actualParams.size() > 0) {
    // passing parameters to constructor of anonymous class
    // this constructor just invokes the constructor of the superclass, and
    // in the AST does not have the parameter nullability annotations from the superclass.
    // so, treat as if the superclass constructor is being invoked directly
    // see https://github.com/uber/NullAway/issues/102
    methodSymbol = getSymbolOfSuperConstructor(methodSymbol, state);
  }
  return handleInvocation(tree, state, methodSymbol, actualParams);
}
 
Example #18
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 #19
Source File: DescriptionBasedDiffTest.java    From Refaster with Apache License 2.0 6 votes vote down vote up
@Test
public void twoDiffs() {
  DescriptionBasedDiff diff = DescriptionBasedDiff.create(compilationUnit);
  diff.onDescribed(new Description(null, "message", 
      SuggestedFix.builder()
          .replace(83, 86, "longer")
          .replace(96, 99, "bar")
          .build(),
      SeverityLevel.NOT_A_PROBLEM));
  diff.applyDifferences(sourceFile);
  assertThat(sourceFile.getLines()).iteratesAs(
      "package foo.bar;",
      "class Foo {",
      "  public static void main(String[] args) {",
      "    System.longer.println(\"bar\");",
      "  }", 
      "}");
}
 
Example #20
Source File: NullAway.java    From NullAway with MIT License 6 votes vote down vote up
/**
 * if any expression has non-primitive type, we should check that it can't be null as it is
 * getting unboxed
 *
 * @param expressions expressions to check
 * @return error Description if an error is found, otherwise NO_MATCH
 */
private Description doUnboxingCheck(VisitorState state, ExpressionTree... expressions) {
  for (ExpressionTree tree : expressions) {
    Type type = ASTHelpers.getType(tree);
    if (type == null) {
      throw new RuntimeException("was not expecting null type");
    }
    if (!type.isPrimitive()) {
      if (mayBeNullExpr(state, tree)) {
        final ErrorMessage errorMessage =
            new ErrorMessage(MessageTypes.UNBOX_NULLABLE, "unboxing of a @Nullable value");
        return errorBuilder.createErrorDescription(errorMessage, buildDescription(tree), state);
      }
    }
  }
  return Description.NO_MATCH;
}
 
Example #21
Source File: PrivateStaticFinalLoggers.java    From besu with Apache License 2.0 6 votes vote down vote up
@Override
public Description matchVariable(final VariableTree tree, final VisitorState state) {
  final Symbol.VarSymbol sym = ASTHelpers.getSymbol(tree);
  if (sym == null || sym.getKind() != ElementKind.FIELD) {
    return NO_MATCH;
  }
  if (sym.getModifiers()
      .containsAll(List.of(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL))) {
    return NO_MATCH;
  }
  if (!isSubtype(
      getType(tree), state.getTypeFromString("org.apache.logging.log4j.Logger"), state)) {
    return NO_MATCH;
  }
  return buildDescription(tree)
      .addFix(addModifiers(tree, state, Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL))
      .build();
}
 
Example #22
Source File: RefasterScanner.java    From Refaster with Apache License 2.0 6 votes vote down vote up
@Override
public Void scan(Tree tree, Context context) {
  if (tree == null) {
    return null;
  }
  JCCompilationUnit compilationUnit = context.get(JCCompilationUnit.class);
  for (T beforeTemplate : rule().beforeTemplates()) {
    for (M match : beforeTemplate.match((JCTree) tree, context)) {
      if (rule().rejectMatchesWithComments()) {
        String matchContents = match.getRange(compilationUnit);
        if (matchContents.contains("//") || matchContents.contains("/*")) {
          continue;
        }
      }
      Fix fix;
      if (rule().afterTemplate() == null) {
        fix = SuggestedFix.delete(match.getLocation());
      } else {
        fix = rule().afterTemplate().replace(match);
      }
      listener().onDescribed(new Description(
          match.getLocation(), rule().qualifiedTemplateClass(), fix, SeverityLevel.WARNING));
    }
  }
  return super.scan(tree, context);
}
 
Example #23
Source File: NullAway.java    From NullAway with MIT License 5 votes vote down vote up
@Override
public Description matchCompoundAssignment(CompoundAssignmentTree tree, VisitorState state) {
  if (!matchWithinClass) {
    return Description.NO_MATCH;
  }
  Type lhsType = ASTHelpers.getType(tree.getVariable());
  Type stringType = state.getTypeFromString("java.lang.String");
  if (lhsType != null && !state.getTypes().isSameType(lhsType, stringType)) {
    // both LHS and RHS could get unboxed
    return doUnboxingCheck(state, tree.getVariable(), tree.getExpression());
  }
  return Description.NO_MATCH;
}
 
Example #24
Source File: NullAway.java    From NullAway with MIT License 5 votes vote down vote up
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
  if (!matchWithinClass) {
    return Description.NO_MATCH;
  }
  final Symbol.MethodSymbol methodSymbol = ASTHelpers.getSymbol(tree);
  if (methodSymbol == null) {
    throw new RuntimeException("not expecting unresolved method here");
  }
  handler.onMatchMethodInvocation(this, tree, state, methodSymbol);
  // assuming this list does not include the receiver
  List<? extends ExpressionTree> actualParams = tree.getArguments();
  return handleInvocation(tree, state, methodSymbol, actualParams);
}
 
Example #25
Source File: NullAway.java    From NullAway with MIT License 5 votes vote down vote up
/**
 * We are trying to see if (1) we are in a method guaranteed to return something non-null, and (2)
 * this return statement can return something null.
 */
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
  if (!matchWithinClass) {
    return Description.NO_MATCH;
  }
  handler.onMatchReturn(this, tree, state);
  ExpressionTree retExpr = tree.getExpression();
  // let's do quick checks on returned expression first
  if (retExpr == null) {
    return Description.NO_MATCH;
  }
  // now let's check the enclosing method
  TreePath enclosingMethodOrLambda =
      NullabilityUtil.findEnclosingMethodOrLambdaOrInitializer(state.getPath());
  if (enclosingMethodOrLambda == null) {
    throw new RuntimeException("no enclosing method, lambda or initializer!");
  }
  if (!(enclosingMethodOrLambda.getLeaf() instanceof MethodTree
      || enclosingMethodOrLambda.getLeaf() instanceof LambdaExpressionTree)) {
    throw new RuntimeException(
        "return statement outside of a method or lambda! (e.g. in an initializer block)");
  }
  Tree leaf = enclosingMethodOrLambda.getLeaf();
  Symbol.MethodSymbol methodSymbol;
  if (leaf instanceof MethodTree) {
    MethodTree enclosingMethod = (MethodTree) leaf;
    methodSymbol = ASTHelpers.getSymbol(enclosingMethod);
  } else {
    // we have a lambda
    methodSymbol =
        NullabilityUtil.getFunctionalInterfaceMethod(
            (LambdaExpressionTree) leaf, state.getTypes());
  }
  return checkReturnExpression(tree, retExpr, methodSymbol, state);
}
 
Example #26
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 #27
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 #28
Source File: NullAway.java    From NullAway with MIT License 5 votes vote down vote up
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
  if (!matchWithinClass) {
    return Description.NO_MATCH;
  }
  VarSymbol symbol = ASTHelpers.getSymbol(tree);
  if (symbol.type.isPrimitive() && tree.getInitializer() != null) {
    return doUnboxingCheck(state, tree.getInitializer());
  }
  if (!symbol.getKind().equals(ElementKind.FIELD)) {
    return Description.NO_MATCH;
  }
  ExpressionTree initializer = tree.getInitializer();
  if (initializer != null) {
    if (!symbol.type.isPrimitive() && !skipDueToFieldAnnotation(symbol)) {
      if (mayBeNullExpr(state, initializer)) {
        final ErrorMessage errorMessage =
            new ErrorMessage(
                MessageTypes.ASSIGN_FIELD_NULLABLE,
                "assigning @Nullable expression to @NonNull field");
        return errorBuilder.createErrorDescriptionForNullAssignment(
            errorMessage, initializer, buildDescription(tree), state);
      }
    }
  }
  return Description.NO_MATCH;
}
 
Example #29
Source File: NullAway.java    From NullAway with MIT License 5 votes vote down vote up
@Override
public Description matchForLoop(ForLoopTree tree, VisitorState state) {
  if (!matchWithinClass) {
    return Description.NO_MATCH;
  }
  if (tree.getCondition() != null) {
    return doUnboxingCheck(state, tree.getCondition());
  }
  return Description.NO_MATCH;
}
 
Example #30
Source File: NullAway.java    From NullAway with MIT License 5 votes vote down vote up
@Override
public Description matchEnhancedForLoop(EnhancedForLoopTree tree, VisitorState state) {
  if (!matchWithinClass) {
    return Description.NO_MATCH;
  }
  ExpressionTree expr = tree.getExpression();
  final ErrorMessage errorMessage =
      new ErrorMessage(
          MessageTypes.DEREFERENCE_NULLABLE,
          "enhanced-for expression " + state.getSourceForNode(expr) + " is @Nullable");
  if (mayBeNullExpr(state, expr)) {
    return errorBuilder.createErrorDescription(errorMessage, buildDescription(expr), state);
  }
  return Description.NO_MATCH;
}