Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

False positives when an expression is wrapped in parentheses or cast to its own type #1993

Closed

Description

@vlsi

Wrapping an expression in parentheses, or casting it to the type it already has, changes neither its value nor its nullness, so NullAway should report the same diagnostics with or without the wrapper. In every case below, the plain form compiles with no warning and the rewritten form gets one, so each warning is a false positive. They were found by a metamorphic harness that rewrites sources from NullAway's own test suite.

Versions

  • NullAway: master at 5ba2b54 (0.14.3-SNAPSHOT)
  • Error Prone: 2.50.0
  • JDK: Corretto 21.0.9
  • Options: legacy cases use -XepOpt:NullAway:AnnotatedPackages=com.uber; JSpecify cases (D) add -XepOpt:NullAway:JSpecifyMode=true and -XDaddTypeAnnotationsToSymbol=true

Each snippet below is one Test.java source passed to a helper built in a NullAwayTestsBase subclass:

  private CompilationTestHelper legacy() {
    return makeTestHelperWithArgs(List.of("-XepOpt:NullAway:AnnotatedPackages=com.uber"));
  }

  private CompilationTestHelper jspecify() {
    return makeTestHelperWithArgs(
        List.of(
            "-XepOpt:NullAway:AnnotatedPackages=com.uber",
            "-XepOpt:NullAway:JSpecifyMode=true",
            "-XDaddTypeAnnotationsToSymbol=true"));
  }

Every warning quoted below is the only one in its compilation; the plain methods produce none. Expected: no warning in any of these files.

A. A cast at the root of a checked expression hides it from dataflow (legacy)

package com.uber;
import javax.annotation.Nullable;
class Test {
  String plain(@Nullable Object o) {
    if (o != null) { return o.toString(); }
    return "";
  }
  String cast(@Nullable Object o) {
    if ((Object) o != null) { return o.toString(); }
    return "";
  }
}
/Test.java:9: warning: [NullAway] dereferenced expression 'o' is @Nullable
    if ((Object) o != null) { return o.toString(); }
                                      ^

The same happens when the cast operand is an argument that a contract, Preconditions.checkNotNull, or a map key refines:

package com.uber;
import javax.annotation.Nullable;
import org.jetbrains.annotations.Contract;
class Test {
  @Contract("null -> false")
  static boolean isNotNull(@Nullable Object o) { return o != null; }
  String plain(@Nullable Object o) {
    if (isNotNull(o)) { return o.toString(); }
    return "";
  }
  String cast(@Nullable Object o) {
    if (isNotNull((Object) o)) { return o.toString(); }
    return "";
  }
}
/Test.java:12: warning: [NullAway] dereferenced expression 'o' is @Nullable
    if (isNotNull((Object) o)) { return o.toString(); }
                                         ^
package com.uber;
import javax.annotation.Nullable;
import com.google.common.base.Preconditions;
class Test {
  int plain(@Nullable Integer i) {
    Preconditions.checkNotNull(i);
    return i;
  }
  int cast(@Nullable Integer i) {
    Preconditions.checkNotNull((Integer) i);
    return i;
  }
}
/Test.java:11: warning: [NullAway] unboxing of a @Nullable expression 'i'
    return i;
           ^
package com.uber;
import java.util.Map;
class Test {
  String plain(Map<String, Object> m, String k) {
    if (m.get(k) != null) { return m.get(k).toString(); }
    return "";
  }
  String cast(Map<String, Object> m, String k) {
    if (m.get((String) k) != null) { return m.get(k).toString(); }
    return "";
  }
}
/Test.java:9: warning: [NullAway] dereferenced expression 'm.get(k)' is @Nullable
    if (m.get((String) k) != null) { return m.get(k).toString(); }
                                                    ^

A cast around a boolean condition loses the condition's then and else facts:

package com.uber;
import javax.annotation.Nullable;
import com.uber.nullaway.annotations.EnsuresNonNullIf;
class Test {
  @Nullable Object item;
  @EnsuresNonNullIf("item")
  boolean plain() { return item != null; }
  @EnsuresNonNullIf("item")
  boolean cast() {
    return (boolean) (item != null);
  }
}
/Test.java:10: warning: [NullAway] Method is annotated with @EnsuresNonNullIf but does not ensure fields [item]
    return (boolean) (item != null);
    ^

