From 42708ade179f75135438ed5d884fce0979923df3 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Sat, 10 Oct 2026 22:37:02 +0300 Subject: [PATCH 01/27] Resolve an inference variable that a type variable admitting null reaches Previously, the constraint solver resolved every inference variable that no constraint fixed as `@NonNull`, the least solution, even where a type variable `T` whose bound admits null flowed into it. With `T extends @Nullable Object`, `List.copyOf(list)` with a `List` passed although `copyOf`'s `E` excludes null, and `var inferred = of(t, "x")` with ` List of(E a, E b)` got a `List<@NonNull Object>`, so `inferred.get(0).toString()` passed while the list may hold a null `T`. The solver now constrains the inference variable `U` of a `? extends U` to be `@Nullable` where the actual is an uncaptured, unannotated type variable whose bound is explicitly nullable and `U`'s own bound excludes null, which no solution satisfies, so the call reports an inference failure. A variable that no constraint fixed but that such a type variable reached is resolved where the inferred nullness is copied onto the type javac inferred, once for every reader of the call: a type variable javac inferred is kept as written, an intersection type carries no annotation, and any other type becomes `@Nullable`, the least type that holds a null `T`, where the bound of `T` and the variable's own bound are explicitly nullable, and `@NonNull` otherwise, as before. Generic method references, including one passed to a diamond, and generic constructors at a diamond take their parameter types through the same copy. Two alternatives were rejected. Leaving the class-type result unspecified let each check read it its own way, so both `List sink = of(t, "x")` and `of(t, "x").get(0).toString()` passed. Reading every synthetic `@NonNull` as unconstrained let a `Box` take the `Box` that `id(boxOfObject)` returns. Caller sees: - `inference failure: type variable U is constrained to be @Nullable, but its upper bound requires it to be @NonNull` where a `Box` whose `T` admits null is passed as the `Box` of a generic method whose `U` excludes null, such as `List.copyOf` with a `List`; accepted before. - `dereferenced expression 'inferred.get(0)' is @Nullable` where javac inferred a class type for a variable that a `T` with an explicitly nullable bound reached, also for the call's own result, an implicit lambda parameter, and an enhanced-for variable; accepted before. - `incompatible types: List<@Nullable Object> cannot be converted to List` under the same condition; accepted before. - `dereferenced expression 'pick(t, "x")' is @Nullable` inside `if (t != null)`, a false positive: dataflow reads such a `T` as non-null with or without the check (#1727). - No report for `List sink = of(t, "x")`, which master reports, since the elements are now `@Nullable`. Not changed: - A class-type result stays non-null where javac inferred an intersection type and where only unannotated bounds are involved. - `first(b).toString()` with ` U first(Box b)`, where javac inferred `T`, is not reported (#1727). Assisted-by: Claude Code (claude-fable-5-1) Assisted-by: Claude Code (claude-opus-5-5) --- .../nullaway/generics/ConstraintSolver.java | 26 +- .../generics/ConstraintSolverImpl.java | 104 +++- .../nullaway/generics/GenericsChecks.java | 59 ++- .../uber/nullaway/generics/GenericsUtils.java | 41 +- .../generics/TypeSubstitutionUtils.java | 72 ++- .../uber/nullaway/jspecify/WildcardTests.java | 485 ++++++++++++++++++ 6 files changed, 750 insertions(+), 37 deletions(-) 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..6eeabc99c5 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java @@ -97,9 +97,33 @@ 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. */ 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. Where javac + * inferred a type variable, the variable is that type variable as written; 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}, the variable is {@code @Nullable}, the + * least type that holds a null {@code T}. + * + *

A variable that no constraint fixed and no such type variable reached is {@link #NONNULL}, + * the least solution. + */ + TYPE_VARIABLE_OR_NULLABLE, + /** + * No constraint fixed the variable and a type variable whose bound admits null flowed into it, + * but no type variable whose bound is explicitly nullable did, or the variable's own bound is + * not explicitly nullable. Where javac inferred a type variable, the variable is that type + * variable as written; 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 reached it. + */ + TYPE_VARIABLE_OR_NONNULL } /** 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..cf9fbbab9d 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java @@ -74,6 +74,19 @@ private static final class VarState { NullnessState nullness = NullnessState.UNKNOWN; + /** + * Whether a type variable that is not under inference, carrying no annotation and bounded by a + * type that admits null, flowed into this variable. Such a flow fixes no nullness, but it means + * the variable takes that type variable's nullness rather than the non-null default. + */ + 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<>(); @@ -276,9 +289,12 @@ 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 uncaptured actual that is an unannotated type variable + * with an explicitly nullable bound also constrains {@code U} to be {@code @Nullable}, which no + * solution satisfies. 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 +314,22 @@ 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 (supertypeWildcard.kind == BoundKind.EXTENDS + && !(subtypeTypeArg instanceof CapturedType) + && admitsNullThroughExplicitBound(subtypeUpperBound) + && supertypeVar != null + && !getState(supertypeVar).nullableAllowed) { + // The containment check judges such a type variable by its nullable bound, which no + // instantiation of a variable bounded by a non-null type can contain. Where the bound + // allows null the constraint is left out: the solver infers one nullness per + // variable, so a @Nullable U would substitute @Nullable T for U where javac inferred + // T, and List copy = copyOf(in) would then be reported. + updateNullness(supertypeVar, NullnessState.NULLABLE); + } + subtypeUpperBound.accept(this, supertypeUpperBound); } case SUPER -> { Type supertypeLowerBound = castToNonNull(supertypeWildcard.getSuperBound()); @@ -391,17 +421,47 @@ public Map solve() } } + /* a variable above a parametric one takes the same type variable's nullness */ + 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 a type variable that may be 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 +497,18 @@ private void directlyConstrainTypePair(Type s, Type t) throws UnsatisfiableConst if (isKnownNullable(s) && tVar != null) { updateNullness(tVar, NullnessState.NULLABLE); } + if (tVar != null + && sVar == null + && s instanceof TypeVar fixedTypeVar + && !isKnownNullable(s) + && !isKnownNonNull(s)) { + VarState st = getState(tVar); + st.parametric = true; + if (GenericsUtils.boundIsExplicitlyNullable( + fixedTypeVar.asElement(), config, handler, state)) { + st.parametricNullable = true; + } + } } /* ───────────────────── nullability bookkeeping ───────────────────── */ @@ -501,6 +573,18 @@ private boolean treatAsTypeVariableForInference(Type t) { return inferenceVariableForUse(t) != null; } + /** + * Returns whether {@code t} is a fixed type variable, not a capture, carrying no nullness + * annotation at this use, whose bound is explicitly nullable. + */ + private boolean admitsNullThroughExplicitBound(Type t) { + return t instanceof TypeVar tv + && !(t instanceof CapturedType) + && !inferenceVariables.containsKey(tv.asElement()) + && !GenericsUtils.hasNullnessAnnotation(t, config) + && GenericsUtils.boundIsExplicitlyNullable(tv.asElement(), config, handler, state); + } + /** 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/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index de436682aa..d5781eabc8 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -2237,7 +2237,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); @@ -3095,6 +3095,7 @@ public void compareGenericTypeParameterNullabilityForCall( * nullability inference, return the method type with inferred nullability for type parameters. * Otherwise, return the original method type. * + * @param memberReferenceTree the generic method reference * @param methodType the original method type * @param state the visitor state (generic method reference should be leaf of {@code * state.getPath()}) @@ -3102,21 +3103,29 @@ public void compareGenericTypeParameterNullabilityForCall( * performed, or the original method type otherwise */ 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)) { + if ((parentTree instanceof MethodInvocationTree || parentTree instanceof NewClassTree) + && isCallNeedingInference((ExpressionTree) parentTree)) { 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; + Type.MethodType typeToUpdate = + referentType instanceof Type.MethodType referentMethodType + && referentMethodType.getParameterTypes().size() + == methodType.getParameterTypes().size() + ? referentMethodType + : methodType; return TypeSubstitutionUtils.updateMethodTypeWithInferredNullability( - methodType, + typeToUpdate, methodType, successResult.typeVarNullabilityForSite(memberReferenceTree), state, @@ -3965,6 +3974,9 @@ private Type.MethodType getInvokedMethodTypeAtCall( && invokedMethodType instanceof Type.ForAll forAllType) { return substituteTypeArgsInGenericMethodType( tree, forAllType, path, state, calledFromDataflow); + } else if (tree instanceof NewClassTree newClassTree + && invokedMethodType instanceof Type.ForAll forAllType) { + invokedMethodType = substituteInferredConstructorTypeArgs(newClassTree, forAllType, state); } Type.MethodType modeledMethodType = handler.onOverrideMethodType( @@ -4192,6 +4204,37 @@ private static Type polyNullAnnotationType(Nullness nullness, VisitorState 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 or no inference result. + * + * @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); + } + /** * Computes the nullness of a formal parameter of a generic method at an invocation, in the * context of the declared type of its receiver argument. If the formal parameter's type is a type 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..3cd1304e4d 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java @@ -377,7 +377,7 @@ 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); } @@ -417,8 +417,38 @@ 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: the declared + * bound is annotated {@code @Nullable}, a library model overrides it, or the declared bound is + * another type variable, carrying no nullness annotation, whose bound is explicitly nullable. + * 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 boolean boundIsExplicitlyNullable( + Element typeVarElement, Config config, Handler handler, VisitorState state) { + Type upperBound = (Type) ((TypeVariable) typeVarElement.asType()).getUpperBound(); + if (isAnnotatedAsNullable(upperBound, config) + || libraryModelMakesBoundNullable(typeVarElement, handler, state)) { + return true; + } + return !hasNullnessAnnotation(upperBound, config) + && upperBound.getKind() == TypeKind.TYPEVAR + && boundIsExplicitlyNullable(upperBound.asElement(), config, handler, state); + } + + /** Returns true if a library model overrides the upper bound of the given type variable. */ + 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 +472,10 @@ static boolean declaredUpperBoundIsNullable( return true; } } - Type upperBound = (Type) ((TypeVariable) typeVarElement.asType()).getUpperBound(); - return isAnnotatedAsNullable(upperBound, config); + return false; } - private static boolean fromUnannotatedMethodOrClass( + 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/TypeSubstitutionUtils.java b/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java index 298c2ceab0..59514b0e4d 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; @@ -143,7 +142,8 @@ 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, 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: a type variable and an intersection type stay unannotated, and any other type becomes + * {@code @Nullable} or {@code @NonNull}, as the result says. * * @param typeToUpdate the type to update * @param origType the original type with type variables and possibly explicit nullability @@ -262,8 +266,11 @@ 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, typeVarNullability, state) + .visit(typeToUpdate, origExplicitAnnotationsRestored); } /** @@ -345,6 +352,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 +370,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(); @@ -588,9 +600,27 @@ 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 when copying + * inferred nullness onto the type javac inferred, the one step that can tell a type variable + * from any other type; {@link #state} is set with it. + */ + private final @Nullable Map typeVarNullability; + + private final @Nullable VisitorState state; + + RestoreNullnessAnnotationsVisitor( + Types types, + Config config, + @Nullable Map typeVarNullability, + @Nullable VisitorState state) { this.types = types; this.config = config; + this.typeVarNullability = typeVarNullability; + this.state = state; } @Override @@ -918,6 +948,24 @@ private Type updateDirectNullabilityAnnotationsForType(Type t, Type other) { return typeWithAnnot(t, annot); } } + // a variable step 1 left unannotated takes javac's type variable as written, and the root of + // an intersection keeps the nullness of its elements + if (typeVarNullability == null + || state == null + || !(other instanceof Type.TypeVar) + || t instanceof Type.TypeVar + || t instanceof Type.IntersectionClassType) { + return t; + } + ConstraintSolver.InferredNullability inferred = typeVarNullability.get(other.tsym); + if (inferred == ConstraintSolver.InferredNullability.TYPE_VARIABLE_OR_NULLABLE) { + return TypeSubstitutionUtils.typeWithAnnot( + t, GenericsChecks.getSyntheticNullableAnnotType(state)); + } + if (inferred == ConstraintSolver.InferredNullability.TYPE_VARIABLE_OR_NONNULL) { + return TypeSubstitutionUtils.typeWithAnnot( + t, GenericsChecks.getSyntheticNonNullAnnotType(state)); + } return t; } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java index 743a79a682..765a1fc288 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -5,6 +5,7 @@ import com.uber.nullaway.generics.JSpecifyJavacConfig; import java.util.Arrays; import java.util.List; +import org.junit.Assume; import org.junit.Test; public class WildcardTests extends NullAwayTestsBase { @@ -2127,4 +2128,488 @@ private CompilationTestHelper makeHelper() { JSpecifyJavacConfig.withJSpecifyModeArgs( Arrays.asList("-XepOpt:NullAway:OnlyNullMarked=true"))); } + + @Test + public void anInferenceResultFixedNonNullKeepsNullOutOfALowerBound() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box { + E e; + Box(E e) { this.e = e; } + void set(E e) { this.e = e; } + E get() { return e; } + } + static Box id(Box box) { + return box; + } + static Box wrap(E e) { + return new Box<>(e); + } + static void leastSolutionOfANonNullArgument() { + var inferred = wrap(new Object()); + // BUG: Diagnostic contains: incompatible types + Box sink = inferred; + sink.set(null); + inferred.get().toString(); + } + static void fixedByTheArgument(Box original) { + var inferred = id(original); + // BUG: Diagnostic contains: incompatible types + Box sink = inferred; + sink.set(null); + original.get().toString(); + } + void fixedByAProjection(Box<@NonNull T> original) { + var inferred = id(original); + // BUG: Diagnostic contains: incompatible types + Box sink = inferred; + } + } + """) + .doTest(); + } + + /** + * Where javac inferred a class type, such as {@code Object} for the least upper bound of {@code + * T} and {@code String}, an inference variable that a {@code T} whose bound admits null reached + * is {@code @Nullable}: no other nullness of {@code Object} holds a null {@code T}. Every reader + * of the result sees the same {@code @Nullable}, so a list that accepts a null through {@code + * sink} also reports the null read back from it. Where javac inferred {@code T} itself, the + * result is {@code T} and is dereferenced without a report, as {@code t} is (#1727). A + * {@code @NonNull} written on the variable's use keeps that use non-null. + */ + @Test + public void anInferenceResultInferredAsAClassTypeHoldsTheNullOfTheTypeVariable() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static List of(E a, E b) { + throw new UnsupportedOperationException(); + } + static U pick(U a, U b) { + return a; + } + static @NonNull U pickNonNull(U a, U b) { + throw new UnsupportedOperationException(); + } + static List<@NonNull U> ofNonNull(U a, U b) { + throw new UnsupportedOperationException(); + } + static void takeObjects(List objects) {} + void throughALocal(T t) { + var inferred = of(t, "x"); + List sink = inferred; + sink.add(null); + // BUG: Diagnostic contains: incompatible types: List<@Nullable Object> cannot be converted to List + List source = inferred; + // BUG: Diagnostic contains: dereferenced expression 'inferred.get(0)' is @Nullable + inferred.get(0).toString(); + // BUG: Diagnostic contains: incompatible types + takeObjects(inferred); + } + void throughTheCall(T t) { + // BUG: Diagnostic contains: dereferenced expression 'pick(t, "x")' is @Nullable + pick(t, "x").toString(); + // BUG: Diagnostic contains: dereferenced expression 'of(t, "x").get(0)' is @Nullable + of(t, "x").get(0).toString(); + } + void explicitlyNonNull(T t) { + pickNonNull(t, "x").toString(); + ofNonNull(t, "x").get(0).toString(); + } + void inferredAsTheTypeVariable(T t) { + pick(t, t).toString(); + } + } + """) + .doTest(); + } + + /** + * The {@code @Nullable} inferred for a class-type result reaches a lambda parameter, an + * enhanced-for variable, and the receiver of a call on the result, which read the inferred type + * rather than the call's return nullness. + */ + @Test + public void aClassTypeResultIsNullableInLambdasLoopsAndReceivers() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import java.util.function.Consumer; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box { + E get() { + throw new UnsupportedOperationException(); + } + } + static List of(E a, E b) { + throw new UnsupportedOperationException(); + } + static U pick(U a, U b) { + return a; + } + static Box wrap(E e) { + throw new UnsupportedOperationException(); + } + static void with(U a, U b, Consumer c) {} + void lambdaParameter(T t) { + with(t, "x", u -> { + // BUG: Diagnostic contains: dereferenced expression 'u' is @Nullable + u.toString(); + }); + } + void loopVariable(T t) { + for (Object o : of(t, "x")) { + // BUG: Diagnostic contains: dereferenced expression 'o' is @Nullable + o.hashCode(); + } + } + void receiver(T t) { + // BUG: Diagnostic contains: dereferenced expression 'wrap(pick(t, "x")).get()' is @Nullable + wrap(pick(t, "x")).get().toString(); + } + } + """) + .doTest(); + } + + /** + * The {@code @Nullable} inferred for a class-type result reaches a wildcard in the result type + * and a wildcard that a member of a diamond's class returns, where javac's type carries a capture + * or a wildcard bound that the inferred nullness was never substituted into. + */ + @Test + public void aClassTypeResultIsNullableInsideAWildcard() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box { + Box(E a, E b) {} + Box self() { + throw new UnsupportedOperationException(); + } + Box sink() { + throw new UnsupportedOperationException(); + } + E get() { + throw new UnsupportedOperationException(); + } + void set(E e) {} + } + static Box wrap(U a, U b) { + throw new UnsupportedOperationException(); + } + static Box sinkOf(U a, U b) { + throw new UnsupportedOperationException(); + } + void f(T t) { + // BUG: Diagnostic contains: dereferenced expression 'wrap(t, "x").get()' is @Nullable + wrap(t, "x").get().toString(); + sinkOf(t, "x").set(null); + var box = new Box<>(t, "x"); + // BUG: Diagnostic contains: dereferenced expression 'box.self().get()' is @Nullable + box.self().get().toString(); + box.sink().set(null); + // BUG: Diagnostic contains: incompatible types + Box nonNull = box.self(); + } + } + """) + .doTest(); + } + + /** + * A class-type result is {@code @Nullable} only where the bound of the type variable that reached + * it and the bound of the inference variable itself are explicitly nullable, directly or through + * another type variable. Elsewhere it is non-null, the least solution: a type variable from + * unannotated code and an unannotated callee are read optimistically, and a {@code @NonNull} + * written in unannotated code still excludes null. + */ + @Test + public void aClassTypeResultIsNullableOnlyThroughExplicitlyNullableBounds() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.NullUnmarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static List of(E a, E b) { + throw new UnsupportedOperationException(); + } + static List ofThroughAVariable(E a, E b) { + throw new UnsupportedOperationException(); + } + static List nonNullOf(E a, E b) { + throw new UnsupportedOperationException(); + } + @NullUnmarked + static class Lib { + static List unannotatedOf(E a, E b) { + throw new UnsupportedOperationException(); + } + static List nonNullOf(E a, E b) { + throw new UnsupportedOperationException(); + } + } + static void boundNullableThroughAVariable(T t) { + // BUG: Diagnostic contains: dereferenced expression 'ofThroughAVariable(t, "x").get(0)' is @Nullable + ofThroughAVariable(t, "x").get(0).toString(); + } + static void ownBoundExcludesNull(T t) { + nonNullOf(t, "x").get(0).toString(); + } + static void unannotatedCallee(T t) { + Lib.unannotatedOf(t, "x").get(0).toString(); + var inferred = Lib.nonNullOf(t, "x"); + inferred.get(0).toString(); + // BUG: Diagnostic contains: incompatible types + List sink = inferred; + } + @NullUnmarked + static class Unmarked { + @NullMarked + void unannotatedTypeVariable(T t) { + var inferred = of(t, "x"); + inferred.get(0).toString(); + // BUG: Diagnostic contains: incompatible types + List sink = inferred; + } + } + } + """) + .doTest(); + } + + /** + * A generic method reference and a generic constructor are judged against the types javac + * inferred for them, as a generic method call is, so the {@code @Nullable} inferred for {@code U} + * on the referenced method and on the constructor is the one its parameters are checked with. + */ + @Test + public void aGenericMethodReferenceAndAGenericConstructorTakeTheInferredClassType() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import java.util.function.Function; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box { + Box(Box input, U hint) {} + } + static class Holder { + Holder(E a, E b, Function> function) {} + } + static void use(U a, U b, Function> function) {} + static List singleton(V value) { + throw new UnsupportedOperationException(); + } + void methodReference(T t) { + use(t, new Object(), Test::singleton); + } + void methodReferenceIntoADiamond(T t) { + var holder = new Holder<>(t, new Object(), Test::singleton); + } + void constructor(Box input) { + var result = new Box<>(input, new Object()); + } + } + """) + .doTest(); + } + + @Test + public void aClassTypeResultIsNullableThroughNestedCallsOfOneMethod() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box { + final E value; + Box(E value) { + this.value = value; + } + E get() { + return value; + } + } + static U pick(U a, U b) { + return a; + } + void nestedDiamonds(T t) { + new Box<>(new Box<>(t)).get().toString(); + } + void nestedCallsOfOneMethod(T t) { + // BUG: Diagnostic contains: dereferenced expression 'pick(pick(t, "x"), "y")' is @Nullable + pick(pick(t, "x"), "y").toString(); + } + } + """) + .doTest(); + } + + /** + * Dataflow reads a {@code T} whose bound admits null as non-null whether or not the code checked + * it (#1727), so inference cannot tell a checked {@code t} from an unchecked one, and a + * class-type result is {@code @Nullable} after a null check too. This is a false positive. + */ + @Test + public void aNullCheckOfATypeVariableDoesNotReachInference() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static U pick(U a, U b) { + return a; + } + void f(T t) { + if (t != null) { + // BUG: Diagnostic contains: dereferenced expression 'pick(t, "x")' is @Nullable + pick(t, "x").toString(); + } + } + } + """) + .doTest(); + } + + /** + * Where javac inferred an intersection type, such as the least upper bound of two classes that + * implement {@code Runnable} and {@code Serializable}, the result carries no annotation, since + * the root of an intersection takes the nullness of its elements, so it stays non-null even where + * a {@code T} that admits null reached it. + */ + @Test + public void aClassTypeResultInferredAsAnIntersectionStaysNonNull() { + // on JDK 17, javac refuses to annotate an intersection type, and NullAway fails on this source + // whether or not this change is applied + Assume.assumeTrue(Runtime.version().feature() > 17); + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.io.Serializable; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class A implements Runnable, Serializable { + public void run() {} + } + static class B implements Runnable, Serializable { + public void run() {} + } + static E pick(E a, E b) { + return a; + } + void f(T t) { + pick(t, new B()).run(); + } + } + """) + .doTest(); + } + + /** + * The JSpecify JDK models decide the bound of the inference variable: {@code Arrays.asList} + * admits null and {@code List.of} does not. + */ + @Test + public void aClassTypeResultFromTheJdkFollowsTheModelsBound() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.Arrays; + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + void f(T t) { + // BUG: Diagnostic contains: dereferenced expression 'Arrays.asList(t, "x").get(0)' is @Nullable + Arrays.asList(t, "x").get(0).toString(); + List.of(t, "x").get(0).toString(); + } + } + """) + .doTest(); + } + + @Test + public void inferenceCannotFitATypeVariableWhoseBoundAdmitsNullIntoANonNullVariable() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static U nonNullVariable(Box b) { + throw new UnsupportedOperationException(); + } + static U nullableVariable(Box b) { + throw new UnsupportedOperationException(); + } + static void intoNonNullVariable(Box b) { + // BUG: Diagnostic contains: inference failure: type variable U is constrained to be @Nullable + Object o = nonNullVariable(b); + } + static void intoNullableVariable(Box b) { + Object o = nullableVariable(b); + } + static void nonNullBoundIntoNonNullVariable(Box b) { + Object o = nonNullVariable(b); + } + static void intoJdkCopyOf(List in) { + // BUG: Diagnostic contains: inference failure: type variable E is constrained to be @Nullable + List copy = List.copyOf(in); + } + } + """) + .doTest(); + } } From aa64a9cbe34dc77c0f287e42ea24134c219c9cef Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Tue, 24 Nov 2026 21:04:43 +0300 Subject: [PATCH 02/27] Keep an inferred type variable only where its bound admits null Where inference leaves a variable to the type javac inferred, the previous commit kept any type variable javac inferred as written. With ``, `pick(t, r)` for ` U pick(U a, U b)` got `R`, whose bound excludes null, so a null `T` passed unreported. PolyNull library models resolved their shared variable to `@Nullable` everywhere instead, so `accept(genericFirst(t, () -> "x"))` with ` void accept(X x)` reported its own argument, and an explicit `@Nullable X` type argument kept `@Nullable` inside `if (x != null)`. Both sites now ask one question, GenericsUtils.keepsInferredTypeAsWritten: an intersection type, or an unannotated, uncaptured type variable whose bound admits null, stays as written; any other type takes the annotation the inference result gives. PolyNull applies it at each modeled location, so the per-call result carries the solver's InferredNullability rather than a Nullness. The commit also carries the rest of the review of the previous commit: the inference failure is thrown directly where the `? extends U` check fails, the visibility of two GenericsUtils helpers is back to private, the Javadoc of InferredNullability and VarState.parametric states the admits-null condition the code checks, and tests cover the generic constructor and method-reference paths, the null check before a call (#1727), and the variables an inference failure discards. The inference failure for a `? extends U` now prints the type argument as passed and the type variable that admits null. User-visible: - `inference failure: type variable U is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument ? extends T passed for ? extends U admits null, since T has a @Nullable upper bound` for a `Box`, and the same suffix with `T` for a `Box`. - `dereferenced expression 'pick(t, r)' is @Nullable` with ``, and `dereferenced expression 'optional.orElseGet(() -> fallback)' is @Nullable` with an `Optional`; accepted at the previous commit. - No report for `accept(PolyNullMethods.genericFirst(t, () -> "x"))` or for `PolyNullMethods.<@Nullable X, String>genericFirst(x, () -> "x").hashCode()` inside `if (x != null)`. Not changed: - `List.copyOf(Legacy.identity(in))`, with an unmarked ` List identity(List xs)`, is not reported; the same call through a `var` local is. Assisted-by: Claude Code (claude-opus-5-5) --- .../nullaway/generics/ConstraintSolver.java | 87 +++++++++--- .../generics/ConstraintSolverImpl.java | 35 ++--- .../nullaway/generics/GenericsChecks.java | 88 +++++++----- .../uber/nullaway/generics/GenericsUtils.java | 23 +++- .../nullaway/generics/PolyNullInference.java | 96 +++++++++---- .../generics/TypeSubstitutionUtils.java | 69 ++++++---- .../librarymodel/NestedTypePathUpdater.java | 43 +++++- .../generics/PolyNullInferenceTests.java | 7 +- .../jspecify/PolyNullLibraryModelsTests.java | 60 +++++++++ .../uber/nullaway/jspecify/WildcardTests.java | 126 +++++++++++++++++- 10 files changed, 509 insertions(+), 125 deletions(-) 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 6eeabc99c5..9a58173ef0 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,49 @@ class UnsatisfiableConstraintsException extends RuntimeException { /** Whether a {@code @Nullable} constraint conflicts with the type variable's upper bound. */ private final boolean causedByNonNullUpperBound; + /** + * The type argument, as passed for a {@code ? extends} wildcard, whose {@code @Nullable} + * constraint conflicts with the bound of {@link #typeVariable}, or {@code null} where another + * constraint caused the conflict. + */ + private final @Nullable Type nullableBoundTypeArgument; + + /** + * The type variable with an explicitly nullable bound through which {@link + * #nullableBoundTypeArgument} admits null: that argument itself, or the bound of a wildcard + * argument; {@code null} where {@link #nullableBoundTypeArgument} is. + */ + private final @Nullable Type nullableBoundTypeVariable; + 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, passed {@code + * nullableBoundTypeArgument} for a {@code ? extends typeVariable} wildcard, where {@code + * nullableBoundTypeVariable} has an explicitly nullable bound and is that argument or the bound + * of that argument. + */ + public UnsatisfiableConstraintsException( + Element typeVariable, Type nullableBoundTypeArgument, Type nullableBoundTypeVariable) { + this(typeVariable, true, nullableBoundTypeArgument, nullableBoundTypeVariable); + } + + private UnsatisfiableConstraintsException( + Element typeVariable, + boolean causedByNonNullUpperBound, + @Nullable Type nullableBoundTypeArgument, + @Nullable Type nullableBoundTypeVariable) { this.typeVariable = typeVariable; this.causedByNonNullUpperBound = causedByNonNullUpperBound; + this.nullableBoundTypeArgument = nullableBoundTypeArgument; + this.nullableBoundTypeVariable = nullableBoundTypeVariable; } public Element getTypeVariable() { @@ -79,6 +115,14 @@ public Element getTypeVariable() { public boolean isCausedByNonNullUpperBound() { return causedByNonNullUpperBound; } + + public @Nullable Type getNullableBoundTypeArgument() { + return nullableBoundTypeArgument; + } + + public @Nullable Type getNullableBoundTypeVariable() { + return nullableBoundTypeVariable; + } } /** @@ -99,31 +143,44 @@ void addSubtypeConstraint(Type subtype, Type supertype, boolean localVariableTyp /** The nullness the solver found for an inference variable. */ enum InferredNullability { - /** A constraint fixed the variable to be non-null. */ + /** + * 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. + */ NONNULL, /** 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. Where javac - * inferred a type variable, the variable is that type variable as written; 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}, the variable is {@code @Nullable}, the - * least type that holds a null {@code T}. - * - *

A variable that no constraint fixed and no such type variable reached is {@link #NONNULL}, - * the least solution. + * inferred a unannotated type variable whose bound admits null, the variable is that type + * variable as written; 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 a type variable whose bound admits null flowed into it, - * but no type variable whose bound is explicitly nullable did, or the variable's own bound is - * not explicitly nullable. Where javac inferred a type variable, the variable is that type - * variable as written; 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 reached it. + * 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 an unannotated type variable whose bound admits + * null, the variable is that type variable as written; 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; + + /** + * Returns whether the variable is {@code @Nullable} where javac inferred a type that {@link + * GenericsUtils#keepsInferredTypeAsWritten} does not keep as written, such as a class type, or + * where such a type stands at a location of a PolyNull model. */ - TYPE_VARIABLE_OR_NONNULL + boolean isNullableWhereNotKeptAsWritten() { + return this == NULLABLE || this == TYPE_VARIABLE_OR_NULLABLE; + } } /** 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 cf9fbbab9d..aff3911885 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java @@ -75,9 +75,10 @@ private static final class VarState { NullnessState nullness = NullnessState.UNKNOWN; /** - * Whether a type variable that is not under inference, carrying no annotation and bounded by a - * type that admits null, flowed into this variable. Such a flow fixes no nullness, but it means - * the variable takes that type variable's nullness rather than the non-null default. + * Whether a type variable that is not under inference, carries no nullness annotation, and is + * bounded by a type that admits null flowed into this variable. Such a flow fixes no nullness, + * but where javac inferred a type variable whose bound admits null, the variable takes that + * type variable as written rather than the non-null default. */ boolean parametric; @@ -322,12 +323,14 @@ private void constrainContainedByWildcard(Type subtypeTypeArg, WildcardType supe && admitsNullThroughExplicitBound(subtypeUpperBound) && supertypeVar != null && !getState(supertypeVar).nullableAllowed) { - // The containment check judges such a type variable by its nullable bound, which no - // instantiation of a variable bounded by a non-null type can contain. Where the bound - // allows null the constraint is left out: the solver infers one nullness per - // variable, so a @Nullable U would substitute @Nullable T for U where javac inferred - // T, and List copy = copyOf(in) would then be reported. - updateNullness(supertypeVar, NullnessState.NULLABLE); + // 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 in), would be reported. + throw new UnsatisfiableConstraintsException( + supertypeVar.typeVariable(), subtypeTypeArg, subtypeUpperBound); } subtypeUpperBound.accept(this, supertypeUpperBound); } @@ -421,7 +424,7 @@ public Map solve() } } - /* a variable above a parametric one takes the same type variable's nullness */ + /* a type variable that flowed into a variable flows into every variable above it */ vars.forEach( (inferenceVar, st) -> { if (st.parametric) { @@ -450,7 +453,8 @@ public Map solve() case NULLABLE -> InferredNullability.NULLABLE; case NONNULL -> InferredNullability.NONNULL; // nothing pushed the variable toward null, so non-null is the least solution, - // unless a type variable that may be null flowed in and decides its nullness + // unless an unannotated type variable whose bound admits null flowed in and + // decides its nullness case UNKNOWN -> { if (!st.parametric) { yield InferredNullability.NONNULL; @@ -499,13 +503,12 @@ private void directlyConstrainTypePair(Type s, Type t) throws UnsatisfiableConst } if (tVar != null && sVar == null - && s instanceof TypeVar fixedTypeVar + && s instanceof TypeVar typeVar && !isKnownNullable(s) && !isKnownNonNull(s)) { VarState st = getState(tVar); st.parametric = true; - if (GenericsUtils.boundIsExplicitlyNullable( - fixedTypeVar.asElement(), config, handler, state)) { + if (GenericsUtils.boundIsExplicitlyNullable(typeVar.asElement(), config, handler, state)) { st.parametricNullable = true; } } @@ -574,8 +577,8 @@ private boolean treatAsTypeVariableForInference(Type t) { } /** - * Returns whether {@code t} is a fixed type variable, not a capture, carrying no nullness - * annotation at this use, whose bound is explicitly nullable. + * Returns whether {@code t} is a type variable not under inference, not a capture, carrying no + * nullness annotation at this use, whose bound is explicitly nullable. */ private boolean admitsNullThroughExplicitBound(Type t) { return t instanceof TypeVar tv 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 d5781eabc8..cc8bdd10da 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -99,7 +99,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 +111,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 +175,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 @@ -1445,15 +1447,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 +1473,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 +1571,8 @@ private CallInferenceResult runInferenceForCall( formalParamGroundTargetType, typeVarNullability, state, - config); + config, + handler); inferredPolyExpressionTypes.put(argument, typeWithInferredNullability); } } @@ -1585,6 +1602,12 @@ private String inferenceFailureMessage( if (polyNullInvocation != null) { return PolyNullInference.inferenceFailureMessage(ASTHelpers.getSymbol(polyNullInvocation)); } + Type nullableBoundTypeArgument = e.getNullableBoundTypeArgument(); + if (nullableBoundTypeArgument != null) { + 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 has a @Nullable upper bound", + typeVariable, nullableBoundTypeArgument, typeVariable, e.getNullableBoundTypeVariable()); + } 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", @@ -3118,8 +3141,12 @@ && isCallNeedingInference((ExpressionTree) parentTree)) { // 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 = referentType instanceof Type.MethodType referentMethodType + // diff-coverage: ignore -- defensive guard, no known call shape reaches it && referentMethodType.getParameterTypes().size() == methodType.getParameterTypes().size() ? referentMethodType @@ -3129,7 +3156,8 @@ && isCallNeedingInference((ExpressionTree) parentTree)) { methodType, successResult.typeVarNullabilityForSite(memberReferenceTree), state, - config); + config, + handler); } } return methodType; @@ -3650,7 +3678,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 @@ -3701,7 +3729,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. @@ -4004,7 +4033,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) { @@ -4012,7 +4041,7 @@ private Type.MethodType applyPolyNullModel( if (locations.isEmpty()) { return substitutedMethodType; } - Nullness polyNullness = + ConstraintSolver.InferredNullability polyNullness = jointlyInferredPolyNullness != null ? jointlyInferredPolyNullness : inferPolyNullnessSeparately( @@ -4027,7 +4056,7 @@ private Type.MethodType applyPolyNullModel( return substitutedMethodType; } return PolyNullInference.applyToMethodType( - substitutedMethodType, locations, polyNullAnnotationType(polyNullness, state)); + substitutedMethodType, locations, polyNullness, state, config, handler); } /** @@ -4040,10 +4069,10 @@ private Type.MethodType applyPolyNullModel( * * @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, @@ -4051,7 +4080,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; } @@ -4088,7 +4118,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); @@ -4100,7 +4130,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; } } @@ -4197,17 +4229,12 @@ 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 or no inference result. + * explicit type arguments or no inference result, 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 @@ -4232,7 +4259,8 @@ private Type substituteInferredConstructorTypeArgs( declaredMethodType, successResult.typeVarNullabilityForSite(tree), state, - config); + config, + handler); } /** 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 3cd1304e4d..dee8fc91b4 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java @@ -381,6 +381,25 @@ static boolean hasNullnessAnnotation(Type type, Config config) { return isAnnotatedAsNonNull(type, config) || isAnnotatedAsNullable(type, config); } + /** + * Returns whether {@code type}, which javac inferred for a variable that inference resolved to + * {@code TYPE_VARIABLE_OR_NULLABLE} or {@code TYPE_VARIABLE_OR_NONNULL}, stays as written rather + * than taking the annotation those results give. It stays where it already holds the null of a + * type variable that flowed into the variable: an unannotated type variable whose bound admits + * null, or an intersection type, whose nullness comes from its elements. A captured type variable + * or a type variable with a nullness annotation takes the annotation. + */ + static boolean keepsInferredTypeAsWritten( + Type type, Config config, Handler handler, VisitorState state) { + if (type.isCompound()) { + return true; + } + return type instanceof Type.TypeVar typeVariable + && !(type instanceof Type.CapturedType) + && !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. * @@ -445,7 +464,7 @@ static boolean boundIsExplicitlyNullable( } /** Returns true if a library model overrides the upper bound of the given type variable. */ - static boolean libraryModelMakesBoundNullable( + 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. @@ -475,7 +494,7 @@ static boolean libraryModelMakesBoundNullable( return false; } - static boolean fromUnannotatedMethodOrClass( + private 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/PolyNullInference.java b/nullaway/src/main/java/com/uber/nullaway/generics/PolyNullInference.java index 13a35aaa94..d8c6aff0d1 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,24 @@ 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. + * + *

Where {@code inferred} is {@code TYPE_VARIABLE_OR_NULLABLE} or {@code + * TYPE_VARIABLE_OR_NONNULL}, a location whose type {@link + * GenericsUtils#keepsInferredTypeAsWritten} accepts keeps that type as written, as {@link + * TypeSubstitutionUtils} keeps the type javac inferred for a method's own type variable. A type + * variable with a nullness annotation, such as an explicit type argument, takes the PolyNull + * annotation. + */ @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 +83,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 +104,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 +133,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 +273,33 @@ 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 annotationType = + inferred.isNullableWhereNotKeptAsWritten() + ? GenericsChecks.getSyntheticNullableAnnotType(state) + : GenericsChecks.getSyntheticNonNullAnnotType(state); + boolean keepTypeVariables = + inferred == ConstraintSolver.InferredNullability.TYPE_VARIABLE_OR_NULLABLE + || inferred == ConstraintSolver.InferredNullability.TYPE_VARIABLE_OR_NONNULL; Type updated = type; for (PolyNullLocation location : locations) { if (location.position().equals(position)) { - updated = NestedTypePathUpdater.addAnnotation(updated, location.typePath(), annotationType); + updated = + keepTypeVariables + ? NestedTypePathUpdater.addAnnotationUnless( + updated, + location.typePath(), + annotationType, + leaf -> GenericsUtils.keepsInferredTypeAsWritten(leaf, config, handler, state)) + : NestedTypePathUpdater.addAnnotation(updated, location.typePath(), annotationType); } } return updated; 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 59514b0e4d..4c46e27671 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java @@ -15,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; @@ -142,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, null, null) + return new RestoreNullnessAnnotationsVisitor(types, config, null, null, null) .visit(newType, origType); } @@ -236,7 +237,8 @@ public static Type.WildcardType replaceImplicitWildcardUpperBound( * 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: a type variable and an intersection type stay unannotated, and any other type becomes + * it: a type that {@link GenericsUtils#keepsInferredTypeAsWritten} accepts, such as a type + * variable whose bound admits null, stays as written, and any other type becomes * {@code @Nullable} or {@code @NonNull}, as the result says. * * @param typeToUpdate the type to update @@ -245,6 +247,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( @@ -252,7 +255,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; @@ -269,15 +273,15 @@ static Type updateTypeWithInferredNullability( // 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, typeVarNullability, state) + state.getTypes(), config, 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 @@ -285,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") @@ -293,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 { @@ -318,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; @@ -612,15 +621,20 @@ private Type restoreImplicitWildcardBound(BoundPair pair, Type targetBound, Type private final @Nullable VisitorState state; + /** Decides whether a type variable's bound admits null; set with {@link #state}. */ + private final @Nullable Handler handler; + RestoreNullnessAnnotationsVisitor( Types types, Config config, @Nullable Map typeVarNullability, - @Nullable VisitorState state) { + @Nullable VisitorState state, + @Nullable Handler handler) { this.types = types; this.config = config; this.typeVarNullability = typeVarNullability; this.state = state; + this.handler = handler; } @Override @@ -921,7 +935,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}, annotates {@code t} as that result says, unless {@link + * GenericsUtils#keepsInferredTypeAsWritten} keeps {@code t} as written. * * @param t the type to update * @param other the type to update from @@ -948,25 +965,25 @@ private Type updateDirectNullabilityAnnotationsForType(Type t, Type other) { return typeWithAnnot(t, annot); } } - // a variable step 1 left unannotated takes javac's type variable as written, and the root of - // an intersection keeps the nullness of its elements if (typeVarNullability == null || state == null - || !(other instanceof Type.TypeVar) - || t instanceof Type.TypeVar - || t instanceof Type.IntersectionClassType) { + || handler == null + || !(other instanceof Type.TypeVar)) { return t; } ConstraintSolver.InferredNullability inferred = typeVarNullability.get(other.tsym); - if (inferred == ConstraintSolver.InferredNullability.TYPE_VARIABLE_OR_NULLABLE) { - return TypeSubstitutionUtils.typeWithAnnot( - t, GenericsChecks.getSyntheticNullableAnnotType(state)); + if (inferred != ConstraintSolver.InferredNullability.TYPE_VARIABLE_OR_NULLABLE + && inferred != ConstraintSolver.InferredNullability.TYPE_VARIABLE_OR_NONNULL) { + return t; } - if (inferred == ConstraintSolver.InferredNullability.TYPE_VARIABLE_OR_NONNULL) { - return TypeSubstitutionUtils.typeWithAnnot( - t, GenericsChecks.getSyntheticNonNullAnnotType(state)); + if (GenericsUtils.keepsInferredTypeAsWritten(t, config, handler, state)) { + return t; } - return t; + return TypeSubstitutionUtils.typeWithAnnot( + t, + inferred.isNullableWhereNotKeptAsWritten() + ? GenericsChecks.getSyntheticNullableAnnotType(state) + : GenericsChecks.getSyntheticNonNullAnnotType(state)); } /** 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..60ed5b907c 100644 --- a/nullaway/src/main/java/com/uber/nullaway/librarymodel/NestedTypePathUpdater.java +++ b/nullaway/src/main/java/com/uber/nullaway/librarymodel/NestedTypePathUpdater.java @@ -10,6 +10,8 @@ import com.sun.tools.javac.util.ListBuffer; import com.uber.nullaway.generics.TypeSubstitutionUtils; import com.uber.nullaway.libmodel.NestedAnnotationInfo; +import java.util.function.Predicate; +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 @@ -24,13 +26,18 @@ private enum UpdateKind { private final Type annotationOrReplacementType; private final UpdateKind updateKind; + /** The types that an added annotation leaves as written, or {@code null} for none. */ + private final @Nullable Predicate keepAsWritten; + private NestedTypePathUpdater( ImmutableList typePath, Type annotationOrReplacementType, - UpdateKind updateKind) { + UpdateKind updateKind, + @Nullable Predicate keepAsWritten) { this.typePath = typePath; this.annotationOrReplacementType = annotationOrReplacementType; this.updateKind = updateKind; + this.keepAsWritten = keepAsWritten; } /** @@ -40,7 +47,25 @@ private NestedTypePathUpdater( */ public static Type addAnnotation( Type type, ImmutableList typePath, Type annotationType) { - return new NestedTypePathUpdater(typePath, annotationType, UpdateKind.ADD_ANNOTATION) + return new NestedTypePathUpdater(typePath, annotationType, UpdateKind.ADD_ANNOTATION, null) + .apply(type); + } + + /** + * Adds {@code annotationType} to {@code type} at {@code typePath}, as {@link #addAnnotation} + * does, except that a type at {@code typePath} that {@code keepAsWritten} accepts is left as + * written. A wildcard or a captured type variable at {@code typePath} is annotated as {@link + * #addAnnotation} annotates it, without the test. + * + * @return the updated type, or the original {@code type} instance if no change was made + */ + public static Type addAnnotationUnless( + Type type, + ImmutableList typePath, + Type annotationType, + Predicate keepAsWritten) { + return new NestedTypePathUpdater( + typePath, annotationType, UpdateKind.ADD_ANNOTATION, keepAsWritten) .apply(type); } @@ -51,7 +76,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, replacement, UpdateKind.REPLACE_TYPE, null) + .apply(type); } private Type apply(Type type) { @@ -59,9 +85,14 @@ private Type apply(Type type) { } private Type updateLeaf(Type type) { - return updateKind == UpdateKind.ADD_ANNOTATION - ? TypeSubstitutionUtils.typeWithAnnot(type, annotationOrReplacementType) - : annotationOrReplacementType; + return updateKind == UpdateKind.ADD_ANNOTATION ? annotate(type) : annotationOrReplacementType; + } + + /** Adds the annotation to {@code type}, unless {@link #keepAsWritten} accepts it. */ + private Type annotate(Type type) { + return keepAsWritten != null && keepAsWritten.test(type) + ? type + : TypeSubstitutionUtils.typeWithAnnot(type, annotationOrReplacementType); } @Override 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/PolyNullLibraryModelsTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/PolyNullLibraryModelsTests.java index 6b613bce45..e9d3be8f31 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/PolyNullLibraryModelsTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/PolyNullLibraryModelsTests.java @@ -1438,6 +1438,66 @@ Object test(Object value) { .doTest(); } + @Test + public void anArgumentWhoseTypeVariableHasANullableBoundMakesThePolyNullLocationsNullable() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import com.uber.lib.unannotated.PolyNullMethods; + import java.util.Map; + import java.util.Optional; + import java.util.function.Function; + import java.util.function.Supplier; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.NullUnmarked; + import org.jspecify.annotations.Nullable; + + @NullMarked + class Test { + void lambdaArgument(T t) { + // BUG: Diagnostic contains: dereferenced expression 'PolyNullMethods.genericObject(t, () -> "x")' is @Nullable + PolyNullMethods.genericObject(t, () -> "x").toString(); + T first = PolyNullMethods.genericFirst(t, () -> "x"); + } + static void accept(X x) {} + void typeVariableResultPassedToAGenericMethod(T t) { + accept(PolyNullMethods.genericFirst(t, () -> "x")); + } + void lambdaParameter(T t) { + // BUG: Diagnostic contains: dereferenced expression 'value' is @Nullable + PolyNullMethods.withMapper(t, value -> value.toString()); + } + void supplierOfTheTypeVariable(Optional optional, Supplier supplier) { + // BUG: Diagnostic contains: dereferenced expression 'optional.orElseGet(supplier)' is @Nullable + optional.orElseGet(supplier).hashCode(); + } + void functionReturningTheTypeVariable(Map map, Function f) { + // BUG: Diagnostic contains: dereferenced expression 'map.computeIfAbsent("key", f)' is @Nullable + map.computeIfAbsent("key", f).hashCode(); + } + void nonNullSupplier(Optional optional, Supplier supplier) { + optional.orElseGet(supplier).hashCode(); + } + void typeVariableWhoseBoundExcludesNull( + Optional optional, S fallback) { + // BUG: Diagnostic contains: dereferenced expression 'optional.orElseGet(() -> fallback)' is @Nullable + optional.orElseGet(() -> fallback).hashCode(); + } + @NullUnmarked + static class Unmarked { + @NullMarked + void explicitlyNullableTypeArgument(X x) { + if (x != null) { + PolyNullMethods.<@Nullable X, String>genericFirst(x, () -> "x").hashCode(); + } + } + } + } + """) + .doTest(); + } + private CompilationTestHelper makeHelper() { return makeTestHelperWithArgs( JSpecifyJavacConfig.withJSpecifyModeArgs(List.of("-XepOpt:NullAway:OnlyNullMarked=true"))); diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java index 765a1fc288..b0a1f8dc20 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -2368,6 +2368,12 @@ class Test { static List ofThroughAVariable(E a, E b) { throw new UnsupportedOperationException(); } + static List ofThroughANonNullVariable(E a, E b) { + throw new UnsupportedOperationException(); + } + static U pick(U a, U b) { + return a; + } static List nonNullOf(E a, E b) { throw new UnsupportedOperationException(); } @@ -2384,6 +2390,19 @@ static List unannotatedOf(E a, E b) { // BUG: Diagnostic contains: dereferenced expression 'ofThroughAVariable(t, "x").get(0)' is @Nullable ofThroughAVariable(t, "x").get(0).toString(); } + static void inferredTypeVariableWhoseBoundExcludesNull( + T t, R r) { + // BUG: Diagnostic contains: dereferenced expression 'pick(t, r)' is @Nullable + pick(t, r).toString(); + } + static void inferredTypeVariableWhoseBoundAdmitsNull( + T t, R r) { + // a false negative: R is kept as written, and dataflow reads it as non-null (#1727) + pick(t, r).toString(); + } + static void boundNonNullThroughAVariable(T t) { + ofThroughANonNullVariable(t, "x").get(0).toString(); + } static void ownBoundExcludesNull(T t) { nonNullOf(t, "x").get(0).toString(); } @@ -2403,6 +2422,16 @@ void unannotatedTypeVariable(T t) { // BUG: Diagnostic contains: incompatible types List sink = inferred; } + @NullMarked + void nullableBoundInsideUnannotatedOutside(N n, T t) { + // BUG: Diagnostic contains: dereferenced expression 'pick(pick(n, "x"), t)' is @Nullable + pick(pick(n, "x"), t).toString(); + } + @NullMarked + void unannotatedInsideNullableBoundOutside(N n, T t) { + // BUG: Diagnostic contains: dereferenced expression 'pick(pick(t, "x"), n)' is @Nullable + pick(pick(t, "x"), n).toString(); + } } } """) @@ -2421,6 +2450,7 @@ public void aGenericMethodReferenceAndAGenericConstructorTakeTheInferredClassTyp "Test.java", """ import java.util.List; + import java.util.function.Consumer; import java.util.function.Function; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @@ -2429,6 +2459,12 @@ class Test { static class Box { Box(Box input, U hint) {} } + static class Taker { + Taker(U a, U b, Consumer c) {} + } + class InnerTaker { + InnerTaker(U a, U b) {} + } static class Holder { Holder(E a, E b, Function> function) {} } @@ -2436,9 +2472,35 @@ static class Holder { static List singleton(V value) { throw new UnsupportedOperationException(); } + static List nonNullSingleton(V value) { + throw new UnsupportedOperationException(); + } void methodReference(T t) { use(t, new Object(), Test::singleton); } + static class GenericConstructor { + GenericConstructor(W w) {} + } + static R map(U a, U b, Function function) { + throw new UnsupportedOperationException(); + } + void constructorReference(T t) { + // BUG: Diagnostic contains: parameter w of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable Object) is @Nullable + map(t, new Object(), GenericConstructor::new); + } + void methodReferenceToANonNullVariable(T t) { + // BUG: Diagnostic contains: parameter value of referenced method is @NonNull + use(t, new Object(), Test::nonNullSingleton); + } + void lambdaPassedToAConstructor(T t) { + new Taker<>(t, "x", u -> { + // BUG: Diagnostic contains: dereferenced expression 'u' is @Nullable + u.toString(); + }); + } + void anonymousSubclassOfAnInnerClass(T t) { + this.new InnerTaker<>(t, "x") {}; + } void methodReferenceIntoADiamond(T t) { var holder = new Holder<>(t, new Object(), Test::singleton); } @@ -2487,7 +2549,8 @@ void nestedCallsOfOneMethod(T t) { /** * Dataflow reads a {@code T} whose bound admits null as non-null whether or not the code checked * it (#1727), so inference cannot tell a checked {@code t} from an unchecked one, and a - * class-type result is {@code @Nullable} after a null check too. This is a false positive. + * class-type result is {@code @Nullable} after a null check or {@code requireNonNull} too. These + * are false positives; an explicit type argument skips inference and avoids them. */ @Test public void aNullCheckOfATypeVariableDoesNotReachInference() { @@ -2495,6 +2558,7 @@ public void aNullCheckOfATypeVariableDoesNotReachInference() { .addSourceLines( "Test.java", """ + import java.util.Objects; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked @@ -2502,12 +2566,22 @@ class Test { static U pick(U a, U b) { return a; } - void f(T t) { + void nullCheck(T t) { if (t != null) { // BUG: Diagnostic contains: dereferenced expression 'pick(t, "x")' is @Nullable pick(t, "x").toString(); } } + void requireNonNull(T t) { + T checked = Objects.requireNonNull(t); + // BUG: Diagnostic contains: dereferenced expression 'pick(checked, "x")' is @Nullable + pick(checked, "x").toString(); + } + void explicitTypeArgument(T t) { + if (t != null) { + Test.pick(t, "x").toString(); + } + } } """) .doTest(); @@ -2584,6 +2658,7 @@ public void inferenceCannotFitATypeVariableWhoseBoundAdmitsNullIntoANonNullVaria """ import java.util.List; import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.NullUnmarked; import org.jspecify.annotations.Nullable; @NullMarked class Test { @@ -2594,18 +2669,59 @@ static U nonNullVariable(Box b) { static U nullableVariable(Box b) { throw new UnsupportedOperationException(); } + static U intoAWildcardOfAFixedType( + Box b, U u) { + return u; + } + static V pair(Box b, V v) { + throw new UnsupportedOperationException(); + } static void intoNonNullVariable(Box b) { - // BUG: Diagnostic contains: inference failure: type variable U is constrained to be @Nullable + // BUG: Diagnostic contains: inference failure: type variable U is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument T passed for ? extends U admits null, since T has a @Nullable upper bound + Object o = nonNullVariable(b); + } + static void intoNonNullVariableThroughAWildcard( + Box b) { + // BUG: Diagnostic contains: the type argument ? extends T passed for ? extends U admits null, since T has a @Nullable upper bound Object o = nonNullVariable(b); } static void intoNullableVariable(Box b) { - Object o = nullableVariable(b); + nullableVariable(b).toString(); + } + static void intoAWildcardThatIsNotAnInferenceVariable( + Box b) { + Object o = intoAWildcardOfAFixedType(b, "x"); } static void nonNullBoundIntoNonNullVariable(Box b) { Object o = nonNullVariable(b); } - static void intoJdkCopyOf(List in) { + static void failureDiscardsTheOtherVariablesOfTheCall( + Box b) { + // BUG: Diagnostic contains: inference failure: type variable U is constrained to be @Nullable + pair(b, + // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required + null) + .hashCode(); + } + @NullUnmarked + static class Legacy { + static List identity(List xs) { + return xs; + } + } + static void intoJdkCopyOfThroughAnUnmarkedCall( + List in) { + var inferred = Legacy.identity(in); // BUG: Diagnostic contains: inference failure: type variable E is constrained to be @Nullable + List copy = List.copyOf(inferred); + } + static void intoJdkCopyOfNestingAnUnmarkedCall( + List in) { + // a false negative: the unmarked call's result reaches copyOf without a local + List copy = List.copyOf(Legacy.identity(in)); + } + static void intoJdkCopyOf(List in) { + // BUG: Diagnostic contains: inference failure: type variable E is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument T passed for ? extends E admits null, since T has a @Nullable upper bound List copy = List.copyOf(in); } } From 8b21c561349e56cab5154495435b1ad4bb8436b2 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Tue, 24 Nov 2026 21:12:47 +0300 Subject: [PATCH 03/27] Link the known gaps in the new tests to their issues Assisted-by: Claude Code (claude-opus-5-5) --- .../test/java/com/uber/nullaway/jspecify/WildcardTests.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java index b0a1f8dc20..15c7a7f3ca 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -2485,6 +2485,8 @@ GenericConstructor(W w) {} throw new UnsupportedOperationException(); } void constructorReference(T t) { + // W takes no inference constraint from a constructor reference, so it stays non-null + // (#1468) // BUG: Diagnostic contains: parameter w of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable Object) is @Nullable map(t, new Object(), GenericConstructor::new); } @@ -2717,7 +2719,7 @@ static List identity(List xs) { } static void intoJdkCopyOfNestingAnUnmarkedCall( List in) { - // a false negative: the unmarked call's result reaches copyOf without a local + // a false negative: the unmarked call's result reaches copyOf without a local (#1947) List copy = List.copyOf(Legacy.identity(in)); } static void intoJdkCopyOf(List in) { From 1e640527553b215abe892517107b454f927fa112 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Tue, 24 Nov 2026 23:01:19 +0300 Subject: [PATCH 04/27] Report a captured nullable-bound argument and name the declaring element A `Box` returned by a call reached `? extends U` unreported, while the same type held in a parameter was reported: the check skipped any captured type argument, although javac captures every such call result. With `T extends @Nullable Object`, `List.copyOf(wildList())` with a `List wildList()` passed. The check now reads a capture through the wildcard it captures, and the message prints that wildcard rather than `capture#514 of ? extends T`. The message named both type variables by their simple names, so `List.copyOf(in)` with a `List` read `the type argument E passed for ? extends E admits null, since E has a @Nullable upper bound`. Each type variable is now named with the method or class that declares it. The choice between keeping the type javac inferred and adding `@Nullable` or `@NonNull` to it was written twice, once for a PolyNull model location and once for a method's own type variable. `GenericsUtils.inferredNullnessAnnotation` now makes it for both, and `NestedTypePathUpdater.addAnnotation` takes the annotation per leaf from it. User-visible: - `inference failure: type variable U of Test.nonNullVariable is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument ? extends T passed for ? extends U admits null, since T of Test.f has a @Nullable upper bound` where a call returns `Box` and the result is passed as `Box`; accepted before. - The type variables in this message carry `of .`, `of `, or `of the constructor of `. Not changed: - `List.copyOf(markedIdentity(in))` and `List.copyOf(new ArrayList<>(in))` with a `List` are not reported (#1947). Assisted-by: Claude Code (claude-opus-5-5) --- .../nullaway/generics/ConstraintSolver.java | 25 ++---- .../generics/ConstraintSolverImpl.java | 22 ++--- .../nullaway/generics/GenericsChecks.java | 34 ++++++-- .../uber/nullaway/generics/GenericsUtils.java | 43 ++++++++-- .../nullaway/generics/PolyNullInference.java | 30 +++---- .../generics/TypeSubstitutionUtils.java | 21 ++--- .../librarymodel/NestedTypePathUpdater.java | 80 +++++++++++-------- .../uber/nullaway/jspecify/WildcardTests.java | 53 ++++++++++-- 8 files changed, 197 insertions(+), 111 deletions(-) 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 9a58173ef0..833c70e947 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java @@ -66,7 +66,7 @@ class UnsatisfiableConstraintsException extends RuntimeException { /** * The type argument, as passed for a {@code ? extends} wildcard, whose {@code @Nullable} * constraint conflicts with the bound of {@link #typeVariable}, or {@code null} where another - * constraint caused the conflict. + * constraint caused the conflict. A captured argument is replaced by the wildcard it captures. */ private final @Nullable Type nullableBoundTypeArgument; @@ -154,10 +154,10 @@ enum InferredNullability { /** * 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. Where javac - * inferred a unannotated type variable whose bound admits null, the variable is that type - * variable as written; 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 + * inferred an unannotated type variable whose bound admits null, the variable is that type + * variable 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}. */ @@ -167,20 +167,11 @@ enum InferredNullability { * 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 an unannotated type variable whose bound admits - * null, the variable is that type variable as written; 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. + * null, the variable is that type variable 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; - - /** - * Returns whether the variable is {@code @Nullable} where javac inferred a type that {@link - * GenericsUtils#keepsInferredTypeAsWritten} does not keep as written, such as a class type, or - * where such a type stands at a location of a PolyNull model. - */ - boolean isNullableWhereNotKeptAsWritten() { - return this == NULLABLE || this == TYPE_VARIABLE_OR_NULLABLE; - } } /** 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 aff3911885..7e853ac21b 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java @@ -78,7 +78,7 @@ private static final class VarState { * Whether a type variable that is not under inference, carries no nullness annotation, and is * bounded by a type that admits null flowed into this variable. Such a flow fixes no nullness, * but where javac inferred a type variable whose bound admits null, the variable takes that - * type variable as written rather than the non-null default. + * type variable with no synthetic annotation rather than the non-null default. */ boolean parametric; @@ -291,11 +291,12 @@ 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 ? extends U}, where {@code U} is an inference - * variable whose bound excludes null, an uncaptured actual that is an unannotated type variable - * with an explicitly nullable bound also constrains {@code U} to be {@code @Nullable}, which no - * solution satisfies. 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. + * variable whose bound excludes null, an actual that is an unannotated type variable {@code T} + * with an explicitly nullable bound, {@code ? extends T}, or a capture of {@code ? extends T} + * also constrains {@code U} to be {@code @Nullable}, which no solution satisfies. 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 @@ -319,7 +320,6 @@ private void constrainContainedByWildcard(Type subtypeTypeArg, WildcardType supe GenericsUtils.wildcardUpperBound(supertypeWildcard, state, config, handler); InferenceVariable supertypeVar = inferenceVariableForUse(supertypeUpperBound); if (supertypeWildcard.kind == BoundKind.EXTENDS - && !(subtypeTypeArg instanceof CapturedType) && admitsNullThroughExplicitBound(subtypeUpperBound) && supertypeVar != null && !getState(supertypeVar).nullableAllowed) { @@ -330,7 +330,11 @@ && admitsNullThroughExplicitBound(subtypeUpperBound) // @Nullable T, and List c = copy(in), with List // copy(List in), would be reported. throw new UnsatisfiableConstraintsException( - supertypeVar.typeVariable(), subtypeTypeArg, subtypeUpperBound); + supertypeVar.typeVariable(), + subtypeTypeArg instanceof CapturedType captured + ? captured.wildcard + : subtypeTypeArg, + subtypeUpperBound); } subtypeUpperBound.accept(this, supertypeUpperBound); } @@ -424,7 +428,7 @@ public Map solve() } } - /* a type variable that flowed into a variable flows into every variable above it */ + /* a type variable that flowed into a variable flows into each of its supertype variables */ vars.forEach( (inferenceVar, st) -> { if (st.parametric) { 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 cc8bdd10da..85a5c82c41 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -1606,7 +1606,10 @@ private String inferenceFailureMessage( if (nullableBoundTypeArgument != null) { 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 has a @Nullable upper bound", - typeVariable, nullableBoundTypeArgument, typeVariable, e.getNullableBoundTypeVariable()); + withDeclaringElement(typeVariable), + nullableBoundTypeArgument, + typeVariable, + withDeclaringElement(castToNonNull(e.getNullableBoundTypeVariable()).tsym)); } if (e.isCausedByNonNullUpperBound()) { return String.format( @@ -1618,6 +1621,21 @@ 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 two type variables with one name can be told apart. + */ + private static String withDeclaringElement(Element typeVariable) { + Symbol owner = ((Symbol) typeVariable).owner; + String ownerName = + owner instanceof Symbol.MethodSymbol method + ? method.isConstructor() + ? "the constructor of " + method.owner.getSimpleName() + : method.owner.getSimpleName() + "." + method.getSimpleName() + : owner.getSimpleName().toString(); + return typeVariable.getSimpleName() + " of " + ownerName; + } + /** Returns the type parameters whose nullability is inferred for {@code callTree}. */ private List getCallTypeParameters(ExpressionTree callTree) { if (callTree instanceof MethodInvocationTree invocationTree) { @@ -3114,16 +3132,18 @@ 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. + * 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. * * @param memberReferenceTree the generic method reference - * @param methodType the original method type + * @param methodType the declared type of the referenced method * @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; {@code methodType} unchanged where the enclosing call needs + * no inference or its inference failed */ private Type.MethodType getInferredMethodTypeForGenericMethodReference( MemberReferenceTree memberReferenceTree, Type.MethodType methodType, VisitorState 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 dee8fc91b4..b21bd2fb2b 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java @@ -382,14 +382,43 @@ static boolean hasNullnessAnnotation(Type type, Config config) { } /** - * Returns whether {@code type}, which javac inferred for a variable that inference resolved to - * {@code TYPE_VARIABLE_OR_NULLABLE} or {@code TYPE_VARIABLE_OR_NONNULL}, stays as written rather - * than taking the annotation those results give. It stays where it already holds the null of a - * type variable that flowed into the variable: an unannotated type variable whose bound admits - * null, or an intersection type, whose nullness comes from its elements. A captured type variable - * or a type variable with a nullness annotation takes the annotation. + * 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 a type that already holds the null of + * a type variable that flowed into the variable: an unannotated, uncaptured type variable whose + * bound admits null, or an intersection type, whose nullness comes from its elements. Any other + * type, including a wildcard, a captured type variable, 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 -> + holdsTheNullOfAFlowedTypeVariable(inferredType, config, handler, state) + ? null + : GenericsChecks.getSyntheticNullableAnnotType(state); + case TYPE_VARIABLE_OR_NONNULL -> + holdsTheNullOfAFlowedTypeVariable(inferredType, config, handler, state) + ? null + : GenericsChecks.getSyntheticNonNullAnnotType(state); + }; + } + + /** + * Returns whether {@code type} is an intersection type or an unannotated, uncaptured type + * variable whose bound admits null. */ - static boolean keepsInferredTypeAsWritten( + private static boolean holdsTheNullOfAFlowedTypeVariable( Type type, Config config, Handler handler, VisitorState state) { if (type.isCompound()) { return true; 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 d8c6aff0d1..1edd06a3f1 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/PolyNullInference.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/PolyNullInference.java @@ -60,12 +60,10 @@ private PolyNullInference() {} /** * Applies the resolved shared PolyNull variable to every modeled parameter and return location. * - *

Where {@code inferred} is {@code TYPE_VARIABLE_OR_NULLABLE} or {@code - * TYPE_VARIABLE_OR_NONNULL}, a location whose type {@link - * GenericsUtils#keepsInferredTypeAsWritten} accepts keeps that type as written, as {@link - * TypeSubstitutionUtils} keeps the type javac inferred for a method's own type variable. A type - * variable with a nullness annotation, such as an explicit type argument, takes the PolyNull - * annotation. + *

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 the PolyNull annotation. */ @SuppressWarnings({"ReferenceEquality", "TypeEquals"}) // deliberate reference equality checks static Type.MethodType applyToMethodType( @@ -282,24 +280,16 @@ private static Type applyToType( VisitorState state, Config config, Handler handler) { - Type annotationType = - inferred.isNullableWhereNotKeptAsWritten() - ? GenericsChecks.getSyntheticNullableAnnotType(state) - : GenericsChecks.getSyntheticNonNullAnnotType(state); - boolean keepTypeVariables = - inferred == ConstraintSolver.InferredNullability.TYPE_VARIABLE_OR_NULLABLE - || inferred == ConstraintSolver.InferredNullability.TYPE_VARIABLE_OR_NONNULL; Type updated = type; for (PolyNullLocation location : locations) { if (location.position().equals(position)) { updated = - keepTypeVariables - ? NestedTypePathUpdater.addAnnotationUnless( - updated, - location.typePath(), - annotationType, - leaf -> GenericsUtils.keepsInferredTypeAsWritten(leaf, config, handler, state)) - : NestedTypePathUpdater.addAnnotation(updated, location.typePath(), annotationType); + 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/TypeSubstitutionUtils.java b/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java index 4c46e27671..71af4a7f4e 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java @@ -237,9 +237,9 @@ public static Type.WildcardType replaceImplicitWildcardUpperBound( * 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: a type that {@link GenericsUtils#keepsInferredTypeAsWritten} accepts, such as a type - * variable whose bound admits null, stays as written, and any other type becomes - * {@code @Nullable} or {@code @NonNull}, as the result says. + * it with {@link GenericsUtils#inferredNullnessAnnotation}: a type variable whose bound admits + * null takes no synthetic annotation, and any other type becomes {@code @Nullable} or + * {@code @NonNull}, as the result says. * * @param typeToUpdate the type to update * @param origType the original type with type variables and possibly explicit nullability @@ -937,8 +937,8 @@ public Type visitForAll(Type.ForAll t, Type other) { * 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. Where {@code other} * is an unannotated type variable that inference resolved to {@code TYPE_VARIABLE_OR_NULLABLE} - * or {@code TYPE_VARIABLE_OR_NONNULL}, annotates {@code t} as that result says, unless {@link - * GenericsUtils#keepsInferredTypeAsWritten} keeps {@code t} as written. + * 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 @@ -976,14 +976,9 @@ private Type updateDirectNullabilityAnnotationsForType(Type t, Type other) { && inferred != ConstraintSolver.InferredNullability.TYPE_VARIABLE_OR_NONNULL) { return t; } - if (GenericsUtils.keepsInferredTypeAsWritten(t, config, handler, state)) { - return t; - } - return TypeSubstitutionUtils.typeWithAnnot( - t, - inferred.isNullableWhereNotKeptAsWritten() - ? GenericsChecks.getSyntheticNullableAnnotType(state) - : GenericsChecks.getSyntheticNonNullAnnotType(state)); + Type annotationType = + GenericsUtils.inferredNullnessAnnotation(t, inferred, config, handler, 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 60ed5b907c..9cf1b0866b 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,7 +11,7 @@ import com.sun.tools.javac.util.ListBuffer; import com.uber.nullaway.generics.TypeSubstitutionUtils; import com.uber.nullaway.libmodel.NestedAnnotationInfo; -import java.util.function.Predicate; +import java.util.function.Function; import org.jspecify.annotations.Nullable; /** Updates a type at a nested location identified by a library-model type path. */ @@ -23,21 +24,26 @@ private enum UpdateKind { } private final ImmutableList typePath; - private final Type annotationOrReplacementType; private final UpdateKind updateKind; - /** The types that an added annotation leaves as written, or {@code null} for none. */ - private final @Nullable Predicate keepAsWritten; + /** 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, - @Nullable Predicate keepAsWritten) { + @Nullable Type replacementType, + @Nullable Function annotationFor) { this.typePath = typePath; - this.annotationOrReplacementType = annotationOrReplacementType; this.updateKind = updateKind; - this.keepAsWritten = keepAsWritten; + this.replacementType = replacementType; + this.annotationFor = annotationFor; } /** @@ -47,25 +53,23 @@ private NestedTypePathUpdater( */ public static Type addAnnotation( Type type, ImmutableList typePath, Type annotationType) { - return new NestedTypePathUpdater(typePath, annotationType, UpdateKind.ADD_ANNOTATION, null) - .apply(type); + return addAnnotation(type, typePath, leaf -> annotationType); } /** - * Adds {@code annotationType} to {@code type} at {@code typePath}, as {@link #addAnnotation} - * does, except that a type at {@code typePath} that {@code keepAsWritten} accepts is left as - * written. A wildcard or a captured type variable at {@code typePath} is annotated as {@link - * #addAnnotation} annotates it, without the test. + * 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, which must return an + * annotation type for it, and the annotation lands on its bound. * * @return the updated type, or the original {@code type} instance if no change was made */ - public static Type addAnnotationUnless( + public static Type addAnnotation( Type type, ImmutableList typePath, - Type annotationType, - Predicate keepAsWritten) { - return new NestedTypePathUpdater( - typePath, annotationType, UpdateKind.ADD_ANNOTATION, keepAsWritten) + Function annotationFor) { + return new NestedTypePathUpdater(typePath, UpdateKind.ADD_ANNOTATION, null, annotationFor) .apply(type); } @@ -76,7 +80,7 @@ public static Type addAnnotationUnless( */ public static Type replaceType( Type type, ImmutableList typePath, Type replacement) { - return new NestedTypePathUpdater(typePath, replacement, UpdateKind.REPLACE_TYPE, null) + return new NestedTypePathUpdater(typePath, UpdateKind.REPLACE_TYPE, replacement, null) .apply(type); } @@ -85,14 +89,26 @@ private Type apply(Type type) { } private Type updateLeaf(Type type) { - return updateKind == UpdateKind.ADD_ANNOTATION ? annotate(type) : annotationOrReplacementType; + if (updateKind == UpdateKind.REPLACE_TYPE) { + return castToNonNull(replacementType); + } + Type annotationType = annotationTypeFor(type); + return annotationType == null + ? type + : TypeSubstitutionUtils.typeWithAnnot(type, annotationType); } - /** Adds the annotation to {@code type}, unless {@link #keepAsWritten} accepts it. */ - private Type annotate(Type type) { - return keepAsWritten != null && keepAsWritten.test(type) - ? type - : TypeSubstitutionUtils.typeWithAnnot(type, annotationOrReplacementType); + /** 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); + } + + /** Returns the annotation type to add to the bound of a wildcard or a capture at the path. */ + private Type annotationTypeForWildcardOrCapture(Type wildcardOrCapture) { + return Verify.verifyNotNull( + annotationTypeFor(wildcardOrCapture), + "no annotation type for the wildcard or capture %s", + wildcardOrCapture); } @Override @@ -148,15 +164,15 @@ public Type visitWildcardType(Type.WildcardType t, Integer pathIndex) { if (updateKind == UpdateKind.REPLACE_TYPE) { return updateLeaf(t); } + Type annotationType = annotationTypeForWildcardOrCapture(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); } @@ -215,11 +231,11 @@ 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 = annotationTypeForWildcardOrCapture(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/jspecify/WildcardTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java index 15c7a7f3ca..9976b98c3c 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -2397,7 +2397,7 @@ static List unannotatedOf(E a, E b) { } static void inferredTypeVariableWhoseBoundAdmitsNull( T t, R r) { - // a false negative: R is kept as written, and dataflow reads it as non-null (#1727) + // a false negative: R takes no synthetic annotation, and dataflow reads it as non-null (#1727) pick(t, r).toString(); } static void boundNonNullThroughAVariable(T t) { @@ -2658,6 +2658,7 @@ public void inferenceCannotFitATypeVariableWhoseBoundAdmitsNullIntoANonNullVaria .addSourceLines( "Test.java", """ + import java.util.ArrayList; import java.util.List; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.NullUnmarked; @@ -2679,14 +2680,31 @@ static U nonNullVariable(Box b) { throw new UnsupportedOperationException(); } static void intoNonNullVariable(Box b) { - // BUG: Diagnostic contains: inference failure: type variable U is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument T passed for ? extends U admits null, since T has a @Nullable upper bound + // BUG: Diagnostic contains: inference failure: type variable U of Test.nonNullVariable is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument T passed for ? extends U admits null, since T of Test.intoNonNullVariable has a @Nullable upper bound Object o = nonNullVariable(b); } static void intoNonNullVariableThroughAWildcard( Box b) { - // BUG: Diagnostic contains: the type argument ? extends T passed for ? extends U admits null, since T has a @Nullable upper bound + // BUG: Diagnostic contains: the type argument ? extends T passed for ? extends U admits null, since T of Test.intoNonNullVariableThroughAWildcard has a @Nullable upper bound Object o = nonNullVariable(b); } + static class Holder { + Box wildBox() { + throw new UnsupportedOperationException(); + } + List wildList() { + throw new UnsupportedOperationException(); + } + } + static void intoNonNullVariableThroughACapture( + Holder h) { + // BUG: Diagnostic contains: the type argument ? extends T passed for ? extends U admits null, since T of Test.intoNonNullVariableThroughACapture has a @Nullable upper bound + Object o = nonNullVariable(h.wildBox()); + } + static void intoJdkCopyOfThroughACapture(Holder h) { + // BUG: Diagnostic contains: type variable E of List.copyOf is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument ? extends T passed for ? extends E admits null, since T of Test.intoJdkCopyOfThroughACapture has a @Nullable upper bound + List copy = List.copyOf(h.wildList()); + } static void intoNullableVariable(Box b) { nullableVariable(b).toString(); } @@ -2699,7 +2717,7 @@ static void nonNullBoundIntoNonNullVariable(Box b) { } static void failureDiscardsTheOtherVariablesOfTheCall( Box b) { - // BUG: Diagnostic contains: inference failure: type variable U is constrained to be @Nullable + // BUG: Diagnostic contains: inference failure: type variable U of Test.pair is constrained to be @Nullable pair(b, // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required null) @@ -2714,7 +2732,7 @@ static List identity(List xs) { static void intoJdkCopyOfThroughAnUnmarkedCall( List in) { var inferred = Legacy.identity(in); - // BUG: Diagnostic contains: inference failure: type variable E is constrained to be @Nullable + // BUG: Diagnostic contains: inference failure: type variable E of List.copyOf is constrained to be @Nullable List copy = List.copyOf(inferred); } static void intoJdkCopyOfNestingAnUnmarkedCall( @@ -2722,10 +2740,33 @@ static List identity(List xs) { // a false negative: the unmarked call's result reaches copyOf without a local (#1947) List copy = List.copyOf(Legacy.identity(in)); } + static List markedIdentity(List xs) { + return xs; + } + static void intoJdkCopyOfNestingAMarkedCall( + List in) { + // a false negative: the marked call's result reaches copyOf without a local (#1947) + List copy = List.copyOf(markedIdentity(in)); + } + static void intoJdkCopyOfThroughADiamond(List in) { + // a false negative: the diamond's result reaches copyOf without a local (#1947) + List copy = List.copyOf(new ArrayList<>(in)); + } static void intoJdkCopyOf(List in) { - // BUG: Diagnostic contains: inference failure: type variable E is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument T passed for ? extends E admits null, since T has a @Nullable upper bound + // BUG: Diagnostic contains: inference failure: type variable E of List.copyOf is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument T passed for ? extends E admits null, since T of Test.intoJdkCopyOf has a @Nullable upper bound List copy = List.copyOf(in); } + static void sameNameAsTheVariableOfCopyOf(List in) { + // BUG: Diagnostic contains: type variable E of List.copyOf is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument E passed for ? extends E admits null, since E of Test.sameNameAsTheVariableOfCopyOf has a @Nullable upper bound + List copy = List.copyOf(in); + } + static class GenericConstructor { + GenericConstructor(Box b) {} + } + static void intoAGenericConstructor(Box b) { + // BUG: Diagnostic contains: type variable W of the constructor of GenericConstructor is constrained to be @Nullable + GenericConstructor c = new GenericConstructor<>(b); + } } """) .doTest(); From cdb98d40309c0b4fd347c604e624c2dcf34a21de Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Tue, 24 Nov 2026 23:36:32 +0300 Subject: [PATCH 05/27] Report a wildcard argument only where its type parameter admits null The capture check reported a wildcard or captured argument of `? extends U` whenever its bound was a `T` whose bound admits null, even where the type parameter the wildcard stands for excludes null: `NonNullBox` with `class NonNullBox`, or the `B` of `Pair` with `class Pair`, holds no null. The check now takes the type parameter from the class of the containing parameterization, substituting a class-type argument passed for a sibling type parameter that its bound names, instead of the mutable `WildcardType.bound`. The walk runs only once the target is an inference variable whose bound excludes null. The message names a class by its flat name where an anonymous class has no simple name, and names both classes by their flat names where the two type variables would otherwise read alike, as for a nested `Set` calling `java.util.Set.copyOf`. Assisted-by: Claude Code (claude-opus-5-5) --- .../nullaway/generics/ConstraintSolver.java | 9 +-- .../generics/ConstraintSolverImpl.java | 67 +++++++++++++++---- .../nullaway/generics/GenericsChecks.java | 39 ++++++++--- .../generics/TypeSubstitutionUtils.java | 5 +- .../uber/nullaway/jspecify/WildcardTests.java | 64 ++++++++++++++++++ 5 files changed, 154 insertions(+), 30 deletions(-) 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 833c70e947..74b40a6c3b 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java @@ -72,8 +72,9 @@ class UnsatisfiableConstraintsException extends RuntimeException { /** * The type variable with an explicitly nullable bound through which {@link - * #nullableBoundTypeArgument} admits null: that argument itself, or the bound of a wildcard - * argument; {@code null} where {@link #nullableBoundTypeArgument} is. + * #nullableBoundTypeArgument} admits null: that argument itself, or the effective upper bound + * of a wildcard or captured argument whose type parameter admits null; {@code null} where + * {@link #nullableBoundTypeArgument} is. */ private final @Nullable Type nullableBoundTypeVariable; @@ -89,8 +90,8 @@ public UnsatisfiableConstraintsException( /** * Creates an exception for a {@code typeVariable} whose bound excludes null, passed {@code * nullableBoundTypeArgument} for a {@code ? extends typeVariable} wildcard, where {@code - * nullableBoundTypeVariable} has an explicitly nullable bound and is that argument or the bound - * of that argument. + * nullableBoundTypeVariable} has an explicitly nullable bound and is that argument or the + * effective upper bound of a wildcard or captured argument whose type parameter admits null. */ public UnsatisfiableConstraintsException( Element typeVariable, Type nullableBoundTypeArgument, Type nullableBoundTypeVariable) { 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 7e853ac21b..1e4fc46b9d 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java @@ -240,7 +240,7 @@ private void constrainTypeArguments(Type subtype, Type supertype) { for (int i = 0; i < numTypeArgs; i++) { Type supertypeTypeArg = supertypeTypeArguments.get(i); Type subtypeTypeArg = subtypeTypeArguments.get(i); - constrainTypeArgumentContainment(subtypeTypeArg, supertypeTypeArg); + constrainTypeArgumentContainment(subtypeTypeArg, supertypeTypeArg, subtype, i); } Type subtypeEnclosing = subtype.getEnclosingType(); Type supertypeEnclosing = supertype.getEnclosingType(); @@ -258,9 +258,11 @@ private void constrainTypeArguments(Type subtype, Type supertype) { * Adds nullability constraints for containment of one type argument by another during generic * class/interface subtyping. For non-wildcard arguments, NullAway requires identical * nullability. When either side is a wildcard, containment is reduced to constraints between - * the wildcard bound and the opposing argument. + * the wildcard bound and the opposing argument. {@code subtypeTypeArg} is the argument at + * {@code index} of {@code subtype}. */ - private void constrainTypeArgumentContainment(Type subtypeTypeArg, Type supertypeTypeArg) { + private void constrainTypeArgumentContainment( + Type subtypeTypeArg, Type supertypeTypeArg, Type subtype, int index) { if (!config.handleWildcardGenerics()) { equateTypeArguments(subtypeTypeArg, supertypeTypeArg); return; @@ -268,7 +270,7 @@ private void constrainTypeArgumentContainment(Type subtypeTypeArg, Type supertyp // A captured formal is a type variable, not a wildcard containment target. Expanding // its backing wildcard can repeatedly unfold self-referential bounds (see issue #1934). if (supertypeTypeArg instanceof WildcardType supertypeWildcard) { - constrainContainedByWildcard(subtypeTypeArg, supertypeWildcard); + constrainContainedByWildcard(subtypeTypeArg, supertypeWildcard, subtype, index); return; } WildcardType subtypeWildcard = GenericsUtils.asWildcard(subtypeTypeArg); @@ -291,18 +293,25 @@ 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 ? extends U}, where {@code U} is an inference - * variable whose bound excludes null, an actual that is an unannotated type variable {@code T} - * with an explicitly nullable bound, {@code ? extends T}, or a capture of {@code ? extends T} - * also constrains {@code U} to be {@code @Nullable}, which no solution satisfies. 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. + * variable whose bound excludes null, an actual whose effective upper bound is an unannotated + * type variable {@code T} with an explicitly nullable bound, such as {@code T}, {@code ? + * extends T}, or a capture of a wildcard bounded by {@code T}, also constrains {@code U} to be + * {@code @Nullable}, which no solution satisfies, unless the actual is a wildcard or a capture + * whose type parameter excludes null. 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 * the outer visit of that pair is already adding them. + * + * @param subtypeTypeArg the actual argument, at {@code index} of {@code subtype} + * @param supertypeWildcard the formal wildcard argument + * @param subtype the parameterization that passes {@code subtypeTypeArg} + * @param index the position of {@code subtypeTypeArg} among the arguments of {@code subtype} */ - private void constrainContainedByWildcard(Type subtypeTypeArg, WildcardType supertypeWildcard) { + private void constrainContainedByWildcard( + Type subtypeTypeArg, WildcardType supertypeWildcard, Type subtype, int index) { Set activeSubtypeArguments = activeWildcardContainments.get(supertypeWildcard); if (activeSubtypeArguments == null) { activeSubtypeArguments = Collections.newSetFromMap(new IdentityHashMap<>()); @@ -320,9 +329,11 @@ private void constrainContainedByWildcard(Type subtypeTypeArg, WildcardType supe GenericsUtils.wildcardUpperBound(supertypeWildcard, state, config, handler); InferenceVariable supertypeVar = inferenceVariableForUse(supertypeUpperBound); if (supertypeWildcard.kind == BoundKind.EXTENDS - && admitsNullThroughExplicitBound(subtypeUpperBound) && supertypeVar != null - && !getState(supertypeVar).nullableAllowed) { + && !getState(supertypeVar).nullableAllowed + && admitsNullThroughExplicitBound(subtypeUpperBound) + && (GenericsUtils.asWildcard(subtypeTypeArg) == null + || typeParameterAdmitsNull(subtype, index))) { // 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 @@ -592,6 +603,36 @@ private boolean admitsNullThroughExplicitBound(Type t) { && GenericsUtils.boundIsExplicitlyNullable(tv.asElement(), config, handler, state); } + /** + * Returns whether the type parameter at {@code index} of the class of {@code container} admits + * null in that parameterization. A wildcard argument of {@code class Box} with a non-null + * {@code E} holds no null, whatever its own bound, and neither does the {@code B} of {@code + * Pair} for {@code class Pair}. A + * bound that is another type parameter of the same class, passed a class type, is replaced by + * that class type; any other bound admits null where it, or a bound it reaches through type + * variables, is explicitly nullable. javac rejects {@code ? extends U} for {@code B} where {@code + * A} is passed a type variable or a wildcard, and for a {@code B} bounded by a type parameter of + * an enclosing class, so no other substitution can change the result. + */ + private boolean typeParameterAdmitsNull(Type container, int index) { + List typeParameters = container.tsym.type.getTypeArguments(); + Type typeParameter = typeParameters.get(index); + if (GenericsUtils.declaredUpperBoundIsNullable(typeParameter.tsym, config, handler, state)) { + return true; + } + Type bound = typeParameter.getUpperBound(); + if (GenericsUtils.isAnnotatedAsNonNull(bound, config) || !(bound instanceof TypeVar)) { + return false; + } + for (int i = 0; i < typeParameters.size(); i++) { + Type argument = container.getTypeArguments().get(i); + if (typeParameters.get(i).tsym.equals(bound.tsym) && argument instanceof ClassType) { + return GenericsUtils.isAnnotatedAsNullable(argument, config); + } + } + return GenericsUtils.upperBoundIsNullable(bound.tsym, config, handler, state); + } + /** 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/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index 85a5c82c41..88c24d3269 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -1604,12 +1604,16 @@ private String inferenceFailureMessage( } Type nullableBoundTypeArgument = e.getNullableBoundTypeArgument(); if (nullableBoundTypeArgument != null) { + Element nullableBoundTypeVariable = castToNonNull(e.getNullableBoundTypeVariable()).tsym; + String constrained = withDeclaringElement(typeVariable, false); + String passed = withDeclaringElement(nullableBoundTypeVariable, false); + if (constrained.equals(passed)) { + constrained = withDeclaringElement(typeVariable, true); + passed = withDeclaringElement(nullableBoundTypeVariable, true); + } 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 has a @Nullable upper bound", - withDeclaringElement(typeVariable), - nullableBoundTypeArgument, - typeVariable, - withDeclaringElement(castToNonNull(e.getNullableBoundTypeVariable()).tsym)); + constrained, nullableBoundTypeArgument, typeVariable, passed); } if (e.isCausedByNonNullUpperBound()) { return String.format( @@ -1623,19 +1627,33 @@ private String inferenceFailureMessage( /** * Returns the name of {@code typeVariable} followed by the class or method that declares it, such - * as {@code E of List.copyOf}, so that two type variables with one name can be told apart. + * 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) { + 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 " + method.owner.getSimpleName() - : method.owner.getSimpleName() + "." + method.getSimpleName() - : owner.getSimpleName().toString(); + ? "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) { @@ -3137,7 +3155,8 @@ public void compareGenericTypeParameterNullabilityForCall( * diamond {@code new} whose inference succeeded. * * @param memberReferenceTree the generic method reference - * @param methodType the declared type of the referenced method + * @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 type javac inferred for the referenced method at the reference, with the inferred 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 71af4a7f4e..64812f1d24 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java @@ -237,9 +237,8 @@ public static Type.WildcardType replaceImplicitWildcardUpperBound( * 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 {@link GenericsUtils#inferredNullnessAnnotation}: a type variable whose bound admits - * null takes no synthetic annotation, and any other type becomes {@code @Nullable} or - * {@code @NonNull}, as the result says. + * 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 diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java index 9976b98c3c..2df1896499 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -2701,6 +2701,62 @@ List wildList() { // BUG: Diagnostic contains: the type argument ? extends T passed for ? extends U admits null, since T of Test.intoNonNullVariableThroughACapture has a @Nullable upper bound Object o = nonNullVariable(h.wildBox()); } + static class NonNullBox { + NonNullBox same() { + return this; + } + } + static class BoundedByANonNullVariable { + BoundedByANonNullVariable same() { + return this; + } + } + static class BoundedByANullableVariable { + Box box() { + throw new UnsupportedOperationException(); + } + } + static void intoNonNullBox(NonNullBox b) {} + static void intoChainedBox(BoundedByANonNullVariable b) {} + static void wildcardOfANonNullTypeParameter( + NonNullBox b) { + intoNonNullBox(b); + intoNonNullBox(b.same()); + } + static void wildcardOfATypeParameterBoundedByANonNullVariable( + BoundedByANonNullVariable b) { + intoChainedBox(b.same()); + } + static void captureOfATypeParameterBoundedByANullableVariable( + BoundedByANullableVariable h) { + // BUG: Diagnostic contains: the type argument ? passed for ? extends U admits null, since T of Test.captureOfATypeParameterBoundedByANullableVariable has a @Nullable upper bound + Object o = nonNullVariable(h.box()); + } + static class Pair { + Pair same() { + return this; + } + } + static void intoObjectPair(Pair p) {} + static void intoNullablePair(Pair<@Nullable Object, ? extends U> p) {} + static void siblingTypeParameterPassedANonNullType( + Pair p) { + intoObjectPair(p); + intoObjectPair(p.same()); + } + static void siblingTypeParameterPassedANullableType( + Pair<@Nullable Object, ? extends T> p) { + // BUG: Diagnostic contains: since T of Test.siblingTypeParameterPassedANullableType has a @Nullable upper bound + intoNullablePair(p); + // BUG: Diagnostic contains: since T of Test.siblingTypeParameterPassedANullableType has a @Nullable upper bound + intoNullablePair(p.same()); + } + static class Set { + void copyOf(java.util.Collection in) { + // BUG: Diagnostic contains: type variable E of java.util.Set.copyOf is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument E passed for ? extends E admits null, since E of Test$Set.copyOf has a @Nullable upper bound + java.util.Set copy = java.util.Set.copyOf(in); + } + } static void intoJdkCopyOfThroughACapture(Holder h) { // BUG: Diagnostic contains: type variable E of List.copyOf is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument ? extends T passed for ? extends E admits null, since T of Test.intoJdkCopyOfThroughACapture has a @Nullable upper bound List copy = List.copyOf(h.wildList()); @@ -2760,6 +2816,14 @@ static List identity(List xs) { // BUG: Diagnostic contains: type variable E of List.copyOf is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument E passed for ? extends E admits null, since E of Test.sameNameAsTheVariableOfCopyOf has a @Nullable upper bound List copy = List.copyOf(in); } + static void genericMethodOfAnAnonymousClass() { + new Object() { + void copy(List in) { + // BUG: Diagnostic contains: since E of Test$1.copy has a @Nullable upper bound + List copy = List.copyOf(in); + } + }; + } static class GenericConstructor { GenericConstructor(Box b) {} } From d90c0e913e99c091d93734fb26196db8dca43deb Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Wed, 25 Nov 2026 15:42:04 +0300 Subject: [PATCH 06/27] Check only a bare type variable passed for a non-null `? extends U` The check also judged a wildcard or captured actual, by the type parameter of the formal's class after `asSuper`, with a class-type sibling argument substituted. That type parameter is not the one the wildcard was written for, so calls that hold no null failed inference: `intoBase(s)` with a `Sub`, `class Sub extends Base` and ` void intoBase(Base b)`; `List.copyOf(nl)` with a `NonNullList`, `class NonNullList extends ArrayList`; and `intoSelfPair(p)` with a `Pair`, ``. The check now applies only where the actual is an unannotated, uncaptured type variable whose bound is explicitly nullable. Wildcard and captured actuals are left to the constraint-solver stack (#2101), which checks `? extends U` obligations when `U` is resolved. The exception carries only the type variable passed. User-visible: - No report for `intoBase(s)`, `List.copyOf(nl)`, or `intoSelfPair(p)` above; reported before as `inference failure: type variable U of Test.intoBase is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument ? extends T passed for ? extends U admits null, since T of Test.f has a @Nullable upper bound`. - No report for `nonNullVariable(b)` with a `Box`, for the same call on a `Box` that a call returns, or for `List.copyOf(h.wildList())` with a `List wildList()`, a false negative (#2189). Assisted-by: Claude Code (claude-opus-5-5) --- .../nullaway/generics/ConstraintSolver.java | 34 +++------ .../generics/ConstraintSolverImpl.java | 72 ++++-------------- .../nullaway/generics/GenericsChecks.java | 11 ++- .../uber/nullaway/jspecify/WildcardTests.java | 76 ++++++++----------- 4 files changed, 60 insertions(+), 133 deletions(-) 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 74b40a6c3b..46e79b55ec 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java @@ -64,17 +64,9 @@ class UnsatisfiableConstraintsException extends RuntimeException { private final boolean causedByNonNullUpperBound; /** - * The type argument, as passed for a {@code ? extends} wildcard, whose {@code @Nullable} - * constraint conflicts with the bound of {@link #typeVariable}, or {@code null} where another - * constraint caused the conflict. A captured argument is replaced by the wildcard it captures. - */ - private final @Nullable Type nullableBoundTypeArgument; - - /** - * The type variable with an explicitly nullable bound through which {@link - * #nullableBoundTypeArgument} admits null: that argument itself, or the effective upper bound - * of a wildcard or captured argument whose type parameter admits null; {@code null} where - * {@link #nullableBoundTypeArgument} is. + * 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; @@ -84,28 +76,24 @@ public UnsatisfiableConstraintsException(Element typeVariable) { public UnsatisfiableConstraintsException( Element typeVariable, boolean causedByNonNullUpperBound) { - this(typeVariable, causedByNonNullUpperBound, null, null); + this(typeVariable, causedByNonNullUpperBound, null); } /** - * Creates an exception for a {@code typeVariable} whose bound excludes null, passed {@code - * nullableBoundTypeArgument} for a {@code ? extends typeVariable} wildcard, where {@code - * nullableBoundTypeVariable} has an explicitly nullable bound and is that argument or the - * effective upper bound of a wildcard or captured argument whose type parameter admits 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}. */ - public UnsatisfiableConstraintsException( - Element typeVariable, Type nullableBoundTypeArgument, Type nullableBoundTypeVariable) { - this(typeVariable, true, nullableBoundTypeArgument, nullableBoundTypeVariable); + public UnsatisfiableConstraintsException(Element typeVariable, Type nullableBoundTypeVariable) { + this(typeVariable, true, nullableBoundTypeVariable); } private UnsatisfiableConstraintsException( Element typeVariable, boolean causedByNonNullUpperBound, - @Nullable Type nullableBoundTypeArgument, @Nullable Type nullableBoundTypeVariable) { this.typeVariable = typeVariable; this.causedByNonNullUpperBound = causedByNonNullUpperBound; - this.nullableBoundTypeArgument = nullableBoundTypeArgument; this.nullableBoundTypeVariable = nullableBoundTypeVariable; } @@ -117,10 +105,6 @@ public boolean isCausedByNonNullUpperBound() { return causedByNonNullUpperBound; } - public @Nullable Type getNullableBoundTypeArgument() { - return nullableBoundTypeArgument; - } - public @Nullable Type getNullableBoundTypeVariable() { return nullableBoundTypeVariable; } 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 1e4fc46b9d..b1fa4a9eea 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java @@ -240,7 +240,7 @@ private void constrainTypeArguments(Type subtype, Type supertype) { for (int i = 0; i < numTypeArgs; i++) { Type supertypeTypeArg = supertypeTypeArguments.get(i); Type subtypeTypeArg = subtypeTypeArguments.get(i); - constrainTypeArgumentContainment(subtypeTypeArg, supertypeTypeArg, subtype, i); + constrainTypeArgumentContainment(subtypeTypeArg, supertypeTypeArg); } Type subtypeEnclosing = subtype.getEnclosingType(); Type supertypeEnclosing = supertype.getEnclosingType(); @@ -258,11 +258,9 @@ private void constrainTypeArguments(Type subtype, Type supertype) { * Adds nullability constraints for containment of one type argument by another during generic * class/interface subtyping. For non-wildcard arguments, NullAway requires identical * nullability. When either side is a wildcard, containment is reduced to constraints between - * the wildcard bound and the opposing argument. {@code subtypeTypeArg} is the argument at - * {@code index} of {@code subtype}. + * the wildcard bound and the opposing argument. */ - private void constrainTypeArgumentContainment( - Type subtypeTypeArg, Type supertypeTypeArg, Type subtype, int index) { + private void constrainTypeArgumentContainment(Type subtypeTypeArg, Type supertypeTypeArg) { if (!config.handleWildcardGenerics()) { equateTypeArguments(subtypeTypeArg, supertypeTypeArg); return; @@ -270,7 +268,7 @@ private void constrainTypeArgumentContainment( // A captured formal is a type variable, not a wildcard containment target. Expanding // its backing wildcard can repeatedly unfold self-referential bounds (see issue #1934). if (supertypeTypeArg instanceof WildcardType supertypeWildcard) { - constrainContainedByWildcard(subtypeTypeArg, supertypeWildcard, subtype, index); + constrainContainedByWildcard(subtypeTypeArg, supertypeWildcard); return; } WildcardType subtypeWildcard = GenericsUtils.asWildcard(subtypeTypeArg); @@ -293,25 +291,19 @@ 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 ? extends U}, where {@code U} is an inference - * variable whose bound excludes null, an actual whose effective upper bound is an unannotated - * type variable {@code T} with an explicitly nullable bound, such as {@code T}, {@code ? - * extends T}, or a capture of a wildcard bounded by {@code T}, also constrains {@code U} to be - * {@code @Nullable}, which no solution satisfies, unless the actual is a wildcard or a capture - * whose type parameter excludes null. 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. + * 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. An actual wildcard or capture bounded by such + * a {@code T}, as in {@code Box}, 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 * the outer visit of that pair is already adding them. - * - * @param subtypeTypeArg the actual argument, at {@code index} of {@code subtype} - * @param supertypeWildcard the formal wildcard argument - * @param subtype the parameterization that passes {@code subtypeTypeArg} - * @param index the position of {@code subtypeTypeArg} among the arguments of {@code subtype} */ - private void constrainContainedByWildcard( - Type subtypeTypeArg, WildcardType supertypeWildcard, Type subtype, int index) { + private void constrainContainedByWildcard(Type subtypeTypeArg, WildcardType supertypeWildcard) { Set activeSubtypeArguments = activeWildcardContainments.get(supertypeWildcard); if (activeSubtypeArguments == null) { activeSubtypeArguments = Collections.newSetFromMap(new IdentityHashMap<>()); @@ -331,9 +323,7 @@ private void constrainContainedByWildcard( if (supertypeWildcard.kind == BoundKind.EXTENDS && supertypeVar != null && !getState(supertypeVar).nullableAllowed - && admitsNullThroughExplicitBound(subtypeUpperBound) - && (GenericsUtils.asWildcard(subtypeTypeArg) == null - || typeParameterAdmitsNull(subtype, index))) { + && admitsNullThroughExplicitBound(subtypeTypeArg)) { // 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 @@ -341,11 +331,7 @@ && admitsNullThroughExplicitBound(subtypeUpperBound) // @Nullable T, and List c = copy(in), with List // copy(List in), would be reported. throw new UnsatisfiableConstraintsException( - supertypeVar.typeVariable(), - subtypeTypeArg instanceof CapturedType captured - ? captured.wildcard - : subtypeTypeArg, - subtypeUpperBound); + supertypeVar.typeVariable(), subtypeTypeArg); } subtypeUpperBound.accept(this, supertypeUpperBound); } @@ -603,36 +589,6 @@ private boolean admitsNullThroughExplicitBound(Type t) { && GenericsUtils.boundIsExplicitlyNullable(tv.asElement(), config, handler, state); } - /** - * Returns whether the type parameter at {@code index} of the class of {@code container} admits - * null in that parameterization. A wildcard argument of {@code class Box} with a non-null - * {@code E} holds no null, whatever its own bound, and neither does the {@code B} of {@code - * Pair} for {@code class Pair}. A - * bound that is another type parameter of the same class, passed a class type, is replaced by - * that class type; any other bound admits null where it, or a bound it reaches through type - * variables, is explicitly nullable. javac rejects {@code ? extends U} for {@code B} where {@code - * A} is passed a type variable or a wildcard, and for a {@code B} bounded by a type parameter of - * an enclosing class, so no other substitution can change the result. - */ - private boolean typeParameterAdmitsNull(Type container, int index) { - List typeParameters = container.tsym.type.getTypeArguments(); - Type typeParameter = typeParameters.get(index); - if (GenericsUtils.declaredUpperBoundIsNullable(typeParameter.tsym, config, handler, state)) { - return true; - } - Type bound = typeParameter.getUpperBound(); - if (GenericsUtils.isAnnotatedAsNonNull(bound, config) || !(bound instanceof TypeVar)) { - return false; - } - for (int i = 0; i < typeParameters.size(); i++) { - Type argument = container.getTypeArguments().get(i); - if (typeParameters.get(i).tsym.equals(bound.tsym) && argument instanceof ClassType) { - return GenericsUtils.isAnnotatedAsNullable(argument, config); - } - } - return GenericsUtils.upperBoundIsNullable(bound.tsym, config, handler, state); - } - /** 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/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index 88c24d3269..4cd6f7e01a 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -1602,18 +1602,17 @@ private String inferenceFailureMessage( if (polyNullInvocation != null) { return PolyNullInference.inferenceFailureMessage(ASTHelpers.getSymbol(polyNullInvocation)); } - Type nullableBoundTypeArgument = e.getNullableBoundTypeArgument(); - if (nullableBoundTypeArgument != null) { - Element nullableBoundTypeVariable = castToNonNull(e.getNullableBoundTypeVariable()).tsym; + Type nullableBoundTypeVariable = e.getNullableBoundTypeVariable(); + if (nullableBoundTypeVariable != null) { String constrained = withDeclaringElement(typeVariable, false); - String passed = withDeclaringElement(nullableBoundTypeVariable, false); + String passed = withDeclaringElement(nullableBoundTypeVariable.tsym, false); if (constrained.equals(passed)) { constrained = withDeclaringElement(typeVariable, true); - passed = withDeclaringElement(nullableBoundTypeVariable, true); + passed = withDeclaringElement(nullableBoundTypeVariable.tsym, true); } 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 has a @Nullable upper bound", - constrained, nullableBoundTypeArgument, typeVariable, passed); + constrained, nullableBoundTypeVariable, typeVariable, passed); } if (e.isCausedByNonNullUpperBound()) { return String.format( diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java index 2df1896499..58898ddf12 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -2660,6 +2660,7 @@ public void inferenceCannotFitATypeVariableWhoseBoundAdmitsNullIntoANonNullVaria """ import java.util.ArrayList; import java.util.List; + import org.jspecify.annotations.NonNull; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.NullUnmarked; import org.jspecify.annotations.Nullable; @@ -2685,7 +2686,7 @@ static U nonNullVariable(Box b) { } static void intoNonNullVariableThroughAWildcard( Box b) { - // BUG: Diagnostic contains: the type argument ? extends T passed for ? extends U admits null, since T of Test.intoNonNullVariableThroughAWildcard has a @Nullable upper bound + // a false negative: a wildcard bounded by T is not checked against the bound of U (#2189) Object o = nonNullVariable(b); } static class Holder { @@ -2698,59 +2699,19 @@ List wildList() { } static void intoNonNullVariableThroughACapture( Holder h) { - // BUG: Diagnostic contains: the type argument ? extends T passed for ? extends U admits null, since T of Test.intoNonNullVariableThroughACapture has a @Nullable upper bound + // a false negative: a capture bounded by T is not checked against the bound of U (#2189) Object o = nonNullVariable(h.wildBox()); } - static class NonNullBox { - NonNullBox same() { - return this; - } - } - static class BoundedByANonNullVariable { - BoundedByANonNullVariable same() { - return this; - } - } static class BoundedByANullableVariable { Box box() { throw new UnsupportedOperationException(); } } - static void intoNonNullBox(NonNullBox b) {} - static void intoChainedBox(BoundedByANonNullVariable b) {} - static void wildcardOfANonNullTypeParameter( - NonNullBox b) { - intoNonNullBox(b); - intoNonNullBox(b.same()); - } - static void wildcardOfATypeParameterBoundedByANonNullVariable( - BoundedByANonNullVariable b) { - intoChainedBox(b.same()); - } static void captureOfATypeParameterBoundedByANullableVariable( BoundedByANullableVariable h) { - // BUG: Diagnostic contains: the type argument ? passed for ? extends U admits null, since T of Test.captureOfATypeParameterBoundedByANullableVariable has a @Nullable upper bound + // a false negative: a capture whose bound reaches T is not checked against the bound of U (#2189) Object o = nonNullVariable(h.box()); } - static class Pair { - Pair same() { - return this; - } - } - static void intoObjectPair(Pair p) {} - static void intoNullablePair(Pair<@Nullable Object, ? extends U> p) {} - static void siblingTypeParameterPassedANonNullType( - Pair p) { - intoObjectPair(p); - intoObjectPair(p.same()); - } - static void siblingTypeParameterPassedANullableType( - Pair<@Nullable Object, ? extends T> p) { - // BUG: Diagnostic contains: since T of Test.siblingTypeParameterPassedANullableType has a @Nullable upper bound - intoNullablePair(p); - // BUG: Diagnostic contains: since T of Test.siblingTypeParameterPassedANullableType has a @Nullable upper bound - intoNullablePair(p.same()); - } static class Set { void copyOf(java.util.Collection in) { // BUG: Diagnostic contains: type variable E of java.util.Set.copyOf is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument E passed for ? extends E admits null, since E of Test$Set.copyOf has a @Nullable upper bound @@ -2758,9 +2719,32 @@ static class Set { } } static void intoJdkCopyOfThroughACapture(Holder h) { - // BUG: Diagnostic contains: type variable E of List.copyOf is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument ? extends T passed for ? extends E admits null, since T of Test.intoJdkCopyOfThroughACapture has a @Nullable upper bound + // a false negative: a capture bounded by T is not checked against the bound of E (#2189) List copy = List.copyOf(h.wildList()); } + static class Base {} + static class Sub extends Base {} + static class NonNullList extends ArrayList {} + static void intoBase(Base b) {} + static void wildcardOfASubclassWhoseTypeParameterExcludesNull( + Sub s) { + intoBase(s); + } + static void wildcardOfANonNullListIntoJdkCopyOf( + NonNullList nl) { + List copy = List.copyOf(nl); + } + static class Pair {} + static void intoSelfPair(Pair p) {} + static void wildcardOfAPairWhoseSiblingIsNonNull( + Pair p) { + intoSelfPair(p); + } + static void wildcardOfAPairWhoseSiblingAdmitsNull( + Pair p) { + // a false negative: a wildcard bounded by X is not checked against the bound of U (#2189) + intoSelfPair(p); + } static void intoNullableVariable(Box b) { nullableVariable(b).toString(); } @@ -2771,6 +2755,10 @@ static class Set { static void nonNullBoundIntoNonNullVariable(Box b) { Object o = nonNullVariable(b); } + static void nonNullTypeVariableIntoNonNullVariable( + Box<@NonNull T> b) { + Object o = nonNullVariable(b); + } static void failureDiscardsTheOtherVariablesOfTheCall( Box b) { // BUG: Diagnostic contains: inference failure: type variable U of Test.pair is constrained to be @Nullable From 93031bc1707bcabb8346c6c1b4fd9d7616ae766b Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Wed, 25 Nov 2026 23:32:19 +0300 Subject: [PATCH 07/27] Decide parametric nullness of a capture by one predicate The solver counted a capture of a wildcard as a type variable with parametric nullness where it flowed into an inference variable, while the step that copies the result onto the type javac inferred did not count it. Without JSpecifyExperimental a capture flows as a type variable, so a capture javac inferred took a synthetic @Nullable: incompatible types: ThrowingSupplier cannot be converted to ThrowingSupplier<@Nullable capture of ?> which failed the junit-framework and vavr builds. Both sites now ask GenericsUtils.hasParametricNullness, and NestedTypePathUpdater leaves a wildcard or capture unchanged where no annotation applies, as it does for other types. The inference failure for a type variable passed for "? extends U" now names the type variable whose own bound is @Nullable, found by GenericsUtils.typeVariableWithNullableBound, as in "since S of X extends R of X, which has a @Nullable upper bound". Calcite reports four true positives; .github/third-party/calcite carries apache/calcite#5454 for them. User-visible: With JSpecifyExperimental, `dereferenced expression 'get(b)' is @Nullable` where a generic call that javac infers to return the capture of a `Box` is dereferenced, as `b.get()` already was. Not changed: Without JSpecifyExperimental, a capture javac inferred keeps its type, as before this change. Assisted-by: Claude Code (claude-opus-5-5) --- .../calcite/5454-nullable-bounds.patch | 50 ++++ .../nullaway/generics/ConstraintSolver.java | 50 +++- .../generics/ConstraintSolverImpl.java | 54 ++-- .../nullaway/generics/GenericsChecks.java | 24 +- .../uber/nullaway/generics/GenericsUtils.java | 67 +++-- .../generics/TypeSubstitutionUtils.java | 47 ++- .../librarymodel/NestedTypePathUpdater.java | 24 +- .../jspecify/PolyNullLibraryModelsTests.java | 27 ++ .../uber/nullaway/jspecify/WildcardTests.java | 267 ++++++++++++++++++ 9 files changed, 502 insertions(+), 108 deletions(-) create mode 100644 .github/third-party/calcite/5454-nullable-bounds.patch diff --git a/.github/third-party/calcite/5454-nullable-bounds.patch b/.github/third-party/calcite/5454-nullable-bounds.patch new file mode 100644 index 0000000000..00521615e4 --- /dev/null +++ b/.github/third-party/calcite/5454-nullable-bounds.patch @@ -0,0 +1,50 @@ +diff --git a/core/src/main/java/org/apache/calcite/rex/RexBiVisitor.java b/core/src/main/java/org/apache/calcite/rex/RexBiVisitor.java +index 2babccb7b337..af6ef1f96f78 100644 +--- a/core/src/main/java/org/apache/calcite/rex/RexBiVisitor.java ++++ b/core/src/main/java/org/apache/calcite/rex/RexBiVisitor.java +@@ -73,6 +73,7 @@ default void visitList(Iterable exprs, P arg, + + /** Visits a list and returns a list of the results. + * The resulting list is immutable and does not contain nulls. */ ++ @SuppressWarnings("NullAway") + default List visitList(Iterable exprs, P arg) { + final List out = new ArrayList<>(); + visitList(exprs, arg, out); +diff --git a/core/src/main/java/org/apache/calcite/rex/RexVisitor.java b/core/src/main/java/org/apache/calcite/rex/RexVisitor.java +index 041662884aa3..9f98b9efb736 100644 +--- a/core/src/main/java/org/apache/calcite/rex/RexVisitor.java ++++ b/core/src/main/java/org/apache/calcite/rex/RexVisitor.java +@@ -74,6 +74,7 @@ default void visitList(Iterable exprs, List out) { + + /** Visits a list and returns a list of the results. + * The resulting list is immutable and does not contain nulls. */ ++ @SuppressWarnings("NullAway") + default List visitList(Iterable exprs) { + final List out = new ArrayList<>(); + visitList(exprs, out); +diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/Linq4j.java b/linq4j/src/main/java/org/apache/calcite/linq4j/Linq4j.java +index 93282abb7176..361b9577a9dc 100644 +--- a/linq4j/src/main/java/org/apache/calcite/linq4j/Linq4j.java ++++ b/linq4j/src/main/java/org/apache/calcite/linq4j/Linq4j.java +@@ -109,7 +109,7 @@ public static Iterator enumeratorIterator(Enumerator enumerator) { + * + * @return enumerator + */ +- public static Enumerator iterableEnumerator( ++ public static Enumerator iterableEnumerator( + final Iterable iterable) { + if (iterable instanceof Enumerable) { + @SuppressWarnings("unchecked") final Enumerable enumerable = +diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/tree/Expressions.java b/linq4j/src/main/java/org/apache/calcite/linq4j/tree/Expressions.java +index bd4e455400a0..2da72aa4b707 100644 +--- a/linq4j/src/main/java/org/apache/calcite/linq4j/tree/Expressions.java ++++ b/linq4j/src/main/java/org/apache/calcite/linq4j/tree/Expressions.java +@@ -3154,7 +3154,7 @@ private static Class deduceType(List parameterList, + } + + /** Converts an Iterable to a List. */ +- private static List toList(Iterable iterable) { ++ private static List toList(Iterable iterable) { + if (iterable instanceof List) { + return (List) iterable; + } 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 46e79b55ec..314b08ba24 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java @@ -70,31 +70,44 @@ class UnsatisfiableConstraintsException extends RuntimeException { */ 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); + 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}. + * {@code ? extends typeVariable}, and the declared bound of {@code + * typeVariableWithNullableBound} makes that bound explicitly nullable. */ - public UnsatisfiableConstraintsException(Element typeVariable, Type nullableBoundTypeVariable) { - this(typeVariable, true, nullableBoundTypeVariable); + public UnsatisfiableConstraintsException( + Element typeVariable, + Type nullableBoundTypeVariable, + Element typeVariableWithNullableBound) { + this(typeVariable, true, nullableBoundTypeVariable, typeVariableWithNullableBound); } private UnsatisfiableConstraintsException( Element typeVariable, boolean causedByNonNullUpperBound, - @Nullable Type nullableBoundTypeVariable) { + @Nullable Type nullableBoundTypeVariable, + @Nullable Element typeVariableWithNullableBound) { this.typeVariable = typeVariable; this.causedByNonNullUpperBound = causedByNonNullUpperBound; this.nullableBoundTypeVariable = nullableBoundTypeVariable; + this.typeVariableWithNullableBound = typeVariableWithNullableBound; } public Element getTypeVariable() { @@ -108,6 +121,10 @@ public boolean isCausedByNonNullUpperBound() { public @Nullable Type getNullableBoundTypeVariable() { return nullableBoundTypeVariable; } + + public @Nullable Element getTypeVariableWithNullableBound() { + return typeVariableWithNullableBound; + } } /** @@ -138,11 +155,15 @@ enum InferredNullability { 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. Where javac - * inferred an unannotated type variable whose bound admits null, the variable is that type - * variable 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 + * nullable flowed into it, and the variable's own bound is explicitly nullable. A bound is + * explicitly nullable where it is annotated {@code @Nullable}, where a library model makes it + * nullable, or where it is another type variable, carrying no nullness annotation, whose bound + * is explicitly nullable; a bound that admits null only because unannotated code declares the + * type variable is not. 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}. */ @@ -151,10 +172,11 @@ enum InferredNullability { * 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 an unannotated type variable whose bound admits - * null, the variable is that type variable 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. + * 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; } 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 b1fa4a9eea..f67fc25bf1 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java @@ -75,10 +75,10 @@ private static final class VarState { NullnessState nullness = NullnessState.UNKNOWN; /** - * Whether a type variable that is not under inference, carries no nullness annotation, and is - * bounded by a type that admits null flowed into this variable. Such a flow fixes no nullness, - * but where javac inferred a type variable whose bound admits null, the variable takes that - * type variable with no synthetic annotation rather than the non-null default. + * 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. */ boolean parametric; @@ -322,16 +322,19 @@ private void constrainContainedByWildcard(Type subtypeTypeArg, WildcardType supe InferenceVariable supertypeVar = inferenceVariableForUse(supertypeUpperBound); if (supertypeWildcard.kind == BoundKind.EXTENDS && supertypeVar != null - && !getState(supertypeVar).nullableAllowed - && admitsNullThroughExplicitBound(subtypeTypeArg)) { - // 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 in), would be reported. - throw new UnsatisfiableConstraintsException( - supertypeVar.typeVariable(), subtypeTypeArg); + && !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 in), would be reported. + throw new UnsatisfiableConstraintsException( + supertypeVar.typeVariable(), subtypeTypeArg, typeVariableWithNullableBound); + } } subtypeUpperBound.accept(this, supertypeUpperBound); } @@ -504,12 +507,10 @@ private void directlyConstrainTypePair(Type s, Type t) throws UnsatisfiableConst } if (tVar != null && sVar == null - && s instanceof TypeVar typeVar - && !isKnownNullable(s) - && !isKnownNonNull(s)) { + && GenericsUtils.hasParametricNullness(s, config, handler, state)) { VarState st = getState(tVar); st.parametric = true; - if (GenericsUtils.boundIsExplicitlyNullable(typeVar.asElement(), config, handler, state)) { + if (GenericsUtils.boundIsExplicitlyNullable(s.asElement(), config, handler, state)) { st.parametricNullable = true; } } @@ -578,15 +579,18 @@ private boolean treatAsTypeVariableForInference(Type t) { } /** - * Returns whether {@code t} is a type variable not under inference, not a capture, carrying no - * nullness annotation at this use, whose bound is explicitly nullable. + * 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 boolean admitsNullThroughExplicitBound(Type t) { + private @Nullable Element typeVariableWithNullableBoundFor(Type t) { return t instanceof TypeVar tv - && !(t instanceof CapturedType) - && !inferenceVariables.containsKey(tv.asElement()) - && !GenericsUtils.hasNullnessAnnotation(t, config) - && GenericsUtils.boundIsExplicitlyNullable(tv.asElement(), config, handler, state); + && !(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. */ 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 4cd6f7e01a..0f19778dd9 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -1603,16 +1603,24 @@ private String inferenceFailureMessage( return PolyNullInference.inferenceFailureMessage(ASTHelpers.getSymbol(polyNullInvocation)); } Type nullableBoundTypeVariable = e.getNullableBoundTypeVariable(); - if (nullableBoundTypeVariable != null) { + Element typeVariableWithNullableBound = e.getTypeVariableWithNullableBound(); + if (nullableBoundTypeVariable != null && typeVariableWithNullableBound != null) { + Element passedElement = nullableBoundTypeVariable.tsym; String constrained = withDeclaringElement(typeVariable, false); - String passed = withDeclaringElement(nullableBoundTypeVariable.tsym, false); - if (constrained.equals(passed)) { + String passed = withDeclaringElement(passedElement, false); + String withNullableBound = withDeclaringElement(typeVariableWithNullableBound, false); + if (constrained.equals(passed) || constrained.equals(withNullableBound)) { constrained = withDeclaringElement(typeVariable, true); - passed = withDeclaringElement(nullableBoundTypeVariable.tsym, 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 has a @Nullable upper bound", - constrained, nullableBoundTypeVariable, typeVariable, passed); + "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( @@ -3170,8 +3178,8 @@ private Type.MethodType getInferredMethodTypeForGenericMethodReference( parentPath = parentPath.getParentPath(); } Tree parentTree = parentPath != null ? parentPath.getLeaf() : null; - if ((parentTree instanceof MethodInvocationTree || parentTree instanceof NewClassTree) - && isCallNeedingInference((ExpressionTree) parentTree)) { + if (parentTree instanceof ExpressionTree parentExpression + && isCallNeedingInference(parentExpression)) { CallInferenceResult inferenceResult = inferredTypeVarNullabilityForGenericCalls.get(parentTree); if (inferenceResult instanceof InferenceSuccess successResult) { 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 b21bd2fb2b..b71484a84d 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java @@ -387,12 +387,12 @@ static boolean hasNullnessAnnotation(Type type, Config config) { * 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 a type that already holds the null of - * a type variable that flowed into the variable: an unannotated, uncaptured type variable whose - * bound admits null, or an intersection type, whose nullness comes from its elements. Any other - * type, including a wildcard, a captured type variable, 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}. + * 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, @@ -404,27 +404,31 @@ static boolean hasNullnessAnnotation(Type type, Config config) { case NULLABLE -> GenericsChecks.getSyntheticNullableAnnotType(state); case NONNULL -> GenericsChecks.getSyntheticNonNullAnnotType(state); case TYPE_VARIABLE_OR_NULLABLE -> - holdsTheNullOfAFlowedTypeVariable(inferredType, config, handler, state) + inferredType.isCompound() || hasParametricNullness(inferredType, config, handler, state) ? null : GenericsChecks.getSyntheticNullableAnnotType(state); case TYPE_VARIABLE_OR_NONNULL -> - holdsTheNullOfAFlowedTypeVariable(inferredType, config, handler, state) + inferredType.isCompound() || hasParametricNullness(inferredType, config, handler, state) ? null : GenericsChecks.getSyntheticNonNullAnnotType(state); }; } /** - * Returns whether {@code type} is an intersection type or an unannotated, uncaptured type - * variable whose bound admits null. + * 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 */ - private static boolean holdsTheNullOfAFlowedTypeVariable( + static boolean hasParametricNullness( Type type, Config config, Handler handler, VisitorState state) { - if (type.isCompound()) { - return true; - } return type instanceof Type.TypeVar typeVariable - && !(type instanceof Type.CapturedType) && !hasNullnessAnnotation(type, config) && upperBoundIsNullable(typeVariable.asElement(), config, handler, state); } @@ -473,23 +477,36 @@ static boolean declaredUpperBoundIsNullable( } /** - * Returns true if the upper bound of the given type variable is explicitly nullable: the declared - * bound is annotated {@code @Nullable}, a library model overrides it, or the declared bound is - * another type variable, carrying no nullness annotation, whose bound is explicitly nullable. - * 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. + * 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) { Type upperBound = (Type) ((TypeVariable) typeVarElement.asType()).getUpperBound(); if (isAnnotatedAsNullable(upperBound, config) || libraryModelMakesBoundNullable(typeVarElement, handler, state)) { - return true; + return typeVarElement; } - return !hasNullnessAnnotation(upperBound, config) - && upperBound.getKind() == TypeKind.TYPEVAR - && boundIsExplicitlyNullable(upperBound.asElement(), config, handler, state); + return !hasNullnessAnnotation(upperBound, config) && upperBound.getKind() == TypeKind.TYPEVAR + ? typeVariableWithNullableBound(upperBound.asElement(), config, handler, state) + : null; } /** Returns true if a library model overrides the upper bound of the given type variable. */ 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 64812f1d24..f48a4a311d 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java @@ -143,8 +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, null, null, null) - .visit(newType, origType); + return new RestoreNullnessAnnotationsVisitor(types, config, null).visit(newType, origType); } /** @@ -272,7 +271,9 @@ static Type updateTypeWithInferredNullability( // 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, typeVarNullability, state, handler) + state.getTypes(), + config, + new InferredTypeVariableNullness(typeVarNullability, state, handler)) .visit(typeToUpdate, origExplicitAnnotationsRestored); } @@ -427,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 @@ -614,26 +625,15 @@ private Type restoreImplicitWildcardBound(BoundPair pair, Type targetBound, Type * ConstraintSolver.InferredNullability#TYPE_VARIABLE_OR_NONNULL} variables this visitor * resolves against the visited type, or {@code null} to resolve none. Set only when copying * inferred nullness onto the type javac inferred, the one step that can tell a type variable - * from any other type; {@link #state} is set with it. + * from any other type. */ - private final @Nullable Map typeVarNullability; - - private final @Nullable VisitorState state; - - /** Decides whether a type variable's bound admits null; set with {@link #state}. */ - private final @Nullable Handler handler; + private final @Nullable InferredTypeVariableNullness inferredNullness; RestoreNullnessAnnotationsVisitor( - Types types, - Config config, - @Nullable Map typeVarNullability, - @Nullable VisitorState state, - @Nullable Handler handler) { + Types types, Config config, @Nullable InferredTypeVariableNullness inferredNullness) { this.types = types; this.config = config; - this.typeVarNullability = typeVarNullability; - this.state = state; - this.handler = handler; + this.inferredNullness = inferredNullness; } @Override @@ -964,19 +964,18 @@ private Type updateDirectNullabilityAnnotationsForType(Type t, Type other) { return typeWithAnnot(t, annot); } } - if (typeVarNullability == null - || state == null - || handler == null - || !(other instanceof Type.TypeVar)) { + if (inferredNullness == null || !(other instanceof Type.TypeVar)) { return t; } - ConstraintSolver.InferredNullability inferred = typeVarNullability.get(other.tsym); + 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, handler, state); + 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 9cf1b0866b..e4ccb75454 100644 --- a/nullaway/src/main/java/com/uber/nullaway/librarymodel/NestedTypePathUpdater.java +++ b/nullaway/src/main/java/com/uber/nullaway/librarymodel/NestedTypePathUpdater.java @@ -60,8 +60,8 @@ public static Type addAnnotation( * 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, which must return an - * annotation type for it, and the annotation lands on its bound. + * variable at {@code typePath} is passed to {@code annotationFor} itself, and the annotation it + * returns lands on the bound. * * @return the updated type, or the original {@code type} instance if no change was made */ @@ -103,14 +103,6 @@ private Type updateLeaf(Type type) { return castToNonNull(annotationFor).apply(type); } - /** Returns the annotation type to add to the bound of a wildcard or a capture at the path. */ - private Type annotationTypeForWildcardOrCapture(Type wildcardOrCapture) { - return Verify.verifyNotNull( - annotationTypeFor(wildcardOrCapture), - "no annotation type for the wildcard or capture %s", - wildcardOrCapture); - } - @Override public Type visitClassType(Type.ClassType t, Integer pathIndex) { if (pathIndex == typePath.size()) { @@ -164,7 +156,12 @@ public Type visitWildcardType(Type.WildcardType t, Integer pathIndex) { if (updateKind == UpdateKind.REPLACE_TYPE) { return updateLeaf(t); } - Type annotationType = annotationTypeForWildcardOrCapture(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, annotationType)); @@ -231,7 +228,10 @@ 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 = annotationTypeForWildcardOrCapture(t); + Type annotationType = annotationTypeFor(t); + if (annotationType == null) { + return t; + } Type updatedUpperBound = TypeSubstitutionUtils.typeWithAnnot(t.getUpperBound(), annotationType); if (wildcard.kind == BoundKind.EXTENDS) { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/PolyNullLibraryModelsTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/PolyNullLibraryModelsTests.java index e9d3be8f31..adf5ba3a27 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/PolyNullLibraryModelsTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/PolyNullLibraryModelsTests.java @@ -1498,6 +1498,33 @@ void explicitlyNullableTypeArgument(X x) { .doTest(); } + @Test + public void aCaptureWhoseBoundAdmitsNullKeepsItsTypeAtAPolyNullLocation() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import com.uber.lib.unannotated.PolyNullMethods; + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static U first(List list) { + return list.get(0); + } + void typeVariableResult(List list) { + T first = PolyNullMethods.genericFirst(first(list), () -> "x"); + } + void classTypeResult(List list) { + // BUG: Diagnostic contains: dereferenced expression 'PolyNullMethods.genericObject(first(list), () -> "x")' is @Nullable + PolyNullMethods.genericObject(first(list), () -> "x").hashCode(); + } + } + """) + .doTest(); + } + private CompilationTestHelper makeHelper() { return makeTestHelperWithArgs( JSpecifyJavacConfig.withJSpecifyModeArgs(List.of("-XepOpt:NullAway:OnlyNullMarked=true"))); diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java index 58898ddf12..ff7e3f828f 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -2222,6 +2222,7 @@ void throughALocal(T t) { takeObjects(inferred); } void throughTheCall(T t) { + List sink = of(t, "x"); // BUG: Diagnostic contains: dereferenced expression 'pick(t, "x")' is @Nullable pick(t, "x").toString(); // BUG: Diagnostic contains: dereferenced expression 'of(t, "x").get(0)' is @Nullable @@ -2509,6 +2510,29 @@ void methodReferenceIntoADiamond(T t) { void constructor(Box input) { var result = new Box<>(input, new Object()); } + static class ListAndElement { + ListAndElement(List ws, W w, E e) {} + } + static class Mapped { + Mapped(W w, Function f) {} + } + static U identity(U u) { + return u; + } + void constructorTakingAListOfNullableElements(List<@Nullable String> l) { + // a false positive: W of a generic constructor at a diamond is not inferred (#1825) + // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required + var c = new ListAndElement<>(l, null, "x"); + } + void constructorTakingAGenericMethodReference(@Nullable String s) { + // a false positive: W of a generic constructor at a diamond is not inferred (#1825) + // BUG: Diagnostic contains: passing @Nullable parameter 's' where @NonNull is required + var c = new Mapped<>(s, Test::identity); + } + void methodReferenceOutsideACall() { + Function> f = Test::singleton; + f = (Test::singleton); + } } """) .doTest(); @@ -2626,6 +2650,157 @@ void f(T t) { .doTest(); } + /** + * Without wildcard handling, a capture flows into an inference variable as a type variable, so a + * capture whose bound admits null is as parametric as a type variable {@code T} whose bound + * admits null, and the call keeps it as javac inferred it. + */ + @Test + public void aCaptureWhoseBoundAdmitsNullStaysAsInferredWithWildcardHandlingDisabled() { + makeTestHelperWithArgs( + List.of( + "-XepOpt:NullAway:OnlyNullMarked=true", + JSpecifyJavacConfig.JSPECIFY_MODE_FLAG, + JSpecifyJavacConfig.ADD_TYPE_ANNOTATIONS_FLAG)) + .addSourceLines( + "Test.java", + """ + import java.util.function.BiPredicate; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + interface Action { + R run() throws Exception; + } + static R call(Action action) { + throw new UnsupportedOperationException(); + } + interface Seq extends Iterable { + Seq seq(); + default boolean corresponds( + Iterable that, BiPredicate predicate) { + return true; + } + } + static U first(Iterable elements) { + throw new UnsupportedOperationException(); + } + Seq anySeq() { + throw new UnsupportedOperationException(); + } + Seq seqOfT() { + throw new UnsupportedOperationException(); + } + Seq<@Nullable String> nullableStrings() { + throw new UnsupportedOperationException(); + } + void castToAWildcardType() { + call((Action) () -> { + throw new Exception(); + }); + } + void receiverOfAWildcardType(Seq self, Seq that) { + self.seq().corresponds(that.seq(), (a, b) -> true); + } + void unboundedWildcard() { + first(anySeq()).hashCode(); + } + void wildcardBoundedByATypeVariable() { + T t = first(seqOfT()); + } + void nullableTypeArgument() { + // BUG: Diagnostic contains: dereferenced expression 'first(nullableStrings())' is @Nullable + first(nullableStrings()).hashCode(); + } + } + """) + .doTest(); + } + + /** + * A value read through {@code ? extends T}, where the bound of {@code T} admits null, may be + * null. A generic call that javac infers to return the capture of that wildcard returns such a + * value too, as reading the element directly does. + */ + @Test + public void aCallReturningACaptureOfAWildcardBoundedByATypeVariableMayReturnNull() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class NullableBox implements Iterable { + public java.util.Iterator iterator() { + throw new UnsupportedOperationException(); + } + } + static class NonNullBox implements Iterable { + public java.util.Iterator iterator() { + throw new UnsupportedOperationException(); + } + } + static class Box { + E get() { + throw new UnsupportedOperationException(); + } + } + static U first(Iterable it) { + throw new UnsupportedOperationException(); + } + static U get(Box b) { + throw new UnsupportedOperationException(); + } + static U getThroughWildcard(Box b) { + throw new UnsupportedOperationException(); + } + static U firstNonNull(Iterable it) { + throw new UnsupportedOperationException(); + } + void readDirectly(Box b, List l) { + // BUG: Diagnostic contains: dereferenced expression 'b.get()' is @Nullable + b.get().toString(); + // BUG: Diagnostic contains: dereferenced expression 'l.get(0)' is @Nullable + l.get(0).toString(); + } + void throughAContainerWhoseParameterAdmitsNull(NullableBox b) { + // BUG: Diagnostic contains: dereferenced expression 'first(b)' is @Nullable + first(b).toString(); + } + void throughAContainerWhoseParameterExcludesNull(NonNullBox b) { + // BUG: Diagnostic contains: dereferenced expression 'first(b)' is @Nullable + first(b).toString(); + } + void throughTheSameContainer(Box b) { + // BUG: Diagnostic contains: dereferenced expression 'get(b)' is @Nullable + get(b).toString(); + } + void throughAWildcardParameter(Box b) { + // BUG: Diagnostic contains: dereferenced expression 'getThroughWildcard(b)' is @Nullable + getThroughWildcard(b).toString(); + } + void intoAVariableWhoseBoundExcludesNull(NullableBox b) { + // the call that passes b for U goes unchecked (#2189), and the value still reads + // through ? extends T + // BUG: Diagnostic contains: dereferenced expression 'firstNonNull(b)' is @Nullable + firstNonNull(b).toString(); + } + void theTypeVariableItself(Box b, NullableBox n) { + get(b).toString(); + first(n).toString(); + } + void aWildcardWhoseBoundExcludesNull(Box b) { + get(b).toString(); + } + } + """) + .doTest(); + } + /** * The JSpecify JDK models decide the bound of the inference variable: {@code Arrays.asList} * admits null and {@code List.of} does not. @@ -2755,6 +2930,36 @@ static void intoSelfPair(Pair p) {} static void nonNullBoundIntoNonNullVariable(Box b) { Object o = nonNullVariable(b); } + static B apply( + A a, java.util.function.Function f) { + throw new UnsupportedOperationException(); + } + static void intoJdkCopyOfThroughAMethodReference( + List in) { + // a false negative: T reaches copyOf through another generic call (#1947) + List copy = apply(in, List::copyOf); + } + static void intoJdkCopyOfInsideALambda(List in) { + // a false negative: T reaches copyOf through another generic call (#1947) + List copy = apply(in, l -> List.copyOf(l)); + } + static void bareTypeVariableIntoJdkListOf(T t) { + // a false negative: only a ? extends U formal constrains U against a T that admits null (#1932) + List list = List.of(t); + } + static List copy(Box b) { + throw new UnsupportedOperationException(); + } + static void intoNullableVariableThatTheContextMakesNonNull( + Box b) { + // a false negative: the assignment, not the bound of U, makes U non-null (#1945) + List c = copy(b); + } + static void intoNonNullVariableByAnExplicitTypeArgument( + Box b) { + // a false negative: only a type argument annotated @Nullable is checked against the bound of U (#1946) + Object o = Test.nonNullVariable(b); + } static void nonNullTypeVariableIntoNonNullVariable( Box<@NonNull T> b) { Object o = nonNullVariable(b); @@ -2823,4 +3028,66 @@ GenericConstructor(Box b) {} """) .doTest(); } + + @Test + public void anInferenceFailureNamesTheTypeVariableWhoseBoundIsNullable() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + void classTypeVariable(List in) { + // BUG: Diagnostic contains: the type argument T passed for ? extends E admits null, since T of Test has a @Nullable upper bound + List copy = List.copyOf(in); + } + static void boundedByATypeVariable( + List in) { + // BUG: Diagnostic contains: the type argument S passed for ? extends E admits null, since S of Test.boundedByATypeVariable extends R of Test.boundedByATypeVariable, which has a @Nullable upper bound + List copy = List.copyOf(in); + } + static + void boundedThroughTwoTypeVariables(List in) { + // BUG: Diagnostic contains: since S of Test.boundedThroughTwoTypeVariables extends Q of Test.boundedThroughTwoTypeVariables, which has a @Nullable upper bound + List copy = List.copyOf(in); + } + void boundedByTheClassTypeVariable(List in) { + // BUG: Diagnostic contains: since S of Test.boundedByTheClassTypeVariable extends T of Test, which has a @Nullable upper bound + List copy = List.copyOf(in); + } + static void boundedByANonNullUse( + List in) { + List copy = List.copyOf(in); + } + static class Source { + static class Box { + static List copy(List in) { + throw new UnsupportedOperationException(); + } + } + } + static class Target { + static class Box { + static void copy(List in) { + // BUG: Diagnostic contains: type variable U of Test$Source$Box.copy is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument U passed for ? extends U admits null, since U of Test$Target$Box.copy extends R of Test$Target$Box.copy, which has a @Nullable upper bound + List copy = Source.Box.copy(in); + } + } + } + static class Witness { + static class Box { + static void copy(List in) { + // BUG: Diagnostic contains: type variable U of Test$Source$Box.copy is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument S passed for ? extends U admits null, since S of Test$Witness$Box.copy extends U of Test$Witness$Box.copy, which has a @Nullable upper bound + List copy = Source.Box.copy(in); + } + } + } + } + """) + .doTest(); + } } From 79f0d24d853b6a81ffbe712edbecea8dc94b584b Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Thu, 26 Nov 2026 10:27:56 +0300 Subject: [PATCH 08/27] Run nullable-bound inference only with JSpecifyExperimental With JSpecifyMode alone, the change already reported `dereferenced expression 'pick(t, "x")' is @Nullable` inside `if (t != null)` (#1727), and with HandleWildcardGenerics and WarnOnGenericInferenceFailure it reported `inference failure` for a `Box` passed for `Box`; master reports neither. Checking a generic constructor at a diamond and a generic method reference against the types javac inferred also added reports without JSpecifyExperimental, such as `incompatible types: List<@Nullable T> cannot be converted to List` for `new C<>(a, b)` with ` C(U a, U b)`. `Config.isNullableBoundInferenceEnabled()`, true with JSpecifyMode and JSpecifyExperimental, now gates every entry point: `ConstraintSolverImpl.directlyConstrainTypePair`, where a type variable whose bound admits null flows into an inference variable; the `? extends U` failure in `constrainContainedByWildcard`; the diamond-constructor substitution; and the choice of javac's referent type for a generic method reference, which otherwise looks up inference only under a method call, as on master. `isPolyNullLibraryModelsEnabled()` has the same value, but these rules cover generic calls with no PolyNull model, so they get an accessor of their own. Not changed: Without JSpecifyExperimental, NullAway reports what master 594cf3dfc reports on every source the PR's tests add, under JSpecifyMode alone and with HandleWildcardGenerics and WarnOnGenericInferenceFailure. The two master false positives at diamond constructors, on `new ListAndElement<>(l, null, "x")` and `new Mapped<>(s, Test::identity)`, are now removed only with JSpecifyExperimental. The constructor tests split each call over lines so the `#1825` marker and the removed false positive sit on different lines, the intersection test gains a reporting control, and the capture test gains a line the gate changes. Assisted-by: Claude Code (claude-opus-5-5) --- .../main/java/com/uber/nullaway/Config.java | 20 ++ .../com/uber/nullaway/DummyOptionsConfig.java | 5 + .../nullaway/ErrorProneCLIFlagsConfig.java | 7 + .../nullaway/generics/ConstraintSolver.java | 4 +- .../generics/ConstraintSolverImpl.java | 12 +- .../nullaway/generics/GenericsChecks.java | 36 +++- .../uber/nullaway/jspecify/WildcardTests.java | 199 +++++++++++++++++- 7 files changed, 256 insertions(+), 27 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/Config.java b/nullaway/src/main/java/com/uber/nullaway/Config.java index 5a3235e33c..0488f2a6f9 100644 --- a/nullaway/src/main/java/com/uber/nullaway/Config.java +++ b/nullaway/src/main/java/com/uber/nullaway/Config.java @@ -315,6 +315,26 @@ 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? 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, as before. + * + *

Where it is true, if no constraint fixes an inference variable and such a type variable + * flows into it, the variable adds no annotation where javac inferred a type variable with + * parametric nullness or an intersection type. Elsewhere it is {@code @Nullable} where the bounds + * of both the passed type variable and the inference variable's own type parameter are explicitly + * nullable, and {@code @NonNull} otherwise. A bound is explicitly nullable where it is annotated + * {@code @Nullable}, where a library model makes it nullable, or where it is another type + * variable whose bound is 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. + */ + 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 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/generics/ConstraintSolver.java b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java index 314b08ba24..53c5d9a8f5 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java @@ -148,7 +148,9 @@ 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. + * 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, /** A constraint fixed the variable to be nullable. */ 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 f67fc25bf1..1353f68a3a 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java @@ -78,7 +78,8 @@ private static final class VarState { * 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. + * annotation rather than the non-null default. Recorded only where {@link + * Config#isNullableBoundInferenceEnabled} holds. */ boolean parametric; @@ -293,7 +294,8 @@ private void equateTypeArguments(Type subtypeTypeArg, Type supertypeTypeArg) { * 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. An actual wildcard or capture bounded by such + * {@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}, 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 @@ -320,7 +322,8 @@ private void constrainContainedByWildcard(Type subtypeTypeArg, WildcardType supe Type supertypeUpperBound = GenericsUtils.wildcardUpperBound(supertypeWildcard, state, config, handler); InferenceVariable supertypeVar = inferenceVariableForUse(supertypeUpperBound); - if (supertypeWildcard.kind == BoundKind.EXTENDS + if (config.isNullableBoundInferenceEnabled() + && supertypeWildcard.kind == BoundKind.EXTENDS && supertypeVar != null && !getState(supertypeVar).nullableAllowed) { Element typeVariableWithNullableBound = @@ -505,7 +508,8 @@ private void directlyConstrainTypePair(Type s, Type t) throws UnsatisfiableConst if (isKnownNullable(s) && tVar != null) { updateNullness(tVar, NullnessState.NULLABLE); } - if (tVar != null + if (config.isNullableBoundInferenceEnabled() + && tVar != null && sVar == null && GenericsUtils.hasParametricNullness(s, config, handler, state)) { VarState st = getState(tVar); 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 0f19778dd9..a151f6820c 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -3159,7 +3159,9 @@ public void compareGenericTypeParameterNullabilityForCall( /** * 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. + * 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 @@ -3168,8 +3170,9 @@ public void compareGenericTypeParameterNullabilityForCall( * state.getPath()}) * @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; {@code methodType} unchanged where the enclosing call needs - * no inference or its inference failed + * 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( MemberReferenceTree memberReferenceTree, Type.MethodType methodType, VisitorState state) { @@ -3178,7 +3181,9 @@ private Type.MethodType getInferredMethodTypeForGenericMethodReference( parentPath = parentPath.getParentPath(); } Tree parentTree = parentPath != null ? parentPath.getLeaf() : null; + boolean useInferredReferentType = config.isNullableBoundInferenceEnabled(); if (parentTree instanceof ExpressionTree parentExpression + && (useInferredReferentType || parentTree instanceof MethodInvocationTree) && isCallNeedingInference(parentExpression)) { CallInferenceResult inferenceResult = inferredTypeVarNullabilityForGenericCalls.get(parentTree); @@ -3191,7 +3196,8 @@ && isCallNeedingInference(parentExpression)) { // 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 = - referentType instanceof Type.MethodType referentMethodType + useInferredReferentType + && referentType instanceof Type.MethodType referentMethodType // diff-coverage: ignore -- defensive guard, no known call shape reaches it && referentMethodType.getParameterTypes().size() == methodType.getParameterTypes().size() @@ -4049,7 +4055,8 @@ private Type.MethodType getInvokedMethodTypeAtCall( && invokedMethodType instanceof Type.ForAll forAllType) { return substituteTypeArgsInGenericMethodType( tree, forAllType, path, state, calledFromDataflow); - } else if (tree instanceof NewClassTree newClassTree + } else if (config.isNullableBoundInferenceEnabled() + && tree instanceof NewClassTree newClassTree && invokedMethodType instanceof Type.ForAll forAllType) { invokedMethodType = substituteInferredConstructorTypeArgs(newClassTree, forAllType, state); } @@ -4109,9 +4116,16 @@ private Type.MethodType applyPolyNullModel( * 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 @@ -4278,9 +4292,9 @@ private void reportInferenceFailure( /** * 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 or no inference result, 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. + * 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 diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java index ff7e3f828f..069b068450 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -2520,19 +2520,43 @@ static class Mapped { return u; } void constructorTakingAListOfNullableElements(List<@Nullable String> l) { - // a false positive: W of a generic constructor at a diamond is not inferred (#1825) - // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required - var c = new ListAndElement<>(l, null, "x"); + var c = + new ListAndElement<>( + l, + // a false positive: W of a generic constructor at a diamond is not inferred + // (#1825) + // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required + null, + "x"); } void constructorTakingAGenericMethodReference(@Nullable String s) { - // a false positive: W of a generic constructor at a diamond is not inferred (#1825) - // BUG: Diagnostic contains: passing @Nullable parameter 's' where @NonNull is required - var c = new Mapped<>(s, Test::identity); + var c = + new Mapped<>( + // a false positive: W of a generic constructor at a diamond is not inferred + // (#1825) + // BUG: Diagnostic contains: passing @Nullable parameter 's' where @NonNull is required + s, + Test::identity); } void methodReferenceOutsideACall() { Function> f = Test::singleton; f = (Test::singleton); } + static class TwoLists { + TwoLists(U a, U b) {} + } + static V nonNullIdentity(V v) { + return v; + } + void takeFn(X x, Function, List<@Nullable T>> f) {} + void genericConstructorAtADiamondTakingTwoLists(List a, List<@Nullable T> b) { + // BUG: Diagnostic contains: incompatible types: List<@Nullable T> cannot be converted to List + var c = new TwoLists<>(a, b); + } + void genericMethodReferenceUnderAGenericCall() { + // BUG: Diagnostic contains: referenced method returns List, but functional interface method returns List<@Nullable T> + takeFn("x", Test::nonNullIdentity); + } } """) .doTest(); @@ -2642,9 +2666,13 @@ public void run() {} static E pick(E a, E b) { return a; } - void f(T t) { + void intersection(T t) { pick(t, new B()).run(); } + void classType(T t) { + // BUG: Diagnostic contains: dereferenced expression 'pick(t, new A())' is @Nullable + pick(t, new A()).run(); + } } """) .doTest(); @@ -2658,10 +2686,10 @@ void f(T t) { @Test public void aCaptureWhoseBoundAdmitsNullStaysAsInferredWithWildcardHandlingDisabled() { makeTestHelperWithArgs( - List.of( - "-XepOpt:NullAway:OnlyNullMarked=true", - JSpecifyJavacConfig.JSPECIFY_MODE_FLAG, - JSpecifyJavacConfig.ADD_TYPE_ANNOTATIONS_FLAG)) + JSpecifyJavacConfig.withJSpecifyModeArgs( + Arrays.asList( + "-XepOpt:NullAway:OnlyNullMarked=true", + "-XepOpt:NullAway:HandleWildcardGenerics=false"))) .addSourceLines( "Test.java", """ @@ -2686,6 +2714,9 @@ interface Seq extends Iterable { static U first(Iterable elements) { throw new UnsupportedOperationException(); } + static U pick(U a, U b) { + return a; + } Seq anySeq() { throw new UnsupportedOperationException(); } @@ -2709,6 +2740,10 @@ void unboundedWildcard() { void wildcardBoundedByATypeVariable() { T t = first(seqOfT()); } + void wildcardBoundedByATypeVariableIntoAClassTypeResult() { + // BUG: Diagnostic contains: dereferenced expression 'pick(first(seqOfT()), "x")' is @Nullable + pick(first(seqOfT()), "x").toString(); + } void nullableTypeArgument() { // BUG: Diagnostic contains: dereferenced expression 'first(nullableStrings())' is @Nullable first(nullableStrings()).hashCode(); @@ -3090,4 +3125,146 @@ static class Box { """) .doTest(); } + + @Test + public void aTypeVariableWithANullableBoundChangesNoReportWithJSpecifyModeAlone() { + makeTestHelperWithArgs( + List.of( + "-XepOpt:NullAway:OnlyNullMarked=true", + JSpecifyJavacConfig.JSPECIFY_MODE_FLAG, + JSpecifyJavacConfig.ADD_TYPE_ANNOTATIONS_FLAG)) + .addSourceLines( + "Test.java", + """ + import java.util.List; + import java.util.Objects; + import java.util.function.Function; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static U pick(U a, U b) { + return a; + } + static List of(E a, E b) { + throw new UnsupportedOperationException(); + } + static class C { + C(U a, U b) {} + } + static void m(U a, U b) {} + static V identity(V v) { + return v; + } + void takeFn(X x, Function, List<@Nullable T>> f) {} + static class Mapped { + Mapped(W w, Function f) {} + } + static class ListAndElement { + ListAndElement(List ws, W w, E e) {} + } + static U nullableIdentity(U u) { + return u; + } + static void apply(A a, Function f) {} + void typeVariable(T t) { + pick(t, "x").toString(); + } + void typeVariableAfterRequireNonNull(T t) { + T checked = Objects.requireNonNull(t); + pick(checked, "x").toString(); + } + void typeVariableInAnEnhancedFor(T t) { + for (Object o : of(t, "x")) { + o.toString(); + } + } + void nullableArgument(@Nullable String s) { + // BUG: Diagnostic contains: dereferenced expression 'pick(s, "x")' is @Nullable + pick(s, "x").toString(); + } + void genericConstructorAtADiamond(List a, List<@Nullable T> b) { + var c = new C<>(a, b); + } + void genericMethod(List a, List<@Nullable T> b) { + // BUG: Diagnostic contains: incompatible types: List<@Nullable T> cannot be converted to List + m(a, b); + } + void genericMethodReferenceUnderAGenericCall() { + takeFn("x", Test::identity); + } + void genericMethodReferenceTakingANullableArgument(@Nullable String s) { + apply(s, Test::nullableIdentity); + } + void genericConstructorTakingAListOfNullableElements(List<@Nullable String> l) { + var c = + new ListAndElement<>( + // a false positive that JSpecifyExperimental removes + // BUG: Diagnostic contains: incompatible types: List<@Nullable String> cannot be converted to List + l, + // a false positive: W of a generic constructor at a diamond is not inferred + // (#1825) + // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required + null, + "x"); + } + void genericMethodReferenceUnderADiamond(@Nullable String s) { + var mapped = + new Mapped<>( + // a false positive: W of a generic constructor at a diamond is not inferred + // (#1825) + // BUG: Diagnostic contains: passing @Nullable parameter 's' where @NonNull is required + s, + // a false positive that JSpecifyExperimental removes + // BUG: Diagnostic contains: parameter u of referenced method is @NonNull + Test::nullableIdentity); + } + } + """) + .doTest(); + } + + @Test + public void aTypeVariableWithANullableBoundFailsNoInferenceWithoutJSpecifyExperimental() { + makeTestHelperWithArgs( + List.of( + "-XepOpt:NullAway:OnlyNullMarked=true", + JSpecifyJavacConfig.JSPECIFY_MODE_FLAG, + JSpecifyJavacConfig.ADD_TYPE_ANNOTATIONS_FLAG, + "-XepOpt:NullAway:HandleWildcardGenerics=true", + "-XepOpt:NullAway:WarnOnGenericInferenceFailure=true")) + .addSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static U nonNullVariable(Box b) { + throw new UnsupportedOperationException(); + } + static U pick(U a, U b) { + return a; + } + static class GenericConstructor { + GenericConstructor(Box b) {} + } + void typeVariable(Box b) { + Object o = nonNullVariable(b); + } + void typeVariableIntoADiamond(Box b) { + var c = new GenericConstructor<>(b); + } + void typeVariableIntoAClassTypeResult(T t) { + pick(t, "x").toString(); + } + void nullableTypeArgument(Box<@Nullable String> b) { + // BUG: Diagnostic contains: inference failure + Object o = nonNullVariable(b); + } + } + """) + .doTest(); + } } From 648f1cf1bec3984e75bed8074d9dd77827f1f083 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Thu, 26 Nov 2026 10:28:02 +0300 Subject: [PATCH 09/27] Describe the inferred-nullness steps precisely in Javadoc `PolyNullInference.applyToMethodType` named an annotated type variable as taking the PolyNull annotation, `NestedTypePathUpdater.addAnnotation` left open which bound a wildcard gets, and `RestoreNullnessAnnotationsVisitor.inferredNullness` claimed its step always visits the type javac inferred. Each now states what the code does. Assisted-by: Claude Code (claude-opus-5-5) --- .../com/uber/nullaway/generics/PolyNullInference.java | 3 ++- .../uber/nullaway/generics/TypeSubstitutionUtils.java | 9 ++++++--- .../nullaway/librarymodel/NestedTypePathUpdater.java | 3 ++- 3 files changed, 10 insertions(+), 5 deletions(-) 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 1edd06a3f1..21a909c975 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/PolyNullInference.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/PolyNullInference.java @@ -63,7 +63,8 @@ private PolyNullInference() {} *

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 the PolyNull annotation. + * 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( 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 f48a4a311d..992160740c 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java @@ -623,9 +623,12 @@ private Type restoreImplicitWildcardBound(BoundPair pair, Type targetBound, Type * 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 when copying - * inferred nullness onto the type javac inferred, the one step that can tell a type variable - * from any other type. + * 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. The destination is a declared type where {@link Config#isNullableBoundInferenceEnabled} + * is false, and then the solver produces none of these variables, and where javac's type for a + * referenced method has another number of parameters. */ private final @Nullable InferredTypeVariableNullness inferredNullness; 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 e4ccb75454..25345990ed 100644 --- a/nullaway/src/main/java/com/uber/nullaway/librarymodel/NestedTypePathUpdater.java +++ b/nullaway/src/main/java/com/uber/nullaway/librarymodel/NestedTypePathUpdater.java @@ -61,7 +61,8 @@ public static Type addAnnotation( * 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 lands on the bound. + * 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 */ From 8f83a0a291e3413bbd814fc076f306b875690a3e Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Thu, 26 Nov 2026 10:28:05 +0300 Subject: [PATCH 10/27] Build Calcite at a commit that includes apache/calcite#5454 apache/calcite#5454, which fixes the four true positives this PR reports in Calcite, is merged as dde58eb5a. CI now builds Calcite at that commit, and the local copy of the patch is removed. Assisted-by: Claude Code (claude-opus-5-5) --- .../calcite/5454-nullable-bounds.patch | 50 ------------------- .github/workflows/continuous-integration.yml | 2 +- 2 files changed, 1 insertion(+), 51 deletions(-) delete mode 100644 .github/third-party/calcite/5454-nullable-bounds.patch diff --git a/.github/third-party/calcite/5454-nullable-bounds.patch b/.github/third-party/calcite/5454-nullable-bounds.patch deleted file mode 100644 index 00521615e4..0000000000 --- a/.github/third-party/calcite/5454-nullable-bounds.patch +++ /dev/null @@ -1,50 +0,0 @@ -diff --git a/core/src/main/java/org/apache/calcite/rex/RexBiVisitor.java b/core/src/main/java/org/apache/calcite/rex/RexBiVisitor.java -index 2babccb7b337..af6ef1f96f78 100644 ---- a/core/src/main/java/org/apache/calcite/rex/RexBiVisitor.java -+++ b/core/src/main/java/org/apache/calcite/rex/RexBiVisitor.java -@@ -73,6 +73,7 @@ default void visitList(Iterable exprs, P arg, - - /** Visits a list and returns a list of the results. - * The resulting list is immutable and does not contain nulls. */ -+ @SuppressWarnings("NullAway") - default List visitList(Iterable exprs, P arg) { - final List out = new ArrayList<>(); - visitList(exprs, arg, out); -diff --git a/core/src/main/java/org/apache/calcite/rex/RexVisitor.java b/core/src/main/java/org/apache/calcite/rex/RexVisitor.java -index 041662884aa3..9f98b9efb736 100644 ---- a/core/src/main/java/org/apache/calcite/rex/RexVisitor.java -+++ b/core/src/main/java/org/apache/calcite/rex/RexVisitor.java -@@ -74,6 +74,7 @@ default void visitList(Iterable exprs, List out) { - - /** Visits a list and returns a list of the results. - * The resulting list is immutable and does not contain nulls. */ -+ @SuppressWarnings("NullAway") - default List visitList(Iterable exprs) { - final List out = new ArrayList<>(); - visitList(exprs, out); -diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/Linq4j.java b/linq4j/src/main/java/org/apache/calcite/linq4j/Linq4j.java -index 93282abb7176..361b9577a9dc 100644 ---- a/linq4j/src/main/java/org/apache/calcite/linq4j/Linq4j.java -+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/Linq4j.java -@@ -109,7 +109,7 @@ public static Iterator enumeratorIterator(Enumerator enumerator) { - * - * @return enumerator - */ -- public static Enumerator iterableEnumerator( -+ public static Enumerator iterableEnumerator( - final Iterable iterable) { - if (iterable instanceof Enumerable) { - @SuppressWarnings("unchecked") final Enumerable enumerable = -diff --git a/linq4j/src/main/java/org/apache/calcite/linq4j/tree/Expressions.java b/linq4j/src/main/java/org/apache/calcite/linq4j/tree/Expressions.java -index bd4e455400a0..2da72aa4b707 100644 ---- a/linq4j/src/main/java/org/apache/calcite/linq4j/tree/Expressions.java -+++ b/linq4j/src/main/java/org/apache/calcite/linq4j/tree/Expressions.java -@@ -3154,7 +3154,7 @@ private static Class deduceType(List parameterList, - } - - /** Converts an Iterable to a List. */ -- private static List toList(Iterable iterable) { -+ private static List toList(Iterable iterable) { - if (iterable instanceof List) { - return (List) iterable; - } 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 From c5dd5dac179378dc8cf3edb7f1c4a75b6250375b Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Thu, 26 Nov 2026 13:12:55 +0300 Subject: [PATCH 11/27] Accept a capture-typed value where the same capture is expected With JSpecifyExperimental, accept(first(list)) for void accept(X x) and a List reported "passing @Nullable parameter 'first(list)'". javac infers the capture of ? extends T for X, so the parameter's type is that capture, and acceptsNoChangeValue only accepted a type variable target or the lower bound of a capture of ? super T; for a capture of ? extends T the lower bound is the null type, so the value was rejected. A target typed as a type variable, a capture included, now accepts a NO_CHANGE value that reaches it through non-nullable bounds, and a capture of ? super T also accepts a value that reaches T. The same holds for varargs, instance methods, diamonds, method references beside the call, nested generic calls, and a return of T. The PolyNull capture test now checks the result through a return rather than a local, and a new case covers an explicit <@Nullable T, String> type argument. The Javadoc of Config, ConstraintSolver.InferredNullability, Nullness.NO_CHANGE, and the TypeSubstitutionUtils inferred-nullness field now points at GenericsUtils.typeVariableWithNullableBound instead of restating it, and no longer claims more than the code does. Not changed: without JSpecifyExperimental the reports match master 594cf3dfc for these shapes. Assisted-by: Claude Code (claude-opus-5-5) --- .../main/java/com/uber/nullaway/Config.java | 25 +-- .../main/java/com/uber/nullaway/Nullness.java | 4 +- .../nullaway/generics/ConstraintSolver.java | 19 +-- .../nullaway/generics/GenericsChecks.java | 36 ++-- .../generics/TypeSubstitutionUtils.java | 7 +- .../jspecify/NullnessOperatorTests.java | 13 +- .../jspecify/PolyNullLibraryModelsTests.java | 12 +- .../uber/nullaway/jspecify/WildcardTests.java | 154 ++++++++++++++++++ 8 files changed, 220 insertions(+), 50 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/Config.java b/nullaway/src/main/java/com/uber/nullaway/Config.java index 0488f2a6f9..6e3aa2d5b7 100644 --- a/nullaway/src/main/java/com/uber/nullaway/Config.java +++ b/nullaway/src/main/java/com/uber/nullaway/Config.java @@ -320,18 +320,19 @@ public interface Config { * included, whose bound admits null? 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, as before. - * - *

Where it is true, if no constraint fixes an inference variable and such a type variable - * flows into it, the variable adds no annotation where javac inferred a type variable with - * parametric nullness or an intersection type. Elsewhere it is {@code @Nullable} where the bounds - * of both the passed type variable and the inference variable's own type parameter are explicitly - * nullable, and {@code @NonNull} otherwise. A bound is explicitly nullable where it is annotated - * {@code @Nullable}, where a library model makes it nullable, or where it is another type - * variable whose bound is 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. + * 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. */ boolean isNullableBoundInferenceEnabled(); diff --git a/nullaway/src/main/java/com/uber/nullaway/Nullness.java b/nullaway/src/main/java/com/uber/nullaway/Nullness.java index de328912a3..513b81942b 100644 --- a/nullaway/src/main/java/com/uber/nullaway/Nullness.java +++ b/nullaway/src/main/java/com/uber/nullaway/Nullness.java @@ -67,8 +67,8 @@ 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 is {@code T}, a capture included, or a + * capture of {@code ? super T}, without {@code @NonNull}, 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/ConstraintSolver.java b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java index 53c5d9a8f5..bd64e6085a 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java @@ -157,17 +157,14 @@ enum InferredNullability { 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. A bound is - * explicitly nullable where it is annotated {@code @Nullable}, where a library model makes it - * nullable, or where it is another type variable, carrying no nullness annotation, whose bound - * is explicitly nullable; a bound that admits null only because unannotated code declares the - * type variable is not. 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}. + * 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, /** 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 a151f6820c..718547e1bc 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -4968,12 +4968,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 @@ -4986,18 +4986,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); + // A capture of ? super T accepts every value of type T + return acceptsNoChangeValueOf(valueType, targetType, state) + || (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/TypeSubstitutionUtils.java b/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java index 992160740c..f7acb58e41 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java @@ -626,9 +626,10 @@ private Type restoreImplicitWildcardBound(BoundPair pair, Type targetBound, Type * 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. The destination is a declared type where {@link Config#isNullableBoundInferenceEnabled} - * is false, and then the solver produces none of these variables, and where javac's type for a - * referenced method has another number of parameters. + * 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; diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/NullnessOperatorTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/NullnessOperatorTests.java index 696efa68e6..7fca1c14cb 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/NullnessOperatorTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/NullnessOperatorTests.java @@ -12,12 +12,13 @@ * captured against one. * *

Such a value carries the JSpecify {@code NO_CHANGE} nullness operator. Wherever the same type - * variable {@code T}, or a capture of {@code ? super T}, is expected, it is accepted: as an - * argument, a return, a field or array store, and a field initializer. An argument is not accepted - * where a library model requires a non-null one. A type variable that the value's type reaches only - * through a {@code @Nullable} bound does not accept it. It stays unsafe to dereference while that - * type variable has a nullable upper bound. An explicit {@code @Nullable}, declared on the member - * or supplied by a library model, overrides that and is reported at every sink. + * variable {@code T}, a capture included, or a capture of {@code ? super T} is expected, it is + * accepted: as an argument, a return, a field or array store, and a field initializer. An argument + * is not accepted where a library model requires a non-null one. A type variable that the value's + * type reaches only through a {@code @Nullable} bound does not accept it. It stays unsafe to + * dereference while that type variable has a nullable upper bound. An explicit {@code @Nullable}, + * declared on the member or supplied by a library model, overrides that and is reported at every + * sink. * *

The tests that expect a diagnostic pin where the value stays nullable: a dereference, * unboxing, a target of a concrete type such as {@code Object}, a {@code @NonNull T} target or diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/PolyNullLibraryModelsTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/PolyNullLibraryModelsTests.java index adf5ba3a27..2aa8083655 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/PolyNullLibraryModelsTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/PolyNullLibraryModelsTests.java @@ -1484,6 +1484,10 @@ void nonNullSupplier(Optional optional, Supplier supplier) { // BUG: Diagnostic contains: dereferenced expression 'optional.orElseGet(() -> fallback)' is @Nullable optional.orElseGet(() -> fallback).hashCode(); } + void explicitlyNullableTypeArgumentForAnExplicitlyNullableBound(T t) { + // BUG: Diagnostic contains: dereferenced expression 'PolyNullMethods.<@Nullable T, String>genericFirst(t, () -> "x")' is @Nullable + PolyNullMethods.<@Nullable T, String>genericFirst(t, () -> "x").hashCode(); + } @NullUnmarked static class Unmarked { @NullMarked @@ -1513,8 +1517,12 @@ class Test { static U first(List list) { return list.get(0); } - void typeVariableResult(List list) { - T first = PolyNullMethods.genericFirst(first(list), () -> "x"); + T typeVariableResult(List list) { + return PolyNullMethods.genericFirst(first(list), () -> "x"); + } + static void accept(X x) {} + void typeVariableResultPassedToAGenericMethod(List list) { + accept(PolyNullMethods.genericFirst(first(list), () -> "x")); } void classTypeResult(List list) { // BUG: Diagnostic contains: dereferenced expression 'PolyNullMethods.genericObject(first(list), () -> "x")' is @Nullable diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java index 069b068450..a7a92805e4 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -2836,6 +2836,106 @@ void aWildcardWhoseBoundExcludesNull(Box b) { .doTest(); } + @Test + public void + aCallResultTypedAsACaptureOfAWildcardBoundedByATypeVariablePassesWhereThatCaptureIsExpected() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import java.util.function.Function; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box { + E get() { + throw new UnsupportedOperationException(); + } + } + static class Holder { + Holder(W w) {} + } + static class Sink { + void take(X x) {} + } + static U first(List list) { + throw new UnsupportedOperationException(); + } + static U get(Box b) { + throw new UnsupportedOperationException(); + } + static U getThroughWildcard(Box b) { + throw new UnsupportedOperationException(); + } + static void accept(X x) {} + static X ret(X x) { + return x; + } + @SafeVarargs + static void acceptAll(X... xs) {} + static void acceptTwo(X a, X b) {} + static B apply( + A a, Function f) { + return f.apply(a); + } + static void acceptNonNull(X x) {} + static V identity(V v) { + return v; + } + void fromAList(List list) { + accept(first(list)); + } + void fromTheSameContainer(Box b) { + accept(get(b)); + } + void fromAWildcardParameter(Box b) { + accept(getThroughWildcard(b)); + } + void intoAGenericMethodWhoseResultIsUnused(List list) { + ret(first(list)); + } + void throughTwoNestedCalls(List list) { + accept(ret(ret(first(list)))); + } + void intoAnInstanceMethod(Sink sink, List list) { + sink.take(first(list)); + } + void intoVarargs(List list) { + acceptAll(first(list)); + } + void twoCapturesOfOneWildcardType(List a, List b) { + acceptTwo(first(a), first(b)); + } + void intoADiamondConstructor(List list) { + new Holder<>(first(list)); + } + void besideAMethodReference(List list) { + apply(first(list), Test::identity); + } + void returnedAsTheTypeVariable(List list) { + accept(returnFirst(list)); + } + T returnFirst(List list) { + return first(list); + } + void readByAMemberCall(Box b) { + accept(b.get()); + } + void intoAVariableWhoseBoundExcludesNull(List list) { + // BUG: Diagnostic contains: passing @Nullable parameter 'first(list)' + acceptNonNull(first(list)); + } + void dereferenced(List list) { + // BUG: Diagnostic contains: dereferenced expression 'ret(first(list))' is @Nullable + ret(first(list)).toString(); + } + } + """) + .doTest(); + } + /** * The JSpecify JDK models decide the bound of the inference variable: {@code Arrays.asList} * admits null and {@code List.of} does not. @@ -3224,6 +3324,60 @@ void genericMethodReferenceUnderADiamond(@Nullable String s) { .doTest(); } + @Test + public void + aCaptureOfAWildcardBoundedByATypeVariableChangesNoReportWithoutJSpecifyExperimental() { + makeTestHelperWithArgs( + List.of( + "-XepOpt:NullAway:OnlyNullMarked=true", + JSpecifyJavacConfig.JSPECIFY_MODE_FLAG, + JSpecifyJavacConfig.ADD_TYPE_ANNOTATIONS_FLAG, + "-XepOpt:NullAway:HandleWildcardGenerics=true")) + .addSourceLines( + "Test.java", + """ + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box { + E get() { + throw new UnsupportedOperationException(); + } + } + static U first(List list) { + throw new UnsupportedOperationException(); + } + static X ret(X x) { + return x; + } + static void accept(X x) {} + static void nonNullParameter(Object o) {} + void callResultThroughAGenericCallDereferenced(List list) { + ret(first(list)).toString(); + } + void callResultIntoAGenericParameter(List list) { + accept(first(list)); + } + void memberCallResultIntoAGenericParameter(Box b) { + accept(b.get()); + } + Object memberCallResultReturnedThroughAGenericCall(Box b) { + return ret(b.get()); + } + T memberCallResultReturnedAsTheTypeVariable(Box b) { + return ret(b.get()); + } + void memberCallResultIntoANonNullParameter(Box b) { + // BUG: Diagnostic contains: passing @Nullable parameter 'b.get()' + nonNullParameter(b.get()); + } + } + """) + .doTest(); + } + @Test public void aTypeVariableWithANullableBoundFailsNoInferenceWithoutJSpecifyExperimental() { makeTestHelperWithArgs( From 15438baf817223ce6855b23026b689499a1a2643 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Thu, 26 Nov 2026 14:49:15 +0300 Subject: [PATCH 12/27] Name which capture accepts a NO_CHANGE value; test the ? super T bound chain The NO_CHANGE Javadoc and the NullnessOperatorTests class comment said a target typed T, "a capture included", accepts the value, which reads as any capture. Only the value's own type, a type variable that type reaches through non-nullable bounds, or a capture of ? super T accepts it. Add cases where a value reaches T only through U extends @Nullable T, directly and two bounds deep, and is passed to Function: both are reported, and a non-null chain is accepted. Assisted-by: Claude Code (claude-opus-5-5) --- .../main/java/com/uber/nullaway/Nullness.java | 6 ++++-- .../nullaway/generics/GenericsChecks.java | 2 +- .../jspecify/NullnessOperatorTests.java | 20 +++++++++++++++++-- 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/Nullness.java b/nullaway/src/main/java/com/uber/nullaway/Nullness.java index 513b81942b..2beaceeafc 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}, a capture included, or a - * capture of {@code ? super T}, without {@code @NonNull}, as {@link + * where nullness subtyping holds: where the target's type is the value's own type, such as the + * capture of {@code ? extends T} that javac infers for a generic parameter, a type variable that + * type reaches through non-nullable bounds, such as {@code T}, or a capture of {@code ? super T}, + * without {@code @NonNull}, 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/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index 718547e1bc..49ab73167f 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -4990,8 +4990,8 @@ public boolean acceptsNoChangeValue(Type valueType, ValueTarget target, VisitorS || (declaration != null && Nullness.hasNonNullAnnotation(declaration, config))) { return false; } - // A capture of ? super T accepts every value of type T 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)); } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/NullnessOperatorTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/NullnessOperatorTests.java index 7fca1c14cb..b0a225f630 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/NullnessOperatorTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/NullnessOperatorTests.java @@ -11,8 +11,9 @@ * Fails when NullAway changes how it treats a value whose type is a type variable, or a wildcard * captured against one. * - *

Such a value carries the JSpecify {@code NO_CHANGE} nullness operator. Wherever the same type - * variable {@code T}, a capture included, or a capture of {@code ? super T} is expected, it is + *

Such a value carries the JSpecify {@code NO_CHANGE} nullness operator. Wherever the value's + * own type, such as the capture of {@code ? extends T}, a type variable that type reaches through + * non-nullable bounds, such as {@code T}, or a capture of {@code ? super T} is expected, it is * accepted: as an argument, a return, a field or array store, and a field initializer. An argument * is not accepted where a library model requires a non-null one. A type variable that the value's * type reaches only through a {@code @Nullable} bound does not accept it. It stays unsafe to @@ -1162,6 +1163,21 @@ interface Box { // BUG: Diagnostic contains: passing @Nullable parameter 'box.get()' f.apply(box.get()); } + static void nonNullChain( + Box box, Function f) { + f.apply(box.get()); + } + static void nullableChain( + Box box, Function f) { + // BUG: Diagnostic contains: passing @Nullable parameter 'box.get()' + f.apply(box.get()); + } + static + void nullableChainTwoBoundsDeep( + Box box, Function f) { + // BUG: Diagnostic contains: passing @Nullable parameter 'box.get()' + f.apply(box.get()); + } } """) .doTest(); From 7c916293cbb85c0a43cfb10bfd2000d85104055e Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Thu, 26 Nov 2026 14:52:56 +0300 Subject: [PATCH 13/27] Carry nullness across a declared bound between inference variables With R viaBound(U a, U b) and a T whose bound is @Nullable, viaBound(t, "x").hashCode() was not reported, while direct(t, "x").hashCode() with R direct(R a, R b) was. The solver propagated nullness only along the edges that argument constraints add, and a declared bound between two inference variables of one call added none, so R never saw the T that U held. An explicit null was missed the same way: viaBoundOne(null).hashCode() passed. registerInferenceVariables now records U <: R where a fresh variable's bound is an unannotated use of another fresh variable of the same site, and solve() adds that edge for every variable a constraint reaches and along the chain of bounds, so the @Nullable, @NonNull, and type-variable flows all cross it. A bound annotated @Nullable, as in U extends @Nullable R, relates nothing, since U may then be null where R is not. The edges are recorded only where isNullableBoundInferenceEnabled() holds. User-visible: dereferenced expression 'viaBound(t, "x")' is @Nullable, and the same through a chain such as Q deep(U a, U b); accepted before. dereferenced expression 'viaBoundOne(null)' is @Nullable with R viaBoundOne(U a), and inference failure: type variable U constrained to be both @NonNull and @Nullable for return viaBoundOne(null); in a method returning Object; accepted before. Not changed: viaNullableBound(null).hashCode() with U extends @Nullable R is not reported. viaBoundOne(t).hashCode() with a bare T t is not reported, as directOne(t) is not: javac infers T for R (#1727). With JSpecifyMode alone, viaBound(t, "x") and viaBoundOne(null) are not reported. Assisted-by: Claude Code (claude-opus-5-5) --- .../generics/ConstraintSolverImpl.java | 31 +++++++ .../uber/nullaway/jspecify/WildcardTests.java | 86 +++++++++++++++++++ 2 files changed, 117 insertions(+) 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 1353f68a3a..0422103d4d 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,14 @@ 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. + * {@link #solve()} makes each such bound a supertype edge. 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(); @@ -134,6 +143,14 @@ 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 boundVar = inferenceVariableForUse(typeVar.getUpperBound()); + if (boundVar != null) { + declaredBounds.put(castToNonNull(inferenceVariables.get(typeVar.tsym)), boundVar); + } + } + } return fresh; } @@ -394,6 +411,20 @@ private void constrainWildcardToSupertype(WildcardType subtypeWildcard, Type sup @Override public Map solve() throws UnsatisfiableConstraintsException { + /* U extends R ⇒ U <: R, for every U that a constraint reaches and along the chain of bounds */ + 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( diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java index a7a92805e4..6729411618 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -2439,6 +2439,80 @@ void unannotatedTypeVariable(T t) { .doTest(); } + @Test + public void aNullableTypeVariableFlowsThroughADeclaredBoundToAnotherInferenceVariable() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static R direct(R a, R b) { + return a; + } + static R viaBound(U a, U b) { + return a; + } + static R viaBoundOne(U a) { + return a; + } + static Q deep(U a, U b) { + return a; + } + static R viaNullableBound(U a) { + throw new UnsupportedOperationException(); + } + static R viaNonNullBound(U a) { + return a; + } + static U viaBoundReturningU(U a, R r) { + return a; + } + void sameVariable(T t) { + // BUG: Diagnostic contains: dereferenced expression 'direct(t, "x")' is @Nullable + direct(t, "x").hashCode(); + } + void throughABound(T t) { + // BUG: Diagnostic contains: dereferenced expression 'viaBound(t, "x")' is @Nullable + viaBound(t, "x").hashCode(); + } + static R directOne(R a) { + return a; + } + void inferredAsTheTypeVariable(T t) { + // false negatives: javac infers T for R, and dataflow reads T as non-null (#1727) + directOne(t).hashCode(); + viaBoundOne(t).hashCode(); + } + void throughAChainOfBounds(T t) { + // BUG: Diagnostic contains: dereferenced expression 'deep(t, "x")' is @Nullable + deep(t, "x").hashCode(); + } + void explicitNullThroughABound() { + // BUG: Diagnostic contains: dereferenced expression 'viaBoundOne(null)' is @Nullable + viaBoundOne(null).hashCode(); + } + void explicitNullThroughANullableBound() { + viaNullableBound(null).hashCode(); + } + void explicitNullThroughANonNullBound() { + // BUG: Diagnostic contains: passing @Nullable parameter + viaNonNullBound(null).hashCode(); + } + Object throughABoundIntoANonNullTarget() { + // BUG: Diagnostic contains: inference failure: type variable U constrained to be both @NonNull and @Nullable + return viaBoundOne(null); + } + void notUpward(T t) { + viaBoundReturningU("x", t).hashCode(); + } + } + """) + .doTest(); + } + /** * A generic method reference and a generic constructor are judged against the types javac * inferred for them, as a generic method call is, so the {@code @Nullable} inferred for {@code U} @@ -3267,9 +3341,21 @@ static class ListAndElement { return u; } static void apply(A a, Function f) {} + static R viaBound(U a, U b) { + return a; + } + static R viaBoundOne(U a) { + return a; + } void typeVariable(T t) { pick(t, "x").toString(); } + void typeVariableThroughADeclaredBound(T t) { + viaBound(t, "x").toString(); + } + void nullThroughADeclaredBound() { + viaBoundOne(null).toString(); + } void typeVariableAfterRequireNonNull(T t) { T checked = Objects.requireNonNull(t); pick(checked, "x").toString(); From 79aa1c45d994d7522132012c8da194cd4c79589b Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Thu, 26 Nov 2026 15:06:32 +0300 Subject: [PATCH 14/27] Keep null-unmarked bounds out of the declared-bound edge An unmarked R choose(R r, U u) made return Legacy.choose("x", null) in a null-marked method returning Object an inference failure: the U <: R edge carried the @Nullable of null into R, though in null-unmarked code U's bound admits null and U is not a subtype of R in nullness. The solver now records a declared-bound edge only where U's declaration does not make its bound nullable (null-unmarked code, a library model, or @Nullable R), the rule GenericsChecks.reachesThroughNonNullableBounds already uses. Each inference variable's bound nullability is computed once per solver, and a variable with a declared-bound edge takes its bound variable's answer, so a chain of bounds is walked once. The edge pass is skipped where no edge was recorded. The flow of T still crosses a variable that a constraint fixed or whose bound excludes null: with a List fixing U, a null t still reaches R, since passing t for U is not checked (#1727). Not changed: fromNonNull(t, v).hashCode() with R fromNonNull(U u, List v) and a List v is reported, as map(t, v, x -> x) was at the PR head. Assisted-by: Claude Code (claude-opus-5-5) --- .../main/java/com/uber/nullaway/Config.java | 8 ++ .../generics/ConstraintSolverImpl.java | 100 ++++++++++++++---- .../uber/nullaway/jspecify/WildcardTests.java | 47 ++++++++ 3 files changed, 133 insertions(+), 22 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/Config.java b/nullaway/src/main/java/com/uber/nullaway/Config.java index 6e3aa2d5b7..4ef26b829a 100644 --- a/nullaway/src/main/java/com/uber/nullaway/Config.java +++ b/nullaway/src/main/java/com/uber/nullaway/Config.java @@ -333,6 +333,14 @@ public interface Config { * 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 as {@code U <: R}, unless the declaration of {@code U} makes its bound + * nullable, as a {@code @Nullable R} bound or unannotated code does: {@code @Nullable} and the + * flow of such a type variable pass from {@code U} to {@code R}, and {@code @NonNull} from {@code + * R} to {@code U}. So {@code viaBound(null).hashCode()} with {@code R viaBound(U u)} is reported, though no type variable whose bound admits null is + * passed. */ boolean isNullableBoundInferenceEnabled(); 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 0422103d4d..69b226a306 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java @@ -21,6 +21,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Deque; +import java.util.HashMap; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -51,12 +52,25 @@ public final class ConstraintSolverImpl implements ConstraintSolver { /** * 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. - * {@link #solve()} makes each such bound a supertype edge. Recorded only where {@link - * Config#isNullableBoundInferenceEnabled} holds. + * 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. Recorded only where {@link Config#isNullableBoundInferenceEnabled} holds. */ private final Map declaredBounds = new LinkedHashMap<>(); + /** + * Whether the bound of each inference variable admits null, by {@link + * GenericsUtils#upperBoundIsNullable}; see {@link #boundAdmitsNull}. + */ + private final Map boundAdmitsNull = new HashMap<>(); + + /** + * Whether the bound of each inference variable is explicitly nullable, by {@link + * GenericsUtils#boundIsExplicitlyNullable}; see {@link #boundIsExplicitlyNullable}. + */ + private final Map boundIsExplicitlyNullable = new HashMap<>(); + public ConstraintSolverImpl(Config config, VisitorState state, NullAway analysis) { this.config = config; this.handler = analysis.getHandler(); @@ -145,9 +159,12 @@ public Map registerInferenceVariables( } if (config.isNullableBoundInferenceEnabled()) { for (Type.TypeVar typeVar : fresh.values()) { + InferenceVariable inferenceVar = castToNonNull(inferenceVariables.get(typeVar.tsym)); InferenceVariable boundVar = inferenceVariableForUse(typeVar.getUpperBound()); - if (boundVar != null) { - declaredBounds.put(castToNonNull(inferenceVariables.get(typeVar.tsym)), boundVar); + if (boundVar != null + && !GenericsUtils.declaredUpperBoundIsNullable( + inferenceVar.typeVariable(), config, handler, state)) { + declaredBounds.put(inferenceVar, boundVar); } } } @@ -412,16 +429,18 @@ private void constrainWildcardToSupertype(WildcardType subtypeWildcard, Type sup public Map solve() throws UnsatisfiableConstraintsException { /* U extends R ⇒ U <: R, for every U that a constraint reaches and along the chain of bounds */ - 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); + 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); } - getState(sub).supertypes.add(sup); - getState(sup).subtypes.add(sub); } } @@ -497,9 +516,7 @@ public Map solve() if (!st.parametric) { yield InferredNullability.NONNULL; } - yield st.parametricNullable - && GenericsUtils.boundIsExplicitlyNullable( - inferenceVar.typeVariable(), config, handler, state) + yield st.parametricNullable && boundIsExplicitlyNullable(inferenceVar) ? InferredNullability.TYPE_VARIABLE_OR_NULLABLE : InferredNullability.TYPE_VARIABLE_OR_NONNULL; } @@ -578,11 +595,50 @@ private boolean updateNullness(InferenceVariable inferenceVar, NullnessState n) /* ───────────────────── helpers & stubs ───────────────────── */ private VarState getState(InferenceVariable inferenceVar) { - return vars.computeIfAbsent( - inferenceVar, - v -> - new VarState( - GenericsUtils.upperBoundIsNullable(v.typeVariable(), config, handler, state))); + VarState st = vars.get(inferenceVar); + if (st == null) { + st = new VarState(boundAdmitsNull(inferenceVar)); + vars.put(inferenceVar, st); + } + return st; + } + + /** + * Returns whether the bound of {@code inferenceVar} admits null, by {@link + * GenericsUtils#upperBoundIsNullable}. A variable with an edge in {@link #declaredBounds} has the + * answer of the variable its bound names, so each variable of a chain of bounds is computed once. + */ + private boolean boundAdmitsNull(InferenceVariable inferenceVar) { + Boolean known = boundAdmitsNull.get(inferenceVar); + if (known == null) { + InferenceVariable boundVar = declaredBounds.get(inferenceVar); + known = + boundVar != null + ? boundAdmitsNull(boundVar) + : GenericsUtils.upperBoundIsNullable( + inferenceVar.typeVariable(), config, handler, state); + boundAdmitsNull.put(inferenceVar, known); + } + return known; + } + + /** + * Returns whether the bound of {@code inferenceVar} is explicitly nullable, by {@link + * GenericsUtils#boundIsExplicitlyNullable}. As in {@link #boundAdmitsNull}, a variable with an + * edge in {@link #declaredBounds} has the answer of the variable its bound names. + */ + private boolean boundIsExplicitlyNullable(InferenceVariable inferenceVar) { + Boolean known = boundIsExplicitlyNullable.get(inferenceVar); + if (known == null) { + InferenceVariable boundVar = declaredBounds.get(inferenceVar); + known = + boundVar != null + ? boundIsExplicitlyNullable(boundVar) + : GenericsUtils.boundIsExplicitlyNullable( + inferenceVar.typeVariable(), config, handler, state); + boundIsExplicitlyNullable.put(inferenceVar, known); + } + return known; } /** diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java index 6729411618..d71007d57c 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -2445,6 +2445,8 @@ public void aNullableTypeVariableFlowsThroughADeclaredBoundToAnotherInferenceVar .addSourceLines( "Test.java", """ + import java.util.List; + import java.util.function.Function; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked @@ -2508,6 +2510,51 @@ Object throughABoundIntoANonNullTarget() { void notUpward(T t) { viaBoundReturningU("x", t).hashCode(); } + static R fromNonNull(U u, List v) { + return u; + } + void throughABoundFromAVariableFixedNonNull(T t, List v) { + // a null t still reaches R: passing t where U is @NonNull Object is not reported (#1727) + // BUG: Diagnostic contains: dereferenced expression 'fromNonNull(t, v)' is @Nullable + fromNonNull(t, v).hashCode(); + } + static R map( + U u, List v, Function f) { + return f.apply(u); + } + void throughALambdaFromAVariableFixedNonNull(T t, List v) { + // BUG: Diagnostic contains: dereferenced expression 'map(t, v, x -> x)' is @Nullable + map(t, v, x -> x).hashCode(); + } + static V throughNonNullBound( + U a, U b, Function f) { + return f.apply(a); + } + static V directNonNullBound( + R a, R b, Function f) { + return f.apply(a); + } + void throughAVariableWhoseBoundExcludesNull(T t) { + // BUG: Diagnostic contains: dereferenced expression 'directNonNullBound(t, "x", x -> x)' is @Nullable + directNonNullBound(t, "x", x -> x).hashCode(); + // BUG: Diagnostic contains: dereferenced expression 'throughNonNullBound(t, "x", x -> x)' is @Nullable + throughNonNullBound(t, "x", x -> x).hashCode(); + } + Object throughAnUnmarkedBound() { + // U extends R relates nothing in unannotated code, where the bound of U admits null + return Legacy.choose("fallback", null); + } + } + """) + .addSourceLines( + "Legacy.java", + """ + import org.jspecify.annotations.NullUnmarked; + @NullUnmarked + class Legacy { + static R choose(R r, U unused) { + return r; + } } """) .doTest(); From c76007452279a59011a6e7e5fa8c1e06d838ebd0 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Thu, 26 Nov 2026 15:25:30 +0300 Subject: [PATCH 15/27] Test the library-model and nested cases of declared-bound edges A bound that a library model makes nullable relates nothing, like a bound in null-unmarked code: ModeledDeclaredBound.choose("fallback", null), with a test library model on U of R choose(R r, U u), is not an inference failure. U extends @NonNull R adds no edge either. A bound that nests another variable, U extends List, adds no constraint: nestedBound(l, "x") with a List l stays unreported, a false negative the test pins. Reword the Javadoc of Config.isNullableBoundInferenceEnabled and of Nullness.NO_CHANGE so the exception and the list of accepted targets each read as one claim, and rename the solver's memo maps apart from the methods that fill them. Assisted-by: Claude Code (claude-opus-5-5) --- .../main/java/com/uber/nullaway/Config.java | 12 +++--- .../main/java/com/uber/nullaway/Nullness.java | 8 ++-- .../generics/ConstraintSolverImpl.java | 12 +++--- .../jspecify/NullnessOperatorTests.java | 18 ++++----- .../uber/nullaway/jspecify/WildcardTests.java | 37 +++++++++++++++++++ .../testlibrarymodels/TestLibraryModels.java | 1 + 6 files changed, 63 insertions(+), 25 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/Config.java b/nullaway/src/main/java/com/uber/nullaway/Config.java index 4ef26b829a..c982bdaaf8 100644 --- a/nullaway/src/main/java/com/uber/nullaway/Config.java +++ b/nullaway/src/main/java/com/uber/nullaway/Config.java @@ -335,12 +335,12 @@ public interface Config { * 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 as {@code U <: R}, unless the declaration of {@code U} makes its bound - * nullable, as a {@code @Nullable R} bound or unannotated code does: {@code @Nullable} and the - * flow of such a type variable pass from {@code U} to {@code R}, and {@code @NonNull} from {@code - * R} to {@code U}. So {@code viaBound(null).hashCode()} with {@code R viaBound(U u)} is reported, though no type variable whose bound admits null is - * passed. + * variables of one call as {@code U <: R}: {@code @Nullable} and the flow of such a type variable + * 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. A + * bound that the declaration of {@code U} makes nullable relates nothing: a {@code @Nullable R} + * bound, a library model, or unannotated code. */ boolean isNullableBoundInferenceEnabled(); diff --git a/nullaway/src/main/java/com/uber/nullaway/Nullness.java b/nullaway/src/main/java/com/uber/nullaway/Nullness.java index 2beaceeafc..8670155d83 100644 --- a/nullaway/src/main/java/com/uber/nullaway/Nullness.java +++ b/nullaway/src/main/java/com/uber/nullaway/Nullness.java @@ -67,10 +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 the value's own type, such as the - * capture of {@code ? extends T} that javac infers for a generic parameter, a type variable that - * type reaches through non-nullable bounds, such as {@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 T}, 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/ConstraintSolverImpl.java b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java index 69b226a306..db1472a2f3 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java @@ -63,13 +63,13 @@ public final class ConstraintSolverImpl implements ConstraintSolver { * Whether the bound of each inference variable admits null, by {@link * GenericsUtils#upperBoundIsNullable}; see {@link #boundAdmitsNull}. */ - private final Map boundAdmitsNull = new HashMap<>(); + private final Map boundAdmitsNullCache = new HashMap<>(); /** * Whether the bound of each inference variable is explicitly nullable, by {@link * GenericsUtils#boundIsExplicitlyNullable}; see {@link #boundIsExplicitlyNullable}. */ - private final Map boundIsExplicitlyNullable = new HashMap<>(); + private final Map boundIsExplicitlyNullableCache = new HashMap<>(); public ConstraintSolverImpl(Config config, VisitorState state, NullAway analysis) { this.config = config; @@ -609,7 +609,7 @@ private VarState getState(InferenceVariable inferenceVar) { * answer of the variable its bound names, so each variable of a chain of bounds is computed once. */ private boolean boundAdmitsNull(InferenceVariable inferenceVar) { - Boolean known = boundAdmitsNull.get(inferenceVar); + Boolean known = boundAdmitsNullCache.get(inferenceVar); if (known == null) { InferenceVariable boundVar = declaredBounds.get(inferenceVar); known = @@ -617,7 +617,7 @@ private boolean boundAdmitsNull(InferenceVariable inferenceVar) { ? boundAdmitsNull(boundVar) : GenericsUtils.upperBoundIsNullable( inferenceVar.typeVariable(), config, handler, state); - boundAdmitsNull.put(inferenceVar, known); + boundAdmitsNullCache.put(inferenceVar, known); } return known; } @@ -628,7 +628,7 @@ private boolean boundAdmitsNull(InferenceVariable inferenceVar) { * edge in {@link #declaredBounds} has the answer of the variable its bound names. */ private boolean boundIsExplicitlyNullable(InferenceVariable inferenceVar) { - Boolean known = boundIsExplicitlyNullable.get(inferenceVar); + Boolean known = boundIsExplicitlyNullableCache.get(inferenceVar); if (known == null) { InferenceVariable boundVar = declaredBounds.get(inferenceVar); known = @@ -636,7 +636,7 @@ private boolean boundIsExplicitlyNullable(InferenceVariable inferenceVar) { ? boundIsExplicitlyNullable(boundVar) : GenericsUtils.boundIsExplicitlyNullable( inferenceVar.typeVariable(), config, handler, state); - boundIsExplicitlyNullable.put(inferenceVar, known); + boundIsExplicitlyNullableCache.put(inferenceVar, known); } return known; } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/NullnessOperatorTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/NullnessOperatorTests.java index b0a225f630..96a4c07bde 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/NullnessOperatorTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/NullnessOperatorTests.java @@ -11,15 +11,15 @@ * Fails when NullAway changes how it treats a value whose type is a type variable, or a wildcard * captured against one. * - *

Such a value carries the JSpecify {@code NO_CHANGE} nullness operator. Wherever the value's - * own type, such as the capture of {@code ? extends T}, a type variable that type reaches through - * non-nullable bounds, such as {@code T}, or a capture of {@code ? super T} is expected, it is - * accepted: as an argument, a return, a field or array store, and a field initializer. An argument - * is not accepted where a library model requires a non-null one. A type variable that the value's - * type reaches only through a {@code @Nullable} bound does not accept it. It stays unsafe to - * dereference while that type variable has a nullable upper bound. An explicit {@code @Nullable}, - * declared on the member or supplied by a library model, overrides that and is reported at every - * sink. + *

Such a value carries the JSpecify {@code NO_CHANGE} nullness operator. It is accepted where + * the expected type is the value's own type (for example the capture of {@code ? extends T}), a + * type variable that the value's type reaches through non-nullable bounds (for example {@code T}), + * or a capture of {@code ? super T}: as an argument, a return, a field or array store, and a field + * initializer. An argument is not accepted where a library model requires a non-null one. A type + * variable that the value's type reaches only through a {@code @Nullable} bound does not accept it. + * It stays unsafe to dereference while that type variable has a nullable upper bound. An explicit + * {@code @Nullable}, declared on the member or supplied by a library model, overrides that and is + * reported at every sink. * *

The tests that expect a diagnostic pin where the value stays nullable: a dereference, * unboxing, a target of a concrete type such as {@code Object}, a {@code @NonNull T} target or diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java index d71007d57c..dc28138b9f 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -2447,6 +2447,7 @@ public void aNullableTypeVariableFlowsThroughADeclaredBoundToAnotherInferenceVar """ import java.util.List; import java.util.function.Function; + import org.jspecify.annotations.NonNull; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked @@ -2540,12 +2541,48 @@ void throughAVariableWhoseBoundExcludesNull(T t) { // BUG: Diagnostic contains: dereferenced expression 'throughNonNullBound(t, "x", x -> x)' is @Nullable throughNonNullBound(t, "x", x -> x).hashCode(); } + static R viaNonNullAnnotatedBound(U a) { + return a; + } + Object explicitNullThroughANonNullAnnotatedBound() { + // BUG: Diagnostic contains: passing @Nullable parameter 'null' + return viaNonNullAnnotatedBound(null); + } + static > R nestedBound( + U u, R r) { + throw new UnsupportedOperationException(); + } + static R nestedArgument(List l, R r) { + throw new UnsupportedOperationException(); + } + void throughABoundThatNestsTheVariable(List l) { + // BUG: Diagnostic contains: dereferenced expression 'nestedArgument(l, "x")' is @Nullable + nestedArgument(l, "x").hashCode(); + // a false negative: inference takes no constraint from a bound that nests R (#NNNN) + nestedBound(l, "x").hashCode(); + } Object throughAnUnmarkedBound() { // U extends R relates nothing in unannotated code, where the bound of U admits null return Legacy.choose("fallback", null); } } """) + .addSourceLines( + "ModeledDeclaredBound.java", + """ + package com.uber; + import org.jspecify.annotations.NullMarked; + @NullMarked + class ModeledDeclaredBound { + // The test library model makes the bound of U nullable, so U extends R relates nothing. + static R choose(R r, U u) { + return r; + } + Object throughAModeledBound() { + return choose("fallback", null); + } + } + """) .addSourceLines( "Legacy.java", """ diff --git a/test-library-models/src/main/java/com/uber/nullaway/testlibrarymodels/TestLibraryModels.java b/test-library-models/src/main/java/com/uber/nullaway/testlibrarymodels/TestLibraryModels.java index 4659ee798e..5b753f1a6f 100644 --- a/test-library-models/src/main/java/com/uber/nullaway/testlibrarymodels/TestLibraryModels.java +++ b/test-library-models/src/main/java/com/uber/nullaway/testlibrarymodels/TestLibraryModels.java @@ -367,6 +367,7 @@ public ImmutableSetMultimap methodTypeVariablesWithNullableU 0) .put(methodRef("com.uber.lib.unannotated.ProviderNullMarkedViaModel", "of(U)"), 0) .put(methodRef("com.uber.ModeledIntersectionBounds", "identity(T)"), 0) + .put(methodRef("com.uber.ModeledDeclaredBound", "choose(R,U)"), 1) .put( methodRef( "com.uber.lib.unannotated.NestedAnnots", "genericMethod(java.lang.Class)"), From 5d871feac2ba8bf8e7d77107844bbbbf650ed0f6 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Thu, 26 Nov 2026 15:31:53 +0300 Subject: [PATCH 16/27] Name every ? super target that accepts a NO_CHANGE value; test the gate without JSpecifyExperimental The NO_CHANGE Javadoc in Nullness and NullnessOperatorTests now lists a capture of ? super of the value's own type or of a type variable the value's type reaches through non-nullable bounds, and superOfAChainVariable pins the second case. The Config and ConstraintSolver.solve() Javadoc say a declared-bound edge exists only for an unannotated R and that solve() also returns the variables reached through declared bounds. The test without JSpecifyExperimental gains the viaBound and viaBoundOne(null) controls. Assisted-by: Claude Code (claude-opus-5-5) --- .../src/main/java/com/uber/nullaway/Config.java | 12 ++++++------ .../main/java/com/uber/nullaway/Nullness.java | 2 +- .../uber/nullaway/generics/ConstraintSolver.java | 4 +++- .../nullaway/jspecify/NullnessOperatorTests.java | 16 ++++++++++------ .../uber/nullaway/jspecify/WildcardTests.java | 12 ++++++++++++ 5 files changed, 32 insertions(+), 14 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/Config.java b/nullaway/src/main/java/com/uber/nullaway/Config.java index c982bdaaf8..22e34a7509 100644 --- a/nullaway/src/main/java/com/uber/nullaway/Config.java +++ b/nullaway/src/main/java/com/uber/nullaway/Config.java @@ -335,12 +335,12 @@ public interface Config { * 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 as {@code U <: R}: {@code @Nullable} and the flow of such a type variable - * 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. A - * bound that the declaration of {@code U} makes nullable relates nothing: a {@code @Nullable R} - * bound, a library model, or unannotated code. + * variables of one call, with no annotation on {@code R}, as {@code U <: R}: {@code @Nullable} + * and the flow of such a type variable 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. A bound that the declaration of {@code U} makes nullable + * relates nothing: a {@code @Nullable R} bound, a library model, or unannotated code. */ boolean isNullableBoundInferenceEnabled(); diff --git a/nullaway/src/main/java/com/uber/nullaway/Nullness.java b/nullaway/src/main/java/com/uber/nullaway/Nullness.java index 8670155d83..90679ba9ee 100644 --- a/nullaway/src/main/java/com/uber/nullaway/Nullness.java +++ b/nullaway/src/main/java/com/uber/nullaway/Nullness.java @@ -70,7 +70,7 @@ public enum Nullness implements AbstractValue { * 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 T}, as {@link + * (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/ConstraintSolver.java b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java index bd64e6085a..b99f72d6ad 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java @@ -182,7 +182,9 @@ enum InferredNullability { /** * 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, in the declared bound of such + * a variable. * * @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/test/java/com/uber/nullaway/jspecify/NullnessOperatorTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/NullnessOperatorTests.java index 96a4c07bde..b6d8ffdf20 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/NullnessOperatorTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/NullnessOperatorTests.java @@ -14,12 +14,12 @@ *

Such a value carries the JSpecify {@code NO_CHANGE} nullness operator. It is accepted where * the expected type is the value's own type (for example the capture of {@code ? extends T}), a * type variable that the value's type reaches through non-nullable bounds (for example {@code T}), - * or a capture of {@code ? super T}: as an argument, a return, a field or array store, and a field - * initializer. An argument is not accepted where a library model requires a non-null one. A type - * variable that the value's type reaches only through a {@code @Nullable} bound does not accept it. - * It stays unsafe to dereference while that type variable has a nullable upper bound. An explicit - * {@code @Nullable}, declared on the member or supplied by a library model, overrides that and is - * reported at every sink. + * or a capture of {@code ? super} either of those types: as an argument, a return, a field or array + * store, and a field initializer. An argument is not accepted where a library model requires a + * non-null one. A type variable that the value's type reaches only through a {@code @Nullable} + * bound does not accept it. It stays unsafe to dereference while that type variable has a nullable + * upper bound. An explicit {@code @Nullable}, declared on the member or supplied by a library + * model, overrides that and is reported at every sink. * *

The tests that expect a diagnostic pin where the value stays nullable: a dereference, * unboxing, a target of a concrete type such as {@code Object}, a {@code @NonNull T} target or @@ -1167,6 +1167,10 @@ interface Box { Box box, Function f) { f.apply(box.get()); } + static void superOfAChainVariable( + Box box, Function f) { + f.apply(box.get()); + } static void nullableChain( Box box, Function f) { // BUG: Diagnostic contains: passing @Nullable parameter 'box.get()' diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java index dc28138b9f..4875276777 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -3580,9 +3580,21 @@ void typeVariable(Box b) { void typeVariableIntoADiamond(Box b) { var c = new GenericConstructor<>(b); } + static R viaBound(U a, U b) { + return a; + } + static R viaBoundOne(U a) { + return a; + } void typeVariableIntoAClassTypeResult(T t) { pick(t, "x").toString(); } + void typeVariableThroughADeclaredBound(T t) { + viaBound(t, "x").toString(); + } + void nullThroughADeclaredBound() { + viaBoundOne(null).toString(); + } void nullableTypeArgument(Box<@Nullable String> b) { // BUG: Diagnostic contains: inference failure Object o = nonNullVariable(b); From a0fa9214ed25e8bd5a9e98a78bfc968e90f19e28 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Thu, 26 Nov 2026 16:57:25 +0300 Subject: [PATCH 17/27] Link the nested-bound false negative to #2192 Assisted-by: Claude Code (claude-opus-5-5) --- .../src/test/java/com/uber/nullaway/jspecify/WildcardTests.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java index 4875276777..a7ee8a6e80 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -2558,7 +2558,7 @@ Object explicitNullThroughANonNullAnnotatedBound() { void throughABoundThatNestsTheVariable(List l) { // BUG: Diagnostic contains: dereferenced expression 'nestedArgument(l, "x")' is @Nullable nestedArgument(l, "x").hashCode(); - // a false negative: inference takes no constraint from a bound that nests R (#NNNN) + // a false negative: inference takes no constraint from a bound that nests R (#2192) nestedBound(l, "x").hashCode(); } Object throughAnUnmarkedBound() { From d0ad3f0ceafd2ba0f277b9fcf37a6e21ba2cca49 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Thu, 26 Nov 2026 17:01:58 +0300 Subject: [PATCH 18/27] Drop the bound-nullability memo from the constraint solver The memo maps returned the answers GenericsUtils.upperBoundIsNullable and boundIsExplicitlyNullable already give: a declared-bound edge U -> R is recorded only where U's bound is an unannotated use of R, and both helpers then recurse into R themselves. A solver serves one call, so without the memo the walk costs at most quadratic time in the type parameters of one declaration, as before this change, and does not grow with the checked code. getState and the solution builder call GenericsUtils directly again. Assisted-by: Claude Code (claude-opus-5-5) --- .../generics/ConstraintSolverImpl.java | 66 +++---------------- 1 file changed, 8 insertions(+), 58 deletions(-) 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 db1472a2f3..e9bd16297f 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java @@ -21,7 +21,6 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Deque; -import java.util.HashMap; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -59,18 +58,6 @@ public final class ConstraintSolverImpl implements ConstraintSolver { */ private final Map declaredBounds = new LinkedHashMap<>(); - /** - * Whether the bound of each inference variable admits null, by {@link - * GenericsUtils#upperBoundIsNullable}; see {@link #boundAdmitsNull}. - */ - private final Map boundAdmitsNullCache = new HashMap<>(); - - /** - * Whether the bound of each inference variable is explicitly nullable, by {@link - * GenericsUtils#boundIsExplicitlyNullable}; see {@link #boundIsExplicitlyNullable}. - */ - private final Map boundIsExplicitlyNullableCache = new HashMap<>(); - public ConstraintSolverImpl(Config config, VisitorState state, NullAway analysis) { this.config = config; this.handler = analysis.getHandler(); @@ -516,7 +503,9 @@ public Map solve() if (!st.parametric) { yield InferredNullability.NONNULL; } - yield st.parametricNullable && boundIsExplicitlyNullable(inferenceVar) + yield st.parametricNullable + && GenericsUtils.boundIsExplicitlyNullable( + inferenceVar.typeVariable(), config, handler, state) ? InferredNullability.TYPE_VARIABLE_OR_NULLABLE : InferredNullability.TYPE_VARIABLE_OR_NONNULL; } @@ -595,50 +584,11 @@ private boolean updateNullness(InferenceVariable inferenceVar, NullnessState n) /* ───────────────────── helpers & stubs ───────────────────── */ private VarState getState(InferenceVariable inferenceVar) { - VarState st = vars.get(inferenceVar); - if (st == null) { - st = new VarState(boundAdmitsNull(inferenceVar)); - vars.put(inferenceVar, st); - } - return st; - } - - /** - * Returns whether the bound of {@code inferenceVar} admits null, by {@link - * GenericsUtils#upperBoundIsNullable}. A variable with an edge in {@link #declaredBounds} has the - * answer of the variable its bound names, so each variable of a chain of bounds is computed once. - */ - private boolean boundAdmitsNull(InferenceVariable inferenceVar) { - Boolean known = boundAdmitsNullCache.get(inferenceVar); - if (known == null) { - InferenceVariable boundVar = declaredBounds.get(inferenceVar); - known = - boundVar != null - ? boundAdmitsNull(boundVar) - : GenericsUtils.upperBoundIsNullable( - inferenceVar.typeVariable(), config, handler, state); - boundAdmitsNullCache.put(inferenceVar, known); - } - return known; - } - - /** - * Returns whether the bound of {@code inferenceVar} is explicitly nullable, by {@link - * GenericsUtils#boundIsExplicitlyNullable}. As in {@link #boundAdmitsNull}, a variable with an - * edge in {@link #declaredBounds} has the answer of the variable its bound names. - */ - private boolean boundIsExplicitlyNullable(InferenceVariable inferenceVar) { - Boolean known = boundIsExplicitlyNullableCache.get(inferenceVar); - if (known == null) { - InferenceVariable boundVar = declaredBounds.get(inferenceVar); - known = - boundVar != null - ? boundIsExplicitlyNullable(boundVar) - : GenericsUtils.boundIsExplicitlyNullable( - inferenceVar.typeVariable(), config, handler, state); - boundIsExplicitlyNullableCache.put(inferenceVar, known); - } - return known; + return vars.computeIfAbsent( + inferenceVar, + v -> + new VarState( + GenericsUtils.upperBoundIsNullable(v.typeVariable(), config, handler, state))); } /** From 145d3ed1406912f958141a7b27fa9da89fed1f6c Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Thu, 26 Nov 2026 17:35:51 +0300 Subject: [PATCH 19/27] State the declared-bound edge rule once, with its chain closure The solve() Javadoc said the solution map held only constrained variables and the declared bound of such a variable, but solve() follows the whole chain of declared bounds, so Q in is in the map too. The Config.isNullableBoundInferenceEnabled Javadoc described the excluded bounds as one that "relates nothing", which names no mechanism, and its summary did not mention the declared-bound edge at all. The declaredBounds Javadoc now states when U <: R is read and that solve() adds it for every variable that appears in a constraint or that an earlier edge reaches; solve(), Config, the inline comment in solve(), and the two test comments state the same rule in the same words. Assisted-by: Claude Code (claude-opus-5-5) --- .../main/java/com/uber/nullaway/Config.java | 19 +++++++++++-------- .../nullaway/generics/ConstraintSolver.java | 5 +++-- .../generics/ConstraintSolverImpl.java | 6 ++++-- .../uber/nullaway/jspecify/WildcardTests.java | 4 ++-- 4 files changed, 20 insertions(+), 14 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/Config.java b/nullaway/src/main/java/com/uber/nullaway/Config.java index 22e34a7509..2a7855d109 100644 --- a/nullaway/src/main/java/com/uber/nullaway/Config.java +++ b/nullaway/src/main/java/com/uber/nullaway/Config.java @@ -317,10 +317,11 @@ public interface Config { /** * Should generic inference account for the nullness of an unannotated type variable, a capture - * included, whose bound admits null? 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. + * 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 @@ -335,12 +336,14 @@ public interface Config { * 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, with no annotation on {@code R}, as {@code U <: R}: {@code @Nullable} - * and the flow of such a type variable pass from {@code U} to {@code R}, and {@code @NonNull} + * 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. A bound that the declaration of {@code U} makes nullable - * relates nothing: a {@code @Nullable R} bound, a library model, or unannotated code. + * 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(); 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 b99f72d6ad..c07b54d601 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java @@ -183,8 +183,9 @@ enum InferredNullability { /** * Solve the constraints, returning a map from inference variables to their inferred nullability. * The map only contains inference variables that appear in constraints or, where {@link - * com.uber.nullaway.Config#isNullableBoundInferenceEnabled} holds, in the declared bound of such - * a variable. + * 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 e9bd16297f..6210eb1a13 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java @@ -54,7 +54,9 @@ public final class ConstraintSolverImpl implements ConstraintSolver { * 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. Recorded only where {@link Config#isNullableBoundInferenceEnabled} holds. + * 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<>(); @@ -415,7 +417,7 @@ private void constrainWildcardToSupertype(WildcardType subtypeWildcard, Type sup @Override public Map solve() throws UnsatisfiableConstraintsException { - /* U extends R ⇒ U <: R, for every U that a constraint reaches and along the chain of bounds */ + /* 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++) { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java index a7ee8a6e80..a81a1b4476 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -2562,7 +2562,7 @@ void throughABoundThatNestsTheVariable(List l) { nestedBound(l, "x").hashCode(); } Object throughAnUnmarkedBound() { - // U extends R relates nothing in unannotated code, where the bound of U admits null + // inference reads no U <: R where U is declared in unannotated code return Legacy.choose("fallback", null); } } @@ -2574,7 +2574,7 @@ Object throughAnUnmarkedBound() { import org.jspecify.annotations.NullMarked; @NullMarked class ModeledDeclaredBound { - // The test library model makes the bound of U nullable, so U extends R relates nothing. + // The test library model makes the bound of U nullable, so inference reads no U <: R. static R choose(R r, U u) { return r; } From 6ba479823702b82dca68d79f6bb9cbf96e007264 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Wed, 9 Sep 2026 17:32:42 +0300 Subject: [PATCH 20/27] Report a generic nullability mismatch as a marked diff of the two types Passing a List to Collection.addAll in @NullMarked code was reported as "incompatible types: List cannot be converted to Collection (List is a subtype of Collection)". The report is correct: an unbounded wildcard takes the upper bound of the type variable it instantiates, and E of List has a @Nullable Object bound in the JSpecify JDK model, while ? extends Object requires a non-null element. Nothing in the message said so, and the parenthetical read as a contradiction (#1822). The shape was the wider problem: two types printed in full, one difference named out of however many failed, and nothing to diff them by once the difference is a @Nullable three levels down. The message is now built from the positions where the two types differ in nullness, which a traversal of the target and the source records as the smallest pair of nodes that still differs. It carries a summary, the two types with a caret under each position at fault, an entry per position naming it in words, and the types to write instead. The summary opens "incompatible nullability:", so the leading text of every generic nullness diagnostic changes, and the two types move into found and required below it. It states the two nodes rather than calling one unassignable to the other, because the difference runs both ways; in the direction that would read as a false subtype claim it says first that a type argument must match exactly. A caret marks the smallest node that differs, in both types. Which node of the source as written it belongs under has two answers, since the comparison views that source as the target's supertype: where the view is the same class, the position is the same position, and 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 "found as" and carries the carets. A path line names the position in words and wraps at its separators, and a note says where a wildcard takes an implicit bound from, naming the type parameter where that parameter is one the message prints and stating the bound alone where it is not. Two repairs are offered, and each is checked before it is printed: the candidate goes to the predicate that rejected the assignment, it has to print as Java a reader could write, and it has to survive printing with its type-use annotations. They differ in what they presume. Writing an explicit bound on a wildcard the reader already wrote repairs that wildcard, so it is offered wherever it works. Changing the required type is a claim about which side of a contract is wrong, so it is offered only where that type is written at the diagnostic itself, and it only ever adds @Nullable. Where the traversal locates no difference, which is what a ? super containment failure looks like from here, the message falls back to the two types and the subtype relation between them. Fixes #1822 Assisted-by: Claude Code (claude-fable-5-1) Assisted-by: Claude Code (claude-opus-5) --- .../GenericTypePrettyPrintingVisitor.java | 108 ++- .../nullaway/generics/GenericsChecks.java | 181 +--- .../generics/NullabilityMismatchMessage.java | 809 ++++++++++++++++++ .../generics/NullabilityMismatches.java | 309 +++++++ .../com/uber/nullaway/generics/TypePath.java | 117 +++ .../uber/nullaway/JSpecifyJDKModelsTest.java | 4 +- .../jspecify/BytecodeGenericsTests.java | 10 +- .../jspecify/GenericDiamondTests.java | 22 +- .../jspecify/GenericInheritanceTests.java | 8 +- ...enericMethodLambdaOrMethodRefArgTests.java | 2 +- .../nullaway/jspecify/GenericMethodTests.java | 64 +- .../uber/nullaway/jspecify/GenericsTests.java | 100 +-- .../nullaway/jspecify/JSpecifyArrayTests.java | 20 +- .../StreamNullabilityPropagatorTests.java | 4 +- 14 files changed, 1466 insertions(+), 292 deletions(-) create mode 100644 nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java create mode 100644 nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java create mode 100644 nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java 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 49ab73167f..597062b33f 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -459,7 +459,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( @@ -467,178 +469,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)); @@ -670,8 +508,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)); @@ -4826,9 +4664,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); } 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..8b454e0397 --- /dev/null +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -0,0 +1,809 @@ +package com.uber.nullaway.generics; + +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. Where the source wildcard + * stands at a position of the type the reader wrote, the note names the type parameter it takes its + * bound from. Where the source was viewed as a supertype, 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} as a {@code Base} keeps + * the wildcard and changes the type printed around it. 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 wildcard takes its upper bound from, or returns {@code null} where the + * printed type already shows that bound or the type variable cannot be named. + * + *

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) { + return 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 once that source is viewed as a + // supertype, 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) { + IdentityHashMap replacements = new IdentityHashMap<>(); + for (NullabilityMismatches.Mismatch mismatch : mismatches) { + Type rewritten = withNullableAddedFrom(mismatch.sourceNode(), mismatch.targetNode()); + if (rewritten == null) { + return null; + } + replacements.put(mismatch.targetNode(), rewritten); + } + if (replacements.isEmpty()) { + return null; + } + Type rewrittenTargetType = replaceNodes(targetType, replacements); + 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 each node in {@code replacements} replaced by its new form. */ + private static Type replaceNodes(Type type, IdentityHashMap replacements) { + return type.accept( + new Type.StructuralTypeMapping<@Nullable Void>() { + private Type replaced(Type t, java.util.function.Supplier otherwise) { + Type replacement = replacements.get(t); + return replacement != null ? replacement : otherwise.get(); + } + + @Override + public Type visitClassType(Type.ClassType t, @Nullable Void unused) { + return replaced(t, () -> super.visitClassType(t, null)); + } + + @Override + public Type visitWildcardType(Type.WildcardType t, @Nullable Void unused) { + return replaced(t, () -> super.visitWildcardType(t, null)); + } + + @Override + public Type visitArrayType(Type.ArrayType t, @Nullable Void unused) { + return replaced(t, () -> super.visitArrayType(t, null)); + } + + @Override + public Type visitTypeVar(Type.TypeVar t, @Nullable Void unused) { + return replaced(t, () -> super.visitTypeVar(t, null)); + } + }, + null); + } + + /** + * 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..aec34c09c8 --- /dev/null +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java @@ -0,0 +1,309 @@ +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.List; +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; + + 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) { + // 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); + 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 + 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; + } + 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/TypePath.java b/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java new file mode 100644 index 0000000000..469d67745a --- /dev/null +++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java @@ -0,0 +1,117 @@ +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()); + } + + 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/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 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/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/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/GenericMethodLambdaOrMethodRefArgTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java index 1db7695fa4..87f196064d 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java @@ -1337,7 +1337,7 @@ void testNegative() { receiver(makeCancelable(this::target)); } void testPositive() { - // BUG: Diagnostic contains: incompatible types: Callback cannot be converted to Callback<@Nullable Object> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object receiver(makeCancelable(this::targetNonNullParam)); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java index 3ef81452f2..6f3f7fb265 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java @@ -958,7 +958,7 @@ static void testLocalAssign() { Foo<@Nullable Object> f5 = Foo.makeNonNull(null); // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required Foo f6 = Foo.makeNonNull(null); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object Foo<@Nullable Object> f7 = Foo.makeNonNull(new Object()); Foo f8 = Foo.makeNonNull(new Object()); } @@ -1013,7 +1013,7 @@ static class Foo { static void test(Foo<@Nullable Object> f1, Foo f2) { // no error expected Foo<@Nullable Object> result = Foo.create(null, f1); - // BUG: Diagnostic contains: incompatible types: Foo cannot be converted to Foo<@Nullable Object> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object Foo<@Nullable Object> result2 = Foo.create(null, f2); } } @@ -1100,9 +1100,9 @@ abstract class Foo { } static void test(Foo f) { Foo> fooNonNull_1 = f.nonNullTest(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String Foo> fooNonNull_2 = f.nonNullTest(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Integer, required @Nullable Integer Foo<@Nullable Integer, ArrayList> fooNonNull_3 = f.nonNullTest(); Foo> fooNull_1 = f.nullTest(); Foo> fooNull_2 = f.nullTest(); @@ -1144,7 +1144,7 @@ static void testLocalAssign() { Foo[]> f3 = Foo.test1Null(null); Foo[]> f4 = Foo.test1Null(null); Foo[]> f5 = Foo.test1Nonnull(new Object()); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object Foo[]> f6 = Foo.test1Nonnull(new Object()); // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required Foo[]> f7 = Foo.test1Nonnull(null); @@ -1156,7 +1156,7 @@ static void testLocalAssign() { Foo[] f11 = Foo.test2Null(null); Foo<@Nullable Object>[] f12 = Foo.test2Null(null); Foo[] f13 = Foo.test2Nonnull(new Object()); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object Foo<@Nullable Object>[] f14 = Foo.test2Nonnull(new Object()); // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required Foo[] f15 = Foo.test2Nonnull(null); @@ -1180,7 +1180,7 @@ abstract class TestCase { static class Bar {} abstract Bar make(Bar other); void test(Bar> other) { - // BUG: Diagnostic contains: incompatible types: Bar> cannot be converted to Bar> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String Bar> unused = make(other); } } @@ -1293,7 +1293,7 @@ void testNegative(Function<@Nullable String, @Nullable String> f) { this.foo(f); } void testPositive(Function f) { - // BUG: Diagnostic contains: incompatible types: Function cannot be converted to + // BUG: Diagnostic contains: incompatible nullability: 2 mismatches between source and target types this.foo(f); } void testPositive2(Function<@Nullable String, @Nullable String> f) { @@ -1456,7 +1456,7 @@ static Foo makeNullInvalid() { return Foo.makeNonNull(null); } static Foo<@Nullable Object> makeNonNullInvalid2() { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object return Foo.makeNonNull(new Object()); } static Foo makeNonNullValid() { @@ -1498,7 +1498,7 @@ static void testCalls() { handleFooNullable(Foo.makeNonNull(null)); // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required handleFooNonNull(Foo.makeNonNull(null)); - // BUG: Diagnostic contains: incompatible types: Foo + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object handleFooNullable(Foo.makeNonNull(new Object())); handleFooNonNull(Foo.makeNonNull(new Object())); } @@ -1515,7 +1515,7 @@ static void testVarargsCalls() { handleFooNullableVarargs(Foo.makeNonNull(null)); // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required handleFooNonNullVarargs(Foo.makeNonNull(null)); - // BUG: Diagnostic contains: incompatible types: Foo + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object handleFooNullableVarargs(Foo.makeNonNull(new Object())); handleFooNonNullVarargs(Foo.makeNonNull(new Object())); } @@ -1928,7 +1928,7 @@ static class Foo {} } Foo foo1 = make(new String[] { "hello", "world" }); Foo<@Nullable String> foo2 = make(new @Nullable String[] { "hello", null, "world" }); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Foo foo3 = make(new @Nullable String[] { "hello", null, "world" }); Foo<@Nullable String> foo4 = make(new String[] { "hello", "world" }); } @@ -2030,7 +2030,7 @@ void test(String[] arr, @Nullable String[] arr2) { String s2 = f(arr, "hi"); // legal s2.hashCode(); - // BUG: Diagnostic contains: incompatible types: @Nullable String [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String stringField = f(arr2, "hi"); } } @@ -2237,6 +2237,19 @@ static void testParam() { @Test public void capturedTypeAtNullUnmarkedBoundary() { makeHelper() + .expectErrorMessage( + "CAPTURE_FROM_UNMARKED", + message -> + message.contains( + """ + incompatible nullability: found @Nullable Object, required Object + found: Foo<@Nullable capture of ?> + ^^^^^^^^^^^^^^^^^^^^^^ + required: Foo + ^ + path: Foo type argument T -> wildcard upper bound + note: the source wildcard is the type argument for type parameter T of Box, and Box is unannotated + """)) .addSourceLines( "Test.java", """ @@ -2262,7 +2275,7 @@ static Foo convert(Box box) { static Foo getReturnType() { var returnType = Api.convert(Api.wildcard()); - // BUG: Diagnostic contains: incompatible types: Foo cannot be converted to Foo (target wildcard upper bound is Object; source wildcard upper bound is @Nullable Object; source wildcard is the type argument for type variable T of Box) + // BUG: Diagnostic matches: CAPTURE_FROM_UNMARKED return returnType; } } @@ -2273,6 +2286,19 @@ static Foo getReturnType() { @Test public void capturedTypeGetsDirectNullableAnnotationFromTypeVariableUse() { makeHelper() + .expectErrorMessage( + "CAPTURE_FROM_MARKED", + message -> + message.contains( + """ + incompatible nullability: found @Nullable Object, required Object + found: Foo<@Nullable capture of ?> + ^^^^^^^^^^^^^^^^^^^^^^ + required: Foo + ^^^^^^ + path: Foo type argument T -> wildcard upper bound + note: the source wildcard is the type argument for type parameter T of Holder + """)) .addSourceLines( "Test.java", """ @@ -2290,7 +2316,7 @@ static class Holder { } static Foo test(Holder holder) { - // BUG: Diagnostic contains: incompatible types: Foo<@Nullable capture of ?> cannot be converted to Foo (target wildcard upper bound is Object; source wildcard upper bound is @Nullable Object; source wildcard is the type argument for type variable T of Holder) + // BUG: Diagnostic matches: CAPTURE_FROM_MARKED return holder.value; } } @@ -2426,7 +2452,7 @@ class Test { class Box {} void swapBoxes(Box box1, Box box2) {} void testPositive(Box box1, Box<@Nullable String> box2) { - // BUG: Diagnostic contains: incompatible types: Test.Box<@Nullable String> cannot be converted to Test.Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String swapBoxes(box1, box2); } void TestNegative(Box<@Nullable String> box1, Box<@Nullable String> box2) { @@ -2521,7 +2547,7 @@ Supplier make2() { } // tests that our repair computes a consistent substitution for the type variables void test2() { - // BUG: Diagnostic contains: incompatible types: Supplier cannot be converted to Supplier<@Nullable OuterT> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found OuterT, required @Nullable OuterT acceptTwoSup(sup, sup2); } } @@ -2653,7 +2679,7 @@ static class Foo { .or(new Foo<@Nullable String>()); // a true positive case - // BUG: Diagnostic contains: incompatible types: Foo<@Nullable String> cannot be converted to Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String static Foo WRONG = Foo.of(new Foo<@Nullable String>()).or(new Foo<@Nullable String>()); } @@ -2709,7 +2735,7 @@ class Test { static class Box {} static void accept(Box<@Nullable T> box) {} void test(Box> box) { - // BUG: Diagnostic contains: incompatible types: Box> cannot be converted to Box<@Nullable CompletableFuture> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found CompletableFuture, required @Nullable CompletableFuture accept(box); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java index b8f9a0b6fb..0afa2bc72c 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java @@ -52,7 +52,7 @@ static void testBadNonNull(NonNullTypeParam t) { // BUG: Diagnostic contains: Generic type parameter testBadNonNull(new NonNullTypeParam<@Nullable String>()); testBadNonNull( - // BUG: Diagnostic contains: incompatible types: NonNullTypeParam<@Nullable String> + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String new NonNullTypeParam< // BUG: Diagnostic contains: Generic type parameter @Nullable String>()); @@ -288,17 +288,17 @@ abstract class Fn { static void param(Wrapper.@Nullable Fn p) {} static void positiveParam() { Wrapper<@Nullable String>.Fn x = null; - // BUG: Diagnostic contains: incompatible types: Test.Wrapper<@Nullable String>.Fn + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Test.Wrapper<@Nullable String>.Fn, required Test.Wrapper.@Nullable Fn param(x); } static void positiveAssign() { Wrapper<@Nullable String>.Fn p1 = null; - // BUG: Diagnostic contains: incompatible types: Test.Wrapper<@Nullable String>.Fn cannot be converted to Test.Wrapper.Fn + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Wrapper.Fn p2 = p1; } static Wrapper.@Nullable Fn positiveReturn() { Wrapper<@Nullable String>.Fn p1 = null; - // BUG: Diagnostic contains: incompatible types: Test.Wrapper<@Nullable String>.Fn + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Test.Wrapper<@Nullable String>.Fn, required Test.Wrapper.@Nullable Fn return p1; } static void negativeParam() { @@ -349,11 +349,11 @@ void callOnResult() { } public void testPositive() { addCallback( - // BUG: Diagnostic contains: incompatible types: Callback cannot be converted to Callback<@Nullable Integer> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Integer, required @Nullable Integer new Callback() { @Override public void onResult(Integer value) { - // BUG: Diagnostic contains: incompatible types: Callback cannot be converted to Callback<@Nullable Integer> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Integer, required @Nullable Integer removeCallback(this); // BUG: Diagnostic contains: incompatible types: Callback cannot be converted to Callback<@Nullable Integer> Callback<@Nullable Integer> self = this; @@ -457,7 +457,7 @@ public void genericsChecksForAssignments() { class Test { static class NullableTypeParam {} 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) { @@ -480,7 +480,7 @@ class Test { static class NullableTypeParam {} static void testNoWarningForMismatch(NullableTypeParam<@Nullable String> t1) { // we still get an error here as we are not forcing use of JSpecify's @Nullable - // 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) { @@ -503,7 +503,7 @@ class Test { static class SampleClass {} static class SampleClassMultipleArguments {} static void testPositive() { - // BUG: Diagnostic contains: incompatible types: SampleClassMultipleArguments> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String SampleClassMultipleArguments>, String> t1 = new SampleClassMultipleArguments>, String>(); } @@ -528,7 +528,7 @@ class Test { interface Fn

{} class FnImpl implements Fn<@Nullable String, @Nullable String> {} void testPositive() { - // BUG: Diagnostic contains: incompatible types: Test.FnImpl + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Fn<@Nullable String, String> f = new FnImpl(); } void testNegative() { @@ -552,7 +552,7 @@ interface Fn1 {} interface Fn2

{} class FnImpl implements Fn1<@Nullable String, @Nullable String>, Fn2 {} void testPositive() { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String Fn2<@Nullable String> f = new FnImpl(); } void testNegative() { @@ -579,7 +579,7 @@ class FnImpl1 extends SubClassA {} class FnImpl2 extends SubClassA<@Nullable String> {} void testPositive() { SuperClassC<@Nullable String> f; - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String f = new FnImpl1(); } void testNegative() { @@ -604,9 +604,9 @@ class Test { class D

{} class B

extends D

{} void testPositive(B<@Nullable String> b) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String D f1 = new B<@Nullable String>(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String D f2 = b; } void testNegative(B b) { @@ -634,7 +634,7 @@ void testNegative() { Super<@Nullable String, String> s = new Sub(); } void testPositive() { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: 2 mismatches between source and target types Super<@Nullable String, String> s2 = new Sub<@Nullable String, String>(); } } @@ -656,11 +656,11 @@ class B

extends D

{} class C

{} class A, P extends @Nullable Object> {} void testPositive() { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String D> f1 = new B>(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String A, String> f2 = new A, @Nullable String>(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found Test.@Nullable C, required Test.C D> f3 = new B<@Nullable C>(); } void testNegative() { @@ -1008,7 +1008,7 @@ public String function(T1 o) { } } static void testPositive() { - // BUG: Diagnostic contains: incompatible types: B cannot be converted to A<@Nullable Object> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object A<@Nullable Object> p = new B<>(); } static void testNegative() { @@ -1030,11 +1030,11 @@ public void genericFunctionReturnTypeNewClassTree() { class Test { static class A { } static A testPositive1() { - // BUG: Diagnostic contains: incompatible types: A<@Nullable String> + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String return new A<@Nullable String>(); } static A<@Nullable String> testPositive2() { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String return new A(); } static A<@Nullable String> testNegative() { @@ -1056,7 +1056,7 @@ public void genericFunctionReturnTypeNormalTree() { class Test { static class A { } static A testPositive(A<@Nullable String> a) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String return a; } static A<@Nullable String> testNegative(A<@Nullable String> a) { @@ -1079,7 +1079,7 @@ class Test { static class A { } static A testPositive(A<@Nullable String> a, int num) { if (num % 2 == 0) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String return a; } else { return new A(); @@ -1225,15 +1225,15 @@ static A sampleMethod2(A> a1, A a2) { static void sampleMethod3(A<@Nullable String> a1) { } static void testPositive1(A> a1, A a2) { - // BUG: Diagnostic contains: incompatible types: A> + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String A a = sampleMethod1(a1, a2); } static void testPositive2(A> a1, A a2) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String A a = sampleMethod2(a1, a2); } static void testPositive3(A a1) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String sampleMethod3(a1); } static void testNegative(A> a1, A a2) { @@ -1258,7 +1258,7 @@ void foo(A a) {} void bar(A a) { foo(a); this.foo(a); } } static void test(A<@Nullable String> p, A q) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String p.foo(q); // this one is fine p.foo(p); @@ -1282,9 +1282,9 @@ static class A { } return new A<@Nullable String>(); } static void testPositive(A<@Nullable String> a1, A a2) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String A<@Nullable String> b = sampleMethodWithVarArgs(a1); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String A<@Nullable String> b2 = sampleMethodWithVarArgs(a2, a1); } static void testNegative(A a1, A a2) { @@ -1310,7 +1310,7 @@ static class A { } return new A<@Nullable String>(); } static void testPositive(A<@Nullable String>[] arr) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String A<@Nullable String> b = sampleMethodWithVarArgs(arr); } static void testNegative(A[] arr) { @@ -1391,9 +1391,9 @@ public void nestedGenericTypeAssignment() { class Test { static class A { } static void testPositive() { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String A[]> var1 = new A[]>(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String A[]> var2 = new A[]>(); } static void testNegative() { @@ -1416,7 +1416,7 @@ public void nestedGenericTypeAssignment2() { class Test { static class A { } static void testPositive() { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String A[]> var2 = new A[]>(); } } @@ -1435,7 +1435,7 @@ public void genericPrimitiveArrayTypeAssignment() { class Test { static class A { } static void testPositive() { - // BUG: Diagnostic contains: incompatible types: A + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found int [], required int @Nullable [] A x = new A(); } static void testNegative() { @@ -1793,7 +1793,7 @@ class D extends A.B {} void test() { C<@Nullable String> c1 = new C<>(); A<@Nullable String>.B<@Nullable String> ok1 = c1.new D<@Nullable String>(); - // BUG: Diagnostic contains: incompatible types: Test.C<@Nullable String>.D<@Nullable String> cannot be converted to Test.A.B<@Nullable String> + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String A.B<@Nullable String> bad = c1.new D<@Nullable String>(); C c2 = new C<>(); A.B<@Nullable String> ok2 = c2.new D<@Nullable String>(); @@ -3138,7 +3138,7 @@ void testNegative(Function<@Nullable V, @Nullable V> f) { foo(f); } void testPositive(Function f) { - // BUG: Diagnostic contains: incompatible types: Function cannot be converted to + // BUG: Diagnostic contains: incompatible nullability: 2 mismatches between source and target types foo(f); } abstract void takesArray(Function<@Nullable V, @Nullable V>[] f); @@ -3146,7 +3146,7 @@ void testNegativeArray(Function<@Nullable V, @Nullable V>[] f) { takesArray(f); } void testPositiveArray(Function[] f) { - // BUG: Diagnostic contains: incompatible types: Function [] cannot be converted to + // BUG: Diagnostic contains: incompatible nullability: 2 mismatches between source and target types takesArray(f); } } @@ -3168,11 +3168,11 @@ public abstract class Generics { abstract void foo( Function<@NonNull V, @NonNull V> f); void testPositive(Function<@Nullable String, @Nullable String> f) { - // BUG: Diagnostic contains: incompatible types: Function<@Nullable String, @Nullable String> cannot be converted to + // BUG: Diagnostic contains: incompatible nullability: 2 mismatches between source and target types this.<@Nullable String>foo(f); } void testPositiveArray(Function f) { - // BUG: Diagnostic contains: incompatible types: Function cannot be converted to + // BUG: Diagnostic contains: incompatible nullability: 2 mismatches between source and target types this.foo(f); } } @@ -3196,15 +3196,15 @@ void testNegative(Function f) { foo(f); } void testPositive1(Function<@Nullable V, V> f) { - // BUG: Diagnostic contains: incompatible types: Function<@Nullable V, V> + // BUG: Diagnostic contains: incompatible nullability: 2 mismatches between source and target types foo(f); } void testPositive2(Function f) { - // BUG: Diagnostic contains: incompatible types: Function cannot be converted to + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found V, required @Nullable V foo(f); } void testPositive3(Function<@Nullable V, @Nullable V> f) { - // BUG: Diagnostic contains: incompatible types: Function<@Nullable V, @Nullable V> cannot be converted to + // BUG: Diagnostic contains: incompatible nullability: found @Nullable V, required V foo(f); } } @@ -3286,7 +3286,7 @@ static class Inner { void bar(Function f) { // no error since foo is in @NullUnmarked code foo = f; - // BUG: Diagnostic contains: incompatible types: Function + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Function, required @Nullable Function<@Nullable String, @Nullable String> bar = f; } } @@ -3440,7 +3440,7 @@ private static class A { } private static class B extends A<@Nullable Object> { B(List l) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object super(l); } } @@ -3678,9 +3678,9 @@ class A {} class B extends A<@Nullable T> {} class C extends A<@NonNull T> {} void test() { - // BUG: Diagnostic contains: incompatible types: Test.B cannot be converted to Test.A (Test.B is a subtype of Test.A<@Nullable Object>) + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object A a = new B(); - // BUG: Diagnostic contains: incompatible types: Test.C<@Nullable Object> cannot be converted to Test.A<@Nullable Object> (Test.C<@Nullable Object> is a subtype of Test.A) + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object A<@Nullable Object> a2 = new C<@Nullable Object>(); } } @@ -3711,10 +3711,10 @@ interface MaybeNull { static void accept(MaybeNull nonNullThing) {} static void test(MaybeNull<@Nullable String> nullable, MaybeNull nonNull) { accept(nullable.asNonNull()); - // BUG: Diagnostic contains: incompatible types: MaybeNull<@Nullable String> cannot be converted to MaybeNull + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String accept(nonNull.asNullable()); MaybeNull<@Nullable String> m1 = nonNull.asNullable(); - // BUG: Diagnostic contains: incompatible types: MaybeNull<@Nullable String> cannot be converted to MaybeNull + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String MaybeNull m2 = nonNull.asNullable(); } } @@ -3737,11 +3737,11 @@ static class Foo { Foo<@NonNull T> nonNullField = new Foo<>(); Foo<@Nullable T> nullableField = new Foo<>(); static void test(Foo<@Nullable String> nullableFoo, Foo<@NonNull String> nonnullFoo) { - // BUG: Diagnostic contains: incompatible types: Foo cannot be converted to Foo<@Nullable String> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String Foo<@Nullable String> f1 = nullableFoo.nonNullField; Foo f2 = nullableFoo.nonNullField; Foo<@Nullable String> f3 = nonnullFoo.nullableField; - // BUG: Diagnostic contains: incompatible types: Foo<@Nullable String> cannot be converted to Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Foo f4 = nonnullFoo.nullableField; } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/JSpecifyArrayTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/JSpecifyArrayTests.java index ba2cc617b8..1e43e8e0ab 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/JSpecifyArrayTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/JSpecifyArrayTests.java @@ -454,7 +454,7 @@ static void passNonNullElements(Test[] array) { takesParameterized(array); } static void passNullableElements(@Nullable Test[] array) { - // BUG: Diagnostic contains: incompatible types: @Nullable Test [] cannot be converted to Test [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Test, required Test takesParameterized(array); } static Test[] returnNonNullElements(Test[] array) { @@ -462,7 +462,7 @@ static Test[] returnNonNullElements(Test[] array) { return array; } static Test[] returnNullableElements(@Nullable Test[] array) { - // BUG: Diagnostic contains: incompatible types: @Nullable Test [] cannot be converted to Test [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Test, required Test return array; } static void assignNonNullElements(Test[] array) { @@ -470,7 +470,7 @@ static void assignNonNullElements(Test[] array) { Test[] assigned = array; } static void assignNullableElements(@Nullable Test[] array) { - // BUG: Diagnostic contains: incompatible types: @Nullable Test [] cannot be converted to Test [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Test, required Test Test[] assigned = array; } static void passNonNullElementsThroughTernary(boolean b, Test[] array) { @@ -558,7 +558,7 @@ static void test(@Nullable Integer[] nullableIntArr, Integer[] nonnullIntArr) { @Nullable Integer[] x2 = nullableIntArr; // legal (covariant array subtypes) x2 = nonnullIntArr; - // BUG: Diagnostic contains: incompatible types: @Nullable Integer [] cannot be converted to Integer [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Integer, required Integer x1 = nullableIntArr; } } @@ -582,7 +582,7 @@ static void test() { @Nullable Integer[] x2 = new Integer[0]; // legal x2 = new @Nullable Integer[0]; - // BUG: Diagnostic contains: incompatible types: @Nullable Integer [] cannot be converted to Integer [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Integer, required Integer x1 = new @Nullable Integer[0]; } } @@ -673,7 +673,7 @@ public void arraysAndGenerics() { class Test { void foo(List<@Nullable Integer[]> l) {} void testPositive(List p) { - // BUG: Diagnostic contains: incompatible types: List + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Integer, required @Nullable Integer foo(p); } void testNegative(List<@Nullable Integer[]> p) { @@ -697,7 +697,7 @@ static class Foo {} static class Bar { Foo[] getFoosPositive() { @Nullable Foo[] result = new Foo[0]; - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Foo, required Foo return result; } Foo[] getFoosNegative() { @@ -706,7 +706,7 @@ Foo[] getFoosNegative() { } void takeFoos(Foo[] foos) {} void callTakeFoosPositive(@Nullable Foo[] p) { - // BUG: Diagnostic contains: incompatible types: @Nullable Foo [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Foo, required Foo takeFoos(p); } void callTakeFoosNegative(Foo[] p) { @@ -716,9 +716,9 @@ void takeFoosVarargs(Foo[]... foos) {} void callTakeFoosVarargsPositive(@Nullable Foo[] p, Foo[] p2) { // Under the hood, a @Nullable Foo[][] is passed, which is not a subtype // of the formal parameter type Foo[][] - // BUG: Diagnostic contains: incompatible types: @Nullable Foo [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Foo, required Foo takeFoosVarargs(p); - // BUG: Diagnostic contains: incompatible types: @Nullable Foo [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Foo, required Foo takeFoosVarargs(p2, p); } void callTakeFoosVarargsNegative(Foo[] p) { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/StreamNullabilityPropagatorTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/StreamNullabilityPropagatorTests.java index 4cc4e960d2..5b47f86248 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/StreamNullabilityPropagatorTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/StreamNullabilityPropagatorTests.java @@ -281,7 +281,7 @@ public void unrelatedFilterDoesNotRefineStreamElementType() { @NullMarked class Test { static List filterDoesNotProveNonNull(List<@Nullable String> values) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String return values.stream().filter(value -> true).toList(); } @@ -302,7 +302,7 @@ static List mapAfterNullRejectingFilterCanStillReturnNullable( return values.stream() .filter(Objects::nonNull) .map(Test::maybeNull) - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String .toList(); } } From e4d367af186c17cef63f411f5b55952cf702aada Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Tue, 13 Oct 2026 02:51:15 +0300 Subject: [PATCH 21/27] Group the mismatch message tests by the part of the message they check The 51 tests of the new diagnostic sat at the end of WildcardTests, one after another, and each matched its message with contains(), so a line the message should not carry needed its own !contains() and was easy to forget. A failure printed the matcher as a lambda, not the expected text. The tests move to the package jspecify.mismatchmessage, one class per part of the message: summary and numbering, carets, path, the viewed source, notes, the source repair, the required-type repair, and the fallback. MismatchMessageTestBase wraps the members of each test in the same @NullMarked class and compares the whole message, printing the expected text when no diagnostic matches. Cases that differ in one input now share their source through a helper that takes that input: five and six mismatches, and a source repair offered or withheld when the printed type would drop @Tainted. The two tests that checked only a "did you mean" substring now state the whole message. Assisted-by: Claude Code (claude-opus-5-5) --- .../jspecify/mismatchmessage/CaretTests.java | 212 +++++++++ .../mismatchmessage/FallbackMessageTests.java | 63 +++ .../MismatchMessageTestBase.java | 94 ++++ .../jspecify/mismatchmessage/NoteTests.java | 146 ++++++ .../jspecify/mismatchmessage/PathTests.java | 135 ++++++ .../RequiredTypeRepairTests.java | 153 +++++++ .../mismatchmessage/SourceRepairTests.java | 427 ++++++++++++++++++ .../SummaryAndNumberingTests.java | 184 ++++++++ .../mismatchmessage/ViewedSourceTests.java | 156 +++++++ 9 files changed, 1570 insertions(+) create mode 100644 nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java create mode 100644 nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FallbackMessageTests.java create mode 100644 nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/MismatchMessageTestBase.java create mode 100644 nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/NoteTests.java create mode 100644 nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java create mode 100644 nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeRepairTests.java create mode 100644 nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceRepairTests.java create mode 100644 nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java create mode 100644 nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/ViewedSourceTests.java diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java new file mode 100644 index 0000000000..62a78be896 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java @@ -0,0 +1,212 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import org.junit.Test; + +/** + * A caret marks, in both printed types, the smallest node that differs in nullness, and no node the + * target accepts as it is. + */ +public class CaretTests extends MismatchMessageTestBase { + + @Test + public void onlyTheInnermostDifferingNodeIsMarkedInsideAWildcardBound() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: List> + ^^^^^^^^^^^^^^^^ + required: List> + ^^^^^^ + path: List type argument E -> wildcard upper bound -> List type argument E + """, + """ + static void take(List> l) {} + void test(List> l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void caretSkipsATypeArgumentTheTargetAccepts() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Map + ^^^^^^^^^^^^^^^^ + required: Map + ^^^^^^ + path: Map type argument V -> wildcard upper bound + """, + """ + static void take(Map m) {} + void accepted(Map m) { + take(m); + } + void test(Map m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void caretNamesTheConcreteArgumentWhenEveryWildcardIsAccepted() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Map + ^^^^^^^^^^^^^^^^ + required: Map + ^^^^^^ + path: Map type argument V + """, + """ + static void take(Map m) {} + void accepted(Map m) { + take(m); + } + void test(Map m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void caretMarksTheFailingArgumentWhereTheTargetRepeatsAType() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Three + ^^^^^^^^^^^^^^^^ + required: Three + ^^^^^^ + path: Three type argument C + """, + """ + static class Three {} + static void take(Three t) {} + void test(Three t) { + // BUG: Diagnostic matches: MESSAGE + take(t); + } + """); + } + + @Test + public void onlyTheFailingArgumentIsNamedBesideAWildcardTheTargetAccepts() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Three + ^^^^^^^^^^^^^^^^ + required: Three + ^^^^^^ + path: Three type argument C + """, + """ + static class Three {} + static void take(Three t) {} + void test(Three t) { + // BUG: Diagnostic matches: MESSAGE + take(t); + } + """); + } + + @Test + public void bothPositionsAreMarkedWhereOneInstanceFillsTwoTypeArguments() { + assertMessage( + """ + incompatible nullability: 2 mismatches between source and target types + found: Map + ^^^^^^^^^^^^ ^^^^^^^^^^^^ + 1 2 + required: Map + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: Map type argument K -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source wildcard is the type argument for type parameter E of List + \s + 2. path: Map type argument V -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source wildcard is the type argument for type parameter E of List + """, + """ + static Map duplicate(List x) { + throw new RuntimeException(); + } + static void take(Map m) {} + void test(List l) { + // BUG: Diagnostic matches: MESSAGE + take(duplicate(l)); + } + """); + } + + @Test + public void aMismatchInsideAnArrayElementTypeArgumentIsMarked() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: List<@Nullable String> [] + ^^^^^^^^^^^^^^^^ + required: List [] + ^^^^^^ + path: array element -> List type argument E + """, + """ + static void take(List[] l) {} + void test(List<@Nullable String>[] l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void aNullableArrayComponentTypeIsMarkedInsideATypeArgument() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: List<@Nullable String []> + ^^^^^^^^^^^^^^^^ + required: List + ^^^^^^ + path: List type argument E -> array element + """, + """ + static void take(List l) {} + void test(List<@Nullable String[]> l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void aNullableArrayTypeIsMarkedInsideATypeArgument() { + assertMessage( + """ + incompatible nullability: found String @Nullable [], required String [] + found: List + ^^^^^^^^^^^^^^^^^^^ + required: List + ^^^^^^^^^ + path: List type argument E + """, + """ + static void take(List l) {} + void test(List l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } +} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FallbackMessageTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FallbackMessageTests.java new file mode 100644 index 0000000000..673fc09bb9 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FallbackMessageTests.java @@ -0,0 +1,63 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import org.junit.Test; + +/** + * Where the search for differing positions finds none, as for a difference in a lower bound, the + * message falls back to the {@code incompatible types:} form, with no carets and no {@code path:} + * line. A raw source has no type arguments to compare and draws no message at all. + */ +public class FallbackMessageTests extends MismatchMessageTestBase { + + @Test + public void aLowerBoundDifferenceFallsBackToThePlainIncompatibleTypesMessage() { + assertMessage( + """ + incompatible types: List cannot be converted to List + """, + """ + static void takeNonNullLower(List l) {} + static void takeNullableLower(List l) {} + void nullableSourceLowerBound(List l) { + takeNonNullLower(l); + } + void nonNullSourceLowerBound(List l) { + // BUG: Diagnostic matches: MESSAGE + takeNullableLower(l); + } + """); + } + + @Test + public void theFallbackMessageStatesTheSubtypeRelationBetweenTheTwoTypes() { + assertMessage( + """ + incompatible types: Sub cannot be converted to Base (Sub is a subtype of Base) + """, + """ + static class Base {} + static class Sub extends Base {} + static void take(Base b) {} + void test(Sub s) { + // BUG: Diagnostic matches: MESSAGE + take(s); + } + """); + } + + @Test + public void aRawSourceTypeIsAcceptedWithNoMismatchToReport() { + makeHelper() + .addSourceLines( + "Test.java", + nullMarkedClass( + """ + @SuppressWarnings("rawtypes") + void test(List raw) { + List typed = raw; + typed.hashCode(); + } + """)) + .doTest(); + } +} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/MismatchMessageTestBase.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/MismatchMessageTestBase.java new file mode 100644 index 0000000000..4374e52696 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/MismatchMessageTestBase.java @@ -0,0 +1,94 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import com.google.errorprone.CompilationTestHelper; +import com.uber.nullaway.NullAwayTestsBase; +import com.uber.nullaway.generics.JSpecifyJavacConfig; +import java.util.List; +import java.util.function.Predicate; + +/** + * Compiles a {@code @NullMarked} class in JSpecify mode and compares the whole text of the generic + * nullability diagnostic reported at one line of it. + * + *

The comparison is exact, so an expected message also states which lines the diagnostic does + * not carry, such as a {@code did you mean} line or a {@code consider changing the required type} + * line. A failure prints the expected message beside every diagnostic the compilation reported. + */ +abstract class MismatchMessageTestBase extends NullAwayTestsBase { + + /** Returns a helper that runs NullAway in JSpecify mode over {@code @NullMarked} code only. */ + CompilationTestHelper makeHelper() { + return makeTestHelperWithArgs( + JSpecifyJavacConfig.withJSpecifyModeArgs(List.of("-XepOpt:NullAway:OnlyNullMarked=true"))); + } + + /** + * Compiles {@code members} as the body of {@code @NullMarked class Test} and expects the line + * after {@code // BUG: Diagnostic matches: MESSAGE} to report exactly {@code expected}. + * + *

The class imports {@code java.util.*} and the JSpecify annotations {@code NonNull}, {@code + * NullMarked}, {@code NullUnmarked}, and {@code Nullable}. Every other line of {@code members} + * must compile without a NullAway diagnostic. + * + * @param expected the message without the {@code [NullAway]} prefix and the link line, ending in + * a line break + * @param members the declarations of {@code class Test}, one line of which carries the marker + */ + void assertMessage(String expected, String members) { + makeHelper() + .expectErrorMessage("MESSAGE", messageIs(expected)) + .addSourceLines("Test.java", nullMarkedClass(members)) + .doTest(); + } + + /** + * Returns the source of {@code @NullMarked class Test} with the given body and the imports {@link + * #assertMessage} documents. + */ + static String nullMarkedClass(String members) { + return """ + import java.util.*; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.NullUnmarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + %s} + """ + .formatted(members); + } + + /** + * Returns a matcher for a diagnostic whose text, without the {@code [NullAway]} prefix and the + * link line, equals {@code expected}. + */ + static Predicate messageIs(String expected) { + return new MessageIs(expected); + } + + /** + * Matches one diagnostic text exactly. Error Prone prints the matcher when no diagnostic on the + * marked line matches it, so {@link #toString} is the expected message. + */ + private record MessageIs(String expected) implements Predicate { + + private static final String PREFIX = "[NullAway] "; + private static final String LINK_LINE = " (see http://t.uber.com/nullaway )"; + + @Override + public boolean test(String message) { + if (!message.startsWith(PREFIX) || !message.endsWith(LINK_LINE)) { + return false; + } + return message + .substring(PREFIX.length(), message.length() - LINK_LINE.length()) + .equals(expected); + } + + @Override + public String toString() { + return "the message\n" + expected; + } + } +} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/NoteTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/NoteTests.java new file mode 100644 index 0000000000..194ee810dd --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/NoteTests.java @@ -0,0 +1,146 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import org.junit.Test; + +/** + * A {@code note:} line says where the source takes a nullness its printed form does not show: the + * bound an unbounded or lower-bounded wildcard inherits, the type parameter a captured wildcard + * instantiates, or the declared bound of a type variable written without nullness. A source that + * prints its own nullness gets no note. + */ +public class NoteTests extends MismatchMessageTestBase { + + // A List passed to Collection.addAll, as issue #1822 reported it. The message used to print + // the + // two types and that List is a subtype of Collection, which read as a contradiction. + @Test + public void anUnboundedWildcardNamesTheTypeParameterItsBoundIsInheritedFrom() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: List + ^ + required: Collection + ^^^^^^ + path: Collection type argument E -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter E of List + did you mean List? + """, + """ + Collection copy(List list) { + List result = new ArrayList<>(); + // BUG: Diagnostic matches: MESSAGE + result.addAll(list); + return result; + } + Collection copyNonNull(List list) { + List result = new ArrayList<>(); + result.addAll(list); + return result; + } + static void takeNullable(Collection c) {} + void nullableTarget(List list) { + takeNullable(list); + } + """); + } + + @Test + public void aSuperBoundedWildcardNamesTheTypeParameterItsUpperBoundIsInheritedFrom() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: List + ^^^^^^^^^^^^^^ + required: Collection + ^^^^^^ + path: Collection type argument E -> wildcard upper bound + note: the source ? super String has no explicit upper bound, so its upper bound is inherited from + type parameter E of List + """, + """ + static void take(Collection c) {} + void test(List list) { + // BUG: Diagnostic matches: MESSAGE + take(list); + } + """); + } + + @Test + public void anExplicitlyWrittenNullableBoundDrawsNoInheritedBoundNote() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: List + ^^^^^^^^^^^^^^^^ + required: List + ^^^^^^ + path: List type argument E -> wildcard upper bound + """, + """ + static void take(List l) {} + void test(List l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void aTypeVariableWithANullableBoundIsReportedBesideAMismatchingSibling() { + assertMessage( + """ + incompatible nullability: 2 mismatches between source and target types + found: Pair + ^ ^^^^^^^^^^^^^^^^ + 1 2 + required: Pair + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: Pair type argument A -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source T has no nullness of its own, so it takes the nullness of its declared upper + bound + \s + 2. path: Pair type argument B + found: @Nullable String + required: String + """, + """ + static class Pair {} + static void take(Pair p) {} + static void test(Pair p) { + // BUG: Diagnostic matches: MESSAGE + take(p); + } + """); + } + + @Test + public void noInheritedBoundNoteWhereTheUseStatesItsOwnNullness() { + assertMessage( + """ + incompatible nullability: found @Nullable T, required Object + found: Box<@Nullable T> + ^^^^^^^^^^^ + required: Box + ^^^^^^ + path: Box type argument T -> wildcard upper bound + """, + """ + static class Box {} + static void takeNonNull(Box b) {} + static void theBoundAloneIsAccepted(Box b) { + takeNonNull(b); + } + static void test(Box<@Nullable T> b) { + // BUG: Diagnostic matches: MESSAGE + takeNonNull(b); + } + """); + } +} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java new file mode 100644 index 0000000000..071bed2e08 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java @@ -0,0 +1,135 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import org.junit.Test; + +/** + * A {@code path:} line names the position of a difference in words: one step per type argument, + * wildcard bound, array element, or enclosing type, each type argument named by the type parameter + * its declaration declares. + */ +public class PathTests extends MismatchMessageTestBase { + + @Test + public void pathNamesTheTypeParameterTheDeclarationDeclared() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Result + ^^^^^^^^^^^^^^^^ + required: Result + ^^^^^^ + path: Result type argument Failure + """, + """ + static class Result {} + static void take(Result r) {} + void test(Result r) { + // BUG: Diagnostic matches: MESSAGE + take(r); + } + """); + } + + @Test + public void pathRepeatsTheTypeParameterNameAtEveryLevelThatSharesIt() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: List>> + ^^^^^^^^^^^^^^^^ + required: List>> + ^^^^^^ + path: List type argument E -> Collection type argument E -> List type argument E + """, + """ + static void take(List>> l) {} + void test(List>> l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void pathKeepsTheEnclosingTypeApartFromTheInnerType() { + assertMessage( + """ + incompatible nullability: found @Nullable Integer, required Integer + found: Outer.Inner<@Nullable Integer> + ^^^^^^^^^^^^^^^^^ + required: Outer.Inner + ^^^^^^^ + path: Inner type argument U + """, + """ + static class Outer { + class Inner {} + } + static void take(Outer.Inner i) {} + void test(Outer.Inner<@Nullable Integer> i) { + // BUG: Diagnostic matches: MESSAGE + take(i); + } + """); + } + + @Test + public void twoMismatchesInsideOneTypeArgumentSharePathPrefix() { + assertMessage( + """ + incompatible nullability: 2 mismatches between source and target types + found: Map> + ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^ + 1 2 + required: Map> + ^^^^^^ ^^^^^^^ + 1 2 + \s + 1. path: Map type argument V -> Map type argument K + found: @Nullable String + required: String + \s + 2. path: Map type argument V -> Map type argument V + found: @Nullable Integer + required: Integer + """, + """ + static void take(Map> m) {} + void test(Map> m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void mismatchesAtDifferentDepthsEachGetTheirOwnPath() { + assertMessage( + """ + incompatible nullability: 2 mismatches between source and target types + found: Map<@Nullable String, List>> + ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^ + 1 2 + required: Map>> + ^^^^^^ ^^^^^^^ + 1 2 + \s + 1. path: Map type argument K + found: @Nullable String + required: String + \s + 2. path: Map type argument V -> List type argument E -> wildcard upper bound + -> Collection type argument E + found: @Nullable Integer + required: Integer + """, + """ + static void take(Map>> m) {} + void test( + Map<@Nullable String, List>> m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } +} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeRepairTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeRepairTests.java new file mode 100644 index 0000000000..09dac5b30e --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeRepairTests.java @@ -0,0 +1,153 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import org.junit.Test; + +/** + * A {@code consider changing the required type to:} line offers the required type with the nullness + * of the source. It appears where the diagnostic points at the declaration that writes the required + * type, a local variable declaration, and not at a call, an assignment, or a return, whose required + * type is written somewhere else. It is also withheld where printing it would drop a type-use + * annotation. + */ +public class RequiredTypeRepairTests extends MismatchMessageTestBase { + + @Test + public void suggestsTheRequiredTypeAtAVariableDeclaration() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Map + ^^^^^^^^^^^^^^^^ + required: Map + ^^^^^^ + path: Map type argument V + consider changing the required type to: + Map + """, + mapWithNullableValuesReaching( + "Map declared = m; return declared;")); + } + + @Test + public void noSuggestedRequiredTypeAtACallSite() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Map + ^^^^^^^^^^^^^^^^ + required: Map + ^^^^^^ + path: Map type argument V + """, + mapWithNullableValuesReaching("take(m); return existing;")); + } + + @Test + public void noSuggestedRequiredTypeAtAnAssignmentToAnExistingVariable() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Map + ^^^^^^^^^^^^^^^^ + required: Map + ^^^^^^ + path: Map type argument V + """, + mapWithNullableValuesReaching("existing = m; return existing;")); + } + + @Test + public void noSuggestedRequiredTypeAtAReturnStatement() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Map + ^^^^^^^^^^^^^^^^ + required: Map + ^^^^^^ + path: Map type argument V + """, + mapWithNullableValuesReaching("return m;")); + } + + @Test + public void theSuggestedRequiredTypeIsTheDeclaredTypeNotAnInstantiatedSupertype() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Sub<@Nullable String> + found as: List<@Nullable String> + ^^^^^^^^^^^^^^^^ + required: List + ^^^^^^ + path: List type argument E + consider changing the required type to: + List<@Nullable String> + """, + """ + static class Sub extends ArrayList {} + void test(Sub<@Nullable String> s) { + // BUG: Diagnostic matches: MESSAGE + List l = s; + l.hashCode(); + } + """); + } + + @Test + public void noSuggestedRequiredTypeWhereItsPrintedFormWouldDropAnnotations() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Map + ^^^^^^^^^^^^^^^^ + required: Map + ^^^^^^ + path: Map type argument V + """, + mapDeclaredWithKeysOfType("@Tainted String")); + } + + /** + * Returns the members of a class whose method {@code test} holds a {@code Map m} and runs {@code statements} on the marked line, where {@code Map} is required. The local {@code existing} and the method {@code take} + * hold and accept that required type, and the method {@code repairedTypeIsAccepted} shows that + * the repaired type accepts {@code m}. + */ + private static String mapWithNullableValuesReaching(String statements) { + return """ + static void take(Map m) {} + static Map existingMap() { + throw new RuntimeException(); + } + void repairedTypeIsAccepted(Map m) { + Map repaired = m; + } + Map test(Map m) { + Map existing = existingMap(); + // BUG: Diagnostic matches: MESSAGE + %s + } + """ + .formatted(statements); + } + + /** + * Returns the members of a class that declares a {@code Map} initialized from a + * {@code Map}. {@code keyType} may carry the type-use annotation + * {@code @Tainted}, which the class declares. + */ + private static String mapDeclaredWithKeysOfType(String keyType) { + return """ + @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) + @interface Tainted {} + void test(Map<%1$s, @Nullable String> m) { + // BUG: Diagnostic matches: MESSAGE + Map<%1$s, String> declared = m; + declared.hashCode(); + } + """ + .formatted(keyType); + } +} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceRepairTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceRepairTests.java new file mode 100644 index 0000000000..67d0bde26c --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceRepairTests.java @@ -0,0 +1,427 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import org.junit.Test; + +/** + * A {@code did you mean} line offers the source type rewritten with explicit wildcard upper bounds. + * It appears only where the rewritten type repairs every difference and prints without losing a + * type-use annotation. + */ +public class SourceRepairTests extends MismatchMessageTestBase { + + @Test + public void suggestionRewritesEveryMismatchingWildcard() { + assertMessage( + """ + incompatible nullability: 2 mismatches between source and target types + found: Map + ^ ^ + 1 2 + required: Map + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: Map type argument K -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter K of Map + \s + 2. path: Map type argument V -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter V of Map + \s + did you mean Map? + """, + """ + static void take(Map m) {} + void suggestedFormIsAccepted(Map m) { + take(m); + } + void test(Map m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void suggestionLeavesAWildcardTheTargetAllowsToBeNullable() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Map + ^ + required: Map + ^^^^^^ + path: Map type argument K -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter K of Map + did you mean Map? + """, + """ + static void take(Map m) {} + void suggestedFormIsAccepted(Map m) { + take(m); + } + void test(Map m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void suggestionSurvivesAMismatchInTheHarmlessDirection() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Box + ^ + required: Box + ^^^^^^ + path: Box type argument T -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter T of Box + did you mean Box? + """, + """ + static class Box {} + static void take(Box b) {} + void test(Box b) { + // BUG: Diagnostic matches: MESSAGE + take(b); + } + void suggestedFormIsAccepted(Box b) { + take(b); + } + """); + } + + @Test + public void suggestionSurvivesASuperBoundedArgumentTheTargetAlsoDeclaresSuper() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Map + ^ + required: Map + ^^^^^^ + path: Map type argument K -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter K of Map + did you mean Map? + """, + """ + static void take(Map m) {} + void suggestedFormIsAccepted(Map m) { + take(m); + } + void test(Map m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void unboundedWildcardSuggestionInsideAnArrayElement() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: List [] + ^ + required: Collection [] + ^^^^^^ + path: array element -> Collection type argument E -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter E of List + did you mean List []? + """, + """ + static void takeArray(Collection[] c) {} + void suggestedFormIsAccepted(List[] lists) { + takeArray(lists); + } + void test(List[] lists) { + // BUG: Diagnostic matches: MESSAGE + takeArray(lists); + } + """); + } + + @Test + public void unboundedWildcardSuggestionInsideANestedTypeArgument() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: List> + ^ + required: Collection> + ^^^^^^ + path: Collection type argument E -> wildcard upper bound -> List type argument E + -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter E of List + did you mean List>? + """, + """ + static void takeNested(Collection> c) {} + void suggestedFormIsAccepted(List> lists) { + takeNested(lists); + } + void test(List> lists) { + // BUG: Diagnostic matches: MESSAGE + takeNested(lists); + } + """); + } + + @Test + public void unboundedWildcardSuggestionInAnEnclosingTypeArgument() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Outer.Inner + ^ + required: Outer.Inner + ^^^^^^ + path: enclosing type -> Outer type argument T -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter T of Outer + did you mean Outer.Inner? + """, + """ + static class Outer { + class Inner {} + } + static void take(Outer.Inner inner) {} + void suggestedFormIsAccepted(Outer.Inner inner) { + take(inner); + } + void test(Outer.Inner inner) { + // BUG: Diagnostic matches: MESSAGE + take(inner); + } + """); + } + + @Test + public void theSourceRepairIsStillOfferedWhereTheRequiredTypeIsNotEditable() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: List + ^ + required: Collection + ^^^^^^ + path: Collection type argument E -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter E of List + did you mean List? + """, + """ + static void take(Collection c) {} + void test(List l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void noSuggestionWhenAnExplicitBoundMismatchRemains() { + assertMessage( + """ + incompatible nullability: 2 mismatches between source and target types + found: Map + ^ ^^^^^^^^^^^^^^^^ + 1 2 + required: Map + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: Map type argument K -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter K of Map + \s + 2. path: Map type argument V -> wildcard upper bound + found: @Nullable Object + required: Object + """, + """ + static void take(Map m) {} + void test(Map m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void noSuggestionWhenAConcreteTypeArgumentAlsoMismatches() { + assertMessage( + """ + incompatible nullability: 2 mismatches between source and target types + found: Map + ^ ^^^^^^^^^^^^^^^^ + 1 2 + required: Map + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: Map type argument K -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter K of Map + \s + 2. path: Map type argument V + found: @Nullable String + required: String + """, + """ + static void take(Map m) {} + void test(Map m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void noSuggestionWhenOneMismatchCannotBeRewritten() { + assertMessage( + """ + incompatible nullability: 2 mismatches between source and target types + found: Map + ^ ^^^^^^^^^^^^^^ + 1 2 + required: Map + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: Map type argument K -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter K of Map + \s + 2. path: Map type argument V -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? super String has no explicit upper bound, so its upper bound is inherited + from type parameter V of Map + """, + """ + static void take(Map m) {} + void test(Map m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void noSuggestionWhenBoundsDifferBelowTheTopLevel() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Holder + ^ + required: Holder> + ^^^^^^ + path: Holder type argument E -> wildcard upper bound -> List type argument E + """, + """ + static class Holder> {} + static void take(Holder> h) {} + void test(Holder h) { + // BUG: Diagnostic matches: MESSAGE + take(h); + } + """); + } + + @Test + public void noSuggestionWhenTheRewrittenTypeHoldsACapture() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Map, capture of ?> + ^ + required: Map, ?> + ^^^^^^ + path: Map type argument K -> wildcard upper bound -> List type argument E -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter E of List + """, + """ + static Map, T> make(List l) { + throw new RuntimeException(); + } + static void take(Map, ?> m) {} + void test(List l) { + // BUG: Diagnostic matches: MESSAGE + take(make(l)); + } + """); + } + + @Test + public void aSourceWithNoOtherTypeUseAnnotationGetsTheRepair() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Map + ^ + required: Map + ^^^^^^ + path: Map type argument K -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter K of Map + did you mean Map? + """, + mapWithValuesOfType("String")); + } + + // The printer drops @Tainted from both printed types, so the message differs from the one in + // aSourceWithNoOtherTypeUseAnnotationGetsTheRepair only by the missing repair line. + @Test + public void noSourceRepairWhereItsPrintedFormWouldDropAnnotations() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Map + ^ + required: Map + ^^^^^^ + path: Map type argument K -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter K of Map + """, + mapWithValuesOfType("@Tainted String")); + } + + /** + * Returns the members of a class that passes {@code Map} where {@code Map} is required. The key wildcard is the one mismatch; {@code valueType} may carry + * the type-use annotation {@code @Tainted}, which the class declares. + */ + private static String mapWithValuesOfType(String valueType) { + return """ + @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) + @interface Tainted {} + static void take(Map m) {} + void test(Map m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """ + .formatted(valueType); + } +} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java new file mode 100644 index 0000000000..0447afc74d --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java @@ -0,0 +1,184 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.junit.Test; + +/** + * The first line of a generic nullability message states the one difference between the two types, + * or how many there are. Where there are several, each gets a numbered entry, five at most, and a + * line after them counts the rest. A type argument that the source states outright has to match + * exactly, and the first line says so where the source is the less nullable side. + */ +public class SummaryAndNumberingTests extends MismatchMessageTestBase { + + @Test + public void listsAtMostFiveMismatchesAndSaysHowManyMoreThereAre() { + assertMessage( + """ + incompatible nullability: 6 mismatches between source and target types + found: Args + ^ ^ ^ ^ ^ + 1 2 3 4 5 + required: Args + ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ + 1 2 3 4 5 + \s + 1. path: Args type argument A -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter A of Args + \s + 2. path: Args type argument B -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter B of Args + \s + 3. path: Args type argument C -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter C of Args + \s + 4. path: Args type argument D -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter D of Args + \s + 5. path: Args type argument E -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter E of Args + \s + and 1 more, not listed + \s + did you mean Args? + """, + wildcardsWhereNonNullBoundsAreRequired(6)); + } + + @Test + public void listsFiveMismatchesWithoutSayingThereAreMore() { + assertMessage( + """ + incompatible nullability: 5 mismatches between source and target types + found: Args + ^ ^ ^ ^ ^ + 1 2 3 4 5 + required: Args + ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ + 1 2 3 4 5 + \s + 1. path: Args type argument A -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter A of Args + \s + 2. path: Args type argument B -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter B of Args + \s + 3. path: Args type argument C -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter C of Args + \s + 4. path: Args type argument D -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter D of Args + \s + 5. path: Args type argument E -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter E of Args + \s + did you mean Args? + """, + wildcardsWhereNonNullBoundsAreRequired(5)); + } + + @Test + public void adjacentTypeArgumentsThatBothMismatchAreNumberedSideBySide() { + assertMessage( + """ + incompatible nullability: 2 mismatches between source and target types + found: Map<@Nullable String, @Nullable String> + ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ + 1 2 + required: Map + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: Map type argument K + found: @Nullable String + required: String + \s + 2. path: Map type argument V + found: @Nullable String + required: String + """, + """ + static void take(Map m) {} + void test(Map<@Nullable String, @Nullable String> m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void invariantTypeArgumentIsReportedWhenTheSourceIsLessNullableThanRequired() { + assertMessage( + """ + incompatible nullability: a type argument must match exactly; found String, required @Nullable String + found: List + ^^^^^^ + required: List<@Nullable String> + ^^^^^^^^^^^^^^^^ + path: List type argument E + """, + """ + void test(List source) { + // BUG: Diagnostic matches: MESSAGE + List<@Nullable String> target = source; + target.hashCode(); + } + """); + } + + /** + * Returns the members of a class that passes {@code Args} where {@code Args} is required. Every type parameter of {@code Args} has a {@code @Nullable Object} + * bound, so each of the {@code count} wildcards is one mismatch. + */ + private static String wildcardsWhereNonNullBoundsAreRequired(int count) { + List parameters = new ArrayList<>(); + for (int i = 0; i < count; i++) { + parameters.add((char) ('A' + i) + " extends @Nullable Object"); + } + return """ + static class Args<%s> {} + static void take(Args<%s> args) {} + void test(Args<%s> args) { + // BUG: Diagnostic matches: MESSAGE + take(args); + } + """ + .formatted( + String.join(", ", parameters), + String.join(", ", Collections.nCopies(count, "? extends Object")), + String.join(", ", Collections.nCopies(count, "?"))); + } +} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/ViewedSourceTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/ViewedSourceTests.java new file mode 100644 index 0000000000..35eb952b8e --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/ViewedSourceTests.java @@ -0,0 +1,156 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import org.junit.Test; + +/** + * Where the source is compared as a supertype of its own class, the message prints that view on a + * {@code found as:} line, draws the source carets under it, and keeps the {@code path:} and {@code + * note:} lines in the coordinates of the view. + */ +public class ViewedSourceTests extends MismatchMessageTestBase { + + @Test + public void aMismatchInsideAWildcardBoundIsMarkedOnTheViewedSource() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Sub> + found as: Base> + ^^^^^^^^^^^^^^^^ + required: Base> + ^^^^^^ + path: Base type argument T -> wildcard upper bound -> List type argument E + """, + """ + static class Base {} + static class Sub extends Base {} + static void take(Base> b) {} + void test(Sub> s) { + // BUG: Diagnostic matches: MESSAGE + take(s); + } + """); + } + + @Test + public void aMismatchInsideAnArrayElementIsMarkedOnTheViewedSource() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Sub<@Nullable String []> + found as: Base<@Nullable String []> + ^^^^^^^^^^^^^^^^ + required: Base + ^^^^^^ + path: Base type argument T -> array element + """, + """ + static class Base {} + static class Sub extends Base {} + static void take(Base b) {} + void test(Sub<@Nullable String[]> s) { + // BUG: Diagnostic matches: MESSAGE + take(s); + } + """); + } + + @Test + public void aCapturedWildcardIsMarkedOnTheViewedSourceAndKeepsItsProvenance() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Sub + found as: Base + ^^^^^^^^^^^^ + required: Base + ^^^^^^ + path: Base type argument T -> wildcard upper bound + note: the source wildcard is the type argument for type parameter T of Sub + """, + """ + static class Base {} + static class Sub extends Base {} + static void take(Base b) {} + static Sub make() { + throw new RuntimeException(); + } + void test() { + // BUG: Diagnostic matches: MESSAGE + take(make()); + } + """); + } + + @Test + public void aPathAcrossAViewReachesIntoWhateverTheSubclassPassed() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Indirect + found as: Base> + ^ + required: Base> + ^^^^^^ + path: Base type argument B -> wildcard upper bound -> List type argument E -> wildcard upper bound + note: the source wildcard has an implicit @Nullable Object upper bound + """, + """ + static class Base {} + static class Indirect extends Base> {} + static void take(Base> b) {} + void test(Indirect i) { + // BUG: Diagnostic matches: MESSAGE + take(i); + } + """); + } + + // b.Result extends a.Result, so the call reaches NullAway and both sides print as + // "Result". + @Test + public void simpleNamesAloneDoNotShowThatTheTwoTypesComeFromDifferentPackages() { + makeHelper() + .addSourceLines( + "a/Result.java", + """ + package a; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + public class Result {} + """) + .addSourceLines( + "b/Result.java", + """ + package b; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + public class Result extends a.Result {} + """) + .expectErrorMessage( + "MESSAGE", + messageIs( + """ + incompatible nullability: found @Nullable String, required String + found: Result<@Nullable String> + found as: Result<@Nullable String> + ^^^^^^^^^^^^^^^^ + required: Result + ^^^^^^ + path: Result type argument T + """)) + .addSourceLines( + "Test.java", + nullMarkedClass( + """ + static void take(a.Result r) {} + void test(b.Result<@Nullable String> r) { + // BUG: Diagnostic matches: MESSAGE + take(r); + } + """)) + .doTest(); + } +} From 3271f4eaee48b4194bcc54e0e3096a750176789b Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Tue, 13 Oct 2026 02:51:26 +0300 Subject: [PATCH 22/27] Offer the required type where one type instance fills two type arguments The "consider changing the required type to:" line was missing for Map declared = m; // m is Map javac hands back one String instance for both type arguments of the required Map, and the repair replaced nodes by identity, so it added @Nullable to the key as well. The rewritten Map<@Nullable String, @Nullable String> no longer accepted the source, and the repair was withheld. A Map got it. The repair now replaces the node at the path of each mismatch, the position TypePath already names for the carets. The test that withholds the repair where printing it would drop @Tainted passed for this reason, not for its own; it now has a counterpart without @Tainted on the same source, which fails without this change. Assisted-by: Claude Code (claude-opus-5-5) --- .../generics/NullabilityMismatchMessage.java | 104 ++++++++++++------ .../com/uber/nullaway/generics/TypePath.java | 5 + .../RequiredTypeRepairTests.java | 18 +++ 3 files changed, 91 insertions(+), 36 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java index 8b454e0397..dfe538fcf1 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -1,5 +1,7 @@ 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; @@ -540,18 +542,20 @@ private static String wrapped(String text, int firstLineIndent, String continuat */ private @Nullable String suggestedTargetType( Type targetType, Type sourceType, List mismatches) { - IdentityHashMap replacements = new IdentityHashMap<>(); + 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; } - replacements.put(mismatch.targetNode(), rewritten); - } - if (replacements.isEmpty()) { - return null; + rewrittenTargetType = replaceAt(rewrittenTargetType, mismatch.path().steps(), 0, rewritten); + if (rewrittenTargetType == null) { + return null; + } } - Type rewrittenTargetType = replaceNodes(targetType, replacements); if (!printsEveryAnnotation(rewrittenTargetType) || !isDenotable(rewrittenTargetType) || !checks.subtypeParameterNullability(rewrittenTargetType, sourceType, state)) { @@ -581,36 +585,64 @@ private static String wrapped(String text, int firstLineIndent, String continuat return null; } - /** Returns {@code type} with each node in {@code replacements} replaced by its new form. */ - private static Type replaceNodes(Type type, IdentityHashMap replacements) { - return type.accept( - new Type.StructuralTypeMapping<@Nullable Void>() { - private Type replaced(Type t, java.util.function.Supplier otherwise) { - Type replacement = replacements.get(t); - return replacement != null ? replacement : otherwise.get(); - } - - @Override - public Type visitClassType(Type.ClassType t, @Nullable Void unused) { - return replaced(t, () -> super.visitClassType(t, null)); - } - - @Override - public Type visitWildcardType(Type.WildcardType t, @Nullable Void unused) { - return replaced(t, () -> super.visitWildcardType(t, null)); - } - - @Override - public Type visitArrayType(Type.ArrayType t, @Nullable Void unused) { - return replaced(t, () -> super.visitArrayType(t, null)); - } - - @Override - public Type visitTypeVar(Type.TypeVar t, @Nullable Void unused) { - return replaced(t, () -> super.visitTypeVar(t, null)); - } - }, - 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()); } /** diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java b/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java index 469d67745a..c42f9b0c01 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java @@ -89,6 +89,11 @@ 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(); } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeRepairTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeRepairTests.java index 09dac5b30e..a39e4117aa 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeRepairTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeRepairTests.java @@ -94,6 +94,24 @@ void test(Sub<@Nullable String> s) { """); } + @Test + public void aRequiredTypeWithNoOtherTypeUseAnnotationGetsTheRepair() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Map + ^^^^^^^^^^^^^^^^ + required: Map + ^^^^^^ + path: Map type argument V + consider changing the required type to: + Map + """, + mapDeclaredWithKeysOfType("String")); + } + + // The printer drops @Tainted from both printed types, so the message differs from the one in + // aRequiredTypeWithNoOtherTypeUseAnnotationGetsTheRepair only by the missing repair lines. @Test public void noSuggestedRequiredTypeWhereItsPrintedFormWouldDropAnnotations() { assertMessage( From f847fe14b00bc4f459182439ccb5c53ef0ef430b Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Fri, 27 Nov 2026 12:46:27 +0300 Subject: [PATCH 23/27] Stop the mismatch traversal at a bound comparison already in progress A wildcard bound can name its own type variable again, as in `X extends NullableSibling`. Building the message for an assignment of such a type, the traversal compared the two wildcards' bounds, reached the same pair of wildcards inside them, and recursed until the compiler crashed: java.lang.StackOverflowError at com.uber.nullaway.generics.NullabilityMismatches.collect(NullabilityMismatches.java:144) The traversal now keeps the pairs of target and source wildcards whose bounds it is comparing, by identity, and reports nothing for a pair it reaches again. CheckIdenticalNullabilityVisitor accepts such a pair in the same way since #2095, so the message lists only what the check rejected. Assisted-by: Claude Code (claude-opus-5-5) --- .../generics/NullabilityMismatches.java | 55 +++++++++++++------ .../SharedIntersectionTimeoutTests.java | 2 +- 2 files changed, 40 insertions(+), 17 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java index aec34c09c8..f049d0d47c 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java @@ -7,7 +7,10 @@ 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; /** @@ -31,6 +34,16 @@ final class NullabilityMismatches { 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}, 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; @@ -135,22 +148,32 @@ private void collect( Type.WildcardType targetWildcard = GenericsUtils.asWildcard(target); Type.WildcardType sourceWildcard = GenericsUtils.asWildcard(source); if (targetWildcard != null && sourceWildcard != null) { - // 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); + 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) { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/SharedIntersectionTimeoutTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/SharedIntersectionTimeoutTests.java index b307333e28..8bc51c1f1a 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/SharedIntersectionTimeoutTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/SharedIntersectionTimeoutTests.java @@ -152,7 +152,7 @@ void argumentWithNonObjectBound() { return comparableSibling(); } void siblingWithNullableBoundAndMismatch() { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String NullableSibling x = nullableSibling(); } void siblingWithNullableNonObjectBound() { From abad664f272eb3129da17a4820e9ba85d460f138 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Fri, 27 Nov 2026 12:46:30 +0300 Subject: [PATCH 24/27] Adapt the mismatch message to master without #1834 This branch no longer builds on #1955 and #1834, so the message is checked against what master's checks report. On master, TypeSubstitutionUtils.asSuper carries a node of the source into the supertype view as the same instance. The caret then goes under the type the reader wrote, and the message prints a `found as:` line only where the view rebuilt the node, as from the supertype a subclass declares. The class Javadoc and the comments on the view now state that condition. The explanation of a type variable judged by its declared bound is left to #1834, since master's check does not reject such a type variable. GenericsUtils.fromUnannotatedMethodOrClass, which the note on an unannotated declaration calls, is package-private, as #1955 made it. Assisted-by: Claude Code (claude-opus-5-5) --- .../uber/nullaway/generics/GenericsUtils.java | 6 +- .../generics/NullabilityMismatchMessage.java | 19 +++-- .../nullaway/ParameterAssignmentTests.java | 4 +- .../GenericInferenceErrorReportingTests.java | 2 +- .../nullaway/jspecify/GenericLambdaTests.java | 4 +- ...enericMethodLambdaOrMethodRefArgTests.java | 2 +- .../nullaway/jspecify/GenericMethodTests.java | 8 +- .../jspecify/GenericVoidReturnTests.java | 4 +- .../uber/nullaway/jspecify/GenericsTests.java | 14 ++-- .../IntersectionBoundNarrowingTests.java | 4 +- .../nullaway/jspecify/JSpecifyArrayTests.java | 16 ++-- .../jspecify/PolyNullLibraryModelsTests.java | 2 +- .../jspecify/VarDeclaredLocalTests.java | 2 +- .../uber/nullaway/jspecify/WildcardTests.java | 50 ++++++------ .../jspecify/mismatchmessage/NoteTests.java | 37 +-------- .../RequiredTypeRepairTests.java | 3 +- .../mismatchmessage/ViewedSourceTests.java | 77 +++++++++++++++---- 17 files changed, 136 insertions(+), 118 deletions(-) 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 b71484a84d..07a8864eda 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java @@ -540,7 +540,11 @@ private static boolean libraryModelMakesBoundNullable( 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 index dfe538fcf1..ea9fe6092c 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -60,9 +60,10 @@ * a node in one where the difference cannot be seen. * *

A note explains itself in the entities the message already shows. Where the source wildcard - * stands at a position of the type the reader wrote, the note names the type parameter it takes its - * bound from. Where the source was viewed as a supertype, that parameter belongs to a declaration - * this message never prints, and naming it would set a second frame of reference against the {@code + * 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 @@ -248,9 +249,10 @@ private String summaryLine(List mismatches) { * 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} as a {@code Base} keeps - * the wildcard and changes the type printed around it. Printing the view gives the caret - * something to point at that the comparison actually used. + * 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) @@ -493,8 +495,9 @@ private static String wrapped(String text, int firstLineIndent, String continuat : "? 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 once that source is viewed as a - // supertype, or the variable it instantiates has no named owner. The note says what the + // 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 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/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/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 87f196064d..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); } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java index 6f3f7fb265..e4a97dbabf 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java @@ -2243,8 +2243,8 @@ public void capturedTypeAtNullUnmarkedBoundary() { message.contains( """ incompatible nullability: found @Nullable Object, required Object - found: Foo<@Nullable capture of ?> - ^^^^^^^^^^^^^^^^^^^^^^ + found: Foo + ^^^^^^^^^^^^ required: Foo ^ path: Foo type argument T -> wildcard upper bound @@ -3348,9 +3348,9 @@ class GInner { return x; } void nullableQualifier(Outer<@Nullable String> o) { - // BUG: Diagnostic contains: incompatible types: Outer<@Nullable String>.Inner cannot be converted to Outer.Inner + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String id(o.new Inner("")); - // BUG: Diagnostic contains: incompatible types: Outer<@Nullable String>.GInner cannot be converted to Outer.GInner + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String id(o.new GInner("")); } void nonNullQualifier(Outer o) { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericVoidReturnTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericVoidReturnTests.java index 77026ab230..77896df833 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericVoidReturnTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericVoidReturnTests.java @@ -93,7 +93,7 @@ void invalidLambdaArgument(@Nullable String value) { exec(() -> requiresNonNull(value), "x"); } void incompatibleLambdaTypeArguments(List<@Nullable Void> values) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Void, required Void execList(() -> values, "x"); } void substitutedVoidLambdaReturn(@Nullable Void value) { @@ -119,7 +119,7 @@ Void invalidArgument(@Nullable String value) { return requiresNonNull(value); } List incompatibleTypeArguments(List<@Nullable Void> values) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Void, required Void return values; } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java index 0afa2bc72c..683e715402 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java @@ -229,7 +229,7 @@ class Test { static class Holder {} static void typeArguments() { Holder other = new Holder<@Other String>(); - // BUG: Diagnostic contains: incompatible types: Holder<@Nullable String> cannot be + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Holder otherThenNullable = new Holder<@Other @Nullable String>(); } } @@ -355,7 +355,7 @@ public void testPositive() { public void onResult(Integer value) { // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Integer, required @Nullable Integer removeCallback(this); - // BUG: Diagnostic contains: incompatible types: Callback cannot be converted to Callback<@Nullable Integer> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Integer, required @Nullable Integer Callback<@Nullable Integer> self = this; } void callOnResult() { @@ -2057,28 +2057,28 @@ void staticSubclassWithNullableOuterMatches(NullableInner input) { Outer<@Nullable String>.Inner result = input; } void staticSubclassWithNullableOuterMismatches(NullableInner input) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Outer.Inner result = input; } void staticSubclassWithNonNullOuterMatches(NonNullInner input) { Outer.Inner result = input; } void staticSubclassWithNonNullOuterMismatches(NonNullInner input) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String Outer<@Nullable String>.Inner result = input; } void unrelatedEnclosingTypeMatches(Unrelated.Derived input) { Outer<@Nullable String>.Inner result = input; } void unrelatedEnclosingTypeMismatches(Unrelated.Derived input) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Outer.Inner result = input; } void lexicalOuterMismatchDoesNotRejectMatchingSupertype(Cross.Derived input) { Outer<@Nullable String>.Inner result = input; } void lexicalOuterMatchDoesNotAcceptMismatchingSupertype(Cross.Derived input) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Outer.Inner result = input; } } @@ -3371,7 +3371,7 @@ private static class Inner { Inner identity() { return this; } } Inner<@Nullable Object> mThing = new Inner<@Nullable Object>().identity(); - // BUG: Diagnostic contains: incompatible types: Inner<@Nullable Object> cannot be converted to Inner + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object Inner mNonNullThing = new Inner<@Nullable Object>().identity(); } """) diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionBoundNarrowingTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionBoundNarrowingTests.java index 814b2a7b26..53361729f0 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionBoundNarrowingTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionBoundNarrowingTests.java @@ -54,12 +54,12 @@ Result acceptsExplicitNonNullLastComponent(LastNonNull source) { } Result rejectsAllNullableFirstComponent(AllNullable source) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable A & @Nullable B, required A return source.result(); } Result rejectsAllNullableLastComponent(AllNullable source) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable A & @Nullable B, required B return source.result(); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/JSpecifyArrayTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/JSpecifyArrayTests.java index 1e43e8e0ab..7fc6cb6e78 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/JSpecifyArrayTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/JSpecifyArrayTests.java @@ -604,12 +604,12 @@ static void test() { // dimension of the creation expression @Nullable Integer[][] x1 = new @Nullable Integer[3][4]; @Nullable Integer[][][] x2 = new @Nullable Integer[1][2][3]; - // BUG: Diagnostic contains: incompatible types: @Nullable Integer [] [] cannot be converted to Integer [] [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Integer, required Integer Integer[][] x3 = new @Nullable Integer[3][4]; // an array creation with an initializer has no explicit dimension expressions, but // still creates a single-dimension array @Nullable Integer[] x4 = new @Nullable Integer[]{null}; - // BUG: Diagnostic contains: incompatible types: @Nullable Integer [] cannot be converted to Integer [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Integer, required Integer Integer[] x5 = new @Nullable Integer[]{null}; // the reverse direction is legal by covariant array subtyping @Nullable Integer[] y1 = new Integer[3]; @@ -647,13 +647,13 @@ static void test( // the declared type and the type computed for the creation expression made // CheckIdenticalNullabilityVisitor#visitArrayType bail out, so the innermost // element types were never compared - // BUG: Diagnostic contains: incompatible types: @Nullable Integer [] [] cannot be converted to Integer @Nullable [] [] + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found @Nullable Integer [], required Integer @Nullable [] Integer[] @Nullable [] y4 = new @Nullable Integer[3][4]; - // BUG: Diagnostic contains: incompatible types: @Nullable Integer [] [] cannot be converted to Integer [] [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Integer, required Integer Integer[][] y1 = nullableElems2D; - // BUG: Diagnostic contains: incompatible types: @Nullable Integer [] [] [] cannot be converted to Integer [] [] [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Integer, required Integer Integer[][][] y2 = nullableElems3D; - // BUG: Diagnostic contains: incompatible types: Integer @Nullable [] [] cannot be converted to Integer [] [] + // BUG: Diagnostic contains: incompatible nullability: found Integer @Nullable [], required Integer [] Integer[][] y3 = nullableInner; } } @@ -1390,7 +1390,7 @@ static void nullableExplicitArrayStore() { static void nullableTypeArgumentRejectedFromNonNullBoundedWildcardArray( CompletableFuture[] futures, CompletableFuture<@Nullable String> value) { - // BUG: Diagnostic contains: incompatible types: CompletableFuture<@Nullable String> cannot be converted to CompletableFuture + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String futures[0] = value; } } @@ -1772,7 +1772,7 @@ void writeNullIntoNonNullElementOfVarLoopVariableOverNestedLocalArray() { } void assignNullableTypeArgumentElementOfLocalArray() { List<@Nullable String>[] local = new List[1]; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String List l = local[0]; } void assignMatchingTypeArgumentElementOfLocalArray() { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/PolyNullLibraryModelsTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/PolyNullLibraryModelsTests.java index 2aa8083655..8c9f6a04bd 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/PolyNullLibraryModelsTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/PolyNullLibraryModelsTests.java @@ -103,7 +103,7 @@ void test(List nonNull, List<@Nullable Object> nullable) { PolyNullMethods.first(nonNull, nonNull).hashCode(); // Without PolyNull, both parameters retain their declared List types. - // BUG: Diagnostic contains: incompatible types: List<@Nullable Object> cannot be converted to List + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object PolyNullMethods.first(nullable, nullable); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/VarDeclaredLocalTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/VarDeclaredLocalTests.java index e3ea7319dd..1cc46f8fc1 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/VarDeclaredLocalTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/VarDeclaredLocalTests.java @@ -247,7 +247,7 @@ void rejectsIncompatibleTypeArgument( boolean b, String s, Box nonNull, Box<@Nullable String> nullable) { s.length(); var x = b ? nonNull : nonNull; - // BUG: Diagnostic contains: incompatible types: Box<@Nullable String> cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String x = id(nullable); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java index a81a1b4476..e04e9870c0 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -320,7 +320,7 @@ void testNegative(Foo<@Nullable String> f, Foo f2) { } void testPositive(Foo<@Nullable String> f, Foo f2) { // not legal since the wildcard upper bound is non-null - // BUG: Diagnostic contains: incompatible types: Test.Foo<@Nullable String> cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String String s = nonnullWildcard(f); // legal String s2 = nonnullWildcard(f2); @@ -349,7 +349,7 @@ void testNegative(Foo<@Nullable String> f) { } void testPositive(Foo<@Nullable String> f) { // not legal since the wildcard upper bound is non-null - // BUG: Diagnostic contains: incompatible types: Test.Foo<@Nullable String> cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String String s = nonnullWildcard(f); s.hashCode(); } @@ -380,7 +380,7 @@ void testNegative(Foo> f) { s.hashCode(); } void testPositive(Foo> f) { - // BUG: Diagnostic contains: incompatible types: Test.Foo> cannot be converted to Test.Foo> + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String String s = nonnullWildcard(f); s.hashCode(); } @@ -412,7 +412,7 @@ void testNegative(Foo>> f) { s.hashCode(); } void testPositive(Foo>> f) { - // BUG: Diagnostic contains: incompatible types: Test.Foo>> cannot be converted to Test.Foo>> + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String String s = nonnullWildcard(f); s.hashCode(); } @@ -444,7 +444,7 @@ void testNegative(Foo<@Nullable Bar>> f) { s.hashCode(); } void testPositive(Foo<@Nullable Bar>> f) { - // BUG: Diagnostic contains: incompatible types: Test.Foo>> cannot be converted to Test.Foo>> + // BUG: Diagnostic contains: incompatible nullability: found Test.@Nullable Bar>, required Test.Bar> String s = nonnullWildcard(f); s.hashCode(); } @@ -474,7 +474,7 @@ void testNegative(Foo f) { s.hashCode(); } void testPositive(Foo f) { - // BUG: Diagnostic contains: incompatible types: Test.Foo cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String String s = nonnullWildcard(f); s.hashCode(); } @@ -497,22 +497,22 @@ class Foo {} Foo nullableField; Test(Foo f) { nullableField = f; - // BUG: Diagnostic contains: incompatible types: Test.Foo cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String nonnullField = f; } Foo nullableReturn(Foo f) { return f; } Foo nonnullReturn(Foo f) { - // BUG: Diagnostic contains: incompatible types: Test.Foo cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String return f; } void testLocal(Foo f) { Foo ok = f; - // BUG: Diagnostic contains: incompatible types: Test.Foo cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Foo bad = f; var f2 = f; - // BUG: Diagnostic contains: incompatible types: Test.Foo cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Foo bad2 = f2; } } @@ -567,11 +567,11 @@ void testLocals( Foo fromNonnullSuper = nonnullSuperFoo; Foo fromNullableSuper = nullableSuperFoo; Foo fromUnbounded = unboundedFoo; - // BUG: Diagnostic contains: incompatible types: Test.Foo cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object Foo badFromNonnullSuper = nonnullSuperFoo; - // BUG: Diagnostic contains: incompatible types: Test.Foo cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object Foo badFromNullableSuper = nullableSuperFoo; - // BUG: Diagnostic contains: incompatible types: Test.Foo cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object Foo badFromUnbounded = unboundedFoo; } } @@ -596,7 +596,7 @@ void testLocals( NonNullBoundFoo nonnullSuperStringFoo) { NonNullBoundFoo fromNonnull = nonnullObjectFoo; NonNullBoundFoo fromNonnullExtends = nonnullExtendsObjectFoo; - // BUG: Diagnostic contains: incompatible types: Test.NonNullBoundFoo cannot be converted to Test.NonNullBoundFoo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object NonNullBoundFoo fromNullableExtends = nullableExtendsObjectWithNonnullBoundFoo; NonNullBoundFoo fromSuper = nonnullSuperStringFoo; } @@ -622,13 +622,13 @@ static void nonNullFirstArgument(Pair pair) { static void nullableFirstArgument(Pair<@Nullable String, ?> pair) { Pair<@Nullable String, ? extends @Nullable String> target = pair; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Pair<@Nullable String, ? extends String> invalid = pair; } static void capturedFirstArgument(Pair pair) { Pair target = pair; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object Pair invalid = pair; } @@ -637,7 +637,7 @@ static class UnmarkedPair {} static void capturedFirstArgumentFromUnmarkedCode(UnmarkedPair pair) { UnmarkedPair target = pair; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object UnmarkedPair invalid = pair; } } @@ -916,18 +916,18 @@ Nested self() { } Nested testDirect(Nested receiver) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String return receiver.wildcardUpperTypeVariable(); } Nested testWithSelf(Nested receiver) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String return receiver.self().wildcardUpperTypeVariable(); } Nested testWithVar(Nested receiver) { var local = receiver; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String return local.wildcardUpperTypeVariable(); } @@ -961,18 +961,18 @@ Nested self() { } Nested testDirect(Nested receiver) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object return receiver.wildcardUpperTypeVariable(); } Nested testWithSelf(Nested receiver) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object return receiver.self().wildcardUpperTypeVariable(); } Nested testWithVar(Nested receiver) { var local = receiver; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object return local.wildcardUpperTypeVariable(); } @@ -1480,7 +1480,7 @@ public Foo or(Foo other) { } // We report an error here since we do not infer Foo<@Nullable Void> as the type of the Foo.of call; // javac itself has a similar inference limitation, see https://godbolt.org/z/Y875ahYMx - // BUG: Diagnostic contains: incompatible types: Foo cannot be converted to Foo<@Nullable Void> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Void, required @Nullable Void static final Foo<@Nullable Void> FOO = Foo.of(new Foo<@Nullable Void>()).or(new Foo<@Nullable Void>()); // This works due to the explicit type argument @@ -2080,7 +2080,7 @@ static void nullableSuperBounded(NullableNode node) { } static void superBoundedNullableElements(ListNode> node) { - // BUG: Diagnostic contains: incompatible types: List<@Nullable String> + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String takesList(node.get()); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/NoteTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/NoteTests.java index 194ee810dd..c0142f66d2 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/NoteTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/NoteTests.java @@ -4,9 +4,8 @@ /** * A {@code note:} line says where the source takes a nullness its printed form does not show: the - * bound an unbounded or lower-bounded wildcard inherits, the type parameter a captured wildcard - * instantiates, or the declared bound of a type variable written without nullness. A source that - * prints its own nullness gets no note. + * bound an unbounded or lower-bounded wildcard inherits, or the type parameter a captured wildcard + * instantiates. A source that prints its own nullness gets no note. */ public class NoteTests extends MismatchMessageTestBase { @@ -88,38 +87,6 @@ void test(List l) { """); } - @Test - public void aTypeVariableWithANullableBoundIsReportedBesideAMismatchingSibling() { - assertMessage( - """ - incompatible nullability: 2 mismatches between source and target types - found: Pair - ^ ^^^^^^^^^^^^^^^^ - 1 2 - required: Pair - ^^^^^^ ^^^^^^ - 1 2 - \s - 1. path: Pair type argument A -> wildcard upper bound - found: @Nullable Object - required: Object - note: the source T has no nullness of its own, so it takes the nullness of its declared upper - bound - \s - 2. path: Pair type argument B - found: @Nullable String - required: String - """, - """ - static class Pair {} - static void take(Pair p) {} - static void test(Pair p) { - // BUG: Diagnostic matches: MESSAGE - take(p); - } - """); - } - @Test public void noInheritedBoundNoteWhereTheUseStatesItsOwnNullness() { assertMessage( diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeRepairTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeRepairTests.java index a39e4117aa..430bfa9ae3 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeRepairTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeRepairTests.java @@ -76,8 +76,7 @@ public void theSuggestedRequiredTypeIsTheDeclaredTypeNotAnInstantiatedSupertype( """ incompatible nullability: found @Nullable String, required String found: Sub<@Nullable String> - found as: List<@Nullable String> - ^^^^^^^^^^^^^^^^ + ^^^^^^^^^^^^^^^^ required: List ^^^^^^ path: List type argument E diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/ViewedSourceTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/ViewedSourceTests.java index 35eb952b8e..45ee3dac13 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/ViewedSourceTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/ViewedSourceTests.java @@ -3,20 +3,20 @@ import org.junit.Test; /** - * Where the source is compared as a supertype of its own class, the message prints that view on a - * {@code found as:} line, draws the source carets under it, and keeps the {@code path:} and {@code - * note:} lines in the coordinates of the view. + * Where the source is compared as a supertype of another class, the {@code path:} line names the + * position in that supertype. A caret goes under the node of the type the reader wrote where the + * substitution carried that node into the view. Where the node at fault is not in the written type, + * the message prints the view on a {@code found as:} line and draws the source carets under it. */ public class ViewedSourceTests extends MismatchMessageTestBase { @Test - public void aMismatchInsideAWildcardBoundIsMarkedOnTheViewedSource() { + public void aCarriedOverNodeInsideAWildcardBoundIsMarkedOnTheWrittenSource() { assertMessage( """ incompatible nullability: found @Nullable String, required String found: Sub> - found as: Base> - ^^^^^^^^^^^^^^^^ + ^^^^^^^^^^^^^^^^ required: Base> ^^^^^^ path: Base type argument T -> wildcard upper bound -> List type argument E @@ -33,13 +33,12 @@ void test(Sub> s) { } @Test - public void aMismatchInsideAnArrayElementIsMarkedOnTheViewedSource() { + public void aCarriedOverNodeInsideAnArrayElementIsMarkedOnTheWrittenSource() { assertMessage( """ incompatible nullability: found @Nullable String, required String found: Sub<@Nullable String []> - found as: Base<@Nullable String []> - ^^^^^^^^^^^^^^^^ + ^^^^^^^^^^^^^^^^ required: Base ^^^^^^ path: Base type argument T -> array element @@ -56,13 +55,12 @@ void test(Sub<@Nullable String[]> s) { } @Test - public void aCapturedWildcardIsMarkedOnTheViewedSourceAndKeepsItsProvenance() { + public void aCarriedOverCaptureIsMarkedOnTheWrittenSourceAndKeepsItsProvenance() { assertMessage( """ incompatible nullability: found @Nullable Object, required Object found: Sub - found as: Base - ^^^^^^^^^^^^ + ^^^^^^^^^^^^ required: Base ^^^^^^ path: Base type argument T -> wildcard upper bound @@ -83,11 +81,34 @@ void test() { } @Test - public void aPathAcrossAViewReachesIntoWhateverTheSubclassPassed() { + public void aNodeFromTheSubclassDeclarationIsMarkedOnTheViewedSource() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Sub + found as: Base> + ^^^^^^^^^^^^^^^^ + required: Base> + ^^^^^^ + path: Base type argument T -> List type argument E + """, + """ + static class Base {} + static class Sub extends Base> {} + static void take(Base> b) {} + void test(Sub s) { + // BUG: Diagnostic matches: MESSAGE + take(s); + } + """); + } + + @Test + public void aWildcardFromTheSubclassDeclarationGetsANoteThatStatesItsBoundOnly() { assertMessage( """ incompatible nullability: found @Nullable Object, required Object - found: Indirect + found: Sub found as: Base> ^ required: Base> @@ -97,6 +118,31 @@ public void aPathAcrossAViewReachesIntoWhateverTheSubclassPassed() { """, """ static class Base {} + static class Sub extends Base> {} + static void take(Base> b) {} + void test(Sub s) { + // BUG: Diagnostic matches: MESSAGE + take(s); + } + """); + } + + @Test + public void aPathAcrossAViewReachesIntoWhateverTheSubclassPassed() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Indirect + ^ + required: Base> + ^^^^^^ + path: Base type argument B -> wildcard upper bound -> List type argument E -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter X of Indirect + did you mean Indirect? + """, + """ + static class Base {} static class Indirect extends Base> {} static void take(Base> b) {} void test(Indirect i) { @@ -109,7 +155,7 @@ void test(Indirect i) { // b.Result extends a.Result, so the call reaches NullAway and both sides print as // "Result". @Test - public void simpleNamesAloneDoNotShowThatTheTwoTypesComeFromDifferentPackages() { + public void aSubclassOfTheSameSimpleNameIsMarkedOnTheWrittenSource() { makeHelper() .addSourceLines( "a/Result.java", @@ -135,7 +181,6 @@ public class Result extends a.Result {} """ incompatible nullability: found @Nullable String, required String found: Result<@Nullable String> - found as: Result<@Nullable String> ^^^^^^^^^^^^^^^^ required: Result ^^^^^^ From bb1e444ae14d108b6b6ffce2e362e61c0397df1a Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Thu, 26 Nov 2026 23:14:29 +0300 Subject: [PATCH 25/27] Report a type variable whose bound admits null where a non-null wildcard is required Previously, a `Box` declared with `T extends @Nullable Object` was accepted where a `Box` was required, and a `Box` was accepted where a `Box` with that `T` was required, so a null could reach a position that excludes one. The containment check judged a type argument by the annotation on its use site, which a bare type variable has none of, so every such assignment, argument, and return passed. No diagnostic marks the defect; the symptom is the missing error. `CheckIdenticalNullabilityVisitor` now decides the top-level nullness of every wildcard containment check, for `? extends`, `?`, and `? super`, with the JSpecify nullness subtyping rules: a type is a nullness subtype of another where the supertype is null-inclusive, where the subtype is null-exclusive, or where the supertype is a type variable, not written `@NonNull`, that the subtype reaches through declared upper bounds none of which is nullable. A type variable is null-exclusive only through its bounds, so `T` with `T extends @Nullable Object` fits neither `? extends Object` nor the lower bound of `? super T` from a `Box`, while `S` with `S extends T` still fits `? extends T` and `@Nullable T` does not. The path may pass through any element of an intersection, so a capture bounded by `T & @Nullable Runnable` fits `? extends T`, and an intersection is null-exclusive where one of its written elements is, not counting the `Object` javac adds to an intersection of interfaces. A capture is judged by its upper bound, which carries the annotation written on the wildcard it captures. Each type usage carries one of the specification's nullness operators, read in the specification's lenient "some world" sense, and NullAway stays optimistic where a usage is `UNSPECIFIED`, for two stated reasons. A capture in the type of a generic method or diamond call that needs inference, used directly, in parentheses, or through a `var` local it initializes, comes from javac's types, whose captured bounds carry no type-use annotation, so a written `@NonNull` there cannot be read (#1585). A bare type variable actual against a wildcard on a type parameter whose declared bound is not nullable fits there exactly when it is a well-formed instantiation of that parameter, a check of its own (#1946), with the same answer for `?` and for `? extends Object`. A type variable declared in unannotated code admits null only where its bound is annotated `@Nullable` or a library model says so; whether a bound admits null is decided by the helper #1955 uses for inference. A rule written by hand for the type-variable case of `? extends` was tried first; every boundary with the rest of the checker needed an exception of its own, and the `? super` case was missed. The override check adapts the overriding method's types to the overridden method's type parameters before comparing, as JLS 8.4.4 does, so a `Box` returned over a `Box` is judged with one `V`; without the adaptation every such override would be reported. JLS 8.4.4 compares the signatures of methods with the same type parameters only, so where the nullness of a type parameter's bound differs, the bound mismatch is the one error reported. NullAway infers neither a generic constructor called without a diamond nor a generic method reference outside a call needing inference, and a diamond call is inferred only with JSpecifyExperimental, so their type variables can reach the check uninstantiated, and judging them by their bounds would report valid code: `new Consumer(input)` with ` Consumer(Box input)` and a `Box` whose `T` admits null, and `use(Test::singleton)` with ` List singleton(U value)` and `use(Function> f)`. While the arguments of a generic constructor call, or the types of such a reference, are checked, GenericsChecks passes the callee's type variables to the check with that comparison only, and the check compares a marked variable written without an annotation as master compares every type variable: only a type annotated `@Nullable` fails, against one not annotated `@Nullable`. So the check rejects every such call that master rejects, including `new Copier(listOfNullable, listOfNonNull)` with ` Copier(List source, List target)`, which no single `U` satisfies. A type variable of a generic functional-interface method, and one in scope, is not marked. Reading a marked variable as unspecified wherever its bound admits null was rejected: each occurrence then takes its own nullness, and that `Copier` call passes. Inferring these uses was rejected too: with javac's instantiation it needs NestedTypeVarSubstitutionRepairVisitor to restore nested nullability in every argument shape javac drops it from, which full-type inference (#1585) replaces. A generic constructor called with explicit type arguments is compared the same way; substituting them is #2194. Caller sees: - `incompatible types: Box cannot be converted to Box` where `T`'s declared bound admits null, including a bound whose every intersection element is `@Nullable`; accepted before. - `incompatible types: Box cannot be converted to Box` where `T`'s declared bound admits null, and the same for a `Box`; accepted before. - `incompatible types: Box cannot be converted to Box` for ``, whatever `T`'s own bound, and `Box` against `Box` where `T`'s bound admits null; accepted before. - `incompatible types` on `Box sink = inferred` and `Box source = inferred`, where `inferred` is a `Box` that javac inferred as `T` for a generic call such as `id(box)` or `new ArrayList<>(list)`; the second was accepted before. - `incompatible types: List cannot be converted to Collection` on `List copy = new ArrayList<>(in)` with a `List` whose `T` admits null, since the target fixes the constructor's `E` to be non-null; accepted before. - `mismatched type parameter nullability` on an override that returns `List` where the overridden method returns `List` and `V` may be null, such as Caffeine's `AsyncCacheLoader.bulk`; accepted before. - `incompatible types: Box cannot be converted to Box` on `return get();` with `get()` returning `Box` where `T`'s bound admits null, and `RunnableBox cannot be converted to RunnableBox` for a capture bounded by `V & @Nullable Runnable` against `? extends @NonNull Runnable`; accepted before. Not changed: - A type variable declared in unannotated code with no `@Nullable` on its bound and no library model is not reported. - A capture in the inferred type of a generic call is not reported where its bound is bare: `return id(get());` passes where `return get();` is reported, because the inferred type cannot show a written `@NonNull`, as in Caffeine's `CacheLoader.asyncLoadAll` (#1585, #2195). - A generic constructor called with explicit type arguments is compared as one without them, as on master (#2193). - An invariant type argument is compared by annotation only, so `Box x = idBox(box)` is accepted (#1945), and so is a `Box<@NonNull T>` where a `Box` is required. A `Class` still fits a `Class` parameter. - A generic constructor without a diamond and a generic method reference outside an inferred call still report `Box<@Nullable String> cannot be converted to Box` where `U` admits null, and report nothing where a `Box` whose `T` admits null meets a `U` that excludes it, as on master. Assisted-by: Claude Code (claude-fable-5-1) Assisted-by: Claude Code (claude-opus-5-5) --- .../CheckIdenticalNullabilityVisitor.java | 251 +++- .../nullaway/generics/GenericsChecks.java | 165 ++- .../uber/nullaway/generics/GenericsUtils.java | 19 +- .../uber/nullaway/jspecify/WildcardTests.java | 1029 ++++++++++++++++- 4 files changed, 1426 insertions(+), 38 deletions(-) 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/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index 597062b33f..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; @@ -980,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); } @@ -2451,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); } @@ -2487,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; } /** @@ -2660,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); } } @@ -2899,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) -> { @@ -2927,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); @@ -2986,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); } @@ -3079,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); + } } /** @@ -3185,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, @@ -3194,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 typeParameterTrees = tree.getTypeParameters(); for (int i = 0; i < overridingTypeParams.size(); i++) { Symbol.TypeVariableSymbol overridingTv = overridingTypeParams.get(i); @@ -3214,6 +3316,7 @@ private void checkMethodTypeVariableUpperBoundNullnessForOverriding( substitutedMethodTypeVarUpperBoundIsNullable( overriddenTypeVar, overriddenMethod, i, state); if (overridingNullable != overriddenNullable) { + boundsAgree = false; reportMismatchedMethodTypeVariableBoundError( typeParameterTrees.get(i), overridingTv, @@ -3223,6 +3326,7 @@ private void checkMethodTypeVariableUpperBoundNullnessForOverriding( state); } } + return boundsAgree; } /** @@ -4496,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, @@ -4507,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 @@ -4527,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); } 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 07a8864eda..6e5a4e179b 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java @@ -499,16 +499,29 @@ static boolean boundIsExplicitlyNullable( */ static @Nullable Element typeVariableWithNullableBound( Element typeVarElement, Config config, Handler handler, VisitorState state) { - Type upperBound = (Type) ((TypeVariable) typeVarElement.asType()).getUpperBound(); - if (isAnnotatedAsNullable(upperBound, config) - || libraryModelMakesBoundNullable(typeVarElement, handler, 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 true if a library model overrides the upper bound of the given type variable. */ private static boolean libraryModelMakesBoundNullable( Element typeVarElement, Handler handler, VisitorState state) { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java index e04e9870c0..81ef945064 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -2129,6 +2129,634 @@ private CompilationTestHelper makeHelper() { Arrays.asList("-XepOpt:NullAway:OnlyNullMarked=true"))); } + @Test + public void aTypeVariableIsJudgedByItsBoundAgainstAConcreteWildcardRequirement() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static void takeNonNull(Box b) {} + static void takeNullable(Box b) {} + static void takeAny(Box b) {} + static void takeNonNullList(List l) {} + static void nullableBoundIntoNonNull(Box b) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + takeNonNull(b); + } + static void nonNullBoundIntoNonNull(Box b) { + takeNonNull(b); + } + static void nullableBoundIntoNullable(Box b) { + takeNullable(b); + } + static void nullableBoundIntoUnbounded(Box b) { + takeAny(b); + } + static class NonNullParameter {} + static void takeAnyNonNullParameter(NonNullParameter b) {} + static void takeNonNullOfNonNullParameter(NonNullParameter b) {} + static void takeExplicitlyNonNullOfNonNullParameter( + NonNullParameter b) {} + // NonNullParameter is not a well-formed type here, which is a check of its own (#1946) + static void nullableBoundIntoUnboundedNonNullParameter( + NonNullParameter b) { + takeAnyNonNullParameter(b); + } + static void nullableBoundIntoNonNullParameterBound( + NonNullParameter b) { + takeNonNullOfNonNullParameter(b); + takeExplicitlyNonNullOfNonNullParameter(b); + } + static void nullableBoundIntoUnannotatedNonNullRequirement( + List l) { + // BUG: Diagnostic contains: incompatible types: List cannot be converted to List + takeNonNullList(l); + } + static boolean nullableBoundIntoClassOfAnything( + Class other, Class type) { + return other.isAssignableFrom(type); + } + } + """) + .doTest(); + } + + @Test + public void nullnessWrittenOnATypeVariableUseOverridesItsBound() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static void takeNonNull(Box b) {} + static void takeNullable(Box b) {} + static void nullableUseIntoNonNull(Box<@Nullable T> b) { + // BUG: Diagnostic contains: incompatible types: Box<@Nullable T> cannot be converted to Box + takeNonNull(b); + } + static void nullableUseIntoNullable(Box<@Nullable T> b) { + takeNullable(b); + } + static void nonNullUseIntoNonNull(Box<@NonNull T> b) { + takeNonNull(b); + } + } + """) + .doTest(); + } + + @Test + public void aBoundReachedThroughAnotherVariableOrAWildcardDecidesAgainstAConcreteRequirement() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static void takeNonNull(Box b) {} + static void variableOverNullableBound( + Box b) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + takeNonNull(b); + } + static void variableOverNonNullBound(Box b) { + takeNonNull(b); + } + static + void nonNullVariableOverNullableBound(Box b) { + takeNonNull(b); + } + static void wildcardOverNullableBound(Box b) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + takeNonNull(b); + } + static void wildcardOverNonNullBound(Box b) { + takeNonNull(b); + } + } + """) + .doTest(); + } + + @Test + public void aTypeVariableDeclaredInUnannotatedCodeAdmitsNullOnlyWhenItsBoundSaysSo() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.NullUnmarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static void takeNonNull(Box b) {} + @NullUnmarked + static class Unannotated { + @NullMarked + void unannotatedDeclarationIntoNonNull(Box b) { + takeNonNull(b); + } + @NullMarked + void variableOverADefaultBound(Box b) { + takeNonNull(b); + } + } + @NullUnmarked + static class UnannotatedNullableBound { + @NullMarked + void explicitNullableBoundIntoNonNull(Box b) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + takeNonNull(b); + } + @NullMarked + void variableOverAnExplicitNullableBound(Box b) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + takeNonNull(b); + } + } + static class Annotated { + void annotatedDeclarationIntoNonNull(Box b) { + takeNonNull(b); + } + } + @NullUnmarked + static class UnannotatedNonNullBound { + @NullMarked + void explicitNonNullBoundIntoNonNull(Box b) { + takeNonNull(b); + } + @NullMarked + void variableOverAnExplicitNonNullBound(Box b) { + takeNonNull(b); + } + } + } + """) + .doTest(); + } + + @Test + public void aTypeVariableIsJudgedByItsBoundAgainstAWildcardWithALowerBound() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box { + void set(E e) {} + } + static class NullableBound { + void takeSuperT(Box b, T t) { + b.set(t); + } + void nonNullArgument(Box b, T t) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + takeSuperT(b, t); + } + void nonNullLowerBound(Box b, T t) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + takeSuperT(b, t); + } + void sameVariable(Box b, T t) { + takeSuperT(b, t); + } + void nullableUse(Box<@Nullable T> b, T t) { + takeSuperT(b, t); + } + void nullableArgument(Box<@Nullable Object> b, T t) { + takeSuperT(b, t); + } + } + static class NonNullBound { + void takeSuperT(Box b, T t) { + b.set(t); + } + void nonNullArgument(Box b, T t) { + takeSuperT(b, t); + } + void nonNullLowerBound(Box b, T t) { + takeSuperT(b, t); + } + } + } + """) + .doTest(); + } + + @Test + public void theTypeArgumentsOfATypeVariableBoundAreComparedAgainstAConcreteRequirement() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static void takeNonNullElements(Box> b) {} + static > void nullableElements(Box b) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box> + takeNonNullElements(b); + } + static > void nonNullElements(Box b) { + takeNonNullElements(b); + } + } + """) + .doTest(); + } + + @Test + public void anIntersectionAdmitsNullOnlyWhereEveryElementDoes() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.io.Serializable; + import java.util.List; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.NullUnmarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static void takeNonNull(Box b) {} + static void everyElementNullable( + Box b) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + takeNonNull(b); + } + static void oneElementNonNull(Box b) { + takeNonNull(b); + } + static void takeNonNullList(List l) {} + static void leastUpperBound(boolean c, List integers, List strings) { + var either = c ? integers : strings; + takeNonNullList(either); + } + @NullUnmarked + static class Unannotated { + @NullMarked + static void everyElementNullable( + Box b) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + takeNonNull(b); + } + @NullMarked + static void oneElementNonNull( + Box b) { + takeNonNull(b); + } + @NullMarked + static void oneElementBare(Box b) { + takeNonNull(b); + } + } + } + """) + .doTest(); + } + + @Test + public void aTypeVariableIsComparedAsWrittenAgainstAWildcardBoundedByATypeVariable() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.NullUnmarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static class NullableBound { + void takeExtendsT(Box b) {} + Box sameVariable(Box b) { + return b; + } + void variableThatExtendsIt(Box b) { + takeExtendsT(b); + } + void nullableUse(Box<@Nullable T> b) { + // BUG: Diagnostic contains: incompatible types: Box<@Nullable T> cannot be converted to Box + takeExtendsT(b); + } + void variableThatAdmitsNullBeyondIt(Box b) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + takeExtendsT(b); + } + void variableReachingItThroughANullableLink( + Box b) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + takeExtendsT(b); + } + void variableReachingItThroughANonNullLink(Box b) { + takeExtendsT(b); + } + void nonNullUseOfAVariableThatAdmitsNull(Box<@NonNull S> b) { + takeExtendsT(b); + } + void nullableLinkAboveANonNullLink( + Box b) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + takeExtendsT(b); + } + void takeExtendsNullableT(Box b) {} + void nullableUseIntoNullableProjection(Box<@Nullable T> b) { + takeExtendsNullableT(b); + } + @NullUnmarked + class Unannotated { + @NullMarked + void variableDeclaredInUnannotatedCode(Box b) { + takeExtendsT(b); + } + } + @NullUnmarked + class UnannotatedNullableLink { + @NullMarked + void explicitNullableLinkDeclaredInUnannotatedCode(Box b) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + takeExtendsT(b); + } + } + @NullUnmarked + class UnannotatedNonNullLink { + @NullMarked + void explicitNonNullLinkDeclaredInUnannotatedCode(Box b) { + takeExtendsT(b); + } + } + } + static class NonNullBound { + void takeExtendsT(Box b) {} + void variableThatAdmitsNull(Box b) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + takeExtendsT(b); + } + void variableThatAdmitsNoNull(Box b) { + takeExtendsT(b); + } + void nullableLinkAboveANonNullLink( + Box b) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + takeExtendsT(b); + } + } + } + """) + .doTest(); + } + + @Test + public void aTypeVariableThatMayBeNullFailsANonNullProjectionOfATypeVariable() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.NullUnmarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static class NullableBound { + void takeExtendsNonNullT(Box b) {} + void bareUse(Box b) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + takeExtendsNonNullT(b); + } + void wildcardUse(Box b) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + takeExtendsNonNullT(b); + } + } + static class NonNullBound { + void takeExtendsNonNullT(Box b) {} + void bareUse(Box b) { + takeExtendsNonNullT(b); + } + } + @NullUnmarked + static class UnannotatedDefaultBound { + @NullMarked + Box bareUse(Box b) { + return b; + } + } + @NullUnmarked + static class UnannotatedNullableBound { + @NullMarked + Box bareUse(Box b) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + return b; + } + } + @NullUnmarked + static class UnannotatedNonNullBound { + @NullMarked + Box bareUse(Box b) { + return b; + } + } + } + """) + .doTest(); + } + + /** + * Taken from Caffeine's {@code CacheLoader.asyncReload}: {@code CompletableFuture.supplyAsync} + * infers {@code CompletableFuture} against {@code CompletableFuture}. + */ + @Test + public void aTypeVariableMeetsAWildcardBoundedByThatSameTypeVariableUnderInference() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.concurrent.CompletableFuture; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + interface Test { + V load(); + CompletableFuture loadFuture(); + default CompletableFuture asyncLoad() { + return CompletableFuture.supplyAsync(() -> load()); + } + default CompletableFuture nonNullFuture() { + // BUG: Diagnostic contains: incompatible types: CompletableFuture cannot be converted to CompletableFuture + return loadFuture(); + } + } + """) + .doTest(); + } + + @Test + public void anInferredTypeArgumentMeetsAWildcardBoundedByTheSameTypeVariable() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.ArrayList; + import java.util.Collection; + import java.util.Collections; + import java.util.HashSet; + import java.util.List; + import java.util.Set; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static List copyOf(Collection c) { + throw new UnsupportedOperationException(); + } + static List copyNonNull( + Collection c) { + throw new UnsupportedOperationException(); + } + void genericMethod(List in) { + List copy = copyOf(in); + } + void writtenNonNullProjection(List in) { + // BUG: Diagnostic contains: incompatible types + List copy = copyNonNull(in); + } + void diamond(List in) { + Set set = new HashSet<>(in); + } + static void methodTypeVariable(List in) { + List copy = new ArrayList<>(in); + List view = Collections.unmodifiableList(in); + } + } + """) + .doTest(); + } + + @Test + public void inferenceAddsNoReportAgainstAConcreteWildcard() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import java.util.Map; + import java.util.concurrent.CompletableFuture; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box { + Box(E e) {} + } + static U id(U u) { + return u; + } + static void takeWithValue(U u, Box b) {} + List nonNullElements() { + throw new UnsupportedOperationException(); + } + Map nonNullValues() { + throw new UnsupportedOperationException(); + } + List elements() { + throw new UnsupportedOperationException(); + } + List captureThroughGenericMethod() { + return id(nonNullElements()); + } + List noCaptureThroughGenericMethod() { + // BUG: Diagnostic contains: incompatible types: List cannot be converted to List + return id(elements()); + } + Box> captureThroughDiamond() { + return new Box<>(nonNullElements()); + } + CompletableFuture> captureThroughLambda() { + return CompletableFuture.supplyAsync(() -> nonNullValues()); + } + static void boundInferredFromAnotherArgument(Box b) { + takeWithValue("x", b); + } + } + """) + .doTest(); + } + + @Test + public void anInferenceVariableFixedByTheTargetExcludesNullAndOneLeftToTheArgumentDoesNot() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.ArrayList; + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static Box idBox(Box b) { + return b; + } + static void variableFixedByAWildcardTarget(Box b) { + // not reported, a known false negative (#1945): the target fixes U as non-null, and + // the argument Box is compared with Box<@NonNull U> by annotation only + Box x = idBox(b); + } + static U first(Box b) { + throw new UnsupportedOperationException(); + } + static Object variableFixedByTheReturnTarget(Box b) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + return first(b); + } + static void variableLeftToTheArgumentThenDereferenced( + Box b) { + first(b).toString(); + } + static void variableFixedByTheTarget(List in) { + // BUG: Diagnostic contains: incompatible types: List cannot be converted to Collection (List is a subtype of Collection) + List copy = new ArrayList<>(in); + } + static void variableLeftToTheArgument(List in) { + List copy = new ArrayList<>(in); + } + } + """) + .doTest(); + } + @Test public void anInferenceResultFixedNonNullKeepsNullOutOfALowerBound() { makeHelper() @@ -2176,6 +2804,70 @@ void fixedByAProjection(Box<@NonNull T> original) { .doTest(); } + /** + * Where javac infers a type argument as a type variable in scope, as {@code E := T} in {@code var + * inferred = id(original)}, the result is judged by the declared bound of {@code T}, which admits + * null. Otherwise a null written through {@code sink} would reach the {@code Box} passed in, + * which holds no null when {@code T} is {@code Object}. + */ + @Test + public void anInferenceResultLeftToATypeVariableIsJudgedAsThatTypeVariable() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.ArrayList; + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box { + void set(E e) {} + } + static Box id(Box box) { + return box; + } + static Box> nest(Box box) { + throw new UnsupportedOperationException(); + } + void intoTheSameTypeVariable(Box original) { + var inferred = id(original); + Box sink = inferred; + Box source = inferred; + } + void intoANullableLowerBound(Box original) { + var inferred = id(original); + // BUG: Diagnostic contains: incompatible types + Box sink = inferred; + sink.set(null); + } + void intoANonNullUpperBound(Box original) { + var inferred = id(original); + // BUG: Diagnostic contains: incompatible types + Box source = inferred; + } + void throughADiamond(List original) { + var inferred = new ArrayList<>(original); + List sink = inferred; + // BUG: Diagnostic contains: incompatible types + List nullableSink = inferred; + } + void inANestedTypeArgument(Box original) { + var inferred = nest(original); + Box> sink = inferred; + // BUG: Diagnostic contains: incompatible types + Box> nullableSink = inferred; + } + void ofACapturedWildcard(Box original) { + var inferred = id(original); + Box sink = inferred; + } + } + """) + .doTest(); + } + /** * Where javac inferred a class type, such as {@code Object} for the least upper bound of {@code * T} and {@code String}, an inference variable that a {@code T} whose bound admits null reached @@ -3148,6 +3840,9 @@ static U nonNullVariable(Box b) { static V pair(Box b, V v) { throw new UnsupportedOperationException(); } + static U nonNullVariableWithValue(Box b, U u) { + return u; + } static void intoNonNullVariable(Box b) { // BUG: Diagnostic contains: inference failure: type variable U of Test.nonNullVariable is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument T passed for ? extends U admits null, since T of Test.intoNonNullVariable has a @Nullable upper bound Object o = nonNullVariable(b); @@ -3206,6 +3901,7 @@ static class Pair {} static void intoSelfPair(Pair p) {} static void wildcardOfAPairWhoseSiblingIsNonNull( Pair p) { + // BUG: Diagnostic contains: incompatible types: Pair cannot be converted to Pair intoSelfPair(p); } static void wildcardOfAPairWhoseSiblingAdmitsNull( @@ -3245,7 +3941,7 @@ static void nonNullBoundIntoNonNullVariable(Box b) { } static void intoNullableVariableThatTheContextMakesNonNull( Box b) { - // a false negative: the assignment, not the bound of U, makes U non-null (#1945) + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box List c = copy(b); } static void intoNonNullVariableByAnExplicitTypeArgument( @@ -3294,6 +3990,11 @@ static List identity(List xs) { // a false negative: the diamond's result reaches copyOf without a local (#1947) List copy = List.copyOf(new ArrayList<>(in)); } + static void intoNonNullVariableFixedByAnotherArgument( + Box b) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + Object o = nonNullVariableWithValue(b, new Object()); + } static void intoJdkCopyOf(List in) { // BUG: Diagnostic contains: inference failure: type variable E of List.copyOf is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument T passed for ? extends E admits null, since T of Test.intoJdkCopyOf has a @Nullable upper bound List copy = List.copyOf(in); @@ -3574,10 +4275,27 @@ static U nonNullVariable(Box b) { static class GenericConstructor { GenericConstructor(Box b) {} } + static class NullableGenericConstructor { + NullableGenericConstructor(Box b) {} + } + static class Sink { + Sink(java.util.List target) {} + } + void typeVariableIntoADiamondWhoseVariableAdmitsNull(Box b) { + var c = new NullableGenericConstructor<>(b); + var s = new Sink<>(new java.util.ArrayList()); + } void typeVariable(Box b) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box Object o = nonNullVariable(b); } void typeVariableIntoADiamond(Box b) { + // not reported, a known false negative: NullAway infers no W for a generic + // constructor without JSpecifyExperimental (#1585) + var c = new GenericConstructor<>(b); + } + void nullableTypeArgumentIntoADiamond(Box<@Nullable String> b) { + // BUG: Diagnostic contains: incompatible types: Box<@Nullable String> cannot be converted to Box var c = new GenericConstructor<>(b); } static R viaBound(U a, U b) { @@ -3603,4 +4321,313 @@ void nullableTypeArgument(Box<@Nullable String> b) { """) .doTest(); } + + @Test + public void aCaptureIsJudgedByItsWildcardBoundOutsideTheInferredTypeOfAGenericCall() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.Map; + import java.util.Set; + import java.util.concurrent.CompletableFuture; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static U id(U u) { + return u; + } + interface ConcreteRequirement { + Box get(); + Box getNonNull(); + default Box passCall() { + // BUG: Diagnostic contains: Box cannot be converted to Box + return get(); + } + default Box passVariable(Box b) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + return b; + } + default void assignCall() { + // BUG: Diagnostic contains: Box cannot be converted to Box + Box x = get(); + } + default Box passNonNullCall() { + return getNonNull(); + } + default Box passNonNullCallThroughInference() { + return id(getNonNull()); + } + default Box passParenthesizedNonNullCallThroughInference() { + return (id(getNonNull())); + } + default Box passNonNullCallThroughAVarLocal() { + var v = id(getNonNull()); + return v; + } + // a capture javac made while inferring id's type has lost any annotation on its + // bound, so a bound written bare is not reported either (#2195) + default Box passCallThroughInference() { + return id(get()); + } + } + static class RunnableBox {} + interface IntersectionRequirement { + RunnableBox loadAll(); + // the capture's bound is V & @Nullable Runnable, an intersection; inference drops + // the @NonNull as in NonNullProjectionRequirement.asyncLoadAll (#1585) + default CompletableFuture> async() { + return CompletableFuture.supplyAsync(() -> loadAll()); + } + } + interface IntersectionDirectRequirement { + RunnableBox loadAll(); + // the capture's bound is V & @Nullable Runnable, and neither element excludes null + default RunnableBox pass() { + // BUG: Diagnostic contains: RunnableBox cannot be converted to RunnableBox + return loadAll(); + } + } + interface IntersectionToItsElement { + RunnableBox loadAll(); + // the capture's bound V & @Nullable Runnable reaches V through its element V + default RunnableBox pass() { + return loadAll(); + } + } + interface AllInterfaceIntersection { + RunnableBox load(); + // the capture's bound @Nullable AutoCloseable & @Nullable Runnable has no element + // that excludes null; javac adds an implicit Object element that is not written + default RunnableBox pass() { + // BUG: Diagnostic contains: RunnableBox cannot be converted to RunnableBox + return load(); + } + } + interface IntersectionReachingNoElement< + W extends @Nullable Object, V extends @Nullable W> { + RunnableBox loadAll(); + // V reaches W only through the nullable link V extends @Nullable W + default RunnableBox pass() { + // BUG: Diagnostic contains: RunnableBox cannot be converted to RunnableBox + return loadAll(); + } + } + interface BareRequirement { + Map loadAll(); + default Map pass() { + return loadAll(); + } + } + interface NonNullProjectionOfAnIntermediateVariable< + V extends @Nullable Object, S extends @Nullable V> { + Map loadAll(); + default CompletableFuture> loadAllAsync() { + return CompletableFuture.supplyAsync(() -> loadAll()); + } + } + interface NonNullProjectionRequirement { + Map loadAll(Set keys); + default CompletableFuture> asyncLoadAll( + Set keys) { + return CompletableFuture.supplyAsync(() -> loadAll(keys)); + } + } + } + """) + .doTest(); + } + + @Test + public void aGenericMethodOverrideMeetsAWildcardBoundedByTheOverriddenMethodTypeVariable() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.function.Function; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + interface Mapper { + Mapper map(Function f); + Box wrap(V v); + Box get(); + Box getWildcard(); + } + abstract static class Impl implements Mapper { + @Override + public abstract Mapper map( + Function f); + @Override + public abstract Box wrap(V v); + } + abstract static class NonNullProjection implements Mapper { + @Override + public abstract Mapper map( + // BUG: Diagnostic contains: mismatched type parameter nullability + Function f); + @Override + public abstract Box wrap(V v); + } + abstract static class Narrowed implements Mapper { + @Override + // BUG: Diagnostic contains: Method type variable R has a non-null upper bound + public abstract + // a report on the parameter's own line would fail the test as unexpected + Mapper map( + Function f); + @Override + public abstract Box wrap(V v); + @Override + // BUG: Diagnostic contains: Method type variable U has a non-null upper bound + public abstract + // a report on the method name's line would fail the test as unexpected + Box + get(); + @Override + // BUG: Diagnostic contains: Method type variable U has a non-null upper bound + public abstract + Box + getWildcard(); + } + } + """) + .doTest(); + } + + @Test + public void anUninferredTypeVariableRejectsOnlyAnExplicitlyNullableTypeArgument() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import java.util.function.Consumer; + import java.util.function.Function; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static class NullableConsumer { + NullableConsumer(Box input) {} + } + static class GenericNullableConsumer { + GenericNullableConsumer(Box input) {} + } + static class StrictConsumer { + StrictConsumer(Box input) {} + } + static class Copier { + Copier(List source, List target) {} + } + interface Sink { + void accept(List elements); + } + static List singleton(U value) { + use(Test::singleton); + throw new UnsupportedOperationException(); + } + static void take(Box input) {} + static void takeAny(Box input) {} + static void takeNonNull(List elements) {} + static void use(Function> f) {} + static void useBoxes(Consumer> c) {} + static void useSink(Sink sink) {} + void aTypeVariableWhoseBoundAdmitsNull(Box input) { + new NullableConsumer(input); + new GenericNullableConsumer(input); + new NullableConsumer(input) {}; + new NullableConsumer(input); + use(Test::singleton); + } + void aTypeVariableWhoseBoundAdmitsNullIntoOneThatExcludesIt(Box input) { + // not reported, a known false negative: NullAway infers no U for a generic + // constructor called without a diamond (#2191) + new StrictConsumer(input); + } + void anExplicitlyNullableTypeArgument( + Box<@Nullable String> nullable, List<@Nullable String> source, List target) { + // BUG: Diagnostic contains: Box<@Nullable String> cannot be converted to Box + new StrictConsumer(nullable); + // BUG: Diagnostic contains: List<@Nullable String> cannot be converted to List + new Copier(source, target); + // BUG: Diagnostic contains: parameter type of referenced method is Box + useBoxes(Test::take); + } + void explicitMethodReferenceTypeArguments() { + useBoxes(Test::<@Nullable String>takeAny); + // BUG: Diagnostic contains: parameter type of referenced method is Box + useBoxes(Test::takeAny); + } + void aTypeVariableOfAGenericFunctionalInterfaceMethodKeepsItsBound() { + // BUG: Diagnostic contains: parameter type of referenced method is List + useSink(Test::takeNonNull); + } + void aTypeVariableInScope(Box box) { + // BUG: Diagnostic contains: Box cannot be converted to Box + Box nonNull = box; + } + void referencedBeforeItsDeclaration() { + use(Test::boxed); + } + static List boxed(U value) { + Box box = new Box<>(); + // BUG: Diagnostic contains: Box cannot be converted to Box + Box nonNull = box; + throw new UnsupportedOperationException(); + } + void constructedBeforeItsDeclaration(Box input) { + new Checked(input); + } + static class Checked { + Checked(Box input) { + Box box = new Box<>(); + // BUG: Diagnostic contains: Box cannot be converted to Box + Box nonNull = box; + } + } + } + """) + .doTest(); + } + + @Test + public void anOverrideReturnTypeMustKeepANonNullProjection() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + interface Test { + List get(); + static Test widened() { + return new Test<>() { + // BUG: Diagnostic contains: Method returns List, but overridden method returns List, which has mismatched type parameter nullability + @Override public List get() { + throw new UnsupportedOperationException(); + } + }; + } + static Test kept() { + return new Test<>() { + @Override public List<@NonNull V> get() { + throw new UnsupportedOperationException(); + } + }; + } + } + """) + .doTest(); + } } From c357279e607cdb592f67ed0810841c715374d660 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Wed, 9 Sep 2026 17:34:12 +0300 Subject: [PATCH 26/27] Explain a type variable whose bound admits null instead of falling back The check rejects a Box declared with T extends @Nullable Object where a Box is required, and the message said only that the two types were incompatible: the traversal that finds the differing positions judged the type variable by its use site, found no difference, and left the reporter with the fallback text. It now takes the same step the check takes, so the reader gets the position and the reason: the caret stays on the T they wrote, found names the bound the variable was declared with, and a note says the nullness comes from there. A use that states its own nullness keeps it, and gets no note, since the printed @Nullable T already says what the note would. A captured wildcard is a Type.TypeVar as well, so the note is reached only after the wildcard arms have had their say, and a capture keeps the provenance note it had. Assisted-by: Claude Code (claude-opus-5) --- .../uber/nullaway/generics/GenericsUtils.java | 18 +++++++++ .../generics/NullabilityMismatchMessage.java | 19 ++++++++-- .../generics/NullabilityMismatches.java | 9 +++++ .../jspecify/mismatchmessage/NoteTests.java | 37 ++++++++++++++++++- 4 files changed, 77 insertions(+), 6 deletions(-) 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 6e5a4e179b..b095911b10 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java @@ -522,6 +522,24 @@ static boolean declaredBoundIsExplicitlyNullable( || 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) { diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java index ea9fe6092c..6922aab756 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -59,7 +59,9 @@ * {@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. Where the source wildcard + *

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 @@ -448,8 +450,9 @@ private static String wrapped(String text, int firstLineIndent, String continuat } /** - * Says where the source wildcard takes its upper bound from, or returns {@code null} where the - * printed type already shows that bound or the type variable cannot be named. + * 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 @@ -464,7 +467,15 @@ private static String wrapped(String text, int firstLineIndent, String continuat // 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) { - return 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 diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java index f049d0d47c..fe9f552abf 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java @@ -193,6 +193,15 @@ private void collect( // 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)) { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/NoteTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/NoteTests.java index c0142f66d2..194ee810dd 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/NoteTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/NoteTests.java @@ -4,8 +4,9 @@ /** * A {@code note:} line says where the source takes a nullness its printed form does not show: the - * bound an unbounded or lower-bounded wildcard inherits, or the type parameter a captured wildcard - * instantiates. A source that prints its own nullness gets no note. + * bound an unbounded or lower-bounded wildcard inherits, the type parameter a captured wildcard + * instantiates, or the declared bound of a type variable written without nullness. A source that + * prints its own nullness gets no note. */ public class NoteTests extends MismatchMessageTestBase { @@ -87,6 +88,38 @@ void test(List l) { """); } + @Test + public void aTypeVariableWithANullableBoundIsReportedBesideAMismatchingSibling() { + assertMessage( + """ + incompatible nullability: 2 mismatches between source and target types + found: Pair + ^ ^^^^^^^^^^^^^^^^ + 1 2 + required: Pair + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: Pair type argument A -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source T has no nullness of its own, so it takes the nullness of its declared upper + bound + \s + 2. path: Pair type argument B + found: @Nullable String + required: String + """, + """ + static class Pair {} + static void take(Pair p) {} + static void test(Pair p) { + // BUG: Diagnostic matches: MESSAGE + take(p); + } + """); + } + @Test public void noInheritedBoundNoteWhereTheUseStatesItsOwnNullness() { assertMessage( From 686063191c5385dc51d2d74e7f32176adcab5152 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Fri, 27 Nov 2026 12:59:45 +0300 Subject: [PATCH 27/27] Check the #1834 tests against the mismatch message With #1828 below it, the containment reports of #1834 print the marked diff of the two types, so the tests that matched the old `incompatible types: A cannot be converted to B` text now match the first line of the new message, or the `found:` line where the old text named the source type alone. CheckIdenticalNullabilityVisitorTests, added on master by #2095, constructs the visitor with the comparison context #1834 added. Assisted-by: Claude Code (claude-opus-5-5) --- ...CheckIdenticalNullabilityVisitorTests.java | 7 +- .../uber/nullaway/jspecify/WildcardTests.java | 96 +++++++++---------- 2 files changed, 54 insertions(+), 49 deletions(-) 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/jspecify/WildcardTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java index 81ef945064..7f28b82277 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -2147,7 +2147,7 @@ static void takeNullable(Box b) {} static void takeAny(Box b) {} static void takeNonNullList(List l) {} static void nullableBoundIntoNonNull(Box b) { - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object takeNonNull(b); } static void nonNullBoundIntoNonNull(Box b) { @@ -2176,7 +2176,7 @@ static void takeExplicitlyNonNullOfNonNullParameter( } static void nullableBoundIntoUnannotatedNonNullRequirement( List l) { - // BUG: Diagnostic contains: incompatible types: List cannot be converted to List + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object takeNonNullList(l); } static boolean nullableBoundIntoClassOfAnything( @@ -2203,7 +2203,7 @@ static class Box {} static void takeNonNull(Box b) {} static void takeNullable(Box b) {} static void nullableUseIntoNonNull(Box<@Nullable T> b) { - // BUG: Diagnostic contains: incompatible types: Box<@Nullable T> cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable T, required Object takeNonNull(b); } static void nullableUseIntoNullable(Box<@Nullable T> b) { @@ -2232,7 +2232,7 @@ static class Box {} static void takeNonNull(Box b) {} static void variableOverNullableBound( Box b) { - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable T, required Object takeNonNull(b); } static void variableOverNonNullBound(Box b) { @@ -2243,7 +2243,7 @@ void nonNullVariableOverNullableBound(Box b) { takeNonNull(b); } static void wildcardOverNullableBound(Box b) { - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object takeNonNull(b); } static void wildcardOverNonNullBound(Box b) { @@ -2283,12 +2283,12 @@ void variableOverADefaultBound(Box b) { static class UnannotatedNullableBound { @NullMarked void explicitNullableBoundIntoNonNull(Box b) { - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object takeNonNull(b); } @NullMarked void variableOverAnExplicitNullableBound(Box b) { - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable T, required Object takeNonNull(b); } } @@ -2378,7 +2378,7 @@ class Test { static class Box {} static void takeNonNullElements(Box> b) {} static > void nullableElements(Box b) { - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box> + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String takeNonNullElements(b); } static > void nonNullElements(Box b) { @@ -2407,7 +2407,7 @@ static class Box {} static void takeNonNull(Box b) {} static void everyElementNullable( Box b) { - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object & @Nullable Serializable, required Object takeNonNull(b); } static void oneElementNonNull(Box b) { @@ -2423,7 +2423,7 @@ static class Unannotated { @NullMarked static void everyElementNullable( Box b) { - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object & @Nullable Serializable, required Object takeNonNull(b); } @NullMarked @@ -2463,16 +2463,16 @@ void variableThatExtendsIt(Box b) { takeExtendsT(b); } void nullableUse(Box<@Nullable T> b) { - // BUG: Diagnostic contains: incompatible types: Box<@Nullable T> cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable T, required T takeExtendsT(b); } void variableThatAdmitsNullBeyondIt(Box b) { - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable T, required T takeExtendsT(b); } void variableReachingItThroughANullableLink( Box b) { - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable S, required T takeExtendsT(b); } void variableReachingItThroughANonNullLink(Box b) { @@ -2483,7 +2483,7 @@ void nullableUse(Box<@Nullable T> b) { } void nullableLinkAboveANonNullLink( Box b) { - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable S, required T takeExtendsT(b); } void takeExtendsNullableT(Box b) {} @@ -2501,7 +2501,7 @@ void variableDeclaredInUnannotatedCode(Box b) { class UnannotatedNullableLink { @NullMarked void explicitNullableLinkDeclaredInUnannotatedCode(Box b) { - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable T, required T takeExtendsT(b); } } @@ -2516,7 +2516,7 @@ void explicitNonNullLinkDeclaredInUnannotatedCode(Box b) { static class NonNullBound { void takeExtendsT(Box b) {} void variableThatAdmitsNull(Box b) { - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable T, required T takeExtendsT(b); } void variableThatAdmitsNoNull(Box b) { @@ -2524,7 +2524,7 @@ void variableThatAdmitsNoNull(Box b) { } void nullableLinkAboveANonNullLink( Box b) { - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable S, required T takeExtendsT(b); } } @@ -2549,11 +2549,11 @@ static class Box {} static class NullableBound { void takeExtendsNonNullT(Box b) {} void bareUse(Box b) { - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required T takeExtendsNonNullT(b); } void wildcardUse(Box b) { - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required T takeExtendsNonNullT(b); } } @@ -2574,7 +2574,7 @@ static class UnannotatedDefaultBound { static class UnannotatedNullableBound { @NullMarked Box bareUse(Box b) { - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required T return b; } } @@ -2611,7 +2611,7 @@ default CompletableFuture asyncLoad() { return CompletableFuture.supplyAsync(() -> load()); } default CompletableFuture nonNullFuture() { - // BUG: Diagnostic contains: incompatible types: CompletableFuture cannot be converted to CompletableFuture + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object return loadFuture(); } } @@ -2647,7 +2647,7 @@ void genericMethod(List in) { List copy = copyOf(in); } void writtenNonNullProjection(List in) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required T List copy = copyNonNull(in); } void diamond(List in) { @@ -2696,7 +2696,7 @@ List captureThroughGenericMethod() { return id(nonNullElements()); } List noCaptureThroughGenericMethod() { - // BUG: Diagnostic contains: incompatible types: List cannot be converted to List + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object return id(elements()); } Box> captureThroughDiamond() { @@ -2738,7 +2738,7 @@ static class Box {} throw new UnsupportedOperationException(); } static Object variableFixedByTheReturnTarget(Box b) { - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required T return first(b); } static void variableLeftToTheArgumentThenDereferenced( @@ -2746,7 +2746,7 @@ static class Box {} first(b).toString(); } static void variableFixedByTheTarget(List in) { - // BUG: Diagnostic contains: incompatible types: List cannot be converted to Collection (List is a subtype of Collection) + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object List copy = new ArrayList<>(in); } static void variableLeftToTheArgument(List in) { @@ -2844,7 +2844,7 @@ void intoANullableLowerBound(Box original) { } void intoANonNullUpperBound(Box original) { var inferred = id(original); - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object Box source = inferred; } void throughADiamond(List original) { @@ -2906,11 +2906,11 @@ void throughALocal(T t) { var inferred = of(t, "x"); List sink = inferred; sink.add(null); - // BUG: Diagnostic contains: incompatible types: List<@Nullable Object> cannot be converted to List + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object List source = inferred; // BUG: Diagnostic contains: dereferenced expression 'inferred.get(0)' is @Nullable inferred.get(0).toString(); - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object takeObjects(inferred); } void throughTheCall(T t) { @@ -3027,7 +3027,7 @@ void f(T t) { // BUG: Diagnostic contains: dereferenced expression 'box.self().get()' is @Nullable box.self().get().toString(); box.sink().set(null); - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object Box nonNull = box.self(); } } @@ -3400,7 +3400,7 @@ static V nonNullIdentity(V v) { } void takeFn(X x, Function, List<@Nullable T>> f) {} void genericConstructorAtADiamondTakingTwoLists(List a, List<@Nullable T> b) { - // BUG: Diagnostic contains: incompatible types: List<@Nullable T> cannot be converted to List + // BUG: Diagnostic contains: incompatible nullability: found @Nullable T, required T var c = new TwoLists<>(a, b); } void genericMethodReferenceUnderAGenericCall() { @@ -3901,7 +3901,7 @@ static class Pair {} static void intoSelfPair(Pair p) {} static void wildcardOfAPairWhoseSiblingIsNonNull( Pair p) { - // BUG: Diagnostic contains: incompatible types: Pair cannot be converted to Pair + // BUG: Diagnostic contains: incompatible nullability: found @Nullable S, required S intoSelfPair(p); } static void wildcardOfAPairWhoseSiblingAdmitsNull( @@ -3941,7 +3941,7 @@ static void nonNullBoundIntoNonNullVariable(Box b) { } static void intoNullableVariableThatTheContextMakesNonNull( Box b) { - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object List c = copy(b); } static void intoNonNullVariableByAnExplicitTypeArgument( @@ -3992,7 +3992,7 @@ static List identity(List xs) { } static void intoNonNullVariableFixedByAnotherArgument( Box b) { - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object Object o = nonNullVariableWithValue(b, new Object()); } static void intoJdkCopyOf(List in) { @@ -4158,7 +4158,7 @@ void genericConstructorAtADiamond(List a, List<@Nullable T> b) { var c = new C<>(a, b); } void genericMethod(List a, List<@Nullable T> b) { - // BUG: Diagnostic contains: incompatible types: List<@Nullable T> cannot be converted to List + // BUG: Diagnostic contains: incompatible nullability: found @Nullable T, required T m(a, b); } void genericMethodReferenceUnderAGenericCall() { @@ -4171,7 +4171,7 @@ void genericConstructorTakingAListOfNullableElements(List<@Nullable String> l) { var c = new ListAndElement<>( // a false positive that JSpecifyExperimental removes - // BUG: Diagnostic contains: incompatible types: List<@Nullable String> cannot be converted to List + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required W l, // a false positive: W of a generic constructor at a diamond is not inferred // (#1825) @@ -4286,7 +4286,7 @@ void typeVariableIntoADiamondWhoseVariableAdmitsNull(Box b) { var s = new Sink<>(new java.util.ArrayList()); } void typeVariable(Box b) { - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required T Object o = nonNullVariable(b); } void typeVariableIntoADiamond(Box b) { @@ -4295,7 +4295,7 @@ void typeVariableIntoADiamond(Box b) { var c = new GenericConstructor<>(b); } void nullableTypeArgumentIntoADiamond(Box<@Nullable String> b) { - // BUG: Diagnostic contains: incompatible types: Box<@Nullable String> cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required W var c = new GenericConstructor<>(b); } static R viaBound(U a, U b) { @@ -4344,15 +4344,15 @@ interface ConcreteRequirement { Box get(); Box getNonNull(); default Box passCall() { - // BUG: Diagnostic contains: Box cannot be converted to Box + // BUG: Diagnostic contains: found: Box return get(); } default Box passVariable(Box b) { - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object return b; } default void assignCall() { - // BUG: Diagnostic contains: Box cannot be converted to Box + // BUG: Diagnostic contains: found: Box Box x = get(); } default Box passNonNullCall() { @@ -4387,7 +4387,7 @@ interface IntersectionDirectRequirement { RunnableBox loadAll(); // the capture's bound is V & @Nullable Runnable, and neither element excludes null default RunnableBox pass() { - // BUG: Diagnostic contains: RunnableBox cannot be converted to RunnableBox + // BUG: Diagnostic contains: found: RunnableBox return loadAll(); } } @@ -4403,7 +4403,7 @@ interface AllInterfaceIntersection { // the capture's bound @Nullable AutoCloseable & @Nullable Runnable has no element // that excludes null; javac adds an implicit Object element that is not written default RunnableBox pass() { - // BUG: Diagnostic contains: RunnableBox cannot be converted to RunnableBox + // BUG: Diagnostic contains: found: RunnableBox return load(); } } @@ -4412,7 +4412,7 @@ interface IntersectionReachingNoElement< RunnableBox loadAll(); // V reaches W only through the nullable link V extends @Nullable W default RunnableBox pass() { - // BUG: Diagnostic contains: RunnableBox cannot be converted to RunnableBox + // BUG: Diagnostic contains: found: RunnableBox return loadAll(); } } @@ -4554,9 +4554,9 @@ void aTypeVariableWhoseBoundAdmitsNullIntoOneThatExcludesIt(Box input) { } void anExplicitlyNullableTypeArgument( Box<@Nullable String> nullable, List<@Nullable String> source, List target) { - // BUG: Diagnostic contains: Box<@Nullable String> cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required U new StrictConsumer(nullable); - // BUG: Diagnostic contains: List<@Nullable String> cannot be converted to List + // BUG: Diagnostic contains: found: List<@Nullable String> new Copier(source, target); // BUG: Diagnostic contains: parameter type of referenced method is Box useBoxes(Test::take); @@ -4571,7 +4571,7 @@ void aTypeVariableOfAGenericFunctionalInterfaceMethodKeepsItsBound() { useSink(Test::takeNonNull); } void aTypeVariableInScope(Box box) { - // BUG: Diagnostic contains: Box cannot be converted to Box + // BUG: Diagnostic contains: found: Box Box nonNull = box; } void referencedBeforeItsDeclaration() { @@ -4579,7 +4579,7 @@ void referencedBeforeItsDeclaration() { } static List boxed(U value) { Box box = new Box<>(); - // BUG: Diagnostic contains: Box cannot be converted to Box + // BUG: Diagnostic contains: found: Box Box nonNull = box; throw new UnsupportedOperationException(); } @@ -4589,7 +4589,7 @@ void constructedBeforeItsDeclaration(Box input) { static class Checked { Checked(Box input) { Box box = new Box<>(); - // BUG: Diagnostic contains: Box cannot be converted to Box + // BUG: Diagnostic contains: found: Box Box nonNull = box; } }