diff --git a/nullaway/src/main/java/com/uber/nullaway/NullAway.java b/nullaway/src/main/java/com/uber/nullaway/NullAway.java index cdc0b25780..9d3fce9d80 100644 --- a/nullaway/src/main/java/com/uber/nullaway/NullAway.java +++ b/nullaway/src/main/java/com/uber/nullaway/NullAway.java @@ -579,6 +579,9 @@ public Description matchAssignment(AssignmentTree tree, VisitorState state) { } ExpressionTree expression = tree.getExpression(); if (mayBeNullExpr(state, expression)) { + if (safeAssignmentOfNullableToMonotonicNonNullField(tree, state, assigned)) { + return Description.NO_MATCH; + } String message = "assigning @Nullable expression to @NonNull field"; return errorBuilder.createErrorDescriptionForNullAssignment( new ErrorMessage(MessageTypes.ASSIGN_FIELD_NULLABLE, message), @@ -591,6 +594,82 @@ public Description matchAssignment(AssignmentTree tree, VisitorState state) { return Description.NO_MATCH; } + /** + * Check for a special case where we allow assignment of a nullable expression to a + * monotonic-nonnull instance field within a constructor of the enclosing class, when we can prove + * that the field was not known to be non-null before the assignment. In particular, the field + * declaration cannot have an initializer expression, and there cannot be any instance initializer + * blocks in the class. + * + * @param tree the assignment tree + * @param state the visitor state + * @param assigned the field being assigned to + * @return true if this is a safe assignment that we should not warn on + */ + private boolean safeAssignmentOfNullableToMonotonicNonNullField( + AssignmentTree tree, VisitorState state, Symbol assigned) { + return assigned instanceof VarSymbol + && Nullness.hasMonotonicNonNullAnnotation(assigned, config) + && assignmentTargetsEnclosingInstanceField(tree.getVariable()) + && inConstructorOfClassWithNoInitializerOfField(assigned, state.getPath()) + && !fieldKnownNonNullBeforeAssignment((VarSymbol) assigned, tree.getVariable(), state); + } + + private boolean assignmentTargetsEnclosingInstanceField(ExpressionTree variableTree) { + if (variableTree instanceof IdentifierTree) { + return true; + } + if (variableTree instanceof MemberSelectTree) { + ExpressionTree receiver = ((MemberSelectTree) variableTree).getExpression(); + return receiver instanceof IdentifierTree + && ((IdentifierTree) receiver).getName().contentEquals("this"); + } + return false; + } + + private boolean fieldKnownNonNullBeforeAssignment( + Symbol.VarSymbol fieldSymbol, ExpressionTree variableTree, VisitorState state) { + TreePath currentPath = state.getPath(); + if (currentPath == null) { + return false; + } + TreePath variablePath = new TreePath(currentPath, variableTree); + Nullness fieldNullness = + getNullnessAnalysis(state) + .getNullnessOfExpressionNamedField(variablePath, state.context, fieldSymbol); + return fieldNullness == Nullness.NONNULL; + } + + /** + * Check if we are in a constructor of the class that declares the given field, and that class has + * no instance initializer blocks and the field has no initializer expression. + * + * @param fieldSymbol the field symbol + * @param path the current tree path + * @return true if we are in such a constructor, false otherwise + */ + private boolean inConstructorOfClassWithNoInitializerOfField(Symbol fieldSymbol, TreePath path) { + for (TreePath current = path; current != null; current = current.getParentPath()) { + Tree leaf = current.getLeaf(); + if (leaf instanceof MethodTree) { + MethodTree methodTree = (MethodTree) leaf; + if (isConstructor(methodTree)) { + // check that class has no instance initializer blocks and no initializer expression for + // the field + ClassSymbol enclClass = ASTHelpers.getSymbol(methodTree).enclClass(); + FieldInitEntities fieldInitEntities = class2Entities.get(enclClass); + return fieldInitEntities != null + && fieldInitEntities.instanceInitializerBlocks().isEmpty() + && fieldInitEntities.uninitMonotonicNonNullInstanceFields().contains(fieldSymbol); + } + } + if (leaf instanceof ClassTree) { + return false; + } + } + return false; + } + @Override public Description matchCompoundAssignment(CompoundAssignmentTree tree, VisitorState state) { if (!withinAnnotatedCode(state)) { @@ -2441,6 +2520,7 @@ private FieldInitEntities collectEntities(ClassTree tree, VisitorState state) { Symbol.ClassSymbol classSymbol = ASTHelpers.getSymbol(tree); Set nonnullInstanceFields = new LinkedHashSet<>(); Set nonnullStaticFields = new LinkedHashSet<>(); + Set uninitMonotonicNonNullInstanceFields = new LinkedHashSet<>(); List instanceInitializerBlocks = new ArrayList<>(); List staticInitializerBlocks = new ArrayList<>(); Set constructors = new LinkedHashSet<>(); @@ -2472,6 +2552,10 @@ private FieldInitEntities collectEntities(ClassTree tree, VisitorState state) { // field declaration VariableTree varTree = (VariableTree) memberTree; Symbol fieldSymbol = ASTHelpers.getSymbol(varTree); + if (Nullness.hasMonotonicNonNullAnnotation(fieldSymbol, config) + && varTree.getInitializer() == null) { + uninitMonotonicNonNullInstanceFields.add(fieldSymbol); + } if (fieldSymbol.type.isPrimitive() || skipFieldInitializationCheckingDueToAnnotation(fieldSymbol)) { continue; @@ -2506,6 +2590,7 @@ private FieldInitEntities collectEntities(ClassTree tree, VisitorState state) { classSymbol, ImmutableSet.copyOf(nonnullInstanceFields), ImmutableSet.copyOf(nonnullStaticFields), + ImmutableSet.copyOf(uninitMonotonicNonNullInstanceFields), ImmutableList.copyOf(instanceInitializerBlocks), ImmutableList.copyOf(staticInitializerBlocks), ImmutableSet.copyOf(constructors), @@ -2851,6 +2936,7 @@ static FieldInitEntities create( Symbol.ClassSymbol classSymbol, Set nonnullInstanceFields, Set nonnullStaticFields, + Set uninitMonotonicNonNullInstanceFields, List instanceInitializerBlocks, List staticInitializerBlocks, Set constructors, @@ -2860,6 +2946,7 @@ static FieldInitEntities create( classSymbol, ImmutableSet.copyOf(nonnullInstanceFields), ImmutableSet.copyOf(nonnullStaticFields), + ImmutableSet.copyOf(uninitMonotonicNonNullInstanceFields), ImmutableList.copyOf(instanceInitializerBlocks), ImmutableList.copyOf(staticInitializerBlocks), ImmutableSet.copyOf(constructors), @@ -2881,6 +2968,9 @@ static FieldInitEntities create( */ abstract ImmutableSet nonnullStaticFields(); + /** {@code @MonotonicNonNull} instance fields with no initializer expression at declaration */ + abstract ImmutableSet uninitMonotonicNonNullInstanceFields(); + /** * Returns the list of instance initializer blocks (e.g. blocks of the form `class X { { //Code * } } ), in the order in which they appear in the class. diff --git a/nullaway/src/main/java/com/uber/nullaway/Nullness.java b/nullaway/src/main/java/com/uber/nullaway/Nullness.java index 3190ed6cdb..2a11e3c998 100644 --- a/nullaway/src/main/java/com/uber/nullaway/Nullness.java +++ b/nullaway/src/main/java/com/uber/nullaway/Nullness.java @@ -79,6 +79,19 @@ private static boolean hasNullableOrMonotonicNonNullAnnotation( .anyMatch(anno -> isNullableAnnotation(anno, config) || isMonotonicNonNullAnnotation(anno)); } + /** + * Check whether {@code symbol} has a {@code @MonotonicNonNull} annotation. + * + * @param symbol symbol to inspect for annotations + * @param config NullAway config to resolve type-use annotations + * @return true if the symbol is annotated with {@code @MonotonicNonNull} + */ + public static boolean hasMonotonicNonNullAnnotation(Symbol symbol, Config config) { + return NullabilityUtil.getAllAnnotations(symbol, config) + .map(anno -> anno.getAnnotationType().toString()) + .anyMatch(Nullness::isMonotonicNonNullAnnotation); + } + // The following leastUpperBound and greatestLowerBound methods were created by handwriting a // truth table and then encoding the values into these functions. A better approach would be to // represent the lattice directly and compute these functions from the lattice. diff --git a/nullaway/src/test/java/com/uber/nullaway/MonotonicNonNullTests.java b/nullaway/src/test/java/com/uber/nullaway/MonotonicNonNullTests.java index 0591c4a296..a531103357 100644 --- a/nullaway/src/test/java/com/uber/nullaway/MonotonicNonNullTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/MonotonicNonNullTests.java @@ -42,6 +42,77 @@ public void assignments() { .doTest(); } + @Test + public void nullableAssignmentInConstructor() { + defaultCompilationHelper + .addSourceLines( + "Test.java", + "package com.uber;", + "import com.uber.nullaway.annotations.MonotonicNonNull;", + "import org.jspecify.annotations.NullMarked;", + "import org.jspecify.annotations.Nullable;", + "@NullMarked", + "class Test {", + " @MonotonicNonNull Object mBar;", + " Test() {", + " mBar = null;", + " }", + " Test(boolean b) {", + " mBar = new Object();", + " // now not allowed!", + " // BUG: Diagnostic contains: assigning @Nullable expression to @NonNull field", + " mBar = null;", + " }", + "}") + .doTest(); + } + + @Test + public void nullableAssignmentInConstructorWithInstanceInitializer() { + defaultCompilationHelper + .addSourceLines( + "Test.java", + "package com.uber;", + "import com.uber.nullaway.annotations.MonotonicNonNull;", + "import org.jspecify.annotations.NullMarked;", + "import org.jspecify.annotations.Nullable;", + "@NullMarked", + "class Test {", + " @MonotonicNonNull Object mBar;", + " { mBar = new Object(); }", + " @Nullable Object maybeNull() {", + " return null;", + " }", + " Test() {", + " // not allowed since enclosing class has an instance initializer block", + " // BUG: Diagnostic contains: assigning @Nullable expression to @NonNull field", + " mBar = maybeNull();", + " }", + "}") + .doTest(); + } + + @Test + public void nullableAssignmentInConstructorWithInitializerExpression() { + defaultCompilationHelper + .addSourceLines( + "Test.java", + "package com.uber;", + "import com.uber.nullaway.annotations.MonotonicNonNull;", + "import org.jspecify.annotations.NullMarked;", + "import org.jspecify.annotations.Nullable;", + "@NullMarked", + "class Test {", + " @MonotonicNonNull Object mBar = new Object();", + " Test() {", + " // not allowed since field already initialized", + " // BUG: Diagnostic contains: assigning @Nullable expression to @NonNull field", + " mBar = null;", + " }", + "}") + .doTest(); + } + @Test public void lambdas() { defaultCompilationHelper