Suspected location: AccessPath.getAccessPathForNode returns null for a TypeCastNode; stripCasts is applied only to receivers and array operands. Calling stripCasts on the node at the top of that method made the first four files compile cleanly. For the @EnsuresNonNullIf file, AccessPathNullnessPropagation.visitTypeCast returns noStoreChanges, which keeps only the regular store; passing the then and else stores through made it compile cleanly.

B. Parentheses break stream filter/map propagation (legacy)

package com.uber;
import javax.annotation.Nullable;
import java.util.stream.Stream;
class Test {
  static class B { @Nullable String v; @Nullable String get() { return v; } }
  Stream<Integer> plain(Stream<B> s) {
    return s.filter(b -> b.get() != null).map(b -> b.get().length());
  }
  Stream<Integer> filterParens(Stream<B> s) {
    return s.filter((b -> b.get() != null)).map(b -> b.get().length());
  }
  Stream<Integer> mapParens(Stream<B> s) {
    return s.filter(b -> b.get() != null).map((b -> b.get().length()));
  }
  Stream<Integer> receiverParens(Stream<B> s) {
    return (s.filter(b -> b.get() != null)).map(b -> b.get().length());
  }
}
/Test.java:10: warning: [NullAway] dereferenced expression 'b.get()' is @Nullable
    return s.filter((b -> b.get() != null)).map(b -> b.get().length());
                                                            ^
/Test.java:13: warning: [NullAway] dereferenced expression 'b.get()' is @Nullable
    return s.filter(b -> b.get() != null).map((b -> b.get().length()));
                                                           ^
/Test.java:16: warning: [NullAway] dereferenced expression 'b.get()' is @Nullable
    return (s.filter(b -> b.get() != null)).map(b -> b.get().length());
                                                            ^

Suspected location: StreamNullabilityPropagator tests the argument tree with instanceof LambdaExpressionTree / MemberReferenceTree without stripping parentheses in handleFilterMethod and handleMapMethod, and buildObservableCallChain tests the receiver with instanceof MethodInvocationTree. I did not patch these.

C. A parenthesized boolean literal in an @EnsuresNonNullIf method (legacy)

package com.uber;
import javax.annotation.Nullable;
import com.uber.nullaway.annotations.EnsuresNonNullIf;
class Test {
  @Nullable Object item;
  @EnsuresNonNullIf("item")
  boolean plain() {
    if (item != null) { return true; }
    return false;
  }
  @EnsuresNonNullIf("item")
  boolean parens() {
    if (item != null) { return (true); }
    return (false);
  }
}
/Test.java:14: warning: [NullAway] Method is annotated with @EnsuresNonNullIf but does not ensure fields [item]
    return (false);
    ^

Suspected location: EnsuresNonNullIfHandler.onDataflowVisitReturn checks returnTree.getExpression() instanceof LiteralTree, so (false) is not recognized as the literal that makes this return correct. I did not patch this.

D. A parenthesized lambda or method reference passed to unmarked code (JSpecify mode)

package com.uber;
import org.jspecify.annotations.Nullable;
import java.util.List;
class Test {
  static @Nullable String toNull(String s) { return null; }
  void plain(List<String> l) {
    l.stream().map(Test::toNull).forEach(s -> {});
  }
  void parens(List<String> l) {
    l.stream().map((Test::toNull)).forEach(s -> {});
  }
}
/Test.java:10: warning: [NullAway] referenced method returns @Nullable, but functional interface method java.util.function.Function.apply(String) returns @NonNull
    l.stream().map((Test::toNull)).forEach(s -> {});
                    ^
package com.uber;
import java.util.Map;
class Test {
  Object plain(Map<String, Object> m, String key) {
    return m.computeIfAbsent(key, k -> null);
  }
  Object parens(Map<String, Object> m, String key) {
    return m.computeIfAbsent(key, (k -> null));
  }
}
/Test.java:8: warning: [NullAway] returning @Nullable expression from method with @NonNull return type
    return m.computeIfAbsent(key, (k -> null));
                                   ^

Suspected location: GenericsChecks.passingLambdaOrMethodRefWithGenericReturnToUnmarkedCode takes the direct parent of the lambda or method reference and expects a MethodInvocationTree; with parentheses the parent is a ParenthesizedTree, so the call into unmarked JDK code is not recognized. Skipping ParenthesizedTree parents there made both files compile cleanly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions