Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,15 @@ static Type wildcardUpperBound(
formalTypeVar == null
? Symtab.instance(state.context).objectType
: formalTypeVar.getUpperBound();
// check if the upper bound should be treated as @Nullable, e.g., due to a library model or a
// type variable in @NullUnmarked code
boolean upperBoundHasExplicitNullnessAnnotation =
Nullness.hasNonNullAnnotation(upperBound.getAnnotationMirrors().stream(), config)
|| Nullness.hasNullableAnnotation(upperBound.getAnnotationMirrors().stream(), config);
// if the upper bound of formalTypeVar is @Nullable, and there is no
// explicit annotation on upperBound already, add a @Nullable annotation to upperBound.
// Explicit annotations on upperBound always take precedence.
if (formalTypeVar != null
&& upperBoundIsNullable(formalTypeVar.asElement(), config, handler, state)
&& !Nullness.hasNullableAnnotation(upperBound.getAnnotationMirrors().stream(), config)) {
&& !upperBoundHasExplicitNullnessAnnotation) {
upperBound =
TypeSubstitutionUtils.typeWithAnnot(
upperBound, GenericsChecks.getSyntheticNullableAnnotType(state));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,25 @@ public static Type.WildcardType replaceUnboundedWildcardUpperBound(
public static Type.WildcardType replaceUnboundedWildcardUpperBound(
Type.WildcardType wildcard, Type.TypeVar typeVariable, Type upperBound) {
Verify.verify(wildcard.kind == BoundKind.UNBOUND, "wildcard must be unbounded");
return replaceImplicitWildcardUpperBound(wildcard, typeVariable, upperBound);
}

/**
* Returns a copy of an unbounded or lower-bounded wildcard with its {@code bound} field set to a
* copy of {@code typeVariable} with {@code upperBound} as its upper bound.
*
* <p>The wildcard and type variable are both copied so that shared javac types are not mutated.
*
* @param wildcard the unbounded or lower-bounded wildcard to copy
* @param typeVariable the type variable that supplies the wildcard's implicit upper bound
* @param upperBound the new implicit upper bound
* @return the copied wildcard
*/
private static Type.WildcardType replaceImplicitWildcardUpperBound(
Type.WildcardType wildcard, Type.TypeVar typeVariable, Type upperBound) {
Verify.verify(
wildcard.kind == BoundKind.UNBOUND || wildcard.kind == BoundKind.SUPER,
"wildcard must have an implicit upper bound");
// A metadata clone of a javac TypeVar delegates setUpperBound() to the original TypeVar. Build
// a genuinely detached TypeVar with the desired bound instead of mutating an apparent clone.
Type.TypeVar updatedFormalTypeVariable =
Expand Down Expand Up @@ -321,7 +340,7 @@ private static class RestoreNullnessAnnotationsVisitor extends Types.MapVisitor<
private final Config config;

/** Pairs of implicit wildcard bounds currently being traversed. */
private final IdentityHashMap<Type.TypeVar, Set<Type.TypeVar>> activeUnboundedWildcardBounds =
private final IdentityHashMap<Type.TypeVar, Set<Type.TypeVar>> activeImplicitWildcardBounds =
new IdentityHashMap<>();

RestoreNullnessAnnotationsVisitor(Config config) {
Expand Down Expand Up @@ -374,20 +393,19 @@ public Type visitClassType(Type.ClassType t, Type other) {
@Override
public Type visitWildcardType(Type.WildcardType wt, Type other) {
if (!(other instanceof Type.WildcardType wildcardType)) {
return wt;
return restoreWildcardUpperBoundAnnotation(wt, wt.bound, other);
}
// for unbound wildcards, we restore annotations onto the upper bound of the underlying type
// variable, stored in the `bound` field
if (wt.kind == BoundKind.UNBOUND
&& wildcardType.kind == BoundKind.UNBOUND
// Unbounded and super wildcards have an implicit upper bound on the formal type variable.
if (wt.kind != BoundKind.EXTENDS
&& wildcardType.kind == wt.kind
&& wt.bound != null
&& wildcardType.bound != null) {
Type.TypeVar formalTypeVariable = wt.bound;
Type.TypeVar otherFormalTypeVariable = wildcardType.bound;
Set<Type.TypeVar> activeOtherBounds = activeUnboundedWildcardBounds.get(formalTypeVariable);
Set<Type.TypeVar> activeOtherBounds = activeImplicitWildcardBounds.get(formalTypeVariable);
if (activeOtherBounds == null) {
activeOtherBounds = Collections.newSetFromMap(new IdentityHashMap<>());
activeUnboundedWildcardBounds.put(formalTypeVariable, activeOtherBounds);
activeImplicitWildcardBounds.put(formalTypeVariable, activeOtherBounds);
} else if (activeOtherBounds.contains(otherFormalTypeVariable)) {
// F-bounded type variables make the implicit upper-bound graph cyclic. Re-entering the
// same pair cannot reveal any annotations that were not handled on the first visit.
Expand All @@ -401,12 +419,17 @@ public Type visitWildcardType(Type.WildcardType wt, Type other) {
} finally {
activeOtherBounds.remove(otherFormalTypeVariable);
if (activeOtherBounds.isEmpty()) {
activeUnboundedWildcardBounds.remove(formalTypeVariable);
activeImplicitWildcardBounds.remove(formalTypeVariable);
}
}
return updatedUpperBound == upperBound
? wt
: replaceUnboundedWildcardUpperBound(wt, updatedUpperBound);
if (updatedUpperBound != upperBound) {
wt = replaceImplicitWildcardUpperBound(wt, formalTypeVariable, updatedUpperBound);
}
// return here for unbounded wildcards. For lower-bounded wildcards we need to fall through
// to restore annotations to the lower bound
if (wt.kind == BoundKind.UNBOUND) {
return wt;
}
}
Type t = wt.type;
if (t != null) {
Expand All @@ -424,6 +447,39 @@ public Type visitTypeVar(Type.TypeVar t, Type other) {
return updateDirectNullabilityAnnotationsForType(t, other);
}

/**
* Restores annotations from another type onto a wildcard's upper bound.
*
* @param wildcard the wildcard type whose upper bound should be updated
* @param implicitUpperBoundTypeVariable for unbounded or lower bounded wildcard types, the type
* variable from which to obtain an upper bound, or null if not available
* @param other the other type from which to restore annotations
*/
private Type.WildcardType restoreWildcardUpperBoundAnnotation(
Type.WildcardType wildcard,
Type.@Nullable TypeVar implicitUpperBoundTypeVariable,
Type other) {
Type upperBound =
wildcard.kind == BoundKind.EXTENDS
? wildcard.type
: implicitUpperBoundTypeVariable == null
? null
: implicitUpperBoundTypeVariable.getUpperBound();
if (upperBound == null) {
return wildcard;
}
Type updatedBound = updateDirectNullabilityAnnotationsForType(upperBound, other);
if (updatedBound == upperBound) {
return wildcard;
}
if (wildcard.kind == BoundKind.EXTENDS) {
return TYPE_METADATA_BUILDER.createWildcardType(wildcard, updatedBound);
} else { // unbounded or lower-bounded wildcard
return replaceImplicitWildcardUpperBound(
wildcard, Verify.verifyNotNull(implicitUpperBoundTypeVariable), updatedBound);
}
}

/**
* Restores annotations on both the captured type {@code t} and its backing wildcard.
*
Expand All @@ -435,9 +491,9 @@ public Type visitTypeVar(Type.TypeVar t, Type other) {
* type. In that case, annotations from {@code other} must be restored to the backing wildcard's
* upper bound.
*
* <p>For an unbounded wildcard, the relevant upper bound is its implicit upper bound from the
* corresponding formal type variable. Wildcard-aware checks use these bounds rather than
* annotations directly on the captured type.
* <p>For an unbounded or super wildcard, the relevant upper bound is its implicit upper bound
* from the corresponding formal type variable. Wildcard-aware checks use these bounds rather
* than annotations directly on the captured type.
*/
@Override
public Type visitCapturedType(Type.CapturedType t, Type other) {
Expand Down Expand Up @@ -468,17 +524,24 @@ public Type visitCapturedType(Type.CapturedType t, Type other) {
return updated;
}
updatedWildcard = TYPE_METADATA_BUILDER.createWildcardType(t.wildcard, updatedBound);
} else if (t.wildcard.kind == BoundKind.UNBOUND) {
Type.TypeVar formalTypeVariable = t.wildcard.bound != null ? t.wildcard.bound : t;
Type upperBound = formalTypeVariable.getUpperBound();
} else {
Verify.verify(t.wildcard.kind == BoundKind.UNBOUND || t.wildcard.kind == BoundKind.SUPER);
// t.wildcard is either unbounded or lower bounded (with super). We want to find the
// corresponding type variable X for t (the type variable for which t.wildcard was passed
// as a type argument), in order to obtain the upper bound of X later on.
// Normally, X is stored in t.wildcard.bound. If it is unavailable, we fall back on using
// the captured type t itself, as its own upper bound (t.getUpperBound()) could provide
// useful information.
Type.TypeVar implicitUpperBoundTypeVariable =
t.wildcard.bound != null ? t.wildcard.bound : t;
Type upperBound = implicitUpperBoundTypeVariable.getUpperBound();
Type updatedUpperBound = upperBound.accept(this, other);
if (updatedUpperBound == upperBound) {
return updated;
}
updatedWildcard =
replaceUnboundedWildcardUpperBound(t.wildcard, formalTypeVariable, updatedUpperBound);
} else {
return updated;
replaceImplicitWildcardUpperBound(
t.wildcard, implicitUpperBoundTypeVariable, updatedUpperBound);
}
if (updatedWildcard == t.wildcard) {
return updated;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,94 @@

public class WildcardTests extends NullAwayTestsBase {

@Test
public void nonNullTypeVariableThroughWildcardCapture() {
// https://github.com/uber/NullAway/issues/1823
// Reproducer from https://github.com/ben-manes/caffeine/issues/2004#issuecomment-5467003874
makeHelper()
.addSourceLines(
"Test.java",
"""
import java.util.concurrent.ConcurrentMap;
import org.jspecify.annotations.*;
@NullMarked
class Test {
interface Holder<V extends @Nullable Object> {
// IMPORTANT: Explicit @NonNull annotation on these methods:
@NonNull V value();
Comment thread
msridhar marked this conversation as resolved.
Resolved
ConcurrentMap<String, @NonNull V> asMap();
}

static void takesNonNull(Object value) {}

static void explicitNullableArgument(Holder<@Nullable Object> holder) {
takesNonNull(holder.value());
holder.asMap().entrySet().forEach(e -> takesNonNull(e.getValue()));
}

static void nonNullBoundedWildcard(Holder<? extends Object> holder) {
takesNonNull(holder.value());
holder.asMap().entrySet().forEach(e -> takesNonNull(e.getValue()));
}

static void unboundedWildcard(Holder<?> holder) {
takesNonNull(holder.value());
holder.asMap().entrySet().forEach(e -> takesNonNull(e.getValue()));
}

static void nullableBoundedWildcard(Holder<? extends @Nullable Object> holder) {
takesNonNull(holder.value());
holder.asMap().entrySet().forEach(e -> takesNonNull(e.getValue()));
}

static void superBoundedWildcard(Holder<? super String> holder) {
takesNonNull(holder.value());
holder.asMap().entrySet().forEach(e -> takesNonNull(e.getValue()));
}
}
""")
.doTest();
}

/**
* Checks that inherited {@code @NonNull V} returns remain non-null through unbounded and super
* wildcards. Interleaving calls to an inherited plain {@code V} return checks that restoring
* {@code @NonNull} does not mutate shared wildcard bounds: the plain return must remain nullable,
* and subsequent explicitly non-null returns must still be accepted.
*/
@Test
public void nonNullWildcardMemberDoesNotChangeOtherInheritedMembers() {
makeHelper()
.addSourceLines(
"Test.java",
"""
import org.jspecify.annotations.*;
@NullMarked
class Test {
interface Holder<V extends @Nullable Object> {
@NonNull V nonNullValue();
V value();
}
interface Child<V extends @Nullable Object> extends Holder<V> {}

static void takesNonNull(Object value) {}

static void unbounded(Child<?> holder) {
takesNonNull(holder.nonNullValue());
// BUG: Diagnostic contains: passing @Nullable parameter 'holder.value()'
takesNonNull(holder.value());
}

static void superBounded(Child<? super String> holder) {
takesNonNull(holder.nonNullValue());
// BUG: Diagnostic contains: passing @Nullable parameter 'holder.value()'
takesNonNull(holder.value());
}
}
""")
.doTest();
}

@Test
public void simpleWildcardNoInference() {
makeHelper()
Expand Down
Loading