diff --git a/.github/workflows/continuous-integration.yml b/.github/workflows/continuous-integration.yml
index 4f14afd79a..8a2aede82b 100644
--- a/.github/workflows/continuous-integration.yml
+++ b/.github/workflows/continuous-integration.yml
@@ -179,7 +179,7 @@ jobs:
- project: calcite
url: https://github.com/apache/calcite.git
branch: main
- sha: 713faf069e246f3430ae23ead1f90430c672cc15
+ sha: dde58eb5a30f245f975d55f88ce2e861a1e82668
build: JAVA_HOME="$JAVA_HOME_21_X64" ./gradlew --init-script use-snapshot.gradle.kts -PenableErrorprone classes jmhClasses
permissions:
contents: read
diff --git a/nullaway/src/main/java/com/uber/nullaway/Config.java b/nullaway/src/main/java/com/uber/nullaway/Config.java
index 5a3235e33c..2a7855d109 100644
--- a/nullaway/src/main/java/com/uber/nullaway/Config.java
+++ b/nullaway/src/main/java/com/uber/nullaway/Config.java
@@ -315,6 +315,38 @@ public interface Config {
/** Should PolyNull library models be enabled? */
boolean isPolyNullLibraryModelsEnabled();
+ /**
+ * Should generic inference account for the nullness of an unannotated type variable, a capture
+ * included, whose bound admits null, and read a declared bound {@code U extends R} between two
+ * type variables of a call as {@code U <: R}? True where both JSpecifyMode and
+ * JSpecifyExperimental are set. Where it is false, every inference variable that no constraint
+ * fixes is {@code @NonNull}, and the checks of a generic constructor at a diamond and of a
+ * generic method reference use the declared types.
+ *
+ *
Where it is true, an inference variable that no constraint fixes and that such a type
+ * variable flows into is {@link
+ * com.uber.nullaway.generics.ConstraintSolver.InferredNullability#TYPE_VARIABLE_OR_NULLABLE}
+ * where the bounds of both that type variable and the inference variable are explicitly nullable,
+ * and {@link
+ * com.uber.nullaway.generics.ConstraintSolver.InferredNullability#TYPE_VARIABLE_OR_NONNULL}
+ * otherwise. {@code GenericsUtils.typeVariableWithNullableBound} decides which bounds are
+ * explicitly nullable. With HandleWildcardGenerics also set, inference fails where an uncaptured
+ * type variable whose bound is explicitly nullable is passed for {@code ? extends U} and the
+ * bound of {@code U} excludes null. A generic constructor at a diamond and a generic method
+ * reference are checked against the types javac inferred for them.
+ *
+ *
Where it is true, inference also reads a declared bound {@code U extends R} between two type
+ * variables of one call, where the use of {@code R} carries no nullness annotation, as {@code U
+ * <: R}, and follows a chain of such bounds. {@code @Nullable} and the flow of an unannotated
+ * type variable whose bound admits null pass from {@code U} to {@code R}, and {@code @NonNull}
+ * passes from {@code R} to {@code U}. So {@code viaBoundOne(null).hashCode()} with {@code R viaBoundOne(U u)} is reported, though no type variable
+ * whose bound admits null is passed. Inference reads no {@code U <: R} where the declaration of
+ * {@code U} makes its bound nullable: where a library model does so, or where {@code U} is
+ * declared in unannotated code.
+ */
+ boolean isNullableBoundInferenceEnabled();
+
/**
* Should wildcard-aware generic nullability checks be enabled? These also compute {@link
* Nullness#NO_CHANGE} for the values listed there, such as the result of {@code Box extends
diff --git a/nullaway/src/main/java/com/uber/nullaway/DummyOptionsConfig.java b/nullaway/src/main/java/com/uber/nullaway/DummyOptionsConfig.java
index f654c645e1..8e23628168 100644
--- a/nullaway/src/main/java/com/uber/nullaway/DummyOptionsConfig.java
+++ b/nullaway/src/main/java/com/uber/nullaway/DummyOptionsConfig.java
@@ -229,6 +229,11 @@ public boolean isPolyNullLibraryModelsEnabled() {
throw new IllegalStateException(ERROR_MESSAGE);
}
+ @Override
+ public boolean isNullableBoundInferenceEnabled() {
+ throw new IllegalStateException(ERROR_MESSAGE);
+ }
+
@Override
public boolean handleWildcardGenerics() {
throw new IllegalStateException(ERROR_MESSAGE);
diff --git a/nullaway/src/main/java/com/uber/nullaway/ErrorProneCLIFlagsConfig.java b/nullaway/src/main/java/com/uber/nullaway/ErrorProneCLIFlagsConfig.java
index 82101acd6a..300f5b8c2c 100644
--- a/nullaway/src/main/java/com/uber/nullaway/ErrorProneCLIFlagsConfig.java
+++ b/nullaway/src/main/java/com/uber/nullaway/ErrorProneCLIFlagsConfig.java
@@ -235,6 +235,7 @@ final class ErrorProneCLIFlagsConfig implements Config {
private final boolean acknowledgeAndroidRecent;
private final boolean jspecifyMode;
private final boolean polyNullLibraryModelsEnabled;
+ private final boolean nullableBoundInferenceEnabled;
private final boolean handleWildcardGenerics;
private final boolean warnOnInferenceFailure;
private final ImmutableSet knownInitializers;
@@ -311,6 +312,7 @@ final class ErrorProneCLIFlagsConfig implements Config {
acknowledgeAndroidRecent = flags.getBoolean(FL_ACKNOWLEDGE_ANDROID_RECENT).orElse(false);
jspecifyMode = flags.getBoolean(FL_JSPECIFY_MODE).orElse(false);
polyNullLibraryModelsEnabled = jspecifyMode && jspecifyExperimental;
+ nullableBoundInferenceEnabled = jspecifyMode && jspecifyExperimental;
handleWildcardGenerics =
flags.getBoolean(FL_HANDLE_WILDCARD_GENERICS).orElse(jspecifyExperimental);
assertsEnabled = flags.getBoolean(FL_ASSERTS_ENABLED).orElse(false);
@@ -624,6 +626,11 @@ public boolean isPolyNullLibraryModelsEnabled() {
return polyNullLibraryModelsEnabled;
}
+ @Override
+ public boolean isNullableBoundInferenceEnabled() {
+ return nullableBoundInferenceEnabled;
+ }
+
@Override
public boolean handleWildcardGenerics() {
return handleWildcardGenerics;
diff --git a/nullaway/src/main/java/com/uber/nullaway/Nullness.java b/nullaway/src/main/java/com/uber/nullaway/Nullness.java
index de328912a3..90679ba9ee 100644
--- a/nullaway/src/main/java/com/uber/nullaway/Nullness.java
+++ b/nullaway/src/main/java/com/uber/nullaway/Nullness.java
@@ -67,8 +67,10 @@ public enum Nullness implements AbstractValue {
*
*
A dereference of the value is reported, since the value is not null-exclusive under every
* parameterization. An assignment, an argument, a return, or an array store accepts the value
- * where nullness subtyping holds: where the target's type is {@code T}, or a capture of {@code ?
- * super T}, without {@code @NonNull}, as {@link
+ * where nullness subtyping holds: where the target's type carries no {@code @NonNull} and is the
+ * value's own type (for example the capture of {@code ? extends T} that javac infers for a
+ * generic parameter), a type variable that the value's type reaches through non-nullable bounds
+ * (for example {@code T}), or a capture of {@code ? super} either of those types, as {@link
* com.uber.nullaway.generics.GenericsChecks#acceptsNoChangeValue} decides. At any other target
* the value is {@link #NULLABLE}, and so is a variable of another type that dataflow assigns it
* to. Generic method inference takes no nullness constraint from the value and infers {@code T}.
diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitor.java b/nullaway/src/main/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitor.java
index a78c52467e..63cf98b455 100644
--- a/nullaway/src/main/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitor.java
+++ b/nullaway/src/main/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitor.java
@@ -3,12 +3,14 @@
import static com.uber.nullaway.NullabilityUtil.castToNonNull;
import com.google.common.base.Equivalence;
+import com.google.common.collect.ImmutableSet;
import com.google.errorprone.VisitorState;
import com.sun.tools.javac.code.BoundKind;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
import com.uber.nullaway.Config;
+import com.uber.nullaway.Nullness;
import com.uber.nullaway.handlers.Handler;
import java.util.Collections;
import java.util.HashSet;
@@ -31,6 +33,24 @@ public class CheckIdenticalNullabilityVisitor extends Types.DefaultTypeVisitor uninferredTypeVariables, boolean actualFromCallInference) {
+ /** A context with no uninferred type variables and an actual type taken from the code. */
+ static final ComparisonContext NONE = new ComparisonContext(ImmutableSet.of(), false);
+ }
/** Successful containment checks, reusable for the lifetime of this visitor. */
private @Nullable Set successfulWildcardComparisons;
@@ -101,11 +121,16 @@ private record ContainmentKey(
}
CheckIdenticalNullabilityVisitor(
- VisitorState state, GenericsChecks genericsChecks, Config config, Handler handler) {
+ VisitorState state,
+ GenericsChecks genericsChecks,
+ Config config,
+ Handler handler,
+ ComparisonContext context) {
this.state = state;
this.genericsChecks = genericsChecks;
this.config = config;
this.handler = handler;
+ this.context = context;
}
/**
@@ -177,6 +202,7 @@ public Boolean visitClassType(Type.ClassType lhsType, Type rhsType) {
GenericsUtils.effectiveUpperBoundsForTypeArguments(
(Type.ClassType) rhsTypeAsSuper, state, config, handler);
}
+ List formalTypeVariables = lhsType.tsym.type.getTypeArguments();
for (int i = 0; i < lhsTypeArguments.size(); i++) {
Type lhsTypeArgument = lhsTypeArguments.get(i);
Type lhsUpperBound = lhsUpperBounds.get(i);
@@ -189,7 +215,8 @@ public Boolean visitClassType(Type.ClassType lhsType, Type rhsType) {
rhsUpperBound,
i,
lhsParameterization,
- rhsParameterization)) {
+ rhsParameterization,
+ (Type.TypeVar) formalTypeVariables.get(i))) {
return false;
}
}
@@ -245,6 +272,8 @@ public Boolean visitType(Type t, Type type) {
* type, and type arguments; {@code null} if wildcard handling is off
* @param rhsParameterization the RHS parameterized type, identified by its declaration, enclosing
* type, and type arguments; {@code null} if wildcard handling is off
+ * @param formalTypeVariable the type parameter of the generic class that both type arguments
+ * instantiate
* @return whether {@code rhsTypeArgument} is contained by {@code lhsTypeArgument}
*/
private boolean typeArgumentContainedBy(
@@ -254,7 +283,8 @@ private boolean typeArgumentContainedBy(
Type rhsUpperBound,
int argumentIndex,
@Nullable ParameterizationKey lhsParameterization,
- @Nullable ParameterizationKey rhsParameterization) {
+ @Nullable ParameterizationKey rhsParameterization,
+ Type.TypeVar formalTypeVariable) {
if (!config.handleWildcardGenerics()) {
if (lhsTypeArgument.getKind().equals(TypeKind.WILDCARD)
|| rhsTypeArgument.getKind().equals(TypeKind.WILDCARD)) {
@@ -280,7 +310,8 @@ private boolean typeArgumentContainedBy(
rhsTypeArgument,
argumentIndex,
castToNonNull(lhsParameterization),
- castToNonNull(rhsParameterization)));
+ castToNonNull(rhsParameterization)),
+ formalTypeVariable);
}
if (rhsWildcard != null) {
// This case should only arise when generic method invocation inference / capture conversion
@@ -314,7 +345,8 @@ private boolean haveIdenticalNullability(Type lhsType, Type rhsType) {
* ? extends S} contains actual arguments whose upper bound is a subtype of {@code S}; a formal
* {@code ? super S} contains concrete actuals {@code T} and wildcard actuals {@code ? super T}
* when {@code S <: T}; and a formal {@code ?} is treated as {@code ? extends B}, where {@code B}
- * is the corresponding type variable's upper bound.
+ * is the corresponding type variable's upper bound. The top-level nullness of each subtype check
+ * is {@link #isNullnessSubtype}, which judges a type variable by its declared bounds.
*
* @param lhsWildcard the formal wildcard type argument on the left
* @param lhsUpperBound the upper bound of {@code lhsWildcard}
@@ -322,6 +354,7 @@ private boolean haveIdenticalNullability(Type lhsType, Type rhsType) {
* @param rhsUpperBound the upper bound of {@code rhsTypeArgument}
* @param key identifies this comparison: {@code lhsWildcard}, {@code rhsTypeArgument}, their
* position, and the parameterized types that contain them, before their bounds are computed
+ * @param formalTypeVariable the type parameter that {@code lhsWildcard} instantiates
* @return whether {@code lhsWildcard} contains {@code rhsTypeArgument}
*/
private boolean wildcardContains(
@@ -329,7 +362,8 @@ private boolean wildcardContains(
Type lhsUpperBound,
Type rhsTypeArgument,
Type rhsUpperBound,
- ContainmentKey key) {
+ ContainmentKey key,
+ Type.TypeVar formalTypeVariable) {
if (successfulWildcardComparisons != null && successfulWildcardComparisons.contains(key)) {
return true;
}
@@ -358,7 +392,11 @@ private boolean wildcardContains(
try {
boolean result =
switch (lhsWildcard.kind) {
- case UNBOUND, EXTENDS -> typeArgumentSubtype(lhsUpperBound, rhsUpperBound);
+ case UNBOUND, EXTENDS ->
+ typeArgumentSubtype(
+ lhsUpperBound,
+ rhsUpperBound,
+ actualOperator(formalTypeVariable, rhsTypeArgument, rhsUpperBound));
case SUPER -> superWildcardContains(lhsWildcard, rhsTypeArgument);
};
// A nested success may rely on an unfinished check, so cache results only after the outer
@@ -381,6 +419,179 @@ private boolean wildcardContains(
}
}
+ /**
+ * The JSpecify nullness operator
+ * of a type usage: what the usage says about null beyond what its base type says.
+ */
+ enum NullnessOperator {
+ /** The usage is annotated {@code @Nullable}, in the code or by NullAway. */
+ UNION_NULL,
+ /** The usage is annotated {@code @NonNull}, in the code or by NullAway. */
+ MINUS_NULL,
+ /** The usage carries no nullness annotation and takes the nullness of its base type. */
+ NO_CHANGE,
+ /**
+ * The check does not decide the usage's nullness: inference removed its annotations, or another
+ * check owns the question. {@link #actualOperator} assigns it to an actual type argument, and
+ * {@link #isNullExclusive} reads it as excluding null, which is the specification's "some
+ * world" rule.
+ */
+ UNSPECIFIED
+ }
+
+ private NullnessOperator operatorOf(Type type) {
+ if (genericsChecks.isNullableAnnotated(type)) {
+ return NullnessOperator.UNION_NULL;
+ }
+ if (Nullness.hasNonNullAnnotation(type.getAnnotationMirrors().stream(), config)) {
+ return NullnessOperator.MINUS_NULL;
+ }
+ return NullnessOperator.NO_CHANGE;
+ }
+
+ /**
+ * Returns the operator of an actual type argument's effective upper bound against a formal {@code
+ * ?} or {@code ? extends}: the operator written on that bound, which for a capture is the one
+ * written on the wildcard it captures. The operator is {@link NullnessOperator#UNSPECIFIED} where
+ * the bound carries none and either of these holds:
+ *
+ *
+ *
The actual is a capture in the type of a generic call that needs inference, as {@link
+ * ComparisonContext#actualFromCallInference} says, so its bound may have lost a written
+ * {@code @NonNull}. A bound written bare is accepted too: a false negative until NullAway
+ * infers the full types of a call (#1585, #2195).
+ *
The bound is a type variable and the bound of {@code formalTypeVariable} is not nullable,
+ * as {@link GenericsUtils#upperBoundIsNullable} decides. Whether such an actual fits is
+ * whether it is a well-formed instantiation of {@code formalTypeVariable}, a check of its
+ * own (#1946), and the answer is the same for {@code ?} and for any {@code ? extends} on
+ * that type variable.
+ *
+ */
+ private NullnessOperator actualOperator(
+ Type.TypeVar formalTypeVariable, Type rhsTypeArgument, Type rhsUpperBound) {
+ NullnessOperator operator = operatorOf(rhsUpperBound);
+ if (operator == NullnessOperator.NO_CHANGE
+ && rhsTypeArgument instanceof Type.CapturedType
+ && context.actualFromCallInference()) {
+ return NullnessOperator.UNSPECIFIED;
+ }
+ if (operator == NullnessOperator.NO_CHANGE
+ && rhsUpperBound instanceof Type.TypeVar
+ && !GenericsUtils.upperBoundIsNullable(
+ formalTypeVariable.asElement(), config, handler, state)) {
+ return NullnessOperator.UNSPECIFIED;
+ }
+ return operator;
+ }
+
+ /**
+ * Returns whether the check treats a value of the type as null-exclusive: never null under any
+ * instantiation of the type variables in scope, or {@link NullnessOperator#UNSPECIFIED}, which
+ * the check reads leniently. That holds for {@link NullnessOperator#MINUS_NULL} and {@link
+ * NullnessOperator#UNSPECIFIED}, never for {@link NullnessOperator#UNION_NULL}, and for {@link
+ * NullnessOperator#NO_CHANGE} where the type is one of these:
+ *
+ *
+ *
a type variable whose bound is not explicitly nullable, as {@link
+ * GenericsUtils#boundIsExplicitlyNullable} decides;
+ *
an intersection with a null-exclusive explicit element, as the bound of a capture or the
+ * least upper bound of the branches of a conditional expression can be;
+ *
any other type: a class or an array.
+ *
+ */
+ private boolean isNullExclusive(Type type, NullnessOperator operator) {
+ return switch (operator) {
+ case UNION_NULL -> false;
+ case MINUS_NULL, UNSPECIFIED -> true;
+ case NO_CHANGE -> {
+ if (type instanceof Type.TypeVar typeVar) {
+ yield !GenericsUtils.boundIsExplicitlyNullable(
+ typeVar.asElement(), config, handler, state);
+ }
+ if (type instanceof Type.IntersectionClassType intersection) {
+ yield intersection.getExplicitComponents().stream()
+ .anyMatch(component -> isNullExclusive(component, operatorOf(component)));
+ }
+ yield true;
+ }
+ };
+ }
+
+ /**
+ * Returns whether the type reaches the type variable {@code target} through declared upper bounds
+ * none of which is explicitly nullable: the specification's nullness-subtype-establishing path,
+ * which makes {@code S} a subtype of {@code T} for {@code } and {@code } but not for {@code }. The path may pass through any
+ * element of an intersection, so a capture bounded by {@code T & @Nullable Runnable} reaches
+ * {@code T}. Returns {@code false} where no chain of bounds reaches {@code target}, as for a
+ * {@code target} declared by another method.
+ */
+ private boolean hasSubtypeEstablishingPath(
+ Type type, NullnessOperator operator, Type.TypeVar target) {
+ if (operator == NullnessOperator.UNION_NULL) {
+ return false;
+ }
+ if (type instanceof Type.IntersectionClassType intersection) {
+ return intersection.getExplicitComponents().stream()
+ .anyMatch(
+ component -> hasSubtypeEstablishingPath(component, operatorOf(component), target));
+ }
+ if (!(type instanceof Type.TypeVar typeVar)) {
+ return false;
+ }
+ if (typeVar.tsym.equals(target.tsym)) {
+ return true;
+ }
+ if (GenericsUtils.declaredBoundIsExplicitlyNullable(
+ typeVar.asElement(), config, handler, state)) {
+ return false;
+ }
+ return hasSubtypeEstablishingPath(typeVar.getUpperBound(), NullnessOperator.NO_CHANGE, target);
+ }
+
+ /**
+ * Returns whether {@code subtype} is a JSpecify nullness subtype of
+ * {@code supertype}, judged at the top level only: a value of {@code subtype} that may be null
+ * fits {@code supertype} only where {@code supertype} admits null. That holds where {@code
+ * supertype} is null-inclusive, where {@code subtype} is null-exclusive, or where {@code
+ * supertype} is a type variable, not written {@code @NonNull}, that {@code subtype} reaches
+ * through bounds none of which is explicitly nullable. Nested type arguments are compared by the
+ * caller.
+ *
+ *
Where either side is a bare type variable that NullAway does not infer at the call or method
+ * reference being checked (see {@link ComparisonContext#uninferredTypeVariables}), its bounds are
+ * not read, and only a {@code subtype} annotated {@code @Nullable} fails.
+ */
+ private boolean isNullnessSubtype(
+ Type subtype,
+ NullnessOperator subtypeOperator,
+ Type supertype,
+ NullnessOperator supertypeOperator) {
+ if (isUninferredTypeVariable(subtype, subtypeOperator)
+ || isUninferredTypeVariable(supertype, supertypeOperator)) {
+ return subtypeOperator != NullnessOperator.UNION_NULL;
+ }
+ if (supertypeOperator == NullnessOperator.UNION_NULL
+ || isNullExclusive(subtype, subtypeOperator)) {
+ return true;
+ }
+ return supertype instanceof Type.TypeVar target
+ && supertypeOperator != NullnessOperator.MINUS_NULL
+ && hasSubtypeEstablishingPath(subtype, subtypeOperator, target);
+ }
+
+ /**
+ * Returns whether {@code type} is a type variable, written without a nullness annotation, that
+ * NullAway does not infer at the call or method reference being checked.
+ */
+ private boolean isUninferredTypeVariable(Type type, NullnessOperator operator) {
+ return operator == NullnessOperator.NO_CHANGE
+ && type instanceof Type.TypeVar
+ && !(type instanceof Type.CapturedType)
+ && context.uninferredTypeVariables().contains(type.tsym);
+ }
+
/**
* Returns whether a formal {@code ? super S} contains the actual type argument on the right. For
* concrete actuals {@code T} and wildcard actuals {@code ? super T}, containment holds when
@@ -399,22 +610,26 @@ private boolean superWildcardContains(Type.WildcardType lhsWildcard, Type rhsTyp
return true;
}
Type rhsBound = castToNonNull(rhsWildcard.getSuperBound());
- return typeArgumentSubtype(rhsBound, lhsBound);
+ return typeArgumentSubtype(rhsBound, lhsBound, operatorOf(lhsBound));
}
- return typeArgumentSubtype(rhsTypeArgument, lhsBound);
+ return typeArgumentSubtype(rhsTypeArgument, lhsBound, operatorOf(lhsBound));
}
/**
- * Returns whether the actual type argument on the right is a nullability-aware subtype of the
- * formal type argument on the left. This check first rejects flows from nullable to non-null at
- * the top level of the type argument, then delegates to {@link
- * GenericsChecks#subtypeParameterNullability(Type, Type, VisitorState)} for recursive nested
- * checks.
+ * Returns whether {@code rhsType} is a nullability-aware subtype of {@code lhsType}. For a formal
+ * {@code ? extends}, {@code rhsType} is the actual's upper bound; for a formal {@code ? super S},
+ * {@code rhsType} is {@code S} and {@code lhsType} is the actual. The top level is {@link
+ * #isNullnessSubtype}; nested type arguments are delegated to {@link
+ * GenericsChecks#subtypeParameterNullability(Type, Type, VisitorState,
+ * CheckIdenticalNullabilityVisitor)}.
+ *
+ * @param lhsType the supertype
+ * @param rhsType the subtype
+ * @param rhsOperator the nullness operator of {@code rhsType}, which the caller may have relaxed
+ * to {@link NullnessOperator#UNSPECIFIED}
*/
- private boolean typeArgumentSubtype(Type lhsType, Type rhsType) {
- boolean isLHSNullableAnnotated = genericsChecks.isNullableAnnotated(lhsType);
- boolean isRHSNullableAnnotated = genericsChecks.isNullableAnnotated(rhsType);
- if (isRHSNullableAnnotated && !isLHSNullableAnnotated) {
+ private boolean typeArgumentSubtype(Type lhsType, Type rhsType, NullnessOperator rhsOperator) {
+ if (!isNullnessSubtype(rhsType, rhsOperator, lhsType, operatorOf(lhsType))) {
return false;
}
return genericsChecks.subtypeParameterNullability(lhsType, rhsType, state, this);
diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java
index 22c3965821..c07b54d601 100644
--- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java
+++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java
@@ -5,6 +5,7 @@
import java.util.List;
import java.util.Map;
import javax.lang.model.element.Element;
+import org.jspecify.annotations.Nullable;
/**
* An interface for solving constraints on type variables, such as subtype relationships between
@@ -62,14 +63,51 @@ class UnsatisfiableConstraintsException extends RuntimeException {
/** Whether a {@code @Nullable} constraint conflicts with the type variable's upper bound. */
private final boolean causedByNonNullUpperBound;
+ /**
+ * The type variable with an explicitly nullable bound that was passed for {@code ? extends}
+ * {@link #typeVariable} and so constrains {@link #typeVariable} to be {@code @Nullable}; {@code
+ * null} where another constraint caused the conflict.
+ */
+ private final @Nullable Type nullableBoundTypeVariable;
+
+ /**
+ * The type variable whose declared bound makes the bound of {@link #nullableBoundTypeVariable}
+ * explicitly nullable: that type variable itself, or one its bound reaches through other type
+ * variables; {@code null} exactly where {@link #nullableBoundTypeVariable} is.
+ */
+ private final @Nullable Element typeVariableWithNullableBound;
+
public UnsatisfiableConstraintsException(Element typeVariable) {
this(typeVariable, false);
}
public UnsatisfiableConstraintsException(
Element typeVariable, boolean causedByNonNullUpperBound) {
+ this(typeVariable, causedByNonNullUpperBound, null, null);
+ }
+
+ /**
+ * Creates an exception for a {@code typeVariable} whose bound excludes null, where {@code
+ * nullableBoundTypeVariable}, a type variable with an explicitly nullable bound, was passed for
+ * {@code ? extends typeVariable}, and the declared bound of {@code
+ * typeVariableWithNullableBound} makes that bound explicitly nullable.
+ */
+ public UnsatisfiableConstraintsException(
+ Element typeVariable,
+ Type nullableBoundTypeVariable,
+ Element typeVariableWithNullableBound) {
+ this(typeVariable, true, nullableBoundTypeVariable, typeVariableWithNullableBound);
+ }
+
+ private UnsatisfiableConstraintsException(
+ Element typeVariable,
+ boolean causedByNonNullUpperBound,
+ @Nullable Type nullableBoundTypeVariable,
+ @Nullable Element typeVariableWithNullableBound) {
this.typeVariable = typeVariable;
this.causedByNonNullUpperBound = causedByNonNullUpperBound;
+ this.nullableBoundTypeVariable = nullableBoundTypeVariable;
+ this.typeVariableWithNullableBound = typeVariableWithNullableBound;
}
public Element getTypeVariable() {
@@ -79,6 +117,14 @@ public Element getTypeVariable() {
public boolean isCausedByNonNullUpperBound() {
return causedByNonNullUpperBound;
}
+
+ public @Nullable Type getNullableBoundTypeVariable() {
+ return nullableBoundTypeVariable;
+ }
+
+ public @Nullable Element getTypeVariableWithNullableBound() {
+ return typeVariableWithNullableBound;
+ }
}
/**
@@ -97,14 +143,49 @@ public boolean isCausedByNonNullUpperBound() {
void addSubtypeConstraint(Type subtype, Type supertype, boolean localVariableType)
throws UnsatisfiableConstraintsException;
+ /** The nullness the solver found for an inference variable. */
enum InferredNullability {
+ /**
+ * A constraint fixed the variable to be non-null, or no constraint fixed it and no unannotated
+ * type variable that is not under inference and whose bound admits null flowed into it, so
+ * non-null is the least solution. The solver tracks such a flow only where {@link
+ * com.uber.nullaway.Config#isNullableBoundInferenceEnabled} holds; otherwise every variable
+ * that no constraint fixed is {@code NONNULL}.
+ */
NONNULL,
- NULLABLE
+ /** A constraint fixed the variable to be nullable. */
+ NULLABLE,
+ /**
+ * No constraint fixed the variable, a type variable {@code T} whose bound is explicitly
+ * nullable flowed into it, and the variable's own bound is explicitly nullable, as {@link
+ * GenericsUtils#typeVariableWithNullableBound} decides it. Where javac inferred a type with
+ * parametric nullness ({@link GenericsUtils#hasParametricNullness}), a capture included, the
+ * variable is that type with no synthetic annotation; where javac inferred an intersection
+ * type, it carries no annotation; where javac inferred any other type, such as the least upper
+ * bound of {@code T} and {@code String}, or a type variable {@code R} whose bound excludes null
+ * for {@code T extends @Nullable R}, the variable is {@code @Nullable}, the least type that
+ * holds a null {@code T}.
+ */
+ TYPE_VARIABLE_OR_NULLABLE,
+ /**
+ * No constraint fixed the variable and an unannotated type variable that is not under inference
+ * and whose bound admits null flowed into it, but {@link #TYPE_VARIABLE_OR_NULLABLE} does not
+ * apply: no such type variable has an explicitly nullable bound, or the variable's own bound is
+ * not explicitly nullable. Where javac inferred a type with parametric nullness ({@link
+ * GenericsUtils#hasParametricNullness}), a capture included, the variable is that type with no
+ * synthetic annotation; where javac inferred an intersection type, it carries no annotation;
+ * where javac inferred any other type, the variable is {@code @NonNull}, as if no type variable
+ * had flowed into it.
+ */
+ TYPE_VARIABLE_OR_NONNULL;
}
/**
* Solve the constraints, returning a map from inference variables to their inferred nullability.
- * The map only contains inference variables that appear in constraints.
+ * The map only contains inference variables that appear in constraints or, where {@link
+ * com.uber.nullaway.Config#isNullableBoundInferenceEnabled} holds, that such a variable reaches
+ * through a chain of declared bounds read as {@code U <: R}: for {@code } with only {@code U} constrained, the map holds {@code U}, {@code R}, and {@code Q}.
*
* @return a map from inference variables to their inferred nullability
* @throws UnsatisfiableConstraintsException if the constraints are determined to be unsatisfiable
diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java
index bc0f890944..6210eb1a13 100644
--- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java
+++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java
@@ -18,6 +18,7 @@
import com.uber.nullaway.Nullness;
import com.uber.nullaway.handlers.Handler;
import java.util.ArrayDeque;
+import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.IdentityHashMap;
@@ -48,6 +49,17 @@ public final class ConstraintSolverImpl implements ConstraintSolver {
private final IdentityHashMap inferenceVariables =
new IdentityHashMap<>();
+ /**
+ * Maps an inference variable whose declared bound is an unannotated use of another inference
+ * variable of the same site, such as {@code U} in {@code }, to that variable,
+ * where the declaration of {@code U} does not make its bound nullable by {@link
+ * GenericsUtils#declaredUpperBoundIsNullable}. {@link #solve()} makes each such bound a supertype
+ * edge {@code U <: R} for every {@code U} that appears in a constraint or that an earlier edge
+ * reaches, so it follows a chain such as {@code } from {@code U} to
+ * {@code Q}. Recorded only where {@link Config#isNullableBoundInferenceEnabled} holds.
+ */
+ private final Map declaredBounds = new LinkedHashMap<>();
+
public ConstraintSolverImpl(Config config, VisitorState state, NullAway analysis) {
this.config = config;
this.handler = analysis.getHandler();
@@ -74,6 +86,21 @@ private static final class VarState {
NullnessState nullness = NullnessState.UNKNOWN;
+ /**
+ * Whether a type with parametric nullness ({@link GenericsUtils#hasParametricNullness}) that is
+ * not under inference flowed into this variable. Such a flow fixes no nullness, but where javac
+ * inferred a type with parametric nullness, the variable takes that type with no synthetic
+ * annotation rather than the non-null default. Recorded only where {@link
+ * Config#isNullableBoundInferenceEnabled} holds.
+ */
+ boolean parametric;
+
+ /**
+ * Whether one of the type variables that set {@link #parametric} has a bound that is explicitly
+ * nullable, rather than nullable by default in unannotated code.
+ */
+ boolean parametricNullable;
+
/** Important to use a LinkedHashSet here for determinism in error messages. */
final Set supertypes = new LinkedHashSet<>();
@@ -119,6 +146,17 @@ public Map registerInferenceVariables(
for (Map.Entry entry : fresh.entrySet()) {
inferenceVariables.put(entry.getValue().tsym, new InferenceVariable(entry.getKey(), site));
}
+ if (config.isNullableBoundInferenceEnabled()) {
+ for (Type.TypeVar typeVar : fresh.values()) {
+ InferenceVariable inferenceVar = castToNonNull(inferenceVariables.get(typeVar.tsym));
+ InferenceVariable boundVar = inferenceVariableForUse(typeVar.getUpperBound());
+ if (boundVar != null
+ && !GenericsUtils.declaredUpperBoundIsNullable(
+ inferenceVar.typeVariable(), config, handler, state)) {
+ declaredBounds.put(inferenceVar, boundVar);
+ }
+ }
+ }
return fresh;
}
@@ -276,9 +314,15 @@ private void equateTypeArguments(Type subtypeTypeArg, Type supertypeTypeArg) {
/**
* Adds constraints for type-argument containment where the formal argument is a wildcard. For
* {@code ? extends S} and {@code ?}, containment requires the actual argument's effective upper
- * bound to be a subtype of {@code S}. For {@code ? super S}, concrete actual arguments require
- * {@code S <: subtypeTypeArg}; {@code ? super T} actual arguments require {@code S <: T}. Other
- * actual wildcard forms place no useful nullability constraint.
+ * bound to be a subtype of {@code S}. For {@code ? extends U}, where {@code U} is an inference
+ * variable whose bound excludes null, an actual that is an unannotated, uncaptured type
+ * variable {@code T} with an explicitly nullable bound also constrains {@code U} to be
+ * {@code @Nullable}, which no solution satisfies; this check runs only where {@link
+ * Config#isNullableBoundInferenceEnabled} holds. An actual wildcard or capture bounded by such
+ * a {@code T}, as in {@code Box extends T>}, adds no such constraint (#2189). For {@code ?
+ * super S}, concrete actual arguments require {@code S <: subtypeTypeArg}; {@code ? super T}
+ * actual arguments require {@code S <: T}. Other actual wildcard forms place no useful
+ * nullability constraint.
*
*
Self-referential bounds such as {@code N extends Node>} can lead back to the exact same
* containment check. Re-entering a check that is already in progress adds no constraints, since
@@ -298,8 +342,27 @@ private void constrainContainedByWildcard(Type subtypeTypeArg, WildcardType supe
case UNBOUND, EXTENDS -> {
Type subtypeUpperBound =
GenericsUtils.effectiveWildcardUpperBound(subtypeTypeArg, state, config, handler);
- subtypeUpperBound.accept(
- this, GenericsUtils.wildcardUpperBound(supertypeWildcard, state, config, handler));
+ Type supertypeUpperBound =
+ GenericsUtils.wildcardUpperBound(supertypeWildcard, state, config, handler);
+ InferenceVariable supertypeVar = inferenceVariableForUse(supertypeUpperBound);
+ if (config.isNullableBoundInferenceEnabled()
+ && supertypeWildcard.kind == BoundKind.EXTENDS
+ && supertypeVar != null
+ && !getState(supertypeVar).nullableAllowed) {
+ Element typeVariableWithNullableBound =
+ typeVariableWithNullableBoundFor(subtypeTypeArg);
+ if (typeVariableWithNullableBound != null) {
+ // Under JSpecify, an unannotated T whose bound is @Nullable is a subtype of U only
+ // where U is @Nullable, and the non-null bound of U forbids that. Where the bound
+ // of U allows null, U is left unconstrained: the solver infers one nullness per
+ // variable, so a @Nullable U would replace the T that javac inferred for U with
+ // @Nullable T, and List c = copy(in), with
+ // List copy(List extends U> in), would be reported.
+ throw new UnsatisfiableConstraintsException(
+ supertypeVar.typeVariable(), subtypeTypeArg, typeVariableWithNullableBound);
+ }
+ }
+ subtypeUpperBound.accept(this, supertypeUpperBound);
}
case SUPER -> {
Type supertypeLowerBound = castToNonNull(supertypeWildcard.getSuperBound());
@@ -354,6 +417,22 @@ private void constrainWildcardToSupertype(WildcardType subtypeWildcard, Type sup
@Override
public Map solve()
throws UnsatisfiableConstraintsException {
+ /* U extends R ⇒ U <: R, for every U that appears in a constraint or that an edge reaches */
+ if (!declaredBounds.isEmpty()) {
+ List boundedVars = new ArrayList<>(vars.keySet());
+ for (int i = 0; i < boundedVars.size(); i++) {
+ InferenceVariable sub = boundedVars.get(i);
+ InferenceVariable sup = declaredBounds.get(sub);
+ if (sup != null) {
+ if (!vars.containsKey(sup)) {
+ boundedVars.add(sup);
+ }
+ getState(sub).supertypes.add(sup);
+ getState(sup).subtypes.add(sub);
+ }
+ }
+ }
+
/* ---------- work-list propagation of nullability ---------- */
Deque work = new ArrayDeque<>();
vars.forEach(
@@ -391,17 +470,48 @@ public Map solve()
}
}
+ /* a type variable that flowed into a variable flows into each of its supertype variables */
+ vars.forEach(
+ (inferenceVar, st) -> {
+ if (st.parametric) {
+ work.add(inferenceVar);
+ }
+ });
+ while (!work.isEmpty()) {
+ VarState st = castToNonNull(vars.get(work.removeFirst()));
+ for (InferenceVariable sup : st.supertypes) {
+ VarState supState = castToNonNull(vars.get(sup));
+ if (!supState.parametric || (st.parametricNullable && !supState.parametricNullable)) {
+ supState.parametric = true;
+ supState.parametricNullable |= st.parametricNullable;
+ work.add(sup);
+ }
+ }
+ }
+
/* ---------- build final solution map ---------- */
Map result = new LinkedHashMap<>();
vars.forEach(
(inferenceVar, st) -> {
- // Note: if the nullness state is UNKNOWN, we infer NONNULL arbitrarily
- // TODO does this matter? should we use NULLABLE instead?
result.put(
inferenceVar,
- st.nullness == NullnessState.NULLABLE
- ? InferredNullability.NULLABLE
- : InferredNullability.NONNULL);
+ switch (st.nullness) {
+ case NULLABLE -> InferredNullability.NULLABLE;
+ case NONNULL -> InferredNullability.NONNULL;
+ // nothing pushed the variable toward null, so non-null is the least solution,
+ // unless an unannotated type variable whose bound admits null flowed in and
+ // decides its nullness
+ case UNKNOWN -> {
+ if (!st.parametric) {
+ yield InferredNullability.NONNULL;
+ }
+ yield st.parametricNullable
+ && GenericsUtils.boundIsExplicitlyNullable(
+ inferenceVar.typeVariable(), config, handler, state)
+ ? InferredNullability.TYPE_VARIABLE_OR_NULLABLE
+ : InferredNullability.TYPE_VARIABLE_OR_NONNULL;
+ }
+ });
});
return result;
}
@@ -437,6 +547,16 @@ private void directlyConstrainTypePair(Type s, Type t) throws UnsatisfiableConst
if (isKnownNullable(s) && tVar != null) {
updateNullness(tVar, NullnessState.NULLABLE);
}
+ if (config.isNullableBoundInferenceEnabled()
+ && tVar != null
+ && sVar == null
+ && GenericsUtils.hasParametricNullness(s, config, handler, state)) {
+ VarState st = getState(tVar);
+ st.parametric = true;
+ if (GenericsUtils.boundIsExplicitlyNullable(s.asElement(), config, handler, state)) {
+ st.parametricNullable = true;
+ }
+ }
}
/* ───────────────────── nullability bookkeeping ───────────────────── */
@@ -501,6 +621,21 @@ private boolean treatAsTypeVariableForInference(Type t) {
return inferenceVariableForUse(t) != null;
}
+ /**
+ * Where {@code t} is a type variable not under inference, not a capture, and carrying no nullness
+ * annotation at this use, returns the type variable whose declared bound makes the bound of
+ * {@code t} explicitly nullable, as {@link GenericsUtils#typeVariableWithNullableBound} finds it;
+ * returns {@code null} otherwise.
+ */
+ private @Nullable Element typeVariableWithNullableBoundFor(Type t) {
+ return t instanceof TypeVar tv
+ && !(t instanceof CapturedType)
+ && !inferenceVariables.containsKey(tv.asElement())
+ && !GenericsUtils.hasNullnessAnnotation(t, config)
+ ? GenericsUtils.typeVariableWithNullableBound(tv.asElement(), config, handler, state)
+ : null;
+ }
+
/** Returns whether a type is explicitly nullable or is the null type. */
private boolean isKnownNullable(Type t) {
return t instanceof NullType || GenericsUtils.isAnnotatedAsNullable(t, config);
diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java
index 6c9f73da45..09021e5ca0 100644
--- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java
+++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java
@@ -8,59 +8,128 @@
import com.sun.tools.javac.code.BoundKind;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Types;
+import java.util.List;
import org.jspecify.annotations.Nullable;
/**
* A visitor that pretty prints a generic type including its type-use nullability annotations, for
* use in error messages.
*
+ *
Nodes named by {@link TypePath} may be marked, in which case each printed form is bracketed by
+ * {@link #MARK_START}, the index of the path that matched, and {@link #MARK_END}, so that a caller
+ * can find its columns and draw a caret under it. A path that the printed type does not reach
+ * leaves no bracket, which is how a caller learns that the node it asked about is not printed: an
+ * unbounded wildcard prints as {@code ?} and its upper bound appears nowhere.
+ *
*
This code is a modified and extended version of code in {@link
* com.google.errorprone.util.Signatures}
*/
final class GenericTypePrettyPrintingVisitor
extends Types.DefaultTypeVisitor {
+ /**
+ * Opens the printed form of a marked node, followed by the digit naming which requested path
+ * matched. The characters cannot occur in a printed type, so the caller can locate the marked
+ * node's columns and then strip them.
+ */
+ static final char MARK_START = '\u0001';
+
+ static final char MARK_END = '\u0002';
+
private final VisitorState state;
+ /**
+ * The positions whose printed form is bracketed, in the order the caller numbers them. At most
+ * ten, since the index is printed as one digit, and disjoint, since a node reported as a mismatch
+ * is never descended into. An entry is {@code null} where the caller has a position for the other
+ * side of the comparison and none here, which keeps the indices of the two sides aligned.
+ */
+ private final List<@Nullable TypePath> markedPaths;
+
+ /** The position of the node being printed, maintained as the visitor descends. */
+ private TypePath currentPath = TypePath.root();
+
GenericTypePrettyPrintingVisitor(VisitorState state) {
+ this(state, List.of());
+ }
+
+ GenericTypePrettyPrintingVisitor(VisitorState state, List<@Nullable TypePath> markedPaths) {
this.state = state;
+ this.markedPaths = markedPaths;
+ }
+
+ /** Brackets {@code printed} when the node being printed sits at one of the requested paths. */
+ private String mark(String printed) {
+ for (int i = 0; i < markedPaths.size(); i++) {
+ TypePath markedPath = markedPaths.get(i);
+ if (markedPath != null && markedPath.reachesSameNodeAs(currentPath)) {
+ return MARK_START + Integer.toString(i) + printed + MARK_END;
+ }
+ }
+ return printed;
+ }
+
+ /** Strips the bracket around {@code printed}, where the whole of it is one marked node. */
+ private static String withoutOuterMark(String printed) {
+ return printed.length() > 2
+ && printed.charAt(0) == MARK_START
+ && printed.charAt(printed.length() - 1) == MARK_END
+ ? printed.substring(2, printed.length() - 1)
+ : printed;
+ }
+
+ /** Prints {@code child}, which {@code step} descends to from the node being printed. */
+ private String descend(TypePath.Step step, Type child) {
+ TypePath enclosingPath = currentPath;
+ currentPath = enclosingPath.then(step);
+ try {
+ return child.accept(this, null);
+ } finally {
+ currentPath = enclosingPath;
+ }
}
@Override
public String visitWildcardType(Type.WildcardType t, @Nullable Void unused) {
- // NOTE: we have not tested this code yet as we do not yet support wildcard types
StringBuilder sb = new StringBuilder();
sb.append(t.kind);
if (t.kind != BoundKind.UNBOUND) {
- sb.append(t.type.accept(this, null));
+ sb.append(descend(TypePath.Step.wildcardBound(), t.type));
}
- return sb.toString();
+ return mark(sb.toString());
}
@Override
public String visitClassType(Type.ClassType t, @Nullable Void s) {
if (t.isIntersection()) {
- return prettyIntersectionType((Type.IntersectionClassType) t);
+ return mark(prettyIntersectionType((Type.IntersectionClassType) t));
}
if (t.tsym.isAnonymous()) {
// eventually, we could probably do even better formatting here, but this provides all the
// needed information for now
- return t.toString();
+ return mark(t.toString());
}
StringBuilder sb = new StringBuilder();
Type enclosingType = t.getEnclosingType();
if (!ASTHelpers.isSameType(enclosingType, Type.noType, state)) {
- sb.append(enclosingType.accept(this, null)).append('.');
+ sb.append(descend(TypePath.Step.enclosingType(), enclosingType)).append('.');
}
appendNullableAnnotationIfPresent(t, sb);
sb.append(t.tsym.getSimpleName());
if (t.getTypeArguments().nonEmpty()) {
sb.append('<');
- sb.append(
- t.getTypeArguments().stream().map(a -> a.accept(this, null)).collect(joining(", ")));
+ StringBuilder arguments = new StringBuilder();
+ for (int i = 0; i < t.getTypeArguments().size(); i++) {
+ if (i > 0) {
+ arguments.append(", ");
+ }
+ arguments.append(
+ descend(TypePath.Step.typeArgument(i, null, null), t.getTypeArguments().get(i)));
+ }
+ sb.append(arguments);
sb.append(">");
}
- return sb.toString();
+ return mark(sb.toString());
}
/**
@@ -70,7 +139,9 @@ public String visitClassType(Type.ClassType t, @Nullable Void s) {
*/
private void appendNullableAnnotationIfPresent(Type t, StringBuilder sb) {
for (Attribute.TypeCompound compound : t.getAnnotationMirrors()) {
- String annotName = compound.type.accept(this, null);
+ // the annotation type is printed by a visitor of its own, so that its own path bookkeeping
+ // does not place a mark inside an annotation name
+ String annotName = compound.type.accept(new GenericTypePrettyPrintingVisitor(state), null);
if ("Nullable".equals(annotName)) {
sb.append("@Nullable ");
break;
@@ -83,7 +154,7 @@ public String visitTypeVar(Type.TypeVar t, @Nullable Void unused) {
StringBuilder sb = new StringBuilder();
appendNullableAnnotationIfPresent(t, sb);
sb.append(t.tsym.getSimpleName());
- return sb.toString();
+ return mark(sb.toString());
}
private String prettyIntersectionType(Type.IntersectionClassType t) {
@@ -97,27 +168,30 @@ public String visitCapturedType(Type.CapturedType t, @Nullable Void s) {
StringBuilder sb = new StringBuilder();
appendNullableAnnotationIfPresent(t, sb);
sb.append("capture of ");
- sb.append(t.wildcard.accept(this, null));
- return sb.toString();
+ // no step: a captured wildcard and the wildcard it captured are one node, which is also how
+ // GenericsUtils.asWildcard reads them, so the two agree on what a path addresses. One node
+ // takes one bracket, and it is the outer one, which covers the annotation printed above
+ sb.append(withoutOuterMark(t.wildcard.accept(this, null)));
+ return mark(sb.toString());
}
@Override
public String visitArrayType(Type.ArrayType t, @Nullable Void unused) {
StringBuilder sb = new StringBuilder();
- sb.append(t.elemtype.accept(this, null)).append(' ');
+ sb.append(descend(TypePath.Step.arrayElement(), t.elemtype)).append(' ');
appendNullableAnnotationIfPresent(t, sb);
- return sb.append("[]").toString();
+ return mark(sb.append("[]").toString());
}
@Override
public String visitErrorType(Type.ErrorType t, @Nullable Void unused) {
// this arises for our synthetic @Nullable and @NonNull annotations; we just return the simple
// name
- return t.tsym.getSimpleName().toString();
+ return mark(t.tsym.getSimpleName().toString());
}
@Override
public String visitType(Type t, @Nullable Void s) {
- return t.toString();
+ return mark(t.toString());
}
}
diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java
index de436682aa..913206b36e 100644
--- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java
+++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java
@@ -59,6 +59,7 @@
import com.uber.nullaway.dataflow.AccessPathNullnessAnalysis;
import com.uber.nullaway.dataflow.EnclosingEnvironmentNullness;
import com.uber.nullaway.dataflow.NullnessStore;
+import com.uber.nullaway.generics.CheckIdenticalNullabilityVisitor.ComparisonContext;
import com.uber.nullaway.generics.ConstraintSolver.UnsatisfiableConstraintsException;
import com.uber.nullaway.generics.GenericsUtils.MethodRefTypeRelationKind;
import com.uber.nullaway.generics.PolyNullInference.PolyNullInferenceContext;
@@ -99,7 +100,8 @@ private static final class InferenceSuccess implements CallInferenceResult {
private final IdentityHashMap>
typeVarNullabilityBySite = new IdentityHashMap<>();
- private final IdentityHashMap polyNullnessByInvocation;
+ private final IdentityHashMap
+ polyNullnessByInvocation;
/**
* Groups the solution by tree identity, preserving solution iteration order within each site's
@@ -110,7 +112,8 @@ private static final class InferenceSuccess implements CallInferenceResult {
*/
private InferenceSuccess(
Map solution,
- IdentityHashMap polyNullnessByInvocation) {
+ IdentityHashMap
+ polyNullnessByInvocation) {
this.polyNullnessByInvocation = polyNullnessByInvocation;
solution.forEach(
(inferenceVar, nullability) ->
@@ -173,8 +176,8 @@ private InferenceFailure(@Nullable String errorMessage) {
* PolyNull results inferred separately from generic call inference, cached by invocation
* identity. Results from joint generic inference remain in {@link InferenceSuccess}.
*/
- private final IdentityHashMap separatelyInferredPolyNullness =
- new IdentityHashMap<>();
+ private final IdentityHashMap
+ separatelyInferredPolyNullness = new IdentityHashMap<>();
/**
* Tracks generic method invocations currently undergoing nested-nullability repair so re-entrant
@@ -457,7 +460,9 @@ private void reportInvalidInstantiationError(
private void reportInvalidAssignmentInstantiationError(
Tree tree, Type lhsType, Type rhsType, VisitorState state) {
ErrorBuilder errorBuilder = analysis.getErrorBuilder();
- String msg = errorMessageForIncompatibleTypesAtPseudoAssignment(lhsType, rhsType, state);
+ String msg =
+ new NullabilityMismatchMessage(this, config, handler, state)
+ .build(lhsType, rhsType, tree instanceof VariableTree);
ErrorMessage errorMessage =
new ErrorMessage(ErrorMessage.MessageTypes.ASSIGN_GENERIC_NULLABLE, msg);
state.reportMatch(
@@ -465,178 +470,14 @@ private void reportInvalidAssignmentInstantiationError(
errorMessage, analysis.buildDescription(tree), state, null));
}
- private String errorMessageForIncompatibleTypesAtPseudoAssignment(
- Type lhsType, Type rhsType, VisitorState state) {
- String prettyRhsType = prettyTypeForError(rhsType, state);
- String prettyLhsType = prettyTypeForError(lhsType, state);
- String result =
- String.format(
- "incompatible types: %s cannot be converted to %s", prettyRhsType, prettyLhsType);
- boolean allowNonCaptureMismatch = prettyRhsType.equals(prettyLhsType);
- WildcardBoundMismatch wildcardBoundMismatch =
- firstWildcardBoundMismatch(lhsType, rhsType, state, allowNonCaptureMismatch);
- if (wildcardBoundMismatch != null) {
- result += " (" + describeWildcardBoundMismatch(wildcardBoundMismatch) + ")";
- }
- if (!ASTHelpers.isSameType(lhsType, rhsType, state)
- && lhsType.getKind() == TypeKind.DECLARED
- && rhsType.getKind() == TypeKind.DECLARED) {
- Symbol.TypeSymbol lhsSym = lhsType.asElement();
- if (lhsSym instanceof Symbol.ClassSymbol classSymbol) {
- Type asSuper =
- TypeSubstitutionUtils.asSuper(state.getTypes(), rhsType, classSymbol, config);
- if (asSuper != null) {
- result +=
- String.format(
- " (%s is a subtype of %s)", prettyRhsType, prettyTypeForError(asSuper, state));
- }
- }
- }
- return result;
- }
-
- /**
- * Returns the first wildcard bound difference between {@code lhsType} and {@code rhsType}, or
- * {@code null} if no such difference can be found. Recursively traverses {@code lhsType} and
- * {@code rhsType} to find such a difference.
- *
- *
This is especially useful when two types pretty-print identically, but differ in the
- * effective upper bound of a wildcard nested somewhere inside the type.
- *
- * @param lhsType the lhs (target) type
- * @param rhsType the rhs (source) type
- * @param state the visitor state
- * @param allowNonCaptureMismatch whether a mismatch may be returned when neither causal wildcard
- * is captured. Such details are useful when the full types print identically, but redundant
- * when the full types already expose the difference.
- */
- private @Nullable WildcardBoundMismatch firstWildcardBoundMismatch(
- Type lhsType, Type rhsType, VisitorState state, boolean allowNonCaptureMismatch) {
- // base case: both wildcard types
- Type.WildcardType lhsWildcard = GenericsUtils.asWildcard(lhsType);
- Type.WildcardType rhsWildcard = GenericsUtils.asWildcard(rhsType);
- if (lhsWildcard != null && rhsWildcard != null) {
- if (!allowNonCaptureMismatch
- && !(lhsType instanceof Type.CapturedType)
- && !(rhsType instanceof Type.CapturedType)) {
- return null;
- }
- return wildcardBoundMismatch(lhsType, rhsType, lhsWildcard, rhsWildcard, state);
- }
- if (lhsType instanceof Type.ClassType lhsClassType && rhsType instanceof Type.ClassType) {
- Type rhsTypeAsSuper =
- TypeSubstitutionUtils.asSuper(
- state.getTypes(), rhsType, (Symbol.ClassSymbol) lhsType.tsym, config);
- if (!(rhsTypeAsSuper instanceof Type.ClassType rhsClassType)
- || rhsTypeAsSuper.isRaw()
- || lhsType.isRaw()) {
- return null;
- }
- List lhsTypeArguments = lhsClassType.getTypeArguments();
- List rhsTypeArguments = rhsClassType.getTypeArguments();
- if (lhsTypeArguments.size() != rhsTypeArguments.size()) {
- return null;
- }
- for (int i = 0; i < lhsTypeArguments.size(); i++) {
- WildcardBoundMismatch mismatch =
- firstWildcardBoundMismatch(
- lhsTypeArguments.get(i), rhsTypeArguments.get(i), state, allowNonCaptureMismatch);
- if (mismatch != null) {
- return mismatch;
- }
- }
- return firstWildcardBoundMismatch(
- lhsClassType.getEnclosingType(),
- rhsClassType.getEnclosingType(),
- state,
- allowNonCaptureMismatch);
- }
- if (lhsType instanceof Type.ArrayType lhsArrayType
- && rhsType instanceof Type.ArrayType rhsArrayType) {
- return firstWildcardBoundMismatch(
- lhsArrayType.elemtype, rhsArrayType.elemtype, state, allowNonCaptureMismatch);
- }
- return null;
- }
-
- /**
- * Creates a structured mismatch for two wildcards with visibly different effective upper bounds,
- * or returns {@code null} if those bounds pretty-print the same.
- */
- private @Nullable WildcardBoundMismatch wildcardBoundMismatch(
- Type lhsType,
- Type rhsType,
- Type.WildcardType lhsWildcard,
- Type.WildcardType rhsWildcard,
- VisitorState state) {
- Type lhsUpperBound = GenericsUtils.wildcardUpperBound(lhsWildcard, state, config, handler);
- Type rhsUpperBound = GenericsUtils.wildcardUpperBound(rhsWildcard, state, config, handler);
- String prettyLhsUpperBound = prettyTypeForError(lhsUpperBound, state);
- String prettyRhsUpperBound = prettyTypeForError(rhsUpperBound, state);
- if (!prettyLhsUpperBound.equals(prettyRhsUpperBound)) {
- return new WildcardBoundMismatch(lhsType, rhsType, prettyLhsUpperBound, prettyRhsUpperBound);
- }
- return null;
- }
-
- /**
- * Describes a wildcard-bound mismatch, including provenance for every captured wildcard that
- * directly participates in that mismatch.
- */
- private static String describeWildcardBoundMismatch(WildcardBoundMismatch mismatch) {
- String result =
- String.format(
- "target wildcard upper bound is %s; source wildcard upper bound is %s",
- mismatch.prettyTargetUpperBound(), mismatch.prettySourceUpperBound());
- String targetCaptureDescription =
- captureProvenanceDescription(mismatch.targetWildcardType(), "target");
- if (targetCaptureDescription != null) {
- result += "; " + targetCaptureDescription;
- }
- String sourceCaptureDescription =
- captureProvenanceDescription(mismatch.sourceWildcardType(), "source");
- if (sourceCaptureDescription != null) {
- result += "; " + sourceCaptureDescription;
- }
- return result;
- }
-
- /** Returns a short description of the type parameter underlying a captured type, if available. */
- private static @Nullable String captureProvenanceDescription(Type type, String assignmentRole) {
- if (!(type instanceof Type.CapturedType capturedType)) {
- return null;
- }
- Type.TypeVar formalTypeVariable = capturedType.wildcard.bound;
- if (formalTypeVariable == null
- || !(formalTypeVariable.tsym.owner instanceof Symbol.ClassSymbol owner)
- || owner.getSimpleName().isEmpty()) {
- return null;
- }
- return String.format(
- "%s wildcard is the type argument for type variable %s of %s",
- assignmentRole, formalTypeVariable.tsym.getSimpleName(), owner.getSimpleName());
- }
-
- /**
- * A difference between the effective upper bounds of two corresponding wildcards.
- *
- *
The wildcard types are retained so the diagnostic can report provenance for the captured
- * wildcard or wildcards that directly caused the mismatch, without reporting unrelated captures
- * elsewhere in the enclosing types.
- */
- private record WildcardBoundMismatch(
- Type targetWildcardType,
- Type sourceWildcardType,
- String prettyTargetUpperBound,
- String prettySourceUpperBound) {}
-
private void reportInvalidReturnTypeError(
Tree tree, Type methodType, Type returnType, VisitorState state) {
ErrorBuilder errorBuilder = analysis.getErrorBuilder();
ErrorMessage errorMessage =
new ErrorMessage(
ErrorMessage.MessageTypes.RETURN_NULLABLE_GENERIC,
- errorMessageForIncompatibleTypesAtPseudoAssignment(methodType, returnType, state));
+ new NullabilityMismatchMessage(this, config, handler, state)
+ .build(methodType, returnType, false));
state.reportMatch(
errorBuilder.createErrorDescription(
errorMessage, analysis.buildDescription(tree), state, null));
@@ -668,8 +509,8 @@ private void reportInvalidParametersNullabilityError(
ErrorMessage errorMessage =
new ErrorMessage(
ErrorMessage.MessageTypes.PASS_NULLABLE_GENERIC,
- errorMessageForIncompatibleTypesAtPseudoAssignment(
- formalParameterType, actualParameterType, state));
+ new NullabilityMismatchMessage(this, config, handler, state)
+ .build(formalParameterType, actualParameterType, false));
state.reportMatch(
errorBuilder.createErrorDescription(
errorMessage, analysis.buildDescription(paramExpression), state, null));
@@ -1140,7 +981,9 @@ public void checkTypeParameterNullnessForAssignability(Tree tree, VisitorState s
if (varLocalDeclaration) {
lhsType = rhsType;
}
- boolean isAssignmentValid = subtypeParameterNullability(lhsType, rhsType, state);
+ boolean isAssignmentValid =
+ subtypeParameterNullability(
+ lhsType, rhsType, state, comparisonContextFor(ImmutableSet.of(), rhsTree));
if (!isAssignmentValid) {
reportInvalidAssignmentInstantiationError(tree, lhsType, rhsType, state);
}
@@ -1445,15 +1288,24 @@ private Type inferCallType(
if (callTree instanceof MethodInvocationTree invocationTree) {
Type inferredCallType =
TypeSubstitutionUtils.updateTypeWithInferredNullability(
- typeAtCallSite, executableType.getReturnType(), typeVarNullability, state, config);
+ typeAtCallSite,
+ executableType.getReturnType(),
+ typeVarNullability,
+ state,
+ config,
+ handler);
if (result instanceof InferenceSuccess successResult) {
- Nullness polyNullness = successResult.polyNullnessByInvocation.get(invocationTree);
+ ConstraintSolver.InferredNullability polyNullness =
+ successResult.polyNullnessByInvocation.get(invocationTree);
if (polyNullness != null) {
inferredCallType =
PolyNullInference.applyToReturnType(
inferredCallType,
handler.onGetPolyNullLocations(ASTHelpers.getSymbol(invocationTree), state),
- polyNullAnnotationType(polyNullness, state));
+ polyNullness,
+ state,
+ config,
+ handler);
}
}
return inferredCallType;
@@ -1462,7 +1314,12 @@ private Type inferCallType(
Type constructedTypeAtCallSite = getConstructedTypeAtCallSite((NewClassTree) callTree);
Type constructedTypeWithTypeVars = constructedTypeAtCallSite.tsym.type;
return TypeSubstitutionUtils.updateTypeWithInferredNullability(
- constructedTypeAtCallSite, constructedTypeWithTypeVars, typeVarNullability, state, config);
+ constructedTypeAtCallSite,
+ constructedTypeWithTypeVars,
+ typeVarNullability,
+ state,
+ config,
+ handler);
}
/**
@@ -1555,7 +1412,8 @@ private CallInferenceResult runInferenceForCall(
formalParamGroundTargetType,
typeVarNullability,
state,
- config);
+ config,
+ handler);
inferredPolyExpressionTypes.put(argument, typeWithInferredNullability);
}
}
@@ -1585,6 +1443,26 @@ private String inferenceFailureMessage(
if (polyNullInvocation != null) {
return PolyNullInference.inferenceFailureMessage(ASTHelpers.getSymbol(polyNullInvocation));
}
+ Type nullableBoundTypeVariable = e.getNullableBoundTypeVariable();
+ Element typeVariableWithNullableBound = e.getTypeVariableWithNullableBound();
+ if (nullableBoundTypeVariable != null && typeVariableWithNullableBound != null) {
+ Element passedElement = nullableBoundTypeVariable.tsym;
+ String constrained = withDeclaringElement(typeVariable, false);
+ String passed = withDeclaringElement(passedElement, false);
+ String withNullableBound = withDeclaringElement(typeVariableWithNullableBound, false);
+ if (constrained.equals(passed) || constrained.equals(withNullableBound)) {
+ constrained = withDeclaringElement(typeVariable, true);
+ passed = withDeclaringElement(passedElement, true);
+ withNullableBound = withDeclaringElement(typeVariableWithNullableBound, true);
+ }
+ String reason =
+ typeVariableWithNullableBound.equals(passedElement)
+ ? passed + " has a @Nullable upper bound"
+ : passed + " extends " + withNullableBound + ", which has a @Nullable upper bound";
+ return String.format(
+ "inference failure: type variable %s is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument %s passed for ? extends %s admits null, since %s",
+ constrained, nullableBoundTypeVariable, typeVariable, reason);
+ }
if (e.isCausedByNonNullUpperBound()) {
return String.format(
"inference failure: type variable %s is constrained to be @Nullable, but its upper bound requires it to be @NonNull",
@@ -1595,6 +1473,35 @@ private String inferenceFailureMessage(
typeVariable);
}
+ /**
+ * Returns the name of {@code typeVariable} followed by the class or method that declares it, such
+ * as {@code E of List.copyOf}, so that type variables of one name declared by different classes
+ * or methods can be told apart.
+ *
+ * @param qualified whether to name the class by its flat name, such as {@code java.util.List},
+ * rather than its simple name
+ */
+ private static String withDeclaringElement(Element typeVariable, boolean qualified) {
+ Symbol owner = ((Symbol) typeVariable).owner;
+ String ownerName =
+ owner instanceof Symbol.MethodSymbol method
+ ? method.isConstructor()
+ ? "the constructor of " + className(method.owner, qualified)
+ : className(method.owner, qualified) + "." + method.getSimpleName()
+ : className(owner, qualified);
+ return typeVariable.getSimpleName() + " of " + ownerName;
+ }
+
+ /**
+ * Returns the flat name of {@code type}, such as {@code Test$Inner}, where {@code qualified} is
+ * set or the class has no simple name, as an anonymous class does; its simple name otherwise.
+ */
+ private static String className(Symbol type, boolean qualified) {
+ return qualified || type.getSimpleName().isEmpty()
+ ? type.flatName().toString()
+ : type.getSimpleName().toString();
+ }
+
/** Returns the type parameters whose nullability is inferred for {@code callTree}. */
private List getCallTypeParameters(ExpressionTree callTree) {
if (callTree instanceof MethodInvocationTree invocationTree) {
@@ -2237,7 +2144,7 @@ private Type.MethodType getFunctionalInterfaceMethodType(
} else if (overridingMethod.asType() instanceof Type.ForAll) {
// the referenced method is a generic method and there are no explicit type arguments
// we need to substitute inferred nullability for type arguments if it was inferred
- result = getInferredMethodTypeForGenericMethodReference(result, state);
+ result = getInferredMethodTypeForGenericMethodReference(memberReferenceTree, result, state);
}
// finally, run any handlers
return handler.onOverrideMethodType(overridingMethod, result, state, null);
@@ -2547,7 +2454,11 @@ public void checkTypeParameterNullnessForFunctionReturnType(
return;
}
boolean isReturnTypeValid =
- subtypeParameterNullability(formalReturnType, returnExpressionType, state);
+ subtypeParameterNullability(
+ formalReturnType,
+ returnExpressionType,
+ state,
+ comparisonContextFor(ImmutableSet.of(), retExpr));
if (!isReturnTypeValid) {
reportInvalidReturnTypeError(retExpr, formalReturnType, returnExpressionType, state);
}
@@ -2583,11 +2494,54 @@ private boolean identicalTypeParameterNullability(
* @param state the visitor state
*/
boolean subtypeParameterNullability(Type lhsType, Type rhsType, VisitorState state) {
+ return subtypeParameterNullability(lhsType, rhsType, state, ComparisonContext.NONE);
+ }
+
+ /**
+ * Like {@link #subtypeParameterNullability(Type, Type, VisitorState)}, with what the caller knows
+ * about the compared types that the types do not show.
+ *
+ * @param lhsType type for the lhs of the assignment
+ * @param rhsType type for the rhs of the assignment
+ * @param state the visitor state
+ * @param context the uninferred type variables and the origin of {@code rhsType}
+ */
+ boolean subtypeParameterNullability(
+ Type lhsType, Type rhsType, VisitorState state, ComparisonContext context) {
return subtypeParameterNullability(
lhsType,
rhsType,
state,
- new CheckIdenticalNullabilityVisitor(state, this, config, handler));
+ new CheckIdenticalNullabilityVisitor(state, this, config, handler, context));
+ }
+
+ /**
+ * Returns the comparison context for the type NullAway computes for {@code actual}, where the
+ * type variables in {@code uninferredTypeVariables} are not instantiated.
+ */
+ private ComparisonContext comparisonContextFor(
+ ImmutableSet uninferredTypeVariables, ExpressionTree actual) {
+ return new ComparisonContext(uninferredTypeVariables, hasTypeOfCallInference(actual));
+ }
+
+ /**
+ * Returns whether the type NullAway computes for {@code expression} is the type of a generic
+ * method or diamond constructor call that needs inference: the expression is such a call, or a
+ * {@code var} local, whose type is that of its initializer, initialized with one.
+ */
+ private boolean hasTypeOfCallInference(ExpressionTree expression) {
+ ExpressionTree stripped = ASTHelpers.stripParentheses(expression);
+ if (isCallNeedingInference(stripped)) {
+ return true;
+ }
+ if (stripped instanceof IdentifierTree) {
+ TreePath declarationPath = varLocalDeclarations.get(ASTHelpers.getSymbol(stripped));
+ if (declarationPath != null) {
+ ExpressionTree initializer = ((VariableTree) declarationPath.getLeaf()).getInitializer();
+ return initializer != null && hasTypeOfCallInference(initializer);
+ }
+ }
+ return false;
}
/**
@@ -2756,12 +2710,20 @@ public void checkTypeParameterNullnessForConditionalExpression(
// the nullability annotations, we check that the true and false parts are assignable to the
// type of the whole expression
if (truePartType != null) {
- if (!subtypeParameterNullability(condExprType, truePartType, state)) {
+ if (!subtypeParameterNullability(
+ condExprType,
+ truePartType,
+ state,
+ comparisonContextFor(ImmutableSet.of(), tree.getTrueExpression()))) {
reportMismatchedTypeForTernaryOperator(truePartTree, condExprType, truePartType, state);
}
}
if (falsePartType != null) {
- if (!subtypeParameterNullability(condExprType, falsePartType, state)) {
+ if (!subtypeParameterNullability(
+ condExprType,
+ falsePartType,
+ state,
+ comparisonContextFor(ImmutableSet.of(), tree.getFalseExpression()))) {
reportMismatchedTypeForTernaryOperator(falsePartTree, condExprType, falsePartType, state);
}
}
@@ -2995,6 +2957,29 @@ public void compareGenericTypeParameterNullabilityForCall(
}
Type.MethodType finalMethodType =
getInvokedMethodTypeAtCall(methodSymbol, tree, null, state, false);
+ ImmutableSet uninferred =
+ tree instanceof NewClassTree
+ ? ImmutableSet.copyOf(methodSymbol.getTypeParameters())
+ : ImmutableSet.of();
+ compareArgumentsAtCall(tree, finalMethodType, uninferred, state);
+ }
+
+ /**
+ * Compares the type parameter nullability of each argument at a call with that of its formal
+ * parameter, as {@link #compareGenericTypeParameterNullabilityForCall} describes.
+ *
+ * @param tree the tree representing the call
+ * @param finalMethodType the type of the invoked method at the call
+ * @param uninferredTypeVariables type variables of the invoked constructor that NullAway does not
+ * instantiate at the call; empty for a method call
+ * @param state the visitor state
+ */
+ @SuppressWarnings("ReferenceEquality") // deliberate reference equality checks
+ private void compareArgumentsAtCall(
+ Tree tree,
+ Type.MethodType finalMethodType,
+ ImmutableSet uninferredTypeVariables,
+ VisitorState state) {
new InvocationArguments(tree, finalMethodType)
.forEach(
(currentActualParam, argPos, formalParameter, unused) -> {
@@ -3023,13 +3008,24 @@ public void compareGenericTypeParameterNullabilityForCall(
handler)) {
Type groundFormalParameter =
GenericsUtils.groundTargetType(formalParameter, state, config, handler);
+ Symbol.MethodSymbol referencedMethod = ASTHelpers.getSymbol(memberReferenceTree);
+ ComparisonContext referenceContext =
+ new ComparisonContext(
+ referencedMethod != null
+ ? ImmutableSet.builder()
+ .addAll(uninferredTypeVariables)
+ .addAll(referencedMethod.getTypeParameters())
+ .build()
+ : uninferredTypeVariables,
+ false);
GenericsUtils.processMethodRefTypeRelations(
this,
groundFormalParameter,
memberReferenceTree,
actualParameterAndState.state(),
(subtype, supertype, relationKind) -> {
- if (!subtypeParameterNullability(supertype, subtype, state)) {
+ if (!subtypeParameterNullability(
+ supertype, subtype, state, referenceContext)) {
if (relationKind == MethodRefTypeRelationKind.RETURN) {
reportInvalidMethodReferenceReturnTypeError(
memberReferenceTree, supertype, subtype, state);
@@ -3082,7 +3078,11 @@ public void compareGenericTypeParameterNullabilityForCall(
if (actualParameterType == null) {
return;
}
- if (!subtypeParameterNullability(formalParameter, actualParameterType, state)) {
+ if (!subtypeParameterNullability(
+ formalParameter,
+ actualParameterType,
+ state,
+ comparisonContextFor(uninferredTypeVariables, currentActualParam))) {
reportInvalidParametersNullabilityError(
formalParameter, actualParameterType, currentActualParam, state);
}
@@ -3091,36 +3091,59 @@ public void compareGenericTypeParameterNullabilityForCall(
}
/**
- * For a generic method reference, if it is being called in a context that requires type argument
- * nullability inference, return the method type with inferred nullability for type parameters.
- * Otherwise, return the original method type.
- *
- * @param methodType the original method type
+ * Returns the type of the method that a generic method reference refers to, with the nullness
+ * inferred for its type parameters, where the reference is an argument of a method call or a
+ * diamond {@code new} whose inference succeeded. Where {@link
+ * Config#isNullableBoundInferenceEnabled} is false, only a method call parent is considered and
+ * the nullness is copied onto {@code methodType} rather than onto the type javac inferred.
+ *
+ * @param memberReferenceTree the generic method reference
+ * @param methodType the member type of the referenced method, with the receiver's type arguments
+ * substituted, before inference of the method's own type arguments
* @param state the visitor state (generic method reference should be leaf of {@code
* state.getPath()})
- * @return the method type with inferred nullability for type parameters if inference was
- * performed, or the original method type otherwise
+ * @return the type javac inferred for the referenced method at the reference, with the inferred
+ * nullness copied onto it; {@code methodType} with that nullness where javac's type has
+ * another number of parameters or {@link Config#isNullableBoundInferenceEnabled} is false;
+ * {@code methodType} unchanged where the enclosing call needs no inference, or is not a
+ * method call while that predicate is false, or its inference failed
*/
private Type.MethodType getInferredMethodTypeForGenericMethodReference(
- Type.MethodType methodType, VisitorState state) {
+ MemberReferenceTree memberReferenceTree, Type.MethodType methodType, VisitorState state) {
TreePath parentPath = state.getPath().getParentPath();
while (parentPath != null && parentPath.getLeaf() instanceof ParenthesizedTree) {
parentPath = parentPath.getParentPath();
}
Tree parentTree = parentPath != null ? parentPath.getLeaf() : null;
- if (parentTree instanceof MethodInvocationTree methodInvocationTree
- && isCallNeedingInference(methodInvocationTree)) {
+ boolean useInferredReferentType = config.isNullableBoundInferenceEnabled();
+ if (parentTree instanceof ExpressionTree parentExpression
+ && (useInferredReferentType || parentTree instanceof MethodInvocationTree)
+ && isCallNeedingInference(parentExpression)) {
CallInferenceResult inferenceResult =
- inferredTypeVarNullabilityForGenericCalls.get(methodInvocationTree);
+ inferredTypeVarNullabilityForGenericCalls.get(parentTree);
if (inferenceResult instanceof InferenceSuccess successResult) {
- // the referenced method's type variables are inferred at the method reference itself
- Tree memberReferenceTree = state.getPath().getLeaf();
+ // the type javac inferred for the referenced method decides what an inference variable
+ // whose nullness depends on it resolves to; the referenced method's type variables are
+ // inferred at the method reference itself
+ Type referentType = ((JCTree.JCMemberReference) memberReferenceTree).referentType;
+ // the inferred nullness is copied parameter by parameter, so a referent type of another
+ // arity falls back to the declared type; no call shape is known to produce one, a
+ // varargs method referenced with two arguments included
+ Type.MethodType typeToUpdate =
+ useInferredReferentType
+ && referentType instanceof Type.MethodType referentMethodType
+ // diff-coverage: ignore -- defensive guard, no known call shape reaches it
+ && referentMethodType.getParameterTypes().size()
+ == methodType.getParameterTypes().size()
+ ? referentMethodType
+ : methodType;
return TypeSubstitutionUtils.updateMethodTypeWithInferredNullability(
- methodType,
+ typeToUpdate,
methodType,
successResult.typeVarNullabilityForSite(memberReferenceTree),
state,
- config);
+ config,
+ handler);
}
}
return methodType;
@@ -3152,10 +3175,13 @@ public void checkTypeParameterNullnessForMethodOverriding(
.isSymbolUnannotated(overriddenMethod, config, handler)) {
return;
}
- checkTypeParameterNullnessForOverridingMethodReturnType(tree, overriddenMethodType, state);
- checkTypeParameterNullnessForOverridingMethodParameterType(tree, overriddenMethodType, state);
- checkMethodTypeVariableUpperBoundNullnessForOverriding(
- tree, overridingMethod, overriddenMethod, overriddenMethodType, state);
+ // JLS 8.4.4 compares the signatures of methods with the same type parameters only; where the
+ // nullness of a bound differs, the bound mismatch is the error to report
+ if (checkMethodTypeVariableUpperBoundNullnessForOverriding(
+ tree, overridingMethod, overriddenMethod, overriddenMethodType, state)) {
+ checkTypeParameterNullnessForOverridingMethodReturnType(tree, overriddenMethodType, state);
+ checkTypeParameterNullnessForOverridingMethodParameterType(tree, overriddenMethodType, state);
+ }
}
/**
@@ -3258,8 +3284,10 @@ public Type getModeledOverriddenMethodType(
* @param overriddenMethodType type of the overridden method after member-type substitution in the
* overriding class context
* @param state the visitor state
+ * @return whether every corresponding pair of upper bounds agrees in nullability, so that nothing
+ * was reported
*/
- private void checkMethodTypeVariableUpperBoundNullnessForOverriding(
+ private boolean checkMethodTypeVariableUpperBoundNullnessForOverriding(
MethodTree tree,
Symbol.MethodSymbol overridingMethod,
Symbol.MethodSymbol overriddenMethod,
@@ -3267,15 +3295,16 @@ private void checkMethodTypeVariableUpperBoundNullnessForOverriding(
VisitorState state) {
// Generic methods are Type.ForAll; non-generic overridden methods have no method type vars.
if (!(overriddenMethodType instanceof Type.ForAll forAll)) {
- return;
+ return true;
}
com.sun.tools.javac.util.List overriddenTypeVars = forAll.tvars;
List overridingTypeParams = overridingMethod.getTypeParameters();
// If counts differ, javac would not treat this as a valid override; leave that to the
// compiler.
if (overridingTypeParams.size() != overriddenTypeVars.size()) {
- return;
+ return true;
}
+ boolean boundsAgree = true;
List extends Tree> typeParameterTrees = tree.getTypeParameters();
for (int i = 0; i < overridingTypeParams.size(); i++) {
Symbol.TypeVariableSymbol overridingTv = overridingTypeParams.get(i);
@@ -3287,6 +3316,7 @@ private void checkMethodTypeVariableUpperBoundNullnessForOverriding(
substitutedMethodTypeVarUpperBoundIsNullable(
overriddenTypeVar, overriddenMethod, i, state);
if (overridingNullable != overriddenNullable) {
+ boundsAgree = false;
reportMismatchedMethodTypeVariableBoundError(
typeParameterTrees.get(i),
overridingTv,
@@ -3296,6 +3326,7 @@ private void checkMethodTypeVariableUpperBoundNullnessForOverriding(
state);
}
}
+ return boundsAgree;
}
/**
@@ -3641,7 +3672,7 @@ private Type.MethodType substituteTypeArgsInGenericMethodType(
: ((NewClassTree) tree).getTypeArguments();
com.sun.tools.javac.util.List explicitTypeArgs = convertTreesToTypes(typeArgumentTrees);
Type.MethodType substitutedMethodType;
- Nullness jointlyInferredPolyNullness = null;
+ ConstraintSolver.InferredNullability jointlyInferredPolyNullness = null;
boolean genericInferenceFailed = false;
// There are no explicit type arguments, so use the inferred types
@@ -3692,7 +3723,8 @@ private Type.MethodType substituteTypeArgsInGenericMethodType(
methodType,
successResult.typeVarNullabilityForSite(invocationTree),
state,
- config);
+ config,
+ handler);
jointlyInferredPolyNullness = successResult.polyNullnessByInvocation.get(invocationTree);
} else {
// Inference failed; use the call-site type without inferred nullability substitutions.
@@ -3965,6 +3997,10 @@ private Type.MethodType getInvokedMethodTypeAtCall(
&& invokedMethodType instanceof Type.ForAll forAllType) {
return substituteTypeArgsInGenericMethodType(
tree, forAllType, path, state, calledFromDataflow);
+ } else if (config.isNullableBoundInferenceEnabled()
+ && tree instanceof NewClassTree newClassTree
+ && invokedMethodType instanceof Type.ForAll forAllType) {
+ invokedMethodType = substituteInferredConstructorTypeArgs(newClassTree, forAllType, state);
}
Type.MethodType modeledMethodType =
handler.onOverrideMethodType(
@@ -3992,7 +4028,7 @@ private Type.MethodType applyPolyNullModel(
Symbol.MethodSymbol methodSymbol,
MethodInvocationTree invocationTree,
Type.MethodType substitutedMethodType,
- @Nullable Nullness jointlyInferredPolyNullness,
+ ConstraintSolver.@Nullable InferredNullability jointlyInferredPolyNullness,
@Nullable TreePath path,
VisitorState state,
boolean calledFromDataflow) {
@@ -4000,7 +4036,7 @@ private Type.MethodType applyPolyNullModel(
if (locations.isEmpty()) {
return substitutedMethodType;
}
- Nullness polyNullness =
+ ConstraintSolver.InferredNullability polyNullness =
jointlyInferredPolyNullness != null
? jointlyInferredPolyNullness
: inferPolyNullnessSeparately(
@@ -4015,23 +4051,30 @@ private Type.MethodType applyPolyNullModel(
return substitutedMethodType;
}
return PolyNullInference.applyToMethodType(
- substitutedMethodType, locations, polyNullAnnotationType(polyNullness, state));
+ substitutedMethodType, locations, polyNullness, state, config, handler);
}
/**
* Infers the nullness shared by all PolyNull occurrences when no jointly inferred value is
* available. This includes non-generic calls and generic calls with explicit type arguments.
*
- *
All modeled locations share one synthetic type variable. Ordinary assignment-compatibility
- * constraints select {@code @NonNull} unless an argument or the result target requires
- * {@code @Nullable}.
+ *
All modeled locations share one synthetic type variable, which ordinary
+ * assignment-compatibility constraints fix as {@code @Nullable} or {@code @NonNull} where an
+ * argument or the result target requires it. Where no constraint fixes it and an argument passes
+ * a type variable with parametric nullness, each location takes the annotation {@link
+ * GenericsUtils#inferredNullnessAnnotation} gives it: a location where javac inferred a type
+ * variable with parametric nullness or an intersection type stays unannotated, and any other
+ * location is {@code @Nullable} where the bound of the passed type variable is explicitly
+ * nullable, and {@code @NonNull} otherwise. So with a {@code Supplier} argument, {@code T
+ * extends @Nullable Object}, and no non-null result target, a location inferred as {@code T}
+ * stays {@code T} and a class-type location becomes {@code @Nullable}.
*
* @return the inferred shared nullness, or {@code null} if no modeled parameter location applies.
* Unsatisfiable constraints return {@code null} when {@code WarnOnGenericInferenceFailure} is
- * enabled; otherwise they return {@code Nullness.NULLABLE} to preserve ordinary nullness
- * errors. They are reported only outside dataflow.
+ * enabled; otherwise they return {@code NULLABLE} to preserve ordinary nullness errors. They
+ * are reported only outside dataflow.
*/
- private @Nullable Nullness inferPolyNullnessSeparately(
+ private ConstraintSolver.@Nullable InferredNullability inferPolyNullnessSeparately(
Symbol.MethodSymbol methodSymbol,
MethodInvocationTree invocationTree,
Type.MethodType substitutedMethodType,
@@ -4039,7 +4082,8 @@ private Type.MethodType applyPolyNullModel(
@Nullable TreePath path,
VisitorState state,
boolean calledFromDataflow) {
- Nullness cached = separatelyInferredPolyNullness.get(invocationTree);
+ ConstraintSolver.InferredNullability cached =
+ separatelyInferredPolyNullness.get(invocationTree);
if (cached != null) {
return cached;
}
@@ -4076,7 +4120,7 @@ private Type.MethodType applyPolyNullModel(
calledFromDataflow);
Map solution =
solver.solve();
- Nullness resolved =
+ ConstraintSolver.InferredNullability resolved =
PolyNullInference.resolveContext(invocationTree, inferenceContext, solution);
if (!calledFromDataflow) {
separatelyInferredPolyNullness.put(invocationTree, resolved);
@@ -4088,7 +4132,9 @@ private Type.MethodType applyPolyNullModel(
PolyNullInference.inferenceFailureMessage(ASTHelpers.getSymbol(invocationTree)),
state,
calledFromDataflow);
- return config.warnOnGenericInferenceFailure() ? null : Nullness.NULLABLE;
+ return config.warnOnGenericInferenceFailure()
+ ? null
+ : ConstraintSolver.InferredNullability.NULLABLE;
}
}
@@ -4185,11 +4231,38 @@ private void reportInferenceFailure(
errorMessage, analysis.buildDescription(callTree), state, null));
}
- /** Returns the synthetic annotation type representing the resolved PolyNull qualifier. */
- private static Type polyNullAnnotationType(Nullness nullness, VisitorState state) {
- return nullness == Nullness.NULLABLE
- ? getSyntheticNullableAnnotType(state)
- : getSyntheticNonNullAnnotType(state);
+ /**
+ * Returns the type of a generic constructor at a diamond call, with the nullness inferred for the
+ * constructor's own type variables. Returns {@code forAllType} unchanged where the call has
+ * explicit type arguments, where its inference did not run or failed, and where the constructor
+ * javac resolved has more parameters than the declared one, as the constructor of an anonymous
+ * subclass of an inner class has: it takes the enclosing instance first.
+ *
+ * @param tree the constructor call
+ * @param forAllType the constructor's type, with the class type variables already substituted
+ * @param state the visitor state
+ */
+ private Type substituteInferredConstructorTypeArgs(
+ NewClassTree tree, Type.ForAll forAllType, VisitorState state) {
+ if (!tree.getTypeArguments().isEmpty()
+ || !(inferredTypeVarNullabilityForGenericCalls.get(tree)
+ instanceof InferenceSuccess successResult)) {
+ return forAllType;
+ }
+ Type.MethodType declaredMethodType = forAllType.asMethodType();
+ Type constructorTypeAtCallSite = ((JCTree.JCNewClass) tree).constructorType;
+ if (!(constructorTypeAtCallSite instanceof Type.MethodType methodTypeAtCallSite)
+ || methodTypeAtCallSite.getParameterTypes().size()
+ != declaredMethodType.getParameterTypes().size()) {
+ return forAllType;
+ }
+ return TypeSubstitutionUtils.updateMethodTypeWithInferredNullability(
+ methodTypeAtCallSite,
+ declaredMethodType,
+ successResult.typeVarNullabilityForSite(tree),
+ state,
+ config,
+ handler);
}
/**
@@ -4527,7 +4600,13 @@ private void checkTypeParameterNullnessForOverridingMethodParameterType(
if (overridingMethodParameterType != null) {
// allow contravariant subtyping
if (!subtypeParameterNullability(
- overridingMethodParameterType, overriddenMethodParameterType, state)) {
+ adaptToOverriddenTypeParameters(
+ overridingMethodParameterType,
+ ASTHelpers.getSymbol(tree).type,
+ overriddenMethodType,
+ state),
+ overriddenMethodParameterType,
+ state)) {
reportInvalidOverridingMethodParamTypeError(
methodParameters.get(i),
overriddenMethodParameterType,
@@ -4538,6 +4617,23 @@ private void checkTypeParameterNullnessForOverridingMethodParameterType(
}
}
+ /**
+ * Adapts {@code type} to the type parameters of the overridden method, as JLS 8.4.4 defines for
+ * methods with the same type parameters: each type variable of the overriding method is replaced
+ * by the corresponding one of the overridden method, so that a bound written against one can be
+ * compared with a use of the other. The result is for the comparison only; a diagnostic prints
+ * the type as declared.
+ */
+ private Type adaptToOverriddenTypeParameters(
+ Type type, Type overridingMethodType, Type overriddenMethodType, VisitorState state) {
+ if (overridingMethodType instanceof Type.ForAll overriding
+ && overriddenMethodType instanceof Type.ForAll overridden) {
+ return TypeSubstitutionUtils.subst(
+ state.getTypes(), type, overriding.tvars, overridden.tvars, config);
+ }
+ return type;
+ }
+
/**
* This method compares the type parameter annotations for an overriding method's return type with
* corresponding type parameters for the overridden method and reports an error if they don't
@@ -4558,7 +4654,13 @@ private void checkTypeParameterNullnessForOverridingMethodReturnType(
}
// allow covariant subtyping
if (!subtypeParameterNullability(
- overriddenMethodReturnType, overridingMethodReturnType, state)) {
+ overriddenMethodReturnType,
+ adaptToOverriddenTypeParameters(
+ overridingMethodReturnType,
+ ASTHelpers.getSymbol(tree).type,
+ overriddenMethodType,
+ state),
+ state)) {
reportInvalidOverridingMethodReturnTypeError(
tree, overriddenMethodReturnType, overridingMethodReturnType, state);
}
@@ -4695,9 +4797,10 @@ private static Nullness getTypeNullnessForRead(
/**
* Returns a pretty-printed representation of type suitable for error messages. The representation
- * uses simple names rather than fully-qualified names, and retains all type-use annotations.
+ * uses simple names rather than fully-qualified names, and keeps {@code @Nullable} and drops
+ * every other type-use annotation.
*/
- private static String prettyTypeForError(Type type, VisitorState state) {
+ static String prettyTypeForError(Type type, VisitorState state) {
return type.accept(new GenericTypePrettyPrintingVisitor(state), null);
}
@@ -4837,12 +4940,12 @@ public static ValueTarget arrayElement(@Nullable Type arrayType) {
* Returns whether {@code target} accepts a value of type {@code valueType} for which {@link
* Nullness#isNoChange()} holds. Such a value is null only when the corresponding type variable
* {@code T} is instantiated with a nullable type argument. A location accepts it when its type is
- * a type variable {@code T}, or a capture of {@code ? super T}, such that neither the type nor
- * the location's declaration is annotated {@code @NonNull}, and {@code valueType} is {@code T} or
- * a subtype of {@code T} that reaches {@code T} through upper bounds none of which is nullable.
- * Then the assigned location admits null whenever the value may be null. In {@code }, the bound of {@code U} breaks the chain, since {@code U} may be nullable
- * while {@code T} is not.
+ * a type variable {@code T}, a capture included, or a capture of {@code ? super T}, such that
+ * neither {@code T} nor the location's declaration is annotated {@code @NonNull}, and {@code
+ * valueType} is {@code T} or a subtype of {@code T} that reaches {@code T} through upper bounds
+ * none of which is nullable. Then the assigned location admits null whenever the value may be
+ * null. In {@code }, the bound of {@code U} breaks the chain, since {@code
+ * U} may be nullable while {@code T} is not.
*
*
This test should be applied to the {@link ValueTarget} of the assigned location at every
* pseudo-assignment, so that a {@code NO_CHANGE} fact always holds relative to the static type of
@@ -4855,18 +4958,26 @@ public static ValueTarget arrayElement(@Nullable Type arrayType) {
public boolean acceptsNoChangeValue(Type valueType, ValueTarget target, VisitorState state) {
Type targetType = target.type();
Symbol declaration = target.declaration();
- // A capture of ? super T accepts every value of type T
- Type typeVariable =
- targetType instanceof Type.CapturedType capturedType
- ? capturedType.getLowerBound()
- : targetType;
if (target.excludesNull()
- || !(typeVariable instanceof Type.TypeVar)
- || GenericsUtils.isAnnotatedAsNonNull(typeVariable, config)
|| (declaration != null && Nullness.hasNonNullAnnotation(declaration, config))) {
return false;
}
- return reachesThroughNonNullableBounds(valueType, typeVariable, state);
+ return acceptsNoChangeValueOf(valueType, targetType, state)
+ // A capture of ? super T accepts every value of type T
+ || (targetType instanceof Type.CapturedType capturedType
+ && acceptsNoChangeValueOf(valueType, capturedType.getLowerBound(), state));
+ }
+
+ /**
+ * Returns whether {@code typeVariable} is a type variable, a capture included, that is not
+ * annotated {@code @NonNull} and that {@code valueType} reaches by {@link
+ * #reachesThroughNonNullableBounds}.
+ */
+ private boolean acceptsNoChangeValueOf(
+ Type valueType, @Nullable Type typeVariable, VisitorState state) {
+ return typeVariable instanceof Type.TypeVar
+ && !GenericsUtils.isAnnotatedAsNonNull(typeVariable, config)
+ && reachesThroughNonNullableBounds(valueType, typeVariable, state);
}
/**
diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java
index 0da472288f..b095911b10 100644
--- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java
+++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java
@@ -377,10 +377,62 @@ private static Type applyDeclarationUpperBoundNullabilityIfApplicable(
return upperBound;
}
- private static boolean hasNullnessAnnotation(Type type, Config config) {
+ static boolean hasNullnessAnnotation(Type type, Config config) {
return isAnnotatedAsNonNull(type, config) || isAnnotatedAsNullable(type, config);
}
+ /**
+ * Returns the synthetic nullness annotation type that {@code inferred} adds to {@code
+ * inferredType}, the type javac inferred for the variable at one location, or {@code null} where
+ * that type takes no synthetic annotation.
+ *
+ *
{@code NULLABLE} and {@code NONNULL} annotate every type. {@code TYPE_VARIABLE_OR_NULLABLE}
+ * and {@code TYPE_VARIABLE_OR_NONNULL} add no annotation to an {@code inferredType} that has
+ * parametric nullness, the test ({@link #hasParametricNullness}) the solver also applies to a
+ * type that flows into the variable, or to an intersection type, whose nullness comes from its
+ * elements and stays non-null where they exclude null. Any other type, including a wildcard and a
+ * type variable with a nullness annotation, takes {@code @Nullable} for {@code
+ * TYPE_VARIABLE_OR_NULLABLE} and {@code @NonNull} for {@code TYPE_VARIABLE_OR_NONNULL}.
+ */
+ static @Nullable Type inferredNullnessAnnotation(
+ Type inferredType,
+ ConstraintSolver.InferredNullability inferred,
+ Config config,
+ Handler handler,
+ VisitorState state) {
+ return switch (inferred) {
+ case NULLABLE -> GenericsChecks.getSyntheticNullableAnnotType(state);
+ case NONNULL -> GenericsChecks.getSyntheticNonNullAnnotType(state);
+ case TYPE_VARIABLE_OR_NULLABLE ->
+ inferredType.isCompound() || hasParametricNullness(inferredType, config, handler, state)
+ ? null
+ : GenericsChecks.getSyntheticNullableAnnotType(state);
+ case TYPE_VARIABLE_OR_NONNULL ->
+ inferredType.isCompound() || hasParametricNullness(inferredType, config, handler, state)
+ ? null
+ : GenericsChecks.getSyntheticNonNullAnnotType(state);
+ };
+ }
+
+ /**
+ * Returns whether {@code type} has parametric nullness as NullAway decides it: it is a type
+ * variable, a captured one included, that carries no nullness annotation at this use and whose
+ * bound admits null by {@link #upperBoundIsNullable}, which counts the default for a type
+ * variable declared in unannotated code. Such a use includes null exactly where the type argument
+ * substituted for it does. The closest JSpecify notion is the {@code NO_CHANGE} nullness
+ * operator, which also covers an unannotated type variable whose bound excludes null and does not
+ * cover one declared in null-unmarked code.
+ *
+ * @see JSpecify: nullness
+ * operator
+ */
+ static boolean hasParametricNullness(
+ Type type, Config config, Handler handler, VisitorState state) {
+ return type instanceof Type.TypeVar typeVariable
+ && !hasNullnessAnnotation(type, config)
+ && upperBoundIsNullable(typeVariable.asElement(), config, handler, state);
+ }
+
/**
* Returns true if the upper bound of the given type variable should be treated as nullable.
*
@@ -417,8 +469,82 @@ static boolean declaredUpperBoundIsNullable(
if (fromUnannotatedMethodOrClass(typeVarElement, config, handler, state)) {
return true;
}
- // Models use declaration indices, which fresh inference symbols do not have. Keep looking at
- // the fresh bound below, but consult its original declaration for library-model overrides.
+ if (libraryModelMakesBoundNullable(typeVarElement, handler, state)) {
+ return true;
+ }
+ Type upperBound = (Type) ((TypeVariable) typeVarElement.asType()).getUpperBound();
+ return isAnnotatedAsNullable(upperBound, config);
+ }
+
+ /**
+ * Returns true if the upper bound of the given type variable is explicitly nullable, as {@link
+ * #typeVariableWithNullableBound} defines it.
+ */
+ static boolean boundIsExplicitlyNullable(
+ Element typeVarElement, Config config, Handler handler, VisitorState state) {
+ return typeVariableWithNullableBound(typeVarElement, config, handler, state) != null;
+ }
+
+ /**
+ * Returns the type variable whose declared bound makes the bound of {@code typeVarElement}
+ * explicitly nullable, or {@code null} where that bound is not explicitly nullable.
+ *
+ *
A declared bound is explicitly nullable where it is annotated {@code @Nullable} or a library
+ * model makes it nullable; that type variable is the result. A declared bound that is another
+ * type variable and carries no nullness annotation is explicitly nullable where the bound of that
+ * type variable is, so for {@code } the
+ * result for {@code T} is {@code S}. Unlike {@link #upperBoundIsNullable}, a type variable
+ * declared in unannotated code gets no nullable default, while a {@code @Nullable} written there
+ * still counts, as JSpecify gives annotations in null-unmarked code their meaning.
+ */
+ static @Nullable Element typeVariableWithNullableBound(
+ Element typeVarElement, Config config, Handler handler, VisitorState state) {
+ if (declaredBoundIsExplicitlyNullable(typeVarElement, config, handler, state)) {
+ return typeVarElement;
+ }
+ Type upperBound = (Type) ((TypeVariable) typeVarElement.asType()).getUpperBound();
+ return !hasNullnessAnnotation(upperBound, config) && upperBound.getKind() == TypeKind.TYPEVAR
+ ? typeVariableWithNullableBound(upperBound.asElement(), config, handler, state)
+ : null;
+ }
+
+ /**
+ * Returns true if the declared upper bound of the given type variable is annotated
+ * {@code @Nullable}, in every element for an intersection, or a library model makes it nullable.
+ * Unlike {@link #typeVariableWithNullableBound}, this does not follow a bound that is itself a
+ * type variable, and unlike {@link #declaredUpperBoundIsNullable}, a type variable declared in
+ * unannotated code gets no nullable default.
+ */
+ static boolean declaredBoundIsExplicitlyNullable(
+ Element typeVarElement, Config config, Handler handler, VisitorState state) {
+ Type upperBound = (Type) ((TypeVariable) typeVarElement.asType()).getUpperBound();
+ return isAnnotatedAsNullable(upperBound, config)
+ || libraryModelMakesBoundNullable(typeVarElement, handler, state);
+ }
+
+ /**
+ * Returns the declared upper bound of {@code typeVariable}, annotated {@code @Nullable} where
+ * {@link #boundIsExplicitlyNullable} holds and the bound does not carry the annotation itself.
+ *
+ *
This describes the declaration and not a use of it: a {@code @Nullable T} carries its own
+ * nullness where it is written, and a caller that replaced it with this bound would discard it.
+ */
+ static Type typeVariableUpperBound(
+ Type.TypeVar typeVariable, VisitorState state, Config config, Handler handler) {
+ Type upperBound = typeVariable.getUpperBound();
+ if (boundIsExplicitlyNullable(typeVariable.asElement(), config, handler, state)
+ && !Nullness.hasNullableAnnotation(upperBound.getAnnotationMirrors().stream(), config)) {
+ return TypeSubstitutionUtils.typeWithAnnot(
+ upperBound, GenericsChecks.getSyntheticNullableAnnotType(state));
+ }
+ return upperBound;
+ }
+
+ /** Returns true if a library model overrides the upper bound of the given type variable. */
+ private static boolean libraryModelMakesBoundNullable(
+ Element typeVarElement, Handler handler, VisitorState state) {
+ // Models use declaration indices, which fresh inference symbols do not have, so consult the
+ // original declaration of a fresh symbol.
Element modeledTypeVariable = typeVarElement;
while (modeledTypeVariable instanceof FreshTypeVariableSymbol freshSymbol) {
modeledTypeVariable = freshSymbol.declaredSymbol;
@@ -442,11 +568,14 @@ static boolean declaredUpperBoundIsNullable(
return true;
}
}
- Type upperBound = (Type) ((TypeVariable) typeVarElement.asType()).getUpperBound();
- return isAnnotatedAsNullable(upperBound, config);
+ return false;
}
- private static boolean fromUnannotatedMethodOrClass(
+ /**
+ * Returns true if {@code typeVarElement} is declared by a method or class that NullAway treats as
+ * unannotated code.
+ */
+ static boolean fromUnannotatedMethodOrClass(
Element typeVarElement, Config config, Handler handler, VisitorState state) {
Element enclosingElement = typeVarElement.getEnclosingElement();
if (!(enclosingElement instanceof Symbol.MethodSymbol)
diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java
new file mode 100644
index 0000000000..6922aab756
--- /dev/null
+++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java
@@ -0,0 +1,855 @@
+package com.uber.nullaway.generics;
+
+import static com.uber.nullaway.generics.TypeMetadataBuilder.TYPE_METADATA_BUILDER;
+
+import com.google.errorprone.VisitorState;
+import com.google.errorprone.util.ASTHelpers;
+import com.sun.tools.javac.code.Attribute;
+import com.sun.tools.javac.code.BoundKind;
+import com.sun.tools.javac.code.Symbol;
+import com.sun.tools.javac.code.Symtab;
+import com.sun.tools.javac.code.Type;
+import com.sun.tools.javac.code.TypeTag;
+import com.sun.tools.javac.code.Types;
+import com.uber.nullaway.Config;
+import com.uber.nullaway.Nullness;
+import com.uber.nullaway.handlers.Handler;
+import java.util.ArrayList;
+import java.util.IdentityHashMap;
+import java.util.List;
+import javax.lang.model.type.TypeKind;
+import org.jspecify.annotations.Nullable;
+
+/**
+ * Renders the diagnostic for a pseudo-assignment whose source type does not have the nullness its
+ * target type requires.
+ *
+ *
The message is built from the positions {@link NullabilityMismatches} found, and this class
+ * decides what a reader is told about them. The rules below are the contract every such message
+ * follows, and a new reporter that reaches this class inherits them; a reporter that builds its own
+ * message text is not bound by them and reads worse for it.
+ *
+ *
The vocabulary
+ *
+ *
Four words carry the message, and they mean the same thing wherever they appear. {@code found}
+ * is what the source has, {@code required} is what the target demands, {@code path} is where in the
+ * type that pair sits, and {@code note} is a fact about the source that its printed form does not
+ * show. A reader who has learned one message has learned every other, and a tool matching on the
+ * text has four stable keys rather than a sentence to parse.
+ *
+ *
The first line
+ *
+ *
It opens {@code incompatible nullability:} and then states the one difference, or how many
+ * there are where naming one would misrepresent the rest. It states the two nodes rather than
+ * calling the source unassignable to the target, because the difference runs both ways: a type
+ * argument the source states outright has to match, so {@code String} fails against
+ * {@code @Nullable String} as surely as the reverse. That direction is the one a reader can misread
+ * as a false subtype claim, since every {@code String} is a {@code @Nullable String}, so there the
+ * line says first that a type argument has to match exactly. It never carries the two whole types,
+ * which are printed below where a caret can point into them.
+ *
+ *
The caret
+ *
+ *
A caret marks the smallest node whose nullness differs, {@code @Nullable String} rather than
+ * the {@code Collection<@Nullable String>} around it, and it marks that node in both printed types.
+ * The comparison views the source as the target's supertype, so which node of the type the reader
+ * wrote the caret belongs under is a question with two answers: where the view is that same class,
+ * the position is the same position; where it is another class, only a node the substitution
+ * carried over rather than rebuilt can be pointed at. Where neither answers, the view is printed as
+ * {@code found as} and carries the carets, so a caret marks the type the check compared rather than
+ * a node in one where the difference cannot be seen.
+ *
+ *
A note explains itself in the entities the message already shows, and it appears where the
+ * printed source does not carry the nullness the comparison used: under a wildcard that inherits a
+ * bound, and under a type variable whose own declaration supplies one. Where the source wildcard
+ * stands at a position of the type the reader wrote, including one the supertype view carried over
+ * from it, the note names the type parameter it takes its bound from. Where the view rebuilt the
+ * wildcard, as from the supertype a subclass declares, that parameter belongs to a declaration this
+ * message never prints, and naming it would set a second frame of reference against the {@code
+ * path} line: {@code Base type argument B} beside {@code type parameter S of Sub} reads as a
+ * contradiction rather than as two answers. The note there states the bound and stops. Where the
+ * node is one a side does not print, as with the bound an unbounded wildcard leaves implicit, the
+ * caret rises to the deepest node that side does print, and a {@code note} says what the reader
+ * cannot see there. Where a position cannot be told from another, because one type instance sits at
+ * two of them, that side gets no caret at all: a caret under a guess is worse than none, and the
+ * {@code path} line still names the position.
+ *
+ *
The repairs
+ *
+ *
Two repairs may be offered, and both are checked before they are printed: the candidate is
+ * passed to the predicate that rejected the assignment, and it has to print as Java a reader could
+ * write, since a type the check accepts may still print {@code capture of ?}.
+ *
+ *
They differ in what they presume. Writing an explicit bound on a wildcard the reader already
+ * wrote is a mechanical repair of that wildcard, so it is offered wherever it works. Changing the
+ * required type is a claim about which side of a contract is wrong, which this class cannot know,
+ * so it comes with two limits: it is offered only where the required type is written at the
+ * diagnostic itself, as it is in a variable declaration, and it only ever adds {@code @Nullable}.
+ * At a call the required type comes from a signature somewhere else, and proposing an edit to it
+ * would be a guess at what that signature is for; taking a {@code @Nullable} away would be a guess
+ * of the same kind about a contract the author stated on purpose.
+ *
+ *
A repair also has to survive printing. The printer shows {@code @Nullable} and drops every
+ * other type-use annotation, which costs a message that only describes a type nothing, and costs a
+ * reader who pastes one whatever the printer left out, so a type carrying such an annotation is not
+ * offered.
+ */
+final class NullabilityMismatchMessage {
+
+ private final GenericsChecks checks;
+ private final Config config;
+ private final Handler handler;
+ private final VisitorState state;
+
+ NullabilityMismatchMessage(
+ GenericsChecks checks, Config config, Handler handler, VisitorState state) {
+ this.checks = checks;
+ this.config = config;
+ this.handler = handler;
+ this.state = state;
+ }
+
+ /** How many mismatches a message lists before it says only how many more there are. */
+ private static final int MAX_LISTED_MISMATCHES = 5;
+
+ /**
+ * Builds the diagnostic for an assignment, a return, or an argument the nullability check
+ * rejected.
+ *
+ *
Where the traversal finds no nullness difference it can name, the message is the two types
+ * and the subtype relation between them, which is all that can be said about a difference nothing
+ * located.
+ *
+ * @param requiredTypeIsWrittenHere whether the required type is written at the diagnostic, which
+ * is what admits a suggestion about it
+ */
+ String build(Type lhsType, Type rhsType, boolean requiredTypeIsWrittenHere) {
+ List mismatches =
+ new NullabilityMismatches(checks, config, handler, state).collect(lhsType, rhsType);
+ if (mismatches.isEmpty()) {
+ return plainIncompatibleTypesMessage(lhsType, rhsType);
+ }
+ List listed =
+ mismatches.size() > MAX_LISTED_MISMATCHES
+ ? mismatches.subList(0, MAX_LISTED_MISMATCHES)
+ : mismatches;
+ boolean numbered = listed.size() > 1;
+ StringBuilder message = new StringBuilder(summaryLine(mismatches));
+ List<@Nullable TypePath> viewCarets = sourceCarets(listed);
+ Type comparedSourceType = sourceViewedAsTarget(lhsType, rhsType);
+ // a position of the view is a position of the written type where the two are one class; where
+ // they are not, only a node the view shares with it can be marked, and the instance says which
+ List<@Nullable TypePath> writtenCarets =
+ comparedSourceType == null ? viewCarets : instanceCarets(listed, rhsType);
+ MarkedType found = markedTypeLines("found", rhsType, writtenCarets, numbered);
+ if (found.marksPlaced() == listed.size()) {
+ message.append(found.lines());
+ } else {
+ message.append(markedTypeLines("found", rhsType, noCarets(listed.size()), numbered).lines());
+ if (comparedSourceType != null) {
+ // what the comparison reached is at no position of the type the reader wrote, so the type
+ // it did compare is printed too and carries the carets
+ message.append(
+ markedTypeLines("found as", comparedSourceType, viewCarets, numbered).lines());
+ }
+ }
+ message.append(markedTypeLines("required", lhsType, targetCarets(listed), numbered).lines());
+ for (int i = 0; i < listed.size(); i++) {
+ message.append(mismatchDetail(listed.get(i), numbered ? i + 1 : 0, rhsType));
+ }
+ // a numbered entry stands apart from the next, so the list stays readable, and what follows
+ // the list stands apart from it in the same way
+ String separator = numbered ? "\n" : "";
+ if (mismatches.size() > listed.size()) {
+ message.append(
+ String.format(
+ "%s\n and %d more, not listed", separator, mismatches.size() - listed.size()));
+ }
+ Type rewrittenSourceType = rewriteWithExplicitBounds(rhsType, mismatches);
+ String suggestion =
+ rewrittenSourceType == null ? null : suggestedSourceType(lhsType, rewrittenSourceType);
+ String targetSuggestion =
+ requiredTypeIsWrittenHere ? suggestedTargetType(lhsType, rhsType, mismatches) : null;
+ if (suggestion != null) {
+ message.append(String.format("%s\n did you mean %s?", separator, suggestion));
+ separator = "";
+ }
+ if (targetSuggestion != null) {
+ message.append(
+ String.format(
+ "%s\n consider changing the required type to:\n %s",
+ separator, targetSuggestion));
+ }
+ return message.toString();
+ }
+
+ /**
+ * Builds the message for a difference the traversal did not locate: the two types, and the
+ * supertype view that lines them up where their erasures differ.
+ */
+ private String plainIncompatibleTypesMessage(Type lhsType, Type rhsType) {
+ String prettyRhsType = GenericsChecks.prettyTypeForError(rhsType, state);
+ String prettyLhsType = GenericsChecks.prettyTypeForError(lhsType, state);
+ String result =
+ String.format(
+ "incompatible types: %s cannot be converted to %s", prettyRhsType, prettyLhsType);
+ if (!ASTHelpers.isSameType(lhsType, rhsType, state)
+ && lhsType.getKind() == TypeKind.DECLARED
+ && rhsType.getKind() == TypeKind.DECLARED
+ && lhsType.asElement() instanceof Symbol.ClassSymbol classSymbol) {
+ Type asSuper = TypeSubstitutionUtils.asSuper(state.getTypes(), rhsType, classSymbol, config);
+ if (asSuper != null) {
+ result +=
+ String.format(
+ " (%s is a subtype of %s)",
+ prettyRhsType, GenericsChecks.prettyTypeForError(asSuper, state));
+ }
+ }
+ return result;
+ }
+
+ /**
+ * The line a reader sees first, and the only one some tools show: the difference itself where
+ * there is one, and how many there are where naming one would misrepresent the rest.
+ */
+ private String summaryLine(List mismatches) {
+ if (mismatches.size() == 1) {
+ NullabilityMismatches.Mismatch only = mismatches.get(0);
+ // a nullable source where a non-null one is required is a subtype claim and reads as one.
+ // The other direction is not: every String is a @Nullable String, and what fails is that a
+ // type argument has to match rather than be a subtype, which the pair alone does not say
+ String exactly =
+ checks.isNullableAnnotated(only.targetNode())
+ && !checks.isNullableAnnotated(only.sourceNode())
+ ? "a type argument must match exactly; "
+ : "";
+ return String.format(
+ "incompatible nullability: %sfound %s, required %s",
+ exactly,
+ GenericsChecks.prettyTypeForError(only.sourceNode(), state),
+ GenericsChecks.prettyTypeForError(only.targetNode(), state));
+ }
+ return String.format(
+ "incompatible nullability: %d mismatches between source and target types",
+ mismatches.size());
+ }
+
+ /**
+ * Where each mismatch is drawn in the target, which the traversal walked as the reader wrote it.
+ */
+ private static List<@Nullable TypePath> targetCarets(
+ List mismatches) {
+ List<@Nullable TypePath> paths = new ArrayList<>();
+ for (NullabilityMismatches.Mismatch mismatch : mismatches) {
+ paths.add(mismatch.targetCaret());
+ }
+ return paths;
+ }
+
+ /**
+ * Returns {@code sourceType} viewed as the class {@code targetType} names, or {@code null} where
+ * that view is the type the reader wrote or cannot be taken.
+ *
+ *
The traversal compares the source in this view at every level, so a node it reports may sit
+ * at no position in the type the reader wrote: viewing a {@code Sub} declared as {@code extends
+ * Base>} as a {@code Base} reports a node that only the declaration of
+ * {@code Sub} contains. Printing the view gives the caret something to point at that the
+ * comparison actually used.
+ */
+ private @Nullable Type sourceViewedAsTarget(Type targetType, Type sourceType) {
+ if (!(targetType.tsym instanceof Symbol.ClassSymbol targetSymbol)
+ || targetSymbol.equals(sourceType.tsym)) {
+ // the same class, so the comparison ran on the type the reader wrote and its positions are
+ // that type's own. Whether the view would print differently decides nothing: two classes of
+ // one simple name print alike and remain two classes
+ return null;
+ }
+ return TypeSubstitutionUtils.asSuper(state.getTypes(), sourceType, targetSymbol, config);
+ }
+
+ /**
+ * Where each mismatch is drawn in the source type as the reader wrote it, with {@code null} for
+ * one that type does not show.
+ *
+ *
By instance, since the view the comparison used is a type of another class and a position in
+ * it names nothing here: what the two share is the node itself, wherever a substitution carried
+ * it over rather than building one of its own.
+ */
+ private static List<@Nullable TypePath> instanceCarets(
+ List mismatches, Type sourceType) {
+ List<@Nullable TypePath> paths = new ArrayList<>();
+ for (NullabilityMismatches.Mismatch mismatch : mismatches) {
+ paths.add(NullabilityMismatches.pathOfInstance(sourceType, mismatch.sourcePrintedNode()));
+ }
+ return paths;
+ }
+
+ /** A caret for no position at all, one per mismatch, so the two sides stay numbered alike. */
+ private static List<@Nullable TypePath> noCarets(int mismatches) {
+ List<@Nullable TypePath> paths = new ArrayList<>();
+ for (int i = 0; i < mismatches; i++) {
+ paths.add(null);
+ }
+ return paths;
+ }
+
+ /**
+ * Where each mismatch sits in the source, as the traversal viewed it.
+ *
+ *
The same positions serve the type the reader wrote and the view of it the comparison used,
+ * since the two agree wherever the view changed nothing; where they do not agree, the position
+ * reaches nothing in the written type and the caller prints the view instead.
+ */
+ private static List<@Nullable TypePath> sourceCarets(
+ List mismatches) {
+ List<@Nullable TypePath> paths = new ArrayList<>();
+ for (NullabilityMismatches.Mismatch mismatch : mismatches) {
+ paths.add(mismatch.sourceCaret());
+ }
+ return paths;
+ }
+
+ /**
+ * Prints {@code type} on a labelled line, with a caret run under each position in {@code paths}
+ * and, where {@code numbered}, the index of each under its caret.
+ *
+ *
Pointing at the position is what naming the type variable cannot do. One type may hold
+ * several arguments for identically named variables — {@code Map, List>} has
+ * two for {@code E} of {@code List} — so a name leaves the reader to work out which occurrence is
+ * meant, and even a unique name makes them map it back onto the printed type themselves.
+ */
+ private MarkedType markedTypeLines(
+ String label, Type type, List<@Nullable TypePath> paths, boolean numbered) {
+ String printed = type.accept(new GenericTypePrettyPrintingVisitor(state, paths), null);
+ StringBuilder stripped = new StringBuilder();
+ StringBuilder carets = new StringBuilder();
+ StringBuilder numbers = new StringBuilder();
+ int marks = 0;
+ int i = 0;
+ while (i < printed.length()) {
+ char c = printed.charAt(i);
+ if (c != GenericTypePrettyPrintingVisitor.MARK_START || i + 1 >= printed.length()) {
+ stripped.append(c);
+ i++;
+ continue;
+ }
+ int index = printed.charAt(i + 1) - '0';
+ int start = stripped.length();
+ i += 2;
+ while (i < printed.length()
+ && printed.charAt(i) != GenericTypePrettyPrintingVisitor.MARK_END) {
+ stripped.append(printed.charAt(i));
+ i++;
+ }
+ i++;
+ padTo(carets, start).append("^".repeat(Math.max(stripped.length() - start, 1)));
+ padTo(numbers, start).append(index + 1);
+ marks++;
+ }
+ String prefix = String.format(" %-9s ", label + ":");
+ // the printer brackets what it was asked to, and this removes any marker regardless: nothing a
+ // caller marks may put a control character in front of a reader
+ String line =
+ "\n"
+ + prefix
+ + stripped
+ .toString()
+ .replace(String.valueOf(GenericTypePrettyPrintingVisitor.MARK_START), "")
+ .replace(String.valueOf(GenericTypePrettyPrintingVisitor.MARK_END), "");
+ if (carets.length() > 0) {
+ line += "\n" + " ".repeat(prefix.length()) + carets;
+ if (numbered) {
+ line += "\n" + " ".repeat(prefix.length()) + numbers;
+ }
+ }
+ return new MarkedType(line, marks);
+ }
+
+ /**
+ * A printed type and the number of positions the printer could mark in it.
+ *
+ *
The count is what tells a caller whether the type it printed is the one to draw on: a
+ * position the traversal reached in its own view of the source reaches nothing in the type the
+ * reader wrote once those two are different types.
+ */
+ private record MarkedType(String lines, int marksPlaced) {}
+
+ /** Pads {@code line} with spaces up to {@code column}, so the next run starts there. */
+ private static StringBuilder padTo(StringBuilder line, int column) {
+ if (line.length() < column) {
+ line.append(" ".repeat(column - line.length()));
+ }
+ return line;
+ }
+
+ /**
+ * Names where one mismatch sits and, for a numbered entry, what the two sides have there.
+ *
+ *
The two shapes carry the same fields in the same order, because a reader who has learned one
+ * message has learned the other: a single mismatch states its position under the two types, and
+ * where there are several, each entry states its own position and the pair the summary could not
+ * name.
+ */
+ private String mismatchDetail(
+ NullabilityMismatches.Mismatch mismatch, int number, Type sourceType) {
+ // the root stands as a guard rather than as a case with traffic: a nullness difference at the
+ // root of the two types is reported by the check for assigning a @Nullable value, before a
+ // pseudo-assignment of type arguments is looked at
+ String position = mismatch.path().isRoot() ? "the type itself" : mismatch.path().describe();
+ String header = number == 0 ? " " : " " + number + ". ";
+ String body = " ".repeat(header.length());
+ StringBuilder detail = new StringBuilder();
+ if (number != 0) {
+ detail.append("\n");
+ }
+ detail
+ .append("\n")
+ .append(header)
+ .append(wrapped("path: " + position, header.length(), body + " "));
+ if (number != 0) {
+ detail.append("\n").append(body).append("found: ");
+ detail.append(GenericsChecks.prettyTypeForError(mismatch.sourceNode(), state));
+ detail.append("\n").append(body).append("required: ");
+ detail.append(GenericsChecks.prettyTypeForError(mismatch.targetNode(), state));
+ }
+ String note = boundOriginNote(mismatch, sourceType);
+ if (note != null) {
+ detail
+ .append("\n")
+ .append(body)
+ .append(wrapped("note: " + note, body.length(), body + " "));
+ }
+ return detail.toString();
+ }
+
+ /** The column a message line may not run past, which a deeply nested type reaches easily. */
+ private static final int MAX_LINE_LENGTH = 100;
+
+ /**
+ * Returns {@code text} broken across lines that end before {@link #MAX_LINE_LENGTH}, with every
+ * line after the first opening at {@code continuation}.
+ *
+ *
A type path breaks before one of its {@code ->} separators, so that a line starts with the
+ * step it describes; any other text breaks at a space.
+ */
+ private static String wrapped(String text, int firstLineIndent, String continuation) {
+ String[] segments = text.contains(" -> ") ? text.split(" (?=-> )") : text.split(" ");
+ StringBuilder wrappedText = new StringBuilder(segments[0]);
+ int lineLength = firstLineIndent + segments[0].length();
+ for (int i = 1; i < segments.length; i++) {
+ String segment = segments[i];
+ if (lineLength + 1 + segment.length() > MAX_LINE_LENGTH) {
+ wrappedText.append("\n").append(continuation).append(segment);
+ lineLength = continuation.length() + segment.length();
+ } else {
+ wrappedText.append(" ").append(segment);
+ lineLength += 1 + segment.length();
+ }
+ }
+ return wrappedText.toString();
+ }
+
+ /**
+ * Says where the source takes a nullness its printed form does not show: the bound a wildcard
+ * inherits, or the bound a type variable was declared with. Returns {@code null} where the
+ * printed type shows it already.
+ *
+ *
A wildcard with no explicit upper bound and a captured one both take a bound the printed
+ * type does not state, and a reader who is not told where it comes from reads the two bounds as a
+ * contradiction. For a captured wildcard the note also says when the owner is unannotated, which
+ * is what makes the bound {@code @Nullable} and the one thing about the situation a reader can go
+ * and change. Unannotated is NullAway's own sense of the word: a class outside
+ * {@code @NullMarked} code, and also one the configuration names as unannotated.
+ */
+ private @Nullable String boundOriginNote(
+ NullabilityMismatches.Mismatch mismatch, Type sourceType) {
+ // the node the caret sits on, not the one that differs: the note answers a reader who is
+ // looking at a wildcard and reading that the source has a bound the wildcard does not print
+ Type.WildcardType wildcard = GenericsUtils.asWildcard(mismatch.sourcePrintedNode());
+ if (wildcard == null) {
+ // a captured wildcard is a Type.TypeVar as well, so it is ruled out above rather than here
+ // a type variable that carries its own @Nullable is printed with it, and needs no note
+ return mismatch.sourcePrintedNode() instanceof Type.TypeVar sourceTypeVariable
+ && !checks.isNullableAnnotated(mismatch.sourcePrintedNode())
+ ? String.format(
+ "the source %s has no nullness of its own, so it takes the nullness of its declared"
+ + " upper bound",
+ sourceTypeVariable.tsym.getSimpleName())
+ : null;
+ }
+ if (mismatch.sourcePrintedNode() instanceof Type.CapturedType) {
+ // a captured wildcard was captured where it was written, so its bound link still names the
+ // type variable of the type the user wrote, e.g. T of Flow for a (Flow>) cast
+ Type.TypeVar capturedTypeVariable = wildcard.bound;
+ Symbol.ClassSymbol owner = typeVariableOwner(capturedTypeVariable);
+ if (capturedTypeVariable == null || owner == null) {
+ return null;
+ }
+ String note =
+ String.format(
+ "the source wildcard is the type argument for type parameter %s of %s",
+ capturedTypeVariable.tsym.getSimpleName(), owner.getSimpleName());
+ return GenericsUtils.fromUnannotatedMethodOrClass(
+ capturedTypeVariable.tsym, config, handler, state)
+ ? note + String.format(", and %s is unannotated", owner.getSimpleName())
+ : note;
+ }
+ if (wildcard.kind == BoundKind.EXTENDS) {
+ return null;
+ }
+ Type.TypeVar formalTypeVariable =
+ typeVariableAtPositionOf(mismatch.sourcePrintedNode(), sourceType);
+ Symbol.ClassSymbol owner = typeVariableOwner(formalTypeVariable);
+ String source =
+ wildcard.kind == BoundKind.UNBOUND
+ ? "?"
+ : "? super " + GenericsChecks.prettyTypeForError(wildcard.type, state);
+ if (formalTypeVariable == null || owner == null) {
+ // no type parameter this message prints stands behind the bound: the wildcard sits at no
+ // position in the type the reader wrote, as happens where the supertype view rebuilt it from
+ // a subclass declaration, or the variable it instantiates has no named owner. The note says
+ // what the
+ // bound is and leaves where it came from alone
+ // "the source wildcard" rather than the symbol: two printed types carry a ? here, and the
+ // note is about the one the comparison used rather than about a character to go and find
+ return String.format(
+ "the source wildcard has an implicit %s upper bound",
+ GenericsChecks.prettyTypeForError(
+ GenericsUtils.wildcardUpperBound(wildcard, state, config, handler), state));
+ }
+ return String.format(
+ "the source %s has no explicit upper bound, so its upper bound is inherited from type parameter %s of %s",
+ source, formalTypeVariable.tsym.getSimpleName(), owner.getSimpleName());
+ }
+
+ /**
+ * Returns the printed form of {@code rewrittenSourceType} where it is worth offering as a
+ * rewrite, or {@code null} where it is not.
+ */
+ private @Nullable String suggestedSourceType(Type targetType, Type rewrittenSourceType) {
+ if (!printsEveryAnnotation(rewrittenSourceType)) {
+ // the printer shows @Nullable and drops every other type-use annotation, which is harmless
+ // where the type is only described and wrong where it is offered to be pasted
+ return null;
+ }
+ if (!isDenotable(rewrittenSourceType)) {
+ // the rewrite would print a type the reader cannot write, such as one holding a captured
+ // wildcard, and the clause invites them to paste it
+ return null;
+ }
+ // javac rejects a `? super S` target holding a `?` before NullAway runs, which is the one
+ // position where the comparison below would accept without analysing
+ if (!checks.subtypeParameterNullability(targetType, rewrittenSourceType, state)) {
+ // the rewrite does not repair every incompatibility, so suggesting it would only produce the
+ // same diagnostic again. This is the check's own comparison rather than a prediction of it:
+ // a mismatch it rejects for a reason writing a bound out does not address, such as a nullness
+ // difference on a concrete type argument, is one no rewritten wildcard reaches.
+ return null;
+ }
+ return GenericsChecks.prettyTypeForError(rewrittenSourceType, state);
+ }
+
+ /**
+ * Returns the printed form of the target type with the nullness the source has at every position
+ * that differs, or {@code null} where that type is not worth offering. Whether it is offered at
+ * all is the caller's decision, which the class comment states.
+ */
+ private @Nullable String suggestedTargetType(
+ Type targetType, Type sourceType, List mismatches) {
+ if (mismatches.isEmpty()) {
+ return null;
+ }
+ Type rewrittenTargetType = targetType;
+ for (NullabilityMismatches.Mismatch mismatch : mismatches) {
+ Type rewritten = withNullableAddedFrom(mismatch.sourceNode(), mismatch.targetNode());
+ if (rewritten == null) {
+ return null;
+ }
+ rewrittenTargetType = replaceAt(rewrittenTargetType, mismatch.path().steps(), 0, rewritten);
+ if (rewrittenTargetType == null) {
+ return null;
+ }
+ }
+ if (!printsEveryAnnotation(rewrittenTargetType)
+ || !isDenotable(rewrittenTargetType)
+ || !checks.subtypeParameterNullability(rewrittenTargetType, sourceType, state)) {
+ return null;
+ }
+ String printed = GenericsChecks.prettyTypeForError(rewrittenTargetType, state);
+ return printed.equals(GenericsChecks.prettyTypeForError(targetType, state)) ? null : printed;
+ }
+
+ /**
+ * Returns {@code target} with {@code @Nullable} added where {@code source} carries it, or {@code
+ * null} where the two already agree or the annotation to copy cannot be found.
+ *
+ *
The repair only ever widens what the target accepts. Taking a {@code @Nullable} away, which
+ * is what the other direction would need, changes a contract the author stated on purpose, and no
+ * reading of the assignment says which of the two sides meant what.
+ */
+ private @Nullable Type withNullableAddedFrom(Type source, Type target) {
+ if (!checks.isNullableAnnotated(source) || checks.isNullableAnnotated(target)) {
+ return null;
+ }
+ for (Attribute.TypeCompound annotation : source.getAnnotationMirrors()) {
+ if (Nullness.isNullableAnnotation(annotation.type.toString(), config)) {
+ return TypeSubstitutionUtils.typeWithAnnot(target, annotation.type);
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns {@code type} with the node that {@code steps} reach, starting at {@code from}, replaced
+ * by {@code replacement}, or {@code null} where {@code type} prints no node there, as for the
+ * bound an unbounded wildcard leaves implicit.
+ *
+ *
A path names the node because one {@code Type} instance can fill several positions, as one
+ * {@code String} does in {@code Map}, and only one of them is to change.
+ */
+ private static @Nullable Type replaceAt(
+ Type type, List steps, int from, Type replacement) {
+ if (from == steps.size()) {
+ return replacement;
+ }
+ TypePath.Step step = steps.get(from);
+ switch (step.kind()) {
+ case TYPE_ARGUMENT -> {
+ if (!(type instanceof Type.ClassType classType)
+ || step.index() >= classType.getTypeArguments().size()) {
+ return null;
+ }
+ List typeArguments = new ArrayList<>(classType.getTypeArguments());
+ Type typeArgument =
+ replaceAt(typeArguments.get(step.index()), steps, from + 1, replacement);
+ if (typeArgument == null) {
+ return null;
+ }
+ typeArguments.set(step.index(), typeArgument);
+ return TYPE_METADATA_BUILDER.createClassType(
+ classType, classType.getEnclosingType(), typeArguments);
+ }
+ case ENCLOSING_TYPE -> {
+ if (!(type instanceof Type.ClassType classType)) {
+ return null;
+ }
+ Type enclosingType = replaceAt(classType.getEnclosingType(), steps, from + 1, replacement);
+ return enclosingType == null
+ ? null
+ : TYPE_METADATA_BUILDER.createClassType(
+ classType, enclosingType, classType.getTypeArguments());
+ }
+ case WILDCARD_BOUND -> {
+ if (!(type instanceof Type.WildcardType wildcard) || wildcard.kind != BoundKind.EXTENDS) {
+ return null;
+ }
+ Type bound = replaceAt(wildcard.type, steps, from + 1, replacement);
+ return bound == null ? null : TYPE_METADATA_BUILDER.createWildcardType(wildcard, bound);
+ }
+ case ARRAY_ELEMENT -> {
+ if (!(type instanceof Type.ArrayType arrayType)) {
+ return null;
+ }
+ Type elementType = replaceAt(arrayType.elemtype, steps, from + 1, replacement);
+ return elementType == null
+ ? null
+ : TYPE_METADATA_BUILDER.createArrayType(arrayType, elementType);
+ }
+ }
+ throw new AssertionError(step.kind());
+ }
+
+ /**
+ * Returns {@code sourceType} with an explicit upper bound written out for every wildcard that
+ * gains one, or {@code null} if there is no such wildcard.
+ *
+ *
A wildcard gains an explicit bound when it is unbounded, its implicit bound is
+ * {@code @Nullable}, and the target requires a non-null class type there: writing that bound out
+ * is the whole of the repair this class knows how to propose. Whether the result is worth
+ * suggesting is decided by the caller, against the rewritten type rather than against this list.
+ *
+ *
Requiring the bound to be a class type stands as a guard rather than as a filter with
+ * traffic: no input is known to reach it, since a target bound naming a method's type variable
+ * fails inference first and a class's type variable is rejected by javac. Passing it would not
+ * put the name in scope where the source type was declared either, because a declared type may be
+ * unimported there or carry a type variable among its own type arguments.
+ */
+ private @Nullable Type rewriteWithExplicitBounds(
+ Type sourceType, List mismatches) {
+ // identity, not isSameType: a wildcard is rewritten where it occurs, not wherever an equal one
+ // does, and the same wildcard may be reported at several positions
+ IdentityHashMap boundForWildcard = new IdentityHashMap<>();
+ for (NullabilityMismatches.Mismatch mismatch : mismatches) {
+ Type.WildcardType sourceWildcard = mismatch.sourceWildcard();
+ Type targetUpperBound = mismatch.targetUpperBound();
+ if (sourceWildcard == null
+ || targetUpperBound == null
+ || sourceWildcard.kind != BoundKind.UNBOUND) {
+ // only an unbounded wildcard gains an upper bound by being written out
+ continue;
+ }
+ if (targetUpperBound.getKind() != TypeKind.DECLARED
+ || Nullness.hasNullableAnnotation(
+ targetUpperBound.getAnnotationMirrors().stream(), config)
+ || !Nullness.hasNullableAnnotation(
+ mismatch.sourceNode().getAnnotationMirrors().stream(), config)) {
+ // the bound to write out is not a class type, or writing it out would not make the source
+ // wildcard non-null, which is the only repair this method knows
+ continue;
+ }
+ boundForWildcard.put(sourceWildcard, targetUpperBound);
+ }
+ if (boundForWildcard.isEmpty()) {
+ return null;
+ }
+ return sourceType.accept(
+ new Type.StructuralTypeMapping<@Nullable Void>() {
+ @Override
+ public Type visitWildcardType(Type.WildcardType t, @Nullable Void unused) {
+ Type requiredBound = boundForWildcard.get(t);
+ return requiredBound == null
+ ? super.visitWildcardType(t, null)
+ : new Type.WildcardType(
+ requiredBound, BoundKind.EXTENDS, Symtab.instance(state.context).boundClass);
+ }
+ },
+ null);
+ }
+
+ /**
+ * Returns whether every type-use annotation in {@code type} survives printing, so that a
+ * suggestion naming it says what the reader would be pasting.
+ *
+ *
{@link GenericTypePrettyPrintingVisitor} prints {@code @Nullable} and drops every other
+ * type-use annotation. A message that only describes a type loses nothing a reader needs; a
+ * suggestion that drops one hands them a type that says something else about their code.
+ */
+ private boolean printsEveryAnnotation(Type type) {
+ for (Attribute.TypeCompound annotation : type.getAnnotationMirrors()) {
+ if (!Nullness.isNullableAnnotation(annotation.type.toString(), config)) {
+ return false;
+ }
+ }
+ if (type instanceof Type.ClassType classType) {
+ for (Type typeArgument : classType.getTypeArguments()) {
+ if (!printsEveryAnnotation(typeArgument)) {
+ return false;
+ }
+ }
+ Type enclosingType = classType.getEnclosingType();
+ return enclosingType.hasTag(TypeTag.NONE) || printsEveryAnnotation(enclosingType);
+ }
+ if (type instanceof Type.WildcardType wildcardType) {
+ return wildcardType.kind == BoundKind.UNBOUND || printsEveryAnnotation(wildcardType.type);
+ }
+ if (type instanceof Type.ArrayType arrayType) {
+ return printsEveryAnnotation(arrayType.elemtype);
+ }
+ return true;
+ }
+
+ /**
+ * Returns whether {@code type} prints as Java a reader could write, so that a suggestion naming
+ * it is worth offering.
+ *
+ *
This mirrors {@link GenericTypePrettyPrintingVisitor}: that printer has four arms whose
+ * output cannot serve as a suggestion. Three emit text no declaration may contain — a captured
+ * wildcard prints as {@code capture of ?}, an intersection as {@code A & B}, an anonymous class
+ * under its binary name. The fourth prints a type that did not resolve under a bare name, which
+ * is writable but denotes nothing, so pasting it trades one compile error for another. Dispatch
+ * is by visitor rather than by {@code instanceof} because {@link Type.CapturedType} extends
+ * {@link Type.TypeVar} and {@link Type.IntersectionClassType} extends {@link Type.ClassType}, so
+ * a chain of {@code instanceof} arms would classify a capture as a type variable.
+ */
+ private static boolean isDenotable(Type type) {
+ return type.accept(DENOTABILITY_VISITOR, null);
+ }
+
+ private static final Types.DefaultTypeVisitor DENOTABILITY_VISITOR =
+ new Types.DefaultTypeVisitor<>() {
+ @Override
+ public Boolean visitClassType(Type.ClassType t, @Nullable Void unused) {
+ if (t.isIntersection() || t.tsym.isAnonymous()) {
+ return false;
+ }
+ for (Type typeArgument : t.getTypeArguments()) {
+ if (!typeArgument.accept(this, null)) {
+ return false;
+ }
+ }
+ Type enclosingType = t.getEnclosingType();
+ return enclosingType.hasTag(TypeTag.NONE) || enclosingType.accept(this, null);
+ }
+
+ @Override
+ public Boolean visitWildcardType(Type.WildcardType t, @Nullable Void unused) {
+ return t.kind == BoundKind.UNBOUND || t.type.accept(this, null);
+ }
+
+ @Override
+ public Boolean visitArrayType(Type.ArrayType t, @Nullable Void unused) {
+ return t.elemtype.accept(this, null);
+ }
+
+ @Override
+ public Boolean visitCapturedType(Type.CapturedType t, @Nullable Void unused) {
+ return false;
+ }
+
+ @Override
+ public Boolean visitErrorType(Type.ErrorType t, @Nullable Void unused) {
+ return false;
+ }
+
+ @Override
+ public Boolean visitType(Type t, @Nullable Void unused) {
+ return true;
+ }
+ };
+
+ /** Returns the named class declaring {@code typeVariable}, or {@code null} if there is none. */
+ private static Symbol.@Nullable ClassSymbol typeVariableOwner(
+ Type.@Nullable TypeVar typeVariable) {
+ if (typeVariable == null
+ || !(typeVariable.tsym.owner instanceof Symbol.ClassSymbol owner)
+ || owner.getSimpleName().isEmpty()) {
+ return null;
+ }
+ return owner;
+ }
+
+ /**
+ * Returns the type variable that {@code typeArgument} instantiates where it occurs inside {@code
+ * enclosingType}, or {@code null} if {@code typeArgument} is not a type argument of {@code
+ * enclosingType} or of a type nested in it.
+ *
+ *
javac keeps a similar link in {@link Type.WildcardType#bound}, but overwrites it whenever
+ * the wildcard is substituted into a supertype: after viewing {@code List>} as a {@code
+ * Collection}, the wildcard points at a type variable of an intermediate supertype rather than at
+ * {@code E} of {@code List}. Locating the wildcard by position reports the type the user wrote.
+ */
+ @SuppressWarnings({"ReferenceEquality", "TypeEquals"})
+ private static Type.@Nullable TypeVar typeVariableAtPositionOf(
+ Type typeArgument, Type enclosingType) {
+ if (enclosingType instanceof Type.ArrayType arrayType) {
+ return typeVariableAtPositionOf(typeArgument, arrayType.elemtype);
+ }
+ if (!(enclosingType instanceof Type.ClassType classType)) {
+ return null;
+ }
+ List typeArguments = classType.getTypeArguments();
+ List formals = classType.tsym.type.getTypeArguments();
+ for (int i = 0; i < typeArguments.size(); i++) {
+ Type actual = typeArguments.get(i);
+ // identity, not isSameType: the same wildcard may appear at several positions
+ if (actual == typeArgument) {
+ return i < formals.size() && formals.get(i) instanceof Type.TypeVar formal ? formal : null;
+ }
+ Type.TypeVar nested = typeVariableAtPositionOf(typeArgument, actual);
+ if (nested != null) {
+ return nested;
+ }
+ }
+ return typeVariableAtPositionOf(typeArgument, classType.getEnclosingType());
+ }
+}
diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java
new file mode 100644
index 0000000000..fe9f552abf
--- /dev/null
+++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java
@@ -0,0 +1,341 @@
+package com.uber.nullaway.generics;
+
+import com.google.errorprone.VisitorState;
+import com.sun.tools.javac.code.BoundKind;
+import com.sun.tools.javac.code.Symbol;
+import com.sun.tools.javac.code.Type;
+import com.uber.nullaway.Config;
+import com.uber.nullaway.handlers.Handler;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Set;
+import org.jspecify.annotations.Nullable;
+
+/**
+ * Finds the positions where a source type does not have the nullness a target type requires.
+ *
+ *
The search descends the two types together and reports the smallest pair of nodes that still
+ * differs, so that a diagnostic can point at {@code @Nullable String} rather than at the {@code
+ * Collection<@Nullable String>} that contains it. A reported node is not descended into, so the
+ * positions are disjoint and a caret drawn under one cannot sit inside another.
+ *
+ *
The two sides are addressed differently, because only one of them is traversed as the reader
+ * wrote it. The target is, so a mismatch names a {@link TypePath} in it, which reads as prose and
+ * also tells the printer where to draw a caret. The source is viewed as the target's supertype at
+ * every level, which is a type the reader never wrote, so a mismatch instead carries the source
+ * node itself; the caller locates that instance in the type the reader did write.
+ */
+final class NullabilityMismatches {
+
+ private final GenericsChecks checks;
+ private final Config config;
+ private final Handler handler;
+ private final VisitorState state;
+
+ /**
+ * The source wildcards whose bound is being compared with each target wildcard's bound, by
+ * identity. A bound can name its own type variable again, as in {@code X extends Sibling, ?
+ * super X>}, and the descent returns to a pair it has not finished; {@code
+ * CheckIdenticalNullabilityVisitor} accepts such a pair, so this traversal reports nothing for
+ * it.
+ */
+ private final IdentityHashMap> activeBoundComparisons =
+ new IdentityHashMap<>();
+
+ NullabilityMismatches(GenericsChecks checks, Config config, Handler handler, VisitorState state) {
+ this.checks = checks;
+ this.config = config;
+ this.handler = handler;
+ this.state = state;
+ }
+
+ /**
+ * One position where the source does not have the nullness the target requires.
+ *
+ * @param path the position in the target, which names the mismatch in prose and carries the
+ * target's caret
+ * @param targetNode the smallest node the target requires
+ * @param sourceNode the smallest node the source has there
+ * @param targetCaret the deepest position the target prints, at or above {@code path}
+ * @param sourcePrintedNode the deepest node the source prints for this mismatch, which is the
+ * wildcard itself where the bound at fault is one the wildcard leaves implicit
+ * @param sourceCaret the deepest position the source prints, in the source as this traversal
+ * views it, which is the type the caller prints where that node sits nowhere in the type the
+ * reader wrote
+ * @param sourceWildcard the source wildcard whose upper bound is at fault, or {@code null} where
+ * the source states the type outright
+ * @param targetUpperBound the bound the target requires there, which is what writing an explicit
+ * bound on {@code sourceWildcard} would have to produce
+ */
+ record Mismatch(
+ TypePath path,
+ Type targetNode,
+ Type sourceNode,
+ TypePath targetCaret,
+ Type sourcePrintedNode,
+ TypePath sourceCaret,
+ Type.@Nullable WildcardType sourceWildcard,
+ @Nullable Type targetUpperBound) {}
+
+ /**
+ * Where a node sits in the target, and the deepest printed position a caret can go under.
+ *
+ *
The two part company as soon as a descent reaches something the printer does not show, such
+ * as the upper bound an unbounded wildcard leaves implicit. Every step below such a node is
+ * invisible too, so {@link #caret} stops there and stays.
+ */
+ private record Position(TypePath path, TypePath caret, boolean printed) {
+
+ static Position root() {
+ return new Position(TypePath.root(), TypePath.root(), true);
+ }
+
+ Position then(TypePath.Step step, boolean stepIsPrinted) {
+ TypePath child = path.then(step);
+ boolean childIsPrinted = printed && stepIsPrinted;
+ return new Position(child, childIsPrinted ? child : caret, childIsPrinted);
+ }
+ }
+
+ /**
+ * The comparison of two upper bounds, which is the one place a difference may be repaired by
+ * writing a bound out, and the one place a non-null source is accepted where a nullable one is
+ * allowed.
+ *
+ * @param sourceWildcard the wildcard the source bound came from, or {@code null} where the source
+ * states the type outright
+ * @param targetUpperBound the bound the target requires
+ */
+ private record BoundComparison(
+ Type.@Nullable WildcardType sourceWildcard, Type targetUpperBound) {}
+
+ /**
+ * Returns every position where {@code sourceType} does not have the nullness {@code targetType}
+ * requires, in the order a traversal of the target encounters them.
+ */
+ List collect(Type targetType, Type sourceType) {
+ List mismatches = new ArrayList<>();
+ collect(targetType, sourceType, Position.root(), sourceType, Position.root(), null, mismatches);
+ return mismatches;
+ }
+
+ /**
+ * Compares one node of the target with the node the source has there, and appends what it finds
+ * to {@code mismatches}.
+ *
+ * @param target the node the target requires
+ * @param source the node the source has there, in the view this traversal took of it
+ * @param targetPosition where {@code target} sits in the target, and the deepest position the
+ * target prints at or above it
+ * @param sourcePrintedNode the deepest node the source prints for this position, which stays on a
+ * wildcard whose bound the printed form does not show
+ * @param sourcePosition the same as {@code targetPosition}, in the source as viewed here
+ * @param bound the bound comparison this descent is part of, or {@code null} where the two nodes
+ * are compared as type arguments, which decides both what a repair could rewrite and whether
+ * a non-null source is accepted where a nullable one is allowed
+ * @param mismatches the list to append to
+ */
+ private void collect(
+ Type target,
+ Type source,
+ Position targetPosition,
+ Type sourcePrintedNode,
+ Position sourcePosition,
+ @Nullable BoundComparison bound,
+ List mismatches) {
+ Type.WildcardType targetWildcard = GenericsUtils.asWildcard(target);
+ Type.WildcardType sourceWildcard = GenericsUtils.asWildcard(source);
+ if (targetWildcard != null && sourceWildcard != null) {
+ Set activeSources =
+ activeBoundComparisons.computeIfAbsent(
+ targetWildcard, unused -> Collections.newSetFromMap(new IdentityHashMap<>()));
+ if (!activeSources.add(sourceWildcard)) {
+ return;
+ }
+ try {
+ // the check compares the effective upper bounds, and only an `? extends X` wildcard prints
+ // the bound it is compared by: `?` and `? super X` take one from a type variable
+ Type targetUpperBound =
+ GenericsUtils.wildcardUpperBound(targetWildcard, state, config, handler);
+ Type sourceUpperBound =
+ GenericsUtils.wildcardUpperBound(sourceWildcard, state, config, handler);
+ collect(
+ targetUpperBound,
+ sourceUpperBound,
+ targetPosition.then(
+ TypePath.Step.wildcardBound(), targetWildcard.kind == BoundKind.EXTENDS),
+ sourceWildcard.kind == BoundKind.EXTENDS ? sourceUpperBound : sourcePrintedNode,
+ sourcePosition.then(
+ TypePath.Step.wildcardBound(), sourceWildcard.kind == BoundKind.EXTENDS),
+ new BoundComparison(sourceWildcard, targetUpperBound),
+ mismatches);
+ } finally {
+ activeSources.remove(sourceWildcard);
+ }
+ return;
+ }
+ if (targetWildcard != null && targetWildcard.kind == BoundKind.EXTENDS) {
+ // a type argument the source states outright, against a bound the target states, as with
+ // List> against ? extends List extends Object>
+ collect(
+ targetWildcard.type,
+ source,
+ targetPosition.then(TypePath.Step.wildcardBound(), true),
+ sourcePrintedNode,
+ sourcePosition,
+ new BoundComparison(null, targetWildcard.type),
+ mismatches);
+ return;
+ }
+ if (sourceWildcard != null || targetWildcard != null) {
+ // a wildcard on one side only, in a position javac itself rejects before NullAway runs
+ return;
+ }
+ if (bound != null
+ && source instanceof Type.TypeVar sourceTypeVar
+ && !(source instanceof Type.CapturedType)
+ && !checks.isNullableAnnotated(source)) {
+ // against a bound, a type variable that says nothing at the use site is judged by the bound
+ // it was declared with, which is what the check compares and what the printed T does not
+ // show. A @Nullable T says it, and is compared as written
+ source = GenericsUtils.typeVariableUpperBound(sourceTypeVar, state, config, handler);
+ }
+ boolean sourceIsNullable = checks.isNullableAnnotated(source);
+ boolean targetIsNullable = checks.isNullableAnnotated(target);
+ if (sourceIsNullable != targetIsNullable && (sourceIsNullable || bound == null)) {
+ // the smallest pair that differs. An upper bound accepts a non-null source where a nullable
+ // one is allowed; a type argument the source states outright has to match
+ mismatches.add(
+ new Mismatch(
+ targetPosition.path(),
+ target,
+ source,
+ targetPosition.caret(),
+ sourcePrintedNode,
+ sourcePosition.caret(),
+ bound == null ? null : bound.sourceWildcard(),
+ bound == null ? null : bound.targetUpperBound()));
+ return;
+ }
+ if (target instanceof Type.ClassType targetClassType
+ && source instanceof Type.ClassType sourceClassType) {
+ collectFromClassTypes(
+ targetClassType, sourceClassType, targetPosition, sourcePosition, mismatches);
+ return;
+ }
+ if (target instanceof Type.ArrayType targetArrayType
+ && source instanceof Type.ArrayType sourceArrayType) {
+ collect(
+ targetArrayType.elemtype,
+ sourceArrayType.elemtype,
+ targetPosition.then(TypePath.Step.arrayElement(), true),
+ sourceArrayType.elemtype,
+ sourcePosition.then(TypePath.Step.arrayElement(), true),
+ null,
+ mismatches);
+ }
+ }
+
+ /** Descends into the type arguments and the enclosing type of two class types. */
+ private void collectFromClassTypes(
+ Type.ClassType target,
+ Type.ClassType source,
+ Position targetPosition,
+ Position sourcePosition,
+ List mismatches) {
+ if (!(target.tsym instanceof Symbol.ClassSymbol targetSymbol)) {
+ return;
+ }
+ Type sourceAsSuper =
+ TypeSubstitutionUtils.asSuper(state.getTypes(), source, targetSymbol, config);
+ if (!(sourceAsSuper instanceof Type.ClassType sourceAsTarget)
+ || sourceAsSuper.isRaw()
+ || target.isRaw()) {
+ return;
+ }
+ List targetArguments = target.getTypeArguments();
+ List sourceArguments = sourceAsTarget.getTypeArguments();
+ if (targetArguments.size() != sourceArguments.size()) {
+ return;
+ }
+ List formals = target.tsym.type.getTypeArguments();
+ for (int i = 0; i < targetArguments.size(); i++) {
+ Type.TypeVar formal =
+ i < formals.size() && formals.get(i) instanceof Type.TypeVar typeVar ? typeVar : null;
+ collect(
+ targetArguments.get(i),
+ sourceArguments.get(i),
+ targetPosition.then(TypePath.Step.typeArgument(i, formal, targetSymbol), true),
+ sourceArguments.get(i),
+ sourcePosition.then(TypePath.Step.typeArgument(i, formal, targetSymbol), true),
+ null,
+ mismatches);
+ }
+ collect(
+ target.getEnclosingType(),
+ sourceAsTarget.getEnclosingType(),
+ targetPosition.then(TypePath.Step.enclosingType(), true),
+ sourceAsTarget.getEnclosingType(),
+ sourcePosition.then(TypePath.Step.enclosingType(), true),
+ null,
+ mismatches);
+ }
+
+ /**
+ * Returns where {@code node} occurs inside {@code type}, or {@code null} where it occurs nowhere
+ * or at more than one position.
+ *
+ *
Identity, not equality: the caller has a node the traversal reached and wants the place the
+ * printer will print it, and javac hands back one instance for a plain reference such as {@code
+ * String}. Where an instance sits at two positions nothing says which one was compared, and a
+ * caret under a guess is worse than none, so the search reports neither.
+ */
+ static @Nullable TypePath pathOfInstance(Type type, Type node) {
+ List found = new ArrayList<>();
+ findInstance(type, node, TypePath.root(), found);
+ return found.size() == 1 ? found.get(0) : null;
+ }
+
+ /**
+ * Appends to {@code found} every position of {@code type} that holds {@code node} itself, walking
+ * the type the way {@link GenericTypePrettyPrintingVisitor} prints it so that a position found
+ * here is one that printer can mark.
+ */
+ @SuppressWarnings({"ReferenceEquality", "TypeEquals"})
+ private static void findInstance(Type type, Type node, TypePath path, List found) {
+ if (type == node) {
+ found.add(path);
+ return;
+ }
+ if (type instanceof Type.CapturedType capturedType) {
+ // the printer treats a capture and the wildcard it captured as one node, and so does the
+ // traversal above, so neither is a step of its own
+ findInstance(capturedType.wildcard, node, path, found);
+ return;
+ }
+ if (type instanceof Type.WildcardType wildcardType) {
+ if (wildcardType.kind != BoundKind.UNBOUND) {
+ findInstance(wildcardType.type, node, path.then(TypePath.Step.wildcardBound()), found);
+ }
+ return;
+ }
+ if (type instanceof Type.ArrayType arrayType) {
+ findInstance(arrayType.elemtype, node, path.then(TypePath.Step.arrayElement()), found);
+ return;
+ }
+ if (type instanceof Type.ClassType classType) {
+ List typeArguments = classType.getTypeArguments();
+ for (int i = 0; i < typeArguments.size(); i++) {
+ findInstance(
+ typeArguments.get(i),
+ node,
+ path.then(TypePath.Step.typeArgument(i, null, null)),
+ found);
+ }
+ findInstance(
+ classType.getEnclosingType(), node, path.then(TypePath.Step.enclosingType()), found);
+ }
+ }
+}
diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/PolyNullInference.java b/nullaway/src/main/java/com/uber/nullaway/generics/PolyNullInference.java
index 13a35aaa94..21a909c975 100644
--- a/nullaway/src/main/java/com/uber/nullaway/generics/PolyNullInference.java
+++ b/nullaway/src/main/java/com/uber/nullaway/generics/PolyNullInference.java
@@ -15,7 +15,7 @@
import com.uber.nullaway.LibraryModels.PolyNullLocation.Position;
import com.uber.nullaway.LibraryModels.PolyNullLocation.Return;
import com.uber.nullaway.NullabilityUtil;
-import com.uber.nullaway.Nullness;
+import com.uber.nullaway.handlers.Handler;
import com.uber.nullaway.librarymodel.NestedTypePathUpdater;
import java.util.ArrayList;
import java.util.IdentityHashMap;
@@ -57,10 +57,23 @@ boolean hasReturnLocations() {
private PolyNullInference() {}
- /** Applies a resolved PolyNull annotation to every modeled parameter and return location. */
+ /**
+ * Applies the resolved shared PolyNull variable to every modeled parameter and return location.
+ *
+ *
Each location takes the annotation that {@link GenericsUtils#inferredNullnessAnnotation}
+ * gives its type, as the type javac inferred for a method's own type variable does in {@link
+ * TypeSubstitutionUtils}. A type variable with a nullness annotation, such as an explicit type
+ * argument, takes {@code @Nullable} for {@code NULLABLE} and {@code TYPE_VARIABLE_OR_NULLABLE},
+ * and {@code @NonNull} otherwise.
+ */
@SuppressWarnings({"ReferenceEquality", "TypeEquals"}) // deliberate reference equality checks
static Type.MethodType applyToMethodType(
- Type.MethodType methodType, ImmutableSet locations, Type annotationType) {
+ Type.MethodType methodType,
+ ImmutableSet locations,
+ ConstraintSolver.InferredNullability inferred,
+ VisitorState state,
+ Config config,
+ Handler handler) {
boolean changed = false;
ListBuffer updatedParameterTypes = new ListBuffer<>();
int parameterIndex = 0;
@@ -69,12 +82,20 @@ static Type.MethodType applyToMethodType(
remaining = remaining.tail, parameterIndex++) {
Type parameterType = remaining.head;
Type updatedParameterType =
- applyToType(parameterType, new Parameter(parameterIndex), locations, annotationType);
+ applyToType(
+ parameterType,
+ new Parameter(parameterIndex),
+ locations,
+ inferred,
+ state,
+ config,
+ handler);
updatedParameterTypes.append(updatedParameterType);
changed |= updatedParameterType != parameterType;
}
Type returnType = methodType.restype;
- Type updatedReturnType = applyToReturnType(returnType, locations, annotationType);
+ Type updatedReturnType =
+ applyToReturnType(returnType, locations, inferred, state, config, handler);
changed |= updatedReturnType != returnType;
return changed
? new Type.MethodType(
@@ -82,17 +103,27 @@ static Type.MethodType applyToMethodType(
: methodType;
}
- /** Applies a resolved PolyNull annotation to every modeled location within a return type. */
+ /**
+ * Applies the resolved shared PolyNull variable to every modeled location within a return type,
+ * as {@link #applyToMethodType} does.
+ */
static Type applyToReturnType(
- Type returnType, ImmutableSet locations, Type annotationType) {
- return applyToType(returnType, new Return(), locations, annotationType);
+ Type returnType,
+ ImmutableSet locations,
+ ConstraintSolver.InferredNullability inferred,
+ VisitorState state,
+ Config config,
+ Handler handler) {
+ return applyToType(returnType, new Return(), locations, inferred, state, config, handler);
}
/** Resolves PolyNull nullness by invocation after a shared generic-inference solver run. */
- static IdentityHashMap resolveNullnessByInvocation(
- IdentityHashMap contexts,
- Map solution) {
- IdentityHashMap nullnessByInvocation = new IdentityHashMap<>();
+ static IdentityHashMap
+ resolveNullnessByInvocation(
+ IdentityHashMap contexts,
+ Map solution) {
+ IdentityHashMap
+ nullnessByInvocation = new IdentityHashMap<>();
for (Map.Entry entry : contexts.entrySet()) {
nullnessByInvocation.put(
entry.getKey(), resolveContext(entry.getKey(), entry.getValue(), solution));
@@ -101,18 +132,14 @@ static IdentityHashMap resolveNullnessByInvocati
}
/** Resolves the shared PolyNull variable for one invocation. */
- static Nullness resolveContext(
+ static ConstraintSolver.InferredNullability resolveContext(
MethodInvocationTree invocationTree,
PolyNullInferenceContext inferenceContext,
Map solution) {
- ConstraintSolver.InferredNullability inferred =
- solution.getOrDefault(
- new ConstraintSolver.InferenceVariable(
- inferenceContext.inferenceVariable().asElement(), invocationTree),
- ConstraintSolver.InferredNullability.NONNULL);
- return inferred == ConstraintSolver.InferredNullability.NULLABLE
- ? Nullness.NULLABLE
- : Nullness.NONNULL;
+ return solution.getOrDefault(
+ new ConstraintSolver.InferenceVariable(
+ inferenceContext.inferenceVariable().asElement(), invocationTree),
+ ConstraintSolver.InferredNullability.NONNULL);
}
/**
@@ -245,13 +272,25 @@ private static Type.TypeVar createInferenceVariable(
return variable;
}
- /** Applies {@code annotationType} at modeled locations within one method-type component. */
+ /** Applies {@code inferred} at modeled locations within one method-type component. */
private static Type applyToType(
- Type type, Position position, ImmutableSet locations, Type annotationType) {
+ Type type,
+ Position position,
+ ImmutableSet locations,
+ ConstraintSolver.InferredNullability inferred,
+ VisitorState state,
+ Config config,
+ Handler handler) {
Type updated = type;
for (PolyNullLocation location : locations) {
if (location.position().equals(position)) {
- updated = NestedTypePathUpdater.addAnnotation(updated, location.typePath(), annotationType);
+ updated =
+ NestedTypePathUpdater.addAnnotation(
+ updated,
+ location.typePath(),
+ leaf ->
+ GenericsUtils.inferredNullnessAnnotation(
+ leaf, inferred, config, handler, state));
}
}
return updated;
diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java b/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java
new file mode 100644
index 0000000000..c42f9b0c01
--- /dev/null
+++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java
@@ -0,0 +1,122 @@
+package com.uber.nullaway.generics;
+
+import com.google.common.collect.ImmutableList;
+import com.sun.tools.javac.code.Symbol;
+import com.sun.tools.javac.code.Type;
+import java.util.stream.Collectors;
+import org.jspecify.annotations.Nullable;
+
+/**
+ * A position inside a printed type, as the sequence of descents that reaches it from the root.
+ *
+ *
A position rather than an instance: javac hands back one {@code Type} instance for a plain
+ * reference such as {@code String}, and substitution can put one instance at two type-argument
+ * positions, so a node cannot be named by identity. The same path addresses the node for two
+ * purposes that have to agree, a caret drawn under it by {@link GenericTypePrettyPrintingVisitor}
+ * and the prose that names it in a diagnostic, which is why the steps are those the printer takes.
+ */
+final class TypePath {
+
+ /** One descent into a type. */
+ record Step(
+ Kind kind, int index, Type.@Nullable TypeVar formal, Symbol.@Nullable ClassSymbol owner) {
+
+ enum Kind {
+ /** Into the type argument at {@link Step#index}. */
+ TYPE_ARGUMENT,
+ /** Into the declared upper bound of a wildcard. */
+ WILDCARD_BOUND,
+ /** Into the element type of an array. */
+ ARRAY_ELEMENT,
+ /** Into the enclosing instance type of an inner class. */
+ ENCLOSING_TYPE
+ }
+
+ static Step typeArgument(
+ int index, Type.@Nullable TypeVar formal, Symbol.@Nullable ClassSymbol owner) {
+ return new Step(Kind.TYPE_ARGUMENT, index, formal, owner);
+ }
+
+ static Step wildcardBound() {
+ return new Step(Kind.WILDCARD_BOUND, -1, null, null);
+ }
+
+ static Step arrayElement() {
+ return new Step(Kind.ARRAY_ELEMENT, -1, null, null);
+ }
+
+ static Step enclosingType() {
+ return new Step(Kind.ENCLOSING_TYPE, -1, null, null);
+ }
+
+ /**
+ * Whether this step reaches the same node as {@code other}, ignoring the names carried for
+ * prose. Two steps of the same kind and index address one node however they were built.
+ */
+ boolean reachesSameNodeAs(Step other) {
+ return kind == other.kind && index == other.index;
+ }
+
+ /** Names this step for a reader, as {@code Map type argument K} or {@code array element}. */
+ String describe() {
+ return switch (kind) {
+ case TYPE_ARGUMENT ->
+ formal == null || owner == null
+ ? "type argument " + (index + 1)
+ : owner.getSimpleName() + " type argument " + formal.tsym.getSimpleName();
+ case WILDCARD_BOUND -> "wildcard upper bound";
+ case ARRAY_ELEMENT -> "array element";
+ case ENCLOSING_TYPE -> "enclosing type";
+ };
+ }
+ }
+
+ private static final TypePath ROOT = new TypePath(ImmutableList.of());
+
+ private final ImmutableList steps;
+
+ private TypePath(ImmutableList steps) {
+ this.steps = steps;
+ }
+
+ /** The path of the type itself, which no step has descended from. */
+ static TypePath root() {
+ return ROOT;
+ }
+
+ /** Returns this path extended by {@code step}. */
+ TypePath then(Step step) {
+ return new TypePath(ImmutableList.builder().addAll(steps).add(step).build());
+ }
+
+ /** Returns the descents from the root, in order. */
+ ImmutableList steps() {
+ return steps;
+ }
+
+ boolean isRoot() {
+ return steps.isEmpty();
+ }
+
+ /** Whether this path and {@code other} address the same node. */
+ boolean reachesSameNodeAs(TypePath other) {
+ if (steps.size() != other.steps.size()) {
+ return false;
+ }
+ for (int i = 0; i < steps.size(); i++) {
+ if (!steps.get(i).reachesSameNodeAs(other.steps.get(i))) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Names this path for a reader, as {@code Map type argument V -> List type argument E -> wildcard
+ * upper bound}. The arrow is ASCII so that the diagnostic survives a console encoding that has no
+ * arrow character.
+ */
+ String describe() {
+ return steps.stream().map(Step::describe).collect(Collectors.joining(" -> "));
+ }
+}
diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java b/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java
index 298c2ceab0..f7acb58e41 100644
--- a/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java
+++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java
@@ -1,7 +1,6 @@
package com.uber.nullaway.generics;
import static com.uber.nullaway.generics.ClassDeclarationNullnessAnnotUtils.getAnnotatedSupertype;
-import static com.uber.nullaway.generics.ConstraintSolver.InferredNullability.NULLABLE;
import static com.uber.nullaway.generics.TypeMetadataBuilder.TYPE_METADATA_BUILDER;
import com.google.common.base.Verify;
@@ -16,6 +15,7 @@
import com.sun.tools.javac.util.ListBuffer;
import com.uber.nullaway.Config;
import com.uber.nullaway.Nullness;
+import com.uber.nullaway.handlers.Handler;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
@@ -143,7 +143,7 @@ public static Type memberType(Types types, Type t, Symbol sym, Config config) {
*/
public static Type restoreExplicitNullabilityAnnotations(
Type origType, Type newType, Types types, Config config) {
- return new RestoreNullnessAnnotationsVisitor(types, config).visit(newType, origType);
+ return new RestoreNullnessAnnotationsVisitor(types, config, null).visit(newType, origType);
}
/**
@@ -233,7 +233,11 @@ public static Type.WildcardType replaceImplicitWildcardUpperBound(
*
*
3 . Apply the nullability annotations from the result of 2 to {@code typeToUpdate}. So, if
* {@code typeToUpdate} is {@code List}, and the result of 2 is {@code List<@Nullable T>},
- * the final result will be {@code List<@Nullable String>}.
+ * the final result will be {@code List<@Nullable String>}. Step 1 leaves a variable inferred as
+ * {@link ConstraintSolver.InferredNullability#TYPE_VARIABLE_OR_NULLABLE} or {@link
+ * ConstraintSolver.InferredNullability#TYPE_VARIABLE_OR_NONNULL} unannotated, and step 3 resolves
+ * it with the annotation, if any, that {@link GenericsUtils#inferredNullnessAnnotation} gives the
+ * type javac inferred.
*
* @param typeToUpdate the type to update
* @param origType the original type with type variables and possibly explicit nullability
@@ -241,6 +245,7 @@ public static Type.WildcardType replaceImplicitWildcardUpperBound(
* @param typeVarNullability a map from type variable elements to their inferred nullability
* @param state the visitor state
* @param config the NullAway config
+ * @param handler the NullAway handler, which decides whether a type variable's bound admits null
* @return the updated type with inferred nullability applied
*/
static Type updateTypeWithInferredNullability(
@@ -248,7 +253,8 @@ static Type updateTypeWithInferredNullability(
Type origType,
@Nullable Map typeVarNullability,
VisitorState state,
- Config config) {
+ Config config,
+ Handler handler) {
if (typeVarNullability == null) {
// no updates to perform
return typeToUpdate;
@@ -262,15 +268,20 @@ static Type updateTypeWithInferredNullability(
origType, inferredNullabilitySubstituted, state.getTypes(), config);
// step 3
// TODO optimize these steps to avoid doing so many substitutions in the future, if needed
- return restoreExplicitNullabilityAnnotations(
- origExplicitAnnotationsRestored, typeToUpdate, state.getTypes(), config);
+ // the only step that sees both the inferred nullness and the type javac inferred, so a
+ // variable step 1 left unannotated is resolved here
+ return new RestoreNullnessAnnotationsVisitor(
+ state.getTypes(),
+ config,
+ new InferredTypeVariableNullness(typeVarNullability, state, handler))
+ .visit(typeToUpdate, origExplicitAnnotationsRestored);
}
/**
* Updates a method type {@code typeToUpdate} by applying inferred nullability for type variables.
* The update is applied to the argument types, return type, and thrown types of the method type,
- * using {@link #updateMethodTypeWithInferredNullability(Type.MethodType, Type.MethodType, Map,
- * VisitorState, Config)}
+ * using {@link #updateTypeWithInferredNullability(Type, Type, Map, VisitorState, Config,
+ * Handler)}
*
* @param methodTypeToUpdate method type to update
* @param origMethodType original method type, with type variables and possibly explicit
@@ -278,6 +289,7 @@ static Type updateTypeWithInferredNullability(
* @param typeVarNullability a map from type variable elements to their inferred nullability
* @param state the visitor state
* @param config the NullAway config
+ * @param handler the NullAway handler, which decides whether a type variable's bound admits null
* @return the updated method type with inferred nullability applied
*/
@SuppressWarnings("ReferenceEquality")
@@ -286,18 +298,20 @@ public static Type.MethodType updateMethodTypeWithInferredNullability(
Type.MethodType origMethodType,
@Nullable Map typeVarNullability,
VisitorState state,
- Config config) {
+ Config config,
+ Handler handler) {
List argtypes = methodTypeToUpdate.argtypes;
Type restype = methodTypeToUpdate.restype;
List thrown = methodTypeToUpdate.thrown;
List argtypes1 =
updateTypeListNullability(
- argtypes, origMethodType.argtypes, typeVarNullability, state, config);
+ argtypes, origMethodType.argtypes, typeVarNullability, state, config, handler);
Type restype1 =
updateTypeWithInferredNullability(
- restype, origMethodType.restype, typeVarNullability, state, config);
+ restype, origMethodType.restype, typeVarNullability, state, config, handler);
List thrown1 =
- updateTypeListNullability(thrown, origMethodType.thrown, typeVarNullability, state, config);
+ updateTypeListNullability(
+ thrown, origMethodType.thrown, typeVarNullability, state, config, handler);
if (argtypes1 == argtypes && restype1 == restype && thrown1 == thrown) {
return methodTypeToUpdate;
} else {
@@ -311,14 +325,16 @@ private static List updateTypeListNullability(
List origTypes,
@Nullable Map typeVarNullability,
VisitorState state,
- Config config) {
+ Config config,
+ Handler handler) {
ListBuffer buf = new ListBuffer<>();
boolean changed = false;
for (List l = typesToUpdate, l1 = origTypes; l.nonEmpty(); l = l.tail, l1 = l1.tail) {
Type toUpdate = l.head;
Type orig = l1.head;
Type t2 =
- updateTypeWithInferredNullability(toUpdate, orig, typeVarNullability, state, config);
+ updateTypeWithInferredNullability(
+ toUpdate, orig, typeVarNullability, state, config, handler);
buf.append(t2);
if (t2 != toUpdate) {
changed = true;
@@ -345,6 +361,16 @@ private static Type substituteInferredNullabilityForTypeVariables(
ListBuffer inferredTypes = new ListBuffer<>();
for (Map.Entry entry :
typeVarNullability.entrySet()) {
+ Type annotType =
+ switch (entry.getValue()) {
+ case NULLABLE -> GenericsChecks.getSyntheticNullableAnnotType(state);
+ case NONNULL -> GenericsChecks.getSyntheticNonNullAnnotType(state);
+ // step 3 resolves these against the type javac inferred
+ case TYPE_VARIABLE_OR_NULLABLE, TYPE_VARIABLE_OR_NONNULL -> null;
+ };
+ if (annotType == null) {
+ continue;
+ }
// find all TypeVars occurring in targetType with the same symbol and substitute for those.
// we can have multiple such TypeVars due to previous substitutions that modified the type
// in some way, e.g., by changing its bounds
@@ -353,12 +379,7 @@ private static Type substituteInferredNullabilityForTypeVariables(
targetType.accept(tvc, null);
for (Type.TypeVar tv : tvc.getMatches()) {
typeVars.append(tv);
- inferredTypes.append(
- typeWithAnnot(
- tv,
- entry.getValue() == NULLABLE
- ? GenericsChecks.getSyntheticNullableAnnotType(state)
- : GenericsChecks.getSyntheticNonNullAnnotType(state)));
+ inferredTypes.append(typeWithAnnot(tv, annotType));
}
}
List typeVarsToReplace = typeVars.toList();
@@ -407,6 +428,16 @@ static Type substituteTypeVariables(
return subst(types, targetType, typeVarsToReplace, replacementTypes.toList(), config);
}
+ /**
+ * The inferred nullness of the type variables of a call, with what {@link
+ * GenericsUtils#inferredNullnessAnnotation} needs to decide whether a type variable's bound
+ * admits null.
+ */
+ private record InferredTypeVariableNullness(
+ Map typeVarNullability,
+ VisitorState state,
+ Handler handler) {}
+
/**
* A visitor that restores explicit nullability annotations on types nested within another type to
* the corresponding positions in the visited type. If no annotations need to be restored, returns
@@ -588,9 +619,25 @@ private Type restoreImplicitWildcardBound(BoundPair pair, Type targetBound, Type
return completed.resultType;
}
- RestoreNullnessAnnotationsVisitor(Types types, Config config) {
+ /**
+ * The inferred nullness whose {@link
+ * ConstraintSolver.InferredNullability#TYPE_VARIABLE_OR_NULLABLE} and {@link
+ * ConstraintSolver.InferredNullability#TYPE_VARIABLE_OR_NONNULL} variables this visitor
+ * resolves against the visited type, or {@code null} to resolve none. Set only in the step that
+ * copies inferred nullness onto the destination type, which is the type javac inferred wherever
+ * one is available; that step alone can tell whether javac inferred a type variable or a class
+ * type. A generic method reference keeps its declared type as the destination where {@link
+ * Config#isNullableBoundInferenceEnabled} is false or javac's type for the referenced method
+ * has another number of parameters. Where that predicate is false, the solver produces none of
+ * these variables.
+ */
+ private final @Nullable InferredTypeVariableNullness inferredNullness;
+
+ RestoreNullnessAnnotationsVisitor(
+ Types types, Config config, @Nullable InferredTypeVariableNullness inferredNullness) {
this.types = types;
this.config = config;
+ this.inferredNullness = inferredNullness;
}
@Override
@@ -891,7 +938,10 @@ public Type visitForAll(Type.ForAll t, Type other) {
* Updates the nullability annotations on a type {@code t} based on the nullability annotations
* on a type {@code other}. When {@code other} is an intersection, copies the nullness
* annotation of the first explicit component that carries one and whose nullability matches the
- * intersection's. If no such component exists, returns {@code t} unchanged.
+ * intersection's. If no such component exists, returns {@code t} unchanged. Where {@code other}
+ * is an unannotated type variable that inference resolved to {@code TYPE_VARIABLE_OR_NULLABLE}
+ * or {@code TYPE_VARIABLE_OR_NONNULL}, adds to {@code t} the annotation that {@link
+ * GenericsUtils#inferredNullnessAnnotation} gives it, if any.
*
* @param t the type to update
* @param other the type to update from
@@ -918,7 +968,19 @@ private Type updateDirectNullabilityAnnotationsForType(Type t, Type other) {
return typeWithAnnot(t, annot);
}
}
- return t;
+ if (inferredNullness == null || !(other instanceof Type.TypeVar)) {
+ return t;
+ }
+ ConstraintSolver.InferredNullability inferred =
+ inferredNullness.typeVarNullability().get(other.tsym);
+ if (inferred != ConstraintSolver.InferredNullability.TYPE_VARIABLE_OR_NULLABLE
+ && inferred != ConstraintSolver.InferredNullability.TYPE_VARIABLE_OR_NONNULL) {
+ return t;
+ }
+ Type annotationType =
+ GenericsUtils.inferredNullnessAnnotation(
+ t, inferred, config, inferredNullness.handler(), inferredNullness.state());
+ return annotationType == null ? t : TypeSubstitutionUtils.typeWithAnnot(t, annotationType);
}
/**
diff --git a/nullaway/src/main/java/com/uber/nullaway/librarymodel/NestedTypePathUpdater.java b/nullaway/src/main/java/com/uber/nullaway/librarymodel/NestedTypePathUpdater.java
index d19e84eaed..25345990ed 100644
--- a/nullaway/src/main/java/com/uber/nullaway/librarymodel/NestedTypePathUpdater.java
+++ b/nullaway/src/main/java/com/uber/nullaway/librarymodel/NestedTypePathUpdater.java
@@ -1,5 +1,6 @@
package com.uber.nullaway.librarymodel;
+import static com.uber.nullaway.NullabilityUtil.castToNonNull;
import static com.uber.nullaway.generics.TypeMetadataBuilder.TYPE_METADATA_BUILDER;
import com.google.common.base.Verify;
@@ -10,6 +11,8 @@
import com.sun.tools.javac.util.ListBuffer;
import com.uber.nullaway.generics.TypeSubstitutionUtils;
import com.uber.nullaway.libmodel.NestedAnnotationInfo;
+import java.util.function.Function;
+import org.jspecify.annotations.Nullable;
/** Updates a type at a nested location identified by a library-model type path. */
@SuppressWarnings({"ReferenceEquality", "TypeEquals"}) // deliberate reference equality checks
@@ -21,16 +24,26 @@ private enum UpdateKind {
}
private final ImmutableList typePath;
- private final Type annotationOrReplacementType;
private final UpdateKind updateKind;
+ /** The type that replaces the type at {@link #typePath}, for {@link UpdateKind#REPLACE_TYPE}. */
+ private final @Nullable Type replacementType;
+
+ /**
+ * For {@link UpdateKind#ADD_ANNOTATION}, maps the type at {@link #typePath} to the annotation
+ * type added to it, or to {@code null} where that type stays unchanged.
+ */
+ private final @Nullable Function annotationFor;
+
private NestedTypePathUpdater(
ImmutableList typePath,
- Type annotationOrReplacementType,
- UpdateKind updateKind) {
+ UpdateKind updateKind,
+ @Nullable Type replacementType,
+ @Nullable Function annotationFor) {
this.typePath = typePath;
- this.annotationOrReplacementType = annotationOrReplacementType;
this.updateKind = updateKind;
+ this.replacementType = replacementType;
+ this.annotationFor = annotationFor;
}
/**
@@ -40,7 +53,24 @@ private NestedTypePathUpdater(
*/
public static Type addAnnotation(
Type type, ImmutableList typePath, Type annotationType) {
- return new NestedTypePathUpdater(typePath, annotationType, UpdateKind.ADD_ANNOTATION)
+ return addAnnotation(type, typePath, leaf -> annotationType);
+ }
+
+ /**
+ * Adds the annotation type that {@code annotationFor} returns for the type at {@code typePath} to
+ * that type, as {@link #addAnnotation(Type, ImmutableList, Type)} adds a fixed one; where {@code
+ * annotationFor} returns {@code null}, the type stays unchanged. A wildcard or a captured type
+ * variable at {@code typePath} is passed to {@code annotationFor} itself, and the annotation it
+ * returns is added to its upper bound: the bound of {@code ? extends}, the upper bound of the
+ * corresponding type parameter for another wildcard, or the upper bound of the capture.
+ *
+ * @return the updated type, or the original {@code type} instance if no change was made
+ */
+ public static Type addAnnotation(
+ Type type,
+ ImmutableList typePath,
+ Function annotationFor) {
+ return new NestedTypePathUpdater(typePath, UpdateKind.ADD_ANNOTATION, null, annotationFor)
.apply(type);
}
@@ -51,7 +81,8 @@ public static Type addAnnotation(
*/
public static Type replaceType(
Type type, ImmutableList typePath, Type replacement) {
- return new NestedTypePathUpdater(typePath, replacement, UpdateKind.REPLACE_TYPE).apply(type);
+ return new NestedTypePathUpdater(typePath, UpdateKind.REPLACE_TYPE, replacement, null)
+ .apply(type);
}
private Type apply(Type type) {
@@ -59,9 +90,18 @@ private Type apply(Type type) {
}
private Type updateLeaf(Type type) {
- return updateKind == UpdateKind.ADD_ANNOTATION
- ? TypeSubstitutionUtils.typeWithAnnot(type, annotationOrReplacementType)
- : annotationOrReplacementType;
+ if (updateKind == UpdateKind.REPLACE_TYPE) {
+ return castToNonNull(replacementType);
+ }
+ Type annotationType = annotationTypeFor(type);
+ return annotationType == null
+ ? type
+ : TypeSubstitutionUtils.typeWithAnnot(type, annotationType);
+ }
+
+ /** Returns the annotation type to add to {@code type} at {@link #typePath}, or {@code null}. */
+ private @Nullable Type annotationTypeFor(Type type) {
+ return castToNonNull(annotationFor).apply(type);
}
@Override
@@ -117,15 +157,20 @@ public Type visitWildcardType(Type.WildcardType t, Integer pathIndex) {
if (updateKind == UpdateKind.REPLACE_TYPE) {
return updateLeaf(t);
}
+ Type annotationType = annotationTypeFor(t);
+ if (annotationType == null) {
+ // diff-coverage: ignore -- PolyNull inference returns no annotation only for a type
+ // variable or an intersection
+ return t;
+ }
if (t.kind == BoundKind.EXTENDS) {
return TYPE_METADATA_BUILDER.createWildcardType(
- t, TypeSubstitutionUtils.typeWithAnnot(t.type, annotationOrReplacementType));
+ t, TypeSubstitutionUtils.typeWithAnnot(t.type, annotationType));
}
Type.TypeVar formalTypeVariable =
Verify.verifyNotNull(t.bound, "wildcard has no corresponding formal type variable");
Type updatedUpperBound =
- TypeSubstitutionUtils.typeWithAnnot(
- formalTypeVariable.getUpperBound(), annotationOrReplacementType);
+ TypeSubstitutionUtils.typeWithAnnot(formalTypeVariable.getUpperBound(), annotationType);
return TypeSubstitutionUtils.replaceImplicitWildcardUpperBound(
t, formalTypeVariable, updatedUpperBound);
}
@@ -184,11 +229,14 @@ public Type visitCapturedType(Type.CapturedType t, Integer pathIndex) {
updatedWildcard = (Type.WildcardType) wildcard.accept(this, pathIndex);
} else {
Verify.verify(pathIndex == typePath.size(), "path index out of bounds");
+ Type annotationType = annotationTypeFor(t);
+ if (annotationType == null) {
+ return t;
+ }
Type updatedUpperBound =
- TypeSubstitutionUtils.typeWithAnnot(t.getUpperBound(), annotationOrReplacementType);
+ TypeSubstitutionUtils.typeWithAnnot(t.getUpperBound(), annotationType);
if (wildcard.kind == BoundKind.EXTENDS) {
- Type updatedBound =
- TypeSubstitutionUtils.typeWithAnnot(wildcard.type, annotationOrReplacementType);
+ Type updatedBound = TypeSubstitutionUtils.typeWithAnnot(wildcard.type, annotationType);
updatedWildcard = TYPE_METADATA_BUILDER.createWildcardType(wildcard, updatedBound);
} else {
// The capture supplies the resolved upper bound, including receiver substitutions.
diff --git a/nullaway/src/test/java/com/uber/nullaway/JSpecifyJDKModelsTest.java b/nullaway/src/test/java/com/uber/nullaway/JSpecifyJDKModelsTest.java
index ea8a80bb89..9b60f8f6af 100644
--- a/nullaway/src/test/java/com/uber/nullaway/JSpecifyJDKModelsTest.java
+++ b/nullaway/src/test/java/com/uber/nullaway/JSpecifyJDKModelsTest.java
@@ -127,7 +127,7 @@ static boolean ownExtendsObject(Collection extends Object> collection) {
}
static boolean callOwnExtendsObject(Collection<@Nullable String> collection) {
- // BUG: Diagnostic contains: incompatible types
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required Object
return ownExtendsObject(collection);
}
}
@@ -513,7 +513,7 @@ class Test {
return list.toArray();
}
static Object[] invalidCall(List list) {
- // BUG: Diagnostic contains: incompatible types: @Nullable Object [] cannot be converted to Object []
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object
return list.toArray();
}
static class DelegatingList extends AbstractList {
diff --git a/nullaway/src/test/java/com/uber/nullaway/ParameterAssignmentTests.java b/nullaway/src/test/java/com/uber/nullaway/ParameterAssignmentTests.java
index 432d2b3443..5779fd78dd 100644
--- a/nullaway/src/test/java/com/uber/nullaway/ParameterAssignmentTests.java
+++ b/nullaway/src/test/java/com/uber/nullaway/ParameterAssignmentTests.java
@@ -72,14 +72,14 @@ public void nestedParameterNullness() {
@NullMarked
class Test {
void typeArgumentMismatchIsReported(List p, List<@Nullable String> q) {
- // BUG: Diagnostic contains: incompatible types: List<@Nullable String> cannot be converted to List
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String
p = q;
}
void matchingTypeArgumentsAreAllowed(List<@Nullable String> p, List<@Nullable String> q) {
p = q;
}
void arrayElementMismatchIsReported(String[] p, @Nullable String[] q) {
- // BUG: Diagnostic contains: incompatible types: @Nullable String [] cannot be converted to String []
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String
p = q;
}
void matchingArrayElementTypesAreAllowed(@Nullable String[] p, @Nullable String[] q) {
diff --git a/nullaway/src/test/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitorTests.java b/nullaway/src/test/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitorTests.java
index 77aee54f7f..ccea236780 100644
--- a/nullaway/src/test/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitorTests.java
+++ b/nullaway/src/test/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitorTests.java
@@ -589,7 +589,12 @@ private static final class CountingVisitor extends CheckIdenticalNullabilityVisi
private int budget;
CountingVisitor(VisitorState state, NullAway nullAway, int budget) {
- super(state, nullAway.getGenericsChecks(), nullAway.getConfig(), nullAway.getHandler());
+ super(
+ state,
+ nullAway.getGenericsChecks(),
+ nullAway.getConfig(),
+ nullAway.getHandler(),
+ ComparisonContext.NONE);
this.budget = budget;
}
diff --git a/nullaway/src/test/java/com/uber/nullaway/generics/PolyNullInferenceTests.java b/nullaway/src/test/java/com/uber/nullaway/generics/PolyNullInferenceTests.java
index dbef2b0dc9..2478781b62 100644
--- a/nullaway/src/test/java/com/uber/nullaway/generics/PolyNullInferenceTests.java
+++ b/nullaway/src/test/java/com/uber/nullaway/generics/PolyNullInferenceTests.java
@@ -14,8 +14,10 @@
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.MethodTree;
import com.sun.tools.javac.code.Type;
+import com.uber.nullaway.DummyOptionsConfig;
import com.uber.nullaway.LibraryModels.PolyNullLocation;
import com.uber.nullaway.LibraryModels.PolyNullLocation.Return;
+import com.uber.nullaway.handlers.Handlers;
import com.uber.nullaway.libmodel.NestedAnnotationInfo.TypePathEntry;
import com.uber.nullaway.libmodel.NestedAnnotationInfo.TypePathEntry.Kind;
import org.junit.Test;
@@ -62,7 +64,10 @@ public Description matchMethod(MethodTree tree, VisitorState state) {
ImmutableSet.of(
new PolyNullLocation(
new Return(), ImmutableList.of(new TypePathEntry(Kind.TYPE_ARGUMENT, 0)))),
- annotation);
+ ConstraintSolver.InferredNullability.NONNULL,
+ state,
+ new DummyOptionsConfig(),
+ Handlers.buildEmpty());
assertThat(updated.getReturnType().getTypeArguments().head.getAnnotationMirrors().head.type)
.isSameInstanceAs(annotation);
assertThat(updated.getParameterTypes().head)
diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/BytecodeGenericsTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/BytecodeGenericsTests.java
index fd25a676ba..8e5a933855 100644
--- a/nullaway/src/test/java/com/uber/nullaway/jspecify/BytecodeGenericsTests.java
+++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/BytecodeGenericsTests.java
@@ -267,7 +267,7 @@ public void genericsChecksForAssignments() {
import com.uber.lib.generics.NullableTypeParam;
class Test {
static void testPositive(NullableTypeParam<@Nullable String> t1) {
- // BUG: Diagnostic contains: incompatible types: NullableTypeParam<@Nullable String>
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String
NullableTypeParam t2 = t1;
}
static void testNegative(NullableTypeParam<@Nullable String> t1) {
@@ -289,9 +289,9 @@ public void genericsChecksForFieldAssignments() {
import com.uber.lib.generics.NullableTypeParam;
class Test {
static void testPositive(NullableTypeParam t1) {
- // BUG: Diagnostic contains: incompatible types: NullableTypeParam
+ // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String
NullableTypeParam.staticField = t1;
- // BUG: Diagnostic contains: incompatible types: NullableTypeParam<@Nullable String>
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String
NullableTypeParam t2 = NullableTypeParam.staticField;
}
static void testNegative(NullableTypeParam<@Nullable String> t1) {
@@ -315,9 +315,9 @@ public void genericsChecksForParamPassingAndReturns() {
import com.uber.lib.generics.GenericTypeArgMethods;
class Test {
static void testPositive(NullableTypeParam t1) {
- // BUG: Diagnostic contains: incompatible types: NullableTypeParam
+ // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String
GenericTypeArgMethods.nullableTypeParamArg(t1);
- // BUG: Diagnostic contains: incompatible types: NullableTypeParam<@Nullable String>
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String
NullableTypeParam t2 = GenericTypeArgMethods.nullableTypeParamReturn();
}
static void testNegative(NullableTypeParam<@Nullable String> t1) {
diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericDiamondTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericDiamondTests.java
index 0e2bbda553..9546db5b86 100644
--- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericDiamondTests.java
+++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericDiamondTests.java
@@ -34,9 +34,9 @@ void testNegative() {
Bar<@Nullable Void> b = new Bar<>(Foo.make());
}
void testPositive() {
- // BUG: Diagnostic contains: incompatible types: Foo<@Nullable String> cannot be converted to Foo
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String
Bar b = new Bar<>(Foo.makeNullableStr());
- // BUG: Diagnostic contains: incompatible types: Foo<@Nullable Void> cannot be converted to Foo
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable Void, required Void
Bar b2 = new Bar<>(Foo.make());
}
}
@@ -103,7 +103,7 @@ static class Bar {
return new Bar<>(Foo.make());
}
Bar testPositive() {
- // BUG: Diagnostic contains: incompatible types: Foo<@Nullable String> cannot be converted to Foo
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String
return new Bar<>(Foo.makeNullableStr());
}
}
@@ -139,7 +139,7 @@ void testNegative() {
takeNullableVoid(new Bar<>(Foo.make()));
}
void testPositive() {
- // BUG: Diagnostic contains: incompatible types: Foo<@Nullable String> cannot be converted to Foo
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String
takeStr(new Bar<>(Foo.makeNullableStr()));
}
}
@@ -172,7 +172,7 @@ static class Bar {
return (new Bar<>(Foo.make()));
}
Bar testPositive() {
- // BUG: Diagnostic contains: incompatible types: Foo<@Nullable String> cannot be converted to Foo
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String
return (new Bar<>(Foo.makeNullableStr()));
}
}
@@ -209,7 +209,7 @@ static class Baz {
return new Baz<>(new Bar<>(Foo.make()));
}
Baz testPositive() {
- // BUG: Diagnostic contains: incompatible types: Foo<@Nullable String> cannot be converted to Foo
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String
return new Baz<>(new Bar<>(Foo.makeNullableStr()));
}
}
@@ -342,14 +342,14 @@ static void takeStr(Bar b) {}
return new Bar<>(Foo.make()) {};
}
Bar returnPositive() {
- // BUG: Diagnostic contains: incompatible types: Foo<@Nullable String> cannot be converted to Foo
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String
return new Bar<>(Foo.makeNullableStr()) {};
}
void paramNegative() {
takeNullableVoid(new Bar<>(Foo.make()) {});
}
void paramPositive() {
- // BUG: Diagnostic contains: incompatible types: Foo<@Nullable String> cannot be converted to Foo
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String
takeStr(new Bar<>(Foo.makeNullableStr()) {});
}
}
@@ -438,7 +438,7 @@ static void testNegative2(Foo<@Nullable String> f1, Foo<@Nullable String> f2) {
new Bar<>(f1, f2);
}
static void testPositive(Foo f1, Foo<@Nullable String> f2) {
- // BUG: Diagnostic contains: incompatible types
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String
new Bar<>(f1, f2);
}
}
@@ -471,7 +471,7 @@ static void testNegative() {
takeFooNullableString(id(new FooImpl<>(makeNullableFoo())));
}
static void testPositive() {
- // BUG: Diagnostic contains: incompatible types
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String
takeFooString(id(new FooImpl<>(makeNullableFoo())));
}
}
@@ -502,7 +502,7 @@ static class Box {
return new Box<>(id(makeNullableFoo()));
}
static Box testPositive() {
- // BUG: Diagnostic contains: incompatible types
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String
return new Box<>(id(makeNullableFoo()));
}
}
diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInferenceErrorReportingTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInferenceErrorReportingTests.java
index 349c3b3200..269d22820d 100644
--- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInferenceErrorReportingTests.java
+++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInferenceErrorReportingTests.java
@@ -234,7 +234,7 @@ class Test {
// since it will pad the array with `null` whenever the passed new length is greater
// than original.length (the example below is safe, but NullAway / JSpecify do not reason
// about integer constraints)
- // BUG: Diagnostic contains: incompatible types: @Nullable E [] cannot be converted to E @Nullable []
+ // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found @Nullable E [], required E @Nullable []
return Arrays.copyOf(original, original.length);
}
}
diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java
index 576610876b..93ff41d452 100644
--- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java
+++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java
@@ -361,7 +361,7 @@ static class ListFuture
}
static MyFuture> invalid() {
- // BUG: Diagnostic contains: incompatible types: ListFuture cannot be converted to MyFuture> (ListFuture is a subtype of MyFuture>)
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable V, required V
return new ListFuture();
}
}
@@ -393,10 +393,10 @@ static void test(
List<@Nullable String> nullableList,
List nonNullList) {
List<@Nullable String> valid = box.get();
- // BUG: Diagnostic contains: incompatible types: List<@Nullable String> cannot be converted to List
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String
List invalid = box.get();
box.set(nullableList);
- // BUG: Diagnostic contains: incompatible types: List cannot be converted to List<@Nullable String>
+ // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String
box.set(nonNullList);
}
}
@@ -423,7 +423,7 @@ abstract class Child
void test(Child child) {
List<@Nullable O> valid = child.get();
- // BUG: Diagnostic contains: incompatible types: List<@Nullable O> cannot be converted to List
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable O, required O
List invalid = child.get();
}
}
diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericLambdaTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericLambdaTests.java
index cb163f3b77..d660011b67 100644
--- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericLambdaTests.java
+++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericLambdaTests.java
@@ -727,11 +727,11 @@ void blockBodyToUnmarkedInterface(List<@Nullable String> l) {
UnmarkedListSupplier s = () -> { return l; };
}
void expressionBodyToMarkedInterface(List<@Nullable String> l) {
- // BUG: Diagnostic contains: incompatible types: List<@Nullable String> cannot be converted to List
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String
MarkedListSupplier s = () -> l;
}
void blockBodyToMarkedInterface(List<@Nullable String> l) {
- // BUG: Diagnostic contains: incompatible types: List<@Nullable String> cannot be converted to List
+ // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String
MarkedListSupplier s = () -> { return l; };
}
void matchingTypeArgumentsToMarkedInterface(List l) {
diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java
index 1db7695fa4..42718e3763 100644
--- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java
+++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java
@@ -231,7 +231,7 @@ static void implicitParameter(Box> nested) {
static void implicitParameterNonNull(Box> nested) {
var flat = nested.flatMap(box -> box);
- // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box<@Nullable String>
+ // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String
acceptsNullable(flat);
}
@@ -1337,7 +1337,7 @@ void testNegative() {
receiver(makeCancelable(this::target));
}
void testPositive() {
- // BUG: Diagnostic contains: incompatible types: Callback