Skip to content

Downcasting (CastToNonNullMethod) does NOT propagate to the other occurrences of the same expression #1628

Description

@stechio

I noticed a discrepancy in the way NullAway handles java.util.Objects.requireNonNull versus CastToNonNullMethod:

  • once an expression is downcast to non-null via java.util.Objects.requireNonNull, NullAway applies its non-null status also to the other occurrences of the same expression downstream; for example, the following code fragment compiles successfully:

    if (java.util.Objects.requireNonNull(value.getToken()).contains("abc")) {
      int len = value.getToken().length();
      . . .
    }
  • on the contrary, downcasting the same expression with a custom method specified via -XepOpt:NullAway:CastToNonNullMethod option, NullAway does NOT apply its non-null status to the other occurrences of the same expression downstream, and emits false-positive warnings:

    if (my.package.MyUtils.castToNonNull(value.getToken()).contains("abc")) {
      int len = value.getToken().length(); // <-- FAILS HERE: "[NullAway] passing @Nullable parameter 'value.getToken()' where @NonNull is required"
      . . .
    }

    NOTE: I'm sure that NullAway is treating my.package.MyUtils.castToNonNull as a properly-specified CastToNonNullMethod, since it emits warnings if my.package.MyUtils.castToNonNull is invoked with a @NonNull argument:

    [NullAway] passing known @NonNull parameter 'value' to CastToNonNullMethod (my.package.MyUtils.castToNonNull) at position 0. This method argument should only take values that NullAway considers @Nullable at the invocation site, but which are known not to be null at runtime.
    

EXPECTED BEHAVIOR

NullAway should handle CastToNonNullMethod the same way as java.util.Objects.requireNonNull, applying the non-null status to the other occurrences of the same expression downstream.

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