Skip to content
Draft
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ Unreleased

* Add `JSpecifyUnrecognizedAnnotationLocation`, an opt-in check that reports nullness annotations in locations JSpecify does not recognize (#1787)
* Fix `RequireExplicitNullMarking` diagnostics repeating the check name, so a report no longer begins with `[RequireExplicitNullMarking] [RequireExplicitNullMarking]` (#1815)
* Fix handling of type variables whose upper bound is an intersection: such a bound includes `null` only when every one of its elements is annotated `@Nullable` (#1836)

Version 0.14.1
--------------
Expand Down
17 changes: 15 additions & 2 deletions nullaway/src/main/java/com/uber/nullaway/NullabilityUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,19 @@ private static boolean targetTypeMatches(Symbol sym, TypeAnnotationPosition posi
* type, false otherwise
*/
private static boolean isDirectTypeUseAnnotation(Attribute.TypeCompound t, Symbol symbol) {
return isDirectTypeUseAnnotation(t, symbol.type);
}

/**
* Check whether a type-use annotation should be treated as applying directly to {@code type}
* rather than to something nested inside it.
*
* @param t the annotation and its position in the type
* @param type the annotated type
* @return {@code true} if the annotation should be treated as applying directly to the top-level
* type, false otherwise
*/
public static boolean isDirectTypeUseAnnotation(Attribute.TypeCompound t, Type type) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These changes give me more motivation to get rid of this fallback code entirely, so we don't need to keep maintaining it.

// location is a list of TypePathEntry objects, indicating whether the annotation is
// on an array, inner type, wildcard, or type argument. If it's empty, then the
// annotation is directly on the type.
Expand All @@ -487,11 +500,11 @@ private static boolean isDirectTypeUseAnnotation(Attribute.TypeCompound t, Symbo
}
}
// For non-nested classes annotations apply to the innermost type.
if (!isTypeOfNestedClass(symbol.type)) {
if (!isTypeOfNestedClass(type)) {
return true;
}
// For nested classes the annotation is only valid if it is on the innermost type.
return innerTypeCount == getNestingDepth(symbol.type) - 1;
return innerTypeCount == getNestingDepth(type) - 1;
}

private static int getNestingDepth(Type type) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -191,8 +191,8 @@ private boolean typeArgumentContainedBy(
* nullability.
*/
private boolean haveIdenticalNullability(Type lhsType, Type rhsType) {
boolean isLHSNullableAnnotated = genericsChecks.isNullableAnnotated(lhsType);
boolean isRHSNullableAnnotated = genericsChecks.isNullableAnnotated(rhsType);
boolean isLHSNullableAnnotated = GenericsUtils.isNullableAnnotated(lhsType, config);
boolean isRHSNullableAnnotated = GenericsUtils.isNullableAnnotated(rhsType, config);
if (isLHSNullableAnnotated != isRHSNullableAnnotated) {
return false;
}
Expand Down Expand Up @@ -302,8 +302,8 @@ private boolean superWildcardContains(Type.WildcardType lhsWildcard, Type rhsTyp
* checks.
*/
private boolean typeArgumentSubtype(Type lhsType, Type rhsType) {
boolean isLHSNullableAnnotated = genericsChecks.isNullableAnnotated(lhsType);
boolean isRHSNullableAnnotated = genericsChecks.isNullableAnnotated(rhsType);
boolean isLHSNullableAnnotated = GenericsUtils.isNullableAnnotated(lhsType, config);
boolean isRHSNullableAnnotated = GenericsUtils.isNullableAnnotated(rhsType, config);
if (isRHSNullableAnnotated && !isLHSNullableAnnotated) {
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -304,9 +304,7 @@ private boolean[] getTypeParamsWithNullableUpperBound(Type type) {
for (int i = 0; i < baseTypeArgs.size(); i++) {
Type typeVariable = baseTypeArgs.get(i);
Type upperBound = typeVariable.getUpperBound();
com.sun.tools.javac.util.List<Attribute.TypeCompound> annotationMirrors =
upperBound.getAnnotationMirrors();
if (Nullness.hasNullableAnnotation(annotationMirrors.stream(), config)
if (GenericsUtils.isNullableAnnotated(upperBound, config)
|| handler.onOverrideClassTypeVariableUpperBound(type.tsym.toString(), i)) {
result[i] = true;
}
Expand All @@ -318,18 +316,69 @@ private boolean[] getTypeParamsWithNullableUpperBound(Type type) {
com.sun.tools.javac.util.List<Attribute.TypeCompound> rawTypeAttributes =
tsym.getRawTypeAttributes();
if (rawTypeAttributes != null) {
Map<Integer, Set<Integer>> nullableBoundsPerTypeParam = new LinkedHashMap<>();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Am I correct that we should actually be removing all this code involving rawTypeAttributes now that we have stronger checks for -XDaddTypeAnnotationsToSymbol=true support in JSpecify mode?

for (Attribute.TypeCompound typeCompound : rawTypeAttributes) {
if (typeCompound.position.type.equals(TargetType.CLASS_TYPE_PARAMETER_BOUND)
&& Nullness.isNullableAnnotation(
if (!typeCompound.position.type.equals(TargetType.CLASS_TYPE_PARAMETER_BOUND)
|| !Nullness.isNullableAnnotation(
typeCompound.type.tsym.getQualifiedName().toString(), config)) {
int index = typeCompound.position.parameter_index;
result[index] = true;
continue;
}
int typeParamIndex = typeCompound.position.parameter_index;
Type bound =
boundAt(
baseTypeArgs.get(typeParamIndex).getUpperBound(),
typeCompound.position.bound_index);
// The annotation may sit on a type argument nested inside the bound, or on an enclosing
// type of a nested-class bound, rather than on the bound itself.
if (bound != null && NullabilityUtil.isDirectTypeUseAnnotation(typeCompound, bound)) {
nullableBoundsPerTypeParam
.computeIfAbsent(typeParamIndex, k -> new LinkedHashSet<>())
.add(typeCompound.position.bound_index);
}
}
nullableBoundsPerTypeParam.forEach(
(index, nullableBounds) ->
result[index] |=
nullableBounds.size() == boundCount(baseTypeArgs.get(index).getUpperBound()));
}
return result;
}

/**
* Returns the bound that {@code boundIndex} names in a {@code CLASS_TYPE_PARAMETER_BOUND}
* type-annotation position, or {@code null} if the index names no bound of an intersection. The
* type path of such an annotation is relative to that one bound, so it cannot be read against the
* intersection. A type variable with a single bound has only that bound, which is returned for
* any index.
*
* <p>javac numbers the bounds of an intersection in declaration order, giving index 0 to the
* class bound. Where the declaration has none, index 0 goes to the implicit {@code Object}
* supertype and the declared bounds start at 1.
*/
private static @Nullable Type boundAt(Type upperBound, int boundIndex) {
if (!(upperBound instanceof Type.IntersectionClassType intersectionType)) {
return upperBound;
}
com.sun.tools.javac.util.List<Type> bounds = intersectionType.getExplicitComponents();
int position = boundIndex - (intersectionType.allInterfaces ? 1 : 0);
return position >= 0 && position < bounds.size() ? bounds.get(position) : null;
}

/**
* Returns the number of bounds declared for a type variable with the given upper bound. An
* intersection bound includes {@code null} only when every one of these bounds is annotated
* {@code @Nullable}.
*
* <p>An intersection whose bounds are all interfaces carries an implicit {@code Object} supertype
* that the declaration did not write, hence {@code getExplicitComponents()}. It occupies {@code
* bound_index} 0 but never carries an annotation; see {@link #boundAt}.
*/
private static int boundCount(Type upperBound) {
return upperBound instanceof Type.IntersectionClassType intersectionType
? intersectionType.getExplicitComponents().size()
: 1;
}

/**
* Checks validity of type arguments at a generic method call. A {@code @Nullable} type argument
* can only be used for a type variable that has a {@code @Nullable} upper bound.
Expand Down Expand Up @@ -373,10 +422,8 @@ public void checkGenericMethodCallTypeArguments(Tree tree, VisitorState state) {
if (nullableTypeArguments.containsKey(i)) {
Type typeVariable = baseTypeVariables.get(i);
Type upperBound = typeVariable.getUpperBound();
com.sun.tools.javac.util.List<Attribute.TypeCompound> annotationMirrors =
upperBound.getAnnotationMirrors();
boolean hasNullableAnnotation =
Nullness.hasNullableAnnotation(annotationMirrors.stream(), config)
GenericsUtils.isNullableAnnotated(upperBound, config)
|| handler.onOverrideClassTypeVariableUpperBound(baseType.tsym.toString(), i);
// if type variable's upper bound does not have @Nullable annotation then the instantiation
// is invalid
Expand Down Expand Up @@ -1988,16 +2035,21 @@ private static boolean shouldRunDataflowForExpression(Type exprType, ExpressionT

private Type updateTypeWithNullness(
VisitorState state, Type argumentType, Nullness refinedNullness) {
// Both branches act on the top-level annotation of argumentType, so they read the mirrors
// rather than going through GenericsUtils#isNullableAnnotated: removeNullableAnnotation
// requires a top-level annotation to be present, which an intersection never has.
boolean hasNullableAnnotation =
Nullness.hasNullableAnnotation(argumentType.getAnnotationMirrors().stream(), config);
if (NullabilityUtil.nullnessToBool(refinedNullness)) {
// refine to @Nullable
if (isNullableAnnotated(argumentType)) {
if (hasNullableAnnotation) {
return argumentType;
}
return TypeSubstitutionUtils.typeWithAnnot(
argumentType, getSyntheticNullableAnnotType(state));
} else {
// refine to @NonNull, by removing the top-level @Nullable annotation if present.
if (!isNullableAnnotated(argumentType)) {
if (!hasNullableAnnotation) {
return argumentType;
}
return TypeSubstitutionUtils.removeNullableAnnotation(argumentType, config);
Expand Down Expand Up @@ -2131,8 +2183,8 @@ boolean subtypeParameterNullability(
Type.ArrayType rhsArrayType = (Type.ArrayType) rhsType;
Type lhsComponentType = lhsArrayType.getComponentType();
Type rhsComponentType = rhsArrayType.getComponentType();
boolean isLHSNullableAnnotated = isNullableAnnotated(lhsComponentType);
boolean isRHSNullableAnnotated = isNullableAnnotated(rhsComponentType);
boolean isLHSNullableAnnotated = GenericsUtils.isNullableAnnotated(lhsComponentType, config);
boolean isRHSNullableAnnotated = GenericsUtils.isNullableAnnotated(rhsComponentType, config);
// an array of @Nullable references is _not_ a subtype of an array of @NonNull references
if (isRHSNullableAnnotated && !isLHSNullableAnnotated) {
return false;
Expand Down Expand Up @@ -2758,7 +2810,7 @@ private boolean substitutedMethodTypeVarUpperBoundIsNullable(
return true;
}
Type upperBound = substitutedTypeVar.getUpperBound();
if (Nullness.hasNullableAnnotation(upperBound.getAnnotationMirrors().stream(), config)) {
if (GenericsUtils.isNullableAnnotated(upperBound, config)) {
return true;
}
if (Nullness.hasNonNullAnnotation(upperBound.getAnnotationMirrors().stream(), config)) {
Expand All @@ -2775,7 +2827,7 @@ private boolean substitutedMethodTypeVarUpperBoundIsNullable(
List<Symbol.TypeVariableSymbol> originalTypeParams = overriddenMethod.getTypeParameters();
Type originalBound =
(Type) ((TypeVariable) originalTypeParams.get(typeVarIndex).asType()).getUpperBound();
if (Nullness.hasNullableAnnotation(originalBound.getAnnotationMirrors().stream(), config)) {
if (GenericsUtils.isNullableAnnotated(originalBound, config)) {
return true;
}
if (Nullness.hasNonNullAnnotation(originalBound.getAnnotationMirrors().stream(), config)) {
Expand Down Expand Up @@ -3587,12 +3639,7 @@ private Nullness getParameterTypeNullness(Type type, boolean isVarargsParam, Vis
* @return Returns the Nullness of the type based on the Nullability annotation.
*/
private Nullness getTypeNullness(Type type) {
boolean hasNullableAnnotation =
Nullness.hasNullableAnnotation(type.getAnnotationMirrors().stream(), config);
if (hasNullableAnnotation) {
return Nullness.NULLABLE;
}
return Nullness.NONNULL;
return GenericsUtils.isNullableAnnotated(type, config) ? Nullness.NULLABLE : Nullness.NONNULL;
}

/**
Expand Down Expand Up @@ -3726,10 +3773,6 @@ public void clearCache() {
nestedNullabilityRepairInProgress.clear();
}

public boolean isNullableAnnotated(Type type) {
return Nullness.hasNullableAnnotation(type.getAnnotationMirrors().stream(), config);
}

/**
* Store a poly expression's target type with explicit type-variable nullability from the
* assignment context, when the expression type has not already been cached.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ static Type wildcardUpperBound(
// type variable in @NullUnmarked code
if (formalTypeVar != null
&& upperBoundIsNullable(formalTypeVar.asElement(), config, handler, state)
&& !Nullness.hasNullableAnnotation(upperBound.getAnnotationMirrors().stream(), config)) {
&& !isNullableAnnotated(upperBound, config)) {
upperBound =
TypeSubstitutionUtils.typeWithAnnot(
upperBound, GenericsChecks.getSyntheticNullableAnnotType(state));
Expand All @@ -116,7 +116,8 @@ && upperBoundIsNullable(formalTypeVar.asElement(), config, handler, state)
* library model overrides the bound nullability for the type variable, or when the declared upper
* bound has an explicit {@code @Nullable} annotation. An explicit {@code @NonNull} annotation on
* a type-variable bound takes precedence over nullability inherited from that type variable's
* upper bound.
* upper bound. An intersection bound is nullable only when every one of its elements is; see
* {@link #isNullableAnnotated}.
*/
static boolean upperBoundIsNullable(
Element typeVarElement, Config config, Handler handler, VisitorState state) {
Expand Down Expand Up @@ -144,7 +145,7 @@ static boolean upperBoundIsNullable(
}
}
Type upperBound = (Type) ((TypeVariable) typeVarElement.asType()).getUpperBound();
if (Nullness.hasNullableAnnotation(upperBound.getAnnotationMirrors().stream(), config)) {
if (isNullableAnnotated(upperBound, config)) {
return true;
}
if (Nullness.hasNonNullAnnotation(upperBound.getAnnotationMirrors().stream(), config)) {
Expand All @@ -156,6 +157,27 @@ static boolean upperBoundIsNullable(
return false;
}

/**
* Returns true if {@code type} carries a {@code @Nullable} annotation, treating an intersection
* type as {@code @Nullable} only when every one of its elements is.
*
* <p>JSpecify assigns a nullness operator to each element of an intersection type separately, and
* fixes the operator of the intersection as a whole to {@code NO_CHANGE}; javac stores type
* annotations on the elements, and an {@code IntersectionClassType} cannot carry one at all. A
* type variable is null-exclusive as soon as one element of its bound is, since that element
* still establishes a nullness-subtyping edge. See the <a
* href="https://jspecify.dev/docs/spec/#intersection-types">JSpecify specification</a>.
Comment on lines +164 to +169

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: I think this should be an inline comment under the type instanceof Type.IntersectionClassType intersectionType case

*/
static boolean isNullableAnnotated(Type type, Config config) {
if (type instanceof Type.IntersectionClassType intersectionType) {
return intersectionType.getExplicitComponents().stream()
.allMatch(
element ->
Nullness.hasNullableAnnotation(element.getAnnotationMirrors().stream(), config));
}
return Nullness.hasNullableAnnotation(type.getAnnotationMirrors().stream(), config);
}

private static boolean fromUnannotatedMethodOrClass(
Element typeVarElement, Config config, Handler handler, VisitorState state) {
Element enclosingElement = typeVarElement.getEnclosingElement();
Expand Down
Loading
Loading