From 0472a25daacbb35caa87b86c67173bd3812f4f26 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Wed, 9 Sep 2026 17:32:42 +0300 Subject: [PATCH 01/43] 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 de436682aa..283af5c409 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -457,7 +457,9 @@ private void reportInvalidInstantiationError( private void reportInvalidAssignmentInstantiationError( Tree tree, Type lhsType, Type rhsType, VisitorState state) { ErrorBuilder errorBuilder = analysis.getErrorBuilder(); - String msg = errorMessageForIncompatibleTypesAtPseudoAssignment(lhsType, rhsType, state); + String msg = + new NullabilityMismatchMessage(this, config, handler, state) + .build(lhsType, rhsType, tree instanceof VariableTree); ErrorMessage errorMessage = new ErrorMessage(ErrorMessage.MessageTypes.ASSIGN_GENERIC_NULLABLE, msg); state.reportMatch( @@ -465,178 +467,14 @@ private void reportInvalidAssignmentInstantiationError( errorMessage, analysis.buildDescription(tree), state, null)); } - private String errorMessageForIncompatibleTypesAtPseudoAssignment( - Type lhsType, Type rhsType, VisitorState state) { - String prettyRhsType = prettyTypeForError(rhsType, state); - String prettyLhsType = prettyTypeForError(lhsType, state); - String result = - String.format( - "incompatible types: %s cannot be converted to %s", prettyRhsType, prettyLhsType); - boolean allowNonCaptureMismatch = prettyRhsType.equals(prettyLhsType); - WildcardBoundMismatch wildcardBoundMismatch = - firstWildcardBoundMismatch(lhsType, rhsType, state, allowNonCaptureMismatch); - if (wildcardBoundMismatch != null) { - result += " (" + describeWildcardBoundMismatch(wildcardBoundMismatch) + ")"; - } - if (!ASTHelpers.isSameType(lhsType, rhsType, state) - && lhsType.getKind() == TypeKind.DECLARED - && rhsType.getKind() == TypeKind.DECLARED) { - Symbol.TypeSymbol lhsSym = lhsType.asElement(); - if (lhsSym instanceof Symbol.ClassSymbol classSymbol) { - Type asSuper = - TypeSubstitutionUtils.asSuper(state.getTypes(), rhsType, classSymbol, config); - if (asSuper != null) { - result += - String.format( - " (%s is a subtype of %s)", prettyRhsType, prettyTypeForError(asSuper, state)); - } - } - } - return result; - } - - /** - * Returns the first wildcard bound difference between {@code lhsType} and {@code rhsType}, or - * {@code null} if no such difference can be found. Recursively traverses {@code lhsType} and - * {@code rhsType} to find such a difference. - * - *

This is especially useful when two types pretty-print identically, but differ in the - * effective upper bound of a wildcard nested somewhere inside the type. - * - * @param lhsType the lhs (target) type - * @param rhsType the rhs (source) type - * @param state the visitor state - * @param allowNonCaptureMismatch whether a mismatch may be returned when neither causal wildcard - * is captured. Such details are useful when the full types print identically, but redundant - * when the full types already expose the difference. - */ - private @Nullable WildcardBoundMismatch firstWildcardBoundMismatch( - Type lhsType, Type rhsType, VisitorState state, boolean allowNonCaptureMismatch) { - // base case: both wildcard types - Type.WildcardType lhsWildcard = GenericsUtils.asWildcard(lhsType); - Type.WildcardType rhsWildcard = GenericsUtils.asWildcard(rhsType); - if (lhsWildcard != null && rhsWildcard != null) { - if (!allowNonCaptureMismatch - && !(lhsType instanceof Type.CapturedType) - && !(rhsType instanceof Type.CapturedType)) { - return null; - } - return wildcardBoundMismatch(lhsType, rhsType, lhsWildcard, rhsWildcard, state); - } - if (lhsType instanceof Type.ClassType lhsClassType && rhsType instanceof Type.ClassType) { - Type rhsTypeAsSuper = - TypeSubstitutionUtils.asSuper( - state.getTypes(), rhsType, (Symbol.ClassSymbol) lhsType.tsym, config); - if (!(rhsTypeAsSuper instanceof Type.ClassType rhsClassType) - || rhsTypeAsSuper.isRaw() - || lhsType.isRaw()) { - return null; - } - List lhsTypeArguments = lhsClassType.getTypeArguments(); - List rhsTypeArguments = rhsClassType.getTypeArguments(); - if (lhsTypeArguments.size() != rhsTypeArguments.size()) { - return null; - } - for (int i = 0; i < lhsTypeArguments.size(); i++) { - WildcardBoundMismatch mismatch = - firstWildcardBoundMismatch( - lhsTypeArguments.get(i), rhsTypeArguments.get(i), state, allowNonCaptureMismatch); - if (mismatch != null) { - return mismatch; - } - } - return firstWildcardBoundMismatch( - lhsClassType.getEnclosingType(), - rhsClassType.getEnclosingType(), - state, - allowNonCaptureMismatch); - } - if (lhsType instanceof Type.ArrayType lhsArrayType - && rhsType instanceof Type.ArrayType rhsArrayType) { - return firstWildcardBoundMismatch( - lhsArrayType.elemtype, rhsArrayType.elemtype, state, allowNonCaptureMismatch); - } - return null; - } - - /** - * Creates a structured mismatch for two wildcards with visibly different effective upper bounds, - * or returns {@code null} if those bounds pretty-print the same. - */ - private @Nullable WildcardBoundMismatch wildcardBoundMismatch( - Type lhsType, - Type rhsType, - Type.WildcardType lhsWildcard, - Type.WildcardType rhsWildcard, - VisitorState state) { - Type lhsUpperBound = GenericsUtils.wildcardUpperBound(lhsWildcard, state, config, handler); - Type rhsUpperBound = GenericsUtils.wildcardUpperBound(rhsWildcard, state, config, handler); - String prettyLhsUpperBound = prettyTypeForError(lhsUpperBound, state); - String prettyRhsUpperBound = prettyTypeForError(rhsUpperBound, state); - if (!prettyLhsUpperBound.equals(prettyRhsUpperBound)) { - return new WildcardBoundMismatch(lhsType, rhsType, prettyLhsUpperBound, prettyRhsUpperBound); - } - return null; - } - - /** - * Describes a wildcard-bound mismatch, including provenance for every captured wildcard that - * directly participates in that mismatch. - */ - private static String describeWildcardBoundMismatch(WildcardBoundMismatch mismatch) { - String result = - String.format( - "target wildcard upper bound is %s; source wildcard upper bound is %s", - mismatch.prettyTargetUpperBound(), mismatch.prettySourceUpperBound()); - String targetCaptureDescription = - captureProvenanceDescription(mismatch.targetWildcardType(), "target"); - if (targetCaptureDescription != null) { - result += "; " + targetCaptureDescription; - } - String sourceCaptureDescription = - captureProvenanceDescription(mismatch.sourceWildcardType(), "source"); - if (sourceCaptureDescription != null) { - result += "; " + sourceCaptureDescription; - } - return result; - } - - /** Returns a short description of the type parameter underlying a captured type, if available. */ - private static @Nullable String captureProvenanceDescription(Type type, String assignmentRole) { - if (!(type instanceof Type.CapturedType capturedType)) { - return null; - } - Type.TypeVar formalTypeVariable = capturedType.wildcard.bound; - if (formalTypeVariable == null - || !(formalTypeVariable.tsym.owner instanceof Symbol.ClassSymbol owner) - || owner.getSimpleName().isEmpty()) { - return null; - } - return String.format( - "%s wildcard is the type argument for type variable %s of %s", - assignmentRole, formalTypeVariable.tsym.getSimpleName(), owner.getSimpleName()); - } - - /** - * A difference between the effective upper bounds of two corresponding wildcards. - * - *

The wildcard types are retained so the diagnostic can report provenance for the captured - * wildcard or wildcards that directly caused the mismatch, without reporting unrelated captures - * elsewhere in the enclosing types. - */ - private record WildcardBoundMismatch( - Type targetWildcardType, - Type sourceWildcardType, - String prettyTargetUpperBound, - String prettySourceUpperBound) {} - private void reportInvalidReturnTypeError( Tree tree, Type methodType, Type returnType, VisitorState state) { ErrorBuilder errorBuilder = analysis.getErrorBuilder(); ErrorMessage errorMessage = new ErrorMessage( ErrorMessage.MessageTypes.RETURN_NULLABLE_GENERIC, - errorMessageForIncompatibleTypesAtPseudoAssignment(methodType, returnType, state)); + new NullabilityMismatchMessage(this, config, handler, state) + .build(methodType, returnType, false)); state.reportMatch( errorBuilder.createErrorDescription( errorMessage, analysis.buildDescription(tree), state, null)); @@ -668,8 +506,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)); @@ -4695,9 +4533,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 880e3b24b1ab8e02c6591049b1e6598b4a7d175b Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Tue, 13 Oct 2026 02:51:15 +0300 Subject: [PATCH 02/43] 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 83b7d1ca7fb20dea4ad6f6b91ab7b1086bed694a Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Tue, 13 Oct 2026 02:51:26 +0300 Subject: [PATCH 03/43] 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 01b758ba663ee22be11690d0ff818d88a80de193 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Fri, 27 Nov 2026 12:46:27 +0300 Subject: [PATCH 04/43] 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 561c91da85daecdd4cef0b9710f67596c139ab93 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Fri, 27 Nov 2026 12:46:30 +0300 Subject: [PATCH 05/43] 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 0da472288f..8b13e7f051 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java @@ -446,7 +446,11 @@ static boolean declaredUpperBoundIsNullable( return isAnnotatedAsNullable(upperBound, config); } - 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 6b613bce45..a2b9c79b1e 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 743a79a682..2cb5f0add5 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -319,7 +319,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); @@ -348,7 +348,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(); } @@ -379,7 +379,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(); } @@ -411,7 +411,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(); } @@ -443,7 +443,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(); } @@ -473,7 +473,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(); } @@ -496,22 +496,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; } } @@ -566,11 +566,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; } } @@ -595,7 +595,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; } @@ -621,13 +621,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; } @@ -636,7 +636,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; } } @@ -915,18 +915,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(); } @@ -960,18 +960,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(); } @@ -1479,7 +1479,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 @@ -2079,7 +2079,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 c9761f0de8acb0c0cd9bea3fcb34ed5faf5ee139 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Fri, 27 Nov 2026 15:07:11 +0300 Subject: [PATCH 06/43] Record the mismatch positions while the nullability check runs The message builder predicted where the check would reject a source with its own copy of the containment rules. The copy disagreed with the check: at an array element and at the root it applied the exact-match rule of a type argument and reported "a type argument must match exactly" about a difference the check accepts; a captured source and a `? super` bound fell back to `incompatible types:`; and it walked a shared wildcard-bound graph once per path, so a depth-24 bound chain did not finish in 60 s where the check takes 0.1 s. CheckIdenticalNullabilityVisitor now reports each step it takes and each comparison it rejects to NullabilityMismatches, and keeps comparing after a rejection when it records, so the message names exactly the positions the check rejected and costs one more run of the check. Array covariance moved from GenericsChecks into the visitor so that it is recorded too. The recorder follows each step in the written source by position, or by instance where the supertype view rebuilt the node, so a caret stays under the written node when a subclass reorders its type arguments, and a note names the type parameter from the step that reached the caret. A verified rewrite is now a `fix: declare as ` line that names the declaration, and the diagnostic carries an Error Prone fix that makes the edit where the declaration is in the same compilation unit and writes its type out. The fix keeps a `@Nullable` written among the modifiers out of the replaced type, prints NullAway's synthetic `@Nullable` as JSpecify's with an import, and is withheld for an annotated nested array, whose dimensions the printer writes innermost first. User-visible: The first line reads `incompatible nullability in [ and N other positions]: found X, required Y`, and stands alone. A difference in a `? super` bound reads `found String, required a supertype of @Nullable String` at a `wildcard lower bound` step. `note:` and `path:` lines are no longer wrapped. `did you mean X?` and `consider changing the required type to:` became `fix: declare as `. Assisted-by: Claude Code (claude-opus-5-5) --- .../jdkannotations/JDKIntegrationTest.java | 28 +- .../CheckIdenticalNullabilityVisitor.java | 223 ++++- .../GenericTypePrettyPrintingVisitor.java | 123 ++- .../nullaway/generics/GenericsChecks.java | 141 +--- .../generics/NullabilityMismatchMessage.java | 787 +++++++++--------- .../generics/NullabilityMismatches.java | 663 ++++++++++----- .../com/uber/nullaway/generics/TypePath.java | 24 +- .../uber/nullaway/JSpecifyJDKModelsTest.java | 4 +- .../nullaway/ParameterAssignmentTests.java | 4 +- .../jspecify/BytecodeGenericsTests.java | 10 +- .../jspecify/GenericDiamondTests.java | 22 +- .../GenericInferenceErrorReportingTests.java | 2 +- .../jspecify/GenericInheritanceTests.java | 12 +- .../nullaway/jspecify/GenericLambdaTests.java | 4 +- ...enericMethodLambdaOrMethodRefArgTests.java | 4 +- .../nullaway/jspecify/GenericMethodTests.java | 76 +- .../jspecify/GenericVoidReturnTests.java | 4 +- .../uber/nullaway/jspecify/GenericsTests.java | 114 +-- .../IntersectionBoundNarrowingTests.java | 4 +- .../IntersectionRestorationTests.java | 6 +- .../nullaway/jspecify/JSpecifyArrayTests.java | 36 +- .../jspecify/PolyNullLibraryModelsTests.java | 2 +- .../SharedIntersectionTimeoutTests.java | 2 +- .../StreamNullabilityPropagatorTests.java | 4 +- .../jspecify/VarDeclaredLocalTests.java | 2 +- .../uber/nullaway/jspecify/WildcardTests.java | 64 +- .../jspecify/mismatchmessage/CaretTests.java | 93 ++- .../mismatchmessage/FallbackMessageTests.java | 63 -- .../jspecify/mismatchmessage/FixTests.java | 175 ++++ .../LowerBoundAndRawSourceTests.java | 76 ++ .../MismatchMessageTestBase.java | 25 +- .../jspecify/mismatchmessage/NoteTests.java | 104 ++- .../jspecify/mismatchmessage/PathTests.java | 197 ++++- .../mismatchmessage/RequiredTypeFixTests.java | 204 +++++ .../RequiredTypeRepairTests.java | 170 ---- ...ceRepairTests.java => SourceFixTests.java} | 249 +++--- .../SummaryAndNumberingTests.java | 95 +-- .../mismatchmessage/TraversalCostTests.java | 106 +++ .../mismatchmessage/ViewedSourceTests.java | 121 ++- .../nullaway/CustomLibraryModelsTests.java | 24 +- 40 files changed, 2621 insertions(+), 1446 deletions(-) delete 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/FixTests.java create mode 100644 nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java create mode 100644 nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeFixTests.java delete mode 100644 nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeRepairTests.java rename nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/{SourceRepairTests.java => SourceFixTests.java} (54%) create mode 100644 nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java diff --git a/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java b/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java index 45936877e4..47ce10f415 100644 --- a/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java +++ b/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java @@ -293,9 +293,9 @@ class Test { void testCall() { ParameterAnnotation.takesNullableArray(nonNullArray); ParameterAnnotation.takesNullableArray(nullableArray); - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable String, required String ParameterAnnotation.takesNullableArray(nullableElements); - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable String, required String ParameterAnnotation.takesNullableArray(nullableArrayAndElements); ParameterAnnotation.takesNullableElements(nonNullArray); ParameterAnnotation.takesNullableElements(nullableElements); @@ -339,12 +339,12 @@ void test() { } int nullableElementsLength = ReturnAnnotation.returnNullableElements().length; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable String, required String String[] nullableElements = ReturnAnnotation.returnNullableElements(); // BUG: Diagnostic contains: dereferenced expression 'ReturnAnnotation.returnNullableArrayAndElements()' is @Nullable int nullableArrayAndElementsLength = ReturnAnnotation.returnNullableArrayAndElements().length; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable String, required String String @Nullable [] nullableArrayAndElements = ReturnAnnotation.returnNullableArrayAndElements(); } @@ -381,7 +381,7 @@ void test() { int nullableComponentArraysLength = ReturnAnnotation.returnNullableComponentArrays2D().length; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in array element: found String @Nullable [], required String [] String[][] nullableComponentArrays = ReturnAnnotation.returnNullableComponentArrays2D(); // TODO: This should report a nullable dereference. NullAway currently loses the @@ -391,7 +391,7 @@ void test() { // BUG: Diagnostic contains: dereferenced expression 'ReturnAnnotation.returnNullableOuterAndComponentArrays2D()' is @Nullable int nullableOuterAndComponentArraysLength = ReturnAnnotation.returnNullableOuterAndComponentArrays2D().length; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in array element: found String @Nullable [], required String [] String @Nullable [][] nullableOuterAndComponentArrays = ReturnAnnotation.returnNullableOuterAndComponentArrays2D(); } @@ -656,21 +656,21 @@ public void loadLibraryModuleMethodReturnTypeNestedAnnotation() { class Test { void testCall() { // -- Type argument nullability - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in List type argument E: found @Nullable String, required String List typeArg1 = ReturnAnnotation.nestedAnnotTypeArg(); List<@Nullable String> typeArg2 = ReturnAnnotation.nestedAnnotTypeArg(); // -- Array Element nullability - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable String, required String String[] arrayElement1 = ReturnAnnotation.nestedAnnotArrayElement(); - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable String, required String String @Nullable [] arrayElement2 = ReturnAnnotation.nestedAnnotArrayElement(); @Nullable String [] arrayElement3 = ReturnAnnotation.nestedAnnotArrayElement(); // -- mixed type nullability - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable List<@Nullable Integer>, required List List[] mixed1 = ReturnAnnotation.nestedAnnotMixed(); - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in array element -> List type argument E: found @Nullable Integer, required Integer @Nullable List[] mixed2 = ReturnAnnotation.nestedAnnotMixed(); - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable List<@Nullable Integer>, required List<@Nullable Integer> List<@Nullable Integer>[] mixed3 = ReturnAnnotation.nestedAnnotMixed(); @Nullable List<@Nullable Integer>[] mixed4 = ReturnAnnotation.nestedAnnotMixed(); } @@ -718,11 +718,11 @@ void testCall() { @Nullable List[] nonNullTypeArgMixed = (@Nullable List[]) new List[3]; // === test calls ParameterAnnotation.nestedAnnotations(nullableTypeArg, nullableArray, nullableMixed); - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in List type argument E: a type argument must match exactly; found String, required @Nullable String ParameterAnnotation.nestedAnnotations(nonNullTypeArg, nullableArray, nullableMixed); ParameterAnnotation.nestedAnnotations(nullableTypeArg, nonNullArray, nullableMixed); ParameterAnnotation.nestedAnnotations(nullableTypeArg, nullableArray, nonNullArrayMixed); - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in array element -> List type argument E: a type argument must match exactly; found Integer, required @Nullable Integer ParameterAnnotation.nestedAnnotations(nullableTypeArg, nullableArray, nonNullTypeArgMixed); } } 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..bb69d9eb41 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitor.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitor.java @@ -25,6 +25,10 @@ *

Performance: a visitor caches successful wildcard containment checks for its lifetime. Reuse * the instance to share those results across checks, as long as the types and their annotations * have not changed. + * + *

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. + * {@link #MARK_START}, the index of every path that reaches it, {@link #MARK_TEXT}, 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} @@ -28,53 +32,130 @@ 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. + * Opens the printed form of a marked node, followed by one digit for each requested path that + * reaches the node. The marker 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'; + /** Ends the digits of a marked node and starts its printed form. */ + static final char MARK_TEXT = '\u0003'; + + /** Ends the printed form of a marked node. */ 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. + * ten, since an index is printed as one digit. Two entries may reach one node, which is then + * bracketed once with both indices. 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(); + /** + * Where the names of classes and annotations are imported for a fix that pastes the printed type, + * or {@code null} where the type is only shown, under simple names. + */ + private final SuggestedFix.@Nullable Builder fix; + + /** + * Whether the {@code @Nullable} on the base type, the type itself or, for an array, its innermost + * element type, is left out because the declaration the fix rewrites states it among its + * modifiers, outside the type tree the fix replaces. + */ + private final boolean omitBaseAnnotation; + GenericTypePrettyPrintingVisitor(VisitorState state) { this(state, List.of()); } GenericTypePrettyPrintingVisitor(VisitorState state, List<@Nullable TypePath> markedPaths) { + this(state, markedPaths, null, false); + } + + private GenericTypePrettyPrintingVisitor( + VisitorState state, + List<@Nullable TypePath> markedPaths, + SuggestedFix.@Nullable Builder fix, + boolean omitBaseAnnotation) { this.state = state; this.markedPaths = markedPaths; + this.fix = fix; + this.omitBaseAnnotation = omitBaseAnnotation; + } + + /** + * Returns {@code type} printed as source code for {@code fix} to paste into the compilation unit + * {@code state} is in: a class or annotation that a simple name does not reach there is imported + * by {@code fix}, or qualified where an import would clash. NullAway's synthetic + * {@code @Nullable} prints as JSpecify's. + * + * @param omitBaseAnnotation whether to leave out the {@code @Nullable} of the base type, the type + * itself or, for an array, its innermost element type, because the declaration states it + * among its modifiers + */ + static String printForFix( + Type type, VisitorState state, SuggestedFix.Builder fix, boolean omitBaseAnnotation) { + return type.accept( + new GenericTypePrettyPrintingVisitor(state, List.of(), fix, omitBaseAnnotation), null); + } + + /** + * Returns the name to print for {@code symbol}, a class not printed inside its enclosing type or + * an annotation type. + */ + private String name(Symbol.TypeSymbol symbol) { + return fix == null + ? symbol.getSimpleName().toString() + : SuggestedFixes.qualifyType(state, fix, symbol); + } + + /** Returns the name to print for the nullable annotation {@code annotationType}. */ + private String annotationName(Type annotationType) { + if (fix != null && GenericsChecks.isSyntheticNullnessAnnotation(annotationType)) { + return SuggestedFixes.qualifyType(state, fix, "org.jspecify.annotations.Nullable"); + } + return name(annotationType.tsym); + } + + /** + * Whether {@code t}, the node being printed, is the base type: the root, or the innermost element + * type of a root array. + */ + private boolean isBase(Type t) { + return !(t instanceof Type.ArrayType) + && currentPath.steps().stream() + .allMatch(step -> step.kind() == TypePath.Step.Kind.ARRAY_ELEMENT); } /** Brackets {@code printed} when the node being printed sits at one of the requested paths. */ private String mark(String printed) { + StringBuilder indices = new StringBuilder(); 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; + indices.append(i); } } - return printed; + return indices.length() == 0 + ? printed + : MARK_START + indices.toString() + MARK_TEXT + printed + MARK_END; } /** Strips the bracket around {@code printed}, where the whole of it is one marked node. */ private static String withoutOuterMark(String printed) { + int text = printed.indexOf(MARK_TEXT); return printed.length() > 2 && printed.charAt(0) == MARK_START + && text > 0 && printed.charAt(printed.length() - 1) == MARK_END - ? printed.substring(2, printed.length() - 1) + ? printed.substring(text + 1, printed.length() - 1) : printed; } @@ -94,7 +175,12 @@ public String visitWildcardType(Type.WildcardType t, @Nullable Void unused) { StringBuilder sb = new StringBuilder(); sb.append(t.kind); if (t.kind != BoundKind.UNBOUND) { - sb.append(descend(TypePath.Step.wildcardBound(), t.type)); + sb.append( + descend( + t.kind == BoundKind.EXTENDS + ? TypePath.Step.wildcardBound() + : TypePath.Step.wildcardLowerBound(), + t.type)); } return mark(sb.toString()); } @@ -111,11 +197,12 @@ public String visitClassType(Type.ClassType t, @Nullable Void s) { } StringBuilder sb = new StringBuilder(); Type enclosingType = t.getEnclosingType(); - if (!ASTHelpers.isSameType(enclosingType, Type.noType, state)) { + boolean printsEnclosingType = !ASTHelpers.isSameType(enclosingType, Type.noType, state); + if (printsEnclosingType) { sb.append(descend(TypePath.Step.enclosingType(), enclosingType)).append('.'); } appendNullableAnnotationIfPresent(t, sb); - sb.append(t.tsym.getSimpleName()); + sb.append(printsEnclosingType ? t.tsym.getSimpleName().toString() : name(t.tsym)); if (t.getTypeArguments().nonEmpty()) { sb.append('<'); StringBuilder arguments = new StringBuilder(); @@ -143,7 +230,9 @@ private void appendNullableAnnotationIfPresent(Type t, StringBuilder sb) { // 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 "); + if (!(omitBaseAnnotation && isBase(t))) { + sb.append('@').append(annotationName(compound.type)).append(' '); + } break; } } 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 283af5c409..f797743953 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -10,6 +10,8 @@ import com.google.common.base.Verify; import com.google.common.collect.ImmutableSet; import com.google.errorprone.VisitorState; +import com.google.errorprone.fixes.SuggestedFix; +import com.google.errorprone.matchers.Description; import com.google.errorprone.suppliers.Suppliers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AnnotatedTypeTree; @@ -455,29 +457,43 @@ private void reportInvalidInstantiationError( } private void reportInvalidAssignmentInstantiationError( - Tree tree, Type lhsType, Type rhsType, VisitorState state) { - ErrorBuilder errorBuilder = analysis.getErrorBuilder(); - String msg = + Tree tree, Type lhsType, Type rhsType, ExpressionTree rhsTree, VisitorState state) { + NullabilityMismatchMessage.Report report = new NullabilityMismatchMessage(this, config, handler, state) - .build(lhsType, rhsType, tree instanceof VariableTree); - ErrorMessage errorMessage = - new ErrorMessage(ErrorMessage.MessageTypes.ASSIGN_GENERIC_NULLABLE, msg); + .build( + lhsType, + rhsType, + tree instanceof VariableTree variableTree ? variableTree : null, + rhsTree); + reportNullabilityMismatch( + tree, ErrorMessage.MessageTypes.ASSIGN_GENERIC_NULLABLE, report, state); + } + + /** Reports {@code report} at {@code tree}, with each of its fixes attached. */ + private void reportNullabilityMismatch( + Tree tree, + ErrorMessage.MessageTypes messageType, + NullabilityMismatchMessage.Report report, + VisitorState state) { + Description.Builder description = analysis.buildDescription(tree); + for (SuggestedFix fix : report.fixes()) { + description.addFix(fix); + } state.reportMatch( - errorBuilder.createErrorDescription( - errorMessage, analysis.buildDescription(tree), state, null)); + analysis + .getErrorBuilder() + .createErrorDescription( + new ErrorMessage(messageType, report.message()), description, state, null)); } private void reportInvalidReturnTypeError( - Tree tree, Type methodType, Type returnType, VisitorState state) { - ErrorBuilder errorBuilder = analysis.getErrorBuilder(); - ErrorMessage errorMessage = - new ErrorMessage( - ErrorMessage.MessageTypes.RETURN_NULLABLE_GENERIC, - new NullabilityMismatchMessage(this, config, handler, state) - .build(methodType, returnType, false)); - state.reportMatch( - errorBuilder.createErrorDescription( - errorMessage, analysis.buildDescription(tree), state, null)); + ExpressionTree tree, Type methodType, Type returnType, VisitorState state) { + reportNullabilityMismatch( + tree, + ErrorMessage.MessageTypes.RETURN_NULLABLE_GENERIC, + new NullabilityMismatchMessage(this, config, handler, state) + .build(methodType, returnType, null, tree), + state); } private void reportMismatchedTypeForTernaryOperator( @@ -502,15 +518,12 @@ private void reportInvalidParametersNullabilityError( Type actualParameterType, ExpressionTree paramExpression, VisitorState state) { - ErrorBuilder errorBuilder = analysis.getErrorBuilder(); - ErrorMessage errorMessage = - new ErrorMessage( - ErrorMessage.MessageTypes.PASS_NULLABLE_GENERIC, - new NullabilityMismatchMessage(this, config, handler, state) - .build(formalParameterType, actualParameterType, false)); - state.reportMatch( - errorBuilder.createErrorDescription( - errorMessage, analysis.buildDescription(paramExpression), state, null)); + reportNullabilityMismatch( + paramExpression, + ErrorMessage.MessageTypes.PASS_NULLABLE_GENERIC, + new NullabilityMismatchMessage(this, config, handler, state) + .build(formalParameterType, actualParameterType, null, paramExpression), + state); } private void reportInvalidMethodReferenceReturnTypeError( @@ -980,7 +993,7 @@ public void checkTypeParameterNullnessForAssignability(Tree tree, VisitorState s } boolean isAssignmentValid = subtypeParameterNullability(lhsType, rhsType, state); if (!isAssignmentValid) { - reportInvalidAssignmentInstantiationError(tree, lhsType, rhsType, state); + reportInvalidAssignmentInstantiationError(tree, lhsType, rhsType, rhsTree, state); } } } @@ -2393,80 +2406,16 @@ public void checkTypeParameterNullnessForFunctionReturnType( } /** - * Compare two types for identical type parameter nullability, recursively checking nested generic - * types. See the JSpecify - * specification and the JLS - * subtyping rules for class and interface types. - * - * @param lhsType type for the lhs of the assignment - * @param rhsType type for the rhs of the assignment - * @param visitor visitor carrying state for the recursive comparison - */ - @SuppressWarnings({"ReferenceEquality", "TypeEquals"}) // deliberate reference equality check - private boolean identicalTypeParameterNullability( - Type lhsType, Type rhsType, CheckIdenticalNullabilityVisitor visitor) { - if (lhsType == rhsType) { - return true; - } - return lhsType.accept(visitor, rhsType); - } - - /** - * Like {@link #identicalTypeParameterNullability(Type, Type, CheckIdenticalNullabilityVisitor)}, - * but allows for covariant array subtyping at every dimension of an array type. + * Returns whether {@code rhsType} may be assigned to {@code lhsType} as far as the nullability of + * their type arguments goes; see {@link CheckIdenticalNullabilityVisitor#isSubtype}. * * @param lhsType type for the lhs of the assignment * @param rhsType type for the rhs of the assignment * @param state the visitor state */ boolean subtypeParameterNullability(Type lhsType, Type rhsType, VisitorState state) { - return subtypeParameterNullability( - lhsType, - rhsType, - state, - new CheckIdenticalNullabilityVisitor(state, this, config, handler)); - } - - /** - * Continues a subtype nullability comparison with an existing visitor so recursive wildcard - * comparisons share cycle-detection state. - * - * @param lhsType type for the lhs of the assignment - * @param rhsType type for the rhs of the assignment - * @param state the visitor state - * @param visitor visitor carrying state for the recursive comparison - */ - boolean subtypeParameterNullability( - Type lhsType, Type rhsType, VisitorState state, CheckIdenticalNullabilityVisitor visitor) { - if (lhsType.isRaw()) { - return true; - } - if (lhsType.getKind().equals(TypeKind.ARRAY) && rhsType.getKind().equals(TypeKind.ARRAY)) { - // for array types we must allow covariance, i.e., an array of @NonNull references is a - // subtype of an array of @Nullable references; see - // https://github.com/jspecify/jspecify/issues/65 - Type.ArrayType lhsArrayType = (Type.ArrayType) lhsType; - Type.ArrayType rhsArrayType = (Type.ArrayType) rhsType; - Type lhsComponentType = lhsArrayType.getComponentType(); - Type rhsComponentType = rhsArrayType.getComponentType(); - boolean isLHSNullableAnnotated = isNullableAnnotated(lhsComponentType); - boolean isRHSNullableAnnotated = isNullableAnnotated(rhsComponentType); - // an array of @Nullable references is _not_ a subtype of an array of @NonNull references - if (isRHSNullableAnnotated && !isLHSNullableAnnotated) { - return false; - } - if (lhsComponentType.getKind().equals(TypeKind.ARRAY) - && rhsComponentType.getKind().equals(TypeKind.ARRAY)) { - // covariance applies at every dimension of a multi-dimensional array, not just the - // outermost one. The ARRAY check keeps array types nested inside generic type arguments - // on the invariant path below, since generics are not covariant. - return subtypeParameterNullability(lhsComponentType, rhsComponentType, state, visitor); - } - return identicalTypeParameterNullability(lhsComponentType, rhsComponentType, visitor); - } else { - return identicalTypeParameterNullability(lhsType, rhsType, visitor); - } + return new CheckIdenticalNullabilityVisitor(state, this, config, handler) + .isSubtype(lhsType, rhsType); } /** 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..e321d6b56f 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -3,7 +3,14 @@ import static com.uber.nullaway.generics.TypeMetadataBuilder.TYPE_METADATA_BUILDER; import com.google.errorprone.VisitorState; +import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.util.ASTHelpers; +import com.sun.source.tree.AnnotationTree; +import com.sun.source.tree.ExpressionTree; +import com.sun.source.tree.Tree; +import com.sun.source.tree.VariableTree; +import com.sun.source.util.TreePath; +import com.sun.tools.javac.api.JavacTrees; import com.sun.tools.javac.code.Attribute; import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Symbol; @@ -17,6 +24,7 @@ import java.util.ArrayList; import java.util.IdentityHashMap; import java.util.List; +import java.util.function.Function; import javax.lang.model.type.TypeKind; import org.jspecify.annotations.Nullable; @@ -24,40 +32,65 @@ * 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. + *

For {@code take(m)} with {@code m} a {@code Map} and {@code take} requiring {@code + * Map}, the text reads: + * + *

+ * incompatible nullability in Map type argument K -> wildcard upper bound: found @Nullable Object, required Object
+ *     found:    Map<?, String>
+ *                   ^
+ *     required: Map<? extends Object, String>
+ *                             ^^^^^^
+ *     note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter K of Map
+ *     fix: declare m as Map<? extends Object, String>
+ * 
+ * + *

The message is built from the positions the check itself rejected, which {@link + * NullabilityMismatches} records while {@link CheckIdenticalNullabilityVisitor} runs, 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. * *

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. + *

Each line opens with a key that means the same thing wherever it appears: {@code found} is the + * source type, {@code found as} the supertype of it the check compared, {@code required} the target + * type, {@code path} where in the type one difference sits, {@code note} a fact about the source + * that its printed form does not show, and {@code fix} a declaration whose rewritten type the check + * accepts. Where there are several differences, each gets a numbered entry with its own {@code + * path}, {@code found}, and {@code required}, five at most, and {@code and N more, not listed} + * counts the rest. * *

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. + *

It stands alone, since a tool may show only that line: {@code incompatible nullability in}, + * the path of the first difference, how many other positions differ, and then the two nodes there. + * 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. + * Where the target bounds a {@code ? super} wildcard, the required side reads {@code a supertype + * of} that bound. + * + *

Where the check records no position, the message is the two types and the subtype relation + * between them, opening {@code incompatible types:}, which is all that can be said about a + * difference nothing located. * *

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. + * The check compares the source viewed as the target's class, which is the source's own class or a + * supertype of it, so which node of the type the reader wrote the caret belongs under has two + * answers: where the view is the same class, the position is the same position; where it is a + * supertype, only a node the substitution carried over from the written type can be pointed at. + * Viewing an {@code ArrayList<@Nullable String>} as a {@code List} carries the {@code @Nullable + * String} over; for {@code class Sub extends Base>}, viewing a {@code Sub} + * as a {@code Base} rebuilds the {@code List<@Nullable String>} from the declaration of {@code + * Sub}, which the written type does not hold. Where neither answers, the view is printed as {@code + * found as} and carries the carets. Two differences below one printed node share its caret, + * numbered for each. * *

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, including one the supertype view carried over @@ -68,29 +101,31 @@ * 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. + * cannot see there. * - *

The repairs

+ *

The fixes

* - *

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 ?}. + *

A {@code fix} line names the declaration it rewrites and the type it declares, and both + * candidates 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 ?}. Where the declaration is in the compilation unit + * being analyzed and writes its type out, the line comes with an Error Prone fix that makes the + * edit. * - *

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. + *

The two candidates differ in what they presume. Writing an explicit bound on a wildcard the + * source declaration already writes is a mechanical fix 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. + *

A fix also has to survive printing. The printer shows {@code @Nullable} and drops every other + * type-use annotation, and it writes the dimensions of a nested array in the reverse of the order a + * declaration gives them, so a type carrying another annotation, or an annotation on a dimension of + * a nested array, is not offered. */ final class NullabilityMismatchMessage { @@ -110,22 +145,44 @@ final class NullabilityMismatchMessage { /** How many mismatches a message lists before it says only how many more there are. */ private static final int MAX_LISTED_MISMATCHES = 5; + /** + * The text of a diagnostic and the fixes to attach to it. + * + * @param message the text + * @param fixes each an alternative edit after which the check accepts the pseudo-assignment, in + * the order the text names them + */ + record Report(String message, List fixes) {} + /** * 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. + *

Where the check records no rejected position, 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 + * @param lhsType the required type + * @param rhsType the type found + * @param requiredTypeDeclaration the declaration of a variable whose type is {@code lhsType} + * where the diagnostic is reported at it, which admits a fix of the required type; {@code + * null} elsewhere + * @param sourceExpression the expression whose type is {@code rhsType}, which admits a fix of the + * declaration it names; {@code null} where there is none */ - String build(Type lhsType, Type rhsType, boolean requiredTypeIsWrittenHere) { - List mismatches = - new NullabilityMismatches(checks, config, handler, state).collect(lhsType, rhsType); + Report build( + Type lhsType, + Type rhsType, + @Nullable VariableTree requiredTypeDeclaration, + @Nullable ExpressionTree sourceExpression) { + NullabilityMismatches recorded = new NullabilityMismatches(lhsType, rhsType); + new CheckIdenticalNullabilityVisitor(state, checks, config, handler, recorded) + .isSubtype(lhsType, rhsType); + List mismatches = recorded.mismatches(); if (mismatches.isEmpty()) { - return plainIncompatibleTypesMessage(lhsType, rhsType); + return new Report( + plainIncompatibleTypesMessage(lhsType, rhsType), + List.of()); // diff-coverage: ignore -- every false result of the visitor comes from a + // reject call, so a rejection records a position } List listed = mismatches.size() > MAX_LISTED_MISMATCHES @@ -133,27 +190,36 @@ String build(Type lhsType, Type rhsType, boolean requiredTypeIsWrittenHere) { : 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()) { + MarkedType found = + markedTypeLines( + "found", + rhsType, + carets(listed, NullabilityMismatches.Mismatch::sourceCaret), + numbered); + Type viewedSource = recorded.viewedSource(); + if (found.marksPlaced() == listed.size() || viewedSource == null) { 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()); + // a node the check compared is at no position of the type the reader wrote, so the view of + // it the check did compare is printed too and carries the carets + message.append(markedTypeLines("found", rhsType, List.of(), numbered).lines()); + message.append( + markedTypeLines( + "found as", + viewedSource, + carets(listed, NullabilityMismatches.Mismatch::viewCaret), + numbered) + .lines()); + } + message.append( + markedTypeLines( + "required", + lhsType, + carets(listed, NullabilityMismatches.Mismatch::targetCaret), + numbered) + .lines()); for (int i = 0; i < listed.size(); i++) { - message.append(mismatchDetail(listed.get(i), numbered ? i + 1 : 0, rhsType)); + message.append(mismatchDetail(listed.get(i), numbered ? i + 1 : 0)); } // 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 @@ -163,22 +229,92 @@ String build(Type lhsType, Type rhsType, boolean requiredTypeIsWrittenHere) { 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 = ""; + List fixes = new ArrayList<>(); + VariableTree sourceDeclaration = sourceDeclaration(sourceExpression, rhsType); + if (sourceDeclaration != null) { + Type rewrittenSourceType = sourceTypeFix(lhsType, rhsType, mismatches); + if (rewrittenSourceType != null) { + message.append(separator); + appendFix(message, fixes, sourceDeclaration, rewrittenSourceType); + separator = ""; + } } - if (targetSuggestion != null) { - message.append( - String.format( - "%s\n consider changing the required type to:\n %s", - separator, targetSuggestion)); + if (requiredTypeDeclaration != null) { + Type rewrittenTargetType = targetTypeFix(lhsType, rhsType, mismatches); + if (rewrittenTargetType != null) { + message.append(separator); + appendFix(message, fixes, requiredTypeDeclaration, rewrittenTargetType); + } } - return message.toString(); + return new Report(message.toString(), fixes); + } + + /** + * Appends the {@code fix:} line that declares {@code declaration} with {@code type}, and adds the + * edit to {@code fixes} where the declaration is in the compilation unit being analyzed and + * writes its type out. + */ + private void appendFix( + StringBuilder message, List fixes, VariableTree declaration, Type type) { + message.append( + String.format( + "\n fix: declare %s as %s", + declaration.getName(), GenericsChecks.prettyTypeForError(type, state))); + Tree typeTree = declaration.getType(); + TreePath declarationPath = TreePath.getPath(state.getPath().getCompilationUnit(), declaration); + if (typeTree == null + || declarationPath == null + || ASTHelpers.hasImplicitType(declaration, state)) { + return; // diff-coverage: ignore -- javac versions differ in whether an inferred type gets a + // synthesized tree + } + SuggestedFix.Builder fix = SuggestedFix.builder(); + String printed = + GenericTypePrettyPrintingVisitor.printForFix( + type, state.withPath(declarationPath), fix, hasNullableModifier(declaration)); + fixes.add(fix.replace(typeTree, printed).build()); + } + + /** + * Whether {@code declaration} writes a nullable annotation among its modifiers, where a type-use + * annotation applies to the base type and lies outside the type tree. + */ + private boolean hasNullableModifier(VariableTree declaration) { + for (AnnotationTree annotation : declaration.getModifiers().getAnnotations()) { + Symbol annotationSymbol = ASTHelpers.getSymbol(annotation.getAnnotationType()); + if (annotationSymbol != null + && Nullness.isNullableAnnotation( + annotationSymbol.getQualifiedName().toString(), config)) { + return true; + } + } + return false; + } + + /** + * Returns the declaration of the variable {@code sourceExpression} reads, where it is in the + * compilation unit being analyzed and declares the very type {@code sourceType}, so that a + * rewrite of that type is a rewrite of the declaration; {@code null} otherwise. + */ + private @Nullable VariableTree sourceDeclaration( + @Nullable ExpressionTree sourceExpression, Type sourceType) { + if (sourceExpression == null + || !(ASTHelpers.getSymbol(ASTHelpers.stripParentheses(sourceExpression)) + instanceof Symbol.VarSymbol variable)) { + return null; + } + // a member read through a parameterized receiver has a type the declaration does not state, + // such as the List a field declared List has in a Box + if (!GenericsChecks.prettyTypeForError(variable.type, state) + .equals(GenericsChecks.prettyTypeForError(sourceType, state))) { + return null; + } + TreePath path = JavacTrees.instance(state.context).getPath(variable); + return path != null + && path.getCompilationUnit() == state.getPath().getCompilationUnit() + && path.getLeaf() instanceof VariableTree declaration + ? declaration + : null; } /** @@ -207,102 +343,52 @@ private String plainIncompatibleTypesMessage(Type lhsType, Type rhsType) { } /** - * 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. + * The line a reader sees first, and the only one some tools show, so it stands alone: it names + * where the first difference sits, how many other positions differ, and the pair at the first. */ 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)); - } + NullabilityMismatches.Mismatch first = mismatches.get(0); + int others = mismatches.size() - 1; + String where = + others == 0 + ? first.path().describe() + : String.format( + "%s and %d other position%s", + first.path().describe(), others, others == 1 ? "" : "s"); + // a non-null type argument where a @Nullable one is required reads as a false subtype claim, + // since every String is a @Nullable String; what fails is that a type argument has to match + String exactly = + first.relation() == NullabilityMismatches.Relation.SAME + && checks.isNullableAnnotated(first.targetNode()) + && !checks.isNullableAnnotated(first.sourceNode()) + ? "a type argument must match exactly; " + : ""; return String.format( - "incompatible nullability: %d mismatches between source and target types", - mismatches.size()); + "incompatible nullability in %s: %sfound %s, required %s", + where, + exactly, + GenericsChecks.prettyTypeForError(first.sourceNode(), state), + required(first)); } /** - * Where each mismatch is drawn in the target, which the traversal walked as the reader wrote it. + * Names what the check required of the source at {@code mismatch}: the target node, or for the + * lower bound of a {@code ? super} wildcard, a supertype of it. */ - private static List<@Nullable TypePath> targetCarets( - List mismatches) { - List<@Nullable TypePath> paths = new ArrayList<>(); - for (NullabilityMismatches.Mismatch mismatch : mismatches) { - paths.add(mismatch.targetCaret()); - } - return paths; - } - - /** - * Returns {@code sourceType} viewed as the class {@code targetType} names, or {@code null} where - * that view is the type the reader wrote or cannot be taken. - * - *

The traversal compares the source in this view at every level, so a node it reports may sit - * at no position in the type the reader wrote: viewing a {@code Sub} declared as {@code extends - * Base>} as a {@code Base} reports a node that only the declaration of - * {@code Sub} contains. Printing the view gives the caret something to point at that the - * comparison actually used. - */ - private @Nullable Type sourceViewedAsTarget(Type targetType, Type sourceType) { - if (!(targetType.tsym instanceof Symbol.ClassSymbol targetSymbol) - || targetSymbol.equals(sourceType.tsym)) { - // the same class, so the comparison ran on the type the reader wrote and its positions are - // that type's own. Whether the view would print differently decides nothing: two classes of - // one simple name print alike and remain two classes - return null; - } - return TypeSubstitutionUtils.asSuper(state.getTypes(), sourceType, targetSymbol, config); + private String required(NullabilityMismatches.Mismatch mismatch) { + String target = GenericsChecks.prettyTypeForError(mismatch.targetNode(), state); + return mismatch.relation() == NullabilityMismatches.Relation.SUPERTYPE + ? "a supertype of " + target + : target; } - /** - * 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) { + /** Returns the caret {@code caret} gives each mismatch, in order. */ + private static List<@Nullable TypePath> carets( + List mismatches, + Function caret) { 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()); + paths.add(caret.apply(mismatch)); } return paths; } @@ -331,9 +417,16 @@ private MarkedType markedTypeLines( i++; continue; } - int index = printed.charAt(i + 1) - '0'; + // one node may carry several indices, where two mismatches share its caret + List indices = new ArrayList<>(); + i++; + while (i < printed.length() + && printed.charAt(i) != GenericTypePrettyPrintingVisitor.MARK_TEXT) { + indices.add(Integer.toString(printed.charAt(i) - '0' + 1)); + i++; + } + i++; int start = stripped.length(); - i += 2; while (i < printed.length() && printed.charAt(i) != GenericTypePrettyPrintingVisitor.MARK_END) { stripped.append(printed.charAt(i)); @@ -341,8 +434,8 @@ private MarkedType markedTypeLines( } i++; padTo(carets, start).append("^".repeat(Math.max(stripped.length() - start, 1))); - padTo(numbers, start).append(index + 1); - marks++; + padTo(numbers, start).append(String.join(",", indices)); + marks += indices.size(); } String prefix = String.format(" %-9s ", label + ":"); // the printer brackets what it was asked to, and this removes any marker regardless: nothing a @@ -353,6 +446,7 @@ private MarkedType markedTypeLines( + stripped .toString() .replace(String.valueOf(GenericTypePrettyPrintingVisitor.MARK_START), "") + .replace(String.valueOf(GenericTypePrettyPrintingVisitor.MARK_TEXT), "") .replace(String.valueOf(GenericTypePrettyPrintingVisitor.MARK_END), ""); if (carets.length() > 0) { line += "\n" + " ".repeat(prefix.length()) + carets; @@ -364,11 +458,8 @@ private MarkedType markedTypeLines( } /** - * 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. + * A printed type and the number of requested positions the printer marked in it, counting a node + * that carries several of them once for each. */ private record MarkedType(String lines, int marksPlaced) {} @@ -381,75 +472,32 @@ private static StringBuilder padTo(StringBuilder line, int column) { } /** - * 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. + * Returns the lines that describe one mismatch below the two types: for a numbered entry its + * position and the pair the first line names only for the first entry, and for any mismatch the + * note about the source wildcard where there is one. */ - 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(); + private String mismatchDetail(NullabilityMismatches.Mismatch mismatch, int number) { 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\n").append(header).append("path: ").append(mismatch.path().describe()); 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)); + detail.append("\n").append(body).append("required: ").append(required(mismatch)); } - String note = boundOriginNote(mismatch, sourceType); + String note = boundOriginNote(mismatch); if (note != null) { - detail - .append("\n") - .append(body) - .append(wrapped("note: " + note, body.length(), body + " ")); + detail.append("\n").append(body).append("note: ").append(note); } 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. + * printed node is not a wildcard, its bound is written out, or it is a captured wildcard whose + * type variable cannot be named. Where an uncaptured wildcard's type parameter cannot be named, + * the note states the bound alone. * *

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 @@ -458,8 +506,7 @@ private static String wrapped(String text, int firstLineIndent, String continuat * 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) { + private @Nullable String boundOriginNote(NullabilityMismatches.Mismatch mismatch) { // 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()); @@ -484,10 +531,19 @@ private static String wrapped(String text, int firstLineIndent, String continuat : note; } if (wildcard.kind == BoundKind.EXTENDS) { - return null; - } + return null; // diff-coverage: ignore -- a ? extends wildcard prints its bound, so the caret + // goes below it + } + // the step that reached the wildcard in the type the reader wrote names the type parameter it + // instantiates there; javac's own link, WildcardType.bound, names a type parameter of whatever + // supertype the wildcard was last substituted into + TypePath caret = mismatch.sourceCaret(); + TypePath.Step reachingStep = + caret == null || caret.isRoot() ? null : caret.steps().get(caret.steps().size() - 1); Type.TypeVar formalTypeVariable = - typeVariableAtPositionOf(mismatch.sourcePrintedNode(), sourceType); + reachingStep != null && reachingStep.kind() == TypePath.Step.Kind.TYPE_ARGUMENT + ? reachingStep.formal() + : null; Symbol.ClassSymbol owner = typeVariableOwner(formalTypeVariable); String source = wildcard.kind == BoundKind.UNBOUND @@ -495,9 +551,8 @@ 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 where the supertype view rebuilt it from - // a subclass declaration, or the variable it instantiates has no named owner. The note says - // what the + // position in the type the reader wrote, as where the supertype view built 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 @@ -512,68 +567,59 @@ private static String wrapped(String text, int firstLineIndent, String continuat } /** - * Returns the printed form of {@code rewrittenSourceType} where it is worth offering as a - * rewrite, or {@code null} where it is not. + * Returns {@code sourceType} with an explicit upper bound written out for each unbounded wildcard + * whose implicit {@code @Nullable} bound the target rejects, where that type is one a reader can + * declare and the check accepts it, and {@code null} otherwise. */ - 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. + private @Nullable Type sourceTypeFix( + Type targetType, Type sourceType, List mismatches) { + Type rewrittenSourceType = rewriteWithExplicitBounds(sourceType, mismatches); + if (rewrittenSourceType == null || !isDeclarable(rewrittenSourceType)) { return null; } - return GenericsChecks.prettyTypeForError(rewrittenSourceType, state); + // the check's own comparison rather than a prediction of it: a rewrite that leaves a mismatch + // writing a bound out does not address, such as a nullness difference on a concrete type + // argument, would only produce the same diagnostic again + return checks.subtypeParameterNullability(targetType, rewrittenSourceType, state) + ? rewrittenSourceType + : null; } /** - * 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. + * Returns {@code targetType} with {@code @Nullable} added at every rejected position, where the + * source has {@code @Nullable} at each of them, the result is a type a reader can declare, and + * the check accepts the source against it; {@code null} otherwise, including where a position + * would need a {@code @Nullable} removed. Whether it is offered at all is the caller's decision, + * which the class comment states. */ - private @Nullable String suggestedTargetType( + private @Nullable Type targetTypeFix( Type targetType, Type sourceType, List mismatches) { - if (mismatches.isEmpty()) { - return null; - } Type rewrittenTargetType = targetType; for (NullabilityMismatches.Mismatch mismatch : mismatches) { Type rewritten = withNullableAddedFrom(mismatch.sourceNode(), mismatch.targetNode()); - if (rewritten == null) { + TypePath targetNodePath = mismatch.targetNodePath(); + if (rewritten == null || targetNodePath == null) { return null; } - rewrittenTargetType = replaceAt(rewrittenTargetType, mismatch.path().steps(), 0, rewritten); + rewrittenTargetType = replaceAt(rewrittenTargetType, targetNodePath.steps(), 0, rewritten); if (rewrittenTargetType == null) { - return null; + return null; // diff-coverage: ignore -- a path from the recorder always addresses a node + // the type has } } - 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; + return isDeclarable(rewrittenTargetType) + && checks.subtypeParameterNullability(rewrittenTargetType, sourceType, state) + ? rewrittenTargetType + : null; } /** * 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. + * null} where {@code source} is not {@code @Nullable}, {@code target} already is, 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 + *

The fix 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) { @@ -585,7 +631,8 @@ private static String wrapped(String text, int firstLineIndent, String continuat return TypeSubstitutionUtils.typeWithAnnot(target, annotation.type); } } - return null; + return null; // diff-coverage: ignore -- isNullableAnnotated is true only where a nullable + // annotation is present } /** @@ -606,13 +653,15 @@ private static String wrapped(String text, int firstLineIndent, String continuat case TYPE_ARGUMENT -> { if (!(type instanceof Type.ClassType classType) || step.index() >= classType.getTypeArguments().size()) { - return null; + return null; // diff-coverage: ignore -- a path from the recorder always addresses a node + // the type has } List typeArguments = new ArrayList<>(classType.getTypeArguments()); Type typeArgument = replaceAt(typeArguments.get(step.index()), steps, from + 1, replacement); if (typeArgument == null) { - return null; + return null; // diff-coverage: ignore -- a path from the recorder always addresses a node + // the type has } typeArguments.set(step.index(), typeArgument); return TYPE_METADATA_BUILDER.createClassType( @@ -620,32 +669,42 @@ private static String wrapped(String text, int firstLineIndent, String continuat } case ENCLOSING_TYPE -> { if (!(type instanceof Type.ClassType classType)) { - return null; + return null; // diff-coverage: ignore -- a path from the recorder always addresses a node + // the type has } Type enclosingType = replaceAt(classType.getEnclosingType(), steps, from + 1, replacement); return enclosingType == null - ? null + ? null // diff-coverage: ignore -- a path from the recorder always addresses a node the + // type has : TYPE_METADATA_BUILDER.createClassType( classType, enclosingType, classType.getTypeArguments()); } case WILDCARD_BOUND -> { if (!(type instanceof Type.WildcardType wildcard) || wildcard.kind != BoundKind.EXTENDS) { - return null; + return null; // diff-coverage: ignore -- a path from the recorder always addresses a node + // the type has } Type bound = replaceAt(wildcard.type, steps, from + 1, replacement); return bound == null ? null : TYPE_METADATA_BUILDER.createWildcardType(wildcard, bound); } + case WILDCARD_LOWER_BOUND -> { + // a lower bound accepts less once it is @Nullable, so no fix adds the annotation there + return null; + } case ARRAY_ELEMENT -> { if (!(type instanceof Type.ArrayType arrayType)) { - return null; + return null; // diff-coverage: ignore -- a path from the recorder always addresses a node + // the type has } Type elementType = replaceAt(arrayType.elemtype, steps, from + 1, replacement); return elementType == null - ? null + ? null // diff-coverage: ignore -- a path from the recorder always addresses a node the + // type has : TYPE_METADATA_BUILDER.createArrayType(arrayType, elementType); } } - throw new AssertionError(step.kind()); + throw new AssertionError( + step.kind()); // diff-coverage: ignore -- the switch covers every step kind } /** @@ -654,14 +713,12 @@ private static String wrapped(String text, int firstLineIndent, String continuat * *

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. + * is the whole of the fix this class knows how to propose. Whether the result is worth offering + * 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. + *

Only a class type is written out as a bound. A type variable would have to be in scope where + * the source type is declared, which nothing here checks; no known input reaches that case, since + * a target bound naming a method's type variable fails inference before this class runs. */ private @Nullable Type rewriteWithExplicitBounds( Type sourceType, List mismatches) { @@ -683,8 +740,9 @@ private static String wrapped(String text, int firstLineIndent, String continuat || !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; + // wildcard non-null, which is the only fix this method knows + continue; // diff-coverage: ignore -- the check rejects an upper bound only where the source + // is @Nullable and the target is not } boundForWildcard.put(sourceWildcard, targetUpperBound); } @@ -706,59 +764,27 @@ public Type visitWildcardType(Type.WildcardType t, @Nullable Void unused) { } /** - * Returns whether every type-use annotation in {@code type} survives printing, so that a - * suggestion naming it says what the reader would be pasting. + * Returns whether {@code type} prints as a type a reader can declare, so that a fix pasting it + * says what the reader gets. * - *

{@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. + *

This mirrors {@link GenericTypePrettyPrintingVisitor}, which prints {@code @Nullable} and + * drops every other type-use annotation, and has four arms whose output no declaration may hold + * or that denotes nothing: a captured wildcard prints as {@code capture of ?}, an intersection as + * {@code A & B}, an anonymous class under its binary name, and a type that did not resolve under + * a bare name. 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 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; + private boolean isDeclarable(Type type) { + return type.accept(declarabilityVisitor, null); } - /** - * 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 = + private final Types.DefaultTypeVisitor declarabilityVisitor = new Types.DefaultTypeVisitor<>() { @Override public Boolean visitClassType(Type.ClassType t, @Nullable Void unused) { - if (t.isIntersection() || t.tsym.isAnonymous()) { + if (t.isIntersection() || t.tsym.isAnonymous() || !printsEveryAnnotation(t)) { return false; } for (Type typeArgument : t.getTypeArguments()) { @@ -772,30 +798,58 @@ public Boolean visitClassType(Type.ClassType t, @Nullable Void unused) { @Override public Boolean visitWildcardType(Type.WildcardType t, @Nullable Void unused) { - return t.kind == BoundKind.UNBOUND || t.type.accept(this, null); + return printsEveryAnnotation(t) + && (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); + // the printer writes the dimensions of a nested array innermost first, the reverse of the + // order a declaration gives them, so an annotated dimension would land on another one + if (t.elemtype instanceof Type.ArrayType && hasAnnotatedDimension(t)) { + return false; + } + return printsEveryAnnotation(t) && t.elemtype.accept(this, null); } @Override public Boolean visitCapturedType(Type.CapturedType t, @Nullable Void unused) { - return false; + return false; // diff-coverage: ignore -- a type holding a capture is no variable's + // declared type, so sourceDeclaration rejects it first } @Override public Boolean visitErrorType(Type.ErrorType t, @Nullable Void unused) { - return false; + return false; // diff-coverage: ignore -- an unresolved type stops compilation before + // NullAway runs } @Override public Boolean visitType(Type t, @Nullable Void unused) { - return true; + return printsEveryAnnotation(t); } }; + /** Returns whether {@code array} or an array it nests directly carries a type-use annotation. */ + private static boolean hasAnnotatedDimension(Type.ArrayType array) { + for (Type t = array; t instanceof Type.ArrayType nested; t = nested.elemtype) { + if (!nested.getAnnotationMirrors().isEmpty()) { + return true; + } + } + return false; + } + + /** Returns whether the only type-use annotation on {@code type} itself is a nullable one. */ + private boolean printsEveryAnnotation(Type type) { + for (Attribute.TypeCompound annotation : type.getAnnotationMirrors()) { + if (!Nullness.isNullableAnnotation(annotation.type.toString(), config)) { + return false; + } + } + 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) { @@ -806,39 +860,4 @@ public Boolean visitType(Type t, @Nullable Void unused) { } 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 index f049d0d47c..fd1c0e41a1 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java @@ -1,284 +1,498 @@ package com.uber.nullaway.generics; -import com.google.errorprone.VisitorState; import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Type; -import com.uber.nullaway.Config; -import com.uber.nullaway.handlers.Handler; import java.util.ArrayList; -import java.util.Collections; -import java.util.IdentityHashMap; import java.util.List; -import java.util.Set; import org.jspecify.annotations.Nullable; /** - * Finds the positions where a source type does not have the nullness a target type requires. + * Records each position where {@link CheckIdenticalNullabilityVisitor} rejects the nullness of a + * source type, so that a diagnostic names the positions the check itself rejected. * - *

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 visitor reports to this class as it compares: the step it takes into each side before it + * descends, and the two nodes of every comparison it rejects. A rejected node is not descended + * into, so the recorded positions are disjoint. Two of them can still share one caret, where both + * lie below a bound the printer does not show and the caret rises to the wildcard that hides it. * - *

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. + *

Each side is followed in two ways. The steps the check took name the position for the {@code + * path} line, in the classes it compared. The type the reader wrote is where a caret goes, and the + * check does not always compare that type: it views a source {@code ArrayList<@Nullable String>} as + * the {@code List<@Nullable String>} a target {@code List} names. So every step is also + * followed in the written type: by position where the written node has the shape of the compared + * one, and by instance where it does not, since a node the view carried over from the written type + * is the same {@code Type} object there. A node the view built itself, such as the {@code + * List<@Nullable String>} a subclass declared as {@code Sub extends Base>} + * passes to {@code Base}, sits nowhere in the written type and gets no caret there. */ final class NullabilityMismatches { - private final GenericsChecks checks; - private final Config config; - private final Handler handler; - private final VisitorState state; + /** What the check required of the source node at a rejected position. */ + enum Relation { + /** The same nullness as the target node, as for a type argument the source states outright. */ + SAME, + /** A subtype of the target node, as under an upper bound or for the element of an array. */ + SUBTYPE, + /** A supertype of the target node, which is the lower bound of a {@code ? super} wildcard. */ + SUPERTYPE; - /** - * 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; - this.handler = handler; - this.state = state; + /** Returns the relation with the two sides swapped. */ + Relation swapped() { + return switch (this) { + case SAME -> SAME; + case SUBTYPE -> SUPERTYPE; + case SUPERTYPE -> + SUBTYPE; // diff-coverage: ignore -- the visitor rejects only SAME and SUBTYPE + }; + } } /** - * One position where the source does not have the nullness the target requires. + * One position where the check rejected the nullness of the source. * - * @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 + * @param relation what the check required of the source node + * @param path the steps the check took into the target, which the {@code path} line names + * @param targetNode the node the target has there + * @param sourceNode the node the source has there + * @param targetNodePath where {@code targetNode} sits in the target as written, or {@code null} + * where it sits nowhere a printer shows, which is what a rewrite of the target has to address + * @param targetCaret where the target's caret goes, or {@code null} where the target gets none + * @param sourceCaret where the source's caret goes in the source as written, or {@code null} + * where the node the check compared sits nowhere in that type + * @param viewCaret where the source's caret goes in {@link #viewedSource()}, or {@code null} + * @param sourcePrintedNode the node under {@code sourceCaret}; where there is no such caret, the + * deepest node the compared view of the source prints. It is the wildcard itself where the + * node at fault lies below a bound the wildcard leaves implicit + * @param sourceWildcard the source wildcard whose upper bound the check compared at this + * position, or {@code null} where the source states the type outright or the comparison was + * not one of upper bounds + * @param targetUpperBound the upper bound the target requires there, which writing an explicit * bound on {@code sourceWildcard} would have to produce */ record Mismatch( + Relation relation, TypePath path, Type targetNode, Type sourceNode, - TypePath targetCaret, + @Nullable TypePath targetNodePath, + @Nullable TypePath targetCaret, + @Nullable TypePath sourceCaret, + @Nullable TypePath viewCaret, 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 written type a comparison is followed in, and how far it could be followed. * - *

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. + *

{@code LOCATED}: {@code node} sits at {@code path} and the printer shows it. {@code HIDDEN}: + * the comparison went below a bound the printer does not show, and {@code node} is the wildcard + * at {@code path} that hides it, which is where a caret goes for everything below. {@code LOST}: + * the comparison reached a node the written type does not hold, and {@code node} is the nearest + * enclosing node it does hold, at {@code path}. */ - private record Position(TypePath path, TypePath caret, boolean printed) { + private record Track(State state, Type node, TypePath path) { - static Position root() { - return new Position(TypePath.root(), TypePath.root(), true); + enum State { + LOCATED, + HIDDEN, + LOST } - Position then(TypePath.Step step, boolean stepIsPrinted) { - TypePath child = path.then(step); - boolean childIsPrinted = printed && stepIsPrinted; - return new Position(child, childIsPrinted ? child : caret, childIsPrinted); + static Track located(Type node, TypePath path) { + return new Track(State.LOCATED, node, path); } } /** - * 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. + * The upper bounds whose comparison is the current one. * - * @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 + * @param sourceWildcard the source wildcard the source bound belongs to, or {@code null} where + * the source states the type outright + * @param targetUpperBound the upper 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. + * Where the comparison stands. The visitor saves one before a descent and restores it after. + * + * @param targetSteps the steps taken into the target, named for the classes compared + * @param target the target as written + * @param source the source as written + * @param view the source viewed as the target's class at the root, or {@code null} where that + * view is the written source itself + * @param sourceShown the deepest node of the compared source a printer would show + * @param swapped whether the visitor's left side is the source, as inside the lower bound of a + * {@code ? super} wildcard, where the check asks whether that bound is a subtype of the + * source + * @param bound the upper bounds this comparison is of, or {@code null} where it is not of bounds + */ + record Frame( + TypePath targetSteps, + Track target, + Track source, + @Nullable Track view, + Type sourceShown, + boolean swapped, + @Nullable BoundComparison bound) {} + + private Frame frame; + + private @Nullable Type viewedSource; + + private final List mismatches = new ArrayList<>(); + + /** + * Starts a record of the comparison of {@code sourceType} against {@code targetType}, as written. */ - List collect(Type targetType, Type sourceType) { - List mismatches = new ArrayList<>(); - collect(targetType, sourceType, Position.root(), sourceType, Position.root(), null, mismatches); + NullabilityMismatches(Type targetType, Type sourceType) { + this.frame = + new Frame( + TypePath.root(), + Track.located(targetType, TypePath.root()), + Track.located(sourceType, TypePath.root()), + null, + sourceType, + false, + null); + } + + /** Returns the rejected positions, in the order the check compared them. */ + List 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 + * Returns the source viewed as the class the target names, where the check compared that view at + * the root rather than the written source, and {@code null} otherwise. */ - private void collect( - Type target, - Type source, - Position targetPosition, - Type sourcePrintedNode, - Position sourcePosition, - @Nullable BoundComparison bound, - List mismatches) { - Type.WildcardType targetWildcard = GenericsUtils.asWildcard(target); - Type.WildcardType sourceWildcard = GenericsUtils.asWildcard(source); - if (targetWildcard != null && sourceWildcard != null) { - Set activeSources = - activeBoundComparisons.computeIfAbsent( - targetWildcard, unused -> Collections.newSetFromMap(new IdentityHashMap<>())); - if (!activeSources.add(sourceWildcard)) { - return; - } - try { - // the check compares the effective upper bounds, and only an `? extends X` wildcard prints - // the bound it is compared by: `?` and `? super X` take one from a type variable - Type targetUpperBound = - GenericsUtils.wildcardUpperBound(targetWildcard, state, config, handler); - Type sourceUpperBound = - GenericsUtils.wildcardUpperBound(sourceWildcard, state, config, handler); - collect( - targetUpperBound, - sourceUpperBound, - targetPosition.then( - TypePath.Step.wildcardBound(), targetWildcard.kind == BoundKind.EXTENDS), - sourceWildcard.kind == BoundKind.EXTENDS ? sourceUpperBound : sourcePrintedNode, - sourcePosition.then( - TypePath.Step.wildcardBound(), sourceWildcard.kind == BoundKind.EXTENDS), - new BoundComparison(sourceWildcard, targetUpperBound), - mismatches); - } finally { - activeSources.remove(sourceWildcard); - } - return; - } - if (targetWildcard != null && targetWildcard.kind == BoundKind.EXTENDS) { - // a type argument the source states outright, against a bound the target states, as with - // List against ? extends List - 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; + @Nullable Type viewedSource() { + return viewedSource; + } + + /** Puts back a frame an {@code enter} method returned. */ + void restore(Frame saved) { + frame = saved; + } + + /** + * Notes that the check compares {@code lhs} against {@code rhsView}, the right side {@code rhs} + * viewed as the class of {@code lhs}. At the root of the source, a view of another class is what + * a caret goes into where the written source does not hold the compared node. + */ + void enterClassComparison(Type rhs, Type rhsView) { + if (frame.view() == null + && !frame.swapped() + && frame.targetSteps().isRoot() + && !rhsView.tsym.equals(rhs.tsym)) { + viewedSource = rhsView; + frame = + new Frame( + frame.targetSteps(), + frame.target(), + frame.source(), + Track.located(rhsView, TypePath.root()), + frame.sourceShown(), + frame.swapped(), + frame.bound()); } - if (target instanceof Type.ClassType targetClassType - && source instanceof Type.ClassType sourceClassType) { - collectFromClassTypes( - targetClassType, sourceClassType, targetPosition, sourcePosition, mismatches); - return; + } + + /** Steps into type argument {@code index} of {@code lhs} and of {@code rhsView}. */ + Frame enterTypeArgument(int index, Type.ClassType lhs, Type.ClassType rhsView) { + return enter( + new Step(TypePath.Step.Kind.TYPE_ARGUMENT, index, lhs, lhs.getTypeArguments().get(index)), + new Step( + TypePath.Step.Kind.TYPE_ARGUMENT, + index, + rhsView, + rhsView.getTypeArguments().get(index)), + null); + } + + /** Steps into the enclosing type of {@code lhs} and of {@code rhsView}. */ + Frame enterEnclosingType(Type.ClassType lhs, Type.ClassType rhsView) { + return enter( + new Step(TypePath.Step.Kind.ENCLOSING_TYPE, -1, lhs, lhs.getEnclosingType()), + new Step(TypePath.Step.Kind.ENCLOSING_TYPE, -1, rhsView, rhsView.getEnclosingType()), + null); + } + + /** Steps into the element type of two arrays. */ + Frame enterArrayElement(Type.ArrayType lhs, Type.ArrayType rhs) { + return enter( + new Step(TypePath.Step.Kind.ARRAY_ELEMENT, -1, lhs, lhs.elemtype), + new Step(TypePath.Step.Kind.ARRAY_ELEMENT, -1, rhs, rhs.elemtype), + null); + } + + /** + * Steps into the upper bounds the check compares. A side whose wildcard is {@code null} states + * its type outright and takes no step. + */ + Frame enterUpperBounds( + @Nullable Type lhsWildcard, Type lhsBound, @Nullable Type rhsWildcard, Type rhsBound) { + BoundComparison bound = + lhsWildcard == null || frame.swapped() + ? null + : new BoundComparison( + rhsWildcard == null ? null : GenericsUtils.asWildcard(rhsWildcard), lhsBound); + return enter( + lhsWildcard == null + ? null + : new Step(TypePath.Step.Kind.WILDCARD_BOUND, -1, lhsWildcard, lhsBound), + rhsWildcard == null + ? null + : new Step(TypePath.Step.Kind.WILDCARD_BOUND, -1, rhsWildcard, rhsBound), + bound); + } + + /** + * Steps into the lower bound of {@code lhsWildcard} and, where {@code rhsWildcard} is not {@code + * null}, of that wildcard too, and swaps the sides: the check goes on to ask whether {@code + * rhsBound} is a subtype of {@code lhsBound}, so its left side is then the source. + */ + Frame enterLowerBounds( + Type lhsWildcard, Type lhsBound, @Nullable Type rhsWildcard, Type rhsBound) { + Frame saved = + enter( + new Step(TypePath.Step.Kind.WILDCARD_LOWER_BOUND, -1, lhsWildcard, lhsBound), + rhsWildcard == null + ? null + : new Step(TypePath.Step.Kind.WILDCARD_LOWER_BOUND, -1, rhsWildcard, rhsBound), + null); + frame = + new Frame( + frame.targetSteps(), + frame.target(), + frame.source(), + frame.view(), + frame.sourceShown(), + !frame.swapped(), + null); + return saved; + } + + /** + * Records that the check rejected {@code rhsNode} where {@code lhsNode} stands, because the right + * side does not stand in {@code relation} to the left. + */ + void reject(Relation relation, Type lhsNode, Type rhsNode) { + boolean swapped = frame.swapped(); + Type targetNode = swapped ? rhsNode : lhsNode; + Type sourceNode = swapped ? lhsNode : rhsNode; + Located target = locate(frame.target()); + Located source = locate(frame.source()); + Located view = frame.view() == null ? null : locate(frame.view()); + BoundComparison bound = frame.bound(); + mismatches.add( + new Mismatch( + swapped ? relation.swapped() : relation, + frame.targetSteps(), + targetNode, + sourceNode, + target == null || target.hidden() ? null : target.path(), + target == null ? null : target.path(), + source == null ? null : source.path(), + view == null ? null : view.path(), + source != null ? source.node() : frame.sourceShown(), + bound == null ? null : bound.sourceWildcard(), + bound == null ? null : bound.targetUpperBound())); + } + + /** + * One step of the comparison into one side. + * + * @param kind the kind of step + * @param index the type argument stepped into, or {@code -1} + * @param parent the node the comparison steps from + * @param child the node it steps to + */ + private record Step(TypePath.Step.Kind kind, int index, Type parent, Type child) {} + + /** + * Takes one step on each side the visitor names, and returns the frame from before it. A {@code + * null} step leaves that side where it is. + */ + private Frame enter(@Nullable Step lhs, @Nullable Step rhs, @Nullable BoundComparison bound) { + Frame saved = frame; + Step targetStep = saved.swapped() ? rhs : lhs; + Step sourceStep = saved.swapped() ? lhs : rhs; + TypePath targetSteps = saved.targetSteps(); + Track target = saved.target(); + if (targetStep != null) { + targetSteps = targetSteps.then(comparedStep(targetStep)); + target = follow(target, targetStep); } - 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); + Track source = saved.source(); + Track view = saved.view(); + Type sourceShown = saved.sourceShown(); + if (sourceStep != null) { + source = follow(source, sourceStep); + view = view == null ? null : follow(view, sourceStep); + if (isShown(sourceStep.kind(), sourceStep.parent())) { + sourceShown = sourceStep.child(); + } } + frame = new Frame(targetSteps, target, source, view, sourceShown, saved.swapped(), bound); + return saved; } - /** 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; + /** Names {@code step} for the {@code path} line, in the class the comparison stepped from. */ + private static TypePath.Step comparedStep(Step step) { + return switch (step.kind()) { + case TYPE_ARGUMENT -> typeArgumentStep(step.parent(), step.index()); + case WILDCARD_BOUND -> TypePath.Step.wildcardBound(); + case WILDCARD_LOWER_BOUND -> TypePath.Step.wildcardLowerBound(); + case ARRAY_ELEMENT -> TypePath.Step.arrayElement(); + case ENCLOSING_TYPE -> TypePath.Step.enclosingType(); + }; + } + + /** + * Whether the printer shows the node {@code kind} steps to from {@code parent}: only the bound a + * wildcard states is printed, and the upper bound of {@code ?} and of {@code ? super X} is not. + */ + private static boolean isShown(TypePath.Step.Kind kind, Type parent) { + if (kind != TypePath.Step.Kind.WILDCARD_BOUND) { + return true; } - List targetArguments = target.getTypeArguments(); - List sourceArguments = sourceAsTarget.getTypeArguments(); - if (targetArguments.size() != sourceArguments.size()) { - return; + Type.WildcardType wildcard = GenericsUtils.asWildcard(parent); + return wildcard != null && wildcard.kind == BoundKind.EXTENDS; + } + + /** + * Follows {@code step} of the comparison in the written type {@code track} follows: by position + * where the written node has the shape of the compared one, and otherwise by finding the compared + * child as an instance inside the nearest written node. + */ + private static Track follow(Track track, Step step) { + switch (track.state()) { + case HIDDEN -> { + return track; + } + case LOST -> { + return relocate(track, step.child()); + } + case LOCATED -> { + Track child = childByPosition(track, step); + return child != null ? child : relocate(track, step.child()); + } } - 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); + throw new AssertionError( + track.state()); // diff-coverage: ignore -- the switch covers every state + } + + /** + * Returns the child {@code step} reaches from the written node of {@code track}, where that node + * has the shape of the node the comparison stepped from, or {@code null} where it has another. + */ + private static @Nullable Track childByPosition(Track track, Step step) { + Type node = track.node(); + switch (step.kind()) { + case TYPE_ARGUMENT -> { + if (node instanceof Type.ClassType classType + && classType.tsym.equals(step.parent().tsym) + && step.index() < classType.getTypeArguments().size()) { + return Track.located( + classType.getTypeArguments().get(step.index()), + track.path().then(typeArgumentStep(classType, step.index()))); + } + return null; + } + case ENCLOSING_TYPE -> { + if (node instanceof Type.ClassType classType && classType.tsym.equals(step.parent().tsym)) { + return Track.located( + classType.getEnclosingType(), track.path().then(TypePath.Step.enclosingType())); + } + return null; + } + case ARRAY_ELEMENT -> { + if (node instanceof Type.ArrayType arrayType) { + return Track.located(arrayType.elemtype, track.path().then(TypePath.Step.arrayElement())); + } + return null; // diff-coverage: ignore -- a step into an array element is taken only from an + // array + } + case WILDCARD_BOUND -> { + Type.WildcardType wildcard = GenericsUtils.asWildcard(node); + if (wildcard == null) { + return null; // diff-coverage: ignore -- a step into a wildcard bound is taken only from a + // wildcard + } + // the upper bound of `?` and `? super X` is not printed, so the caret stays on the wildcard + return wildcard.kind == BoundKind.EXTENDS + ? Track.located(wildcard.type, track.path().then(TypePath.Step.wildcardBound())) + : new Track(Track.State.HIDDEN, node, track.path()); + } + case WILDCARD_LOWER_BOUND -> { + Type.WildcardType wildcard = GenericsUtils.asWildcard(node); + return wildcard != null && wildcard.kind == BoundKind.SUPER + ? Track.located(wildcard.type, track.path().then(TypePath.Step.wildcardLowerBound())) + : null; // diff-coverage: ignore -- a step into a lower bound is taken only from a ? + // super wildcard + } } - collect( - target.getEnclosingType(), - sourceAsTarget.getEnclosingType(), - targetPosition.then(TypePath.Step.enclosingType(), true), - sourceAsTarget.getEnclosingType(), - sourcePosition.then(TypePath.Step.enclosingType(), true), - null, - mismatches); + throw new AssertionError( + step.kind()); // diff-coverage: ignore -- the switch covers every step kind + } + + /** + * Finds {@code compared} inside the written node of {@code track}, and returns the track located + * there, or the track lost at that node where {@code compared} occurs there nowhere or at more + * than one position. + */ + private static Track relocate(Track track, Type compared) { + TypePath relative = pathOfInstance(track.node(), compared); + return relative == null + ? new Track(Track.State.LOST, track.node(), track.path()) + : Track.located(compared, track.path().append(relative)); + } + + /** + * A position in a written type where a compared node is drawn. + * + * @param path where the caret goes + * @param node the printed node at {@code path} + * @param hidden whether the compared node lies below a bound the node at {@code path} hides + */ + private record Located(TypePath path, Type node, boolean hidden) {} + + /** + * Returns where the node the check rejected is drawn in the written type {@code track} follows, + * or {@code null} where that type does not hold it. + */ + private static @Nullable Located locate(Track track) { + return switch (track.state()) { + case LOCATED -> new Located(track.path(), track.node(), false); + case HIDDEN -> new Located(track.path(), track.node(), true); + // follow already looked for the compared node as an instance of the written type, and a + // track it left lost holds no such instance + case LOST -> null; + }; + } + + /** + * Returns the step into type argument {@code index} of {@code type}, named for the type parameter + * of its class. + */ + private static TypePath.Step typeArgumentStep(Type type, int index) { + List formals = type.tsym.type.getTypeArguments(); + Type.TypeVar formal = + index < formals.size() && formals.get(index) instanceof Type.TypeVar typeVar + ? typeVar + : null; + return TypePath.Step.typeArgument( + index, formal, type.tsym instanceof Symbol.ClassSymbol owner ? owner : null); } /** * 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 + *

Identity, not equality: the caller has a node the comparison 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. @@ -301,14 +515,21 @@ private static void findInstance(Type type, Type node, TypePath path, 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(typeArguments.get(i), node, path.then(typeArgumentStep(classType, i)), 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 index c42f9b0c01..b989e21772 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java @@ -24,8 +24,13 @@ record Step( enum Kind { /** Into the type argument at {@link Step#index}. */ TYPE_ARGUMENT, - /** Into the declared upper bound of a wildcard. */ + /** + * Into the upper bound of a wildcard: the bound {@code ? extends X} states, and the one + * {@code ?} and {@code ? super X} take from their type parameter, which is not printed. + */ WILDCARD_BOUND, + /** Into the bound {@code ? super X} states. */ + WILDCARD_LOWER_BOUND, /** Into the element type of an array. */ ARRAY_ELEMENT, /** Into the enclosing instance type of an inner class. */ @@ -41,6 +46,10 @@ static Step wildcardBound() { return new Step(Kind.WILDCARD_BOUND, -1, null, null); } + static Step wildcardLowerBound() { + return new Step(Kind.WILDCARD_LOWER_BOUND, -1, null, null); + } + static Step arrayElement() { return new Step(Kind.ARRAY_ELEMENT, -1, null, null); } @@ -62,9 +71,13 @@ String describe() { return switch (kind) { case TYPE_ARGUMENT -> formal == null || owner == null - ? "type argument " + (index + 1) + ? "type argument " + + (index + + 1) // diff-coverage: ignore -- every step the recorder builds carries its + // formal and owner : owner.getSimpleName() + " type argument " + formal.tsym.getSimpleName(); case WILDCARD_BOUND -> "wildcard upper bound"; + case WILDCARD_LOWER_BOUND -> "wildcard lower bound"; case ARRAY_ELEMENT -> "array element"; case ENCLOSING_TYPE -> "enclosing type"; }; @@ -89,6 +102,13 @@ TypePath then(Step step) { return new TypePath(ImmutableList.builder().addAll(steps).add(step).build()); } + /** Returns this path extended by every step of {@code relative}, in order. */ + TypePath append(TypePath relative) { + return relative.isRoot() + ? this // diff-coverage: ignore -- append is called only with a non-root path + : new TypePath(ImmutableList.builder().addAll(steps).addAll(relative.steps).build()); + } + /** Returns the descents from the root, in order. */ ImmutableList steps() { return steps; diff --git a/nullaway/src/test/java/com/uber/nullaway/JSpecifyJDKModelsTest.java b/nullaway/src/test/java/com/uber/nullaway/JSpecifyJDKModelsTest.java index 9b60f8f6af..256316736e 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 nullability: found @Nullable String, required Object + // BUG: Diagnostic contains: incompatible nullability in Collection type argument E -> wildcard upper bound: 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 nullability: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable Object, required Object return list.toArray(); } static class DelegatingList extends AbstractList { diff --git a/nullaway/src/test/java/com/uber/nullaway/ParameterAssignmentTests.java b/nullaway/src/test/java/com/uber/nullaway/ParameterAssignmentTests.java index 5779fd78dd..af9acdafe8 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in List type argument E: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in array element: 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/BytecodeGenericsTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/BytecodeGenericsTests.java index 8e5a933855..66821145f4 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in NullableTypeParam type argument E: 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 nullability: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in NullableTypeParam type argument E: a type argument must match exactly; found String, required @Nullable String NullableTypeParam.staticField = t1; - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in NullableTypeParam type argument E: 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 nullability: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in NullableTypeParam type argument E: a type argument must match exactly; found String, required @Nullable String GenericTypeArgMethods.nullableTypeParamArg(t1); - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in NullableTypeParam type argument E: 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 9546db5b86..c7ee49cedb 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: found @Nullable String, required String Bar b = new Bar<>(Foo.makeNullableStr()); - // BUG: Diagnostic contains: incompatible nullability: found @Nullable Void, required Void + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: found @Nullable String, required String return new Bar<>(Foo.makeNullableStr()) {}; } void paramNegative() { takeNullableVoid(new Bar<>(Foo.make()) {}); } void paramPositive() { - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: found @Nullable String, required String return new Box<>(id(makeNullableFoo())); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInferenceErrorReportingTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInferenceErrorReportingTests.java index 269d22820d..6b00b90a29 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 nullability: a type argument must match exactly; found @Nullable E [], required E @Nullable [] + // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable E, required E return Arrays.copyOf(original, original.length); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java index 93ff41d452..f46862872b 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java @@ -245,7 +245,7 @@ static class Sub extends Outer<@Nullable S> {} > void nullableThroughBound(Y y) { // BUG: Diagnostic contains: dereferenced expression 'y.get()' is @Nullable y.get().hashCode(); - // BUG: Diagnostic contains: incompatible types: Y cannot be converted to Outer + // BUG: Diagnostic contains: incompatible nullability in Outer type argument O: found @Nullable String, required String Outer nonNull = y; Outer<@Nullable String> nullable = y; y.new Inner(null); @@ -272,7 +272,7 @@ > void nonNullThroughBoundOfBound(Z z) { void nullableThroughCapturedWildcard(List> l) { // BUG: Diagnostic contains: dereferenced expression 'l.get(0).get()' is @Nullable l.get(0).get().hashCode(); - // BUG: Diagnostic contains: incompatible types: capture of ? extends Sub cannot be converted to Outer + // BUG: Diagnostic contains: incompatible nullability in Outer type argument O: found @Nullable String, required String Outer nonNull = l.get(0); Outer<@Nullable String> nullable = l.get(0); } @@ -361,7 +361,7 @@ static class ListFuture } static MyFuture> invalid() { - // BUG: Diagnostic contains: incompatible nullability: found @Nullable V, required V + // BUG: Diagnostic contains: incompatible nullability in MyFuture type argument T -> List type argument E: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in List type argument E: found @Nullable String, required String List invalid = box.get(); box.set(nullableList); - // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in List type argument E: 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 nullability: found @Nullable O, required O + // BUG: Diagnostic contains: incompatible nullability in List type argument E: found @Nullable O, required O List invalid = child.get(); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericLambdaTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericLambdaTests.java index d660011b67..4e8392d3af 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in List type argument E: found @Nullable String, required String MarkedListSupplier s = () -> l; } void blockBodyToMarkedInterface(List<@Nullable String> l) { - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in List type argument E: 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 42718e3763..d80bccfc54 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 nullability: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in Box type argument T: a type argument must match exactly; found String, required @Nullable String acceptsNullable(flat); } @@ -1337,7 +1337,7 @@ void testNegative() { receiver(makeCancelable(this::target)); } void testPositive() { - // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in Callback type argument T: 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 e4a97dbabf..cfb298c8bc 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java @@ -559,9 +559,9 @@ interface B { X b(); } id1(value).a().length(); A<@Nullable String> nullableA = id1(value); B nonNullB = id1(value); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in A type argument X: found @Nullable String, required String A nonNullA = id1(value); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in B type argument X: a type argument must match exactly; found String, required @Nullable String B<@Nullable String> nullableB = id1(value); } @@ -572,9 +572,9 @@ interface B { X b(); } id2(value).a().length(); A<@Nullable String> nullableA = id2(value); B nonNullB = id2(value); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in A type argument X: found @Nullable String, required String A nonNullA = id2(value); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in B type argument X: a type argument must match exactly; found String, required @Nullable String B<@Nullable String> nullableB = id2(value); } @@ -585,9 +585,9 @@ interface B { X b(); } id3(value).a().length(); A<@Nullable String> nullableA = id3(value); B nonNullB = id3(value); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in A type argument X: found @Nullable String, required String A nonNullA = id3(value); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in B type argument X: a type argument must match exactly; found String, required @Nullable String B<@Nullable String> nullableB = id3(value); } @@ -598,9 +598,9 @@ interface B { X b(); } id4(value).a().length(); A<@Nullable String> nullableA = id4(value); B nonNullB = id4(value); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in A type argument X: found @Nullable String, required String A nonNullA = id4(value); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in B type argument X: a type argument must match exactly; found String, required @Nullable String B<@Nullable String> nullableB = id4(value); } } @@ -634,9 +634,9 @@ static class Box1> & B>> { box.get().a().get(0).length(); A> nullableA = box.get(); B> nonNullB = box.get(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in A type argument X -> List type argument E: found @Nullable String, required String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in B type argument X -> List type argument E: a type argument must match exactly; found String, required @Nullable String B> nullableB = box.get(); } @@ -652,9 +652,9 @@ static class Box2> & A>> { box.get().a().get(0).length(); A> nullableA = box.get(); B> nonNullB = box.get(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in A type argument X -> List type argument E: found @Nullable String, required String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in B type argument X -> List type argument E: a type argument must match exactly; found String, required @Nullable String B> nullableB = box.get(); } @@ -670,9 +670,9 @@ static class Box3> & B>> box.get().a().get(0).length(); A> nullableA = box.get(); B> nonNullB = box.get(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in A type argument X -> List type argument E: found @Nullable String, required String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in B type argument X -> List type argument E: a type argument must match exactly; found String, required @Nullable String B> nullableB = box.get(); } @@ -688,9 +688,9 @@ static class Box4> & A>> box.get().a().get(0).length(); A> nullableA = box.get(); B> nonNullB = box.get(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in A type argument X -> List type argument E: found @Nullable String, required String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in B type argument X -> List type argument E: a type argument must match exactly; found String, required @Nullable String B> nullableB = box.get(); } } @@ -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 nullability: a type argument must match exactly; found Object, required @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: 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 nullability: a type argument must match exactly; found Object, required @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: 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 nullability: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument V -> ArrayList type argument E: a type argument must match exactly; found String, required @Nullable String Foo> fooNonNull_2 = f.nonNullTest(); - // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Integer, required @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in Foo type argument K: 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 nullability: a type argument must match exactly; found Object, required @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> array element -> Foo type argument T: 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 nullability: a type argument must match exactly; found Object, required @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in array element -> Foo type argument T: 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 nullability: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in Bar type argument T -> Bar type argument T: 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 nullability: 2 mismatches between source and target types + // BUG: Diagnostic contains: incompatible nullability in Function type argument T and 1 other position: a type argument must match exactly; found String, required @Nullable String 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 nullability: a type argument must match exactly; found Object, required @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: 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 nullability: a type argument must match exactly; found Object, required @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: 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 nullability: a type argument must match exactly; found Object, required @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in array element: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable String, required String stringField = f(arr2, "hi"); } } @@ -2242,12 +2242,11 @@ public void capturedTypeAtNullUnmarkedBoundary() { message -> message.contains( """ - incompatible nullability: found @Nullable Object, required Object + incompatible nullability in Foo type argument T -> wildcard upper bound: found @Nullable Object, required Object found: Foo ^^^^^^^^^^^^ 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( @@ -2291,12 +2290,11 @@ public void capturedTypeGetsDirectNullableAnnotationFromTypeVariableUse() { message -> message.contains( """ - incompatible nullability: found @Nullable Object, required Object + incompatible nullability in Foo type argument T -> wildcard upper bound: 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( @@ -2452,7 +2450,7 @@ class Test { class Box {} void swapBoxes(Box box1, Box box2) {} void testPositive(Box box1, Box<@Nullable String> box2) { - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Box type argument T: found @Nullable String, required String swapBoxes(box1, box2); } void TestNegative(Box<@Nullable String> box1, Box<@Nullable String> box2) { @@ -2547,7 +2545,7 @@ Supplier make2() { } // tests that our repair computes a consistent substitution for the type variables void test2() { - // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found OuterT, required @Nullable OuterT + // BUG: Diagnostic contains: incompatible nullability in Supplier type argument T: a type argument must match exactly; found OuterT, required @Nullable OuterT acceptTwoSup(sup, sup2); } } @@ -2679,7 +2677,7 @@ static class Foo { .or(new Foo<@Nullable String>()); // a true positive case - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: found @Nullable String, required String static Foo WRONG = Foo.of(new Foo<@Nullable String>()).or(new Foo<@Nullable String>()); } @@ -2735,7 +2733,7 @@ class Test { static class Box {} static void accept(Box<@Nullable T> box) {} void test(Box> box) { - // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found CompletableFuture, required @Nullable CompletableFuture + // BUG: Diagnostic contains: incompatible nullability in Box type argument T: a type argument must match exactly; found CompletableFuture, required @Nullable CompletableFuture accept(box); } } @@ -3348,9 +3346,9 @@ class GInner { return x; } void nullableQualifier(Outer<@Nullable String> o) { - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Outer type argument O: found @Nullable String, required String id(o.new Inner("")); - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Outer type argument O: 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 77896df833..75ef763cc4 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 nullability: found @Nullable Void, required Void + // BUG: Diagnostic contains: incompatible nullability in List type argument E: 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 nullability: found @Nullable Void, required Void + // BUG: Diagnostic contains: incompatible nullability in List type argument E: 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 683e715402..5bcc4a69a1 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in NonNullTypeParam type argument E: found @Nullable String, required String new NonNullTypeParam< // BUG: Diagnostic contains: Generic type parameter @Nullable String>()); @@ -229,7 +229,7 @@ class Test { static class Holder {} static void typeArguments() { Holder other = new Holder<@Other String>(); - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Holder type argument E: found @Nullable String, required String Holder otherThenNullable = new Holder<@Other @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 nullability: a type argument must match exactly; found Test.Wrapper<@Nullable String>.Fn, required Test.Wrapper.@Nullable Fn + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Wrapper type argument P: found @Nullable String, required String param(x); } static void positiveAssign() { Wrapper<@Nullable String>.Fn p1 = null; - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Wrapper type argument P: found @Nullable String, required String Wrapper.Fn p2 = p1; } static Wrapper.@Nullable Fn positiveReturn() { Wrapper<@Nullable String>.Fn p1 = null; - // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Test.Wrapper<@Nullable String>.Fn, required Test.Wrapper.@Nullable Fn + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Wrapper type argument P: found @Nullable String, required String return p1; } static void negativeParam() { @@ -349,13 +349,13 @@ void callOnResult() { } public void testPositive() { addCallback( - // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Integer, required @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in Callback type argument T: a type argument must match exactly; found Integer, required @Nullable Integer new Callback() { @Override public void onResult(Integer value) { - // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Integer, required @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in Callback type argument T: a type argument must match exactly; found Integer, required @Nullable Integer removeCallback(this); - // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Integer, required @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in Callback type argument T: a type argument must match exactly; found Integer, required @Nullable Integer Callback<@Nullable Integer> self = this; } void callOnResult() { @@ -457,7 +457,7 @@ public void genericsChecksForAssignments() { class Test { static class NullableTypeParam {} static void testPositive(NullableTypeParam<@Nullable String> t1) { - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in NullableTypeParam type argument E: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in NullableTypeParam type argument E: 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 nullability: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in SampleClassMultipleArguments type argument E1 -> SampleClass type argument E -> SampleClass type argument E: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Fn type argument R: 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 nullability: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in Fn2 type argument P: 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 nullability: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in SuperClassC type argument P1: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in D type argument P: found @Nullable String, required String D f1 = new B<@Nullable String>(); - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in D type argument P: 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 nullability: 2 mismatches between source and target types + // BUG: Diagnostic contains: incompatible nullability in Super type argument A and 1 other position: a type argument must match exactly; found String, required @Nullable String 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in D type argument P -> C type argument P: found @Nullable String, required String D> f1 = new B>(); - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument P: found @Nullable String, required String A, String> f2 = new A, @Nullable String>(); - // BUG: Diagnostic contains: incompatible nullability: found Test.@Nullable C, required Test.C + // BUG: Diagnostic contains: incompatible nullability in D type argument P: 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 nullability: a type argument must match exactly; found Object, required @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in A type argument T1: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument T: found @Nullable String, required String return new A<@Nullable String>(); } static A<@Nullable String> testPositive2() { - // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in A type argument T: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument T: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument T: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument T -> A type argument T: found @Nullable String, required String A a = sampleMethod1(a1, a2); } static void testPositive2(A> a1, A a2) { - // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in A type argument T -> A type argument T: 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 nullability: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in A type argument T: 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 nullability: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in A type argument T: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument T: found @Nullable String, required String A<@Nullable String> b = sampleMethodWithVarArgs(a1); - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument T: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in array element -> A type argument T: 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 nullability: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in A type argument T -> array element -> A type argument T: a type argument must match exactly; found String, required @Nullable String A[]> var1 = new A[]>(); - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument T -> array element -> A type argument T: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument T -> array element -> A type argument T: 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 nullability: a type argument must match exactly; found int [], required int @Nullable [] + // BUG: Diagnostic contains: incompatible nullability in A type argument T: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> A type argument X: 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>(); @@ -2057,28 +2057,28 @@ void staticSubclassWithNullableOuterMatches(NullableInner input) { Outer<@Nullable String>.Inner result = input; } void staticSubclassWithNullableOuterMismatches(NullableInner input) { - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Outer type argument T: 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 nullability: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Outer type argument T: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Outer type argument T: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Outer type argument T: found @Nullable String, required String Outer.Inner result = input; } } @@ -3138,7 +3138,7 @@ void testNegative(Function<@Nullable V, @Nullable V> f) { foo(f); } void testPositive(Function f) { - // BUG: Diagnostic contains: incompatible nullability: 2 mismatches between source and target types + // BUG: Diagnostic contains: incompatible nullability in Function type argument T and 1 other position: a type argument must match exactly; found V, required @Nullable V 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 nullability: 2 mismatches between source and target types + // BUG: Diagnostic contains: incompatible nullability in array element -> Function type argument T and 1 other position: a type argument must match exactly; found V, required @Nullable V 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 nullability: 2 mismatches between source and target types + // BUG: Diagnostic contains: incompatible nullability in Function type argument T and 1 other position: found @Nullable String, required String this.<@Nullable String>foo(f); } void testPositiveArray(Function f) { - // BUG: Diagnostic contains: incompatible nullability: 2 mismatches between source and target types + // BUG: Diagnostic contains: incompatible nullability in Function type argument T and 1 other position: found String @Nullable [], required String [] this.foo(f); } } @@ -3196,15 +3196,15 @@ void testNegative(Function f) { foo(f); } void testPositive1(Function<@Nullable V, V> f) { - // BUG: Diagnostic contains: incompatible nullability: 2 mismatches between source and target types + // BUG: Diagnostic contains: incompatible nullability in Function type argument T and 1 other position: found @Nullable V, required V foo(f); } void testPositive2(Function f) { - // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found V, required @Nullable V + // BUG: Diagnostic contains: incompatible nullability in Function type argument R: 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 nullability: found @Nullable V, required V + // BUG: Diagnostic contains: incompatible nullability in Function type argument T: 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 nullability: a type argument must match exactly; found Function, required @Nullable Function<@Nullable String, @Nullable String> + // BUG: Diagnostic contains: incompatible nullability in Function type argument T and 1 other position: a type argument must match exactly; found String, required @Nullable String bar = f; } } @@ -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 nullability: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in Inner type argument T: found @Nullable Object, required Object Inner mNonNullThing = new Inner<@Nullable Object>().identity(); } """) @@ -3440,7 +3440,7 @@ private static class A { } private static class B extends A<@Nullable Object> { B(List l) { - // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in List type argument E: 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 nullability: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in A type argument T: found @Nullable Object, required Object A a = new B(); - // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in A type argument T: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in MaybeNull type argument T: found @Nullable String, required String accept(nonNull.asNullable()); MaybeNull<@Nullable String> m1 = nonNull.asNullable(); - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in MaybeNull type argument T: 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 nullability: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: found @Nullable String, required String Foo f4 = nonnullFoo.nullableField; } } 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 53361729f0..95ab83176f 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 nullability: found @Nullable A & @Nullable B, required A + // BUG: Diagnostic contains: incompatible nullability in Result type argument T -> wildcard upper bound: found @Nullable A & @Nullable B, required A return source.result(); } Result rejectsAllNullableLastComponent(AllNullable source) { - // BUG: Diagnostic contains: incompatible nullability: found @Nullable A & @Nullable B, required B + // BUG: Diagnostic contains: incompatible nullability in Result type argument T -> wildcard upper bound: found @Nullable A & @Nullable B, required B return source.result(); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java index 3bf603888b..7a6ad346c3 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java @@ -36,7 +36,7 @@ void acceptsMatchingNullableComponent(Factory factory) { } void rejectsNonNullMatchingComponent(Factory factory) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in A type argument E: found @Nullable String, required String A result = factory.fromA().get(); } @@ -45,7 +45,7 @@ void acceptsOtherNonNullComponent(Factory factory) { } void rejectsWideningOtherInvariantComponent(Factory factory) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in B type argument E: a type argument must match exactly; found String, required @Nullable String B<@Nullable String> result = factory.fromA().get(); } @@ -54,7 +54,7 @@ void acceptsMatchingNonNullComponent(Factory factory) { } void rejectsWideningMatchingInvariantComponent(Factory factory) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in B type argument E: a type argument must match exactly; found String, required @Nullable String B<@Nullable String> result = factory.fromB().get(); } } 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 7fc6cb6e78..3304ec7291 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 nullability: found @Nullable Test, required Test + // BUG: Diagnostic contains: incompatible nullability in array element: 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 nullability: found @Nullable Test, required Test + // BUG: Diagnostic contains: incompatible nullability in array element: 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 nullability: found @Nullable Test, required Test + // BUG: Diagnostic contains: incompatible nullability in array element: 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 nullability: found @Nullable Integer, required Integer + // BUG: Diagnostic contains: incompatible nullability in array element: 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 nullability: found @Nullable Integer, required Integer + // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable Integer, required Integer x1 = new @Nullable Integer[0]; } } @@ -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 nullability: found @Nullable Integer, required Integer + // BUG: Diagnostic contains: incompatible nullability in array element -> array element: 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 nullability: found @Nullable Integer, required Integer + // BUG: Diagnostic contains: incompatible nullability in array element: 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 nullability: a type argument must match exactly; found @Nullable Integer [], required Integer @Nullable [] + // BUG: Diagnostic contains: incompatible nullability in array element -> array element: found @Nullable Integer, required Integer Integer[] @Nullable [] y4 = new @Nullable Integer[3][4]; - // BUG: Diagnostic contains: incompatible nullability: found @Nullable Integer, required Integer + // BUG: Diagnostic contains: incompatible nullability in array element -> array element: found @Nullable Integer, required Integer Integer[][] y1 = nullableElems2D; - // BUG: Diagnostic contains: incompatible nullability: found @Nullable Integer, required Integer + // BUG: Diagnostic contains: incompatible nullability in array element -> array element -> array element: found @Nullable Integer, required Integer Integer[][][] y2 = nullableElems3D; - // BUG: Diagnostic contains: incompatible nullability: found Integer @Nullable [], required Integer [] + // BUG: Diagnostic contains: incompatible nullability in array element: found Integer @Nullable [], required Integer [] Integer[][] y3 = nullableInner; } } @@ -673,7 +673,7 @@ public void arraysAndGenerics() { class Test { void foo(List<@Nullable Integer[]> l) {} void testPositive(List p) { - // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Integer, required @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in List type argument E -> array element: 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 nullability: found @Nullable Foo, required Foo + // BUG: Diagnostic contains: incompatible nullability in array element: 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 nullability: found @Nullable Foo, required Foo + // BUG: Diagnostic contains: incompatible nullability in array element: 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 nullability: found @Nullable Foo, required Foo + // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable Foo, required Foo takeFoosVarargs(p); - // BUG: Diagnostic contains: incompatible nullability: found @Nullable Foo, required Foo + // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable Foo, required Foo takeFoosVarargs(p2, p); } void callTakeFoosVarargsNegative(Foo[] p) { @@ -1390,7 +1390,7 @@ static void nullableExplicitArrayStore() { static void nullableTypeArgumentRejectedFromNonNullBoundedWildcardArray( CompletableFuture[] futures, CompletableFuture<@Nullable String> value) { - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in CompletableFuture type argument T -> wildcard upper bound: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in List type argument E: 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 a2b9c79b1e..f12d87fe59 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 nullability: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in List type argument E: found @Nullable Object, required Object PolyNullMethods.first(nullable, nullable); } } 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 8bc51c1f1a..d522e81b4c 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in NullableSibling type argument Y: found @Nullable String, required String NullableSibling x = nullableSibling(); } void siblingWithNullableNonObjectBound() { 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 5b47f86248..4b93d68e2a 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in List type argument E: 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in List type argument E: found @Nullable String, required String .toList(); } } 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 1cc46f8fc1..21d3c8ea34 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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Box type argument T: 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 2cb5f0add5..b8b9fa58d2 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -319,7 +319,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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: found @Nullable String, required String String s = nonnullWildcard(f); // legal String s2 = nonnullWildcard(f2); @@ -348,7 +348,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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: found @Nullable String, required String String s = nonnullWildcard(f); s.hashCode(); } @@ -379,7 +379,7 @@ void testNegative(Foo> f) { s.hashCode(); } void testPositive(Foo> f) { - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound -> Bar type argument T: found @Nullable String, required String String s = nonnullWildcard(f); s.hashCode(); } @@ -411,7 +411,7 @@ void testNegative(Foo>> f) { s.hashCode(); } void testPositive(Foo>> f) { - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound -> Bar type argument T -> Baz type argument T: found @Nullable String, required String String s = nonnullWildcard(f); s.hashCode(); } @@ -443,7 +443,7 @@ void testNegative(Foo<@Nullable Bar>> f) { s.hashCode(); } void testPositive(Foo<@Nullable Bar>> f) { - // BUG: Diagnostic contains: incompatible nullability: found Test.@Nullable Bar>, required Test.Bar> + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: found Test.@Nullable Bar>, required Test.Bar> String s = nonnullWildcard(f); s.hashCode(); } @@ -473,7 +473,7 @@ void testNegative(Foo f) { s.hashCode(); } void testPositive(Foo f) { - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: found @Nullable String, required String String s = nonnullWildcard(f); s.hashCode(); } @@ -496,22 +496,22 @@ class Foo {} Foo nullableField; Test(Foo f) { nullableField = f; - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: found @Nullable String, required String nonnullField = f; } Foo nullableReturn(Foo f) { return f; } Foo nonnullReturn(Foo f) { - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: found @Nullable String, required String return f; } void testLocal(Foo f) { Foo ok = f; - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: found @Nullable String, required String Foo bad = f; var f2 = f; - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: found @Nullable String, required String Foo bad2 = f2; } } @@ -538,10 +538,10 @@ void testLocals( Foo nonnullSuperLocal = nullableObjectFoo; Foo nullableSuperLocal = nullableObjectFoo; Foo nullableSuperLocal2 = nullableStringFoo; - // BUG: Diagnostic contains: incompatible types: Test.Foo cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard lower bound: found Object, required a supertype of @Nullable String Foo nullableSuperLocal3 = objectFoo; Foo nonnullSuperFromNullableSuper = nullableSuperFoo; - // BUG: Diagnostic contains: incompatible types: Test.Foo cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard lower bound: found String, required a supertype of @Nullable String Foo nullableSuperFromNonnullSuper = nonnullSuperFoo; } } @@ -566,11 +566,11 @@ void testLocals( Foo fromNonnullSuper = nonnullSuperFoo; Foo fromNullableSuper = nullableSuperFoo; Foo fromUnbounded = unboundedFoo; - // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: found @Nullable Object, required Object Foo badFromNonnullSuper = nonnullSuperFoo; - // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: found @Nullable Object, required Object Foo badFromNullableSuper = nullableSuperFoo; - // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: found @Nullable Object, required Object Foo badFromUnbounded = unboundedFoo; } } @@ -595,7 +595,7 @@ void testLocals( NonNullBoundFoo nonnullSuperStringFoo) { NonNullBoundFoo fromNonnull = nonnullObjectFoo; NonNullBoundFoo fromNonnullExtends = nonnullExtendsObjectFoo; - // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in NonNullBoundFoo type argument T -> wildcard upper bound: found @Nullable Object, required Object NonNullBoundFoo fromNullableExtends = nullableExtendsObjectWithNonnullBoundFoo; NonNullBoundFoo fromSuper = nonnullSuperStringFoo; } @@ -621,13 +621,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 nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Pair type argument U -> wildcard upper bound: found @Nullable String, required String Pair<@Nullable String, ? extends String> invalid = pair; } static void capturedFirstArgument(Pair pair) { Pair target = pair; - // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in Pair type argument U -> wildcard upper bound: found @Nullable Object, required Object Pair invalid = pair; } @@ -636,7 +636,7 @@ static class UnmarkedPair {} static void capturedFirstArgumentFromUnmarkedCode(UnmarkedPair pair) { UnmarkedPair target = pair; - // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in UnmarkedPair type argument U -> wildcard upper bound: found @Nullable Object, required Object UnmarkedPair invalid = pair; } } @@ -754,7 +754,7 @@ T get() { } } static void test(Holder> holder) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in Box type argument T: found @Nullable String, required String Box box = holder.get(); } } @@ -880,7 +880,7 @@ static void nullable(NullableHolder holder) { // BUG: Diagnostic contains: dereferenced expression 'box.get()' is @Nullable box.get().length(); Box<@Nullable String> compatible = holder.nonNullValue(); - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in Box type argument E: found @Nullable String, required String Box incompatible = holder.nonNullValue(); // BUG: Diagnostic contains: dereferenced expression 'holder.value()' is @Nullable holder.value().hashCode(); @@ -915,18 +915,18 @@ Nested self() { } Nested testDirect(Nested receiver) { - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: found @Nullable String, required String return receiver.wildcardUpperTypeVariable(); } Nested testWithSelf(Nested receiver) { - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: found @Nullable String, required String return receiver.self().wildcardUpperTypeVariable(); } Nested testWithVar(Nested receiver) { var local = receiver; - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: found @Nullable String, required String return local.wildcardUpperTypeVariable(); } @@ -960,18 +960,18 @@ Nested self() { } Nested testDirect(Nested receiver) { - // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: found @Nullable Object, required Object return receiver.wildcardUpperTypeVariable(); } Nested testWithSelf(Nested receiver) { - // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: found @Nullable Object, required Object return receiver.self().wildcardUpperTypeVariable(); } Nested testWithVar(Nested receiver) { var local = receiver; - // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: found @Nullable Object, required Object return local.wildcardUpperTypeVariable(); } @@ -1038,7 +1038,7 @@ interface NullableI2< } NullableI1 incompatible(NullableI2 i2) { var i2var = i2; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in NullableI1 type argument X: found @Nullable Object, required Object return i2var.get(); } } @@ -1479,7 +1479,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 nullability: a type argument must match exactly; found Void, required @Nullable Void + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: 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 @@ -1532,7 +1532,7 @@ void test( Box nonNullBoundBox, Box nullableBoundBox) { Box ok = identity(nullableBoundBox); - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in Box type argument T -> wildcard lower bound: found String, required a supertype of @Nullable String Box bad = identity(nonNullBoundBox); } } @@ -1556,7 +1556,7 @@ interface Nested {} return box; } void test(Box> box) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in Box type argument T -> wildcard lower bound -> Nested type argument T: a type argument must match exactly; found String, required @Nullable String Box> bad = identity(box); } } @@ -2079,7 +2079,7 @@ static void nullableSuperBounded(NullableNode node) { } static void superBoundedNullableElements(ListNode> node) { - // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in List type argument E: found @Nullable String, required String takesList(node.get()); } } 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 index 62a78be896..766de2c221 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java @@ -4,7 +4,8 @@ /** * A caret marks, in both printed types, the smallest node that differs in nullness, and no node the - * target accepts as it is. + * target accepts as it is. Differences below one printed node, such as a {@code ?} whose implicit + * bound holds two of them, share its caret, which is numbered for each. */ public class CaretTests extends MismatchMessageTestBase { @@ -12,12 +13,11 @@ public class CaretTests extends MismatchMessageTestBase { public void onlyTheInnermostDifferingNodeIsMarkedInsideAWildcardBound() { assertMessage( """ - incompatible nullability: found @Nullable String, required String + incompatible nullability in List type argument E -> wildcard upper bound -> List type argument E: 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) {} @@ -32,12 +32,11 @@ void test(List> l) { public void caretSkipsATypeArgumentTheTargetAccepts() { assertMessage( """ - incompatible nullability: found @Nullable Object, required Object + incompatible nullability in Map type argument V -> wildcard upper bound: found @Nullable Object, required Object found: Map ^^^^^^^^^^^^^^^^ required: Map ^^^^^^ - path: Map type argument V -> wildcard upper bound """, """ static void take(Map m) {} @@ -55,12 +54,11 @@ void test(Map m) { public void caretNamesTheConcreteArgumentWhenEveryWildcardIsAccepted() { assertMessage( """ - incompatible nullability: found @Nullable String, required String + incompatible nullability in Map type argument V: found @Nullable String, required String found: Map ^^^^^^^^^^^^^^^^ required: Map ^^^^^^ - path: Map type argument V """, """ static void take(Map m) {} @@ -78,12 +76,11 @@ void test(Map m) { public void caretMarksTheFailingArgumentWhereTheTargetRepeatsAType() { assertMessage( """ - incompatible nullability: found @Nullable String, required String + incompatible nullability in Three type argument C: found @Nullable String, required String found: Three ^^^^^^^^^^^^^^^^ required: Three ^^^^^^ - path: Three type argument C """, """ static class Three {} @@ -99,12 +96,11 @@ void test(Three t) { public void onlyTheFailingArgumentIsNamedBesideAWildcardTheTargetAccepts() { assertMessage( """ - incompatible nullability: found @Nullable String, required String + incompatible nullability in Three type argument C: found @Nullable String, required String found: Three ^^^^^^^^^^^^^^^^ required: Three ^^^^^^ - path: Three type argument C """, """ static class Three {} @@ -120,7 +116,7 @@ void test(Three t) { public void bothPositionsAreMarkedWhereOneInstanceFillsTwoTypeArguments() { assertMessage( """ - incompatible nullability: 2 mismatches between source and target types + incompatible nullability in Map type argument K -> wildcard upper bound and 1 other position: found @Nullable Object, required Object found: Map ^^^^^^^^^^^^ ^^^^^^^^^^^^ 1 2 @@ -154,12 +150,11 @@ void test(List l) { public void aMismatchInsideAnArrayElementTypeArgumentIsMarked() { assertMessage( """ - incompatible nullability: found @Nullable String, required String + incompatible nullability in array element -> List type argument E: found @Nullable String, required String found: List<@Nullable String> [] ^^^^^^^^^^^^^^^^ required: List [] ^^^^^^ - path: array element -> List type argument E """, """ static void take(List[] l) {} @@ -174,12 +169,11 @@ void test(List<@Nullable String>[] l) { public void aNullableArrayComponentTypeIsMarkedInsideATypeArgument() { assertMessage( """ - incompatible nullability: found @Nullable String, required String + incompatible nullability in List type argument E -> array element: found @Nullable String, required String found: List<@Nullable String []> ^^^^^^^^^^^^^^^^ required: List ^^^^^^ - path: List type argument E -> array element """, """ static void take(List l) {} @@ -194,12 +188,11 @@ void test(List<@Nullable String[]> l) { public void aNullableArrayTypeIsMarkedInsideATypeArgument() { assertMessage( """ - incompatible nullability: found String @Nullable [], required String [] + incompatible nullability in List type argument E: found String @Nullable [], required String [] found: List ^^^^^^^^^^^^^^^^^^^ required: List ^^^^^^^^^ - path: List type argument E """, """ static void take(List l) {} @@ -209,4 +202,68 @@ void test(List l) { } """); } + + @Test + public void twoMismatchesUnderOneWildcardShareItsCaret() { + assertMessage( + """ + incompatible nullability in Foo type argument T -> wildcard upper bound -> Map type argument K and 1 other position: found @Nullable String, required String + found: Foo + ^ + 1,2 + required: Foo> + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: Foo type argument T -> wildcard upper bound -> Map type argument K + found: @Nullable String + required: String + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Foo + \s + 2. path: Foo type argument T -> wildcard upper bound -> Map type argument V + found: @Nullable String + required: String + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Foo + """, + """ + static class Foo> {} + static void take(Foo> f) {} + void test(Foo f) { + // BUG: Diagnostic matches: MESSAGE + take(f); + } + """); + } + + @Test + public void twoMismatchesUnderOneNestedWildcardShareItsCaret() { + assertMessage( + """ + incompatible nullability in List type argument E -> wildcard upper bound -> Foo type argument T -> wildcard upper bound -> Map type argument K and 1 other position: found @Nullable String, required String + found: List> + ^ + 1,2 + required: List>> + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: List type argument E -> wildcard upper bound -> Foo type argument T -> wildcard upper bound -> Map type argument K + found: @Nullable String + required: String + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Foo + \s + 2. path: List type argument E -> wildcard upper bound -> Foo type argument T -> wildcard upper bound -> Map type argument V + found: @Nullable String + required: String + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Foo + """, + """ + static class Foo> {} + static void take(List>> f) {} + void test(List> f) { + // BUG: Diagnostic matches: MESSAGE + take(f); + } + """); + } } 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 deleted file mode 100644 index 673fc09bb9..0000000000 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FallbackMessageTests.java +++ /dev/null @@ -1,63 +0,0 @@ -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/FixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java new file mode 100644 index 0000000000..a1983a7e4c --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java @@ -0,0 +1,175 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import com.google.common.collect.ImmutableList; +import com.google.errorprone.BugCheckerRefactoringTestHelper; +import com.uber.nullaway.NullAway; +import com.uber.nullaway.generics.JSpecifyJavacConfig; +import java.io.IOException; +import java.util.List; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +/** + * A {@code fix:} line comes with an Error Prone fix that rewrites the type the named declaration + * writes, where that declaration is in the compilation unit being analyzed and writes its type out. + */ +public class FixTests { + + @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + private BugCheckerRefactoringTestHelper makeHelper() { + return BugCheckerRefactoringTestHelper.newInstance(NullAway.class, getClass()) + .setArgs( + ImmutableList.copyOf( + JSpecifyJavacConfig.withJSpecifyModeArgs( + List.of( + "-d", + temporaryFolder.getRoot().getAbsolutePath(), + "-XepOpt:NullAway:OnlyNullMarked=true")))); + } + + @Test + public void theRequiredTypeFixImportsTheNullableAnnotationItAdds() throws IOException { + makeHelper() + .addInputLines( + "Lib.java", + """ + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Lib { + static List<@Nullable String> get() { + throw new RuntimeException(); + } + } + """) + .expectUnchanged() + .addInputLines( + "Test.java", + """ + import java.util.List; + import org.jspecify.annotations.NullMarked; + @NullMarked + class Test { + void test() { + List l = Lib.get(); + l.hashCode(); + } + } + """) + .addOutputLines( + "Test.java", + """ + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + void test() { + List<@Nullable String> l = Lib.get(); + l.hashCode(); + } + } + """) + .doTest(); + } + + @Test + public void theSourceFixKeepsANullableAnnotationWrittenAmongTheModifiers() throws IOException { + makeHelper() + .addInputLines( + "Test.java", + """ + import java.util.Collection; + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static void take(Collection c) {} + void test(@Nullable List l) { + if (l != null) { + take(l); + } + } + } + """) + .addOutputLines( + "Test.java", + """ + import java.util.Collection; + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static void take(Collection c) {} + void test(@Nullable List l) { + if (l != null) { + take(l); + } + } + } + """) + .doTest(); + } + + @Test + public void noEditForADeclarationInAnotherCompilationUnit() throws IOException { + makeHelper() + .addInputLines( + "Lib.java", + """ + import java.util.ArrayList; + import java.util.List; + import org.jspecify.annotations.NullMarked; + @NullMarked + class Lib { + static List field = new ArrayList<>(); + } + """) + .expectUnchanged() + .addInputLines( + "Test.java", + """ + import java.util.Collection; + import org.jspecify.annotations.NullMarked; + @NullMarked + class Test { + static void take(Collection c) {} + void test() { + take(Lib.field); + } + } + """) + .expectUnchanged() + .doTest(); + } + + @Test + public void noEditForADeclarationWithAnInferredType() throws IOException { + makeHelper() + .addInputLines( + "Test.java", + """ + import java.util.Collection; + import java.util.List; + import org.jspecify.annotations.NullMarked; + @NullMarked + class Test { + static void take(Collection c) {} + static List make() { + throw new RuntimeException(); + } + void test() { + var l = make(); + take(l); + } + } + """) + .expectUnchanged() + .doTest(); + } +} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java new file mode 100644 index 0000000000..268b646c64 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java @@ -0,0 +1,76 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import org.junit.Test; + +/** + * A difference in a {@code ? super} bound is located like any other, and the required side reads as + * {@code a supertype of} the bound the target states. A raw source has no type arguments to compare + * and draws no message at all, and neither does an array of a raw target type. + */ +public class LowerBoundAndRawSourceTests extends MismatchMessageTestBase { + + @Test + public void aLowerBoundDifferenceIsMarkedInBothTypes() { + assertMessage( + """ + incompatible nullability in List type argument E -> wildcard lower bound: found String, required a supertype of @Nullable String + found: List + ^^^^^^ + required: 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 aLowerBoundDifferenceIsMarkedAcrossASupertypeView() { + assertMessage( + """ + incompatible nullability in Base type argument T -> wildcard lower bound: found String, required a supertype of @Nullable String + found: Sub + ^^^^^^ + required: 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 aRawTypeOnEitherSideIsAcceptedWithNoMismatchToReport() { + makeHelper() + .addSourceLines( + "Test.java", + nullMarkedClass( + """ + @SuppressWarnings("rawtypes") + void rawSource(List raw) { + List typed = raw; + typed.hashCode(); + } + @SuppressWarnings("rawtypes") + void rawArrayTarget(List<@Nullable String>[] typed) { + List[] raw = typed; + raw.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 index 4374e52696..cecd6f9da0 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/MismatchMessageTestBase.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/MismatchMessageTestBase.java @@ -4,15 +4,17 @@ import com.uber.nullaway.NullAwayTestsBase; import com.uber.nullaway.generics.JSpecifyJavacConfig; import java.util.List; +import java.util.Map; import java.util.function.Predicate; +import java.util.regex.Pattern; /** * 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. + * not carry, such as a {@code fix:} line. A failure prints the expected message beside every + * diagnostic the compilation reported. */ abstract class MismatchMessageTestBase extends NullAwayTestsBase { @@ -41,6 +43,17 @@ void assertMessage(String expected, String members) { .doTest(); } + /** + * Compiles {@code members} as the body of {@code @NullMarked class Test} and expects, for each + * key of {@code expectedByKey}, the line after {@code // BUG: Diagnostic matches: KEY} to report + * exactly the message mapped to that key. {@link #assertMessage} documents the rest. + */ + void assertMessages(Map expectedByKey, String members) { + CompilationTestHelper helper = makeHelper(); + expectedByKey.forEach((key, expected) -> helper.expectErrorMessage(key, messageIs(expected))); + helper.addSourceLines("Test.java", nullMarkedClass(members)).doTest(); + } + /** * Returns the source of {@code @NullMarked class Test} with the given body and the imports {@link * #assertMessage} documents. @@ -69,15 +82,19 @@ static Predicate messageIs(String 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. + * marked line matches it, so {@link #toString} is the expected message. The {@code Did you mean} + * line Error Prone appends for an attached fix is not part of the message, and {@link FixTests} + * checks the fixes. */ 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 )"; + private static final Pattern FIX_LINE = Pattern.compile("\n Did you mean '.*'\\?$"); @Override - public boolean test(String message) { + public boolean test(String diagnostic) { + String message = FIX_LINE.matcher(diagnostic).replaceFirst(""); if (!message.startsWith(PREFIX) || !message.endsWith(LINK_LINE)) { return false; } 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..011d74eb99 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 @@ -16,15 +16,13 @@ public class NoteTests extends MismatchMessageTestBase { public void anUnboundedWildcardNamesTheTypeParameterItsBoundIsInheritedFrom() { assertMessage( """ - incompatible nullability: found @Nullable Object, required Object + incompatible nullability in Collection type argument E -> wildcard upper bound: 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? + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List + fix: declare list as List """, """ Collection copy(List list) { @@ -49,14 +47,12 @@ void nullableTarget(List list) { public void aSuperBoundedWildcardNamesTheTypeParameterItsUpperBoundIsInheritedFrom() { assertMessage( """ - incompatible nullability: found @Nullable Object, required Object + incompatible nullability in Collection type argument E -> wildcard upper bound: 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 + 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) {} @@ -71,12 +67,11 @@ void test(List list) { public void anExplicitlyWrittenNullableBoundDrawsNoInheritedBoundNote() { assertMessage( """ - incompatible nullability: found @Nullable String, required String + incompatible nullability in List type argument E -> wildcard upper bound: found @Nullable String, required String found: List ^^^^^^^^^^^^^^^^ required: List ^^^^^^ - path: List type argument E -> wildcard upper bound """, """ static void take(List l) {} @@ -91,12 +86,11 @@ void test(List l) { public void noInheritedBoundNoteWhereTheUseStatesItsOwnNullness() { assertMessage( """ - incompatible nullability: found @Nullable T, required Object + incompatible nullability in Box type argument T -> wildcard upper bound: found @Nullable T, required Object found: Box<@Nullable T> ^^^^^^^^^^^ required: Box ^^^^^^ - path: Box type argument T -> wildcard upper bound """, """ static class Box {} @@ -110,4 +104,88 @@ static void test(Box<@Nullable T> b) { } """); } + + @Test + public void aWildcardWhoseImplicitBoundHoldsTheMismatchNamesItsTypeParameter() { + assertMessage( + """ + incompatible nullability in Foo type argument T -> wildcard upper bound -> List type argument E: found @Nullable String, required String + found: Foo + ^ + required: Foo> + ^^^^^^ + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Foo + """, + """ + static class Foo> {} + static void take(Foo> f) {} + void test(Foo f) { + // BUG: Diagnostic matches: MESSAGE + take(f); + } + """); + } + + @Test + public void aNestedWildcardWhoseImplicitBoundHoldsTheMismatchNamesItsTypeParameter() { + assertMessage( + """ + incompatible nullability in List type argument E -> wildcard upper bound -> Foo type argument T -> wildcard upper bound -> List type argument E: found @Nullable String, required String + found: List> + ^ + required: List>> + ^^^^^^ + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Foo + """, + """ + static class Foo> {} + static void take(List>> f) {} + void test(List> f) { + // BUG: Diagnostic matches: MESSAGE + take(f); + } + """); + } + + @Test + public void aWildcardInsideAWildcardBoundNamesItsTypeParameter() { + assertMessage( + """ + incompatible nullability in List type argument E -> wildcard upper bound -> List type argument E -> wildcard upper bound: found @Nullable Object, required Object + found: List> + ^ + required: List> + ^^^^^^ + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List + fix: declare l as List> + """, + """ + static void take(List> l) {} + void test(List> l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void aWildcardInsideAnArrayInsideAWildcardBoundNamesItsTypeParameter() { + assertMessage( + """ + incompatible nullability in List type argument E -> wildcard upper bound -> array element -> List type argument E -> wildcard upper bound: found @Nullable Object, required Object + found: List []> + ^ + required: List []> + ^^^^^^ + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List + fix: declare l as List []> + """, + """ + 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/PathTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java index 071bed2e08..065333eb4a 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java @@ -3,9 +3,11 @@ 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. + * A {@code path:} line, and the first line of the message, name 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. The position is the one the check + * rejects, so a nullable root or array is compared below its own nullness, and a captured source + * through its upper bound. */ public class PathTests extends MismatchMessageTestBase { @@ -13,12 +15,11 @@ public class PathTests extends MismatchMessageTestBase { public void pathNamesTheTypeParameterTheDeclarationDeclared() { assertMessage( """ - incompatible nullability: found @Nullable String, required String + incompatible nullability in Result type argument Failure: found @Nullable String, required String found: Result ^^^^^^^^^^^^^^^^ required: Result ^^^^^^ - path: Result type argument Failure """, """ static class Result {} @@ -34,12 +35,11 @@ void test(Result r) { public void pathRepeatsTheTypeParameterNameAtEveryLevelThatSharesIt() { assertMessage( """ - incompatible nullability: found @Nullable String, required String + incompatible nullability in List type argument E -> Collection type argument E -> List type argument E: 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) {} @@ -54,12 +54,11 @@ void test(List>> l) { public void pathKeepsTheEnclosingTypeApartFromTheInnerType() { assertMessage( """ - incompatible nullability: found @Nullable Integer, required Integer + incompatible nullability in Inner type argument U: found @Nullable Integer, required Integer found: Outer.Inner<@Nullable Integer> ^^^^^^^^^^^^^^^^^ required: Outer.Inner ^^^^^^^ - path: Inner type argument U """, """ static class Outer { @@ -77,7 +76,7 @@ void test(Outer.Inner<@Nullable Integer> i) { public void twoMismatchesInsideOneTypeArgumentSharePathPrefix() { assertMessage( """ - incompatible nullability: 2 mismatches between source and target types + incompatible nullability in Map type argument V -> Map type argument K and 1 other position: found @Nullable String, required String found: Map> ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^ 1 2 @@ -106,7 +105,7 @@ void test(Map> m) { public void mismatchesAtDifferentDepthsEachGetTheirOwnPath() { assertMessage( """ - incompatible nullability: 2 mismatches between source and target types + incompatible nullability in Map type argument K and 1 other position: found @Nullable String, required String found: Map<@Nullable String, List>> ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^ 1 2 @@ -118,8 +117,7 @@ public void mismatchesAtDifferentDepthsEachGetTheirOwnPath() { found: @Nullable String required: String \s - 2. path: Map type argument V -> List type argument E -> wildcard upper bound - -> Collection type argument E + 2. path: Map type argument V -> List type argument E -> wildcard upper bound -> Collection type argument E found: @Nullable Integer required: Integer """, @@ -132,4 +130,177 @@ void test( } """); } + + @Test + public void pathReachesATypeArgumentOfAnArrayElement() { + assertMessage( + """ + incompatible nullability in array element -> List type argument E: a type argument must match exactly; found String, required @Nullable String + found: List [] + ^^^^^^ + required: @Nullable List<@Nullable String> [] + ^^^^^^^^^^^^^^^^ + """, + """ + void test(List[] arr) { + // BUG: Diagnostic matches: MESSAGE + @Nullable List<@Nullable String>[] x = arr; + } + """); + } + + @Test + public void pathDescendsIntoEveryDimensionOfANestedArray() { + assertMessage( + """ + incompatible nullability in array element -> array element: found @Nullable Integer, required Integer + found: @Nullable Integer [] [] + ^^^^^^^^^^^^^^^^^ + required: Integer @Nullable [] [] + ^^^^^^^ + """, + """ + void test(@Nullable Integer[][] src) { + // BUG: Diagnostic matches: MESSAGE + Integer[] @Nullable [] t = src; + } + """); + } + + @Test + public void pathDescendsIntoEveryDimensionOfAThreeDimensionalArray() { + assertMessage( + """ + incompatible nullability in array element -> array element -> array element: found @Nullable Integer, required Integer + found: @Nullable Integer [] [] [] + ^^^^^^^^^^^^^^^^^ + required: Integer @Nullable [] [] [] + ^^^^^^^ + """, + """ + void test(@Nullable Integer[][][] src3) { + // BUG: Diagnostic matches: MESSAGE + Integer[][] @Nullable [] t = src3; + } + """); + } + + @Test + public void aNullableSourceIsComparedBelowItsOwnNullness() { + assertMessage( + """ + incompatible nullability in Collection type argument E -> wildcard upper bound: found @Nullable Object, required Object + found: @Nullable List + ^ + required: Collection + ^^^^^^ + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List + fix: declare l as @Nullable List + """, + """ + static void take(Collection c) {} + void test(@Nullable List l) { + if (l != null) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + } + """); + } + + @Test + public void aNullableTargetIsComparedBelowItsOwnNullness() { + assertMessage( + """ + incompatible nullability in List type argument E: found @Nullable String, required String + found: List<@Nullable String> + ^^^^^^^^^^^^^^^^ + required: @Nullable List + ^^^^^^ + """, + """ + static void param(@Nullable List l) {} + void test(List<@Nullable String> x) { + // BUG: Diagnostic matches: MESSAGE + param(x); + } + """); + } + + @Test + public void pathNamesOnlyTheTypeArgumentTheCheckRejects() { + assertMessage( + """ + incompatible nullability in Pair type argument A: found @Nullable String, required String + found: Pair<@Nullable String, Integer []> + ^^^^^^^^^^^^^^^^ + required: Pair + ^^^^^^ + """, + """ + static class Pair {} + static void take(Pair p) {} + void test(Pair<@Nullable String, Integer[]> p) { + // BUG: Diagnostic matches: MESSAGE + take(p); + } + """); + } + + @Test + public void aCapturedSourceIsComparedThroughItsUpperBound() { + assertMessage( + """ + incompatible nullability in List type argument E: found @Nullable String, required String + found: capture of ? extends List<@Nullable String> + ^^^^^^^^^^^^^^^^ + required: List + ^^^^^^ + fix: declare l as List<@Nullable String> + """, + """ + void test(List> wl) { + // BUG: Diagnostic matches: MESSAGE + List l = wl.get(0); + } + """); + } + + @Test + public void aCapturedArgumentIsComparedThroughItsUpperBound() { + assertMessage( + """ + incompatible nullability in List type argument E: found @Nullable String, required String + found: List<@Nullable String> + ^^^^^^^^^^^^^^^^ + required: List + ^^^^^^ + """, + """ + static void take(List l) {} + void test(List> wl) { + // BUG: Diagnostic matches: MESSAGE + take(wl.get(0)); + } + """); + } + + @Test + public void pathCrossesAWildcardLowerBound() { + assertMessage( + """ + incompatible nullability in List type argument E -> wildcard lower bound -> List type argument E -> wildcard upper bound: found Object, required a supertype of @Nullable Object + found: List> + ^^^^^^ + required: List> + ^ + """, + """ + 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/RequiredTypeFixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeFixTests.java new file mode 100644 index 0000000000..b210ea78e1 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeFixTests.java @@ -0,0 +1,204 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import java.util.Map; +import org.junit.Test; + +/** + * A {@code fix:} line that names the variable a declaration declares 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. {@link FixTests} checks the edit the fix makes. + */ +public class RequiredTypeFixTests extends MismatchMessageTestBase { + + private static final String MAP_VALUES_MESSAGE = + """ + incompatible nullability in Map type argument V: found @Nullable String, required String + found: Map + ^^^^^^^^^^^^^^^^ + required: Map + ^^^^^^ + """; + + @Test + public void theFixIsOfferedOnlyWhereTheDiagnosticPointsAtTheRequiredTypeDeclaration() { + assertMessages( + Map.of( + "DECLARATION", + MAP_VALUES_MESSAGE + + " fix: declare declared as Map\n", + "CALL", + MAP_VALUES_MESSAGE, + "ASSIGNMENT", + MAP_VALUES_MESSAGE, + "RETURN", + MAP_VALUES_MESSAGE), + """ + static void take(Map m) {} + void fixedTypeIsAccepted(Map m) { + Map fixed = m; + } + void declaration(Map m) { + // BUG: Diagnostic matches: DECLARATION + Map declared = m; + declared.hashCode(); + } + void call(Map m) { + // BUG: Diagnostic matches: CALL + take(m); + } + void assignment(Map m, Map existing) { + // BUG: Diagnostic matches: ASSIGNMENT + existing = m; + existing.hashCode(); + } + Map returned(Map m) { + // BUG: Diagnostic matches: RETURN + return m; + } + """); + } + + @Test + public void theFixIsTheDeclaredTypeNotAnInstantiatedSupertype() { + assertMessage( + """ + incompatible nullability in List type argument E: found @Nullable String, required String + found: Sub<@Nullable String> + ^^^^^^^^^^^^^^^^ + required: List + ^^^^^^ + fix: declare l as 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 theFixReplacesTheNodeAtEveryKindOfStep() { + assertMessages( + Map.of( + "WILDCARD_BOUND", + """ + incompatible nullability in Collection type argument E -> wildcard upper bound: found @Nullable Object, required Object + found: List + ^ + required: Collection + ^^^^^^ + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List + fix: declare list as List + fix: declare c as Collection + """, + "ARRAY_ELEMENT", + """ + incompatible nullability in array element -> List type argument E: found @Nullable String, required String + found: List<@Nullable String> [] + ^^^^^^^^^^^^^^^^ + required: List [] + ^^^^^^ + fix: declare d as List<@Nullable String> [] + """, + "ENCLOSING_TYPE", + """ + incompatible nullability in enclosing type -> Outer type argument T: found @Nullable String, required String + found: Outer<@Nullable String>.Inner + ^^^^^^^^^^^^^^^^ + required: Outer.Inner + ^^^^^^ + fix: declare d as Outer<@Nullable String>.Inner + """), + """ + static class Outer { + class Inner {} + } + void wildcardBound(List list) { + // BUG: Diagnostic matches: WILDCARD_BOUND + Collection c = list; + c.hashCode(); + } + void arrayElement(List<@Nullable String>[] src) { + // BUG: Diagnostic matches: ARRAY_ELEMENT + List[] d = src; + d.hashCode(); + } + void enclosingType(Outer<@Nullable String>.Inner src) { + // BUG: Diagnostic matches: ENCLOSING_TYPE + Outer.Inner d = src; + d.hashCode(); + } + """); + } + + // The printer drops @Tainted from the printed types, so TAINTED and TAINTED_BOUND differ from + // PLAIN and a message with a fix only by the missing fix line. + @Test + public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { + assertMessages( + Map.of( + "PLAIN", + """ + incompatible nullability in Map type argument V: found @Nullable String, required String + found: Map + ^^^^^^^^^^^^^^^^ + required: Map + ^^^^^^ + fix: declare plain as Map + """, + "TAINTED", + """ + incompatible nullability in Map type argument V: found @Nullable String, required String + found: Map + ^^^^^^^^^^^^^^^^ + required: Map + ^^^^^^ + """, + "TAINTED_BOUND", + """ + incompatible nullability in Map type argument V: found @Nullable String, required String + found: Map + ^^^^^^^^^^^^^^^^ + required: Map + ^^^^^^ + """, + "TYPE_VARIABLE", + """ + incompatible nullability in Map type argument V: found @Nullable String, required String + found: Map + ^^^^^^^^^^^^^^^^ + required: Map + ^^^^^^ + fix: declare d as Map + """), + """ + @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) + @interface Tainted {} + void plain(Map m) { + // BUG: Diagnostic matches: PLAIN + Map plain = m; + plain.hashCode(); + } + void tainted(Map<@Tainted String, @Nullable String> m) { + // BUG: Diagnostic matches: TAINTED + Map<@Tainted String, String> d = m; + d.hashCode(); + } + void taintedBound(Map m) { + // BUG: Diagnostic matches: TAINTED_BOUND + Map d = m; + d.hashCode(); + } + static void typeVariable(Map m) { + // BUG: Diagnostic matches: TYPE_VARIABLE + Map d = m; + d.hashCode(); + } + """); + } +} 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 deleted file mode 100644 index 430bfa9ae3..0000000000 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeRepairTests.java +++ /dev/null @@ -1,170 +0,0 @@ -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> - ^^^^^^^^^^^^^^^^ - 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 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( - """ - 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/SourceFixTests.java similarity index 54% rename from nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceRepairTests.java rename to nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java index 67d0bde26c..b362627744 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceRepairTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java @@ -1,19 +1,21 @@ package com.uber.nullaway.jspecify.mismatchmessage; +import java.util.Map; 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. + * A {@code fix:} line that names the variable the source reads offers the source type rewritten + * with explicit wildcard upper bounds. It appears only where the rewritten type removes every + * difference and prints without losing a type-use annotation. {@link FixTests} checks the edit the + * fix makes. */ -public class SourceRepairTests extends MismatchMessageTestBase { +public class SourceFixTests extends MismatchMessageTestBase { @Test - public void suggestionRewritesEveryMismatchingWildcard() { + public void theFixRewritesEveryMismatchingWildcard() { assertMessage( """ - incompatible nullability: 2 mismatches between source and target types + incompatible nullability in Map type argument K -> wildcard upper bound and 1 other position: found @Nullable Object, required Object found: Map ^ ^ 1 2 @@ -24,20 +26,18 @@ public void suggestionRewritesEveryMismatchingWildcard() { 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 + 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 + 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? + fix: declare m as Map """, """ static void take(Map m) {} - void suggestedFormIsAccepted(Map m) { + void fixedFormIsAccepted(Map m) { take(m); } void test(Map m) { @@ -48,22 +48,20 @@ void test(Map m) { } @Test - public void suggestionLeavesAWildcardTheTargetAllowsToBeNullable() { + public void theFixLeavesAWildcardTheTargetAllowsToBeNullable() { assertMessage( """ - incompatible nullability: found @Nullable Object, required Object + incompatible nullability in Map type argument K -> wildcard upper bound: 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? + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter K of Map + fix: declare m as Map """, """ static void take(Map m) {} - void suggestedFormIsAccepted(Map m) { + void fixedFormIsAccepted(Map m) { take(m); } void test(Map m) { @@ -74,18 +72,16 @@ void test(Map m) { } @Test - public void suggestionSurvivesAMismatchInTheHarmlessDirection() { + public void theFixSurvivesAMismatchInTheHarmlessDirection() { assertMessage( """ - incompatible nullability: found @Nullable Object, required Object + incompatible nullability in Box type argument T -> wildcard upper bound: 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? + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Box + fix: declare b as Box """, """ static class Box {} @@ -94,29 +90,27 @@ void test(Box b) { // BUG: Diagnostic matches: MESSAGE take(b); } - void suggestedFormIsAccepted(Box b) { + void fixedFormIsAccepted(Box b) { take(b); } """); } @Test - public void suggestionSurvivesASuperBoundedArgumentTheTargetAlsoDeclaresSuper() { + public void theFixSurvivesASuperBoundedArgumentTheTargetAlsoDeclaresSuper() { assertMessage( """ - incompatible nullability: found @Nullable Object, required Object + incompatible nullability in Map type argument K -> wildcard upper bound: 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? + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter K of Map + fix: declare m as Map """, """ static void take(Map m) {} - void suggestedFormIsAccepted(Map m) { + void fixedFormIsAccepted(Map m) { take(m); } void test(Map m) { @@ -127,22 +121,20 @@ void test(Map m) { } @Test - public void unboundedWildcardSuggestionInsideAnArrayElement() { + public void theFixRewritesAWildcardInsideAnArrayElement() { assertMessage( """ - incompatible nullability: found @Nullable Object, required Object + incompatible nullability in array element -> Collection type argument E -> wildcard upper bound: 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 []? + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List + fix: declare lists as List [] """, """ static void takeArray(Collection[] c) {} - void suggestedFormIsAccepted(List[] lists) { + void fixedFormIsAccepted(List[] lists) { takeArray(lists); } void test(List[] lists) { @@ -153,23 +145,20 @@ void test(List[] lists) { } @Test - public void unboundedWildcardSuggestionInsideANestedTypeArgument() { + public void theFixRewritesAWildcardInsideANestedTypeArgument() { assertMessage( """ - incompatible nullability: found @Nullable Object, required Object + incompatible nullability in Collection type argument E -> wildcard upper bound -> List type argument E -> wildcard upper bound: 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>? + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List + fix: declare lists as List> """, """ static void takeNested(Collection> c) {} - void suggestedFormIsAccepted(List> lists) { + void fixedFormIsAccepted(List> lists) { takeNested(lists); } void test(List> lists) { @@ -180,25 +169,23 @@ void test(List> lists) { } @Test - public void unboundedWildcardSuggestionInAnEnclosingTypeArgument() { + public void theFixRewritesAWildcardInAnEnclosingTypeArgument() { assertMessage( """ - incompatible nullability: found @Nullable Object, required Object + incompatible nullability in enclosing type -> Outer type argument T -> wildcard upper bound: 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? + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Outer + fix: declare inner as Outer.Inner """, """ static class Outer { class Inner {} } static void take(Outer.Inner inner) {} - void suggestedFormIsAccepted(Outer.Inner inner) { + void fixedFormIsAccepted(Outer.Inner inner) { take(inner); } void test(Outer.Inner inner) { @@ -209,18 +196,16 @@ void test(Outer.Inner inner) { } @Test - public void theSourceRepairIsStillOfferedWhereTheRequiredTypeIsNotEditable() { + public void theSourceFixIsStillOfferedWhereTheRequiredTypeIsNotEditable() { assertMessage( """ - incompatible nullability: found @Nullable Object, required Object + incompatible nullability in Collection type argument E -> wildcard upper bound: 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? + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List + fix: declare l as List """, """ static void take(Collection c) {} @@ -232,10 +217,10 @@ void test(List l) { } @Test - public void noSuggestionWhenAnExplicitBoundMismatchRemains() { + public void noFixWhenAnExplicitBoundMismatchRemains() { assertMessage( """ - incompatible nullability: 2 mismatches between source and target types + incompatible nullability in Map type argument K -> wildcard upper bound and 1 other position: found @Nullable Object, required Object found: Map ^ ^^^^^^^^^^^^^^^^ 1 2 @@ -246,8 +231,7 @@ public void noSuggestionWhenAnExplicitBoundMismatchRemains() { 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 + 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 @@ -263,10 +247,10 @@ void test(Map m) { } @Test - public void noSuggestionWhenAConcreteTypeArgumentAlsoMismatches() { + public void noFixWhenAConcreteTypeArgumentAlsoMismatches() { assertMessage( """ - incompatible nullability: 2 mismatches between source and target types + incompatible nullability in Map type argument K -> wildcard upper bound and 1 other position: found @Nullable Object, required Object found: Map ^ ^^^^^^^^^^^^^^^^ 1 2 @@ -277,8 +261,7 @@ public void noSuggestionWhenAConcreteTypeArgumentAlsoMismatches() { 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 + 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 @@ -294,10 +277,10 @@ void test(Map m) { } @Test - public void noSuggestionWhenOneMismatchCannotBeRewritten() { + public void noFixWhenOneMismatchCannotBeRewritten() { assertMessage( """ - incompatible nullability: 2 mismatches between source and target types + incompatible nullability in Map type argument K -> wildcard upper bound and 1 other position: found @Nullable Object, required Object found: Map ^ ^^^^^^^^^^^^^^ 1 2 @@ -308,14 +291,12 @@ public void noSuggestionWhenOneMismatchCannotBeRewritten() { 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 + 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 + 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) {} @@ -327,15 +308,15 @@ void test(Map m) { } @Test - public void noSuggestionWhenBoundsDifferBelowTheTopLevel() { + public void noFixWhenBoundsDifferBelowTheTopLevel() { assertMessage( """ - incompatible nullability: found @Nullable Object, required Object + incompatible nullability in Holder type argument E -> wildcard upper bound -> List type argument E: found @Nullable Object, required Object found: Holder ^ required: Holder> ^^^^^^ - path: Holder type argument E -> wildcard upper bound -> List type argument E + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of Holder """, """ static class Holder> {} @@ -348,17 +329,15 @@ void test(Holder h) { } @Test - public void noSuggestionWhenTheRewrittenTypeHoldsACapture() { + public void noFixWhenTheRewrittenTypeHoldsACapture() { assertMessage( """ - incompatible nullability: found @Nullable Object, required Object + incompatible nullability in Map type argument K -> wildcard upper bound -> List type argument E -> wildcard upper bound: 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 + 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) { @@ -372,56 +351,78 @@ void test(List l) { """); } + // The printer drops @Tainted from the printed types, so TAINTED differs from PLAIN only by the + // missing fix line. @Test - public void aSourceWithNoOtherTypeUseAnnotationGetsTheRepair() { - assertMessage( + public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { + assertMessages( + Map.of( + "PLAIN", + """ + incompatible nullability in Map type argument K -> wildcard upper bound: found @Nullable Object, required Object + found: Map + ^ + required: Map + ^^^^^^ + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter K of Map + fix: declare plain as Map + """, + "TAINTED", + """ + incompatible nullability in Map type argument K -> wildcard upper bound: found @Nullable Object, required Object + found: Map + ^ + required: Map + ^^^^^^ + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter K of Map + """, + "TAINTED_ARRAY_ELEMENT", + """ + incompatible nullability in Map type argument K -> wildcard upper bound: found @Nullable Object, required Object + found: Map + ^ + required: Map + ^^^^^^ + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter K of Map + """), """ - 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")); + @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) + @interface Tainted {} + static void take(Map m) {} + static void takeArrays(Map m) {} + void plain(Map plain) { + // BUG: Diagnostic matches: PLAIN + take(plain); + } + void tainted(Map tainted) { + // BUG: Diagnostic matches: TAINTED + take(tainted); + } + void taintedArrayElement(Map m) { + // BUG: Diagnostic matches: TAINTED_ARRAY_ELEMENT + takeArrays(m); + } + """); } - // 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() { + public void theFixNamesTheFieldItRewrites() { 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 + incompatible nullability in Collection type argument E -> wildcard upper bound: found @Nullable Object, required Object + found: List + ^ + required: Collection + ^^^^^^ + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List + fix: declare field as List """, - 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) { + """ + List field = new ArrayList<>(); + void test(List result) { // BUG: Diagnostic matches: MESSAGE - take(m); + result.addAll(field); } - """ - .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 index 0447afc74d..142fe17e43 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java @@ -1,14 +1,12 @@ 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 + * The first line of a generic nullability message names the position of the first difference, how + * many other positions differ, and the two types at the first one, so that it stands alone where a + * tool shows only that line. 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 { @@ -17,7 +15,7 @@ public class SummaryAndNumberingTests extends MismatchMessageTestBase { public void listsAtMostFiveMismatchesAndSaysHowManyMoreThereAre() { assertMessage( """ - incompatible nullability: 6 mismatches between source and target types + incompatible nullability in Args type argument A -> wildcard upper bound and 5 other positions: found @Nullable Object, required Object found: Args ^ ^ ^ ^ ^ 1 2 3 4 5 @@ -28,45 +26,47 @@ public void listsAtMostFiveMismatchesAndSaysHowManyMoreThereAre() { 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 + 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 + 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 + 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 + 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 + 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? + fix: declare args as Args """, - wildcardsWhereNonNullBoundsAreRequired(6)); + """ + static class Args {} + static void take(Args args) {} + void test(Args args) { + // BUG: Diagnostic matches: MESSAGE + take(args); + } + """); } @Test public void listsFiveMismatchesWithoutSayingThereAreMore() { assertMessage( """ - incompatible nullability: 5 mismatches between source and target types + incompatible nullability in Args type argument A -> wildcard upper bound and 4 other positions: found @Nullable Object, required Object found: Args ^ ^ ^ ^ ^ 1 2 3 4 5 @@ -77,43 +77,45 @@ public void listsFiveMismatchesWithoutSayingThereAreMore() { 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 + 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 + 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 + 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 + 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 + 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? + fix: declare args as Args """, - wildcardsWhereNonNullBoundsAreRequired(5)); + """ + static class Args {} + static void take(Args args) {} + void test(Args args) { + // BUG: Diagnostic matches: MESSAGE + take(args); + } + """); } @Test public void adjacentTypeArgumentsThatBothMismatchAreNumberedSideBySide() { assertMessage( """ - incompatible nullability: 2 mismatches between source and target types + incompatible nullability in Map type argument K and 1 other position: found @Nullable String, required String found: Map<@Nullable String, @Nullable String> ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ 1 2 @@ -142,12 +144,11 @@ void test(Map<@Nullable String, @Nullable String> m) { public void invariantTypeArgumentIsReportedWhenTheSourceIsLessNullableThanRequired() { assertMessage( """ - incompatible nullability: a type argument must match exactly; found String, required @Nullable String + incompatible nullability in List type argument E: 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) { @@ -157,28 +158,4 @@ void test(List source) { } """); } - - /** - * 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/TraversalCostTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java new file mode 100644 index 0000000000..da7cc28cd2 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java @@ -0,0 +1,106 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import org.junit.Test; + +/** + * Building the message costs time linear in the bound graph the check walks, however many paths + * reach a shared wildcard bound. Each {@code L} bounds its type parameter by a pair of two + * {@code L}, so a walk that revisits a bound once per path takes time exponential in the + * depth, and the timeout of each test is far below what depth 24 takes then. + */ +public class TraversalCostTests extends MismatchMessageTestBase { + + @Test(timeout = 30_000) + public void aSharedBoundBesideTheMismatchIsWalkedOnce() { + assertMessage( + """ + incompatible nullability in P type argument A: found @Nullable String, required String + found: P<@Nullable String, L24> + ^^^^^^^^^^^^^^^^ + required: P> + ^^^^^^ + fix: declare x as P<@Nullable String, L24> + """, + """ + interface P {} + interface L0 {} + interface L1, L0>> {} + interface L2, L1>> {} + interface L3, L2>> {} + interface L4, L3>> {} + interface L5, L4>> {} + interface L6, L5>> {} + interface L7, L6>> {} + interface L8, L7>> {} + interface L9, L8>> {} + interface L10, L9>> {} + interface L11, L10>> {} + interface L12, L11>> {} + interface L13, L12>> {} + interface L14, L13>> {} + interface L15, L14>> {} + interface L16, L15>> {} + interface L17, L16>> {} + interface L18, L17>> {} + interface L19, L18>> {} + interface L20, L19>> {} + interface L21, L20>> {} + interface L22, L21>> {} + interface L23, L22>> {} + interface L24, L23>> {} + static P<@Nullable String, L24> get() { + throw new RuntimeException(); + } + void test() { + // BUG: Diagnostic matches: MESSAGE + P> x = get(); + } + """); + } + + @Test(timeout = 30_000) + public void aSharedBoundBesideANestedMismatchIsWalkedOnce() { + assertMessage( + """ + incompatible nullability in List type argument E -> Box type argument B: found @Nullable String, required String + found: List, @Nullable String>> + ^^^^^^^^^^^^^^^^ + required: List, String>> + ^^^^^^ + fix: declare x as List, @Nullable String>> + """, + """ + interface P {} + interface L0 {} + interface L1, L0>> {} + interface L2, L1>> {} + interface L3, L2>> {} + interface L4, L3>> {} + interface L5, L4>> {} + interface L6, L5>> {} + interface L7, L6>> {} + interface L8, L7>> {} + interface L9, L8>> {} + interface L10, L9>> {} + interface L11, L10>> {} + interface L12, L11>> {} + interface L13, L12>> {} + interface L14, L13>> {} + interface L15, L14>> {} + interface L16, L15>> {} + interface L17, L16>> {} + interface L18, L17>> {} + interface L19, L18>> {} + interface L20, L19>> {} + interface L21, L20>> {} + interface L22, L21>> {} + interface L23, L22>> {} + interface L24, L23>> {} + static class Box {} + void test(List, @Nullable String>> l) { + // BUG: Diagnostic matches: MESSAGE + List, String>> x = l; + } + """); + } +} 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 45ee3dac13..94c4a0a52f 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,10 +3,11 @@ import org.junit.Test; /** - * 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. + * Where the check views the source as a supertype of its own class, the one the target names, 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 { @@ -14,12 +15,11 @@ public class ViewedSourceTests extends MismatchMessageTestBase { public void aCarriedOverNodeInsideAWildcardBoundIsMarkedOnTheWrittenSource() { assertMessage( """ - incompatible nullability: found @Nullable String, required String + incompatible nullability in Base type argument T -> wildcard upper bound -> List type argument E: found @Nullable String, required String found: Sub> ^^^^^^^^^^^^^^^^ required: Base> ^^^^^^ - path: Base type argument T -> wildcard upper bound -> List type argument E """, """ static class Base {} @@ -36,12 +36,11 @@ void test(Sub> s) { public void aCarriedOverNodeInsideAnArrayElementIsMarkedOnTheWrittenSource() { assertMessage( """ - incompatible nullability: found @Nullable String, required String + incompatible nullability in Base type argument T -> array element: found @Nullable String, required String found: Sub<@Nullable String []> ^^^^^^^^^^^^^^^^ required: Base ^^^^^^ - path: Base type argument T -> array element """, """ static class Base {} @@ -58,12 +57,11 @@ void test(Sub<@Nullable String[]> s) { public void aCarriedOverCaptureIsMarkedOnTheWrittenSourceAndKeepsItsProvenance() { assertMessage( """ - incompatible nullability: found @Nullable Object, required Object + incompatible nullability in Base type argument T -> wildcard upper bound: found @Nullable Object, required Object found: Sub ^^^^^^^^^^^^ required: Base ^^^^^^ - path: Base type argument T -> wildcard upper bound note: the source wildcard is the type argument for type parameter T of Sub """, """ @@ -84,13 +82,12 @@ void test() { public void aNodeFromTheSubclassDeclarationIsMarkedOnTheViewedSource() { assertMessage( """ - incompatible nullability: found @Nullable String, required String + incompatible nullability in Base type argument T -> List type argument E: found @Nullable String, required String found: Sub found as: Base> ^^^^^^^^^^^^^^^^ required: Base> ^^^^^^ - path: Base type argument T -> List type argument E """, """ static class Base {} @@ -107,13 +104,12 @@ void test(Sub s) { public void aWildcardFromTheSubclassDeclarationGetsANoteThatStatesItsBoundOnly() { assertMessage( """ - incompatible nullability: found @Nullable Object, required Object + incompatible nullability in Base type argument B -> wildcard upper bound -> List type argument E -> wildcard upper bound: found @Nullable Object, required Object found: Sub 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 """, """ @@ -131,15 +127,13 @@ void test(Sub s) { public void aPathAcrossAViewReachesIntoWhateverTheSubclassPassed() { assertMessage( """ - incompatible nullability: found @Nullable Object, required Object + incompatible nullability in Base type argument B -> wildcard upper bound -> List type argument E -> wildcard upper bound: 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? + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter X of Indirect + fix: declare i as Indirect """, """ static class Base {} @@ -179,12 +173,11 @@ public class Result extends a.Result {} "MESSAGE", messageIs( """ - incompatible nullability: found @Nullable String, required String + incompatible nullability in Result type argument T: found @Nullable String, required String found: Result<@Nullable String> ^^^^^^^^^^^^^^^^ required: Result ^^^^^^ - path: Result type argument T """)) .addSourceLines( "Test.java", @@ -198,4 +191,90 @@ void test(b.Result<@Nullable String> r) { """)) .doTest(); } + + @Test + public void aReorderingSubclassIsMarkedAtTheArgumentItPassesOn() { + assertMessage( + """ + incompatible nullability in List type argument E -> wildcard upper bound -> Pair type argument A: found @Nullable String, required String + found: List> + ^^^^^^^^^^^^^^^^ + required: List> + ^^^^^^ + """, + """ + static class Pair {} + static class Swap extends Pair {} + static void take(List> l) {} + void test(List> l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void aReorderingSubclassInsideAnArrayIsMarkedAtTheArgumentItPassesOn() { + assertMessage( + """ + incompatible nullability in array element -> Pair type argument A: found @Nullable String, required String + found: Swap [] + ^^^^^^^^^^^^^^^^ + required: Pair [] + ^^^^^^ + """, + """ + static class Pair {} + static class Swap extends Pair {} + static void take(Pair[] a) {} + void test(Swap[] a) { + // BUG: Diagnostic matches: MESSAGE + take(a); + } + """); + } + + @Test + public void aReorderingSubclassTwoLevelsDownIsMarkedAtTheArgumentItPassesOn() { + assertMessage( + """ + incompatible nullability in List type argument E -> wildcard upper bound -> List type argument E -> wildcard upper bound -> Pair type argument A: found @Nullable String, required String + found: List>> + ^^^^^^^^^^^^^^^^ + required: List>> + ^^^^^^ + """, + """ + static class Pair {} + static class Swap extends Pair {} + static void take(List>> l) {} + void test(List>> l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void anEnclosingTypeArgumentOfASubclassIsMarkedOnTheWrittenSource() { + assertMessage( + """ + incompatible nullability in enclosing type -> Outer type argument T: found @Nullable String, required String + found: Outer<@Nullable String>.SubInner + ^^^^^^^^^^^^^^^^ + required: Outer.Inner + ^^^^^^ + """, + """ + static class Outer { + class Inner {} + class SubInner extends Inner {} + } + static void take(Outer.Inner i) {} + void test(Outer<@Nullable String>.SubInner s) { + // BUG: Diagnostic matches: MESSAGE + take(s); + } + """); + } } diff --git a/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java b/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java index eb3fd45924..5c13338d8c 100644 --- a/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java +++ b/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java @@ -611,7 +611,7 @@ public void deeplyNestedTypeAnnot() { @NullMarked public class Test { void testPositive(NestedAnnots> p) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> NestedAnnots type argument T: a type argument must match exactly; found String, required @Nullable String NestedAnnots.deeplyNested(p); } void testNegative(NestedAnnots> p) { @@ -638,7 +638,7 @@ public void nestedArray1() { @NullMarked public class Test { void testPositive() { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> array element -> NestedAnnots type argument T: found @Nullable String, required String NestedAnnots[]> unused = NestedAnnots.nestedArray1(); } void testNegative() { @@ -665,7 +665,7 @@ public void nestedArray2() { @NullMarked public class Test { void testPositive() { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T: found String @Nullable [], required String [] NestedAnnots unused = NestedAnnots.nestedArray2(); } void testNegative() { @@ -692,11 +692,11 @@ public void nestedWildcards() { @NullMarked public class Test { void testUpper(NestedAnnots<@Nullable String> t) { - // BUG: Diagnostic contains: incompatible types: NestedAnnots<@Nullable String> cannot be converted to NestedAnnots + // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> wildcard upper bound: found @Nullable String, required String NestedAnnots.wildcardUpper(t); } void testLower(NestedAnnots t) { - // BUG: Diagnostic contains: incompatible types: NestedAnnots cannot be converted to NestedAnnots + // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> wildcard lower bound: found String, required a supertype of @Nullable String NestedAnnots.wildcardLower(t); } } @@ -725,7 +725,7 @@ NestedAnnots testDirect( // should reject since return type of wildcardUpperTypeVariable // is modeled to be NestedAnnots, which // here is incompatible with the return type NestedAnnots - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> wildcard upper bound: found @Nullable String, required String return receiver.wildcardUpperTypeVariable(); } @@ -734,7 +734,7 @@ NestedAnnots testWithSelf( // should reject since return type of wildcardUpperTypeVariable // is modeled to be NestedAnnots, which // here is incompatible with the return type NestedAnnots - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> wildcard upper bound: found @Nullable String, required String return receiver.self().wildcardUpperTypeVariable(); } @@ -745,7 +745,7 @@ NestedAnnots testWithVar( // should reject since return type of wildcardUpperTypeVariable // is modeled to be NestedAnnots, which // here is incompatible with the return type NestedAnnots - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> wildcard upper bound: found @Nullable String, required String return foo.wildcardUpperTypeVariable(); } @@ -771,7 +771,7 @@ public void nestedAnnotationsOnUnboundedWildcardBounds() { public class Test { UnboundWildcards testLiteral() { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in UnboundWildcards type argument T -> wildcard upper bound: found @Nullable Object, required Object return UnboundWildcards.literalWildcard(); } @@ -781,7 +781,7 @@ UnboundWildcards testLiteral() { UnboundWildcards testCaptured( UnboundWildcards receiver) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in UnboundWildcards type argument T -> wildcard upper bound: found @Nullable Object, required Object return receiver.self().typeVariable(); } @@ -811,9 +811,9 @@ public void multipleArgs() { public class Test { void testPositive() { NestedAnnots.multipleArgs( - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T: found @Nullable String, required String new NestedAnnots<@Nullable String>(), - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T: a type argument must match exactly; found Integer, required @Nullable Integer new NestedAnnots()); } void testNegative() { From df658216c927827b0b5a55366272fa977934a8da Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Fri, 27 Nov 2026 15:25:18 +0300 Subject: [PATCH 07/43] Keep the declaration fix valid for qualified names, varargs, and shared types The fix printed the annotation in front of a qualified name, as in `@Nullable Map.Entry` or `@Nullable java.util.List`, which javac rejects; it now goes before the last segment, `Map.@Nullable Entry`. The edit for a varargs parameter replaced `List...` with `List[]`, and the edit for one variable of `List a, b;` rewrote the type tree both share; neither declaration gets an edit now, and the `fix:` line stays. The class comparison at the root now restores the frame it changed, so a second component of an intersection target is not compared against the first one's view. Assisted-by: Claude Code (claude-opus-5-5) --- .../CheckIdenticalNullabilityVisitor.java | 13 +-- .../GenericTypePrettyPrintingVisitor.java | 6 +- .../generics/NullabilityMismatchMessage.java | 35 ++++++++ .../generics/NullabilityMismatches.java | 7 +- .../jspecify/mismatchmessage/FixTests.java | 82 +++++++++++++++++++ 5 files changed, 135 insertions(+), 8 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 bb69d9eb41..c2e4f9cb8c 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitor.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitor.java @@ -113,8 +113,10 @@ private record ContainmentKey( } /** - * Creates a visitor that records every comparison it rejects in {@code mismatches}, where that is - * not {@code null}. + * Creates a visitor that, where {@code mismatches} is not {@code null}, records in it each + * comparison it rejects. A wildcard comparison met again within the same outermost wildcard + * comparison, whether still in progress or already done, is taken to hold the second time; it is + * recorded where it was first made. */ CheckIdenticalNullabilityVisitor( VisitorState state, @@ -274,9 +276,8 @@ public Boolean visitClassType(Type.ClassType lhsType, Type rhsType) { GenericsUtils.effectiveUpperBoundsForTypeArguments( rhsClassTypeAsSuper, state, config, handler); } - if (mismatches != null) { - mismatches.enterClassComparison(rhsType, rhsClassTypeAsSuper); - } + NullabilityMismatches.Frame savedOutside = + mismatches == null ? null : mismatches.enterClassComparison(rhsType, rhsClassTypeAsSuper); boolean contained = true; for (int i = 0; i < lhsTypeArguments.size(); i++) { Type lhsTypeArgument = lhsTypeArguments.get(i); @@ -315,6 +316,8 @@ public Boolean visitClassType(Type.ClassType lhsType, Type rhsType) { && contained; } finally { restore(saved); + // the loop above returns early only without a recorder, so this is the one exit to undo + restore(savedOutside); } } 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 b369fc10f2..740e9a857b 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java @@ -201,8 +201,12 @@ public String visitClassType(Type.ClassType t, @Nullable Void s) { if (printsEnclosingType) { sb.append(descend(TypePath.Step.enclosingType(), enclosingType)).append('.'); } + String className = printsEnclosingType ? t.tsym.getSimpleName().toString() : name(t.tsym); + // a type annotation on a qualified name goes before its last segment: Map.@Nullable Entry + int lastDot = className.lastIndexOf('.'); + sb.append(className, 0, lastDot + 1); appendNullableAnnotationIfPresent(t, sb); - sb.append(printsEnclosingType ? t.tsym.getSimpleName().toString() : name(t.tsym)); + sb.append(className, lastDot + 1, className.length()); if (t.getTypeArguments().nonEmpty()) { sb.append('<'); StringBuilder arguments = new StringBuilder(); 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 e321d6b56f..41bf5623d4 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -10,9 +10,11 @@ import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; +import com.sun.source.util.TreeScanner; import com.sun.tools.javac.api.JavacTrees; import com.sun.tools.javac.code.Attribute; import com.sun.tools.javac.code.BoundKind; +import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.code.Type; @@ -268,6 +270,10 @@ private void appendFix( return; // diff-coverage: ignore -- javac versions differ in whether an inferred type gets a // synthesized tree } + if (isVarargs(declaration) || sharesTypeTree(declarationPath)) { + // the printed type has no form for "...", and a shared type tree declares other variables too + return; + } SuggestedFix.Builder fix = SuggestedFix.builder(); String printed = GenericTypePrettyPrintingVisitor.printForFix( @@ -275,6 +281,35 @@ private void appendFix( fixes.add(fix.replace(typeTree, printed).build()); } + /** Whether {@code declaration} is a varargs parameter, whose type tree is written with "...". */ + private static boolean isVarargs(VariableTree declaration) { + Symbol symbol = ASTHelpers.getSymbol(declaration); + return symbol != null && (symbol.flags() & Flags.VARARGS) != 0; + } + + /** + * Whether the declaration at {@code declarationPath} shares its type tree with another variable, + * as each variable of {@code List a, b;} does. + */ + private static boolean sharesTypeTree(TreePath declarationPath) { + VariableTree declaration = (VariableTree) declarationPath.getLeaf(); + Tree typeTree = declaration.getType(); + Boolean shared = + new TreeScanner() { + @Override + public Boolean visitVariable(VariableTree variable, @Nullable Void unused) { + return (variable != declaration && variable.getType() == typeTree) + || Boolean.TRUE.equals(super.visitVariable(variable, null)); + } + + @Override + public Boolean reduce(@Nullable Boolean left, @Nullable Boolean right) { + return Boolean.TRUE.equals(left) || Boolean.TRUE.equals(right); + } + }.scan(declarationPath.getParentPath().getLeaf(), null); + return Boolean.TRUE.equals(shared); + } + /** * Whether {@code declaration} writes a nullable annotation among its modifiers, where a type-use * annotation applies to the base type and lies outside the type tree. 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 fd1c0e41a1..78df48de11 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java @@ -180,9 +180,11 @@ void restore(Frame saved) { /** * Notes that the check compares {@code lhs} against {@code rhsView}, the right side {@code rhs} * viewed as the class of {@code lhs}. At the root of the source, a view of another class is what - * a caret goes into where the written source does not hold the compared node. + * a caret goes into where the written source does not hold the compared node. Returns the frame + * to restore once the comparison ends. */ - void enterClassComparison(Type rhs, Type rhsView) { + Frame enterClassComparison(Type rhs, Type rhsView) { + Frame saved = frame; if (frame.view() == null && !frame.swapped() && frame.targetSteps().isRoot() @@ -198,6 +200,7 @@ void enterClassComparison(Type rhs, Type rhsView) { frame.swapped(), frame.bound()); } + return saved; } /** Steps into type argument {@code index} of {@code lhs} and of {@code rhsView}. */ diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java index a1983a7e4c..d0ff96d53b 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java @@ -172,4 +172,86 @@ void test() { .expectUnchanged() .doTest(); } + + @Test + public void theFixPutsTheAnnotationBeforeTheLastSegmentOfAQualifiedName() throws IOException { + makeHelper() + .addInputLines( + "Lib.java", + """ + import java.util.List; + import java.util.Map; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Lib { + static List> entries() { + throw new RuntimeException(); + } + static java.util.List> lists() { + throw new RuntimeException(); + } + } + """) + .expectUnchanged() + .addInputLines( + "Test.java", + """ + import java.util.Map; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class List {} + void test() { + java.util.List> nested = Lib.entries(); + java.util.List> clashing = Lib.lists(); + } + } + """) + .addOutputLines( + "Test.java", + """ + import java.util.Map; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class List {} + void test() { + java.util.List> nested = Lib.entries(); + java.util.List> clashing = Lib.lists(); + } + } + """) + .doTest(); + } + + @Test + public void noEditForAVarargsParameterOrADeclarationOfSeveralVariables() throws IOException { + makeHelper() + .addInputLines( + "Test.java", + """ + import java.util.ArrayList; + import java.util.Collection; + import java.util.List; + import org.jspecify.annotations.NullMarked; + @NullMarked + class Test { + static void take(Collection c) {} + static void takeArray(Collection[] c) {} + void varargs(List... lists) { + takeArray(lists); + } + void several() { + List first = new ArrayList<>(), second = new ArrayList<>(); + take(first); + take(second); + } + } + """) + .expectUnchanged() + .doTest(); + } } From e022a7a321e2e86cc01a45f0292a17ea9350b71d Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Fri, 27 Nov 2026 15:33:32 +0300 Subject: [PATCH 08/43] Print the view the rejected comparison used on the found as line The source view for the `found as:` line was one field that every class comparison at the root overwrote. For an intersection target, each component is such a comparison, so `B` assigned to `A & Serializable` printed `found as: Serializable`, though the rejected comparison viewed `B` as `A<@Nullable String>`. Each recorded mismatch now carries the view it was compared under, and the line is printed only where the mismatches without a source caret share one view. The JDK 25 test `GenericsTests.intersectionTypeInvalidAssign` still expected the old `incompatible types:` text; it now expects the new message. The class comment now says that a view is printed only at the root, which is what the code does. Assisted-by: Claude Code (claude-opus-5-5) --- .../CheckIdenticalNullabilityVisitor.java | 7 +-- .../generics/NullabilityMismatchMessage.java | 50 +++++++++++++++---- .../generics/NullabilityMismatches.java | 38 ++++++++------ .../uber/nullaway/jspecify/GenericsTests.java | 4 +- .../mismatchmessage/ViewedSourceTests.java | 6 +-- 5 files changed, 69 insertions(+), 36 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 c2e4f9cb8c..a91567d1d7 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitor.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitor.java @@ -328,12 +328,9 @@ private Boolean handleIntersectionType( for (Type bound : intersectionType.getExplicitComponents()) { if (!bound.accept(this, rhsType)) { if (mismatches == null) { - return false; // diff-coverage: ignore -- no test reaches an intersection target that - // fails, here or on master + return false; // diff-coverage: ignore -- reached on JDK 25+ only } - contained = - false; // diff-coverage: ignore -- no test reaches an intersection target that fails, - // here or on master + contained = false; // diff-coverage: ignore -- reached on JDK 25+ only } } return contained; 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 41bf5623d4..c99f7f8091 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -84,15 +84,16 @@ *

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 check compares the source viewed as the target's class, which is the source's own class or a - * supertype of it, so which node of the type the reader wrote the caret belongs under has two - * answers: where the view is the same class, the position is the same position; where it is a - * supertype, only a node the substitution carried over from the written type can be pointed at. - * Viewing an {@code ArrayList<@Nullable String>} as a {@code List} carries the {@code @Nullable - * String} over; for {@code class Sub extends Base>}, viewing a {@code Sub} - * as a {@code Base} rebuilds the {@code List<@Nullable String>} from the declaration of {@code - * Sub}, which the written type does not hold. Where neither answers, the view is printed as {@code - * found as} and carries the carets. Two differences below one printed node share its caret, - * numbered for each. + * supertype of it, and the source caret goes into the type the reader wrote. Where the view is the + * source's own class, the caret goes at the same position. Where the view is a supertype, it goes + * only under a node the substitution carried over from the written type. Viewing an {@code + * ArrayList<@Nullable String>} as a {@code List} carries the {@code @Nullable String} over; for + * {@code class Sub extends Base>}, viewing a {@code Sub} as a {@code Base} + * rebuilds the {@code List<@Nullable String>} from the declaration of {@code Sub}, which the + * written type does not hold. Where the source is viewed as a supertype at the root and the node is + * not in the written type, that view is printed as {@code found as} and carries the carets. Below + * the root, as for an element of {@code List}, no view is printed, and such a node gets no + * source caret. Two differences below one printed node share its caret, numbered for each. * *

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, including one the supertype view carried over @@ -198,7 +199,7 @@ Report build( rhsType, carets(listed, NullabilityMismatches.Mismatch::sourceCaret), numbered); - Type viewedSource = recorded.viewedSource(); + Type viewedSource = sharedView(listed); if (found.marksPlaced() == listed.size() || viewedSource == null) { message.append(found.lines()); } else { @@ -209,7 +210,14 @@ Report build( markedTypeLines( "found as", viewedSource, - carets(listed, NullabilityMismatches.Mismatch::viewCaret), + carets( + listed, + mismatch -> + mismatch.viewedSource() != null + && ASTHelpers.isSameType( + mismatch.viewedSource(), viewedSource, state) + ? mismatch.viewCaret() + : null), numbered) .lines()); } @@ -417,6 +425,26 @@ private String required(NullabilityMismatches.Mismatch mismatch) { : target; } + /** + * Returns the view of the source that every mismatch in {@code listed} without a caret in the + * written source was compared under, or {@code null} where one of them has no view or two have + * different ones, as the components of an intersection target do. + */ + private @Nullable Type sharedView(List listed) { + Type shared = null; + for (NullabilityMismatches.Mismatch mismatch : listed) { + if (mismatch.sourceCaret() != null) { + continue; + } + Type view = mismatch.viewedSource(); + if (view == null || (shared != null && !ASTHelpers.isSameType(shared, view, state))) { + return null; + } + shared = view; + } + return shared; + } + /** Returns the caret {@code caret} gives each mismatch, in order. */ private static List<@Nullable TypePath> carets( List mismatches, 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 78df48de11..1225b67094 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java @@ -60,7 +60,9 @@ Relation swapped() { * @param targetCaret where the target's caret goes, or {@code null} where the target gets none * @param sourceCaret where the source's caret goes in the source as written, or {@code null} * where the node the check compared sits nowhere in that type - * @param viewCaret where the source's caret goes in {@link #viewedSource()}, or {@code null} + * @param viewedSource the source viewed as the class the target names at the root, where the + * check compared that view rather than the written source, or {@code null} + * @param viewCaret where the source's caret goes in {@code viewedSource}, or {@code null} * @param sourcePrintedNode the node under {@code sourceCaret}; where there is no such caret, the * deepest node the compared view of the source prints. It is the wildcard itself where the * node at fault lies below a bound the wildcard leaves implicit @@ -78,6 +80,7 @@ record Mismatch( @Nullable TypePath targetNodePath, @Nullable TypePath targetCaret, @Nullable TypePath sourceCaret, + @Nullable Type viewedSource, @Nullable TypePath viewCaret, Type sourcePrintedNode, Type.@Nullable WildcardType sourceWildcard, @@ -121,8 +124,10 @@ private record BoundComparison( * @param targetSteps the steps taken into the target, named for the classes compared * @param target the target as written * @param source the source as written - * @param view the source viewed as the target's class at the root, or {@code null} where that - * view is the written source itself + * @param viewedSource the source viewed as the target's class at the root, or {@code null} where + * that view is the written source itself + * @param view where the comparison stands in {@code viewedSource}, or {@code null} where there is + * no such view * @param sourceShown the deepest node of the compared source a printer would show * @param swapped whether the visitor's left side is the source, as inside the lower bound of a * {@code ? super} wildcard, where the check asks whether that bound is a subtype of the @@ -133,6 +138,7 @@ record Frame( TypePath targetSteps, Track target, Track source, + @Nullable Type viewedSource, @Nullable Track view, Type sourceShown, boolean swapped, @@ -140,8 +146,6 @@ record Frame( private Frame frame; - private @Nullable Type viewedSource; - private final List mismatches = new ArrayList<>(); /** @@ -154,6 +158,7 @@ record Frame( Track.located(targetType, TypePath.root()), Track.located(sourceType, TypePath.root()), null, + null, sourceType, false, null); @@ -164,14 +169,6 @@ List mismatches() { return mismatches; } - /** - * Returns the source viewed as the class the target names, where the check compared that view at - * the root rather than the written source, and {@code null} otherwise. - */ - @Nullable Type viewedSource() { - return viewedSource; - } - /** Puts back a frame an {@code enter} method returned. */ void restore(Frame saved) { frame = saved; @@ -189,12 +186,12 @@ Frame enterClassComparison(Type rhs, Type rhsView) { && !frame.swapped() && frame.targetSteps().isRoot() && !rhsView.tsym.equals(rhs.tsym)) { - viewedSource = rhsView; frame = new Frame( frame.targetSteps(), frame.target(), frame.source(), + rhsView, Track.located(rhsView, TypePath.root()), frame.sourceShown(), frame.swapped(), @@ -271,6 +268,7 @@ Frame enterLowerBounds( frame.targetSteps(), frame.target(), frame.source(), + frame.viewedSource(), frame.view(), frame.sourceShown(), !frame.swapped(), @@ -299,6 +297,7 @@ void reject(Relation relation, Type lhsNode, Type rhsNode) { target == null || target.hidden() ? null : target.path(), target == null ? null : target.path(), source == null ? null : source.path(), + frame.viewedSource(), view == null ? null : view.path(), source != null ? source.node() : frame.sourceShown(), bound == null ? null : bound.sourceWildcard(), @@ -339,7 +338,16 @@ private Frame enter(@Nullable Step lhs, @Nullable Step rhs, @Nullable BoundCompa sourceShown = sourceStep.child(); } } - frame = new Frame(targetSteps, target, source, view, sourceShown, saved.swapped(), bound); + frame = + new Frame( + targetSteps, + target, + source, + saved.viewedSource(), + view, + sourceShown, + saved.swapped(), + bound); return saved; } 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 5bcc4a69a1..6853d79a99 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java @@ -3033,7 +3033,7 @@ static class B implements A<@Nullable String>, Serializable {} static class C implements A, Serializable {} static void test1(Object o) { var x = (A & Serializable) o; - // BUG: Diagnostic contains: incompatible types: B cannot be converted to A & Serializable + // BUG: Diagnostic contains: found as: A<@Nullable String> x = new B(); // ok x = new C(); @@ -3041,7 +3041,7 @@ static void test1(Object o) { static void test2(Object o) { var x = (A<@Nullable String> & Serializable) o; x = new B(); - // BUG: Diagnostic contains: incompatible types: C cannot be converted to A<@Nullable String> & Serializable + // BUG: Diagnostic contains: incompatible nullability in A type argument T: a type argument must match exactly; found String, required @Nullable String x = new C(); } } 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 94c4a0a52f..c864937fbc 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 @@ -5,9 +5,9 @@ /** * Where the check views the source as a supertype of its own class, the one the target names, 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. + * the reader wrote where the substitution carried that node into the view. Where the source itself + * is viewed as a supertype and 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 { From 87a64bbf1b8e440145cefe365b35ef6c744dde6d Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Fri, 27 Nov 2026 15:35:05 +0300 Subject: [PATCH 09/43] Rejoin comments the formatter broke after one word Assisted-by: Claude Code (claude-opus-5-5) --- .../com/uber/nullaway/generics/NullabilityMismatches.java | 6 ++---- .../uber/nullaway/jspecify/mismatchmessage/NoteTests.java | 3 +-- 2 files changed, 3 insertions(+), 6 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 1225b67094..92267ea091 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java @@ -424,14 +424,12 @@ private static Track follow(Track track, Step step) { if (node instanceof Type.ArrayType arrayType) { return Track.located(arrayType.elemtype, track.path().then(TypePath.Step.arrayElement())); } - return null; // diff-coverage: ignore -- a step into an array element is taken only from an - // array + return null; // diff-coverage: ignore -- only an array has an element to step into } case WILDCARD_BOUND -> { Type.WildcardType wildcard = GenericsUtils.asWildcard(node); if (wildcard == null) { - return null; // diff-coverage: ignore -- a step into a wildcard bound is taken only from a - // wildcard + return null; // diff-coverage: ignore -- only a wildcard has a bound to step into } // the upper bound of `?` and `? super X` is not printed, so the caret stays on the wildcard return wildcard.kind == BoundKind.EXTENDS 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 011d74eb99..26752ab181 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 @@ -10,8 +10,7 @@ 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. + // the two types and that List is a subtype of Collection, which read as a contradiction. @Test public void anUnboundedWildcardNamesTheTypeParameterItsBoundIsInheritedFrom() { assertMessage( From ecb7afc1793a28e0347a8378e3f8159534d7b880 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Fri, 27 Nov 2026 20:14:42 +0300 Subject: [PATCH 10/43] Label the two sides of a nullability mismatch source and target The mismatch message named one pair of types two ways: the type lines and the first line said found and required, while the notes said "the source wildcard" and the summary of several mismatches said "between source and target types". Every case the message reports is a pseudo-assignment, and JLS chapter 5 calls its left side the target type, so source and target is the pair that fits all of them. The keys of the type lines are padded to the widest key the message prints, so the two types still start in one column and the carets stay under the node they mark. User-visible: The first line reads `incompatible nullability in : source has X where target requires Y`, and `a type argument must match exactly; source has String where target requires @Nullable String` where the source is the less nullable side. The type lines and the numbered entries are keyed `source:` and `target:`, and the supertype view of the source is keyed `source viewed as:`. Not changed: The `incompatible types: A cannot be converted to B` text, printed where the check records no position, keeps javac's wording. Assisted-by: Claude Code (claude-opus-5-5) --- .../jdkannotations/JDKIntegrationTest.java | 28 +-- .../generics/NullabilityMismatchMessage.java | 178 ++++++++------ .../uber/nullaway/JSpecifyJDKModelsTest.java | 4 +- .../nullaway/ParameterAssignmentTests.java | 4 +- .../jspecify/BytecodeGenericsTests.java | 10 +- .../jspecify/GenericDiamondTests.java | 22 +- .../GenericInferenceErrorReportingTests.java | 2 +- .../jspecify/GenericInheritanceTests.java | 12 +- .../nullaway/jspecify/GenericLambdaTests.java | 4 +- ...enericMethodLambdaOrMethodRefArgTests.java | 4 +- .../nullaway/jspecify/GenericMethodTests.java | 90 +++---- .../jspecify/GenericVoidReturnTests.java | 4 +- .../uber/nullaway/jspecify/GenericsTests.java | 118 +++++----- .../IntersectionBoundNarrowingTests.java | 4 +- .../IntersectionRestorationTests.java | 6 +- .../nullaway/jspecify/JSpecifyArrayTests.java | 36 +-- .../jspecify/PolyNullLibraryModelsTests.java | 2 +- .../SharedIntersectionTimeoutTests.java | 2 +- .../StreamNullabilityPropagatorTests.java | 4 +- .../jspecify/VarDeclaredLocalTests.java | 2 +- .../uber/nullaway/jspecify/WildcardTests.java | 64 ++--- .../jspecify/mismatchmessage/CaretTests.java | 146 ++++++------ .../jspecify/mismatchmessage/FixTests.java | 2 +- .../LowerBoundAndRawSourceTests.java | 22 +- .../jspecify/mismatchmessage/NoteTests.java | 80 +++---- .../jspecify/mismatchmessage/PathTests.java | 164 ++++++------- .../mismatchmessage/SourceFixTests.java | 220 +++++++++--------- .../SummaryAndNumberingTests.java | 102 ++++---- ...eFixTests.java => TargetTypeFixTests.java} | 100 ++++---- .../mismatchmessage/TraversalCostTests.java | 20 +- .../mismatchmessage/ViewedSourceTests.java | 116 ++++----- .../nullaway/CustomLibraryModelsTests.java | 24 +- 32 files changed, 812 insertions(+), 784 deletions(-) rename nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/{RequiredTypeFixTests.java => TargetTypeFixTests.java} (64%) diff --git a/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java b/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java index 47ce10f415..a6c700e578 100644 --- a/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java +++ b/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java @@ -293,9 +293,9 @@ class Test { void testCall() { ParameterAnnotation.takesNullableArray(nonNullArray); ParameterAnnotation.takesNullableArray(nullableArray); - // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable String where target requires String ParameterAnnotation.takesNullableArray(nullableElements); - // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable String where target requires String ParameterAnnotation.takesNullableArray(nullableArrayAndElements); ParameterAnnotation.takesNullableElements(nonNullArray); ParameterAnnotation.takesNullableElements(nullableElements); @@ -339,12 +339,12 @@ void test() { } int nullableElementsLength = ReturnAnnotation.returnNullableElements().length; - // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable String where target requires String String[] nullableElements = ReturnAnnotation.returnNullableElements(); // BUG: Diagnostic contains: dereferenced expression 'ReturnAnnotation.returnNullableArrayAndElements()' is @Nullable int nullableArrayAndElementsLength = ReturnAnnotation.returnNullableArrayAndElements().length; - // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable String where target requires String String @Nullable [] nullableArrayAndElements = ReturnAnnotation.returnNullableArrayAndElements(); } @@ -381,7 +381,7 @@ void test() { int nullableComponentArraysLength = ReturnAnnotation.returnNullableComponentArrays2D().length; - // BUG: Diagnostic contains: incompatible nullability in array element: found String @Nullable [], required String [] + // BUG: Diagnostic contains: incompatible nullability in array element: source has String @Nullable [] where target requires String [] String[][] nullableComponentArrays = ReturnAnnotation.returnNullableComponentArrays2D(); // TODO: This should report a nullable dereference. NullAway currently loses the @@ -391,7 +391,7 @@ void test() { // BUG: Diagnostic contains: dereferenced expression 'ReturnAnnotation.returnNullableOuterAndComponentArrays2D()' is @Nullable int nullableOuterAndComponentArraysLength = ReturnAnnotation.returnNullableOuterAndComponentArrays2D().length; - // BUG: Diagnostic contains: incompatible nullability in array element: found String @Nullable [], required String [] + // BUG: Diagnostic contains: incompatible nullability in array element: source has String @Nullable [] where target requires String [] String @Nullable [][] nullableOuterAndComponentArrays = ReturnAnnotation.returnNullableOuterAndComponentArrays2D(); } @@ -656,21 +656,21 @@ public void loadLibraryModuleMethodReturnTypeNestedAnnotation() { class Test { void testCall() { // -- Type argument nullability - // BUG: Diagnostic contains: incompatible nullability in List type argument E: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in List type argument E: source has @Nullable String where target requires String List typeArg1 = ReturnAnnotation.nestedAnnotTypeArg(); List<@Nullable String> typeArg2 = ReturnAnnotation.nestedAnnotTypeArg(); // -- Array Element nullability - // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable String where target requires String String[] arrayElement1 = ReturnAnnotation.nestedAnnotArrayElement(); - // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable String where target requires String String @Nullable [] arrayElement2 = ReturnAnnotation.nestedAnnotArrayElement(); @Nullable String [] arrayElement3 = ReturnAnnotation.nestedAnnotArrayElement(); // -- mixed type nullability - // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable List<@Nullable Integer>, required List + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable List<@Nullable Integer> where target requires List List[] mixed1 = ReturnAnnotation.nestedAnnotMixed(); - // BUG: Diagnostic contains: incompatible nullability in array element -> List type argument E: found @Nullable Integer, required Integer + // BUG: Diagnostic contains: incompatible nullability in array element -> List type argument E: source has @Nullable Integer where target requires Integer @Nullable List[] mixed2 = ReturnAnnotation.nestedAnnotMixed(); - // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable List<@Nullable Integer>, required List<@Nullable Integer> + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable List<@Nullable Integer> where target requires List<@Nullable Integer> List<@Nullable Integer>[] mixed3 = ReturnAnnotation.nestedAnnotMixed(); @Nullable List<@Nullable Integer>[] mixed4 = ReturnAnnotation.nestedAnnotMixed(); } @@ -718,11 +718,11 @@ void testCall() { @Nullable List[] nonNullTypeArgMixed = (@Nullable List[]) new List[3]; // === test calls ParameterAnnotation.nestedAnnotations(nullableTypeArg, nullableArray, nullableMixed); - // BUG: Diagnostic contains: incompatible nullability in List type argument E: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in List type argument E: a type argument must match exactly; source has String where target requires @Nullable String ParameterAnnotation.nestedAnnotations(nonNullTypeArg, nullableArray, nullableMixed); ParameterAnnotation.nestedAnnotations(nullableTypeArg, nonNullArray, nullableMixed); ParameterAnnotation.nestedAnnotations(nullableTypeArg, nullableArray, nonNullArrayMixed); - // BUG: Diagnostic contains: incompatible nullability in array element -> List type argument E: a type argument must match exactly; found Integer, required @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in array element -> List type argument E: a type argument must match exactly; source has Integer where target requires @Nullable Integer ParameterAnnotation.nestedAnnotations(nullableTypeArg, nullableArray, nonNullTypeArgMixed); } } 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 c99f7f8091..bbd862a863 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -38,11 +38,11 @@ * Map}, the text reads: * *

- * incompatible nullability in Map type argument K -> wildcard upper bound: found @Nullable Object, required Object
- *     found:    Map<?, String>
- *                   ^
- *     required: Map<? extends Object, String>
- *                             ^^^^^^
+ * incompatible nullability in Map type argument K -> wildcard upper bound: source has @Nullable Object where target requires Object
+ *     source: Map<?, String>
+ *                 ^
+ *     target: Map<? extends Object, String>
+ *                           ^^^^^^
  *     note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter K of Map
  *     fix: declare m as Map<? extends Object, String>
  * 
@@ -55,13 +55,14 @@ * *

The vocabulary

* - *

Each line opens with a key that means the same thing wherever it appears: {@code found} is the - * source type, {@code found as} the supertype of it the check compared, {@code required} the target - * type, {@code path} where in the type one difference sits, {@code note} a fact about the source - * that its printed form does not show, and {@code fix} a declaration whose rewritten type the check - * accepts. Where there are several differences, each gets a numbered entry with its own {@code - * path}, {@code found}, and {@code required}, five at most, and {@code and N more, not listed} - * counts the rest. + *

Each line opens with a key that means the same thing wherever it appears: {@code source} is + * the source type, {@code source viewed as} the supertype of it the check compared, {@code target} + * the target type, {@code path} where in the type one difference sits, {@code note} a fact about + * the source that its printed form does not show, and {@code fix} a declaration whose rewritten + * type the check accepts. Where there are several differences, each gets a numbered entry with its + * own {@code path}, {@code source}, and {@code target}, five at most, and {@code and N more, not + * listed} counts the rest. The keys of the type lines are padded to one width, so the types of one + * message start in the same column. * *

The first line

* @@ -72,8 +73,8 @@ * 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. - * Where the target bounds a {@code ? super} wildcard, the required side reads {@code a supertype - * of} that bound. + * Where the target bounds a {@code ? super} wildcard, the target side reads {@code a supertype of} + * that bound. * *

Where the check records no position, the message is the two types and the subtype relation * between them, opening {@code incompatible types:}, which is all that can be said about a @@ -91,9 +92,9 @@ * {@code class Sub extends Base>}, viewing a {@code Sub} as a {@code Base} * rebuilds the {@code List<@Nullable String>} from the declaration of {@code Sub}, which the * written type does not hold. Where the source is viewed as a supertype at the root and the node is - * not in the written type, that view is printed as {@code found as} and carries the carets. Below - * the root, as for an element of {@code List}, no view is printed, and such a node gets no - * source caret. Two differences below one printed node share its caret, numbered for each. + * not in the written type, that view is printed as {@code source viewed as} and carries the carets. + * Below the root, as for an element of {@code List}, no view is printed, and such a node gets + * no source caret. Two differences below one printed node share its caret, numbered for each. * *

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, including one the supertype view carried over @@ -117,13 +118,12 @@ * *

The two candidates differ in what they presume. Writing an explicit bound on a wildcard the * source declaration already writes is a mechanical fix 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. + * it works. Changing the target 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 target 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 target 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 fix also has to survive printing. The printer shows {@code @Nullable} and drops every other * type-use annotation, and it writes the dimensions of a nested array in the reverse of the order a @@ -148,6 +148,25 @@ final class NullabilityMismatchMessage { /** How many mismatches a message lists before it says only how many more there are. */ private static final int MAX_LISTED_MISMATCHES = 5; + /** + * The key of the line that prints the source type, and of the source node in a numbered entry. + */ + private static final String SOURCE_LABEL = "source"; + + /** The key of the line that prints the supertype of the source type the check compared. */ + private static final String VIEWED_SOURCE_LABEL = "source viewed as"; + + /** + * The key of the line that prints the target type, and of the target node in a numbered entry. + */ + private static final String TARGET_LABEL = "target"; + + /** + * The width the keys of the type lines are padded to where no viewed source is printed: the + * length of {@link #SOURCE_LABEL} and {@link #TARGET_LABEL}, which is the same. + */ + private static final int TYPE_LABEL_WIDTH = SOURCE_LABEL.length(); + /** * The text of a diagnostic and the fixes to attach to it. * @@ -164,26 +183,26 @@ record Report(String message, List fixes) {} *

Where the check records no rejected position, 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 lhsType the required type - * @param rhsType the type found - * @param requiredTypeDeclaration the declaration of a variable whose type is {@code lhsType} - * where the diagnostic is reported at it, which admits a fix of the required type; {@code - * null} elsewhere - * @param sourceExpression the expression whose type is {@code rhsType}, which admits a fix of the - * declaration it names; {@code null} where there is none + * @param targetType the type the pseudo-assignment assigns to + * @param sourceType the type of the value assigned + * @param targetTypeDeclaration the declaration of a variable whose type is {@code targetType} + * where the diagnostic is reported at it, which admits a fix of the target type; {@code null} + * elsewhere + * @param sourceExpression the expression whose type is {@code sourceType}, which admits a fix of + * the declaration it names; {@code null} where there is none */ Report build( - Type lhsType, - Type rhsType, - @Nullable VariableTree requiredTypeDeclaration, + Type targetType, + Type sourceType, + @Nullable VariableTree targetTypeDeclaration, @Nullable ExpressionTree sourceExpression) { - NullabilityMismatches recorded = new NullabilityMismatches(lhsType, rhsType); + NullabilityMismatches recorded = new NullabilityMismatches(targetType, sourceType); new CheckIdenticalNullabilityVisitor(state, checks, config, handler, recorded) - .isSubtype(lhsType, rhsType); + .isSubtype(targetType, sourceType); List mismatches = recorded.mismatches(); if (mismatches.isEmpty()) { return new Report( - plainIncompatibleTypesMessage(lhsType, rhsType), + plainIncompatibleTypesMessage(targetType, sourceType), List.of()); // diff-coverage: ignore -- every false result of the visitor comes from a // reject call, so a rejection records a position } @@ -193,22 +212,27 @@ Report build( : mismatches; boolean numbered = listed.size() > 1; StringBuilder message = new StringBuilder(summaryLine(mismatches)); - MarkedType found = + MarkedType source = markedTypeLines( - "found", - rhsType, + SOURCE_LABEL, + TYPE_LABEL_WIDTH, + sourceType, carets(listed, NullabilityMismatches.Mismatch::sourceCaret), numbered); Type viewedSource = sharedView(listed); - if (found.marksPlaced() == listed.size() || viewedSource == null) { - message.append(found.lines()); + int labelWidth = TYPE_LABEL_WIDTH; + if (source.marksPlaced() == listed.size() || viewedSource == null) { + message.append(source.lines()); } else { // a node the check compared is at no position of the type the reader wrote, so the view of // it the check did compare is printed too and carries the carets - message.append(markedTypeLines("found", rhsType, List.of(), numbered).lines()); + labelWidth = VIEWED_SOURCE_LABEL.length(); + message.append( + markedTypeLines(SOURCE_LABEL, labelWidth, sourceType, List.of(), numbered).lines()); message.append( markedTypeLines( - "found as", + VIEWED_SOURCE_LABEL, + labelWidth, viewedSource, carets( listed, @@ -223,8 +247,9 @@ Report build( } message.append( markedTypeLines( - "required", - lhsType, + TARGET_LABEL, + labelWidth, + targetType, carets(listed, NullabilityMismatches.Mismatch::targetCaret), numbered) .lines()); @@ -240,20 +265,20 @@ Report build( "%s\n and %d more, not listed", separator, mismatches.size() - listed.size())); } List fixes = new ArrayList<>(); - VariableTree sourceDeclaration = sourceDeclaration(sourceExpression, rhsType); + VariableTree sourceDeclaration = sourceDeclaration(sourceExpression, sourceType); if (sourceDeclaration != null) { - Type rewrittenSourceType = sourceTypeFix(lhsType, rhsType, mismatches); + Type rewrittenSourceType = sourceTypeFix(targetType, sourceType, mismatches); if (rewrittenSourceType != null) { message.append(separator); appendFix(message, fixes, sourceDeclaration, rewrittenSourceType); separator = ""; } } - if (requiredTypeDeclaration != null) { - Type rewrittenTargetType = targetTypeFix(lhsType, rhsType, mismatches); + if (targetTypeDeclaration != null) { + Type rewrittenTargetType = targetTypeFix(targetType, sourceType, mismatches); if (rewrittenTargetType != null) { message.append(separator); - appendFix(message, fixes, requiredTypeDeclaration, rewrittenTargetType); + appendFix(message, fixes, targetTypeDeclaration, rewrittenTargetType); } } return new Report(message.toString(), fixes); @@ -364,22 +389,23 @@ private boolean hasNullableModifier(VariableTree declaration) { * 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); + private String plainIncompatibleTypesMessage(Type targetType, Type sourceType) { + String prettySourceType = GenericsChecks.prettyTypeForError(sourceType, state); + String prettyTargetType = GenericsChecks.prettyTypeForError(targetType, 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); + "incompatible types: %s cannot be converted to %s", prettySourceType, prettyTargetType); + if (!ASTHelpers.isSameType(targetType, sourceType, state) + && targetType.getKind() == TypeKind.DECLARED + && sourceType.getKind() == TypeKind.DECLARED + && targetType.asElement() instanceof Symbol.ClassSymbol classSymbol) { + Type asSuper = + TypeSubstitutionUtils.asSuper(state.getTypes(), sourceType, classSymbol, config); if (asSuper != null) { result += String.format( " (%s is a subtype of %s)", - prettyRhsType, GenericsChecks.prettyTypeForError(asSuper, state)); + prettySourceType, GenericsChecks.prettyTypeForError(asSuper, state)); } } return result; @@ -398,7 +424,7 @@ private String summaryLine(List mismatches) { : String.format( "%s and %d other position%s", first.path().describe(), others, others == 1 ? "" : "s"); - // a non-null type argument where a @Nullable one is required reads as a false subtype claim, + // a non-null type argument where the target has a @Nullable one reads as a false subtype claim, // since every String is a @Nullable String; what fails is that a type argument has to match String exactly = first.relation() == NullabilityMismatches.Relation.SAME @@ -407,18 +433,18 @@ private String summaryLine(List mismatches) { ? "a type argument must match exactly; " : ""; return String.format( - "incompatible nullability in %s: %sfound %s, required %s", + "incompatible nullability in %s: %ssource has %s where target requires %s", where, exactly, GenericsChecks.prettyTypeForError(first.sourceNode(), state), - required(first)); + targetRequirement(first)); } /** - * Names what the check required of the source at {@code mismatch}: the target node, or for the + * Names what the target requires of the source at {@code mismatch}: the target node, or for the * lower bound of a {@code ? super} wildcard, a supertype of it. */ - private String required(NullabilityMismatches.Mismatch mismatch) { + private String targetRequirement(NullabilityMismatches.Mismatch mismatch) { String target = GenericsChecks.prettyTypeForError(mismatch.targetNode(), state); return mismatch.relation() == NullabilityMismatches.Relation.SUPERTYPE ? "a supertype of " + target @@ -457,8 +483,9 @@ private String required(NullabilityMismatches.Mismatch mismatch) { } /** - * 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. + * Prints {@code type} on a line keyed {@code label}, padded to {@code labelWidth} so that the + * types of one message start in the same column, 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 @@ -466,7 +493,7 @@ private String required(NullabilityMismatches.Mismatch mismatch) { * 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 label, int labelWidth, 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(); @@ -500,7 +527,7 @@ private MarkedType markedTypeLines( padTo(numbers, start).append(String.join(",", indices)); marks += indices.size(); } - String prefix = String.format(" %-9s ", label + ":"); + String prefix = " " + padTo(new StringBuilder(label + ":"), labelWidth + 1) + " "; // 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 = @@ -545,9 +572,10 @@ private String mismatchDetail(NullabilityMismatches.Mismatch mismatch, int numbe StringBuilder detail = new StringBuilder(); if (number != 0) { detail.append("\n\n").append(header).append("path: ").append(mismatch.path().describe()); - detail.append("\n").append(body).append("found: "); + detail.append("\n").append(body).append(SOURCE_LABEL).append(": "); detail.append(GenericsChecks.prettyTypeForError(mismatch.sourceNode(), state)); - detail.append("\n").append(body).append("required: ").append(required(mismatch)); + detail.append("\n").append(body).append(TARGET_LABEL).append(": "); + detail.append(targetRequirement(mismatch)); } String note = boundOriginNote(mismatch); if (note != null) { @@ -816,11 +844,11 @@ private String mismatchDetail(NullabilityMismatches.Mismatch mismatch, int numbe new Type.StructuralTypeMapping<@Nullable Void>() { @Override public Type visitWildcardType(Type.WildcardType t, @Nullable Void unused) { - Type requiredBound = boundForWildcard.get(t); - return requiredBound == null + Type targetBound = boundForWildcard.get(t); + return targetBound == null ? super.visitWildcardType(t, null) : new Type.WildcardType( - requiredBound, BoundKind.EXTENDS, Symtab.instance(state.context).boundClass); + targetBound, BoundKind.EXTENDS, Symtab.instance(state.context).boundClass); } }, null); diff --git a/nullaway/src/test/java/com/uber/nullaway/JSpecifyJDKModelsTest.java b/nullaway/src/test/java/com/uber/nullaway/JSpecifyJDKModelsTest.java index 256316736e..253a9d654b 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 nullability in Collection type argument E -> wildcard upper bound: found @Nullable String, required Object + // BUG: Diagnostic contains: incompatible nullability in Collection type argument E -> wildcard upper bound: source has @Nullable String where target requires Object return ownExtendsObject(collection); } } @@ -513,7 +513,7 @@ class Test { return list.toArray(); } static Object[] invalidCall(List list) { - // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable Object where target requires Object return list.toArray(); } static class DelegatingList extends AbstractList { diff --git a/nullaway/src/test/java/com/uber/nullaway/ParameterAssignmentTests.java b/nullaway/src/test/java/com/uber/nullaway/ParameterAssignmentTests.java index af9acdafe8..9b438ca395 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 nullability in List type argument E: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in List type argument E: source has @Nullable String where target requires 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 nullability in array element: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable String where target requires String p = q; } void matchingArrayElementTypesAreAllowed(@Nullable String[] p, @Nullable String[] q) { 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 66821145f4..c1f9077d41 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 nullability in NullableTypeParam type argument E: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in NullableTypeParam type argument E: source has @Nullable String where target requires 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 nullability in NullableTypeParam type argument E: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in NullableTypeParam type argument E: a type argument must match exactly; source has String where target requires @Nullable String NullableTypeParam.staticField = t1; - // BUG: Diagnostic contains: incompatible nullability in NullableTypeParam type argument E: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in NullableTypeParam type argument E: source has @Nullable String where target requires 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 nullability in NullableTypeParam type argument E: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in NullableTypeParam type argument E: a type argument must match exactly; source has String where target requires @Nullable String GenericTypeArgMethods.nullableTypeParamArg(t1); - // BUG: Diagnostic contains: incompatible nullability in NullableTypeParam type argument E: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in NullableTypeParam type argument E: source has @Nullable String where target requires 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 c7ee49cedb..e3c312b55d 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 nullability in Foo type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: source has @Nullable String where target requires String Bar b = new Bar<>(Foo.makeNullableStr()); - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: found @Nullable Void, required Void + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: source has @Nullable Void where target requires 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 nullability in Foo type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: source has @Nullable String where target requires String return new Bar<>(Foo.makeNullableStr()); } } @@ -139,7 +139,7 @@ void testNegative() { takeNullableVoid(new Bar<>(Foo.make())); } void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: source has @Nullable String where target requires String takeStr(new Bar<>(Foo.makeNullableStr())); } } @@ -172,7 +172,7 @@ static class Bar { return (new Bar<>(Foo.make())); } Bar testPositive() { - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: source has @Nullable String where target requires 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 nullability in Foo type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: source has @Nullable String where target requires 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 nullability in Foo type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: source has @Nullable String where target requires String return new Bar<>(Foo.makeNullableStr()) {}; } void paramNegative() { takeNullableVoid(new Bar<>(Foo.make()) {}); } void paramPositive() { - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: source has @Nullable String where target requires 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 nullability in Foo type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: source has @Nullable String where target requires String new Bar<>(f1, f2); } } @@ -471,7 +471,7 @@ static void testNegative() { takeFooNullableString(id(new FooImpl<>(makeNullableFoo()))); } static void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: source has @Nullable String where target requires 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 nullability in Foo type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: source has @Nullable String where target requires String return new Box<>(id(makeNullableFoo())); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInferenceErrorReportingTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInferenceErrorReportingTests.java index 6b00b90a29..4fcefad8f3 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 nullability in array element: found @Nullable E, required E + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable E where target requires E return Arrays.copyOf(original, original.length); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java index f46862872b..9d70370643 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java @@ -245,7 +245,7 @@ static class Sub extends Outer<@Nullable S> {} > void nullableThroughBound(Y y) { // BUG: Diagnostic contains: dereferenced expression 'y.get()' is @Nullable y.get().hashCode(); - // BUG: Diagnostic contains: incompatible nullability in Outer type argument O: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Outer type argument O: source has @Nullable String where target requires String Outer nonNull = y; Outer<@Nullable String> nullable = y; y.new Inner(null); @@ -272,7 +272,7 @@ > void nonNullThroughBoundOfBound(Z z) { void nullableThroughCapturedWildcard(List> l) { // BUG: Diagnostic contains: dereferenced expression 'l.get(0).get()' is @Nullable l.get(0).get().hashCode(); - // BUG: Diagnostic contains: incompatible nullability in Outer type argument O: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Outer type argument O: source has @Nullable String where target requires String Outer nonNull = l.get(0); Outer<@Nullable String> nullable = l.get(0); } @@ -361,7 +361,7 @@ static class ListFuture } static MyFuture> invalid() { - // BUG: Diagnostic contains: incompatible nullability in MyFuture type argument T -> List type argument E: found @Nullable V, required V + // BUG: Diagnostic contains: incompatible nullability in MyFuture type argument T -> List type argument E: source has @Nullable V where target requires 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 nullability in List type argument E: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in List type argument E: source has @Nullable String where target requires String List invalid = box.get(); box.set(nullableList); - // BUG: Diagnostic contains: incompatible nullability in List type argument E: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in List type argument E: a type argument must match exactly; source has String where target requires @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 nullability in List type argument E: found @Nullable O, required O + // BUG: Diagnostic contains: incompatible nullability in List type argument E: source has @Nullable O where target requires O List invalid = child.get(); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericLambdaTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericLambdaTests.java index 4e8392d3af..2489e6323d 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 nullability in List type argument E: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in List type argument E: source has @Nullable String where target requires String MarkedListSupplier s = () -> l; } void blockBodyToMarkedInterface(List<@Nullable String> l) { - // BUG: Diagnostic contains: incompatible nullability in List type argument E: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in List type argument E: source has @Nullable String where target requires 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 d80bccfc54..eb4ebf08e1 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 nullability in Box type argument T: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in Box type argument T: a type argument must match exactly; source has String where target requires @Nullable String acceptsNullable(flat); } @@ -1337,7 +1337,7 @@ void testNegative() { receiver(makeCancelable(this::target)); } void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in Callback type argument T: a type argument must match exactly; found Object, required @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in Callback type argument T: a type argument must match exactly; source has Object where target requires @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 cfb298c8bc..261ec2c674 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java @@ -559,9 +559,9 @@ interface B { X b(); } id1(value).a().length(); A<@Nullable String> nullableA = id1(value); B nonNullB = id1(value); - // BUG: Diagnostic contains: incompatible nullability in A type argument X: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument X: source has @Nullable String where target requires String A nonNullA = id1(value); - // BUG: Diagnostic contains: incompatible nullability in B type argument X: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in B type argument X: a type argument must match exactly; source has String where target requires @Nullable String B<@Nullable String> nullableB = id1(value); } @@ -572,9 +572,9 @@ interface B { X b(); } id2(value).a().length(); A<@Nullable String> nullableA = id2(value); B nonNullB = id2(value); - // BUG: Diagnostic contains: incompatible nullability in A type argument X: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument X: source has @Nullable String where target requires String A nonNullA = id2(value); - // BUG: Diagnostic contains: incompatible nullability in B type argument X: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in B type argument X: a type argument must match exactly; source has String where target requires @Nullable String B<@Nullable String> nullableB = id2(value); } @@ -585,9 +585,9 @@ interface B { X b(); } id3(value).a().length(); A<@Nullable String> nullableA = id3(value); B nonNullB = id3(value); - // BUG: Diagnostic contains: incompatible nullability in A type argument X: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument X: source has @Nullable String where target requires String A nonNullA = id3(value); - // BUG: Diagnostic contains: incompatible nullability in B type argument X: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in B type argument X: a type argument must match exactly; source has String where target requires @Nullable String B<@Nullable String> nullableB = id3(value); } @@ -598,9 +598,9 @@ interface B { X b(); } id4(value).a().length(); A<@Nullable String> nullableA = id4(value); B nonNullB = id4(value); - // BUG: Diagnostic contains: incompatible nullability in A type argument X: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument X: source has @Nullable String where target requires String A nonNullA = id4(value); - // BUG: Diagnostic contains: incompatible nullability in B type argument X: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in B type argument X: a type argument must match exactly; source has String where target requires @Nullable String B<@Nullable String> nullableB = id4(value); } } @@ -634,9 +634,9 @@ static class Box1> & B>> { box.get().a().get(0).length(); A> nullableA = box.get(); B> nonNullB = box.get(); - // BUG: Diagnostic contains: incompatible nullability in A type argument X -> List type argument E: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument X -> List type argument E: source has @Nullable String where target requires String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible nullability in B type argument X -> List type argument E: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in B type argument X -> List type argument E: a type argument must match exactly; source has String where target requires @Nullable String B> nullableB = box.get(); } @@ -652,9 +652,9 @@ static class Box2> & A>> { box.get().a().get(0).length(); A> nullableA = box.get(); B> nonNullB = box.get(); - // BUG: Diagnostic contains: incompatible nullability in A type argument X -> List type argument E: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument X -> List type argument E: source has @Nullable String where target requires String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible nullability in B type argument X -> List type argument E: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in B type argument X -> List type argument E: a type argument must match exactly; source has String where target requires @Nullable String B> nullableB = box.get(); } @@ -670,9 +670,9 @@ static class Box3> & B>> box.get().a().get(0).length(); A> nullableA = box.get(); B> nonNullB = box.get(); - // BUG: Diagnostic contains: incompatible nullability in A type argument X -> List type argument E: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument X -> List type argument E: source has @Nullable String where target requires String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible nullability in B type argument X -> List type argument E: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in B type argument X -> List type argument E: a type argument must match exactly; source has String where target requires @Nullable String B> nullableB = box.get(); } @@ -688,9 +688,9 @@ static class Box4> & A>> box.get().a().get(0).length(); A> nullableA = box.get(); B> nonNullB = box.get(); - // BUG: Diagnostic contains: incompatible nullability in A type argument X -> List type argument E: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument X -> List type argument E: source has @Nullable String where target requires String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible nullability in B type argument X -> List type argument E: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in B type argument X -> List type argument E: a type argument must match exactly; source has String where target requires @Nullable String B> nullableB = box.get(); } } @@ -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 nullability in Foo type argument T: a type argument must match exactly; found Object, required @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: a type argument must match exactly; source has Object where target requires @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 nullability in Foo type argument T: a type argument must match exactly; found Object, required @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: a type argument must match exactly; source has Object where target requires @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 nullability in Foo type argument V -> ArrayList type argument E: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument V -> ArrayList type argument E: a type argument must match exactly; source has String where target requires @Nullable String Foo> fooNonNull_2 = f.nonNullTest(); - // BUG: Diagnostic contains: incompatible nullability in Foo type argument K: a type argument must match exactly; found Integer, required @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in Foo type argument K: a type argument must match exactly; source has Integer where target requires @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 nullability in Foo type argument T -> array element -> Foo type argument T: a type argument must match exactly; found Object, required @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> array element -> Foo type argument T: a type argument must match exactly; source has Object where target requires @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 nullability in array element -> Foo type argument T: a type argument must match exactly; found Object, required @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in array element -> Foo type argument T: a type argument must match exactly; source has Object where target requires @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 nullability in Bar type argument T -> Bar type argument T: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in Bar type argument T -> Bar type argument T: a type argument must match exactly; source has String where target requires @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 nullability in Function type argument T and 1 other position: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in Function type argument T and 1 other position: a type argument must match exactly; source has String where target requires @Nullable String 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 nullability in Foo type argument T: a type argument must match exactly; found Object, required @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: a type argument must match exactly; source has Object where target requires @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 nullability in Foo type argument T: a type argument must match exactly; found Object, required @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: a type argument must match exactly; source has Object where target requires @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 nullability in Foo type argument T: a type argument must match exactly; found Object, required @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: a type argument must match exactly; source has Object where target requires @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 nullability in array element: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable String where target requires 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 nullability in array element: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable String where target requires String stringField = f(arr2, "hi"); } } @@ -2242,11 +2242,11 @@ public void capturedTypeAtNullUnmarkedBoundary() { message -> message.contains( """ - incompatible nullability in Foo type argument T -> wildcard upper bound: found @Nullable Object, required Object - found: Foo - ^^^^^^^^^^^^ - required: Foo - ^ + incompatible nullability in Foo type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object + source: Foo + ^^^^^^^^^^^^ + target: Foo + ^ note: the source wildcard is the type argument for type parameter T of Box, and Box is unannotated """)) .addSourceLines( @@ -2290,11 +2290,11 @@ public void capturedTypeGetsDirectNullableAnnotationFromTypeVariableUse() { message -> message.contains( """ - incompatible nullability in Foo type argument T -> wildcard upper bound: found @Nullable Object, required Object - found: Foo<@Nullable capture of ?> - ^^^^^^^^^^^^^^^^^^^^^^ - required: Foo - ^^^^^^ + incompatible nullability in Foo type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object + source: Foo<@Nullable capture of ?> + ^^^^^^^^^^^^^^^^^^^^^^ + target: Foo + ^^^^^^ note: the source wildcard is the type argument for type parameter T of Holder """)) .addSourceLines( @@ -2450,7 +2450,7 @@ class Test { class Box {} void swapBoxes(Box box1, Box box2) {} void testPositive(Box box1, Box<@Nullable String> box2) { - // BUG: Diagnostic contains: incompatible nullability in Box type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Box type argument T: source has @Nullable String where target requires String swapBoxes(box1, box2); } void TestNegative(Box<@Nullable String> box1, Box<@Nullable String> box2) { @@ -2545,7 +2545,7 @@ Supplier make2() { } // tests that our repair computes a consistent substitution for the type variables void test2() { - // BUG: Diagnostic contains: incompatible nullability in Supplier type argument T: a type argument must match exactly; found OuterT, required @Nullable OuterT + // BUG: Diagnostic contains: incompatible nullability in Supplier type argument T: a type argument must match exactly; source has OuterT where target requires @Nullable OuterT acceptTwoSup(sup, sup2); } } @@ -2677,7 +2677,7 @@ static class Foo { .or(new Foo<@Nullable String>()); // a true positive case - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: source has @Nullable String where target requires String static Foo WRONG = Foo.of(new Foo<@Nullable String>()).or(new Foo<@Nullable String>()); } @@ -2733,7 +2733,7 @@ class Test { static class Box {} static void accept(Box<@Nullable T> box) {} void test(Box> box) { - // BUG: Diagnostic contains: incompatible nullability in Box type argument T: a type argument must match exactly; found CompletableFuture, required @Nullable CompletableFuture + // BUG: Diagnostic contains: incompatible nullability in Box type argument T: a type argument must match exactly; source has CompletableFuture where target requires @Nullable CompletableFuture accept(box); } } @@ -3346,9 +3346,9 @@ class GInner { return x; } void nullableQualifier(Outer<@Nullable String> o) { - // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Outer type argument O: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Outer type argument O: source has @Nullable String where target requires String id(o.new Inner("")); - // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Outer type argument O: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Outer type argument O: source has @Nullable String where target requires 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 75ef763cc4..88c18c8b69 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 nullability in List type argument E: found @Nullable Void, required Void + // BUG: Diagnostic contains: incompatible nullability in List type argument E: source has @Nullable Void where target requires 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 nullability in List type argument E: found @Nullable Void, required Void + // BUG: Diagnostic contains: incompatible nullability in List type argument E: source has @Nullable Void where target requires 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 6853d79a99..f4710616bc 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 nullability in NonNullTypeParam type argument E: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in NonNullTypeParam type argument E: source has @Nullable String where target requires String new NonNullTypeParam< // BUG: Diagnostic contains: Generic type parameter @Nullable String>()); @@ -229,7 +229,7 @@ class Test { static class Holder {} static void typeArguments() { Holder other = new Holder<@Other String>(); - // BUG: Diagnostic contains: incompatible nullability in Holder type argument E: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Holder type argument E: source has @Nullable String where target requires String Holder otherThenNullable = new Holder<@Other @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 nullability in enclosing type -> Wrapper type argument P: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Wrapper type argument P: source has @Nullable String where target requires String param(x); } static void positiveAssign() { Wrapper<@Nullable String>.Fn p1 = null; - // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Wrapper type argument P: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Wrapper type argument P: source has @Nullable String where target requires String Wrapper.Fn p2 = p1; } static Wrapper.@Nullable Fn positiveReturn() { Wrapper<@Nullable String>.Fn p1 = null; - // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Wrapper type argument P: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Wrapper type argument P: source has @Nullable String where target requires String return p1; } static void negativeParam() { @@ -349,13 +349,13 @@ void callOnResult() { } public void testPositive() { addCallback( - // BUG: Diagnostic contains: incompatible nullability in Callback type argument T: a type argument must match exactly; found Integer, required @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in Callback type argument T: a type argument must match exactly; source has Integer where target requires @Nullable Integer new Callback() { @Override public void onResult(Integer value) { - // BUG: Diagnostic contains: incompatible nullability in Callback type argument T: a type argument must match exactly; found Integer, required @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in Callback type argument T: a type argument must match exactly; source has Integer where target requires @Nullable Integer removeCallback(this); - // BUG: Diagnostic contains: incompatible nullability in Callback type argument T: a type argument must match exactly; found Integer, required @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in Callback type argument T: a type argument must match exactly; source has Integer where target requires @Nullable Integer Callback<@Nullable Integer> self = this; } void callOnResult() { @@ -457,7 +457,7 @@ public void genericsChecksForAssignments() { class Test { static class NullableTypeParam {} static void testPositive(NullableTypeParam<@Nullable String> t1) { - // BUG: Diagnostic contains: incompatible nullability in NullableTypeParam type argument E: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in NullableTypeParam type argument E: source has @Nullable String where target requires 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 nullability in NullableTypeParam type argument E: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in NullableTypeParam type argument E: source has @Nullable String where target requires 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 nullability in SampleClassMultipleArguments type argument E1 -> SampleClass type argument E -> SampleClass type argument E: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in SampleClassMultipleArguments type argument E1 -> SampleClass type argument E -> SampleClass type argument E: a type argument must match exactly; source has String where target requires @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 nullability in Fn type argument R: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Fn type argument R: source has @Nullable String where target requires 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 nullability in Fn2 type argument P: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in Fn2 type argument P: a type argument must match exactly; source has String where target requires @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 nullability in SuperClassC type argument P1: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in SuperClassC type argument P1: a type argument must match exactly; source has String where target requires @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 nullability in D type argument P: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in D type argument P: source has @Nullable String where target requires String D f1 = new B<@Nullable String>(); - // BUG: Diagnostic contains: incompatible nullability in D type argument P: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in D type argument P: source has @Nullable String where target requires 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 nullability in Super type argument A and 1 other position: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in Super type argument A and 1 other position: a type argument must match exactly; source has String where target requires @Nullable String 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 nullability in D type argument P -> C type argument P: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in D type argument P -> C type argument P: source has @Nullable String where target requires String D> f1 = new B>(); - // BUG: Diagnostic contains: incompatible nullability in A type argument P: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument P: source has @Nullable String where target requires String A, String> f2 = new A, @Nullable String>(); - // BUG: Diagnostic contains: incompatible nullability in D type argument P: found Test.@Nullable C, required Test.C + // BUG: Diagnostic contains: incompatible nullability in D type argument P: source has Test.@Nullable C where target requires 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 nullability in A type argument T1: a type argument must match exactly; found Object, required @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in A type argument T1: a type argument must match exactly; source has Object where target requires @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 nullability in A type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument T: source has @Nullable String where target requires String return new A<@Nullable String>(); } static A<@Nullable String> testPositive2() { - // BUG: Diagnostic contains: incompatible nullability in A type argument T: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in A type argument T: a type argument must match exactly; source has String where target requires @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 nullability in A type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument T: source has @Nullable String where target requires 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 nullability in A type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument T: source has @Nullable String where target requires 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 nullability in A type argument T -> A type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument T -> A type argument T: source has @Nullable String where target requires String A a = sampleMethod1(a1, a2); } static void testPositive2(A> a1, A a2) { - // BUG: Diagnostic contains: incompatible nullability in A type argument T -> A type argument T: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in A type argument T -> A type argument T: a type argument must match exactly; source has String where target requires @Nullable String A a = sampleMethod2(a1, a2); } static void testPositive3(A a1) { - // BUG: Diagnostic contains: incompatible nullability in A type argument T: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in A type argument T: a type argument must match exactly; source has String where target requires @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 nullability in A type argument T: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in A type argument T: a type argument must match exactly; source has String where target requires @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 nullability in A type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument T: source has @Nullable String where target requires String A<@Nullable String> b = sampleMethodWithVarArgs(a1); - // BUG: Diagnostic contains: incompatible nullability in A type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument T: source has @Nullable String where target requires 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 nullability in array element -> A type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in array element -> A type argument T: source has @Nullable String where target requires 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 nullability in A type argument T -> array element -> A type argument T: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in A type argument T -> array element -> A type argument T: a type argument must match exactly; source has String where target requires @Nullable String A[]> var1 = new A[]>(); - // BUG: Diagnostic contains: incompatible nullability in A type argument T -> array element -> A type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument T -> array element -> A type argument T: source has @Nullable String where target requires 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 nullability in A type argument T -> array element -> A type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument T -> array element -> A type argument T: source has @Nullable String where target requires String A[]> var2 = new A[]>(); } } @@ -1435,7 +1435,7 @@ public void genericPrimitiveArrayTypeAssignment() { class Test { static class A { } static void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in A type argument T: a type argument must match exactly; found int [], required int @Nullable [] + // BUG: Diagnostic contains: incompatible nullability in A type argument T: a type argument must match exactly; source has int [] where target requires 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 nullability in enclosing type -> A type argument X: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> A type argument X: source has @Nullable String where target requires 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>(); @@ -2057,28 +2057,28 @@ void staticSubclassWithNullableOuterMatches(NullableInner input) { Outer<@Nullable String>.Inner result = input; } void staticSubclassWithNullableOuterMismatches(NullableInner input) { - // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Outer type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Outer type argument T: source has @Nullable String where target requires String Outer.Inner result = input; } void staticSubclassWithNonNullOuterMatches(NonNullInner input) { Outer.Inner result = input; } void staticSubclassWithNonNullOuterMismatches(NonNullInner input) { - // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Outer type argument T: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Outer type argument T: a type argument must match exactly; source has String where target requires @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 nullability in enclosing type -> Outer type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Outer type argument T: source has @Nullable String where target requires 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 nullability in enclosing type -> Outer type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Outer type argument T: source has @Nullable String where target requires String Outer.Inner result = input; } } @@ -3033,7 +3033,7 @@ static class B implements A<@Nullable String>, Serializable {} static class C implements A, Serializable {} static void test1(Object o) { var x = (A & Serializable) o; - // BUG: Diagnostic contains: found as: A<@Nullable String> + // BUG: Diagnostic contains: source viewed as: A<@Nullable String> x = new B(); // ok x = new C(); @@ -3041,7 +3041,7 @@ static void test1(Object o) { static void test2(Object o) { var x = (A<@Nullable String> & Serializable) o; x = new B(); - // BUG: Diagnostic contains: incompatible nullability in A type argument T: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in A type argument T: a type argument must match exactly; source has String where target requires @Nullable String x = new C(); } } @@ -3138,7 +3138,7 @@ void testNegative(Function<@Nullable V, @Nullable V> f) { foo(f); } void testPositive(Function f) { - // BUG: Diagnostic contains: incompatible nullability in Function type argument T and 1 other position: a type argument must match exactly; found V, required @Nullable V + // BUG: Diagnostic contains: incompatible nullability in Function type argument T and 1 other position: a type argument must match exactly; source has V where target requires @Nullable V 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 nullability in array element -> Function type argument T and 1 other position: a type argument must match exactly; found V, required @Nullable V + // BUG: Diagnostic contains: incompatible nullability in array element -> Function type argument T and 1 other position: a type argument must match exactly; source has V where target requires @Nullable V 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 nullability in Function type argument T and 1 other position: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Function type argument T and 1 other position: source has @Nullable String where target requires String this.<@Nullable String>foo(f); } void testPositiveArray(Function f) { - // BUG: Diagnostic contains: incompatible nullability in Function type argument T and 1 other position: found String @Nullable [], required String [] + // BUG: Diagnostic contains: incompatible nullability in Function type argument T and 1 other position: source has String @Nullable [] where target requires String [] this.foo(f); } } @@ -3196,15 +3196,15 @@ void testNegative(Function f) { foo(f); } void testPositive1(Function<@Nullable V, V> f) { - // BUG: Diagnostic contains: incompatible nullability in Function type argument T and 1 other position: found @Nullable V, required V + // BUG: Diagnostic contains: incompatible nullability in Function type argument T and 1 other position: source has @Nullable V where target requires V foo(f); } void testPositive2(Function f) { - // BUG: Diagnostic contains: incompatible nullability in Function type argument R: a type argument must match exactly; found V, required @Nullable V + // BUG: Diagnostic contains: incompatible nullability in Function type argument R: a type argument must match exactly; source has V where target requires @Nullable V foo(f); } void testPositive3(Function<@Nullable V, @Nullable V> f) { - // BUG: Diagnostic contains: incompatible nullability in Function type argument T: found @Nullable V, required V + // BUG: Diagnostic contains: incompatible nullability in Function type argument T: source has @Nullable V where target requires 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 nullability in Function type argument T and 1 other position: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in Function type argument T and 1 other position: a type argument must match exactly; source has String where target requires @Nullable String bar = f; } } @@ -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 nullability in Inner type argument T: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in Inner type argument T: source has @Nullable Object where target requires Object Inner mNonNullThing = new Inner<@Nullable Object>().identity(); } """) @@ -3440,7 +3440,7 @@ private static class A { } private static class B extends A<@Nullable Object> { B(List l) { - // BUG: Diagnostic contains: incompatible nullability in List type argument E: a type argument must match exactly; found Object, required @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in List type argument E: a type argument must match exactly; source has Object where target requires @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 nullability in A type argument T: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in A type argument T: source has @Nullable Object where target requires Object A a = new B(); - // BUG: Diagnostic contains: incompatible nullability in A type argument T: a type argument must match exactly; found Object, required @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in A type argument T: a type argument must match exactly; source has Object where target requires @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 nullability in MaybeNull type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in MaybeNull type argument T: source has @Nullable String where target requires String accept(nonNull.asNullable()); MaybeNull<@Nullable String> m1 = nonNull.asNullable(); - // BUG: Diagnostic contains: incompatible nullability in MaybeNull type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in MaybeNull type argument T: source has @Nullable String where target requires 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 nullability in Foo type argument T: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: a type argument must match exactly; source has String where target requires @Nullable String Foo<@Nullable String> f1 = nullableFoo.nonNullField; Foo f2 = nullableFoo.nonNullField; Foo<@Nullable String> f3 = nonnullFoo.nullableField; - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: source has @Nullable String where target requires String Foo f4 = nonnullFoo.nullableField; } } 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 95ab83176f..f4beb5739c 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 nullability in Result type argument T -> wildcard upper bound: found @Nullable A & @Nullable B, required A + // BUG: Diagnostic contains: incompatible nullability in Result type argument T -> wildcard upper bound: source has @Nullable A & @Nullable B where target requires A return source.result(); } Result rejectsAllNullableLastComponent(AllNullable source) { - // BUG: Diagnostic contains: incompatible nullability in Result type argument T -> wildcard upper bound: found @Nullable A & @Nullable B, required B + // BUG: Diagnostic contains: incompatible nullability in Result type argument T -> wildcard upper bound: source has @Nullable A & @Nullable B where target requires B return source.result(); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java index 7a6ad346c3..cc987f04da 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java @@ -36,7 +36,7 @@ void acceptsMatchingNullableComponent(Factory factory) { } void rejectsNonNullMatchingComponent(Factory factory) { - // BUG: Diagnostic contains: incompatible nullability in A type argument E: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in A type argument E: source has @Nullable String where target requires String A result = factory.fromA().get(); } @@ -45,7 +45,7 @@ void acceptsOtherNonNullComponent(Factory factory) { } void rejectsWideningOtherInvariantComponent(Factory factory) { - // BUG: Diagnostic contains: incompatible nullability in B type argument E: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in B type argument E: a type argument must match exactly; source has String where target requires @Nullable String B<@Nullable String> result = factory.fromA().get(); } @@ -54,7 +54,7 @@ void acceptsMatchingNonNullComponent(Factory factory) { } void rejectsWideningMatchingInvariantComponent(Factory factory) { - // BUG: Diagnostic contains: incompatible nullability in B type argument E: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in B type argument E: a type argument must match exactly; source has String where target requires @Nullable String B<@Nullable String> result = factory.fromB().get(); } } 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 3304ec7291..635f9849ad 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 nullability in array element: found @Nullable Test, required Test + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable Test where target requires 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 nullability in array element: found @Nullable Test, required Test + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable Test where target requires 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 nullability in array element: found @Nullable Test, required Test + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable Test where target requires 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 nullability in array element: found @Nullable Integer, required Integer + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable Integer where target requires 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 nullability in array element: found @Nullable Integer, required Integer + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable Integer where target requires Integer x1 = new @Nullable Integer[0]; } } @@ -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 nullability in array element -> array element: found @Nullable Integer, required Integer + // BUG: Diagnostic contains: incompatible nullability in array element -> array element: source has @Nullable Integer where target requires 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 nullability in array element: found @Nullable Integer, required Integer + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable Integer where target requires 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 nullability in array element -> array element: found @Nullable Integer, required Integer + // BUG: Diagnostic contains: incompatible nullability in array element -> array element: source has @Nullable Integer where target requires Integer Integer[] @Nullable [] y4 = new @Nullable Integer[3][4]; - // BUG: Diagnostic contains: incompatible nullability in array element -> array element: found @Nullable Integer, required Integer + // BUG: Diagnostic contains: incompatible nullability in array element -> array element: source has @Nullable Integer where target requires Integer Integer[][] y1 = nullableElems2D; - // BUG: Diagnostic contains: incompatible nullability in array element -> array element -> array element: found @Nullable Integer, required Integer + // BUG: Diagnostic contains: incompatible nullability in array element -> array element -> array element: source has @Nullable Integer where target requires Integer Integer[][][] y2 = nullableElems3D; - // BUG: Diagnostic contains: incompatible nullability in array element: found Integer @Nullable [], required Integer [] + // BUG: Diagnostic contains: incompatible nullability in array element: source has Integer @Nullable [] where target requires Integer [] Integer[][] y3 = nullableInner; } } @@ -673,7 +673,7 @@ public void arraysAndGenerics() { class Test { void foo(List<@Nullable Integer[]> l) {} void testPositive(List p) { - // BUG: Diagnostic contains: incompatible nullability in List type argument E -> array element: a type argument must match exactly; found Integer, required @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in List type argument E -> array element: a type argument must match exactly; source has Integer where target requires @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 nullability in array element: found @Nullable Foo, required Foo + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable Foo where target requires Foo return result; } Foo[] getFoosNegative() { @@ -706,7 +706,7 @@ Foo[] getFoosNegative() { } void takeFoos(Foo[] foos) {} void callTakeFoosPositive(@Nullable Foo[] p) { - // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable Foo, required Foo + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable Foo where target requires 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 nullability in array element: found @Nullable Foo, required Foo + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable Foo where target requires Foo takeFoosVarargs(p); - // BUG: Diagnostic contains: incompatible nullability in array element: found @Nullable Foo, required Foo + // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable Foo where target requires Foo takeFoosVarargs(p2, p); } void callTakeFoosVarargsNegative(Foo[] p) { @@ -1390,7 +1390,7 @@ static void nullableExplicitArrayStore() { static void nullableTypeArgumentRejectedFromNonNullBoundedWildcardArray( CompletableFuture[] futures, CompletableFuture<@Nullable String> value) { - // BUG: Diagnostic contains: incompatible nullability in CompletableFuture type argument T -> wildcard upper bound: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in CompletableFuture type argument T -> wildcard upper bound: source has @Nullable String where target requires String futures[0] = value; } } @@ -1772,7 +1772,7 @@ void writeNullIntoNonNullElementOfVarLoopVariableOverNestedLocalArray() { } void assignNullableTypeArgumentElementOfLocalArray() { List<@Nullable String>[] local = new List[1]; - // BUG: Diagnostic contains: incompatible nullability in List type argument E: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in List type argument E: source has @Nullable String where target requires 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 f12d87fe59..4173fa66ce 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 nullability in List type argument E: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in List type argument E: source has @Nullable Object where target requires Object PolyNullMethods.first(nullable, nullable); } } 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 d522e81b4c..8d4f090ff0 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 nullability in NullableSibling type argument Y: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in NullableSibling type argument Y: source has @Nullable String where target requires String NullableSibling x = nullableSibling(); } void siblingWithNullableNonObjectBound() { 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 4b93d68e2a..7aaae5ad16 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 nullability in List type argument E: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in List type argument E: source has @Nullable String where target requires 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 nullability in List type argument E: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in List type argument E: source has @Nullable String where target requires String .toList(); } } 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 21d3c8ea34..c6b7e51245 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 nullability in Box type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Box type argument T: source has @Nullable String where target requires 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 b8b9fa58d2..94a7507d0b 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -319,7 +319,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 nullability in Foo type argument T -> wildcard upper bound: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: source has @Nullable String where target requires String String s = nonnullWildcard(f); // legal String s2 = nonnullWildcard(f2); @@ -348,7 +348,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 nullability in Foo type argument T -> wildcard upper bound: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: source has @Nullable String where target requires String String s = nonnullWildcard(f); s.hashCode(); } @@ -379,7 +379,7 @@ void testNegative(Foo> f) { s.hashCode(); } void testPositive(Foo> f) { - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound -> Bar type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound -> Bar type argument T: source has @Nullable String where target requires String String s = nonnullWildcard(f); s.hashCode(); } @@ -411,7 +411,7 @@ void testNegative(Foo>> f) { s.hashCode(); } void testPositive(Foo>> f) { - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound -> Bar type argument T -> Baz type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound -> Bar type argument T -> Baz type argument T: source has @Nullable String where target requires String String s = nonnullWildcard(f); s.hashCode(); } @@ -443,7 +443,7 @@ void testNegative(Foo<@Nullable Bar>> f) { s.hashCode(); } void testPositive(Foo<@Nullable Bar>> f) { - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: found Test.@Nullable Bar>, required Test.Bar> + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: source has Test.@Nullable Bar> where target requires Test.Bar> String s = nonnullWildcard(f); s.hashCode(); } @@ -473,7 +473,7 @@ void testNegative(Foo f) { s.hashCode(); } void testPositive(Foo f) { - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: source has @Nullable String where target requires String String s = nonnullWildcard(f); s.hashCode(); } @@ -496,22 +496,22 @@ class Foo {} Foo nullableField; Test(Foo f) { nullableField = f; - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: source has @Nullable String where target requires String nonnullField = f; } Foo nullableReturn(Foo f) { return f; } Foo nonnullReturn(Foo f) { - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: source has @Nullable String where target requires String return f; } void testLocal(Foo f) { Foo ok = f; - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: source has @Nullable String where target requires String Foo bad = f; var f2 = f; - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: source has @Nullable String where target requires String Foo bad2 = f2; } } @@ -538,10 +538,10 @@ void testLocals( Foo nonnullSuperLocal = nullableObjectFoo; Foo nullableSuperLocal = nullableObjectFoo; Foo nullableSuperLocal2 = nullableStringFoo; - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard lower bound: found Object, required a supertype of @Nullable String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard lower bound: source has Object where target requires a supertype of @Nullable String Foo nullableSuperLocal3 = objectFoo; Foo nonnullSuperFromNullableSuper = nullableSuperFoo; - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard lower bound: found String, required a supertype of @Nullable String + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard lower bound: source has String where target requires a supertype of @Nullable String Foo nullableSuperFromNonnullSuper = nonnullSuperFoo; } } @@ -566,11 +566,11 @@ void testLocals( Foo fromNonnullSuper = nonnullSuperFoo; Foo fromNullableSuper = nullableSuperFoo; Foo fromUnbounded = unboundedFoo; - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object Foo badFromNonnullSuper = nonnullSuperFoo; - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object Foo badFromNullableSuper = nullableSuperFoo; - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object Foo badFromUnbounded = unboundedFoo; } } @@ -595,7 +595,7 @@ void testLocals( NonNullBoundFoo nonnullSuperStringFoo) { NonNullBoundFoo fromNonnull = nonnullObjectFoo; NonNullBoundFoo fromNonnullExtends = nonnullExtendsObjectFoo; - // BUG: Diagnostic contains: incompatible nullability in NonNullBoundFoo type argument T -> wildcard upper bound: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in NonNullBoundFoo type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object NonNullBoundFoo fromNullableExtends = nullableExtendsObjectWithNonnullBoundFoo; NonNullBoundFoo fromSuper = nonnullSuperStringFoo; } @@ -621,13 +621,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 nullability in Pair type argument U -> wildcard upper bound: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Pair type argument U -> wildcard upper bound: source has @Nullable String where target requires String Pair<@Nullable String, ? extends String> invalid = pair; } static void capturedFirstArgument(Pair pair) { Pair target = pair; - // BUG: Diagnostic contains: incompatible nullability in Pair type argument U -> wildcard upper bound: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in Pair type argument U -> wildcard upper bound: source has @Nullable Object where target requires Object Pair invalid = pair; } @@ -636,7 +636,7 @@ static class UnmarkedPair {} static void capturedFirstArgumentFromUnmarkedCode(UnmarkedPair pair) { UnmarkedPair target = pair; - // BUG: Diagnostic contains: incompatible nullability in UnmarkedPair type argument U -> wildcard upper bound: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in UnmarkedPair type argument U -> wildcard upper bound: source has @Nullable Object where target requires Object UnmarkedPair invalid = pair; } } @@ -754,7 +754,7 @@ T get() { } } static void test(Holder> holder) { - // BUG: Diagnostic contains: incompatible nullability in Box type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Box type argument T: source has @Nullable String where target requires String Box box = holder.get(); } } @@ -880,7 +880,7 @@ static void nullable(NullableHolder holder) { // BUG: Diagnostic contains: dereferenced expression 'box.get()' is @Nullable box.get().length(); Box<@Nullable String> compatible = holder.nonNullValue(); - // BUG: Diagnostic contains: incompatible nullability in Box type argument E: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Box type argument E: source has @Nullable String where target requires String Box incompatible = holder.nonNullValue(); // BUG: Diagnostic contains: dereferenced expression 'holder.value()' is @Nullable holder.value().hashCode(); @@ -915,18 +915,18 @@ Nested self() { } Nested testDirect(Nested receiver) { - // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: source has @Nullable String where target requires String return receiver.wildcardUpperTypeVariable(); } Nested testWithSelf(Nested receiver) { - // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: source has @Nullable String where target requires String return receiver.self().wildcardUpperTypeVariable(); } Nested testWithVar(Nested receiver) { var local = receiver; - // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: source has @Nullable String where target requires String return local.wildcardUpperTypeVariable(); } @@ -960,18 +960,18 @@ Nested self() { } Nested testDirect(Nested receiver) { - // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object return receiver.wildcardUpperTypeVariable(); } Nested testWithSelf(Nested receiver) { - // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object return receiver.self().wildcardUpperTypeVariable(); } Nested testWithVar(Nested receiver) { var local = receiver; - // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object return local.wildcardUpperTypeVariable(); } @@ -1038,7 +1038,7 @@ interface NullableI2< } NullableI1 incompatible(NullableI2 i2) { var i2var = i2; - // BUG: Diagnostic contains: incompatible nullability in NullableI1 type argument X: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in NullableI1 type argument X: source has @Nullable Object where target requires Object return i2var.get(); } } @@ -1479,7 +1479,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 nullability in Foo type argument T: a type argument must match exactly; found Void, required @Nullable Void + // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: a type argument must match exactly; source has Void where target requires @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 @@ -1532,7 +1532,7 @@ void test( Box nonNullBoundBox, Box nullableBoundBox) { Box ok = identity(nullableBoundBox); - // BUG: Diagnostic contains: incompatible nullability in Box type argument T -> wildcard lower bound: found String, required a supertype of @Nullable String + // BUG: Diagnostic contains: incompatible nullability in Box type argument T -> wildcard lower bound: source has String where target requires a supertype of @Nullable String Box bad = identity(nonNullBoundBox); } } @@ -1556,7 +1556,7 @@ interface Nested {} return box; } void test(Box> box) { - // BUG: Diagnostic contains: incompatible nullability in Box type argument T -> wildcard lower bound -> Nested type argument T: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in Box type argument T -> wildcard lower bound -> Nested type argument T: a type argument must match exactly; source has String where target requires @Nullable String Box> bad = identity(box); } } @@ -2079,7 +2079,7 @@ static void nullableSuperBounded(NullableNode node) { } static void superBoundedNullableElements(ListNode> node) { - // BUG: Diagnostic contains: incompatible nullability in List type argument E: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in List type argument E: source has @Nullable String where target requires String takesList(node.get()); } } 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 index 766de2c221..cd1ed2acea 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java @@ -13,11 +13,11 @@ public class CaretTests extends MismatchMessageTestBase { public void onlyTheInnermostDifferingNodeIsMarkedInsideAWildcardBound() { assertMessage( """ - incompatible nullability in List type argument E -> wildcard upper bound -> List type argument E: found @Nullable String, required String - found: List> - ^^^^^^^^^^^^^^^^ - required: List> - ^^^^^^ + incompatible nullability in List type argument E -> wildcard upper bound -> List type argument E: source has @Nullable String where target requires String + source: List> + ^^^^^^^^^^^^^^^^ + target: List> + ^^^^^^ """, """ static void take(List> l) {} @@ -32,11 +32,11 @@ void test(List> l) { public void caretSkipsATypeArgumentTheTargetAccepts() { assertMessage( """ - incompatible nullability in Map type argument V -> wildcard upper bound: found @Nullable Object, required Object - found: Map - ^^^^^^^^^^^^^^^^ - required: Map - ^^^^^^ + incompatible nullability in Map type argument V -> wildcard upper bound: source has @Nullable Object where target requires Object + source: Map + ^^^^^^^^^^^^^^^^ + target: Map + ^^^^^^ """, """ static void take(Map m) {} @@ -54,11 +54,11 @@ void test(Map m) { public void caretNamesTheConcreteArgumentWhenEveryWildcardIsAccepted() { assertMessage( """ - incompatible nullability in Map type argument V: found @Nullable String, required String - found: Map - ^^^^^^^^^^^^^^^^ - required: Map - ^^^^^^ + incompatible nullability in Map type argument V: source has @Nullable String where target requires String + source: Map + ^^^^^^^^^^^^^^^^ + target: Map + ^^^^^^ """, """ static void take(Map m) {} @@ -76,11 +76,11 @@ void test(Map m) { public void caretMarksTheFailingArgumentWhereTheTargetRepeatsAType() { assertMessage( """ - incompatible nullability in Three type argument C: found @Nullable String, required String - found: Three - ^^^^^^^^^^^^^^^^ - required: Three - ^^^^^^ + incompatible nullability in Three type argument C: source has @Nullable String where target requires String + source: Three + ^^^^^^^^^^^^^^^^ + target: Three + ^^^^^^ """, """ static class Three {} @@ -96,11 +96,11 @@ void test(Three t) { public void onlyTheFailingArgumentIsNamedBesideAWildcardTheTargetAccepts() { assertMessage( """ - incompatible nullability in Three type argument C: found @Nullable String, required String - found: Three - ^^^^^^^^^^^^^^^^ - required: Three - ^^^^^^ + incompatible nullability in Three type argument C: source has @Nullable String where target requires String + source: Three + ^^^^^^^^^^^^^^^^ + target: Three + ^^^^^^ """, """ static class Three {} @@ -116,22 +116,22 @@ void test(Three t) { public void bothPositionsAreMarkedWhereOneInstanceFillsTwoTypeArguments() { assertMessage( """ - incompatible nullability in Map type argument K -> wildcard upper bound and 1 other position: found @Nullable Object, required Object - found: Map - ^^^^^^^^^^^^ ^^^^^^^^^^^^ - 1 2 - required: Map - ^^^^^^ ^^^^^^ - 1 2 + incompatible nullability in Map type argument K -> wildcard upper bound and 1 other position: source has @Nullable Object where target requires Object + source: Map + ^^^^^^^^^^^^ ^^^^^^^^^^^^ + 1 2 + target: Map + ^^^^^^ ^^^^^^ + 1 2 \s 1. path: Map type argument K -> wildcard upper bound - found: @Nullable Object - required: Object + source: @Nullable Object + target: 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 + source: @Nullable Object + target: Object note: the source wildcard is the type argument for type parameter E of List """, """ @@ -150,11 +150,11 @@ void test(List l) { public void aMismatchInsideAnArrayElementTypeArgumentIsMarked() { assertMessage( """ - incompatible nullability in array element -> List type argument E: found @Nullable String, required String - found: List<@Nullable String> [] - ^^^^^^^^^^^^^^^^ - required: List [] - ^^^^^^ + incompatible nullability in array element -> List type argument E: source has @Nullable String where target requires String + source: List<@Nullable String> [] + ^^^^^^^^^^^^^^^^ + target: List [] + ^^^^^^ """, """ static void take(List[] l) {} @@ -169,11 +169,11 @@ void test(List<@Nullable String>[] l) { public void aNullableArrayComponentTypeIsMarkedInsideATypeArgument() { assertMessage( """ - incompatible nullability in List type argument E -> array element: found @Nullable String, required String - found: List<@Nullable String []> - ^^^^^^^^^^^^^^^^ - required: List - ^^^^^^ + incompatible nullability in List type argument E -> array element: source has @Nullable String where target requires String + source: List<@Nullable String []> + ^^^^^^^^^^^^^^^^ + target: List + ^^^^^^ """, """ static void take(List l) {} @@ -188,11 +188,11 @@ void test(List<@Nullable String[]> l) { public void aNullableArrayTypeIsMarkedInsideATypeArgument() { assertMessage( """ - incompatible nullability in List type argument E: found String @Nullable [], required String [] - found: List - ^^^^^^^^^^^^^^^^^^^ - required: List - ^^^^^^^^^ + incompatible nullability in List type argument E: source has String @Nullable [] where target requires String [] + source: List + ^^^^^^^^^^^^^^^^^^^ + target: List + ^^^^^^^^^ """, """ static void take(List l) {} @@ -207,22 +207,22 @@ void test(List l) { public void twoMismatchesUnderOneWildcardShareItsCaret() { assertMessage( """ - incompatible nullability in Foo type argument T -> wildcard upper bound -> Map type argument K and 1 other position: found @Nullable String, required String - found: Foo - ^ - 1,2 - required: Foo> - ^^^^^^ ^^^^^^ - 1 2 + incompatible nullability in Foo type argument T -> wildcard upper bound -> Map type argument K and 1 other position: source has @Nullable String where target requires String + source: Foo + ^ + 1,2 + target: Foo> + ^^^^^^ ^^^^^^ + 1 2 \s 1. path: Foo type argument T -> wildcard upper bound -> Map type argument K - found: @Nullable String - required: String + source: @Nullable String + target: String note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Foo \s 2. path: Foo type argument T -> wildcard upper bound -> Map type argument V - found: @Nullable String - required: String + source: @Nullable String + target: String note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Foo """, """ @@ -239,22 +239,22 @@ void test(Foo f) { public void twoMismatchesUnderOneNestedWildcardShareItsCaret() { assertMessage( """ - incompatible nullability in List type argument E -> wildcard upper bound -> Foo type argument T -> wildcard upper bound -> Map type argument K and 1 other position: found @Nullable String, required String - found: List> - ^ - 1,2 - required: List>> - ^^^^^^ ^^^^^^ - 1 2 + incompatible nullability in List type argument E -> wildcard upper bound -> Foo type argument T -> wildcard upper bound -> Map type argument K and 1 other position: source has @Nullable String where target requires String + source: List> + ^ + 1,2 + target: List>> + ^^^^^^ ^^^^^^ + 1 2 \s 1. path: List type argument E -> wildcard upper bound -> Foo type argument T -> wildcard upper bound -> Map type argument K - found: @Nullable String - required: String + source: @Nullable String + target: String note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Foo \s 2. path: List type argument E -> wildcard upper bound -> Foo type argument T -> wildcard upper bound -> Map type argument V - found: @Nullable String - required: String + source: @Nullable String + target: String note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Foo """, """ diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java index d0ff96d53b..3ab80edfcf 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java @@ -30,7 +30,7 @@ private BugCheckerRefactoringTestHelper makeHelper() { } @Test - public void theRequiredTypeFixImportsTheNullableAnnotationItAdds() throws IOException { + public void theTargetTypeFixImportsTheNullableAnnotationItAdds() throws IOException { makeHelper() .addInputLines( "Lib.java", diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java index 268b646c64..41fe6204e6 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java @@ -3,7 +3,7 @@ import org.junit.Test; /** - * A difference in a {@code ? super} bound is located like any other, and the required side reads as + * A difference in a {@code ? super} bound is located like any other, and the target side reads as * {@code a supertype of} the bound the target states. A raw source has no type arguments to compare * and draws no message at all, and neither does an array of a raw target type. */ @@ -13,11 +13,11 @@ public class LowerBoundAndRawSourceTests extends MismatchMessageTestBase { public void aLowerBoundDifferenceIsMarkedInBothTypes() { assertMessage( """ - incompatible nullability in List type argument E -> wildcard lower bound: found String, required a supertype of @Nullable String - found: List - ^^^^^^ - required: List - ^^^^^^^^^^^^^^^^ + incompatible nullability in List type argument E -> wildcard lower bound: source has String where target requires a supertype of @Nullable String + source: List + ^^^^^^ + target: List + ^^^^^^^^^^^^^^^^ """, """ static void takeNonNullLower(List l) {} @@ -36,11 +36,11 @@ void nonNullSourceLowerBound(List l) { public void aLowerBoundDifferenceIsMarkedAcrossASupertypeView() { assertMessage( """ - incompatible nullability in Base type argument T -> wildcard lower bound: found String, required a supertype of @Nullable String - found: Sub - ^^^^^^ - required: Base - ^^^^^^^^^^^^^^^^ + incompatible nullability in Base type argument T -> wildcard lower bound: source has String where target requires a supertype of @Nullable String + source: Sub + ^^^^^^ + target: Base + ^^^^^^^^^^^^^^^^ """, """ static class Base {} 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 26752ab181..6cca9afd20 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 @@ -15,11 +15,11 @@ public class NoteTests extends MismatchMessageTestBase { public void anUnboundedWildcardNamesTheTypeParameterItsBoundIsInheritedFrom() { assertMessage( """ - incompatible nullability in Collection type argument E -> wildcard upper bound: found @Nullable Object, required Object - found: List - ^ - required: Collection - ^^^^^^ + incompatible nullability in Collection type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + source: List + ^ + target: Collection + ^^^^^^ note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List fix: declare list as List """, @@ -46,11 +46,11 @@ void nullableTarget(List list) { public void aSuperBoundedWildcardNamesTheTypeParameterItsUpperBoundIsInheritedFrom() { assertMessage( """ - incompatible nullability in Collection type argument E -> wildcard upper bound: found @Nullable Object, required Object - found: List - ^^^^^^^^^^^^^^ - required: Collection - ^^^^^^ + incompatible nullability in Collection type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + source: List + ^^^^^^^^^^^^^^ + target: Collection + ^^^^^^ note: the source ? super String has no explicit upper bound, so its upper bound is inherited from type parameter E of List """, """ @@ -66,11 +66,11 @@ void test(List list) { public void anExplicitlyWrittenNullableBoundDrawsNoInheritedBoundNote() { assertMessage( """ - incompatible nullability in List type argument E -> wildcard upper bound: found @Nullable String, required String - found: List - ^^^^^^^^^^^^^^^^ - required: List - ^^^^^^ + incompatible nullability in List type argument E -> wildcard upper bound: source has @Nullable String where target requires String + source: List + ^^^^^^^^^^^^^^^^ + target: List + ^^^^^^ """, """ static void take(List l) {} @@ -85,11 +85,11 @@ void test(List l) { public void noInheritedBoundNoteWhereTheUseStatesItsOwnNullness() { assertMessage( """ - incompatible nullability in Box type argument T -> wildcard upper bound: found @Nullable T, required Object - found: Box<@Nullable T> - ^^^^^^^^^^^ - required: Box - ^^^^^^ + incompatible nullability in Box type argument T -> wildcard upper bound: source has @Nullable T where target requires Object + source: Box<@Nullable T> + ^^^^^^^^^^^ + target: Box + ^^^^^^ """, """ static class Box {} @@ -108,11 +108,11 @@ static void test(Box<@Nullable T> b) { public void aWildcardWhoseImplicitBoundHoldsTheMismatchNamesItsTypeParameter() { assertMessage( """ - incompatible nullability in Foo type argument T -> wildcard upper bound -> List type argument E: found @Nullable String, required String - found: Foo - ^ - required: Foo> - ^^^^^^ + incompatible nullability in Foo type argument T -> wildcard upper bound -> List type argument E: source has @Nullable String where target requires String + source: Foo + ^ + target: Foo> + ^^^^^^ note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Foo """, """ @@ -129,11 +129,11 @@ void test(Foo f) { public void aNestedWildcardWhoseImplicitBoundHoldsTheMismatchNamesItsTypeParameter() { assertMessage( """ - incompatible nullability in List type argument E -> wildcard upper bound -> Foo type argument T -> wildcard upper bound -> List type argument E: found @Nullable String, required String - found: List> - ^ - required: List>> - ^^^^^^ + incompatible nullability in List type argument E -> wildcard upper bound -> Foo type argument T -> wildcard upper bound -> List type argument E: source has @Nullable String where target requires String + source: List> + ^ + target: List>> + ^^^^^^ note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Foo """, """ @@ -150,11 +150,11 @@ void test(List> f) { public void aWildcardInsideAWildcardBoundNamesItsTypeParameter() { assertMessage( """ - incompatible nullability in List type argument E -> wildcard upper bound -> List type argument E -> wildcard upper bound: found @Nullable Object, required Object - found: List> - ^ - required: List> - ^^^^^^ + incompatible nullability in List type argument E -> wildcard upper bound -> List type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + source: List> + ^ + target: List> + ^^^^^^ note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List fix: declare l as List> """, @@ -171,11 +171,11 @@ void test(List> l) { public void aWildcardInsideAnArrayInsideAWildcardBoundNamesItsTypeParameter() { assertMessage( """ - incompatible nullability in List type argument E -> wildcard upper bound -> array element -> List type argument E -> wildcard upper bound: found @Nullable Object, required Object - found: List []> - ^ - required: List []> - ^^^^^^ + incompatible nullability in List type argument E -> wildcard upper bound -> array element -> List type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + source: List []> + ^ + target: List []> + ^^^^^^ note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List fix: declare l as List []> """, 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 index 065333eb4a..58bb0185d3 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java @@ -15,11 +15,11 @@ public class PathTests extends MismatchMessageTestBase { public void pathNamesTheTypeParameterTheDeclarationDeclared() { assertMessage( """ - incompatible nullability in Result type argument Failure: found @Nullable String, required String - found: Result - ^^^^^^^^^^^^^^^^ - required: Result - ^^^^^^ + incompatible nullability in Result type argument Failure: source has @Nullable String where target requires String + source: Result + ^^^^^^^^^^^^^^^^ + target: Result + ^^^^^^ """, """ static class Result {} @@ -35,11 +35,11 @@ void test(Result r) { public void pathRepeatsTheTypeParameterNameAtEveryLevelThatSharesIt() { assertMessage( """ - incompatible nullability in List type argument E -> Collection type argument E -> List type argument E: found @Nullable String, required String - found: List>> - ^^^^^^^^^^^^^^^^ - required: List>> - ^^^^^^ + incompatible nullability in List type argument E -> Collection type argument E -> List type argument E: source has @Nullable String where target requires String + source: List>> + ^^^^^^^^^^^^^^^^ + target: List>> + ^^^^^^ """, """ static void take(List>> l) {} @@ -54,11 +54,11 @@ void test(List>> l) { public void pathKeepsTheEnclosingTypeApartFromTheInnerType() { assertMessage( """ - incompatible nullability in Inner type argument U: found @Nullable Integer, required Integer - found: Outer.Inner<@Nullable Integer> - ^^^^^^^^^^^^^^^^^ - required: Outer.Inner - ^^^^^^^ + incompatible nullability in Inner type argument U: source has @Nullable Integer where target requires Integer + source: Outer.Inner<@Nullable Integer> + ^^^^^^^^^^^^^^^^^ + target: Outer.Inner + ^^^^^^^ """, """ static class Outer { @@ -76,21 +76,21 @@ void test(Outer.Inner<@Nullable Integer> i) { public void twoMismatchesInsideOneTypeArgumentSharePathPrefix() { assertMessage( """ - incompatible nullability in Map type argument V -> Map type argument K and 1 other position: found @Nullable String, required String - found: Map> - ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^ - 1 2 - required: Map> - ^^^^^^ ^^^^^^^ - 1 2 + incompatible nullability in Map type argument V -> Map type argument K and 1 other position: source has @Nullable String where target requires String + source: Map> + ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^ + 1 2 + target: Map> + ^^^^^^ ^^^^^^^ + 1 2 \s 1. path: Map type argument V -> Map type argument K - found: @Nullable String - required: String + source: @Nullable String + target: String \s 2. path: Map type argument V -> Map type argument V - found: @Nullable Integer - required: Integer + source: @Nullable Integer + target: Integer """, """ static void take(Map> m) {} @@ -105,21 +105,21 @@ void test(Map> m) { public void mismatchesAtDifferentDepthsEachGetTheirOwnPath() { assertMessage( """ - incompatible nullability in Map type argument K and 1 other position: found @Nullable String, required String - found: Map<@Nullable String, List>> - ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^ - 1 2 - required: Map>> - ^^^^^^ ^^^^^^^ - 1 2 + incompatible nullability in Map type argument K and 1 other position: source has @Nullable String where target requires String + source: Map<@Nullable String, List>> + ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^ + 1 2 + target: Map>> + ^^^^^^ ^^^^^^^ + 1 2 \s 1. path: Map type argument K - found: @Nullable String - required: String + source: @Nullable String + target: String \s 2. path: Map type argument V -> List type argument E -> wildcard upper bound -> Collection type argument E - found: @Nullable Integer - required: Integer + source: @Nullable Integer + target: Integer """, """ static void take(Map>> m) {} @@ -135,11 +135,11 @@ void test( public void pathReachesATypeArgumentOfAnArrayElement() { assertMessage( """ - incompatible nullability in array element -> List type argument E: a type argument must match exactly; found String, required @Nullable String - found: List [] - ^^^^^^ - required: @Nullable List<@Nullable String> [] - ^^^^^^^^^^^^^^^^ + incompatible nullability in array element -> List type argument E: a type argument must match exactly; source has String where target requires @Nullable String + source: List [] + ^^^^^^ + target: @Nullable List<@Nullable String> [] + ^^^^^^^^^^^^^^^^ """, """ void test(List[] arr) { @@ -153,11 +153,11 @@ void test(List[] arr) { public void pathDescendsIntoEveryDimensionOfANestedArray() { assertMessage( """ - incompatible nullability in array element -> array element: found @Nullable Integer, required Integer - found: @Nullable Integer [] [] - ^^^^^^^^^^^^^^^^^ - required: Integer @Nullable [] [] - ^^^^^^^ + incompatible nullability in array element -> array element: source has @Nullable Integer where target requires Integer + source: @Nullable Integer [] [] + ^^^^^^^^^^^^^^^^^ + target: Integer @Nullable [] [] + ^^^^^^^ """, """ void test(@Nullable Integer[][] src) { @@ -171,11 +171,11 @@ void test(@Nullable Integer[][] src) { public void pathDescendsIntoEveryDimensionOfAThreeDimensionalArray() { assertMessage( """ - incompatible nullability in array element -> array element -> array element: found @Nullable Integer, required Integer - found: @Nullable Integer [] [] [] - ^^^^^^^^^^^^^^^^^ - required: Integer @Nullable [] [] [] - ^^^^^^^ + incompatible nullability in array element -> array element -> array element: source has @Nullable Integer where target requires Integer + source: @Nullable Integer [] [] [] + ^^^^^^^^^^^^^^^^^ + target: Integer @Nullable [] [] [] + ^^^^^^^ """, """ void test(@Nullable Integer[][][] src3) { @@ -189,11 +189,11 @@ void test(@Nullable Integer[][][] src3) { public void aNullableSourceIsComparedBelowItsOwnNullness() { assertMessage( """ - incompatible nullability in Collection type argument E -> wildcard upper bound: found @Nullable Object, required Object - found: @Nullable List - ^ - required: Collection - ^^^^^^ + incompatible nullability in Collection type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + source: @Nullable List + ^ + target: Collection + ^^^^^^ note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List fix: declare l as @Nullable List """, @@ -212,11 +212,11 @@ void test(@Nullable List l) { public void aNullableTargetIsComparedBelowItsOwnNullness() { assertMessage( """ - incompatible nullability in List type argument E: found @Nullable String, required String - found: List<@Nullable String> - ^^^^^^^^^^^^^^^^ - required: @Nullable List - ^^^^^^ + incompatible nullability in List type argument E: source has @Nullable String where target requires String + source: List<@Nullable String> + ^^^^^^^^^^^^^^^^ + target: @Nullable List + ^^^^^^ """, """ static void param(@Nullable List l) {} @@ -231,11 +231,11 @@ void test(List<@Nullable String> x) { public void pathNamesOnlyTheTypeArgumentTheCheckRejects() { assertMessage( """ - incompatible nullability in Pair type argument A: found @Nullable String, required String - found: Pair<@Nullable String, Integer []> - ^^^^^^^^^^^^^^^^ - required: Pair - ^^^^^^ + incompatible nullability in Pair type argument A: source has @Nullable String where target requires String + source: Pair<@Nullable String, Integer []> + ^^^^^^^^^^^^^^^^ + target: Pair + ^^^^^^ """, """ static class Pair {} @@ -251,11 +251,11 @@ void test(Pair<@Nullable String, Integer[]> p) { public void aCapturedSourceIsComparedThroughItsUpperBound() { assertMessage( """ - incompatible nullability in List type argument E: found @Nullable String, required String - found: capture of ? extends List<@Nullable String> - ^^^^^^^^^^^^^^^^ - required: List - ^^^^^^ + incompatible nullability in List type argument E: source has @Nullable String where target requires String + source: capture of ? extends List<@Nullable String> + ^^^^^^^^^^^^^^^^ + target: List + ^^^^^^ fix: declare l as List<@Nullable String> """, """ @@ -270,11 +270,11 @@ void test(List> wl) { public void aCapturedArgumentIsComparedThroughItsUpperBound() { assertMessage( """ - incompatible nullability in List type argument E: found @Nullable String, required String - found: List<@Nullable String> - ^^^^^^^^^^^^^^^^ - required: List - ^^^^^^ + incompatible nullability in List type argument E: source has @Nullable String where target requires String + source: List<@Nullable String> + ^^^^^^^^^^^^^^^^ + target: List + ^^^^^^ """, """ static void take(List l) {} @@ -289,11 +289,11 @@ void test(List> wl) { public void pathCrossesAWildcardLowerBound() { assertMessage( """ - incompatible nullability in List type argument E -> wildcard lower bound -> List type argument E -> wildcard upper bound: found Object, required a supertype of @Nullable Object - found: List> - ^^^^^^ - required: List> - ^ + incompatible nullability in List type argument E -> wildcard lower bound -> List type argument E -> wildcard upper bound: source has Object where target requires a supertype of @Nullable Object + source: List> + ^^^^^^ + target: List> + ^ """, """ static void take(List> l) {} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java index b362627744..dddc35dffd 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java @@ -15,22 +15,22 @@ public class SourceFixTests extends MismatchMessageTestBase { public void theFixRewritesEveryMismatchingWildcard() { assertMessage( """ - incompatible nullability in Map type argument K -> wildcard upper bound and 1 other position: found @Nullable Object, required Object - found: Map - ^ ^ - 1 2 - required: Map - ^^^^^^ ^^^^^^ - 1 2 + incompatible nullability in Map type argument K -> wildcard upper bound and 1 other position: source has @Nullable Object where target requires Object + source: Map + ^ ^ + 1 2 + target: Map + ^^^^^^ ^^^^^^ + 1 2 \s 1. path: Map type argument K -> wildcard upper bound - found: @Nullable Object - required: Object + source: @Nullable Object + target: 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 + source: @Nullable Object + target: Object note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter V of Map \s fix: declare m as Map @@ -51,11 +51,11 @@ void test(Map m) { public void theFixLeavesAWildcardTheTargetAllowsToBeNullable() { assertMessage( """ - incompatible nullability in Map type argument K -> wildcard upper bound: found @Nullable Object, required Object - found: Map - ^ - required: Map - ^^^^^^ + incompatible nullability in Map type argument K -> wildcard upper bound: source has @Nullable Object where target requires Object + source: Map + ^ + target: Map + ^^^^^^ note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter K of Map fix: declare m as Map """, @@ -75,11 +75,11 @@ void test(Map m) { public void theFixSurvivesAMismatchInTheHarmlessDirection() { assertMessage( """ - incompatible nullability in Box type argument T -> wildcard upper bound: found @Nullable Object, required Object - found: Box - ^ - required: Box - ^^^^^^ + incompatible nullability in Box type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object + source: Box + ^ + target: Box + ^^^^^^ note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Box fix: declare b as Box """, @@ -100,11 +100,11 @@ void fixedFormIsAccepted(Box b) { public void theFixSurvivesASuperBoundedArgumentTheTargetAlsoDeclaresSuper() { assertMessage( """ - incompatible nullability in Map type argument K -> wildcard upper bound: found @Nullable Object, required Object - found: Map - ^ - required: Map - ^^^^^^ + incompatible nullability in Map type argument K -> wildcard upper bound: source has @Nullable Object where target requires Object + source: Map + ^ + target: Map + ^^^^^^ note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter K of Map fix: declare m as Map """, @@ -124,11 +124,11 @@ void test(Map m) { public void theFixRewritesAWildcardInsideAnArrayElement() { assertMessage( """ - incompatible nullability in array element -> Collection type argument E -> wildcard upper bound: found @Nullable Object, required Object - found: List [] - ^ - required: Collection [] - ^^^^^^ + incompatible nullability in array element -> Collection type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + source: List [] + ^ + target: Collection [] + ^^^^^^ note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List fix: declare lists as List [] """, @@ -148,11 +148,11 @@ void test(List[] lists) { public void theFixRewritesAWildcardInsideANestedTypeArgument() { assertMessage( """ - incompatible nullability in Collection type argument E -> wildcard upper bound -> List type argument E -> wildcard upper bound: found @Nullable Object, required Object - found: List> - ^ - required: Collection> - ^^^^^^ + incompatible nullability in Collection type argument E -> wildcard upper bound -> List type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + source: List> + ^ + target: Collection> + ^^^^^^ note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List fix: declare lists as List> """, @@ -172,11 +172,11 @@ void test(List> lists) { public void theFixRewritesAWildcardInAnEnclosingTypeArgument() { assertMessage( """ - incompatible nullability in enclosing type -> Outer type argument T -> wildcard upper bound: found @Nullable Object, required Object - found: Outer.Inner - ^ - required: Outer.Inner - ^^^^^^ + incompatible nullability in enclosing type -> Outer type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object + source: Outer.Inner + ^ + target: Outer.Inner + ^^^^^^ note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Outer fix: declare inner as Outer.Inner """, @@ -196,14 +196,14 @@ void test(Outer.Inner inner) { } @Test - public void theSourceFixIsStillOfferedWhereTheRequiredTypeIsNotEditable() { + public void theSourceFixIsStillOfferedWhereTheTargetTypeIsNotEditable() { assertMessage( """ - incompatible nullability in Collection type argument E -> wildcard upper bound: found @Nullable Object, required Object - found: List - ^ - required: Collection - ^^^^^^ + incompatible nullability in Collection type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + source: List + ^ + target: Collection + ^^^^^^ note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List fix: declare l as List """, @@ -220,22 +220,22 @@ void test(List l) { public void noFixWhenAnExplicitBoundMismatchRemains() { assertMessage( """ - incompatible nullability in Map type argument K -> wildcard upper bound and 1 other position: found @Nullable Object, required Object - found: Map - ^ ^^^^^^^^^^^^^^^^ - 1 2 - required: Map - ^^^^^^ ^^^^^^ - 1 2 + incompatible nullability in Map type argument K -> wildcard upper bound and 1 other position: source has @Nullable Object where target requires Object + source: Map + ^ ^^^^^^^^^^^^^^^^ + 1 2 + target: Map + ^^^^^^ ^^^^^^ + 1 2 \s 1. path: Map type argument K -> wildcard upper bound - found: @Nullable Object - required: Object + source: @Nullable Object + target: 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 + source: @Nullable Object + target: Object """, """ static void take(Map m) {} @@ -250,22 +250,22 @@ void test(Map m) { public void noFixWhenAConcreteTypeArgumentAlsoMismatches() { assertMessage( """ - incompatible nullability in Map type argument K -> wildcard upper bound and 1 other position: found @Nullable Object, required Object - found: Map - ^ ^^^^^^^^^^^^^^^^ - 1 2 - required: Map - ^^^^^^ ^^^^^^ - 1 2 + incompatible nullability in Map type argument K -> wildcard upper bound and 1 other position: source has @Nullable Object where target requires Object + source: Map + ^ ^^^^^^^^^^^^^^^^ + 1 2 + target: Map + ^^^^^^ ^^^^^^ + 1 2 \s 1. path: Map type argument K -> wildcard upper bound - found: @Nullable Object - required: Object + source: @Nullable Object + target: 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 + source: @Nullable String + target: String """, """ static void take(Map m) {} @@ -280,22 +280,22 @@ void test(Map m) { public void noFixWhenOneMismatchCannotBeRewritten() { assertMessage( """ - incompatible nullability in Map type argument K -> wildcard upper bound and 1 other position: found @Nullable Object, required Object - found: Map - ^ ^^^^^^^^^^^^^^ - 1 2 - required: Map - ^^^^^^ ^^^^^^ - 1 2 + incompatible nullability in Map type argument K -> wildcard upper bound and 1 other position: source has @Nullable Object where target requires Object + source: Map + ^ ^^^^^^^^^^^^^^ + 1 2 + target: Map + ^^^^^^ ^^^^^^ + 1 2 \s 1. path: Map type argument K -> wildcard upper bound - found: @Nullable Object - required: Object + source: @Nullable Object + target: 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 + source: @Nullable Object + target: Object note: the source ? super String has no explicit upper bound, so its upper bound is inherited from type parameter V of Map """, """ @@ -311,11 +311,11 @@ void test(Map m) { public void noFixWhenBoundsDifferBelowTheTopLevel() { assertMessage( """ - incompatible nullability in Holder type argument E -> wildcard upper bound -> List type argument E: found @Nullable Object, required Object - found: Holder - ^ - required: Holder> - ^^^^^^ + incompatible nullability in Holder type argument E -> wildcard upper bound -> List type argument E: source has @Nullable Object where target requires Object + source: Holder + ^ + target: Holder> + ^^^^^^ note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of Holder """, """ @@ -332,11 +332,11 @@ void test(Holder h) { public void noFixWhenTheRewrittenTypeHoldsACapture() { assertMessage( """ - incompatible nullability in Map type argument K -> wildcard upper bound -> List type argument E -> wildcard upper bound: found @Nullable Object, required Object - found: Map, capture of ?> - ^ - required: Map, ?> - ^^^^^^ + incompatible nullability in Map type argument K -> wildcard upper bound -> List type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + source: Map, capture of ?> + ^ + target: Map, ?> + ^^^^^^ note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List """, """ @@ -359,30 +359,30 @@ public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { Map.of( "PLAIN", """ - incompatible nullability in Map type argument K -> wildcard upper bound: found @Nullable Object, required Object - found: Map - ^ - required: Map - ^^^^^^ + incompatible nullability in Map type argument K -> wildcard upper bound: source has @Nullable Object where target requires Object + source: Map + ^ + target: Map + ^^^^^^ note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter K of Map fix: declare plain as Map """, "TAINTED", """ - incompatible nullability in Map type argument K -> wildcard upper bound: found @Nullable Object, required Object - found: Map - ^ - required: Map - ^^^^^^ + incompatible nullability in Map type argument K -> wildcard upper bound: source has @Nullable Object where target requires Object + source: Map + ^ + target: Map + ^^^^^^ note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter K of Map """, "TAINTED_ARRAY_ELEMENT", """ - incompatible nullability in Map type argument K -> wildcard upper bound: found @Nullable Object, required Object - found: Map - ^ - required: Map - ^^^^^^ + incompatible nullability in Map type argument K -> wildcard upper bound: source has @Nullable Object where target requires Object + source: Map + ^ + target: Map + ^^^^^^ note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter K of Map """), """ @@ -409,11 +409,11 @@ void taintedArrayElement(Map m) { public void theFixNamesTheFieldItRewrites() { assertMessage( """ - incompatible nullability in Collection type argument E -> wildcard upper bound: found @Nullable Object, required Object - found: List - ^ - required: Collection - ^^^^^^ + incompatible nullability in Collection type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + source: List + ^ + target: Collection + ^^^^^^ note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List fix: declare field as List """, 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 index 142fe17e43..680fec201c 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java @@ -15,37 +15,37 @@ public class SummaryAndNumberingTests extends MismatchMessageTestBase { public void listsAtMostFiveMismatchesAndSaysHowManyMoreThereAre() { assertMessage( """ - incompatible nullability in Args type argument A -> wildcard upper bound and 5 other positions: found @Nullable Object, required Object - found: Args - ^ ^ ^ ^ ^ - 1 2 3 4 5 - required: Args - ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ - 1 2 3 4 5 + incompatible nullability in Args type argument A -> wildcard upper bound and 5 other positions: source has @Nullable Object where target requires Object + source: Args + ^ ^ ^ ^ ^ + 1 2 3 4 5 + target: Args + ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ + 1 2 3 4 5 \s 1. path: Args type argument A -> wildcard upper bound - found: @Nullable Object - required: Object + source: @Nullable Object + target: 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 + source: @Nullable Object + target: 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 + source: @Nullable Object + target: 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 + source: @Nullable Object + target: 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 + source: @Nullable Object + target: 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 @@ -66,37 +66,37 @@ void test(Args args) { public void listsFiveMismatchesWithoutSayingThereAreMore() { assertMessage( """ - incompatible nullability in Args type argument A -> wildcard upper bound and 4 other positions: found @Nullable Object, required Object - found: Args - ^ ^ ^ ^ ^ - 1 2 3 4 5 - required: Args - ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ - 1 2 3 4 5 + incompatible nullability in Args type argument A -> wildcard upper bound and 4 other positions: source has @Nullable Object where target requires Object + source: Args + ^ ^ ^ ^ ^ + 1 2 3 4 5 + target: Args + ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ + 1 2 3 4 5 \s 1. path: Args type argument A -> wildcard upper bound - found: @Nullable Object - required: Object + source: @Nullable Object + target: 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 + source: @Nullable Object + target: 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 + source: @Nullable Object + target: 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 + source: @Nullable Object + target: 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 + source: @Nullable Object + target: Object note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of Args \s fix: declare args as Args @@ -115,21 +115,21 @@ void test(Args args) { public void adjacentTypeArgumentsThatBothMismatchAreNumberedSideBySide() { assertMessage( """ - incompatible nullability in Map type argument K and 1 other position: found @Nullable String, required String - found: Map<@Nullable String, @Nullable String> - ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ - 1 2 - required: Map - ^^^^^^ ^^^^^^ - 1 2 + incompatible nullability in Map type argument K and 1 other position: source has @Nullable String where target requires String + source: Map<@Nullable String, @Nullable String> + ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ + 1 2 + target: Map + ^^^^^^ ^^^^^^ + 1 2 \s 1. path: Map type argument K - found: @Nullable String - required: String + source: @Nullable String + target: String \s 2. path: Map type argument V - found: @Nullable String - required: String + source: @Nullable String + target: String """, """ static void take(Map m) {} @@ -141,14 +141,14 @@ void test(Map<@Nullable String, @Nullable String> m) { } @Test - public void invariantTypeArgumentIsReportedWhenTheSourceIsLessNullableThanRequired() { + public void invariantTypeArgumentIsReportedWhenTheSourceIsLessNullableThanTheTarget() { assertMessage( """ - incompatible nullability in List type argument E: a type argument must match exactly; found String, required @Nullable String - found: List - ^^^^^^ - required: List<@Nullable String> - ^^^^^^^^^^^^^^^^ + incompatible nullability in List type argument E: a type argument must match exactly; source has String where target requires @Nullable String + source: List + ^^^^^^ + target: List<@Nullable String> + ^^^^^^^^^^^^^^^^ """, """ void test(List source) { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeFixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java similarity index 64% rename from nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeFixTests.java rename to nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java index b210ea78e1..a9da09e316 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeFixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java @@ -4,25 +4,25 @@ import org.junit.Test; /** - * A {@code fix:} line that names the variable a declaration declares offers the required type with + * A {@code fix:} line that names the variable a declaration declares offers the target 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 + * the target type, a local variable declaration, and not at a call, an assignment, or a return, + * whose target type is written somewhere else. It is also withheld where printing it would drop a * type-use annotation. {@link FixTests} checks the edit the fix makes. */ -public class RequiredTypeFixTests extends MismatchMessageTestBase { +public class TargetTypeFixTests extends MismatchMessageTestBase { private static final String MAP_VALUES_MESSAGE = """ - incompatible nullability in Map type argument V: found @Nullable String, required String - found: Map - ^^^^^^^^^^^^^^^^ - required: Map - ^^^^^^ + incompatible nullability in Map type argument V: source has @Nullable String where target requires String + source: Map + ^^^^^^^^^^^^^^^^ + target: Map + ^^^^^^ """; @Test - public void theFixIsOfferedOnlyWhereTheDiagnosticPointsAtTheRequiredTypeDeclaration() { + public void theFixIsOfferedOnlyWhereTheDiagnosticPointsAtTheTargetTypeDeclaration() { assertMessages( Map.of( "DECLARATION", @@ -64,11 +64,11 @@ Map returned(Map m public void theFixIsTheDeclaredTypeNotAnInstantiatedSupertype() { assertMessage( """ - incompatible nullability in List type argument E: found @Nullable String, required String - found: Sub<@Nullable String> - ^^^^^^^^^^^^^^^^ - required: List - ^^^^^^ + incompatible nullability in List type argument E: source has @Nullable String where target requires String + source: Sub<@Nullable String> + ^^^^^^^^^^^^^^^^ + target: List + ^^^^^^ fix: declare l as List<@Nullable String> """, """ @@ -87,31 +87,31 @@ public void theFixReplacesTheNodeAtEveryKindOfStep() { Map.of( "WILDCARD_BOUND", """ - incompatible nullability in Collection type argument E -> wildcard upper bound: found @Nullable Object, required Object - found: List - ^ - required: Collection - ^^^^^^ + incompatible nullability in Collection type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + source: List + ^ + target: Collection + ^^^^^^ note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List fix: declare list as List fix: declare c as Collection """, "ARRAY_ELEMENT", """ - incompatible nullability in array element -> List type argument E: found @Nullable String, required String - found: List<@Nullable String> [] - ^^^^^^^^^^^^^^^^ - required: List [] - ^^^^^^ + incompatible nullability in array element -> List type argument E: source has @Nullable String where target requires String + source: List<@Nullable String> [] + ^^^^^^^^^^^^^^^^ + target: List [] + ^^^^^^ fix: declare d as List<@Nullable String> [] """, "ENCLOSING_TYPE", """ - incompatible nullability in enclosing type -> Outer type argument T: found @Nullable String, required String - found: Outer<@Nullable String>.Inner - ^^^^^^^^^^^^^^^^ - required: Outer.Inner - ^^^^^^ + incompatible nullability in enclosing type -> Outer type argument T: source has @Nullable String where target requires String + source: Outer<@Nullable String>.Inner + ^^^^^^^^^^^^^^^^ + target: Outer.Inner + ^^^^^^ fix: declare d as Outer<@Nullable String>.Inner """), """ @@ -144,36 +144,36 @@ public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { Map.of( "PLAIN", """ - incompatible nullability in Map type argument V: found @Nullable String, required String - found: Map - ^^^^^^^^^^^^^^^^ - required: Map - ^^^^^^ + incompatible nullability in Map type argument V: source has @Nullable String where target requires String + source: Map + ^^^^^^^^^^^^^^^^ + target: Map + ^^^^^^ fix: declare plain as Map """, "TAINTED", """ - incompatible nullability in Map type argument V: found @Nullable String, required String - found: Map - ^^^^^^^^^^^^^^^^ - required: Map - ^^^^^^ + incompatible nullability in Map type argument V: source has @Nullable String where target requires String + source: Map + ^^^^^^^^^^^^^^^^ + target: Map + ^^^^^^ """, "TAINTED_BOUND", """ - incompatible nullability in Map type argument V: found @Nullable String, required String - found: Map - ^^^^^^^^^^^^^^^^ - required: Map - ^^^^^^ + incompatible nullability in Map type argument V: source has @Nullable String where target requires String + source: Map + ^^^^^^^^^^^^^^^^ + target: Map + ^^^^^^ """, "TYPE_VARIABLE", """ - incompatible nullability in Map type argument V: found @Nullable String, required String - found: Map - ^^^^^^^^^^^^^^^^ - required: Map - ^^^^^^ + incompatible nullability in Map type argument V: source has @Nullable String where target requires String + source: Map + ^^^^^^^^^^^^^^^^ + target: Map + ^^^^^^ fix: declare d as Map """), """ diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java index da7cc28cd2..f6770e54e2 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java @@ -14,11 +14,11 @@ public class TraversalCostTests extends MismatchMessageTestBase { public void aSharedBoundBesideTheMismatchIsWalkedOnce() { assertMessage( """ - incompatible nullability in P type argument A: found @Nullable String, required String - found: P<@Nullable String, L24> - ^^^^^^^^^^^^^^^^ - required: P> - ^^^^^^ + incompatible nullability in P type argument A: source has @Nullable String where target requires String + source: P<@Nullable String, L24> + ^^^^^^^^^^^^^^^^ + target: P> + ^^^^^^ fix: declare x as P<@Nullable String, L24> """, """ @@ -62,11 +62,11 @@ void test() { public void aSharedBoundBesideANestedMismatchIsWalkedOnce() { assertMessage( """ - incompatible nullability in List type argument E -> Box type argument B: found @Nullable String, required String - found: List, @Nullable String>> - ^^^^^^^^^^^^^^^^ - required: List, String>> - ^^^^^^ + incompatible nullability in List type argument E -> Box type argument B: source has @Nullable String where target requires String + source: List, @Nullable String>> + ^^^^^^^^^^^^^^^^ + target: List, String>> + ^^^^^^ fix: declare x as List, @Nullable String>> """, """ 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 c864937fbc..b66c82f71a 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 @@ -7,7 +7,7 @@ * {@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 source itself * is viewed as a supertype and 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. + * view on a {@code source viewed as:} line and draws the source carets under it. */ public class ViewedSourceTests extends MismatchMessageTestBase { @@ -15,11 +15,11 @@ public class ViewedSourceTests extends MismatchMessageTestBase { public void aCarriedOverNodeInsideAWildcardBoundIsMarkedOnTheWrittenSource() { assertMessage( """ - incompatible nullability in Base type argument T -> wildcard upper bound -> List type argument E: found @Nullable String, required String - found: Sub> - ^^^^^^^^^^^^^^^^ - required: Base> - ^^^^^^ + incompatible nullability in Base type argument T -> wildcard upper bound -> List type argument E: source has @Nullable String where target requires String + source: Sub> + ^^^^^^^^^^^^^^^^ + target: Base> + ^^^^^^ """, """ static class Base {} @@ -36,11 +36,11 @@ void test(Sub> s) { public void aCarriedOverNodeInsideAnArrayElementIsMarkedOnTheWrittenSource() { assertMessage( """ - incompatible nullability in Base type argument T -> array element: found @Nullable String, required String - found: Sub<@Nullable String []> - ^^^^^^^^^^^^^^^^ - required: Base - ^^^^^^ + incompatible nullability in Base type argument T -> array element: source has @Nullable String where target requires String + source: Sub<@Nullable String []> + ^^^^^^^^^^^^^^^^ + target: Base + ^^^^^^ """, """ static class Base {} @@ -57,11 +57,11 @@ void test(Sub<@Nullable String[]> s) { public void aCarriedOverCaptureIsMarkedOnTheWrittenSourceAndKeepsItsProvenance() { assertMessage( """ - incompatible nullability in Base type argument T -> wildcard upper bound: found @Nullable Object, required Object - found: Sub - ^^^^^^^^^^^^ - required: Base - ^^^^^^ + incompatible nullability in Base type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object + source: Sub + ^^^^^^^^^^^^ + target: Base + ^^^^^^ note: the source wildcard is the type argument for type parameter T of Sub """, """ @@ -82,12 +82,12 @@ void test() { public void aNodeFromTheSubclassDeclarationIsMarkedOnTheViewedSource() { assertMessage( """ - incompatible nullability in Base type argument T -> List type argument E: found @Nullable String, required String - found: Sub - found as: Base> - ^^^^^^^^^^^^^^^^ - required: Base> - ^^^^^^ + incompatible nullability in Base type argument T -> List type argument E: source has @Nullable String where target requires String + source: Sub + source viewed as: Base> + ^^^^^^^^^^^^^^^^ + target: Base> + ^^^^^^ """, """ static class Base {} @@ -104,12 +104,12 @@ void test(Sub s) { public void aWildcardFromTheSubclassDeclarationGetsANoteThatStatesItsBoundOnly() { assertMessage( """ - incompatible nullability in Base type argument B -> wildcard upper bound -> List type argument E -> wildcard upper bound: found @Nullable Object, required Object - found: Sub - found as: Base> - ^ - required: Base> - ^^^^^^ + incompatible nullability in Base type argument B -> wildcard upper bound -> List type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + source: Sub + source viewed as: Base> + ^ + target: Base> + ^^^^^^ note: the source wildcard has an implicit @Nullable Object upper bound """, """ @@ -127,11 +127,11 @@ void test(Sub s) { public void aPathAcrossAViewReachesIntoWhateverTheSubclassPassed() { assertMessage( """ - incompatible nullability in Base type argument B -> wildcard upper bound -> List type argument E -> wildcard upper bound: found @Nullable Object, required Object - found: Indirect - ^ - required: Base> - ^^^^^^ + incompatible nullability in Base type argument B -> wildcard upper bound -> List type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + source: Indirect + ^ + target: Base> + ^^^^^^ note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter X of Indirect fix: declare i as Indirect """, @@ -173,11 +173,11 @@ public class Result extends a.Result {} "MESSAGE", messageIs( """ - incompatible nullability in Result type argument T: found @Nullable String, required String - found: Result<@Nullable String> - ^^^^^^^^^^^^^^^^ - required: Result - ^^^^^^ + incompatible nullability in Result type argument T: source has @Nullable String where target requires String + source: Result<@Nullable String> + ^^^^^^^^^^^^^^^^ + target: Result + ^^^^^^ """)) .addSourceLines( "Test.java", @@ -196,11 +196,11 @@ void test(b.Result<@Nullable String> r) { public void aReorderingSubclassIsMarkedAtTheArgumentItPassesOn() { assertMessage( """ - incompatible nullability in List type argument E -> wildcard upper bound -> Pair type argument A: found @Nullable String, required String - found: List> - ^^^^^^^^^^^^^^^^ - required: List> - ^^^^^^ + incompatible nullability in List type argument E -> wildcard upper bound -> Pair type argument A: source has @Nullable String where target requires String + source: List> + ^^^^^^^^^^^^^^^^ + target: List> + ^^^^^^ """, """ static class Pair {} @@ -217,11 +217,11 @@ void test(List> l) { public void aReorderingSubclassInsideAnArrayIsMarkedAtTheArgumentItPassesOn() { assertMessage( """ - incompatible nullability in array element -> Pair type argument A: found @Nullable String, required String - found: Swap [] - ^^^^^^^^^^^^^^^^ - required: Pair [] - ^^^^^^ + incompatible nullability in array element -> Pair type argument A: source has @Nullable String where target requires String + source: Swap [] + ^^^^^^^^^^^^^^^^ + target: Pair [] + ^^^^^^ """, """ static class Pair {} @@ -238,11 +238,11 @@ void test(Swap[] a) { public void aReorderingSubclassTwoLevelsDownIsMarkedAtTheArgumentItPassesOn() { assertMessage( """ - incompatible nullability in List type argument E -> wildcard upper bound -> List type argument E -> wildcard upper bound -> Pair type argument A: found @Nullable String, required String - found: List>> - ^^^^^^^^^^^^^^^^ - required: List>> - ^^^^^^ + incompatible nullability in List type argument E -> wildcard upper bound -> List type argument E -> wildcard upper bound -> Pair type argument A: source has @Nullable String where target requires String + source: List>> + ^^^^^^^^^^^^^^^^ + target: List>> + ^^^^^^ """, """ static class Pair {} @@ -259,11 +259,11 @@ void test(List>> l) { public void anEnclosingTypeArgumentOfASubclassIsMarkedOnTheWrittenSource() { assertMessage( """ - incompatible nullability in enclosing type -> Outer type argument T: found @Nullable String, required String - found: Outer<@Nullable String>.SubInner - ^^^^^^^^^^^^^^^^ - required: Outer.Inner - ^^^^^^ + incompatible nullability in enclosing type -> Outer type argument T: source has @Nullable String where target requires String + source: Outer<@Nullable String>.SubInner + ^^^^^^^^^^^^^^^^ + target: Outer.Inner + ^^^^^^ """, """ static class Outer { diff --git a/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java b/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java index 5c13338d8c..c36ebd06f8 100644 --- a/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java +++ b/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java @@ -611,7 +611,7 @@ public void deeplyNestedTypeAnnot() { @NullMarked public class Test { void testPositive(NestedAnnots> p) { - // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> NestedAnnots type argument T: a type argument must match exactly; found String, required @Nullable String + // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> NestedAnnots type argument T: a type argument must match exactly; source has String where target requires @Nullable String NestedAnnots.deeplyNested(p); } void testNegative(NestedAnnots> p) { @@ -638,7 +638,7 @@ public void nestedArray1() { @NullMarked public class Test { void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> array element -> NestedAnnots type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> array element -> NestedAnnots type argument T: source has @Nullable String where target requires String NestedAnnots[]> unused = NestedAnnots.nestedArray1(); } void testNegative() { @@ -665,7 +665,7 @@ public void nestedArray2() { @NullMarked public class Test { void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T: found String @Nullable [], required String [] + // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T: source has String @Nullable [] where target requires String [] NestedAnnots unused = NestedAnnots.nestedArray2(); } void testNegative() { @@ -692,11 +692,11 @@ public void nestedWildcards() { @NullMarked public class Test { void testUpper(NestedAnnots<@Nullable String> t) { - // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> wildcard upper bound: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> wildcard upper bound: source has @Nullable String where target requires String NestedAnnots.wildcardUpper(t); } void testLower(NestedAnnots t) { - // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> wildcard lower bound: found String, required a supertype of @Nullable String + // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> wildcard lower bound: source has String where target requires a supertype of @Nullable String NestedAnnots.wildcardLower(t); } } @@ -725,7 +725,7 @@ NestedAnnots testDirect( // should reject since return type of wildcardUpperTypeVariable // is modeled to be NestedAnnots, which // here is incompatible with the return type NestedAnnots - // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> wildcard upper bound: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> wildcard upper bound: source has @Nullable String where target requires String return receiver.wildcardUpperTypeVariable(); } @@ -734,7 +734,7 @@ NestedAnnots testWithSelf( // should reject since return type of wildcardUpperTypeVariable // is modeled to be NestedAnnots, which // here is incompatible with the return type NestedAnnots - // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> wildcard upper bound: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> wildcard upper bound: source has @Nullable String where target requires String return receiver.self().wildcardUpperTypeVariable(); } @@ -745,7 +745,7 @@ NestedAnnots testWithVar( // should reject since return type of wildcardUpperTypeVariable // is modeled to be NestedAnnots, which // here is incompatible with the return type NestedAnnots - // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> wildcard upper bound: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> wildcard upper bound: source has @Nullable String where target requires String return foo.wildcardUpperTypeVariable(); } @@ -771,7 +771,7 @@ public void nestedAnnotationsOnUnboundedWildcardBounds() { public class Test { UnboundWildcards testLiteral() { - // BUG: Diagnostic contains: incompatible nullability in UnboundWildcards type argument T -> wildcard upper bound: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in UnboundWildcards type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object return UnboundWildcards.literalWildcard(); } @@ -781,7 +781,7 @@ UnboundWildcards testLiteral() { UnboundWildcards testCaptured( UnboundWildcards receiver) { - // BUG: Diagnostic contains: incompatible nullability in UnboundWildcards type argument T -> wildcard upper bound: found @Nullable Object, required Object + // BUG: Diagnostic contains: incompatible nullability in UnboundWildcards type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object return receiver.self().typeVariable(); } @@ -811,9 +811,9 @@ public void multipleArgs() { public class Test { void testPositive() { NestedAnnots.multipleArgs( - // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T: found @Nullable String, required String + // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T: source has @Nullable String where target requires String new NestedAnnots<@Nullable String>(), - // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T: a type argument must match exactly; found Integer, required @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T: a type argument must match exactly; source has Integer where target requires @Nullable Integer new NestedAnnots()); } void testNegative() { From 697497e5c14c8deba213163e72f6d13610213198 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Sat, 28 Nov 2026 22:33:32 +0300 Subject: [PATCH 11/43] Attach the declaration edit only to a local variable A generic nullability mismatch attached its fix: rewrite as an Error Prone edit wherever the declaration was in the compilation unit. Patch mode then applied it unasked: with SuggestSuppressions=true the edit came before the suppression ErrorBuilder appends, so the run retyped declarations instead of suppressing (F42), and without it the run narrowed public and overriding parameters and fields (F45). The edit now goes only to a local variable, and not at all in a run that suggests suppressions; a parameter or a field keeps the fix: line without the edit. The local declaration comes from an index of the compilation unit built once, on the first lookup, so a file with k mismatches is walked once rather than up to twice per mismatch (F44), and the JavacTrees lookup that broke :nullaway:javadoc is gone (F43). A suppressed mismatch now returns before its message is built, which reran the check (F59). The message tests now compare the Did you mean line too, so each states the edit it carries. Assisted-by: Claude Code (claude-opus-5-5) --- .../java/com/uber/nullaway/ErrorBuilder.java | 28 ++- .../nullaway/generics/GenericsChecks.java | 61 ++++-- .../generics/LocalVariableDeclarations.java | 75 +++++++ .../generics/NullabilityMismatchMessage.java | 88 ++++---- .../generics/MismatchMessageWorkTests.java | 113 ++++++++++ .../jspecify/mismatchmessage/FixTests.java | 207 ++++++++++++++++-- .../MismatchMessageTestBase.java | 20 +- .../jspecify/mismatchmessage/PathTests.java | 1 + .../mismatchmessage/TargetTypeFixTests.java | 9 +- .../mismatchmessage/TraversalCostTests.java | 2 + 10 files changed, 509 insertions(+), 95 deletions(-) create mode 100644 nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java create mode 100644 nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java diff --git a/nullaway/src/main/java/com/uber/nullaway/ErrorBuilder.java b/nullaway/src/main/java/com/uber/nullaway/ErrorBuilder.java index 50b36cbf10..2c9a653f57 100755 --- a/nullaway/src/main/java/com/uber/nullaway/ErrorBuilder.java +++ b/nullaway/src/main/java/com/uber/nullaway/ErrorBuilder.java @@ -219,18 +219,9 @@ private Description createErrorDescriptionImpl( @Nullable Symbol nonNullTarget, @Nullable ExpressionTree nullableExpression) { Description.Builder builder = descriptionBuilder.setMessage(errorMessage.message); - String checkName = CORE_CHECK_NAME; - if (errorMessage.messageType.equals(GET_ON_EMPTY_OPTIONAL)) { - checkName = OPTIONAL_CHECK_NAME; - } else if (errorMessage.messageType.equals(FIELD_NO_INIT) - || errorMessage.messageType.equals(METHOD_NO_INIT) - || errorMessage.messageType.equals(NONNULL_FIELD_READ_BEFORE_INIT)) { - checkName = INITIALIZATION_CHECK_NAME; - } - // Mildly expensive state.getPath() traversal, occurs only once per potentially // reported error. - if (hasPathSuppression(state.getPath(), checkName)) { + if (isSuppressed(errorMessage.messageType, state)) { return Description.NO_MATCH; } @@ -315,6 +306,23 @@ private Description createErrorDescriptionImpl( ((JCTree) nullableExpression).pos().getStartPosition()); } + /** + * Returns whether an error of {@code messageType} at {@code state.getPath()} is suppressed, so + * that {@link #createErrorDescription} would drop it. A reporter whose message is costly to build + * asks first. + */ + public boolean isSuppressed(ErrorMessage.MessageTypes messageType, VisitorState state) { + String checkName = CORE_CHECK_NAME; + if (messageType.equals(GET_ON_EMPTY_OPTIONAL)) { + checkName = OPTIONAL_CHECK_NAME; + } else if (messageType.equals(FIELD_NO_INIT) + || messageType.equals(METHOD_NO_INIT) + || messageType.equals(NONNULL_FIELD_READ_BEFORE_INIT)) { + checkName = INITIALIZATION_CHECK_NAME; + } + return hasPathSuppression(state.getPath(), checkName); + } + private static boolean canHaveSuppressWarningsAnnotation(Tree tree) { return tree instanceof MethodTree || (tree instanceof ClassTree classTree && classTree.getSimpleName().length() != 0) 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 f797743953..9fd3e8c2da 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -171,6 +171,10 @@ private InferenceFailure(@Nullable String errorMessage) { /** Maps each {@code var}-declared local to its declaration path. */ private final Map varLocalDeclarations = new LinkedHashMap<>(); + /** The local variable declarations a nullability mismatch fix rewrites, cleared per unit. */ + private final LocalVariableDeclarations localVariableDeclarations = + new LocalVariableDeclarations(); + /** * PolyNull results inferred separately from generic call inference, cached by invocation * identity. Results from joint generic inference remain in {@link InferenceSuccess}. @@ -458,32 +462,43 @@ private void reportInvalidInstantiationError( private void reportInvalidAssignmentInstantiationError( Tree tree, Type lhsType, Type rhsType, ExpressionTree rhsTree, VisitorState state) { - NullabilityMismatchMessage.Report report = - new NullabilityMismatchMessage(this, config, handler, state) - .build( - lhsType, - rhsType, - tree instanceof VariableTree variableTree ? variableTree : null, - rhsTree); reportNullabilityMismatch( - tree, ErrorMessage.MessageTypes.ASSIGN_GENERIC_NULLABLE, report, state); + tree, + ErrorMessage.MessageTypes.ASSIGN_GENERIC_NULLABLE, + lhsType, + rhsType, + tree instanceof VariableTree variableTree ? variableTree : null, + rhsTree, + state); } - /** Reports {@code report} at {@code tree}, with each of its fixes attached. */ + /** + * Reports at {@code tree} that {@code sourceType} cannot be assigned to {@code targetType}, with + * the fixes {@link NullabilityMismatchMessage} finds attached. A suppressed error builds no + * message, since building one reruns the check. + */ private void reportNullabilityMismatch( Tree tree, ErrorMessage.MessageTypes messageType, - NullabilityMismatchMessage.Report report, + Type targetType, + Type sourceType, + @Nullable VariableTree targetTypeDeclaration, + @Nullable ExpressionTree sourceExpression, VisitorState state) { + ErrorBuilder errorBuilder = analysis.getErrorBuilder(); + if (errorBuilder.isSuppressed(messageType, state)) { + return; + } + NullabilityMismatchMessage.Report report = + new NullabilityMismatchMessage(this, config, handler, state) + .build(targetType, sourceType, targetTypeDeclaration, sourceExpression); Description.Builder description = analysis.buildDescription(tree); for (SuggestedFix fix : report.fixes()) { description.addFix(fix); } state.reportMatch( - analysis - .getErrorBuilder() - .createErrorDescription( - new ErrorMessage(messageType, report.message()), description, state, null)); + errorBuilder.createErrorDescription( + new ErrorMessage(messageType, report.message()), description, state, null)); } private void reportInvalidReturnTypeError( @@ -491,8 +506,10 @@ private void reportInvalidReturnTypeError( reportNullabilityMismatch( tree, ErrorMessage.MessageTypes.RETURN_NULLABLE_GENERIC, - new NullabilityMismatchMessage(this, config, handler, state) - .build(methodType, returnType, null, tree), + methodType, + returnType, + null, + tree, state); } @@ -521,8 +538,10 @@ private void reportInvalidParametersNullabilityError( reportNullabilityMismatch( paramExpression, ErrorMessage.MessageTypes.PASS_NULLABLE_GENERIC, - new NullabilityMismatchMessage(this, config, handler, state) - .build(formalParameterType, actualParameterType, null, paramExpression), + formalParameterType, + actualParameterType, + null, + paramExpression, state); } @@ -4570,6 +4589,12 @@ public void clearCache() { inferredVarLocalTypes.clear(); varLocalDeclarations.clear(); nestedNullabilityRepairInProgress.clear(); + localVariableDeclarations.clear(); + } + + /** Returns the index of local variable declarations of the compilation unit being analyzed. */ + LocalVariableDeclarations localVariableDeclarations() { + return localVariableDeclarations; } public boolean isNullableAnnotated(Type type) { diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java b/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java new file mode 100644 index 0000000000..d909242e0d --- /dev/null +++ b/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java @@ -0,0 +1,75 @@ +package com.uber.nullaway.generics; + +import com.google.common.annotations.VisibleForTesting; +import com.google.errorprone.util.ASTHelpers; +import com.sun.source.tree.CompilationUnitTree; +import com.sun.source.tree.VariableTree; +import com.sun.source.util.TreePath; +import com.sun.source.util.TreePathScanner; +import com.sun.tools.javac.code.Symbol; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Consumer; +import javax.lang.model.element.ElementKind; +import org.jspecify.annotations.Nullable; + +/** + * Finds the declaration of a local variable of the compilation unit being analyzed. + * + *

The first lookup in a compilation unit walks it once and indexes every local variable + * declaration it holds; later lookups in the same unit read the index, so a unit with many + * diagnostics is walked once rather than once per diagnostic. {@link #clear} drops the index, which + * otherwise keeps the trees of the unit alive. + */ +final class LocalVariableDeclarations { + + /** + * Receives each compilation unit just before it is indexed. Tests set it to count the walks; it + * is {@code null} otherwise. + */ + @VisibleForTesting static volatile @Nullable Consumer indexListener; + + /** The compilation unit {@link #paths} indexes, or {@code null} before the first lookup. */ + private @Nullable CompilationUnitTree unit; + + private final Map paths = new HashMap<>(); + + /** + * Returns the path to the declaration of {@code variable} in {@code compilationUnit}, or {@code + * null} where {@code variable} is not a local variable declared there. + */ + @Nullable TreePath find(Symbol.VarSymbol variable, CompilationUnitTree compilationUnit) { + if (variable.getKind() != ElementKind.LOCAL_VARIABLE) { + return null; + } + if (unit != compilationUnit) { + index(compilationUnit); + } + return paths.get(variable); + } + + /** Forgets the indexed compilation unit. */ + void clear() { + unit = null; + paths.clear(); + } + + private void index(CompilationUnitTree compilationUnit) { + Consumer listener = indexListener; + if (listener != null) { + listener.accept(compilationUnit); + } + paths.clear(); + unit = compilationUnit; + new TreePathScanner<@Nullable Void, @Nullable Void>() { + @Override + public @Nullable Void visitVariable(VariableTree variable, @Nullable Void unused) { + Symbol symbol = ASTHelpers.getSymbol(variable); + if (symbol != null && symbol.getKind() == ElementKind.LOCAL_VARIABLE) { + paths.put(symbol, getCurrentPath()); + } + return super.visitVariable(variable, null); + } + }.scan(compilationUnit, 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 index bbd862a863..0726daaabf 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -11,10 +11,8 @@ import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; import com.sun.source.util.TreeScanner; -import com.sun.tools.javac.api.JavacTrees; import com.sun.tools.javac.code.Attribute; import com.sun.tools.javac.code.BoundKind; -import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.code.Type; @@ -109,12 +107,16 @@ * *

The fixes

* - *

A {@code fix} line names the declaration it rewrites and the type it declares, and both - * candidates 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 ?}. Where the declaration is in the compilation unit - * being analyzed and writes its type out, the line comes with an Error Prone fix that makes the - * edit. + *

A {@code fix} line names the declaration it rewrites and the type it declares: the source + * variable with explicit wildcard bounds, or the target variable with {@code @Nullable} added. Each + * candidate is checked before it is printed: it 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 ?}. Where the declaration is a local variable of the compilation + * unit being analyzed, writes its type out, and declares no other variable, the line comes with an + * Error Prone fix that makes the edit, except in a run that suggests suppressions, which asks for + * the suppression instead. A parameter or a field gets the line without the edit: its type is a + * contract that callers, overriders, and other assignments rely on, and the check that accepts the + * rewrite consults none of them. * *

The two candidates differ in what they presume. Writing an explicit bound on a wildcard the * source declaration already writes is a mechanical fix of that wildcard, so it is offered wherever @@ -265,12 +267,12 @@ Report build( "%s\n and %d more, not listed", separator, mismatches.size() - listed.size())); } List fixes = new ArrayList<>(); - VariableTree sourceDeclaration = sourceDeclaration(sourceExpression, sourceType); - if (sourceDeclaration != null) { + Symbol.VarSymbol sourceVariable = sourceVariable(sourceExpression, sourceType); + if (sourceVariable != null) { Type rewrittenSourceType = sourceTypeFix(targetType, sourceType, mismatches); if (rewrittenSourceType != null) { message.append(separator); - appendFix(message, fixes, sourceDeclaration, rewrittenSourceType); + appendFix(message, fixes, sourceVariable, rewrittenSourceType); separator = ""; } } @@ -278,33 +280,42 @@ Report build( Type rewrittenTargetType = targetTypeFix(targetType, sourceType, mismatches); if (rewrittenTargetType != null) { message.append(separator); - appendFix(message, fixes, targetTypeDeclaration, rewrittenTargetType); + appendFix(message, fixes, ASTHelpers.getSymbol(targetTypeDeclaration), rewrittenTargetType); } } return new Report(message.toString(), fixes); } /** - * Appends the {@code fix:} line that declares {@code declaration} with {@code type}, and adds the - * edit to {@code fixes} where the declaration is in the compilation unit being analyzed and - * writes its type out. + * Appends the {@code fix:} line that declares {@code variable} with {@code type}, and adds the + * edit to {@code fixes} where {@code variable} is a local variable of the compilation unit being + * analyzed, its declaration writes its type out and declares no other variable, and the run does + * not suggest suppressions. */ private void appendFix( - StringBuilder message, List fixes, VariableTree declaration, Type type) { + StringBuilder message, List fixes, Symbol.VarSymbol variable, Type type) { message.append( String.format( "\n fix: declare %s as %s", - declaration.getName(), GenericsChecks.prettyTypeForError(type, state))); + variable.getSimpleName(), GenericsChecks.prettyTypeForError(type, state))); + if (config.suggestSuppressions()) { + // the run asks for the suppression ErrorBuilder adds after these fixes, and patching + // applies only the first fix of a diagnostic + return; + } + // the type of a parameter or a field is a contract that callers, overriders, and other + // assignments rely on, and the check that accepts the rewrite consults none of them + TreePath declarationPath = + checks.localVariableDeclarations().find(variable, state.getPath().getCompilationUnit()); + if (declarationPath == null) { + return; + } + VariableTree declaration = (VariableTree) declarationPath.getLeaf(); Tree typeTree = declaration.getType(); - TreePath declarationPath = TreePath.getPath(state.getPath().getCompilationUnit(), declaration); - if (typeTree == null - || declarationPath == null - || ASTHelpers.hasImplicitType(declaration, state)) { - return; // diff-coverage: ignore -- javac versions differ in whether an inferred type gets a - // synthesized tree - } - if (isVarargs(declaration) || sharesTypeTree(declarationPath)) { - // the printed type has no form for "...", and a shared type tree declares other variables too + if (typeTree == null || ASTHelpers.hasImplicitType(declaration, state)) { + return; // diff-coverage: ignore -- javac versions differ in whether var gets a type tree + } + if (sharesTypeTree(declarationPath)) { return; } SuggestedFix.Builder fix = SuggestedFix.builder(); @@ -314,12 +325,6 @@ private void appendFix( fixes.add(fix.replace(typeTree, printed).build()); } - /** Whether {@code declaration} is a varargs parameter, whose type tree is written with "...". */ - private static boolean isVarargs(VariableTree declaration) { - Symbol symbol = ASTHelpers.getSymbol(declaration); - return symbol != null && (symbol.flags() & Flags.VARARGS) != 0; - } - /** * Whether the declaration at {@code declarationPath} shares its type tree with another variable, * as each variable of {@code List a, b;} does. @@ -360,11 +365,11 @@ private boolean hasNullableModifier(VariableTree declaration) { } /** - * Returns the declaration of the variable {@code sourceExpression} reads, where it is in the - * compilation unit being analyzed and declares the very type {@code sourceType}, so that a - * rewrite of that type is a rewrite of the declaration; {@code null} otherwise. + * Returns the variable {@code sourceExpression} reads, where it is declared in the compilation + * unit being analyzed with the very type {@code sourceType}, so that a rewrite of that type is a + * rewrite of the declaration; {@code null} otherwise. */ - private @Nullable VariableTree sourceDeclaration( + private Symbol.@Nullable VarSymbol sourceVariable( @Nullable ExpressionTree sourceExpression, Type sourceType) { if (sourceExpression == null || !(ASTHelpers.getSymbol(ASTHelpers.stripParentheses(sourceExpression)) @@ -377,11 +382,12 @@ private boolean hasNullableModifier(VariableTree declaration) { .equals(GenericsChecks.prettyTypeForError(sourceType, state))) { return null; } - TreePath path = JavacTrees.instance(state.context).getPath(variable); - return path != null - && path.getCompilationUnit() == state.getPath().getCompilationUnit() - && path.getLeaf() instanceof VariableTree declaration - ? declaration + Symbol.ClassSymbol outermostClass = variable.outermostClass(); + return outermostClass != null + && outermostClass.sourcefile != null + && outermostClass.sourcefile.equals( + state.getPath().getCompilationUnit().getSourceFile()) + ? variable : null; } diff --git a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java new file mode 100644 index 0000000000..15e98131fd --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java @@ -0,0 +1,113 @@ +package com.uber.nullaway.generics; + +import static com.google.common.truth.Truth.assertWithMessage; + +import com.google.errorprone.CompilationTestHelper; +import com.uber.nullaway.NullAway; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.junit.Test; + +/** + * Building a generic nullability mismatch message walks the compilation unit to find the local + * variable a fix rewrites. The walk happens at most once per unit, and not at all for a mismatch + * whose error is suppressed. + */ +public class MismatchMessageWorkTests { + + @Test + public void oneWalkOfTheCompilationUnitServesEveryLocalFix() { + List walks = + walksWhileCompiling( + """ + import java.util.Collection; + import java.util.List; + import org.jspecify.annotations.NullMarked; + @NullMarked + class Test { + static void take(Collection c) {} + static List make() { + throw new RuntimeException(); + } + void assignment() { + List l = make(); + // BUG: Diagnostic contains: fix: declare l as List + Collection c = l; + } + void argument() { + List l = make(); + // BUG: Diagnostic contains: fix: declare l as List + take(l); + } + Collection returned() { + List l = make(); + // BUG: Diagnostic contains: fix: declare l as List + return l; + } + } + """); + assertWithMessage("compilation units walked for local declarations") + .that(walks) + .containsExactly("Test.java"); + } + + @Test + public void aSuppressedMismatchCostsNoWalk() { + List walks = + walksWhileCompiling( + """ + import java.util.Collection; + import java.util.List; + import org.jspecify.annotations.NullMarked; + @NullMarked + class Test { + static void take(Collection c) {} + static List make() { + throw new RuntimeException(); + } + @SuppressWarnings("NullAway") + void assignment() { + List l = make(); + Collection c = l; + } + @SuppressWarnings("NullAway") + void argument() { + List l = make(); + take(l); + } + @SuppressWarnings("NullAway") + Collection returned() { + List l = make(); + return l; + } + } + """); + assertWithMessage("compilation units walked for local declarations").that(walks).isEmpty(); + } + + /** + * Compiles {@code source} as {@code Test.java} in JSpecify mode, expecting the diagnostics its + * {@code // BUG: Diagnostic contains:} comments mark and no others, and returns the file name of + * each compilation unit indexed for local declarations, once per walk. + */ + private List walksWhileCompiling(String source) { + List walks = Collections.synchronizedList(new ArrayList<>()); + LocalVariableDeclarations.indexListener = + unit -> { + String path = unit.getSourceFile().getName(); + walks.add(path.substring(path.lastIndexOf('/') + 1)); + }; + try { + CompilationTestHelper.newInstance(NullAway.class, getClass()) + .setArgs( + JSpecifyJavacConfig.withJSpecifyModeArgs( + List.of("-XepOpt:NullAway:OnlyNullMarked=true"))) + .addSourceLines("Test.java", source) + .doTest(); + } finally { + LocalVariableDeclarations.indexListener = null; + } + return walks; + } +} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java index 3ab80edfcf..0e27abfa1d 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java @@ -5,6 +5,7 @@ import com.uber.nullaway.NullAway; import com.uber.nullaway.generics.JSpecifyJavacConfig; import java.io.IOException; +import java.util.ArrayList; import java.util.List; import org.junit.Rule; import org.junit.Test; @@ -12,21 +13,155 @@ /** * A {@code fix:} line comes with an Error Prone fix that rewrites the type the named declaration - * writes, where that declaration is in the compilation unit being analyzed and writes its type out. + * writes, where that declaration is a local variable of the compilation unit being analyzed, writes + * its type out, and declares no other variable, and the run does not suggest suppressions. */ public class FixTests { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); - private BugCheckerRefactoringTestHelper makeHelper() { + private BugCheckerRefactoringTestHelper makeHelper(String... extraArgs) { + List args = new ArrayList<>(); + args.add("-d"); + args.add(temporaryFolder.getRoot().getAbsolutePath()); + args.add("-XepOpt:NullAway:OnlyNullMarked=true"); + args.addAll(List.of(extraArgs)); return BugCheckerRefactoringTestHelper.newInstance(NullAway.class, getClass()) - .setArgs( - ImmutableList.copyOf( - JSpecifyJavacConfig.withJSpecifyModeArgs( - List.of( - "-d", - temporaryFolder.getRoot().getAbsolutePath(), - "-XepOpt:NullAway:OnlyNullMarked=true")))); + .setArgs(ImmutableList.copyOf(JSpecifyJavacConfig.withJSpecifyModeArgs(args))); + } + + @Test + public void withSuggestSuppressionsTheEditIsTheSuppression() throws IOException { + makeHelper("-XepOpt:NullAway:SuggestSuppressions=true") + .addInputLines( + "Test.java", + """ + import java.util.ArrayList; + import java.util.Collection; + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static List<@Nullable String> get() { + throw new RuntimeException(); + } + void assignment() { + List l = get(); + } + Collection argument(List list) { + List result = new ArrayList<>(); + result.addAll(list); + return result; + } + } + """) + .addOutputLines( + "Test.java", + """ + import java.util.ArrayList; + import java.util.Collection; + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static List<@Nullable String> get() { + throw new RuntimeException(); + } + void assignment() { + @SuppressWarnings("NullAway") + List l = get(); + } + @SuppressWarnings("NullAway") + Collection argument(List list) { + List result = new ArrayList<>(); + result.addAll(list); + return result; + } + } + """) + .doTest(); + } + + @Test + public void theEditRewritesOnlyALocalVariable() throws IOException { + makeHelper() + .addInputLines( + "Test.java", + """ + import java.util.Collection; + import java.util.HashMap; + import java.util.List; + import java.util.Map; + import org.jspecify.annotations.NullMarked; + @NullMarked + class Test { + interface I { + void overridden(List l); + } + static void take(Collection c) {} + static void takeMap(Map m) {} + static List make() { + throw new RuntimeException(); + } + public Map field = new HashMap<>(); + public void parameter(List l) { + take(l); + } + static class Impl implements I { + @Override + public void overridden(List l) { + take(l); + } + } + void fieldRead() { + takeMap(field); + } + void local() { + List l = make(); + take(l); + } + } + """) + .addOutputLines( + "Test.java", + """ + import java.util.Collection; + import java.util.HashMap; + import java.util.List; + import java.util.Map; + import org.jspecify.annotations.NullMarked; + @NullMarked + class Test { + interface I { + void overridden(List l); + } + static void take(Collection c) {} + static void takeMap(Map m) {} + static List make() { + throw new RuntimeException(); + } + public Map field = new HashMap<>(); + public void parameter(List l) { + take(l); + } + static class Impl implements I { + @Override + public void overridden(List l) { + take(l); + } + } + void fieldRead() { + takeMap(field); + } + void local() { + List l = make(); + take(l); + } + } + """) + .doTest(); } @Test @@ -77,23 +212,44 @@ void test() { } @Test - public void theSourceFixKeepsANullableAnnotationWrittenAmongTheModifiers() throws IOException { + public void theSourceFixKeepsEveryNullableAnnotationTheDeclarationWrites() throws IOException { makeHelper() .addInputLines( "Test.java", """ import java.util.Collection; import java.util.List; + import java.util.Map; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked class Test { static void take(Collection c) {} - void test(@Nullable List l) { + static void takeMap(Map m) {} + static @Nullable List list() { + throw new RuntimeException(); + } + static @Nullable Map map() { + throw new RuntimeException(); + } + void modifier() { + @Nullable List l = list(); + if (l != null) { + take(l); + } + } + void typeTree() { + java.util.@Nullable List l = list(); if (l != null) { take(l); } } + void modifierAndTypeArgument() { + @Nullable Map m = map(); + if (m != null) { + takeMap(m); + } + } } """) .addOutputLines( @@ -101,16 +257,37 @@ void test(@Nullable List l) { """ import java.util.Collection; import java.util.List; + import java.util.Map; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked class Test { static void take(Collection c) {} - void test(@Nullable List l) { + static void takeMap(Map m) {} + static @Nullable List list() { + throw new RuntimeException(); + } + static @Nullable Map map() { + throw new RuntimeException(); + } + void modifier() { + @Nullable List l = list(); if (l != null) { take(l); } } + void typeTree() { + @Nullable List l = list(); + if (l != null) { + take(l); + } + } + void modifierAndTypeArgument() { + @Nullable Map m = map(); + if (m != null) { + takeMap(m); + } + } } """) .doTest(); @@ -228,7 +405,7 @@ void test() { } @Test - public void noEditForAVarargsParameterOrADeclarationOfSeveralVariables() throws IOException { + public void noEditForADeclarationOfSeveralVariables() throws IOException { makeHelper() .addInputLines( "Test.java", @@ -240,10 +417,6 @@ public void noEditForAVarargsParameterOrADeclarationOfSeveralVariables() throws @NullMarked class Test { static void take(Collection c) {} - static void takeArray(Collection[] c) {} - void varargs(List... lists) { - takeArray(lists); - } void several() { List first = new ArrayList<>(), second = new ArrayList<>(); take(first); 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 index cecd6f9da0..5acc13b84c 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/MismatchMessageTestBase.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/MismatchMessageTestBase.java @@ -6,7 +6,6 @@ import java.util.List; import java.util.Map; import java.util.function.Predicate; -import java.util.regex.Pattern; /** * Compiles a {@code @NullMarked} class in JSpecify mode and compares the whole text of the generic @@ -83,23 +82,28 @@ static Predicate messageIs(String 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. The {@code Did you mean} - * line Error Prone appends for an attached fix is not part of the message, and {@link FixTests} - * checks the fixes. + * line Error Prone appends for an attached fix is part of the expected message, so a test that + * expects none states that the diagnostic carries no edit; {@link FixTests} applies the edits. */ 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 )"; - private static final Pattern FIX_LINE = Pattern.compile("\n Did you mean '.*'\\?$"); @Override public boolean test(String diagnostic) { - String message = FIX_LINE.matcher(diagnostic).replaceFirst(""); - if (!message.startsWith(PREFIX) || !message.endsWith(LINK_LINE)) { + if (!diagnostic.startsWith(PREFIX)) { return false; } - return message - .substring(PREFIX.length(), message.length() - LINK_LINE.length()) + int link = diagnostic.indexOf(LINK_LINE); + if (link < 0) { + return false; + } + // Error Prone appends "\n Did you mean '...'?" after the link line; the expected message + // carries it as its last line + String edit = diagnostic.substring(link + LINK_LINE.length()); + return (diagnostic.substring(PREFIX.length(), link) + + (edit.isEmpty() ? "" : edit.substring(1) + "\n")) .equals(expected); } 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 index 58bb0185d3..356af5cc49 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java @@ -257,6 +257,7 @@ public void aCapturedSourceIsComparedThroughItsUpperBound() { target: List ^^^^^^ fix: declare l as List<@Nullable String> + Did you mean 'List<@Nullable String> l = wl.get(0);'? """, """ void test(List> wl) { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java index a9da09e316..365f5efa01 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java @@ -27,7 +27,8 @@ public void theFixIsOfferedOnlyWhereTheDiagnosticPointsAtTheTargetTypeDeclaratio Map.of( "DECLARATION", MAP_VALUES_MESSAGE - + " fix: declare declared as Map\n", + + " fix: declare declared as Map\n" + + " Did you mean 'Map declared = m;'?\n", "CALL", MAP_VALUES_MESSAGE, "ASSIGNMENT", @@ -70,6 +71,7 @@ public void theFixIsTheDeclaredTypeNotAnInstantiatedSupertype() { target: List ^^^^^^ fix: declare l as List<@Nullable String> + Did you mean 'List<@Nullable String> l = s;'? """, """ static class Sub extends ArrayList {} @@ -95,6 +97,7 @@ public void theFixReplacesTheNodeAtEveryKindOfStep() { note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List fix: declare list as List fix: declare c as Collection + Did you mean 'Collection c = list;'? """, "ARRAY_ELEMENT", """ @@ -104,6 +107,7 @@ public void theFixReplacesTheNodeAtEveryKindOfStep() { target: List [] ^^^^^^ fix: declare d as List<@Nullable String> [] + Did you mean 'List<@Nullable String> [] d = src;'? """, "ENCLOSING_TYPE", """ @@ -113,6 +117,7 @@ public void theFixReplacesTheNodeAtEveryKindOfStep() { target: Outer.Inner ^^^^^^ fix: declare d as Outer<@Nullable String>.Inner + Did you mean 'Outer<@Nullable String>.Inner d = src;'? """), """ static class Outer { @@ -150,6 +155,7 @@ public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { target: Map ^^^^^^ fix: declare plain as Map + Did you mean 'Map plain = m;'? """, "TAINTED", """ @@ -175,6 +181,7 @@ public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { target: Map ^^^^^^ fix: declare d as Map + Did you mean 'Map d = m;'? """), """ @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java index f6770e54e2..ff7d079e97 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java @@ -20,6 +20,7 @@ public void aSharedBoundBesideTheMismatchIsWalkedOnce() { target: P> ^^^^^^ fix: declare x as P<@Nullable String, L24> + Did you mean 'P<@Nullable String, L24> x = get();'? """, """ interface P {} @@ -68,6 +69,7 @@ public void aSharedBoundBesideANestedMismatchIsWalkedOnce() { target: List, String>> ^^^^^^ fix: declare x as List, @Nullable String>> + Did you mean 'List, @Nullable String>> x = l;'? """, """ interface P {} From 1c34a3709a1c12c8f3235b5ffa4470e588d1f036 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Sat, 28 Nov 2026 22:39:54 +0300 Subject: [PATCH 12/43] Follow a supertype view through the declared supertype The source caret was placed by finding the compared node as the same Type instance in the written type. A non-generic class has one instance wherever it appears, so for Sub implements Base the caret went under the whole written Sub although the Sub in the view comes from the declaration (F55). Where the check views a written class as a supertype, the recorder now walks the supertype that class declares, by position, and returns to the written type only where that walk reaches one of the class's own type variables. The instance search, TypePath.append, and the Located record that restated a Track are gone (F68). Coverage markers now sit on the line they acknowledge and claim only what holds. The fallback for a rejection that recorded no position is replaced by a Verify of that invariant (F16). replaceAt descends into a ? super bound, so a target such as List> gets its fix (F54). A test on JDK 21 reaches an intersection target whose two components both reject the source, and the "JDK 25+ only" markers on that path are dropped (F57). Comments: enterLowerBounds states the direction the check asks (F52), enterClassComparison names only its parameters (F66), and the class comment says how a step is followed in each case (F67). Assisted-by: Claude Code (claude-opus-5-5) --- .../CheckIdenticalNullabilityVisitor.java | 4 +- .../generics/NullabilityMismatchMessage.java | 160 +++----- .../generics/NullabilityMismatches.java | 362 +++++++++--------- .../com/uber/nullaway/generics/TypePath.java | 21 +- .../mismatchmessage/TargetTypeFixTests.java | 18 + .../mismatchmessage/ViewedSourceTests.java | 68 ++++ 6 files changed, 342 insertions(+), 291 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 a91567d1d7..45549ee288 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitor.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitor.java @@ -328,9 +328,9 @@ private Boolean handleIntersectionType( for (Type bound : intersectionType.getExplicitComponents()) { if (!bound.accept(this, rhsType)) { if (mismatches == null) { - return false; // diff-coverage: ignore -- reached on JDK 25+ only + return false; } - contained = false; // diff-coverage: ignore -- reached on JDK 25+ only + contained = false; } } return contained; 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 0726daaabf..9177cdd3e8 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -2,6 +2,7 @@ import static com.uber.nullaway.generics.TypeMetadataBuilder.TYPE_METADATA_BUILDER; +import com.google.common.base.Verify; import com.google.errorprone.VisitorState; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.util.ASTHelpers; @@ -74,10 +75,6 @@ * Where the target bounds a {@code ? super} wildcard, the target side reads {@code a supertype of} * that bound. * - *

Where the check records no position, the message is the two types and the subtype relation - * between them, opening {@code incompatible types:}, which is all that can be said about a - * difference nothing located. - * *

The caret

* *

A caret marks the smallest node whose nullness differs, {@code @Nullable String} rather than @@ -182,9 +179,6 @@ record Report(String message, List fixes) {} * Builds the diagnostic for an assignment, a return, or an argument the nullability check * rejected. * - *

Where the check records no rejected position, 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 targetType the type the pseudo-assignment assigns to * @param sourceType the type of the value assigned * @param targetTypeDeclaration the declaration of a variable whose type is {@code targetType} @@ -198,16 +192,17 @@ Report build( Type sourceType, @Nullable VariableTree targetTypeDeclaration, @Nullable ExpressionTree sourceExpression) { - NullabilityMismatches recorded = new NullabilityMismatches(targetType, sourceType); + NullabilityMismatches recorded = + new NullabilityMismatches(targetType, sourceType, state.getTypes(), config); new CheckIdenticalNullabilityVisitor(state, checks, config, handler, recorded) .isSubtype(targetType, sourceType); List mismatches = recorded.mismatches(); - if (mismatches.isEmpty()) { - return new Report( - plainIncompatibleTypesMessage(targetType, sourceType), - List.of()); // diff-coverage: ignore -- every false result of the visitor comes from a - // reject call, so a rejection records a position - } + // the visitor returns false only after a reject call, and the caller saw it return false + Verify.verify( + !mismatches.isEmpty(), + "the check rejected %s for %s without recording a position", + sourceType, + targetType); List listed = mismatches.size() > MAX_LISTED_MISMATCHES ? mismatches.subList(0, MAX_LISTED_MISMATCHES) @@ -391,32 +386,6 @@ private boolean hasNullableModifier(VariableTree declaration) { : null; } - /** - * 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 targetType, Type sourceType) { - String prettySourceType = GenericsChecks.prettyTypeForError(sourceType, state); - String prettyTargetType = GenericsChecks.prettyTypeForError(targetType, state); - String result = - String.format( - "incompatible types: %s cannot be converted to %s", prettySourceType, prettyTargetType); - if (!ASTHelpers.isSameType(targetType, sourceType, state) - && targetType.getKind() == TypeKind.DECLARED - && sourceType.getKind() == TypeKind.DECLARED - && targetType.asElement() instanceof Symbol.ClassSymbol classSymbol) { - Type asSuper = - TypeSubstitutionUtils.asSuper(state.getTypes(), sourceType, classSymbol, config); - if (asSuper != null) { - result += - String.format( - " (%s is a subtype of %s)", - prettySourceType, GenericsChecks.prettyTypeForError(asSuper, state)); - } - } - return result; - } - /** * The line a reader sees first, and the only one some tools show, so it stands alone: it names * where the first difference sits, how many other positions differ, and the pair at the first. @@ -628,8 +597,7 @@ private String mismatchDetail(NullabilityMismatches.Mismatch mismatch, int numbe : note; } if (wildcard.kind == BoundKind.EXTENDS) { - return null; // diff-coverage: ignore -- a ? extends wildcard prints its bound, so the caret - // goes below it + return null; // diff-coverage: ignore -- a caret goes below a written bound } // the step that reached the wildcard in the type the reader wrote names the type parameter it // instantiates there; javac's own link, WildcardType.bound, names a type parameter of whatever @@ -700,8 +668,7 @@ private String mismatchDetail(NullabilityMismatches.Mismatch mismatch, int numbe } rewrittenTargetType = replaceAt(rewrittenTargetType, targetNodePath.steps(), 0, rewritten); if (rewrittenTargetType == null) { - return null; // diff-coverage: ignore -- a path from the recorder always addresses a node - // the type has + return null; // diff-coverage: ignore -- see replaceAt } } return isDeclarable(rewrittenTargetType) @@ -728,14 +695,14 @@ private String mismatchDetail(NullabilityMismatches.Mismatch mismatch, int numbe return TypeSubstitutionUtils.typeWithAnnot(target, annotation.type); } } - return null; // diff-coverage: ignore -- isNullableAnnotated is true only where a nullable - // annotation is present + return null; // diff-coverage: ignore -- source carries a nullable annotation } /** * 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. + * by {@code replacement}, or {@code null} where {@code type} has no such node. A path the + * recorder gives a target node it located always reaches a node, since the recorder follows the + * written target by position and a replacement keeps the shape of the type. * *

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. @@ -746,62 +713,50 @@ private String mismatchDetail(NullabilityMismatches.Mismatch mismatch, int numbe return replacement; } TypePath.Step step = steps.get(from); - switch (step.kind()) { + Type child = + switch (step.kind()) { + case TYPE_ARGUMENT -> + type instanceof Type.ClassType classType + && step.index() < classType.getTypeArguments().size() + ? classType.getTypeArguments().get(step.index()) + : null; + case ENCLOSING_TYPE -> + type instanceof Type.ClassType classType ? classType.getEnclosingType() : null; + case WILDCARD_BOUND, WILDCARD_LOWER_BOUND -> + type instanceof Type.WildcardType wildcard + && wildcard.kind + == (step.kind() == TypePath.Step.Kind.WILDCARD_BOUND + ? BoundKind.EXTENDS + : BoundKind.SUPER) + ? wildcard.type + : null; + case ARRAY_ELEMENT -> + type instanceof Type.ArrayType arrayType ? arrayType.elemtype : null; + }; + if (child == null) { + return null; // diff-coverage: ignore -- see the method comment + } + Type replaced = replaceAt(child, steps, from + 1, replacement); + if (replaced == null) { + return null; // diff-coverage: ignore -- see the method comment + } + return switch (step.kind()) { case TYPE_ARGUMENT -> { - if (!(type instanceof Type.ClassType classType) - || step.index() >= classType.getTypeArguments().size()) { - return null; // diff-coverage: ignore -- a path from the recorder always addresses a node - // the type has - } + Type.ClassType classType = (Type.ClassType) type; List typeArguments = new ArrayList<>(classType.getTypeArguments()); - Type typeArgument = - replaceAt(typeArguments.get(step.index()), steps, from + 1, replacement); - if (typeArgument == null) { - return null; // diff-coverage: ignore -- a path from the recorder always addresses a node - // the type has - } - typeArguments.set(step.index(), typeArgument); - return TYPE_METADATA_BUILDER.createClassType( + typeArguments.set(step.index(), replaced); + yield TYPE_METADATA_BUILDER.createClassType( classType, classType.getEnclosingType(), typeArguments); } case ENCLOSING_TYPE -> { - if (!(type instanceof Type.ClassType classType)) { - return null; // diff-coverage: ignore -- a path from the recorder always addresses a node - // the type has - } - Type enclosingType = replaceAt(classType.getEnclosingType(), steps, from + 1, replacement); - return enclosingType == null - ? null // diff-coverage: ignore -- a path from the recorder always addresses a node the - // type has - : TYPE_METADATA_BUILDER.createClassType( - classType, enclosingType, classType.getTypeArguments()); - } - case WILDCARD_BOUND -> { - if (!(type instanceof Type.WildcardType wildcard) || wildcard.kind != BoundKind.EXTENDS) { - return null; // diff-coverage: ignore -- a path from the recorder always addresses a node - // the type has - } - Type bound = replaceAt(wildcard.type, steps, from + 1, replacement); - return bound == null ? null : TYPE_METADATA_BUILDER.createWildcardType(wildcard, bound); + Type.ClassType classType = (Type.ClassType) type; + yield TYPE_METADATA_BUILDER.createClassType( + classType, replaced, classType.getTypeArguments()); } - case WILDCARD_LOWER_BOUND -> { - // a lower bound accepts less once it is @Nullable, so no fix adds the annotation there - return null; - } - case ARRAY_ELEMENT -> { - if (!(type instanceof Type.ArrayType arrayType)) { - return null; // diff-coverage: ignore -- a path from the recorder always addresses a node - // the type has - } - Type elementType = replaceAt(arrayType.elemtype, steps, from + 1, replacement); - return elementType == null - ? null // diff-coverage: ignore -- a path from the recorder always addresses a node the - // type has - : TYPE_METADATA_BUILDER.createArrayType(arrayType, elementType); - } - } - throw new AssertionError( - step.kind()); // diff-coverage: ignore -- the switch covers every step kind + case WILDCARD_BOUND, WILDCARD_LOWER_BOUND -> + TYPE_METADATA_BUILDER.createWildcardType((Type.WildcardType) type, replaced); + case ARRAY_ELEMENT -> TYPE_METADATA_BUILDER.createArrayType((Type.ArrayType) type, replaced); + }; } /** @@ -838,8 +793,7 @@ private String mismatchDetail(NullabilityMismatches.Mismatch mismatch, int numbe 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 fix this method knows - continue; // diff-coverage: ignore -- the check rejects an upper bound only where the source - // is @Nullable and the target is not + continue; // diff-coverage: ignore -- the check rejects only these } boundForWildcard.put(sourceWildcard, targetUpperBound); } @@ -911,14 +865,12 @@ public Boolean visitArrayType(Type.ArrayType t, @Nullable Void unused) { @Override public Boolean visitCapturedType(Type.CapturedType t, @Nullable Void unused) { - return false; // diff-coverage: ignore -- a type holding a capture is no variable's - // declared type, so sourceDeclaration rejects it first + return false; // diff-coverage: ignore -- no variable declares a capture } @Override public Boolean visitErrorType(Type.ErrorType t, @Nullable Void unused) { - return false; // diff-coverage: ignore -- an unresolved type stops compilation before - // NullAway runs + return false; // diff-coverage: ignore -- javac stops first } @Override 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 92267ea091..fd802bbabf 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java @@ -1,8 +1,12 @@ package com.uber.nullaway.generics; +import static com.uber.nullaway.NullabilityUtil.castToNonNull; + 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 java.util.ArrayList; import java.util.List; import org.jspecify.annotations.Nullable; @@ -20,11 +24,14 @@ * path} line, in the classes it compared. The type the reader wrote is where a caret goes, and the * check does not always compare that type: it views a source {@code ArrayList<@Nullable String>} as * the {@code List<@Nullable String>} a target {@code List} names. So every step is also - * followed in the written type: by position where the written node has the shape of the compared - * one, and by instance where it does not, since a node the view carried over from the written type - * is the same {@code Type} object there. A node the view built itself, such as the {@code - * List<@Nullable String>} a subclass declared as {@code Sub extends Base>} - * passes to {@code Base}, sits nowhere in the written type and gets no caret there. + * followed in the written type. Where the written node is what the check compared, the step is + * followed by position. Where the check views a written class as a supertype, the step is followed + * in the supertype the class declares, until that reaches one of the class's own type variables: + * the view holds the written type argument for that variable there, as {@code ArrayList} hands + * {@code List} its {@code E}, and the step goes on by position in that argument. A node the + * declaration writes itself, such as the {@code List<@Nullable String>} in {@code Sub extends + * Base>} or the {@code Sub} in {@code Sub implements Base}, sits + * nowhere in the written type and gets no caret there. */ final class NullabilityMismatches { @@ -42,8 +49,7 @@ Relation swapped() { return switch (this) { case SAME -> SAME; case SUBTYPE -> SUPERTYPE; - case SUPERTYPE -> - SUBTYPE; // diff-coverage: ignore -- the visitor rejects only SAME and SUBTYPE + case SUPERTYPE -> SUBTYPE; // diff-coverage: ignore -- only SAME and SUBTYPE are rejected }; } } @@ -91,20 +97,35 @@ record Mismatch( * *

{@code LOCATED}: {@code node} sits at {@code path} and the printer shows it. {@code HIDDEN}: * the comparison went below a bound the printer does not show, and {@code node} is the wildcard - * at {@code path} that hides it, which is where a caret goes for everything below. {@code LOST}: - * the comparison reached a node the written type does not hold, and {@code node} is the nearest - * enclosing node it does hold, at {@code path}. + * at {@code path} that hides it, which is where a caret goes for everything below. {@code + * DECLARED}: the check views {@code node}, the written class at {@code path}, as a supertype, and + * the comparison stands at {@code declared} in the supertype that class declares. {@code LOST}: + * the comparison reached a node the written type does not hold. + * + * @param declared the node of the declared supertype where the comparison stands, for {@code + * DECLARED} only */ - private record Track(State state, Type node, TypePath path) { + private record Track(State state, Type node, TypePath path, @Nullable Type declared) { enum State { LOCATED, HIDDEN, + DECLARED, LOST } static Track located(Type node, TypePath path) { - return new Track(State.LOCATED, node, path); + return new Track(State.LOCATED, node, path, null); + } + + /** Returns the track where the comparison leaves the written type at {@code track}. */ + static Track lost(Track track) { + return new Track(State.LOST, track.node(), track.path(), null); + } + + /** Returns where a caret goes for this track, or {@code null} where it gets none. */ + @Nullable TypePath caret() { + return state == State.LOCATED || state == State.HIDDEN ? path : null; } } @@ -148,10 +169,15 @@ record Frame( private final List mismatches = new ArrayList<>(); + private final Types types; + private final Config config; + /** * Starts a record of the comparison of {@code sourceType} against {@code targetType}, as written. */ - NullabilityMismatches(Type targetType, Type sourceType) { + NullabilityMismatches(Type targetType, Type sourceType, Types types, Config config) { + this.types = types; + this.config = config; this.frame = new Frame( TypePath.root(), @@ -175,31 +201,62 @@ void restore(Frame saved) { } /** - * Notes that the check compares {@code lhs} against {@code rhsView}, the right side {@code rhs} - * viewed as the class of {@code lhs}. At the root of the source, a view of another class is what - * a caret goes into where the written source does not hold the compared node. Returns the frame - * to restore once the comparison ends. + * Notes that the check compares the left side against {@code rhsView}, the right side {@code rhs} + * viewed as the class of the left side. At the root of the source, a view of another class is + * what a caret goes into where the written source does not hold the compared node. Returns the + * frame to restore once the comparison ends. */ Frame enterClassComparison(Type rhs, Type rhsView) { Frame saved = frame; - if (frame.view() == null + Type viewedSource = frame.viewedSource(); + Track view = frame.view(); + if (view == null && !frame.swapped() && frame.targetSteps().isRoot() && !rhsView.tsym.equals(rhs.tsym)) { - frame = - new Frame( - frame.targetSteps(), - frame.target(), - frame.source(), - rhsView, - Track.located(rhsView, TypePath.root()), - frame.sourceShown(), - frame.swapped(), - frame.bound()); + viewedSource = rhsView; + view = Track.located(rhsView, TypePath.root()); + } + Track target = frame.target(); + Track source = frame.source(); + if (frame.swapped()) { + target = viewedAs(target, rhs, rhsView); + } else { + source = viewedAs(source, rhs, rhsView); + view = view == null ? null : viewedAs(view, rhs, rhsView); } + frame = + new Frame( + frame.targetSteps(), + target, + source, + viewedSource, + view, + frame.sourceShown(), + frame.swapped(), + frame.bound()); return saved; } + /** + * Returns {@code track} for a comparison that views {@code rhs}, the node {@code track} stands + * at, as {@code rhsView}: where that is another class, the comparison goes on in the supertype + * the written class declares. + */ + private Track viewedAs(Track track, Type rhs, Type rhsView) { + if (track.state() != Track.State.LOCATED + || !(track.node() instanceof Type.ClassType written) + || !written.tsym.equals(rhs.tsym) + || written.tsym.equals(rhsView.tsym) + || !(rhsView.tsym instanceof Symbol.ClassSymbol viewClass)) { + return track; + } + Type declared = TypeSubstitutionUtils.asSuper(types, written.tsym.type, viewClass, config); + return declared == null + ? Track.lost(track) + : new Track(Track.State.DECLARED, written, track.path(), declared); + } + /** Steps into type argument {@code index} of {@code lhs} and of {@code rhsView}. */ Frame enterTypeArgument(int index, Type.ClassType lhs, Type.ClassType rhsView) { return enter( @@ -252,7 +309,7 @@ Frame enterUpperBounds( /** * Steps into the lower bound of {@code lhsWildcard} and, where {@code rhsWildcard} is not {@code * null}, of that wildcard too, and swaps the sides: the check goes on to ask whether {@code - * rhsBound} is a subtype of {@code lhsBound}, so its left side is then the source. + * lhsBound} is a subtype of {@code rhsBound}, so its left side is then the source. */ Frame enterLowerBounds( Type lhsWildcard, Type lhsBound, @Nullable Type rhsWildcard, Type rhsBound) { @@ -284,9 +341,9 @@ void reject(Relation relation, Type lhsNode, Type rhsNode) { boolean swapped = frame.swapped(); Type targetNode = swapped ? rhsNode : lhsNode; Type sourceNode = swapped ? lhsNode : rhsNode; - Located target = locate(frame.target()); - Located source = locate(frame.source()); - Located view = frame.view() == null ? null : locate(frame.view()); + Track target = frame.target(); + Track source = frame.source(); + Track view = frame.view(); BoundComparison bound = frame.bound(); mismatches.add( new Mismatch( @@ -294,12 +351,12 @@ void reject(Relation relation, Type lhsNode, Type rhsNode) { frame.targetSteps(), targetNode, sourceNode, - target == null || target.hidden() ? null : target.path(), - target == null ? null : target.path(), - source == null ? null : source.path(), + target.state() == Track.State.LOCATED ? target.path() : null, + target.caret(), + source.caret(), frame.viewedSource(), - view == null ? null : view.path(), - source != null ? source.node() : frame.sourceShown(), + view == null ? null : view.caret(), + source.caret() != null ? source.node() : frame.sourceShown(), bound == null ? null : bound.sourceWildcard(), bound == null ? null : bound.targetUpperBound())); } @@ -375,112 +432,134 @@ private static boolean isShown(TypePath.Step.Kind kind, Type parent) { } /** - * Follows {@code step} of the comparison in the written type {@code track} follows: by position - * where the written node has the shape of the compared one, and otherwise by finding the compared - * child as an instance inside the nearest written node. + * Follows {@code step} of the comparison in the written type {@code track} follows, as the class + * comment describes. */ private static Track follow(Track track, Step step) { - switch (track.state()) { - case HIDDEN -> { - return track; - } - case LOST -> { - return relocate(track, step.child()); - } + return switch (track.state()) { + case HIDDEN, LOST -> track; + case DECLARED -> followDeclared(track, step); case LOCATED -> { Track child = childByPosition(track, step); - return child != null ? child : relocate(track, step.child()); + yield child != null ? child : Track.lost(track); } - } - throw new AssertionError( - track.state()); // diff-coverage: ignore -- the switch covers every state + }; } /** * Returns the child {@code step} reaches from the written node of {@code track}, where that node - * has the shape of the node the comparison stepped from, or {@code null} where it has another. + * is of the kind the step descends from: a class type of the class the comparison stepped from + * for a type argument or an enclosing type, an array for an array element, and a wildcard for a + * bound. Returns {@code null} where it is of another kind. */ private static @Nullable Track childByPosition(Track track, Step step) { Type node = track.node(); - switch (step.kind()) { - case TYPE_ARGUMENT -> { - if (node instanceof Type.ClassType classType - && classType.tsym.equals(step.parent().tsym) - && step.index() < classType.getTypeArguments().size()) { - return Track.located( - classType.getTypeArguments().get(step.index()), - track.path().then(typeArgumentStep(classType, step.index()))); - } - return null; - } - case ENCLOSING_TYPE -> { - if (node instanceof Type.ClassType classType && classType.tsym.equals(step.parent().tsym)) { - return Track.located( - classType.getEnclosingType(), track.path().then(TypePath.Step.enclosingType())); - } - return null; - } - case ARRAY_ELEMENT -> { - if (node instanceof Type.ArrayType arrayType) { - return Track.located(arrayType.elemtype, track.path().then(TypePath.Step.arrayElement())); - } - return null; // diff-coverage: ignore -- only an array has an element to step into - } + return switch (step.kind()) { + case TYPE_ARGUMENT -> + node instanceof Type.ClassType classType + && classType.tsym.equals(step.parent().tsym) + && step.index() < classType.getTypeArguments().size() + ? Track.located( + classType.getTypeArguments().get(step.index()), + track.path().then(typeArgumentStep(classType, step.index()))) + : null; + case ENCLOSING_TYPE -> + node instanceof Type.ClassType classType && classType.tsym.equals(step.parent().tsym) + ? Track.located( + classType.getEnclosingType(), track.path().then(TypePath.Step.enclosingType())) + : null; + case ARRAY_ELEMENT -> + node instanceof Type.ArrayType arrayType + ? Track.located(arrayType.elemtype, track.path().then(TypePath.Step.arrayElement())) + : null; case WILDCARD_BOUND -> { Type.WildcardType wildcard = GenericsUtils.asWildcard(node); if (wildcard == null) { - return null; // diff-coverage: ignore -- only a wildcard has a bound to step into + yield null; } // the upper bound of `?` and `? super X` is not printed, so the caret stays on the wildcard - return wildcard.kind == BoundKind.EXTENDS + yield wildcard.kind == BoundKind.EXTENDS ? Track.located(wildcard.type, track.path().then(TypePath.Step.wildcardBound())) - : new Track(Track.State.HIDDEN, node, track.path()); + : new Track(Track.State.HIDDEN, node, track.path(), null); } case WILDCARD_LOWER_BOUND -> { Type.WildcardType wildcard = GenericsUtils.asWildcard(node); - return wildcard != null && wildcard.kind == BoundKind.SUPER + yield wildcard != null && wildcard.kind == BoundKind.SUPER ? Track.located(wildcard.type, track.path().then(TypePath.Step.wildcardLowerBound())) - : null; // diff-coverage: ignore -- a step into a lower bound is taken only from a ? - // super wildcard + : null; } - } - throw new AssertionError( - step.kind()); // diff-coverage: ignore -- the switch covers every step kind + }; } /** - * Finds {@code compared} inside the written node of {@code track}, and returns the track located - * there, or the track lost at that node where {@code compared} occurs there nowhere or at more - * than one position. + * Follows {@code step} in the supertype the written class of {@code track} declares. Where the + * step reaches one of the class's own type variables, written without an annotation, the view + * holds the written type argument for it, and the track is located there. */ - private static Track relocate(Track track, Type compared) { - TypePath relative = pathOfInstance(track.node(), compared); - return relative == null - ? new Track(Track.State.LOST, track.node(), track.path()) - : Track.located(compared, track.path().append(relative)); + private static Track followDeclared(Track track, Step step) { + Type declared = castToNonNull(track.declared()); + Type child = + switch (step.kind()) { + case TYPE_ARGUMENT -> + declared instanceof Type.ClassType classType + && classType.tsym.equals(step.parent().tsym) + && step.index() < classType.getTypeArguments().size() + ? classType.getTypeArguments().get(step.index()) + : null; + case ENCLOSING_TYPE -> + declared instanceof Type.ClassType classType + && classType.tsym.equals(step.parent().tsym) + ? classType.getEnclosingType() + : null; + case ARRAY_ELEMENT -> + declared instanceof Type.ArrayType arrayType ? arrayType.elemtype : null; + case WILDCARD_BOUND, WILDCARD_LOWER_BOUND -> { + Type.WildcardType wildcard = GenericsUtils.asWildcard(declared); + BoundKind kind = + step.kind() == TypePath.Step.Kind.WILDCARD_BOUND + ? BoundKind.EXTENDS + : BoundKind.SUPER; + yield wildcard != null && wildcard.kind == kind ? wildcard.type : null; + } + }; + if (child == null) { + return Track.lost(track); + } + Track written = + child instanceof Type.TypeVar typeVariable + && !(child instanceof Type.CapturedType) + && child.getAnnotationMirrors().isEmpty() + ? writtenArgumentFor(typeVariable, (Type.ClassType) track.node(), track.path()) + : null; + return written != null + ? written + : new Track(Track.State.DECLARED, track.node(), track.path(), child); } /** - * A position in a written type where a compared node is drawn. - * - * @param path where the caret goes - * @param node the printed node at {@code path} - * @param hidden whether the compared node lies below a bound the node at {@code path} hides - */ - private record Located(TypePath path, Type node, boolean hidden) {} - - /** - * Returns where the node the check rejected is drawn in the written type {@code track} follows, - * or {@code null} where that type does not hold it. + * Returns the track located at the type argument {@code written} gives {@code typeVariable}, + * where {@code typeVariable} is a type parameter of the class of {@code written} or of a class + * enclosing it, or {@code null} where it is neither. */ - private static @Nullable Located locate(Track track) { - return switch (track.state()) { - case LOCATED -> new Located(track.path(), track.node(), false); - case HIDDEN -> new Located(track.path(), track.node(), true); - // follow already looked for the compared node as an instance of the written type, and a - // track it left lost holds no such instance - case LOST -> null; - }; + private static @Nullable Track writtenArgumentFor( + Type.TypeVar typeVariable, Type.ClassType written, TypePath path) { + Type declaredForm = written.tsym.type; + Type actual = written; + TypePath actualPath = path; + while (declaredForm instanceof Type.ClassType declaredClass + && actual instanceof Type.ClassType actualClass) { + List formals = declaredClass.getTypeArguments(); + List arguments = actualClass.getTypeArguments(); + for (int i = 0; i < formals.size() && i < arguments.size(); i++) { + if (formals.get(i).tsym.equals(typeVariable.tsym)) { + return Track.located(arguments.get(i), actualPath.then(typeArgumentStep(actualClass, i))); + } + } + declaredForm = declaredClass.getEnclosingType(); + actual = actualClass.getEnclosingType(); + actualPath = actualPath.then(TypePath.Step.enclosingType()); + } + return null; } /** @@ -496,63 +575,4 @@ private static TypePath.Step typeArgumentStep(Type type, int index) { return TypePath.Step.typeArgument( index, formal, type.tsym instanceof Symbol.ClassSymbol owner ? owner : null); } - - /** - * 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 comparison 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, so the capture is - // not 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( - wildcardType.kind == BoundKind.EXTENDS - ? TypePath.Step.wildcardBound() - : TypePath.Step.wildcardLowerBound()), - 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(typeArgumentStep(classType, i)), 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 index b989e21772..d603c696f7 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java @@ -69,13 +69,13 @@ boolean reachesSameNodeAs(Step other) { /** 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) // diff-coverage: ignore -- every step the recorder builds carries its - // formal and owner - : owner.getSimpleName() + " type argument " + formal.tsym.getSimpleName(); + case TYPE_ARGUMENT -> { + if (formal == null || owner == null) { + yield "type argument " + + (index + 1); // diff-coverage: ignore -- the recorder names both + } + yield owner.getSimpleName() + " type argument " + formal.tsym.getSimpleName(); + } case WILDCARD_BOUND -> "wildcard upper bound"; case WILDCARD_LOWER_BOUND -> "wildcard lower bound"; case ARRAY_ELEMENT -> "array element"; @@ -102,13 +102,6 @@ TypePath then(Step step) { return new TypePath(ImmutableList.builder().addAll(steps).add(step).build()); } - /** Returns this path extended by every step of {@code relative}, in order. */ - TypePath append(TypePath relative) { - return relative.isRoot() - ? this // diff-coverage: ignore -- append is called only with a non-root path - : new TypePath(ImmutableList.builder().addAll(steps).addAll(relative.steps).build()); - } - /** Returns the descents from the root, in order. */ ImmutableList steps() { return steps; diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java index 365f5efa01..7f5889df35 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java @@ -118,11 +118,29 @@ public void theFixReplacesTheNodeAtEveryKindOfStep() { ^^^^^^ fix: declare d as Outer<@Nullable String>.Inner Did you mean 'Outer<@Nullable String>.Inner d = src;'? + """, + "WILDCARD_LOWER_BOUND", + """ + incompatible nullability in List type argument E -> wildcard lower bound -> List type argument E: source has @Nullable String where target requires String + source: List> + ^^^^^^^^^^^^^^^^ + target: List> + ^^^^^^ + fix: declare l as List> + Did you mean 'List> l = lower();'? """), """ static class Outer { class Inner {} } + static List> lower() { + throw new RuntimeException(); + } + void wildcardLowerBound() { + // BUG: Diagnostic matches: WILDCARD_LOWER_BOUND + List> l = lower(); + l.hashCode(); + } void wildcardBound(List list) { // BUG: Diagnostic matches: WILDCARD_BOUND Collection c = list; 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 b66c82f71a..f87bc7113f 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 @@ -1,5 +1,6 @@ package com.uber.nullaway.jspecify.mismatchmessage; +import java.util.Map; import org.junit.Test; /** @@ -100,6 +101,73 @@ void test(Sub s) { """); } + @Test + public void + aTypeTheSubclassDeclarationWritesIsMarkedOnTheViewedSourceEvenWhereTheReaderWroteIt() { + assertMessages( + Map.of( + "SELF", + """ + incompatible nullability in Base type argument T: a type argument must match exactly; source has Sub where target requires @Nullable Sub + source: Sub + source viewed as: Base + ^^^ + target: Base<@Nullable Sub> + ^^^^^^^^^^^^^ + """, + "ARGUMENT", + """ + incompatible nullability in Base type argument T: a type argument must match exactly; source has Sub where target requires @Nullable Sub + source: Holder + source viewed as: Base + ^^^ + target: Base<@Nullable Sub> + ^^^^^^^^^^^^^ + """), + """ + interface Base {} + static final class Sub implements Base {} + static final class Holder implements Base {} + static void take(Base<@Nullable Sub> b) {} + void self(Sub s) { + // BUG: Diagnostic matches: SELF + take(s); + } + void argument(Holder h) { + // BUG: Diagnostic matches: ARGUMENT + take(h); + } + """); + } + + @Test + public void eachComponentOfAnIntersectionTargetIsComparedUnderItsOwnView() { + assertMessage( + """ + incompatible nullability in A type argument T and 1 other position: source has @Nullable String where target requires String + source: B + target: A & D + \s + 1. path: A type argument T + source: @Nullable String + target: String + \s + 2. path: D type argument T + source: @Nullable String + target: String + """, + """ + interface A {} + interface D {} + static class B implements A<@Nullable String>, D<@Nullable String> {} + static void test(Object o) { + var x = (A & D) o; + // BUG: Diagnostic matches: MESSAGE + x = new B(); + } + """); + } + @Test public void aWildcardFromTheSubclassDeclarationGetsANoteThatStatesItsBoundOnly() { assertMessage( From 43d0bd650a0997320a403959f408b672911d483a Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Sat, 28 Nov 2026 22:43:28 +0300 Subject: [PATCH 13/43] Name the type parameter of a wildcard marked on the viewed source A wildcard the supertype view rebuilt got only "has an implicit @Nullable Object upper bound", even where the source viewed as: line prints it and carries its caret (F49). The note now takes the type parameter from the step that reached the wildcard on whichever printed line marks it, and states the bound alone only where no line marks it. The class comment says so, and says that only the source gets a note for a node a side does not print (F50). A numbered entry whose source is non-null where the target is @Nullable says that a type argument must match exactly, as the first line already does for the first entry (F51). The printer reads the simple name of an annotation type instead of printing it with a second visitor (F69). FixTests applies the edits for an implicit wildcard bound, an inner class, and a @Nullable written in the declaration's type tree (F56, F58). Assisted-by: Claude Code (claude-opus-5-5) --- .../GenericTypePrettyPrintingVisitor.java | 5 +- .../generics/NullabilityMismatchMessage.java | 92 +++++++++++-------- .../jspecify/mismatchmessage/FixTests.java | 66 +++++++++++++ .../SummaryAndNumberingTests.java | 48 +++++++--- .../mismatchmessage/ViewedSourceTests.java | 59 +++++++++--- 5 files changed, 205 insertions(+), 65 deletions(-) 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 740e9a857b..7212f2fa3e 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java @@ -230,10 +230,7 @@ public String visitClassType(Type.ClassType t, @Nullable Void s) { */ private void appendNullableAnnotationIfPresent(Type t, StringBuilder sb) { for (Attribute.TypeCompound compound : t.getAnnotationMirrors()) { - // 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)) { + if (compound.type.tsym.getSimpleName().contentEquals("Nullable")) { if (!(omitBaseAnnotation && isBase(t))) { sb.append('@').append(annotationName(compound.type)).append(' '); } 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 9177cdd3e8..7113a4d775 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -91,16 +91,14 @@ * Below the root, as for an element of {@code List}, no view is printed, and such a node gets * no source caret. Two differences below one printed node share its caret, numbered for each. * - *

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, including one the supertype view carried over - * from it, the note names the type parameter it takes its bound from. Where the view rebuilt the - * wildcard, as from the supertype a subclass declares, that parameter belongs to a declaration this - * message never prints, and naming it would set a second frame of reference against the {@code - * path} line: {@code Base type argument B} beside {@code type parameter S of Sub} reads as a - * contradiction rather than as two answers. The note there states the bound and stops. Where the - * node is one a side does not print, as with the bound an unbounded wildcard leaves implicit, the - * caret rises to the deepest node that side does print, and a {@code note} says what the reader - * cannot see there. + *

A note explains itself in the entities the message already shows. Where the source wildcard is + * marked on a printed type, the type the reader wrote or the {@code source viewed as} line, the + * note names the type parameter of the class at that position, which the wildcard takes its bound + * from. Where it is marked on neither, as below the root of a supertype view, the type parameter + * belongs to a declaration this message never prints, and the note 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 for the source a {@code + * note} says what the reader cannot see there. * *

The fixes

* @@ -218,9 +216,11 @@ Report build( numbered); Type viewedSource = sharedView(listed); int labelWidth = TYPE_LABEL_WIDTH; + Type printedView = null; if (source.marksPlaced() == listed.size() || viewedSource == null) { message.append(source.lines()); } else { + printedView = viewedSource; // a node the check compared is at no position of the type the reader wrote, so the view of // it the check did compare is printed too and carries the carets labelWidth = VIEWED_SOURCE_LABEL.length(); @@ -231,14 +231,7 @@ Report build( VIEWED_SOURCE_LABEL, labelWidth, viewedSource, - carets( - listed, - mismatch -> - mismatch.viewedSource() != null - && ASTHelpers.isSameType( - mismatch.viewedSource(), viewedSource, state) - ? mismatch.viewCaret() - : null), + carets(listed, mismatch -> printedViewCaret(mismatch, viewedSource)), numbered) .lines()); } @@ -251,7 +244,7 @@ Report build( numbered) .lines()); for (int i = 0; i < listed.size(); i++) { - message.append(mismatchDetail(listed.get(i), numbered ? i + 1 : 0)); + message.append(mismatchDetail(listed.get(i), numbered ? i + 1 : 0, printedView)); } // 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 @@ -399,14 +392,7 @@ private String summaryLine(List mismatches) { : String.format( "%s and %d other position%s", first.path().describe(), others, others == 1 ? "" : "s"); - // a non-null type argument where the target has a @Nullable one reads as a false subtype claim, - // since every String is a @Nullable String; what fails is that a type argument has to match - String exactly = - first.relation() == NullabilityMismatches.Relation.SAME - && checks.isNullableAnnotated(first.targetNode()) - && !checks.isNullableAnnotated(first.sourceNode()) - ? "a type argument must match exactly; " - : ""; + String exactly = mustMatchExactly(first) ? "a type argument must match exactly; " : ""; return String.format( "incompatible nullability in %s: %ssource has %s where target requires %s", where, @@ -415,6 +401,17 @@ private String summaryLine(List mismatches) { targetRequirement(first)); } + /** + * Whether {@code mismatch} is a non-null type argument where the target has a {@code @Nullable} + * one, which reads as a false subtype claim, since every {@code String} is a {@code @Nullable + * String}; what fails there is that a type argument has to match exactly. + */ + private boolean mustMatchExactly(NullabilityMismatches.Mismatch mismatch) { + return mismatch.relation() == NullabilityMismatches.Relation.SAME + && checks.isNullableAnnotated(mismatch.targetNode()) + && !checks.isNullableAnnotated(mismatch.sourceNode()); + } + /** * Names what the target requires of the source at {@code mismatch}: the target node, or for the * lower bound of a {@code ? super} wildcard, a supertype of it. @@ -536,12 +533,28 @@ private static StringBuilder padTo(StringBuilder line, int column) { return line; } + /** + * Returns where {@code mismatch} is marked on the {@code source viewed as} line that prints + * {@code printedView}, or {@code null} where it is not marked there or no such line is printed. + */ + private @Nullable TypePath printedViewCaret( + NullabilityMismatches.Mismatch mismatch, @Nullable Type printedView) { + Type view = mismatch.viewedSource(); + return printedView != null && view != null && ASTHelpers.isSameType(view, printedView, state) + ? mismatch.viewCaret() + : null; + } + /** * Returns the lines that describe one mismatch below the two types: for a numbered entry its * position and the pair the first line names only for the first entry, and for any mismatch the * note about the source wildcard where there is one. + * + * @param printedView the view of the source the {@code source viewed as} line prints, or {@code + * null} where no such line is printed */ - private String mismatchDetail(NullabilityMismatches.Mismatch mismatch, int number) { + private String mismatchDetail( + NullabilityMismatches.Mismatch mismatch, int number, @Nullable Type printedView) { String header = number == 0 ? " " : " " + number + ". "; String body = " ".repeat(header.length()); StringBuilder detail = new StringBuilder(); @@ -551,8 +564,11 @@ private String mismatchDetail(NullabilityMismatches.Mismatch mismatch, int numbe detail.append(GenericsChecks.prettyTypeForError(mismatch.sourceNode(), state)); detail.append("\n").append(body).append(TARGET_LABEL).append(": "); detail.append(targetRequirement(mismatch)); + if (mustMatchExactly(mismatch)) { + detail.append(" (a type argument must match exactly)"); + } } - String note = boundOriginNote(mismatch); + String note = boundOriginNote(mismatch, printedView); if (note != null) { detail.append("\n").append(body).append("note: ").append(note); } @@ -572,7 +588,8 @@ private String mismatchDetail(NullabilityMismatches.Mismatch mismatch, int numbe * 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) { + private @Nullable String boundOriginNote( + NullabilityMismatches.Mismatch mismatch, @Nullable Type printedView) { // 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()); @@ -599,10 +616,13 @@ private String mismatchDetail(NullabilityMismatches.Mismatch mismatch, int numbe if (wildcard.kind == BoundKind.EXTENDS) { return null; // diff-coverage: ignore -- a caret goes below a written bound } - // the step that reached the wildcard in the type the reader wrote names the type parameter it - // instantiates there; javac's own link, WildcardType.bound, names a type parameter of whatever - // supertype the wildcard was last substituted into + // the step that reached the wildcard in the printed type that marks it names the type parameter + // it instantiates there; javac's own link, WildcardType.bound, names a type parameter of + // whatever supertype the wildcard was last substituted into TypePath caret = mismatch.sourceCaret(); + if (caret == null) { + caret = printedViewCaret(mismatch, printedView); + } TypePath.Step reachingStep = caret == null || caret.isRoot() ? null : caret.steps().get(caret.steps().size() - 1); Type.TypeVar formalTypeVariable = @@ -616,9 +636,9 @@ private String mismatchDetail(NullabilityMismatches.Mismatch mismatch, int numbe : "? 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 where the supertype view built 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 + // position of a printed type, as below the root of a supertype view (#2197), 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( diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java index 0e27abfa1d..62a7afb2e7 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java @@ -293,6 +293,72 @@ void modifierAndTypeArgument() { .doTest(); } + @Test + public void theTargetTypeFixWritesAnImplicitBoundAndAnInnerClassAsJava() throws IOException { + makeHelper() + .addInputLines( + "Outer.java", + """ + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Outer { + class Inner {} + } + """) + .expectUnchanged() + .addInputLines( + "Test.java", + """ + import java.util.Collection; + import java.util.List; + import org.jspecify.annotations.NullMarked; + @NullMarked + class Test { + static List list() { + throw new RuntimeException(); + } + static Outer<@org.jspecify.annotations.Nullable String>.Inner inner() { + throw new RuntimeException(); + } + void implicitBound(List list) { + Collection c = list; + c.hashCode(); + } + void innerClass() { + Outer.Inner d = inner(); + d.hashCode(); + } + } + """) + .addOutputLines( + "Test.java", + """ + import java.util.Collection; + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static List list() { + throw new RuntimeException(); + } + static Outer<@org.jspecify.annotations.Nullable String>.Inner inner() { + throw new RuntimeException(); + } + void implicitBound(List list) { + Collection c = list; + c.hashCode(); + } + void innerClass() { + Outer<@Nullable String>.Inner d = inner(); + d.hashCode(); + } + } + """) + .doTest(); + } + @Test public void noEditForADeclarationInAnotherCompilationUnit() throws IOException { makeHelper() 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 index 680fec201c..f799be1b95 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java @@ -1,5 +1,6 @@ package com.uber.nullaway.jspecify.mismatchmessage; +import java.util.Map; import org.junit.Test; /** @@ -141,21 +142,46 @@ void test(Map<@Nullable String, @Nullable String> m) { } @Test - public void invariantTypeArgumentIsReportedWhenTheSourceIsLessNullableThanTheTarget() { - assertMessage( - """ - incompatible nullability in List type argument E: a type argument must match exactly; source has String where target requires @Nullable String - source: List - ^^^^^^ - target: List<@Nullable String> - ^^^^^^^^^^^^^^^^ - """, + public void everyPositionWhereTheSourceIsLessNullableSaysTheTypeArgumentMustMatchExactly() { + assertMessages( + Map.of( + "ONLY", + """ + incompatible nullability in List type argument E: a type argument must match exactly; source has String where target requires @Nullable String + source: List + ^^^^^^ + target: List<@Nullable String> + ^^^^^^^^^^^^^^^^ + """, + "SECOND", + """ + incompatible nullability in Map type argument K and 1 other position: source has @Nullable String where target requires String + source: Map<@Nullable String, String> + ^^^^^^^^^^^^^^^^ ^^^^^^ + 1 2 + target: Map + ^^^^^^ ^^^^^^^^^^^^^^^^ + 1 2 + \s + 1. path: Map type argument K + source: @Nullable String + target: String + \s + 2. path: Map type argument V + source: String + target: @Nullable String (a type argument must match exactly) + """), """ - void test(List source) { - // BUG: Diagnostic matches: MESSAGE + static void takeMap(Map m) {} + void only(List source) { + // BUG: Diagnostic matches: ONLY List<@Nullable String> target = source; target.hashCode(); } + void second(Map<@Nullable String, String> m) { + // BUG: Diagnostic matches: SECOND + takeMap(m); + } """); } } 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 f87bc7113f..18fa68d0e1 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 @@ -169,25 +169,56 @@ static void test(Object o) { } @Test - public void aWildcardFromTheSubclassDeclarationGetsANoteThatStatesItsBoundOnly() { - assertMessage( - """ - incompatible nullability in Base type argument B -> wildcard upper bound -> List type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object - source: Sub - source viewed as: Base> - ^ - target: Base> - ^^^^^^ - note: the source wildcard has an implicit @Nullable Object upper bound - """, + public void aWildcardFromTheSubclassDeclarationIsNamedOnlyWhereALinePrintsIt() { + assertMessages( + Map.of( + "LIST", + """ + incompatible nullability in Base type argument B -> wildcard upper bound -> List type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + source: ListSub + source viewed as: Base> + ^ + target: Base> + ^^^^^^ + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List + """, + "MAP", + """ + incompatible nullability in Base type argument B -> wildcard upper bound -> Map type argument V -> wildcard upper bound: source has @Nullable Object where target requires Object + source: MapSub + source viewed as: Base> + ^ + target: Base> + ^^^^^^ + note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter V of Map + """, + "BELOW_ROOT", + """ + incompatible nullability in List type argument E -> wildcard upper bound -> Base type argument B -> wildcard upper bound -> List type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + source: List + target: List>> + ^^^^^^ + note: the source wildcard has an implicit @Nullable Object upper bound + """), """ static class Base {} - static class Sub extends Base> {} + static class ListSub extends Base> {} + static class MapSub extends Base> {} static void take(Base> b) {} - void test(Sub s) { - // BUG: Diagnostic matches: MESSAGE + static void takeMap(Base> b) {} + static void takeList(List>> l) {} + void list(ListSub s) { + // BUG: Diagnostic matches: LIST take(s); } + void map(MapSub s) { + // BUG: Diagnostic matches: MAP + takeMap(s); + } + void belowRoot(List l) { + // BUG: Diagnostic matches: BELOW_ROOT + takeList(l); + } """); } From ef9de37c11e89caaad12a96be4ae057977e2818d Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Sat, 28 Nov 2026 22:54:22 +0300 Subject: [PATCH 14/43] Test the suppressed-mismatch shortcut through an excluded class The test of the shortcut that builds no message for a suppressed mismatch put @SuppressWarnings("NullAway") on the methods, so Error Prone never ran NullAway there and the shortcut was never reached; it passed with the shortcut removed. NullAway does check a nested class that carries an annotation from ExcludedClassAnnotations and drops its errors at report time, so the test now uses one, and fails without the shortcut. An array the subclass declaration writes into its supertype, as in `implements Box<@Nullable String[]>` or `implements Box`, is now followed into its element by a test, and a local carrying another annotation beside @Nullable by the fix test. The remaining unreached defensive branches carry a diff-coverage marker on the line coverage reports. Assisted-by: Claude Code (claude-opus-5-5) --- .../GenericTypePrettyPrintingVisitor.java | 2 +- .../generics/NullabilityMismatchMessage.java | 15 +++-- .../generics/NullabilityMismatches.java | 14 ++--- .../com/uber/nullaway/generics/TypePath.java | 3 +- .../generics/MismatchMessageWorkTests.java | 59 +++++++++++-------- .../jspecify/mismatchmessage/FixTests.java | 12 ++++ .../mismatchmessage/ViewedSourceTests.java | 37 ++++++++++++ 7 files changed, 100 insertions(+), 42 deletions(-) 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 7212f2fa3e..e763b9b9ea 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java @@ -277,7 +277,7 @@ public String visitArrayType(Type.ArrayType t, @Nullable Void unused) { 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 mark(t.tsym.getSimpleName().toString()); + return mark(t.tsym.getSimpleName().toString()); // diff-coverage: ignore -- javac stops first } @Override 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 7113a4d775..f7154a2e17 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -710,12 +710,11 @@ private String mismatchDetail( 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; // diff-coverage: ignore -- source carries a nullable annotation + return source.getAnnotationMirrors().stream() + .filter(annotation -> Nullness.isNullableAnnotation(annotation.type.toString(), config)) + .findFirst() + .map(annotation -> TypeSubstitutionUtils.typeWithAnnot(target, annotation.type)) + .orElse(null); } /** @@ -739,7 +738,7 @@ private String mismatchDetail( type instanceof Type.ClassType classType && step.index() < classType.getTypeArguments().size() ? classType.getTypeArguments().get(step.index()) - : null; + : null; // diff-coverage: ignore -- see the method comment case ENCLOSING_TYPE -> type instanceof Type.ClassType classType ? classType.getEnclosingType() : null; case WILDCARD_BOUND, WILDCARD_LOWER_BOUND -> @@ -749,7 +748,7 @@ private String mismatchDetail( ? BoundKind.EXTENDS : BoundKind.SUPER) ? wildcard.type - : null; + : null; // diff-coverage: ignore -- see the method comment case ARRAY_ELEMENT -> type instanceof Type.ArrayType arrayType ? arrayType.elemtype : null; }; 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 fd802bbabf..cff7082437 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java @@ -253,7 +253,7 @@ private Track viewedAs(Track track, Type rhs, Type rhsView) { } Type declared = TypeSubstitutionUtils.asSuper(types, written.tsym.type, viewClass, config); return declared == null - ? Track.lost(track) + ? Track.lost(track) // diff-coverage: ignore -- a view is a supertype : new Track(Track.State.DECLARED, written, track.path(), declared); } @@ -471,11 +471,11 @@ private static Track follow(Track track, Step step) { case ARRAY_ELEMENT -> node instanceof Type.ArrayType arrayType ? Track.located(arrayType.elemtype, track.path().then(TypePath.Step.arrayElement())) - : null; + : null; // diff-coverage: ignore -- the track stands at the node the check steps from case WILDCARD_BOUND -> { Type.WildcardType wildcard = GenericsUtils.asWildcard(node); if (wildcard == null) { - yield null; + yield null; // diff-coverage: ignore -- the track stands at the node the check steps from } // the upper bound of `?` and `? super X` is not printed, so the caret stays on the wildcard yield wildcard.kind == BoundKind.EXTENDS @@ -486,7 +486,7 @@ private static Track follow(Track track, Step step) { Type.WildcardType wildcard = GenericsUtils.asWildcard(node); yield wildcard != null && wildcard.kind == BoundKind.SUPER ? Track.located(wildcard.type, track.path().then(TypePath.Step.wildcardLowerBound())) - : null; + : null; // diff-coverage: ignore -- the track stands at the node the check steps from } }; } @@ -505,12 +505,12 @@ private static Track followDeclared(Track track, Step step) { && classType.tsym.equals(step.parent().tsym) && step.index() < classType.getTypeArguments().size() ? classType.getTypeArguments().get(step.index()) - : null; + : null; // diff-coverage: ignore -- the view has this shape case ENCLOSING_TYPE -> declared instanceof Type.ClassType classType && classType.tsym.equals(step.parent().tsym) ? classType.getEnclosingType() - : null; + : null; // diff-coverage: ignore -- the view has this shape case ARRAY_ELEMENT -> declared instanceof Type.ArrayType arrayType ? arrayType.elemtype : null; case WILDCARD_BOUND, WILDCARD_LOWER_BOUND -> { @@ -559,7 +559,7 @@ private static Track followDeclared(Track track, Step step) { actual = actualClass.getEnclosingType(); actualPath = actualPath.then(TypePath.Step.enclosingType()); } - return null; + return null; // diff-coverage: ignore -- a supertype names only the type variables in scope } /** 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 d603c696f7..69e420a293 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java @@ -71,8 +71,7 @@ String describe() { return switch (kind) { case TYPE_ARGUMENT -> { if (formal == null || owner == null) { - yield "type argument " - + (index + 1); // diff-coverage: ignore -- the recorder names both + yield "type argument " + (index + 1); // diff-coverage: ignore -- the recorder sets both } yield owner.getSimpleName() + " type argument " + formal.tsym.getSimpleName(); } diff --git a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java index 15e98131fd..9cecded7df 100644 --- a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java @@ -7,6 +7,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.stream.Stream; import org.junit.Test; /** @@ -20,9 +21,10 @@ public class MismatchMessageWorkTests { public void oneWalkOfTheCompilationUnitServesEveryLocalFix() { List walks = walksWhileCompiling( - """ +""" import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.jspecify.annotations.NullMarked; @NullMarked class Test { @@ -53,45 +55,52 @@ Collection returned() { } @Test - public void aSuppressedMismatchCostsNoWalk() { + public void aMismatchInAnExcludedNestedClassCostsNoWalk() { List walks = walksWhileCompiling( - """ +""" import java.util.Collection; import java.util.List; +import java.util.stream.Stream; import org.jspecify.annotations.NullMarked; @NullMarked class Test { + @interface Excluded {} static void take(Collection c) {} static List make() { throw new RuntimeException(); } - @SuppressWarnings("NullAway") - void assignment() { - List l = make(); - Collection c = l; - } - @SuppressWarnings("NullAway") - void argument() { - List l = make(); - take(l); - } - @SuppressWarnings("NullAway") - Collection returned() { - List l = make(); - return l; + @Excluded + static class Inner { + void assignment() { + List l = make(); + Collection c = l; + } + void argument() { + List l = make(); + take(l); + } + Collection returned() { + List l = make(); + return l; + } } } - """); - assertWithMessage("compilation units walked for local declarations").that(walks).isEmpty(); + """, + "-XepOpt:NullAway:ExcludedClassAnnotations=Test.Excluded"); + assertWithMessage( + "NullAway checks an excluded nested class and drops its errors as suppressed, so no" + + " message is built for them and no compilation unit is walked") + .that(walks) + .isEmpty(); } /** - * Compiles {@code source} as {@code Test.java} in JSpecify mode, expecting the diagnostics its - * {@code // BUG: Diagnostic contains:} comments mark and no others, and returns the file name of - * each compilation unit indexed for local declarations, once per walk. + * Compiles {@code source} as {@code Test.java} in JSpecify mode with {@code extraArgs}, expecting + * the diagnostics its {@code // BUG: Diagnostic contains:} comments mark and no others, and + * returns the file name of each compilation unit indexed for local declarations, once per walk. */ - private List walksWhileCompiling(String source) { + private List walksWhileCompiling(String source, String... extraArgs) { List walks = Collections.synchronizedList(new ArrayList<>()); LocalVariableDeclarations.indexListener = unit -> { @@ -102,7 +111,9 @@ private List walksWhileCompiling(String source) { CompilationTestHelper.newInstance(NullAway.class, getClass()) .setArgs( JSpecifyJavacConfig.withJSpecifyModeArgs( - List.of("-XepOpt:NullAway:OnlyNullMarked=true"))) + Stream.concat( + Stream.of("-XepOpt:NullAway:OnlyNullMarked=true"), Stream.of(extraArgs)) + .toList())) .addSourceLines("Test.java", source) .doTest(); } finally { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java index 62a7afb2e7..5c8c1caa5c 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java @@ -250,6 +250,12 @@ void modifierAndTypeArgument() { takeMap(m); } } + void modifierAfterAnotherAnnotation() { + @SuppressWarnings("unchecked") @Nullable List l = list(); + if (l != null) { + take(l); + } + } } """) .addOutputLines( @@ -288,6 +294,12 @@ void modifierAndTypeArgument() { takeMap(m); } } + void modifierAfterAnotherAnnotation() { + @SuppressWarnings("unchecked") @Nullable List l = list(); + if (l != null) { + take(l); + } + } } """) .doTest(); 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 18fa68d0e1..b314b3305d 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 @@ -140,6 +140,43 @@ void argument(Holder h) { """); } + @Test + public void anArrayTheSubclassDeclarationWritesIsFollowedIntoItsElement() { + assertMessages( + Map.of( + "WRITTEN_ELEMENT", + """ + incompatible nullability in Box type argument T -> array element: source has @Nullable String where target requires String + source: Strings + source viewed as: Box<@Nullable String []> + ^^^^^^^^^^^^^^^^ + target: Box + ^^^^^^ + """, + "PASSED_ELEMENT", + """ + incompatible nullability in Box type argument T -> array element: source has @Nullable String where target requires String + source: Elements<@Nullable String> + ^^^^^^^^^^^^^^^^ + target: Box + ^^^^^^ + """), + """ + interface Box {} + static final class Strings implements Box<@Nullable String[]> {} + static final class Elements implements Box {} + static void take(Box b) {} + void written(Strings s) { + // BUG: Diagnostic matches: WRITTEN_ELEMENT + take(s); + } + void passed(Elements<@Nullable String> e) { + // BUG: Diagnostic matches: PASSED_ELEMENT + take(e); + } + """); + } + @Test public void eachComponentOfAnIntersectionTargetIsComparedUnderItsOwnView() { assertMessage( From c07bd0c498706cbdf156527489fb2ebf87eca73f Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Sat, 28 Nov 2026 22:58:29 +0300 Subject: [PATCH 15/43] Test that a parameter or field source is never looked up The local-declaration index answers only for local variables; a parameter or a field source gets the fix line without an edit and must not trigger a walk of the compilation unit. Without the kind check in LocalVariableDeclarations.find, such a source walks the unit, and no test noticed. Assisted-by: Claude Code (claude-opus-5-5) --- .../generics/MismatchMessageWorkTests.java | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java index 9cecded7df..bbad939376 100644 --- a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java @@ -54,6 +54,34 @@ Collection returned() { .containsExactly("Test.java"); } + @Test + public void aParameterOrFieldSourceCostsNoWalk() { + List walks = + walksWhileCompiling( + """ + import java.util.Collection; + import java.util.List; + import org.jspecify.annotations.NullMarked; + @NullMarked + class Test { + List field = List.of(); + static void take(Collection c) {} + void parameter(List l) { + // BUG: Diagnostic contains: fix: declare l as List + take(l); + } + void field() { + // BUG: Diagnostic contains: fix: declare field as List + take(field); + } + } + """); + assertWithMessage( + "only a local variable gets an edit, so a parameter or a field source is never looked up") + .that(walks) + .isEmpty(); + } + @Test public void aMismatchInAnExcludedNestedClassCostsNoWalk() { List walks = From 72b7001da7fd423861186b63c400aea80d30dd0f Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Sat, 28 Nov 2026 23:16:17 +0300 Subject: [PATCH 16/43] Keep following the written source through a nested supertype view A source whose class declares its supertype with a parameterized class around a type variable lost its caret on the written source line: for `Sub implements Base>` passed as `Sub<@Nullable String>` to `Base>`, the comparison views `ArrayList` as `List` a second time, and the track already in the declared supertype was not re-viewed, so only the `source viewed as:` line was marked. The same happened below an annotated type variable, as in `Base>`. viewedAs now re-views a declared-supertype track at a nested class comparison, and followDeclared resolves a type variable of the written class to the written argument before stepping below it, so the walk covers every kind of node a supertype declaration holds. Whether a local declaration shares its type tree with another variable (`List a, b;`) was decided by scanning the whole enclosing block for every fix, so k fixes in a block of N trees cost O(k*N). The per-compilation-unit index now records those declarations during its one walk. An import replacement in the previous commit also hit two test sources inside text blocks; they are restored. Assisted-by: Claude Code (claude-opus-5-5) --- .../generics/LocalVariableDeclarations.java | 35 +++++++++++- .../generics/NullabilityMismatchMessage.java | 26 +-------- .../generics/NullabilityMismatches.java | 39 +++++++++---- .../generics/MismatchMessageWorkTests.java | 6 +- .../jspecify/mismatchmessage/FixTests.java | 56 ++++++++++++++++++- .../mismatchmessage/ViewedSourceTests.java | 51 +++++++++++++++++ 6 files changed, 169 insertions(+), 44 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java b/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java index d909242e0d..4e39c111e4 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java @@ -1,14 +1,18 @@ package com.uber.nullaway.generics; import com.google.common.annotations.VisibleForTesting; +import com.google.common.collect.Sets; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.CompilationUnitTree; +import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; import com.sun.source.util.TreePathScanner; import com.sun.tools.javac.code.Symbol; import java.util.HashMap; +import java.util.IdentityHashMap; import java.util.Map; +import java.util.Set; import java.util.function.Consumer; import javax.lang.model.element.ElementKind; import org.jspecify.annotations.Nullable; @@ -18,8 +22,9 @@ * *

The first lookup in a compilation unit walks it once and indexes every local variable * declaration it holds; later lookups in the same unit read the index, so a unit with many * diagnostics is walked once rather than once per diagnostic. The same walk notes the declarations - * that share their type tree with another variable, as each variable of {@code List a, b;} does. - * {@link #clear} drops the index, which otherwise keeps the trees of the unit alive. + * that share their type tree with another variable, as each variable of {@code List a, b;} does, + * or its element type, as {@code a} and {@code b} of {@code List a, b[];} do. {@link #clear} + * drops the index, which otherwise keeps the trees of the unit alive. */ final class LocalVariableDeclarations { @@ -39,10 +42,10 @@ final class LocalVariableDeclarations { private final Map paths = new HashMap<>(); - /** The first variable declared with each type tree of the indexed unit. */ + /** The first variable declared with each element type tree of the indexed unit. */ private final IdentityHashMap firstByTypeTree = new IdentityHashMap<>(); - /** The declarations of the indexed unit whose type tree another variable also has. */ + /** The declarations of the indexed unit whose element type tree another variable also has. */ private final Set sharingTypeTree = Sets.newIdentityHashSet(); /** @@ -61,12 +64,28 @@ final class LocalVariableDeclarations { /** * Whether {@code declaration}, a local variable declaration of the compilation unit last passed - * to {@link #find}, shares its type tree with another variable. + * to {@link #find}, shares its element type tree with another variable. */ boolean sharesTypeTree(VariableTree declaration) { return sharingTypeTree.contains(declaration); } + /** + * Returns {@code typeTree} without the array and annotation trees around its element type. javac + * gives each variable of one declaration the same element type tree and wraps it in an array tree + * of its own for brackets written after the name. + */ + private static @Nullable Tree baseTypeTree(@Nullable Tree typeTree) { + Tree base = typeTree; + while (base instanceof ArrayTypeTree || base instanceof AnnotatedTypeTree) { + base = + base instanceof ArrayTypeTree array + ? array.getType() + : ((AnnotatedTypeTree) base).getUnderlyingType(); + } + return base; + } + /** Forgets the indexed compilation unit. */ void clear() { unit = null; @@ -88,7 +107,7 @@ private void index(CompilationUnitTree compilationUnit) { Symbol symbol = ASTHelpers.getSymbol(variable); if (symbol != null && symbol.getKind() == ElementKind.LOCAL_VARIABLE) { paths.put(symbol, getCurrentPath()); - Tree typeTree = variable.getType(); + Tree typeTree = baseTypeTree(variable.getType()); if (typeTree != null) { VariableTree first = firstByTypeTree.putIfAbsent(typeTree, variable); if (first != 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 index aff7b44b9b..9ecd78c911 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -18,6 +18,7 @@ import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.TypeTag; import com.sun.tools.javac.code.Types; +import com.sun.tools.javac.tree.JCTree; import com.uber.nullaway.Config; import com.uber.nullaway.Nullness; import com.uber.nullaway.handlers.Handler; @@ -302,7 +303,9 @@ private void appendFix( if (typeTree == null || ASTHelpers.hasImplicitType(declaration, state)) { return; // diff-coverage: ignore -- javac versions differ in whether var gets a type tree } - if (checks.localVariableDeclarations().sharesTypeTree(declaration)) { + // in `List a[]` the type tree spans the name, which a replacement of it would overwrite + if (checks.localVariableDeclarations().sharesTypeTree(declaration) + || state.getEndPosition(typeTree) > ((JCTree) declaration).pos) { return; } SuggestedFix.Builder fix = SuggestedFix.builder(); 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 ad79ec3dee..2a1bad3ce5 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java @@ -250,6 +250,10 @@ private Track viewedAs(Track track, Type rhs, Type rhsView) { if (rhs.tsym.equals(rhsView.tsym) || !(rhsView.tsym instanceof Symbol.ClassSymbol viewClass)) { return track; } + Track argument = writtenArgumentAt(track); + if (argument != null) { + return viewedAs(argument, rhs, rhsView); + } Type declared = switch (track.state()) { case LOCATED -> track.node() instanceof Type.ClassType written ? written.tsym.type : null; @@ -504,17 +508,15 @@ private static Track follow(Track track, Step step) { * step reaches one of the class's own type variables, written without an annotation, the view * holds the written type argument for it, and the track is located there. A type variable written * with an annotation, as in {@code Base>}, keeps the track in the declared - * supertype, since the annotation is not written at the argument; a step below it goes on from - * the written type argument. + * supertype, since the annotation is not written at the argument; a step below it, or a class + * comparison at it ({@link #viewedAs}), goes on from the written type argument. */ private static Track followDeclared(Track track, Step step) { - Type declared = castToNonNull(track.declared()); - if (declared instanceof Type.TypeVar typeVariable && !(declared instanceof Type.CapturedType)) { - Track written = writtenArgumentFor(typeVariable, (Type.ClassType) track.node(), track.path()); - if (written != null) { - return follow(written, step); - } + Track argument = writtenArgumentAt(track); + if (argument != null) { + return follow(argument, step); } + Type declared = castToNonNull(track.declared()); Type child = switch (step.kind()) { case TYPE_ARGUMENT -> @@ -553,6 +555,20 @@ private static Track followDeclared(Track track, Step step) { : new Track(Track.State.DECLARED, track.node(), track.path(), child); } + /** + * Returns the track located at the type argument the written class gives the type variable {@code + * track} stands at in a declared supertype, or {@code null} where {@code track} stands elsewhere. + * The written argument holds every node below that type variable, so a comparison that goes on + * below it goes on from there. + */ + private static @Nullable Track writtenArgumentAt(Track track) { + return track.state() == Track.State.DECLARED + && track.declared() instanceof Type.TypeVar typeVariable + && !(typeVariable instanceof Type.CapturedType) + ? writtenArgumentFor(typeVariable, (Type.ClassType) track.node(), track.path()) + : null; + } + /** * Returns the track located at the type argument {@code written} gives {@code typeVariable}, * where {@code typeVariable} is a type parameter of the class of {@code written} or of a class diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java index 26ba03305d..3a010a796a 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java @@ -559,4 +559,41 @@ void besideSeveral() { """) .doTest(); } + + @Test + public void noEditForADeclarationWithBracketsAfterTheName() throws IOException { + makeHelper() + .addInputLines( + "Test.java", + """ + import java.util.Collection; + import java.util.List; + import org.jspecify.annotations.NullMarked; + @NullMarked + class Test { + static void take(List[] c) {} + static void takeOne(Collection c) {} + static List[] many() { + throw new RuntimeException(); + } + static List one() { + throw new RuntimeException(); + } + void bracketsAfterTheName() { + List a[] = many(); + take(a); + } + void beforeADeclaratorWithBrackets() { + List a = one(), b[] = many(); + takeOne(a); + } + void afterADeclaratorWithBrackets() { + List a[] = many(), b = one(); + takeOne(b); + } + } + """) + .expectUnchanged() + .doTest(); + } } 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 dbc195b0fa..ae275c6def 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 @@ -197,6 +197,14 @@ public void aViewNestedInADeclaredSupertypeStillReachesTheWrittenArgument() { target: Base>> ^^^^^^ """, + "VIEWED_BELOW_ANNOTATED", + """ + incompatible nullability in Base type argument B -> wildcard upper bound -> List type argument E -> wildcard upper bound -> List type argument E: source has @Nullable String where target requires String + source: Annotated> + ^^^^^^^^^^^^^^^^ + target: Base>> + ^^^^^^ + """, "WRITTEN", """ incompatible nullability in Base type argument B -> wildcard upper bound -> List type argument E: source has @Nullable String where target requires String @@ -221,6 +229,11 @@ void belowAnnotated(Annotated> a) { // BUG: Diagnostic matches: BELOW_ANNOTATED takeNested(a); } + static void takeViewed(Base>> b) {} + void viewedBelowAnnotated(Annotated> a) { + // BUG: Diagnostic matches: VIEWED_BELOW_ANNOTATED + takeViewed(a); + } void written(Strings s) { // BUG: Diagnostic matches: WRITTEN take(s); From 62ec1d03098c330a49d3cdee5ff522336f56d969 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Sat, 28 Nov 2026 23:30:49 +0300 Subject: [PATCH 18/43] Say that the declaration edit needs the type before the name The class comment and the appendFix Javadoc list when the diagnostic carries the declaration edit; the previous commit withheld it for brackets after the name without updating either. Assisted-by: Claude Code (claude-opus-5-5) --- .../generics/NullabilityMismatchMessage.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 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 9ecd78c911..19837dc601 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -107,11 +107,11 @@ * candidate is checked before it is printed: it 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 ?}. Where the declaration is a local variable of the compilation - * unit being analyzed, writes its type out, and declares no other variable, the line comes with an - * Error Prone fix that makes the edit, except in a run that suggests suppressions, which asks for - * the suppression instead. A parameter or a field gets the line without the edit: its type is a - * contract that callers, overriders, and other assignments rely on, and the check that accepts the - * rewrite consults none of them. + * unit being analyzed, writes its type out before the name, and declares no other variable, the + * line comes with an Error Prone fix that makes the edit, except in a run that suggests + * suppressions, which asks for the suppression instead. A parameter or a field gets the line + * without the edit: its type is a contract that callers, overriders, and other assignments rely on, + * and the check that accepts the rewrite consults none of them. * *

The two candidates differ in what they presume. Writing an explicit bound on a wildcard the * source declaration already writes is a mechanical fix of that wildcard, so it is offered wherever @@ -277,8 +277,8 @@ Report build( /** * Appends the {@code fix:} line that declares {@code variable} with {@code type}, and adds the * edit to {@code fixes} where {@code variable} is a local variable of the compilation unit being - * analyzed, its declaration writes its type out and declares no other variable, and the run does - * not suggest suppressions. + * analyzed, its declaration writes its type out before the name and declares no other variable, + * and the run does not suggest suppressions. */ private void appendFix( StringBuilder message, List fixes, Symbol.VarSymbol variable, Type type) { @@ -303,7 +303,7 @@ private void appendFix( if (typeTree == null || ASTHelpers.hasImplicitType(declaration, state)) { return; // diff-coverage: ignore -- javac versions differ in whether var gets a type tree } - // in `List a[]` the type tree spans the name, which a replacement of it would overwrite + // in `List a[]` the type tree spans the name, which replacing it would overwrite if (checks.localVariableDeclarations().sharesTypeTree(declaration) || state.getEndPosition(typeTree) > ((JCTree) declaration).pos) { return; From 31cda792419c17b85d0296c17d81c5605ecc7982 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Sat, 28 Nov 2026 23:35:20 +0300 Subject: [PATCH 19/43] Say which tracks a view re-views and which variables get the edit Assisted-by: Claude Code (claude-opus-5-5) --- .../generics/LocalVariableDeclarations.java | 3 ++- .../generics/NullabilityMismatchMessage.java | 16 +++++++++------- .../nullaway/generics/NullabilityMismatches.java | 7 +++++-- 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java b/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java index 76292d8580..6d30ed2d7d 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java @@ -20,7 +20,8 @@ import org.jspecify.annotations.Nullable; /** - * Finds the declaration of a local variable of the compilation unit being analyzed. + * Finds the declaration of a local variable of the compilation unit being analyzed. A pattern, + * resource, or exception variable is not one: javac gives each its own element kind. * *

The first lookup in a compilation unit walks it once and indexes every local variable * declaration it holds; later lookups in the same unit read the index, so a unit with many 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 19837dc601..6c98f58ecd 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -107,11 +107,12 @@ * candidate is checked before it is printed: it 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 ?}. Where the declaration is a local variable of the compilation - * unit being analyzed, writes its type out before the name, and declares no other variable, the - * line comes with an Error Prone fix that makes the edit, except in a run that suggests - * suppressions, which asks for the suppression instead. A parameter or a field gets the line - * without the edit: its type is a contract that callers, overriders, and other assignments rely on, - * and the check that accepts the rewrite consults none of them. + * unit being analyzed, other than a pattern, resource, or exception variable, writes its type out + * before the name, and declares no other variable, the line comes with an Error Prone fix that + * makes the edit, except in a run that suggests suppressions, which asks for the suppression + * instead. A parameter or a field gets the line without the edit: its type is a contract that + * callers, overriders, and other assignments rely on, and the check that accepts the rewrite + * consults none of them. * *

The two candidates differ in what they presume. Writing an explicit bound on a wildcard the * source declaration already writes is a mechanical fix of that wildcard, so it is offered wherever @@ -277,8 +278,9 @@ Report build( /** * Appends the {@code fix:} line that declares {@code variable} with {@code type}, and adds the * edit to {@code fixes} where {@code variable} is a local variable of the compilation unit being - * analyzed, its declaration writes its type out before the name and declares no other variable, - * and the run does not suggest suppressions. + * analyzed, other than a pattern, resource, or exception variable, its declaration writes its + * type out before the name and declares no other variable, and the run does not suggest + * suppressions. */ private void appendFix( StringBuilder message, List fixes, Symbol.VarSymbol variable, Type type) { 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 2a1bad3ce5..3ca24ef96c 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java @@ -99,8 +99,11 @@ record Mismatch( * the comparison went below a bound the printer does not show, and {@code node} is the wildcard * at {@code path} that hides it, which is where a caret goes for everything below. {@code * DECLARED}: the check views {@code node}, the written class at {@code path}, as a supertype, and - * the comparison stands at {@code declared} in the supertype that class declares. {@code LOST}: - * the comparison reached a node the written type does not hold. + * the comparison stands at {@code declared} in the supertype that class declares; a view of a + * class inside that supertype goes on in that class's own supertype, and a comparison that goes + * on below a type variable of the written class goes on from the type argument written for it, as + * a {@code LOCATED} track. {@code LOST}: the comparison reached a node the written type does not + * hold. * * @param declared the node of the declared supertype where the comparison stands, for {@code * DECLARED} only From d113efb23257eaf88d9777d7995891d5aafec5ed Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Sat, 28 Nov 2026 23:44:54 +0300 Subject: [PATCH 20/43] Test that a pattern or resource variable gets no declaration edit The comments said these variables get no edit, but no test showed it. FixTests.theEditRewritesOnlyALocalVariable now covers both and fails when the index admits their element kinds. The SuggestSuppressions test now takes its argument case from a local variable, so it reaches the branch that withholds the edit. Comments that no longer matched the code are corrected: the visitErrorType note (no annotation type reaches the printer since F69), the ErrorBuilder note on the suppression check (generic mismatches run it twice), the clearCache Javadoc, and the FixTests class comment, which now states the whole rule. Exception variables are no longer listed, since a catch type cannot be parameterized. Assisted-by: Claude Code (claude-opus-5-5) --- .../java/com/uber/nullaway/ErrorBuilder.java | 4 +- .../GenericTypePrettyPrintingVisitor.java | 3 +- .../nullaway/generics/GenericsChecks.java | 4 +- .../generics/LocalVariableDeclarations.java | 4 +- .../generics/NullabilityMismatchMessage.java | 16 +++--- .../jspecify/mismatchmessage/FixTests.java | 55 +++++++++++++++++-- 6 files changed, 65 insertions(+), 21 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/ErrorBuilder.java b/nullaway/src/main/java/com/uber/nullaway/ErrorBuilder.java index 2c9a653f57..9719d735f5 100755 --- a/nullaway/src/main/java/com/uber/nullaway/ErrorBuilder.java +++ b/nullaway/src/main/java/com/uber/nullaway/ErrorBuilder.java @@ -219,8 +219,8 @@ private Description createErrorDescriptionImpl( @Nullable Symbol nonNullTarget, @Nullable ExpressionTree nullableExpression) { Description.Builder builder = descriptionBuilder.setMessage(errorMessage.message); - // Mildly expensive state.getPath() traversal, occurs only once per potentially - // reported error. + // Mildly expensive state.getPath() traversal. A reporter whose message costs more to build, + // as for a generic nullability mismatch, runs it once more before building the message. if (isSuppressed(errorMessage.messageType, state)) { return Description.NO_MATCH; } 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 e763b9b9ea..416e0f02c4 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java @@ -275,8 +275,7 @@ public String visitArrayType(Type.ArrayType t, @Nullable Void unused) { @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 + // javac reports an unresolved type before NullAway runs, so a type printed here holds none return mark(t.tsym.getSimpleName().toString()); // diff-coverage: ignore -- javac stops first } 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 9fd3e8c2da..604a864438 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -4578,8 +4578,8 @@ public boolean passingLambdaOrMethodRefWithGenericReturnToUnmarkedCode( } /** - * Clears the inference caches. Call after each CompilationUnit; otherwise the caches keep trees - * alive and leak memory. + * Clears the inference caches and the index of local variable declarations. Call after each + * CompilationUnit; otherwise they keep trees alive and leak memory. */ public void clearCache() { inferredTypeVarNullabilityForGenericCalls.clear(); diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java b/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java index 6d30ed2d7d..ba1638df60 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java @@ -20,8 +20,8 @@ import org.jspecify.annotations.Nullable; /** - * Finds the declaration of a local variable of the compilation unit being analyzed. A pattern, - * resource, or exception variable is not one: javac gives each its own element kind. + * Finds the declaration of a local variable of the compilation unit being analyzed. A pattern or + * resource variable is not one, since javac gives each its own element kind, so it is never found. * *

The first lookup in a compilation unit walks it once and indexes every local variable * declaration it holds; later lookups in the same unit read the index, so a unit with many 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 6c98f58ecd..cd4811b23d 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -107,12 +107,11 @@ * candidate is checked before it is printed: it 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 ?}. Where the declaration is a local variable of the compilation - * unit being analyzed, other than a pattern, resource, or exception variable, writes its type out - * before the name, and declares no other variable, the line comes with an Error Prone fix that - * makes the edit, except in a run that suggests suppressions, which asks for the suppression - * instead. A parameter or a field gets the line without the edit: its type is a contract that - * callers, overriders, and other assignments rely on, and the check that accepts the rewrite - * consults none of them. + * unit being analyzed, other than a pattern or resource variable, writes its type out before the + * name, and declares no other variable, the line comes with an Error Prone fix that makes the edit, + * except in a run that suggests suppressions, which asks for the suppression instead. A parameter + * or a field gets the line without the edit: its type is a contract that callers, overriders, and + * other assignments rely on, and the check that accepts the rewrite consults none of them. * *

The two candidates differ in what they presume. Writing an explicit bound on a wildcard the * source declaration already writes is a mechanical fix of that wildcard, so it is offered wherever @@ -278,9 +277,8 @@ Report build( /** * Appends the {@code fix:} line that declares {@code variable} with {@code type}, and adds the * edit to {@code fixes} where {@code variable} is a local variable of the compilation unit being - * analyzed, other than a pattern, resource, or exception variable, its declaration writes its - * type out before the name and declares no other variable, and the run does not suggest - * suppressions. + * analyzed, other than a pattern or resource variable, its declaration writes its type out before + * the name and declares no other variable, and the run does not suggest suppressions. */ private void appendFix( StringBuilder message, List fixes, Symbol.VarSymbol variable, Type type) { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java index 3a010a796a..d9d1e66f44 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java @@ -13,8 +13,9 @@ /** * A {@code fix:} line comes with an Error Prone fix that rewrites the type the named declaration - * writes, where that declaration is a local variable of the compilation unit being analyzed, writes - * its type out, and declares no other variable, and the run does not suggest suppressions. + * writes, where that declaration is a local variable of the compilation unit being analyzed, other + * than a pattern or resource variable, writes its type out before the name, and declares no other + * variable, and the run does not suggest suppressions. */ public class FixTests { @@ -46,10 +47,14 @@ class Test { static List<@Nullable String> get() { throw new RuntimeException(); } + static List make() { + throw new RuntimeException(); + } void assignment() { List l = get(); } - Collection argument(List list) { + Collection argument() { + List list = make(); List result = new ArrayList<>(); result.addAll(list); return result; @@ -69,12 +74,16 @@ class Test { static List<@Nullable String> get() { throw new RuntimeException(); } + static List make() { + throw new RuntimeException(); + } void assignment() { @SuppressWarnings("NullAway") List l = get(); } @SuppressWarnings("NullAway") - Collection argument(List list) { + Collection argument() { + List list = make(); List result = new ArrayList<>(); result.addAll(list); return result; @@ -95,6 +104,7 @@ public void theEditRewritesOnlyALocalVariable() throws IOException { import java.util.List; import java.util.Map; import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; @NullMarked class Test { interface I { @@ -105,6 +115,14 @@ static void takeMap(Map m) {} static List make() { throw new RuntimeException(); } + interface Resource extends AutoCloseable { + @Override + void close(); + } + static void takeResource(Resource r) {} + static Resource open() { + throw new RuntimeException(); + } public Map field = new HashMap<>(); public void parameter(List l) { take(l); @@ -118,6 +136,16 @@ public void overridden(List l) { void fieldRead() { takeMap(field); } + void pattern(Object o) { + if (o instanceof List l) { + take(l); + } + } + void resource() { + try (Resource r = open()) { + takeResource(r); + } + } void local() { List l = make(); take(l); @@ -132,6 +160,7 @@ void local() { import java.util.List; import java.util.Map; import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; @NullMarked class Test { interface I { @@ -142,6 +171,14 @@ static void takeMap(Map m) {} static List make() { throw new RuntimeException(); } + interface Resource extends AutoCloseable { + @Override + void close(); + } + static void takeResource(Resource r) {} + static Resource open() { + throw new RuntimeException(); + } public Map field = new HashMap<>(); public void parameter(List l) { take(l); @@ -155,6 +192,16 @@ public void overridden(List l) { void fieldRead() { takeMap(field); } + void pattern(Object o) { + if (o instanceof List l) { + take(l); + } + } + void resource() { + try (Resource r = open()) { + takeResource(r); + } + } void local() { List l = make(); take(l); From 0e2f51b33e3eeed8b5efcebde3012b6cd4ad25e8 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Sun, 29 Nov 2026 01:21:46 +0300 Subject: [PATCH 21/43] Name the positions of a generic nullability mismatch in JLS terms The message mixed its own words with the JLS: `Collection type argument E` merged a type argument with the type parameter it is for, `array element` named one level of an array where the JLS element type is the innermost one, and the note said a bound was "inherited" without saying what it was. User-visible: A path step reads `type argument for E of Collection`, `upper bound of wildcard`, `lower bound of wildcard`, `component type`, or `enclosing type`. The supertype line reads `source supertype:` instead of `source viewed as:`. The fix line reads `possible fix: declare as `, since callers or other assignments of a parameter or a field may still reject the rewritten type. Where the source states a type argument outright, the first line reads `a non-wildcard type argument must be the same type;`. For an unbounded `?` or a `? super X` in the source, the note names the class holding that wildcard, the type parameter it takes its upper bound from, and the bound, as `note: the unbounded wildcard ? in Triple has the upper bound of type parameter B of Triple, which is @Nullable Object (JLS 5.1.10)`. Every other type argument of that class that holds a wildcard or a type argument of its own is printed as `...`, so the one `?` printed is the wildcard meant. A captured wildcard's note reads `the wildcard in the source is the type argument for T of Box`. Assisted-by: Claude Code (claude-opus-5-5) --- .../generics/NullabilityMismatchMessage.java | 202 ++++++++++++------ .../com/uber/nullaway/generics/TypePath.java | 19 +- .../uber/nullaway/JSpecifyJDKModelsTest.java | 4 +- .../nullaway/ParameterAssignmentTests.java | 4 +- .../generics/MismatchMessageWorkTests.java | 10 +- .../jspecify/BytecodeGenericsTests.java | 10 +- .../jspecify/GenericDiamondTests.java | 22 +- .../GenericInferenceErrorReportingTests.java | 2 +- .../jspecify/GenericInheritanceTests.java | 12 +- .../nullaway/jspecify/GenericLambdaTests.java | 4 +- ...enericMethodLambdaOrMethodRefArgTests.java | 4 +- .../nullaway/jspecify/GenericMethodTests.java | 78 +++---- .../jspecify/GenericVoidReturnTests.java | 4 +- .../uber/nullaway/jspecify/GenericsTests.java | 118 +++++----- .../IntersectionBoundNarrowingTests.java | 4 +- .../IntersectionRestorationTests.java | 6 +- .../nullaway/jspecify/JSpecifyArrayTests.java | 36 ++-- .../jspecify/PolyNullLibraryModelsTests.java | 2 +- .../SharedIntersectionTimeoutTests.java | 2 +- .../StreamNullabilityPropagatorTests.java | 4 +- .../jspecify/VarDeclaredLocalTests.java | 2 +- .../uber/nullaway/jspecify/WildcardTests.java | 64 +++--- .../jspecify/mismatchmessage/CaretTests.java | 46 ++-- .../jspecify/mismatchmessage/FixTests.java | 8 +- .../LowerBoundAndRawSourceTests.java | 4 +- .../MismatchMessageTestBase.java | 4 +- .../jspecify/mismatchmessage/NoteTests.java | 62 ++++-- .../jspecify/mismatchmessage/PathTests.java | 52 ++--- .../mismatchmessage/SourceFixTests.java | 116 +++++----- .../SummaryAndNumberingTests.java | 64 +++--- .../mismatchmessage/TargetTypeFixTests.java | 50 ++--- .../mismatchmessage/TraversalCostTests.java | 8 +- .../mismatchmessage/ViewedSourceTests.java | 76 +++---- 33 files changed, 602 insertions(+), 501 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 cd4811b23d..e17ee2187e 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -37,13 +37,13 @@ * Map}, the text reads: * *
- * incompatible nullability in Map type argument K -> wildcard upper bound: source has @Nullable Object where target requires Object
+ * incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object
  *     source: Map<?, String>
  *                 ^
  *     target: Map<? extends Object, String>
  *                           ^^^^^^
- *     note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter K of Map
- *     fix: declare m as Map<? extends Object, String>
+ *     note: the unbounded wildcard ? in Map<?, String> has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10)
+ *     possible fix: declare m as Map<? extends Object, String>
  * 
* *

The message is built from the positions the check itself rejected, which {@link @@ -55,13 +55,15 @@ *

The vocabulary

* *

Each line opens with a key that means the same thing wherever it appears: {@code source} is - * the source type, {@code source viewed as} the supertype of it the check compared, {@code target} + * the source type, {@code source supertype} the supertype of it the check compared, {@code target} * the target type, {@code path} where in the type one difference sits, {@code note} a fact about - * the source that its printed form does not show, and {@code fix} a declaration whose rewritten - * type the check accepts. Where there are several differences, each gets a numbered entry with its - * own {@code path}, {@code source}, and {@code target}, five at most, and {@code and N more, not - * listed} counts the rest. The keys of the type lines are padded to one width, so the types of one - * message start in the same column. + * the source that its printed form does not show, and {@code possible fix} a declaration whose + * rewritten type the check accepts, which callers or other assignments may still reject. Java + * constructs are named in the terms of the JLS, as {@code type argument for K of Map}, {@code upper + * bound of wildcard}, and {@code component type}, and nullness in those of JSpecify. Where there + * are several differences, each gets a numbered entry with its own {@code path}, {@code source}, + * and {@code target}, five at most, and {@code and N more, not listed} counts the rest. The keys of + * the type lines are padded to one width, so the types of one message start in the same column. * *

The first line

* @@ -71,9 +73,9 @@ * 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. - * Where the target bounds a {@code ? super} wildcard, the target side reads {@code a supertype of} - * that bound. + * {@code @Nullable String}, so there the line says first that a non-wildcard type argument must be + * the same type. Where the target bounds a {@code ? super} wildcard, the target side reads {@code a + * supertype of} that bound. * *

The caret

* @@ -87,31 +89,34 @@ * {@code class Sub extends Base>}, viewing a {@code Sub} as a {@code Base} * rebuilds the {@code List<@Nullable String>} from the declaration of {@code Sub}, which the * written type does not hold. Where the source is viewed as a supertype at the root and the node is - * not in the written type, that view is printed as {@code source viewed as} and carries the carets. + * not in the written type, that view is printed as {@code source supertype} and carries the carets. * Below the root, as for an element of {@code List}, no view is printed, and such a node gets * no source caret. Two differences below one printed node share its caret, numbered for each. * *

A note explains itself in the entities the message already shows. Where the source wildcard is - * marked on a printed type, the type the reader wrote or the {@code source viewed as} line, the - * note names the type parameter of the class at that position, which the wildcard takes its bound - * from. Where it is marked on neither, as below the root of a supertype view, the type parameter - * belongs to a declaration this message never prints, and the note 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 for the source a {@code - * note} says what the reader cannot see there. + * marked on a printed type, the type the reader wrote or the {@code source supertype} line, the + * note prints the class the wildcard is a type argument of and names the type parameter the + * wildcard takes its bound from. Every other type argument of that class that is or holds a + * wildcard or a type argument of its own is printed as {@code ...}, so the one {@code ?} printed is + * the wildcard meant and a long type is not repeated. Where it is marked on neither, as below the + * root of a supertype view, the type parameter belongs to a declaration this message never prints, + * and the note 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 for the source a {@code note} says what the reader cannot see there. * *

The fixes

* - *

A {@code fix} line names the declaration it rewrites and the type it declares: the source - * variable with explicit wildcard bounds, or the target variable with {@code @Nullable} added. Each - * candidate is checked before it is printed: it 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 ?}. Where the declaration is a local variable of the compilation - * unit being analyzed, other than a pattern or resource variable, writes its type out before the - * name, and declares no other variable, the line comes with an Error Prone fix that makes the edit, - * except in a run that suggests suppressions, which asks for the suppression instead. A parameter - * or a field gets the line without the edit: its type is a contract that callers, overriders, and - * other assignments rely on, and the check that accepts the rewrite consults none of them. + *

A {@code possible fix} line names the declaration it rewrites and the type it declares: the + * source variable with explicit wildcard bounds, or the target variable with {@code @Nullable} + * added. Each candidate is checked before it is printed: it 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 ?}. Where the declaration is a local variable of the + * compilation unit being analyzed, other than a pattern or resource variable, writes its type out + * before the name, and declares no other variable, the line comes with an Error Prone fix that + * makes the edit, except in a run that suggests suppressions, which asks for the suppression + * instead. A parameter or a field gets the line without the edit: its type is a contract that + * callers, overriders, and other assignments rely on, and the check that accepts the rewrite + * consults none of them. * *

The two candidates differ in what they presume. Writing an explicit bound on a wildcard the * source declaration already writes is a mechanical fix of that wildcard, so it is offered wherever @@ -151,7 +156,7 @@ final class NullabilityMismatchMessage { private static final String SOURCE_LABEL = "source"; /** The key of the line that prints the supertype of the source type the check compared. */ - private static final String VIEWED_SOURCE_LABEL = "source viewed as"; + private static final String VIEWED_SOURCE_LABEL = "source supertype"; /** * The key of the line that prints the target type, and of the target node in a numbered entry. @@ -244,7 +249,7 @@ Report build( numbered) .lines()); for (int i = 0; i < listed.size(); i++) { - message.append(mismatchDetail(listed.get(i), numbered ? i + 1 : 0, printedView)); + message.append(mismatchDetail(listed.get(i), numbered ? i + 1 : 0, sourceType, printedView)); } // 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 @@ -275,16 +280,16 @@ Report build( } /** - * Appends the {@code fix:} line that declares {@code variable} with {@code type}, and adds the - * edit to {@code fixes} where {@code variable} is a local variable of the compilation unit being - * analyzed, other than a pattern or resource variable, its declaration writes its type out before - * the name and declares no other variable, and the run does not suggest suppressions. + * Appends the {@code possible fix:} line that declares {@code variable} with {@code type}, and + * adds the edit to {@code fixes} where {@code variable} is a local variable of the compilation + * unit being analyzed, other than a pattern or resource variable, its declaration writes its type + * out before the name and declares no other variable, and the run does not suggest suppressions. */ private void appendFix( StringBuilder message, List fixes, Symbol.VarSymbol variable, Type type) { message.append( String.format( - "\n fix: declare %s as %s", + "\n possible fix: declare %s as %s", variable.getSimpleName(), GenericsChecks.prettyTypeForError(type, state))); if (config.suggestSuppressions()) { // the run asks for the suppression ErrorBuilder adds after these fixes, and patching @@ -371,7 +376,8 @@ private String summaryLine(List mismatches) { : String.format( "%s and %d other position%s", first.path().describe(), others, others == 1 ? "" : "s"); - String exactly = mustMatchExactly(first) ? "a type argument must match exactly; " : ""; + String exactly = + mustMatchExactly(first) ? "a non-wildcard type argument must be the same type; " : ""; return String.format( "incompatible nullability in %s: %ssource has %s where target requires %s", where, @@ -383,7 +389,7 @@ private String summaryLine(List mismatches) { /** * Whether {@code mismatch} is a non-null type argument where the target has a {@code @Nullable} * one, which reads as a false subtype claim, since every {@code String} is a {@code @Nullable - * String}; what fails there is that a type argument has to match exactly. + * String}; what fails there is that a non-wildcard type argument must be the same type. */ private boolean mustMatchExactly(NullabilityMismatches.Mismatch mismatch) { return mismatch.relation() == NullabilityMismatches.Relation.SAME @@ -513,7 +519,7 @@ private static StringBuilder padTo(StringBuilder line, int column) { } /** - * Returns where {@code mismatch} is marked on the {@code source viewed as} line that prints + * Returns where {@code mismatch} is marked on the {@code source supertype} line that prints * {@code printedView}, or {@code null} where it is not marked there or no such line is printed. */ private @Nullable TypePath printedViewCaret( @@ -529,11 +535,15 @@ private static StringBuilder padTo(StringBuilder line, int column) { * position and the pair the first line names only for the first entry, and for any mismatch the * note about the source wildcard where there is one. * - * @param printedView the view of the source the {@code source viewed as} line prints, or {@code + * @param sourceType the source type the {@code source} line prints + * @param printedView the view of the source the {@code source supertype} line prints, or {@code * null} where no such line is printed */ private String mismatchDetail( - NullabilityMismatches.Mismatch mismatch, int number, @Nullable Type printedView) { + NullabilityMismatches.Mismatch mismatch, + int number, + Type sourceType, + @Nullable Type printedView) { String header = number == 0 ? " " : " " + number + ". "; String body = " ".repeat(header.length()); StringBuilder detail = new StringBuilder(); @@ -544,10 +554,10 @@ private String mismatchDetail( detail.append("\n").append(body).append(TARGET_LABEL).append(": "); detail.append(targetRequirement(mismatch)); if (mustMatchExactly(mismatch)) { - detail.append(" (a type argument must match exactly)"); + detail.append(" (a non-wildcard type argument must be the same type)"); } } - String note = boundOriginNote(mismatch, printedView); + String note = boundOriginNote(mismatch, sourceType, printedView); if (note != null) { detail.append("\n").append(body).append("note: ").append(note); } @@ -555,10 +565,10 @@ private String mismatchDetail( } /** - * Says where the source wildcard takes its upper bound from, or returns {@code null} where the - * printed node is not a wildcard, its bound is written out, or it is a captured wildcard whose - * type variable cannot be named. Where an uncaptured wildcard's type parameter cannot be named, - * the note states the bound alone. + * Says where the source wildcard takes its upper bound from and what that bound is, or returns + * {@code null} where the printed node is not a wildcard, its bound is written out, or it is a + * captured wildcard whose type variable cannot be named. Where an uncaptured wildcard's type + * parameter cannot be named, the note states the bound alone. * *

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 @@ -568,7 +578,7 @@ private String mismatchDetail( * {@code @NullMarked} code, and also one the configuration names as unannotated. */ private @Nullable String boundOriginNote( - NullabilityMismatches.Mismatch mismatch, @Nullable Type printedView) { + NullabilityMismatches.Mismatch mismatch, Type sourceType, @Nullable Type printedView) { // 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()); @@ -585,7 +595,7 @@ private String mismatchDetail( } String note = String.format( - "the source wildcard is the type argument for type parameter %s of %s", + "the wildcard in the source is the type argument for %s of %s", capturedTypeVariable.tsym.getSimpleName(), owner.getSimpleName()); return GenericsUtils.fromUnannotatedMethodOrClass( capturedTypeVariable.tsym, config, handler, state) @@ -599,8 +609,10 @@ private String mismatchDetail( // it instantiates there; javac's own link, WildcardType.bound, names a type parameter of // whatever supertype the wildcard was last substituted into TypePath caret = mismatch.sourceCaret(); + Type printed = sourceType; if (caret == null) { caret = printedViewCaret(mismatch, printedView); + printed = printedView; } TypePath.Step reachingStep = caret == null || caret.isRoot() ? null : caret.steps().get(caret.steps().size() - 1); @@ -609,25 +621,87 @@ private String mismatchDetail( ? reachingStep.formal() : null; Symbol.ClassSymbol owner = typeVariableOwner(formalTypeVariable); + String upperBound = + GenericsChecks.prettyTypeForError( + GenericsUtils.wildcardUpperBound(wildcard, state, config, handler), state); + boolean unbounded = wildcard.kind == BoundKind.UNBOUND; String source = - wildcard.kind == BoundKind.UNBOUND - ? "?" - : "? super " + GenericsChecks.prettyTypeForError(wildcard.type, state); - if (formalTypeVariable == null || owner == null) { + unbounded + ? "the unbounded wildcard ?" + : "the wildcard ? super " + GenericsChecks.prettyTypeForError(wildcard.type, state); + String hasBound = + unbounded ? " has the upper bound" : " has no upper bound of its own; its upper bound is"; + if (formalTypeVariable == null || owner == null || caret == null || reachingStep == null) { // no type parameter this message prints stands behind the bound: the wildcard sits at no // position of a printed type, as below the root of a supertype view (#2197), 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)); - } + // came from alone. "in the source" says which ? is meant, since two printed types carry one + return String.format("%s in the source%s %s (JLS 5.1.10)", source, hasBound, upperBound); + } + // the class the wildcard is a type argument of, printed so the reader can find that ? + Type holder = + printed == null + ? null // diff-coverage: ignore -- a caret is placed only on a printed type + : nodeAt(printed, caret.steps().subList(0, caret.steps().size() - 1)); + String in = + holder instanceof Type.ClassType holderClass + ? " in " + withOtherTypeArgumentsElided(holderClass, reachingStep.index()) + : ""; // diff-coverage: ignore -- the caret path reaches the wildcard through its class 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()); + "%s%s%s %s type parameter %s of %s, which is %s (JLS 5.1.10)", + source, + in, + hasBound, + unbounded ? "of" : "the bound of", + formalTypeVariable.tsym.getSimpleName(), + owner.getSimpleName(), + upperBound); + } + + /** + * Returns the node of {@code root} that {@code steps} reach, or {@code null} where one of them + * finds no such node. + */ + private static @Nullable Type nodeAt(Type root, List steps) { + Type node = root; + for (TypePath.Step step : steps) { + node = + switch (step.kind()) { + case TYPE_ARGUMENT -> + node instanceof Type.ClassType classType + && step.index() < classType.getTypeArguments().size() + ? classType.getTypeArguments().get(step.index()) + : null; // diff-coverage: ignore -- the path was recorded on this type + case WILDCARD_BOUND, WILDCARD_LOWER_BOUND -> + node instanceof Type.WildcardType wildcard ? wildcard.type : null; + case ARRAY_ELEMENT -> node instanceof Type.ArrayType array ? array.elemtype : null; + case ENCLOSING_TYPE -> + node instanceof Type.ClassType classType ? classType.getEnclosingType() : null; + }; + if (node == null) { + return null; // diff-coverage: ignore -- the path was recorded on this type + } + } + return node; + } + + /** + * Prints {@code holder} with its type argument at {@code index} in full, and as {@code ...} every + * other type argument that is or holds a wildcard or a type argument of its own, as {@code + * BiFunction}. So the one {@code ?} printed is the wildcard a note means, and a + * long type the {@code source} line already prints is not repeated. + */ + private String withOtherTypeArgumentsElided(Type.ClassType holder, int index) { + List typeArguments = holder.getTypeArguments(); + List printed = new ArrayList<>(); + for (int i = 0; i < typeArguments.size(); i++) { + String argument = GenericsChecks.prettyTypeForError(typeArguments.get(i), state); + printed.add( + i == index || (argument.indexOf('<') < 0 && argument.indexOf('?') < 0) + ? argument + : "..."); + } + return holder.tsym.getSimpleName() + "<" + String.join(", ", printed) + ">"; } /** 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 69e420a293..41912c37ca 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java @@ -66,18 +66,21 @@ 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}. */ + /** + * Names this step for a reader in the terms of the JLS, as {@code type argument for K of Map} + * or {@code component type}. + */ String describe() { return switch (kind) { case TYPE_ARGUMENT -> { if (formal == null || owner == null) { yield "type argument " + (index + 1); // diff-coverage: ignore -- the recorder sets both } - yield owner.getSimpleName() + " type argument " + formal.tsym.getSimpleName(); + yield "type argument for " + formal.tsym.getSimpleName() + " of " + owner.getSimpleName(); } - case WILDCARD_BOUND -> "wildcard upper bound"; - case WILDCARD_LOWER_BOUND -> "wildcard lower bound"; - case ARRAY_ELEMENT -> "array element"; + case WILDCARD_BOUND -> "upper bound of wildcard"; + case WILDCARD_LOWER_BOUND -> "lower bound of wildcard"; + case ARRAY_ELEMENT -> "component type"; case ENCLOSING_TYPE -> "enclosing type"; }; } @@ -124,9 +127,9 @@ boolean reachesSameNodeAs(TypePath other) { } /** - * 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. + * Names this path for a reader, as {@code type argument for V of Map -> type argument for E of + * List -> upper bound of wildcard}. 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 253a9d654b..6879beecf7 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 nullability in Collection type argument E -> wildcard upper bound: source has @Nullable String where target requires Object + // BUG: Diagnostic contains: incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable String where target requires Object return ownExtendsObject(collection); } } @@ -513,7 +513,7 @@ class Test { return list.toArray(); } static Object[] invalidCall(List list) { - // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable Object where target requires Object + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable Object where target requires Object return list.toArray(); } static class DelegatingList extends AbstractList { diff --git a/nullaway/src/test/java/com/uber/nullaway/ParameterAssignmentTests.java b/nullaway/src/test/java/com/uber/nullaway/ParameterAssignmentTests.java index 9b438ca395..29d0a6774e 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 nullability in List type argument E: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: source has @Nullable String where target requires 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 nullability in array element: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable String where target requires String p = q; } void matchingArrayElementTypesAreAllowed(@Nullable String[] p, @Nullable String[] q) { diff --git a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java index ff7bb78bfb..e379296c1a 100644 --- a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java @@ -33,17 +33,17 @@ static List make() { } void assignment() { List l = make(); - // BUG: Diagnostic contains: fix: declare l as List + // BUG: Diagnostic contains: possible fix: declare l as List Collection c = l; } void argument() { List l = make(); - // BUG: Diagnostic contains: fix: declare l as List + // BUG: Diagnostic contains: possible fix: declare l as List take(l); } Collection returned() { List l = make(); - // BUG: Diagnostic contains: fix: declare l as List + // BUG: Diagnostic contains: possible fix: declare l as List return l; } } @@ -66,11 +66,11 @@ class Test { List field = List.of(); static void take(Collection c) {} void parameter(List l) { - // BUG: Diagnostic contains: fix: declare l as List + // BUG: Diagnostic contains: possible fix: declare l as List take(l); } void field() { - // BUG: Diagnostic contains: fix: declare field as List + // BUG: Diagnostic contains: possible fix: declare field as List take(field); } } 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 c1f9077d41..b34a38fd6a 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 nullability in NullableTypeParam type argument E: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of NullableTypeParam: source has @Nullable String where target requires 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 nullability in NullableTypeParam type argument E: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of NullableTypeParam: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String NullableTypeParam.staticField = t1; - // BUG: Diagnostic contains: incompatible nullability in NullableTypeParam type argument E: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of NullableTypeParam: source has @Nullable String where target requires 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 nullability in NullableTypeParam type argument E: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of NullableTypeParam: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String GenericTypeArgMethods.nullableTypeParamArg(t1); - // BUG: Diagnostic contains: incompatible nullability in NullableTypeParam type argument E: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of NullableTypeParam: source has @Nullable String where target requires 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 e3c312b55d..9886b935eb 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 nullability in Foo type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: source has @Nullable String where target requires String Bar b = new Bar<>(Foo.makeNullableStr()); - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: source has @Nullable Void where target requires Void + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: source has @Nullable Void where target requires 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 nullability in Foo type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: source has @Nullable String where target requires String return new Bar<>(Foo.makeNullableStr()); } } @@ -139,7 +139,7 @@ void testNegative() { takeNullableVoid(new Bar<>(Foo.make())); } void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: source has @Nullable String where target requires String takeStr(new Bar<>(Foo.makeNullableStr())); } } @@ -172,7 +172,7 @@ static class Bar { return (new Bar<>(Foo.make())); } Bar testPositive() { - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: source has @Nullable String where target requires 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 nullability in Foo type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: source has @Nullable String where target requires 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 nullability in Foo type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: source has @Nullable String where target requires String return new Bar<>(Foo.makeNullableStr()) {}; } void paramNegative() { takeNullableVoid(new Bar<>(Foo.make()) {}); } void paramPositive() { - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: source has @Nullable String where target requires 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 nullability in Foo type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: source has @Nullable String where target requires String new Bar<>(f1, f2); } } @@ -471,7 +471,7 @@ static void testNegative() { takeFooNullableString(id(new FooImpl<>(makeNullableFoo()))); } static void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: source has @Nullable String where target requires 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 nullability in Foo type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: source has @Nullable String where target requires String return new Box<>(id(makeNullableFoo())); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInferenceErrorReportingTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInferenceErrorReportingTests.java index 4fcefad8f3..b4789f18f5 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 nullability in array element: source has @Nullable E where target requires E + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable E where target requires E return Arrays.copyOf(original, original.length); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java index 9d70370643..13812b831d 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java @@ -245,7 +245,7 @@ static class Sub extends Outer<@Nullable S> {} > void nullableThroughBound(Y y) { // BUG: Diagnostic contains: dereferenced expression 'y.get()' is @Nullable y.get().hashCode(); - // BUG: Diagnostic contains: incompatible nullability in Outer type argument O: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for O of Outer: source has @Nullable String where target requires String Outer nonNull = y; Outer<@Nullable String> nullable = y; y.new Inner(null); @@ -272,7 +272,7 @@ > void nonNullThroughBoundOfBound(Z z) { void nullableThroughCapturedWildcard(List> l) { // BUG: Diagnostic contains: dereferenced expression 'l.get(0).get()' is @Nullable l.get(0).get().hashCode(); - // BUG: Diagnostic contains: incompatible nullability in Outer type argument O: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for O of Outer: source has @Nullable String where target requires String Outer nonNull = l.get(0); Outer<@Nullable String> nullable = l.get(0); } @@ -361,7 +361,7 @@ static class ListFuture } static MyFuture> invalid() { - // BUG: Diagnostic contains: incompatible nullability in MyFuture type argument T -> List type argument E: source has @Nullable V where target requires V + // BUG: Diagnostic contains: incompatible nullability in type argument for T of MyFuture -> type argument for E of List: source has @Nullable V where target requires 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 nullability in List type argument E: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: source has @Nullable String where target requires String List invalid = box.get(); box.set(nullableList); - // BUG: Diagnostic contains: incompatible nullability in List type argument E: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: a non-wildcard type argument must be the same type; source has String where target requires @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 nullability in List type argument E: source has @Nullable O where target requires O + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: source has @Nullable O where target requires O List invalid = child.get(); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericLambdaTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericLambdaTests.java index 2489e6323d..a1f5fb0663 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 nullability in List type argument E: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: source has @Nullable String where target requires String MarkedListSupplier s = () -> l; } void blockBodyToMarkedInterface(List<@Nullable String> l) { - // BUG: Diagnostic contains: incompatible nullability in List type argument E: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: source has @Nullable String where target requires 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 eb4ebf08e1..158c3ba86f 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 nullability in Box type argument T: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Box: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String acceptsNullable(flat); } @@ -1337,7 +1337,7 @@ void testNegative() { receiver(makeCancelable(this::target)); } void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in Callback type argument T: a type argument must match exactly; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Callback: a non-wildcard type argument must be the same type; source has Object where target requires @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 261ec2c674..d2e251849a 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java @@ -559,9 +559,9 @@ interface B { X b(); } id1(value).a().length(); A<@Nullable String> nullableA = id1(value); B nonNullB = id1(value); - // BUG: Diagnostic contains: incompatible nullability in A type argument X: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of A: source has @Nullable String where target requires String A nonNullA = id1(value); - // BUG: Diagnostic contains: incompatible nullability in B type argument X: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String B<@Nullable String> nullableB = id1(value); } @@ -572,9 +572,9 @@ interface B { X b(); } id2(value).a().length(); A<@Nullable String> nullableA = id2(value); B nonNullB = id2(value); - // BUG: Diagnostic contains: incompatible nullability in A type argument X: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of A: source has @Nullable String where target requires String A nonNullA = id2(value); - // BUG: Diagnostic contains: incompatible nullability in B type argument X: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String B<@Nullable String> nullableB = id2(value); } @@ -585,9 +585,9 @@ interface B { X b(); } id3(value).a().length(); A<@Nullable String> nullableA = id3(value); B nonNullB = id3(value); - // BUG: Diagnostic contains: incompatible nullability in A type argument X: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of A: source has @Nullable String where target requires String A nonNullA = id3(value); - // BUG: Diagnostic contains: incompatible nullability in B type argument X: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String B<@Nullable String> nullableB = id3(value); } @@ -598,9 +598,9 @@ interface B { X b(); } id4(value).a().length(); A<@Nullable String> nullableA = id4(value); B nonNullB = id4(value); - // BUG: Diagnostic contains: incompatible nullability in A type argument X: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of A: source has @Nullable String where target requires String A nonNullA = id4(value); - // BUG: Diagnostic contains: incompatible nullability in B type argument X: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String B<@Nullable String> nullableB = id4(value); } } @@ -634,9 +634,9 @@ static class Box1> & B>> { box.get().a().get(0).length(); A> nullableA = box.get(); B> nonNullB = box.get(); - // BUG: Diagnostic contains: incompatible nullability in A type argument X -> List type argument E: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of A -> type argument for E of List: source has @Nullable String where target requires String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible nullability in B type argument X -> List type argument E: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String B> nullableB = box.get(); } @@ -652,9 +652,9 @@ static class Box2> & A>> { box.get().a().get(0).length(); A> nullableA = box.get(); B> nonNullB = box.get(); - // BUG: Diagnostic contains: incompatible nullability in A type argument X -> List type argument E: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of A -> type argument for E of List: source has @Nullable String where target requires String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible nullability in B type argument X -> List type argument E: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String B> nullableB = box.get(); } @@ -670,9 +670,9 @@ static class Box3> & B>> box.get().a().get(0).length(); A> nullableA = box.get(); B> nonNullB = box.get(); - // BUG: Diagnostic contains: incompatible nullability in A type argument X -> List type argument E: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of A -> type argument for E of List: source has @Nullable String where target requires String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible nullability in B type argument X -> List type argument E: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String B> nullableB = box.get(); } @@ -688,9 +688,9 @@ static class Box4> & A>> box.get().a().get(0).length(); A> nullableA = box.get(); B> nonNullB = box.get(); - // BUG: Diagnostic contains: incompatible nullability in A type argument X -> List type argument E: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of A -> type argument for E of List: source has @Nullable String where target requires String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible nullability in B type argument X -> List type argument E: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String B> nullableB = box.get(); } } @@ -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 nullability in Foo type argument T: a type argument must match exactly; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: a non-wildcard type argument must be the same type; source has Object where target requires @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 nullability in Foo type argument T: a type argument must match exactly; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: a non-wildcard type argument must be the same type; source has Object where target requires @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 nullability in Foo type argument V -> ArrayList type argument E: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for V of Foo -> type argument for E of ArrayList: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String Foo> fooNonNull_2 = f.nonNullTest(); - // BUG: Diagnostic contains: incompatible nullability in Foo type argument K: a type argument must match exactly; source has Integer where target requires @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in type argument for K of Foo: a non-wildcard type argument must be the same type; source has Integer where target requires @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 nullability in Foo type argument T -> array element -> Foo type argument T: a type argument must match exactly; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo -> component type -> type argument for T of Foo: a non-wildcard type argument must be the same type; source has Object where target requires @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 nullability in array element -> Foo type argument T: a type argument must match exactly; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in component type -> type argument for T of Foo: a non-wildcard type argument must be the same type; source has Object where target requires @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 nullability in Bar type argument T -> Bar type argument T: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Bar -> type argument for T of Bar: a non-wildcard type argument must be the same type; source has String where target requires @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 nullability in Function type argument T and 1 other position: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Function and 1 other position: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String 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 nullability in Foo type argument T: a type argument must match exactly; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: a non-wildcard type argument must be the same type; source has Object where target requires @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 nullability in Foo type argument T: a type argument must match exactly; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: a non-wildcard type argument must be the same type; source has Object where target requires @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 nullability in Foo type argument T: a type argument must match exactly; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: a non-wildcard type argument must be the same type; source has Object where target requires @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 nullability in array element: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable String where target requires 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 nullability in array element: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable String where target requires String stringField = f(arr2, "hi"); } } @@ -2242,12 +2242,12 @@ public void capturedTypeAtNullUnmarkedBoundary() { message -> message.contains( """ - incompatible nullability in Foo type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for T of Foo -> upper bound of wildcard: source has @Nullable Object where target requires Object source: Foo ^^^^^^^^^^^^ target: Foo ^ - note: the source wildcard is the type argument for type parameter T of Box, and Box is unannotated + note: the wildcard in the source is the type argument for T of Box, and Box is unannotated """)) .addSourceLines( "Test.java", @@ -2290,12 +2290,12 @@ public void capturedTypeGetsDirectNullableAnnotationFromTypeVariableUse() { message -> message.contains( """ - incompatible nullability in Foo type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for T of Foo -> upper bound of wildcard: source has @Nullable Object where target requires Object source: Foo<@Nullable capture of ?> ^^^^^^^^^^^^^^^^^^^^^^ target: Foo ^^^^^^ - note: the source wildcard is the type argument for type parameter T of Holder + note: the wildcard in the source is the type argument for T of Holder """)) .addSourceLines( "Test.java", @@ -2450,7 +2450,7 @@ class Test { class Box {} void swapBoxes(Box box1, Box box2) {} void testPositive(Box box1, Box<@Nullable String> box2) { - // BUG: Diagnostic contains: incompatible nullability in Box type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Box: source has @Nullable String where target requires String swapBoxes(box1, box2); } void TestNegative(Box<@Nullable String> box1, Box<@Nullable String> box2) { @@ -2545,7 +2545,7 @@ Supplier make2() { } // tests that our repair computes a consistent substitution for the type variables void test2() { - // BUG: Diagnostic contains: incompatible nullability in Supplier type argument T: a type argument must match exactly; source has OuterT where target requires @Nullable OuterT + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Supplier: a non-wildcard type argument must be the same type; source has OuterT where target requires @Nullable OuterT acceptTwoSup(sup, sup2); } } @@ -2677,7 +2677,7 @@ static class Foo { .or(new Foo<@Nullable String>()); // a true positive case - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: source has @Nullable String where target requires String static Foo WRONG = Foo.of(new Foo<@Nullable String>()).or(new Foo<@Nullable String>()); } @@ -2733,7 +2733,7 @@ class Test { static class Box {} static void accept(Box<@Nullable T> box) {} void test(Box> box) { - // BUG: Diagnostic contains: incompatible nullability in Box type argument T: a type argument must match exactly; source has CompletableFuture where target requires @Nullable CompletableFuture + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Box: a non-wildcard type argument must be the same type; source has CompletableFuture where target requires @Nullable CompletableFuture accept(box); } } @@ -3346,9 +3346,9 @@ class GInner { return x; } void nullableQualifier(Outer<@Nullable String> o) { - // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Outer type argument O: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> type argument for O of Outer: source has @Nullable String where target requires String id(o.new Inner("")); - // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Outer type argument O: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> type argument for O of Outer: source has @Nullable String where target requires 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 88c18c8b69..86f2e93e76 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 nullability in List type argument E: source has @Nullable Void where target requires Void + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: source has @Nullable Void where target requires 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 nullability in List type argument E: source has @Nullable Void where target requires Void + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: source has @Nullable Void where target requires 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 f4710616bc..3c3d1c6037 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 nullability in NonNullTypeParam type argument E: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of NonNullTypeParam: source has @Nullable String where target requires String new NonNullTypeParam< // BUG: Diagnostic contains: Generic type parameter @Nullable String>()); @@ -229,7 +229,7 @@ class Test { static class Holder {} static void typeArguments() { Holder other = new Holder<@Other String>(); - // BUG: Diagnostic contains: incompatible nullability in Holder type argument E: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of Holder: source has @Nullable String where target requires String Holder otherThenNullable = new Holder<@Other @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 nullability in enclosing type -> Wrapper type argument P: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> type argument for P of Wrapper: source has @Nullable String where target requires String param(x); } static void positiveAssign() { Wrapper<@Nullable String>.Fn p1 = null; - // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Wrapper type argument P: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> type argument for P of Wrapper: source has @Nullable String where target requires String Wrapper.Fn p2 = p1; } static Wrapper.@Nullable Fn positiveReturn() { Wrapper<@Nullable String>.Fn p1 = null; - // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Wrapper type argument P: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> type argument for P of Wrapper: source has @Nullable String where target requires String return p1; } static void negativeParam() { @@ -349,13 +349,13 @@ void callOnResult() { } public void testPositive() { addCallback( - // BUG: Diagnostic contains: incompatible nullability in Callback type argument T: a type argument must match exactly; source has Integer where target requires @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Callback: a non-wildcard type argument must be the same type; source has Integer where target requires @Nullable Integer new Callback() { @Override public void onResult(Integer value) { - // BUG: Diagnostic contains: incompatible nullability in Callback type argument T: a type argument must match exactly; source has Integer where target requires @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Callback: a non-wildcard type argument must be the same type; source has Integer where target requires @Nullable Integer removeCallback(this); - // BUG: Diagnostic contains: incompatible nullability in Callback type argument T: a type argument must match exactly; source has Integer where target requires @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Callback: a non-wildcard type argument must be the same type; source has Integer where target requires @Nullable Integer Callback<@Nullable Integer> self = this; } void callOnResult() { @@ -457,7 +457,7 @@ public void genericsChecksForAssignments() { class Test { static class NullableTypeParam {} static void testPositive(NullableTypeParam<@Nullable String> t1) { - // BUG: Diagnostic contains: incompatible nullability in NullableTypeParam type argument E: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of NullableTypeParam: source has @Nullable String where target requires 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 nullability in NullableTypeParam type argument E: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of NullableTypeParam: source has @Nullable String where target requires 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 nullability in SampleClassMultipleArguments type argument E1 -> SampleClass type argument E -> SampleClass type argument E: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for E1 of SampleClassMultipleArguments -> type argument for E of SampleClass -> type argument for E of SampleClass: a non-wildcard type argument must be the same type; source has String where target requires @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 nullability in Fn type argument R: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for R of Fn: source has @Nullable String where target requires 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 nullability in Fn2 type argument P: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for P of Fn2: a non-wildcard type argument must be the same type; source has String where target requires @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 nullability in SuperClassC type argument P1: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for P1 of SuperClassC: a non-wildcard type argument must be the same type; source has String where target requires @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 nullability in D type argument P: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for P of D: source has @Nullable String where target requires String D f1 = new B<@Nullable String>(); - // BUG: Diagnostic contains: incompatible nullability in D type argument P: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for P of D: source has @Nullable String where target requires 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 nullability in Super type argument A and 1 other position: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for A of Super and 1 other position: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String 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 nullability in D type argument P -> C type argument P: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for P of D -> type argument for P of C: source has @Nullable String where target requires String D> f1 = new B>(); - // BUG: Diagnostic contains: incompatible nullability in A type argument P: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for P of A: source has @Nullable String where target requires String A, String> f2 = new A, @Nullable String>(); - // BUG: Diagnostic contains: incompatible nullability in D type argument P: source has Test.@Nullable C where target requires Test.C + // BUG: Diagnostic contains: incompatible nullability in type argument for P of D: source has Test.@Nullable C where target requires 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 nullability in A type argument T1: a type argument must match exactly; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T1 of A: a non-wildcard type argument must be the same type; source has Object where target requires @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 nullability in A type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: source has @Nullable String where target requires String return new A<@Nullable String>(); } static A<@Nullable String> testPositive2() { - // BUG: Diagnostic contains: incompatible nullability in A type argument T: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must be the same type; source has String where target requires @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 nullability in A type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: source has @Nullable String where target requires 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 nullability in A type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: source has @Nullable String where target requires 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 nullability in A type argument T -> A type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A -> type argument for T of A: source has @Nullable String where target requires String A a = sampleMethod1(a1, a2); } static void testPositive2(A> a1, A a2) { - // BUG: Diagnostic contains: incompatible nullability in A type argument T -> A type argument T: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A -> type argument for T of A: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String A a = sampleMethod2(a1, a2); } static void testPositive3(A a1) { - // BUG: Diagnostic contains: incompatible nullability in A type argument T: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must be the same type; source has String where target requires @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 nullability in A type argument T: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must be the same type; source has String where target requires @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 nullability in A type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: source has @Nullable String where target requires String A<@Nullable String> b = sampleMethodWithVarArgs(a1); - // BUG: Diagnostic contains: incompatible nullability in A type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: source has @Nullable String where target requires 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 nullability in array element -> A type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in component type -> type argument for T of A: source has @Nullable String where target requires 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 nullability in A type argument T -> array element -> A type argument T: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A -> component type -> type argument for T of A: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String A[]> var1 = new A[]>(); - // BUG: Diagnostic contains: incompatible nullability in A type argument T -> array element -> A type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A -> component type -> type argument for T of A: source has @Nullable String where target requires 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 nullability in A type argument T -> array element -> A type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A -> component type -> type argument for T of A: source has @Nullable String where target requires String A[]> var2 = new A[]>(); } } @@ -1435,7 +1435,7 @@ public void genericPrimitiveArrayTypeAssignment() { class Test { static class A { } static void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in A type argument T: a type argument must match exactly; source has int [] where target requires int @Nullable [] + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must be the same type; source has int [] where target requires 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 nullability in enclosing type -> A type argument X: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> type argument for X of A: source has @Nullable String where target requires 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>(); @@ -2057,28 +2057,28 @@ void staticSubclassWithNullableOuterMatches(NullableInner input) { Outer<@Nullable String>.Inner result = input; } void staticSubclassWithNullableOuterMismatches(NullableInner input) { - // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Outer type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> type argument for T of Outer: source has @Nullable String where target requires String Outer.Inner result = input; } void staticSubclassWithNonNullOuterMatches(NonNullInner input) { Outer.Inner result = input; } void staticSubclassWithNonNullOuterMismatches(NonNullInner input) { - // BUG: Diagnostic contains: incompatible nullability in enclosing type -> Outer type argument T: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> type argument for T of Outer: a non-wildcard type argument must be the same type; source has String where target requires @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 nullability in enclosing type -> Outer type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> type argument for T of Outer: source has @Nullable String where target requires 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 nullability in enclosing type -> Outer type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> type argument for T of Outer: source has @Nullable String where target requires String Outer.Inner result = input; } } @@ -3033,7 +3033,7 @@ static class B implements A<@Nullable String>, Serializable {} static class C implements A, Serializable {} static void test1(Object o) { var x = (A & Serializable) o; - // BUG: Diagnostic contains: source viewed as: A<@Nullable String> + // BUG: Diagnostic contains: source supertype: A<@Nullable String> x = new B(); // ok x = new C(); @@ -3041,7 +3041,7 @@ static void test1(Object o) { static void test2(Object o) { var x = (A<@Nullable String> & Serializable) o; x = new B(); - // BUG: Diagnostic contains: incompatible nullability in A type argument T: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String x = new C(); } } @@ -3138,7 +3138,7 @@ void testNegative(Function<@Nullable V, @Nullable V> f) { foo(f); } void testPositive(Function f) { - // BUG: Diagnostic contains: incompatible nullability in Function type argument T and 1 other position: a type argument must match exactly; source has V where target requires @Nullable V + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Function and 1 other position: a non-wildcard type argument must be the same type; source has V where target requires @Nullable V 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 nullability in array element -> Function type argument T and 1 other position: a type argument must match exactly; source has V where target requires @Nullable V + // BUG: Diagnostic contains: incompatible nullability in component type -> type argument for T of Function and 1 other position: a non-wildcard type argument must be the same type; source has V where target requires @Nullable V 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 nullability in Function type argument T and 1 other position: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Function and 1 other position: source has @Nullable String where target requires String this.<@Nullable String>foo(f); } void testPositiveArray(Function f) { - // BUG: Diagnostic contains: incompatible nullability in Function type argument T and 1 other position: source has String @Nullable [] where target requires String [] + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Function and 1 other position: source has String @Nullable [] where target requires String [] this.foo(f); } } @@ -3196,15 +3196,15 @@ void testNegative(Function f) { foo(f); } void testPositive1(Function<@Nullable V, V> f) { - // BUG: Diagnostic contains: incompatible nullability in Function type argument T and 1 other position: source has @Nullable V where target requires V + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Function and 1 other position: source has @Nullable V where target requires V foo(f); } void testPositive2(Function f) { - // BUG: Diagnostic contains: incompatible nullability in Function type argument R: a type argument must match exactly; source has V where target requires @Nullable V + // BUG: Diagnostic contains: incompatible nullability in type argument for R of Function: a non-wildcard type argument must be the same type; source has V where target requires @Nullable V foo(f); } void testPositive3(Function<@Nullable V, @Nullable V> f) { - // BUG: Diagnostic contains: incompatible nullability in Function type argument T: source has @Nullable V where target requires V + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Function: source has @Nullable V where target requires 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 nullability in Function type argument T and 1 other position: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Function and 1 other position: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String bar = f; } } @@ -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 nullability in Inner type argument T: source has @Nullable Object where target requires Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Inner: source has @Nullable Object where target requires Object Inner mNonNullThing = new Inner<@Nullable Object>().identity(); } """) @@ -3440,7 +3440,7 @@ private static class A { } private static class B extends A<@Nullable Object> { B(List l) { - // BUG: Diagnostic contains: incompatible nullability in List type argument E: a type argument must match exactly; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: a non-wildcard type argument must be the same type; source has Object where target requires @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 nullability in A type argument T: source has @Nullable Object where target requires Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: source has @Nullable Object where target requires Object A a = new B(); - // BUG: Diagnostic contains: incompatible nullability in A type argument T: a type argument must match exactly; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must be the same type; source has Object where target requires @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 nullability in MaybeNull type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of MaybeNull: source has @Nullable String where target requires String accept(nonNull.asNullable()); MaybeNull<@Nullable String> m1 = nonNull.asNullable(); - // BUG: Diagnostic contains: incompatible nullability in MaybeNull type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of MaybeNull: source has @Nullable String where target requires 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 nullability in Foo type argument T: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String Foo<@Nullable String> f1 = nullableFoo.nonNullField; Foo f2 = nullableFoo.nonNullField; Foo<@Nullable String> f3 = nonnullFoo.nullableField; - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: source has @Nullable String where target requires String Foo f4 = nonnullFoo.nullableField; } } 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 f4beb5739c..40a8f0f806 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 nullability in Result type argument T -> wildcard upper bound: source has @Nullable A & @Nullable B where target requires A + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Result -> upper bound of wildcard: source has @Nullable A & @Nullable B where target requires A return source.result(); } Result rejectsAllNullableLastComponent(AllNullable source) { - // BUG: Diagnostic contains: incompatible nullability in Result type argument T -> wildcard upper bound: source has @Nullable A & @Nullable B where target requires B + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Result -> upper bound of wildcard: source has @Nullable A & @Nullable B where target requires B return source.result(); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java index cc987f04da..6ca561eda6 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java @@ -36,7 +36,7 @@ void acceptsMatchingNullableComponent(Factory factory) { } void rejectsNonNullMatchingComponent(Factory factory) { - // BUG: Diagnostic contains: incompatible nullability in A type argument E: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of A: source has @Nullable String where target requires String A result = factory.fromA().get(); } @@ -45,7 +45,7 @@ void acceptsOtherNonNullComponent(Factory factory) { } void rejectsWideningOtherInvariantComponent(Factory factory) { - // BUG: Diagnostic contains: incompatible nullability in B type argument E: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of B: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String B<@Nullable String> result = factory.fromA().get(); } @@ -54,7 +54,7 @@ void acceptsMatchingNonNullComponent(Factory factory) { } void rejectsWideningMatchingInvariantComponent(Factory factory) { - // BUG: Diagnostic contains: incompatible nullability in B type argument E: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of B: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String B<@Nullable String> result = factory.fromB().get(); } } 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 635f9849ad..6f0dcb7fac 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 nullability in array element: source has @Nullable Test where target requires Test + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable Test where target requires 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 nullability in array element: source has @Nullable Test where target requires Test + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable Test where target requires 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 nullability in array element: source has @Nullable Test where target requires Test + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable Test where target requires 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 nullability in array element: source has @Nullable Integer where target requires Integer + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable Integer where target requires 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 nullability in array element: source has @Nullable Integer where target requires Integer + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable Integer where target requires Integer x1 = new @Nullable Integer[0]; } } @@ -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 nullability in array element -> array element: source has @Nullable Integer where target requires Integer + // BUG: Diagnostic contains: incompatible nullability in component type -> component type: source has @Nullable Integer where target requires 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 nullability in array element: source has @Nullable Integer where target requires Integer + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable Integer where target requires 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 nullability in array element -> array element: source has @Nullable Integer where target requires Integer + // BUG: Diagnostic contains: incompatible nullability in component type -> component type: source has @Nullable Integer where target requires Integer Integer[] @Nullable [] y4 = new @Nullable Integer[3][4]; - // BUG: Diagnostic contains: incompatible nullability in array element -> array element: source has @Nullable Integer where target requires Integer + // BUG: Diagnostic contains: incompatible nullability in component type -> component type: source has @Nullable Integer where target requires Integer Integer[][] y1 = nullableElems2D; - // BUG: Diagnostic contains: incompatible nullability in array element -> array element -> array element: source has @Nullable Integer where target requires Integer + // BUG: Diagnostic contains: incompatible nullability in component type -> component type -> component type: source has @Nullable Integer where target requires Integer Integer[][][] y2 = nullableElems3D; - // BUG: Diagnostic contains: incompatible nullability in array element: source has Integer @Nullable [] where target requires Integer [] + // BUG: Diagnostic contains: incompatible nullability in component type: source has Integer @Nullable [] where target requires Integer [] Integer[][] y3 = nullableInner; } } @@ -673,7 +673,7 @@ public void arraysAndGenerics() { class Test { void foo(List<@Nullable Integer[]> l) {} void testPositive(List p) { - // BUG: Diagnostic contains: incompatible nullability in List type argument E -> array element: a type argument must match exactly; source has Integer where target requires @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List -> component type: a non-wildcard type argument must be the same type; source has Integer where target requires @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 nullability in array element: source has @Nullable Foo where target requires Foo + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable Foo where target requires Foo return result; } Foo[] getFoosNegative() { @@ -706,7 +706,7 @@ Foo[] getFoosNegative() { } void takeFoos(Foo[] foos) {} void callTakeFoosPositive(@Nullable Foo[] p) { - // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable Foo where target requires Foo + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable Foo where target requires 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 nullability in array element: source has @Nullable Foo where target requires Foo + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable Foo where target requires Foo takeFoosVarargs(p); - // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable Foo where target requires Foo + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable Foo where target requires Foo takeFoosVarargs(p2, p); } void callTakeFoosVarargsNegative(Foo[] p) { @@ -1390,7 +1390,7 @@ static void nullableExplicitArrayStore() { static void nullableTypeArgumentRejectedFromNonNullBoundedWildcardArray( CompletableFuture[] futures, CompletableFuture<@Nullable String> value) { - // BUG: Diagnostic contains: incompatible nullability in CompletableFuture type argument T -> wildcard upper bound: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of CompletableFuture -> upper bound of wildcard: source has @Nullable String where target requires String futures[0] = value; } } @@ -1772,7 +1772,7 @@ void writeNullIntoNonNullElementOfVarLoopVariableOverNestedLocalArray() { } void assignNullableTypeArgumentElementOfLocalArray() { List<@Nullable String>[] local = new List[1]; - // BUG: Diagnostic contains: incompatible nullability in List type argument E: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: source has @Nullable String where target requires 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 4173fa66ce..06923dcd8a 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 nullability in List type argument E: source has @Nullable Object where target requires Object + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: source has @Nullable Object where target requires Object PolyNullMethods.first(nullable, nullable); } } 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 8d4f090ff0..1a95b64afd 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 nullability in NullableSibling type argument Y: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for Y of NullableSibling: source has @Nullable String where target requires String NullableSibling x = nullableSibling(); } void siblingWithNullableNonObjectBound() { 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 7aaae5ad16..9d97792e9f 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 nullability in List type argument E: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: source has @Nullable String where target requires 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 nullability in List type argument E: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: source has @Nullable String where target requires String .toList(); } } 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 c6b7e51245..7de2949103 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 nullability in Box type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Box: source has @Nullable String where target requires 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 94a7507d0b..83f20cf4bc 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -319,7 +319,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 nullability in Foo type argument T -> wildcard upper bound: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo -> upper bound of wildcard: source has @Nullable String where target requires String String s = nonnullWildcard(f); // legal String s2 = nonnullWildcard(f2); @@ -348,7 +348,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 nullability in Foo type argument T -> wildcard upper bound: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo -> upper bound of wildcard: source has @Nullable String where target requires String String s = nonnullWildcard(f); s.hashCode(); } @@ -379,7 +379,7 @@ void testNegative(Foo> f) { s.hashCode(); } void testPositive(Foo> f) { - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound -> Bar type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo -> upper bound of wildcard -> type argument for T of Bar: source has @Nullable String where target requires String String s = nonnullWildcard(f); s.hashCode(); } @@ -411,7 +411,7 @@ void testNegative(Foo>> f) { s.hashCode(); } void testPositive(Foo>> f) { - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound -> Bar type argument T -> Baz type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo -> upper bound of wildcard -> type argument for T of Bar -> type argument for T of Baz: source has @Nullable String where target requires String String s = nonnullWildcard(f); s.hashCode(); } @@ -443,7 +443,7 @@ void testNegative(Foo<@Nullable Bar>> f) { s.hashCode(); } void testPositive(Foo<@Nullable Bar>> f) { - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: source has Test.@Nullable Bar> where target requires Test.Bar> + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo -> upper bound of wildcard: source has Test.@Nullable Bar> where target requires Test.Bar> String s = nonnullWildcard(f); s.hashCode(); } @@ -473,7 +473,7 @@ void testNegative(Foo f) { s.hashCode(); } void testPositive(Foo f) { - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo -> upper bound of wildcard: source has @Nullable String where target requires String String s = nonnullWildcard(f); s.hashCode(); } @@ -496,22 +496,22 @@ class Foo {} Foo nullableField; Test(Foo f) { nullableField = f; - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo -> upper bound of wildcard: source has @Nullable String where target requires String nonnullField = f; } Foo nullableReturn(Foo f) { return f; } Foo nonnullReturn(Foo f) { - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo -> upper bound of wildcard: source has @Nullable String where target requires String return f; } void testLocal(Foo f) { Foo ok = f; - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo -> upper bound of wildcard: source has @Nullable String where target requires String Foo bad = f; var f2 = f; - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo -> upper bound of wildcard: source has @Nullable String where target requires String Foo bad2 = f2; } } @@ -538,10 +538,10 @@ void testLocals( Foo nonnullSuperLocal = nullableObjectFoo; Foo nullableSuperLocal = nullableObjectFoo; Foo nullableSuperLocal2 = nullableStringFoo; - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard lower bound: source has Object where target requires a supertype of @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo -> lower bound of wildcard: source has Object where target requires a supertype of @Nullable String Foo nullableSuperLocal3 = objectFoo; Foo nonnullSuperFromNullableSuper = nullableSuperFoo; - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard lower bound: source has String where target requires a supertype of @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo -> lower bound of wildcard: source has String where target requires a supertype of @Nullable String Foo nullableSuperFromNonnullSuper = nonnullSuperFoo; } } @@ -566,11 +566,11 @@ void testLocals( Foo fromNonnullSuper = nonnullSuperFoo; Foo fromNullableSuper = nullableSuperFoo; Foo fromUnbounded = unboundedFoo; - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo -> upper bound of wildcard: source has @Nullable Object where target requires Object Foo badFromNonnullSuper = nonnullSuperFoo; - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo -> upper bound of wildcard: source has @Nullable Object where target requires Object Foo badFromNullableSuper = nullableSuperFoo; - // BUG: Diagnostic contains: incompatible nullability in Foo type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo -> upper bound of wildcard: source has @Nullable Object where target requires Object Foo badFromUnbounded = unboundedFoo; } } @@ -595,7 +595,7 @@ void testLocals( NonNullBoundFoo nonnullSuperStringFoo) { NonNullBoundFoo fromNonnull = nonnullObjectFoo; NonNullBoundFoo fromNonnullExtends = nonnullExtendsObjectFoo; - // BUG: Diagnostic contains: incompatible nullability in NonNullBoundFoo type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NonNullBoundFoo -> upper bound of wildcard: source has @Nullable Object where target requires Object NonNullBoundFoo fromNullableExtends = nullableExtendsObjectWithNonnullBoundFoo; NonNullBoundFoo fromSuper = nonnullSuperStringFoo; } @@ -621,13 +621,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 nullability in Pair type argument U -> wildcard upper bound: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for U of Pair -> upper bound of wildcard: source has @Nullable String where target requires String Pair<@Nullable String, ? extends String> invalid = pair; } static void capturedFirstArgument(Pair pair) { Pair target = pair; - // BUG: Diagnostic contains: incompatible nullability in Pair type argument U -> wildcard upper bound: source has @Nullable Object where target requires Object + // BUG: Diagnostic contains: incompatible nullability in type argument for U of Pair -> upper bound of wildcard: source has @Nullable Object where target requires Object Pair invalid = pair; } @@ -636,7 +636,7 @@ static class UnmarkedPair {} static void capturedFirstArgumentFromUnmarkedCode(UnmarkedPair pair) { UnmarkedPair target = pair; - // BUG: Diagnostic contains: incompatible nullability in UnmarkedPair type argument U -> wildcard upper bound: source has @Nullable Object where target requires Object + // BUG: Diagnostic contains: incompatible nullability in type argument for U of UnmarkedPair -> upper bound of wildcard: source has @Nullable Object where target requires Object UnmarkedPair invalid = pair; } } @@ -754,7 +754,7 @@ T get() { } } static void test(Holder> holder) { - // BUG: Diagnostic contains: incompatible nullability in Box type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Box: source has @Nullable String where target requires String Box box = holder.get(); } } @@ -880,7 +880,7 @@ static void nullable(NullableHolder holder) { // BUG: Diagnostic contains: dereferenced expression 'box.get()' is @Nullable box.get().length(); Box<@Nullable String> compatible = holder.nonNullValue(); - // BUG: Diagnostic contains: incompatible nullability in Box type argument E: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of Box: source has @Nullable String where target requires String Box incompatible = holder.nonNullValue(); // BUG: Diagnostic contains: dereferenced expression 'holder.value()' is @Nullable holder.value().hashCode(); @@ -915,18 +915,18 @@ Nested self() { } Nested testDirect(Nested receiver) { - // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Nested -> upper bound of wildcard: source has @Nullable String where target requires String return receiver.wildcardUpperTypeVariable(); } Nested testWithSelf(Nested receiver) { - // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Nested -> upper bound of wildcard: source has @Nullable String where target requires String return receiver.self().wildcardUpperTypeVariable(); } Nested testWithVar(Nested receiver) { var local = receiver; - // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Nested -> upper bound of wildcard: source has @Nullable String where target requires String return local.wildcardUpperTypeVariable(); } @@ -960,18 +960,18 @@ Nested self() { } Nested testDirect(Nested receiver) { - // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Nested -> upper bound of wildcard: source has @Nullable Object where target requires Object return receiver.wildcardUpperTypeVariable(); } Nested testWithSelf(Nested receiver) { - // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Nested -> upper bound of wildcard: source has @Nullable Object where target requires Object return receiver.self().wildcardUpperTypeVariable(); } Nested testWithVar(Nested receiver) { var local = receiver; - // BUG: Diagnostic contains: incompatible nullability in Nested type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Nested -> upper bound of wildcard: source has @Nullable Object where target requires Object return local.wildcardUpperTypeVariable(); } @@ -1038,7 +1038,7 @@ interface NullableI2< } NullableI1 incompatible(NullableI2 i2) { var i2var = i2; - // BUG: Diagnostic contains: incompatible nullability in NullableI1 type argument X: source has @Nullable Object where target requires Object + // BUG: Diagnostic contains: incompatible nullability in type argument for X of NullableI1: source has @Nullable Object where target requires Object return i2var.get(); } } @@ -1479,7 +1479,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 nullability in Foo type argument T: a type argument must match exactly; source has Void where target requires @Nullable Void + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: a non-wildcard type argument must be the same type; source has Void where target requires @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 @@ -1532,7 +1532,7 @@ void test( Box nonNullBoundBox, Box nullableBoundBox) { Box ok = identity(nullableBoundBox); - // BUG: Diagnostic contains: incompatible nullability in Box type argument T -> wildcard lower bound: source has String where target requires a supertype of @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Box -> lower bound of wildcard: source has String where target requires a supertype of @Nullable String Box bad = identity(nonNullBoundBox); } } @@ -1556,7 +1556,7 @@ interface Nested {} return box; } void test(Box> box) { - // BUG: Diagnostic contains: incompatible nullability in Box type argument T -> wildcard lower bound -> Nested type argument T: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Box -> lower bound of wildcard -> type argument for T of Nested: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String Box> bad = identity(box); } } @@ -2079,7 +2079,7 @@ static void nullableSuperBounded(NullableNode node) { } static void superBoundedNullableElements(ListNode> node) { - // BUG: Diagnostic contains: incompatible nullability in List type argument E: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: source has @Nullable String where target requires String takesList(node.get()); } } 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 index cd1ed2acea..073daff9fe 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java @@ -13,7 +13,7 @@ public class CaretTests extends MismatchMessageTestBase { public void onlyTheInnermostDifferingNodeIsMarkedInsideAWildcardBound() { assertMessage( """ - incompatible nullability in List type argument E -> wildcard upper bound -> List type argument E: source has @Nullable String where target requires String + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String source: List> ^^^^^^^^^^^^^^^^ target: List> @@ -32,7 +32,7 @@ void test(List> l) { public void caretSkipsATypeArgumentTheTargetAccepts() { assertMessage( """ - incompatible nullability in Map type argument V -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for V of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object source: Map ^^^^^^^^^^^^^^^^ target: Map @@ -54,7 +54,7 @@ void test(Map m) { public void caretNamesTheConcreteArgumentWhenEveryWildcardIsAccepted() { assertMessage( """ - incompatible nullability in Map type argument V: source has @Nullable String where target requires String + incompatible nullability in type argument for V of Map: source has @Nullable String where target requires String source: Map ^^^^^^^^^^^^^^^^ target: Map @@ -76,7 +76,7 @@ void test(Map m) { public void caretMarksTheFailingArgumentWhereTheTargetRepeatsAType() { assertMessage( """ - incompatible nullability in Three type argument C: source has @Nullable String where target requires String + incompatible nullability in type argument for C of Three: source has @Nullable String where target requires String source: Three ^^^^^^^^^^^^^^^^ target: Three @@ -96,7 +96,7 @@ void test(Three t) { public void onlyTheFailingArgumentIsNamedBesideAWildcardTheTargetAccepts() { assertMessage( """ - incompatible nullability in Three type argument C: source has @Nullable String where target requires String + incompatible nullability in type argument for C of Three: source has @Nullable String where target requires String source: Three ^^^^^^^^^^^^^^^^ target: Three @@ -116,7 +116,7 @@ void test(Three t) { public void bothPositionsAreMarkedWhereOneInstanceFillsTwoTypeArguments() { assertMessage( """ - incompatible nullability in Map type argument K -> wildcard upper bound and 1 other position: source has @Nullable Object where target requires Object + incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other position: source has @Nullable Object where target requires Object source: Map ^^^^^^^^^^^^ ^^^^^^^^^^^^ 1 2 @@ -124,15 +124,15 @@ public void bothPositionsAreMarkedWhereOneInstanceFillsTwoTypeArguments() { ^^^^^^ ^^^^^^ 1 2 \s - 1. path: Map type argument K -> wildcard upper bound + 1. path: type argument for K of Map -> upper bound of wildcard source: @Nullable Object target: Object - note: the source wildcard is the type argument for type parameter E of List + note: the wildcard in the source is the type argument for E of List \s - 2. path: Map type argument V -> wildcard upper bound + 2. path: type argument for V of Map -> upper bound of wildcard source: @Nullable Object target: Object - note: the source wildcard is the type argument for type parameter E of List + note: the wildcard in the source is the type argument for E of List """, """ static Map duplicate(List x) { @@ -150,7 +150,7 @@ void test(List l) { public void aMismatchInsideAnArrayElementTypeArgumentIsMarked() { assertMessage( """ - incompatible nullability in array element -> List type argument E: source has @Nullable String where target requires String + incompatible nullability in component type -> type argument for E of List: source has @Nullable String where target requires String source: List<@Nullable String> [] ^^^^^^^^^^^^^^^^ target: List [] @@ -169,7 +169,7 @@ void test(List<@Nullable String>[] l) { public void aNullableArrayComponentTypeIsMarkedInsideATypeArgument() { assertMessage( """ - incompatible nullability in List type argument E -> array element: source has @Nullable String where target requires String + incompatible nullability in type argument for E of List -> component type: source has @Nullable String where target requires String source: List<@Nullable String []> ^^^^^^^^^^^^^^^^ target: List @@ -188,7 +188,7 @@ void test(List<@Nullable String[]> l) { public void aNullableArrayTypeIsMarkedInsideATypeArgument() { assertMessage( """ - incompatible nullability in List type argument E: source has String @Nullable [] where target requires String [] + incompatible nullability in type argument for E of List: source has String @Nullable [] where target requires String [] source: List ^^^^^^^^^^^^^^^^^^^ target: List @@ -207,7 +207,7 @@ void test(List l) { public void twoMismatchesUnderOneWildcardShareItsCaret() { assertMessage( """ - incompatible nullability in Foo type argument T -> wildcard upper bound -> Map type argument K and 1 other position: source has @Nullable String where target requires String + incompatible nullability in type argument for T of Foo -> upper bound of wildcard -> type argument for K of Map and 1 other position: source has @Nullable String where target requires String source: Foo ^ 1,2 @@ -215,15 +215,15 @@ public void twoMismatchesUnderOneWildcardShareItsCaret() { ^^^^^^ ^^^^^^ 1 2 \s - 1. path: Foo type argument T -> wildcard upper bound -> Map type argument K + 1. path: type argument for T of Foo -> upper bound of wildcard -> type argument for K of Map source: @Nullable String target: String - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Foo + note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) \s - 2. path: Foo type argument T -> wildcard upper bound -> Map type argument V + 2. path: type argument for T of Foo -> upper bound of wildcard -> type argument for V of Map source: @Nullable String target: String - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Foo + note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) """, """ static class Foo> {} @@ -239,7 +239,7 @@ void test(Foo f) { public void twoMismatchesUnderOneNestedWildcardShareItsCaret() { assertMessage( """ - incompatible nullability in List type argument E -> wildcard upper bound -> Foo type argument T -> wildcard upper bound -> Map type argument K and 1 other position: source has @Nullable String where target requires String + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for T of Foo -> upper bound of wildcard -> type argument for K of Map and 1 other position: source has @Nullable String where target requires String source: List> ^ 1,2 @@ -247,15 +247,15 @@ public void twoMismatchesUnderOneNestedWildcardShareItsCaret() { ^^^^^^ ^^^^^^ 1 2 \s - 1. path: List type argument E -> wildcard upper bound -> Foo type argument T -> wildcard upper bound -> Map type argument K + 1. path: type argument for E of List -> upper bound of wildcard -> type argument for T of Foo -> upper bound of wildcard -> type argument for K of Map source: @Nullable String target: String - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Foo + note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) \s - 2. path: List type argument E -> wildcard upper bound -> Foo type argument T -> wildcard upper bound -> Map type argument V + 2. path: type argument for E of List -> upper bound of wildcard -> type argument for T of Foo -> upper bound of wildcard -> type argument for V of Map source: @Nullable String target: String - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Foo + note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) """, """ static class Foo> {} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java index d9d1e66f44..72ec07c6ce 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java @@ -12,10 +12,10 @@ import org.junit.rules.TemporaryFolder; /** - * A {@code fix:} line comes with an Error Prone fix that rewrites the type the named declaration - * writes, where that declaration is a local variable of the compilation unit being analyzed, other - * than a pattern or resource variable, writes its type out before the name, and declares no other - * variable, and the run does not suggest suppressions. + * A {@code possible fix:} line comes with an Error Prone fix that rewrites the type the named + * declaration writes, where that declaration is a local variable of the compilation unit being + * analyzed, other than a pattern or resource variable, writes its type out before the name, and + * declares no other variable, and the run does not suggest suppressions. */ public class FixTests { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java index 41fe6204e6..c092cba254 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java @@ -13,7 +13,7 @@ public class LowerBoundAndRawSourceTests extends MismatchMessageTestBase { public void aLowerBoundDifferenceIsMarkedInBothTypes() { assertMessage( """ - incompatible nullability in List type argument E -> wildcard lower bound: source has String where target requires a supertype of @Nullable String + incompatible nullability in type argument for E of List -> lower bound of wildcard: source has String where target requires a supertype of @Nullable String source: List ^^^^^^ target: List @@ -36,7 +36,7 @@ void nonNullSourceLowerBound(List l) { public void aLowerBoundDifferenceIsMarkedAcrossASupertypeView() { assertMessage( """ - incompatible nullability in Base type argument T -> wildcard lower bound: source has String where target requires a supertype of @Nullable String + incompatible nullability in type argument for T of Base -> lower bound of wildcard: source has String where target requires a supertype of @Nullable String source: Sub ^^^^^^ target: Base 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 index 5acc13b84c..62472f169a 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/MismatchMessageTestBase.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/MismatchMessageTestBase.java @@ -12,8 +12,8 @@ * 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 fix:} line. A failure prints the expected message beside every - * diagnostic the compilation reported. + * not carry, such as a {@code possible fix:} line. A failure prints the expected message beside + * every diagnostic the compilation reported. */ abstract class MismatchMessageTestBase extends NullAwayTestsBase { 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 6cca9afd20..c3deb80299 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,10 @@ /** * 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. + * upper bound an unbounded or lower-bounded wildcard takes from its type parameter, or the type + * parameter a captured wildcard instantiates. It prints the class the wildcard is a type argument + * of, with the other type arguments that hold a wildcard or a type argument of their own written as + * {@code ...}. A source that prints its own nullness gets no note. */ public class NoteTests extends MismatchMessageTestBase { @@ -15,13 +17,13 @@ public class NoteTests extends MismatchMessageTestBase { public void anUnboundedWildcardNamesTheTypeParameterItsBoundIsInheritedFrom() { assertMessage( """ - incompatible nullability in Collection type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object source: List ^ target: Collection ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List - fix: declare list as List + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + possible fix: declare list as List """, """ Collection copy(List list) { @@ -42,16 +44,38 @@ void nullableTarget(List list) { """); } + @Test + public void theNotePrintsOnlyTheWildcardItMeansAndSimpleTypeArguments() { + assertMessage( + """ + incompatible nullability in type argument for B of Triple -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Triple> + ^ + target: Triple + ^^^^^^ + note: the unbounded wildcard ? in Triple has the upper bound of type parameter B of Triple, which is @Nullable Object (JLS 5.1.10) + possible fix: declare t as Triple> + """, + """ + static class Triple {} + static void take(Triple t) {} + void test(Triple> t) { + // BUG: Diagnostic matches: MESSAGE + take(t); + } + """); + } + @Test public void aSuperBoundedWildcardNamesTheTypeParameterItsUpperBoundIsInheritedFrom() { assertMessage( """ - incompatible nullability in Collection type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object source: List ^^^^^^^^^^^^^^ target: Collection ^^^^^^ - note: the source ? super String has no explicit upper bound, so its upper bound is inherited from type parameter E of List + note: the wildcard ? super String in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) """, """ static void take(Collection c) {} @@ -66,7 +90,7 @@ void test(List list) { public void anExplicitlyWrittenNullableBoundDrawsNoInheritedBoundNote() { assertMessage( """ - incompatible nullability in List type argument E -> wildcard upper bound: source has @Nullable String where target requires String + incompatible nullability in type argument for E of List -> upper bound of wildcard: source has @Nullable String where target requires String source: List ^^^^^^^^^^^^^^^^ target: List @@ -85,7 +109,7 @@ void test(List l) { public void noInheritedBoundNoteWhereTheUseStatesItsOwnNullness() { assertMessage( """ - incompatible nullability in Box type argument T -> wildcard upper bound: source has @Nullable T where target requires Object + incompatible nullability in type argument for T of Box -> upper bound of wildcard: source has @Nullable T where target requires Object source: Box<@Nullable T> ^^^^^^^^^^^ target: Box @@ -108,12 +132,12 @@ static void test(Box<@Nullable T> b) { public void aWildcardWhoseImplicitBoundHoldsTheMismatchNamesItsTypeParameter() { assertMessage( """ - incompatible nullability in Foo type argument T -> wildcard upper bound -> List type argument E: source has @Nullable String where target requires String + incompatible nullability in type argument for T of Foo -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String source: Foo ^ target: Foo> ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Foo + note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is List<@Nullable String> (JLS 5.1.10) """, """ static class Foo> {} @@ -129,12 +153,12 @@ void test(Foo f) { public void aNestedWildcardWhoseImplicitBoundHoldsTheMismatchNamesItsTypeParameter() { assertMessage( """ - incompatible nullability in List type argument E -> wildcard upper bound -> Foo type argument T -> wildcard upper bound -> List type argument E: source has @Nullable String where target requires String + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for T of Foo -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String source: List> ^ target: List>> ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Foo + note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is List<@Nullable String> (JLS 5.1.10) """, """ static class Foo> {} @@ -150,13 +174,13 @@ void test(List> f) { public void aWildcardInsideAWildcardBoundNamesItsTypeParameter() { assertMessage( """ - incompatible nullability in List type argument E -> wildcard upper bound -> List type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object source: List> ^ target: List> ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List - fix: declare l as List> + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + possible fix: declare l as List> """, """ static void take(List> l) {} @@ -171,13 +195,13 @@ void test(List> l) { public void aWildcardInsideAnArrayInsideAWildcardBoundNamesItsTypeParameter() { assertMessage( """ - incompatible nullability in List type argument E -> wildcard upper bound -> array element -> List type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for E of List -> upper bound of wildcard -> component type -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object source: List []> ^ target: List []> ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List - fix: declare l as List []> + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + possible fix: declare l as List []> """, """ static void take(List[]> l) {} 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 index 356af5cc49..f18650d650 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java @@ -3,11 +3,11 @@ import org.junit.Test; /** - * A {@code path:} line, and the first line of the message, name 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. The position is the one the check - * rejects, so a nullable root or array is compared below its own nullness, and a captured source - * through its upper bound. + * A {@code path:} line, and the first line of the message, name the position of a difference in the + * terms of the JLS: one step per type argument, wildcard bound, component type, or enclosing type, + * each type argument named by the type parameter it is for and the class that declares it. The + * position is the one the check rejects, so a nullable root or array is compared below its own + * nullness, and a captured source through its upper bound. */ public class PathTests extends MismatchMessageTestBase { @@ -15,7 +15,7 @@ public class PathTests extends MismatchMessageTestBase { public void pathNamesTheTypeParameterTheDeclarationDeclared() { assertMessage( """ - incompatible nullability in Result type argument Failure: source has @Nullable String where target requires String + incompatible nullability in type argument for Failure of Result: source has @Nullable String where target requires String source: Result ^^^^^^^^^^^^^^^^ target: Result @@ -35,7 +35,7 @@ void test(Result r) { public void pathRepeatsTheTypeParameterNameAtEveryLevelThatSharesIt() { assertMessage( """ - incompatible nullability in List type argument E -> Collection type argument E -> List type argument E: source has @Nullable String where target requires String + incompatible nullability in type argument for E of List -> type argument for E of Collection -> type argument for E of List: source has @Nullable String where target requires String source: List>> ^^^^^^^^^^^^^^^^ target: List>> @@ -54,7 +54,7 @@ void test(List>> l) { public void pathKeepsTheEnclosingTypeApartFromTheInnerType() { assertMessage( """ - incompatible nullability in Inner type argument U: source has @Nullable Integer where target requires Integer + incompatible nullability in type argument for U of Inner: source has @Nullable Integer where target requires Integer source: Outer.Inner<@Nullable Integer> ^^^^^^^^^^^^^^^^^ target: Outer.Inner @@ -76,7 +76,7 @@ void test(Outer.Inner<@Nullable Integer> i) { public void twoMismatchesInsideOneTypeArgumentSharePathPrefix() { assertMessage( """ - incompatible nullability in Map type argument V -> Map type argument K and 1 other position: source has @Nullable String where target requires String + incompatible nullability in type argument for V of Map -> type argument for K of Map and 1 other position: source has @Nullable String where target requires String source: Map> ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^ 1 2 @@ -84,11 +84,11 @@ public void twoMismatchesInsideOneTypeArgumentSharePathPrefix() { ^^^^^^ ^^^^^^^ 1 2 \s - 1. path: Map type argument V -> Map type argument K + 1. path: type argument for V of Map -> type argument for K of Map source: @Nullable String target: String \s - 2. path: Map type argument V -> Map type argument V + 2. path: type argument for V of Map -> type argument for V of Map source: @Nullable Integer target: Integer """, @@ -105,7 +105,7 @@ void test(Map> m) { public void mismatchesAtDifferentDepthsEachGetTheirOwnPath() { assertMessage( """ - incompatible nullability in Map type argument K and 1 other position: source has @Nullable String where target requires String + incompatible nullability in type argument for K of Map and 1 other position: source has @Nullable String where target requires String source: Map<@Nullable String, List>> ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^ 1 2 @@ -113,11 +113,11 @@ public void mismatchesAtDifferentDepthsEachGetTheirOwnPath() { ^^^^^^ ^^^^^^^ 1 2 \s - 1. path: Map type argument K + 1. path: type argument for K of Map source: @Nullable String target: String \s - 2. path: Map type argument V -> List type argument E -> wildcard upper bound -> Collection type argument E + 2. path: type argument for V of Map -> type argument for E of List -> upper bound of wildcard -> type argument for E of Collection source: @Nullable Integer target: Integer """, @@ -135,7 +135,7 @@ void test( public void pathReachesATypeArgumentOfAnArrayElement() { assertMessage( """ - incompatible nullability in array element -> List type argument E: a type argument must match exactly; source has String where target requires @Nullable String + incompatible nullability in component type -> type argument for E of List: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String source: List [] ^^^^^^ target: @Nullable List<@Nullable String> [] @@ -153,7 +153,7 @@ void test(List[] arr) { public void pathDescendsIntoEveryDimensionOfANestedArray() { assertMessage( """ - incompatible nullability in array element -> array element: source has @Nullable Integer where target requires Integer + incompatible nullability in component type -> component type: source has @Nullable Integer where target requires Integer source: @Nullable Integer [] [] ^^^^^^^^^^^^^^^^^ target: Integer @Nullable [] [] @@ -171,7 +171,7 @@ void test(@Nullable Integer[][] src) { public void pathDescendsIntoEveryDimensionOfAThreeDimensionalArray() { assertMessage( """ - incompatible nullability in array element -> array element -> array element: source has @Nullable Integer where target requires Integer + incompatible nullability in component type -> component type -> component type: source has @Nullable Integer where target requires Integer source: @Nullable Integer [] [] [] ^^^^^^^^^^^^^^^^^ target: Integer @Nullable [] [] [] @@ -189,13 +189,13 @@ void test(@Nullable Integer[][][] src3) { public void aNullableSourceIsComparedBelowItsOwnNullness() { assertMessage( """ - incompatible nullability in Collection type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object source: @Nullable List ^ target: Collection ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List - fix: declare l as @Nullable List + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + possible fix: declare l as @Nullable List """, """ static void take(Collection c) {} @@ -212,7 +212,7 @@ void test(@Nullable List l) { public void aNullableTargetIsComparedBelowItsOwnNullness() { assertMessage( """ - incompatible nullability in List type argument E: source has @Nullable String where target requires String + incompatible nullability in type argument for E of List: source has @Nullable String where target requires String source: List<@Nullable String> ^^^^^^^^^^^^^^^^ target: @Nullable List @@ -231,7 +231,7 @@ void test(List<@Nullable String> x) { public void pathNamesOnlyTheTypeArgumentTheCheckRejects() { assertMessage( """ - incompatible nullability in Pair type argument A: source has @Nullable String where target requires String + incompatible nullability in type argument for A of Pair: source has @Nullable String where target requires String source: Pair<@Nullable String, Integer []> ^^^^^^^^^^^^^^^^ target: Pair @@ -251,12 +251,12 @@ void test(Pair<@Nullable String, Integer[]> p) { public void aCapturedSourceIsComparedThroughItsUpperBound() { assertMessage( """ - incompatible nullability in List type argument E: source has @Nullable String where target requires String + incompatible nullability in type argument for E of List: source has @Nullable String where target requires String source: capture of ? extends List<@Nullable String> ^^^^^^^^^^^^^^^^ target: List ^^^^^^ - fix: declare l as List<@Nullable String> + possible fix: declare l as List<@Nullable String> Did you mean 'List<@Nullable String> l = wl.get(0);'? """, """ @@ -271,7 +271,7 @@ void test(List> wl) { public void aCapturedArgumentIsComparedThroughItsUpperBound() { assertMessage( """ - incompatible nullability in List type argument E: source has @Nullable String where target requires String + incompatible nullability in type argument for E of List: source has @Nullable String where target requires String source: List<@Nullable String> ^^^^^^^^^^^^^^^^ target: List @@ -290,7 +290,7 @@ void test(List> wl) { public void pathCrossesAWildcardLowerBound() { assertMessage( """ - incompatible nullability in List type argument E -> wildcard lower bound -> List type argument E -> wildcard upper bound: source has Object where target requires a supertype of @Nullable Object + incompatible nullability in type argument for E of List -> lower bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has Object where target requires a supertype of @Nullable Object source: List> ^^^^^^ target: List> diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java index dddc35dffd..e42b0a2a46 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java @@ -4,10 +4,10 @@ import org.junit.Test; /** - * A {@code fix:} line that names the variable the source reads offers the source type rewritten - * with explicit wildcard upper bounds. It appears only where the rewritten type removes every - * difference and prints without losing a type-use annotation. {@link FixTests} checks the edit the - * fix makes. + * A {@code possible fix:} line that names the variable the source reads offers the source type + * rewritten with explicit wildcard upper bounds. It appears only where the rewritten type removes + * every difference and prints without losing a type-use annotation. {@link FixTests} checks the + * edit the fix makes. */ public class SourceFixTests extends MismatchMessageTestBase { @@ -15,7 +15,7 @@ public class SourceFixTests extends MismatchMessageTestBase { public void theFixRewritesEveryMismatchingWildcard() { assertMessage( """ - incompatible nullability in Map type argument K -> wildcard upper bound and 1 other position: source has @Nullable Object where target requires Object + incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other position: source has @Nullable Object where target requires Object source: Map ^ ^ 1 2 @@ -23,17 +23,17 @@ public void theFixRewritesEveryMismatchingWildcard() { ^^^^^^ ^^^^^^ 1 2 \s - 1. path: Map type argument K -> wildcard upper bound + 1. path: type argument for K of Map -> upper bound of wildcard source: @Nullable Object target: Object - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter K of Map + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) \s - 2. path: Map type argument V -> wildcard upper bound + 2. path: type argument for V of Map -> upper bound of wildcard source: @Nullable Object target: Object - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter V of Map + note: the unbounded wildcard ? in Map<..., ?> has the upper bound of type parameter V of Map, which is @Nullable Object (JLS 5.1.10) \s - fix: declare m as Map + possible fix: declare m as Map """, """ static void take(Map m) {} @@ -51,13 +51,13 @@ void test(Map m) { public void theFixLeavesAWildcardTheTargetAllowsToBeNullable() { assertMessage( """ - incompatible nullability in Map type argument K -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object source: Map ^ target: Map ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter K of Map - fix: declare m as Map + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + possible fix: declare m as Map """, """ static void take(Map m) {} @@ -75,13 +75,13 @@ void test(Map m) { public void theFixSurvivesAMismatchInTheHarmlessDirection() { assertMessage( """ - incompatible nullability in Box type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for T of Box -> upper bound of wildcard: source has @Nullable Object where target requires Object source: Box ^ target: Box ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Box - fix: declare b as Box + note: the unbounded wildcard ? in Box has the upper bound of type parameter T of Box, which is @Nullable Object (JLS 5.1.10) + possible fix: declare b as Box """, """ static class Box {} @@ -100,13 +100,13 @@ void fixedFormIsAccepted(Box b) { public void theFixSurvivesASuperBoundedArgumentTheTargetAlsoDeclaresSuper() { assertMessage( """ - incompatible nullability in Map type argument K -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object source: Map ^ target: Map ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter K of Map - fix: declare m as Map + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + possible fix: declare m as Map """, """ static void take(Map m) {} @@ -124,13 +124,13 @@ void test(Map m) { public void theFixRewritesAWildcardInsideAnArrayElement() { assertMessage( """ - incompatible nullability in array element -> Collection type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in component type -> type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object source: List [] ^ target: Collection [] ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List - fix: declare lists as List [] + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + possible fix: declare lists as List [] """, """ static void takeArray(Collection[] c) {} @@ -148,13 +148,13 @@ void test(List[] lists) { public void theFixRewritesAWildcardInsideANestedTypeArgument() { assertMessage( """ - incompatible nullability in Collection type argument E -> wildcard upper bound -> List type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for E of Collection -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object source: List> ^ target: Collection> ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List - fix: declare lists as List> + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + possible fix: declare lists as List> """, """ static void takeNested(Collection> c) {} @@ -172,13 +172,13 @@ void test(List> lists) { public void theFixRewritesAWildcardInAnEnclosingTypeArgument() { assertMessage( """ - incompatible nullability in enclosing type -> Outer type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in enclosing type -> type argument for T of Outer -> upper bound of wildcard: source has @Nullable Object where target requires Object source: Outer.Inner ^ target: Outer.Inner ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter T of Outer - fix: declare inner as Outer.Inner + note: the unbounded wildcard ? in Outer has the upper bound of type parameter T of Outer, which is @Nullable Object (JLS 5.1.10) + possible fix: declare inner as Outer.Inner """, """ static class Outer { @@ -199,13 +199,13 @@ void test(Outer.Inner inner) { public void theSourceFixIsStillOfferedWhereTheTargetTypeIsNotEditable() { assertMessage( """ - incompatible nullability in Collection type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object source: List ^ target: Collection ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List - fix: declare l as List + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + possible fix: declare l as List """, """ static void take(Collection c) {} @@ -220,7 +220,7 @@ void test(List l) { public void noFixWhenAnExplicitBoundMismatchRemains() { assertMessage( """ - incompatible nullability in Map type argument K -> wildcard upper bound and 1 other position: source has @Nullable Object where target requires Object + incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other position: source has @Nullable Object where target requires Object source: Map ^ ^^^^^^^^^^^^^^^^ 1 2 @@ -228,12 +228,12 @@ public void noFixWhenAnExplicitBoundMismatchRemains() { ^^^^^^ ^^^^^^ 1 2 \s - 1. path: Map type argument K -> wildcard upper bound + 1. path: type argument for K of Map -> upper bound of wildcard source: @Nullable Object target: Object - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter K of Map + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) \s - 2. path: Map type argument V -> wildcard upper bound + 2. path: type argument for V of Map -> upper bound of wildcard source: @Nullable Object target: Object """, @@ -250,7 +250,7 @@ void test(Map m) { public void noFixWhenAConcreteTypeArgumentAlsoMismatches() { assertMessage( """ - incompatible nullability in Map type argument K -> wildcard upper bound and 1 other position: source has @Nullable Object where target requires Object + incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other position: source has @Nullable Object where target requires Object source: Map ^ ^^^^^^^^^^^^^^^^ 1 2 @@ -258,12 +258,12 @@ public void noFixWhenAConcreteTypeArgumentAlsoMismatches() { ^^^^^^ ^^^^^^ 1 2 \s - 1. path: Map type argument K -> wildcard upper bound + 1. path: type argument for K of Map -> upper bound of wildcard source: @Nullable Object target: Object - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter K of Map + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) \s - 2. path: Map type argument V + 2. path: type argument for V of Map source: @Nullable String target: String """, @@ -280,7 +280,7 @@ void test(Map m) { public void noFixWhenOneMismatchCannotBeRewritten() { assertMessage( """ - incompatible nullability in Map type argument K -> wildcard upper bound and 1 other position: source has @Nullable Object where target requires Object + incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other position: source has @Nullable Object where target requires Object source: Map ^ ^^^^^^^^^^^^^^ 1 2 @@ -288,15 +288,15 @@ public void noFixWhenOneMismatchCannotBeRewritten() { ^^^^^^ ^^^^^^ 1 2 \s - 1. path: Map type argument K -> wildcard upper bound + 1. path: type argument for K of Map -> upper bound of wildcard source: @Nullable Object target: Object - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter K of Map + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) \s - 2. path: Map type argument V -> wildcard upper bound + 2. path: type argument for V of Map -> upper bound of wildcard source: @Nullable Object target: Object - note: the source ? super String has no explicit upper bound, so its upper bound is inherited from type parameter V of Map + note: the wildcard ? super String in Map<..., ? super String> has no upper bound of its own; its upper bound is the bound of type parameter V of Map, which is @Nullable Object (JLS 5.1.10) """, """ static void take(Map m) {} @@ -311,12 +311,12 @@ void test(Map m) { public void noFixWhenBoundsDifferBelowTheTopLevel() { assertMessage( """ - incompatible nullability in Holder type argument E -> wildcard upper bound -> List type argument E: source has @Nullable Object where target requires Object + incompatible nullability in type argument for E of Holder -> upper bound of wildcard -> type argument for E of List: source has @Nullable Object where target requires Object source: Holder ^ target: Holder> ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of Holder + note: the unbounded wildcard ? in Holder has the upper bound of type parameter E of Holder, which is List<@Nullable Object> (JLS 5.1.10) """, """ static class Holder> {} @@ -332,12 +332,12 @@ void test(Holder h) { public void noFixWhenTheRewrittenTypeHoldsACapture() { assertMessage( """ - incompatible nullability in Map type argument K -> wildcard upper bound -> List type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for K of Map -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object source: Map, capture of ?> ^ target: Map, ?> ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) """, """ static Map, T> make(List l) { @@ -359,31 +359,31 @@ public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { Map.of( "PLAIN", """ - incompatible nullability in Map type argument K -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object source: Map ^ target: Map ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter K of Map - fix: declare plain as Map + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + possible fix: declare plain as Map """, "TAINTED", """ - incompatible nullability in Map type argument K -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object source: Map ^ target: Map ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter K of Map + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) """, "TAINTED_ARRAY_ELEMENT", """ - incompatible nullability in Map type argument K -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object source: Map ^ target: Map ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter K of Map + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) """), """ @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) @@ -409,13 +409,13 @@ void taintedArrayElement(Map m) { public void theFixNamesTheFieldItRewrites() { assertMessage( """ - incompatible nullability in Collection type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object source: List ^ target: Collection ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List - fix: declare field as List + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + possible fix: declare field as List """, """ List field = new ArrayList<>(); 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 index f799be1b95..d571ac9fd3 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java @@ -16,7 +16,7 @@ public class SummaryAndNumberingTests extends MismatchMessageTestBase { public void listsAtMostFiveMismatchesAndSaysHowManyMoreThereAre() { assertMessage( """ - incompatible nullability in Args type argument A -> wildcard upper bound and 5 other positions: source has @Nullable Object where target requires Object + incompatible nullability in type argument for A of Args -> upper bound of wildcard and 5 other positions: source has @Nullable Object where target requires Object source: Args ^ ^ ^ ^ ^ 1 2 3 4 5 @@ -24,34 +24,34 @@ public void listsAtMostFiveMismatchesAndSaysHowManyMoreThereAre() { ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ 1 2 3 4 5 \s - 1. path: Args type argument A -> wildcard upper bound + 1. path: type argument for A of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter A of Args + note: the unbounded wildcard ? in Args has the upper bound of type parameter A of Args, which is @Nullable Object (JLS 5.1.10) \s - 2. path: Args type argument B -> wildcard upper bound + 2. path: type argument for B of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter B of Args + note: the unbounded wildcard ? in Args<..., ?, ..., ..., ..., ...> has the upper bound of type parameter B of Args, which is @Nullable Object (JLS 5.1.10) \s - 3. path: Args type argument C -> wildcard upper bound + 3. path: type argument for C of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter C of Args + note: the unbounded wildcard ? in Args<..., ..., ?, ..., ..., ...> has the upper bound of type parameter C of Args, which is @Nullable Object (JLS 5.1.10) \s - 4. path: Args type argument D -> wildcard upper bound + 4. path: type argument for D of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter D of Args + note: the unbounded wildcard ? in Args<..., ..., ..., ?, ..., ...> has the upper bound of type parameter D of Args, which is @Nullable Object (JLS 5.1.10) \s - 5. path: Args type argument E -> wildcard upper bound + 5. path: type argument for E of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of Args + note: the unbounded wildcard ? in Args<..., ..., ..., ..., ?, ...> has the upper bound of type parameter E of Args, which is @Nullable Object (JLS 5.1.10) \s and 1 more, not listed \s - fix: declare args as Args + possible fix: declare args as Args """, """ static class Args {} @@ -67,7 +67,7 @@ void test(Args args) { public void listsFiveMismatchesWithoutSayingThereAreMore() { assertMessage( """ - incompatible nullability in Args type argument A -> wildcard upper bound and 4 other positions: source has @Nullable Object where target requires Object + incompatible nullability in type argument for A of Args -> upper bound of wildcard and 4 other positions: source has @Nullable Object where target requires Object source: Args ^ ^ ^ ^ ^ 1 2 3 4 5 @@ -75,32 +75,32 @@ public void listsFiveMismatchesWithoutSayingThereAreMore() { ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ 1 2 3 4 5 \s - 1. path: Args type argument A -> wildcard upper bound + 1. path: type argument for A of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter A of Args + note: the unbounded wildcard ? in Args has the upper bound of type parameter A of Args, which is @Nullable Object (JLS 5.1.10) \s - 2. path: Args type argument B -> wildcard upper bound + 2. path: type argument for B of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter B of Args + note: the unbounded wildcard ? in Args<..., ?, ..., ..., ...> has the upper bound of type parameter B of Args, which is @Nullable Object (JLS 5.1.10) \s - 3. path: Args type argument C -> wildcard upper bound + 3. path: type argument for C of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter C of Args + note: the unbounded wildcard ? in Args<..., ..., ?, ..., ...> has the upper bound of type parameter C of Args, which is @Nullable Object (JLS 5.1.10) \s - 4. path: Args type argument D -> wildcard upper bound + 4. path: type argument for D of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter D of Args + note: the unbounded wildcard ? in Args<..., ..., ..., ?, ...> has the upper bound of type parameter D of Args, which is @Nullable Object (JLS 5.1.10) \s - 5. path: Args type argument E -> wildcard upper bound + 5. path: type argument for E of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of Args + note: the unbounded wildcard ? in Args<..., ..., ..., ..., ?> has the upper bound of type parameter E of Args, which is @Nullable Object (JLS 5.1.10) \s - fix: declare args as Args + possible fix: declare args as Args """, """ static class Args {} @@ -116,7 +116,7 @@ void test(Args args) { public void adjacentTypeArgumentsThatBothMismatchAreNumberedSideBySide() { assertMessage( """ - incompatible nullability in Map type argument K and 1 other position: source has @Nullable String where target requires String + incompatible nullability in type argument for K of Map and 1 other position: source has @Nullable String where target requires String source: Map<@Nullable String, @Nullable String> ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ 1 2 @@ -124,11 +124,11 @@ public void adjacentTypeArgumentsThatBothMismatchAreNumberedSideBySide() { ^^^^^^ ^^^^^^ 1 2 \s - 1. path: Map type argument K + 1. path: type argument for K of Map source: @Nullable String target: String \s - 2. path: Map type argument V + 2. path: type argument for V of Map source: @Nullable String target: String """, @@ -147,7 +147,7 @@ public void everyPositionWhereTheSourceIsLessNullableSaysTheTypeArgumentMustMatc Map.of( "ONLY", """ - incompatible nullability in List type argument E: a type argument must match exactly; source has String where target requires @Nullable String + incompatible nullability in type argument for E of List: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String source: List ^^^^^^ target: List<@Nullable String> @@ -155,7 +155,7 @@ public void everyPositionWhereTheSourceIsLessNullableSaysTheTypeArgumentMustMatc """, "SECOND", """ - incompatible nullability in Map type argument K and 1 other position: source has @Nullable String where target requires String + incompatible nullability in type argument for K of Map and 1 other position: source has @Nullable String where target requires String source: Map<@Nullable String, String> ^^^^^^^^^^^^^^^^ ^^^^^^ 1 2 @@ -163,13 +163,13 @@ public void everyPositionWhereTheSourceIsLessNullableSaysTheTypeArgumentMustMatc ^^^^^^ ^^^^^^^^^^^^^^^^ 1 2 \s - 1. path: Map type argument K + 1. path: type argument for K of Map source: @Nullable String target: String \s - 2. path: Map type argument V + 2. path: type argument for V of Map source: String - target: @Nullable String (a type argument must match exactly) + target: @Nullable String (a non-wildcard type argument must be the same type) """), """ static void takeMap(Map m) {} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java index 7f5889df35..abc2ca8914 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java @@ -4,17 +4,17 @@ import org.junit.Test; /** - * A {@code fix:} line that names the variable a declaration declares offers the target type with - * the nullness of the source. It appears where the diagnostic points at the declaration that writes - * the target type, a local variable declaration, and not at a call, an assignment, or a return, - * whose target type is written somewhere else. It is also withheld where printing it would drop a - * type-use annotation. {@link FixTests} checks the edit the fix makes. + * A {@code possible fix:} line that names the variable a declaration declares offers the target + * type with the nullness of the source. It appears where the diagnostic points at the declaration + * that writes the target type, a local variable declaration, and not at a call, an assignment, or a + * return, whose target type is written somewhere else. It is also withheld where printing it would + * drop a type-use annotation. {@link FixTests} checks the edit the fix makes. */ public class TargetTypeFixTests extends MismatchMessageTestBase { private static final String MAP_VALUES_MESSAGE = """ - incompatible nullability in Map type argument V: source has @Nullable String where target requires String + incompatible nullability in type argument for V of Map: source has @Nullable String where target requires String source: Map ^^^^^^^^^^^^^^^^ target: Map @@ -27,7 +27,7 @@ public void theFixIsOfferedOnlyWhereTheDiagnosticPointsAtTheTargetTypeDeclaratio Map.of( "DECLARATION", MAP_VALUES_MESSAGE - + " fix: declare declared as Map\n" + + " possible fix: declare declared as Map\n" + " Did you mean 'Map declared = m;'?\n", "CALL", MAP_VALUES_MESSAGE, @@ -65,12 +65,12 @@ Map returned(Map m public void theFixIsTheDeclaredTypeNotAnInstantiatedSupertype() { assertMessage( """ - incompatible nullability in List type argument E: source has @Nullable String where target requires String + incompatible nullability in type argument for E of List: source has @Nullable String where target requires String source: Sub<@Nullable String> ^^^^^^^^^^^^^^^^ target: List ^^^^^^ - fix: declare l as List<@Nullable String> + possible fix: declare l as List<@Nullable String> Did you mean 'List<@Nullable String> l = s;'? """, """ @@ -89,44 +89,44 @@ public void theFixReplacesTheNodeAtEveryKindOfStep() { Map.of( "WILDCARD_BOUND", """ - incompatible nullability in Collection type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object source: List ^ target: Collection ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List - fix: declare list as List - fix: declare c as Collection + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + possible fix: declare list as List + possible fix: declare c as Collection Did you mean 'Collection c = list;'? """, "ARRAY_ELEMENT", """ - incompatible nullability in array element -> List type argument E: source has @Nullable String where target requires String + incompatible nullability in component type -> type argument for E of List: source has @Nullable String where target requires String source: List<@Nullable String> [] ^^^^^^^^^^^^^^^^ target: List [] ^^^^^^ - fix: declare d as List<@Nullable String> [] + possible fix: declare d as List<@Nullable String> [] Did you mean 'List<@Nullable String> [] d = src;'? """, "ENCLOSING_TYPE", """ - incompatible nullability in enclosing type -> Outer type argument T: source has @Nullable String where target requires String + incompatible nullability in enclosing type -> type argument for T of Outer: source has @Nullable String where target requires String source: Outer<@Nullable String>.Inner ^^^^^^^^^^^^^^^^ target: Outer.Inner ^^^^^^ - fix: declare d as Outer<@Nullable String>.Inner + possible fix: declare d as Outer<@Nullable String>.Inner Did you mean 'Outer<@Nullable String>.Inner d = src;'? """, "WILDCARD_LOWER_BOUND", """ - incompatible nullability in List type argument E -> wildcard lower bound -> List type argument E: source has @Nullable String where target requires String + incompatible nullability in type argument for E of List -> lower bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String source: List> ^^^^^^^^^^^^^^^^ target: List> ^^^^^^ - fix: declare l as List> + possible fix: declare l as List> Did you mean 'List> l = lower();'? """), """ @@ -167,17 +167,17 @@ public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { Map.of( "PLAIN", """ - incompatible nullability in Map type argument V: source has @Nullable String where target requires String + incompatible nullability in type argument for V of Map: source has @Nullable String where target requires String source: Map ^^^^^^^^^^^^^^^^ target: Map ^^^^^^ - fix: declare plain as Map + possible fix: declare plain as Map Did you mean 'Map plain = m;'? """, "TAINTED", """ - incompatible nullability in Map type argument V: source has @Nullable String where target requires String + incompatible nullability in type argument for V of Map: source has @Nullable String where target requires String source: Map ^^^^^^^^^^^^^^^^ target: Map @@ -185,7 +185,7 @@ public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { """, "TAINTED_BOUND", """ - incompatible nullability in Map type argument V: source has @Nullable String where target requires String + incompatible nullability in type argument for V of Map: source has @Nullable String where target requires String source: Map ^^^^^^^^^^^^^^^^ target: Map @@ -193,12 +193,12 @@ public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { """, "TYPE_VARIABLE", """ - incompatible nullability in Map type argument V: source has @Nullable String where target requires String + incompatible nullability in type argument for V of Map: source has @Nullable String where target requires String source: Map ^^^^^^^^^^^^^^^^ target: Map ^^^^^^ - fix: declare d as Map + possible fix: declare d as Map Did you mean 'Map d = m;'? """), """ diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java index ff7d079e97..4d0af86ba4 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java @@ -14,12 +14,12 @@ public class TraversalCostTests extends MismatchMessageTestBase { public void aSharedBoundBesideTheMismatchIsWalkedOnce() { assertMessage( """ - incompatible nullability in P type argument A: source has @Nullable String where target requires String + incompatible nullability in type argument for A of P: source has @Nullable String where target requires String source: P<@Nullable String, L24> ^^^^^^^^^^^^^^^^ target: P> ^^^^^^ - fix: declare x as P<@Nullable String, L24> + possible fix: declare x as P<@Nullable String, L24> Did you mean 'P<@Nullable String, L24> x = get();'? """, """ @@ -63,12 +63,12 @@ void test() { public void aSharedBoundBesideANestedMismatchIsWalkedOnce() { assertMessage( """ - incompatible nullability in List type argument E -> Box type argument B: source has @Nullable String where target requires String + incompatible nullability in type argument for E of List -> type argument for B of Box: source has @Nullable String where target requires String source: List, @Nullable String>> ^^^^^^^^^^^^^^^^ target: List, String>> ^^^^^^ - fix: declare x as List, @Nullable String>> + possible fix: declare x as List, @Nullable String>> Did you mean 'List, @Nullable String>> x = l;'? """, """ 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 ae275c6def..b6e1fa5ba1 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 @@ -8,7 +8,7 @@ * {@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 source itself * is viewed as a supertype and the node at fault is not in the written type, the message prints the - * view on a {@code source viewed as:} line and draws the source carets under it. + * view on a {@code source supertype:} line and draws the source carets under it. */ public class ViewedSourceTests extends MismatchMessageTestBase { @@ -16,7 +16,7 @@ public class ViewedSourceTests extends MismatchMessageTestBase { public void aCarriedOverNodeInsideAWildcardBoundIsMarkedOnTheWrittenSource() { assertMessage( """ - incompatible nullability in Base type argument T -> wildcard upper bound -> List type argument E: source has @Nullable String where target requires String + incompatible nullability in type argument for T of Base -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String source: Sub> ^^^^^^^^^^^^^^^^ target: Base> @@ -37,7 +37,7 @@ void test(Sub> s) { public void aCarriedOverNodeInsideAnArrayElementIsMarkedOnTheWrittenSource() { assertMessage( """ - incompatible nullability in Base type argument T -> array element: source has @Nullable String where target requires String + incompatible nullability in type argument for T of Base -> component type: source has @Nullable String where target requires String source: Sub<@Nullable String []> ^^^^^^^^^^^^^^^^ target: Base @@ -58,12 +58,12 @@ void test(Sub<@Nullable String[]> s) { public void aCarriedOverCaptureIsMarkedOnTheWrittenSourceAndKeepsItsProvenance() { assertMessage( """ - incompatible nullability in Base type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for T of Base -> upper bound of wildcard: source has @Nullable Object where target requires Object source: Sub ^^^^^^^^^^^^ target: Base ^^^^^^ - note: the source wildcard is the type argument for type parameter T of Sub + note: the wildcard in the source is the type argument for T of Sub """, """ static class Base {} @@ -83,9 +83,9 @@ void test() { public void aNodeFromTheSubclassDeclarationIsMarkedOnTheViewedSource() { assertMessage( """ - incompatible nullability in Base type argument T -> List type argument E: source has @Nullable String where target requires String + incompatible nullability in type argument for T of Base -> type argument for E of List: source has @Nullable String where target requires String source: Sub - source viewed as: Base> + source supertype: Base> ^^^^^^^^^^^^^^^^ target: Base> ^^^^^^ @@ -108,18 +108,18 @@ void test(Sub s) { Map.of( "SELF", """ - incompatible nullability in Base type argument T: a type argument must match exactly; source has Sub where target requires @Nullable Sub + incompatible nullability in type argument for T of Base: a non-wildcard type argument must be the same type; source has Sub where target requires @Nullable Sub source: Sub - source viewed as: Base + source supertype: Base ^^^ target: Base<@Nullable Sub> ^^^^^^^^^^^^^ """, "ARGUMENT", """ - incompatible nullability in Base type argument T: a type argument must match exactly; source has Sub where target requires @Nullable Sub + incompatible nullability in type argument for T of Base: a non-wildcard type argument must be the same type; source has Sub where target requires @Nullable Sub source: Holder - source viewed as: Base + source supertype: Base ^^^ target: Base<@Nullable Sub> ^^^^^^^^^^^^^ @@ -146,16 +146,16 @@ public void anArrayTheSubclassDeclarationWritesIsFollowedIntoItsElement() { Map.of( "WRITTEN_ELEMENT", """ - incompatible nullability in Box type argument T -> array element: source has @Nullable String where target requires String + incompatible nullability in type argument for T of Box -> component type: source has @Nullable String where target requires String source: Strings - source viewed as: Box<@Nullable String []> + source supertype: Box<@Nullable String []> ^^^^^^^^^^^^^^^^ target: Box ^^^^^^ """, "PASSED_ELEMENT", """ - incompatible nullability in Box type argument T -> array element: source has @Nullable String where target requires String + incompatible nullability in type argument for T of Box -> component type: source has @Nullable String where target requires String source: Elements<@Nullable String> ^^^^^^^^^^^^^^^^ target: Box @@ -183,7 +183,7 @@ public void aViewNestedInADeclaredSupertypeStillReachesTheWrittenArgument() { Map.of( "PASSED", """ - incompatible nullability in Base type argument B -> wildcard upper bound -> List type argument E: source has @Nullable String where target requires String + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String source: Sub<@Nullable String> ^^^^^^^^^^^^^^^^ target: Base> @@ -191,7 +191,7 @@ public void aViewNestedInADeclaredSupertypeStillReachesTheWrittenArgument() { """, "BELOW_ANNOTATED", """ - incompatible nullability in Base type argument B -> wildcard upper bound -> List type argument E -> List type argument E: source has @Nullable String where target requires String + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for E of List -> type argument for E of List: source has @Nullable String where target requires String source: Annotated> ^^^^^^^^^^^^^^^^ target: Base>> @@ -199,7 +199,7 @@ public void aViewNestedInADeclaredSupertypeStillReachesTheWrittenArgument() { """, "VIEWED_BELOW_ANNOTATED", """ - incompatible nullability in Base type argument B -> wildcard upper bound -> List type argument E -> wildcard upper bound -> List type argument E: source has @Nullable String where target requires String + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String source: Annotated> ^^^^^^^^^^^^^^^^ target: Base>> @@ -207,9 +207,9 @@ public void aViewNestedInADeclaredSupertypeStillReachesTheWrittenArgument() { """, "WRITTEN", """ - incompatible nullability in Base type argument B -> wildcard upper bound -> List type argument E: source has @Nullable String where target requires String + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String source: Strings - source viewed as: Base> + source supertype: Base> ^^^^^^^^^^^^^^^^ target: Base> ^^^^^^ @@ -245,15 +245,15 @@ void written(Strings s) { public void eachComponentOfAnIntersectionTargetIsComparedUnderItsOwnView() { assertMessage( """ - incompatible nullability in A type argument T and 1 other position: source has @Nullable String where target requires String + incompatible nullability in type argument for T of A and 1 other position: source has @Nullable String where target requires String source: B target: A & D \s - 1. path: A type argument T + 1. path: type argument for T of A source: @Nullable String target: String \s - 2. path: D type argument T + 2. path: type argument for T of D source: @Nullable String target: String """, @@ -275,31 +275,31 @@ public void aWildcardFromTheSubclassDeclarationIsNamedOnlyWhereALinePrintsIt() { Map.of( "LIST", """ - incompatible nullability in Base type argument B -> wildcard upper bound -> List type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object source: ListSub - source viewed as: Base> + source supertype: Base> ^ target: Base> ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter E of List + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) """, "MAP", """ - incompatible nullability in Base type argument B -> wildcard upper bound -> Map type argument V -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for V of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object source: MapSub - source viewed as: Base> + source supertype: Base> ^ target: Base> ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter V of Map + note: the unbounded wildcard ? in Map has the upper bound of type parameter V of Map, which is @Nullable Object (JLS 5.1.10) """, "BELOW_ROOT", """ - incompatible nullability in List type argument E -> wildcard upper bound -> Base type argument B -> wildcard upper bound -> List type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for B of Base -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object source: List target: List>> ^^^^^^ - note: the source wildcard has an implicit @Nullable Object upper bound + note: the unbounded wildcard ? in the source has the upper bound @Nullable Object (JLS 5.1.10) """), """ static class Base {} @@ -327,13 +327,13 @@ void belowRoot(List l) { public void aPathAcrossAViewReachesIntoWhateverTheSubclassPassed() { assertMessage( """ - incompatible nullability in Base type argument B -> wildcard upper bound -> List type argument E -> wildcard upper bound: source has @Nullable Object where target requires Object + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object source: Indirect ^ target: Base> ^^^^^^ - note: the source ? has no explicit upper bound, so its upper bound is inherited from type parameter X of Indirect - fix: declare i as Indirect + note: the unbounded wildcard ? in Indirect has the upper bound of type parameter X of Indirect, which is @Nullable Object (JLS 5.1.10) + possible fix: declare i as Indirect """, """ static class Base {} @@ -373,7 +373,7 @@ public class Result extends a.Result {} "MESSAGE", messageIs( """ - incompatible nullability in Result type argument T: source has @Nullable String where target requires String + incompatible nullability in type argument for T of Result: source has @Nullable String where target requires String source: Result<@Nullable String> ^^^^^^^^^^^^^^^^ target: Result @@ -396,7 +396,7 @@ void test(b.Result<@Nullable String> r) { public void aReorderingSubclassIsMarkedAtTheArgumentItPassesOn() { assertMessage( """ - incompatible nullability in List type argument E -> wildcard upper bound -> Pair type argument A: source has @Nullable String where target requires String + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for A of Pair: source has @Nullable String where target requires String source: List> ^^^^^^^^^^^^^^^^ target: List> @@ -417,7 +417,7 @@ void test(List> l) { public void aReorderingSubclassInsideAnArrayIsMarkedAtTheArgumentItPassesOn() { assertMessage( """ - incompatible nullability in array element -> Pair type argument A: source has @Nullable String where target requires String + incompatible nullability in component type -> type argument for A of Pair: source has @Nullable String where target requires String source: Swap [] ^^^^^^^^^^^^^^^^ target: Pair [] @@ -438,7 +438,7 @@ void test(Swap[] a) { public void aReorderingSubclassTwoLevelsDownIsMarkedAtTheArgumentItPassesOn() { assertMessage( """ - incompatible nullability in List type argument E -> wildcard upper bound -> List type argument E -> wildcard upper bound -> Pair type argument A: source has @Nullable String where target requires String + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard -> type argument for A of Pair: source has @Nullable String where target requires String source: List>> ^^^^^^^^^^^^^^^^ target: List>> @@ -459,7 +459,7 @@ void test(List>> l) { public void anEnclosingTypeArgumentOfASubclassIsMarkedOnTheWrittenSource() { assertMessage( """ - incompatible nullability in enclosing type -> Outer type argument T: source has @Nullable String where target requires String + incompatible nullability in enclosing type -> type argument for T of Outer: source has @Nullable String where target requires String source: Outer<@Nullable String>.SubInner ^^^^^^^^^^^^^^^^ target: Outer.Inner From dff79d5da2f0752a1ad0498ca3bc1e4a92a6c3b9 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Sun, 29 Nov 2026 01:32:25 +0300 Subject: [PATCH 22/43] Give the same wording to both wildcard notes and update the other modules The note for an unbounded ? and for a ? super X now share one sentence: it says that the wildcard has no upper bound of its own and that its upper bound is the bound of the named type parameter. The bound is taken from the class the note prints, with the other type arguments substituted. Expectations in jdk-integration-test and test-library-models follow the JLS vocabulary of the previous commit. The test names that still said "inherited" or "must match exactly" are renamed. User-visible: `note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10)` Assisted-by: Claude Code (claude-opus-5-5) --- .../jdkannotations/JDKIntegrationTest.java | 28 ++++++------- .../generics/NullabilityMismatchMessage.java | 38 +++++++++-------- .../jspecify/mismatchmessage/CaretTests.java | 8 ++-- .../jspecify/mismatchmessage/NoteTests.java | 42 ++++++++++++++----- .../jspecify/mismatchmessage/PathTests.java | 2 +- .../mismatchmessage/SourceFixTests.java | 36 ++++++++-------- .../SummaryAndNumberingTests.java | 26 ++++++------ .../mismatchmessage/TargetTypeFixTests.java | 2 +- .../mismatchmessage/ViewedSourceTests.java | 8 ++-- .../nullaway/CustomLibraryModelsTests.java | 24 +++++------ 10 files changed, 120 insertions(+), 94 deletions(-) diff --git a/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java b/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java index a6c700e578..2699def406 100644 --- a/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java +++ b/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java @@ -293,9 +293,9 @@ class Test { void testCall() { ParameterAnnotation.takesNullableArray(nonNullArray); ParameterAnnotation.takesNullableArray(nullableArray); - // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable String where target requires String ParameterAnnotation.takesNullableArray(nullableElements); - // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable String where target requires String ParameterAnnotation.takesNullableArray(nullableArrayAndElements); ParameterAnnotation.takesNullableElements(nonNullArray); ParameterAnnotation.takesNullableElements(nullableElements); @@ -339,12 +339,12 @@ void test() { } int nullableElementsLength = ReturnAnnotation.returnNullableElements().length; - // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable String where target requires String String[] nullableElements = ReturnAnnotation.returnNullableElements(); // BUG: Diagnostic contains: dereferenced expression 'ReturnAnnotation.returnNullableArrayAndElements()' is @Nullable int nullableArrayAndElementsLength = ReturnAnnotation.returnNullableArrayAndElements().length; - // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable String where target requires String String @Nullable [] nullableArrayAndElements = ReturnAnnotation.returnNullableArrayAndElements(); } @@ -381,7 +381,7 @@ void test() { int nullableComponentArraysLength = ReturnAnnotation.returnNullableComponentArrays2D().length; - // BUG: Diagnostic contains: incompatible nullability in array element: source has String @Nullable [] where target requires String [] + // BUG: Diagnostic contains: incompatible nullability in component type: source has String @Nullable [] where target requires String [] String[][] nullableComponentArrays = ReturnAnnotation.returnNullableComponentArrays2D(); // TODO: This should report a nullable dereference. NullAway currently loses the @@ -391,7 +391,7 @@ void test() { // BUG: Diagnostic contains: dereferenced expression 'ReturnAnnotation.returnNullableOuterAndComponentArrays2D()' is @Nullable int nullableOuterAndComponentArraysLength = ReturnAnnotation.returnNullableOuterAndComponentArrays2D().length; - // BUG: Diagnostic contains: incompatible nullability in array element: source has String @Nullable [] where target requires String [] + // BUG: Diagnostic contains: incompatible nullability in component type: source has String @Nullable [] where target requires String [] String @Nullable [][] nullableOuterAndComponentArrays = ReturnAnnotation.returnNullableOuterAndComponentArrays2D(); } @@ -656,21 +656,21 @@ public void loadLibraryModuleMethodReturnTypeNestedAnnotation() { class Test { void testCall() { // -- Type argument nullability - // BUG: Diagnostic contains: incompatible nullability in List type argument E: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: source has @Nullable String where target requires String List typeArg1 = ReturnAnnotation.nestedAnnotTypeArg(); List<@Nullable String> typeArg2 = ReturnAnnotation.nestedAnnotTypeArg(); // -- Array Element nullability - // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable String where target requires String String[] arrayElement1 = ReturnAnnotation.nestedAnnotArrayElement(); - // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable String where target requires String String @Nullable [] arrayElement2 = ReturnAnnotation.nestedAnnotArrayElement(); @Nullable String [] arrayElement3 = ReturnAnnotation.nestedAnnotArrayElement(); // -- mixed type nullability - // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable List<@Nullable Integer> where target requires List + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable List<@Nullable Integer> where target requires List List[] mixed1 = ReturnAnnotation.nestedAnnotMixed(); - // BUG: Diagnostic contains: incompatible nullability in array element -> List type argument E: source has @Nullable Integer where target requires Integer + // BUG: Diagnostic contains: incompatible nullability in component type -> type argument for E of List: source has @Nullable Integer where target requires Integer @Nullable List[] mixed2 = ReturnAnnotation.nestedAnnotMixed(); - // BUG: Diagnostic contains: incompatible nullability in array element: source has @Nullable List<@Nullable Integer> where target requires List<@Nullable Integer> + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable List<@Nullable Integer> where target requires List<@Nullable Integer> List<@Nullable Integer>[] mixed3 = ReturnAnnotation.nestedAnnotMixed(); @Nullable List<@Nullable Integer>[] mixed4 = ReturnAnnotation.nestedAnnotMixed(); } @@ -718,11 +718,11 @@ void testCall() { @Nullable List[] nonNullTypeArgMixed = (@Nullable List[]) new List[3]; // === test calls ParameterAnnotation.nestedAnnotations(nullableTypeArg, nullableArray, nullableMixed); - // BUG: Diagnostic contains: incompatible nullability in List type argument E: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String ParameterAnnotation.nestedAnnotations(nonNullTypeArg, nullableArray, nullableMixed); ParameterAnnotation.nestedAnnotations(nullableTypeArg, nonNullArray, nullableMixed); ParameterAnnotation.nestedAnnotations(nullableTypeArg, nullableArray, nonNullArrayMixed); - // BUG: Diagnostic contains: incompatible nullability in array element -> List type argument E: a type argument must match exactly; source has Integer where target requires @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in component type -> type argument for E of List: a non-wildcard type argument must be the same type; source has Integer where target requires @Nullable Integer ParameterAnnotation.nestedAnnotations(nullableTypeArg, nullableArray, nonNullTypeArgMixed); } } 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 e17ee2187e..3463168642 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -42,7 +42,7 @@ * ^ * target: Map<? extends Object, String> * ^^^^^^ - * note: the unbounded wildcard ? in Map<?, String> has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + * note: the unbounded wildcard ? in Map<?, String> has no upper bound of its own; its upper bound is the bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) * possible fix: declare m as Map<? extends Object, String> * * @@ -621,41 +621,45 @@ private String mismatchDetail( ? reachingStep.formal() : null; Symbol.ClassSymbol owner = typeVariableOwner(formalTypeVariable); - String upperBound = - GenericsChecks.prettyTypeForError( - GenericsUtils.wildcardUpperBound(wildcard, state, config, handler), state); - boolean unbounded = wildcard.kind == BoundKind.UNBOUND; String source = - unbounded + wildcard.kind == BoundKind.UNBOUND ? "the unbounded wildcard ?" : "the wildcard ? super " + GenericsChecks.prettyTypeForError(wildcard.type, state); - String hasBound = - unbounded ? " has the upper bound" : " has no upper bound of its own; its upper bound is"; + String hasBound = " has no upper bound of its own; its upper bound is"; if (formalTypeVariable == null || owner == null || caret == null || reachingStep == null) { // no type parameter this message prints stands behind the bound: the wildcard sits at no // position of a printed type, as below the root of a supertype view (#2197), or the variable // it instantiates has no named owner. The note says what the bound is and leaves where it // came from alone. "in the source" says which ? is meant, since two printed types carry one - return String.format("%s in the source%s %s (JLS 5.1.10)", source, hasBound, upperBound); + return String.format( + "%s in the source%s %s (JLS 5.1.10)", + source, + hasBound, + GenericsChecks.prettyTypeForError( + GenericsUtils.wildcardUpperBound(wildcard, state, config, handler), state)); } // the class the wildcard is a type argument of, printed so the reader can find that ? Type holder = printed == null ? null // diff-coverage: ignore -- a caret is placed only on a printed type : nodeAt(printed, caret.steps().subList(0, caret.steps().size() - 1)); - String in = - holder instanceof Type.ClassType holderClass - ? " in " + withOtherTypeArgumentsElided(holderClass, reachingStep.index()) - : ""; // diff-coverage: ignore -- the caret path reaches the wildcard through its class + if (!(holder instanceof Type.ClassType holderClass)) { + return null; // diff-coverage: ignore -- the caret path reaches the wildcard through its class + } + // the bound of the type parameter with the other type arguments of the holder substituted, as + // capture conversion gives it: for Foo>, the ? of Foo has the + // upper bound List + Type upperBound = + GenericsUtils.effectiveUpperBoundsForTypeArguments(holderClass, state, config, handler) + .get(reachingStep.index()); return String.format( - "%s%s%s %s type parameter %s of %s, which is %s (JLS 5.1.10)", + "%s in %s%s the bound of type parameter %s of %s, which is %s (JLS 5.1.10)", source, - in, + withOtherTypeArgumentsElided(holderClass, reachingStep.index()), hasBound, - unbounded ? "of" : "the bound of", formalTypeVariable.tsym.getSimpleName(), owner.getSimpleName(), - upperBound); + GenericsChecks.prettyTypeForError(upperBound, state)); } /** 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 index 073daff9fe..a1c538447f 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java @@ -218,12 +218,12 @@ public void twoMismatchesUnderOneWildcardShareItsCaret() { 1. path: type argument for T of Foo -> upper bound of wildcard -> type argument for K of Map source: @Nullable String target: String - note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) + note: the unbounded wildcard ? in Foo has no upper bound of its own; its upper bound is the bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) \s 2. path: type argument for T of Foo -> upper bound of wildcard -> type argument for V of Map source: @Nullable String target: String - note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) + note: the unbounded wildcard ? in Foo has no upper bound of its own; its upper bound is the bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) """, """ static class Foo> {} @@ -250,12 +250,12 @@ public void twoMismatchesUnderOneNestedWildcardShareItsCaret() { 1. path: type argument for E of List -> upper bound of wildcard -> type argument for T of Foo -> upper bound of wildcard -> type argument for K of Map source: @Nullable String target: String - note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) + note: the unbounded wildcard ? in Foo has no upper bound of its own; its upper bound is the bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) \s 2. path: type argument for E of List -> upper bound of wildcard -> type argument for T of Foo -> upper bound of wildcard -> type argument for V of Map source: @Nullable String target: String - note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) + note: the unbounded wildcard ? in Foo has no upper bound of its own; its upper bound is the bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) """, """ static class Foo> {} 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 c3deb80299..d1d44171fa 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 @@ -14,7 +14,7 @@ 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() { + public void anUnboundedWildcardNamesTheTypeParameterItsUpperBoundComesFrom() { assertMessage( """ incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object @@ -22,7 +22,7 @@ public void anUnboundedWildcardNamesTheTypeParameterItsBoundIsInheritedFrom() { ^ target: Collection ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) possible fix: declare list as List """, """ @@ -53,7 +53,7 @@ public void theNotePrintsOnlyTheWildcardItMeansAndSimpleTypeArguments() { ^ target: Triple ^^^^^^ - note: the unbounded wildcard ? in Triple has the upper bound of type parameter B of Triple, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Triple has no upper bound of its own; its upper bound is the bound of type parameter B of Triple, which is @Nullable Object (JLS 5.1.10) possible fix: declare t as Triple> """, """ @@ -67,7 +67,29 @@ void test(Triple> t) { } @Test - public void aSuperBoundedWildcardNamesTheTypeParameterItsUpperBoundIsInheritedFrom() { + public void theNoteGivesTheBoundWithTheOtherTypeArgumentsSubstituted() { + assertMessage( + """ + incompatible nullability in type argument for B of Foo -> upper bound of wildcard: source has @Nullable List where target requires List + source: Foo + ^ + target: Foo> + ^^^^^^^^^^^^ + note: the unbounded wildcard ? in Foo has no upper bound of its own; its upper bound is the bound of type parameter B of Foo, which is @Nullable List (JLS 5.1.10) + possible fix: declare f as Foo> + """, + """ + static class Foo> {} + static void take(Foo> f) {} + void test(Foo f) { + // BUG: Diagnostic matches: MESSAGE + take(f); + } + """); + } + + @Test + public void aSuperBoundedWildcardNamesTheTypeParameterItsUpperBoundComesFrom() { assertMessage( """ incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object @@ -87,7 +109,7 @@ void test(List list) { } @Test - public void anExplicitlyWrittenNullableBoundDrawsNoInheritedBoundNote() { + public void anExplicitlyWrittenNullableBoundDrawsNoNote() { assertMessage( """ incompatible nullability in type argument for E of List -> upper bound of wildcard: source has @Nullable String where target requires String @@ -106,7 +128,7 @@ void test(List l) { } @Test - public void noInheritedBoundNoteWhereTheUseStatesItsOwnNullness() { + public void noNoteWhereTheUseStatesItsOwnNullness() { assertMessage( """ incompatible nullability in type argument for T of Box -> upper bound of wildcard: source has @Nullable T where target requires Object @@ -137,7 +159,7 @@ public void aWildcardWhoseImplicitBoundHoldsTheMismatchNamesItsTypeParameter() { ^ target: Foo> ^^^^^^ - note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is List<@Nullable String> (JLS 5.1.10) + note: the unbounded wildcard ? in Foo has no upper bound of its own; its upper bound is the bound of type parameter T of Foo, which is List<@Nullable String> (JLS 5.1.10) """, """ static class Foo> {} @@ -158,7 +180,7 @@ public void aNestedWildcardWhoseImplicitBoundHoldsTheMismatchNamesItsTypeParamet ^ target: List>> ^^^^^^ - note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is List<@Nullable String> (JLS 5.1.10) + note: the unbounded wildcard ? in Foo has no upper bound of its own; its upper bound is the bound of type parameter T of Foo, which is List<@Nullable String> (JLS 5.1.10) """, """ static class Foo> {} @@ -179,7 +201,7 @@ public void aWildcardInsideAWildcardBoundNamesItsTypeParameter() { ^ target: List> ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) possible fix: declare l as List> """, """ @@ -200,7 +222,7 @@ public void aWildcardInsideAnArrayInsideAWildcardBoundNamesItsTypeParameter() { ^ target: List []> ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) possible fix: declare l as List []> """, """ 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 index f18650d650..7efab68db6 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java @@ -194,7 +194,7 @@ public void aNullableSourceIsComparedBelowItsOwnNullness() { ^ target: Collection ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) possible fix: declare l as @Nullable List """, """ diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java index e42b0a2a46..0456c9ca46 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java @@ -26,12 +26,12 @@ public void theFixRewritesEveryMismatchingWildcard() { 1. path: type argument for K of Map -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Map has no upper bound of its own; its upper bound is the bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) \s 2. path: type argument for V of Map -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Map<..., ?> has the upper bound of type parameter V of Map, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Map<..., ?> has no upper bound of its own; its upper bound is the bound of type parameter V of Map, which is @Nullable Object (JLS 5.1.10) \s possible fix: declare m as Map """, @@ -56,7 +56,7 @@ public void theFixLeavesAWildcardTheTargetAllowsToBeNullable() { ^ target: Map ^^^^^^ - note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Map has no upper bound of its own; its upper bound is the bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) possible fix: declare m as Map """, """ @@ -80,7 +80,7 @@ public void theFixSurvivesAMismatchInTheHarmlessDirection() { ^ target: Box ^^^^^^ - note: the unbounded wildcard ? in Box has the upper bound of type parameter T of Box, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Box has no upper bound of its own; its upper bound is the bound of type parameter T of Box, which is @Nullable Object (JLS 5.1.10) possible fix: declare b as Box """, """ @@ -105,7 +105,7 @@ public void theFixSurvivesASuperBoundedArgumentTheTargetAlsoDeclaresSuper() { ^ target: Map ^^^^^^ - note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Map has no upper bound of its own; its upper bound is the bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) possible fix: declare m as Map """, """ @@ -129,7 +129,7 @@ public void theFixRewritesAWildcardInsideAnArrayElement() { ^ target: Collection [] ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) possible fix: declare lists as List [] """, """ @@ -153,7 +153,7 @@ public void theFixRewritesAWildcardInsideANestedTypeArgument() { ^ target: Collection> ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) possible fix: declare lists as List> """, """ @@ -177,7 +177,7 @@ public void theFixRewritesAWildcardInAnEnclosingTypeArgument() { ^ target: Outer.Inner ^^^^^^ - note: the unbounded wildcard ? in Outer has the upper bound of type parameter T of Outer, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Outer has no upper bound of its own; its upper bound is the bound of type parameter T of Outer, which is @Nullable Object (JLS 5.1.10) possible fix: declare inner as Outer.Inner """, """ @@ -204,7 +204,7 @@ public void theSourceFixIsStillOfferedWhereTheTargetTypeIsNotEditable() { ^ target: Collection ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) possible fix: declare l as List """, """ @@ -231,7 +231,7 @@ public void noFixWhenAnExplicitBoundMismatchRemains() { 1. path: type argument for K of Map -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Map has no upper bound of its own; its upper bound is the bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) \s 2. path: type argument for V of Map -> upper bound of wildcard source: @Nullable Object @@ -261,7 +261,7 @@ public void noFixWhenAConcreteTypeArgumentAlsoMismatches() { 1. path: type argument for K of Map -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Map has no upper bound of its own; its upper bound is the bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) \s 2. path: type argument for V of Map source: @Nullable String @@ -291,7 +291,7 @@ public void noFixWhenOneMismatchCannotBeRewritten() { 1. path: type argument for K of Map -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Map has no upper bound of its own; its upper bound is the bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) \s 2. path: type argument for V of Map -> upper bound of wildcard source: @Nullable Object @@ -316,7 +316,7 @@ public void noFixWhenBoundsDifferBelowTheTopLevel() { ^ target: Holder> ^^^^^^ - note: the unbounded wildcard ? in Holder has the upper bound of type parameter E of Holder, which is List<@Nullable Object> (JLS 5.1.10) + note: the unbounded wildcard ? in Holder has no upper bound of its own; its upper bound is the bound of type parameter E of Holder, which is List<@Nullable Object> (JLS 5.1.10) """, """ static class Holder> {} @@ -337,7 +337,7 @@ public void noFixWhenTheRewrittenTypeHoldsACapture() { ^ target: Map, ?> ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) """, """ static Map, T> make(List l) { @@ -364,7 +364,7 @@ public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { ^ target: Map ^^^^^^ - note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Map has no upper bound of its own; its upper bound is the bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) possible fix: declare plain as Map """, "TAINTED", @@ -374,7 +374,7 @@ public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { ^ target: Map ^^^^^^ - note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Map has no upper bound of its own; its upper bound is the bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) """, "TAINTED_ARRAY_ELEMENT", """ @@ -383,7 +383,7 @@ public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { ^ target: Map ^^^^^^ - note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Map has no upper bound of its own; its upper bound is the bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) """), """ @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) @@ -414,7 +414,7 @@ public void theFixNamesTheFieldItRewrites() { ^ target: Collection ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) possible fix: declare field as List """, """ 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 index d571ac9fd3..c1a95ad33a 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java @@ -7,8 +7,8 @@ * The first line of a generic nullability message names the position of the first difference, how * many other positions differ, and the two types at the first one, so that it stands alone where a * tool shows only that line. 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. + * a line after them counts the rest. A non-wildcard type argument must be the same type in the + * source and the target, and the first line says so where the source is the less nullable side. */ public class SummaryAndNumberingTests extends MismatchMessageTestBase { @@ -27,27 +27,27 @@ public void listsAtMostFiveMismatchesAndSaysHowManyMoreThereAre() { 1. path: type argument for A of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Args has the upper bound of type parameter A of Args, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Args has no upper bound of its own; its upper bound is the bound of type parameter A of Args, which is @Nullable Object (JLS 5.1.10) \s 2. path: type argument for B of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Args<..., ?, ..., ..., ..., ...> has the upper bound of type parameter B of Args, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Args<..., ?, ..., ..., ..., ...> has no upper bound of its own; its upper bound is the bound of type parameter B of Args, which is @Nullable Object (JLS 5.1.10) \s 3. path: type argument for C of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Args<..., ..., ?, ..., ..., ...> has the upper bound of type parameter C of Args, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Args<..., ..., ?, ..., ..., ...> has no upper bound of its own; its upper bound is the bound of type parameter C of Args, which is @Nullable Object (JLS 5.1.10) \s 4. path: type argument for D of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Args<..., ..., ..., ?, ..., ...> has the upper bound of type parameter D of Args, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Args<..., ..., ..., ?, ..., ...> has no upper bound of its own; its upper bound is the bound of type parameter D of Args, which is @Nullable Object (JLS 5.1.10) \s 5. path: type argument for E of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Args<..., ..., ..., ..., ?, ...> has the upper bound of type parameter E of Args, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Args<..., ..., ..., ..., ?, ...> has no upper bound of its own; its upper bound is the bound of type parameter E of Args, which is @Nullable Object (JLS 5.1.10) \s and 1 more, not listed \s @@ -78,27 +78,27 @@ public void listsFiveMismatchesWithoutSayingThereAreMore() { 1. path: type argument for A of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Args has the upper bound of type parameter A of Args, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Args has no upper bound of its own; its upper bound is the bound of type parameter A of Args, which is @Nullable Object (JLS 5.1.10) \s 2. path: type argument for B of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Args<..., ?, ..., ..., ...> has the upper bound of type parameter B of Args, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Args<..., ?, ..., ..., ...> has no upper bound of its own; its upper bound is the bound of type parameter B of Args, which is @Nullable Object (JLS 5.1.10) \s 3. path: type argument for C of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Args<..., ..., ?, ..., ...> has the upper bound of type parameter C of Args, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Args<..., ..., ?, ..., ...> has no upper bound of its own; its upper bound is the bound of type parameter C of Args, which is @Nullable Object (JLS 5.1.10) \s 4. path: type argument for D of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Args<..., ..., ..., ?, ...> has the upper bound of type parameter D of Args, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Args<..., ..., ..., ?, ...> has no upper bound of its own; its upper bound is the bound of type parameter D of Args, which is @Nullable Object (JLS 5.1.10) \s 5. path: type argument for E of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Args<..., ..., ..., ..., ?> has the upper bound of type parameter E of Args, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Args<..., ..., ..., ..., ?> has no upper bound of its own; its upper bound is the bound of type parameter E of Args, which is @Nullable Object (JLS 5.1.10) \s possible fix: declare args as Args """, @@ -142,7 +142,7 @@ void test(Map<@Nullable String, @Nullable String> m) { } @Test - public void everyPositionWhereTheSourceIsLessNullableSaysTheTypeArgumentMustMatchExactly() { + public void everyPositionWhereTheSourceIsLessNullableSaysTheTypeArgumentMustBeTheSameType() { assertMessages( Map.of( "ONLY", diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java index abc2ca8914..fe09e787ec 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java @@ -94,7 +94,7 @@ public void theFixReplacesTheNodeAtEveryKindOfStep() { ^ target: Collection ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) possible fix: declare list as List possible fix: declare c as Collection Did you mean 'Collection c = list;'? 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 b6e1fa5ba1..6b9bc6ee19 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 @@ -281,7 +281,7 @@ public void aWildcardFromTheSubclassDeclarationIsNamedOnlyWhereALinePrintsIt() { ^ target: Base> ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) """, "MAP", """ @@ -291,7 +291,7 @@ public void aWildcardFromTheSubclassDeclarationIsNamedOnlyWhereALinePrintsIt() { ^ target: Base> ^^^^^^ - note: the unbounded wildcard ? in Map has the upper bound of type parameter V of Map, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Map has no upper bound of its own; its upper bound is the bound of type parameter V of Map, which is @Nullable Object (JLS 5.1.10) """, "BELOW_ROOT", """ @@ -299,7 +299,7 @@ public void aWildcardFromTheSubclassDeclarationIsNamedOnlyWhereALinePrintsIt() { source: List target: List>> ^^^^^^ - note: the unbounded wildcard ? in the source has the upper bound @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in the source has no upper bound of its own; its upper bound is @Nullable Object (JLS 5.1.10) """), """ static class Base {} @@ -332,7 +332,7 @@ public void aPathAcrossAViewReachesIntoWhateverTheSubclassPassed() { ^ target: Base> ^^^^^^ - note: the unbounded wildcard ? in Indirect has the upper bound of type parameter X of Indirect, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Indirect has no upper bound of its own; its upper bound is the bound of type parameter X of Indirect, which is @Nullable Object (JLS 5.1.10) possible fix: declare i as Indirect """, """ diff --git a/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java b/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java index c36ebd06f8..225921bc5f 100644 --- a/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java +++ b/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java @@ -611,7 +611,7 @@ public void deeplyNestedTypeAnnot() { @NullMarked public class Test { void testPositive(NestedAnnots> p) { - // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> NestedAnnots type argument T: a type argument must match exactly; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots -> type argument for T of NestedAnnots: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String NestedAnnots.deeplyNested(p); } void testNegative(NestedAnnots> p) { @@ -638,7 +638,7 @@ public void nestedArray1() { @NullMarked public class Test { void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> array element -> NestedAnnots type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots -> component type -> type argument for T of NestedAnnots: source has @Nullable String where target requires String NestedAnnots[]> unused = NestedAnnots.nestedArray1(); } void testNegative() { @@ -665,7 +665,7 @@ public void nestedArray2() { @NullMarked public class Test { void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T: source has String @Nullable [] where target requires String [] + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots: source has String @Nullable [] where target requires String [] NestedAnnots unused = NestedAnnots.nestedArray2(); } void testNegative() { @@ -692,11 +692,11 @@ public void nestedWildcards() { @NullMarked public class Test { void testUpper(NestedAnnots<@Nullable String> t) { - // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> wildcard upper bound: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots -> upper bound of wildcard: source has @Nullable String where target requires String NestedAnnots.wildcardUpper(t); } void testLower(NestedAnnots t) { - // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> wildcard lower bound: source has String where target requires a supertype of @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots -> lower bound of wildcard: source has String where target requires a supertype of @Nullable String NestedAnnots.wildcardLower(t); } } @@ -725,7 +725,7 @@ NestedAnnots testDirect( // should reject since return type of wildcardUpperTypeVariable // is modeled to be NestedAnnots, which // here is incompatible with the return type NestedAnnots - // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> wildcard upper bound: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots -> upper bound of wildcard: source has @Nullable String where target requires String return receiver.wildcardUpperTypeVariable(); } @@ -734,7 +734,7 @@ NestedAnnots testWithSelf( // should reject since return type of wildcardUpperTypeVariable // is modeled to be NestedAnnots, which // here is incompatible with the return type NestedAnnots - // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> wildcard upper bound: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots -> upper bound of wildcard: source has @Nullable String where target requires String return receiver.self().wildcardUpperTypeVariable(); } @@ -745,7 +745,7 @@ NestedAnnots testWithVar( // should reject since return type of wildcardUpperTypeVariable // is modeled to be NestedAnnots, which // here is incompatible with the return type NestedAnnots - // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T -> wildcard upper bound: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots -> upper bound of wildcard: source has @Nullable String where target requires String return foo.wildcardUpperTypeVariable(); } @@ -771,7 +771,7 @@ public void nestedAnnotationsOnUnboundedWildcardBounds() { public class Test { UnboundWildcards testLiteral() { - // BUG: Diagnostic contains: incompatible nullability in UnboundWildcards type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of UnboundWildcards -> upper bound of wildcard: source has @Nullable Object where target requires Object return UnboundWildcards.literalWildcard(); } @@ -781,7 +781,7 @@ UnboundWildcards testLiteral() { UnboundWildcards testCaptured( UnboundWildcards receiver) { - // BUG: Diagnostic contains: incompatible nullability in UnboundWildcards type argument T -> wildcard upper bound: source has @Nullable Object where target requires Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of UnboundWildcards -> upper bound of wildcard: source has @Nullable Object where target requires Object return receiver.self().typeVariable(); } @@ -811,9 +811,9 @@ public void multipleArgs() { public class Test { void testPositive() { NestedAnnots.multipleArgs( - // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots: source has @Nullable String where target requires String new NestedAnnots<@Nullable String>(), - // BUG: Diagnostic contains: incompatible nullability in NestedAnnots type argument T: a type argument must match exactly; source has Integer where target requires @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots: a non-wildcard type argument must be the same type; source has Integer where target requires @Nullable Integer new NestedAnnots()); } void testNegative() { From 2c39198d406120ee0fa0279c326bd72162e049d1 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Sun, 29 Nov 2026 01:37:07 +0300 Subject: [PATCH 23/43] Keep the approved wording of the note for an unbounded wildcard The previous commit gave `?` the sentence of `? super X`. Its claim that `?` "has no upper bound of its own" contradicts JLS 4.5.1, where `?` is equivalent to `? extends Object`. The note for `?` goes back to the wording the maintainer approved. Only `? super X` keeps "no upper bound of its own". User-visible: `note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10)` Assisted-by: Claude Code (claude-opus-5-5) --- .../generics/NullabilityMismatchMessage.java | 13 ++++--- .../jspecify/mismatchmessage/CaretTests.java | 8 ++--- .../jspecify/mismatchmessage/NoteTests.java | 14 ++++---- .../jspecify/mismatchmessage/PathTests.java | 2 +- .../mismatchmessage/SourceFixTests.java | 36 +++++++++---------- .../SummaryAndNumberingTests.java | 20 +++++------ .../mismatchmessage/TargetTypeFixTests.java | 2 +- .../mismatchmessage/ViewedSourceTests.java | 8 ++--- 8 files changed, 54 insertions(+), 49 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 3463168642..cc9c2f51a9 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -42,7 +42,7 @@ * ^ * target: Map<? extends Object, String> * ^^^^^^ - * note: the unbounded wildcard ? in Map<?, String> has no upper bound of its own; its upper bound is the bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + * note: the unbounded wildcard ? in Map<?, String> has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) * possible fix: declare m as Map<? extends Object, String> * * @@ -621,11 +621,15 @@ private String mismatchDetail( ? reachingStep.formal() : null; Symbol.ClassSymbol owner = typeVariableOwner(formalTypeVariable); + // ? has an upper bound, Object as the JLS writes it (4.5.1), and ? super X has none of its + // own; capture conversion gives both the bound of the type parameter (5.1.10) + boolean unbounded = wildcard.kind == BoundKind.UNBOUND; String source = - wildcard.kind == BoundKind.UNBOUND + unbounded ? "the unbounded wildcard ?" : "the wildcard ? super " + GenericsChecks.prettyTypeForError(wildcard.type, state); - String hasBound = " has no upper bound of its own; its upper bound is"; + String hasBound = + unbounded ? " has the upper bound" : " has no upper bound of its own; its upper bound is"; if (formalTypeVariable == null || owner == null || caret == null || reachingStep == null) { // no type parameter this message prints stands behind the bound: the wildcard sits at no // position of a printed type, as below the root of a supertype view (#2197), or the variable @@ -653,10 +657,11 @@ private String mismatchDetail( GenericsUtils.effectiveUpperBoundsForTypeArguments(holderClass, state, config, handler) .get(reachingStep.index()); return String.format( - "%s in %s%s the bound of type parameter %s of %s, which is %s (JLS 5.1.10)", + "%s in %s%s %s type parameter %s of %s, which is %s (JLS 5.1.10)", source, withOtherTypeArgumentsElided(holderClass, reachingStep.index()), hasBound, + unbounded ? "of" : "the bound of", formalTypeVariable.tsym.getSimpleName(), owner.getSimpleName(), GenericsChecks.prettyTypeForError(upperBound, state)); 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 index a1c538447f..073daff9fe 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java @@ -218,12 +218,12 @@ public void twoMismatchesUnderOneWildcardShareItsCaret() { 1. path: type argument for T of Foo -> upper bound of wildcard -> type argument for K of Map source: @Nullable String target: String - note: the unbounded wildcard ? in Foo has no upper bound of its own; its upper bound is the bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) + note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) \s 2. path: type argument for T of Foo -> upper bound of wildcard -> type argument for V of Map source: @Nullable String target: String - note: the unbounded wildcard ? in Foo has no upper bound of its own; its upper bound is the bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) + note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) """, """ static class Foo> {} @@ -250,12 +250,12 @@ public void twoMismatchesUnderOneNestedWildcardShareItsCaret() { 1. path: type argument for E of List -> upper bound of wildcard -> type argument for T of Foo -> upper bound of wildcard -> type argument for K of Map source: @Nullable String target: String - note: the unbounded wildcard ? in Foo has no upper bound of its own; its upper bound is the bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) + note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) \s 2. path: type argument for E of List -> upper bound of wildcard -> type argument for T of Foo -> upper bound of wildcard -> type argument for V of Map source: @Nullable String target: String - note: the unbounded wildcard ? in Foo has no upper bound of its own; its upper bound is the bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) + note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) """, """ static class Foo> {} 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 d1d44171fa..b9ef464e67 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 @@ -22,7 +22,7 @@ public void anUnboundedWildcardNamesTheTypeParameterItsUpperBoundComesFrom() { ^ target: Collection ^^^^^^ - note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) possible fix: declare list as List """, """ @@ -53,7 +53,7 @@ public void theNotePrintsOnlyTheWildcardItMeansAndSimpleTypeArguments() { ^ target: Triple ^^^^^^ - note: the unbounded wildcard ? in Triple has no upper bound of its own; its upper bound is the bound of type parameter B of Triple, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Triple has the upper bound of type parameter B of Triple, which is @Nullable Object (JLS 5.1.10) possible fix: declare t as Triple> """, """ @@ -75,7 +75,7 @@ public void theNoteGivesTheBoundWithTheOtherTypeArgumentsSubstituted() { ^ target: Foo> ^^^^^^^^^^^^ - note: the unbounded wildcard ? in Foo has no upper bound of its own; its upper bound is the bound of type parameter B of Foo, which is @Nullable List (JLS 5.1.10) + note: the unbounded wildcard ? in Foo has the upper bound of type parameter B of Foo, which is @Nullable List (JLS 5.1.10) possible fix: declare f as Foo> """, """ @@ -159,7 +159,7 @@ public void aWildcardWhoseImplicitBoundHoldsTheMismatchNamesItsTypeParameter() { ^ target: Foo> ^^^^^^ - note: the unbounded wildcard ? in Foo has no upper bound of its own; its upper bound is the bound of type parameter T of Foo, which is List<@Nullable String> (JLS 5.1.10) + note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is List<@Nullable String> (JLS 5.1.10) """, """ static class Foo> {} @@ -180,7 +180,7 @@ public void aNestedWildcardWhoseImplicitBoundHoldsTheMismatchNamesItsTypeParamet ^ target: List>> ^^^^^^ - note: the unbounded wildcard ? in Foo has no upper bound of its own; its upper bound is the bound of type parameter T of Foo, which is List<@Nullable String> (JLS 5.1.10) + note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is List<@Nullable String> (JLS 5.1.10) """, """ static class Foo> {} @@ -201,7 +201,7 @@ public void aWildcardInsideAWildcardBoundNamesItsTypeParameter() { ^ target: List> ^^^^^^ - note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) possible fix: declare l as List> """, """ @@ -222,7 +222,7 @@ public void aWildcardInsideAnArrayInsideAWildcardBoundNamesItsTypeParameter() { ^ target: List []> ^^^^^^ - note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) possible fix: declare l as List []> """, """ 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 index 7efab68db6..f18650d650 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java @@ -194,7 +194,7 @@ public void aNullableSourceIsComparedBelowItsOwnNullness() { ^ target: Collection ^^^^^^ - note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) possible fix: declare l as @Nullable List """, """ diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java index 0456c9ca46..e42b0a2a46 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java @@ -26,12 +26,12 @@ public void theFixRewritesEveryMismatchingWildcard() { 1. path: type argument for K of Map -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Map has no upper bound of its own; its upper bound is the bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) \s 2. path: type argument for V of Map -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Map<..., ?> has no upper bound of its own; its upper bound is the bound of type parameter V of Map, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Map<..., ?> has the upper bound of type parameter V of Map, which is @Nullable Object (JLS 5.1.10) \s possible fix: declare m as Map """, @@ -56,7 +56,7 @@ public void theFixLeavesAWildcardTheTargetAllowsToBeNullable() { ^ target: Map ^^^^^^ - note: the unbounded wildcard ? in Map has no upper bound of its own; its upper bound is the bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) possible fix: declare m as Map """, """ @@ -80,7 +80,7 @@ public void theFixSurvivesAMismatchInTheHarmlessDirection() { ^ target: Box ^^^^^^ - note: the unbounded wildcard ? in Box has no upper bound of its own; its upper bound is the bound of type parameter T of Box, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Box has the upper bound of type parameter T of Box, which is @Nullable Object (JLS 5.1.10) possible fix: declare b as Box """, """ @@ -105,7 +105,7 @@ public void theFixSurvivesASuperBoundedArgumentTheTargetAlsoDeclaresSuper() { ^ target: Map ^^^^^^ - note: the unbounded wildcard ? in Map has no upper bound of its own; its upper bound is the bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) possible fix: declare m as Map """, """ @@ -129,7 +129,7 @@ public void theFixRewritesAWildcardInsideAnArrayElement() { ^ target: Collection [] ^^^^^^ - note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) possible fix: declare lists as List [] """, """ @@ -153,7 +153,7 @@ public void theFixRewritesAWildcardInsideANestedTypeArgument() { ^ target: Collection> ^^^^^^ - note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) possible fix: declare lists as List> """, """ @@ -177,7 +177,7 @@ public void theFixRewritesAWildcardInAnEnclosingTypeArgument() { ^ target: Outer.Inner ^^^^^^ - note: the unbounded wildcard ? in Outer has no upper bound of its own; its upper bound is the bound of type parameter T of Outer, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Outer has the upper bound of type parameter T of Outer, which is @Nullable Object (JLS 5.1.10) possible fix: declare inner as Outer.Inner """, """ @@ -204,7 +204,7 @@ public void theSourceFixIsStillOfferedWhereTheTargetTypeIsNotEditable() { ^ target: Collection ^^^^^^ - note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) possible fix: declare l as List """, """ @@ -231,7 +231,7 @@ public void noFixWhenAnExplicitBoundMismatchRemains() { 1. path: type argument for K of Map -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Map has no upper bound of its own; its upper bound is the bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) \s 2. path: type argument for V of Map -> upper bound of wildcard source: @Nullable Object @@ -261,7 +261,7 @@ public void noFixWhenAConcreteTypeArgumentAlsoMismatches() { 1. path: type argument for K of Map -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Map has no upper bound of its own; its upper bound is the bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) \s 2. path: type argument for V of Map source: @Nullable String @@ -291,7 +291,7 @@ public void noFixWhenOneMismatchCannotBeRewritten() { 1. path: type argument for K of Map -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Map has no upper bound of its own; its upper bound is the bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) \s 2. path: type argument for V of Map -> upper bound of wildcard source: @Nullable Object @@ -316,7 +316,7 @@ public void noFixWhenBoundsDifferBelowTheTopLevel() { ^ target: Holder> ^^^^^^ - note: the unbounded wildcard ? in Holder has no upper bound of its own; its upper bound is the bound of type parameter E of Holder, which is List<@Nullable Object> (JLS 5.1.10) + note: the unbounded wildcard ? in Holder has the upper bound of type parameter E of Holder, which is List<@Nullable Object> (JLS 5.1.10) """, """ static class Holder> {} @@ -337,7 +337,7 @@ public void noFixWhenTheRewrittenTypeHoldsACapture() { ^ target: Map, ?> ^^^^^^ - note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) """, """ static Map, T> make(List l) { @@ -364,7 +364,7 @@ public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { ^ target: Map ^^^^^^ - note: the unbounded wildcard ? in Map has no upper bound of its own; its upper bound is the bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) possible fix: declare plain as Map """, "TAINTED", @@ -374,7 +374,7 @@ public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { ^ target: Map ^^^^^^ - note: the unbounded wildcard ? in Map has no upper bound of its own; its upper bound is the bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) """, "TAINTED_ARRAY_ELEMENT", """ @@ -383,7 +383,7 @@ public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { ^ target: Map ^^^^^^ - note: the unbounded wildcard ? in Map has no upper bound of its own; its upper bound is the bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) """), """ @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) @@ -414,7 +414,7 @@ public void theFixNamesTheFieldItRewrites() { ^ target: Collection ^^^^^^ - note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) possible fix: declare field as List """, """ 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 index c1a95ad33a..fb96c606be 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java @@ -27,27 +27,27 @@ public void listsAtMostFiveMismatchesAndSaysHowManyMoreThereAre() { 1. path: type argument for A of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Args has no upper bound of its own; its upper bound is the bound of type parameter A of Args, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Args has the upper bound of type parameter A of Args, which is @Nullable Object (JLS 5.1.10) \s 2. path: type argument for B of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Args<..., ?, ..., ..., ..., ...> has no upper bound of its own; its upper bound is the bound of type parameter B of Args, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Args<..., ?, ..., ..., ..., ...> has the upper bound of type parameter B of Args, which is @Nullable Object (JLS 5.1.10) \s 3. path: type argument for C of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Args<..., ..., ?, ..., ..., ...> has no upper bound of its own; its upper bound is the bound of type parameter C of Args, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Args<..., ..., ?, ..., ..., ...> has the upper bound of type parameter C of Args, which is @Nullable Object (JLS 5.1.10) \s 4. path: type argument for D of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Args<..., ..., ..., ?, ..., ...> has no upper bound of its own; its upper bound is the bound of type parameter D of Args, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Args<..., ..., ..., ?, ..., ...> has the upper bound of type parameter D of Args, which is @Nullable Object (JLS 5.1.10) \s 5. path: type argument for E of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Args<..., ..., ..., ..., ?, ...> has no upper bound of its own; its upper bound is the bound of type parameter E of Args, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Args<..., ..., ..., ..., ?, ...> has the upper bound of type parameter E of Args, which is @Nullable Object (JLS 5.1.10) \s and 1 more, not listed \s @@ -78,27 +78,27 @@ public void listsFiveMismatchesWithoutSayingThereAreMore() { 1. path: type argument for A of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Args has no upper bound of its own; its upper bound is the bound of type parameter A of Args, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Args has the upper bound of type parameter A of Args, which is @Nullable Object (JLS 5.1.10) \s 2. path: type argument for B of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Args<..., ?, ..., ..., ...> has no upper bound of its own; its upper bound is the bound of type parameter B of Args, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Args<..., ?, ..., ..., ...> has the upper bound of type parameter B of Args, which is @Nullable Object (JLS 5.1.10) \s 3. path: type argument for C of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Args<..., ..., ?, ..., ...> has no upper bound of its own; its upper bound is the bound of type parameter C of Args, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Args<..., ..., ?, ..., ...> has the upper bound of type parameter C of Args, which is @Nullable Object (JLS 5.1.10) \s 4. path: type argument for D of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Args<..., ..., ..., ?, ...> has no upper bound of its own; its upper bound is the bound of type parameter D of Args, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Args<..., ..., ..., ?, ...> has the upper bound of type parameter D of Args, which is @Nullable Object (JLS 5.1.10) \s 5. path: type argument for E of Args -> upper bound of wildcard source: @Nullable Object target: Object - note: the unbounded wildcard ? in Args<..., ..., ..., ..., ?> has no upper bound of its own; its upper bound is the bound of type parameter E of Args, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Args<..., ..., ..., ..., ?> has the upper bound of type parameter E of Args, which is @Nullable Object (JLS 5.1.10) \s possible fix: declare args as Args """, diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java index fe09e787ec..abc2ca8914 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java @@ -94,7 +94,7 @@ public void theFixReplacesTheNodeAtEveryKindOfStep() { ^ target: Collection ^^^^^^ - note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) possible fix: declare list as List possible fix: declare c as Collection Did you mean 'Collection c = list;'? 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 6b9bc6ee19..b6e1fa5ba1 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 @@ -281,7 +281,7 @@ public void aWildcardFromTheSubclassDeclarationIsNamedOnlyWhereALinePrintsIt() { ^ target: Base> ^^^^^^ - note: the unbounded wildcard ? in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) """, "MAP", """ @@ -291,7 +291,7 @@ public void aWildcardFromTheSubclassDeclarationIsNamedOnlyWhereALinePrintsIt() { ^ target: Base> ^^^^^^ - note: the unbounded wildcard ? in Map has no upper bound of its own; its upper bound is the bound of type parameter V of Map, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Map has the upper bound of type parameter V of Map, which is @Nullable Object (JLS 5.1.10) """, "BELOW_ROOT", """ @@ -299,7 +299,7 @@ public void aWildcardFromTheSubclassDeclarationIsNamedOnlyWhereALinePrintsIt() { source: List target: List>> ^^^^^^ - note: the unbounded wildcard ? in the source has no upper bound of its own; its upper bound is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in the source has the upper bound @Nullable Object (JLS 5.1.10) """), """ static class Base {} @@ -332,7 +332,7 @@ public void aPathAcrossAViewReachesIntoWhateverTheSubclassPassed() { ^ target: Base> ^^^^^^ - note: the unbounded wildcard ? in Indirect has no upper bound of its own; its upper bound is the bound of type parameter X of Indirect, which is @Nullable Object (JLS 5.1.10) + note: the unbounded wildcard ? in Indirect has the upper bound of type parameter X of Indirect, which is @Nullable Object (JLS 5.1.10) possible fix: declare i as Indirect """, """ From 06c4764379c9cd9ccee6678ffa5c1fd0ef8baa17 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Sun, 29 Nov 2026 01:41:26 +0300 Subject: [PATCH 24/43] Describe the note and its elision rule as the code builds them The class comment now says the note states the bound. The elision rule reads the same in its three places: every other type argument whose printed form contains ? or < is printed as '...'. The below-root comment no longer claims that the source prints a ?. Assisted-by: Claude Code (claude-opus-5-5) --- .../generics/NullabilityMismatchMessage.java | 22 ++++++++++--------- .../jspecify/mismatchmessage/NoteTests.java | 2 +- 2 files changed, 13 insertions(+), 11 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 cc9c2f51a9..69ef3b3aa6 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -95,9 +95,10 @@ * *

A note explains itself in the entities the message already shows. Where the source wildcard is * marked on a printed type, the type the reader wrote or the {@code source supertype} line, the - * note prints the class the wildcard is a type argument of and names the type parameter the - * wildcard takes its bound from. Every other type argument of that class that is or holds a - * wildcard or a type argument of its own is printed as {@code ...}, so the one {@code ?} printed is + * note prints the class the wildcard is a type argument of, names the type parameter the wildcard + * takes its upper bound from, and states that bound with the class's other type arguments + * substituted. Every other type argument whose printed form contains {@code ?} or {@code <}, such + * as a wildcard or a parameterized type, is printed as {@code ...}, so the one {@code ?} printed is * the wildcard meant and a long type is not repeated. Where it is marked on neither, as below the * root of a supertype view, the type parameter belongs to a declaration this message never prints, * and the note states the bound and stops. Where the node is one a side does not print, as with the @@ -156,7 +157,7 @@ final class NullabilityMismatchMessage { private static final String SOURCE_LABEL = "source"; /** The key of the line that prints the supertype of the source type the check compared. */ - private static final String VIEWED_SOURCE_LABEL = "source supertype"; + private static final String SOURCE_SUPERTYPE_LABEL = "source supertype"; /** * The key of the line that prints the target type, and of the target node in a numbered entry. @@ -228,12 +229,12 @@ Report build( printedView = viewedSource; // a node the check compared is at no position of the type the reader wrote, so the view of // it the check did compare is printed too and carries the carets - labelWidth = VIEWED_SOURCE_LABEL.length(); + labelWidth = SOURCE_SUPERTYPE_LABEL.length(); message.append( markedTypeLines(SOURCE_LABEL, labelWidth, sourceType, List.of(), numbered).lines()); message.append( markedTypeLines( - VIEWED_SOURCE_LABEL, + SOURCE_SUPERTYPE_LABEL, labelWidth, viewedSource, carets(listed, mismatch -> printedViewCaret(mismatch, viewedSource)), @@ -634,7 +635,8 @@ private String mismatchDetail( // no type parameter this message prints stands behind the bound: the wildcard sits at no // position of a printed type, as below the root of a supertype view (#2197), or the variable // it instantiates has no named owner. The note says what the bound is and leaves where it - // came from alone. "in the source" says which ? is meant, since two printed types carry one + // came from alone. "in the source" tells it from a wildcard of the target; below the root the + // ? itself is in a declaration this message does not print return String.format( "%s in the source%s %s (JLS 5.1.10)", source, @@ -696,9 +698,9 @@ private String mismatchDetail( /** * Prints {@code holder} with its type argument at {@code index} in full, and as {@code ...} every - * other type argument that is or holds a wildcard or a type argument of its own, as {@code - * BiFunction}. So the one {@code ?} printed is the wildcard a note means, and a - * long type the {@code source} line already prints is not repeated. + * other type argument whose printed form contains {@code ?} or {@code <}, such as a wildcard or a + * parameterized type, as {@code BiFunction}. So the one {@code ?} printed is the + * wildcard a note means, and a long type the {@code source} line already prints is not repeated. */ private String withOtherTypeArgumentsElided(Type.ClassType holder, int index) { List typeArguments = holder.getTypeArguments(); 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 b9ef464e67..346ab6033d 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 @@ -6,7 +6,7 @@ * A {@code note:} line says where the source takes a nullness its printed form does not show: the * upper bound an unbounded or lower-bounded wildcard takes from its type parameter, or the type * parameter a captured wildcard instantiates. It prints the class the wildcard is a type argument - * of, with the other type arguments that hold a wildcard or a type argument of their own written as + * of, with every other type argument whose printed form contains {@code ?} or {@code <} written as * {@code ...}. A source that prints its own nullness gets no note. */ public class NoteTests extends MismatchMessageTestBase { From da8978d56b48be2ee0fc3e32095d171ffb010395 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Sun, 29 Nov 2026 11:45:52 +0300 Subject: [PATCH 25/43] Link the tests that pin a known message gap to their issues The target line of a nested array prints its dimensions innermost first (#2201), and the target line of an intersection has no caret (#2202). Assisted-by: Claude Code (claude-opus-5-5) --- .../com/uber/nullaway/jspecify/mismatchmessage/PathTests.java | 2 ++ .../nullaway/jspecify/mismatchmessage/ViewedSourceTests.java | 1 + 2 files changed, 3 insertions(+) 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 index f18650d650..0ec1bf6919 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java @@ -149,6 +149,8 @@ void test(List[] arr) { """); } + // The target line prints the dimensions innermost first, Integer @Nullable [] [] for the declared + // Integer[] @Nullable [], so it reads as the opposite nullness (#2201). @Test public void pathDescendsIntoEveryDimensionOfANestedArray() { assertMessage( 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 b6e1fa5ba1..ae377cfe0b 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 @@ -241,6 +241,7 @@ void written(Strings s) { """); } + // The target line of an intersection has no caret under either differing position (#2202). @Test public void eachComponentOfAnIntersectionTargetIsComparedUnderItsOwnView() { assertMessage( From 778449f1a053a51b99ae3b239fd180ce1858f87b Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Mon, 30 Nov 2026 00:16:22 +0300 Subject: [PATCH 26/43] Print a fix type only as Java that compiles and keeps its annotations A `possible fix:` line, and the edit that pastes it, could print a type that does not compile or that drops an annotation the check relied on: - With `CustomNullableAnnotations` naming a type-use annotation whose simple name is not `Nullable`, `Map m = make();` was rewritten to `Map m = make();`. `isDeclarable` accepted every nullable annotation, while the printer prints only one named `Nullable`. - A local class declared in an instance method, a constructor, or an initializer printed as `Test.Local`, which names no type. - For an inner class, `@Nullable Test.Inner x` was rewritten to `@Nullable @Nullable Test.Inner x`. javac attaches a type-use annotation among the modifiers to `Test`, the leftmost type the type tree names, and the printer left the annotation out only on the root type. The printer and `isDeclarable` now read the same two predicates: which annotation the printer prints, and whether a class prints its enclosing type. A type carrying any other annotation withholds the fix. The enclosing type prints only for a member class, as javac's `ClassType.toString` does. The modifier's annotation is left out on the leftmost type, reached through array elements and enclosing types. User-visible: A custom type-use nullable annotation of another simple name withholds the `possible fix:` line and its edit. The `source:` and `target:` lines print a local class under its simple name, `Local`, where they printed `Test.Local`. The `possible fix:` line and its edit spell an array as a declaration does, `List<@Nullable String>[]`; the `source:` and `target:` lines keep `List<@Nullable String> []`. Assisted-by: Claude Code (claude-opus-5-5) --- .../GenericTypePrettyPrintingVisitor.java | 109 +++++++++++---- .../generics/NullabilityMismatchMessage.java | 53 +++---- .../jspecify/mismatchmessage/FixTests.java | 132 ++++++++++++++++++ .../jspecify/mismatchmessage/NoteTests.java | 2 +- .../mismatchmessage/SourceFixTests.java | 77 +++++++++- .../mismatchmessage/TargetTypeFixTests.java | 77 ++++++++-- 6 files changed, 380 insertions(+), 70 deletions(-) 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 416e0f02c4..5badde0b0d 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java @@ -5,11 +5,12 @@ import com.google.errorprone.VisitorState; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; -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.Kinds; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Type; +import com.sun.tools.javac.code.TypeTag; import com.sun.tools.javac.code.Types; import java.util.List; import org.jspecify.annotations.Nullable; @@ -65,29 +66,40 @@ final class GenericTypePrettyPrintingVisitor private final SuggestedFix.@Nullable Builder fix; /** - * Whether the {@code @Nullable} on the base type, the type itself or, for an array, its innermost - * element type, is left out because the declaration the fix rewrites states it among its - * modifiers, outside the type tree the fix replaces. + * Whether the {@code @Nullable} on the base type is left out because the declaration the fix + * rewrites states it among its modifiers, outside the type tree the fix replaces. The base type + * is the leftmost type the type tree names, where javac attaches such a modifier: the type itself + * or, for an array, its innermost element type, and for an inner class the outermost enclosing + * type printed before it. */ private final boolean omitBaseAnnotation; + /** + * Whether an array prints as a declaration spells it, {@code String[]}, rather than with the + * space the {@code source:} and {@code target:} lines put before an unannotated dimension, {@code + * String []}. + */ + private final boolean sourceSpelling; + GenericTypePrettyPrintingVisitor(VisitorState state) { this(state, List.of()); } GenericTypePrettyPrintingVisitor(VisitorState state, List<@Nullable TypePath> markedPaths) { - this(state, markedPaths, null, false); + this(state, markedPaths, null, false, false); } private GenericTypePrettyPrintingVisitor( VisitorState state, List<@Nullable TypePath> markedPaths, SuggestedFix.@Nullable Builder fix, - boolean omitBaseAnnotation) { + boolean omitBaseAnnotation, + boolean sourceSpelling) { this.state = state; this.markedPaths = markedPaths; this.fix = fix; this.omitBaseAnnotation = omitBaseAnnotation; + this.sourceSpelling = sourceSpelling; } /** @@ -96,14 +108,49 @@ private GenericTypePrettyPrintingVisitor( * by {@code fix}, or qualified where an import would clash. NullAway's synthetic * {@code @Nullable} prints as JSpecify's. * - * @param omitBaseAnnotation whether to leave out the {@code @Nullable} of the base type, the type - * itself or, for an array, its innermost element type, because the declaration states it - * among its modifiers + * @param omitBaseAnnotation whether to leave out the {@code @Nullable} of the base type, the + * leftmost type the declaration's type tree names, because the declaration states it among + * its modifiers */ static String printForFix( Type type, VisitorState state, SuggestedFix.Builder fix, boolean omitBaseAnnotation) { return type.accept( - new GenericTypePrettyPrintingVisitor(state, List.of(), fix, omitBaseAnnotation), null); + new GenericTypePrettyPrintingVisitor(state, List.of(), fix, omitBaseAnnotation, true), + null); + } + + /** + * Returns {@code type} as a {@code possible fix:} line names it: under simple names, as the + * {@code source:} and {@code target:} lines print it, with each array spelled as a declaration + * writes it. + */ + static String printForFixLine(Type type, VisitorState state) { + return type.accept( + new GenericTypePrettyPrintingVisitor(state, List.of(), null, false, true), null); + } + + /** + * Returns the type-use annotation on {@code type} itself that the printer prints, or {@code null} + * if it prints none. The printer prints the first annotation whose simple name is {@code + * Nullable} and drops every other one, including a nullable annotation of another name. + */ + static Attribute.@Nullable TypeCompound printedAnnotation(Type type) { + for (Attribute.TypeCompound compound : type.getAnnotationMirrors()) { + if (compound.type.tsym.getSimpleName().contentEquals("Nullable")) { + return compound; + } + } + return null; + } + + /** + * Returns whether the printer prints the enclosing type of {@code t} before its name, as in + * {@code Outer.Inner}. It does for a member class with an enclosing instance, as javac's + * {@code ClassType.toString} does. A local class has no name qualified by its enclosing type, so + * it prints under its simple name even where it has an enclosing instance. + */ + static boolean printsEnclosingType(Type.ClassType t) { + return t.getEnclosingType().hasTag(TypeTag.CLASS) && t.tsym.owner.kind == Kinds.Kind.TYP; } /** @@ -125,13 +172,18 @@ private String annotationName(Type annotationType) { } /** - * Whether {@code t}, the node being printed, is the base type: the root, or the innermost element - * type of a root array. + * Whether {@code t}, the node being printed, is the base type: the leftmost type the printed type + * names. That node is reached from the root through array elements and enclosing types only, and + * is neither an array nor a class printed after its enclosing type. */ private boolean isBase(Type t) { return !(t instanceof Type.ArrayType) + && !(t instanceof Type.ClassType classType && printsEnclosingType(classType)) && currentPath.steps().stream() - .allMatch(step -> step.kind() == TypePath.Step.Kind.ARRAY_ELEMENT); + .allMatch( + step -> + step.kind() == TypePath.Step.Kind.ARRAY_ELEMENT + || step.kind() == TypePath.Step.Kind.ENCLOSING_TYPE); } /** Brackets {@code printed} when the node being printed sits at one of the requested paths. */ @@ -196,10 +248,9 @@ public String visitClassType(Type.ClassType t, @Nullable Void s) { return mark(t.toString()); } StringBuilder sb = new StringBuilder(); - Type enclosingType = t.getEnclosingType(); - boolean printsEnclosingType = !ASTHelpers.isSameType(enclosingType, Type.noType, state); + boolean printsEnclosingType = printsEnclosingType(t); if (printsEnclosingType) { - sb.append(descend(TypePath.Step.enclosingType(), enclosingType)).append('.'); + sb.append(descend(TypePath.Step.enclosingType(), t.getEnclosingType())).append('.'); } String className = printsEnclosingType ? t.tsym.getSimpleName().toString() : name(t.tsym); // a type annotation on a qualified name goes before its last segment: Map.@Nullable Entry @@ -224,18 +275,14 @@ public String visitClassType(Type.ClassType t, @Nullable Void s) { } /** - * Appends {@code "@Nullable "} to {@code sb} if {@code t} has a type-use {@code @Nullable} - * annotation. We ignore all other type use annotations, including {@code @NonNull} as it is the - * default + * Appends {@code "@Nullable "} to {@code sb} if {@code t} has the annotation {@link + * #printedAnnotation} returns. We ignore all other type use annotations, including + * {@code @NonNull} as it is the default */ private void appendNullableAnnotationIfPresent(Type t, StringBuilder sb) { - for (Attribute.TypeCompound compound : t.getAnnotationMirrors()) { - if (compound.type.tsym.getSimpleName().contentEquals("Nullable")) { - if (!(omitBaseAnnotation && isBase(t))) { - sb.append('@').append(annotationName(compound.type)).append(' '); - } - break; - } + Attribute.TypeCompound compound = printedAnnotation(t); + if (compound != null && !(omitBaseAnnotation && isBase(t))) { + sb.append('@').append(annotationName(compound.type)).append(' '); } } @@ -268,9 +315,13 @@ public String visitCapturedType(Type.CapturedType t, @Nullable Void s) { @Override public String visitArrayType(Type.ArrayType t, @Nullable Void unused) { StringBuilder sb = new StringBuilder(); - sb.append(descend(TypePath.Step.arrayElement(), t.elemtype)).append(' '); - appendNullableAnnotationIfPresent(t, sb); - return mark(sb.append("[]").toString()); + sb.append(descend(TypePath.Step.arrayElement(), t.elemtype)); + StringBuilder annotation = new StringBuilder(); + appendNullableAnnotationIfPresent(t, annotation); + if (!sourceSpelling || annotation.length() > 0) { + sb.append(' '); + } + return mark(sb.append(annotation).append("[]").toString()); } @Override 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 69ef3b3aa6..aa9d834418 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -16,7 +16,6 @@ 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.sun.tools.javac.tree.JCTree; import com.uber.nullaway.Config; @@ -128,10 +127,11 @@ * 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 fix also has to survive printing. The printer shows {@code @Nullable} and drops every other - * type-use annotation, and it writes the dimensions of a nested array in the reverse of the order a - * declaration gives them, so a type carrying another annotation, or an annotation on a dimension of - * a nested array, is not offered. + *

A fix also has to survive printing. The printer shows an annotation named {@code Nullable} and + * drops every other type-use annotation, a custom nullable annotation of another name included, and + * it writes the dimensions of a nested array in the reverse of the order a declaration gives them, + * so a type carrying another annotation, or an annotation on a dimension of a nested array, is not + * offered. */ final class NullabilityMismatchMessage { @@ -291,7 +291,8 @@ private void appendFix( message.append( String.format( "\n possible fix: declare %s as %s", - variable.getSimpleName(), GenericsChecks.prettyTypeForError(type, state))); + variable.getSimpleName(), + GenericTypePrettyPrintingVisitor.printForFixLine(type, state))); if (config.suggestSuppressions()) { // the run asks for the suppression ErrorBuilder adds after these fixes, and patching // applies only the first fix of a diagnostic @@ -901,14 +902,16 @@ public Type visitWildcardType(Type.WildcardType t, @Nullable Void unused) { * Returns whether {@code type} prints as a type a reader can declare, so that a fix pasting it * says what the reader gets. * - *

This mirrors {@link GenericTypePrettyPrintingVisitor}, which prints {@code @Nullable} and - * drops every other type-use annotation, and has four arms whose output no declaration may hold - * or that denotes nothing: a captured wildcard prints as {@code capture of ?}, an intersection as - * {@code A & B}, an anonymous class under its binary name, and a type that did not resolve under - * a bare name. 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. + *

This mirrors {@link GenericTypePrettyPrintingVisitor}, which prints the annotation {@link + * GenericTypePrettyPrintingVisitor#printedAnnotation} returns and drops every other type-use + * annotation, prints the enclosing type only where {@link + * GenericTypePrettyPrintingVisitor#printsEnclosingType} holds, and has four arms whose output no + * declaration may hold or that denotes nothing: a captured wildcard prints as {@code capture of + * ?}, an intersection as {@code A & B}, an anonymous class under its binary name, and a type that + * did not resolve under a bare name. 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 boolean isDeclarable(Type type) { return type.accept(declarabilityVisitor, null); @@ -926,8 +929,8 @@ public Boolean visitClassType(Type.ClassType t, @Nullable Void unused) { return false; } } - Type enclosingType = t.getEnclosingType(); - return enclosingType.hasTag(TypeTag.NONE) || enclosingType.accept(this, null); + return !GenericTypePrettyPrintingVisitor.printsEnclosingType(t) + || t.getEnclosingType().accept(this, null); } @Override @@ -972,14 +975,16 @@ private static boolean hasAnnotatedDimension(Type.ArrayType array) { return false; } - /** Returns whether the only type-use annotation on {@code type} itself is a nullable one. */ - private boolean printsEveryAnnotation(Type type) { - for (Attribute.TypeCompound annotation : type.getAnnotationMirrors()) { - if (!Nullness.isNullableAnnotation(annotation.type.toString(), config)) { - return false; - } - } - return true; + /** + * Returns whether every type-use annotation on {@code type} itself is the one the printer prints, + * so that a custom nullable annotation of another name withholds the fix rather than being + * dropped from it. + */ + private static boolean printsEveryAnnotation(Type type) { + List annotations = type.getAnnotationMirrors(); + return annotations.isEmpty() + || (annotations.size() == 1 + && GenericTypePrettyPrintingVisitor.printedAnnotation(type) != null); } /** Returns the named class declaring {@code typeVariable}, or {@code null} if there is none. */ diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java index 72ec07c6ce..73d19a90ca 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java @@ -258,6 +258,8 @@ void test() { .doTest(); } + // javac attaches a type-use annotation among the modifiers to the leftmost type the type tree + // names, which for an inner class is its enclosing type, such as Test in @Nullable Test.Inner. @Test public void theSourceFixKeepsEveryNullableAnnotationTheDeclarationWrites() throws IOException { makeHelper() @@ -271,8 +273,17 @@ public void theSourceFixKeepsEveryNullableAnnotationTheDeclarationWrites() throw import org.jspecify.annotations.Nullable; @NullMarked class Test { + class Inner {} + static class Outer { + class Inner {} + } static void take(Collection c) {} static void takeMap(Map m) {} + static void takeInner(Test.Inner i) {} + static void takeNullableInner(Test.@Nullable Inner i) {} + static void takeInners(Test.Inner[] i) {} + static void takeOuterInner(Outer<@Nullable String>.Inner i) {} + static void takeArray(@Nullable List @Nullable [] a) {} static @Nullable List list() { throw new RuntimeException(); } @@ -303,6 +314,26 @@ void modifierAfterAnotherAnnotation() { take(l); } } + void modifierOnAnInnerClass(Inner init) { + @Nullable Test.Inner x = init; + takeInner(x); + } + void modifierAndInnerClassAnnotation(Inner init) { + @Nullable Test.@Nullable Inner x = init; + takeNullableInner(x); + } + void modifierOnAnArrayOfAnInnerClass(Inner[] init) { + @Nullable Test.Inner[] x = init; + takeInners(x); + } + void modifierAndEnclosingTypeArgument(Outer<@Nullable String>.Inner init) { + @Nullable Outer<@Nullable String>.Inner x = init; + takeOuterInner(x); + } + void modifierAndAnnotatedDimension(List @Nullable [] init) { + @Nullable List @Nullable [] x = init; + takeArray(x); + } } """) .addOutputLines( @@ -315,8 +346,17 @@ void modifierAfterAnotherAnnotation() { import org.jspecify.annotations.Nullable; @NullMarked class Test { + class Inner {} + static class Outer { + class Inner {} + } static void take(Collection c) {} static void takeMap(Map m) {} + static void takeInner(Test.Inner i) {} + static void takeNullableInner(Test.@Nullable Inner i) {} + static void takeInners(Test.Inner[] i) {} + static void takeOuterInner(Outer<@Nullable String>.Inner i) {} + static void takeArray(@Nullable List @Nullable [] a) {} static @Nullable List list() { throw new RuntimeException(); } @@ -347,6 +387,26 @@ void modifierAfterAnotherAnnotation() { take(l); } } + void modifierOnAnInnerClass(Inner init) { + @Nullable Test.Inner x = init; + takeInner(x); + } + void modifierAndInnerClassAnnotation(Inner init) { + @Nullable Test.@Nullable Inner x = init; + takeNullableInner(x); + } + void modifierOnAnArrayOfAnInnerClass(Inner[] init) { + @Nullable Test.Inner[] x = init; + takeInners(x); + } + void modifierAndEnclosingTypeArgument(Outer<@Nullable String>.Inner init) { + @Nullable Outer<@Nullable String>.Inner x = init; + takeOuterInner(x); + } + void modifierAndAnnotatedDimension(List @Nullable [] init) { + @Nullable List @Nullable [] x = init; + takeArray(x); + } } """) .doTest(); @@ -643,4 +703,76 @@ void afterADeclaratorWithBrackets() { .expectUnchanged() .doTest(); } + + @Test + public void aLocalClassIsWrittenUnderItsSimpleName() throws IOException { + makeHelper() + .addInputLines( + "Test.java", + """ + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + Test() { + class Local {} + Local t = new Local(); + Local l = new Local(); + t = l; + } + { + class Local {} + Local t = new Local(); + Local l = new Local(); + t = l; + } + void instanceMethod() { + class Local {} + Local t = new Local(); + Local l = new Local(); + t = l; + } + static void staticMethod() { + class Local {} + Local t = new Local(); + Local l = new Local(); + t = l; + } + } + """) + .addOutputLines( + "Test.java", + """ + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + Test() { + class Local {} + Local t = new Local(); + Local l = new Local(); + t = l; + } + { + class Local {} + Local t = new Local(); + Local l = new Local(); + t = l; + } + void instanceMethod() { + class Local {} + Local t = new Local(); + Local l = new Local(); + t = l; + } + static void staticMethod() { + class Local {} + Local t = new Local(); + Local l = new Local(); + t = l; + } + } + """) + .doTest(); + } } 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 346ab6033d..6a506b7058 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 @@ -223,7 +223,7 @@ public void aWildcardInsideAnArrayInsideAWildcardBoundNamesItsTypeParameter() { target: List []> ^^^^^^ note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - possible fix: declare l as List []> + possible fix: declare l as List[]> """, """ static void take(List[]> l) {} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java index e42b0a2a46..1706bf58f4 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java @@ -1,5 +1,8 @@ package com.uber.nullaway.jspecify.mismatchmessage; +import com.google.errorprone.CompilationTestHelper; +import com.uber.nullaway.generics.JSpecifyJavacConfig; +import java.util.List; import java.util.Map; import org.junit.Test; @@ -130,7 +133,7 @@ public void theFixRewritesAWildcardInsideAnArrayElement() { target: Collection [] ^^^^^^ note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - possible fix: declare lists as List [] + possible fix: declare lists as List[] """, """ static void takeArray(Collection[] c) {} @@ -351,12 +354,17 @@ void test(List l) { """); } - // The printer drops @Tainted from the printed types, so TAINTED differs from PLAIN only by the - // missing fix line. + // The printer drops @Tainted and the custom nullable @CanBeNull from the printed types, so + // TAINTED and CUSTOM_NULLABLE differ from PLAIN only by the missing fix line. @Test public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { - assertMessages( - Map.of( + CompilationTestHelper helper = + makeTestHelperWithArgs( + JSpecifyJavacConfig.withJSpecifyModeArgs( + List.of( + "-XepOpt:NullAway:OnlyNullMarked=true", + "-XepOpt:NullAway:CustomNullableAnnotations=Test.CanBeNull"))); + Map.of( "PLAIN", """ incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object @@ -384,10 +392,31 @@ public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { target: Map ^^^^^^ note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) - """), - """ + """, + "CUSTOM_NULLABLE", + """ + incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Map + ^ + target: Map + ^^^^^^ + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + """) + .forEach((key, expected) -> helper.expectErrorMessage(key, messageIs(expected))); + helper + .addSourceLines( + "Test.java", + nullMarkedClass( + """ @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) @interface Tainted {} + @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) + @interface CanBeNull {} + static void takeCustom(Map m) {} + void customNullable(Map custom) { + // BUG: Diagnostic matches: CUSTOM_NULLABLE + takeCustom(custom); + } static void take(Map m) {} static void takeArrays(Map m) {} void plain(Map plain) { @@ -402,6 +431,40 @@ void taintedArrayElement(Map m) { // BUG: Diagnostic matches: TAINTED_ARRAY_ELEMENT takeArrays(m); } + """)) + .doTest(); + } + + @Test + public void aLocalClassIsPrintedUnderItsSimpleName() { + String expected = + """ + incompatible nullability in type argument for T of Local -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Local + ^ + target: Local + ^^^^^^ + note: the unbounded wildcard ? in Local has the upper bound of type parameter T of Local, which is @Nullable Object (JLS 5.1.10) + possible fix: declare l as Local + Did you mean 'Local l = new Local();'? + """; + assertMessages( + Map.of("INSTANCE_METHOD", expected, "STATIC_METHOD", expected), + """ + void instanceMethod() { + class Local {} + Local t = new Local(); + Local l = new Local(); + // BUG: Diagnostic matches: INSTANCE_METHOD + t = l; + } + static void staticMethod() { + class Local {} + Local t = new Local(); + Local l = new Local(); + // BUG: Diagnostic matches: STATIC_METHOD + t = l; + } """); } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java index abc2ca8914..797d6e01a0 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java @@ -1,5 +1,8 @@ package com.uber.nullaway.jspecify.mismatchmessage; +import com.google.errorprone.CompilationTestHelper; +import com.uber.nullaway.generics.JSpecifyJavacConfig; +import java.util.List; import java.util.Map; import org.junit.Test; @@ -106,8 +109,8 @@ public void theFixReplacesTheNodeAtEveryKindOfStep() { ^^^^^^^^^^^^^^^^ target: List [] ^^^^^^ - possible fix: declare d as List<@Nullable String> [] - Did you mean 'List<@Nullable String> [] d = src;'? + possible fix: declare d as List<@Nullable String>[] + Did you mean 'List<@Nullable String>[] d = src;'? """, "ENCLOSING_TYPE", """ @@ -159,12 +162,18 @@ void enclosingType(Outer<@Nullable String>.Inner src) { """); } - // The printer drops @Tainted from the printed types, so TAINTED and TAINTED_BOUND differ from - // PLAIN and a message with a fix only by the missing fix line. + // The printer drops @Tainted and the custom nullable @CanBeNull from the printed types, so the + // keys + // whose types carry one get no fix line. @Test public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { - assertMessages( - Map.of( + CompilationTestHelper helper = + makeTestHelperWithArgs( + JSpecifyJavacConfig.withJSpecifyModeArgs( + List.of( + "-XepOpt:NullAway:OnlyNullMarked=true", + "-XepOpt:NullAway:CustomNullableAnnotations=Test.CanBeNull"))); + Map.of( "PLAIN", """ incompatible nullability in type argument for V of Map: source has @Nullable String where target requires String @@ -200,10 +209,44 @@ public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { ^^^^^^ possible fix: declare d as Map Did you mean 'Map d = m;'? - """), - """ + """, + "TAINTED_TYPE_VARIABLE", + """ + incompatible nullability in type argument for V of Map: source has @Nullable String where target requires String + source: Map + ^^^^^^^^^^^^^^^^ + target: Map + ^^^^^^ + """, + "TAINTED_ENCLOSING_TYPE", + """ + incompatible nullability in type argument for U of Inner: source has @Nullable String where target requires String + source: Outer.Inner<@Nullable String> + ^^^^^^^^^^^^^^^^ + target: Outer.Inner + ^^^^^^ + """, + "CUSTOM_NULLABLE", + """ + incompatible nullability in type argument for V of Map: source has String where target requires String + source: Map + ^^^^^^ + target: Map + ^^^^^^ + """) + .forEach((key, expected) -> helper.expectErrorMessage(key, messageIs(expected))); + helper + .addSourceLines( + "Test.java", + nullMarkedClass( + """ @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) @interface Tainted {} + @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) + @interface CanBeNull {} + static class Outer { + class Inner {} + } void plain(Map m) { // BUG: Diagnostic matches: PLAIN Map plain = m; @@ -224,6 +267,22 @@ static void typeVariable(Map m) { Map d = m; d.hashCode(); } - """); + static void taintedTypeVariable(Map<@Tainted T, @Nullable String> m) { + // BUG: Diagnostic matches: TAINTED_TYPE_VARIABLE + Map<@Tainted T, String> d = m; + d.hashCode(); + } + void taintedEnclosingType(Outer<@Tainted String>.Inner<@Nullable String> src) { + // BUG: Diagnostic matches: TAINTED_ENCLOSING_TYPE + Outer<@Tainted String>.Inner d = src; + d.hashCode(); + } + void customNullable(Map m) { + // BUG: Diagnostic matches: CUSTOM_NULLABLE + Map d = m; + d.hashCode(); + } + """)) + .doTest(); } } From 12d2b7d97cc12885e7b30106fc8d5970ab26e163 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Mon, 30 Nov 2026 00:27:52 +0300 Subject: [PATCH 27/43] Check that applying a possible fix round-trips through NullAway A `possible fix:` line or its Error Prone edit can produce code that does not compile or that NullAway rejects again: the edit for a local is checked only at the reported pseudo-assignment, and the printed type can drop a custom nullable annotation, qualify a local class, or repeat a modifier's annotation. FixRoundTripTests applies every fix of a program, the edits through `-XepPatchChecks` and each `declare as ` line by rewriting that declaration, and compiles the result with NullAway again. After the edits, no generic mismatch may remain on a line naming the rewritten variable; after a text line, none on the reported line and no javac error. The programs these fixes break today are marked as known failures, which fail once they start passing: four for the edit of a local (`List l = make(); take(l);`, a `@Nullable` type argument in the initializer, a rejected reassignment, and a target local that is returned) and seven for the printed type (a custom nullable annotation, local classes outside a static method, and an inner class with a nullable modifier). Assisted-by: Claude Code (claude-opus-5-5) --- .../mismatchmessage/FixRoundTripTests.java | 527 ++++++++++++++++++ 1 file changed, 527 insertions(+) create mode 100644 nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java new file mode 100644 index 0000000000..e751277a51 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java @@ -0,0 +1,527 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import static com.google.common.truth.Truth.assertWithMessage; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.assertThrows; + +import com.google.errorprone.BaseErrorProneJavaCompiler; +import com.google.errorprone.scanner.ScannerSupplier; +import com.sun.source.tree.AnnotationTree; +import com.sun.source.tree.CompilationUnitTree; +import com.sun.source.tree.IdentifierTree; +import com.sun.source.tree.MemberSelectTree; +import com.sun.source.tree.Tree; +import com.sun.source.tree.VariableTree; +import com.sun.source.util.JavacTask; +import com.sun.source.util.SourcePositions; +import com.sun.source.util.TreeScanner; +import com.sun.source.util.Trees; +import com.sun.tools.javac.api.JavacTool; +import com.uber.nullaway.NullAway; +import com.uber.nullaway.generics.JSpecifyJavacConfig; +import java.io.IOException; +import java.io.StringWriter; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import javax.tools.Diagnostic; +import javax.tools.DiagnosticCollector; +import javax.tools.JavaFileObject; +import javax.tools.StandardJavaFileManager; +import org.jspecify.annotations.Nullable; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +/** + * Applying a fix that a generic nullability mismatch message offers yields code that compiles and + * that NullAway accepts where the fix claims it does. The Error Prone edit, applied as {@code + * -XepPatchChecks} applies it, has to leave no generic mismatch on any line that names the + * rewritten variable, since a reader applies it without judging it. A {@code declare as + * } line, applied by writing {@code } in place of the declared type of {@code } + * and of the nullable annotations among its modifiers, has to compile and leave no generic mismatch + * on the line the diagnostic reported; uses elsewhere may still reject it, which is what {@code + * possible} says. + */ +public class FixRoundTripTests { + + @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + /** The first words of every generic nullability mismatch message. */ + private static final String MISMATCH = "incompatible nullability in "; + + private static final Pattern FIX_LINE = Pattern.compile("declare (\\w+) as (.+)$"); + + @Test + public void sourceEditWhoseInitializerRejectsTheRewrite() { + assertKnownFailure( + "fixed by C1 (F45, F77)", + """ + static void take(Collection c) {} + static List make() { + throw new RuntimeException(); + } + void test() { + List l = make(); + take(l); + } + """); + } + + @Test + public void sourceEditWhoseInitializerHasANullableTypeArgument() { + assertKnownFailure( + "fixed by C1 (F45, F77)", + """ + static void take(Collection c) {} + void test() { + List l = new ArrayList<@Nullable String>(); + take(l); + } + """); + } + + @Test + public void sourceEditWhoseReassignmentRejectsTheRewrite() { + assertKnownFailure( + "fixed by C1 (F45, F77)", + """ + static void take(Collection c) {} + static List make() { + throw new RuntimeException(); + } + void test(List init) { + List l = init; + take(l); + l = make(); + } + """); + } + + @Test + public void targetEditOfALocalThatIsReturned() { + assertKnownFailure( + "fixed by C1 (F45, F77)", + """ + Map test(Map m) { + Map declared = m; + return declared; + } + """); + } + + @Test + public void sourceFixWithACustomNullableAnnotation() { + assertKnownFailure( + "fixed by W1-B (F70); enable after merge", + """ + static void take(Map map) {} + void test() { + Map m = new HashMap(); + take(m); + } + """, + CAN_BE_NULL); + } + + @Test + public void targetFixWithACustomNullableAnnotation() { + assertKnownFailure( + "fixed by W1-B (F70); enable after merge", + """ + void test(Map m) { + Map d = m; + d.hashCode(); + } + """, + CAN_BE_NULL); + } + + @Test + public void localClassInAnInstanceMethod() { + assertKnownFailure( + "fixed by W1-B (F71); enable after merge", + """ + void test() { + class Local {} + Local l = new Local(); + Local t = l; + t.hashCode(); + } + """); + } + + @Test + public void localClassInAConstructor() { + assertKnownFailure( + "fixed by W1-B (F71); enable after merge", + """ + Test() { + class Local {} + Local l = new Local(); + Local t = l; + t.hashCode(); + } + """); + } + + @Test + public void localClassInAnInitializer() { + assertKnownFailure( + "fixed by W1-B (F71); enable after merge", + """ + { + class Local {} + Local l = new Local(); + Local t = l; + t.hashCode(); + } + """); + } + + @Test + public void innerClassWithANullableModifier() { + assertKnownFailure( + "fixed by W1-B (F74); enable after merge", + """ + class Inner {} + void test(Inner<@Nullable String> src) { + @Nullable Test.Inner x = src; + if (x != null) { + x.hashCode(); + } + } + """); + } + + @Test + public void innerClassArrayWithANullableModifier() { + assertKnownFailure( + "fixed by W1-B (F74); enable after merge", + """ + class Inner {} + void test(Inner<@Nullable String>[] src) { + @Nullable Test.Inner[] x = src; + x.hashCode(); + } + """); + } + + @Test + public void sourceEditWhoseInitializerAcceptsTheRewrite() { + assertRoundTrip( + """ + static void take(Collection c) {} + void test() { + List l = new ArrayList(); + take(l); + } + """); + } + + @Test + public void localClassInAStaticMethod() { + assertRoundTrip( + """ + static void test() { + class Local {} + Local l = new Local(); + Local t = l; + t.hashCode(); + } + """); + } + + @Test + public void sourceFixOfAParameter() { + assertRoundTrip( + """ + static void take(Collection c) {} + void test(List l) { + take(l); + } + """); + } + + @Test + public void sourceFixOfAField() { + assertRoundTrip( + """ + static void take(Collection c) {} + List field = new ArrayList(); + void test() { + take(field); + } + """); + } + + /** A custom type-use nullable annotation, {@code p.CanBeNull}, and the flag that names it. */ + private static final Extra CAN_BE_NULL = + new Extra( + Map.of( + "p/CanBeNull.java", + """ + package p; + import java.lang.annotation.ElementType; + import java.lang.annotation.Target; + @Target(ElementType.TYPE_USE) + public @interface CanBeNull {} + """), + "import p.CanBeNull;\n", + List.of("-XepOpt:NullAway:CustomNullableAnnotations=p.CanBeNull"), + Set.of("Nullable", "CanBeNull")); + + private static final Extra NONE = new Extra(Map.of(), "", List.of(), Set.of("Nullable")); + + /** + * What a program needs beyond {@code class Test}: other source files by path, imports added to + * {@code Test.java}, javac arguments, and the simple names of the nullable annotations a {@code + * declare} line replaces among the modifiers. + */ + private record Extra( + Map files, + String imports, + List args, + Set nullableAnnotationNames) {} + + private void assertRoundTrip(String members) { + assertRoundTrip(members, NONE); + } + + /** + * Expects {@link #assertRoundTrip} to fail on {@code members}, and fails once it passes, so the + * mark is removed when the fix lands. + */ + private void assertKnownFailure(String reason, String members, Extra... extra) { + assertThrows( + "the fixes now round-trip; remove the mark: " + reason, + AssertionError.class, + () -> assertRoundTrip(members, extra.length == 0 ? NONE : extra[0])); + } + + /** + * Compiles {@code members} as the body of {@code @NullMarked class Test}, expects at least one + * generic nullability mismatch, and applies each fix of each such diagnostic in a copy of the + * program: the Error Prone edits through {@code -XepPatchChecks}, and every {@code declare + * as } line by rewriting the declaration of {@code }. + */ + private void assertRoundTrip(String members, Extra extra) { + String test = extra.imports() + MismatchMessageTestBase.nullMarkedClass(members); + List> original = + compile(write("original", test, extra), extra, false); + assertWithMessage("javac errors in the program\n%s", test).that(errors(original)).isEmpty(); + List> mismatches = mismatches(original); + assertWithMessage("generic nullability mismatches of the program\n%s", test) + .that(mismatches) + .isNotEmpty(); + for (Diagnostic mismatch : mismatches) { + String message = mismatch.getMessage(Locale.ROOT); + for (String line : message.lines().toList()) { + Matcher fix = FIX_LINE.matcher(line.trim()); + if (fix.find()) { + String rewritten = + withDeclaredType(test, fix.group(1), fix.group(2), extra.nullableAnnotationNames()); + List> after = + compile(write("text", rewritten, extra), extra, false); + assertWithMessage( + "javac errors after applying `%s` of the diagnostic\n%s\nto get\n%s", + line.trim(), message, rewritten) + .that(errors(after)) + .isEmpty(); + assertWithMessage( + "generic mismatches on line %s, which the diagnostic reported, after applying" + + " `%s` of the diagnostic\n%s\nto get\n%s", + mismatch.getLineNumber(), line.trim(), message, rewritten) + .that( + mismatches(after).stream() + .filter(d -> d.getLineNumber() == mismatch.getLineNumber()) + .map(d -> d.getMessage(Locale.ROOT)) + .toList()) + .isEmpty(); + } + } + } + Path patched = write("patched", test, extra); + compile(patched, extra, true); + String edited = read(patched.resolve("Test.java")); + if (edited.equals(test)) { + return; + } + List names = + mismatches.stream() + .flatMap(d -> d.getMessage(Locale.ROOT).lines()) + .map(line -> FIX_LINE.matcher(line.trim())) + .filter(Matcher::find) + .map(fix -> fix.group(1)) + .distinct() + .toList(); + List> after = compile(patched, extra, false); + assertWithMessage("javac errors after applying the Error Prone edits to get\n%s", edited) + .that(errors(after)) + .isEmpty(); + List lines = edited.lines().toList(); + assertWithMessage( + "generic mismatches on a line naming %s after applying the Error Prone edits to get\n%s", + names, edited) + .that( + mismatches(after).stream() + .filter( + d -> + names.stream() + .anyMatch( + name -> + Pattern.compile("\\b" + name + "\\b") + .matcher(lines.get((int) d.getLineNumber() - 1)) + .find())) + .map(d -> "line " + d.getLineNumber() + ": " + d.getMessage(Locale.ROOT)) + .toList()) + .isEmpty(); + } + + /** Writes {@code test} as {@code Test.java} and the files of {@code extra} into a new folder. */ + private Path write(String name, String test, Extra extra) { + try { + Path folder = temporaryFolder.newFolder().toPath().resolve(name); + Files.createDirectories(folder); + Files.writeString(folder.resolve("Test.java"), test, UTF_8); + for (Map.Entry file : extra.files().entrySet()) { + Path path = folder.resolve(file.getKey()); + Files.createDirectories(path.getParent()); + Files.writeString(path, file.getValue(), UTF_8); + } + return folder; + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private static String read(Path path) { + try { + return Files.readString(path, UTF_8); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** + * Compiles every Java file under {@code folder} with NullAway in JSpecify mode over + * {@code @NullMarked} code, and with {@code patch}, applies the first fix of each NullAway + * diagnostic to the files in place. + */ + private List> compile( + Path folder, Extra extra, boolean patch) { + List args = new ArrayList<>(); + args.addAll(List.of("-d", folder.resolve("classes").toString(), "-proc:none")); + args.add("-XepOpt:NullAway:OnlyNullMarked=true"); + args.addAll(extra.args()); + if (patch) { + args.addAll(List.of("-XepPatchChecks:NullAway", "-XepPatchLocation:IN_PLACE")); + } + DiagnosticCollector diagnostics = new DiagnosticCollector<>(); + BaseErrorProneJavaCompiler compiler = + new BaseErrorProneJavaCompiler(ScannerSupplier.fromBugCheckerClasses(NullAway.class)); + try (StandardJavaFileManager fileManager = + compiler.getStandardFileManager(diagnostics, Locale.ROOT, UTF_8); + Stream files = Files.walk(folder)) { + List sources = files.filter(path -> path.toString().endsWith(".java")).toList(); + compiler + .getTask( + new StringWriter(), + fileManager, + diagnostics, + JSpecifyJavacConfig.withJSpecifyModeArgs(args), + null, + fileManager.getJavaFileObjectsFromPaths(sources)) + .call(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return diagnostics.getDiagnostics().stream() + .filter(d -> d.getSource() != null && d.getSource().getName().endsWith("Test.java")) + .collect(Collectors.toList()); + } + + private static List> mismatches( + List> diagnostics) { + return diagnostics.stream() + .filter(d -> d.getMessage(Locale.ROOT).contains("[NullAway] " + MISMATCH)) + .toList(); + } + + private static List errors(List> diagnostics) { + return diagnostics.stream() + .filter(d -> d.getKind() == Diagnostic.Kind.ERROR) + .map(d -> "line " + d.getLineNumber() + ": " + d.getMessage(Locale.ROOT)) + .toList(); + } + + /** + * Returns {@code source} with {@code type} written in place of the declared type of the variable + * {@code name} and of the annotations among its modifiers whose simple name is in {@code + * nullableNames}, as a reader applies {@code declare as }. + */ + @SuppressWarnings("removal") // the replacements are missing from the JDKs the tests run on + private static String withDeclaredType( + String source, String name, String type, Set nullableNames) { + JavaFileObject file = + new javax.tools.SimpleJavaFileObject( + java.net.URI.create("string:///Test.java"), JavaFileObject.Kind.SOURCE) { + @Override + public String getCharContent(boolean ignoreEncodingErrors) { + return source; + } + }; + JavacTask task = JavacTool.create().getTask(null, null, null, List.of(), null, List.of(file)); + try { + CompilationUnitTree unit = task.parse().iterator().next(); + SourcePositions positions = Trees.instance(task).getSourcePositions(); + VariableTree[] found = {null}; + new TreeScanner<@Nullable Void, @Nullable Void>() { + @Override + public @Nullable Void visitVariable(VariableTree variable, @Nullable Void unused) { + if (variable.getName().contentEquals(name)) { + assertWithMessage("declarations of %s in\n%s", name, source).that(found[0]).isNull(); + found[0] = variable; + } + return super.visitVariable(variable, null); + } + }.scan(unit, null); + VariableTree declaration = found[0]; + assertWithMessage("declaration of %s in\n%s", name, source).that(declaration).isNotNull(); + Tree typeTree = declaration.getType(); + int start = (int) positions.getStartPosition(unit, typeTree); + int end = (int) positions.getEndPosition(unit, typeTree); + StringBuilder rewritten = new StringBuilder(source); + rewritten.replace(start, end, type); + List annotations = declaration.getModifiers().getAnnotations(); + for (int i = annotations.size() - 1; i >= 0; i--) { + AnnotationTree annotation = annotations.get(i); + Tree annotationType = annotation.getAnnotationType(); + String simpleName = + annotationType instanceof MemberSelectTree select + ? select.getIdentifier().toString() + : ((IdentifierTree) annotationType).getName().toString(); + if (nullableNames.contains(simpleName)) { + int annotationStart = (int) positions.getStartPosition(unit, annotation); + int annotationEnd = (int) positions.getEndPosition(unit, annotation); + while (annotationEnd < rewritten.length() && rewritten.charAt(annotationEnd) == ' ') { + annotationEnd++; + } + rewritten.delete(annotationStart, annotationEnd); + } + } + return rewritten.toString(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +} From f5c6bfe4009c5f2eca8d78e08642ac6ba6b79efa Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Mon, 30 Nov 2026 00:09:20 +0300 Subject: [PATCH 28/43] Offer the source fix of a local only where every value of the local accepts it The source fix of a local was checked only at the reported pseudo-assignment. For `List l = make(); take(l);`, with `make()` returning `List`, the message offered `declare l as List` and the edit wrote it, and NullAway then reported `List l = make();`, with a fix that wrote the old type back. The target-side edit had the same gap at a later read of the local: after `Map declared = m;`, NullAway reported `return declared;`. The source rewrite makes the local's type less nullable, so only the values assigned to the local can reject it. Where the check rejects the rewritten type for the initializer or for a simple assignment to the local, the source fix is not offered; a target fix, where there is one, stays. Where every value is accepted, the fix gets the edit as well. The walk that already indexes the local declarations of the unit records those values, and their paths share the enclosing method's path with the reported site, so a dataflow run keyed on it is reused. The edit, but not the line, is withheld where the type of a value cannot be computed without changing what the check later computes: a lambda, a method reference, a conditional expression, and a generic call or diamond whose inference the check has not run yet, since running it against the rewritten type would cache that result. The variable of an enhanced for loop gets the line and no edit. The target fix gets no edit at all, since the rewritten variable may be read as a source anywhere in its scope. `FixRoundTripTests` applies each fix line and each edit and recompiles: a source fix has to leave no mismatch on any line naming the variable, a target fix none on the reported line. User-visible: A local source whose initializer or an assignment to it rejects the rewritten type gets no `possible fix:` line for itself; where the target can be fixed, the message offers only that fix. A `possible fix:` line for the target type carries no `Did you mean` edit. A `possible fix:` line for a local source carries the edit only where the type of every value assigned to it is known and accepts the rewritten type. Where both fixes are offered, the message lists them under `possible fixes:`, each with its condition: possible fixes: if list never holds null: declare list as List if it may: declare c as Collection Assisted-by: Claude Code (claude-opus-5-5) --- .../nullaway/generics/GenericsChecks.java | 30 ++ .../generics/LocalVariableDeclarations.java | 92 ++++- .../generics/NullabilityMismatchMessage.java | 133 +++++-- .../generics/MismatchMessageWorkTests.java | 12 +- .../mismatchmessage/FixRoundTripTests.java | 187 ++++++---- .../jspecify/mismatchmessage/FixTests.java | 342 +++++++++++------- .../jspecify/mismatchmessage/PathTests.java | 1 - .../mismatchmessage/TargetTypeFixTests.java | 92 ++++- .../mismatchmessage/TraversalCostTests.java | 2 - 9 files changed, 637 insertions(+), 254 deletions(-) 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 604a864438..a97c97b8c2 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -1017,6 +1017,36 @@ public void checkTypeParameterNullnessForAssignability(Tree tree, VisitorState s } } + /** + * Whether the check of {@link #checkTypeParameterNullnessForAssignability} accepts {@code value} + * assigned to a local variable of type {@code localType}, for a type other than the local's + * declared one. + * + * @param localType the type to check the value against + * @param value the path to the initializer of the local or the right-hand side of an assignment + * to it + * @param state the visitor state + * @return {@code null} where the type of {@code value} cannot be computed without changing what + * the check later computes for it: a lambda, a method reference, or a conditional expression, + * which take their types from the target; a generic call or diamond whose inference the check + * has not yet run, since running it against {@code localType} would cache the result for the + * declared type's check; and a value whose type is raw + */ + @Nullable Boolean acceptsValueOfLocal(Type localType, TreePath value, VisitorState state) { + ExpressionTree expression = ASTHelpers.stripParentheses((ExpressionTree) value.getLeaf()); + if (expression instanceof LambdaExpressionTree + || expression instanceof MemberReferenceTree + || expression instanceof ConditionalExpressionTree + || (isCallNeedingInference(expression) + && !inferredTypeVarNullabilityForGenericCalls.containsKey(expression))) { + return null; + } + Type valueType = + getTypeForRhsOfAssignment( + (ExpressionTree) value.getLeaf(), value, localType, true, state, false); + return valueType == null ? null : subtypeParameterNullability(localType, valueType, state); + } + private static boolean isAssignmentToLocalVariable(Tree tree) { return isAssignmentToKind(tree, ElementKind.LOCAL_VARIABLE) || isAssignmentToKind(tree, ElementKind.RESOURCE_VARIABLE); diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java b/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java index ba1638df60..2c21a290d5 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java @@ -5,14 +5,20 @@ import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AnnotatedTypeTree; import com.sun.source.tree.ArrayTypeTree; +import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.CompilationUnitTree; +import com.sun.source.tree.EnhancedForLoopTree; +import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; import com.sun.source.util.TreePathScanner; import com.sun.tools.javac.code.Symbol; +import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.IdentityHashMap; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Consumer; @@ -27,8 +33,9 @@ * declaration it holds; later lookups in the same unit read the index, so a unit with many * diagnostics is walked once rather than once per diagnostic. The same walk notes the declarations * that share their type tree with another variable, as each variable of {@code List a, b;} does, - * or its element type, as {@code a} and {@code b} of {@code List a, b[];} do. {@link #clear} - * drops the index, which otherwise keeps the trees of the unit alive. + * or its element type, as {@code a} and {@code b} of {@code List a, b[];} do, and records the + * values assigned to each local: its initializer and the right-hand side of each {@code l = expr}. + * {@link #clear} drops the index, which otherwise keeps the trees of the unit alive. */ final class LocalVariableDeclarations { @@ -49,6 +56,15 @@ final class LocalVariableDeclarations { /** The declarations of the indexed unit whose element type tree another variable also has. */ private final Set sharingTypeTree = Sets.newIdentityHashSet(); + /** + * The paths to the initializer of each local of the indexed unit and to the right-hand side of + * each simple assignment to it, in source order. A local with neither has no entry. + */ + private final Map> assignedValues = new HashMap<>(); + + /** The variables of the enhanced {@code for} loops of the indexed unit. */ + private final Set loopVariables = new HashSet<>(); + /** * Returns the path to the declaration of {@code variable} in {@code compilationUnit}, or {@code * null} where {@code variable} is not a local variable declared there. @@ -71,6 +87,52 @@ boolean sharesTypeTree(VariableTree declaration) { return sharingTypeTree.contains(declaration); } + /** + * Returns the paths to the values assigned to {@code variable}, a local variable of the + * compilation unit last passed to {@link #find}: its initializer and the right-hand side of each + * simple assignment to it, in source order. Returns {@code null} for the variable of an enhanced + * {@code for} loop, which takes each element of the loop's expression without a tree of its own. + * + *

Each path is rebuilt on {@code site}, a path into the same compilation unit, from the + * deepest tree the two share, so that a path into the method {@code site} is in shares its + * enclosing paths with {@code site}. A dataflow run keyed on the path to that method is then + * reused rather than repeated. + */ + @Nullable List assignedValues(Symbol.VarSymbol variable, TreePath site) { + if (loopVariables.contains(variable)) { + return null; + } + List recorded = assignedValues.getOrDefault(variable, List.of()); + IdentityHashMap siteAncestors = new IdentityHashMap<>(); + for (TreePath path = site; path != null; path = path.getParentPath()) { + siteAncestors.put(path.getLeaf(), path); + } + List rebuilt = new ArrayList<>(recorded.size()); + for (TreePath value : recorded) { + rebuilt.add(rebuild(value, siteAncestors)); + } + return rebuilt; + } + + /** + * Returns a path with the leaves of {@code path} whose enclosing paths, from the deepest tree + * {@code path} shares with {@code siteAncestors}, are those of {@code siteAncestors}. Both paths + * start at the same compilation unit, so they share at least its tree. + */ + private static TreePath rebuild(TreePath path, IdentityHashMap siteAncestors) { + List below = new ArrayList<>(); + TreePath shared = path; + while (!siteAncestors.containsKey(shared.getLeaf())) { + below.add(shared.getLeaf()); + shared = shared.getParentPath(); + } + TreePath result = siteAncestors.get(shared.getLeaf()); + for (int i = below.size() - 1; i >= 0; i--) { + result = new TreePath(result, below.get(i)); + } + return result; + } + /** * Returns {@code typeTree} without the array and annotation trees around its element type. javac * gives each variable of one declaration the same element type tree and wraps it in an array tree @@ -93,6 +155,8 @@ void clear() { paths.clear(); firstByTypeTree.clear(); sharingTypeTree.clear(); + assignedValues.clear(); + loopVariables.clear(); } private void index(CompilationUnitTree compilationUnit) { @@ -116,9 +180,33 @@ private void index(CompilationUnitTree compilationUnit) { sharingTypeTree.add(variable); } } + ExpressionTree initializer = variable.getInitializer(); + if (initializer != null) { + recordValue(symbol, initializer); + } + // a loop body cannot be a declaration, so a declaration under the loop is its variable + if (getCurrentPath().getParentPath().getLeaf() instanceof EnhancedForLoopTree) { + loopVariables.add(symbol); + } } return super.visitVariable(variable, null); } + + @Override + public @Nullable Void visitAssignment(AssignmentTree assignment, @Nullable Void unused) { + Symbol symbol = ASTHelpers.getSymbol(assignment.getVariable()); + if (symbol != null && symbol.getKind() == ElementKind.LOCAL_VARIABLE) { + recordValue(symbol, assignment.getExpression()); + } + return super.visitAssignment(assignment, null); + } + + // records the path to value, a child of the current tree, assigned to local + private void recordValue(Symbol local, ExpressionTree value) { + assignedValues + .computeIfAbsent(local, unused -> new ArrayList<>()) + .add(new TreePath(getCurrentPath(), value)); + } }.scan(compilationUnit, 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 index 69ef3b3aa6..2c1501b65e 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -111,13 +111,22 @@ * source variable with explicit wildcard bounds, or the target variable with {@code @Nullable} * added. Each candidate is checked before it is printed: it 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 ?}. Where the declaration is a local variable of the - * compilation unit being analyzed, other than a pattern or resource variable, writes its type out - * before the name, and declares no other variable, the line comes with an Error Prone fix that - * makes the edit, except in a run that suggests suppressions, which asks for the suppression - * instead. A parameter or a field gets the line without the edit: its type is a contract that - * callers, overriders, and other assignments rely on, and the check that accepts the rewrite - * consults none of them. + * accepts may still print {@code capture of ?}. Where both candidates pass, the message lists them + * under {@code possible fixes}, the source first, each with the condition under which it is the + * right one. + * + *

The source fix of a local variable of the compilation unit being analyzed is checked once + * more: the rewrite makes the local's type less nullable, so the values assigned to it, its + * initializer and the right-hand side of each assignment to it, are the only pseudo-assignments it + * can break. Where the check rejects one of them against the rewritten type, the source fix is not + * offered. Only the source fix comes with an Error Prone fix that makes the edit, and only where + * the check accepts every one of those values, the local is not a pattern, resource, or enhanced + * {@code for} variable, and its declaration writes its type out before the name and declares no + * other variable. A run that suggests suppressions asks for the suppression instead. A parameter or + * a field gets the line without the edit: its type is a contract that callers, overriders, and + * other assignments rely on, and the check that accepts the rewrite consults none of them. The + * target fix never gets the edit, since the rewritten variable may be read as a source anywhere in + * its scope. * *

The two candidates differ in what they presume. Writing an explicit bound on a wildcard the * source declaration already writes is a mechanical fix of that wildcard, so it is offered wherever @@ -260,50 +269,104 @@ Report build( String.format( "%s\n and %d more, not listed", separator, mismatches.size() - listed.size())); } - List fixes = new ArrayList<>(); Symbol.VarSymbol sourceVariable = sourceVariable(sourceExpression, sourceType); - if (sourceVariable != null) { - Type rewrittenSourceType = sourceTypeFix(targetType, sourceType, mismatches); - if (rewrittenSourceType != null) { - message.append(separator); - appendFix(message, fixes, sourceVariable, rewrittenSourceType); - separator = ""; + Type rewrittenSourceType = + sourceVariable == null ? null : sourceTypeFix(targetType, sourceType, mismatches); + TreePath sourceDeclaration = null; + Boolean valuesAccept = null; + if (sourceVariable != null && rewrittenSourceType != null) { + // the type of a parameter or a field is a contract that callers, overriders, and other + // assignments rely on, and the check that accepts the rewrite consults none of them + sourceDeclaration = + checks + .localVariableDeclarations() + .find(sourceVariable, state.getPath().getCompilationUnit()); + if (sourceDeclaration != null) { + valuesAccept = valuesAccept(sourceVariable, rewrittenSourceType); + if (Boolean.FALSE.equals(valuesAccept)) { + // a value the local already holds rejects the rewrite, so the fix would only move the + // error + rewrittenSourceType = null; + } } } - if (targetTypeDeclaration != null) { - Type rewrittenTargetType = targetTypeFix(targetType, sourceType, mismatches); - if (rewrittenTargetType != null) { - message.append(separator); - appendFix(message, fixes, ASTHelpers.getSymbol(targetTypeDeclaration), rewrittenTargetType); + Symbol.VarSymbol targetVariable = + targetTypeDeclaration == null ? null : ASTHelpers.getSymbol(targetTypeDeclaration); + Type rewrittenTargetType = + targetVariable == null ? null : targetTypeFix(targetType, sourceType, mismatches); + List fixes = new ArrayList<>(); + if (sourceVariable != null && rewrittenSourceType != null) { + message.append(separator); + if (targetVariable != null && rewrittenTargetType != null) { + message.append( + String.format( + "\n possible fixes:\n if %s never holds null: %s\n if it may: %s", + sourceVariable.getSimpleName(), + declaration(sourceVariable, rewrittenSourceType), + declaration(targetVariable, rewrittenTargetType))); + } else { + message + .append("\n possible fix: ") + .append(declaration(sourceVariable, rewrittenSourceType)); + } + if (sourceDeclaration != null && Boolean.TRUE.equals(valuesAccept)) { + addSourceFixEdit(fixes, sourceDeclaration, rewrittenSourceType); } + } else if (targetVariable != null && rewrittenTargetType != null) { + // the target's uses as a source can be anywhere, and the check that accepts the rewrite + // consults none of them, so the fix gets no edit + message + .append(separator) + .append("\n possible fix: ") + .append(declaration(targetVariable, rewrittenTargetType)); } return new Report(message.toString(), fixes); } + /** Returns {@code declare as }, the text of a fix. */ + private String declaration(Symbol.VarSymbol variable, Type type) { + return String.format( + "declare %s as %s", + variable.getSimpleName(), GenericsChecks.prettyTypeForError(type, state)); + } + /** - * Appends the {@code possible fix:} line that declares {@code variable} with {@code type}, and - * adds the edit to {@code fixes} where {@code variable} is a local variable of the compilation - * unit being analyzed, other than a pattern or resource variable, its declaration writes its type + * Whether the check accepts against {@code type} every value assigned to {@code variable}, a + * local variable of the compilation unit being analyzed: its initializer and the right-hand side + * of each assignment to it. Returns {@code false} where one of them rejects {@code type}, and + * otherwise {@code null} where the type of one cannot be computed or {@code variable} is the + * variable of an enhanced {@code for} loop. + */ + private @Nullable Boolean valuesAccept(Symbol.VarSymbol variable, Type type) { + List values = + checks.localVariableDeclarations().assignedValues(variable, state.getPath()); + if (values == null) { + return null; + } + Boolean result = true; + for (TreePath value : values) { + Boolean accepted = checks.acceptsValueOfLocal(type, value, state.withPath(value)); + if (Boolean.FALSE.equals(accepted)) { + return false; + } + if (accepted == null) { + result = null; + } + } + return result; + } + + /** + * Adds to {@code fixes} the edit that declares the local variable at {@code declarationPath}, + * whose values all accept {@code type}, with {@code type}, where the declaration writes its type * out before the name and declares no other variable, and the run does not suggest suppressions. */ - private void appendFix( - StringBuilder message, List fixes, Symbol.VarSymbol variable, Type type) { - message.append( - String.format( - "\n possible fix: declare %s as %s", - variable.getSimpleName(), GenericsChecks.prettyTypeForError(type, state))); + private void addSourceFixEdit(List fixes, TreePath declarationPath, Type type) { if (config.suggestSuppressions()) { // the run asks for the suppression ErrorBuilder adds after these fixes, and patching // applies only the first fix of a diagnostic return; } - // the type of a parameter or a field is a contract that callers, overriders, and other - // assignments rely on, and the check that accepts the rewrite consults none of them - TreePath declarationPath = - checks.localVariableDeclarations().find(variable, state.getPath().getCompilationUnit()); - if (declarationPath == null) { - return; - } VariableTree declaration = (VariableTree) declarationPath.getLeaf(); Tree typeTree = declaration.getType(); if (typeTree == null || ASTHelpers.hasImplicitType(declaration, state)) { diff --git a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java index e379296c1a..8de6f57c47 100644 --- a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java @@ -22,27 +22,25 @@ public void oneWalkOfTheCompilationUnitServesEveryLocalFix() { List walks = walksWhileCompiling( """ + import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.jspecify.annotations.NullMarked; @NullMarked class Test { static void take(Collection c) {} - static List make() { - throw new RuntimeException(); - } void assignment() { - List l = make(); - // BUG: Diagnostic contains: possible fix: declare l as List + List l = new ArrayList(); + // BUG: Diagnostic contains: declare l as List Collection c = l; } void argument() { - List l = make(); + List l = new ArrayList(); // BUG: Diagnostic contains: possible fix: declare l as List take(l); } Collection returned() { - List l = make(); + List l = new ArrayList(); // BUG: Diagnostic contains: possible fix: declare l as List return l; } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java index e751277a51..29420ebc07 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java @@ -44,13 +44,14 @@ /** * Applying a fix that a generic nullability mismatch message offers yields code that compiles and - * that NullAway accepts where the fix claims it does. The Error Prone edit, applied as {@code - * -XepPatchChecks} applies it, has to leave no generic mismatch on any line that names the - * rewritten variable, since a reader applies it without judging it. A {@code declare as - * } line, applied by writing {@code } in place of the declared type of {@code } - * and of the nullable annotations among its modifiers, has to compile and leave no generic mismatch - * on the line the diagnostic reported; uses elsewhere may still reject it, which is what {@code - * possible} says. + * that NullAway accepts where the fix claims it does. A {@code declare as } line is + * applied by writing {@code } in place of the declared type of {@code } and of the + * nullable annotations among its modifiers, and the Error Prone edit as {@code -XepPatchChecks} + * applies it. A fix of the source, as a line or as the edit, has to leave no generic mismatch on + * any line that names the rewritten variable: its declaration, its initializer, every assignment to + * it, and the reported read. A fix of the target, the variable declared on the reported line, has + * to leave none on that line; a later read of the variable may still reject it, which is what + * {@code possible} says. */ public class FixRoundTripTests { @@ -63,8 +64,7 @@ public class FixRoundTripTests { @Test public void sourceEditWhoseInitializerRejectsTheRewrite() { - assertKnownFailure( - "fixed by C1 (F45, F77)", + assertRoundTrip( """ static void take(Collection c) {} static List make() { @@ -79,8 +79,7 @@ void test() { @Test public void sourceEditWhoseInitializerHasANullableTypeArgument() { - assertKnownFailure( - "fixed by C1 (F45, F77)", + assertRoundTrip( """ static void take(Collection c) {} void test() { @@ -92,8 +91,7 @@ void test() { @Test public void sourceEditWhoseReassignmentRejectsTheRewrite() { - assertKnownFailure( - "fixed by C1 (F45, F77)", + assertRoundTrip( """ static void take(Collection c) {} static List make() { @@ -109,8 +107,7 @@ void test(List init) { @Test public void targetEditOfALocalThatIsReturned() { - assertKnownFailure( - "fixed by C1 (F45, F77)", + assertRoundTrip( """ Map test(Map m) { Map declared = m; @@ -190,8 +187,7 @@ class Local {} @Test public void innerClassWithANullableModifier() { - assertKnownFailure( - "fixed by W1-B (F74); enable after merge", + assertRoundTrip( """ class Inner {} void test(Inner<@Nullable String> src) { @@ -204,9 +200,22 @@ void test(Inner<@Nullable String> src) { } @Test - public void innerClassArrayWithANullableModifier() { + public void innerClassSourceWithANullableModifier() { assertKnownFailure( "fixed by W1-B (F74); enable after merge", + """ + class Inner {} + static void take(@Nullable Inner i) {} + void test() { + @Nullable Test.Inner x = new Inner(); + take(x); + } + """); + } + + @Test + public void innerClassArrayWithANullableModifier() { + assertRoundTrip( """ class Inner {} void test(Inner<@Nullable String>[] src) { @@ -328,8 +337,9 @@ private void assertRoundTrip(String members, Extra extra) { for (String line : message.lines().toList()) { Matcher fix = FIX_LINE.matcher(line.trim()); if (fix.find()) { - String rewritten = - withDeclaredType(test, fix.group(1), fix.group(2), extra.nullableAnnotationNames()); + String name = fix.group(1); + Declaration declaration = declaration(test, name); + String rewritten = declaration.withType(fix.group(2), extra.nullableAnnotationNames()); List> after = compile(write("text", rewritten, extra), extra, false); assertWithMessage( @@ -337,16 +347,25 @@ private void assertRoundTrip(String members, Extra extra) { line.trim(), message, rewritten) .that(errors(after)) .isEmpty(); - assertWithMessage( - "generic mismatches on line %s, which the diagnostic reported, after applying" - + " `%s` of the diagnostic\n%s\nto get\n%s", - mismatch.getLineNumber(), line.trim(), message, rewritten) - .that( - mismatches(after).stream() - .filter(d -> d.getLineNumber() == mismatch.getLineNumber()) - .map(d -> d.getMessage(Locale.ROOT)) - .toList()) - .isEmpty(); + if (declaration.line() == mismatch.getLineNumber()) { + assertWithMessage( + "generic mismatches on line %s, which the diagnostic reported, after applying" + + " `%s` of the diagnostic\n%s\nto get\n%s", + mismatch.getLineNumber(), line.trim(), message, rewritten) + .that( + mismatches(after).stream() + .filter(d -> d.getLineNumber() == mismatch.getLineNumber()) + .map(d -> d.getMessage(Locale.ROOT)) + .toList()) + .isEmpty(); + } else { + assertWithMessage( + "generic mismatches on a line naming %s after applying `%s` of the" + + " diagnostic\n%s\nto get\n%s", + name, line.trim(), message, rewritten) + .that(mismatchesNaming(after, rewritten, List.of(name))) + .isEmpty(); + } } } } @@ -368,25 +387,33 @@ private void assertRoundTrip(String members, Extra extra) { assertWithMessage("javac errors after applying the Error Prone edits to get\n%s", edited) .that(errors(after)) .isEmpty(); - List lines = edited.lines().toList(); assertWithMessage( "generic mismatches on a line naming %s after applying the Error Prone edits to get\n%s", names, edited) - .that( - mismatches(after).stream() - .filter( - d -> - names.stream() - .anyMatch( - name -> - Pattern.compile("\\b" + name + "\\b") - .matcher(lines.get((int) d.getLineNumber() - 1)) - .find())) - .map(d -> "line " + d.getLineNumber() + ": " + d.getMessage(Locale.ROOT)) - .toList()) + .that(mismatchesNaming(after, edited, names)) .isEmpty(); } + /** + * Returns the generic mismatches among {@code diagnostics} on a line of {@code source} that names + * one of {@code names}, each with its line number. + */ + private static List mismatchesNaming( + List> diagnostics, String source, List names) { + List lines = source.lines().toList(); + return mismatches(diagnostics).stream() + .filter( + d -> + names.stream() + .anyMatch( + name -> + Pattern.compile("\\b" + name + "\\b") + .matcher(lines.get((int) d.getLineNumber() - 1)) + .find())) + .map(d -> "line " + d.getLineNumber() + ": " + d.getMessage(Locale.ROOT)) + .toList(); + } + /** Writes {@code test} as {@code Test.java} and the files of {@code extra} into a new folder. */ private Path write(String name, String test, Extra extra) { try { @@ -465,13 +492,40 @@ private static List errors(List> di } /** - * Returns {@code source} with {@code type} written in place of the declared type of the variable - * {@code name} and of the annotations among its modifiers whose simple name is in {@code - * nullableNames}, as a reader applies {@code declare as }. + * The declaration of a variable in {@code source}: its line, 1-based, and the positions of its + * type tree and of the nullable annotations among its modifiers. */ + private record Declaration( + String source, long line, int typeStart, int typeEnd, Map annotations) { + + /** + * Returns {@link #source} with {@code type} written in place of the declared type and of the + * annotations whose simple name is in {@code nullableNames}, as a reader applies {@code declare + * as }. + */ + String withType(String type, Set nullableNames) { + StringBuilder rewritten = new StringBuilder(source); + rewritten.replace(typeStart, typeEnd, type); + List removed = + annotations.entrySet().stream() + .filter(annotation -> nullableNames.contains(annotation.getKey())) + .map(Map.Entry::getValue) + .sorted((a, b) -> Integer.compare(b[0], a[0])) + .toList(); + for (int[] span : removed) { + int end = span[1]; + while (end < rewritten.length() && rewritten.charAt(end) == ' ') { + end++; + } + rewritten.delete(span[0], end); + } + return rewritten.toString(); + } + } + + /** Returns the one declaration of a variable named {@code name} in {@code source}. */ @SuppressWarnings("removal") // the replacements are missing from the JDKs the tests run on - private static String withDeclaredType( - String source, String name, String type, Set nullableNames) { + private static Declaration declaration(String source, String name) { JavaFileObject file = new javax.tools.SimpleJavaFileObject( java.net.URI.create("string:///Test.java"), JavaFileObject.Kind.SOURCE) { @@ -495,31 +549,30 @@ public String getCharContent(boolean ignoreEncodingErrors) { return super.visitVariable(variable, null); } }.scan(unit, null); - VariableTree declaration = found[0]; - assertWithMessage("declaration of %s in\n%s", name, source).that(declaration).isNotNull(); - Tree typeTree = declaration.getType(); - int start = (int) positions.getStartPosition(unit, typeTree); - int end = (int) positions.getEndPosition(unit, typeTree); - StringBuilder rewritten = new StringBuilder(source); - rewritten.replace(start, end, type); - List annotations = declaration.getModifiers().getAnnotations(); - for (int i = annotations.size() - 1; i >= 0; i--) { - AnnotationTree annotation = annotations.get(i); + VariableTree variable = found[0]; + assertWithMessage("declaration of %s in\n%s", name, source).that(variable).isNotNull(); + Tree typeTree = variable.getType(); + Map annotations = new java.util.HashMap<>(); + for (AnnotationTree annotation : variable.getModifiers().getAnnotations()) { Tree annotationType = annotation.getAnnotationType(); String simpleName = annotationType instanceof MemberSelectTree select ? select.getIdentifier().toString() : ((IdentifierTree) annotationType).getName().toString(); - if (nullableNames.contains(simpleName)) { - int annotationStart = (int) positions.getStartPosition(unit, annotation); - int annotationEnd = (int) positions.getEndPosition(unit, annotation); - while (annotationEnd < rewritten.length() && rewritten.charAt(annotationEnd) == ' ') { - annotationEnd++; - } - rewritten.delete(annotationStart, annotationEnd); - } + annotations.put( + simpleName, + new int[] { + (int) positions.getStartPosition(unit, annotation), + (int) positions.getEndPosition(unit, annotation) + }); } - return rewritten.toString(); + int typeStart = (int) positions.getStartPosition(unit, typeTree); + return new Declaration( + source, + unit.getLineMap().getLineNumber(positions.getStartPosition(unit, variable)), + typeStart, + (int) positions.getEndPosition(unit, typeTree), + annotations); } catch (IOException e) { throw new UncheckedIOException(e); } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java index 72ec07c6ce..b3f5f1878c 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java @@ -12,10 +12,12 @@ import org.junit.rules.TemporaryFolder; /** - * A {@code possible fix:} line comes with an Error Prone fix that rewrites the type the named - * declaration writes, where that declaration is a local variable of the compilation unit being - * analyzed, other than a pattern or resource variable, writes its type out before the name, and - * declares no other variable, and the run does not suggest suppressions. + * A {@code possible fix:} line that rewrites the source comes with an Error Prone fix that rewrites + * the type the named declaration writes, where that declaration is a local variable of the + * compilation unit being analyzed, other than a pattern, resource, or enhanced {@code for} + * variable, writes its type out before the name, declares no other variable, and gets only values + * the check accepts against the rewritten type, and the run does not suggest suppressions. A fix of + * the target type gets no edit. */ public class FixTests { @@ -47,14 +49,11 @@ class Test { static List<@Nullable String> get() { throw new RuntimeException(); } - static List make() { - throw new RuntimeException(); - } void assignment() { List l = get(); } Collection argument() { - List list = make(); + List list = new ArrayList(); List result = new ArrayList<>(); result.addAll(list); return result; @@ -74,16 +73,13 @@ class Test { static List<@Nullable String> get() { throw new RuntimeException(); } - static List make() { - throw new RuntimeException(); - } void assignment() { @SuppressWarnings("NullAway") List l = get(); } @SuppressWarnings("NullAway") Collection argument() { - List list = make(); + List list = new ArrayList(); List result = new ArrayList<>(); result.addAll(list); return result; @@ -99,6 +95,7 @@ public void theEditRewritesOnlyALocalVariable() throws IOException { .addInputLines( "Test.java", """ + import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; @@ -147,7 +144,7 @@ void resource() { } } void local() { - List l = make(); + List l = new ArrayList(); take(l); } } @@ -155,6 +152,7 @@ void local() { .addOutputLines( "Test.java", """ + import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; @@ -203,7 +201,7 @@ void resource() { } } void local() { - List l = make(); + List l = new ArrayList(); take(l); } } @@ -212,47 +210,209 @@ void local() { } @Test - public void theTargetTypeFixImportsTheNullableAnnotationItAdds() throws IOException { + public void theSourceFixEditIsAttachedOnlyWhereEveryValueAssignedToTheLocalAcceptsIt() + throws IOException { makeHelper() .addInputLines( - "Lib.java", + "Test.java", """ + import java.util.ArrayList; + import java.util.Collection; import java.util.List; + import java.util.function.Supplier; import org.jspecify.annotations.NullMarked; - import org.jspecify.annotations.Nullable; @NullMarked - class Lib { - static List<@Nullable String> get() { + class Test { + static void take(Collection c) {} + static void takeSupplier(Supplier s) {} + static List make() { throw new RuntimeException(); } + static String name() { + return "a"; + } + void initializerRejects() { + List l = make(); + take(l); + } + void initializerAccepts() { + List l = new ArrayList(); + take(l); + } + void reassignmentRejects() { + List l = new ArrayList(); + take(l); + l = make(); + } + void reassignmentAccepts() { + List l = new ArrayList(); + take(l); + l = new ArrayList(); + } + void nullInitializer() { + List l = null; + l = new ArrayList(); + take(l); + } + void inferredCallBeforeTheReport() { + List l = List.of("a"); + take(l); + } + void inferredCallAfterTheReport() { + List l = new ArrayList(); + take(l); + l = List.of("a"); + } + void conditional(boolean b, List x, List y) { + List l = b ? x : y; + take(l); + } + void lambda() { + Supplier s = () -> "a"; + takeSupplier(s); + } + void methodReference() { + Supplier s = Test::name; + takeSupplier(s); + } + void loopVariable(List> lists) { + for (List l : lists) { + take(l); + } + } } """) - .expectUnchanged() + .addOutputLines( + "Test.java", + """ + import java.util.ArrayList; + import java.util.Collection; + import java.util.List; + import java.util.function.Supplier; + import org.jspecify.annotations.NullMarked; + @NullMarked + class Test { + static void take(Collection c) {} + static void takeSupplier(Supplier s) {} + static List make() { + throw new RuntimeException(); + } + static String name() { + return "a"; + } + void initializerRejects() { + List l = make(); + take(l); + } + void initializerAccepts() { + List l = new ArrayList(); + take(l); + } + void reassignmentRejects() { + List l = new ArrayList(); + take(l); + l = make(); + } + void reassignmentAccepts() { + List l = new ArrayList(); + take(l); + l = new ArrayList(); + } + void nullInitializer() { + List l = null; + l = new ArrayList(); + take(l); + } + void inferredCallBeforeTheReport() { + List l = List.of("a"); + take(l); + } + void inferredCallAfterTheReport() { + List l = new ArrayList(); + take(l); + l = List.of("a"); + } + void conditional(boolean b, List x, List y) { + List l = b ? x : y; + take(l); + } + void lambda() { + Supplier s = () -> "a"; + takeSupplier(s); + } + void methodReference() { + Supplier s = Test::name; + takeSupplier(s); + } + void loopVariable(List> lists) { + for (List l : lists) { + take(l); + } + } + } + """) + .doTest(); + } + + @Test + public void theTargetTypeFixCarriesNoEdit() throws IOException { + makeHelper() .addInputLines( "Test.java", """ + import java.util.ArrayList; + import java.util.Collection; import java.util.List; + import java.util.Map; import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; @NullMarked class Test { - void test() { - List l = Lib.get(); + static void take(Collection c) {} + static List<@Nullable String> get() { + throw new RuntimeException(); + } + Map targetReadByAReturn(Map m) { + Map declared = m; + return declared; + } + void targetNotReadAsASource() { + List l = get(); l.hashCode(); } + void sourceFix() { + List l = new ArrayList(); + take(l); + } } """) .addOutputLines( "Test.java", """ + import java.util.ArrayList; + import java.util.Collection; import java.util.List; + import java.util.Map; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked class Test { - void test() { - List<@Nullable String> l = Lib.get(); + static void take(Collection c) {} + static List<@Nullable String> get() { + throw new RuntimeException(); + } + Map targetReadByAReturn(Map m) { + Map declared = m; + return declared; + } + void targetNotReadAsASource() { + List l = get(); l.hashCode(); } + void sourceFix() { + List l = new ArrayList(); + take(l); + } } """) .doTest(); @@ -273,10 +433,10 @@ public void theSourceFixKeepsEveryNullableAnnotationTheDeclarationWrites() throw class Test { static void take(Collection c) {} static void takeMap(Map m) {} - static @Nullable List list() { + static @Nullable List list() { throw new RuntimeException(); } - static @Nullable Map map() { + static @Nullable Map map() { throw new RuntimeException(); } void modifier() { @@ -317,10 +477,10 @@ void modifierAfterAnotherAnnotation() { class Test { static void take(Collection c) {} static void takeMap(Map m) {} - static @Nullable List list() { + static @Nullable List list() { throw new RuntimeException(); } - static @Nullable Map map() { + static @Nullable Map map() { throw new RuntimeException(); } void modifier() { @@ -352,72 +512,6 @@ void modifierAfterAnotherAnnotation() { .doTest(); } - @Test - public void theTargetTypeFixWritesAnImplicitBoundAndAnInnerClassAsJava() throws IOException { - makeHelper() - .addInputLines( - "Outer.java", - """ - import org.jspecify.annotations.NullMarked; - import org.jspecify.annotations.Nullable; - @NullMarked - class Outer { - class Inner {} - } - """) - .expectUnchanged() - .addInputLines( - "Test.java", - """ - import java.util.Collection; - import java.util.List; - import org.jspecify.annotations.NullMarked; - @NullMarked - class Test { - static List list() { - throw new RuntimeException(); - } - static Outer<@org.jspecify.annotations.Nullable String>.Inner inner() { - throw new RuntimeException(); - } - void implicitBound(List list) { - Collection c = list; - c.hashCode(); - } - void innerClass() { - Outer.Inner d = inner(); - d.hashCode(); - } - } - """) - .addOutputLines( - "Test.java", - """ - import java.util.Collection; - import java.util.List; - import org.jspecify.annotations.NullMarked; - import org.jspecify.annotations.Nullable; - @NullMarked - class Test { - static List list() { - throw new RuntimeException(); - } - static Outer<@org.jspecify.annotations.Nullable String>.Inner inner() { - throw new RuntimeException(); - } - void implicitBound(List list) { - Collection c = list; - c.hashCode(); - } - void innerClass() { - Outer<@Nullable String>.Inner d = inner(); - d.hashCode(); - } - } - """) - .doTest(); - } - @Test public void noEditForADeclarationInAnotherCompilationUnit() throws IOException { makeHelper() @@ -478,51 +572,43 @@ void test() { @Test public void theFixPutsTheAnnotationBeforeTheLastSegmentOfAQualifiedName() throws IOException { makeHelper() - .addInputLines( - "Lib.java", - """ - import java.util.List; - import java.util.Map; - import org.jspecify.annotations.NullMarked; - import org.jspecify.annotations.Nullable; - @NullMarked - class Lib { - static List> entries() { - throw new RuntimeException(); - } - static java.util.List> lists() { - throw new RuntimeException(); - } - } - """) - .expectUnchanged() .addInputLines( "Test.java", """ + import java.util.HashMap; import java.util.Map; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked class Test { static class List {} + static void takeEntries(Map> m) {} + static void takeLists(Map> m) {} void test() { - java.util.List> nested = Lib.entries(); - java.util.List> clashing = Lib.lists(); + Map> nested = new HashMap>(); + takeEntries(nested); + Map> clashing = new HashMap>(); + takeLists(clashing); } } """) .addOutputLines( "Test.java", """ + import java.util.HashMap; import java.util.Map; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @NullMarked class Test { static class List {} + static void takeEntries(Map> m) {} + static void takeLists(Map> m) {} void test() { - java.util.List> nested = Lib.entries(); - java.util.List> clashing = Lib.lists(); + Map> nested = new HashMap>(); + takeEntries(nested); + Map> clashing = new HashMap>(); + takeLists(clashing); } } """) @@ -543,27 +629,27 @@ public void noEditForADeclarationOfSeveralVariables() throws IOException { class Test { static void take(Collection c) {} void several() { - List first = new ArrayList<>(), second = new ArrayList<>(); + List first = new ArrayList(), second = new ArrayList(); take(first); take(second); } void loop() { - for (List first = new ArrayList<>(), second = first; ; ) { + for (List first = new ArrayList(), second = first; ; ) { take(first); } } void oldStyleCase(int k) { switch (k) { case 1: - List first = new ArrayList<>(), second = new ArrayList<>(); + List first = new ArrayList(), second = new ArrayList(); take(first); break; default: } } void besideSeveral() { - List first = new ArrayList<>(), second = new ArrayList<>(); - List alone = first; + List first = new ArrayList(), second = new ArrayList(); + List alone = new ArrayList(); take(alone); } } @@ -579,27 +665,27 @@ void besideSeveral() { class Test { static void take(Collection c) {} void several() { - List first = new ArrayList<>(), second = new ArrayList<>(); + List first = new ArrayList(), second = new ArrayList(); take(first); take(second); } void loop() { - for (List first = new ArrayList<>(), second = first; ; ) { + for (List first = new ArrayList(), second = first; ; ) { take(first); } } void oldStyleCase(int k) { switch (k) { case 1: - List first = new ArrayList<>(), second = new ArrayList<>(); + List first = new ArrayList(), second = new ArrayList(); take(first); break; default: } } void besideSeveral() { - List first = new ArrayList<>(), second = new ArrayList<>(); - List alone = first; + List first = new ArrayList(), second = new ArrayList(); + List alone = new ArrayList(); take(alone); } } @@ -620,10 +706,10 @@ public void noEditForADeclarationWithBracketsAfterTheName() throws IOException { class Test { static void take(List[] c) {} static void takeOne(Collection c) {} - static List[] many() { + static List[] many() { throw new RuntimeException(); } - static List one() { + static List one() { throw new RuntimeException(); } void bracketsAfterTheName() { 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 index 0ec1bf6919..03a3251e83 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java @@ -259,7 +259,6 @@ public void aCapturedSourceIsComparedThroughItsUpperBound() { target: List ^^^^^^ possible fix: declare l as List<@Nullable String> - Did you mean 'List<@Nullable String> l = wl.get(0);'? """, """ void test(List> wl) { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java index abc2ca8914..4d0ca89b93 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java @@ -8,7 +8,7 @@ * type with the nullness of the source. It appears where the diagnostic points at the declaration * that writes the target type, a local variable declaration, and not at a call, an assignment, or a * return, whose target type is written somewhere else. It is also withheld where printing it would - * drop a type-use annotation. {@link FixTests} checks the edit the fix makes. + * drop a type-use annotation. The fix carries no Error Prone edit, which {@link FixTests} checks. */ public class TargetTypeFixTests extends MismatchMessageTestBase { @@ -27,8 +27,7 @@ public void theFixIsOfferedOnlyWhereTheDiagnosticPointsAtTheTargetTypeDeclaratio Map.of( "DECLARATION", MAP_VALUES_MESSAGE - + " possible fix: declare declared as Map\n" - + " Did you mean 'Map declared = m;'?\n", + + " possible fix: declare declared as Map\n", "CALL", MAP_VALUES_MESSAGE, "ASSIGNMENT", @@ -61,6 +60,81 @@ Map returned(Map m """); } + @Test + public void aMismatchFixableOnEitherSideListsBothFixesUnlessAValueOfTheSourceRejectsItsFix() { + assertMessages( + Map.of( + "BOTH", + """ + incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: List + ^ + target: Collection + ^^^^^^ + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + possible fixes: + if list never holds null: declare list as List + if it may: declare c as Collection + Did you mean 'List list = new ArrayList();'? + """, + "BOTH_WITHOUT_EDIT", + """ + incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: List + ^ + target: Collection + ^^^^^^ + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + possible fixes: + if list never holds null: declare list as List + if it may: declare c as Collection + """, + "TARGET_ONLY", + """ + incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: List + ^ + target: Collection + ^^^^^^ + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + possible fix: declare c as Collection + """), + """ + static List make() { + throw new RuntimeException(); + } + void valuesAcceptTheSourceFix() { + List list = new ArrayList(); + // BUG: Diagnostic matches: BOTH + Collection c = list; + c.hashCode(); + } + void aValueOfUnknownTypeKeepsTheSourceFixWithoutItsEdit(boolean flag, List raw) { + List list = flag ? new ArrayList() : new ArrayList(); + // BUG: Diagnostic matches: BOTH_WITHOUT_EDIT + Collection c = list; + c.hashCode(); + List fromRaw = raw; + // BUG: Diagnostic contains: if fromRaw never holds null: declare fromRaw as List + Collection d = fromRaw; + d.hashCode(); + } + void aLoopVariableKeepsTheSourceFixWithoutItsEdit(List> lists) { + for (List list : lists) { + // BUG: Diagnostic matches: BOTH_WITHOUT_EDIT + Collection c = list; + c.hashCode(); + } + } + void initializerRejectsTheSourceFix() { + List list = make(); + // BUG: Diagnostic matches: TARGET_ONLY + Collection c = list; + c.hashCode(); + } + """); + } + @Test public void theFixIsTheDeclaredTypeNotAnInstantiatedSupertype() { assertMessage( @@ -71,7 +145,6 @@ public void theFixIsTheDeclaredTypeNotAnInstantiatedSupertype() { target: List ^^^^^^ possible fix: declare l as List<@Nullable String> - Did you mean 'List<@Nullable String> l = s;'? """, """ static class Sub extends ArrayList {} @@ -95,9 +168,9 @@ public void theFixReplacesTheNodeAtEveryKindOfStep() { target: Collection ^^^^^^ note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - possible fix: declare list as List - possible fix: declare c as Collection - Did you mean 'Collection c = list;'? + possible fixes: + if list never holds null: declare list as List + if it may: declare c as Collection """, "ARRAY_ELEMENT", """ @@ -107,7 +180,6 @@ public void theFixReplacesTheNodeAtEveryKindOfStep() { target: List [] ^^^^^^ possible fix: declare d as List<@Nullable String> [] - Did you mean 'List<@Nullable String> [] d = src;'? """, "ENCLOSING_TYPE", """ @@ -117,7 +189,6 @@ public void theFixReplacesTheNodeAtEveryKindOfStep() { target: Outer.Inner ^^^^^^ possible fix: declare d as Outer<@Nullable String>.Inner - Did you mean 'Outer<@Nullable String>.Inner d = src;'? """, "WILDCARD_LOWER_BOUND", """ @@ -127,7 +198,6 @@ public void theFixReplacesTheNodeAtEveryKindOfStep() { target: List> ^^^^^^ possible fix: declare l as List> - Did you mean 'List> l = lower();'? """), """ static class Outer { @@ -173,7 +243,6 @@ public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { target: Map ^^^^^^ possible fix: declare plain as Map - Did you mean 'Map plain = m;'? """, "TAINTED", """ @@ -199,7 +268,6 @@ public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { target: Map ^^^^^^ possible fix: declare d as Map - Did you mean 'Map d = m;'? """), """ @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java index 4d0af86ba4..5e8edfb3b5 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java @@ -20,7 +20,6 @@ public void aSharedBoundBesideTheMismatchIsWalkedOnce() { target: P> ^^^^^^ possible fix: declare x as P<@Nullable String, L24> - Did you mean 'P<@Nullable String, L24> x = get();'? """, """ interface P {} @@ -69,7 +68,6 @@ public void aSharedBoundBesideANestedMismatchIsWalkedOnce() { target: List, String>> ^^^^^^ possible fix: declare x as List, @Nullable String>> - Did you mean 'List, @Nullable String>> x = l;'? """, """ interface P {} From 869299e4e34cb87ce87d0b4372aba3c90e4eb6c2 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Mon, 30 Nov 2026 01:00:52 +0300 Subject: [PATCH 29/43] Check every bound note a message test compares A note under a wildcard mismatch could leave out the bound, state a bound with `capture of ?` substituted into it, or state a bound whose nullness contradicts the first line of the message, and a test that pinned such a note passed. MismatchMessageTestBase now checks every diagnostic it compares, whatever text the test expects: each note states an upper bound and cites JLS 5.1.10, the stated bound contains no `capture of`, and where the message has one note and its path ends at the source wildcard's upper bound, the bound has the top-level nullness the first line gives the source. A test reports every broken invariant it saw, with the text mismatch attached as suppressed. NoteTests gains the cases that break them on this commit: captured wildcards whose note names only a type parameter, a subclass bound that disagrees with the compared one (#2206), and bounds that depend on a wildcard argument. These tests and the captured-note tests in CaretTests and ViewedSourceTests fail until the next commit fixes the notes. Assisted-by: Claude Code (claude-opus-5-5) --- .../MismatchMessageTestBase.java | 130 ++++++- .../jspecify/mismatchmessage/NoteTests.java | 356 +++++++++++++++++- 2 files changed, 470 insertions(+), 16 deletions(-) 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 index 62472f169a..908271fb2a 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/MismatchMessageTestBase.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/MismatchMessageTestBase.java @@ -3,9 +3,15 @@ import com.google.errorprone.CompilationTestHelper; import com.uber.nullaway.NullAwayTestsBase; import com.uber.nullaway.generics.JSpecifyJavacConfig; +import java.util.ArrayList; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.function.Predicate; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.jspecify.annotations.Nullable; /** * Compiles a {@code @NullMarked} class in JSpecify mode and compares the whole text of the generic @@ -14,6 +20,9 @@ *

The comparison is exact, so an expected message also states which lines the diagnostic does * not carry, such as a {@code possible fix:} line. A failure prints the expected message beside * every diagnostic the compilation reported. + * + *

Every diagnostic a test compares must also hold the invariants {@link #checkNotes} states, + * whatever message the test expects. */ abstract class MismatchMessageTestBase extends NullAwayTestsBase { @@ -36,10 +45,7 @@ CompilationTestHelper makeHelper() { * @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(); + assertMessages(Map.of("MESSAGE", expected), members); } /** @@ -49,8 +55,27 @@ void assertMessage(String expected, String members) { */ void assertMessages(Map expectedByKey, String members) { CompilationTestHelper helper = makeHelper(); - expectedByKey.forEach((key, expected) -> helper.expectErrorMessage(key, messageIs(expected))); - helper.addSourceLines("Test.java", nullMarkedClass(members)).doTest(); + Set violations = new LinkedHashSet<>(); + expectedByKey.forEach( + (key, expected) -> helper.expectErrorMessage(key, new MessageIs(expected, violations))); + AssertionError mismatch = null; + try { + helper.addSourceLines("Test.java", nullMarkedClass(members)).doTest(); + } catch (AssertionError e) { + mismatch = e; + } + if (!violations.isEmpty()) { + // a broken invariant usually also makes the text differ from the expected message; the + // invariant names the defect, and the mismatch stays attached as suppressed + AssertionError broken = new AssertionError(String.join("\n", violations)); + if (mismatch != null) { + broken.addSuppressed(mismatch); + } + throw broken; + } + if (mismatch != null) { + throw mismatch; + } } /** @@ -73,10 +98,83 @@ class Test { /** * Returns a matcher for a diagnostic whose text, without the {@code [NullAway]} prefix and the - * link line, equals {@code expected}. + * link line, equals {@code expected}. The matcher throws {@link AssertionError} on a diagnostic + * that breaks the invariants {@link #checkNotes} states. */ static Predicate messageIs(String expected) { - return new MessageIs(expected); + return new MessageIs(expected, null); + } + + /** The first line of a message: the path to the mismatch and the type the source has there. */ + private static final Pattern FIRST_LINE = + Pattern.compile("incompatible nullability in (.*?): source has (.*?) where target requires"); + + /** A {@code note:} line, without its indentation. */ + private static final Pattern NOTE = Pattern.compile("(?m)^\\s*note: (.*)$"); + + /** The citation every note about a wildcard's upper bound ends its bound with. */ + private static final String CITATION = " (JLS 5.1.10)"; + + /** + * Returns why {@code message} breaks the invariants below, or an empty list where it holds them: + * every {@code note:} line states the upper bound of the source wildcard and cites JLS 5.1.10, + * and the bound it states contains no captured type. Where the message has one note and the check + * compared the source's wildcard bound itself, the last step of the first line's path, the bound + * the note states must have the top-level nullness the first line gives the source. + * + * @param message the text of one diagnostic, without the {@code [NullAway]} prefix and the link + * line + */ + static List checkNotes(String message) { + List violations = new ArrayList<>(); + Matcher notes = NOTE.matcher(message); + int noteCount = 0; + String lastBound = null; + while (notes.find()) { + noteCount++; + String note = notes.group(1); + int citation = note.indexOf(CITATION); + String bound = citation < 0 ? null : statedBound(note.substring(0, citation)); + if (bound == null) { + violations.add("a note must state the upper bound and cite JLS 5.1.10, got:\n" + message); + continue; + } + if (bound.contains("capture of")) { + violations.add( + "the bound a note states must not contain a captured type, got:\n" + message); + } + lastBound = bound; + } + Matcher firstLine = FIRST_LINE.matcher(message); + if (noteCount != 1 || lastBound == null || !firstLine.find()) { + return violations; + } + List path = List.of(firstLine.group(1).split(" -> ")); + if (!path.get(path.size() - 1).equals("upper bound of wildcard") + || path.indexOf("upper bound of wildcard") != path.size() - 1) { + return violations; + } + boolean sourceNullable = firstLine.group(2).startsWith("@Nullable "); + if (lastBound.startsWith("@Nullable ") != sourceNullable) { + violations.add( + "the bound a note states must have the nullness the first line gives the source, got:\n" + + message); + } + return violations; + } + + /** + * Returns the upper bound a note states before its citation, or {@code null} where it states + * none. + */ + private static @Nullable String statedBound(String beforeCitation) { + for (String lead : List.of(", which is ", "upper bound is ", "has the upper bound ")) { + int at = beforeCitation.lastIndexOf(lead); + if (at >= 0) { + return beforeCitation.substring(at + lead.length()); + } + } + return null; } /** @@ -84,8 +182,11 @@ static Predicate messageIs(String expected) { * marked line matches it, so {@link #toString} is the expected message. The {@code Did you mean} * line Error Prone appends for an attached fix is part of the expected message, so a test that * expects none states that the diagnostic carries no edit; {@link FixTests} applies the edits. + * What {@link #checkNotes} finds wrong in a diagnostic it is shown goes to {@code violations}, + * and where that is {@code null}, fails the test at once. */ - private record MessageIs(String expected) implements Predicate { + private record MessageIs(String expected, @Nullable Set violations) + implements Predicate { private static final String PREFIX = "[NullAway] "; private static final String LINK_LINE = " (see http://t.uber.com/nullaway )"; @@ -102,9 +203,14 @@ public boolean test(String diagnostic) { // Error Prone appends "\n Did you mean '...'?" after the link line; the expected message // carries it as its last line String edit = diagnostic.substring(link + LINK_LINE.length()); - return (diagnostic.substring(PREFIX.length(), link) - + (edit.isEmpty() ? "" : edit.substring(1) + "\n")) - .equals(expected); + String message = diagnostic.substring(PREFIX.length(), link); + List broken = checkNotes(message); + if (violations != null) { + violations.addAll(broken); + } else if (!broken.isEmpty()) { + throw new AssertionError(String.join("\n", broken)); + } + return (message + (edit.isEmpty() ? "" : edit.substring(1) + "\n")).equals(expected); } @Override 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 346ab6033d..2e5b71301d 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 @@ -1,13 +1,14 @@ package com.uber.nullaway.jspecify.mismatchmessage; +import java.util.Map; import org.junit.Test; /** * A {@code note:} line says where the source takes a nullness its printed form does not show: the - * upper bound an unbounded or lower-bounded wildcard takes from its type parameter, or the type - * parameter a captured wildcard instantiates. It prints the class the wildcard is a type argument - * of, with every other type argument whose printed form contains {@code ?} or {@code <} written as - * {@code ...}. A source that prints its own nullness gets no note. + * upper bound an unbounded or lower-bounded wildcard takes from its type parameter, or the upper + * bound of a captured wildcard. It prints the class the wildcard is a type argument of, with every + * other type argument whose printed form contains {@code ?} or {@code <} written as {@code ...}. A + * source that prints its own nullness gets no note. */ public class NoteTests extends MismatchMessageTestBase { @@ -233,4 +234,351 @@ void test(List[]> l) { } """); } + + @Test + public void aCapturedWildcardNamesTheTypeParameterOnlyWhereItInstantiatesIt() { + assertMessages( + Map.of( + "CAPTURED_FROM_AN_UNANNOTATED_CLASS", + """ + incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Legacy + ^^^^^^^^^^^^ + target: Legacy + ^^^^^^ + note: capture of ? is the captured type argument for T of Legacy, whose upper bound is @Nullable Object (JLS 5.1.10), and Legacy is unannotated + """, + "CAPTURED_IN_A_SUBCLASS", + """ + incompatible nullability in type argument for T of Box -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: SubBox + ^^^^^^^^^^^^ + target: Box + ^^^^^^ + note: capture of ? is a captured wildcard whose upper bound is @Nullable Object (JLS 5.1.10) + """, + "CAPTURED_WHERE_WRITTEN", + """ + incompatible nullability in type argument for T of Box -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Box + ^^^^^^^^^^^^ + target: Box + ^^^^^^ + note: capture of ? is the captured type argument for T of Box, whose upper bound is @Nullable Object (JLS 5.1.10) + """, + "SUBSTITUTED_INTO_ANOTHER_CLASS", + """ + incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other position: source has @Nullable Object where target requires Object + source: Map + ^^^^^^^^^^^^ ^^^^^^^^^^^^ + 1 2 + target: Map + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: type argument for K of Map -> upper bound of wildcard + source: @Nullable Object + target: Object + note: capture of ? is a captured wildcard whose upper bound is @Nullable Object (JLS 5.1.10) + \s + 2. path: type argument for V of Map -> upper bound of wildcard + source: @Nullable Object + target: Object + note: capture of ? is a captured wildcard whose upper bound is @Nullable Object (JLS 5.1.10) + """, + "EARLIER_VIEW", + """ + incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: List + ^ + target: Collection + ^^^^^^ + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + possible fix: declare l as List + """, + "SUBSTITUTED_AFTER_AN_EARLIER_VIEW", + """ + incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other position: source has @Nullable Object where target requires Object + source: Map + ^^^^^^^^^^^^ ^^^^^^^^^^^^ + 1 2 + target: Map + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: type argument for K of Map -> upper bound of wildcard + source: @Nullable Object + target: Object + note: capture of ? is a captured wildcard whose upper bound is @Nullable Object (JLS 5.1.10) + \s + 2. path: type argument for V of Map -> upper bound of wildcard + source: @Nullable Object + target: Object + note: capture of ? is a captured wildcard whose upper bound is @Nullable Object (JLS 5.1.10) + """), + """ + static class Box {} + static void takeBox(Box b) {} + static Box make() { + throw new RuntimeException(); + } + @NullUnmarked + static class Legacy {} + @NullUnmarked + static Legacy makeLegacy() { + throw new RuntimeException(); + } + static void takeLegacy(Legacy l) {} + void capturedFromAnUnannotatedClass() { + // BUG: Diagnostic matches: CAPTURED_FROM_AN_UNANNOTATED_CLASS + takeLegacy(makeLegacy()); + } + static class SubBox extends Box {} + static SubBox makeSubBox() { + throw new RuntimeException(); + } + void capturedInASubclass() { + // BUG: Diagnostic matches: CAPTURED_IN_A_SUBCLASS + takeBox(makeSubBox()); + } + void capturedWhereWritten() { + // BUG: Diagnostic matches: CAPTURED_WHERE_WRITTEN + takeBox(make()); + } + static Map duplicate(List x) { + throw new RuntimeException(); + } + static void takeMap(Map m) {} + void substitutedIntoAnotherClass(List l) { + // BUG: Diagnostic matches: SUBSTITUTED_INTO_ANOTHER_CLASS + takeMap(duplicate(l)); + } + static void takeCollection(Collection c) {} + void substitutedAfterAnEarlierView(List l) { + // BUG: Diagnostic matches: EARLIER_VIEW + takeCollection(l); + // BUG: Diagnostic matches: SUBSTITUTED_AFTER_AN_EARLIER_VIEW + takeMap(duplicate(l)); + } + """); + } + + // The check views SubL as Base, where U is @Nullable, and reports a false positive (#2206); a + // note giving the bound T of SubL declares would contradict the first line. + @Test + public void aHolderNoteIsPrintedOnlyWhereItsBoundHasTheNullnessTheCheckCompared() { + assertMessages( + Map.of( + "SUBCLASS_BOUND_IS_NON_NULL", + """ + incompatible nullability in type argument for U of Base -> upper bound of wildcard: source has @Nullable Object where target requires List + source: SubL + ^ + target: Base> + ^^^^^^^^^^^^ + possible fix: declare s as SubL> + """, + "SUBCLASS_BOUND_INSIDE_A_LIST", + """ + incompatible nullability in type argument for U of Base -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: SubW + ^ + target: Base> + ^^^^^^ + possible fix: declare s as SubW + """, + "BOUND_HOLDS_A_WILDCARD", + """ + incompatible nullability in type argument for T of Wild -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Wild + ^ + target: Wild> + ^^^^^^ + note: the unbounded wildcard ? in Wild has the upper bound of type parameter T of Wild, which is List (JLS 5.1.10) + """, + "BOUND_HOLDS_AN_ARRAY", + """ + incompatible nullability in type argument for T of Arr -> upper bound of wildcard -> type argument for E of List -> component type -> type argument for E of List: source has @Nullable String where target requires String + source: Arr + ^ + target: Arr []>> + ^^^^^^ + note: the unbounded wildcard ? in Arr has the upper bound of type parameter T of Arr, which is List []> (JLS 5.1.10) + """, + "BOUND_HOLDS_A_LOWER_BOUND", + """ + incompatible nullability in type argument for T of Low -> upper bound of wildcard -> type argument for E of List -> lower bound of wildcard: source has String where target requires a supertype of @Nullable String + source: Low + ^ + target: Low> + ^^^^^^^^^^^^^^^^ + note: the unbounded wildcard ? in Low has the upper bound of type parameter T of Low, which is List (JLS 5.1.10) + """, + "BOUND_HOLDS_AN_INNER_CLASS", + """ + incompatible nullability in type argument for T of In -> upper bound of wildcard -> enclosing type -> type argument for E of Outer: source has @Nullable String where target requires String + source: In + ^ + target: In.Inner> + ^^^^^^ + note: the unbounded wildcard ? in In has the upper bound of type parameter T of In, which is Test.Outer<@Nullable String>.Inner (JLS 5.1.10) + """, + "BOUND_IS_A_SUBCLASS_OF_THE_COMPARED_CLASS", + """ + incompatible nullability in type argument for U of Coll -> upper bound of wildcard -> type argument for V of Map: source has @Nullable String where target requires String + source: SubColl + ^ + target: Coll> + ^^^^^^ + note: the unbounded wildcard ? in SubColl has the upper bound of type parameter T of SubColl, which is Reversed<@Nullable String, String> (JLS 5.1.10) + """, + "SUBCLASS_BOUND_STATES_A_TYPE_ARGUMENT", + """ + incompatible nullability in type argument for U of Wide -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Narrow + ^ + target: Wide> + ^^^^^^ + """, + "SUBCLASS_BOUND_IS_NULLABLE", + """ + incompatible nullability in type argument for U of Base -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Sub + ^ + target: Base + ^^^^^^ + note: the unbounded wildcard ? in Sub has the upper bound of type parameter T of Sub, which is @Nullable Object (JLS 5.1.10) + possible fix: declare s as Sub + """), + """ + static class Base {} + static class SubL> extends Base {} + static class SubW extends Base> {} + static class Sub extends Base {} + static void takeList(Base> b) {} + static void takeListOfNonNull(Base> b) {} + static void takeNonNull(Base b) {} + void subclassBoundIsNonNull(SubL s) { + // BUG: Diagnostic matches: SUBCLASS_BOUND_IS_NON_NULL + takeList(s); + } + void subclassBoundInsideAList(SubW s) { + // BUG: Diagnostic matches: SUBCLASS_BOUND_INSIDE_A_LIST + takeListOfNonNull(s); + } + static class Wild> {} + void boundHoldsAWildcard(Wild w, Wild> t) { + // BUG: Diagnostic matches: BOUND_HOLDS_A_WILDCARD + t = w; + } + static class Arr[]>> {} + void boundHoldsAnArray(Arr a, Arr[]>> t) { + // BUG: Diagnostic matches: BOUND_HOLDS_AN_ARRAY + t = a; + } + static class Low> {} + void boundHoldsALowerBound(Low l, Low> t) { + // BUG: Diagnostic matches: BOUND_HOLDS_A_LOWER_BOUND + t = l; + } + class Outer { + class Inner {} + } + static class In.Inner> {} + void boundHoldsAnInnerClass(In i, In.Inner> t) { + // BUG: Diagnostic matches: BOUND_HOLDS_AN_INNER_CLASS + t = i; + } + static class Reversed + extends HashMap {} + static class Coll> {} + static class SubColl> extends Coll {} + static void takeCollection(Coll> c) {} + void boundIsASubclassOfTheComparedClass(SubColl s) { + // BUG: Diagnostic matches: BOUND_IS_A_SUBCLASS_OF_THE_COMPARED_CLASS + takeCollection(s); + } + static class Wide> {} + static class Narrow> extends Wide {} + static void takeWide(Wide> w) {} + void subclassBoundStatesATypeArgument(Narrow n) { + // BUG: Diagnostic matches: SUBCLASS_BOUND_STATES_A_TYPE_ARGUMENT + takeWide(n); + } + void subclassBoundIsNullable(Sub s) { + // BUG: Diagnostic matches: SUBCLASS_BOUND_IS_NULLABLE + takeNonNull(s); + } + """); + } + + @Test + public void aBoundSubstitutesOnlyTheTypeArgumentsThatAreNotWildcards() { + assertMessages( + Map.of( + "DEPENDS_ON_A_WILDCARD", + """ + incompatible nullability in type argument for B of Dep -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Dep + ^ + target: Dep> + ^^^^^^ + note: the unbounded wildcard ? in Dep<..., ?> has the upper bound of type parameter B of Dep, which is List (JLS 5.1.10) + possible fix: declare d as Dep + """, + "DEPENDS_ON_ITSELF", + """ + incompatible nullability in type argument for T of Self -> upper bound of wildcard: source has @Nullable Comparable where target requires Comparable + source: Self + ^ + target: Self> + ^^^^^^^^^^^^^ + note: the unbounded wildcard ? in Self has the upper bound of type parameter T of Self, which is @Nullable Comparable (JLS 5.1.10) + possible fix: declare s as Self> + """, + "DEPENDS_ON_A_WILDCARD_AND_A_STATED_ARGUMENT", + """ + incompatible nullability in type argument for B of Tri -> upper bound of wildcard -> type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Tri + ^ + target: Tri> + ^^^^^^ + note: the unbounded wildcard ? in Tri<..., String, ?> has the upper bound of type parameter B of Tri, which is Map (JLS 5.1.10) + possible fix: declare t as Tri + """, + "DEPENDS_ON_A_STATED_ARGUMENT", + """ + incompatible nullability in type argument for B of Dep -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: Dep<@Nullable String, ?> + ^ + target: Dep<@Nullable String, ? extends List> + ^^^^^^ + note: the unbounded wildcard ? in Dep<@Nullable String, ?> has the upper bound of type parameter B of Dep, which is List<@Nullable String> (JLS 5.1.10) + """), + """ + static class Dep> {} + static class Self> {} + static class Tri> {} + static void takeDep(Dep> d) {} + static void takeSelf(Self> s) {} + static void takeTri(Tri> t) {} + static void takeStatedDep(Dep<@Nullable String, ? extends List> d) {} + void dependsOnAWildcard(Dep d) { + // BUG: Diagnostic matches: DEPENDS_ON_A_WILDCARD + takeDep(d); + } + void dependsOnItself(Self s) { + // BUG: Diagnostic matches: DEPENDS_ON_ITSELF + takeSelf(s); + } + void dependsOnAWildcardAndAStatedArgument(Tri t) { + // BUG: Diagnostic matches: DEPENDS_ON_A_WILDCARD_AND_A_STATED_ARGUMENT + takeTri(t); + } + void dependsOnAStatedArgument(Dep<@Nullable String, ?> d) { + // BUG: Diagnostic matches: DEPENDS_ON_A_STATED_ARGUMENT + takeStatedDep(d); + } + """); + } } From a51be983959e3f08bd36192543d019672dd31e39 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Mon, 30 Nov 2026 01:03:25 +0300 Subject: [PATCH 30/43] Keep the bound note consistent with the bound the check compared The note under a wildcard mismatch could contradict the first line of the message or name the wrong type parameter. For a captured wildcard it named the type parameter from WildcardType.bound, which javac rebinds whenever it substitutes the wildcard into a supertype, so an unrelated earlier statement changed the note from `E of List` to `E of SequencedCollection`. Where the class the target names bounds its type parameter otherwise than the printed holder does (#2206), the holder note gave the holder's bound, whose nullness disagrees with the one the first line reports. And a bound that depends on another wildcard argument was printed with `capture of ?` substituted into it. The check now records, where it goes below a wildcard's implicit bound, the bound it stepped to and the steps it took below it. The note for a captured wildcard states that bound and names a type parameter only where the caret's type-argument step is the one the capture instantiates. A holder note is printed only where its declared bound, followed along the recorded steps, has the nullness the first line gives. The declared bound substitutes only the type arguments that are neither wildcards nor captures. User-visible: A captured wildcard's note reads `capture of ? is the captured type argument for T of Box, whose upper bound is @Nullable Object (JLS 5.1.10)` where the capture instantiates the printed type parameter, and `capture of ? is a captured wildcard whose upper bound is @Nullable Object (JLS 5.1.10)` otherwise. Where the printed holder's declared bound disagrees with the nullness the check found, the message has no note. A bound that depends on a wildcard argument keeps that type parameter's name, as in `which is List`. Assisted-by: Claude Code (claude-opus-5-5) --- .../uber/nullaway/generics/GenericsUtils.java | 10 + .../generics/NullabilityMismatchMessage.java | 257 ++++++++++++++---- .../generics/NullabilityMismatches.java | 52 +++- .../nullaway/jspecify/GenericMethodTests.java | 4 +- .../jspecify/mismatchmessage/CaretTests.java | 4 +- .../mismatchmessage/ViewedSourceTests.java | 2 +- 6 files changed, 256 insertions(+), 73 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 8b13e7f051..a53e34d1cf 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java @@ -137,6 +137,16 @@ static Type wildcardUpperBound( wildcardType, wildcardType.bound, Map.of(), state, config, handler); } + /** + * Returns the upper bound {@code formalTypeVariable} declares, with the nullness {@link + * #wildcardUpperBound} gives an unbounded wildcard that instantiates it. + */ + static Type declaredUpperBound( + Type.TypeVar formalTypeVariable, VisitorState state, Config config, Handler handler) { + return applyDeclarationUpperBoundNullabilityIfApplicable( + formalTypeVariable.getUpperBound(), formalTypeVariable, state, config, handler); + } + /** * Returns the effective upper bound of each type argument of {@code classType}. * 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 69ef3b3aa6..9973e46364 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -19,6 +19,7 @@ import com.sun.tools.javac.code.TypeTag; import com.sun.tools.javac.code.Types; import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.util.ListBuffer; import com.uber.nullaway.Config; import com.uber.nullaway.Nullness; import com.uber.nullaway.handlers.Handler; @@ -97,13 +98,18 @@ * marked on a printed type, the type the reader wrote or the {@code source supertype} line, the * note prints the class the wildcard is a type argument of, names the type parameter the wildcard * takes its upper bound from, and states that bound with the class's other type arguments - * substituted. Every other type argument whose printed form contains {@code ?} or {@code <}, such - * as a wildcard or a parameterized type, is printed as {@code ...}, so the one {@code ?} printed is - * the wildcard meant and a long type is not repeated. Where it is marked on neither, as below the - * root of a supertype view, the type parameter belongs to a declaration this message never prints, - * and the note 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 for the source a {@code note} says what the reader cannot see there. + * substituted, except a wildcard, whose type parameter keeps its name. Every other type argument + * whose printed form contains {@code ?} or {@code <}, such as a wildcard or a parameterized type, + * is printed as {@code ...}, so the one {@code ?} printed is the wildcard meant and a long type is + * not repeated. The check compares the wildcard as the class the target names holds it, so where a + * subclass bounds the type parameter otherwise, the bound of the printed class can have another + * nullness than the first line states, and then there is no note. Where it is marked on neither, as + * below the root of a supertype view, the type parameter belongs to a declaration this message + * never prints, and the note states the bound and stops. A note for a captured wildcard states the + * upper bound the check compared, and names a type parameter only where the caret's position on a + * printed type is the one the capture instantiates. 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 for the source a {@code note} says what the reader cannot see there. * *

The fixes

* @@ -566,49 +572,32 @@ private String mismatchDetail( } /** - * Says where the source wildcard takes its upper bound from and what that bound is, or returns - * {@code null} where the printed node is not a wildcard, its bound is written out, or it is a - * captured wildcard whose type variable cannot be named. Where an uncaptured wildcard's type - * parameter cannot be named, the note states the bound alone. + * Says what upper bound the source wildcard has and, where the message prints the type parameter + * it comes from, names that parameter; returns {@code null} where the printed node is not a + * wildcard, its bound is written out, or the bound the note would state disagrees with the + * nullness the check found. * *

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. + * type does not state, and a reader who is not told what it is reads the two bounds as a + * contradiction. For a captured wildcard the note also says when the class of the type parameter + * it names 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, @Nullable Type printedView) { // 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()); + Type printedNode = mismatch.sourcePrintedNode(); + Type.WildcardType wildcard = GenericsUtils.asWildcard(printedNode); 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 wildcard in the source is the type argument for %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; // diff-coverage: ignore -- a caret goes below a written bound - } // the step that reached the wildcard in the printed type that marks it names the type parameter // it instantiates there; javac's own link, WildcardType.bound, names a type parameter of - // whatever supertype the wildcard was last substituted into + // whatever supertype the wildcard was last substituted into, which an unrelated earlier + // statement can change TypePath caret = mismatch.sourceCaret(); Type printed = sourceType; if (caret == null) { @@ -617,11 +606,42 @@ private String mismatchDetail( } TypePath.Step reachingStep = caret == null || caret.isRoot() ? null : caret.steps().get(caret.steps().size() - 1); - Type.TypeVar formalTypeVariable = - reachingStep != null && reachingStep.kind() == TypePath.Step.Kind.TYPE_ARGUMENT - ? reachingStep.formal() - : null; + // the class the wildcard is a type argument of, printed so the reader can find that ? + PrintedHolder holder = null; + if (printed != null + && caret != null + && reachingStep != null + && reachingStep.kind() == TypePath.Step.Kind.TYPE_ARGUMENT + && nodeAt(printed, caret.steps().subList(0, caret.steps().size() - 1)) + instanceof Type.ClassType holderClass) { + holder = + new PrintedHolder( + holderClass, + reachingStep.index(), + reachingStep.formal(), + boundWithStatedArgumentsSubstituted(holderClass, reachingStep.index())); + } + Type.TypeVar formalTypeVariable = holder == null ? null : holder.formal(); Symbol.ClassSymbol owner = typeVariableOwner(formalTypeVariable); + // the check compares the wildcard as the class the target names holds it, and where that class + // bounds its type parameter otherwise than the holder does, a note about the holder's type + // parameter would contradict the first line (#2206) + NullabilityMismatches.HiddenBound hidden = mismatch.sourceHiddenBound(); + boolean declaredBoundAgrees = + holder != null + && (hidden == null + || hasNullnessAt(holder.declaredBound(), hidden.steps(), mismatch.sourceNode())); + if (printedNode instanceof Type.CapturedType capture) { + return capturedWildcardNote( + capture, + wildcard, + declaredBoundAgrees ? formalTypeVariable : null, + owner, + hidden == null ? null : hidden.bound()); + } + if (wildcard.kind == BoundKind.EXTENDS) { + return null; // diff-coverage: ignore -- a caret goes below a written bound + } // ? has an upper bound, Object as the JLS writes it (4.5.1), and ? super X has none of its // own; capture conversion gives both the bound of the type parameter (5.1.10) boolean unbounded = wildcard.kind == BoundKind.UNBOUND; @@ -631,7 +651,7 @@ private String mismatchDetail( : "the wildcard ? super " + GenericsChecks.prettyTypeForError(wildcard.type, state); String hasBound = unbounded ? " has the upper bound" : " has no upper bound of its own; its upper bound is"; - if (formalTypeVariable == null || owner == null || caret == null || reachingStep == null) { + if (formalTypeVariable == null || owner == null || holder == null) { // no type parameter this message prints stands behind the bound: the wildcard sits at no // position of a printed type, as below the root of a supertype view (#2197), or the variable // it instantiates has no named owner. The note says what the bound is and leaves where it @@ -644,29 +664,148 @@ private String mismatchDetail( GenericsChecks.prettyTypeForError( GenericsUtils.wildcardUpperBound(wildcard, state, config, handler), state)); } - // the class the wildcard is a type argument of, printed so the reader can find that ? - Type holder = - printed == null - ? null // diff-coverage: ignore -- a caret is placed only on a printed type - : nodeAt(printed, caret.steps().subList(0, caret.steps().size() - 1)); - if (!(holder instanceof Type.ClassType holderClass)) { - return null; // diff-coverage: ignore -- the caret path reaches the wildcard through its class - } - // the bound of the type parameter with the other type arguments of the holder substituted, as - // capture conversion gives it: for Foo>, the ? of Foo has the - // upper bound List - Type upperBound = - GenericsUtils.effectiveUpperBoundsForTypeArguments(holderClass, state, config, handler) - .get(reachingStep.index()); + if (!declaredBoundAgrees) { + return null; + } return String.format( "%s in %s%s %s type parameter %s of %s, which is %s (JLS 5.1.10)", source, - withOtherTypeArgumentsElided(holderClass, reachingStep.index()), + withOtherTypeArgumentsElided(holder.type(), holder.index()), hasBound, unbounded ? "of" : "the bound of", formalTypeVariable.tsym.getSimpleName(), owner.getSimpleName(), - GenericsChecks.prettyTypeForError(upperBound, state)); + GenericsChecks.prettyTypeForError(holder.declaredBound(), state)); + } + + /** + * A printed class type that holds the source wildcard as a type argument. + * + * @param type the printed class type + * @param index the position of the wildcard among the type arguments of {@code type} + * @param formal the type parameter at {@code index}, where the caret's step records it + * @param declaredBound the upper bound the type parameter at {@code index} declares, with the + * type arguments of {@code type} that are neither wildcards nor captures substituted + */ + private record PrintedHolder( + Type.ClassType type, int index, Type.@Nullable TypeVar formal, Type declaredBound) {} + + /** + * Returns the note for a captured wildcard: its upper bound as the check compared it, and the + * type parameter it is the type argument for where the caller names one and the captured wildcard + * instantiates that same one. + * + * @param formalTypeVariable the type parameter the caret's last step reaches, where its declared + * bound agrees with the nullness the check found; {@code null} otherwise + * @param owner the class of {@code formalTypeVariable}, or {@code null} where it has none + * @param comparedBound the upper bound of the capture the check compared, or {@code null} where + * the check did not go below the capture + */ + private String capturedWildcardNote( + Type.CapturedType capture, + Type.WildcardType wildcard, + Type.@Nullable TypeVar formalTypeVariable, + Symbol.@Nullable ClassSymbol owner, + @Nullable Type comparedBound) { + Type upperBound = + comparedBound != null + ? comparedBound + : GenericsUtils.effectiveWildcardUpperBound(capture, state, config, handler); + String captured = "capture of " + GenericsChecks.prettyTypeForError(wildcard, state); + String bound = GenericsChecks.prettyTypeForError(upperBound, state); + // WildcardType.bound names the type parameter the wildcard was last substituted for, so it + // only confirms the caret's type parameter and never names one by itself + Type.TypeVar instantiated = wildcard.bound; + if (formalTypeVariable == null + || owner == null + || instantiated == null + || !instantiated.tsym.equals(formalTypeVariable.tsym)) { + return String.format( + "%s is a captured wildcard whose upper bound is %s (JLS 5.1.10)", captured, bound); + } + String note = + String.format( + "%s is the captured type argument for %s of %s, whose upper bound is %s (JLS 5.1.10)", + captured, formalTypeVariable.tsym.getSimpleName(), owner.getSimpleName(), bound); + return GenericsUtils.fromUnannotatedMethodOrClass( + formalTypeVariable.tsym, config, handler, state) + ? note + String.format(", and %s is unannotated", owner.getSimpleName()) + : note; + } + + /** + * Returns the upper bound the type parameter at {@code index} of {@code holder}'s class declares, + * with each type argument of {@code holder} that is not a wildcard or a capture substituted for + * its type parameter. A type parameter whose argument is a wildcard or a capture keeps its name, + * as in {@code List} for the second {@code ?} of {@code Dep} where {@code Dep>}. + */ + private Type boundWithStatedArgumentsSubstituted(Type.ClassType holder, int index) { + List formals = holder.tsym.type.getTypeArguments(); + List arguments = holder.getTypeArguments(); + ListBuffer from = new ListBuffer<>(); + ListBuffer to = new ListBuffer<>(); + for (int i = 0; i < arguments.size(); i++) { + Type argument = arguments.get(i); + if (GenericsUtils.asWildcard(argument) == null && !(argument instanceof Type.CapturedType)) { + from.append(formals.get(i)); + to.append(argument); + } + } + Type declared = + GenericsUtils.declaredUpperBound((Type.TypeVar) formals.get(index), state, config, handler); + return TypeSubstitutionUtils.subst( + state.getTypes(), declared, from.toList(), to.toList(), config); + } + + /** + * Whether the node {@code steps} reach from {@code bound} has the nullness of {@code sourceNode}; + * {@code false} where a step finds no such node. A step into an upper bound goes into the bound + * of a wildcard, a capture, or a type variable. + */ + private boolean hasNullnessAt(Type bound, TypePath steps, Type sourceNode) { + Type node = bound; + for (TypePath.Step step : steps.steps()) { + node = + switch (step.kind()) { + case TYPE_ARGUMENT -> typeArgumentAt(node, step); + case WILDCARD_BOUND -> + node instanceof Type.TypeVar typeVariable && !(node instanceof Type.CapturedType) + ? GenericsUtils.declaredUpperBound(typeVariable, state, config, handler) + : GenericsUtils.asWildcard(node) != null + ? GenericsUtils.effectiveWildcardUpperBound(node, state, config, handler) + : null; + case WILDCARD_LOWER_BOUND -> { + Type.WildcardType wildcard = GenericsUtils.asWildcard(node); + yield wildcard != null && wildcard.kind == BoundKind.SUPER ? wildcard.type : null; + } + case ARRAY_ELEMENT -> node instanceof Type.ArrayType array ? array.elemtype : null; + case ENCLOSING_TYPE -> + node instanceof Type.ClassType classType ? classType.getEnclosingType() : null; + }; + if (node == null) { + return false; + } + } + return checks.isNullableAnnotated(node) == checks.isNullableAnnotated(sourceNode); + } + + /** + * Returns the type argument {@code step} reaches in {@code node}, viewed as the class whose type + * parameter the step names, or {@code null} where {@code node} has no such type argument. + */ + private @Nullable Type typeArgumentAt(Type node, TypePath.Step step) { + Type.TypeVar formal = step.formal(); + Type viewed = node; + if (formal != null + && formal.tsym.owner instanceof Symbol.ClassSymbol stepClass + && !node.tsym.equals(stepClass)) { + viewed = TypeSubstitutionUtils.asSuper(state.getTypes(), node, stepClass, config); + } + return viewed instanceof Type.ClassType classType + && step.index() < classType.getTypeArguments().size() + ? classType.getTypeArguments().get(step.index()) + : null; } /** 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 3ca24ef96c..8e408a3b45 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java @@ -77,6 +77,9 @@ Relation swapped() { * not one of upper bounds * @param targetUpperBound the upper bound the target requires there, which writing an explicit * bound on {@code sourceWildcard} would have to produce + * @param sourceHiddenBound the upper bound the check compared for the wildcard under {@code + * sourceCaret} and the steps it took into that bound, where the printer does not show that + * bound; {@code null} otherwise */ record Mismatch( Relation relation, @@ -90,7 +93,17 @@ record Mismatch( @Nullable TypePath viewCaret, Type sourcePrintedNode, Type.@Nullable WildcardType sourceWildcard, - @Nullable Type targetUpperBound) {} + @Nullable Type targetUpperBound, + @Nullable HiddenBound sourceHiddenBound) {} + + /** + * The upper bound the check compared below a wildcard whose bound the printer does not show, and + * the steps the comparison took from that bound to the node it stands at. + * + * @param bound the upper bound, as the check compared it + * @param steps the steps from {@code bound}, named for the classes compared + */ + record HiddenBound(Type bound, TypePath steps) {} /** * The written type a comparison is followed in, and how far it could be followed. @@ -107,8 +120,14 @@ record Mismatch( * * @param declared the node of the declared supertype where the comparison stands, for {@code * DECLARED} only + * @param hidden the bound below {@code node} the comparison went into, for {@code HIDDEN} only */ - private record Track(State state, Type node, TypePath path, @Nullable Type declared) { + private record Track( + State state, + Type node, + TypePath path, + @Nullable Type declared, + @Nullable HiddenBound hidden) { enum State { LOCATED, @@ -118,12 +137,12 @@ enum State { } static Track located(Type node, TypePath path) { - return new Track(State.LOCATED, node, path, null); + return new Track(State.LOCATED, node, path, null, null); } /** Returns the track where the comparison leaves the written type at {@code track}. */ static Track lost(Track track) { - return new Track(State.LOST, track.node(), track.path(), null); + return new Track(State.LOST, track.node(), track.path(), null, null); } /** Returns where a caret goes for this track, or {@code null} where it gets none. */ @@ -269,7 +288,7 @@ private Track viewedAs(Track track, Type rhs, Type rhsView) { Type view = TypeSubstitutionUtils.asSuper(types, declared, viewClass, config); return view == null ? Track.lost(track) // diff-coverage: ignore -- a view is a supertype - : new Track(Track.State.DECLARED, track.node(), track.path(), view); + : new Track(Track.State.DECLARED, track.node(), track.path(), view, null); } /** Steps into type argument {@code index} of {@code lhs} and of {@code rhsView}. */ @@ -373,7 +392,8 @@ void reject(Relation relation, Type lhsNode, Type rhsNode) { view == null ? null : view.caret(), source.caret() != null ? source.node() : frame.sourceShown(), bound == null ? null : bound.sourceWildcard(), - bound == null ? null : bound.targetUpperBound())); + bound == null ? null : bound.targetUpperBound(), + source.hidden())); } /** @@ -452,7 +472,16 @@ private static boolean isShown(TypePath.Step.Kind kind, Type parent) { */ private static Track follow(Track track, Step step) { return switch (track.state()) { - case HIDDEN, LOST -> track; + case HIDDEN -> { + HiddenBound hidden = castToNonNull(track.hidden()); + yield new Track( + Track.State.HIDDEN, + track.node(), + track.path(), + null, + new HiddenBound(hidden.bound(), hidden.steps().then(comparedStep(step)))); + } + case LOST -> track; case DECLARED -> followDeclared(track, step); case LOCATED -> { Track child = childByPosition(track, step); @@ -495,7 +524,12 @@ private static Track follow(Track track, Step step) { // the upper bound of `?` and `? super X` is not printed, so the caret stays on the wildcard yield wildcard.kind == BoundKind.EXTENDS ? Track.located(wildcard.type, track.path().then(TypePath.Step.wildcardBound())) - : new Track(Track.State.HIDDEN, node, track.path(), null); + : new Track( + Track.State.HIDDEN, + node, + track.path(), + null, + new HiddenBound(step.child(), TypePath.root())); } case WILDCARD_LOWER_BOUND -> { Type.WildcardType wildcard = GenericsUtils.asWildcard(node); @@ -555,7 +589,7 @@ private static Track followDeclared(Track track, Step step) { : null; return written != null ? written - : new Track(Track.State.DECLARED, track.node(), track.path(), child); + : new Track(Track.State.DECLARED, track.node(), track.path(), child, null); } /** 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 d2e251849a..2a88a88242 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java @@ -2247,7 +2247,7 @@ public void capturedTypeAtNullUnmarkedBoundary() { ^^^^^^^^^^^^ target: Foo ^ - note: the wildcard in the source is the type argument for T of Box, and Box is unannotated + note: capture of ? is a captured wildcard whose upper bound is @Nullable Object (JLS 5.1.10) """)) .addSourceLines( "Test.java", @@ -2295,7 +2295,7 @@ public void capturedTypeGetsDirectNullableAnnotationFromTypeVariableUse() { ^^^^^^^^^^^^^^^^^^^^^^ target: Foo ^^^^^^ - note: the wildcard in the source is the type argument for T of Holder + note: capture of ? is a captured wildcard whose upper bound is @Nullable Object (JLS 5.1.10) """)) .addSourceLines( "Test.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 index 073daff9fe..535496419f 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java @@ -127,12 +127,12 @@ public void bothPositionsAreMarkedWhereOneInstanceFillsTwoTypeArguments() { 1. path: type argument for K of Map -> upper bound of wildcard source: @Nullable Object target: Object - note: the wildcard in the source is the type argument for E of List + note: capture of ? is a captured wildcard whose upper bound is @Nullable Object (JLS 5.1.10) \s 2. path: type argument for V of Map -> upper bound of wildcard source: @Nullable Object target: Object - note: the wildcard in the source is the type argument for E of List + note: capture of ? is a captured wildcard whose upper bound is @Nullable Object (JLS 5.1.10) """, """ static Map duplicate(List x) { 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 ae377cfe0b..4505544e0b 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 @@ -63,7 +63,7 @@ public void aCarriedOverCaptureIsMarkedOnTheWrittenSourceAndKeepsItsProvenance() ^^^^^^^^^^^^ target: Base ^^^^^^ - note: the wildcard in the source is the type argument for T of Sub + note: capture of ? is the captured type argument for T of Sub, whose upper bound is @Nullable Object (JLS 5.1.10) """, """ static class Base {} From 553fd9ba32da5087371ae548449b31b036906467 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Mon, 30 Nov 2026 11:07:53 +0300 Subject: [PATCH 31/43] Name what a type argument must match and what each count counts A message whose source is less nullable than the target said "a non-wildcard type argument must be the same type", which did not say the same as what, and a Java reader sees String and @Nullable String as one type. The first line now says "a non-wildcard type argument must have the same nullness in source and target", and so does the numbered entry. The first line said "and N other positions" and the line after the list said "and N more, not listed", which read as two counts of different things. Both now count differing positions: "and N other differing positions" on the first line, and "and N more differing positions, not listed" after the five listed entries. TypePath.Step no longer carries the owner class of a type-argument step beside its type parameter; describe() takes it from the type parameter's owner. Kind.WILDCARD_BOUND and wildcardBound() are WILDCARD_UPPER_BOUND and wildcardUpperBound(), beside WILDCARD_LOWER_BOUND. Three guards gain the tests they lacked: the source fix is withheld for a member read through a parameterized receiver, whose declared type differs from the type it is read at; under a ? super bound the target is the subtype side, for a reordering subclass and for a wildcard only the source states; and a declaration whose second declarator has annotated brackets gets no edit. User-visible: Where a non-null type argument meets a @Nullable one, the first line and the numbered entry say "a non-wildcard type argument must have the same nullness in source and target". Where several positions differ, the first line says "and N other differing position(s)" and the line after the five listed entries says "and N more differing position(s), not listed". Assisted-by: Claude Code (claude-opus-5-5) --- .../jdkannotations/JDKIntegrationTest.java | 4 +- .../GenericTypePrettyPrintingVisitor.java | 5 +- .../generics/NullabilityMismatchMessage.java | 48 +++++++------ .../generics/NullabilityMismatches.java | 21 +++--- .../com/uber/nullaway/generics/TypePath.java | 34 ++++----- .../jspecify/BytecodeGenericsTests.java | 4 +- .../jspecify/GenericInheritanceTests.java | 2 +- ...enericMethodLambdaOrMethodRefArgTests.java | 4 +- .../nullaway/jspecify/GenericMethodTests.java | 42 +++++------ .../uber/nullaway/jspecify/GenericsTests.java | 52 +++++++------- .../IntersectionRestorationTests.java | 4 +- .../nullaway/jspecify/JSpecifyArrayTests.java | 2 +- .../uber/nullaway/jspecify/WildcardTests.java | 4 +- .../jspecify/mismatchmessage/CaretTests.java | 6 +- .../jspecify/mismatchmessage/FixTests.java | 6 ++ .../LowerBoundAndRawSourceTests.java | 40 +++++++++++ .../jspecify/mismatchmessage/NoteTests.java | 4 +- .../jspecify/mismatchmessage/PathTests.java | 6 +- .../mismatchmessage/SourceFixTests.java | 37 ++++++++-- .../SummaryAndNumberingTests.java | 72 ++++++++++++++++--- .../mismatchmessage/TargetTypeFixTests.java | 13 ++-- .../mismatchmessage/ViewedSourceTests.java | 6 +- .../nullaway/CustomLibraryModelsTests.java | 4 +- 23 files changed, 274 insertions(+), 146 deletions(-) diff --git a/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java b/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java index 2699def406..fb3ea719ef 100644 --- a/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java +++ b/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java @@ -718,11 +718,11 @@ void testCall() { @Nullable List[] nonNullTypeArgMixed = (@Nullable List[]) new List[3]; // === test calls ParameterAnnotation.nestedAnnotations(nullableTypeArg, nullableArray, nullableMixed); - // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String ParameterAnnotation.nestedAnnotations(nonNullTypeArg, nullableArray, nullableMixed); ParameterAnnotation.nestedAnnotations(nullableTypeArg, nonNullArray, nullableMixed); ParameterAnnotation.nestedAnnotations(nullableTypeArg, nullableArray, nonNullArrayMixed); - // BUG: Diagnostic contains: incompatible nullability in component type -> type argument for E of List: a non-wildcard type argument must be the same type; source has Integer where target requires @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in component type -> type argument for E of List: a non-wildcard type argument must have the same nullness in source and target; source has Integer where target requires @Nullable Integer ParameterAnnotation.nestedAnnotations(nullableTypeArg, nullableArray, nonNullTypeArgMixed); } } 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 5badde0b0d..32d49fe658 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java @@ -230,7 +230,7 @@ public String visitWildcardType(Type.WildcardType t, @Nullable Void unused) { sb.append( descend( t.kind == BoundKind.EXTENDS - ? TypePath.Step.wildcardBound() + ? TypePath.Step.wildcardUpperBound() : TypePath.Step.wildcardLowerBound(), t.type)); } @@ -265,8 +265,7 @@ public String visitClassType(Type.ClassType t, @Nullable Void s) { if (i > 0) { arguments.append(", "); } - arguments.append( - descend(TypePath.Step.typeArgument(i, null, null), t.getTypeArguments().get(i))); + arguments.append(descend(TypePath.Step.typeArgument(i, null), t.getTypeArguments().get(i))); } sb.append(arguments); sb.append(">"); 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 df0ae1e3d4..0c59c224d8 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -62,20 +62,21 @@ * constructs are named in the terms of the JLS, as {@code type argument for K of Map}, {@code upper * bound of wildcard}, and {@code component type}, and nullness in those of JSpecify. Where there * are several differences, each gets a numbered entry with its own {@code path}, {@code source}, - * and {@code target}, five at most, and {@code and N more, not listed} counts the rest. The keys of - * the type lines are padded to one width, so the types of one message start in the same column. + * and {@code target}, five at most, and {@code and N more differing positions, not listed} counts + * the rest. The keys of the type lines are padded to one width, so the types of one message start + * in the same column. * *

The first line

* *

It stands alone, since a tool may show only that line: {@code incompatible nullability in}, - * the path of the first difference, how many other positions differ, and then the two nodes there. - * 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 non-wildcard type argument must be - * the same type. Where the target bounds a {@code ? super} wildcard, the target side reads {@code a - * supertype of} that bound. + * the path of the first difference, {@code and N other differing positions} where there are more, + * and then the two nodes there. 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 non-wildcard type + * argument must have the same nullness in source and target. Where the target bounds a {@code ? + * super} wildcard, the target side reads {@code a supertype of} that bound. * *

The caret

* @@ -273,7 +274,10 @@ Report build( if (mismatches.size() > listed.size()) { message.append( String.format( - "%s\n and %d more, not listed", separator, mismatches.size() - listed.size())); + "%s\n and %d more differing position%s, not listed", + separator, + mismatches.size() - listed.size(), + mismatches.size() - listed.size() == 1 ? "" : "s")); } Symbol.VarSymbol sourceVariable = sourceVariable(sourceExpression, sourceType); Type rewrittenSourceType = @@ -444,10 +448,12 @@ private String summaryLine(List mismatches) { others == 0 ? first.path().describe() : String.format( - "%s and %d other position%s", + "%s and %d other differing position%s", first.path().describe(), others, others == 1 ? "" : "s"); String exactly = - mustMatchExactly(first) ? "a non-wildcard type argument must be the same type; " : ""; + mustMatchExactly(first) + ? "a non-wildcard type argument must have the same nullness in source and target; " + : ""; return String.format( "incompatible nullability in %s: %ssource has %s where target requires %s", where, @@ -459,7 +465,8 @@ private String summaryLine(List mismatches) { /** * Whether {@code mismatch} is a non-null type argument where the target has a {@code @Nullable} * one, which reads as a false subtype claim, since every {@code String} is a {@code @Nullable - * String}; what fails there is that a non-wildcard type argument must be the same type. + * String}; what fails there is that a non-wildcard type argument must have the same nullness in + * source and target. */ private boolean mustMatchExactly(NullabilityMismatches.Mismatch mismatch) { return mismatch.relation() == NullabilityMismatches.Relation.SAME @@ -624,7 +631,8 @@ private String mismatchDetail( detail.append("\n").append(body).append(TARGET_LABEL).append(": "); detail.append(targetRequirement(mismatch)); if (mustMatchExactly(mismatch)) { - detail.append(" (a non-wildcard type argument must be the same type)"); + detail.append( + " (a non-wildcard type argument must have the same nullness in source and target)"); } } String note = boundOriginNote(mismatch, sourceType, printedView); @@ -832,7 +840,7 @@ private boolean hasNullnessAt(Type bound, TypePath steps, Type sourceNode) { node = switch (step.kind()) { case TYPE_ARGUMENT -> typeArgumentAt(node, step); - case WILDCARD_BOUND -> + case WILDCARD_UPPER_BOUND -> node instanceof Type.TypeVar typeVariable && !(node instanceof Type.CapturedType) ? GenericsUtils.declaredUpperBound(typeVariable, state, config, handler) : GenericsUtils.asWildcard(node) != null @@ -885,7 +893,7 @@ private boolean hasNullnessAt(Type bound, TypePath steps, Type sourceNode) { && step.index() < classType.getTypeArguments().size() ? classType.getTypeArguments().get(step.index()) : null; // diff-coverage: ignore -- the path was recorded on this type - case WILDCARD_BOUND, WILDCARD_LOWER_BOUND -> + case WILDCARD_UPPER_BOUND, WILDCARD_LOWER_BOUND -> node instanceof Type.WildcardType wildcard ? wildcard.type : null; case ARRAY_ELEMENT -> node instanceof Type.ArrayType array ? array.elemtype : null; case ENCLOSING_TYPE -> @@ -1007,10 +1015,10 @@ private String withOtherTypeArgumentsElided(Type.ClassType holder, int index) { : null; // diff-coverage: ignore -- see the method comment case ENCLOSING_TYPE -> type instanceof Type.ClassType classType ? classType.getEnclosingType() : null; - case WILDCARD_BOUND, WILDCARD_LOWER_BOUND -> + case WILDCARD_UPPER_BOUND, WILDCARD_LOWER_BOUND -> type instanceof Type.WildcardType wildcard && wildcard.kind - == (step.kind() == TypePath.Step.Kind.WILDCARD_BOUND + == (step.kind() == TypePath.Step.Kind.WILDCARD_UPPER_BOUND ? BoundKind.EXTENDS : BoundKind.SUPER) ? wildcard.type @@ -1038,7 +1046,7 @@ private String withOtherTypeArgumentsElided(Type.ClassType holder, int index) { yield TYPE_METADATA_BUILDER.createClassType( classType, replaced, classType.getTypeArguments()); } - case WILDCARD_BOUND, WILDCARD_LOWER_BOUND -> + case WILDCARD_UPPER_BOUND, WILDCARD_LOWER_BOUND -> TYPE_METADATA_BUILDER.createWildcardType((Type.WildcardType) type, replaced); case ARRAY_ELEMENT -> TYPE_METADATA_BUILDER.createArrayType((Type.ArrayType) type, replaced); }; 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 8e408a3b45..e8609c14f3 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java @@ -311,7 +311,7 @@ Frame enterEnclosingType(Type.ClassType lhs, Type.ClassType rhsView) { null); } - /** Steps into the element type of two arrays. */ + /** Steps into the component types of two arrays. */ Frame enterArrayElement(Type.ArrayType lhs, Type.ArrayType rhs) { return enter( new Step(TypePath.Step.Kind.ARRAY_ELEMENT, -1, lhs, lhs.elemtype), @@ -333,10 +333,10 @@ Frame enterUpperBounds( return enter( lhsWildcard == null ? null - : new Step(TypePath.Step.Kind.WILDCARD_BOUND, -1, lhsWildcard, lhsBound), + : new Step(TypePath.Step.Kind.WILDCARD_UPPER_BOUND, -1, lhsWildcard, lhsBound), rhsWildcard == null ? null - : new Step(TypePath.Step.Kind.WILDCARD_BOUND, -1, rhsWildcard, rhsBound), + : new Step(TypePath.Step.Kind.WILDCARD_UPPER_BOUND, -1, rhsWildcard, rhsBound), bound); } @@ -447,7 +447,7 @@ private Frame enter(@Nullable Step lhs, @Nullable Step rhs, @Nullable BoundCompa private static TypePath.Step comparedStep(Step step) { return switch (step.kind()) { case TYPE_ARGUMENT -> typeArgumentStep(step.parent(), step.index()); - case WILDCARD_BOUND -> TypePath.Step.wildcardBound(); + case WILDCARD_UPPER_BOUND -> TypePath.Step.wildcardUpperBound(); case WILDCARD_LOWER_BOUND -> TypePath.Step.wildcardLowerBound(); case ARRAY_ELEMENT -> TypePath.Step.arrayElement(); case ENCLOSING_TYPE -> TypePath.Step.enclosingType(); @@ -459,7 +459,7 @@ private static TypePath.Step comparedStep(Step step) { * wildcard states is printed, and the upper bound of {@code ?} and of {@code ? super X} is not. */ private static boolean isShown(TypePath.Step.Kind kind, Type parent) { - if (kind != TypePath.Step.Kind.WILDCARD_BOUND) { + if (kind != TypePath.Step.Kind.WILDCARD_UPPER_BOUND) { return true; } Type.WildcardType wildcard = GenericsUtils.asWildcard(parent); @@ -516,14 +516,14 @@ yield new Track( node instanceof Type.ArrayType arrayType ? Track.located(arrayType.elemtype, track.path().then(TypePath.Step.arrayElement())) : null; // diff-coverage: ignore -- the track stands at the node the check steps from - case WILDCARD_BOUND -> { + case WILDCARD_UPPER_BOUND -> { Type.WildcardType wildcard = GenericsUtils.asWildcard(node); if (wildcard == null) { yield null; // diff-coverage: ignore -- the track stands at the node the check steps from } // the upper bound of `?` and `? super X` is not printed, so the caret stays on the wildcard yield wildcard.kind == BoundKind.EXTENDS - ? Track.located(wildcard.type, track.path().then(TypePath.Step.wildcardBound())) + ? Track.located(wildcard.type, track.path().then(TypePath.Step.wildcardUpperBound())) : new Track( Track.State.HIDDEN, node, @@ -569,10 +569,10 @@ private static Track followDeclared(Track track, Step step) { : null; // diff-coverage: ignore -- the view has this shape case ARRAY_ELEMENT -> declared instanceof Type.ArrayType arrayType ? arrayType.elemtype : null; - case WILDCARD_BOUND, WILDCARD_LOWER_BOUND -> { + case WILDCARD_UPPER_BOUND, WILDCARD_LOWER_BOUND -> { Type.WildcardType wildcard = GenericsUtils.asWildcard(declared); BoundKind kind = - step.kind() == TypePath.Step.Kind.WILDCARD_BOUND + step.kind() == TypePath.Step.Kind.WILDCARD_UPPER_BOUND ? BoundKind.EXTENDS : BoundKind.SUPER; yield wildcard != null && wildcard.kind == kind ? wildcard.type : null; @@ -642,7 +642,6 @@ private static TypePath.Step typeArgumentStep(Type type, int index) { index < formals.size() && formals.get(index) instanceof Type.TypeVar typeVar ? typeVar : null; - return TypePath.Step.typeArgument( - index, formal, type.tsym instanceof Symbol.ClassSymbol owner ? owner : null); + return TypePath.Step.typeArgument(index, formal); } } 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 41912c37ca..4212f9638c 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java @@ -1,7 +1,6 @@ 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; @@ -18,8 +17,7 @@ final class TypePath { /** One descent into a type. */ - record Step( - Kind kind, int index, Type.@Nullable TypeVar formal, Symbol.@Nullable ClassSymbol owner) { + record Step(Kind kind, int index, Type.@Nullable TypeVar formal) { enum Kind { /** Into the type argument at {@link Step#index}. */ @@ -28,34 +26,33 @@ enum Kind { * Into the upper bound of a wildcard: the bound {@code ? extends X} states, and the one * {@code ?} and {@code ? super X} take from their type parameter, which is not printed. */ - WILDCARD_BOUND, + WILDCARD_UPPER_BOUND, /** Into the bound {@code ? super X} states. */ WILDCARD_LOWER_BOUND, - /** Into the element type of an array. */ + /** Into the component type of an array, one dimension down (JLS 10.1). */ 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 typeArgument(int index, Type.@Nullable TypeVar formal) { + return new Step(Kind.TYPE_ARGUMENT, index, formal); } - static Step wildcardBound() { - return new Step(Kind.WILDCARD_BOUND, -1, null, null); + static Step wildcardUpperBound() { + return new Step(Kind.WILDCARD_UPPER_BOUND, -1, null); } static Step wildcardLowerBound() { - return new Step(Kind.WILDCARD_LOWER_BOUND, -1, null, null); + return new Step(Kind.WILDCARD_LOWER_BOUND, -1, null); } static Step arrayElement() { - return new Step(Kind.ARRAY_ELEMENT, -1, null, null); + return new Step(Kind.ARRAY_ELEMENT, -1, null); } static Step enclosingType() { - return new Step(Kind.ENCLOSING_TYPE, -1, null, null); + return new Step(Kind.ENCLOSING_TYPE, -1, null); } /** @@ -73,12 +70,15 @@ boolean reachesSameNodeAs(Step other) { String describe() { return switch (kind) { case TYPE_ARGUMENT -> { - if (formal == null || owner == null) { - yield "type argument " + (index + 1); // diff-coverage: ignore -- the recorder sets both + if (formal == null) { + yield "type argument " + (index + 1); // diff-coverage: ignore -- the recorder sets it } - yield "type argument for " + formal.tsym.getSimpleName() + " of " + owner.getSimpleName(); + yield "type argument for " + + formal.tsym.getSimpleName() + + " of " + + formal.tsym.owner.getSimpleName(); } - case WILDCARD_BOUND -> "upper bound of wildcard"; + case WILDCARD_UPPER_BOUND -> "upper bound of wildcard"; case WILDCARD_LOWER_BOUND -> "lower bound of wildcard"; case ARRAY_ELEMENT -> "component type"; case ENCLOSING_TYPE -> "enclosing type"; 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 b34a38fd6a..deddd3cbdf 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/BytecodeGenericsTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/BytecodeGenericsTests.java @@ -289,7 +289,7 @@ public void genericsChecksForFieldAssignments() { import com.uber.lib.generics.NullableTypeParam; class Test { static void testPositive(NullableTypeParam t1) { - // BUG: Diagnostic contains: incompatible nullability in type argument for E of NullableTypeParam: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of NullableTypeParam: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String NullableTypeParam.staticField = t1; // BUG: Diagnostic contains: incompatible nullability in type argument for E of NullableTypeParam: source has @Nullable String where target requires String NullableTypeParam t2 = NullableTypeParam.staticField; @@ -315,7 +315,7 @@ public void genericsChecksForParamPassingAndReturns() { import com.uber.lib.generics.GenericTypeArgMethods; class Test { static void testPositive(NullableTypeParam t1) { - // BUG: Diagnostic contains: incompatible nullability in type argument for E of NullableTypeParam: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of NullableTypeParam: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String GenericTypeArgMethods.nullableTypeParamArg(t1); // BUG: Diagnostic contains: incompatible nullability in type argument for E of NullableTypeParam: source has @Nullable String where target requires String NullableTypeParam t2 = GenericTypeArgMethods.nullableTypeParamReturn(); 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 13812b831d..eca3da1dc1 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java @@ -396,7 +396,7 @@ static void test( // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: source has @Nullable String where target requires String List invalid = box.get(); box.set(nullableList); - // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String box.set(nonNullList); } } 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 158c3ba86f..437a3e1376 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 nullability in type argument for T of Box: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Box: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String acceptsNullable(flat); } @@ -1337,7 +1337,7 @@ void testNegative() { receiver(makeCancelable(this::target)); } void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of Callback: a non-wildcard type argument must be the same type; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Callback: a non-wildcard type argument must have the same nullness in source and target; source has Object where target requires @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 2a88a88242..a2ff941909 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java @@ -561,7 +561,7 @@ interface B { X b(); } B nonNullB = id1(value); // BUG: Diagnostic contains: incompatible nullability in type argument for X of A: source has @Nullable String where target requires String A nonNullA = id1(value); - // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String B<@Nullable String> nullableB = id1(value); } @@ -574,7 +574,7 @@ interface B { X b(); } B nonNullB = id2(value); // BUG: Diagnostic contains: incompatible nullability in type argument for X of A: source has @Nullable String where target requires String A nonNullA = id2(value); - // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String B<@Nullable String> nullableB = id2(value); } @@ -587,7 +587,7 @@ interface B { X b(); } B nonNullB = id3(value); // BUG: Diagnostic contains: incompatible nullability in type argument for X of A: source has @Nullable String where target requires String A nonNullA = id3(value); - // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String B<@Nullable String> nullableB = id3(value); } @@ -600,7 +600,7 @@ interface B { X b(); } B nonNullB = id4(value); // BUG: Diagnostic contains: incompatible nullability in type argument for X of A: source has @Nullable String where target requires String A nonNullA = id4(value); - // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String B<@Nullable String> nullableB = id4(value); } } @@ -636,7 +636,7 @@ static class Box1> & B>> { B> nonNullB = box.get(); // BUG: Diagnostic contains: incompatible nullability in type argument for X of A -> type argument for E of List: source has @Nullable String where target requires String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String B> nullableB = box.get(); } @@ -654,7 +654,7 @@ static class Box2> & A>> { B> nonNullB = box.get(); // BUG: Diagnostic contains: incompatible nullability in type argument for X of A -> type argument for E of List: source has @Nullable String where target requires String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String B> nullableB = box.get(); } @@ -672,7 +672,7 @@ static class Box3> & B>> B> nonNullB = box.get(); // BUG: Diagnostic contains: incompatible nullability in type argument for X of A -> type argument for E of List: source has @Nullable String where target requires String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String B> nullableB = box.get(); } @@ -690,7 +690,7 @@ static class Box4> & A>> B> nonNullB = box.get(); // BUG: Diagnostic contains: incompatible nullability in type argument for X of A -> type argument for E of List: source has @Nullable String where target requires String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String B> nullableB = box.get(); } } @@ -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 nullability in type argument for T of Foo: a non-wildcard type argument must be the same type; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: a non-wildcard type argument must have the same nullness in source and target; source has Object where target requires @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 nullability in type argument for T of Foo: a non-wildcard type argument must be the same type; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: a non-wildcard type argument must have the same nullness in source and target; source has Object where target requires @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 nullability in type argument for V of Foo -> type argument for E of ArrayList: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for V of Foo -> type argument for E of ArrayList: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String Foo> fooNonNull_2 = f.nonNullTest(); - // BUG: Diagnostic contains: incompatible nullability in type argument for K of Foo: a non-wildcard type argument must be the same type; source has Integer where target requires @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in type argument for K of Foo: a non-wildcard type argument must have the same nullness in source and target; source has Integer where target requires @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 nullability in type argument for T of Foo -> component type -> type argument for T of Foo: a non-wildcard type argument must be the same type; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo -> component type -> type argument for T of Foo: a non-wildcard type argument must have the same nullness in source and target; source has Object where target requires @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 nullability in component type -> type argument for T of Foo: a non-wildcard type argument must be the same type; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in component type -> type argument for T of Foo: a non-wildcard type argument must have the same nullness in source and target; source has Object where target requires @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 nullability in type argument for T of Bar -> type argument for T of Bar: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Bar -> type argument for T of Bar: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @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 nullability in type argument for T of Function and 1 other position: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Function and 1 other differing position: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String 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 nullability in type argument for T of Foo: a non-wildcard type argument must be the same type; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: a non-wildcard type argument must have the same nullness in source and target; source has Object where target requires @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 nullability in type argument for T of Foo: a non-wildcard type argument must be the same type; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: a non-wildcard type argument must have the same nullness in source and target; source has Object where target requires @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 nullability in type argument for T of Foo: a non-wildcard type argument must be the same type; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: a non-wildcard type argument must have the same nullness in source and target; source has Object where target requires @Nullable Object handleFooNullableVarargs(Foo.makeNonNull(new Object())); handleFooNonNullVarargs(Foo.makeNonNull(new Object())); } @@ -2545,7 +2545,7 @@ Supplier make2() { } // tests that our repair computes a consistent substitution for the type variables void test2() { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of Supplier: a non-wildcard type argument must be the same type; source has OuterT where target requires @Nullable OuterT + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Supplier: a non-wildcard type argument must have the same nullness in source and target; source has OuterT where target requires @Nullable OuterT acceptTwoSup(sup, sup2); } } @@ -2733,7 +2733,7 @@ class Test { static class Box {} static void accept(Box<@Nullable T> box) {} void test(Box> box) { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of Box: a non-wildcard type argument must be the same type; source has CompletableFuture where target requires @Nullable CompletableFuture + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Box: a non-wildcard type argument must have the same nullness in source and target; source has CompletableFuture where target requires @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 3c3d1c6037..6e373d7fb1 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java @@ -349,13 +349,13 @@ void callOnResult() { } public void testPositive() { addCallback( - // BUG: Diagnostic contains: incompatible nullability in type argument for T of Callback: a non-wildcard type argument must be the same type; source has Integer where target requires @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Callback: a non-wildcard type argument must have the same nullness in source and target; source has Integer where target requires @Nullable Integer new Callback() { @Override public void onResult(Integer value) { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of Callback: a non-wildcard type argument must be the same type; source has Integer where target requires @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Callback: a non-wildcard type argument must have the same nullness in source and target; source has Integer where target requires @Nullable Integer removeCallback(this); - // BUG: Diagnostic contains: incompatible nullability in type argument for T of Callback: a non-wildcard type argument must be the same type; source has Integer where target requires @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Callback: a non-wildcard type argument must have the same nullness in source and target; source has Integer where target requires @Nullable Integer Callback<@Nullable Integer> self = this; } void callOnResult() { @@ -503,7 +503,7 @@ class Test { static class SampleClass {} static class SampleClassMultipleArguments {} static void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in type argument for E1 of SampleClassMultipleArguments -> type argument for E of SampleClass -> type argument for E of SampleClass: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for E1 of SampleClassMultipleArguments -> type argument for E of SampleClass -> type argument for E of SampleClass: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String SampleClassMultipleArguments>, String> t1 = new SampleClassMultipleArguments>, String>(); } @@ -552,7 +552,7 @@ interface Fn1 {} interface Fn2

{} class FnImpl implements Fn1<@Nullable String, @Nullable String>, Fn2 {} void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in type argument for P of Fn2: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for P of Fn2: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @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 nullability in type argument for P1 of SuperClassC: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for P1 of SuperClassC: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String f = new FnImpl1(); } void testNegative() { @@ -634,7 +634,7 @@ void testNegative() { Super<@Nullable String, String> s = new Sub(); } void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in type argument for A of Super and 1 other position: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for A of Super and 1 other differing position: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String Super<@Nullable String, String> s2 = new Sub<@Nullable String, String>(); } } @@ -1008,7 +1008,7 @@ public String function(T1 o) { } } static void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in type argument for T1 of A: a non-wildcard type argument must be the same type; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T1 of A: a non-wildcard type argument must have the same nullness in source and target; source has Object where target requires @Nullable Object A<@Nullable Object> p = new B<>(); } static void testNegative() { @@ -1034,7 +1034,7 @@ static A testPositive1() { return new A<@Nullable String>(); } static A<@Nullable String> testPositive2() { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String return new A(); } static A<@Nullable String> testNegative() { @@ -1229,11 +1229,11 @@ static void testPositive1(A> a1, A a2) { A a = sampleMethod1(a1, a2); } static void testPositive2(A> a1, A a2) { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of A -> type argument for T of A: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A -> type argument for T of A: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String A a = sampleMethod2(a1, a2); } static void testPositive3(A a1) { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @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 nullability in type argument for T of A: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String p.foo(q); // this one is fine p.foo(p); @@ -1391,7 +1391,7 @@ public void nestedGenericTypeAssignment() { class Test { static class A { } static void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of A -> component type -> type argument for T of A: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A -> component type -> type argument for T of A: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String A[]> var1 = new A[]>(); // BUG: Diagnostic contains: incompatible nullability in type argument for T of A -> component type -> type argument for T of A: source has @Nullable String where target requires String A[]> var2 = new A[]>(); @@ -1435,7 +1435,7 @@ public void genericPrimitiveArrayTypeAssignment() { class Test { static class A { } static void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must be the same type; source has int [] where target requires int @Nullable [] + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must have the same nullness in source and target; source has int [] where target requires int @Nullable [] A x = new A(); } static void testNegative() { @@ -2064,7 +2064,7 @@ void staticSubclassWithNonNullOuterMatches(NonNullInner input) { Outer.Inner result = input; } void staticSubclassWithNonNullOuterMismatches(NonNullInner input) { - // BUG: Diagnostic contains: incompatible nullability in enclosing type -> type argument for T of Outer: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> type argument for T of Outer: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String Outer<@Nullable String>.Inner result = input; } void unrelatedEnclosingTypeMatches(Unrelated.Derived input) { @@ -3041,7 +3041,7 @@ static void test1(Object o) { static void test2(Object o) { var x = (A<@Nullable String> & Serializable) o; x = new B(); - // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String x = new C(); } } @@ -3138,7 +3138,7 @@ void testNegative(Function<@Nullable V, @Nullable V> f) { foo(f); } void testPositive(Function f) { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of Function and 1 other position: a non-wildcard type argument must be the same type; source has V where target requires @Nullable V + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Function and 1 other differing position: a non-wildcard type argument must have the same nullness in source and target; source has V where target requires @Nullable V 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 nullability in component type -> type argument for T of Function and 1 other position: a non-wildcard type argument must be the same type; source has V where target requires @Nullable V + // BUG: Diagnostic contains: incompatible nullability in component type -> type argument for T of Function and 1 other differing position: a non-wildcard type argument must have the same nullness in source and target; source has V where target requires @Nullable V 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 nullability in type argument for T of Function and 1 other position: source has @Nullable String where target requires String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Function and 1 other differing position: source has @Nullable String where target requires String this.<@Nullable String>foo(f); } void testPositiveArray(Function f) { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of Function and 1 other position: source has String @Nullable [] where target requires String [] + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Function and 1 other differing position: source has String @Nullable [] where target requires String [] this.foo(f); } } @@ -3196,11 +3196,11 @@ void testNegative(Function f) { foo(f); } void testPositive1(Function<@Nullable V, V> f) { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of Function and 1 other position: source has @Nullable V where target requires V + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Function and 1 other differing position: source has @Nullable V where target requires V foo(f); } void testPositive2(Function f) { - // BUG: Diagnostic contains: incompatible nullability in type argument for R of Function: a non-wildcard type argument must be the same type; source has V where target requires @Nullable V + // BUG: Diagnostic contains: incompatible nullability in type argument for R of Function: a non-wildcard type argument must have the same nullness in source and target; source has V where target requires @Nullable V foo(f); } void testPositive3(Function<@Nullable V, @Nullable V> 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 nullability in type argument for T of Function and 1 other position: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Function and 1 other differing position: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @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 nullability in type argument for E of List: a non-wildcard type argument must be the same type; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: a non-wildcard type argument must have the same nullness in source and target; source has Object where target requires @Nullable Object super(l); } } @@ -3680,7 +3680,7 @@ class C extends A<@NonNull T> {} void test() { // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: source has @Nullable Object where target requires Object A a = new B(); - // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must be the same type; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must have the same nullness in source and target; source has Object where target requires @Nullable Object A<@Nullable Object> a2 = new C<@Nullable Object>(); } } @@ -3737,7 +3737,7 @@ 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 nullability in type argument for T of Foo: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String Foo<@Nullable String> f1 = nullableFoo.nonNullField; Foo f2 = nullableFoo.nonNullField; Foo<@Nullable String> f3 = nonnullFoo.nullableField; diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java index 6ca561eda6..29df2eb5a1 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java @@ -45,7 +45,7 @@ void acceptsOtherNonNullComponent(Factory factory) { } void rejectsWideningOtherInvariantComponent(Factory factory) { - // BUG: Diagnostic contains: incompatible nullability in type argument for E of B: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of B: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String B<@Nullable String> result = factory.fromA().get(); } @@ -54,7 +54,7 @@ void acceptsMatchingNonNullComponent(Factory factory) { } void rejectsWideningMatchingInvariantComponent(Factory factory) { - // BUG: Diagnostic contains: incompatible nullability in type argument for E of B: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of B: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String B<@Nullable String> result = factory.fromB().get(); } } 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 6f0dcb7fac..ceb6632152 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/JSpecifyArrayTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/JSpecifyArrayTests.java @@ -673,7 +673,7 @@ public void arraysAndGenerics() { class Test { void foo(List<@Nullable Integer[]> l) {} void testPositive(List p) { - // BUG: Diagnostic contains: incompatible nullability in type argument for E of List -> component type: a non-wildcard type argument must be the same type; source has Integer where target requires @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List -> component type: a non-wildcard type argument must have the same nullness in source and target; source has Integer where target requires @Nullable Integer foo(p); } void testNegative(List<@Nullable Integer[]> p) { 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 83f20cf4bc..b7600bea5b 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -1479,7 +1479,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 nullability in type argument for T of Foo: a non-wildcard type argument must be the same type; source has Void where target requires @Nullable Void + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: a non-wildcard type argument must have the same nullness in source and target; source has Void where target requires @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 @@ -1556,7 +1556,7 @@ interface Nested {} return box; } void test(Box> box) { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of Box -> lower bound of wildcard -> type argument for T of Nested: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Box -> lower bound of wildcard -> type argument for T of Nested: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String Box> bad = identity(box); } } 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 index 535496419f..19698ab7c0 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java @@ -116,7 +116,7 @@ void test(Three t) { public void bothPositionsAreMarkedWhereOneInstanceFillsTwoTypeArguments() { assertMessage( """ - incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other position: source has @Nullable Object where target requires Object + incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other differing position: source has @Nullable Object where target requires Object source: Map ^^^^^^^^^^^^ ^^^^^^^^^^^^ 1 2 @@ -207,7 +207,7 @@ void test(List l) { public void twoMismatchesUnderOneWildcardShareItsCaret() { assertMessage( """ - incompatible nullability in type argument for T of Foo -> upper bound of wildcard -> type argument for K of Map and 1 other position: source has @Nullable String where target requires String + incompatible nullability in type argument for T of Foo -> upper bound of wildcard -> type argument for K of Map and 1 other differing position: source has @Nullable String where target requires String source: Foo ^ 1,2 @@ -239,7 +239,7 @@ void test(Foo f) { public void twoMismatchesUnderOneNestedWildcardShareItsCaret() { assertMessage( """ - incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for T of Foo -> upper bound of wildcard -> type argument for K of Map and 1 other position: source has @Nullable String where target requires String + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for T of Foo -> upper bound of wildcard -> type argument for K of Map and 1 other differing position: source has @Nullable String where target requires String source: List> ^ 1,2 diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java index 14e5887d0d..c30785248d 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java @@ -784,6 +784,12 @@ void afterADeclaratorWithBrackets() { List a[] = many(), b = one(); takeOne(b); } + @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) + @interface Tainted {} + void beforeADeclaratorWithAnnotatedBrackets() { + List a = one(), b @Tainted [] = many(); + takeOne(a); + } } """) .expectUnchanged() diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java index c092cba254..dbd4298667 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java @@ -1,5 +1,6 @@ package com.uber.nullaway.jspecify.mismatchmessage; +import java.util.Map; import org.junit.Test; /** @@ -73,4 +74,43 @@ void rawArrayTarget(List<@Nullable String>[] typed) { """)) .doTest(); } + + @Test + public void underALowerBoundTheTargetIsTheSubtypeSide() { + assertMessages( + Map.of( + "REORDERING_SUBCLASS", + """ + incompatible nullability in type argument for E of List -> lower bound of wildcard -> type argument for B of Pair: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + source: List> + ^^^^^^ + target: List> + ^^^^^^^^^^^^^^^^ + """, + "WILDCARD_ONLY_IN_SOURCE", + """ + incompatible nullability in type argument for E of List -> lower bound of wildcard -> type argument for T of Box: source has Object where target requires a supertype of @Nullable String + source: List> + ^^^^^^ + target: List> + ^^^^^^^^^^^^^^^^ + """), + """ + static class Pair {} + static class Rev extends Pair {} + static class Box {} + static List> pairs() { throw new RuntimeException(); } + static List> boxes() { throw new RuntimeException(); } + void reorderingSubclass() { + // BUG: Diagnostic matches: REORDERING_SUBCLASS + List> l = pairs(); + l.hashCode(); + } + void wildcardOnlyInSource() { + // BUG: Diagnostic matches: WILDCARD_ONLY_IN_SOURCE + List> l = boxes(); + l.hashCode(); + } + """); + } } 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 0f24b28c50..fba73df19c 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 @@ -268,7 +268,7 @@ public void aCapturedWildcardNamesTheTypeParameterOnlyWhereItInstantiatesIt() { """, "SUBSTITUTED_INTO_ANOTHER_CLASS", """ - incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other position: source has @Nullable Object where target requires Object + incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other differing position: source has @Nullable Object where target requires Object source: Map ^^^^^^^^^^^^ ^^^^^^^^^^^^ 1 2 @@ -298,7 +298,7 @@ public void aCapturedWildcardNamesTheTypeParameterOnlyWhereItInstantiatesIt() { """, "SUBSTITUTED_AFTER_AN_EARLIER_VIEW", """ - incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other position: source has @Nullable Object where target requires Object + incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other differing position: source has @Nullable Object where target requires Object source: Map ^^^^^^^^^^^^ ^^^^^^^^^^^^ 1 2 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 index 03a3251e83..2757893859 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java @@ -76,7 +76,7 @@ void test(Outer.Inner<@Nullable Integer> i) { public void twoMismatchesInsideOneTypeArgumentSharePathPrefix() { assertMessage( """ - incompatible nullability in type argument for V of Map -> type argument for K of Map and 1 other position: source has @Nullable String where target requires String + incompatible nullability in type argument for V of Map -> type argument for K of Map and 1 other differing position: source has @Nullable String where target requires String source: Map> ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^ 1 2 @@ -105,7 +105,7 @@ void test(Map> m) { public void mismatchesAtDifferentDepthsEachGetTheirOwnPath() { assertMessage( """ - incompatible nullability in type argument for K of Map and 1 other position: source has @Nullable String where target requires String + incompatible nullability in type argument for K of Map and 1 other differing position: source has @Nullable String where target requires String source: Map<@Nullable String, List>> ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^ 1 2 @@ -135,7 +135,7 @@ void test( public void pathReachesATypeArgumentOfAnArrayElement() { assertMessage( """ - incompatible nullability in component type -> type argument for E of List: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + incompatible nullability in component type -> type argument for E of List: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String source: List [] ^^^^^^ target: @Nullable List<@Nullable String> [] diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java index 1706bf58f4..b87c8bb8c6 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java @@ -8,9 +8,9 @@ /** * A {@code possible fix:} line that names the variable the source reads offers the source type - * rewritten with explicit wildcard upper bounds. It appears only where the rewritten type removes - * every difference and prints without losing a type-use annotation. {@link FixTests} checks the - * edit the fix makes. + * rewritten with an explicit upper bound on each wildcard whose implicit bound the target rejects. + * It appears only where the rewritten type removes every difference and prints without losing a + * type-use annotation. {@link FixTests} checks the edit the fix makes. */ public class SourceFixTests extends MismatchMessageTestBase { @@ -18,7 +18,7 @@ public class SourceFixTests extends MismatchMessageTestBase { public void theFixRewritesEveryMismatchingWildcard() { assertMessage( """ - incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other position: source has @Nullable Object where target requires Object + incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other differing position: source has @Nullable Object where target requires Object source: Map ^ ^ 1 2 @@ -223,7 +223,7 @@ void test(List l) { public void noFixWhenAnExplicitBoundMismatchRemains() { assertMessage( """ - incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other position: source has @Nullable Object where target requires Object + incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other differing position: source has @Nullable Object where target requires Object source: Map ^ ^^^^^^^^^^^^^^^^ 1 2 @@ -253,7 +253,7 @@ void test(Map m) { public void noFixWhenAConcreteTypeArgumentAlsoMismatches() { assertMessage( """ - incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other position: source has @Nullable Object where target requires Object + incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other differing position: source has @Nullable Object where target requires Object source: Map ^ ^^^^^^^^^^^^^^^^ 1 2 @@ -283,7 +283,7 @@ void test(Map m) { public void noFixWhenOneMismatchCannotBeRewritten() { assertMessage( """ - incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other position: source has @Nullable Object where target requires Object + incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other differing position: source has @Nullable Object where target requires Object source: Map ^ ^^^^^^^^^^^^^^ 1 2 @@ -488,4 +488,27 @@ void test(List result) { } """); } + + @Test + public void noFixForAMemberReadThroughAParameterizedReceiver() { + assertMessage( + """ + incompatible nullability in type argument for V of Map -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Map> + ^ + target: Map> + ^^^^^^ + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + """, + """ + static class Box { + Map> field = new HashMap<>(); + } + static void takeMap(Map> m) {} + void test(Box b) { + // BUG: Diagnostic matches: MESSAGE + takeMap(b.field); + } + """); + } } 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 index fb96c606be..e2cf61aa88 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java @@ -7,8 +7,8 @@ * The first line of a generic nullability message names the position of the first difference, how * many other positions differ, and the two types at the first one, so that it stands alone where a * tool shows only that line. Where there are several, each gets a numbered entry, five at most, and - * a line after them counts the rest. A non-wildcard type argument must be the same type in the - * source and the target, and the first line says so where the source is the less nullable side. + * a line after them counts the rest. A non-wildcard type argument must have the same nullness in + * the source and the target, and the first line says so where the source is the less nullable side. */ public class SummaryAndNumberingTests extends MismatchMessageTestBase { @@ -16,7 +16,7 @@ public class SummaryAndNumberingTests extends MismatchMessageTestBase { public void listsAtMostFiveMismatchesAndSaysHowManyMoreThereAre() { assertMessage( """ - incompatible nullability in type argument for A of Args -> upper bound of wildcard and 5 other positions: source has @Nullable Object where target requires Object + incompatible nullability in type argument for A of Args -> upper bound of wildcard and 5 other differing positions: source has @Nullable Object where target requires Object source: Args ^ ^ ^ ^ ^ 1 2 3 4 5 @@ -49,7 +49,7 @@ public void listsAtMostFiveMismatchesAndSaysHowManyMoreThereAre() { target: Object note: the unbounded wildcard ? in Args<..., ..., ..., ..., ?, ...> has the upper bound of type parameter E of Args, which is @Nullable Object (JLS 5.1.10) \s - and 1 more, not listed + and 1 more differing position, not listed \s possible fix: declare args as Args """, @@ -67,7 +67,7 @@ void test(Args args) { public void listsFiveMismatchesWithoutSayingThereAreMore() { assertMessage( """ - incompatible nullability in type argument for A of Args -> upper bound of wildcard and 4 other positions: source has @Nullable Object where target requires Object + incompatible nullability in type argument for A of Args -> upper bound of wildcard and 4 other differing positions: source has @Nullable Object where target requires Object source: Args ^ ^ ^ ^ ^ 1 2 3 4 5 @@ -116,7 +116,7 @@ void test(Args args) { public void adjacentTypeArgumentsThatBothMismatchAreNumberedSideBySide() { assertMessage( """ - incompatible nullability in type argument for K of Map and 1 other position: source has @Nullable String where target requires String + incompatible nullability in type argument for K of Map and 1 other differing position: source has @Nullable String where target requires String source: Map<@Nullable String, @Nullable String> ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ 1 2 @@ -142,12 +142,13 @@ void test(Map<@Nullable String, @Nullable String> m) { } @Test - public void everyPositionWhereTheSourceIsLessNullableSaysTheTypeArgumentMustBeTheSameType() { + public void + everyPositionWhereTheSourceIsLessNullableSaysTheTypeArgumentMustHaveTheSameNullness() { assertMessages( Map.of( "ONLY", """ - incompatible nullability in type argument for E of List: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + incompatible nullability in type argument for E of List: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String source: List ^^^^^^ target: List<@Nullable String> @@ -155,7 +156,7 @@ public void everyPositionWhereTheSourceIsLessNullableSaysTheTypeArgumentMustBeTh """, "SECOND", """ - incompatible nullability in type argument for K of Map and 1 other position: source has @Nullable String where target requires String + incompatible nullability in type argument for K of Map and 1 other differing position: source has @Nullable String where target requires String source: Map<@Nullable String, String> ^^^^^^^^^^^^^^^^ ^^^^^^ 1 2 @@ -169,7 +170,7 @@ public void everyPositionWhereTheSourceIsLessNullableSaysTheTypeArgumentMustBeTh \s 2. path: type argument for V of Map source: String - target: @Nullable String (a non-wildcard type argument must be the same type) + target: @Nullable String (a non-wildcard type argument must have the same nullness in source and target) """), """ static void takeMap(Map m) {} @@ -184,4 +185,55 @@ void second(Map<@Nullable String, String> m) { } """); } + + @Test + public void countsSeveralUnlistedMismatchesInThePlural() { + assertMessage( + """ + incompatible nullability in type argument for A of Args -> upper bound of wildcard and 6 other differing positions: source has @Nullable Object where target requires Object + source: Args + ^ ^ ^ ^ ^ + 1 2 3 4 5 + target: Args + ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ + 1 2 3 4 5 + \s + 1. path: type argument for A of Args -> upper bound of wildcard + source: @Nullable Object + target: Object + note: the unbounded wildcard ? in Args has the upper bound of type parameter A of Args, which is @Nullable Object (JLS 5.1.10) + \s + 2. path: type argument for B of Args -> upper bound of wildcard + source: @Nullable Object + target: Object + note: the unbounded wildcard ? in Args<..., ?, ..., ..., ..., ..., ...> has the upper bound of type parameter B of Args, which is @Nullable Object (JLS 5.1.10) + \s + 3. path: type argument for C of Args -> upper bound of wildcard + source: @Nullable Object + target: Object + note: the unbounded wildcard ? in Args<..., ..., ?, ..., ..., ..., ...> has the upper bound of type parameter C of Args, which is @Nullable Object (JLS 5.1.10) + \s + 4. path: type argument for D of Args -> upper bound of wildcard + source: @Nullable Object + target: Object + note: the unbounded wildcard ? in Args<..., ..., ..., ?, ..., ..., ...> has the upper bound of type parameter D of Args, which is @Nullable Object (JLS 5.1.10) + \s + 5. path: type argument for E of Args -> upper bound of wildcard + source: @Nullable Object + target: Object + note: the unbounded wildcard ? in Args<..., ..., ..., ..., ?, ..., ...> has the upper bound of type parameter E of Args, which is @Nullable Object (JLS 5.1.10) + \s + and 2 more differing positions, not listed + \s + possible fix: declare args as Args + """, + """ + static class Args {} + static void take(Args args) {} + void test(Args args) { + // BUG: Diagnostic matches: MESSAGE + take(args); + } + """); + } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java index 6a3fd103e3..a2f4c4c875 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java @@ -9,9 +9,10 @@ /** * A {@code possible fix:} line that names the variable a declaration declares offers the target * type with the nullness of the source. It appears where the diagnostic points at the declaration - * that writes the target type, a local variable declaration, and not at a call, an assignment, or a - * return, whose target type is written somewhere else. It is also withheld where printing it would - * drop a type-use annotation. The fix carries no Error Prone edit, which {@link FixTests} checks. + * that writes the target type, a variable declaration with an initializer, and not at a call, an + * assignment, or a return, whose target type is written somewhere else. It is also withheld where + * printing it would drop a type-use annotation. The fix carries no Error Prone edit, which {@link + * FixTests} checks. */ public class TargetTypeFixTests extends MismatchMessageTestBase { @@ -163,7 +164,7 @@ void test(Sub<@Nullable String> s) { public void theFixReplacesTheNodeAtEveryKindOfStep() { assertMessages( Map.of( - "WILDCARD_BOUND", + "WILDCARD_UPPER_BOUND", """ incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object source: List @@ -214,8 +215,8 @@ void wildcardLowerBound() { List> l = lower(); l.hashCode(); } - void wildcardBound(List list) { - // BUG: Diagnostic matches: WILDCARD_BOUND + void wildcardUpperBound(List list) { + // BUG: Diagnostic matches: WILDCARD_UPPER_BOUND Collection c = list; c.hashCode(); } 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 4505544e0b..ec7433d5fd 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 @@ -108,7 +108,7 @@ void test(Sub s) { Map.of( "SELF", """ - incompatible nullability in type argument for T of Base: a non-wildcard type argument must be the same type; source has Sub where target requires @Nullable Sub + incompatible nullability in type argument for T of Base: a non-wildcard type argument must have the same nullness in source and target; source has Sub where target requires @Nullable Sub source: Sub source supertype: Base ^^^ @@ -117,7 +117,7 @@ void test(Sub s) { """, "ARGUMENT", """ - incompatible nullability in type argument for T of Base: a non-wildcard type argument must be the same type; source has Sub where target requires @Nullable Sub + incompatible nullability in type argument for T of Base: a non-wildcard type argument must have the same nullness in source and target; source has Sub where target requires @Nullable Sub source: Holder source supertype: Base ^^^ @@ -246,7 +246,7 @@ void written(Strings s) { public void eachComponentOfAnIntersectionTargetIsComparedUnderItsOwnView() { assertMessage( """ - incompatible nullability in type argument for T of A and 1 other position: source has @Nullable String where target requires String + incompatible nullability in type argument for T of A and 1 other differing position: source has @Nullable String where target requires String source: B target: A & D \s diff --git a/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java b/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java index 225921bc5f..d0b7882c70 100644 --- a/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java +++ b/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java @@ -611,7 +611,7 @@ public void deeplyNestedTypeAnnot() { @NullMarked public class Test { void testPositive(NestedAnnots> p) { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots -> type argument for T of NestedAnnots: a non-wildcard type argument must be the same type; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots -> type argument for T of NestedAnnots: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String NestedAnnots.deeplyNested(p); } void testNegative(NestedAnnots> p) { @@ -813,7 +813,7 @@ void testPositive() { NestedAnnots.multipleArgs( // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots: source has @Nullable String where target requires String new NestedAnnots<@Nullable String>(), - // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots: a non-wildcard type argument must be the same type; source has Integer where target requires @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots: a non-wildcard type argument must have the same nullness in source and target; source has Integer where target requires @Nullable Integer new NestedAnnots()); } void testNegative() { From 85e55b2f9ca99a6e38deddc8e9cecca373423013 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Mon, 30 Nov 2026 15:10:34 +0300 Subject: [PATCH 32/43] Offer the source fix of a local only where each of its values is shown to accept it The source fix of a local was dropped only where a value assigned to the local was known to reject the rewritten type. Where the type of a value was not computed, the `possible fix:` line was still printed, and applying it could move the error. After `declare s as Source` for `Source s = () -> null;`, NullAway reported the lambda. A resource variable skipped the check entirely, so `try (Res r = open())` got the line even where `open()` rejects the rewrite. The loop variable of an enhanced for loop also skipped it, including assignments to it in the body. Each branch of a conditional expression is now checked as a value of its own, under the path of the conditional, as the conditional check compares each branch with the local's type. A raw value is accepted, since the assignment check skips it. The initializer of a resource variable is recorded and checked in the walk that already indexes the unit. For the variable of an enhanced for loop, the loop's elements count as accepted, since no generic check compares them with the variable's type, and assignments to it in the body are checked. Where a value still cannot be shown to accept the rewrite, such as a lambda, a method reference, or a generic call whose inference has not run, the source fix is not offered. A resource or loop variable gets the line without the edit. User-visible: A local or resource variable source gets no `possible fix:` line for itself unless each value assigned to it is shown to accept the rewritten type; where the target can be fixed, the message offers only that fix. A local initialized by a conditional expression whose branches each accept the rewritten type gets the source fix and its `Did you mean` edit. Assisted-by: Claude Code (claude-opus-5-5) --- .../nullaway/generics/GenericsChecks.java | 45 ++++-- .../generics/LocalVariableDeclarations.java | 73 ++++++---- .../generics/NullabilityMismatchMessage.java | 89 ++++++------ .../mismatchmessage/FixRoundTripTests.java | 137 ++++++++++++++++++ .../jspecify/mismatchmessage/FixTests.java | 10 +- .../mismatchmessage/TargetTypeFixTests.java | 68 +++++++-- 6 files changed, 329 insertions(+), 93 deletions(-) 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 a97c97b8c2..6a4446f60e 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -1020,30 +1020,53 @@ public void checkTypeParameterNullnessForAssignability(Tree tree, VisitorState s /** * Whether the check of {@link #checkTypeParameterNullnessForAssignability} accepts {@code value} * assigned to a local variable of type {@code localType}, for a type other than the local's - * declared one. + * declared one. A conditional expression is accepted where each of its branches is, as {@link + * #checkTypeParameterNullnessForConditionalExpression} checks each branch against the type of the + * local; a raw value is accepted, as the check skips it. * * @param localType the type to check the value against * @param value the path to the initializer of the local or the right-hand side of an assignment * to it * @param state the visitor state - * @return {@code null} where the type of {@code value} cannot be computed without changing what - * the check later computes for it: a lambda, a method reference, or a conditional expression, - * which take their types from the target; a generic call or diamond whose inference the check - * has not yet run, since running it against {@code localType} would cache the result for the - * declared type's check; and a value whose type is raw + * @return {@code false} where the check rejects {@code value} or a branch of it, and otherwise + * {@code null} where the type of {@code value} or of a branch cannot be computed without + * changing what the check later computes for it: a lambda or a method reference, which takes + * its type from the target, and a generic call or diamond whose inference the check has not + * yet run, since running it against {@code localType} would cache the result for the declared + * type's check */ @Nullable Boolean acceptsValueOfLocal(Type localType, TreePath value, VisitorState state) { - ExpressionTree expression = ASTHelpers.stripParentheses((ExpressionTree) value.getLeaf()); + TreePath path = value; + while (path.getLeaf() instanceof ParenthesizedTree parenthesized) { + path = new TreePath(path, parenthesized.getExpression()); + } + ExpressionTree expression = (ExpressionTree) path.getLeaf(); + if (expression instanceof ConditionalExpressionTree conditional) { + Boolean trueBranch = + acceptsValueOfLocal( + localType, new TreePath(path, conditional.getTrueExpression()), state); + if (Boolean.FALSE.equals(trueBranch)) { + return false; + } + Boolean falseBranch = + acceptsValueOfLocal( + localType, new TreePath(path, conditional.getFalseExpression()), state); + if (Boolean.FALSE.equals(falseBranch)) { + return false; + } + return (trueBranch == null || falseBranch == null) ? null : true; + } if (expression instanceof LambdaExpressionTree || expression instanceof MemberReferenceTree - || expression instanceof ConditionalExpressionTree || (isCallNeedingInference(expression) && !inferredTypeVarNullabilityForGenericCalls.containsKey(expression))) { return null; } - Type valueType = - getTypeForRhsOfAssignment( - (ExpressionTree) value.getLeaf(), value, localType, true, state, false); + Type javacType = ASTHelpers.getType(expression); + if (javacType != null && typeOrNullIfRawNonArray(javacType) == null) { + return true; + } + Type valueType = getTypeForRhsOfAssignment(expression, path, localType, true, state, false); return valueType == null ? null : subtypeParameterNullability(localType, valueType, state); } diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java b/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java index 2c21a290d5..a599fdc1b6 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java @@ -27,15 +27,17 @@ /** * Finds the declaration of a local variable of the compilation unit being analyzed. A pattern or - * resource variable is not one, since javac gives each its own element kind, so it is never found. + * resource variable is not one, since javac gives each its own element kind, so it is never found; + * the values assigned to a resource variable are recorded all the same. * *

The first lookup in a compilation unit walks it once and indexes every local variable * declaration it holds; later lookups in the same unit read the index, so a unit with many * diagnostics is walked once rather than once per diagnostic. The same walk notes the declarations * that share their type tree with another variable, as each variable of {@code List a, b;} does, * or its element type, as {@code a} and {@code b} of {@code List a, b[];} do, and records the - * values assigned to each local: its initializer and the right-hand side of each {@code l = expr}. - * {@link #clear} drops the index, which otherwise keeps the trees of the unit alive. + * values assigned to each local or resource variable: its initializer and the right-hand side of + * each {@code l = expr}. {@link #clear} drops the index, which otherwise keeps the trees of the + * unit alive. */ final class LocalVariableDeclarations { @@ -57,8 +59,9 @@ final class LocalVariableDeclarations { private final Set sharingTypeTree = Sets.newIdentityHashSet(); /** - * The paths to the initializer of each local of the indexed unit and to the right-hand side of - * each simple assignment to it, in source order. A local with neither has no entry. + * The paths to the initializer of each local or resource variable of the indexed unit and to the + * right-hand side of each simple assignment to it, in source order. A variable with neither has + * no entry. */ private final Map> assignedValues = new HashMap<>(); @@ -73,9 +76,7 @@ final class LocalVariableDeclarations { if (variable.getKind() != ElementKind.LOCAL_VARIABLE) { return null; } - if (unit != compilationUnit) { - index(compilationUnit); - } + indexOnce(compilationUnit); return paths.get(variable); } @@ -88,20 +89,26 @@ boolean sharesTypeTree(VariableTree declaration) { } /** - * Returns the paths to the values assigned to {@code variable}, a local variable of the - * compilation unit last passed to {@link #find}: its initializer and the right-hand side of each - * simple assignment to it, in source order. Returns {@code null} for the variable of an enhanced - * {@code for} loop, which takes each element of the loop's expression without a tree of its own. + * Whether {@code variable}, a local variable of the compilation unit last indexed, is the + * variable of an enhanced {@code for} loop. + */ + boolean isLoopVariable(Symbol.VarSymbol variable) { + return loopVariables.contains(variable); + } + + /** + * Returns the paths to the values assigned to {@code variable}, a local or resource variable + * declared in the compilation unit of {@code site}: its initializer and the right-hand side of + * each simple assignment to it, in source order. The variable of an enhanced {@code for} loop + * takes each element of the loop's expression without a tree of its own, so only the assignments + * to it are returned. * - *

Each path is rebuilt on {@code site}, a path into the same compilation unit, from the - * deepest tree the two share, so that a path into the method {@code site} is in shares its - * enclosing paths with {@code site}. A dataflow run keyed on the path to that method is then - * reused rather than repeated. + *

Each path is rebuilt on {@code site} from the deepest tree the two share, so that a path + * into the method {@code site} is in shares its enclosing paths with {@code site}. A dataflow run + * keyed on the path to that method is then reused rather than repeated. */ - @Nullable List assignedValues(Symbol.VarSymbol variable, TreePath site) { - if (loopVariables.contains(variable)) { - return null; - } + List assignedValues(Symbol.VarSymbol variable, TreePath site) { + indexOnce(site.getCompilationUnit()); List recorded = assignedValues.getOrDefault(variable, List.of()); IdentityHashMap siteAncestors = new IdentityHashMap<>(); for (TreePath path = site; path != null; path = path.getParentPath()) { @@ -149,6 +156,14 @@ private static TreePath rebuild(TreePath path, IdentityHashMap s return base; } + /** + * Whether {@code symbol} is a local or resource variable, the kinds whose values are recorded. + */ + static boolean isLocalOrResource(Symbol symbol) { + return symbol.getKind() == ElementKind.LOCAL_VARIABLE + || symbol.getKind() == ElementKind.RESOURCE_VARIABLE; + } + /** Forgets the indexed compilation unit. */ void clear() { unit = null; @@ -159,6 +174,13 @@ void clear() { loopVariables.clear(); } + /** Indexes {@code compilationUnit} unless it is the unit indexed last. */ + private void indexOnce(CompilationUnitTree compilationUnit) { + if (unit != compilationUnit) { + index(compilationUnit); + } + } + private void index(CompilationUnitTree compilationUnit) { Consumer listener = indexListener; if (listener != null) { @@ -170,6 +192,11 @@ private void index(CompilationUnitTree compilationUnit) { @Override public @Nullable Void visitVariable(VariableTree variable, @Nullable Void unused) { Symbol symbol = ASTHelpers.getSymbol(variable); + // the initializer of a resource variable, which is implicitly final, is its only value + ExpressionTree initializer = variable.getInitializer(); + if (initializer != null && symbol != null && isLocalOrResource(symbol)) { + recordValue(symbol, initializer); + } if (symbol != null && symbol.getKind() == ElementKind.LOCAL_VARIABLE) { paths.put(symbol, getCurrentPath()); Tree typeTree = baseTypeTree(variable.getType()); @@ -180,10 +207,6 @@ private void index(CompilationUnitTree compilationUnit) { sharingTypeTree.add(variable); } } - ExpressionTree initializer = variable.getInitializer(); - if (initializer != null) { - recordValue(symbol, initializer); - } // a loop body cannot be a declaration, so a declaration under the loop is its variable if (getCurrentPath().getParentPath().getLeaf() instanceof EnhancedForLoopTree) { loopVariables.add(symbol); @@ -195,7 +218,7 @@ private void index(CompilationUnitTree compilationUnit) { @Override public @Nullable Void visitAssignment(AssignmentTree assignment, @Nullable Void unused) { Symbol symbol = ASTHelpers.getSymbol(assignment.getVariable()); - if (symbol != null && symbol.getKind() == ElementKind.LOCAL_VARIABLE) { + if (symbol != null && isLocalOrResource(symbol)) { recordValue(symbol, assignment.getExpression()); } return super.visitAssignment(assignment, 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 index 0c59c224d8..89efdee230 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -121,18 +121,22 @@ * under {@code possible fixes}, the source first, each with the condition under which it is the * right one. * - *

The source fix of a local variable of the compilation unit being analyzed is checked once - * more: the rewrite makes the local's type less nullable, so the values assigned to it, its - * initializer and the right-hand side of each assignment to it, are the only pseudo-assignments it - * can break. Where the check rejects one of them against the rewritten type, the source fix is not - * offered. Only the source fix comes with an Error Prone fix that makes the edit, and only where - * the check accepts every one of those values, the local is not a pattern, resource, or enhanced - * {@code for} variable, and its declaration writes its type out before the name and declares no - * other variable. A run that suggests suppressions asks for the suppression instead. A parameter or - * a field gets the line without the edit: its type is a contract that callers, overriders, and - * other assignments rely on, and the check that accepts the rewrite consults none of them. The - * target fix never gets the edit, since the rewritten variable may be read as a source anywhere in - * its scope. + *

The source fix of a local or resource variable of the compilation unit being analyzed is + * checked once more: the rewrite makes the variable's type less nullable, so the values assigned to + * it, its initializer and the right-hand side of each assignment to it, are the only + * pseudo-assignments it can break. The source fix is offered only where the check is shown to + * accept each of them against the rewritten type. Each branch of a conditional expression counts as + * a value of its own, and a raw value is accepted, as the check skips it. A lambda, a method + * reference, or a generic call or diamond whose inference the check has not run yet cannot be shown + * accepted, so a variable holding one gets no source fix. The elements an enhanced {@code for} loop + * gives its variable count as accepted, since no generic check compares them with its type. Only + * the source fix comes with an Error Prone fix that makes the edit, and only where the variable is + * a local other than a pattern or enhanced {@code for} variable, and its declaration writes its + * type out before the name and declares no other variable. A run that suggests suppressions asks + * for the suppression instead. A parameter or a field gets the line without the check or the edit: + * its type is a contract that callers, overriders, and other assignments rely on, and the check + * that accepts the rewrite consults none of them. The target fix never gets the edit, since the + * rewritten variable may be read as a source anywhere in its scope. * *

The two candidates differ in what they presume. Writing an explicit bound on a wildcard the * source declaration already writes is a mechanical fix of that wildcard, so it is offered wherever @@ -283,21 +287,19 @@ Report build( Type rewrittenSourceType = sourceVariable == null ? null : sourceTypeFix(targetType, sourceType, mismatches); TreePath sourceDeclaration = null; - Boolean valuesAccept = null; - if (sourceVariable != null && rewrittenSourceType != null) { - // the type of a parameter or a field is a contract that callers, overriders, and other - // assignments rely on, and the check that accepts the rewrite consults none of them - sourceDeclaration = - checks - .localVariableDeclarations() - .find(sourceVariable, state.getPath().getCompilationUnit()); - if (sourceDeclaration != null) { - valuesAccept = valuesAccept(sourceVariable, rewrittenSourceType); - if (Boolean.FALSE.equals(valuesAccept)) { - // a value the local already holds rejects the rewrite, so the fix would only move the - // error - rewrittenSourceType = null; - } + // the type of a parameter or a field is a contract that callers, overriders, and other + // assignments rely on, and the check that accepts the rewrite consults none of them + if (sourceVariable != null + && rewrittenSourceType != null + && LocalVariableDeclarations.isLocalOrResource(sourceVariable)) { + if (valuesAccept(sourceVariable, rewrittenSourceType)) { + sourceDeclaration = + checks + .localVariableDeclarations() + .find(sourceVariable, state.getPath().getCompilationUnit()); + } else { + // a value the variable holds rejects the rewrite, or may, so the fix could move the error + rewrittenSourceType = null; } } Symbol.VarSymbol targetVariable = @@ -319,7 +321,9 @@ Report build( .append("\n possible fix: ") .append(declaration(sourceVariable, rewrittenSourceType)); } - if (sourceDeclaration != null && Boolean.TRUE.equals(valuesAccept)) { + // no check compares the loop's elements with the rewritten type, so no edit is shown to hold + if (sourceDeclaration != null + && !checks.localVariableDeclarations().isLoopVariable(sourceVariable)) { addSourceFixEdit(fixes, sourceDeclaration, rewrittenSourceType); } } else if (targetVariable != null && rewrittenTargetType != null) { @@ -341,29 +345,20 @@ private String declaration(Symbol.VarSymbol variable, Type type) { } /** - * Whether the check accepts against {@code type} every value assigned to {@code variable}, a - * local variable of the compilation unit being analyzed: its initializer and the right-hand side - * of each assignment to it. Returns {@code false} where one of them rejects {@code type}, and - * otherwise {@code null} where the type of one cannot be computed or {@code variable} is the - * variable of an enhanced {@code for} loop. + * Whether the check is shown to accept against {@code type} every value assigned to {@code + * variable}, a local or resource variable of the compilation unit being analyzed: its initializer + * and the right-hand side of each assignment to it. The elements an enhanced {@code for} loop + * gives its variable count as accepted, since no generic check compares them with its type. + * Returns {@code false} where one value is rejected or its type cannot be computed. */ - private @Nullable Boolean valuesAccept(Symbol.VarSymbol variable, Type type) { - List values = - checks.localVariableDeclarations().assignedValues(variable, state.getPath()); - if (values == null) { - return null; - } - Boolean result = true; - for (TreePath value : values) { - Boolean accepted = checks.acceptsValueOfLocal(type, value, state.withPath(value)); - if (Boolean.FALSE.equals(accepted)) { + private boolean valuesAccept(Symbol.VarSymbol variable, Type type) { + for (TreePath value : + checks.localVariableDeclarations().assignedValues(variable, state.getPath())) { + if (!Boolean.TRUE.equals(checks.acceptsValueOfLocal(type, value, state.withPath(value)))) { return false; } - if (accepted == null) { - result = null; - } } - return result; + return true; } /** diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java index 19b3b442ea..ff5d4cc4c0 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java @@ -243,6 +243,143 @@ class Local {} """); } + @Test + public void conditionalWithABranchThatRejectsTheRewrite() { + assertRoundTrip( + """ + static void take(Collection c) {} + static List make() { + throw new RuntimeException(); + } + void test(boolean flag) { + List l = flag ? new ArrayList() : make(); + take(l); + } + """); + } + + @Test + public void nestedConditionalWithABranchThatRejectsTheRewrite() { + assertRoundTrip( + """ + static void take(Collection c) {} + static List make() { + throw new RuntimeException(); + } + void test(boolean flag, boolean other) { + List l = (flag ? new ArrayList() : (other ? new ArrayList() : make())); + take(l); + } + """); + } + + @Test + public void conditionalWhoseBranchesAcceptTheRewrite() { + assertRoundTrip( + """ + static void take(Collection c) {} + void test(boolean flag) { + List l = flag ? new ArrayList() : new ArrayList(); + take(l); + } + """); + } + + @Test + public void lambdaInitializer() { + assertRoundTrip( + """ + interface Source { + T get(); + } + static void take(Source s) {} + void test() { + Source s = () -> null; + take(s); + } + """); + } + + @Test + public void resourceVariableWhoseInitializerRejectsTheRewrite() { + assertRoundTrip( + """ + static class Res implements AutoCloseable { + @Override + public void close() {} + } + static void take(Res resource) {} + static Res open() { + throw new RuntimeException(); + } + void test() { + try (Res r = open()) { + take(r); + } + } + """); + } + + @Test + public void resourceVariableWhoseInitializerAcceptsTheRewrite() { + assertRoundTrip( + """ + static class Res implements AutoCloseable { + @Override + public void close() {} + } + static void take(Res resource) {} + void test() { + try (Res r = new Res()) { + take(r); + } + } + """); + } + + @Test + public void loopVariable() { + assertRoundTrip( + """ + static void take(Collection c) {} + void test(List> lists) { + for (List l : lists) { + take(l); + } + } + """); + } + + @Test + public void loopVariableReassignedToAValueThatRejectsTheRewrite() { + assertRoundTrip( + """ + static void take(Collection c) {} + static List make() { + throw new RuntimeException(); + } + void test(List> lists) { + for (List l : lists) { + l = make(); + take(l); + } + } + """); + } + + @Test + public void rawInitializer() { + assertRoundTrip( + """ + static void take(Collection c) {} + @SuppressWarnings("rawtypes") + void test(List raw) { + List l = raw; + take(l); + } + """); + } + @Test public void sourceFixOfAParameter() { assertRoundTrip( diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java index c30785248d..5e6455ecd6 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java @@ -267,6 +267,10 @@ void conditional(boolean b, List x, List y) { List l = b ? x : y; take(l); } + void conditionalWithABranchThatRejects(boolean b, List x) { + List l = (b ? x : (b ? x : make())); + take(l); + } void lambda() { Supplier s = () -> "a"; takeSupplier(s); @@ -333,7 +337,11 @@ void inferredCallAfterTheReport() { l = List.of("a"); } void conditional(boolean b, List x, List y) { - List l = b ? x : y; + List l = b ? x : y; + take(l); + } + void conditionalWithABranchThatRejects(boolean b, List x) { + List l = (b ? x : (b ? x : make())); take(l); } void lambda() { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java index a2f4c4c875..42aad9858c 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java @@ -65,7 +65,8 @@ Map returned(Map m } @Test - public void aMismatchFixableOnEitherSideListsBothFixesUnlessAValueOfTheSourceRejectsItsFix() { + public void + aMismatchFixableOnEitherSideListsTheSourceFixOnlyWhereEveryValueOfTheSourceAcceptsIt() { assertMessages( Map.of( "BOTH", @@ -81,6 +82,19 @@ public void aMismatchFixableOnEitherSideListsBothFixesUnlessAValueOfTheSourceRej if it may: declare c as Collection Did you mean 'List list = new ArrayList();'? """, + "BOTH_FOR_A_CONDITIONAL", + """ + incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: List + ^ + target: Collection + ^^^^^^ + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + possible fixes: + if list never holds null: declare list as List + if it may: declare c as Collection + Did you mean 'List list = flag ? new ArrayList() : new ArrayList();'? + """, "BOTH_WITHOUT_EDIT", """ incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object @@ -102,40 +116,76 @@ public void aMismatchFixableOnEitherSideListsBothFixesUnlessAValueOfTheSourceRej ^^^^^^ note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) possible fix: declare c as Collection + """, + "TARGET_ONLY_FOR_A_LAMBDA", + """ + incompatible nullability in type argument for T of Source -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Source + ^ + target: Source + ^^^^^^ + note: the unbounded wildcard ? in Source has the upper bound of type parameter T of Source, which is @Nullable Object (JLS 5.1.10) + possible fix: declare s as Source """), """ + interface Source { + T get(); + } static List make() { throw new RuntimeException(); } - void valuesAcceptTheSourceFix() { + void initializerAccepts() { List list = new ArrayList(); // BUG: Diagnostic matches: BOTH Collection c = list; c.hashCode(); } - void aValueOfUnknownTypeKeepsTheSourceFixWithoutItsEdit(boolean flag, List raw) { + void eachBranchOfAConditionalAccepts(boolean flag) { List list = flag ? new ArrayList() : new ArrayList(); - // BUG: Diagnostic matches: BOTH_WITHOUT_EDIT + // BUG: Diagnostic matches: BOTH_FOR_A_CONDITIONAL Collection c = list; c.hashCode(); + } + @SuppressWarnings("rawtypes") + void rawInitializer(List raw) { List fromRaw = raw; - // BUG: Diagnostic contains: if fromRaw never holds null: declare fromRaw as List - Collection d = fromRaw; - d.hashCode(); + // BUG: Diagnostic contains: Did you mean 'List fromRaw = raw;'? + Collection c = fromRaw; + c.hashCode(); } - void aLoopVariableKeepsTheSourceFixWithoutItsEdit(List> lists) { + void loopVariable(List> lists) { for (List list : lists) { // BUG: Diagnostic matches: BOTH_WITHOUT_EDIT Collection c = list; c.hashCode(); } } - void initializerRejectsTheSourceFix() { + void initializerRejects() { List list = make(); // BUG: Diagnostic matches: TARGET_ONLY Collection c = list; c.hashCode(); } + void aBranchOfAConditionalRejects(boolean flag) { + List list = flag ? new ArrayList() : make(); + // BUG: Diagnostic matches: TARGET_ONLY + Collection c = list; + c.hashCode(); + } + void loopVariableReassignedToAValueThatRejects(List> lists) { + for (List list : lists) { + list = make(); + // BUG: Diagnostic matches: TARGET_ONLY + Collection c = list; + c.hashCode(); + } + } + void lambdaInitializer() { + Source source = () -> "a"; + // BUG: Diagnostic matches: TARGET_ONLY_FOR_A_LAMBDA + Source s = source; + s.hashCode(); + } """); } From bf28d51ce44428c1d5c45afe4648403ca7a8bbac Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Mon, 30 Nov 2026 15:59:07 +0300 Subject: [PATCH 33/43] Withhold a fix the printer cannot write as declared, and check each local value once MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four gaps in the `possible fix:` lines of a generic nullability mismatch message. The printer writes an annotation named `Nullable` without its element values and writes none on a wildcard, but the declarability check accepted both. So `Map` got `declare m as Map`, which does not compile where `value` is required. The target fix had the same gap where it copied such an annotation from the source. The check also looked only at the rewritten type, which a rewrite builds from new nodes, so an annotation on the node it replaced was dropped silently: `Map d = m` got `declare d as Map`, and `Map<@Tainted ?, String>` lost its `@Tainted`. A fix is now offered only where the printer reproduces every annotation of both the declared type it replaces and the type it declares: `@Nullable` with no element values, and no annotation on a wildcard. The target fix copies a nullable annotation only where it has no element values. The source fix of a local checked every value assigned to the local against the rewritten type once per diagnostic that read the local, so a local with W values read R times cost R × W checks. A definite result is now kept per value tree and rewritten type, keyed by `Type.toString()`, which qualifies names and keeps annotations, and cleared with the unit's index. An unknown result, such as a generic call whose inference has not run yet, is computed again on the next read. A pattern variable, and any variable kind other than a local, resource, parameter, or field, got an unchecked source fix. Only those four kinds now get one: a local or resource where its values are shown to accept the rewrite, and a parameter or field unchecked, as before. User-visible: No `possible fix:` line is offered where the declared type it replaces or the type it declares carries a type-use annotation other than `@Nullable`, a `@Nullable` with element values, or an annotation on a wildcard. A pattern variable gets no source fix; a target fix beside it is unchanged. Assisted-by: Claude Code (claude-opus-5-5) --- .../GenericTypePrettyPrintingVisitor.java | 23 ++++ .../generics/LocalVariableDeclarations.java | 42 ++++++- .../generics/NullabilityMismatchMessage.java | 109 +++++++++++------- .../generics/MismatchMessageWorkTests.java | 85 ++++++++++++-- .../mismatchmessage/FixRoundTripTests.java | 46 ++++++++ .../mismatchmessage/SourceFixTests.java | 103 ++++++++++++++++- .../mismatchmessage/TargetTypeFixTests.java | 65 ++++++++++- 7 files changed, 422 insertions(+), 51 deletions(-) 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 32d49fe658..ebb873d4a1 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java @@ -143,6 +143,29 @@ static String printForFixLine(Type type, VisitorState state) { return null; } + /** + * Returns whether the printer prints {@code compound} as it is written: its simple name is {@code + * Nullable}, and it has no element values, which the printer never writes. So {@code @Nullable} + * is reproduced and {@code @Nullable("reason")} is not. + */ + static boolean reproduces(Attribute.TypeCompound compound) { + return compound.type.tsym.getSimpleName().contentEquals("Nullable") + && compound.values.isEmpty(); + } + + /** + * Returns whether the printer prints every type-use annotation on {@code type} itself as it is + * written, which holds where there is none, or one that {@link #reproduces}. A wildcard's own + * annotations are never printed, so a wildcard holds this only where it has none. + */ + static boolean printsEveryAnnotation(Type type) { + List annotations = type.getAnnotationMirrors(); + return annotations.isEmpty() + || (!(type instanceof Type.WildcardType) + && annotations.size() == 1 + && reproduces(annotations.get(0))); + } + /** * Returns whether the printer prints the enclosing type of {@code t} before its name, as in * {@code Outer.Inner}. It does for a member class with an enclosing instance, as javac's diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java b/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java index a599fdc1b6..eea14da245 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java @@ -14,6 +14,7 @@ import com.sun.source.util.TreePath; import com.sun.source.util.TreePathScanner; import com.sun.tools.javac.code.Symbol; +import com.sun.tools.javac.code.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -22,6 +23,7 @@ import java.util.Map; import java.util.Set; import java.util.function.Consumer; +import java.util.function.Supplier; import javax.lang.model.element.ElementKind; import org.jspecify.annotations.Nullable; @@ -47,6 +49,12 @@ final class LocalVariableDeclarations { */ @VisibleForTesting static volatile @Nullable Consumer indexListener; + /** + * Receives each value whose acceptance {@link #acceptance} computes rather than reads from its + * cache. Tests set it to count the checks; it is {@code null} otherwise. + */ + @VisibleForTesting static volatile @Nullable Consumer acceptanceListener; + /** The compilation unit {@link #paths} indexes, or {@code null} before the first lookup. */ private @Nullable CompilationUnitTree unit; @@ -68,6 +76,13 @@ final class LocalVariableDeclarations { /** The variables of the enhanced {@code for} loops of the indexed unit. */ private final Set loopVariables = new HashSet<>(); + /** + * Whether the check accepts each value of the indexed unit against a rewritten type, keyed by the + * value's tree and the rewritten type's {@code toString()}, which qualifies every name and keeps + * every annotation. An unknown result is not kept. + */ + private final IdentityHashMap> acceptances = new IdentityHashMap<>(); + /** * Returns the path to the declaration of {@code variable} in {@code compilationUnit}, or {@code * null} where {@code variable} is not a local variable declared there. @@ -164,6 +179,30 @@ static boolean isLocalOrResource(Symbol symbol) { || symbol.getKind() == ElementKind.RESOURCE_VARIABLE; } + /** + * Returns whether the check accepts {@code value}, a value of a local or resource variable of the + * indexed unit, against {@code type}, as {@code check} computes it. A definite result is computed + * once per value and type, however many diagnostics read the variable; an unknown one, {@code + * null}, is computed again, since an inference that has not run yet may run before the next read. + */ + @Nullable Boolean acceptance(Tree value, Type type, Supplier<@Nullable Boolean> check) { + Map byType = acceptances.computeIfAbsent(value, unused -> new HashMap<>()); + String key = type.toString(); + Boolean known = byType.get(key); + if (known != null) { + return known; + } + Consumer listener = acceptanceListener; + if (listener != null) { + listener.accept(value); + } + Boolean computed = check.get(); + if (computed != null) { + byType.put(key, computed); + } + return computed; + } + /** Forgets the indexed compilation unit. */ void clear() { unit = null; @@ -172,6 +211,7 @@ void clear() { sharingTypeTree.clear(); assignedValues.clear(); loopVariables.clear(); + acceptances.clear(); } /** Indexes {@code compilationUnit} unless it is the unit indexed last. */ @@ -192,7 +232,7 @@ private void index(CompilationUnitTree compilationUnit) { @Override public @Nullable Void visitVariable(VariableTree variable, @Nullable Void unused) { Symbol symbol = ASTHelpers.getSymbol(variable); - // the initializer of a resource variable, which is implicitly final, is its only value + // a value is the initializer of a local or resource variable, or an assignment to one ExpressionTree initializer = variable.getInitializer(); if (initializer != null && symbol != null && isLocalOrResource(symbol)) { recordValue(symbol, initializer); 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 89efdee230..9661d7886d 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -3,6 +3,8 @@ import static com.uber.nullaway.generics.TypeMetadataBuilder.TYPE_METADATA_BUILDER; import com.google.common.base.Verify; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Sets; import com.google.errorprone.VisitorState; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.util.ASTHelpers; @@ -11,7 +13,6 @@ import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; -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; @@ -26,6 +27,7 @@ import java.util.IdentityHashMap; import java.util.List; import java.util.function.Function; +import javax.lang.model.element.ElementKind; import javax.lang.model.type.TypeKind; import org.jspecify.annotations.Nullable; @@ -131,12 +133,13 @@ * accepted, so a variable holding one gets no source fix. The elements an enhanced {@code for} loop * gives its variable count as accepted, since no generic check compares them with its type. Only * the source fix comes with an Error Prone fix that makes the edit, and only where the variable is - * a local other than a pattern or enhanced {@code for} variable, and its declaration writes its - * type out before the name and declares no other variable. A run that suggests suppressions asks - * for the suppression instead. A parameter or a field gets the line without the check or the edit: - * its type is a contract that callers, overriders, and other assignments rely on, and the check - * that accepts the rewrite consults none of them. The target fix never gets the edit, since the - * rewritten variable may be read as a source anywhere in its scope. + * a local other than an enhanced {@code for} variable, and its declaration writes its type out + * before the name and declares no other variable. A run that suggests suppressions asks for the + * suppression instead. A parameter or a field gets the line without the check or the edit: its type + * is a contract that callers, overriders, and other assignments rely on, and the check that accepts + * the rewrite consults none of them. A variable of any other kind, such as a pattern variable, gets + * no source fix, since no check compares its values with a rewritten type. The target fix never + * gets the edit, since the rewritten variable may be read as a source anywhere in its scope. * *

The two candidates differ in what they presume. Writing an explicit bound on a wildcard the * source declaration already writes is a mechanical fix of that wildcard, so it is offered wherever @@ -147,11 +150,13 @@ * 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 fix also has to survive printing. The printer shows an annotation named {@code Nullable} and - * drops every other type-use annotation, a custom nullable annotation of another name included, and - * it writes the dimensions of a nested array in the reverse of the order a declaration gives them, - * so a type carrying another annotation, or an annotation on a dimension of a nested array, is not - * offered. + *

A fix also has to survive printing. The printer shows an annotation named {@code Nullable} + * without its element values, shows none on a wildcard, and drops every other type-use annotation, + * a custom nullable annotation of another name included. It also writes the dimensions of a nested + * array in the reverse of the order a declaration gives them. So a fix is not offered where the + * declared type it replaces or the type it declares carries an annotation the printer would drop or + * change, such as {@code @Nullable("reason")}, an annotated wildcard, or an annotation on a + * dimension of a nested array. */ final class NullabilityMismatchMessage { @@ -284,8 +289,12 @@ Report build( mismatches.size() - listed.size() == 1 ? "" : "s")); } Symbol.VarSymbol sourceVariable = sourceVariable(sourceExpression, sourceType); + // the declared type is checked as well as the rewritten one, since a rewrite builds new nodes + // and drops an annotation the declaration writes on the node it replaces Type rewrittenSourceType = - sourceVariable == null ? null : sourceTypeFix(targetType, sourceType, mismatches); + (sourceVariable == null || !isDeclarable(sourceVariable.type)) + ? null + : sourceTypeFix(targetType, sourceType, mismatches); TreePath sourceDeclaration = null; // the type of a parameter or a field is a contract that callers, overriders, and other // assignments rely on, and the check that accepts the rewrite consults none of them @@ -305,7 +314,9 @@ Report build( Symbol.VarSymbol targetVariable = targetTypeDeclaration == null ? null : ASTHelpers.getSymbol(targetTypeDeclaration); Type rewrittenTargetType = - targetVariable == null ? null : targetTypeFix(targetType, sourceType, mismatches); + (targetVariable == null || !isDeclarable(targetVariable.type)) + ? null + : targetTypeFix(targetType, sourceType, mismatches); List fixes = new ArrayList<>(); if (sourceVariable != null && rewrittenSourceType != null) { message.append(separator); @@ -321,7 +332,9 @@ Report build( .append("\n possible fix: ") .append(declaration(sourceVariable, rewrittenSourceType)); } - // no check compares the loop's elements with the rewritten type, so no edit is shown to hold + // a loop variable's line is offered because no check compares the loop's elements with + // its type, so no error can move to them; an edit would rest on that missing check rather + // than on a check that passed, so none is attached if (sourceDeclaration != null && !checks.localVariableDeclarations().isLoopVariable(sourceVariable)) { addSourceFixEdit(fixes, sourceDeclaration, rewrittenSourceType); @@ -354,7 +367,14 @@ private String declaration(Symbol.VarSymbol variable, Type type) { private boolean valuesAccept(Symbol.VarSymbol variable, Type type) { for (TreePath value : checks.localVariableDeclarations().assignedValues(variable, state.getPath())) { - if (!Boolean.TRUE.equals(checks.acceptsValueOfLocal(type, value, state.withPath(value)))) { + Boolean accepted = + checks + .localVariableDeclarations() + .acceptance( + value.getLeaf(), + type, + () -> checks.acceptsValueOfLocal(type, value, state.withPath(value))); + if (!Boolean.TRUE.equals(accepted)) { return false; } } @@ -406,15 +426,30 @@ private boolean hasNullableModifier(VariableTree declaration) { } /** - * Returns the variable {@code sourceExpression} reads, where it is declared in the compilation - * unit being analyzed with the very type {@code sourceType}, so that a rewrite of that type is a - * rewrite of the declaration; {@code null} otherwise. + * The kinds of variable that can get a source fix. A local or resource variable gets it where its + * values are shown to accept the rewrite, and a parameter or a field gets it unchecked. Any other + * kind, such as a pattern variable or a catch parameter, has values no check compares with a + * rewritten type, so it gets none. + */ + private static final ImmutableSet FIXABLE_SOURCE_KINDS = + Sets.immutableEnumSet( + ElementKind.LOCAL_VARIABLE, + ElementKind.RESOURCE_VARIABLE, + ElementKind.PARAMETER, + ElementKind.FIELD); + + /** + * Returns the variable {@code sourceExpression} reads, where it is of a kind in {@link + * #FIXABLE_SOURCE_KINDS} and is declared in the compilation unit being analyzed with the very + * type {@code sourceType}, so that a rewrite of that type is a rewrite of the declaration; {@code + * null} otherwise. */ private Symbol.@Nullable VarSymbol sourceVariable( @Nullable ExpressionTree sourceExpression, Type sourceType) { if (sourceExpression == null || !(ASTHelpers.getSymbol(ASTHelpers.stripParentheses(sourceExpression)) - instanceof Symbol.VarSymbol variable)) { + instanceof Symbol.VarSymbol variable) + || !FIXABLE_SOURCE_KINDS.contains(variable.getKind())) { return null; } // a member read through a parameterized receiver has a type the declaration does not state, @@ -969,7 +1004,8 @@ private String withOtherTypeArgumentsElided(Type.ClassType holder, int index) { /** * Returns {@code target} with {@code @Nullable} added where {@code source} carries it, or {@code * null} where {@code source} is not {@code @Nullable}, {@code target} already is, or the - * annotation to copy cannot be found. + * annotation to copy cannot be found or is not one the printer {@linkplain + * GenericTypePrettyPrintingVisitor#reproduces reproduces}. * *

The fix 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 @@ -982,6 +1018,8 @@ private String withOtherTypeArgumentsElided(Type.ClassType holder, int index) { return source.getAnnotationMirrors().stream() .filter(annotation -> Nullness.isNullableAnnotation(annotation.type.toString(), config)) .findFirst() + // the copy keeps only the annotation's type, so one with element values is not copied + .filter(GenericTypePrettyPrintingVisitor::reproduces) .map(annotation -> TypeSubstitutionUtils.typeWithAnnot(target, annotation.type)) .orElse(null); } @@ -1107,8 +1145,10 @@ public Type visitWildcardType(Type.WildcardType t, @Nullable Void unused) { * says what the reader gets. * *

This mirrors {@link GenericTypePrettyPrintingVisitor}, which prints the annotation {@link - * GenericTypePrettyPrintingVisitor#printedAnnotation} returns and drops every other type-use - * annotation, prints the enclosing type only where {@link + * GenericTypePrettyPrintingVisitor#printedAnnotation} returns without its element values, prints + * no annotation on a wildcard, and drops every other type-use annotation, so a type is declarable + * only where {@link GenericTypePrettyPrintingVisitor#printsEveryAnnotation} holds at each node. + * It prints the enclosing type only where {@link * GenericTypePrettyPrintingVisitor#printsEnclosingType} holds, and has four arms whose output no * declaration may hold or that denotes nothing: a captured wildcard prints as {@code capture of * ?}, an intersection as {@code A & B}, an anonymous class under its binary name, and a type that @@ -1125,7 +1165,9 @@ private boolean isDeclarable(Type type) { new Types.DefaultTypeVisitor<>() { @Override public Boolean visitClassType(Type.ClassType t, @Nullable Void unused) { - if (t.isIntersection() || t.tsym.isAnonymous() || !printsEveryAnnotation(t)) { + if (t.isIntersection() + || t.tsym.isAnonymous() + || !GenericTypePrettyPrintingVisitor.printsEveryAnnotation(t)) { return false; } for (Type typeArgument : t.getTypeArguments()) { @@ -1139,7 +1181,7 @@ public Boolean visitClassType(Type.ClassType t, @Nullable Void unused) { @Override public Boolean visitWildcardType(Type.WildcardType t, @Nullable Void unused) { - return printsEveryAnnotation(t) + return GenericTypePrettyPrintingVisitor.printsEveryAnnotation(t) && (t.kind == BoundKind.UNBOUND || t.type.accept(this, null)); } @@ -1150,7 +1192,8 @@ public Boolean visitArrayType(Type.ArrayType t, @Nullable Void unused) { if (t.elemtype instanceof Type.ArrayType && hasAnnotatedDimension(t)) { return false; } - return printsEveryAnnotation(t) && t.elemtype.accept(this, null); + return GenericTypePrettyPrintingVisitor.printsEveryAnnotation(t) + && t.elemtype.accept(this, null); } @Override @@ -1165,7 +1208,7 @@ public Boolean visitErrorType(Type.ErrorType t, @Nullable Void unused) { @Override public Boolean visitType(Type t, @Nullable Void unused) { - return printsEveryAnnotation(t); + return GenericTypePrettyPrintingVisitor.printsEveryAnnotation(t); } }; @@ -1179,18 +1222,6 @@ private static boolean hasAnnotatedDimension(Type.ArrayType array) { return false; } - /** - * Returns whether every type-use annotation on {@code type} itself is the one the printer prints, - * so that a custom nullable annotation of another name withholds the fix rather than being - * dropped from it. - */ - private static boolean printsEveryAnnotation(Type type) { - List annotations = type.getAnnotationMirrors(); - return annotations.isEmpty() - || (annotations.size() == 1 - && GenericTypePrettyPrintingVisitor.printedAnnotation(type) != null); - } - /** Returns the named class declaring {@code typeVariable}, or {@code null} if there is none. */ private static Symbol.@Nullable ClassSymbol typeVariableOwner( Type.@Nullable TypeVar typeVariable) { diff --git a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java index 8de6f57c47..da6a466416 100644 --- a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java @@ -13,7 +13,8 @@ /** * Building a generic nullability mismatch message walks the compilation unit to find the local * variable a fix rewrites. The walk happens at most once per unit, and not at all for a mismatch - * whose error is suppressed. + * whose error is suppressed. Whether the check accepts a value of that local against the rewritten + * type is computed once per value and type, however many diagnostics read the local. */ public class MismatchMessageWorkTests { @@ -51,6 +52,64 @@ Collection returned() { .containsExactly("Test.java"); } + @Test + public void eachValueOfALocalIsCheckedOnceForEveryDiagnosticThatReadsIt() { + List checks = Collections.synchronizedList(new ArrayList<>()); + LocalVariableDeclarations.acceptanceListener = value -> checks.add(value.toString()); + try { + compile( + """ + import java.util.ArrayList; + import java.util.Collection; + import java.util.LinkedList; + import java.util.List; + import org.jspecify.annotations.NullMarked; + @NullMarked + class Test { + static void take(Collection c) {} + void everyValueAccepts() { + List l = new ArrayList(); + l = new ArrayList(); + l = new LinkedList(); + // BUG: Diagnostic contains: possible fix: declare l as List + take(l); + // BUG: Diagnostic contains: possible fix: declare l as List + take(l); + // BUG: Diagnostic contains: possible fix: declare l as List + take(l); + } + void oneValueIsUnknown() { + List l = new ArrayList(); + l = new LinkedList(); + // BUG: Diagnostic contains: incompatible nullability + take(l); + // BUG: Diagnostic contains: incompatible nullability + take(l); + // BUG: Diagnostic contains: incompatible nullability + take(l); + l = List.of("b"); + } + } + """); + } finally { + LocalVariableDeclarations.acceptanceListener = null; + } + assertWithMessage( + "values whose acceptance was computed rather than read from the cache; a definite" + + " result is kept, and the unknown one, a call whose inference runs only after" + + " the reads, is computed for each read") + .that(checks) + .containsExactly( + "new ArrayList()", + "new ArrayList()", + "new LinkedList()", + "new ArrayList()", + "new LinkedList()", + "List.of(\"b\")", + "List.of(\"b\")", + "List.of(\"b\")"); + } + @Test public void aParameterOrFieldSourceCostsNoWalk() { List walks = @@ -132,17 +191,25 @@ private List walksWhileCompiling(String source, String... extraArgs) { walks.add(path.substring(path.lastIndexOf('/') + 1)); }; try { - CompilationTestHelper.newInstance(NullAway.class, getClass()) - .setArgs( - JSpecifyJavacConfig.withJSpecifyModeArgs( - Stream.concat( - Stream.of("-XepOpt:NullAway:OnlyNullMarked=true"), Stream.of(extraArgs)) - .toList())) - .addSourceLines("Test.java", source) - .doTest(); + compile(source, extraArgs); } finally { LocalVariableDeclarations.indexListener = null; } return walks; } + + /** + * Compiles {@code source} as {@code Test.java} in JSpecify mode with {@code extraArgs}, expecting + * the diagnostics its {@code // BUG: Diagnostic contains:} comments mark and no others. + */ + private void compile(String source, String... extraArgs) { + CompilationTestHelper.newInstance(NullAway.class, getClass()) + .setArgs( + JSpecifyJavacConfig.withJSpecifyModeArgs( + Stream.concat( + Stream.of("-XepOpt:NullAway:OnlyNullMarked=true"), Stream.of(extraArgs)) + .toList())) + .addSourceLines("Test.java", source) + .doTest(); + } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java index ff5d4cc4c0..57e2e05c11 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java @@ -380,6 +380,31 @@ void test(List raw) { """); } + @Test + public void sourceFixWithANullableAnnotationThatHasAValue() { + assertRoundTrip( + """ + static void take(Map m) {} + void test() { + Map m = new HashMap(); + take(m); + } + """, + NULLABLE_WITH_A_VALUE); + } + + @Test + public void targetFixCopyingANullableAnnotationThatHasAValue() { + assertRoundTrip( + """ + void test(Map m) { + Map d = m; + d.hashCode(); + } + """, + NULLABLE_WITH_A_VALUE); + } + @Test public void sourceFixOfAParameter() { assertRoundTrip( @@ -403,6 +428,27 @@ void test() { """); } + /** + * A type-use nullable annotation named {@code Nullable} with a required element, {@code + * p.Nullable}, and the flag that names it. + */ + private static final Extra NULLABLE_WITH_A_VALUE = + new Extra( + Map.of( + "p/Nullable.java", + """ + package p; + import java.lang.annotation.ElementType; + import java.lang.annotation.Target; + @Target(ElementType.TYPE_USE) + public @interface Nullable { + String value(); + } + """), + "", + List.of("-XepOpt:NullAway:CustomNullableAnnotations=p.Nullable"), + Set.of("Nullable")); + /** A custom type-use nullable annotation, {@code p.CanBeNull}, and the flag that names it. */ private static final Extra CAN_BE_NULL = new Extra( diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java index b87c8bb8c6..d108aba0c6 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java @@ -356,6 +356,57 @@ void test(List l) { // The printer drops @Tainted and the custom nullable @CanBeNull from the printed types, so // TAINTED and CUSTOM_NULLABLE differ from PLAIN only by the missing fix line. + @Test + public void aPatternVariableGetsNoSourceFix() { + assertMessages( + Map.of( + "NO_FIX", + """ + incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: List + ^ + target: Collection + ^^^^^^ + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + """, + "TARGET_FIX_ONLY", + """ + incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: List + ^ + target: Collection + ^^^^^^ + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + possible fix: declare c as Collection + """), + """ + static void take(Collection c) {} + static List make() { + throw new RuntimeException(); + } + void pattern(Object o) { + if (o instanceof List l) { + // BUG: Diagnostic matches: NO_FIX + take(l); + } + } + void reassignedPattern(Object o) { + if (o instanceof List l) { + l = make(); + // BUG: Diagnostic matches: NO_FIX + take(l); + } + } + void patternWithATargetFix(Object o) { + if (o instanceof List l) { + // BUG: Diagnostic matches: TARGET_FIX_ONLY + Collection c = l; + c.hashCode(); + } + } + """); + } + @Test public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { CompilationTestHelper helper = @@ -363,8 +414,35 @@ public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { JSpecifyJavacConfig.withJSpecifyModeArgs( List.of( "-XepOpt:NullAway:OnlyNullMarked=true", - "-XepOpt:NullAway:CustomNullableAnnotations=Test.CanBeNull"))); + "-XepOpt:NullAway:CustomNullableAnnotations=Test.CanBeNull,p.Nullable"))); Map.of( + "NULLABLE_WITH_A_VALUE", + """ + incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Map + ^ + target: Map + ^^^^^^ + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + """, + "ANNOTATED_WILDCARD", + """ + incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Map + ^ + target: Map + ^^^^^^ + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + """, + "NULLABLE_WILDCARD", + """ + incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Map + ^ + target: Map + ^^^^^^ + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + """, "PLAIN", """ incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object @@ -431,7 +509,30 @@ void taintedArrayElement(Map m) { // BUG: Diagnostic matches: TAINTED_ARRAY_ELEMENT takeArrays(m); } + static void takeNullableValues(Map m) {} + void nullableWithAValue(Map m) { + // BUG: Diagnostic matches: NULLABLE_WITH_A_VALUE + takeNullableValues(m); + } + void annotatedWildcard(Map<@Tainted ?, String> m) { + // BUG: Diagnostic matches: ANNOTATED_WILDCARD + take(m); + } + // BUG: Diagnostic contains: nullness annotations cannot be written directly on a wildcard + void nullableWildcard(Map<@Nullable ?, String> m) { + // BUG: Diagnostic matches: NULLABLE_WILDCARD + take(m); + } """)) + .addSourceLines( + "p/Nullable.java", + """ + package p; + @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) + public @interface Nullable { + String value(); + } + """) .doTest(); } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java index 42aad9858c..eb95ffdfeb 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java @@ -293,7 +293,41 @@ public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { JSpecifyJavacConfig.withJSpecifyModeArgs( List.of( "-XepOpt:NullAway:OnlyNullMarked=true", - "-XepOpt:NullAway:CustomNullableAnnotations=Test.CanBeNull"))); + "-XepOpt:NullAway:CustomNullableAnnotations=Test.CanBeNull,p.Nullable"))); + Map.of( + "NULLABLE_WITH_A_VALUE", + """ + incompatible nullability in type argument for V of Map: source has @Nullable String where target requires String + source: Map + ^^^^^^^^^^^^^^^^ + target: Map + ^^^^^^ + """, + "TAINTED_REPLACED_NODE", + """ + incompatible nullability in type argument for V of Map: source has @Nullable String where target requires String + source: Map + ^^^^^^^^^^^^^^^^ + target: Map + ^^^^^^ + """, + "TAINTED_ROOT", + """ + incompatible nullability in type argument for V of Map: source has @Nullable String where target requires String + source: Map + ^^^^^^^^^^^^^^^^ + target: Map + ^^^^^^ + """, + "ANNOTATED_WILDCARD", + """ + incompatible nullability in type argument for V of Map: source has @Nullable String where target requires String + source: Map + ^^^^^^^^^^^^^^^^ + target: Map + ^^^^^^ + """) + .forEach((key, expected) -> helper.expectErrorMessage(key, messageIs(expected))); Map.of( "PLAIN", """ @@ -401,7 +435,36 @@ void customNullable(Map m) { Map d = m; d.hashCode(); } + void nullableWithAValue(Map m) { + // BUG: Diagnostic matches: NULLABLE_WITH_A_VALUE + Map d = m; + d.hashCode(); + } + void taintedReplacedNode(Map m) { + // BUG: Diagnostic matches: TAINTED_REPLACED_NODE + Map d = m; + d.hashCode(); + } + void taintedRoot(Map m) { + // BUG: Diagnostic matches: TAINTED_ROOT + @Tainted Map d = m; + d.hashCode(); + } + void annotatedWildcard(Map m) { + // BUG: Diagnostic matches: ANNOTATED_WILDCARD + Map<@Tainted ? extends String, String> d = m; + d.hashCode(); + } """)) + .addSourceLines( + "p/Nullable.java", + """ + package p; + @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) + public @interface Nullable { + String value(); + } + """) .doTest(); } } From 1759a84e4541e8028103389b880d7cd06760d414 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Mon, 30 Nov 2026 16:35:43 +0300 Subject: [PATCH 34/43] Print a captured bound by type parameter and withhold a lambda parameter's fix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A `note:` about a captured wildcard printed the capture's upper bound as javac holds it, and that bound refers to the captures of the class that holds the wildcard. For `Self>` and a `Self` source, the note read `whose upper bound is @Nullable Comparable`. The note now prints each capture among the holder's type arguments as the type parameter it instantiates: `@Nullable Comparable`. Where the note does not name the holder's class, a type parameter of that class or of a class enclosing it would name nothing, so the note is left out, as it is where the bound still holds a capture. The note on an unbounded wildcard below the root of a supertype view printed such a capture too, and is left out the same way. A lambda parameter, explicitly or implicitly typed, got `declare l as List`. The functional interface fixes that type: the line compiles, since javac treats `List` and `List` as the same type, and NullAway then reports the parameter as one whose type arguments differ from those of the method it overrides. A lambda parameter now gets no source fix. `FixRoundTripTests` counts that report as well as a generic mismatch on the lines it checks. Each diagnostic that read a local rebuilt the path of every value assigned to it before looking up the kept result, so D reads of a local with A values cost D × A rebuilds. A path is now rebuilt only where the check runs, and the values after an unknown one are still checked so that their definite results are kept. User-visible: A `note:` about a captured wildcard prints a type parameter of the class that holds it where its bound used to print `capture of ?`, and is left out where the bound cannot be printed without one. A lambda parameter gets no `possible fix:` line for itself. Assisted-by: Claude Code (claude-opus-5-5) --- .../GenericTypePrettyPrintingVisitor.java | 8 +- .../generics/LocalVariableDeclarations.java | 64 +++-- .../generics/NullabilityMismatchMessage.java | 232 +++++++++++++++--- .../generics/NullabilityMismatches.java | 16 +- .../generics/MismatchMessageWorkTests.java | 44 +++- .../mismatchmessage/FixRoundTripTests.java | 44 +++- .../jspecify/mismatchmessage/NoteTests.java | 109 ++++++++ .../mismatchmessage/SourceFixTests.java | 48 +++- 8 files changed, 492 insertions(+), 73 deletions(-) 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 ebb873d4a1..5cd3b72108 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java @@ -284,11 +284,13 @@ public String visitClassType(Type.ClassType t, @Nullable Void s) { if (t.getTypeArguments().nonEmpty()) { sb.append('<'); StringBuilder arguments = new StringBuilder(); - for (int i = 0; i < t.getTypeArguments().size(); i++) { - if (i > 0) { + int index = 0; + for (Type typeArgument : t.getTypeArguments()) { + if (index > 0) { arguments.append(", "); } - arguments.append(descend(TypePath.Step.typeArgument(i, null), t.getTypeArguments().get(i))); + arguments.append(descend(TypePath.Step.typeArgument(index, null), typeArgument)); + index++; } sb.append(arguments); sb.append(">"); diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java b/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java index eea14da245..2e35abc544 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java @@ -23,6 +23,7 @@ import java.util.Map; import java.util.Set; import java.util.function.Consumer; +import java.util.function.Function; import java.util.function.Supplier; import javax.lang.model.element.ElementKind; import org.jspecify.annotations.Nullable; @@ -55,6 +56,12 @@ final class LocalVariableDeclarations { */ @VisibleForTesting static volatile @Nullable Consumer acceptanceListener; + /** + * Receives the leaf of each path {@link #onSite} rebuilds. Tests set it to count the rebuilds; it + * is {@code null} otherwise. + */ + @VisibleForTesting static volatile @Nullable Consumer rebuildListener; + /** The compilation unit {@link #paths} indexes, or {@code null} before the first lookup. */ private @Nullable CompilationUnitTree unit; @@ -113,27 +120,46 @@ boolean isLoopVariable(Symbol.VarSymbol variable) { /** * Returns the paths to the values assigned to {@code variable}, a local or resource variable - * declared in the compilation unit of {@code site}: its initializer and the right-hand side of - * each simple assignment to it, in source order. The variable of an enhanced {@code for} loop - * takes each element of the loop's expression without a tree of its own, so only the assignments - * to it are returned. + * declared in {@code compilationUnit}: its initializer and the right-hand side of each simple + * assignment to it, in source order. The variable of an enhanced {@code for} loop takes each + * element of the loop's expression without a tree of its own, so only the assignments to it are + * returned. * - *

Each path is rebuilt on {@code site} from the deepest tree the two share, so that a path - * into the method {@code site} is in shares its enclosing paths with {@code site}. A dataflow run - * keyed on the path to that method is then reused rather than repeated. + *

A path is the one the walk recorded, so its enclosing paths are not those of the site being + * analyzed; {@link #onSite} rebuilds it before anything computes a type on it. */ - List assignedValues(Symbol.VarSymbol variable, TreePath site) { - indexOnce(site.getCompilationUnit()); - List recorded = assignedValues.getOrDefault(variable, List.of()); - IdentityHashMap siteAncestors = new IdentityHashMap<>(); - for (TreePath path = site; path != null; path = path.getParentPath()) { - siteAncestors.put(path.getLeaf(), path); - } - List rebuilt = new ArrayList<>(recorded.size()); - for (TreePath value : recorded) { - rebuilt.add(rebuild(value, siteAncestors)); - } - return rebuilt; + List assignedValues(Symbol.VarSymbol variable, CompilationUnitTree compilationUnit) { + indexOnce(compilationUnit); + return assignedValues.getOrDefault(variable, List.of()); + } + + /** + * Returns a function that rebuilds a path {@link #assignedValues} returns on {@code site}, from + * the deepest tree the two share, so that a path into the method {@code site} is in shares its + * enclosing paths with {@code site}. A dataflow run keyed on the path to that method is then + * reused rather than repeated. The ancestors of {@code site} are collected on the first call. + */ + static Function onSite(TreePath site) { + return new Function<>() { + private @Nullable IdentityHashMap siteAncestors; + + @Override + public TreePath apply(TreePath value) { + IdentityHashMap ancestors = siteAncestors; + if (ancestors == null) { + ancestors = new IdentityHashMap<>(); + for (TreePath path = site; path != null; path = path.getParentPath()) { + ancestors.put(path.getLeaf(), path); + } + siteAncestors = ancestors; + } + Consumer listener = rebuildListener; + if (listener != null) { + listener.accept(value.getLeaf()); + } + return rebuild(value, ancestors); + } + }; } /** 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 9661d7886d..b35fdd00c7 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -10,6 +10,7 @@ import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.ExpressionTree; +import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; @@ -25,8 +26,10 @@ import com.uber.nullaway.handlers.Handler; import java.util.ArrayList; import java.util.IdentityHashMap; +import java.util.Iterator; import java.util.List; import java.util.function.Function; +import java.util.function.Predicate; import javax.lang.model.element.ElementKind; import javax.lang.model.type.TypeKind; import org.jspecify.annotations.Nullable; @@ -137,9 +140,10 @@ * before the name and declares no other variable. A run that suggests suppressions asks for the * suppression instead. A parameter or a field gets the line without the check or the edit: its type * is a contract that callers, overriders, and other assignments rely on, and the check that accepts - * the rewrite consults none of them. A variable of any other kind, such as a pattern variable, gets - * no source fix, since no check compares its values with a rewritten type. The target fix never - * gets the edit, since the rewritten variable may be read as a source anywhere in its scope. + * the rewrite consults none of them. A parameter of a lambda expression gets no source fix, since + * the functional interface fixes its type. A variable of any other kind gets none either; {@link + * #FIXABLE_SOURCE_KINDS} gives the reason for each. The target fix never gets the edit, since the + * rewritten variable may be read as a source anywhere in its scope. * *

The two candidates differ in what they presume. Writing an explicit bound on a wildcard the * source declaration already writes is a mechanical fix of that wildcard, so it is offered wherever @@ -365,20 +369,29 @@ private String declaration(Symbol.VarSymbol variable, Type type) { * Returns {@code false} where one value is rejected or its type cannot be computed. */ private boolean valuesAccept(Symbol.VarSymbol variable, Type type) { - for (TreePath value : - checks.localVariableDeclarations().assignedValues(variable, state.getPath())) { + LocalVariableDeclarations declarations = checks.localVariableDeclarations(); + // a value whose acceptance is kept needs no path, so a path is rebuilt only where the check + // runs + Function onSite = LocalVariableDeclarations.onSite(state.getPath()); + boolean everyValueAccepts = true; + for (TreePath recorded : + declarations.assignedValues(variable, state.getPath().getCompilationUnit())) { Boolean accepted = - checks - .localVariableDeclarations() - .acceptance( - value.getLeaf(), - type, - () -> checks.acceptsValueOfLocal(type, value, state.withPath(value))); - if (!Boolean.TRUE.equals(accepted)) { + declarations.acceptance( + recorded.getLeaf(), + type, + () -> { + TreePath value = onSite.apply(recorded); + return checks.acceptsValueOfLocal(type, value, state.withPath(value)); + }); + if (Boolean.FALSE.equals(accepted)) { return false; } + // an unknown value already leaves the fix out; the values after it are still checked so that + // their definite results are kept for the next diagnostic that reads the variable + everyValueAccepts &= accepted != null; } - return true; + return everyValueAccepts; } /** @@ -426,10 +439,22 @@ private boolean hasNullableModifier(VariableTree declaration) { } /** - * The kinds of variable that can get a source fix. A local or resource variable gets it where its - * values are shown to accept the rewrite, and a parameter or a field gets it unchecked. Any other - * kind, such as a pattern variable or a catch parameter, has values no check compares with a - * rewritten type, so it gets none. + * The kinds of variable that can get a source fix. The type of a local or resource variable is + * not a contract, so it gets the fix where each of its values is shown to accept the rewrite. The + * type of a parameter or a field is a contract, so it gets the line as text, with no check of its + * values and no edit; a parameter of a lambda expression gets none (see {@link + * #isLambdaParameter}). The other kinds get none: + * + *

    + *
  • a pattern variable takes its value from the expression the pattern matches, which the + * value check of a local does not cover; + *
  • a catch parameter has a type that takes no type arguments (JLS 8.1.2, 14.20), so it is + * never the source of a generic mismatch; + *
  • an enum constant has the type of its enum, which declares no type parameters (JLS 8.9), + * so no bound written on it can change the mismatch; + *
  • a record component is read through its field or its accessor, so no source expression + * names it. + *
*/ private static final ImmutableSet FIXABLE_SOURCE_KINDS = Sets.immutableEnumSet( @@ -449,7 +474,8 @@ private boolean hasNullableModifier(VariableTree declaration) { if (sourceExpression == null || !(ASTHelpers.getSymbol(ASTHelpers.stripParentheses(sourceExpression)) instanceof Symbol.VarSymbol variable) - || !FIXABLE_SOURCE_KINDS.contains(variable.getKind())) { + || !FIXABLE_SOURCE_KINDS.contains(variable.getKind()) + || isLambdaParameter(variable)) { return null; } // a member read through a parameterized receiver has a type the declaration does not state, @@ -467,6 +493,30 @@ private boolean hasNullableModifier(VariableTree declaration) { : null; } + /** + * Whether {@code variable} is a parameter of a lambda expression enclosing the site being + * analyzed, which is where a read of it can be. The functional interface fixes the type of such a + * parameter: javac rejects a declared type the function type does not have (JLS 15.27.3), and + * NullAway reports one that differs from it only in nullness, as {@code List} + * for {@code List}, as a parameter that does not match the one it overrides. So a rewrite of + * its type moves the error rather than fixing it. + */ + private boolean isLambdaParameter(Symbol.VarSymbol variable) { + if (variable.getKind() != ElementKind.PARAMETER) { + return false; + } + for (TreePath path = state.getPath(); path != null; path = path.getParentPath()) { + if (path.getLeaf() instanceof LambdaExpressionTree lambda) { + for (VariableTree parameter : lambda.getParameters()) { + if (variable.equals(ASTHelpers.getSymbol(parameter))) { + return true; + } + } + } + } + return false; + } + /** * The line a reader sees first, and the only one some tools show, so it stands alone: it names * where the first difference sits, how many other positions differ, and the pair at the first. @@ -736,6 +786,7 @@ && nodeAt(printed, caret.steps().subList(0, caret.steps().size() - 1)) return capturedWildcardNote( capture, wildcard, + holder == null ? null : holder.type(), declaredBoundAgrees ? formalTypeVariable : null, owner, hidden == null ? null : hidden.bound()); @@ -758,12 +809,13 @@ && nodeAt(printed, caret.steps().subList(0, caret.steps().size() - 1)) // it instantiates has no named owner. The note says what the bound is and leaves where it // came from alone. "in the source" tells it from a wildcard of the target; below the root the // ? itself is in a declaration this message does not print + Type upperBound = GenericsUtils.wildcardUpperBound(wildcard, state, config, handler); + if (printsTypeVariable(upperBound, Type.CapturedType.class::isInstance)) { + return null; + } return String.format( "%s in the source%s %s (JLS 5.1.10)", - source, - hasBound, - GenericsChecks.prettyTypeForError( - GenericsUtils.wildcardUpperBound(wildcard, state, config, handler), state)); + source, hasBound, GenericsChecks.prettyTypeForError(upperBound, state)); } if (!declaredBoundAgrees) { return null; @@ -794,17 +846,26 @@ private record PrintedHolder( /** * Returns the note for a captured wildcard: its upper bound as the check compared it, and the * type parameter it is the type argument for where the caller names one and the captured wildcard - * instantiates that same one. + * instantiates that same one; {@code null} where the bound cannot be printed without a capture or + * a type parameter the note does not name the class of. + * + *

The bound of a capture refers to the captures the class holds as its type arguments, its own + * included where the type parameter's bound refers to it, as in {@code Self>}. Each capture among the type arguments of {@code holder} is printed as the type + * parameter it instantiates. * + * @param holder the printed class type that holds {@code capture} as a type argument, or {@code + * null} where the wildcard sits at no position of a printed type * @param formalTypeVariable the type parameter the caret's last step reaches, where its declared * bound agrees with the nullness the check found; {@code null} otherwise * @param owner the class of {@code formalTypeVariable}, or {@code null} where it has none * @param comparedBound the upper bound of the capture the check compared, or {@code null} where * the check did not go below the capture */ - private String capturedWildcardNote( + private @Nullable String capturedWildcardNote( Type.CapturedType capture, Type.WildcardType wildcard, + Type.@Nullable ClassType holder, Type.@Nullable TypeVar formalTypeVariable, Symbol.@Nullable ClassSymbol owner, @Nullable Type comparedBound) { @@ -813,7 +874,6 @@ private String capturedWildcardNote( ? comparedBound : GenericsUtils.effectiveWildcardUpperBound(capture, state, config, handler); String captured = "capture of " + GenericsChecks.prettyTypeForError(wildcard, state); - String bound = GenericsChecks.prettyTypeForError(upperBound, state); // WildcardType.bound names the type parameter the wildcard was last substituted for, so it // only confirms the caret's type parameter and never names one by itself Type.TypeVar instantiated = wildcard.bound; @@ -821,8 +881,15 @@ private String capturedWildcardNote( || owner == null || instantiated == null || !instantiated.tsym.equals(formalTypeVariable.tsym)) { - return String.format( - "%s is a captured wildcard whose upper bound is %s (JLS 5.1.10)", captured, bound); + String bound = printedCapturedBound(upperBound, holder, null); + return bound == null + ? null + : String.format( + "%s is a captured wildcard whose upper bound is %s (JLS 5.1.10)", captured, bound); + } + String bound = printedCapturedBound(upperBound, holder, owner); + if (bound == null) { + return null; } String note = String.format( @@ -834,6 +901,102 @@ private String capturedWildcardNote( : note; } + /** + * Returns {@code bound} printed with each capture among the type arguments of {@code holder} + * replaced by the type parameter it instantiates, or {@code null} where the result still prints a + * capture, or prints a type parameter of {@code holder}'s class or of a class enclosing it while + * {@code namedClass} is another class or {@code null}. + * + * @param holder the printed class type whose captures are replaced, or {@code null} for none + * @param namedClass the class the note names, or {@code null} where it names none + */ + private @Nullable String printedCapturedBound( + Type bound, Type.@Nullable ClassType holder, Symbol.@Nullable ClassSymbol namedClass) { + Type printed = bound; + if (holder != null) { + ListBuffer from = new ListBuffer<>(); + ListBuffer to = new ListBuffer<>(); + Iterator formal = holder.tsym.type.getTypeArguments().iterator(); + for (Type argument : holder.getTypeArguments()) { + Type parameter = formal.next(); + if (argument instanceof Type.CapturedType) { + from.append(argument); + to.append(parameter); + } + } + // Types.subst finds a capture by identity, ignoring its annotations, and does not descend + // into its bound + printed = + TypeSubstitutionUtils.subst(state.getTypes(), bound, from.toList(), to.toList(), config); + Symbol holderClass = holder.tsym; + if (!holderClass.equals(namedClass) + && printsTypeVariable( + printed, + t -> + !(t instanceof Type.CapturedType) + && t.tsym.owner instanceof Symbol.ClassSymbol declaring + && holderClass.isEnclosedBy(declaring))) { + return null; + } + } + if (printsTypeVariable(printed, Type.CapturedType.class::isInstance)) { + return null; + } + return GenericsChecks.prettyTypeForError(printed, state); + } + + /** + * Returns whether {@code type} prints a type variable for which {@code matches} holds, a capture + * included. A type variable prints as its name, so its bounds are not searched. + */ + private static boolean printsTypeVariable(Type type, Predicate matches) { + return type.accept( + new Types.DefaultTypeVisitor() { + @Override + public Boolean visitClassType(Type.ClassType t, @Nullable Void unused) { + if (t instanceof Type.IntersectionClassType intersection) { + return anyPrints(intersection.getComponents()); + } + return anyPrints(t.getTypeArguments()) || t.getEnclosingType().accept(this, null); + } + + private boolean anyPrints(List types) { + for (Type component : types) { + if (component.accept(this, null)) { + return true; + } + } + return false; + } + + @Override + public Boolean visitWildcardType(Type.WildcardType t, @Nullable Void unused) { + return t.type.accept(this, null); + } + + @Override + public Boolean visitArrayType(Type.ArrayType t, @Nullable Void unused) { + return t.elemtype.accept(this, null); + } + + @Override + public Boolean visitTypeVar(Type.TypeVar t, @Nullable Void unused) { + return matches.test(t); + } + + @Override + public Boolean visitCapturedType(Type.CapturedType t, @Nullable Void unused) { + return matches.test(t); + } + + @Override + public Boolean visitType(Type t, @Nullable Void unused) { + return false; + } + }, + null); + } + /** * Returns the upper bound the type parameter at {@code index} of {@code holder}'s class declares, * with each type argument of {@code holder} that is not a wildcard or a capture substituted for @@ -843,13 +1006,13 @@ private String capturedWildcardNote( */ private Type boundWithStatedArgumentsSubstituted(Type.ClassType holder, int index) { List formals = holder.tsym.type.getTypeArguments(); - List arguments = holder.getTypeArguments(); ListBuffer from = new ListBuffer<>(); ListBuffer to = new ListBuffer<>(); - for (int i = 0; i < arguments.size(); i++) { - Type argument = arguments.get(i); + Iterator formal = formals.iterator(); + for (Type argument : holder.getTypeArguments()) { + Type parameter = formal.next(); if (GenericsUtils.asWildcard(argument) == null && !(argument instanceof Type.CapturedType)) { - from.append(formals.get(i)); + from.append(parameter); to.append(argument); } } @@ -943,12 +1106,11 @@ private boolean hasNullnessAt(Type bound, TypePath steps, Type sourceNode) { * wildcard a note means, and a long type the {@code source} line already prints is not repeated. */ private String withOtherTypeArgumentsElided(Type.ClassType holder, int index) { - List typeArguments = holder.getTypeArguments(); List printed = new ArrayList<>(); - for (int i = 0; i < typeArguments.size(); i++) { - String argument = GenericsChecks.prettyTypeForError(typeArguments.get(i), state); + for (Type typeArgument : holder.getTypeArguments()) { + String argument = GenericsChecks.prettyTypeForError(typeArgument, state); printed.add( - i == index || (argument.indexOf('<') < 0 && argument.indexOf('?') < 0) + printed.size() == index || (argument.indexOf('<') < 0 && argument.indexOf('?') < 0) ? argument : "..."); } 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 e8609c14f3..b9dc82a9c3 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java @@ -8,6 +8,7 @@ import com.sun.tools.javac.code.Types; import com.uber.nullaway.Config; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; import org.jspecify.annotations.Nullable; @@ -618,12 +619,17 @@ private static Track followDeclared(Track track, Step step) { TypePath actualPath = path; while (declaredForm instanceof Type.ClassType declaredClass && actual instanceof Type.ClassType actualClass) { - List formals = declaredClass.getTypeArguments(); - List arguments = actualClass.getTypeArguments(); - for (int i = 0; i < formals.size() && i < arguments.size(); i++) { - if (formals.get(i).tsym.equals(typeVariable.tsym)) { - return Track.located(arguments.get(i), actualPath.then(typeArgumentStep(actualClass, i))); + Iterator arguments = actualClass.getTypeArguments().iterator(); + int index = 0; + for (Type formal : declaredClass.getTypeArguments()) { + if (!arguments.hasNext()) { + break; } + Type argument = arguments.next(); + if (formal.tsym.equals(typeVariable.tsym)) { + return Track.located(argument, actualPath.then(typeArgumentStep(actualClass, index))); + } + index++; } declaredForm = declaredClass.getEnclosingType(); actual = actualClass.getEnclosingType(); diff --git a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java index da6a466416..be68c40bc1 100644 --- a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java @@ -14,7 +14,8 @@ * Building a generic nullability mismatch message walks the compilation unit to find the local * variable a fix rewrites. The walk happens at most once per unit, and not at all for a mismatch * whose error is suppressed. Whether the check accepts a value of that local against the rewritten - * type is computed once per value and type, however many diagnostics read the local. + * type is computed once per value and type, however many diagnostics read the local, and the path + * to a value is rebuilt only where that is computed. */ public class MismatchMessageWorkTests { @@ -53,7 +54,7 @@ Collection returned() { } @Test - public void eachValueOfALocalIsCheckedOnceForEveryDiagnosticThatReadsIt() { + public void eachValueOfALocalIsCheckedOnceHoweverManyDiagnosticsReadIt() { List checks = Collections.synchronizedList(new ArrayList<>()); LocalVariableDeclarations.acceptanceListener = value -> checks.add(value.toString()); try { @@ -110,6 +111,45 @@ void oneValueIsUnknown() { "List.of(\"b\")"); } + @Test + public void aValuePathIsRebuiltOnlyWhereItsAcceptanceIsComputed() { + List rebuilds = Collections.synchronizedList(new ArrayList<>()); + LocalVariableDeclarations.rebuildListener = value -> rebuilds.add(value.toString()); + try { + compile( + """ + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + interface Source { + T get(); + } + static void take(Source s) {} + void lambdaInitializer(Source a, Source b) { + Source s = () -> "x"; + s = a; + s = b; + // BUG: Diagnostic contains: incompatible nullability + take(s); + // BUG: Diagnostic contains: incompatible nullability + take(s); + // BUG: Diagnostic contains: incompatible nullability + take(s); + } + } + """); + } finally { + LocalVariableDeclarations.rebuildListener = null; + } + assertWithMessage( + "value paths rebuilt; the acceptance of a and b is kept after the first read, and that" + + " of the lambda is unknown, so only the lambda is checked again") + .that(rebuilds) + .containsExactly("()->\"x\"", "a", "b", "()->\"x\"", "()->\"x\"") + .inOrder(); + } + @Test public void aParameterOrFieldSourceCostsNoWalk() { List walks = diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java index 57e2e05c11..bcfca58d8a 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java @@ -46,11 +46,11 @@ * that NullAway accepts where the fix claims it does. A {@code declare as } line is * applied by writing {@code } in place of the declared type of {@code } and of the * nullable annotations among its modifiers, and the Error Prone edit as {@code -XepPatchChecks} - * applies it. A fix of the source, as a line or as the edit, has to leave no generic mismatch on - * any line that names the rewritten variable: its declaration, its initializer, every assignment to - * it, and the reported read. A fix of the target, the variable declared on the reported line, has - * to leave none on that line; a later read of the variable may still reject it, which is what - * {@code possible} says. + * applies it. A fix of the source, as a line or as the edit, has to leave no generic mismatch, and + * no override whose type arguments differ in nullness, on any line that names the rewritten + * variable: its declaration, its initializer, every assignment to it, and the reported read. A fix + * of the target, the variable declared on the reported line, has to leave none on that line; a + * later read of the variable may still reject it, which is what {@code possible} says. */ public class FixRoundTripTests { @@ -59,6 +59,9 @@ public class FixRoundTripTests { /** The first words of every generic nullability mismatch message. */ private static final String MISMATCH = "incompatible nullability in "; + /** The end of the first line of a report of an override whose type arguments differ. */ + private static final String OVERRIDE_MISMATCH = "which has mismatched type parameter nullability"; + private static final Pattern FIX_LINE = Pattern.compile("declare (\\w+) as (.+)$"); @Test @@ -416,6 +419,18 @@ void test(List l) { """); } + @Test + public void sourceFixOfAnExplicitlyTypedLambdaParameter() { + assertRoundTrip( + """ + interface Sink { + void accept(T t); + } + static void take(Collection c) {} + Sink> sink = (List l) -> take(l); + """); + } + @Test public void sourceFixOfAField() { assertRoundTrip( @@ -518,7 +533,7 @@ private void assertRoundTrip(String members, Extra extra) { + " `%s` of the diagnostic\n%s\nto get\n%s", mismatch.getLineNumber(), line.trim(), message, rewritten) .that( - mismatches(after).stream() + genericErrors(after).stream() .filter(d -> d.getLineNumber() == mismatch.getLineNumber()) .map(d -> d.getMessage(Locale.ROOT)) .toList()) @@ -566,7 +581,7 @@ private void assertRoundTrip(String members, Extra extra) { private static List mismatchesNaming( List> diagnostics, String source, List names) { List lines = source.lines().toList(); - return mismatches(diagnostics).stream() + return genericErrors(diagnostics).stream() .filter( d -> names.stream() @@ -649,6 +664,21 @@ private static List> mismatches( .toList(); } + /** + * Returns the generic mismatches among {@code diagnostics} and the reports of a parameter or a + * return type whose type arguments differ in nullness from those of the method it overrides, the + * error a rewritten parameter type can move to. + */ + private static List> genericErrors( + List> diagnostics) { + return diagnostics.stream() + .filter( + d -> + d.getMessage(Locale.ROOT).contains("[NullAway] " + MISMATCH) + || d.getMessage(Locale.ROOT).contains(OVERRIDE_MISMATCH)) + .toList(); + } + private static List errors(List> diagnostics) { return diagnostics.stream() .filter(d -> d.getKind() == Diagnostic.Kind.ERROR) 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 fba73df19c..c047ac3158 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 @@ -363,6 +363,115 @@ void substitutedAfterAnEarlierView(List l) { """); } + @Test + public void aCapturedWildcardsBoundNamesTypeParametersRatherThanCaptures() { + assertMessages( + Map.of( + "SELF", + """ + incompatible nullability in type argument for T of Self -> upper bound of wildcard: source has @Nullable Comparable where target requires Comparable + source: Self + ^^^^^^^^^^^^ + target: Self> + ^^^^^^^^^^^^^ + note: capture of ? is the captured type argument for T of Self, whose upper bound is @Nullable Comparable (JLS 5.1.10) + """, + "SUBCLASS_DECLARING_THE_SAME_BOUND", + """ + incompatible nullability in type argument for T of Self -> upper bound of wildcard: source has @Nullable Comparable where target requires Comparable + source: SubSelf + ^^^^^^^^^^^^ + target: Self> + ^^^^^^^^^^^^^ + note: capture of ? is the captured type argument for U of SubSelf, whose upper bound is @Nullable Comparable (JLS 5.1.10) + """, + "SUBCLASS_DECLARING_ANOTHER_BOUND", + """ + incompatible nullability in type argument for T of Self -> upper bound of wildcard: source has @Nullable Comparable where target requires Comparable + source: NonNullSubSelf + ^^^^^^^^^^^^ + target: Self> + ^^^^^^^^^^^^^ + """, + "BELOW_ROOT_NAMES_NO_HOLDER", + """ + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for B of Base -> upper bound of wildcard -> type argument for T of Self -> upper bound of wildcard: source has @Nullable Comparable where target requires Comparable + source: List + target: List>>> + ^^^^^^^^^^^^^ + """, + "INNER", + """ + incompatible nullability in type argument for I of Inner -> upper bound of wildcard: source has @Nullable List where target requires List + source: Outer.Inner + ^^^^^^^^^^^^ + target: Outer.Inner> + ^^^^^^^ + note: capture of ? is the captured type argument for I of Inner, whose upper bound is @Nullable List (JLS 5.1.10) + """, + "INNER_SUBCLASS", + """ + incompatible nullability in type argument for I of Inner -> upper bound of wildcard: source has @Nullable List where target requires List + source: Outer.NonNullInner + ^^^^^^^^^^^^ + target: Outer.Inner> + ^^^^^^^ + """), + """ + static class Self> {} + static Self makeSelf() { + throw new RuntimeException(); + } + static void takeSelf(Self> s) {} + void self() { + // BUG: Diagnostic matches: SELF + takeSelf(makeSelf()); + } + static class SubSelf> extends Self {} + static SubSelf makeSubSelf() { + throw new RuntimeException(); + } + void subclassDeclaringTheSameBound() { + // BUG: Diagnostic matches: SUBCLASS_DECLARING_THE_SAME_BOUND + takeSelf(makeSubSelf()); + } + static class NonNullSubSelf> extends Self {} + static NonNullSubSelf makeNonNullSubSelf() { + throw new RuntimeException(); + } + void subclassDeclaringAnotherBound() { + // BUG: Diagnostic matches: SUBCLASS_DECLARING_ANOTHER_BOUND + takeSelf(makeNonNullSubSelf()); + } + static class Base {} + static class SelfSub extends Base> {} + static void takeList(List>>> l) {} + void belowRootNamesNoHolder(List l) { + // BUG: Diagnostic matches: BELOW_ROOT_NAMES_NO_HOLDER + takeList(l); + } + static class Outer { + class Inner> {} + class NonNullInner> extends Inner {} + } + static Outer.NonNullInner makeNonNullInner() { + throw new RuntimeException(); + } + static Outer.Inner makeInner() { + throw new RuntimeException(); + } + static void takeInner(Outer.Inner> i) {} + void inner() { + // BUG: Diagnostic matches: INNER + takeInner(makeInner()); + } + void innerSubclass() { + // BUG: Diagnostic matches: INNER_SUBCLASS + takeInner(makeNonNullInner()); + } + """); + } + // The check views SubL as Base, where U is @Nullable, and reports a false positive (#2206); a // note giving the bound T of SubL declares would contradict the first line. @Test diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java index d108aba0c6..c3d6ba4a79 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java @@ -354,8 +354,6 @@ void test(List l) { """); } - // The printer drops @Tainted and the custom nullable @CanBeNull from the printed types, so - // TAINTED and CUSTOM_NULLABLE differ from PLAIN only by the missing fix line. @Test public void aPatternVariableGetsNoSourceFix() { assertMessages( @@ -407,6 +405,52 @@ void patternWithATargetFix(Object o) { """); } + @Test + public void aLambdaParameterGetsNoSourceFix() { + assertMessages( + Map.of( + "NO_FIX", + """ + incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: List + ^ + target: Collection + ^^^^^^ + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + """, + "METHOD_PARAMETER", + """ + incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: List + ^ + target: Collection + ^^^^^^ + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + possible fix: declare l as List + """), + """ + interface Sink { + void accept(T t); + } + static void take(Collection c) {} + // BUG: Diagnostic matches: NO_FIX + Sink> explicitlyTyped = (List l) -> take(l); + // BUG: Diagnostic matches: NO_FIX + Sink> implicitlyTyped = l -> take(l); + Sink> block = + (List l) -> { + // BUG: Diagnostic matches: NO_FIX + take(l); + }; + void methodParameter(List l) { + // BUG: Diagnostic matches: METHOD_PARAMETER + take(l); + } + """); + } + + // The printer drops @Tainted and the custom nullable @CanBeNull from the printed types, so + // TAINTED and CUSTOM_NULLABLE differ from PLAIN only by the missing fix line. @Test public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { CompilationTestHelper helper = From d252b10c2d1e49f88740b9894f42e973d9ea468e Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Mon, 30 Nov 2026 17:54:33 +0300 Subject: [PATCH 35/43] Remove the possible fix line from generic mismatch messages A generic nullability message ended with a `possible fix:` line that named a declaration to rewrite. For a local variable, it also attached an edit. Keeping the line correct took a check of every value assigned to the local, a printer mode that reproduces declarations as written, and a cache cleared per compilation unit. It also needed rules for where the rewritten type compiles yet moves the error, such as a lambda parameter. The fix is moved to #2216, so this change keeps the path, caret, and note lines and drops the rest. The printer goes back to master's printing of a local class's enclosing type, which only the fix needed to change. Two display cases that only the fix tests checked move to `NoteTests` and `CaretTests`: a wildcard in an enclosing type argument, and the printed form of annotations not named `Nullable`. User-visible: A generic nullability mismatch no longer prints a `possible fix:` line and carries no suggested edit. Assisted-by: Claude Code (claude-opus-5-5) --- .../GenericTypePrettyPrintingVisitor.java | 182 +--- .../nullaway/generics/GenericsChecks.java | 108 +-- .../generics/LocalVariableDeclarations.java | 301 ------ .../generics/NullabilityMismatchMessage.java | 598 +----------- .../generics/NullabilityMismatches.java | 68 +- .../generics/MismatchMessageWorkTests.java | 255 ----- .../jspecify/mismatchmessage/CaretTests.java | 102 ++ .../mismatchmessage/FixRoundTripTests.java | 775 ---------------- .../jspecify/mismatchmessage/FixTests.java | 878 ------------------ .../MismatchMessageTestBase.java | 21 +- .../jspecify/mismatchmessage/NoteTests.java | 35 +- .../jspecify/mismatchmessage/PathTests.java | 2 - .../mismatchmessage/SourceFixTests.java | 659 ------------- .../SummaryAndNumberingTests.java | 6 - .../mismatchmessage/TargetTypeFixTests.java | 470 ---------- .../mismatchmessage/TraversalCostTests.java | 2 - .../mismatchmessage/ViewedSourceTests.java | 1 - 17 files changed, 183 insertions(+), 4280 deletions(-) delete mode 100644 nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java delete mode 100644 nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java delete mode 100644 nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java delete mode 100644 nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java delete mode 100644 nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java delete mode 100644 nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.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 5cd3b72108..c23e7ee654 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java @@ -3,14 +3,10 @@ import static java.util.stream.Collectors.joining; import com.google.errorprone.VisitorState; -import com.google.errorprone.fixes.SuggestedFix; -import com.google.errorprone.fixes.SuggestedFixes; +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.Kinds; -import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Type; -import com.sun.tools.javac.code.TypeTag; import com.sun.tools.javac.code.Types; import java.util.List; import org.jspecify.annotations.Nullable; @@ -59,154 +55,13 @@ final class GenericTypePrettyPrintingVisitor /** The position of the node being printed, maintained as the visitor descends. */ private TypePath currentPath = TypePath.root(); - /** - * Where the names of classes and annotations are imported for a fix that pastes the printed type, - * or {@code null} where the type is only shown, under simple names. - */ - private final SuggestedFix.@Nullable Builder fix; - - /** - * Whether the {@code @Nullable} on the base type is left out because the declaration the fix - * rewrites states it among its modifiers, outside the type tree the fix replaces. The base type - * is the leftmost type the type tree names, where javac attaches such a modifier: the type itself - * or, for an array, its innermost element type, and for an inner class the outermost enclosing - * type printed before it. - */ - private final boolean omitBaseAnnotation; - - /** - * Whether an array prints as a declaration spells it, {@code String[]}, rather than with the - * space the {@code source:} and {@code target:} lines put before an unannotated dimension, {@code - * String []}. - */ - private final boolean sourceSpelling; - GenericTypePrettyPrintingVisitor(VisitorState state) { this(state, List.of()); } GenericTypePrettyPrintingVisitor(VisitorState state, List<@Nullable TypePath> markedPaths) { - this(state, markedPaths, null, false, false); - } - - private GenericTypePrettyPrintingVisitor( - VisitorState state, - List<@Nullable TypePath> markedPaths, - SuggestedFix.@Nullable Builder fix, - boolean omitBaseAnnotation, - boolean sourceSpelling) { this.state = state; this.markedPaths = markedPaths; - this.fix = fix; - this.omitBaseAnnotation = omitBaseAnnotation; - this.sourceSpelling = sourceSpelling; - } - - /** - * Returns {@code type} printed as source code for {@code fix} to paste into the compilation unit - * {@code state} is in: a class or annotation that a simple name does not reach there is imported - * by {@code fix}, or qualified where an import would clash. NullAway's synthetic - * {@code @Nullable} prints as JSpecify's. - * - * @param omitBaseAnnotation whether to leave out the {@code @Nullable} of the base type, the - * leftmost type the declaration's type tree names, because the declaration states it among - * its modifiers - */ - static String printForFix( - Type type, VisitorState state, SuggestedFix.Builder fix, boolean omitBaseAnnotation) { - return type.accept( - new GenericTypePrettyPrintingVisitor(state, List.of(), fix, omitBaseAnnotation, true), - null); - } - - /** - * Returns {@code type} as a {@code possible fix:} line names it: under simple names, as the - * {@code source:} and {@code target:} lines print it, with each array spelled as a declaration - * writes it. - */ - static String printForFixLine(Type type, VisitorState state) { - return type.accept( - new GenericTypePrettyPrintingVisitor(state, List.of(), null, false, true), null); - } - - /** - * Returns the type-use annotation on {@code type} itself that the printer prints, or {@code null} - * if it prints none. The printer prints the first annotation whose simple name is {@code - * Nullable} and drops every other one, including a nullable annotation of another name. - */ - static Attribute.@Nullable TypeCompound printedAnnotation(Type type) { - for (Attribute.TypeCompound compound : type.getAnnotationMirrors()) { - if (compound.type.tsym.getSimpleName().contentEquals("Nullable")) { - return compound; - } - } - return null; - } - - /** - * Returns whether the printer prints {@code compound} as it is written: its simple name is {@code - * Nullable}, and it has no element values, which the printer never writes. So {@code @Nullable} - * is reproduced and {@code @Nullable("reason")} is not. - */ - static boolean reproduces(Attribute.TypeCompound compound) { - return compound.type.tsym.getSimpleName().contentEquals("Nullable") - && compound.values.isEmpty(); - } - - /** - * Returns whether the printer prints every type-use annotation on {@code type} itself as it is - * written, which holds where there is none, or one that {@link #reproduces}. A wildcard's own - * annotations are never printed, so a wildcard holds this only where it has none. - */ - static boolean printsEveryAnnotation(Type type) { - List annotations = type.getAnnotationMirrors(); - return annotations.isEmpty() - || (!(type instanceof Type.WildcardType) - && annotations.size() == 1 - && reproduces(annotations.get(0))); - } - - /** - * Returns whether the printer prints the enclosing type of {@code t} before its name, as in - * {@code Outer.Inner}. It does for a member class with an enclosing instance, as javac's - * {@code ClassType.toString} does. A local class has no name qualified by its enclosing type, so - * it prints under its simple name even where it has an enclosing instance. - */ - static boolean printsEnclosingType(Type.ClassType t) { - return t.getEnclosingType().hasTag(TypeTag.CLASS) && t.tsym.owner.kind == Kinds.Kind.TYP; - } - - /** - * Returns the name to print for {@code symbol}, a class not printed inside its enclosing type or - * an annotation type. - */ - private String name(Symbol.TypeSymbol symbol) { - return fix == null - ? symbol.getSimpleName().toString() - : SuggestedFixes.qualifyType(state, fix, symbol); - } - - /** Returns the name to print for the nullable annotation {@code annotationType}. */ - private String annotationName(Type annotationType) { - if (fix != null && GenericsChecks.isSyntheticNullnessAnnotation(annotationType)) { - return SuggestedFixes.qualifyType(state, fix, "org.jspecify.annotations.Nullable"); - } - return name(annotationType.tsym); - } - - /** - * Whether {@code t}, the node being printed, is the base type: the leftmost type the printed type - * names. That node is reached from the root through array elements and enclosing types only, and - * is neither an array nor a class printed after its enclosing type. - */ - private boolean isBase(Type t) { - return !(t instanceof Type.ArrayType) - && !(t instanceof Type.ClassType classType && printsEnclosingType(classType)) - && currentPath.steps().stream() - .allMatch( - step -> - step.kind() == TypePath.Step.Kind.ARRAY_ELEMENT - || step.kind() == TypePath.Step.Kind.ENCLOSING_TYPE); } /** Brackets {@code printed} when the node being printed sits at one of the requested paths. */ @@ -271,16 +126,12 @@ public String visitClassType(Type.ClassType t, @Nullable Void s) { return mark(t.toString()); } StringBuilder sb = new StringBuilder(); - boolean printsEnclosingType = printsEnclosingType(t); - if (printsEnclosingType) { - sb.append(descend(TypePath.Step.enclosingType(), t.getEnclosingType())).append('.'); + Type enclosingType = t.getEnclosingType(); + if (!ASTHelpers.isSameType(enclosingType, Type.noType, state)) { + sb.append(descend(TypePath.Step.enclosingType(), enclosingType)).append('.'); } - String className = printsEnclosingType ? t.tsym.getSimpleName().toString() : name(t.tsym); - // a type annotation on a qualified name goes before its last segment: Map.@Nullable Entry - int lastDot = className.lastIndexOf('.'); - sb.append(className, 0, lastDot + 1); appendNullableAnnotationIfPresent(t, sb); - sb.append(className, lastDot + 1, className.length()); + sb.append(t.tsym.getSimpleName()); if (t.getTypeArguments().nonEmpty()) { sb.append('<'); StringBuilder arguments = new StringBuilder(); @@ -299,14 +150,16 @@ public String visitClassType(Type.ClassType t, @Nullable Void s) { } /** - * Appends {@code "@Nullable "} to {@code sb} if {@code t} has the annotation {@link - * #printedAnnotation} returns. We ignore all other type use annotations, including - * {@code @NonNull} as it is the default + * Appends {@code "@Nullable "} to {@code sb} if {@code t} has a type-use annotation whose simple + * name is {@code Nullable}. We ignore all other type use annotations, including {@code @NonNull} + * as it is the default */ private void appendNullableAnnotationIfPresent(Type t, StringBuilder sb) { - Attribute.TypeCompound compound = printedAnnotation(t); - if (compound != null && !(omitBaseAnnotation && isBase(t))) { - sb.append('@').append(annotationName(compound.type)).append(' '); + for (Attribute.TypeCompound compound : t.getAnnotationMirrors()) { + if (compound.type.tsym.getSimpleName().contentEquals("Nullable")) { + sb.append("@Nullable "); + break; + } } } @@ -340,12 +193,9 @@ public String visitCapturedType(Type.CapturedType t, @Nullable Void s) { public String visitArrayType(Type.ArrayType t, @Nullable Void unused) { StringBuilder sb = new StringBuilder(); sb.append(descend(TypePath.Step.arrayElement(), t.elemtype)); - StringBuilder annotation = new StringBuilder(); - appendNullableAnnotationIfPresent(t, annotation); - if (!sourceSpelling || annotation.length() > 0) { - sb.append(' '); - } - return mark(sb.append(annotation).append("[]").toString()); + sb.append(' '); + appendNullableAnnotationIfPresent(t, sb); + return mark(sb.append("[]").toString()); } @Override 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 6a4446f60e..e61009a937 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -10,8 +10,6 @@ import com.google.common.base.Verify; import com.google.common.collect.ImmutableSet; import com.google.errorprone.VisitorState; -import com.google.errorprone.fixes.SuggestedFix; -import com.google.errorprone.matchers.Description; import com.google.errorprone.suppliers.Suppliers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AnnotatedTypeTree; @@ -171,10 +169,6 @@ private InferenceFailure(@Nullable String errorMessage) { /** Maps each {@code var}-declared local to its declaration path. */ private final Map varLocalDeclarations = new LinkedHashMap<>(); - /** The local variable declarations a nullability mismatch fix rewrites, cleared per unit. */ - private final LocalVariableDeclarations localVariableDeclarations = - new LocalVariableDeclarations(); - /** * PolyNull results inferred separately from generic call inference, cached by invocation * identity. Results from joint generic inference remain in {@link InferenceSuccess}. @@ -461,56 +455,37 @@ private void reportInvalidInstantiationError( } private void reportInvalidAssignmentInstantiationError( - Tree tree, Type lhsType, Type rhsType, ExpressionTree rhsTree, VisitorState state) { + Tree tree, Type lhsType, Type rhsType, VisitorState state) { reportNullabilityMismatch( - tree, - ErrorMessage.MessageTypes.ASSIGN_GENERIC_NULLABLE, - lhsType, - rhsType, - tree instanceof VariableTree variableTree ? variableTree : null, - rhsTree, - state); + tree, ErrorMessage.MessageTypes.ASSIGN_GENERIC_NULLABLE, lhsType, rhsType, state); } /** * Reports at {@code tree} that {@code sourceType} cannot be assigned to {@code targetType}, with - * the fixes {@link NullabilityMismatchMessage} finds attached. A suppressed error builds no - * message, since building one reruns the check. + * the message {@link NullabilityMismatchMessage} builds. A suppressed error builds no message, + * since building one reruns the check. */ private void reportNullabilityMismatch( Tree tree, ErrorMessage.MessageTypes messageType, Type targetType, Type sourceType, - @Nullable VariableTree targetTypeDeclaration, - @Nullable ExpressionTree sourceExpression, VisitorState state) { ErrorBuilder errorBuilder = analysis.getErrorBuilder(); if (errorBuilder.isSuppressed(messageType, state)) { return; } - NullabilityMismatchMessage.Report report = - new NullabilityMismatchMessage(this, config, handler, state) - .build(targetType, sourceType, targetTypeDeclaration, sourceExpression); - Description.Builder description = analysis.buildDescription(tree); - for (SuggestedFix fix : report.fixes()) { - description.addFix(fix); - } + String message = + new NullabilityMismatchMessage(this, config, handler, state).build(targetType, sourceType); state.reportMatch( errorBuilder.createErrorDescription( - new ErrorMessage(messageType, report.message()), description, state, null)); + new ErrorMessage(messageType, message), analysis.buildDescription(tree), state, null)); } private void reportInvalidReturnTypeError( ExpressionTree tree, Type methodType, Type returnType, VisitorState state) { reportNullabilityMismatch( - tree, - ErrorMessage.MessageTypes.RETURN_NULLABLE_GENERIC, - methodType, - returnType, - null, - tree, - state); + tree, ErrorMessage.MessageTypes.RETURN_NULLABLE_GENERIC, methodType, returnType, state); } private void reportMismatchedTypeForTernaryOperator( @@ -540,8 +515,6 @@ private void reportInvalidParametersNullabilityError( ErrorMessage.MessageTypes.PASS_NULLABLE_GENERIC, formalParameterType, actualParameterType, - null, - paramExpression, state); } @@ -1012,64 +985,11 @@ public void checkTypeParameterNullnessForAssignability(Tree tree, VisitorState s } boolean isAssignmentValid = subtypeParameterNullability(lhsType, rhsType, state); if (!isAssignmentValid) { - reportInvalidAssignmentInstantiationError(tree, lhsType, rhsType, rhsTree, state); + reportInvalidAssignmentInstantiationError(tree, lhsType, rhsType, state); } } } - /** - * Whether the check of {@link #checkTypeParameterNullnessForAssignability} accepts {@code value} - * assigned to a local variable of type {@code localType}, for a type other than the local's - * declared one. A conditional expression is accepted where each of its branches is, as {@link - * #checkTypeParameterNullnessForConditionalExpression} checks each branch against the type of the - * local; a raw value is accepted, as the check skips it. - * - * @param localType the type to check the value against - * @param value the path to the initializer of the local or the right-hand side of an assignment - * to it - * @param state the visitor state - * @return {@code false} where the check rejects {@code value} or a branch of it, and otherwise - * {@code null} where the type of {@code value} or of a branch cannot be computed without - * changing what the check later computes for it: a lambda or a method reference, which takes - * its type from the target, and a generic call or diamond whose inference the check has not - * yet run, since running it against {@code localType} would cache the result for the declared - * type's check - */ - @Nullable Boolean acceptsValueOfLocal(Type localType, TreePath value, VisitorState state) { - TreePath path = value; - while (path.getLeaf() instanceof ParenthesizedTree parenthesized) { - path = new TreePath(path, parenthesized.getExpression()); - } - ExpressionTree expression = (ExpressionTree) path.getLeaf(); - if (expression instanceof ConditionalExpressionTree conditional) { - Boolean trueBranch = - acceptsValueOfLocal( - localType, new TreePath(path, conditional.getTrueExpression()), state); - if (Boolean.FALSE.equals(trueBranch)) { - return false; - } - Boolean falseBranch = - acceptsValueOfLocal( - localType, new TreePath(path, conditional.getFalseExpression()), state); - if (Boolean.FALSE.equals(falseBranch)) { - return false; - } - return (trueBranch == null || falseBranch == null) ? null : true; - } - if (expression instanceof LambdaExpressionTree - || expression instanceof MemberReferenceTree - || (isCallNeedingInference(expression) - && !inferredTypeVarNullabilityForGenericCalls.containsKey(expression))) { - return null; - } - Type javacType = ASTHelpers.getType(expression); - if (javacType != null && typeOrNullIfRawNonArray(javacType) == null) { - return true; - } - Type valueType = getTypeForRhsOfAssignment(expression, path, localType, true, state, false); - return valueType == null ? null : subtypeParameterNullability(localType, valueType, state); - } - private static boolean isAssignmentToLocalVariable(Tree tree) { return isAssignmentToKind(tree, ElementKind.LOCAL_VARIABLE) || isAssignmentToKind(tree, ElementKind.RESOURCE_VARIABLE); @@ -4631,8 +4551,8 @@ public boolean passingLambdaOrMethodRefWithGenericReturnToUnmarkedCode( } /** - * Clears the inference caches and the index of local variable declarations. Call after each - * CompilationUnit; otherwise they keep trees alive and leak memory. + * Clears the inference caches. Call after each CompilationUnit; otherwise the caches keep trees + * alive and leak memory. */ public void clearCache() { inferredTypeVarNullabilityForGenericCalls.clear(); @@ -4642,12 +4562,6 @@ public void clearCache() { inferredVarLocalTypes.clear(); varLocalDeclarations.clear(); nestedNullabilityRepairInProgress.clear(); - localVariableDeclarations.clear(); - } - - /** Returns the index of local variable declarations of the compilation unit being analyzed. */ - LocalVariableDeclarations localVariableDeclarations() { - return localVariableDeclarations; } public boolean isNullableAnnotated(Type type) { diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java b/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java deleted file mode 100644 index 2e35abc544..0000000000 --- a/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java +++ /dev/null @@ -1,301 +0,0 @@ -package com.uber.nullaway.generics; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.Sets; -import com.google.errorprone.util.ASTHelpers; -import com.sun.source.tree.AnnotatedTypeTree; -import com.sun.source.tree.ArrayTypeTree; -import com.sun.source.tree.AssignmentTree; -import com.sun.source.tree.CompilationUnitTree; -import com.sun.source.tree.EnhancedForLoopTree; -import com.sun.source.tree.ExpressionTree; -import com.sun.source.tree.Tree; -import com.sun.source.tree.VariableTree; -import com.sun.source.util.TreePath; -import com.sun.source.util.TreePathScanner; -import com.sun.tools.javac.code.Symbol; -import com.sun.tools.javac.code.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Supplier; -import javax.lang.model.element.ElementKind; -import org.jspecify.annotations.Nullable; - -/** - * Finds the declaration of a local variable of the compilation unit being analyzed. A pattern or - * resource variable is not one, since javac gives each its own element kind, so it is never found; - * the values assigned to a resource variable are recorded all the same. - * - *

The first lookup in a compilation unit walks it once and indexes every local variable - * declaration it holds; later lookups in the same unit read the index, so a unit with many - * diagnostics is walked once rather than once per diagnostic. The same walk notes the declarations - * that share their type tree with another variable, as each variable of {@code List a, b;} does, - * or its element type, as {@code a} and {@code b} of {@code List a, b[];} do, and records the - * values assigned to each local or resource variable: its initializer and the right-hand side of - * each {@code l = expr}. {@link #clear} drops the index, which otherwise keeps the trees of the - * unit alive. - */ -final class LocalVariableDeclarations { - - /** - * Receives each compilation unit just before it is indexed. Tests set it to count the walks; it - * is {@code null} otherwise. - */ - @VisibleForTesting static volatile @Nullable Consumer indexListener; - - /** - * Receives each value whose acceptance {@link #acceptance} computes rather than reads from its - * cache. Tests set it to count the checks; it is {@code null} otherwise. - */ - @VisibleForTesting static volatile @Nullable Consumer acceptanceListener; - - /** - * Receives the leaf of each path {@link #onSite} rebuilds. Tests set it to count the rebuilds; it - * is {@code null} otherwise. - */ - @VisibleForTesting static volatile @Nullable Consumer rebuildListener; - - /** The compilation unit {@link #paths} indexes, or {@code null} before the first lookup. */ - private @Nullable CompilationUnitTree unit; - - private final Map paths = new HashMap<>(); - - /** The first variable declared with each element type tree of the indexed unit. */ - private final IdentityHashMap firstByTypeTree = new IdentityHashMap<>(); - - /** The declarations of the indexed unit whose element type tree another variable also has. */ - private final Set sharingTypeTree = Sets.newIdentityHashSet(); - - /** - * The paths to the initializer of each local or resource variable of the indexed unit and to the - * right-hand side of each simple assignment to it, in source order. A variable with neither has - * no entry. - */ - private final Map> assignedValues = new HashMap<>(); - - /** The variables of the enhanced {@code for} loops of the indexed unit. */ - private final Set loopVariables = new HashSet<>(); - - /** - * Whether the check accepts each value of the indexed unit against a rewritten type, keyed by the - * value's tree and the rewritten type's {@code toString()}, which qualifies every name and keeps - * every annotation. An unknown result is not kept. - */ - private final IdentityHashMap> acceptances = new IdentityHashMap<>(); - - /** - * Returns the path to the declaration of {@code variable} in {@code compilationUnit}, or {@code - * null} where {@code variable} is not a local variable declared there. - */ - @Nullable TreePath find(Symbol.VarSymbol variable, CompilationUnitTree compilationUnit) { - if (variable.getKind() != ElementKind.LOCAL_VARIABLE) { - return null; - } - indexOnce(compilationUnit); - return paths.get(variable); - } - - /** - * Whether {@code declaration}, a local variable declaration of the compilation unit last passed - * to {@link #find}, shares its element type tree with another variable. - */ - boolean sharesTypeTree(VariableTree declaration) { - return sharingTypeTree.contains(declaration); - } - - /** - * Whether {@code variable}, a local variable of the compilation unit last indexed, is the - * variable of an enhanced {@code for} loop. - */ - boolean isLoopVariable(Symbol.VarSymbol variable) { - return loopVariables.contains(variable); - } - - /** - * Returns the paths to the values assigned to {@code variable}, a local or resource variable - * declared in {@code compilationUnit}: its initializer and the right-hand side of each simple - * assignment to it, in source order. The variable of an enhanced {@code for} loop takes each - * element of the loop's expression without a tree of its own, so only the assignments to it are - * returned. - * - *

A path is the one the walk recorded, so its enclosing paths are not those of the site being - * analyzed; {@link #onSite} rebuilds it before anything computes a type on it. - */ - List assignedValues(Symbol.VarSymbol variable, CompilationUnitTree compilationUnit) { - indexOnce(compilationUnit); - return assignedValues.getOrDefault(variable, List.of()); - } - - /** - * Returns a function that rebuilds a path {@link #assignedValues} returns on {@code site}, from - * the deepest tree the two share, so that a path into the method {@code site} is in shares its - * enclosing paths with {@code site}. A dataflow run keyed on the path to that method is then - * reused rather than repeated. The ancestors of {@code site} are collected on the first call. - */ - static Function onSite(TreePath site) { - return new Function<>() { - private @Nullable IdentityHashMap siteAncestors; - - @Override - public TreePath apply(TreePath value) { - IdentityHashMap ancestors = siteAncestors; - if (ancestors == null) { - ancestors = new IdentityHashMap<>(); - for (TreePath path = site; path != null; path = path.getParentPath()) { - ancestors.put(path.getLeaf(), path); - } - siteAncestors = ancestors; - } - Consumer listener = rebuildListener; - if (listener != null) { - listener.accept(value.getLeaf()); - } - return rebuild(value, ancestors); - } - }; - } - - /** - * Returns a path with the leaves of {@code path} whose enclosing paths, from the deepest tree - * {@code path} shares with {@code siteAncestors}, are those of {@code siteAncestors}. Both paths - * start at the same compilation unit, so they share at least its tree. - */ - private static TreePath rebuild(TreePath path, IdentityHashMap siteAncestors) { - List below = new ArrayList<>(); - TreePath shared = path; - while (!siteAncestors.containsKey(shared.getLeaf())) { - below.add(shared.getLeaf()); - shared = shared.getParentPath(); - } - TreePath result = siteAncestors.get(shared.getLeaf()); - for (int i = below.size() - 1; i >= 0; i--) { - result = new TreePath(result, below.get(i)); - } - return result; - } - - /** - * Returns {@code typeTree} without the array and annotation trees around its element type. javac - * gives each variable of one declaration the same element type tree and wraps it in an array tree - * of its own for brackets written after the name. - */ - private static @Nullable Tree baseTypeTree(@Nullable Tree typeTree) { - Tree base = typeTree; - while (base instanceof ArrayTypeTree || base instanceof AnnotatedTypeTree) { - base = - base instanceof ArrayTypeTree array - ? array.getType() - : ((AnnotatedTypeTree) base).getUnderlyingType(); - } - return base; - } - - /** - * Whether {@code symbol} is a local or resource variable, the kinds whose values are recorded. - */ - static boolean isLocalOrResource(Symbol symbol) { - return symbol.getKind() == ElementKind.LOCAL_VARIABLE - || symbol.getKind() == ElementKind.RESOURCE_VARIABLE; - } - - /** - * Returns whether the check accepts {@code value}, a value of a local or resource variable of the - * indexed unit, against {@code type}, as {@code check} computes it. A definite result is computed - * once per value and type, however many diagnostics read the variable; an unknown one, {@code - * null}, is computed again, since an inference that has not run yet may run before the next read. - */ - @Nullable Boolean acceptance(Tree value, Type type, Supplier<@Nullable Boolean> check) { - Map byType = acceptances.computeIfAbsent(value, unused -> new HashMap<>()); - String key = type.toString(); - Boolean known = byType.get(key); - if (known != null) { - return known; - } - Consumer listener = acceptanceListener; - if (listener != null) { - listener.accept(value); - } - Boolean computed = check.get(); - if (computed != null) { - byType.put(key, computed); - } - return computed; - } - - /** Forgets the indexed compilation unit. */ - void clear() { - unit = null; - paths.clear(); - firstByTypeTree.clear(); - sharingTypeTree.clear(); - assignedValues.clear(); - loopVariables.clear(); - acceptances.clear(); - } - - /** Indexes {@code compilationUnit} unless it is the unit indexed last. */ - private void indexOnce(CompilationUnitTree compilationUnit) { - if (unit != compilationUnit) { - index(compilationUnit); - } - } - - private void index(CompilationUnitTree compilationUnit) { - Consumer listener = indexListener; - if (listener != null) { - listener.accept(compilationUnit); - } - clear(); - unit = compilationUnit; - new TreePathScanner<@Nullable Void, @Nullable Void>() { - @Override - public @Nullable Void visitVariable(VariableTree variable, @Nullable Void unused) { - Symbol symbol = ASTHelpers.getSymbol(variable); - // a value is the initializer of a local or resource variable, or an assignment to one - ExpressionTree initializer = variable.getInitializer(); - if (initializer != null && symbol != null && isLocalOrResource(symbol)) { - recordValue(symbol, initializer); - } - if (symbol != null && symbol.getKind() == ElementKind.LOCAL_VARIABLE) { - paths.put(symbol, getCurrentPath()); - Tree typeTree = baseTypeTree(variable.getType()); - if (typeTree != null) { - VariableTree first = firstByTypeTree.putIfAbsent(typeTree, variable); - if (first != null) { - sharingTypeTree.add(first); - sharingTypeTree.add(variable); - } - } - // a loop body cannot be a declaration, so a declaration under the loop is its variable - if (getCurrentPath().getParentPath().getLeaf() instanceof EnhancedForLoopTree) { - loopVariables.add(symbol); - } - } - return super.visitVariable(variable, null); - } - - @Override - public @Nullable Void visitAssignment(AssignmentTree assignment, @Nullable Void unused) { - Symbol symbol = ASTHelpers.getSymbol(assignment.getVariable()); - if (symbol != null && isLocalOrResource(symbol)) { - recordValue(symbol, assignment.getExpression()); - } - return super.visitAssignment(assignment, null); - } - - // records the path to value, a child of the current tree, assigned to local - private void recordValue(Symbol local, ExpressionTree value) { - assignedValues - .computeIfAbsent(local, unused -> new ArrayList<>()) - .add(new TreePath(getCurrentPath(), value)); - } - }.scan(compilationUnit, 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 index b35fdd00c7..d977c24401 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -1,37 +1,20 @@ package com.uber.nullaway.generics; -import static com.uber.nullaway.generics.TypeMetadataBuilder.TYPE_METADATA_BUILDER; - import com.google.common.base.Verify; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Sets; import com.google.errorprone.VisitorState; -import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.util.ASTHelpers; -import com.sun.source.tree.AnnotationTree; -import com.sun.source.tree.ExpressionTree; -import com.sun.source.tree.LambdaExpressionTree; -import com.sun.source.tree.Tree; -import com.sun.source.tree.VariableTree; -import com.sun.source.util.TreePath; 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.Types; -import com.sun.tools.javac.tree.JCTree; 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.ArrayList; -import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.function.Function; import java.util.function.Predicate; -import javax.lang.model.element.ElementKind; -import javax.lang.model.type.TypeKind; import org.jspecify.annotations.Nullable; /** @@ -48,7 +31,6 @@ * target: Map<? extends Object, String> * ^^^^^^ * note: the unbounded wildcard ? in Map<?, String> has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) - * possible fix: declare m as Map<? extends Object, String> * * *

The message is built from the positions the check itself rejected, which {@link @@ -61,15 +43,13 @@ * *

Each line opens with a key that means the same thing wherever it appears: {@code source} is * the source type, {@code source supertype} the supertype of it the check compared, {@code target} - * the target type, {@code path} where in the type one difference sits, {@code note} a fact about - * the source that its printed form does not show, and {@code possible fix} a declaration whose - * rewritten type the check accepts, which callers or other assignments may still reject. Java - * constructs are named in the terms of the JLS, as {@code type argument for K of Map}, {@code upper - * bound of wildcard}, and {@code component type}, and nullness in those of JSpecify. Where there - * are several differences, each gets a numbered entry with its own {@code path}, {@code source}, - * and {@code target}, five at most, and {@code and N more differing positions, not listed} counts - * the rest. The keys of the type lines are padded to one width, so the types of one message start - * in the same column. + * the target type, {@code path} where in the type one difference sits, and {@code note} a fact + * about the source that its printed form does not show. Java constructs are named in the terms of + * the JLS, as {@code type argument for K of Map}, {@code upper bound of wildcard}, and {@code + * component type}, and nullness in those of JSpecify. Where there are several differences, each + * gets a numbered entry with its own {@code path}, {@code source}, and {@code target}, five at + * most, and {@code and N more differing positions, not listed} counts the rest. The keys of the + * type lines are padded to one width, so the types of one message start in the same column. * *

The first line

* @@ -115,52 +95,6 @@ * printed type is the one the capture instantiates. 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 for the source a {@code note} says what the reader cannot see there. - * - *

The fixes

- * - *

A {@code possible fix} line names the declaration it rewrites and the type it declares: the - * source variable with explicit wildcard bounds, or the target variable with {@code @Nullable} - * added. Each candidate is checked before it is printed: it 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 ?}. Where both candidates pass, the message lists them - * under {@code possible fixes}, the source first, each with the condition under which it is the - * right one. - * - *

The source fix of a local or resource variable of the compilation unit being analyzed is - * checked once more: the rewrite makes the variable's type less nullable, so the values assigned to - * it, its initializer and the right-hand side of each assignment to it, are the only - * pseudo-assignments it can break. The source fix is offered only where the check is shown to - * accept each of them against the rewritten type. Each branch of a conditional expression counts as - * a value of its own, and a raw value is accepted, as the check skips it. A lambda, a method - * reference, or a generic call or diamond whose inference the check has not run yet cannot be shown - * accepted, so a variable holding one gets no source fix. The elements an enhanced {@code for} loop - * gives its variable count as accepted, since no generic check compares them with its type. Only - * the source fix comes with an Error Prone fix that makes the edit, and only where the variable is - * a local other than an enhanced {@code for} variable, and its declaration writes its type out - * before the name and declares no other variable. A run that suggests suppressions asks for the - * suppression instead. A parameter or a field gets the line without the check or the edit: its type - * is a contract that callers, overriders, and other assignments rely on, and the check that accepts - * the rewrite consults none of them. A parameter of a lambda expression gets no source fix, since - * the functional interface fixes its type. A variable of any other kind gets none either; {@link - * #FIXABLE_SOURCE_KINDS} gives the reason for each. The target fix never gets the edit, since the - * rewritten variable may be read as a source anywhere in its scope. - * - *

The two candidates differ in what they presume. Writing an explicit bound on a wildcard the - * source declaration already writes is a mechanical fix of that wildcard, so it is offered wherever - * it works. Changing the target 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 target 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 target 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 fix also has to survive printing. The printer shows an annotation named {@code Nullable} - * without its element values, shows none on a wildcard, and drops every other type-use annotation, - * a custom nullable annotation of another name included. It also writes the dimensions of a nested - * array in the reverse of the order a declaration gives them. So a fix is not offered where the - * declared type it replaces or the type it declares carries an annotation the printer would drop or - * change, such as {@code @Nullable("reason")}, an annotated wildcard, or an annotation on a - * dimension of a nested array. */ final class NullabilityMismatchMessage { @@ -199,32 +133,14 @@ final class NullabilityMismatchMessage { */ private static final int TYPE_LABEL_WIDTH = SOURCE_LABEL.length(); - /** - * The text of a diagnostic and the fixes to attach to it. - * - * @param message the text - * @param fixes each an alternative edit after which the check accepts the pseudo-assignment, in - * the order the text names them - */ - record Report(String message, List fixes) {} - /** * Builds the diagnostic for an assignment, a return, or an argument the nullability check * rejected. * * @param targetType the type the pseudo-assignment assigns to * @param sourceType the type of the value assigned - * @param targetTypeDeclaration the declaration of a variable whose type is {@code targetType} - * where the diagnostic is reported at it, which admits a fix of the target type; {@code null} - * elsewhere - * @param sourceExpression the expression whose type is {@code sourceType}, which admits a fix of - * the declaration it names; {@code null} where there is none */ - Report build( - Type targetType, - Type sourceType, - @Nullable VariableTree targetTypeDeclaration, - @Nullable ExpressionTree sourceExpression) { + String build(Type targetType, Type sourceType) { NullabilityMismatches recorded = new NullabilityMismatches(targetType, sourceType, state.getTypes(), config); new CheckIdenticalNullabilityVisitor(state, checks, config, handler, recorded) @@ -281,240 +197,17 @@ Report build( for (int i = 0; i < listed.size(); i++) { message.append(mismatchDetail(listed.get(i), numbered ? i + 1 : 0, sourceType, printedView)); } - // 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()) { + // a numbered entry stands apart from the next, so the list stays readable, and the count + // after the list stands apart from it in the same way message.append( String.format( "%s\n and %d more differing position%s, not listed", - separator, + numbered ? "\n" : "", mismatches.size() - listed.size(), mismatches.size() - listed.size() == 1 ? "" : "s")); } - Symbol.VarSymbol sourceVariable = sourceVariable(sourceExpression, sourceType); - // the declared type is checked as well as the rewritten one, since a rewrite builds new nodes - // and drops an annotation the declaration writes on the node it replaces - Type rewrittenSourceType = - (sourceVariable == null || !isDeclarable(sourceVariable.type)) - ? null - : sourceTypeFix(targetType, sourceType, mismatches); - TreePath sourceDeclaration = null; - // the type of a parameter or a field is a contract that callers, overriders, and other - // assignments rely on, and the check that accepts the rewrite consults none of them - if (sourceVariable != null - && rewrittenSourceType != null - && LocalVariableDeclarations.isLocalOrResource(sourceVariable)) { - if (valuesAccept(sourceVariable, rewrittenSourceType)) { - sourceDeclaration = - checks - .localVariableDeclarations() - .find(sourceVariable, state.getPath().getCompilationUnit()); - } else { - // a value the variable holds rejects the rewrite, or may, so the fix could move the error - rewrittenSourceType = null; - } - } - Symbol.VarSymbol targetVariable = - targetTypeDeclaration == null ? null : ASTHelpers.getSymbol(targetTypeDeclaration); - Type rewrittenTargetType = - (targetVariable == null || !isDeclarable(targetVariable.type)) - ? null - : targetTypeFix(targetType, sourceType, mismatches); - List fixes = new ArrayList<>(); - if (sourceVariable != null && rewrittenSourceType != null) { - message.append(separator); - if (targetVariable != null && rewrittenTargetType != null) { - message.append( - String.format( - "\n possible fixes:\n if %s never holds null: %s\n if it may: %s", - sourceVariable.getSimpleName(), - declaration(sourceVariable, rewrittenSourceType), - declaration(targetVariable, rewrittenTargetType))); - } else { - message - .append("\n possible fix: ") - .append(declaration(sourceVariable, rewrittenSourceType)); - } - // a loop variable's line is offered because no check compares the loop's elements with - // its type, so no error can move to them; an edit would rest on that missing check rather - // than on a check that passed, so none is attached - if (sourceDeclaration != null - && !checks.localVariableDeclarations().isLoopVariable(sourceVariable)) { - addSourceFixEdit(fixes, sourceDeclaration, rewrittenSourceType); - } - } else if (targetVariable != null && rewrittenTargetType != null) { - // the target's uses as a source can be anywhere, and the check that accepts the rewrite - // consults none of them, so the fix gets no edit - message - .append(separator) - .append("\n possible fix: ") - .append(declaration(targetVariable, rewrittenTargetType)); - } - return new Report(message.toString(), fixes); - } - - /** Returns {@code declare as }, the text of a fix. */ - private String declaration(Symbol.VarSymbol variable, Type type) { - return String.format( - "declare %s as %s", - variable.getSimpleName(), GenericTypePrettyPrintingVisitor.printForFixLine(type, state)); - } - - /** - * Whether the check is shown to accept against {@code type} every value assigned to {@code - * variable}, a local or resource variable of the compilation unit being analyzed: its initializer - * and the right-hand side of each assignment to it. The elements an enhanced {@code for} loop - * gives its variable count as accepted, since no generic check compares them with its type. - * Returns {@code false} where one value is rejected or its type cannot be computed. - */ - private boolean valuesAccept(Symbol.VarSymbol variable, Type type) { - LocalVariableDeclarations declarations = checks.localVariableDeclarations(); - // a value whose acceptance is kept needs no path, so a path is rebuilt only where the check - // runs - Function onSite = LocalVariableDeclarations.onSite(state.getPath()); - boolean everyValueAccepts = true; - for (TreePath recorded : - declarations.assignedValues(variable, state.getPath().getCompilationUnit())) { - Boolean accepted = - declarations.acceptance( - recorded.getLeaf(), - type, - () -> { - TreePath value = onSite.apply(recorded); - return checks.acceptsValueOfLocal(type, value, state.withPath(value)); - }); - if (Boolean.FALSE.equals(accepted)) { - return false; - } - // an unknown value already leaves the fix out; the values after it are still checked so that - // their definite results are kept for the next diagnostic that reads the variable - everyValueAccepts &= accepted != null; - } - return everyValueAccepts; - } - - /** - * Adds to {@code fixes} the edit that declares the local variable at {@code declarationPath}, - * whose values all accept {@code type}, with {@code type}, where the declaration writes its type - * out before the name and declares no other variable, and the run does not suggest suppressions. - */ - private void addSourceFixEdit(List fixes, TreePath declarationPath, Type type) { - if (config.suggestSuppressions()) { - // the run asks for the suppression ErrorBuilder adds after these fixes, and patching - // applies only the first fix of a diagnostic - return; - } - VariableTree declaration = (VariableTree) declarationPath.getLeaf(); - Tree typeTree = declaration.getType(); - if (typeTree == null || ASTHelpers.hasImplicitType(declaration, state)) { - return; // diff-coverage: ignore -- javac versions differ in whether var gets a type tree - } - // in `List a[]` the type tree spans the name, which replacing it would overwrite - if (checks.localVariableDeclarations().sharesTypeTree(declaration) - || state.getEndPosition(typeTree) > ((JCTree) declaration).pos) { - return; - } - SuggestedFix.Builder fix = SuggestedFix.builder(); - String printed = - GenericTypePrettyPrintingVisitor.printForFix( - type, state.withPath(declarationPath), fix, hasNullableModifier(declaration)); - fixes.add(fix.replace(typeTree, printed).build()); - } - - /** - * Whether {@code declaration} writes a nullable annotation among its modifiers, where a type-use - * annotation applies to the base type and lies outside the type tree. - */ - private boolean hasNullableModifier(VariableTree declaration) { - for (AnnotationTree annotation : declaration.getModifiers().getAnnotations()) { - Symbol annotationSymbol = ASTHelpers.getSymbol(annotation.getAnnotationType()); - if (annotationSymbol != null - && Nullness.isNullableAnnotation( - annotationSymbol.getQualifiedName().toString(), config)) { - return true; - } - } - return false; - } - - /** - * The kinds of variable that can get a source fix. The type of a local or resource variable is - * not a contract, so it gets the fix where each of its values is shown to accept the rewrite. The - * type of a parameter or a field is a contract, so it gets the line as text, with no check of its - * values and no edit; a parameter of a lambda expression gets none (see {@link - * #isLambdaParameter}). The other kinds get none: - * - *

    - *
  • a pattern variable takes its value from the expression the pattern matches, which the - * value check of a local does not cover; - *
  • a catch parameter has a type that takes no type arguments (JLS 8.1.2, 14.20), so it is - * never the source of a generic mismatch; - *
  • an enum constant has the type of its enum, which declares no type parameters (JLS 8.9), - * so no bound written on it can change the mismatch; - *
  • a record component is read through its field or its accessor, so no source expression - * names it. - *
- */ - private static final ImmutableSet FIXABLE_SOURCE_KINDS = - Sets.immutableEnumSet( - ElementKind.LOCAL_VARIABLE, - ElementKind.RESOURCE_VARIABLE, - ElementKind.PARAMETER, - ElementKind.FIELD); - - /** - * Returns the variable {@code sourceExpression} reads, where it is of a kind in {@link - * #FIXABLE_SOURCE_KINDS} and is declared in the compilation unit being analyzed with the very - * type {@code sourceType}, so that a rewrite of that type is a rewrite of the declaration; {@code - * null} otherwise. - */ - private Symbol.@Nullable VarSymbol sourceVariable( - @Nullable ExpressionTree sourceExpression, Type sourceType) { - if (sourceExpression == null - || !(ASTHelpers.getSymbol(ASTHelpers.stripParentheses(sourceExpression)) - instanceof Symbol.VarSymbol variable) - || !FIXABLE_SOURCE_KINDS.contains(variable.getKind()) - || isLambdaParameter(variable)) { - return null; - } - // a member read through a parameterized receiver has a type the declaration does not state, - // such as the List a field declared List has in a Box - if (!GenericsChecks.prettyTypeForError(variable.type, state) - .equals(GenericsChecks.prettyTypeForError(sourceType, state))) { - return null; - } - Symbol.ClassSymbol outermostClass = variable.outermostClass(); - return outermostClass != null - && outermostClass.sourcefile != null - && outermostClass.sourcefile.equals( - state.getPath().getCompilationUnit().getSourceFile()) - ? variable - : null; - } - - /** - * Whether {@code variable} is a parameter of a lambda expression enclosing the site being - * analyzed, which is where a read of it can be. The functional interface fixes the type of such a - * parameter: javac rejects a declared type the function type does not have (JLS 15.27.3), and - * NullAway reports one that differs from it only in nullness, as {@code List} - * for {@code List}, as a parameter that does not match the one it overrides. So a rewrite of - * its type moves the error rather than fixing it. - */ - private boolean isLambdaParameter(Symbol.VarSymbol variable) { - if (variable.getKind() != ElementKind.PARAMETER) { - return false; - } - for (TreePath path = state.getPath(); path != null; path = path.getParentPath()) { - if (path.getLeaf() instanceof LambdaExpressionTree lambda) { - for (VariableTree parameter : lambda.getParameters()) { - if (variable.equals(ASTHelpers.getSymbol(parameter))) { - return true; - } - } - } - } - return false; + return message.toString(); } /** @@ -1117,273 +810,6 @@ private String withOtherTypeArgumentsElided(Type.ClassType holder, int index) { return holder.tsym.getSimpleName() + "<" + String.join(", ", printed) + ">"; } - /** - * Returns {@code sourceType} with an explicit upper bound written out for each unbounded wildcard - * whose implicit {@code @Nullable} bound the target rejects, where that type is one a reader can - * declare and the check accepts it, and {@code null} otherwise. - */ - private @Nullable Type sourceTypeFix( - Type targetType, Type sourceType, List mismatches) { - Type rewrittenSourceType = rewriteWithExplicitBounds(sourceType, mismatches); - if (rewrittenSourceType == null || !isDeclarable(rewrittenSourceType)) { - return null; - } - // the check's own comparison rather than a prediction of it: a rewrite that leaves a mismatch - // writing a bound out does not address, such as a nullness difference on a concrete type - // argument, would only produce the same diagnostic again - return checks.subtypeParameterNullability(targetType, rewrittenSourceType, state) - ? rewrittenSourceType - : null; - } - - /** - * Returns {@code targetType} with {@code @Nullable} added at every rejected position, where the - * source has {@code @Nullable} at each of them, the result is a type a reader can declare, and - * the check accepts the source against it; {@code null} otherwise, including where a position - * would need a {@code @Nullable} removed. Whether it is offered at all is the caller's decision, - * which the class comment states. - */ - private @Nullable Type targetTypeFix( - Type targetType, Type sourceType, List mismatches) { - Type rewrittenTargetType = targetType; - for (NullabilityMismatches.Mismatch mismatch : mismatches) { - Type rewritten = withNullableAddedFrom(mismatch.sourceNode(), mismatch.targetNode()); - TypePath targetNodePath = mismatch.targetNodePath(); - if (rewritten == null || targetNodePath == null) { - return null; - } - rewrittenTargetType = replaceAt(rewrittenTargetType, targetNodePath.steps(), 0, rewritten); - if (rewrittenTargetType == null) { - return null; // diff-coverage: ignore -- see replaceAt - } - } - return isDeclarable(rewrittenTargetType) - && checks.subtypeParameterNullability(rewrittenTargetType, sourceType, state) - ? rewrittenTargetType - : null; - } - - /** - * Returns {@code target} with {@code @Nullable} added where {@code source} carries it, or {@code - * null} where {@code source} is not {@code @Nullable}, {@code target} already is, or the - * annotation to copy cannot be found or is not one the printer {@linkplain - * GenericTypePrettyPrintingVisitor#reproduces reproduces}. - * - *

The fix 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; - } - return source.getAnnotationMirrors().stream() - .filter(annotation -> Nullness.isNullableAnnotation(annotation.type.toString(), config)) - .findFirst() - // the copy keeps only the annotation's type, so one with element values is not copied - .filter(GenericTypePrettyPrintingVisitor::reproduces) - .map(annotation -> TypeSubstitutionUtils.typeWithAnnot(target, annotation.type)) - .orElse(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} has no such node. A path the - * recorder gives a target node it located always reaches a node, since the recorder follows the - * written target by position and a replacement keeps the shape of the type. - * - *

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); - Type child = - switch (step.kind()) { - case TYPE_ARGUMENT -> - type instanceof Type.ClassType classType - && step.index() < classType.getTypeArguments().size() - ? classType.getTypeArguments().get(step.index()) - : null; // diff-coverage: ignore -- see the method comment - case ENCLOSING_TYPE -> - type instanceof Type.ClassType classType ? classType.getEnclosingType() : null; - case WILDCARD_UPPER_BOUND, WILDCARD_LOWER_BOUND -> - type instanceof Type.WildcardType wildcard - && wildcard.kind - == (step.kind() == TypePath.Step.Kind.WILDCARD_UPPER_BOUND - ? BoundKind.EXTENDS - : BoundKind.SUPER) - ? wildcard.type - : null; // diff-coverage: ignore -- see the method comment - case ARRAY_ELEMENT -> - type instanceof Type.ArrayType arrayType ? arrayType.elemtype : null; - }; - if (child == null) { - return null; // diff-coverage: ignore -- see the method comment - } - Type replaced = replaceAt(child, steps, from + 1, replacement); - if (replaced == null) { - return null; // diff-coverage: ignore -- see the method comment - } - return switch (step.kind()) { - case TYPE_ARGUMENT -> { - Type.ClassType classType = (Type.ClassType) type; - List typeArguments = new ArrayList<>(classType.getTypeArguments()); - typeArguments.set(step.index(), replaced); - yield TYPE_METADATA_BUILDER.createClassType( - classType, classType.getEnclosingType(), typeArguments); - } - case ENCLOSING_TYPE -> { - Type.ClassType classType = (Type.ClassType) type; - yield TYPE_METADATA_BUILDER.createClassType( - classType, replaced, classType.getTypeArguments()); - } - case WILDCARD_UPPER_BOUND, WILDCARD_LOWER_BOUND -> - TYPE_METADATA_BUILDER.createWildcardType((Type.WildcardType) type, replaced); - case ARRAY_ELEMENT -> TYPE_METADATA_BUILDER.createArrayType((Type.ArrayType) type, replaced); - }; - } - - /** - * 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 fix this class knows how to propose. Whether the result is worth offering - * is decided by the caller, against the rewritten type rather than against this list. - * - *

Only a class type is written out as a bound. A type variable would have to be in scope where - * the source type is declared, which nothing here checks; no known input reaches that case, since - * a target bound naming a method's type variable fails inference before this class runs. - */ - 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 fix this method knows - continue; // diff-coverage: ignore -- the check rejects only these - } - 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 targetBound = boundForWildcard.get(t); - return targetBound == null - ? super.visitWildcardType(t, null) - : new Type.WildcardType( - targetBound, BoundKind.EXTENDS, Symtab.instance(state.context).boundClass); - } - }, - null); - } - - /** - * Returns whether {@code type} prints as a type a reader can declare, so that a fix pasting it - * says what the reader gets. - * - *

This mirrors {@link GenericTypePrettyPrintingVisitor}, which prints the annotation {@link - * GenericTypePrettyPrintingVisitor#printedAnnotation} returns without its element values, prints - * no annotation on a wildcard, and drops every other type-use annotation, so a type is declarable - * only where {@link GenericTypePrettyPrintingVisitor#printsEveryAnnotation} holds at each node. - * It prints the enclosing type only where {@link - * GenericTypePrettyPrintingVisitor#printsEnclosingType} holds, and has four arms whose output no - * declaration may hold or that denotes nothing: a captured wildcard prints as {@code capture of - * ?}, an intersection as {@code A & B}, an anonymous class under its binary name, and a type that - * did not resolve under a bare name. 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 boolean isDeclarable(Type type) { - return type.accept(declarabilityVisitor, null); - } - - private final Types.DefaultTypeVisitor declarabilityVisitor = - new Types.DefaultTypeVisitor<>() { - @Override - public Boolean visitClassType(Type.ClassType t, @Nullable Void unused) { - if (t.isIntersection() - || t.tsym.isAnonymous() - || !GenericTypePrettyPrintingVisitor.printsEveryAnnotation(t)) { - return false; - } - for (Type typeArgument : t.getTypeArguments()) { - if (!typeArgument.accept(this, null)) { - return false; - } - } - return !GenericTypePrettyPrintingVisitor.printsEnclosingType(t) - || t.getEnclosingType().accept(this, null); - } - - @Override - public Boolean visitWildcardType(Type.WildcardType t, @Nullable Void unused) { - return GenericTypePrettyPrintingVisitor.printsEveryAnnotation(t) - && (t.kind == BoundKind.UNBOUND || t.type.accept(this, null)); - } - - @Override - public Boolean visitArrayType(Type.ArrayType t, @Nullable Void unused) { - // the printer writes the dimensions of a nested array innermost first, the reverse of the - // order a declaration gives them, so an annotated dimension would land on another one - if (t.elemtype instanceof Type.ArrayType && hasAnnotatedDimension(t)) { - return false; - } - return GenericTypePrettyPrintingVisitor.printsEveryAnnotation(t) - && t.elemtype.accept(this, null); - } - - @Override - public Boolean visitCapturedType(Type.CapturedType t, @Nullable Void unused) { - return false; // diff-coverage: ignore -- no variable declares a capture - } - - @Override - public Boolean visitErrorType(Type.ErrorType t, @Nullable Void unused) { - return false; // diff-coverage: ignore -- javac stops first - } - - @Override - public Boolean visitType(Type t, @Nullable Void unused) { - return GenericTypePrettyPrintingVisitor.printsEveryAnnotation(t); - } - }; - - /** Returns whether {@code array} or an array it nests directly carries a type-use annotation. */ - private static boolean hasAnnotatedDimension(Type.ArrayType array) { - for (Type t = array; t instanceof Type.ArrayType nested; t = nested.elemtype) { - if (!nested.getAnnotationMirrors().isEmpty()) { - return true; - } - } - return false; - } - /** Returns the named class declaring {@code typeVariable}, or {@code null} if there is none. */ private static Symbol.@Nullable ClassSymbol typeVariableOwner( Type.@Nullable TypeVar typeVariable) { 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 b9dc82a9c3..8dba430b2a 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java @@ -62,8 +62,6 @@ Relation swapped() { * @param path the steps the check took into the target, which the {@code path} line names * @param targetNode the node the target has there * @param sourceNode the node the source has there - * @param targetNodePath where {@code targetNode} sits in the target as written, or {@code null} - * where it sits nowhere a printer shows, which is what a rewrite of the target has to address * @param targetCaret where the target's caret goes, or {@code null} where the target gets none * @param sourceCaret where the source's caret goes in the source as written, or {@code null} * where the node the check compared sits nowhere in that type @@ -73,11 +71,6 @@ Relation swapped() { * @param sourcePrintedNode the node under {@code sourceCaret}; where there is no such caret, the * deepest node the compared view of the source prints. It is the wildcard itself where the * node at fault lies below a bound the wildcard leaves implicit - * @param sourceWildcard the source wildcard whose upper bound the check compared at this - * position, or {@code null} where the source states the type outright or the comparison was - * not one of upper bounds - * @param targetUpperBound the upper bound the target requires there, which writing an explicit - * bound on {@code sourceWildcard} would have to produce * @param sourceHiddenBound the upper bound the check compared for the wildcard under {@code * sourceCaret} and the steps it took into that bound, where the printer does not show that * bound; {@code null} otherwise @@ -87,14 +80,11 @@ record Mismatch( TypePath path, Type targetNode, Type sourceNode, - @Nullable TypePath targetNodePath, @Nullable TypePath targetCaret, @Nullable TypePath sourceCaret, @Nullable Type viewedSource, @Nullable TypePath viewCaret, Type sourcePrintedNode, - Type.@Nullable WildcardType sourceWildcard, - @Nullable Type targetUpperBound, @Nullable HiddenBound sourceHiddenBound) {} /** @@ -152,16 +142,6 @@ static Track lost(Track track) { } } - /** - * The upper bounds whose comparison is the current one. - * - * @param sourceWildcard the source wildcard the source bound belongs to, or {@code null} where - * the source states the type outright - * @param targetUpperBound the upper bound the target requires - */ - private record BoundComparison( - Type.@Nullable WildcardType sourceWildcard, Type targetUpperBound) {} - /** * Where the comparison stands. The visitor saves one before a descent and restores it after. * @@ -176,7 +156,6 @@ private record BoundComparison( * @param swapped whether the visitor's left side is the source, as inside the lower bound of a * {@code ? super} wildcard, where the check asks whether that bound is a subtype of the * source - * @param bound the upper bounds this comparison is of, or {@code null} where it is not of bounds */ record Frame( TypePath targetSteps, @@ -185,8 +164,7 @@ record Frame( @Nullable Type viewedSource, @Nullable Track view, Type sourceShown, - boolean swapped, - @Nullable BoundComparison bound) {} + boolean swapped) {} private Frame frame; @@ -209,8 +187,7 @@ record Frame( null, null, sourceType, - false, - null); + false); } /** Returns the rejected positions, in the order the check compared them. */ @@ -256,8 +233,7 @@ Frame enterClassComparison(Type rhs, Type rhsView) { viewedSource, view, frame.sourceShown(), - frame.swapped(), - frame.bound()); + frame.swapped()); return saved; } @@ -300,24 +276,21 @@ Frame enterTypeArgument(int index, Type.ClassType lhs, Type.ClassType rhsView) { TypePath.Step.Kind.TYPE_ARGUMENT, index, rhsView, - rhsView.getTypeArguments().get(index)), - null); + rhsView.getTypeArguments().get(index))); } /** Steps into the enclosing type of {@code lhs} and of {@code rhsView}. */ Frame enterEnclosingType(Type.ClassType lhs, Type.ClassType rhsView) { return enter( new Step(TypePath.Step.Kind.ENCLOSING_TYPE, -1, lhs, lhs.getEnclosingType()), - new Step(TypePath.Step.Kind.ENCLOSING_TYPE, -1, rhsView, rhsView.getEnclosingType()), - null); + new Step(TypePath.Step.Kind.ENCLOSING_TYPE, -1, rhsView, rhsView.getEnclosingType())); } /** Steps into the component types of two arrays. */ Frame enterArrayElement(Type.ArrayType lhs, Type.ArrayType rhs) { return enter( new Step(TypePath.Step.Kind.ARRAY_ELEMENT, -1, lhs, lhs.elemtype), - new Step(TypePath.Step.Kind.ARRAY_ELEMENT, -1, rhs, rhs.elemtype), - null); + new Step(TypePath.Step.Kind.ARRAY_ELEMENT, -1, rhs, rhs.elemtype)); } /** @@ -326,19 +299,13 @@ Frame enterArrayElement(Type.ArrayType lhs, Type.ArrayType rhs) { */ Frame enterUpperBounds( @Nullable Type lhsWildcard, Type lhsBound, @Nullable Type rhsWildcard, Type rhsBound) { - BoundComparison bound = - lhsWildcard == null || frame.swapped() - ? null - : new BoundComparison( - rhsWildcard == null ? null : GenericsUtils.asWildcard(rhsWildcard), lhsBound); return enter( lhsWildcard == null ? null : new Step(TypePath.Step.Kind.WILDCARD_UPPER_BOUND, -1, lhsWildcard, lhsBound), rhsWildcard == null ? null - : new Step(TypePath.Step.Kind.WILDCARD_UPPER_BOUND, -1, rhsWildcard, rhsBound), - bound); + : new Step(TypePath.Step.Kind.WILDCARD_UPPER_BOUND, -1, rhsWildcard, rhsBound)); } /** @@ -353,8 +320,7 @@ Frame enterLowerBounds( new Step(TypePath.Step.Kind.WILDCARD_LOWER_BOUND, -1, lhsWildcard, lhsBound), rhsWildcard == null ? null - : new Step(TypePath.Step.Kind.WILDCARD_LOWER_BOUND, -1, rhsWildcard, rhsBound), - null); + : new Step(TypePath.Step.Kind.WILDCARD_LOWER_BOUND, -1, rhsWildcard, rhsBound)); frame = new Frame( frame.targetSteps(), @@ -363,8 +329,7 @@ Frame enterLowerBounds( frame.viewedSource(), frame.view(), frame.sourceShown(), - !frame.swapped(), - null); + !frame.swapped()); return saved; } @@ -379,21 +344,17 @@ void reject(Relation relation, Type lhsNode, Type rhsNode) { Track target = frame.target(); Track source = frame.source(); Track view = frame.view(); - BoundComparison bound = frame.bound(); mismatches.add( new Mismatch( swapped ? relation.swapped() : relation, frame.targetSteps(), targetNode, sourceNode, - target.state() == Track.State.LOCATED ? target.path() : null, target.caret(), source.caret(), frame.viewedSource(), view == null ? null : view.caret(), source.caret() != null ? source.node() : frame.sourceShown(), - bound == null ? null : bound.sourceWildcard(), - bound == null ? null : bound.targetUpperBound(), source.hidden())); } @@ -411,7 +372,7 @@ private record Step(TypePath.Step.Kind kind, int index, Type parent, Type child) * Takes one step on each side the visitor names, and returns the frame from before it. A {@code * null} step leaves that side where it is. */ - private Frame enter(@Nullable Step lhs, @Nullable Step rhs, @Nullable BoundComparison bound) { + private Frame enter(@Nullable Step lhs, @Nullable Step rhs) { Frame saved = frame; Step targetStep = saved.swapped() ? rhs : lhs; Step sourceStep = saved.swapped() ? lhs : rhs; @@ -433,14 +394,7 @@ private Frame enter(@Nullable Step lhs, @Nullable Step rhs, @Nullable BoundCompa } frame = new Frame( - targetSteps, - target, - source, - saved.viewedSource(), - view, - sourceShown, - saved.swapped(), - bound); + targetSteps, target, source, saved.viewedSource(), view, sourceShown, saved.swapped()); return saved; } diff --git a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java deleted file mode 100644 index be68c40bc1..0000000000 --- a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java +++ /dev/null @@ -1,255 +0,0 @@ -package com.uber.nullaway.generics; - -import static com.google.common.truth.Truth.assertWithMessage; - -import com.google.errorprone.CompilationTestHelper; -import com.uber.nullaway.NullAway; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.stream.Stream; -import org.junit.Test; - -/** - * Building a generic nullability mismatch message walks the compilation unit to find the local - * variable a fix rewrites. The walk happens at most once per unit, and not at all for a mismatch - * whose error is suppressed. Whether the check accepts a value of that local against the rewritten - * type is computed once per value and type, however many diagnostics read the local, and the path - * to a value is rebuilt only where that is computed. - */ -public class MismatchMessageWorkTests { - - @Test - public void oneWalkOfTheCompilationUnitServesEveryLocalFix() { - List walks = - walksWhileCompiling( - """ - import java.util.ArrayList; - import java.util.Collection; - import java.util.List; - import org.jspecify.annotations.NullMarked; - @NullMarked - class Test { - static void take(Collection c) {} - void assignment() { - List l = new ArrayList(); - // BUG: Diagnostic contains: declare l as List - Collection c = l; - } - void argument() { - List l = new ArrayList(); - // BUG: Diagnostic contains: possible fix: declare l as List - take(l); - } - Collection returned() { - List l = new ArrayList(); - // BUG: Diagnostic contains: possible fix: declare l as List - return l; - } - } - """); - assertWithMessage("compilation units walked for local declarations") - .that(walks) - .containsExactly("Test.java"); - } - - @Test - public void eachValueOfALocalIsCheckedOnceHoweverManyDiagnosticsReadIt() { - List checks = Collections.synchronizedList(new ArrayList<>()); - LocalVariableDeclarations.acceptanceListener = value -> checks.add(value.toString()); - try { - compile( - """ - import java.util.ArrayList; - import java.util.Collection; - import java.util.LinkedList; - import java.util.List; - import org.jspecify.annotations.NullMarked; - @NullMarked - class Test { - static void take(Collection c) {} - void everyValueAccepts() { - List l = new ArrayList(); - l = new ArrayList(); - l = new LinkedList(); - // BUG: Diagnostic contains: possible fix: declare l as List - take(l); - // BUG: Diagnostic contains: possible fix: declare l as List - take(l); - // BUG: Diagnostic contains: possible fix: declare l as List - take(l); - } - void oneValueIsUnknown() { - List l = new ArrayList(); - l = new LinkedList(); - // BUG: Diagnostic contains: incompatible nullability - take(l); - // BUG: Diagnostic contains: incompatible nullability - take(l); - // BUG: Diagnostic contains: incompatible nullability - take(l); - l = List.of("b"); - } - } - """); - } finally { - LocalVariableDeclarations.acceptanceListener = null; - } - assertWithMessage( - "values whose acceptance was computed rather than read from the cache; a definite" - + " result is kept, and the unknown one, a call whose inference runs only after" - + " the reads, is computed for each read") - .that(checks) - .containsExactly( - "new ArrayList()", - "new ArrayList()", - "new LinkedList()", - "new ArrayList()", - "new LinkedList()", - "List.of(\"b\")", - "List.of(\"b\")", - "List.of(\"b\")"); - } - - @Test - public void aValuePathIsRebuiltOnlyWhereItsAcceptanceIsComputed() { - List rebuilds = Collections.synchronizedList(new ArrayList<>()); - LocalVariableDeclarations.rebuildListener = value -> rebuilds.add(value.toString()); - try { - compile( - """ - import org.jspecify.annotations.NullMarked; - import org.jspecify.annotations.Nullable; - @NullMarked - class Test { - interface Source { - T get(); - } - static void take(Source s) {} - void lambdaInitializer(Source a, Source b) { - Source s = () -> "x"; - s = a; - s = b; - // BUG: Diagnostic contains: incompatible nullability - take(s); - // BUG: Diagnostic contains: incompatible nullability - take(s); - // BUG: Diagnostic contains: incompatible nullability - take(s); - } - } - """); - } finally { - LocalVariableDeclarations.rebuildListener = null; - } - assertWithMessage( - "value paths rebuilt; the acceptance of a and b is kept after the first read, and that" - + " of the lambda is unknown, so only the lambda is checked again") - .that(rebuilds) - .containsExactly("()->\"x\"", "a", "b", "()->\"x\"", "()->\"x\"") - .inOrder(); - } - - @Test - public void aParameterOrFieldSourceCostsNoWalk() { - List walks = - walksWhileCompiling( - """ - import java.util.Collection; - import java.util.List; - import org.jspecify.annotations.NullMarked; - @NullMarked - class Test { - List field = List.of(); - static void take(Collection c) {} - void parameter(List l) { - // BUG: Diagnostic contains: possible fix: declare l as List - take(l); - } - void field() { - // BUG: Diagnostic contains: possible fix: declare field as List - take(field); - } - } - """); - assertWithMessage( - "only a local variable gets an edit, so a parameter or a field source is never looked up") - .that(walks) - .isEmpty(); - } - - @Test - public void aMismatchInAnExcludedNestedClassCostsNoWalk() { - List walks = - walksWhileCompiling( - """ - import java.util.Collection; - import java.util.List; - import org.jspecify.annotations.NullMarked; - @NullMarked - class Test { - @interface Excluded {} - static void take(Collection c) {} - static List make() { - throw new RuntimeException(); - } - @Excluded - static class Inner { - void assignment() { - List l = make(); - Collection c = l; - } - void argument() { - List l = make(); - take(l); - } - Collection returned() { - List l = make(); - return l; - } - } - } - """, - "-XepOpt:NullAway:ExcludedClassAnnotations=Test.Excluded"); - assertWithMessage( - "NullAway checks an excluded nested class and drops its errors as suppressed, so no" - + " message is built for them and no compilation unit is walked") - .that(walks) - .isEmpty(); - } - - /** - * Compiles {@code source} as {@code Test.java} in JSpecify mode with {@code extraArgs}, expecting - * the diagnostics its {@code // BUG: Diagnostic contains:} comments mark and no others, and - * returns the file name of each compilation unit indexed for local declarations, once per walk. - */ - private List walksWhileCompiling(String source, String... extraArgs) { - List walks = Collections.synchronizedList(new ArrayList<>()); - LocalVariableDeclarations.indexListener = - unit -> { - String path = unit.getSourceFile().getName(); - walks.add(path.substring(path.lastIndexOf('/') + 1)); - }; - try { - compile(source, extraArgs); - } finally { - LocalVariableDeclarations.indexListener = null; - } - return walks; - } - - /** - * Compiles {@code source} as {@code Test.java} in JSpecify mode with {@code extraArgs}, expecting - * the diagnostics its {@code // BUG: Diagnostic contains:} comments mark and no others. - */ - private void compile(String source, String... extraArgs) { - CompilationTestHelper.newInstance(NullAway.class, getClass()) - .setArgs( - JSpecifyJavacConfig.withJSpecifyModeArgs( - Stream.concat( - Stream.of("-XepOpt:NullAway:OnlyNullMarked=true"), Stream.of(extraArgs)) - .toList())) - .addSourceLines("Test.java", source) - .doTest(); - } -} 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 index 19698ab7c0..fb405ef5b0 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java @@ -1,5 +1,9 @@ package com.uber.nullaway.jspecify.mismatchmessage; +import com.google.errorprone.CompilationTestHelper; +import com.uber.nullaway.generics.JSpecifyJavacConfig; +import java.util.List; +import java.util.Map; import org.junit.Test; /** @@ -266,4 +270,102 @@ void test(List> f) { } """); } + + // The printed types show a type-use annotation only where its simple name is Nullable, so the + // caret columns count no other annotation + @Test + public void printedTypesShowOnlyAnAnnotationNamedNullable() { + CompilationTestHelper helper = + makeTestHelperWithArgs( + JSpecifyJavacConfig.withJSpecifyModeArgs( + List.of( + "-XepOpt:NullAway:OnlyNullMarked=true", + "-XepOpt:NullAway:CustomNullableAnnotations=Test.CanBeNull,p.Nullable"))); + String withoutAnnotation = + """ + incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Map + ^ + target: Map + ^^^^^^ + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + """; + Map.of( + "NULLABLE_WITH_A_VALUE", + """ + incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Map + ^ + target: Map + ^^^^^^ + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + """, + "ANNOTATED_WILDCARD", + withoutAnnotation, + "NULLABLE_WILDCARD", + withoutAnnotation, + "TAINTED", + withoutAnnotation, + "TAINTED_ARRAY_ELEMENT", + """ + incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Map + ^ + target: Map + ^^^^^^ + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + """, + "CUSTOM_NULLABLE", + withoutAnnotation) + .forEach((key, expected) -> helper.expectErrorMessage(key, messageIs(expected))); + helper + .addSourceLines( + "Test.java", + nullMarkedClass( + """ + @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) + @interface Tainted {} + @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) + @interface CanBeNull {} + static void takeCustom(Map m) {} + void customNullable(Map custom) { + // BUG: Diagnostic matches: CUSTOM_NULLABLE + takeCustom(custom); + } + static void take(Map m) {} + static void takeArrays(Map m) {} + void tainted(Map tainted) { + // BUG: Diagnostic matches: TAINTED + take(tainted); + } + void taintedArrayElement(Map m) { + // BUG: Diagnostic matches: TAINTED_ARRAY_ELEMENT + takeArrays(m); + } + static void takeNullableValues(Map m) {} + void nullableWithAValue(Map m) { + // BUG: Diagnostic matches: NULLABLE_WITH_A_VALUE + takeNullableValues(m); + } + void annotatedWildcard(Map<@Tainted ?, String> m) { + // BUG: Diagnostic matches: ANNOTATED_WILDCARD + take(m); + } + // BUG: Diagnostic contains: nullness annotations cannot be written directly on a wildcard + void nullableWildcard(Map<@Nullable ?, String> m) { + // BUG: Diagnostic matches: NULLABLE_WILDCARD + take(m); + } + """)) + .addSourceLines( + "p/Nullable.java", + """ + package p; + @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) + public @interface Nullable { + String value(); + } + """) + .doTest(); + } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java deleted file mode 100644 index bcfca58d8a..0000000000 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixRoundTripTests.java +++ /dev/null @@ -1,775 +0,0 @@ -package com.uber.nullaway.jspecify.mismatchmessage; - -import static com.google.common.truth.Truth.assertWithMessage; -import static java.nio.charset.StandardCharsets.UTF_8; - -import com.google.errorprone.BaseErrorProneJavaCompiler; -import com.google.errorprone.scanner.ScannerSupplier; -import com.sun.source.tree.AnnotationTree; -import com.sun.source.tree.CompilationUnitTree; -import com.sun.source.tree.IdentifierTree; -import com.sun.source.tree.MemberSelectTree; -import com.sun.source.tree.Tree; -import com.sun.source.tree.VariableTree; -import com.sun.source.util.JavacTask; -import com.sun.source.util.SourcePositions; -import com.sun.source.util.TreeScanner; -import com.sun.source.util.Trees; -import com.sun.tools.javac.api.JavacTool; -import com.uber.nullaway.NullAway; -import com.uber.nullaway.generics.JSpecifyJavacConfig; -import java.io.IOException; -import java.io.StringWriter; -import java.io.UncheckedIOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import javax.tools.Diagnostic; -import javax.tools.DiagnosticCollector; -import javax.tools.JavaFileObject; -import javax.tools.StandardJavaFileManager; -import org.jspecify.annotations.Nullable; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -/** - * Applying a fix that a generic nullability mismatch message offers yields code that compiles and - * that NullAway accepts where the fix claims it does. A {@code declare as } line is - * applied by writing {@code } in place of the declared type of {@code } and of the - * nullable annotations among its modifiers, and the Error Prone edit as {@code -XepPatchChecks} - * applies it. A fix of the source, as a line or as the edit, has to leave no generic mismatch, and - * no override whose type arguments differ in nullness, on any line that names the rewritten - * variable: its declaration, its initializer, every assignment to it, and the reported read. A fix - * of the target, the variable declared on the reported line, has to leave none on that line; a - * later read of the variable may still reject it, which is what {@code possible} says. - */ -public class FixRoundTripTests { - - @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - /** The first words of every generic nullability mismatch message. */ - private static final String MISMATCH = "incompatible nullability in "; - - /** The end of the first line of a report of an override whose type arguments differ. */ - private static final String OVERRIDE_MISMATCH = "which has mismatched type parameter nullability"; - - private static final Pattern FIX_LINE = Pattern.compile("declare (\\w+) as (.+)$"); - - @Test - public void sourceEditWhoseInitializerRejectsTheRewrite() { - assertRoundTrip( - """ - static void take(Collection c) {} - static List make() { - throw new RuntimeException(); - } - void test() { - List l = make(); - take(l); - } - """); - } - - @Test - public void sourceEditWhoseInitializerHasANullableTypeArgument() { - assertRoundTrip( - """ - static void take(Collection c) {} - void test() { - List l = new ArrayList<@Nullable String>(); - take(l); - } - """); - } - - @Test - public void sourceEditWhoseReassignmentRejectsTheRewrite() { - assertRoundTrip( - """ - static void take(Collection c) {} - static List make() { - throw new RuntimeException(); - } - void test(List init) { - List l = init; - take(l); - l = make(); - } - """); - } - - @Test - public void targetEditOfALocalThatIsReturned() { - assertRoundTrip( - """ - Map test(Map m) { - Map declared = m; - return declared; - } - """); - } - - @Test - public void sourceFixWithACustomNullableAnnotation() { - assertRoundTrip( - """ - static void take(Map map) {} - void test() { - Map m = new HashMap(); - take(m); - } - """, - CAN_BE_NULL); - } - - @Test - public void targetFixWithACustomNullableAnnotation() { - assertRoundTrip( - """ - void test(Map m) { - Map d = m; - d.hashCode(); - } - """, - CAN_BE_NULL); - } - - @Test - public void localClassInAnInstanceMethod() { - assertRoundTrip( - """ - void test() { - class Local {} - Local l = new Local(); - Local t = l; - t.hashCode(); - } - """); - } - - @Test - public void localClassInAConstructor() { - assertRoundTrip( - """ - Test() { - class Local {} - Local l = new Local(); - Local t = l; - t.hashCode(); - } - """); - } - - @Test - public void localClassInAnInitializer() { - assertRoundTrip( - """ - { - class Local {} - Local l = new Local(); - Local t = l; - t.hashCode(); - } - """); - } - - @Test - public void innerClassWithANullableModifier() { - assertRoundTrip( - """ - class Inner {} - void test(Inner<@Nullable String> src) { - @Nullable Test.Inner x = src; - if (x != null) { - x.hashCode(); - } - } - """); - } - - @Test - public void innerClassSourceWithANullableModifier() { - assertRoundTrip( - """ - class Inner {} - static void take(@Nullable Inner i) {} - void test() { - @Nullable Test.Inner x = new Inner(); - take(x); - } - """); - } - - @Test - public void innerClassArrayWithANullableModifier() { - assertRoundTrip( - """ - class Inner {} - void test(Inner<@Nullable String>[] src) { - @Nullable Test.Inner[] x = src; - x.hashCode(); - } - """); - } - - @Test - public void sourceEditWhoseInitializerAcceptsTheRewrite() { - assertRoundTrip( - """ - static void take(Collection c) {} - void test() { - List l = new ArrayList(); - take(l); - } - """); - } - - @Test - public void localClassInAStaticMethod() { - assertRoundTrip( - """ - static void test() { - class Local {} - Local l = new Local(); - Local t = l; - t.hashCode(); - } - """); - } - - @Test - public void conditionalWithABranchThatRejectsTheRewrite() { - assertRoundTrip( - """ - static void take(Collection c) {} - static List make() { - throw new RuntimeException(); - } - void test(boolean flag) { - List l = flag ? new ArrayList() : make(); - take(l); - } - """); - } - - @Test - public void nestedConditionalWithABranchThatRejectsTheRewrite() { - assertRoundTrip( - """ - static void take(Collection c) {} - static List make() { - throw new RuntimeException(); - } - void test(boolean flag, boolean other) { - List l = (flag ? new ArrayList() : (other ? new ArrayList() : make())); - take(l); - } - """); - } - - @Test - public void conditionalWhoseBranchesAcceptTheRewrite() { - assertRoundTrip( - """ - static void take(Collection c) {} - void test(boolean flag) { - List l = flag ? new ArrayList() : new ArrayList(); - take(l); - } - """); - } - - @Test - public void lambdaInitializer() { - assertRoundTrip( - """ - interface Source { - T get(); - } - static void take(Source s) {} - void test() { - Source s = () -> null; - take(s); - } - """); - } - - @Test - public void resourceVariableWhoseInitializerRejectsTheRewrite() { - assertRoundTrip( - """ - static class Res implements AutoCloseable { - @Override - public void close() {} - } - static void take(Res resource) {} - static Res open() { - throw new RuntimeException(); - } - void test() { - try (Res r = open()) { - take(r); - } - } - """); - } - - @Test - public void resourceVariableWhoseInitializerAcceptsTheRewrite() { - assertRoundTrip( - """ - static class Res implements AutoCloseable { - @Override - public void close() {} - } - static void take(Res resource) {} - void test() { - try (Res r = new Res()) { - take(r); - } - } - """); - } - - @Test - public void loopVariable() { - assertRoundTrip( - """ - static void take(Collection c) {} - void test(List> lists) { - for (List l : lists) { - take(l); - } - } - """); - } - - @Test - public void loopVariableReassignedToAValueThatRejectsTheRewrite() { - assertRoundTrip( - """ - static void take(Collection c) {} - static List make() { - throw new RuntimeException(); - } - void test(List> lists) { - for (List l : lists) { - l = make(); - take(l); - } - } - """); - } - - @Test - public void rawInitializer() { - assertRoundTrip( - """ - static void take(Collection c) {} - @SuppressWarnings("rawtypes") - void test(List raw) { - List l = raw; - take(l); - } - """); - } - - @Test - public void sourceFixWithANullableAnnotationThatHasAValue() { - assertRoundTrip( - """ - static void take(Map m) {} - void test() { - Map m = new HashMap(); - take(m); - } - """, - NULLABLE_WITH_A_VALUE); - } - - @Test - public void targetFixCopyingANullableAnnotationThatHasAValue() { - assertRoundTrip( - """ - void test(Map m) { - Map d = m; - d.hashCode(); - } - """, - NULLABLE_WITH_A_VALUE); - } - - @Test - public void sourceFixOfAParameter() { - assertRoundTrip( - """ - static void take(Collection c) {} - void test(List l) { - take(l); - } - """); - } - - @Test - public void sourceFixOfAnExplicitlyTypedLambdaParameter() { - assertRoundTrip( - """ - interface Sink { - void accept(T t); - } - static void take(Collection c) {} - Sink> sink = (List l) -> take(l); - """); - } - - @Test - public void sourceFixOfAField() { - assertRoundTrip( - """ - static void take(Collection c) {} - List field = new ArrayList(); - void test() { - take(field); - } - """); - } - - /** - * A type-use nullable annotation named {@code Nullable} with a required element, {@code - * p.Nullable}, and the flag that names it. - */ - private static final Extra NULLABLE_WITH_A_VALUE = - new Extra( - Map.of( - "p/Nullable.java", - """ - package p; - import java.lang.annotation.ElementType; - import java.lang.annotation.Target; - @Target(ElementType.TYPE_USE) - public @interface Nullable { - String value(); - } - """), - "", - List.of("-XepOpt:NullAway:CustomNullableAnnotations=p.Nullable"), - Set.of("Nullable")); - - /** A custom type-use nullable annotation, {@code p.CanBeNull}, and the flag that names it. */ - private static final Extra CAN_BE_NULL = - new Extra( - Map.of( - "p/CanBeNull.java", - """ - package p; - import java.lang.annotation.ElementType; - import java.lang.annotation.Target; - @Target(ElementType.TYPE_USE) - public @interface CanBeNull {} - """), - "import p.CanBeNull;\n", - List.of("-XepOpt:NullAway:CustomNullableAnnotations=p.CanBeNull"), - Set.of("Nullable", "CanBeNull")); - - private static final Extra NONE = new Extra(Map.of(), "", List.of(), Set.of("Nullable")); - - /** - * What a program needs beyond {@code class Test}: other source files by path, imports added to - * {@code Test.java}, javac arguments, and the simple names of the nullable annotations a {@code - * declare} line replaces among the modifiers. - */ - private record Extra( - Map files, - String imports, - List args, - Set nullableAnnotationNames) {} - - private void assertRoundTrip(String members) { - assertRoundTrip(members, NONE); - } - - /** - * Compiles {@code members} as the body of {@code @NullMarked class Test}, expects at least one - * generic nullability mismatch, and applies each fix of each such diagnostic in a copy of the - * program: the Error Prone edits through {@code -XepPatchChecks}, and every {@code declare - * as } line by rewriting the declaration of {@code }. - */ - private void assertRoundTrip(String members, Extra extra) { - String test = extra.imports() + MismatchMessageTestBase.nullMarkedClass(members); - List> original = - compile(write("original", test, extra), extra, false); - assertWithMessage("javac errors in the program\n%s", test).that(errors(original)).isEmpty(); - List> mismatches = mismatches(original); - assertWithMessage("generic nullability mismatches of the program\n%s", test) - .that(mismatches) - .isNotEmpty(); - for (Diagnostic mismatch : mismatches) { - String message = mismatch.getMessage(Locale.ROOT); - for (String line : message.lines().toList()) { - Matcher fix = FIX_LINE.matcher(line.trim()); - if (fix.find()) { - String name = fix.group(1); - Declaration declaration = declaration(test, name); - String rewritten = declaration.withType(fix.group(2), extra.nullableAnnotationNames()); - List> after = - compile(write("text", rewritten, extra), extra, false); - assertWithMessage( - "javac errors after applying `%s` of the diagnostic\n%s\nto get\n%s", - line.trim(), message, rewritten) - .that(errors(after)) - .isEmpty(); - if (declaration.line() == mismatch.getLineNumber()) { - assertWithMessage( - "generic mismatches on line %s, which the diagnostic reported, after applying" - + " `%s` of the diagnostic\n%s\nto get\n%s", - mismatch.getLineNumber(), line.trim(), message, rewritten) - .that( - genericErrors(after).stream() - .filter(d -> d.getLineNumber() == mismatch.getLineNumber()) - .map(d -> d.getMessage(Locale.ROOT)) - .toList()) - .isEmpty(); - } else { - assertWithMessage( - "generic mismatches on a line naming %s after applying `%s` of the" - + " diagnostic\n%s\nto get\n%s", - name, line.trim(), message, rewritten) - .that(mismatchesNaming(after, rewritten, List.of(name))) - .isEmpty(); - } - } - } - } - Path patched = write("patched", test, extra); - compile(patched, extra, true); - String edited = read(patched.resolve("Test.java")); - if (edited.equals(test)) { - return; - } - List names = - mismatches.stream() - .flatMap(d -> d.getMessage(Locale.ROOT).lines()) - .map(line -> FIX_LINE.matcher(line.trim())) - .filter(Matcher::find) - .map(fix -> fix.group(1)) - .distinct() - .toList(); - List> after = compile(patched, extra, false); - assertWithMessage("javac errors after applying the Error Prone edits to get\n%s", edited) - .that(errors(after)) - .isEmpty(); - assertWithMessage( - "generic mismatches on a line naming %s after applying the Error Prone edits to get\n%s", - names, edited) - .that(mismatchesNaming(after, edited, names)) - .isEmpty(); - } - - /** - * Returns the generic mismatches among {@code diagnostics} on a line of {@code source} that names - * one of {@code names}, each with its line number. - */ - private static List mismatchesNaming( - List> diagnostics, String source, List names) { - List lines = source.lines().toList(); - return genericErrors(diagnostics).stream() - .filter( - d -> - names.stream() - .anyMatch( - name -> - Pattern.compile("\\b" + name + "\\b") - .matcher(lines.get((int) d.getLineNumber() - 1)) - .find())) - .map(d -> "line " + d.getLineNumber() + ": " + d.getMessage(Locale.ROOT)) - .toList(); - } - - /** Writes {@code test} as {@code Test.java} and the files of {@code extra} into a new folder. */ - private Path write(String name, String test, Extra extra) { - try { - Path folder = temporaryFolder.newFolder().toPath().resolve(name); - Files.createDirectories(folder); - Files.writeString(folder.resolve("Test.java"), test, UTF_8); - for (Map.Entry file : extra.files().entrySet()) { - Path path = folder.resolve(file.getKey()); - Files.createDirectories(path.getParent()); - Files.writeString(path, file.getValue(), UTF_8); - } - return folder; - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } - - private static String read(Path path) { - try { - return Files.readString(path, UTF_8); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } - - /** - * Compiles every Java file under {@code folder} with NullAway in JSpecify mode over - * {@code @NullMarked} code, and with {@code patch}, applies the first fix of each NullAway - * diagnostic to the files in place. - */ - private List> compile( - Path folder, Extra extra, boolean patch) { - List args = new ArrayList<>(); - args.addAll(List.of("-d", folder.resolve("classes").toString(), "-proc:none")); - args.add("-XepOpt:NullAway:OnlyNullMarked=true"); - args.addAll(extra.args()); - if (patch) { - args.addAll(List.of("-XepPatchChecks:NullAway", "-XepPatchLocation:IN_PLACE")); - } - DiagnosticCollector diagnostics = new DiagnosticCollector<>(); - BaseErrorProneJavaCompiler compiler = - new BaseErrorProneJavaCompiler(ScannerSupplier.fromBugCheckerClasses(NullAway.class)); - try (StandardJavaFileManager fileManager = - compiler.getStandardFileManager(diagnostics, Locale.ROOT, UTF_8); - Stream files = Files.walk(folder)) { - List sources = files.filter(path -> path.toString().endsWith(".java")).toList(); - compiler - .getTask( - new StringWriter(), - fileManager, - diagnostics, - JSpecifyJavacConfig.withJSpecifyModeArgs(args), - null, - fileManager.getJavaFileObjectsFromPaths(sources)) - .call(); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - return diagnostics.getDiagnostics().stream() - .filter(d -> d.getSource() != null && d.getSource().getName().endsWith("Test.java")) - .collect(Collectors.toList()); - } - - private static List> mismatches( - List> diagnostics) { - return diagnostics.stream() - .filter(d -> d.getMessage(Locale.ROOT).contains("[NullAway] " + MISMATCH)) - .toList(); - } - - /** - * Returns the generic mismatches among {@code diagnostics} and the reports of a parameter or a - * return type whose type arguments differ in nullness from those of the method it overrides, the - * error a rewritten parameter type can move to. - */ - private static List> genericErrors( - List> diagnostics) { - return diagnostics.stream() - .filter( - d -> - d.getMessage(Locale.ROOT).contains("[NullAway] " + MISMATCH) - || d.getMessage(Locale.ROOT).contains(OVERRIDE_MISMATCH)) - .toList(); - } - - private static List errors(List> diagnostics) { - return diagnostics.stream() - .filter(d -> d.getKind() == Diagnostic.Kind.ERROR) - .map(d -> "line " + d.getLineNumber() + ": " + d.getMessage(Locale.ROOT)) - .toList(); - } - - /** - * The declaration of a variable in {@code source}: its line, 1-based, and the positions of its - * type tree and of the nullable annotations among its modifiers. - */ - private record Declaration( - String source, long line, int typeStart, int typeEnd, Map annotations) { - - /** - * Returns {@link #source} with {@code type} written in place of the declared type and of the - * annotations whose simple name is in {@code nullableNames}, as a reader applies {@code declare - * as }. - */ - String withType(String type, Set nullableNames) { - StringBuilder rewritten = new StringBuilder(source); - rewritten.replace(typeStart, typeEnd, type); - List removed = - annotations.entrySet().stream() - .filter(annotation -> nullableNames.contains(annotation.getKey())) - .map(Map.Entry::getValue) - .sorted((a, b) -> Integer.compare(b[0], a[0])) - .toList(); - for (int[] span : removed) { - int end = span[1]; - while (end < rewritten.length() && rewritten.charAt(end) == ' ') { - end++; - } - rewritten.delete(span[0], end); - } - return rewritten.toString(); - } - } - - /** Returns the one declaration of a variable named {@code name} in {@code source}. */ - @SuppressWarnings("removal") // the replacements are missing from the JDKs the tests run on - private static Declaration declaration(String source, String name) { - JavaFileObject file = - new javax.tools.SimpleJavaFileObject( - java.net.URI.create("string:///Test.java"), JavaFileObject.Kind.SOURCE) { - @Override - public String getCharContent(boolean ignoreEncodingErrors) { - return source; - } - }; - JavacTask task = JavacTool.create().getTask(null, null, null, List.of(), null, List.of(file)); - try { - CompilationUnitTree unit = task.parse().iterator().next(); - SourcePositions positions = Trees.instance(task).getSourcePositions(); - VariableTree[] found = {null}; - new TreeScanner<@Nullable Void, @Nullable Void>() { - @Override - public @Nullable Void visitVariable(VariableTree variable, @Nullable Void unused) { - if (variable.getName().contentEquals(name)) { - assertWithMessage("declarations of %s in\n%s", name, source).that(found[0]).isNull(); - found[0] = variable; - } - return super.visitVariable(variable, null); - } - }.scan(unit, null); - VariableTree variable = found[0]; - assertWithMessage("declaration of %s in\n%s", name, source).that(variable).isNotNull(); - Tree typeTree = variable.getType(); - Map annotations = new java.util.HashMap<>(); - for (AnnotationTree annotation : variable.getModifiers().getAnnotations()) { - Tree annotationType = annotation.getAnnotationType(); - String simpleName = - annotationType instanceof MemberSelectTree select - ? select.getIdentifier().toString() - : ((IdentifierTree) annotationType).getName().toString(); - annotations.put( - simpleName, - new int[] { - (int) positions.getStartPosition(unit, annotation), - (int) positions.getEndPosition(unit, annotation) - }); - } - int typeStart = (int) positions.getStartPosition(unit, typeTree); - return new Declaration( - source, - unit.getLineMap().getLineNumber(positions.getStartPosition(unit, variable)), - typeStart, - (int) positions.getEndPosition(unit, typeTree), - annotations); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } -} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java deleted file mode 100644 index 5e6455ecd6..0000000000 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java +++ /dev/null @@ -1,878 +0,0 @@ -package com.uber.nullaway.jspecify.mismatchmessage; - -import com.google.common.collect.ImmutableList; -import com.google.errorprone.BugCheckerRefactoringTestHelper; -import com.uber.nullaway.NullAway; -import com.uber.nullaway.generics.JSpecifyJavacConfig; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -/** - * A {@code possible fix:} line that rewrites the source comes with an Error Prone fix that rewrites - * the type the named declaration writes, where that declaration is a local variable of the - * compilation unit being analyzed, other than a pattern, resource, or enhanced {@code for} - * variable, writes its type out before the name, declares no other variable, and gets only values - * the check accepts against the rewritten type, and the run does not suggest suppressions. A fix of - * the target type gets no edit. - */ -public class FixTests { - - @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - private BugCheckerRefactoringTestHelper makeHelper(String... extraArgs) { - List args = new ArrayList<>(); - args.add("-d"); - args.add(temporaryFolder.getRoot().getAbsolutePath()); - args.add("-XepOpt:NullAway:OnlyNullMarked=true"); - args.addAll(List.of(extraArgs)); - return BugCheckerRefactoringTestHelper.newInstance(NullAway.class, getClass()) - .setArgs(ImmutableList.copyOf(JSpecifyJavacConfig.withJSpecifyModeArgs(args))); - } - - @Test - public void withSuggestSuppressionsTheEditIsTheSuppression() throws IOException { - makeHelper("-XepOpt:NullAway:SuggestSuppressions=true") - .addInputLines( - "Test.java", - """ - import java.util.ArrayList; - import java.util.Collection; - import java.util.List; - import org.jspecify.annotations.NullMarked; - import org.jspecify.annotations.Nullable; - @NullMarked - class Test { - static List<@Nullable String> get() { - throw new RuntimeException(); - } - void assignment() { - List l = get(); - } - Collection argument() { - List list = new ArrayList(); - List result = new ArrayList<>(); - result.addAll(list); - return result; - } - } - """) - .addOutputLines( - "Test.java", - """ - import java.util.ArrayList; - import java.util.Collection; - import java.util.List; - import org.jspecify.annotations.NullMarked; - import org.jspecify.annotations.Nullable; - @NullMarked - class Test { - static List<@Nullable String> get() { - throw new RuntimeException(); - } - void assignment() { - @SuppressWarnings("NullAway") - List l = get(); - } - @SuppressWarnings("NullAway") - Collection argument() { - List list = new ArrayList(); - List result = new ArrayList<>(); - result.addAll(list); - return result; - } - } - """) - .doTest(); - } - - @Test - public void theEditRewritesOnlyALocalVariable() throws IOException { - makeHelper() - .addInputLines( - "Test.java", - """ - import java.util.ArrayList; - import java.util.Collection; - import java.util.HashMap; - import java.util.List; - import java.util.Map; - import org.jspecify.annotations.NullMarked; - import org.jspecify.annotations.Nullable; - @NullMarked - class Test { - interface I { - void overridden(List l); - } - static void take(Collection c) {} - static void takeMap(Map m) {} - static List make() { - throw new RuntimeException(); - } - interface Resource extends AutoCloseable { - @Override - void close(); - } - static void takeResource(Resource r) {} - static Resource open() { - throw new RuntimeException(); - } - public Map field = new HashMap<>(); - public void parameter(List l) { - take(l); - } - static class Impl implements I { - @Override - public void overridden(List l) { - take(l); - } - } - void fieldRead() { - takeMap(field); - } - void pattern(Object o) { - if (o instanceof List l) { - take(l); - } - } - void resource() { - try (Resource r = open()) { - takeResource(r); - } - } - void local() { - List l = new ArrayList(); - take(l); - } - } - """) - .addOutputLines( - "Test.java", - """ - import java.util.ArrayList; - import java.util.Collection; - import java.util.HashMap; - import java.util.List; - import java.util.Map; - import org.jspecify.annotations.NullMarked; - import org.jspecify.annotations.Nullable; - @NullMarked - class Test { - interface I { - void overridden(List l); - } - static void take(Collection c) {} - static void takeMap(Map m) {} - static List make() { - throw new RuntimeException(); - } - interface Resource extends AutoCloseable { - @Override - void close(); - } - static void takeResource(Resource r) {} - static Resource open() { - throw new RuntimeException(); - } - public Map field = new HashMap<>(); - public void parameter(List l) { - take(l); - } - static class Impl implements I { - @Override - public void overridden(List l) { - take(l); - } - } - void fieldRead() { - takeMap(field); - } - void pattern(Object o) { - if (o instanceof List l) { - take(l); - } - } - void resource() { - try (Resource r = open()) { - takeResource(r); - } - } - void local() { - List l = new ArrayList(); - take(l); - } - } - """) - .doTest(); - } - - @Test - public void theSourceFixEditIsAttachedOnlyWhereEveryValueAssignedToTheLocalAcceptsIt() - throws IOException { - makeHelper() - .addInputLines( - "Test.java", - """ - import java.util.ArrayList; - import java.util.Collection; - import java.util.List; - import java.util.function.Supplier; - import org.jspecify.annotations.NullMarked; - @NullMarked - class Test { - static void take(Collection c) {} - static void takeSupplier(Supplier s) {} - static List make() { - throw new RuntimeException(); - } - static String name() { - return "a"; - } - void initializerRejects() { - List l = make(); - take(l); - } - void initializerAccepts() { - List l = new ArrayList(); - take(l); - } - void reassignmentRejects() { - List l = new ArrayList(); - take(l); - l = make(); - } - void reassignmentAccepts() { - List l = new ArrayList(); - take(l); - l = new ArrayList(); - } - void nullInitializer() { - List l = null; - l = new ArrayList(); - take(l); - } - void inferredCallBeforeTheReport() { - List l = List.of("a"); - take(l); - } - void inferredCallAfterTheReport() { - List l = new ArrayList(); - take(l); - l = List.of("a"); - } - void conditional(boolean b, List x, List y) { - List l = b ? x : y; - take(l); - } - void conditionalWithABranchThatRejects(boolean b, List x) { - List l = (b ? x : (b ? x : make())); - take(l); - } - void lambda() { - Supplier s = () -> "a"; - takeSupplier(s); - } - void methodReference() { - Supplier s = Test::name; - takeSupplier(s); - } - void loopVariable(List> lists) { - for (List l : lists) { - take(l); - } - } - } - """) - .addOutputLines( - "Test.java", - """ - import java.util.ArrayList; - import java.util.Collection; - import java.util.List; - import java.util.function.Supplier; - import org.jspecify.annotations.NullMarked; - @NullMarked - class Test { - static void take(Collection c) {} - static void takeSupplier(Supplier s) {} - static List make() { - throw new RuntimeException(); - } - static String name() { - return "a"; - } - void initializerRejects() { - List l = make(); - take(l); - } - void initializerAccepts() { - List l = new ArrayList(); - take(l); - } - void reassignmentRejects() { - List l = new ArrayList(); - take(l); - l = make(); - } - void reassignmentAccepts() { - List l = new ArrayList(); - take(l); - l = new ArrayList(); - } - void nullInitializer() { - List l = null; - l = new ArrayList(); - take(l); - } - void inferredCallBeforeTheReport() { - List l = List.of("a"); - take(l); - } - void inferredCallAfterTheReport() { - List l = new ArrayList(); - take(l); - l = List.of("a"); - } - void conditional(boolean b, List x, List y) { - List l = b ? x : y; - take(l); - } - void conditionalWithABranchThatRejects(boolean b, List x) { - List l = (b ? x : (b ? x : make())); - take(l); - } - void lambda() { - Supplier s = () -> "a"; - takeSupplier(s); - } - void methodReference() { - Supplier s = Test::name; - takeSupplier(s); - } - void loopVariable(List> lists) { - for (List l : lists) { - take(l); - } - } - } - """) - .doTest(); - } - - @Test - public void theTargetTypeFixCarriesNoEdit() throws IOException { - makeHelper() - .addInputLines( - "Test.java", - """ - import java.util.ArrayList; - import java.util.Collection; - import java.util.List; - import java.util.Map; - import org.jspecify.annotations.NullMarked; - import org.jspecify.annotations.Nullable; - @NullMarked - class Test { - static void take(Collection c) {} - static List<@Nullable String> get() { - throw new RuntimeException(); - } - Map targetReadByAReturn(Map m) { - Map declared = m; - return declared; - } - void targetNotReadAsASource() { - List l = get(); - l.hashCode(); - } - void sourceFix() { - List l = new ArrayList(); - take(l); - } - } - """) - .addOutputLines( - "Test.java", - """ - import java.util.ArrayList; - import java.util.Collection; - import java.util.List; - import java.util.Map; - import org.jspecify.annotations.NullMarked; - import org.jspecify.annotations.Nullable; - @NullMarked - class Test { - static void take(Collection c) {} - static List<@Nullable String> get() { - throw new RuntimeException(); - } - Map targetReadByAReturn(Map m) { - Map declared = m; - return declared; - } - void targetNotReadAsASource() { - List l = get(); - l.hashCode(); - } - void sourceFix() { - List l = new ArrayList(); - take(l); - } - } - """) - .doTest(); - } - - // javac attaches a type-use annotation among the modifiers to the leftmost type the type tree - // names, which for an inner class is its enclosing type, such as Test in @Nullable Test.Inner. - @Test - public void theSourceFixKeepsEveryNullableAnnotationTheDeclarationWrites() throws IOException { - makeHelper() - .addInputLines( - "Test.java", - """ - import java.util.Collection; - import java.util.List; - import java.util.Map; - import org.jspecify.annotations.NullMarked; - import org.jspecify.annotations.Nullable; - @NullMarked - class Test { - class Inner {} - static class Outer { - class Inner {} - } - static void take(Collection c) {} - static void takeMap(Map m) {} - static void takeInner(Test.Inner i) {} - static void takeNullableInner(Test.@Nullable Inner i) {} - static void takeInners(Test.Inner[] i) {} - static void takeOuterInner(Outer<@Nullable String>.Inner i) {} - static void takeArray(@Nullable List @Nullable [] a) {} - static @Nullable List list() { - throw new RuntimeException(); - } - static @Nullable Map map() { - throw new RuntimeException(); - } - void modifier() { - @Nullable List l = list(); - if (l != null) { - take(l); - } - } - void typeTree() { - java.util.@Nullable List l = list(); - if (l != null) { - take(l); - } - } - void modifierAndTypeArgument() { - @Nullable Map m = map(); - if (m != null) { - takeMap(m); - } - } - void modifierAfterAnotherAnnotation() { - @SuppressWarnings("unchecked") @Nullable List l = list(); - if (l != null) { - take(l); - } - } - void modifierOnAnInnerClass(Inner init) { - @Nullable Test.Inner x = init; - takeInner(x); - } - void modifierAndInnerClassAnnotation(Inner init) { - @Nullable Test.@Nullable Inner x = init; - takeNullableInner(x); - } - void modifierOnAnArrayOfAnInnerClass(Inner[] init) { - @Nullable Test.Inner[] x = init; - takeInners(x); - } - void modifierAndEnclosingTypeArgument(Outer<@Nullable String>.Inner init) { - @Nullable Outer<@Nullable String>.Inner x = init; - takeOuterInner(x); - } - void modifierAndAnnotatedDimension(List @Nullable [] init) { - @Nullable List @Nullable [] x = init; - takeArray(x); - } - } - """) - .addOutputLines( - "Test.java", - """ - import java.util.Collection; - import java.util.List; - import java.util.Map; - import org.jspecify.annotations.NullMarked; - import org.jspecify.annotations.Nullable; - @NullMarked - class Test { - class Inner {} - static class Outer { - class Inner {} - } - static void take(Collection c) {} - static void takeMap(Map m) {} - static void takeInner(Test.Inner i) {} - static void takeNullableInner(Test.@Nullable Inner i) {} - static void takeInners(Test.Inner[] i) {} - static void takeOuterInner(Outer<@Nullable String>.Inner i) {} - static void takeArray(@Nullable List @Nullable [] a) {} - static @Nullable List list() { - throw new RuntimeException(); - } - static @Nullable Map map() { - throw new RuntimeException(); - } - void modifier() { - @Nullable List l = list(); - if (l != null) { - take(l); - } - } - void typeTree() { - @Nullable List l = list(); - if (l != null) { - take(l); - } - } - void modifierAndTypeArgument() { - @Nullable Map m = map(); - if (m != null) { - takeMap(m); - } - } - void modifierAfterAnotherAnnotation() { - @SuppressWarnings("unchecked") @Nullable List l = list(); - if (l != null) { - take(l); - } - } - void modifierOnAnInnerClass(Inner init) { - @Nullable Test.Inner x = init; - takeInner(x); - } - void modifierAndInnerClassAnnotation(Inner init) { - @Nullable Test.@Nullable Inner x = init; - takeNullableInner(x); - } - void modifierOnAnArrayOfAnInnerClass(Inner[] init) { - @Nullable Test.Inner[] x = init; - takeInners(x); - } - void modifierAndEnclosingTypeArgument(Outer<@Nullable String>.Inner init) { - @Nullable Outer<@Nullable String>.Inner x = init; - takeOuterInner(x); - } - void modifierAndAnnotatedDimension(List @Nullable [] init) { - @Nullable List @Nullable [] x = init; - takeArray(x); - } - } - """) - .doTest(); - } - - @Test - public void noEditForADeclarationInAnotherCompilationUnit() throws IOException { - makeHelper() - .addInputLines( - "Lib.java", - """ - import java.util.ArrayList; - import java.util.List; - import org.jspecify.annotations.NullMarked; - @NullMarked - class Lib { - static List field = new ArrayList<>(); - } - """) - .expectUnchanged() - .addInputLines( - "Test.java", - """ - import java.util.Collection; - import org.jspecify.annotations.NullMarked; - @NullMarked - class Test { - static void take(Collection c) {} - void test() { - take(Lib.field); - } - } - """) - .expectUnchanged() - .doTest(); - } - - @Test - public void noEditForADeclarationWithAnInferredType() throws IOException { - makeHelper() - .addInputLines( - "Test.java", - """ - import java.util.Collection; - import java.util.List; - import org.jspecify.annotations.NullMarked; - @NullMarked - class Test { - static void take(Collection c) {} - static List make() { - throw new RuntimeException(); - } - void test() { - var l = make(); - take(l); - } - } - """) - .expectUnchanged() - .doTest(); - } - - @Test - public void theFixPutsTheAnnotationBeforeTheLastSegmentOfAQualifiedName() throws IOException { - makeHelper() - .addInputLines( - "Test.java", - """ - import java.util.HashMap; - import java.util.Map; - import org.jspecify.annotations.NullMarked; - import org.jspecify.annotations.Nullable; - @NullMarked - class Test { - static class List {} - static void takeEntries(Map> m) {} - static void takeLists(Map> m) {} - void test() { - Map> nested = new HashMap>(); - takeEntries(nested); - Map> clashing = new HashMap>(); - takeLists(clashing); - } - } - """) - .addOutputLines( - "Test.java", - """ - import java.util.HashMap; - import java.util.Map; - import org.jspecify.annotations.NullMarked; - import org.jspecify.annotations.Nullable; - @NullMarked - class Test { - static class List {} - static void takeEntries(Map> m) {} - static void takeLists(Map> m) {} - void test() { - Map> nested = new HashMap>(); - takeEntries(nested); - Map> clashing = new HashMap>(); - takeLists(clashing); - } - } - """) - .doTest(); - } - - @Test - public void noEditForADeclarationOfSeveralVariables() throws IOException { - makeHelper() - .addInputLines( - "Test.java", - """ - import java.util.ArrayList; - import java.util.Collection; - import java.util.List; - import org.jspecify.annotations.NullMarked; - @NullMarked - class Test { - static void take(Collection c) {} - void several() { - List first = new ArrayList(), second = new ArrayList(); - take(first); - take(second); - } - void loop() { - for (List first = new ArrayList(), second = first; ; ) { - take(first); - } - } - void oldStyleCase(int k) { - switch (k) { - case 1: - List first = new ArrayList(), second = new ArrayList(); - take(first); - break; - default: - } - } - void besideSeveral() { - List first = new ArrayList(), second = new ArrayList(); - List alone = new ArrayList(); - take(alone); - } - } - """) - .addOutputLines( - "Test.java", - """ - import java.util.ArrayList; - import java.util.Collection; - import java.util.List; - import org.jspecify.annotations.NullMarked; - @NullMarked - class Test { - static void take(Collection c) {} - void several() { - List first = new ArrayList(), second = new ArrayList(); - take(first); - take(second); - } - void loop() { - for (List first = new ArrayList(), second = first; ; ) { - take(first); - } - } - void oldStyleCase(int k) { - switch (k) { - case 1: - List first = new ArrayList(), second = new ArrayList(); - take(first); - break; - default: - } - } - void besideSeveral() { - List first = new ArrayList(), second = new ArrayList(); - List alone = new ArrayList(); - take(alone); - } - } - """) - .doTest(); - } - - @Test - public void noEditForADeclarationWithBracketsAfterTheName() throws IOException { - makeHelper() - .addInputLines( - "Test.java", - """ - import java.util.Collection; - import java.util.List; - import org.jspecify.annotations.NullMarked; - @NullMarked - class Test { - static void take(List[] c) {} - static void takeOne(Collection c) {} - static List[] many() { - throw new RuntimeException(); - } - static List one() { - throw new RuntimeException(); - } - void bracketsAfterTheName() { - List a[] = many(); - take(a); - } - void beforeADeclaratorWithBrackets() { - List a = one(), b[] = many(); - takeOne(a); - } - void afterADeclaratorWithBrackets() { - List a[] = many(), b = one(); - takeOne(b); - } - @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) - @interface Tainted {} - void beforeADeclaratorWithAnnotatedBrackets() { - List a = one(), b @Tainted [] = many(); - takeOne(a); - } - } - """) - .expectUnchanged() - .doTest(); - } - - @Test - public void aLocalClassIsWrittenUnderItsSimpleName() throws IOException { - makeHelper() - .addInputLines( - "Test.java", - """ - import org.jspecify.annotations.NullMarked; - import org.jspecify.annotations.Nullable; - @NullMarked - class Test { - Test() { - class Local {} - Local t = new Local(); - Local l = new Local(); - t = l; - } - { - class Local {} - Local t = new Local(); - Local l = new Local(); - t = l; - } - void instanceMethod() { - class Local {} - Local t = new Local(); - Local l = new Local(); - t = l; - } - static void staticMethod() { - class Local {} - Local t = new Local(); - Local l = new Local(); - t = l; - } - } - """) - .addOutputLines( - "Test.java", - """ - import org.jspecify.annotations.NullMarked; - import org.jspecify.annotations.Nullable; - @NullMarked - class Test { - Test() { - class Local {} - Local t = new Local(); - Local l = new Local(); - t = l; - } - { - class Local {} - Local t = new Local(); - Local l = new Local(); - t = l; - } - void instanceMethod() { - class Local {} - Local t = new Local(); - Local l = new Local(); - t = l; - } - static void staticMethod() { - class Local {} - Local t = new Local(); - Local l = new Local(); - t = l; - } - } - """) - .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 index 908271fb2a..1899bdefe9 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/MismatchMessageTestBase.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/MismatchMessageTestBase.java @@ -18,8 +18,8 @@ * 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 possible fix:} line. A failure prints the expected message beside - * every diagnostic the compilation reported. + * not carry, such as a {@code note:} line. A failure prints the expected message beside every + * diagnostic the compilation reported. * *

Every diagnostic a test compares must also hold the invariants {@link #checkNotes} states, * whatever message the test expects. @@ -179,11 +179,9 @@ static List checkNotes(String message) { /** * 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. The {@code Did you mean} - * line Error Prone appends for an attached fix is part of the expected message, so a test that - * expects none states that the diagnostic carries no edit; {@link FixTests} applies the edits. - * What {@link #checkNotes} finds wrong in a diagnostic it is shown goes to {@code violations}, - * and where that is {@code null}, fails the test at once. + * marked line matches it, so {@link #toString} is the expected message. What {@link #checkNotes} + * finds wrong in a diagnostic it is shown goes to {@code violations}, and where that is {@code + * null}, fails the test at once. */ private record MessageIs(String expected, @Nullable Set violations) implements Predicate { @@ -196,13 +194,10 @@ public boolean test(String diagnostic) { if (!diagnostic.startsWith(PREFIX)) { return false; } - int link = diagnostic.indexOf(LINK_LINE); - if (link < 0) { + if (!diagnostic.endsWith(LINK_LINE)) { return false; } - // Error Prone appends "\n Did you mean '...'?" after the link line; the expected message - // carries it as its last line - String edit = diagnostic.substring(link + LINK_LINE.length()); + int link = diagnostic.length() - LINK_LINE.length(); String message = diagnostic.substring(PREFIX.length(), link); List broken = checkNotes(message); if (violations != null) { @@ -210,7 +205,7 @@ public boolean test(String diagnostic) { } else if (!broken.isEmpty()) { throw new AssertionError(String.join("\n", broken)); } - return (message + (edit.isEmpty() ? "" : edit.substring(1) + "\n")).equals(expected); + return message.equals(expected); } @Override 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 c047ac3158..f8d38847b2 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 @@ -24,7 +24,6 @@ public void anUnboundedWildcardNamesTheTypeParameterItsUpperBoundComesFrom() { target: Collection ^^^^^^ note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - possible fix: declare list as List """, """ Collection copy(List list) { @@ -55,7 +54,6 @@ public void theNotePrintsOnlyTheWildcardItMeansAndSimpleTypeArguments() { target: Triple ^^^^^^ note: the unbounded wildcard ? in Triple has the upper bound of type parameter B of Triple, which is @Nullable Object (JLS 5.1.10) - possible fix: declare t as Triple> """, """ static class Triple {} @@ -77,7 +75,6 @@ public void theNoteGivesTheBoundWithTheOtherTypeArgumentsSubstituted() { target: Foo> ^^^^^^^^^^^^ note: the unbounded wildcard ? in Foo has the upper bound of type parameter B of Foo, which is @Nullable List (JLS 5.1.10) - possible fix: declare f as Foo> """, """ static class Foo> {} @@ -203,7 +200,6 @@ public void aWildcardInsideAWildcardBoundNamesItsTypeParameter() { target: List> ^^^^^^ note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - possible fix: declare l as List> """, """ static void take(List> l) {} @@ -224,7 +220,6 @@ public void aWildcardInsideAnArrayInsideAWildcardBoundNamesItsTypeParameter() { target: List []> ^^^^^^ note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - possible fix: declare l as List[]> """, """ static void take(List[]> l) {} @@ -294,7 +289,6 @@ public void aCapturedWildcardNamesTheTypeParameterOnlyWhereItInstantiatesIt() { target: Collection ^^^^^^ note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - possible fix: declare l as List """, "SUBSTITUTED_AFTER_AN_EARLIER_VIEW", """ @@ -485,7 +479,6 @@ public void aHolderNoteIsPrintedOnlyWhereItsBoundHasTheNullnessTheCheckCompared( ^ target: Base> ^^^^^^^^^^^^ - possible fix: declare s as SubL> """, "SUBCLASS_BOUND_INSIDE_A_LIST", """ @@ -494,7 +487,6 @@ public void aHolderNoteIsPrintedOnlyWhereItsBoundHasTheNullnessTheCheckCompared( ^ target: Base> ^^^^^^ - possible fix: declare s as SubW """, "BOUND_HOLDS_A_WILDCARD", """ @@ -557,7 +549,6 @@ public void aHolderNoteIsPrintedOnlyWhereItsBoundHasTheNullnessTheCheckCompared( target: Base ^^^^^^ note: the unbounded wildcard ? in Sub has the upper bound of type parameter T of Sub, which is @Nullable Object (JLS 5.1.10) - possible fix: declare s as Sub """), """ static class Base {} @@ -633,7 +624,6 @@ public void aBoundSubstitutesOnlyTheTypeArgumentsThatAreNotWildcards() { target: Dep> ^^^^^^ note: the unbounded wildcard ? in Dep<..., ?> has the upper bound of type parameter B of Dep, which is List (JLS 5.1.10) - possible fix: declare d as Dep """, "DEPENDS_ON_ITSELF", """ @@ -643,7 +633,6 @@ public void aBoundSubstitutesOnlyTheTypeArgumentsThatAreNotWildcards() { target: Self> ^^^^^^^^^^^^^ note: the unbounded wildcard ? in Self has the upper bound of type parameter T of Self, which is @Nullable Comparable (JLS 5.1.10) - possible fix: declare s as Self> """, "DEPENDS_ON_A_WILDCARD_AND_A_STATED_ARGUMENT", """ @@ -653,7 +642,6 @@ public void aBoundSubstitutesOnlyTheTypeArgumentsThatAreNotWildcards() { target: Tri> ^^^^^^ note: the unbounded wildcard ? in Tri<..., String, ?> has the upper bound of type parameter B of Tri, which is Map (JLS 5.1.10) - possible fix: declare t as Tri """, "DEPENDS_ON_A_STATED_ARGUMENT", """ @@ -690,4 +678,27 @@ void dependsOnAStatedArgument(Dep<@Nullable String, ?> d) { } """); } + + @Test + public void aWildcardInAnEnclosingTypeArgumentGetsANote() { + assertMessage( + """ + incompatible nullability in enclosing type -> type argument for T of Outer -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Outer.Inner + ^ + target: Outer.Inner + ^^^^^^ + note: the unbounded wildcard ? in Outer has the upper bound of type parameter T of Outer, which is @Nullable Object (JLS 5.1.10) + """, + """ + static class Outer { + class Inner {} + } + static void take(Outer.Inner inner) {} + void test(Outer.Inner inner) { + // BUG: Diagnostic matches: MESSAGE + take(inner); + } + """); + } } 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 index 2757893859..30e9c53235 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java @@ -197,7 +197,6 @@ public void aNullableSourceIsComparedBelowItsOwnNullness() { target: Collection ^^^^^^ note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - possible fix: declare l as @Nullable List """, """ static void take(Collection c) {} @@ -258,7 +257,6 @@ public void aCapturedSourceIsComparedThroughItsUpperBound() { ^^^^^^^^^^^^^^^^ target: List ^^^^^^ - possible fix: declare l as List<@Nullable String> """, """ void test(List> wl) { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java deleted file mode 100644 index c3d6ba4a79..0000000000 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceFixTests.java +++ /dev/null @@ -1,659 +0,0 @@ -package com.uber.nullaway.jspecify.mismatchmessage; - -import com.google.errorprone.CompilationTestHelper; -import com.uber.nullaway.generics.JSpecifyJavacConfig; -import java.util.List; -import java.util.Map; -import org.junit.Test; - -/** - * A {@code possible fix:} line that names the variable the source reads offers the source type - * rewritten with an explicit upper bound on each wildcard whose implicit bound the target rejects. - * It appears only where the rewritten type removes every difference and prints without losing a - * type-use annotation. {@link FixTests} checks the edit the fix makes. - */ -public class SourceFixTests extends MismatchMessageTestBase { - - @Test - public void theFixRewritesEveryMismatchingWildcard() { - assertMessage( - """ - incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other differing position: source has @Nullable Object where target requires Object - source: Map - ^ ^ - 1 2 - target: Map - ^^^^^^ ^^^^^^ - 1 2 - \s - 1. path: type argument for K of Map -> upper bound of wildcard - source: @Nullable Object - target: Object - note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) - \s - 2. path: type argument for V of Map -> upper bound of wildcard - source: @Nullable Object - target: Object - note: the unbounded wildcard ? in Map<..., ?> has the upper bound of type parameter V of Map, which is @Nullable Object (JLS 5.1.10) - \s - possible fix: declare m as Map - """, - """ - static void take(Map m) {} - void fixedFormIsAccepted(Map m) { - take(m); - } - void test(Map m) { - // BUG: Diagnostic matches: MESSAGE - take(m); - } - """); - } - - @Test - public void theFixLeavesAWildcardTheTargetAllowsToBeNullable() { - assertMessage( - """ - incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Map - ^ - target: Map - ^^^^^^ - note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) - possible fix: declare m as Map - """, - """ - static void take(Map m) {} - void fixedFormIsAccepted(Map m) { - take(m); - } - void test(Map m) { - // BUG: Diagnostic matches: MESSAGE - take(m); - } - """); - } - - @Test - public void theFixSurvivesAMismatchInTheHarmlessDirection() { - assertMessage( - """ - incompatible nullability in type argument for T of Box -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Box - ^ - target: Box - ^^^^^^ - note: the unbounded wildcard ? in Box has the upper bound of type parameter T of Box, which is @Nullable Object (JLS 5.1.10) - possible fix: declare b as Box - """, - """ - static class Box {} - static void take(Box b) {} - void test(Box b) { - // BUG: Diagnostic matches: MESSAGE - take(b); - } - void fixedFormIsAccepted(Box b) { - take(b); - } - """); - } - - @Test - public void theFixSurvivesASuperBoundedArgumentTheTargetAlsoDeclaresSuper() { - assertMessage( - """ - incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Map - ^ - target: Map - ^^^^^^ - note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) - possible fix: declare m as Map - """, - """ - static void take(Map m) {} - void fixedFormIsAccepted(Map m) { - take(m); - } - void test(Map m) { - // BUG: Diagnostic matches: MESSAGE - take(m); - } - """); - } - - @Test - public void theFixRewritesAWildcardInsideAnArrayElement() { - assertMessage( - """ - incompatible nullability in component type -> type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: List [] - ^ - target: Collection [] - ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - possible fix: declare lists as List[] - """, - """ - static void takeArray(Collection[] c) {} - void fixedFormIsAccepted(List[] lists) { - takeArray(lists); - } - void test(List[] lists) { - // BUG: Diagnostic matches: MESSAGE - takeArray(lists); - } - """); - } - - @Test - public void theFixRewritesAWildcardInsideANestedTypeArgument() { - assertMessage( - """ - incompatible nullability in type argument for E of Collection -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: List> - ^ - target: Collection> - ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - possible fix: declare lists as List> - """, - """ - static void takeNested(Collection> c) {} - void fixedFormIsAccepted(List> lists) { - takeNested(lists); - } - void test(List> lists) { - // BUG: Diagnostic matches: MESSAGE - takeNested(lists); - } - """); - } - - @Test - public void theFixRewritesAWildcardInAnEnclosingTypeArgument() { - assertMessage( - """ - incompatible nullability in enclosing type -> type argument for T of Outer -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Outer.Inner - ^ - target: Outer.Inner - ^^^^^^ - note: the unbounded wildcard ? in Outer has the upper bound of type parameter T of Outer, which is @Nullable Object (JLS 5.1.10) - possible fix: declare inner as Outer.Inner - """, - """ - static class Outer { - class Inner {} - } - static void take(Outer.Inner inner) {} - void fixedFormIsAccepted(Outer.Inner inner) { - take(inner); - } - void test(Outer.Inner inner) { - // BUG: Diagnostic matches: MESSAGE - take(inner); - } - """); - } - - @Test - public void theSourceFixIsStillOfferedWhereTheTargetTypeIsNotEditable() { - assertMessage( - """ - incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: List - ^ - target: Collection - ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - possible fix: declare l as List - """, - """ - static void take(Collection c) {} - void test(List l) { - // BUG: Diagnostic matches: MESSAGE - take(l); - } - """); - } - - @Test - public void noFixWhenAnExplicitBoundMismatchRemains() { - assertMessage( - """ - incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other differing position: source has @Nullable Object where target requires Object - source: Map - ^ ^^^^^^^^^^^^^^^^ - 1 2 - target: Map - ^^^^^^ ^^^^^^ - 1 2 - \s - 1. path: type argument for K of Map -> upper bound of wildcard - source: @Nullable Object - target: Object - note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) - \s - 2. path: type argument for V of Map -> upper bound of wildcard - source: @Nullable Object - target: Object - """, - """ - static void take(Map m) {} - void test(Map m) { - // BUG: Diagnostic matches: MESSAGE - take(m); - } - """); - } - - @Test - public void noFixWhenAConcreteTypeArgumentAlsoMismatches() { - assertMessage( - """ - incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other differing position: source has @Nullable Object where target requires Object - source: Map - ^ ^^^^^^^^^^^^^^^^ - 1 2 - target: Map - ^^^^^^ ^^^^^^ - 1 2 - \s - 1. path: type argument for K of Map -> upper bound of wildcard - source: @Nullable Object - target: Object - note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) - \s - 2. path: type argument for V of Map - source: @Nullable String - target: String - """, - """ - static void take(Map m) {} - void test(Map m) { - // BUG: Diagnostic matches: MESSAGE - take(m); - } - """); - } - - @Test - public void noFixWhenOneMismatchCannotBeRewritten() { - assertMessage( - """ - incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other differing position: source has @Nullable Object where target requires Object - source: Map - ^ ^^^^^^^^^^^^^^ - 1 2 - target: Map - ^^^^^^ ^^^^^^ - 1 2 - \s - 1. path: type argument for K of Map -> upper bound of wildcard - source: @Nullable Object - target: Object - note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) - \s - 2. path: type argument for V of Map -> upper bound of wildcard - source: @Nullable Object - target: Object - note: the wildcard ? super String in Map<..., ? super String> has no upper bound of its own; its upper bound is the bound of type parameter V of Map, which is @Nullable Object (JLS 5.1.10) - """, - """ - static void take(Map m) {} - void test(Map m) { - // BUG: Diagnostic matches: MESSAGE - take(m); - } - """); - } - - @Test - public void noFixWhenBoundsDifferBelowTheTopLevel() { - assertMessage( - """ - incompatible nullability in type argument for E of Holder -> upper bound of wildcard -> type argument for E of List: source has @Nullable Object where target requires Object - source: Holder - ^ - target: Holder> - ^^^^^^ - note: the unbounded wildcard ? in Holder has the upper bound of type parameter E of Holder, which is List<@Nullable Object> (JLS 5.1.10) - """, - """ - static class Holder> {} - static void take(Holder> h) {} - void test(Holder h) { - // BUG: Diagnostic matches: MESSAGE - take(h); - } - """); - } - - @Test - public void noFixWhenTheRewrittenTypeHoldsACapture() { - assertMessage( - """ - incompatible nullability in type argument for K of Map -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Map, capture of ?> - ^ - target: Map, ?> - ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - """, - """ - 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 aPatternVariableGetsNoSourceFix() { - assertMessages( - Map.of( - "NO_FIX", - """ - incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: List - ^ - target: Collection - ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - """, - "TARGET_FIX_ONLY", - """ - incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: List - ^ - target: Collection - ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - possible fix: declare c as Collection - """), - """ - static void take(Collection c) {} - static List make() { - throw new RuntimeException(); - } - void pattern(Object o) { - if (o instanceof List l) { - // BUG: Diagnostic matches: NO_FIX - take(l); - } - } - void reassignedPattern(Object o) { - if (o instanceof List l) { - l = make(); - // BUG: Diagnostic matches: NO_FIX - take(l); - } - } - void patternWithATargetFix(Object o) { - if (o instanceof List l) { - // BUG: Diagnostic matches: TARGET_FIX_ONLY - Collection c = l; - c.hashCode(); - } - } - """); - } - - @Test - public void aLambdaParameterGetsNoSourceFix() { - assertMessages( - Map.of( - "NO_FIX", - """ - incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: List - ^ - target: Collection - ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - """, - "METHOD_PARAMETER", - """ - incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: List - ^ - target: Collection - ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - possible fix: declare l as List - """), - """ - interface Sink { - void accept(T t); - } - static void take(Collection c) {} - // BUG: Diagnostic matches: NO_FIX - Sink> explicitlyTyped = (List l) -> take(l); - // BUG: Diagnostic matches: NO_FIX - Sink> implicitlyTyped = l -> take(l); - Sink> block = - (List l) -> { - // BUG: Diagnostic matches: NO_FIX - take(l); - }; - void methodParameter(List l) { - // BUG: Diagnostic matches: METHOD_PARAMETER - take(l); - } - """); - } - - // The printer drops @Tainted and the custom nullable @CanBeNull from the printed types, so - // TAINTED and CUSTOM_NULLABLE differ from PLAIN only by the missing fix line. - @Test - public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { - CompilationTestHelper helper = - makeTestHelperWithArgs( - JSpecifyJavacConfig.withJSpecifyModeArgs( - List.of( - "-XepOpt:NullAway:OnlyNullMarked=true", - "-XepOpt:NullAway:CustomNullableAnnotations=Test.CanBeNull,p.Nullable"))); - Map.of( - "NULLABLE_WITH_A_VALUE", - """ - incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Map - ^ - target: Map - ^^^^^^ - note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) - """, - "ANNOTATED_WILDCARD", - """ - incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Map - ^ - target: Map - ^^^^^^ - note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) - """, - "NULLABLE_WILDCARD", - """ - incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Map - ^ - target: Map - ^^^^^^ - note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) - """, - "PLAIN", - """ - incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Map - ^ - target: Map - ^^^^^^ - note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) - possible fix: declare plain as Map - """, - "TAINTED", - """ - incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Map - ^ - target: Map - ^^^^^^ - note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) - """, - "TAINTED_ARRAY_ELEMENT", - """ - incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Map - ^ - target: Map - ^^^^^^ - note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) - """, - "CUSTOM_NULLABLE", - """ - incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Map - ^ - target: Map - ^^^^^^ - note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) - """) - .forEach((key, expected) -> helper.expectErrorMessage(key, messageIs(expected))); - helper - .addSourceLines( - "Test.java", - nullMarkedClass( - """ - @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) - @interface Tainted {} - @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) - @interface CanBeNull {} - static void takeCustom(Map m) {} - void customNullable(Map custom) { - // BUG: Diagnostic matches: CUSTOM_NULLABLE - takeCustom(custom); - } - static void take(Map m) {} - static void takeArrays(Map m) {} - void plain(Map plain) { - // BUG: Diagnostic matches: PLAIN - take(plain); - } - void tainted(Map tainted) { - // BUG: Diagnostic matches: TAINTED - take(tainted); - } - void taintedArrayElement(Map m) { - // BUG: Diagnostic matches: TAINTED_ARRAY_ELEMENT - takeArrays(m); - } - static void takeNullableValues(Map m) {} - void nullableWithAValue(Map m) { - // BUG: Diagnostic matches: NULLABLE_WITH_A_VALUE - takeNullableValues(m); - } - void annotatedWildcard(Map<@Tainted ?, String> m) { - // BUG: Diagnostic matches: ANNOTATED_WILDCARD - take(m); - } - // BUG: Diagnostic contains: nullness annotations cannot be written directly on a wildcard - void nullableWildcard(Map<@Nullable ?, String> m) { - // BUG: Diagnostic matches: NULLABLE_WILDCARD - take(m); - } - """)) - .addSourceLines( - "p/Nullable.java", - """ - package p; - @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) - public @interface Nullable { - String value(); - } - """) - .doTest(); - } - - @Test - public void aLocalClassIsPrintedUnderItsSimpleName() { - String expected = - """ - incompatible nullability in type argument for T of Local -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Local - ^ - target: Local - ^^^^^^ - note: the unbounded wildcard ? in Local has the upper bound of type parameter T of Local, which is @Nullable Object (JLS 5.1.10) - possible fix: declare l as Local - Did you mean 'Local l = new Local();'? - """; - assertMessages( - Map.of("INSTANCE_METHOD", expected, "STATIC_METHOD", expected), - """ - void instanceMethod() { - class Local {} - Local t = new Local(); - Local l = new Local(); - // BUG: Diagnostic matches: INSTANCE_METHOD - t = l; - } - static void staticMethod() { - class Local {} - Local t = new Local(); - Local l = new Local(); - // BUG: Diagnostic matches: STATIC_METHOD - t = l; - } - """); - } - - @Test - public void theFixNamesTheFieldItRewrites() { - assertMessage( - """ - incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: List - ^ - target: Collection - ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - possible fix: declare field as List - """, - """ - List field = new ArrayList<>(); - void test(List result) { - // BUG: Diagnostic matches: MESSAGE - result.addAll(field); - } - """); - } - - @Test - public void noFixForAMemberReadThroughAParameterizedReceiver() { - assertMessage( - """ - incompatible nullability in type argument for V of Map -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Map> - ^ - target: Map> - ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - """, - """ - static class Box { - Map> field = new HashMap<>(); - } - static void takeMap(Map> m) {} - void test(Box b) { - // BUG: Diagnostic matches: MESSAGE - takeMap(b.field); - } - """); - } -} 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 index e2cf61aa88..ec8b3a3451 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java @@ -50,8 +50,6 @@ public void listsAtMostFiveMismatchesAndSaysHowManyMoreThereAre() { note: the unbounded wildcard ? in Args<..., ..., ..., ..., ?, ...> has the upper bound of type parameter E of Args, which is @Nullable Object (JLS 5.1.10) \s and 1 more differing position, not listed - \s - possible fix: declare args as Args """, """ static class Args {} @@ -99,8 +97,6 @@ public void listsFiveMismatchesWithoutSayingThereAreMore() { source: @Nullable Object target: Object note: the unbounded wildcard ? in Args<..., ..., ..., ..., ?> has the upper bound of type parameter E of Args, which is @Nullable Object (JLS 5.1.10) - \s - possible fix: declare args as Args """, """ static class Args {} @@ -224,8 +220,6 @@ public void countsSeveralUnlistedMismatchesInThePlural() { note: the unbounded wildcard ? in Args<..., ..., ..., ..., ?, ..., ...> has the upper bound of type parameter E of Args, which is @Nullable Object (JLS 5.1.10) \s and 2 more differing positions, not listed - \s - possible fix: declare args as Args """, """ static class Args {} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java deleted file mode 100644 index eb95ffdfeb..0000000000 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TargetTypeFixTests.java +++ /dev/null @@ -1,470 +0,0 @@ -package com.uber.nullaway.jspecify.mismatchmessage; - -import com.google.errorprone.CompilationTestHelper; -import com.uber.nullaway.generics.JSpecifyJavacConfig; -import java.util.List; -import java.util.Map; -import org.junit.Test; - -/** - * A {@code possible fix:} line that names the variable a declaration declares offers the target - * type with the nullness of the source. It appears where the diagnostic points at the declaration - * that writes the target type, a variable declaration with an initializer, and not at a call, an - * assignment, or a return, whose target type is written somewhere else. It is also withheld where - * printing it would drop a type-use annotation. The fix carries no Error Prone edit, which {@link - * FixTests} checks. - */ -public class TargetTypeFixTests extends MismatchMessageTestBase { - - private static final String MAP_VALUES_MESSAGE = - """ - incompatible nullability in type argument for V of Map: source has @Nullable String where target requires String - source: Map - ^^^^^^^^^^^^^^^^ - target: Map - ^^^^^^ - """; - - @Test - public void theFixIsOfferedOnlyWhereTheDiagnosticPointsAtTheTargetTypeDeclaration() { - assertMessages( - Map.of( - "DECLARATION", - MAP_VALUES_MESSAGE - + " possible fix: declare declared as Map\n", - "CALL", - MAP_VALUES_MESSAGE, - "ASSIGNMENT", - MAP_VALUES_MESSAGE, - "RETURN", - MAP_VALUES_MESSAGE), - """ - static void take(Map m) {} - void fixedTypeIsAccepted(Map m) { - Map fixed = m; - } - void declaration(Map m) { - // BUG: Diagnostic matches: DECLARATION - Map declared = m; - declared.hashCode(); - } - void call(Map m) { - // BUG: Diagnostic matches: CALL - take(m); - } - void assignment(Map m, Map existing) { - // BUG: Diagnostic matches: ASSIGNMENT - existing = m; - existing.hashCode(); - } - Map returned(Map m) { - // BUG: Diagnostic matches: RETURN - return m; - } - """); - } - - @Test - public void - aMismatchFixableOnEitherSideListsTheSourceFixOnlyWhereEveryValueOfTheSourceAcceptsIt() { - assertMessages( - Map.of( - "BOTH", - """ - incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: List - ^ - target: Collection - ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - possible fixes: - if list never holds null: declare list as List - if it may: declare c as Collection - Did you mean 'List list = new ArrayList();'? - """, - "BOTH_FOR_A_CONDITIONAL", - """ - incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: List - ^ - target: Collection - ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - possible fixes: - if list never holds null: declare list as List - if it may: declare c as Collection - Did you mean 'List list = flag ? new ArrayList() : new ArrayList();'? - """, - "BOTH_WITHOUT_EDIT", - """ - incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: List - ^ - target: Collection - ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - possible fixes: - if list never holds null: declare list as List - if it may: declare c as Collection - """, - "TARGET_ONLY", - """ - incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: List - ^ - target: Collection - ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - possible fix: declare c as Collection - """, - "TARGET_ONLY_FOR_A_LAMBDA", - """ - incompatible nullability in type argument for T of Source -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Source - ^ - target: Source - ^^^^^^ - note: the unbounded wildcard ? in Source has the upper bound of type parameter T of Source, which is @Nullable Object (JLS 5.1.10) - possible fix: declare s as Source - """), - """ - interface Source { - T get(); - } - static List make() { - throw new RuntimeException(); - } - void initializerAccepts() { - List list = new ArrayList(); - // BUG: Diagnostic matches: BOTH - Collection c = list; - c.hashCode(); - } - void eachBranchOfAConditionalAccepts(boolean flag) { - List list = flag ? new ArrayList() : new ArrayList(); - // BUG: Diagnostic matches: BOTH_FOR_A_CONDITIONAL - Collection c = list; - c.hashCode(); - } - @SuppressWarnings("rawtypes") - void rawInitializer(List raw) { - List fromRaw = raw; - // BUG: Diagnostic contains: Did you mean 'List fromRaw = raw;'? - Collection c = fromRaw; - c.hashCode(); - } - void loopVariable(List> lists) { - for (List list : lists) { - // BUG: Diagnostic matches: BOTH_WITHOUT_EDIT - Collection c = list; - c.hashCode(); - } - } - void initializerRejects() { - List list = make(); - // BUG: Diagnostic matches: TARGET_ONLY - Collection c = list; - c.hashCode(); - } - void aBranchOfAConditionalRejects(boolean flag) { - List list = flag ? new ArrayList() : make(); - // BUG: Diagnostic matches: TARGET_ONLY - Collection c = list; - c.hashCode(); - } - void loopVariableReassignedToAValueThatRejects(List> lists) { - for (List list : lists) { - list = make(); - // BUG: Diagnostic matches: TARGET_ONLY - Collection c = list; - c.hashCode(); - } - } - void lambdaInitializer() { - Source source = () -> "a"; - // BUG: Diagnostic matches: TARGET_ONLY_FOR_A_LAMBDA - Source s = source; - s.hashCode(); - } - """); - } - - @Test - public void theFixIsTheDeclaredTypeNotAnInstantiatedSupertype() { - assertMessage( - """ - incompatible nullability in type argument for E of List: source has @Nullable String where target requires String - source: Sub<@Nullable String> - ^^^^^^^^^^^^^^^^ - target: List - ^^^^^^ - possible fix: declare l as 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 theFixReplacesTheNodeAtEveryKindOfStep() { - assertMessages( - Map.of( - "WILDCARD_UPPER_BOUND", - """ - incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: List - ^ - target: Collection - ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - possible fixes: - if list never holds null: declare list as List - if it may: declare c as Collection - """, - "ARRAY_ELEMENT", - """ - incompatible nullability in component type -> type argument for E of List: source has @Nullable String where target requires String - source: List<@Nullable String> [] - ^^^^^^^^^^^^^^^^ - target: List [] - ^^^^^^ - possible fix: declare d as List<@Nullable String>[] - """, - "ENCLOSING_TYPE", - """ - incompatible nullability in enclosing type -> type argument for T of Outer: source has @Nullable String where target requires String - source: Outer<@Nullable String>.Inner - ^^^^^^^^^^^^^^^^ - target: Outer.Inner - ^^^^^^ - possible fix: declare d as Outer<@Nullable String>.Inner - """, - "WILDCARD_LOWER_BOUND", - """ - incompatible nullability in type argument for E of List -> lower bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String - source: List> - ^^^^^^^^^^^^^^^^ - target: List> - ^^^^^^ - possible fix: declare l as List> - """), - """ - static class Outer { - class Inner {} - } - static List> lower() { - throw new RuntimeException(); - } - void wildcardLowerBound() { - // BUG: Diagnostic matches: WILDCARD_LOWER_BOUND - List> l = lower(); - l.hashCode(); - } - void wildcardUpperBound(List list) { - // BUG: Diagnostic matches: WILDCARD_UPPER_BOUND - Collection c = list; - c.hashCode(); - } - void arrayElement(List<@Nullable String>[] src) { - // BUG: Diagnostic matches: ARRAY_ELEMENT - List[] d = src; - d.hashCode(); - } - void enclosingType(Outer<@Nullable String>.Inner src) { - // BUG: Diagnostic matches: ENCLOSING_TYPE - Outer.Inner d = src; - d.hashCode(); - } - """); - } - - // The printer drops @Tainted and the custom nullable @CanBeNull from the printed types, so the - // keys - // whose types carry one get no fix line. - @Test - public void theFixIsWithheldWhereItsPrintedFormWouldDropAnAnnotation() { - CompilationTestHelper helper = - makeTestHelperWithArgs( - JSpecifyJavacConfig.withJSpecifyModeArgs( - List.of( - "-XepOpt:NullAway:OnlyNullMarked=true", - "-XepOpt:NullAway:CustomNullableAnnotations=Test.CanBeNull,p.Nullable"))); - Map.of( - "NULLABLE_WITH_A_VALUE", - """ - incompatible nullability in type argument for V of Map: source has @Nullable String where target requires String - source: Map - ^^^^^^^^^^^^^^^^ - target: Map - ^^^^^^ - """, - "TAINTED_REPLACED_NODE", - """ - incompatible nullability in type argument for V of Map: source has @Nullable String where target requires String - source: Map - ^^^^^^^^^^^^^^^^ - target: Map - ^^^^^^ - """, - "TAINTED_ROOT", - """ - incompatible nullability in type argument for V of Map: source has @Nullable String where target requires String - source: Map - ^^^^^^^^^^^^^^^^ - target: Map - ^^^^^^ - """, - "ANNOTATED_WILDCARD", - """ - incompatible nullability in type argument for V of Map: source has @Nullable String where target requires String - source: Map - ^^^^^^^^^^^^^^^^ - target: Map - ^^^^^^ - """) - .forEach((key, expected) -> helper.expectErrorMessage(key, messageIs(expected))); - Map.of( - "PLAIN", - """ - incompatible nullability in type argument for V of Map: source has @Nullable String where target requires String - source: Map - ^^^^^^^^^^^^^^^^ - target: Map - ^^^^^^ - possible fix: declare plain as Map - """, - "TAINTED", - """ - incompatible nullability in type argument for V of Map: source has @Nullable String where target requires String - source: Map - ^^^^^^^^^^^^^^^^ - target: Map - ^^^^^^ - """, - "TAINTED_BOUND", - """ - incompatible nullability in type argument for V of Map: source has @Nullable String where target requires String - source: Map - ^^^^^^^^^^^^^^^^ - target: Map - ^^^^^^ - """, - "TYPE_VARIABLE", - """ - incompatible nullability in type argument for V of Map: source has @Nullable String where target requires String - source: Map - ^^^^^^^^^^^^^^^^ - target: Map - ^^^^^^ - possible fix: declare d as Map - """, - "TAINTED_TYPE_VARIABLE", - """ - incompatible nullability in type argument for V of Map: source has @Nullable String where target requires String - source: Map - ^^^^^^^^^^^^^^^^ - target: Map - ^^^^^^ - """, - "TAINTED_ENCLOSING_TYPE", - """ - incompatible nullability in type argument for U of Inner: source has @Nullable String where target requires String - source: Outer.Inner<@Nullable String> - ^^^^^^^^^^^^^^^^ - target: Outer.Inner - ^^^^^^ - """, - "CUSTOM_NULLABLE", - """ - incompatible nullability in type argument for V of Map: source has String where target requires String - source: Map - ^^^^^^ - target: Map - ^^^^^^ - """) - .forEach((key, expected) -> helper.expectErrorMessage(key, messageIs(expected))); - helper - .addSourceLines( - "Test.java", - nullMarkedClass( - """ - @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) - @interface Tainted {} - @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) - @interface CanBeNull {} - static class Outer { - class Inner {} - } - void plain(Map m) { - // BUG: Diagnostic matches: PLAIN - Map plain = m; - plain.hashCode(); - } - void tainted(Map<@Tainted String, @Nullable String> m) { - // BUG: Diagnostic matches: TAINTED - Map<@Tainted String, String> d = m; - d.hashCode(); - } - void taintedBound(Map m) { - // BUG: Diagnostic matches: TAINTED_BOUND - Map d = m; - d.hashCode(); - } - static void typeVariable(Map m) { - // BUG: Diagnostic matches: TYPE_VARIABLE - Map d = m; - d.hashCode(); - } - static void taintedTypeVariable(Map<@Tainted T, @Nullable String> m) { - // BUG: Diagnostic matches: TAINTED_TYPE_VARIABLE - Map<@Tainted T, String> d = m; - d.hashCode(); - } - void taintedEnclosingType(Outer<@Tainted String>.Inner<@Nullable String> src) { - // BUG: Diagnostic matches: TAINTED_ENCLOSING_TYPE - Outer<@Tainted String>.Inner d = src; - d.hashCode(); - } - void customNullable(Map m) { - // BUG: Diagnostic matches: CUSTOM_NULLABLE - Map d = m; - d.hashCode(); - } - void nullableWithAValue(Map m) { - // BUG: Diagnostic matches: NULLABLE_WITH_A_VALUE - Map d = m; - d.hashCode(); - } - void taintedReplacedNode(Map m) { - // BUG: Diagnostic matches: TAINTED_REPLACED_NODE - Map d = m; - d.hashCode(); - } - void taintedRoot(Map m) { - // BUG: Diagnostic matches: TAINTED_ROOT - @Tainted Map d = m; - d.hashCode(); - } - void annotatedWildcard(Map m) { - // BUG: Diagnostic matches: ANNOTATED_WILDCARD - Map<@Tainted ? extends String, String> d = m; - d.hashCode(); - } - """)) - .addSourceLines( - "p/Nullable.java", - """ - package p; - @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) - public @interface Nullable { - String value(); - } - """) - .doTest(); - } -} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java index 5e8edfb3b5..177adba281 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java @@ -19,7 +19,6 @@ public void aSharedBoundBesideTheMismatchIsWalkedOnce() { ^^^^^^^^^^^^^^^^ target: P> ^^^^^^ - possible fix: declare x as P<@Nullable String, L24> """, """ interface P {} @@ -67,7 +66,6 @@ public void aSharedBoundBesideANestedMismatchIsWalkedOnce() { ^^^^^^^^^^^^^^^^ target: List, String>> ^^^^^^ - possible fix: declare x as List, @Nullable String>> """, """ interface P {} 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 ec7433d5fd..34a415f955 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 @@ -334,7 +334,6 @@ public void aPathAcrossAViewReachesIntoWhateverTheSubclassPassed() { target: Base> ^^^^^^ note: the unbounded wildcard ? in Indirect has the upper bound of type parameter X of Indirect, which is @Nullable Object (JLS 5.1.10) - possible fix: declare i as Indirect """, """ static class Base {} From 25871d2ee9106077495f2c890bdda25497fd1ed0 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Mon, 30 Nov 2026 18:25:29 +0300 Subject: [PATCH 36/43] Give each nested marked node its own caret row and share path prefixes Two mismatches can mark nested nodes of one printed type. This happens where a supertype view puts one type argument at two positions: for `interface Same extends Pair`, passing a `Same<@Nullable List<@Nullable String>>` to a `Pair, ? extends @Nullable List>` marks both the list and its element. The caret parser assumed marks never nest. It stopped at the inner end marker, so the source line read `Same<@Nullable List<1@Nullable String>>`, and the second caret and its number were lost. The parser now keeps open marks on a stack. Each level of nesting gets its own caret row, and its own number row where the message is numbered, outermost first. Output where nothing nests is unchanged. `TypePath.then` copied every step above it, so walking or printing a type nested N deep stored N(N+1)/2 steps, even with no caret requested. A path now shares its parent and stores one step. `steps()` builds the list root-first on demand. Building a message reruns the nullability check over both types, and `reportNullabilityMismatch` skips that for a suppressed error. The test for that shortcut went away with the fix code. A counting hook on the message build brings it back: three mismatches in a class excluded by `ExcludedClassAnnotations` build no message, and one outside it builds one. User-visible: Where a supertype view marks a node inside another marked node, the `source:` line prints the type without stray digits, and each marked node gets its own caret run and number. Assisted-by: Claude Code (claude-opus-5-5) --- .../generics/NullabilityMismatchMessage.java | 111 +++++++++++------- .../com/uber/nullaway/generics/TypePath.java | 69 +++++++++-- .../generics/MismatchMessageWorkTests.java | 94 +++++++++++++++ .../mismatchmessage/ViewedSourceTests.java | 98 ++++++++++++++++ 4 files changed, 319 insertions(+), 53 deletions(-) create mode 100644 nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java 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 d977c24401..fa8ee33382 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -10,9 +10,12 @@ import com.sun.tools.javac.util.ListBuffer; import com.uber.nullaway.Config; import com.uber.nullaway.handlers.Handler; +import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Comparator; import java.util.Iterator; import java.util.List; +import java.util.Objects; import java.util.function.Function; import java.util.function.Predicate; import org.jspecify.annotations.Nullable; @@ -77,7 +80,10 @@ * written type does not hold. Where the source is viewed as a supertype at the root and the node is * not in the written type, that view is printed as {@code source supertype} and carries the carets. * Below the root, as for an element of {@code List}, no view is printed, and such a node gets - * no source caret. Two differences below one printed node share its caret, numbered for each. + * no source caret. Two differences below one printed node share its caret, numbered for each. Where + * a marked node holds another marked node, as where a supertype view puts one type argument of the + * source at two positions, each node gets its own caret run, on one row per level of nesting with + * the outermost row first, and its number in a row below its run. * *

A note explains itself in the entities the message already shows. Where the source wildcard is * marked on a printed type, the type the reader wrote or the {@code source supertype} line, the @@ -347,26 +349,37 @@ private MarkedType markedTypeLines( } i++; } - // one caret row, and one number row where numbered, for each depth of nesting, outermost - // first, so a node marked inside a marked node still gets a run of its own + // each depth of nesting, outermost first, gets a caret row and, where numbered, number rows + // under it, so a node marked inside a marked node still gets a run of its own. A label goes on + // the first number row of its depth that leaves a space before it, so two labels never run + // together, and a depth's number rows all come before the next depth's caret row spans.sort(Comparator.comparingInt(MarkSpan::depth).thenComparingInt(MarkSpan::start)); List rows = new ArrayList<>(); StringBuilder carets = new StringBuilder(); - StringBuilder numbers = new StringBuilder(); + List numberRows = new ArrayList<>(); int depth = -1; for (MarkSpan span : spans) { if (span.depth() != depth) { + addDepthRows(rows, carets, numberRows, numbered); depth = span.depth(); carets = new StringBuilder(); - numbers = new StringBuilder(); - rows.add(carets); - if (numbered) { - rows.add(numbers); - } + numberRows = new ArrayList<>(); } padTo(carets, span.start()).append("^".repeat(Math.max(span.end() - span.start(), 1))); + StringBuilder numbers = null; + for (StringBuilder row : numberRows) { + if (row.length() < span.start()) { + numbers = row; + break; + } + } + if (numbers == null) { + numbers = new StringBuilder(); + numberRows.add(numbers); + } padTo(numbers, span.start()).append(String.join(",", span.indices())); } + addDepthRows(rows, carets, numberRows, numbered); String prefix = " " + padTo(new StringBuilder(label + ":"), labelWidth + 1) + " "; String line = "\n" + prefix + stripped; for (StringBuilder row : rows) { @@ -375,6 +388,24 @@ private MarkedType markedTypeLines( return new MarkedType(line, marks); } + /** + * Adds the rows of one depth of nesting to {@code rows}: its caret row and, where {@code + * numbered}, its number rows. Adds nothing where the depth has no caret. + */ + private static void addDepthRows( + List rows, + StringBuilder carets, + List numberRows, + boolean numbered) { + if (carets.length() == 0) { + return; + } + rows.add(carets); + if (numbered) { + rows.addAll(numberRows); + } + } + /** A mark whose start the parse has passed and whose end it has not reached yet. */ private record OpenMark(int start, List indices) {} 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 e0691165c5..aa7c46849a 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java @@ -3,7 +3,6 @@ import com.google.common.collect.ImmutableList; import com.sun.tools.javac.code.Type; import java.util.Objects; -import java.util.function.IntConsumer; import java.util.stream.Collectors; import org.jspecify.annotations.Nullable; @@ -90,13 +89,6 @@ String describe() { private static final TypePath ROOT = new TypePath(null, null, 0); - /** - * Called with the number of {@link Step} references each {@link #then} stores in the path it - * returns, or {@code null} where nobody listens. A test sets it to show that descending one level - * stores one step, not a copy of every step above it. - */ - static @Nullable IntConsumer stepsStoredListener; - /** The path this one extends by {@link #last}, or {@code null} for the root. */ private final @Nullable TypePath parent; @@ -122,10 +114,6 @@ static TypePath root() { * it, so descending one level of a type costs the same at any depth. */ TypePath then(Step step) { - IntConsumer listener = stepsStoredListener; - if (listener != null) { - listener.accept(1); - } return new TypePath(this, step, depth + 1); } diff --git a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java index ba2b5736f6..d8f336d04d 100644 --- a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java @@ -4,6 +4,9 @@ import com.google.errorprone.CompilationTestHelper; import com.uber.nullaway.NullAway; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; @@ -11,8 +14,8 @@ /** * Building a generic nullability mismatch message reruns the check over both types, so it is - * skipped for a mismatch whose error is suppressed, and the paths it follows cost one stored step - * per level of a type, however deep. + * skipped for a mismatch whose error is suppressed, and each path it follows links to the path it + * extends rather than copying it. */ public class MismatchMessageWorkTests { @@ -29,9 +32,12 @@ public void aMismatchInAnExcludedNestedClassBuildsNoMessage() { "-XepOpt:NullAway:ExcludedClassAnnotations=Test.Excluded"))) .addSourceLines( "Test.java", - """ +""" import java.util.Collection; - import java.util.List; + import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.List; import org.jspecify.annotations.NullMarked; @NullMarked class Test { @@ -70,25 +76,28 @@ void reported() { .isEqualTo(1); } + // a path that copied the steps above it would cost time and memory quadratic in the depth of the + // type it walks; these are the fields a path that shares its parent needs, and no others @Test - public void eachDescentStoresOneStepHoweverDeepThePath() { - int depth = 50; - AtomicInteger stored = new AtomicInteger(); - TypePath.stepsStoredListener = stored::addAndGet; + public void eachDescentLinksToThePathItExtends() { TypePath path = TypePath.root(); - try { - for (int i = 0; i < depth; i++) { - path = path.then(TypePath.Step.typeArgument(i, null)); - } - } finally { - TypePath.stepsStoredListener = null; + for (int i = 0; i < 50; i++) { + TypePath next = path.then(TypePath.Step.typeArgument(i, null)); + assertWithMessage("parent of the path at depth %s", i + 1) + .that(next.parent()) + .isSameInstanceAs(path); + path = next; } - assertWithMessage("steps stored to reach depth %s, one per descent", depth) - .that(stored.get()) - .isEqualTo(depth); assertWithMessage("type argument indices of the steps, root first") .that(path.steps().stream().map(TypePath.Step::index).toList()) - .containsExactlyElementsIn(IntStream.range(0, depth).boxed().toList()) + .containsExactlyElementsIn(IntStream.range(0, 50).boxed().toList()) .inOrder(); + assertWithMessage("instance fields of TypePath") + .that( + Arrays.stream(TypePath.class.getDeclaredFields()) + .filter(field -> !Modifier.isStatic(field.getModifiers())) + .map(Field::getName) + .toList()) + .containsExactly("parent", "last", "depth"); } } 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 index fb405ef5b0..089f10bd15 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java @@ -368,4 +368,132 @@ void nullableWildcard(Map<@Nullable ?, String> m) { """) .doTest(); } + + @Test + public void aNumberThatWouldRunIntoTheOneBeforeItGoesOnAnotherRow() { + assertMessages( + Map.of( + "COLLIDING", + """ + incompatible nullability in type argument for A of ThreeAndTwo -> upper bound of wildcard -> type argument for A of Three and 4 other differing positions: source has @Nullable String where target requires String + source: ThreeAndTwo + ^ ^ + 1,2,3 + 4,5 + target: ThreeAndTwo, ? extends Two> + ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ + 1 2 3 4 5 + \s + 1. path: type argument for A of ThreeAndTwo -> upper bound of wildcard -> type argument for A of Three + source: @Nullable String + target: String + note: the unbounded wildcard ? in ThreeAndTwo has the upper bound of type parameter A of ThreeAndTwo, which is Three<@Nullable String, @Nullable String, @Nullable String> (JLS 5.1.10) + \s + 2. path: type argument for A of ThreeAndTwo -> upper bound of wildcard -> type argument for B of Three + source: @Nullable String + target: String + note: the unbounded wildcard ? in ThreeAndTwo has the upper bound of type parameter A of ThreeAndTwo, which is Three<@Nullable String, @Nullable String, @Nullable String> (JLS 5.1.10) + \s + 3. path: type argument for A of ThreeAndTwo -> upper bound of wildcard -> type argument for C of Three + source: @Nullable String + target: String + note: the unbounded wildcard ? in ThreeAndTwo has the upper bound of type parameter A of ThreeAndTwo, which is Three<@Nullable String, @Nullable String, @Nullable String> (JLS 5.1.10) + \s + 4. path: type argument for B of ThreeAndTwo -> upper bound of wildcard -> type argument for A of Two + source: @Nullable String + target: String + note: the unbounded wildcard ? in ThreeAndTwo<..., ?> has the upper bound of type parameter B of ThreeAndTwo, which is Two<@Nullable String, @Nullable String> (JLS 5.1.10) + \s + 5. path: type argument for B of ThreeAndTwo -> upper bound of wildcard -> type argument for B of Two + source: @Nullable String + target: String + note: the unbounded wildcard ? in ThreeAndTwo<..., ?> has the upper bound of type parameter B of ThreeAndTwo, which is Two<@Nullable String, @Nullable String> (JLS 5.1.10) + """, + "COLLIDING_INSIDE_A_MARKED_NODE", + """ + incompatible nullability in type argument for A of Pair -> upper bound of wildcard and 4 other differing positions: source has @Nullable TwoAndTwo where target requires TwoAndTwo + source: Same<@Nullable TwoAndTwo> + ^^^^^^^^^^^^^^^^^^^^^^^^^ + 1 + ^ ^ + 2,3 + 4,5 + target: Pair, ? extends @Nullable TwoAndTwo, ? extends Two>> + ^^^^^^^^^^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ + 1 2 3 4 5 + \s + 1. path: type argument for A of Pair -> upper bound of wildcard + source: @Nullable TwoAndTwo + target: TwoAndTwo + \s + 2. path: type argument for B of Pair -> upper bound of wildcard -> type argument for A of TwoAndTwo -> upper bound of wildcard -> type argument for A of Two + source: @Nullable String + target: String + note: the unbounded wildcard ? in TwoAndTwo has the upper bound of type parameter A of TwoAndTwo, which is Two<@Nullable String, @Nullable String> (JLS 5.1.10) + \s + 3. path: type argument for B of Pair -> upper bound of wildcard -> type argument for A of TwoAndTwo -> upper bound of wildcard -> type argument for B of Two + source: @Nullable String + target: String + note: the unbounded wildcard ? in TwoAndTwo has the upper bound of type parameter A of TwoAndTwo, which is Two<@Nullable String, @Nullable String> (JLS 5.1.10) + \s + 4. path: type argument for B of Pair -> upper bound of wildcard -> type argument for B of TwoAndTwo -> upper bound of wildcard -> type argument for A of Two + source: @Nullable String + target: String + note: the unbounded wildcard ? in TwoAndTwo<..., ?> has the upper bound of type parameter B of TwoAndTwo, which is Two<@Nullable String, @Nullable String> (JLS 5.1.10) + \s + 5. path: type argument for B of Pair -> upper bound of wildcard -> type argument for B of TwoAndTwo -> upper bound of wildcard -> type argument for B of Two + source: @Nullable String + target: String + note: the unbounded wildcard ? in TwoAndTwo<..., ?> has the upper bound of type parameter B of TwoAndTwo, which is Two<@Nullable String, @Nullable String> (JLS 5.1.10) + """, + "FITTING", + """ + incompatible nullability in type argument for A of OneAndTwo -> upper bound of wildcard -> type argument for A of Two and 2 other differing positions: source has @Nullable String where target requires String + source: OneAndTwo + ^ ^ + 1 2,3 + target: OneAndTwo, ? extends Two> + ^^^^^^ ^^^^^^ ^^^^^^ + 1 2 3 + \s + 1. path: type argument for A of OneAndTwo -> upper bound of wildcard -> type argument for A of Two + source: @Nullable String + target: String + note: the unbounded wildcard ? in OneAndTwo has the upper bound of type parameter A of OneAndTwo, which is Two<@Nullable String, String> (JLS 5.1.10) + \s + 2. path: type argument for B of OneAndTwo -> upper bound of wildcard -> type argument for A of Two + source: @Nullable String + target: String + note: the unbounded wildcard ? in OneAndTwo<..., ?> has the upper bound of type parameter B of OneAndTwo, which is Two<@Nullable String, @Nullable String> (JLS 5.1.10) + \s + 3. path: type argument for B of OneAndTwo -> upper bound of wildcard -> type argument for B of Two + source: @Nullable String + target: String + note: the unbounded wildcard ? in OneAndTwo<..., ?> has the upper bound of type parameter B of OneAndTwo, which is Two<@Nullable String, @Nullable String> (JLS 5.1.10) + """), + """ + static class Two {} + static class Three {} + static class ThreeAndTwo, B extends Two<@Nullable String, @Nullable String>> {} + static class TwoAndTwo, B extends Two<@Nullable String, @Nullable String>> {} + static class OneAndTwo, B extends Two<@Nullable String, @Nullable String>> {} + interface Pair {} + interface Same extends Pair {} + static void takeThreeAndTwo(ThreeAndTwo, ? extends Two> t) {} + static void takePair(Pair, ? extends @Nullable TwoAndTwo, ? extends Two>> p) {} + static void takeOneAndTwo(OneAndTwo, ? extends Two> o) {} + void colliding(ThreeAndTwo t) { + // BUG: Diagnostic matches: COLLIDING + takeThreeAndTwo(t); + } + void collidingInsideAMarkedNode(Same<@Nullable TwoAndTwo> s) { + // BUG: Diagnostic matches: COLLIDING_INSIDE_A_MARKED_NODE + takePair(s); + } + void fitting(OneAndTwo o) { + // BUG: Diagnostic matches: FITTING + takeOneAndTwo(o); + } + """); + } } From af204ca0a0ec7b43c9eadd2594e02f20998f0143 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Mon, 30 Nov 2026 18:42:42 +0300 Subject: [PATCH 38/43] Restore a test source and test number rows above a deeper caret row The previous commit put four `import` lines into the Java source that `aMismatchInAnExcludedNestedClassBuildsNoMessage` compiles. They belonged in the test class's import list. The formatter then moved the text block's opening quotes to column 0. The block is restored as it was. A new `CaretTests` case has a number row that would collide at a level with a deeper caret row below it. Its extra number row prints before that caret row, and a version that appends extra number rows after every caret row fails the case. Assisted-by: Claude Code (claude-opus-5-5) --- .../generics/MismatchMessageWorkTests.java | 7 +-- .../jspecify/mismatchmessage/CaretTests.java | 43 +++++++++++++++++++ 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java index d8f336d04d..ab23a64c58 100644 --- a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java @@ -32,12 +32,9 @@ public void aMismatchInAnExcludedNestedClassBuildsNoMessage() { "-XepOpt:NullAway:ExcludedClassAnnotations=Test.Excluded"))) .addSourceLines( "Test.java", -""" + """ import java.util.Collection; - import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.Arrays; -import java.util.List; + import java.util.List; import org.jspecify.annotations.NullMarked; @NullMarked class Test { 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 index 089f10bd15..4d3e2fecfd 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java @@ -446,6 +446,42 @@ public void aNumberThatWouldRunIntoTheOneBeforeItGoesOnAnotherRow() { target: String note: the unbounded wildcard ? in TwoAndTwo<..., ?> has the upper bound of type parameter B of TwoAndTwo, which is Two<@Nullable String, @Nullable String> (JLS 5.1.10) """, + "COLLIDING_ABOVE_A_DEEPER_CARET", + """ + incompatible nullability in type argument for A of Triple -> upper bound of wildcard -> type argument for A of Three and 4 other differing positions: source has @Nullable String where target requires String + source: ThreeThenSame> + ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 1,2,3 + 4 + ^^^^^^^^^^^^^^^^ + 5 + target: Triple, ? extends List<@Nullable String>, ? extends @Nullable List> + ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^ + 1 2 3 4 5 + \s + 1. path: type argument for A of Triple -> upper bound of wildcard -> type argument for A of Three + source: @Nullable String + target: String + note: the unbounded wildcard ? in ThreeThenSame has the upper bound of type parameter X of ThreeThenSame, which is Three<@Nullable String, @Nullable String, @Nullable String> (JLS 5.1.10) + \s + 2. path: type argument for A of Triple -> upper bound of wildcard -> type argument for B of Three + source: @Nullable String + target: String + note: the unbounded wildcard ? in ThreeThenSame has the upper bound of type parameter X of ThreeThenSame, which is Three<@Nullable String, @Nullable String, @Nullable String> (JLS 5.1.10) + \s + 3. path: type argument for A of Triple -> upper bound of wildcard -> type argument for C of Three + source: @Nullable String + target: String + note: the unbounded wildcard ? in ThreeThenSame has the upper bound of type parameter X of ThreeThenSame, which is Three<@Nullable String, @Nullable String, @Nullable String> (JLS 5.1.10) + \s + 4. path: type argument for B of Triple -> upper bound of wildcard + source: @Nullable List<@Nullable String> + target: List<@Nullable String> + \s + 5. path: type argument for C of Triple -> upper bound of wildcard -> type argument for E of List + source: @Nullable String + target: String + """, "FITTING", """ incompatible nullability in type argument for A of OneAndTwo -> upper bound of wildcard -> type argument for A of Two and 2 other differing positions: source has @Nullable String where target requires String @@ -490,6 +526,13 @@ void collidingInsideAMarkedNode(Same<@Nullable TwoAndTwo> s) { // BUG: Diagnostic matches: COLLIDING_INSIDE_A_MARKED_NODE takePair(s); } + interface Triple, B extends @Nullable Object, C extends @Nullable Object> {} + interface ThreeThenSame, T extends @Nullable Object> extends Triple {} + static void takeTriple(Triple, ? extends List<@Nullable String>, ? extends @Nullable List> t) {} + void collidingAboveADeeperCaret(ThreeThenSame> t) { + // BUG: Diagnostic matches: COLLIDING_ABOVE_A_DEEPER_CARET + takeTriple(t); + } void fitting(OneAndTwo o) { // BUG: Diagnostic matches: FITTING takeOneAndTwo(o); From ed7b2faac2aefe37680ada9cc781c3b410ff081e Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Mon, 30 Nov 2026 23:23:42 +0300 Subject: [PATCH 39/43] Descend one type-path step in one place, and close round-4 test gaps Building the message for a mismatch whose compared bound is an inner class of a generic outer crashed NullAway where the holder's type parameter was bounded by a top-level subclass of it: java.lang.NullPointerException: Cannot invoke "Object.equals(Object)" because "node.tsym" is null at NullabilityMismatchMessage.typeArgumentAt `hasNullnessAt` stepped into the enclosing type of the top-level class, got javac's `noType`, and the next type-argument step dereferenced its null `tsym`. A second copy of the same descent, `nodeAt`, did not step through a captured wildcard, so a `?` marked inside a capture's printed bound got the bare `in the source` note instead of naming its class and type parameter. Four walkers (`nodeAt`, `hasNullnessAt`, `childByPosition`, `followDeclared`) each worked out the child a `TypePath.Step` reaches, and the copies had drifted. `TypePath.childAt` now owns that descent: an enclosing type only where it is a class type, and a wildcard bound, of a wildcard or of the wildcard a capture stands for, only where the wildcard states a bound of the step's kind. The walkers keep only their own cases: the hidden track below `?`, the bound of a type variable, the supertype view, and the class check. Also: tests that kill the round-4 survivors in `followDeclared`, `viewedAs`, `printsTypeVariable`, `printedCapturedBound`, `enterLowerBounds`, and the provisional wildcard-comparison entry (a depth-24 input whose sides differ at every level, which times out without that entry); comment fixes; the private comparison record renamed `ComparisonStep`; the marking printer checks its ten-path limit. User-visible: A mismatch whose holder's type parameter is bounded by a top-level subclass of an inner class is reported instead of crashing NullAway. A `?` inside the printed bound of a captured wildcard gets the note that names its class and type parameter, as `note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10)`. The clause for a non-wildcard type argument reads `a non-wildcard type argument must have the same nullability in source and target`. Assisted-by: Claude Code (claude-opus-5-5) --- .../jdkannotations/JDKIntegrationTest.java | 4 +- .../CheckIdenticalNullabilityVisitor.java | 9 +- .../GenericTypePrettyPrintingVisitor.java | 21 ++- .../generics/NullabilityMismatchMessage.java | 49 +++---- .../generics/NullabilityMismatches.java | 131 +++++++---------- .../com/uber/nullaway/generics/TypePath.java | 38 ++++- .../jspecify/BytecodeGenericsTests.java | 4 +- .../jspecify/GenericInheritanceTests.java | 2 +- ...enericMethodLambdaOrMethodRefArgTests.java | 4 +- .../nullaway/jspecify/GenericMethodTests.java | 42 +++--- .../uber/nullaway/jspecify/GenericsTests.java | 46 +++--- .../IntersectionRestorationTests.java | 4 +- .../nullaway/jspecify/JSpecifyArrayTests.java | 2 +- .../uber/nullaway/jspecify/WildcardTests.java | 4 +- .../jspecify/mismatchmessage/CaretTests.java | 39 +++++ .../LowerBoundAndRawSourceTests.java | 28 +++- .../jspecify/mismatchmessage/NoteTests.java | 133 ++++++++++++++++-- .../jspecify/mismatchmessage/PathTests.java | 2 +- .../SummaryAndNumberingTests.java | 6 +- .../mismatchmessage/TraversalCostTests.java | 72 ++++++++++ .../mismatchmessage/ViewedSourceTests.java | 58 +++++++- .../nullaway/CustomLibraryModelsTests.java | 4 +- 22 files changed, 504 insertions(+), 198 deletions(-) diff --git a/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java b/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java index fb3ea719ef..f280fe17c0 100644 --- a/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java +++ b/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java @@ -718,11 +718,11 @@ void testCall() { @Nullable List[] nonNullTypeArgMixed = (@Nullable List[]) new List[3]; // === test calls ParameterAnnotation.nestedAnnotations(nullableTypeArg, nullableArray, nullableMixed); - // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String ParameterAnnotation.nestedAnnotations(nonNullTypeArg, nullableArray, nullableMixed); ParameterAnnotation.nestedAnnotations(nullableTypeArg, nonNullArray, nullableMixed); ParameterAnnotation.nestedAnnotations(nullableTypeArg, nullableArray, nonNullArrayMixed); - // BUG: Diagnostic contains: incompatible nullability in component type -> type argument for E of List: a non-wildcard type argument must have the same nullness in source and target; source has Integer where target requires @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in component type -> type argument for E of List: a non-wildcard type argument must have the same nullability in source and target; source has Integer where target requires @Nullable Integer ParameterAnnotation.nestedAnnotations(nullableTypeArg, nullableArray, nonNullTypeArgMixed); } } 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 45549ee288..8750fa1e28 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitor.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitor.java @@ -43,9 +43,10 @@ public class CheckIdenticalNullabilityVisitor extends Types.DefaultTypeVisitor successfulWildcardComparisons; /** - * Checks in progress or passed during the current outermost wildcard comparison. Every nested - * check must pass for the outermost check to pass, so a repeat can return true while the first - * check finishes. Save these results only if the outermost check succeeds; otherwise discard + * Checks in progress or finished during the current outermost wildcard comparison. Every nested + * check must pass for the outermost check to pass, so a repeat can return true: a check still in + * progress decides the outermost result when it finishes, and a finished one that failed has + * already failed it. Save these results only if the outermost check succeeds; otherwise discard * them. */ private @Nullable Set provisionalWildcardComparisons; @@ -481,7 +482,7 @@ private boolean wildcardContains( Set activeRhsArguments = active.get(lhsWildcard); if ((activeRhsArguments != null && activeRhsArguments.contains(rhsTypeArgument)) || !provisional.add(key)) { - // This check is in progress or has already passed. Any later failure still fails the outer + // This check is in progress or has already been made. A failure of either fails the outer // check. return true; } 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 c23e7ee654..c76711ccb3 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java @@ -2,6 +2,7 @@ import static java.util.stream.Collectors.joining; +import com.google.common.base.Preconditions; import com.google.errorprone.VisitorState; import com.google.errorprone.util.ASTHelpers; import com.sun.tools.javac.code.Attribute; @@ -12,8 +13,9 @@ import org.jspecify.annotations.Nullable; /** - * A visitor that pretty prints a generic type including its type-use nullability annotations, for - * use in error messages. + * A visitor that pretty prints a generic type for use in error messages, writing {@code @Nullable} + * for a type-use annotation whose simple name is {@code Nullable} and dropping every other type-use + * annotation. * *

Nodes named by {@link TypePath} may be marked, in which case each printed form is bracketed by * {@link #MARK_START}, the index of every path that reaches it, {@link #MARK_TEXT}, and {@link @@ -43,12 +45,14 @@ final class GenericTypePrettyPrintingVisitor private final VisitorState state; + /** How many paths a printer may mark: an index is printed as one digit. */ + static final int MAX_MARKED_PATHS = 10; + /** * The positions whose printed form is bracketed, in the order the caller numbers them. At most - * ten, since an index is printed as one digit. Two entries may reach one node, which is then - * bracketed once with both indices. 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. + * {@link #MAX_MARKED_PATHS}. Two entries may reach one node, which is then bracketed once with + * both indices. 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; @@ -60,6 +64,11 @@ final class GenericTypePrettyPrintingVisitor } GenericTypePrettyPrintingVisitor(VisitorState state, List<@Nullable TypePath> markedPaths) { + Preconditions.checkArgument( + markedPaths.size() <= MAX_MARKED_PATHS, + "%s marked paths; a mark index is printed as one digit, so at most %s are supported", + markedPaths.size(), + MAX_MARKED_PATHS); this.state = state; this.markedPaths = markedPaths; } 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 078e98457b..72a881e29f 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -63,7 +63,7 @@ * 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 non-wildcard type - * argument must have the same nullness in source and target. Where the target bounds a {@code ? + * argument must have the same nullability in source and target. Where the target bounds a {@code ? * super} wildcard, the target side reads {@code a supertype of} that bound. * *

The caret

@@ -119,7 +119,11 @@ final class NullabilityMismatchMessage { this.state = state; } - /** How many mismatches a message lists before it says only how many more there are. */ + /** + * How many mismatches a message lists before it says only how many more there are. Each listed + * mismatch is a marked path, so it is at most {@link + * GenericTypePrettyPrintingVisitor#MAX_MARKED_PATHS}. + */ private static final int MAX_LISTED_MISMATCHES = 5; /** @@ -243,7 +247,7 @@ private String summaryLine(List mismatches) { first.path().describe(), others, others == 1 ? "" : "s"); String exactly = mustMatchExactly(first) - ? "a non-wildcard type argument must have the same nullness in source and target; " + ? "a non-wildcard type argument must have the same nullability in source and target; " : ""; return String.format( "incompatible nullability in %s: %ssource has %s where target requires %s", @@ -256,8 +260,8 @@ private String summaryLine(List mismatches) { /** * Whether {@code mismatch} is a non-null type argument where the target has a {@code @Nullable} * one, which reads as a false subtype claim, since every {@code String} is a {@code @Nullable - * String}; what fails there is that a non-wildcard type argument must have the same nullness in - * source and target. + * String}; what fails there is that a non-wildcard type argument must have the same nullability + * in source and target. */ private boolean mustMatchExactly(NullabilityMismatches.Mismatch mismatch) { return mismatch.relation() == NullabilityMismatches.Relation.SAME @@ -466,7 +470,7 @@ private String mismatchDetail( detail.append(targetRequirement(mismatch)); if (mustMatchExactly(mismatch)) { detail.append( - " (a non-wildcard type argument must have the same nullness in source and target)"); + " (a non-wildcard type argument must have the same nullability in source and target)"); } } String note = boundOriginNote(mismatch, sourceType, printedView); @@ -479,8 +483,9 @@ private String mismatchDetail( /** * Says what upper bound the source wildcard has and, where the message prints the type parameter * it comes from, names that parameter; returns {@code null} where the printed node is not a - * wildcard, its bound is written out, or the bound the note would state disagrees with the - * nullness the check found. + * wildcard, its bound is written out, the bound the note would state disagrees with the nullness + * the check found, or the bound cannot be printed without a captured type or a type parameter of + * a class the note does not name. * *

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 what it is reads the two bounds as a @@ -792,13 +797,8 @@ private boolean hasNullnessAt(Type bound, TypePath steps, Type sourceNode) { : GenericsUtils.asWildcard(node) != null ? GenericsUtils.effectiveWildcardUpperBound(node, state, config, handler) : null; - case WILDCARD_LOWER_BOUND -> { - Type.WildcardType wildcard = GenericsUtils.asWildcard(node); - yield wildcard != null && wildcard.kind == BoundKind.SUPER ? wildcard.type : null; - } - case ARRAY_ELEMENT -> node instanceof Type.ArrayType array ? array.elemtype : null; - case ENCLOSING_TYPE -> - node instanceof Type.ClassType classType ? classType.getEnclosingType() : null; + case WILDCARD_LOWER_BOUND, ARRAY_ELEMENT, ENCLOSING_TYPE -> + TypePath.childAt(node, step.kind(), step.index()); }; if (node == null) { return false; @@ -819,10 +819,7 @@ private boolean hasNullnessAt(Type bound, TypePath steps, Type sourceNode) { && !node.tsym.equals(stepClass)) { viewed = TypeSubstitutionUtils.asSuper(state.getTypes(), node, stepClass, config); } - return viewed instanceof Type.ClassType classType - && step.index() < classType.getTypeArguments().size() - ? classType.getTypeArguments().get(step.index()) - : null; + return viewed == null ? null : TypePath.childAt(viewed, step.kind(), step.index()); } /** @@ -832,19 +829,7 @@ private boolean hasNullnessAt(Type bound, TypePath steps, Type sourceNode) { private static @Nullable Type nodeAt(Type root, List steps) { Type node = root; for (TypePath.Step step : steps) { - node = - switch (step.kind()) { - case TYPE_ARGUMENT -> - node instanceof Type.ClassType classType - && step.index() < classType.getTypeArguments().size() - ? classType.getTypeArguments().get(step.index()) - : null; // diff-coverage: ignore -- the path was recorded on this type - case WILDCARD_UPPER_BOUND, WILDCARD_LOWER_BOUND -> - node instanceof Type.WildcardType wildcard ? wildcard.type : null; - case ARRAY_ELEMENT -> node instanceof Type.ArrayType array ? array.elemtype : null; - case ENCLOSING_TYPE -> - node instanceof Type.ClassType classType ? classType.getEnclosingType() : null; - }; + node = TypePath.childAt(node, step.kind(), step.index()); if (node == null) { return null; // diff-coverage: ignore -- the path was recorded on this type } 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 8dba430b2a..05f103438d 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java @@ -271,8 +271,9 @@ private Track viewedAs(Track track, Type rhs, Type rhsView) { /** Steps into type argument {@code index} of {@code lhs} and of {@code rhsView}. */ Frame enterTypeArgument(int index, Type.ClassType lhs, Type.ClassType rhsView) { return enter( - new Step(TypePath.Step.Kind.TYPE_ARGUMENT, index, lhs, lhs.getTypeArguments().get(index)), - new Step( + new ComparisonStep( + TypePath.Step.Kind.TYPE_ARGUMENT, index, lhs, lhs.getTypeArguments().get(index)), + new ComparisonStep( TypePath.Step.Kind.TYPE_ARGUMENT, index, rhsView, @@ -282,15 +283,16 @@ Frame enterTypeArgument(int index, Type.ClassType lhs, Type.ClassType rhsView) { /** Steps into the enclosing type of {@code lhs} and of {@code rhsView}. */ Frame enterEnclosingType(Type.ClassType lhs, Type.ClassType rhsView) { return enter( - new Step(TypePath.Step.Kind.ENCLOSING_TYPE, -1, lhs, lhs.getEnclosingType()), - new Step(TypePath.Step.Kind.ENCLOSING_TYPE, -1, rhsView, rhsView.getEnclosingType())); + new ComparisonStep(TypePath.Step.Kind.ENCLOSING_TYPE, -1, lhs, lhs.getEnclosingType()), + new ComparisonStep( + TypePath.Step.Kind.ENCLOSING_TYPE, -1, rhsView, rhsView.getEnclosingType())); } /** Steps into the component types of two arrays. */ Frame enterArrayElement(Type.ArrayType lhs, Type.ArrayType rhs) { return enter( - new Step(TypePath.Step.Kind.ARRAY_ELEMENT, -1, lhs, lhs.elemtype), - new Step(TypePath.Step.Kind.ARRAY_ELEMENT, -1, rhs, rhs.elemtype)); + new ComparisonStep(TypePath.Step.Kind.ARRAY_ELEMENT, -1, lhs, lhs.elemtype), + new ComparisonStep(TypePath.Step.Kind.ARRAY_ELEMENT, -1, rhs, rhs.elemtype)); } /** @@ -302,10 +304,12 @@ Frame enterUpperBounds( return enter( lhsWildcard == null ? null - : new Step(TypePath.Step.Kind.WILDCARD_UPPER_BOUND, -1, lhsWildcard, lhsBound), + : new ComparisonStep( + TypePath.Step.Kind.WILDCARD_UPPER_BOUND, -1, lhsWildcard, lhsBound), rhsWildcard == null ? null - : new Step(TypePath.Step.Kind.WILDCARD_UPPER_BOUND, -1, rhsWildcard, rhsBound)); + : new ComparisonStep( + TypePath.Step.Kind.WILDCARD_UPPER_BOUND, -1, rhsWildcard, rhsBound)); } /** @@ -317,10 +321,11 @@ Frame enterLowerBounds( Type lhsWildcard, Type lhsBound, @Nullable Type rhsWildcard, Type rhsBound) { Frame saved = enter( - new Step(TypePath.Step.Kind.WILDCARD_LOWER_BOUND, -1, lhsWildcard, lhsBound), + new ComparisonStep(TypePath.Step.Kind.WILDCARD_LOWER_BOUND, -1, lhsWildcard, lhsBound), rhsWildcard == null ? null - : new Step(TypePath.Step.Kind.WILDCARD_LOWER_BOUND, -1, rhsWildcard, rhsBound)); + : new ComparisonStep( + TypePath.Step.Kind.WILDCARD_LOWER_BOUND, -1, rhsWildcard, rhsBound)); frame = new Frame( frame.targetSteps(), @@ -366,16 +371,16 @@ void reject(Relation relation, Type lhsNode, Type rhsNode) { * @param parent the node the comparison steps from * @param child the node it steps to */ - private record Step(TypePath.Step.Kind kind, int index, Type parent, Type child) {} + private record ComparisonStep(TypePath.Step.Kind kind, int index, Type parent, Type child) {} /** * Takes one step on each side the visitor names, and returns the frame from before it. A {@code * null} step leaves that side where it is. */ - private Frame enter(@Nullable Step lhs, @Nullable Step rhs) { + private Frame enter(@Nullable ComparisonStep lhs, @Nullable ComparisonStep rhs) { Frame saved = frame; - Step targetStep = saved.swapped() ? rhs : lhs; - Step sourceStep = saved.swapped() ? lhs : rhs; + ComparisonStep targetStep = saved.swapped() ? rhs : lhs; + ComparisonStep sourceStep = saved.swapped() ? lhs : rhs; TypePath targetSteps = saved.targetSteps(); Track target = saved.target(); if (targetStep != null) { @@ -399,7 +404,7 @@ private Frame enter(@Nullable Step lhs, @Nullable Step rhs) { } /** Names {@code step} for the {@code path} line, in the class the comparison stepped from. */ - private static TypePath.Step comparedStep(Step step) { + private static TypePath.Step comparedStep(ComparisonStep step) { return switch (step.kind()) { case TYPE_ARGUMENT -> typeArgumentStep(step.parent(), step.index()); case WILDCARD_UPPER_BOUND -> TypePath.Step.wildcardUpperBound(); @@ -425,7 +430,7 @@ private static boolean isShown(TypePath.Step.Kind kind, Type parent) { * Follows {@code step} of the comparison in the written type {@code track} follows, as the class * comment describes. */ - private static Track follow(Track track, Step step) { + private static Track follow(Track track, ComparisonStep step) { return switch (track.state()) { case HIDDEN -> { HiddenBound hidden = castToNonNull(track.hidden()); @@ -451,47 +456,35 @@ yield new Track( * for a type argument or an enclosing type, an array for an array element, and a wildcard for a * bound. Returns {@code null} where it is of another kind. */ - private static @Nullable Track childByPosition(Track track, Step step) { + private static @Nullable Track childByPosition(Track track, ComparisonStep step) { Type node = track.node(); + if (!isOfSteppedFromClass(node, step)) { + return null; + } + Type child = TypePath.childAt(node, step.kind(), step.index()); + if (child != null) { + return Track.located(child, track.path().then(comparedStep(step))); + } + // the upper bound of `?` and `? super X` is not printed, so the caret stays on the wildcard + return step.kind() == TypePath.Step.Kind.WILDCARD_UPPER_BOUND + && GenericsUtils.asWildcard(node) != null + ? new Track( + Track.State.HIDDEN, + node, + track.path(), + null, + new HiddenBound(step.child(), TypePath.root())) + : null; // diff-coverage: ignore -- the track stands at the node the check steps from + } + + /** + * Whether {@code node} is of the class the comparison stepped from, where {@code step} goes into + * a type argument or an enclosing type; other steps descend from a node of any class. + */ + private static boolean isOfSteppedFromClass(Type node, ComparisonStep step) { return switch (step.kind()) { - case TYPE_ARGUMENT -> - node instanceof Type.ClassType classType - && classType.tsym.equals(step.parent().tsym) - && step.index() < classType.getTypeArguments().size() - ? Track.located( - classType.getTypeArguments().get(step.index()), - track.path().then(typeArgumentStep(classType, step.index()))) - : null; - case ENCLOSING_TYPE -> - node instanceof Type.ClassType classType && classType.tsym.equals(step.parent().tsym) - ? Track.located( - classType.getEnclosingType(), track.path().then(TypePath.Step.enclosingType())) - : null; - case ARRAY_ELEMENT -> - node instanceof Type.ArrayType arrayType - ? Track.located(arrayType.elemtype, track.path().then(TypePath.Step.arrayElement())) - : null; // diff-coverage: ignore -- the track stands at the node the check steps from - case WILDCARD_UPPER_BOUND -> { - Type.WildcardType wildcard = GenericsUtils.asWildcard(node); - if (wildcard == null) { - yield null; // diff-coverage: ignore -- the track stands at the node the check steps from - } - // the upper bound of `?` and `? super X` is not printed, so the caret stays on the wildcard - yield wildcard.kind == BoundKind.EXTENDS - ? Track.located(wildcard.type, track.path().then(TypePath.Step.wildcardUpperBound())) - : new Track( - Track.State.HIDDEN, - node, - track.path(), - null, - new HiddenBound(step.child(), TypePath.root())); - } - case WILDCARD_LOWER_BOUND -> { - Type.WildcardType wildcard = GenericsUtils.asWildcard(node); - yield wildcard != null && wildcard.kind == BoundKind.SUPER - ? Track.located(wildcard.type, track.path().then(TypePath.Step.wildcardLowerBound())) - : null; // diff-coverage: ignore -- the track stands at the node the check steps from - } + case TYPE_ARGUMENT, ENCLOSING_TYPE -> step.parent().tsym.equals(node.tsym); + case WILDCARD_UPPER_BOUND, WILDCARD_LOWER_BOUND, ARRAY_ELEMENT -> true; }; } @@ -503,36 +496,16 @@ yield new Track( * supertype, since the annotation is not written at the argument; a step below it, or a class * comparison at it ({@link #viewedAs}), goes on from the written type argument. */ - private static Track followDeclared(Track track, Step step) { + private static Track followDeclared(Track track, ComparisonStep step) { Track argument = writtenArgumentAt(track); if (argument != null) { return follow(argument, step); } Type declared = castToNonNull(track.declared()); Type child = - switch (step.kind()) { - case TYPE_ARGUMENT -> - declared instanceof Type.ClassType classType - && classType.tsym.equals(step.parent().tsym) - && step.index() < classType.getTypeArguments().size() - ? classType.getTypeArguments().get(step.index()) - : null; // diff-coverage: ignore -- the view has this shape - case ENCLOSING_TYPE -> - declared instanceof Type.ClassType classType - && classType.tsym.equals(step.parent().tsym) - ? classType.getEnclosingType() - : null; // diff-coverage: ignore -- the view has this shape - case ARRAY_ELEMENT -> - declared instanceof Type.ArrayType arrayType ? arrayType.elemtype : null; - case WILDCARD_UPPER_BOUND, WILDCARD_LOWER_BOUND -> { - Type.WildcardType wildcard = GenericsUtils.asWildcard(declared); - BoundKind kind = - step.kind() == TypePath.Step.Kind.WILDCARD_UPPER_BOUND - ? BoundKind.EXTENDS - : BoundKind.SUPER; - yield wildcard != null && wildcard.kind == kind ? wildcard.type : null; - } - }; + isOfSteppedFromClass(declared, step) + ? TypePath.childAt(declared, step.kind(), step.index()) + : null; // diff-coverage: ignore -- the view has this shape if (child == null) { return Track.lost(track); } 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 aa7c46849a..aae884bb55 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java @@ -1,13 +1,16 @@ package com.uber.nullaway.generics; import com.google.common.collect.ImmutableList; +import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Type; import java.util.Objects; 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 inside a type, as the sequence of descents that reaches it from the root. A position + * may lie below a bound the printer does not show, such as the upper bound of {@code ?}; a caret + * for such a position goes under the wildcard that hides the bound. * *

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 @@ -87,6 +90,39 @@ String describe() { } } + /** + * Returns the node a step of {@code kind} reaches from {@code node}, or {@code null} where {@code + * node} is not of the kind the step descends from: a class type with a type argument at {@code + * index}, a class type whose enclosing type is a class type, an array, or a wildcard or capture + * that states a bound of the step's kind. So it returns {@code null} for the upper bound of + * {@code ?} and of {@code ? super X}, which neither states. + */ + static @Nullable Type childAt(Type node, Step.Kind kind, int index) { + return switch (kind) { + case TYPE_ARGUMENT -> + node instanceof Type.ClassType classType && index < classType.getTypeArguments().size() + ? classType.getTypeArguments().get(index) + : null; // diff-coverage: ignore -- no test replays a path on a shorter type + case ENCLOSING_TYPE -> + node instanceof Type.ClassType classType + && classType.getEnclosingType() instanceof Type.ClassType enclosing + ? enclosing + : null; + case ARRAY_ELEMENT -> node instanceof Type.ArrayType array ? array.elemtype : null; + case WILDCARD_UPPER_BOUND -> statedBound(node, BoundKind.EXTENDS); + case WILDCARD_LOWER_BOUND -> statedBound(node, BoundKind.SUPER); + }; + } + + /** + * Returns the bound of {@code kind} that {@code node} states, where it is a wildcard or the + * capture of one, or {@code null}. + */ + private static @Nullable Type statedBound(Type node, BoundKind kind) { + Type.WildcardType wildcard = GenericsUtils.asWildcard(node); + return wildcard != null && wildcard.kind == kind ? wildcard.type : null; + } + private static final TypePath ROOT = new TypePath(null, null, 0); /** The path this one extends by {@link #last}, or {@code null} for the root. */ 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 deddd3cbdf..bce37ae945 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/BytecodeGenericsTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/BytecodeGenericsTests.java @@ -289,7 +289,7 @@ public void genericsChecksForFieldAssignments() { import com.uber.lib.generics.NullableTypeParam; class Test { static void testPositive(NullableTypeParam t1) { - // BUG: Diagnostic contains: incompatible nullability in type argument for E of NullableTypeParam: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of NullableTypeParam: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String NullableTypeParam.staticField = t1; // BUG: Diagnostic contains: incompatible nullability in type argument for E of NullableTypeParam: source has @Nullable String where target requires String NullableTypeParam t2 = NullableTypeParam.staticField; @@ -315,7 +315,7 @@ public void genericsChecksForParamPassingAndReturns() { import com.uber.lib.generics.GenericTypeArgMethods; class Test { static void testPositive(NullableTypeParam t1) { - // BUG: Diagnostic contains: incompatible nullability in type argument for E of NullableTypeParam: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of NullableTypeParam: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String GenericTypeArgMethods.nullableTypeParamArg(t1); // BUG: Diagnostic contains: incompatible nullability in type argument for E of NullableTypeParam: source has @Nullable String where target requires String NullableTypeParam t2 = GenericTypeArgMethods.nullableTypeParamReturn(); 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 eca3da1dc1..b4bac8dba3 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java @@ -396,7 +396,7 @@ static void test( // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: source has @Nullable String where target requires String List invalid = box.get(); box.set(nullableList); - // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String box.set(nonNullList); } } 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 437a3e1376..1b3a1bb3ac 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 nullability in type argument for T of Box: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Box: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String acceptsNullable(flat); } @@ -1337,7 +1337,7 @@ void testNegative() { receiver(makeCancelable(this::target)); } void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of Callback: a non-wildcard type argument must have the same nullness in source and target; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Callback: a non-wildcard type argument must have the same nullability in source and target; source has Object where target requires @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 a2ff941909..cad8f0cf7f 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java @@ -561,7 +561,7 @@ interface B { X b(); } B nonNullB = id1(value); // BUG: Diagnostic contains: incompatible nullability in type argument for X of A: source has @Nullable String where target requires String A nonNullA = id1(value); - // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String B<@Nullable String> nullableB = id1(value); } @@ -574,7 +574,7 @@ interface B { X b(); } B nonNullB = id2(value); // BUG: Diagnostic contains: incompatible nullability in type argument for X of A: source has @Nullable String where target requires String A nonNullA = id2(value); - // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String B<@Nullable String> nullableB = id2(value); } @@ -587,7 +587,7 @@ interface B { X b(); } B nonNullB = id3(value); // BUG: Diagnostic contains: incompatible nullability in type argument for X of A: source has @Nullable String where target requires String A nonNullA = id3(value); - // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String B<@Nullable String> nullableB = id3(value); } @@ -600,7 +600,7 @@ interface B { X b(); } B nonNullB = id4(value); // BUG: Diagnostic contains: incompatible nullability in type argument for X of A: source has @Nullable String where target requires String A nonNullA = id4(value); - // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String B<@Nullable String> nullableB = id4(value); } } @@ -636,7 +636,7 @@ static class Box1> & B>> { B> nonNullB = box.get(); // BUG: Diagnostic contains: incompatible nullability in type argument for X of A -> type argument for E of List: source has @Nullable String where target requires String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String B> nullableB = box.get(); } @@ -654,7 +654,7 @@ static class Box2> & A>> { B> nonNullB = box.get(); // BUG: Diagnostic contains: incompatible nullability in type argument for X of A -> type argument for E of List: source has @Nullable String where target requires String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String B> nullableB = box.get(); } @@ -672,7 +672,7 @@ static class Box3> & B>> B> nonNullB = box.get(); // BUG: Diagnostic contains: incompatible nullability in type argument for X of A -> type argument for E of List: source has @Nullable String where target requires String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String B> nullableB = box.get(); } @@ -690,7 +690,7 @@ static class Box4> & A>> B> nonNullB = box.get(); // BUG: Diagnostic contains: incompatible nullability in type argument for X of A -> type argument for E of List: source has @Nullable String where target requires String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String B> nullableB = box.get(); } } @@ -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 nullability in type argument for T of Foo: a non-wildcard type argument must have the same nullness in source and target; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: a non-wildcard type argument must have the same nullability in source and target; source has Object where target requires @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 nullability in type argument for T of Foo: a non-wildcard type argument must have the same nullness in source and target; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: a non-wildcard type argument must have the same nullability in source and target; source has Object where target requires @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 nullability in type argument for V of Foo -> type argument for E of ArrayList: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for V of Foo -> type argument for E of ArrayList: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String Foo> fooNonNull_2 = f.nonNullTest(); - // BUG: Diagnostic contains: incompatible nullability in type argument for K of Foo: a non-wildcard type argument must have the same nullness in source and target; source has Integer where target requires @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in type argument for K of Foo: a non-wildcard type argument must have the same nullability in source and target; source has Integer where target requires @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 nullability in type argument for T of Foo -> component type -> type argument for T of Foo: a non-wildcard type argument must have the same nullness in source and target; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo -> component type -> type argument for T of Foo: a non-wildcard type argument must have the same nullability in source and target; source has Object where target requires @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 nullability in component type -> type argument for T of Foo: a non-wildcard type argument must have the same nullness in source and target; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in component type -> type argument for T of Foo: a non-wildcard type argument must have the same nullability in source and target; source has Object where target requires @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 nullability in type argument for T of Bar -> type argument for T of Bar: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Bar -> type argument for T of Bar: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @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 nullability in type argument for T of Function and 1 other differing position: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Function and 1 other differing position: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String 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 nullability in type argument for T of Foo: a non-wildcard type argument must have the same nullness in source and target; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: a non-wildcard type argument must have the same nullability in source and target; source has Object where target requires @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 nullability in type argument for T of Foo: a non-wildcard type argument must have the same nullness in source and target; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: a non-wildcard type argument must have the same nullability in source and target; source has Object where target requires @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 nullability in type argument for T of Foo: a non-wildcard type argument must have the same nullness in source and target; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: a non-wildcard type argument must have the same nullability in source and target; source has Object where target requires @Nullable Object handleFooNullableVarargs(Foo.makeNonNull(new Object())); handleFooNonNullVarargs(Foo.makeNonNull(new Object())); } @@ -2545,7 +2545,7 @@ Supplier make2() { } // tests that our repair computes a consistent substitution for the type variables void test2() { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of Supplier: a non-wildcard type argument must have the same nullness in source and target; source has OuterT where target requires @Nullable OuterT + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Supplier: a non-wildcard type argument must have the same nullability in source and target; source has OuterT where target requires @Nullable OuterT acceptTwoSup(sup, sup2); } } @@ -2733,7 +2733,7 @@ class Test { static class Box {} static void accept(Box<@Nullable T> box) {} void test(Box> box) { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of Box: a non-wildcard type argument must have the same nullness in source and target; source has CompletableFuture where target requires @Nullable CompletableFuture + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Box: a non-wildcard type argument must have the same nullability in source and target; source has CompletableFuture where target requires @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 6e373d7fb1..f475924f18 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java @@ -349,13 +349,13 @@ void callOnResult() { } public void testPositive() { addCallback( - // BUG: Diagnostic contains: incompatible nullability in type argument for T of Callback: a non-wildcard type argument must have the same nullness in source and target; source has Integer where target requires @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Callback: a non-wildcard type argument must have the same nullability in source and target; source has Integer where target requires @Nullable Integer new Callback() { @Override public void onResult(Integer value) { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of Callback: a non-wildcard type argument must have the same nullness in source and target; source has Integer where target requires @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Callback: a non-wildcard type argument must have the same nullability in source and target; source has Integer where target requires @Nullable Integer removeCallback(this); - // BUG: Diagnostic contains: incompatible nullability in type argument for T of Callback: a non-wildcard type argument must have the same nullness in source and target; source has Integer where target requires @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Callback: a non-wildcard type argument must have the same nullability in source and target; source has Integer where target requires @Nullable Integer Callback<@Nullable Integer> self = this; } void callOnResult() { @@ -503,7 +503,7 @@ class Test { static class SampleClass {} static class SampleClassMultipleArguments {} static void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in type argument for E1 of SampleClassMultipleArguments -> type argument for E of SampleClass -> type argument for E of SampleClass: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for E1 of SampleClassMultipleArguments -> type argument for E of SampleClass -> type argument for E of SampleClass: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String SampleClassMultipleArguments>, String> t1 = new SampleClassMultipleArguments>, String>(); } @@ -552,7 +552,7 @@ interface Fn1 {} interface Fn2

{} class FnImpl implements Fn1<@Nullable String, @Nullable String>, Fn2 {} void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in type argument for P of Fn2: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for P of Fn2: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @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 nullability in type argument for P1 of SuperClassC: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for P1 of SuperClassC: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String f = new FnImpl1(); } void testNegative() { @@ -634,7 +634,7 @@ void testNegative() { Super<@Nullable String, String> s = new Sub(); } void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in type argument for A of Super and 1 other differing position: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for A of Super and 1 other differing position: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String Super<@Nullable String, String> s2 = new Sub<@Nullable String, String>(); } } @@ -1008,7 +1008,7 @@ public String function(T1 o) { } } static void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in type argument for T1 of A: a non-wildcard type argument must have the same nullness in source and target; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T1 of A: a non-wildcard type argument must have the same nullability in source and target; source has Object where target requires @Nullable Object A<@Nullable Object> p = new B<>(); } static void testNegative() { @@ -1034,7 +1034,7 @@ static A testPositive1() { return new A<@Nullable String>(); } static A<@Nullable String> testPositive2() { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String return new A(); } static A<@Nullable String> testNegative() { @@ -1229,11 +1229,11 @@ static void testPositive1(A> a1, A a2) { A a = sampleMethod1(a1, a2); } static void testPositive2(A> a1, A a2) { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of A -> type argument for T of A: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A -> type argument for T of A: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String A a = sampleMethod2(a1, a2); } static void testPositive3(A a1) { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @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 nullability in type argument for T of A: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String p.foo(q); // this one is fine p.foo(p); @@ -1391,7 +1391,7 @@ public void nestedGenericTypeAssignment() { class Test { static class A { } static void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of A -> component type -> type argument for T of A: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A -> component type -> type argument for T of A: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String A[]> var1 = new A[]>(); // BUG: Diagnostic contains: incompatible nullability in type argument for T of A -> component type -> type argument for T of A: source has @Nullable String where target requires String A[]> var2 = new A[]>(); @@ -1435,7 +1435,7 @@ public void genericPrimitiveArrayTypeAssignment() { class Test { static class A { } static void testPositive() { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must have the same nullness in source and target; source has int [] where target requires int @Nullable [] + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must have the same nullability in source and target; source has int [] where target requires int @Nullable [] A x = new A(); } static void testNegative() { @@ -2064,7 +2064,7 @@ void staticSubclassWithNonNullOuterMatches(NonNullInner input) { Outer.Inner result = input; } void staticSubclassWithNonNullOuterMismatches(NonNullInner input) { - // BUG: Diagnostic contains: incompatible nullability in enclosing type -> type argument for T of Outer: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in enclosing type -> type argument for T of Outer: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String Outer<@Nullable String>.Inner result = input; } void unrelatedEnclosingTypeMatches(Unrelated.Derived input) { @@ -3041,7 +3041,7 @@ static void test1(Object o) { static void test2(Object o) { var x = (A<@Nullable String> & Serializable) o; x = new B(); - // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String x = new C(); } } @@ -3138,7 +3138,7 @@ void testNegative(Function<@Nullable V, @Nullable V> f) { foo(f); } void testPositive(Function f) { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of Function and 1 other differing position: a non-wildcard type argument must have the same nullness in source and target; source has V where target requires @Nullable V + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Function and 1 other differing position: a non-wildcard type argument must have the same nullability in source and target; source has V where target requires @Nullable V 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 nullability in component type -> type argument for T of Function and 1 other differing position: a non-wildcard type argument must have the same nullness in source and target; source has V where target requires @Nullable V + // BUG: Diagnostic contains: incompatible nullability in component type -> type argument for T of Function and 1 other differing position: a non-wildcard type argument must have the same nullability in source and target; source has V where target requires @Nullable V takesArray(f); } } @@ -3200,7 +3200,7 @@ void testPositive1(Function<@Nullable V, V> f) { foo(f); } void testPositive2(Function f) { - // BUG: Diagnostic contains: incompatible nullability in type argument for R of Function: a non-wildcard type argument must have the same nullness in source and target; source has V where target requires @Nullable V + // BUG: Diagnostic contains: incompatible nullability in type argument for R of Function: a non-wildcard type argument must have the same nullability in source and target; source has V where target requires @Nullable V foo(f); } void testPositive3(Function<@Nullable V, @Nullable V> 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 nullability in type argument for T of Function and 1 other differing position: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Function and 1 other differing position: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @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 nullability in type argument for E of List: a non-wildcard type argument must have the same nullness in source and target; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: a non-wildcard type argument must have the same nullability in source and target; source has Object where target requires @Nullable Object super(l); } } @@ -3680,7 +3680,7 @@ class C extends A<@NonNull T> {} void test() { // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: source has @Nullable Object where target requires Object A a = new B(); - // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must have the same nullness in source and target; source has Object where target requires @Nullable Object + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must have the same nullability in source and target; source has Object where target requires @Nullable Object A<@Nullable Object> a2 = new C<@Nullable Object>(); } } @@ -3737,7 +3737,7 @@ 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 nullability in type argument for T of Foo: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String Foo<@Nullable String> f1 = nullableFoo.nonNullField; Foo f2 = nullableFoo.nonNullField; Foo<@Nullable String> f3 = nonnullFoo.nullableField; diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java index 29df2eb5a1..2e6d0a53e2 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java @@ -45,7 +45,7 @@ void acceptsOtherNonNullComponent(Factory factory) { } void rejectsWideningOtherInvariantComponent(Factory factory) { - // BUG: Diagnostic contains: incompatible nullability in type argument for E of B: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of B: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String B<@Nullable String> result = factory.fromA().get(); } @@ -54,7 +54,7 @@ void acceptsMatchingNonNullComponent(Factory factory) { } void rejectsWideningMatchingInvariantComponent(Factory factory) { - // BUG: Diagnostic contains: incompatible nullability in type argument for E of B: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for E of B: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String B<@Nullable String> result = factory.fromB().get(); } } 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 ceb6632152..39a2b67d5f 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/JSpecifyArrayTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/JSpecifyArrayTests.java @@ -673,7 +673,7 @@ public void arraysAndGenerics() { class Test { void foo(List<@Nullable Integer[]> l) {} void testPositive(List p) { - // BUG: Diagnostic contains: incompatible nullability in type argument for E of List -> component type: a non-wildcard type argument must have the same nullness in source and target; source has Integer where target requires @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List -> component type: a non-wildcard type argument must have the same nullability in source and target; source has Integer where target requires @Nullable Integer foo(p); } void testNegative(List<@Nullable Integer[]> p) { 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 b7600bea5b..d4ac629d54 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -1479,7 +1479,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 nullability in type argument for T of Foo: a non-wildcard type argument must have the same nullness in source and target; source has Void where target requires @Nullable Void + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo: a non-wildcard type argument must have the same nullability in source and target; source has Void where target requires @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 @@ -1556,7 +1556,7 @@ interface Nested {} return box; } void test(Box> box) { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of Box -> lower bound of wildcard -> type argument for T of Nested: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Box -> lower bound of wildcard -> type argument for T of Nested: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String Box> bad = identity(box); } } 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 index 4d3e2fecfd..8e64f16da4 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java @@ -32,6 +32,45 @@ void test(List> l) { """); } + @Test + public void aClassInsideAnImplicitBoundViewedAsItsSupertypeIsMarkedAtTheWildcard() { + assertMessages( + Map.of( + "WRITTEN", + """ + incompatible nullability in type argument for T of Box -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: Box + ^ + target: Box> + ^^^^^^ + note: the unbounded wildcard ? in Box has the upper bound of type parameter T of Box, which is ArrayList<@Nullable String> (JLS 5.1.10) + """, + "CAPTURED", + """ + incompatible nullability in type argument for T of Box -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: Box + ^^^^^^^^^^^^ + target: Box> + ^^^^^^ + note: capture of ? is the captured type argument for T of Box, whose upper bound is ArrayList<@Nullable String> (JLS 5.1.10) + """), + """ + static class Box> {} + static void take(Box> b) {} + static Box make() { + throw new RuntimeException(); + } + void written(Box b) { + // BUG: Diagnostic matches: WRITTEN + take(b); + } + void captured() { + // BUG: Diagnostic matches: CAPTURED + take(make()); + } + """); + } + @Test public void caretSkipsATypeArgumentTheTargetAccepts() { assertMessage( diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java index dbd4298667..2a6a6407d8 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java @@ -81,7 +81,7 @@ public void underALowerBoundTheTargetIsTheSubtypeSide() { Map.of( "REORDERING_SUBCLASS", """ - incompatible nullability in type argument for E of List -> lower bound of wildcard -> type argument for B of Pair: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + incompatible nullability in type argument for E of List -> lower bound of wildcard -> type argument for B of Pair: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String source: List> ^^^^^^ target: List> @@ -94,6 +94,22 @@ public void underALowerBoundTheTargetIsTheSubtypeSide() { ^^^^^^ target: List> ^^^^^^^^^^^^^^^^ + """, + "TWO_LOWER_BOUNDS", + """ + incompatible nullability in type argument for E of List -> lower bound of wildcard -> type argument for E of List -> lower bound of wildcard: source has @Nullable String where target requires String + source: List> + ^^^^^^^^^^^^^^^^ + target: List> + ^^^^^^ + """, + "TWO_LOWER_BOUNDS_THEN_A_TYPE_ARGUMENT", + """ + incompatible nullability in type argument for E of List -> lower bound of wildcard -> type argument for E of List -> lower bound of wildcard -> type argument for T of Box: source has @Nullable String where target requires String + source: List>> + ^^^^^^^^^^^^^^^^ + target: List>> + ^^^^^^ """), """ static class Pair {} @@ -111,6 +127,16 @@ void wildcardOnlyInSource() { List> l = boxes(); l.hashCode(); } + static void takeTwo(List> l) {} + void twoLowerBounds(List> l) { + // BUG: Diagnostic matches: TWO_LOWER_BOUNDS + takeTwo(l); + } + static void takeTwoBoxes(List>> l) {} + void twoLowerBoundsThenATypeArgument(List>> l) { + // BUG: Diagnostic matches: TWO_LOWER_BOUNDS_THEN_A_TYPE_ARGUMENT + takeTwoBoxes(l); + } """); } } 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 f8d38847b2..1fe965cdd4 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 @@ -192,21 +192,56 @@ void test(List> f) { @Test public void aWildcardInsideAWildcardBoundNamesItsTypeParameter() { - assertMessage( - """ - incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: List> - ^ - target: List> - ^^^^^^ - note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) - """, + assertMessages( + Map.of( + "WRITTEN", + """ + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: List> + ^ + target: List> + ^^^^^^ + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + """, + "CAPTURED", + """ + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: List> + ^ + target: List> + ^^^^^^ + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + """, + "CAPTURED_ONE_LEVEL_DOWN", + """ + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: List>> + ^ + target: List>> + ^^^^^^ + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + """), """ static void take(List> l) {} - void test(List> l) { - // BUG: Diagnostic matches: MESSAGE + static void takeNested(List>> l) {} + static List same(List l) { + throw new RuntimeException(); + } + static List wrap(T t) { + throw new RuntimeException(); + } + void written(List> l) { + // BUG: Diagnostic matches: WRITTEN take(l); } + void captured(List> l) { + // BUG: Diagnostic matches: CAPTURED + take(same(l)); + } + void capturedOneLevelDown(List> l) { + // BUG: Diagnostic matches: CAPTURED_ONE_LEVEL_DOWN + takeNested(wrap(same(l))); + } """); } @@ -410,6 +445,32 @@ public void aCapturedWildcardsBoundNamesTypeParametersRatherThanCaptures() { ^^^^^^^^^^^^ target: Outer.Inner> ^^^^^^^ + """, + "WILDCARD_IN_BOUND", + """ + incompatible nullability in type argument for B of Dep -> upper bound of wildcard: source has @Nullable List where target requires List + source: Dep + ^^^^^^^^^^^^ + target: Dep> + ^^^^^^^ + note: capture of ? is the captured type argument for B of Dep, whose upper bound is @Nullable List (JLS 5.1.10) + """, + "ARRAY_IN_BOUND", + """ + incompatible nullability in type argument for B of ArrayDep -> upper bound of wildcard: source has @Nullable List where target requires List + source: ArrayDep + ^^^^^^^^^^^^ + target: ArrayDep> + ^^^^^^^ + note: capture of ? is the captured type argument for B of ArrayDep, whose upper bound is @Nullable List (JLS 5.1.10) + """, + "CAPTURE_OF_ANOTHER_TYPE_IN_BOUND", + """ + incompatible nullability in type argument for B of Dep -> upper bound of wildcard: source has @Nullable List> where target requires List + source: Dep, capture of ?> + ^^^^^^^^^^^^ + target: Dep> + ^^^^^^^ """), """ static class Self> {} @@ -463,6 +524,34 @@ void innerSubclass() { // BUG: Diagnostic matches: INNER_SUBCLASS takeInner(makeNonNullInner()); } + static class Dep> {} + static Dep makeDep() { + throw new RuntimeException(); + } + static void takeDep(Dep> d) {} + void wildcardInBound() { + // BUG: Diagnostic matches: WILDCARD_IN_BOUND + takeDep(makeDep()); + } + static class ArrayDep> {} + static ArrayDep makeArrayDep() { + throw new RuntimeException(); + } + static void takeArrayDep(ArrayDep> d) {} + void arrayInBound() { + // BUG: Diagnostic matches: ARRAY_IN_BOUND + takeArrayDep(makeArrayDep()); + } + static Dep depOf(T t) { + throw new RuntimeException(); + } + static List makeList() { + throw new RuntimeException(); + } + void captureOfAnotherTypeInBound() { + // BUG: Diagnostic matches: CAPTURE_OF_ANOTHER_TYPE_IN_BOUND + takeDep(depOf(makeList())); + } """); } @@ -549,6 +638,14 @@ public void aHolderNoteIsPrintedOnlyWhereItsBoundHasTheNullnessTheCheckCompared( target: Base ^^^^^^ note: the unbounded wildcard ? in Sub has the upper bound of type parameter T of Sub, which is @Nullable Object (JLS 5.1.10) + """, + "SUBCLASS_BOUND_HAS_NO_ENCLOSING_TYPE", + """ + incompatible nullability in type argument for T of Holder -> upper bound of wildcard -> enclosing type -> type argument for X of Enclosing: source has @Nullable String where target requires String + source: TopSub + ^ + target: Holder.Nested> + ^^^^^^ """), """ static class Base {} @@ -609,6 +706,20 @@ void subclassBoundIsNullable(Sub s) { // BUG: Diagnostic matches: SUBCLASS_BOUND_IS_NULLABLE takeNonNull(s); } + static class Enclosing { + class Nested {} + } + static class TopNested extends Enclosing<@Nullable String>.Nested { + TopNested(Enclosing<@Nullable String> e) { + e.super(); + } + } + static class Holder.Nested> {} + static class TopSub extends Holder {} + void subclassBoundHasNoEnclosingType(TopSub s) { + // BUG: Diagnostic matches: SUBCLASS_BOUND_HAS_NO_ENCLOSING_TYPE + Holder.Nested> h = s; + } """); } 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 index 30e9c53235..b4992d871e 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java @@ -135,7 +135,7 @@ void test( public void pathReachesATypeArgumentOfAnArrayElement() { assertMessage( """ - incompatible nullability in component type -> type argument for E of List: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + incompatible nullability in component type -> type argument for E of List: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String source: List [] ^^^^^^ target: @Nullable List<@Nullable String> [] 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 index ec8b3a3451..99d16c5e9d 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java @@ -7,7 +7,7 @@ * The first line of a generic nullability message names the position of the first difference, how * many other positions differ, and the two types at the first one, so that it stands alone where a * tool shows only that line. Where there are several, each gets a numbered entry, five at most, and - * a line after them counts the rest. A non-wildcard type argument must have the same nullness in + * a line after them counts the rest. A non-wildcard type argument must have the same nullability in * the source and the target, and the first line says so where the source is the less nullable side. */ public class SummaryAndNumberingTests extends MismatchMessageTestBase { @@ -144,7 +144,7 @@ void test(Map<@Nullable String, @Nullable String> m) { Map.of( "ONLY", """ - incompatible nullability in type argument for E of List: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + incompatible nullability in type argument for E of List: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String source: List ^^^^^^ target: List<@Nullable String> @@ -166,7 +166,7 @@ void test(Map<@Nullable String, @Nullable String> m) { \s 2. path: type argument for V of Map source: String - target: @Nullable String (a non-wildcard type argument must have the same nullness in source and target) + target: @Nullable String (a non-wildcard type argument must have the same nullability in source and target) """), """ static void takeMap(Map m) {} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java index 177adba281..df48f9ad63 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java @@ -101,4 +101,76 @@ void test(List, @Nullable String>> l) { } """); } + + // Each L passes its X on to both L in its bound, so the two sides differ at every level + // and + // no level shares a bound object with the other side. + @Test(timeout = 30_000) + public void aRejectedComparisonReachedAlongManyPathsIsWalkedOnce() { + assertMessage( + """ + incompatible nullability in type argument for X of L24 and 94 other differing positions: source has @Nullable String where target requires String + source: L24<@Nullable String, ?> + ^^^^^^^^^^^^^^^^ ^ + 1 2,3,4,5 + target: L24 + ^^^^^^ ^ + 1 2,3,4,5 + \s + 1. path: type argument for X of L24 + source: @Nullable String + target: String + \s + 2. path: type argument for T of L24 -> upper bound of wildcard -> type argument for A of P -> type argument for X of L23 + source: @Nullable String + target: String + note: the unbounded wildcard ? in L24<@Nullable String, ?> has the upper bound of type parameter T of L24, which is P, L23<@Nullable String, ?>> (JLS 5.1.10) + \s + 3. path: type argument for T of L24 -> upper bound of wildcard -> type argument for A of P -> type argument for T of L23 -> upper bound of wildcard -> type argument for A of P -> type argument for X of L22 + source: @Nullable String + target: String + \s + 4. path: type argument for T of L24 -> upper bound of wildcard -> type argument for A of P -> type argument for T of L23 -> upper bound of wildcard -> type argument for A of P -> type argument for T of L22 -> upper bound of wildcard -> type argument for A of P -> type argument for X of L21 + source: @Nullable String + target: String + \s + 5. path: type argument for T of L24 -> upper bound of wildcard -> type argument for A of P -> type argument for T of L23 -> upper bound of wildcard -> type argument for A of P -> type argument for T of L22 -> upper bound of wildcard -> type argument for A of P -> type argument for T of L21 -> upper bound of wildcard -> type argument for A of P -> type argument for X of L20 + source: @Nullable String + target: String + \s + and 90 more differing positions, not listed + """, + """ + interface P {} + interface L0 {} + interface L1, L0>> {} + interface L2, L1>> {} + interface L3, L2>> {} + interface L4, L3>> {} + interface L5, L4>> {} + interface L6, L5>> {} + interface L7, L6>> {} + interface L8, L7>> {} + interface L9, L8>> {} + interface L10, L9>> {} + interface L11, L10>> {} + interface L12, L11>> {} + interface L13, L12>> {} + interface L14, L13>> {} + interface L15, L14>> {} + interface L16, L15>> {} + interface L17, L16>> {} + interface L18, L17>> {} + interface L19, L18>> {} + interface L20, L19>> {} + interface L21, L20>> {} + interface L22, L21>> {} + interface L23, L22>> {} + interface L24, L23>> {} + void test(L24<@Nullable String, ?> l) { + // BUG: Diagnostic matches: MESSAGE + L24 x = l; + } + """); + } } 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 ff8ab9615d..aeafb9fbd8 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 @@ -108,7 +108,7 @@ void test(Sub s) { Map.of( "SELF", """ - incompatible nullability in type argument for T of Base: a non-wildcard type argument must have the same nullness in source and target; source has Sub where target requires @Nullable Sub + incompatible nullability in type argument for T of Base: a non-wildcard type argument must have the same nullability in source and target; source has Sub where target requires @Nullable Sub source: Sub source supertype: Base ^^^ @@ -117,7 +117,7 @@ void test(Sub s) { """, "ARGUMENT", """ - incompatible nullability in type argument for T of Base: a non-wildcard type argument must have the same nullness in source and target; source has Sub where target requires @Nullable Sub + incompatible nullability in type argument for T of Base: a non-wildcard type argument must have the same nullability in source and target; source has Sub where target requires @Nullable Sub source: Holder source supertype: Base ^^^ @@ -241,6 +241,58 @@ void written(Strings s) { """); } + @Test + public void aTypeVariableBelowAWildcardBoundOfTheDeclaredSupertypeIsMarkedAtTheWrittenArgument() { + assertMessages( + Map.of( + "UPPER_BOUND", + """ + incompatible nullability in type argument for B of Base -> type argument for E of List -> upper bound of wildcard -> type argument for X of Box: source has @Nullable String where target requires String + source: Sub<@Nullable String> + ^^^^^^^^^^^^^^^^ + target: Base>> + ^^^^^^ + """, + "LOWER_BOUND", + """ + incompatible nullability in type argument for B of Base -> type argument for E of List -> lower bound of wildcard -> type argument for X of Box: source has @Nullable String where target requires String + source: SuperSub<@Nullable String> + ^^^^^^^^^^^^^^^^ + target: Base>> + ^^^^^^ + """, + "WRITTEN", + """ + incompatible nullability in type argument for B of Base -> type argument for E of List -> upper bound of wildcard -> type argument for X of Box: source has @Nullable String where target requires String + source: Strings + source supertype: Base>> + ^^^^^^^^^^^^^^^^ + target: Base>> + ^^^^^^ + """), + """ + static class Base {} + static class Box {} + static class Sub extends Base>> {} + static class SuperSub extends Base>> {} + static class Strings extends Base>> {} + static void take(Base>> b) {} + static void takeSuper(Base>> b) {} + void upperBound(Sub<@Nullable String> s) { + // BUG: Diagnostic matches: UPPER_BOUND + take(s); + } + void lowerBound(SuperSub<@Nullable String> s) { + // BUG: Diagnostic matches: LOWER_BOUND + takeSuper(s); + } + void written(Strings s) { + // BUG: Diagnostic matches: WRITTEN + take(s); + } + """); + } + // The target line of an intersection has no caret under either differing position (#2202). @Test public void eachComponentOfAnIntersectionTargetIsComparedUnderItsOwnView() { @@ -270,6 +322,8 @@ static void test(Object o) { """); } + // Below the root of the type, the source line of BELOW_ROOT gets no caret and no source supertype + // line (#2197). @Test public void aWildcardFromTheSubclassDeclarationIsNamedOnlyWhereALinePrintsIt() { assertMessages( diff --git a/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java b/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java index d0b7882c70..3dec5d892a 100644 --- a/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java +++ b/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java @@ -611,7 +611,7 @@ public void deeplyNestedTypeAnnot() { @NullMarked public class Test { void testPositive(NestedAnnots> p) { - // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots -> type argument for T of NestedAnnots: a non-wildcard type argument must have the same nullness in source and target; source has String where target requires @Nullable String + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots -> type argument for T of NestedAnnots: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String NestedAnnots.deeplyNested(p); } void testNegative(NestedAnnots> p) { @@ -813,7 +813,7 @@ void testPositive() { NestedAnnots.multipleArgs( // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots: source has @Nullable String where target requires String new NestedAnnots<@Nullable String>(), - // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots: a non-wildcard type argument must have the same nullness in source and target; source has Integer where target requires @Nullable Integer + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots: a non-wildcard type argument must have the same nullability in source and target; source has Integer where target requires @Nullable Integer new NestedAnnots()); } void testNegative() { From 1ddcbcfa4f2db02a878f0f5fdacb26d4a96f419e Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Mon, 30 Nov 2026 23:46:59 +0300 Subject: [PATCH 40/43] Test the class check of a source caret, and correct comments A source caret was placed only on a node of the class the comparison steps from. No test checked that: mutation testing removed the check and every test still passed, because the one input that reaches it, an intersection source whose other component holds a type argument at the same index, asserted only the first line. ViewedSourceTests now asserts the whole message for it; with the check removed, the caret moves under the type argument of the other component. childByPosition returns null for the enclosing type of a top-level class, which nearly every message reaches; its Javadoc now says so, and the diff-coverage marker that called the branch unreached is gone. A test key in NoteTests that pins a missing note below the enclosing type of a subclass bound is renamed to say the note is missing, and a comment explains why. The TypePath class comment no longer says every step is one the printer takes, and a comment in TraversalCostTests is rewrapped. Assisted-by: Claude Code (claude-opus-5-5) --- .../generics/NullabilityMismatches.java | 5 ++-- .../com/uber/nullaway/generics/TypePath.java | 3 +- .../jspecify/mismatchmessage/NoteTests.java | 7 +++-- .../mismatchmessage/TraversalCostTests.java | 3 +- .../mismatchmessage/ViewedSourceTests.java | 29 +++++++++++++++++++ 5 files changed, 40 insertions(+), 7 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 05f103438d..3dcd6115d9 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java @@ -454,7 +454,8 @@ yield new Track( * Returns the child {@code step} reaches from the written node of {@code track}, where that node * is of the kind the step descends from: a class type of the class the comparison stepped from * for a type argument or an enclosing type, an array for an array element, and a wildcard for a - * bound. Returns {@code null} where it is of another kind. + * bound. Returns {@code null} where it is of another kind, and for the enclosing type of a + * top-level class, which is not a class type. */ private static @Nullable Track childByPosition(Track track, ComparisonStep step) { Type node = track.node(); @@ -474,7 +475,7 @@ yield new Track( track.path(), null, new HiddenBound(step.child(), TypePath.root())) - : null; // diff-coverage: ignore -- the track stands at the node the check steps from + : null; } /** 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 aae884bb55..f4244f5f85 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java @@ -16,7 +16,8 @@ * 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. + * and the prose that names it in a diagnostic, which is why the steps are the kinds of descent the + * printer takes. */ final class TypePath { 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 1fe965cdd4..b04b792714 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 @@ -557,6 +557,9 @@ void captureOfAnotherTypeInBound() { // The check views SubL as Base, where U is @Nullable, and reports a false positive (#2206); a // note giving the bound T of SubL declares would contradict the first line. + // NO_NOTE_BELOW_AN_ENCLOSING_TYPE_OF_A_SUBCLASS_BOUND pins a known gap: the bound TopNested, + // viewed as Nested, does hold @Nullable String at X, but the walk to the note takes the enclosing + // type of TopNested itself, which has none, so no note is printed. @Test public void aHolderNoteIsPrintedOnlyWhereItsBoundHasTheNullnessTheCheckCompared() { assertMessages( @@ -639,7 +642,7 @@ public void aHolderNoteIsPrintedOnlyWhereItsBoundHasTheNullnessTheCheckCompared( ^^^^^^ note: the unbounded wildcard ? in Sub has the upper bound of type parameter T of Sub, which is @Nullable Object (JLS 5.1.10) """, - "SUBCLASS_BOUND_HAS_NO_ENCLOSING_TYPE", + "NO_NOTE_BELOW_AN_ENCLOSING_TYPE_OF_A_SUBCLASS_BOUND", """ incompatible nullability in type argument for T of Holder -> upper bound of wildcard -> enclosing type -> type argument for X of Enclosing: source has @Nullable String where target requires String source: TopSub @@ -717,7 +720,7 @@ static class TopNested extends Enclosing<@Nullable String>.Nested { static class Holder.Nested> {} static class TopSub extends Holder {} void subclassBoundHasNoEnclosingType(TopSub s) { - // BUG: Diagnostic matches: SUBCLASS_BOUND_HAS_NO_ENCLOSING_TYPE + // BUG: Diagnostic matches: NO_NOTE_BELOW_AN_ENCLOSING_TYPE_OF_A_SUBCLASS_BOUND Holder.Nested> h = s; } """); diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java index df48f9ad63..483ee0b87d 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java @@ -103,8 +103,7 @@ void test(List, @Nullable String>> l) { } // Each L passes its X on to both L in its bound, so the two sides differ at every level - // and - // no level shares a bound object with the other side. + // and no level shares a bound object with the other side. @Test(timeout = 30_000) public void aRejectedComparisonReachedAlongManyPathsIsWalkedOnce() { assertMessage( 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 aeafb9fbd8..712cec49b0 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 @@ -322,6 +322,35 @@ static void test(Object o) { """); } + // The written source is the capture of ? extends A<@Nullable String>, while the comparison steps + // into B; the type argument of A is not the one compared, so the source line gets no caret. + @Test + public void theTypeArgumentOfAnotherIntersectionComponentIsNotMarked() { + assertMessage( + """ + incompatible nullability in type argument for E of B: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String + source: capture of ? extends A<@Nullable String> + source supertype: B + ^^^^^^ + target: B<@Nullable String> + ^^^^^^^^^^^^^^^^ + """, + """ + interface A { E a(); } + interface B { E b(); } + interface Holder & B> { + T get(); + } + interface Factory { + Holder> fromA(); + } + static void test(Factory factory) { + // BUG: Diagnostic matches: MESSAGE + B<@Nullable String> result = factory.fromA().get(); + } + """); + } + // Below the root of the type, the source line of BELOW_ROOT gets no caret and no source supertype // line (#2197). @Test From d75bba59b68e9d6abcbe74364c65ef00f376078d Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Tue, 1 Dec 2026 00:25:02 +0300 Subject: [PATCH 41/43] Name the issue for the missing note below an enclosing type Assisted-by: Claude Code (claude-opus-5-5) --- .../com/uber/nullaway/jspecify/mismatchmessage/NoteTests.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 b04b792714..ba83593082 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 @@ -559,7 +559,7 @@ void captureOfAnotherTypeInBound() { // note giving the bound T of SubL declares would contradict the first line. // NO_NOTE_BELOW_AN_ENCLOSING_TYPE_OF_A_SUBCLASS_BOUND pins a known gap: the bound TopNested, // viewed as Nested, does hold @Nullable String at X, but the walk to the note takes the enclosing - // type of TopNested itself, which has none, so no note is printed. + // type of TopNested itself, which has none, so no note is printed (#2224). @Test public void aHolderNoteIsPrintedOnlyWhereItsBoundHasTheNullnessTheCheckCompared() { assertMessages( From c863efe2c3af37916f66d61dc8ffc3f222fe942b Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Tue, 1 Dec 2026 10:09:31 +0300 Subject: [PATCH 42/43] Keep the source caret on the written type and derive the note from one bound origin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Where the check viewed the source as a supertype and the differing node was also in the written type, as for an intersection bound, the caret moved to the `source supertype:` line and the `source:` line printed none. The note was built from two separate decisions, one on whether the wildcard's bound came from the class that declares the type parameter and one on whether that class is unannotated, so a captured wildcard two subclasses down was named as the type argument of a class it does not instantiate, and the `, and X is unannotated` ending appeared for a captured wildcard only. Below a hidden bound the note could name a bound whose declaration carries no nullness at the compared position (#2206). `boundOriginNote` now computes one `BoundOrigin` (the type parameter, its owner, and whether the owner is unannotated) and every kind of wildcard reads from it. `NullabilityMismatches.Frame` records the bound the walk entered below the last shown source node, whether or not a line marks that node, so the note checks the bound the check compared even below the root of a supertype view. User-visible: Where a `source supertype:` line is printed and the differing node is in the written type, the caret stays on the `source:` line. A note for an unbounded `?` or a `? super X` ends in `, and X is unannotated` where the class that declares the type parameter is unannotated, as the captured-wildcard note already did. A captured wildcard is named `the captured type argument for T of C` only where it fills `T` of `C`; otherwise the note reads `is a captured wildcard whose upper bound is …`. Below an implicit bound whose declaration has no nullness at the compared position, there is no note, also below the root of a supertype view (#2206). Assisted-by: Claude Code (claude-opus-5-5) --- .../generics/NullabilityMismatchMessage.java | 238 +++++++++++------- .../generics/NullabilityMismatches.java | 93 +++---- .../com/uber/nullaway/generics/TypePath.java | 11 +- .../LowerBoundAndRawSourceTests.java | 29 +++ .../jspecify/mismatchmessage/NoteTests.java | 206 ++++++++++++++- .../mismatchmessage/ViewedSourceTests.java | 197 ++++++++++++++- 6 files changed, 641 insertions(+), 133 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 72a881e29f..0d400435e6 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,6 @@ package com.uber.nullaway.generics; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Verify; import com.google.errorprone.VisitorState; import com.google.errorprone.util.ASTHelpers; @@ -63,8 +64,11 @@ * 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 non-wildcard type - * argument must have the same nullability in source and target. Where the target bounds a {@code ? - * super} wildcard, the target side reads {@code a supertype of} that bound. + * argument must have the same nullability in source and target. Where the check requires the source + * node to be a supertype of the target node, the target side reads {@code a supertype of} the + * target node. That holds at the lower bound of a {@code ? super} wildcard and at the positions + * compared inside it, as for {@code List>} against {@code List>}; inside a second {@code ? super} the sides turn back. * *

The caret

* @@ -77,15 +81,17 @@ * ArrayList<@Nullable String>} as a {@code List} carries the {@code @Nullable String} over; for * {@code class Sub extends Base>}, viewing a {@code Sub} as a {@code Base} * rebuilds the {@code List<@Nullable String>} from the declaration of {@code Sub}, which the - * written type does not hold. Where the source is viewed as a supertype at the root and the node is - * not in the written type, that view is printed as {@code source supertype} and carries the carets. - * Below the root, as for an element of {@code List}, no view is printed, and such a node gets - * no source caret. Two differences below one printed node share its caret, numbered for each. Where - * a marked node holds another marked node, as where a supertype view puts one type argument of the - * source at two positions, each node gets its own caret run, on one row per level of nesting with - * the outermost row first, and its number in a row below its run. A number starts under the first - * column of its run, and where it would run into the number before it, it goes on another row - * below, still above the carets of the next level. + * written type does not hold. Where the source is viewed as a supertype at the root and a node is + * not in the written type, that view is printed as {@code source supertype} and carries the carets + * of such nodes, while a node the written type holds keeps its caret on the {@code source} line, so + * each difference is marked on one source line. Below the root, as for an element of {@code + * List}, no view is printed, and such a node gets no source caret. Two differences below one + * printed node share its caret, numbered for each. Where a marked node holds another marked node, + * as where a supertype view puts one type argument of the source at two positions, each node gets + * its own caret run, on one row per level of nesting with the outermost row first, and its number + * in a row below its run. A number starts under the first column of its run, and where it would run + * into the number before it, it goes on another row below, still above the carets of the next + * level. * *

A note explains itself in the entities the message already shows. Where the source wildcard is * marked on a printed type, the type the reader wrote or the {@code source supertype} line, the @@ -94,15 +100,25 @@ * substituted, except a wildcard, whose type parameter keeps its name. Every other type argument * whose printed form contains {@code ?} or {@code <}, such as a wildcard or a parameterized type, * is printed as {@code ...}, so the one {@code ?} printed is the wildcard meant and a long type is - * not repeated. The check compares the wildcard as the class the target names holds it, so where a - * subclass bounds the type parameter otherwise, the bound of the printed class can have another - * nullness than the first line states, and then there is no note. Where it is marked on neither, as - * below the root of a supertype view, the type parameter belongs to a declaration this message - * never prints, and the note states the bound and stops. A note for a captured wildcard states the - * upper bound the check compared, and names a type parameter only where the caret's position on a - * printed type is the one the capture instantiates. 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 for the source a {@code note} says what the reader cannot see there. + * not repeated. Where the class of that type parameter is unannotated, the note says so. Where the + * wildcard is marked on neither printed type, as below the root of a supertype view, the type + * parameter belongs to a declaration this message never prints, and the note states the bound and + * stops. + * + *

The check takes the wildcard's bound from the class the target type names, not from the class + * that holds the wildcard on the printed type. For {@code SubL> extends + * Base}, a {@code SubL} compared with {@code Base>} takes the + * {@code @Nullable} bound of {@code Base}, while {@code SubL} declares a non-null one; a note there + * would contradict the first line, so there is none, for a written and a captured wildcard alike. A + * note for a captured wildcard states the upper bound the check compared, and names a type + * parameter only where the caret's position on a printed type is the one the capture instantiates. + * In {@code Map}, from a {@code List} passed to {@code Map + * duplicate(List)}, each capture instantiates {@code E} of {@code List} while the caret's step + * is {@code K} or {@code V} of {@code Map}, so the note names no type parameter. Where that bound + * would print a capture, or a type parameter of a class the note does not name, there is no note. + * 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 for the source a {@code + * note} says what the reader cannot see there. */ final class NullabilityMismatchMessage { @@ -149,7 +165,7 @@ final class NullabilityMismatchMessage { * Called each time {@link #build} starts, or {@code null} where nobody listens. A test sets it to * count the messages built, since building one reruns the nullability check over both types. */ - static @Nullable Runnable buildListener; + @VisibleForTesting static volatile @Nullable Runnable buildListener; /** * Builds the diagnostic for an assignment, a return, or an argument the nullability check @@ -195,10 +211,16 @@ String build(Type targetType, Type sourceType) { } else { printedView = viewedSource; // a node the check compared is at no position of the type the reader wrote, so the view of - // it the check did compare is printed too and carries the carets + // it the check did compare is printed too and carries the carets of such nodes labelWidth = SOURCE_SUPERTYPE_LABEL.length(); message.append( - markedTypeLines(SOURCE_LABEL, labelWidth, sourceType, List.of(), numbered).lines()); + markedTypeLines( + SOURCE_LABEL, + labelWidth, + sourceType, + carets(listed, NullabilityMismatches.Mismatch::sourceCaret), + numbered) + .lines()); message.append( markedTypeLines( SOURCE_SUPERTYPE_LABEL, @@ -270,8 +292,9 @@ private boolean mustMatchExactly(NullabilityMismatches.Mismatch mismatch) { } /** - * Names what the target requires of the source at {@code mismatch}: the target node, or for the - * lower bound of a {@code ? super} wildcard, a supertype of it. + * Names what the target requires of the source at {@code mismatch}: the target node, or {@code a + * supertype of} it where the check requires the source node to be a supertype of it, as at the + * lower bound of a {@code ? super} wildcard and at the positions compared inside it. */ private String targetRequirement(NullabilityMismatches.Mismatch mismatch) { String target = GenericsChecks.prettyTypeForError(mismatch.targetNode(), state); @@ -435,12 +458,17 @@ private static StringBuilder padTo(StringBuilder line, int column) { /** * Returns where {@code mismatch} is marked on the {@code source supertype} line that prints - * {@code printedView}, or {@code null} where it is not marked there or no such line is printed. + * {@code printedView}, or {@code null} where it is not marked there. A mismatch with a caret in + * the written source is marked on the {@code source} line only, so each mismatch is marked on one + * source line, and its note describes the node marked there. */ private @Nullable TypePath printedViewCaret( NullabilityMismatches.Mismatch mismatch, @Nullable Type printedView) { Type view = mismatch.viewedSource(); - return printedView != null && view != null && ASTHelpers.isSameType(view, printedView, state) + return mismatch.sourceCaret() == null + && printedView != null + && view != null + && ASTHelpers.isSameType(view, printedView, state) ? mismatch.viewCaret() : null; } @@ -483,17 +511,18 @@ private String mismatchDetail( /** * Says what upper bound the source wildcard has and, where the message prints the type parameter * it comes from, names that parameter; returns {@code null} where the printed node is not a - * wildcard, its bound is written out, the bound the note would state disagrees with the nullness - * the check found, or the bound cannot be printed without a captured type or a type parameter of - * a class the note does not name. + * wildcard, its bound is written out, the bound the note would state lacks the nullness the check + * found at the compared position (#2206), or the bound cannot be printed without a captured type + * or a type parameter of a class the note does not name. * *

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 what it is reads the two bounds as a - * contradiction. For a captured wildcard the note also says when the class of the type parameter - * it names 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. + * contradiction. Both kinds take the same decision of where the bound comes from: the type + * parameter at the wildcard's position on the printed type that marks it, which for a capture + * must also be the one the capture instantiates. Where that parameter's class is unannotated, the + * note says so, 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, @Nullable Type printedView) { @@ -530,23 +559,22 @@ && nodeAt(printed, Objects.requireNonNull(caret.parent()).steps()) reachingStep.formal(), boundWithStatedArgumentsSubstituted(holderClass, reachingStep.index())); } - Type.TypeVar formalTypeVariable = holder == null ? null : holder.formal(); - Symbol.ClassSymbol owner = typeVariableOwner(formalTypeVariable); + BoundOrigin origin = boundOrigin(holder, wildcard, printedNode); + NullabilityMismatches.HiddenBound hidden = mismatch.sourceHiddenBound(); // the check compares the wildcard as the class the target names holds it, and where that class // bounds its type parameter otherwise than the holder does, a note about the holder's type // parameter would contradict the first line (#2206) - NullabilityMismatches.HiddenBound hidden = mismatch.sourceHiddenBound(); - boolean declaredBoundAgrees = - holder != null - && (hidden == null - || hasNullnessAt(holder.declaredBound(), hidden.steps(), mismatch.sourceNode())); + if (origin != null + && hidden != null + && !hasNullnessAt(origin.holder().declaredBound(), hidden.steps(), mismatch.sourceNode())) { + return null; + } if (printedNode instanceof Type.CapturedType capture) { return capturedWildcardNote( capture, wildcard, holder == null ? null : holder.type(), - declaredBoundAgrees ? formalTypeVariable : null, - owner, + origin, hidden == null ? null : hidden.bound()); } if (wildcard.kind == BoundKind.EXTENDS) { @@ -561,32 +589,31 @@ && nodeAt(printed, Objects.requireNonNull(caret.parent()).steps()) : "the wildcard ? super " + GenericsChecks.prettyTypeForError(wildcard.type, state); String hasBound = unbounded ? " has the upper bound" : " has no upper bound of its own; its upper bound is"; - if (formalTypeVariable == null || owner == null || holder == null) { + if (origin == null) { // no type parameter this message prints stands behind the bound: the wildcard sits at no // position of a printed type, as below the root of a supertype view (#2197), or the variable // it instantiates has no named owner. The note says what the bound is and leaves where it // came from alone. "in the source" tells it from a wildcard of the target; below the root the // ? itself is in a declaration this message does not print Type upperBound = GenericsUtils.wildcardUpperBound(wildcard, state, config, handler); - if (printsTypeVariable(upperBound, Type.CapturedType.class::isInstance)) { - return null; + if (printsTypeVariable(upperBound, Type.CapturedType.class::isInstance) + || (hidden != null + && !hasNullnessAt(upperBound, hidden.steps(), mismatch.sourceNode()))) { + return null; // a bound without the compared nullness contradicts the first line (#2206) } return String.format( "%s in the source%s %s (JLS 5.1.10)", source, hasBound, GenericsChecks.prettyTypeForError(upperBound, state)); } - if (!declaredBoundAgrees) { - return null; - } return String.format( - "%s in %s%s %s type parameter %s of %s, which is %s (JLS 5.1.10)", + "%s in %s%s %s type parameter %s, which is %s (JLS 5.1.10)%s", source, - withOtherTypeArgumentsElided(holder.type(), holder.index()), + withOtherTypeArgumentsElided(origin.holder().type(), origin.holder().index()), hasBound, unbounded ? "of" : "the bound of", - formalTypeVariable.tsym.getSimpleName(), - owner.getSimpleName(), - GenericsChecks.prettyTypeForError(holder.declaredBound(), state)); + origin.named(), + GenericsChecks.prettyTypeForError(origin.holder().declaredBound(), state), + origin.unannotatedEnding()); } /** @@ -601,11 +628,69 @@ && nodeAt(printed, Objects.requireNonNull(caret.parent()).steps()) private record PrintedHolder( Type.ClassType type, int index, Type.@Nullable TypeVar formal, Type declaredBound) {} + /** + * The type parameter a note names as where the source wildcard takes its upper bound from. + * + * @param holder the printed class type that holds the wildcard at that type parameter's position + * @param formal the type parameter + * @param owner the class of {@code formal} + * @param unannotated whether {@code owner} is unannotated, in NullAway's sense + */ + private record BoundOrigin( + PrintedHolder holder, Type.TypeVar formal, Symbol.ClassSymbol owner, boolean unannotated) { + + /** Names the type parameter as {@code T of Map}. */ + String named() { + return formal.tsym.getSimpleName() + " of " + owner.getSimpleName(); + } + + /** Returns the ending a note takes where {@link #owner} is unannotated, or an empty string. */ + String unannotatedEnding() { + return unannotated ? String.format(", and %s is unannotated", owner.getSimpleName()) : ""; + } + } + + /** + * Returns the type parameter of {@code holder} that the source wildcard takes its upper bound + * from, or {@code null} where no type parameter the message prints is that one: {@code holder} is + * {@code null}, its step records no type parameter, the type parameter has no named class, or + * {@code printedNode} is a capture whose wildcard was last substituted for another type + * parameter. + * + * @param printedNode the wildcard or capture under the caret + * @param wildcard {@code printedNode} as a wildcard, the captured one for a capture + */ + private @Nullable BoundOrigin boundOrigin( + @Nullable PrintedHolder holder, Type.WildcardType wildcard, Type printedNode) { + if (holder == null) { + return null; + } + Type.TypeVar formal = holder.formal(); + Symbol.ClassSymbol owner = typeVariableOwner(formal); + if (formal == null || owner == null) { + return null; + } + // a capture made elsewhere can stand at this position, as where duplicate(List) substitutes + // a capture of List for K of Map. WildcardType.bound names the type parameter the wildcard + // was last substituted for, which need not be the one at this position, so it only confirms + // the caret's type parameter and never names one by itself + Type.TypeVar instantiated = wildcard.bound; + if (printedNode instanceof Type.CapturedType + && (instantiated == null || !instantiated.tsym.equals(formal.tsym))) { + return null; + } + return new BoundOrigin( + holder, + formal, + owner, + GenericsUtils.fromUnannotatedMethodOrClass(formal.tsym, config, handler, state)); + } + /** * Returns the note for a captured wildcard: its upper bound as the check compared it, and the - * type parameter it is the type argument for where the caller names one and the captured wildcard - * instantiates that same one; {@code null} where the bound cannot be printed without a capture or - * a type parameter the note does not name the class of. + * type parameter it is the type argument for where {@code origin} names one; {@code null} where + * the bound cannot be printed without a capture or a type parameter the note does not name the + * class of. * *

The caret

* @@ -84,14 +86,17 @@ * written type does not hold. Where the source is viewed as a supertype at the root and a node is * not in the written type, that view is printed as {@code source supertype} and carries the carets * of such nodes, while a node the written type holds keeps its caret on the {@code source} line, so - * each difference is marked on one source line. Below the root, as for an element of {@code - * List}, no view is printed, and such a node gets no source caret. Two differences below one - * printed node share its caret, numbered for each. Where a marked node holds another marked node, - * as where a supertype view puts one type argument of the source at two positions, each node gets - * its own caret run, on one row per level of nesting with the outermost row first, and its number - * in a row below its run. A number starts under the first column of its run, and where it would run - * into the number before it, it goes on another row below, still above the carets of the next - * level. + * each difference is marked on one source line. The {@code source supertype} line is printed only + * where it carries a caret. Below the root, as for an element of {@code List}, no view is + * printed, and such a node gets no source caret. Two differences below one printed node share its + * caret, numbered for each. A captured wildcard and an intersection are each one node: the caret + * marks the whole, never a part of it. Numbers follow the order of the entries, which is the order + * of their positions on the target line, so on the source lines a higher number can come before a + * lower one. Where a marked node holds another marked node, as where a supertype view puts one type + * argument of the source at two positions, each node gets its own caret run, on one row per level + * of nesting with the outermost row first, and its number in a row below its run. A number starts + * under the first column of its run, and where it would run into the number before it, it goes on + * another row below, still above the carets of the next level. * *

A note explains itself in the entities the message already shows. Where the source wildcard is * marked on a printed type, the type the reader wrote or the {@code source supertype} line, the @@ -100,25 +105,37 @@ * substituted, except a wildcard, whose type parameter keeps its name. Every other type argument * whose printed form contains {@code ?} or {@code <}, such as a wildcard or a parameterized type, * is printed as {@code ...}, so the one {@code ?} printed is the wildcard meant and a long type is - * not repeated. Where the class of that type parameter is unannotated, the note says so. Where the - * wildcard is marked on neither printed type, as below the root of a supertype view, the type - * parameter belongs to a declaration this message never prints, and the note states the bound and - * stops. + * not repeated. * - *

The check takes the wildcard's bound from the class the target type names, not from the class - * that holds the wildcard on the printed type. For {@code SubL> extends - * Base}, a {@code SubL} compared with {@code Base>} takes the - * {@code @Nullable} bound of {@code Base}, while {@code SubL} declares a non-null one; a note there - * would contradict the first line, so there is none, for a written and a captured wildcard alike. A - * note for a captured wildcard states the upper bound the check compared, and names a type - * parameter only where the caret's position on a printed type is the one the capture instantiates. - * In {@code Map}, from a {@code List} passed to {@code Map - * duplicate(List)}, each capture instantiates {@code E} of {@code List} while the caret's step - * is {@code K} or {@code V} of {@code Map}, so the note names no type parameter. Where that bound - * would print a capture, or a type parameter of a class the note does not name, there is no note. - * 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 for the source a {@code - * note} says what the reader cannot see there. + *

A note ends by saying that the bound is {@code @Nullable} because the class of the compared + * type parameter is unannotated where three things hold. The types differ at the bound itself, not + * below it. The compared bound is {@code @Nullable} solely through NullAway's default for + * unannotated code, which it loses where capture conversion replaces it with a type argument, as + * for {@code B extends A}. The bound of the type parameter the note names is {@code @Nullable} the + * same way. A bound with a nullness annotation of its own gets no such ending. + * + *

Where the wildcard is marked on neither printed type, as below the root of a supertype view, + * the type parameter belongs to a declaration this message never prints, and the note states the + * bound and stops. + * + *

The check takes the wildcard's bound from the type parameter at its position in the class the + * check compared there, which is the class the target type names, not the class that holds the + * wildcard on the printed type (#2206). For {@code Base} and {@code + * SubL> extends Base}, a {@code SubL} compared with {@code Base>} takes the {@code @Nullable Object} bound of {@code U}, while {@code T} + * declares {@code List}. A note would attribute the compared bound to the wildcard's own + * type parameter, so there is a note only where that type parameter's declared bound prints as the + * compared bound does, {@code @Nullable} at every node included. A subtype with the same nullness, + * such as {@code @Nullable List} for {@code @Nullable Object}, gets no note. This holds for + * a written and a captured wildcard alike. A note for a captured wildcard states the upper bound + * the check compared, and names a type parameter only where the caret's position on a printed type + * is the one the capture instantiates. In {@code Map}, from a {@code + * List} passed to {@code Map duplicate(List)}, each capture instantiates {@code E} + * of {@code List} while the caret's step is {@code K} or {@code V} of {@code Map}, so the note + * names no type parameter. Where that bound would print a capture, or a type parameter of a class + * the note does not name, there is no note. 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 for the source a {@code note} says what the reader cannot see there. */ final class NullabilityMismatchMessage { @@ -204,14 +221,24 @@ String build(Type targetType, Type sourceType) { carets(listed, NullabilityMismatches.Mismatch::sourceCaret), numbered); Type viewedSource = sharedView(listed); + // a node the check compared can be at no position of the type the reader wrote, and then the + // view of the source the check did compare carries its caret. The view is printed only where + // it marks a node, since that is all it is printed for + MarkedType view = + viewedSource == null + ? null + : markedTypeLines( + SOURCE_SUPERTYPE_LABEL, + SOURCE_SUPERTYPE_LABEL.length(), + viewedSource, + carets(listed, mismatch -> printedViewCaret(mismatch, viewedSource)), + numbered); int labelWidth = TYPE_LABEL_WIDTH; Type printedView = null; - if (source.marksPlaced() == listed.size() || viewedSource == null) { + if (view == null || view.marksPlaced() == 0) { message.append(source.lines()); } else { printedView = viewedSource; - // a node the check compared is at no position of the type the reader wrote, so the view of - // it the check did compare is printed too and carries the carets of such nodes labelWidth = SOURCE_SUPERTYPE_LABEL.length(); message.append( markedTypeLines( @@ -221,14 +248,7 @@ String build(Type targetType, Type sourceType) { carets(listed, NullabilityMismatches.Mismatch::sourceCaret), numbered) .lines()); - message.append( - markedTypeLines( - SOURCE_SUPERTYPE_LABEL, - labelWidth, - viewedSource, - carets(listed, mismatch -> printedViewCaret(mismatch, viewedSource)), - numbered) - .lines()); + message.append(view.lines()); } message.append( markedTypeLines( @@ -511,18 +531,20 @@ private String mismatchDetail( /** * Says what upper bound the source wildcard has and, where the message prints the type parameter * it comes from, names that parameter; returns {@code null} where the printed node is not a - * wildcard, its bound is written out, the bound the note would state lacks the nullness the check - * found at the compared position (#2206), or the bound cannot be printed without a captured type - * or a type parameter of a class the note does not name. + * wildcard, its bound is written out, the check compared no bound below it, the wildcard's own + * type parameter declares a bound other than the one the check compared (#2206), or the bound + * cannot be printed without a captured type or a type parameter of a class the note does not + * name. * *

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 what it is reads the two bounds as a * contradiction. Both kinds take the same decision of where the bound comes from: the type * parameter at the wildcard's position on the printed type that marks it, which for a capture - * must also be the one the capture instantiates. Where that parameter's class is unannotated, the - * note says so, 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. + * must also be the one the capture instantiates. Where the class's default explains the + * difference, as {@link #boundOrigin} decides, the note says that the bound is {@code @Nullable} + * because the class is unannotated: that is 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, @Nullable Type printedView) { @@ -530,7 +552,10 @@ private String mismatchDetail( // looking at a wildcard and reading that the source has a bound the wildcard does not print Type printedNode = mismatch.sourcePrintedNode(); Type.WildcardType wildcard = GenericsUtils.asWildcard(printedNode); - if (wildcard == null) { + // the note states the bound the check compared, so it has nothing to say where the check did + // not go below the wildcard + NullabilityMismatches.HiddenBound hidden = mismatch.sourceHiddenBound(); + if (wildcard == null || hidden == null) { return null; } // the step that reached the wildcard in the printed type that marks it names the type parameter @@ -559,23 +584,21 @@ && nodeAt(printed, Objects.requireNonNull(caret.parent()).steps()) reachingStep.formal(), boundWithStatedArgumentsSubstituted(holderClass, reachingStep.index())); } - BoundOrigin origin = boundOrigin(holder, wildcard, printedNode); - NullabilityMismatches.HiddenBound hidden = mismatch.sourceHiddenBound(); - // the check compares the wildcard as the class the target names holds it, and where that class - // bounds its type parameter otherwise than the holder does, a note about the holder's type - // parameter would contradict the first line (#2206) - if (origin != null - && hidden != null - && !hasNullnessAt(origin.holder().declaredBound(), hidden.steps(), mismatch.sourceNode())) { + // compared: the type parameter whose bound the check compared, recorded where it compared it. + // own: the wildcard's own type parameter, the one at its position on the printed type that + // marks it, or, where no printed type does, the one javac links the wildcard to + Type.TypeVar compared = hidden.formal(); + Type.TypeVar own = holder != null && holder.formal() != null ? holder.formal() : wildcard.bound; + if (own != null && compared != null && !boundsAgree(own, compared)) { + // the note would attribute the compared bound to a type parameter that declares another + // (#2206) return null; } - if (printedNode instanceof Type.CapturedType capture) { + BoundOrigin origin = + compared == null ? null : boundOrigin(holder, compared, wildcard, printedNode, hidden); + if (printedNode instanceof Type.CapturedType) { return capturedWildcardNote( - capture, - wildcard, - holder == null ? null : holder.type(), - origin, - hidden == null ? null : hidden.bound()); + wildcard, holder == null ? null : holder.type(), origin, hidden.bound()); } if (wildcard.kind == BoundKind.EXTENDS) { return null; // diff-coverage: ignore -- a caret goes below a written bound @@ -595,11 +618,9 @@ && nodeAt(printed, Objects.requireNonNull(caret.parent()).steps()) // it instantiates has no named owner. The note says what the bound is and leaves where it // came from alone. "in the source" tells it from a wildcard of the target; below the root the // ? itself is in a declaration this message does not print - Type upperBound = GenericsUtils.wildcardUpperBound(wildcard, state, config, handler); - if (printsTypeVariable(upperBound, Type.CapturedType.class::isInstance) - || (hidden != null - && !hasNullnessAt(upperBound, hidden.steps(), mismatch.sourceNode()))) { - return null; // a bound without the compared nullness contradicts the first line (#2206) + Type upperBound = hidden.bound(); + if (printsTypeVariable(upperBound, Type.CapturedType.class::isInstance)) { + return null; } return String.format( "%s in the source%s %s (JLS 5.1.10)", @@ -634,19 +655,30 @@ private record PrintedHolder( * @param holder the printed class type that holds the wildcard at that type parameter's position * @param formal the type parameter * @param owner the class of {@code formal} - * @param unannotated whether {@code owner} is unannotated, in NullAway's sense + * @param unannotatedClass the class of the type parameter whose bound the check compared, where + * NullAway's default for unannotated code explains the difference, as {@link #boundOrigin} + * decides; {@code null} otherwise */ private record BoundOrigin( - PrintedHolder holder, Type.TypeVar formal, Symbol.ClassSymbol owner, boolean unannotated) { + PrintedHolder holder, + Type.TypeVar formal, + Symbol.ClassSymbol owner, + Symbol.@Nullable ClassSymbol unannotatedClass) { /** Names the type parameter as {@code T of Map}. */ String named() { return formal.tsym.getSimpleName() + " of " + owner.getSimpleName(); } - /** Returns the ending a note takes where {@link #owner} is unannotated, or an empty string. */ + /** + * Returns the ending a note takes where {@link #unannotatedClass} is set, or an empty string. + */ String unannotatedEnding() { - return unannotated ? String.format(", and %s is unannotated", owner.getSimpleName()) : ""; + return unannotatedClass == null + ? "" + : String.format( + "; the bound is @Nullable because %s is unannotated", + unannotatedClass.getSimpleName()); } } @@ -654,14 +686,28 @@ String unannotatedEnding() { * Returns the type parameter of {@code holder} that the source wildcard takes its upper bound * from, or {@code null} where no type parameter the message prints is that one: {@code holder} is * {@code null}, its step records no type parameter, the type parameter has no named class, or - * {@code printedNode} is a capture whose wildcard was last substituted for another type - * parameter. + * {@code printedNode} is a capture that does not instantiate the type parameter at the caret's + * position, because javac records no type parameter for its wildcard or records another one. * + *

The type parameter carries the class of {@code compared} as the class to call unannotated + * where three things hold: the types differ at {@code hidden.bound()} itself, not below it; that + * bound keeps the class {@code compared} declares, so capture conversion did not replace it; and + * both it and the declared bound of the named type parameter are {@code @Nullable} solely through + * the annotation NullAway adds for unannotated code. + * + * @param compared the type parameter whose bound the check compared for the wildcard, which the + * caller has found to declare the bound the type parameter of {@code holder} declares * @param printedNode the wildcard or capture under the caret * @param wildcard {@code printedNode} as a wildcard, the captured one for a capture + * @param hidden the bound the check compared for the wildcard, and the steps from it to the node + * where the two types differ */ private @Nullable BoundOrigin boundOrigin( - @Nullable PrintedHolder holder, Type.WildcardType wildcard, Type printedNode) { + @Nullable PrintedHolder holder, + Type.TypeVar compared, + Type.WildcardType wildcard, + Type printedNode, + NullabilityMismatches.HiddenBound hidden) { if (holder == null) { return null; } @@ -679,11 +725,57 @@ String unannotatedEnding() { && (instantiated == null || !instantiated.tsym.equals(formal.tsym))) { return null; } - return new BoundOrigin( - holder, - formal, - owner, - GenericsUtils.fromUnannotatedMethodOrClass(formal.tsym, config, handler, state)); + // the ending says why the compared bound is @Nullable, so that @Nullable has to be the one + // NullAway adds for unannotated code, both on the bound the check compared and on the bound of + // the type parameter the note names. NullAway adds that default only to a bound that keeps the + // class its type parameter declares; a bound capture conversion replaced, as B extends A with + // A instantiated, takes its nullness from the type argument, written or inferred. That default + // sits on the bound itself, so it explains the mismatch only where the types differ there + Type comparedBound = hidden.bound(); + Symbol.ClassSymbol comparedClass = typeVariableOwner(compared); + boolean unannotated = + comparedClass != null + && hidden.steps().isRoot() + && GenericsUtils.fromUnannotatedMethodOrClass(compared.tsym, config, handler, state) + && comparedBound.tsym.equals(compared.getUpperBound().tsym) + && GenericsUtils.hasSyntheticNullable(comparedBound, state) + && GenericsUtils.hasSyntheticNullable( + GenericsUtils.declaredUpperBound(formal, state, config, handler), state); + return new BoundOrigin(holder, formal, owner, unannotated ? comparedClass : null); + } + + /** + * Whether {@code named}, the type parameter a note would name, declares the bound the check + * compared for {@code compared}: it is {@code compared}, or its declared upper bound prints as + * the bound {@code compared} declares, {@code @Nullable} at every node included. A subtype of + * that bound does not agree, even with the same nullness at the top level. The bound of {@code + * compared} refers to the type parameters of its class, and where the class of {@code named} + * extends that class, they are replaced by the type arguments it passes, as {@code SubSelf> extends Self} passes {@code U} for the {@code T} of {@code Self>}. + */ + private boolean boundsAgree(Type.TypeVar named, Type.TypeVar compared) { + if (named.tsym.equals(compared.tsym)) { + return true; + } + Types types = state.getTypes(); + Type namedBound = GenericsUtils.declaredUpperBound(named, state, config, handler); + Type comparedBound = GenericsUtils.declaredUpperBound(compared, state, config, handler); + if (compared.tsym.owner instanceof Symbol.ClassSymbol comparedClass + && named.tsym.owner instanceof Symbol.ClassSymbol namedClass) { + Type passed = TypeSubstitutionUtils.asSuper(types, namedClass.type, comparedClass, config); + if (passed != null) { + comparedBound = + TypeSubstitutionUtils.subst( + types, + comparedBound, + comparedClass.type.getTypeArguments(), + passed.getTypeArguments(), + config); + } + } + return GenericsChecks.prettyTypeForError(namedBound, state) + .equals(GenericsChecks.prettyTypeForError(comparedBound, state)); } /** @@ -697,25 +789,21 @@ String unannotatedEnding() { * Comparable>}. Each capture among the type arguments of {@code holder} is printed as the type * parameter it instantiates. * - * @param holder the printed class type that holds {@code capture} as a type argument, or {@code - * null} where the wildcard sits at no position of a printed type + * @param wildcard the wildcard the capture was made from + * @param holder the printed class type that holds the capture as a type argument, or {@code null} + * where the wildcard sits at no position of a printed type * @param origin the type parameter the capture takes its bound from, or {@code null} where the * message prints none - * @param comparedBound the upper bound of the capture the check compared, or {@code null} where - * the check did not go below the capture + * @param comparedBound the upper bound of the capture the check compared */ private @Nullable String capturedWildcardNote( - Type.CapturedType capture, Type.WildcardType wildcard, Type.@Nullable ClassType holder, @Nullable BoundOrigin origin, - @Nullable Type comparedBound) { - Type upperBound = - comparedBound != null - ? comparedBound - : GenericsUtils.effectiveWildcardUpperBound(capture, state, config, handler); + Type comparedBound) { String captured = "capture of " + GenericsChecks.prettyTypeForError(wildcard, state); - String bound = printedCapturedBound(upperBound, holder, origin == null ? null : origin.owner()); + String bound = + printedCapturedBound(comparedBound, holder, origin == null ? null : origin.owner()); if (bound == null) { return null; } @@ -848,48 +936,6 @@ private Type boundWithStatedArgumentsSubstituted(Type.ClassType holder, int inde state.getTypes(), declared, from.toList(), to.toList(), config); } - /** - * Whether the node {@code steps} reach from {@code bound} has the nullness of {@code sourceNode}; - * {@code false} where a step finds no such node. A step into an upper bound goes into the bound - * of a wildcard, a capture, or a type variable. - */ - private boolean hasNullnessAt(Type bound, TypePath steps, Type sourceNode) { - Type node = bound; - for (TypePath.Step step : steps.steps()) { - node = - switch (step.kind()) { - case TYPE_ARGUMENT -> typeArgumentAt(node, step); - case WILDCARD_UPPER_BOUND -> - node instanceof Type.TypeVar typeVariable && !(node instanceof Type.CapturedType) - ? GenericsUtils.declaredUpperBound(typeVariable, state, config, handler) - : GenericsUtils.asWildcard(node) != null - ? GenericsUtils.effectiveWildcardUpperBound(node, state, config, handler) - : null; - case WILDCARD_LOWER_BOUND, ARRAY_ELEMENT, ENCLOSING_TYPE -> - TypePath.childAt(node, step.kind(), step.index()); - }; - if (node == null) { - return false; - } - } - return checks.isNullableAnnotated(node) == checks.isNullableAnnotated(sourceNode); - } - - /** - * Returns the type argument {@code step} reaches in {@code node}, viewed as the class whose type - * parameter the step names, or {@code null} where {@code node} has no such type argument. - */ - private @Nullable Type typeArgumentAt(Type node, TypePath.Step step) { - Type.TypeVar formal = step.formal(); - Type viewed = node; - if (formal != null - && formal.tsym.owner instanceof Symbol.ClassSymbol stepClass - && !node.tsym.equals(stepClass)) { - viewed = TypeSubstitutionUtils.asSuper(state.getTypes(), node, stepClass, config); - } - return viewed == null ? null : TypePath.childAt(viewed, step.kind(), step.index()); - } - /** * Returns the node of {@code root} that {@code steps} reach, or {@code null} where one of them * finds no such node. 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 c2d3ba1ff8..dd1190acc6 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java @@ -96,8 +96,12 @@ record Mismatch( * * @param bound the upper bound, as the check compared it * @param steps the steps from {@code bound}, named for the classes compared + * @param formal the type parameter whose declared bound the check took for the wildcard: the one + * at the wildcard's position in the class the check compared there. {@code null} where the + * check reached the wildcard by another step than into a type argument, and so took the bound + * from the type parameter javac links the wildcard to */ - record HiddenBound(Type bound, TypePath steps) {} + record HiddenBound(Type bound, TypePath steps, Type.@Nullable TypeVar formal) {} /** * The written type a comparison is followed in, and how far it could be followed. @@ -154,6 +158,8 @@ static Track lost(Track track) { * @param hiddenBound the bound below {@code sourceShown} the comparison went into, and the steps * it took there, or {@code null} where it has not gone below such a bound; once set, no later * step moves {@code sourceShown} + * @param sourceFormal the type parameter of the class the check compared that the source's last + * step reached, where that step went into a type argument; {@code null} after any other step * @param swapped whether the visitor's left side is the source, as inside the lower bound of a * {@code ? super} wildcard, where the check asks whether that bound is a subtype of the * source @@ -166,6 +172,7 @@ record Frame( @Nullable Track view, Type sourceShown, @Nullable HiddenBound hiddenBound, + Type.@Nullable TypeVar sourceFormal, boolean swapped) {} private Frame frame; @@ -190,6 +197,7 @@ record Frame( null, sourceType, null, + null, false); } @@ -237,6 +245,7 @@ Frame enterClassComparison(Type rhs, Type rhsView) { view, frame.sourceShown(), frame.hiddenBound(), + frame.sourceFormal(), frame.swapped()); return saved; } @@ -339,6 +348,7 @@ Frame enterLowerBounds( frame.view(), frame.sourceShown(), frame.hiddenBound(), + frame.sourceFormal(), !frame.swapped()); return saved; } @@ -396,18 +406,25 @@ private Frame enter(@Nullable ComparisonStep lhs, @Nullable ComparisonStep rhs) Track view = saved.view(); Type sourceShown = saved.sourceShown(); HiddenBound hiddenBound = saved.hiddenBound(); + Type.TypeVar sourceFormal = saved.sourceFormal(); if (sourceStep != null) { source = follow(source, sourceStep); view = view == null ? null : follow(view, sourceStep); if (hiddenBound != null) { hiddenBound = new HiddenBound( - hiddenBound.bound(), hiddenBound.steps().then(comparedStep(sourceStep))); - } else if (isShown(sourceStep.kind(), sourceStep.parent())) { + hiddenBound.bound(), + hiddenBound.steps().then(comparedStep(sourceStep)), + hiddenBound.formal()); + } else if (isShown(sourceStep)) { sourceShown = sourceStep.child(); } else { - hiddenBound = new HiddenBound(sourceStep.child(), TypePath.root()); + hiddenBound = new HiddenBound(sourceStep.child(), TypePath.root(), sourceFormal); } + sourceFormal = + sourceStep.kind() == TypePath.Step.Kind.TYPE_ARGUMENT + ? comparedStep(sourceStep).formal() + : null; } frame = new Frame( @@ -418,6 +435,7 @@ private Frame enter(@Nullable ComparisonStep lhs, @Nullable ComparisonStep rhs) view, sourceShown, hiddenBound, + sourceFormal, saved.swapped()); return saved; } @@ -434,14 +452,16 @@ private static TypePath.Step comparedStep(ComparisonStep step) { } /** - * Whether the printer shows the node {@code kind} steps to from {@code parent}: only the bound a - * wildcard states is printed, and the upper bound of {@code ?} and of {@code ? super X} is not. + * Whether the printer shows the node {@code step} reaches: only the bound a wildcard states is + * printed, and the upper bound of {@code ?} and of {@code ? super X} is not. It decides both + * where a track stops ({@link #follow}) and when {@link Frame#hiddenBound} is recorded, so the + * caret and the note describe one node. */ - private static boolean isShown(TypePath.Step.Kind kind, Type parent) { - if (kind != TypePath.Step.Kind.WILDCARD_UPPER_BOUND) { + private static boolean isShown(ComparisonStep step) { + if (step.kind() != TypePath.Step.Kind.WILDCARD_UPPER_BOUND) { return true; } - Type.WildcardType wildcard = GenericsUtils.asWildcard(parent); + Type.WildcardType wildcard = GenericsUtils.asWildcard(step.parent()); return wildcard != null && wildcard.kind == BoundKind.EXTENDS; } @@ -454,6 +474,10 @@ private static Track follow(Track track, ComparisonStep step) { case HIDDEN, LOST -> track; case DECLARED -> followDeclared(track, step); case LOCATED -> { + if (!isShown(step)) { + // the caret stays on the wildcard that hides the bound + yield new Track(Track.State.HIDDEN, track.node(), track.path(), null); + } Track child = childByPosition(track, step); yield child != null ? child : Track.lost(track); } @@ -473,14 +497,7 @@ private static Track follow(Track track, ComparisonStep step) { return null; } Type child = TypePath.childAt(node, step.kind(), step.index()); - if (child != null) { - return Track.located(child, track.path().then(comparedStep(step))); - } - // the upper bound of `?` and `? super X` is not printed, so the caret stays on the wildcard - return step.kind() == TypePath.Step.Kind.WILDCARD_UPPER_BOUND - && GenericsUtils.asWildcard(node) != null - ? new Track(Track.State.HIDDEN, node, track.path(), null) - : null; + return child == null ? null : Track.located(child, track.path().then(comparedStep(step))); } /** 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 index 8e64f16da4..1cd8d2cbd9 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java @@ -578,4 +578,48 @@ void fitting(OneAndTwo o) { } """); } + + @Test + public void anIntersectionIsMarkedOnceAsOneNode() { + assertMessages( + Map.of( + "INTERSECTION", + """ + incompatible nullability in type argument for E of List -> lower bound of wildcard: source has I1 & I2 where target requires a supertype of @Nullable C1 + source: List> + ^^^^^^^^^^^^^^^ + target: List + ^^^^^^^^^^^^ + """, + "INTERSECTION_BELOW_ANOTHER_TYPE_ARGUMENT", + """ + incompatible nullability in type argument for V of Map -> lower bound of wildcard: source has I1 & I2 where target requires a supertype of @Nullable C1 + source: Map> + ^^^^^^^^^^^^^^^ + target: Map + ^^^^^^^^^^^^ + """), + """ + interface I1 {} + interface I2 {} + static class C1 implements I1, I2 {} + static class C2 implements I1, I2 {} + static List of2(T a, T b) { + throw new RuntimeException(); + } + void intersection(C1 a, C2 b) { + var l = of2(a, b); + // BUG: Diagnostic matches: INTERSECTION + List t = l; + } + static Map mapOf2(T a, T b) { + throw new RuntimeException(); + } + void intersectionBelowAnotherTypeArgument(C1 a, C2 b) { + var m = mapOf2(a, b); + // BUG: Diagnostic matches: INTERSECTION_BELOW_ANOTHER_TYPE_ARGUMENT + Map t = m; + } + """); + } } 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 index 1899bdefe9..a495e09dde 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/MismatchMessageTestBase.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/MismatchMessageTestBase.java @@ -21,8 +21,8 @@ * not carry, such as a {@code note:} line. A failure prints the expected message beside every * diagnostic the compilation reported. * - *

Every diagnostic a test compares must also hold the invariants {@link #checkNotes} states, - * whatever message the test expects. + *

Every diagnostic a test compares must also hold the invariants {@link #checkInvariants} + * states, whatever message the test expects. */ abstract class MismatchMessageTestBase extends NullAwayTestsBase { @@ -99,12 +99,27 @@ class Test { /** * Returns a matcher for a diagnostic whose text, without the {@code [NullAway]} prefix and the * link line, equals {@code expected}. The matcher throws {@link AssertionError} on a diagnostic - * that breaks the invariants {@link #checkNotes} states. + * that breaks the invariants {@link #checkInvariants} states. */ static Predicate messageIs(String expected) { return new MessageIs(expected, null); } + /** + * Returns why {@code message} breaks the invariants every message holds, or an empty list where + * it holds them all: those of {@link #checkNotes}, {@link #checkUnannotatedClassWasCompared}, and + * {@link #checkCarets}. + * + * @param message the text of one diagnostic, without the {@code [NullAway]} prefix and the link + * line + */ + static List checkInvariants(String message) { + List violations = new ArrayList<>(checkNotes(message)); + violations.addAll(checkUnannotatedClassWasCompared(message)); + violations.addAll(checkCarets(message)); + return violations; + } + /** The first line of a message: the path to the mismatch and the type the source has there. */ private static final Pattern FIRST_LINE = Pattern.compile("incompatible nullability in (.*?): source has (.*?) where target requires"); @@ -154,8 +169,8 @@ static List checkNotes(String message) { || path.indexOf("upper bound of wildcard") != path.size() - 1) { return violations; } - boolean sourceNullable = firstLine.group(2).startsWith("@Nullable "); - if (lastBound.startsWith("@Nullable ") != sourceNullable) { + boolean sourceNullable = isTopLevelNullable(firstLine.group(2)); + if (isTopLevelNullable(lastBound) != sourceNullable) { violations.add( "the bound a note states must have the nullness the first line gives the source, got:\n" + message); @@ -177,11 +192,247 @@ static List checkNotes(String message) { return null; } + /** The path the first line names, without the count of the other differing positions. */ + private static final Pattern FIRST_LINE_PATH = + Pattern.compile( + "^incompatible nullability in (.*?)(?: and \\d+ other differing positions?)?:" + + " (?:source has|a non-wildcard)"); + + /** The {@code path:} line of a numbered entry. */ + private static final Pattern ENTRY_PATH = Pattern.compile("^\\s*\\d+\\. path: (.*)$"); + + /** The class a note names as unannotated, which makes the bound it states {@code @Nullable}. */ + private static final Pattern UNANNOTATED_CLASS = + Pattern.compile("the bound is @Nullable because (\\w+) is unannotated"); + + /** The step of a path into a type argument, naming the type parameter there. */ + private static final String TYPE_ARGUMENT_STEP = "type argument for "; + + /** The step of a path into the upper bound of a wildcard. */ + private static final String UPPER_BOUND_STEP = "upper bound of wildcard"; + + /** + * Returns why {@code message} breaks this invariant, or an empty list where it holds it: a note + * that blames an unannotated class for the {@code @Nullable} bound it states names the class of a + * type parameter whose bound the check compared. Such a type parameter is one the path of the + * note's mismatch steps into just before an {@code upper bound of wildcard} step. A note under a + * numbered entry belongs to that entry's {@code path:}, and any other note to the path the first + * line names. Such a note also states a bound that is {@code @Nullable} at its top level, since + * an unannotated class keeps an explicit {@code @NonNull}, and belongs to a path that ends in the + * {@code upper bound of wildcard} step, since NullAway's default for unannotated code makes only + * the bound itself {@code @Nullable} and explains no difference below it. + * + * @param message the text of one diagnostic, without the {@code [NullAway]} prefix and the link + * line + */ + static List checkUnannotatedClassWasCompared(String message) { + List violations = new ArrayList<>(); + String[] lines = message.split("\n", -1); + Matcher first = FIRST_LINE_PATH.matcher(lines[0]); + String path = first.find() ? first.group(1) : ""; + for (String line : lines) { + Matcher entry = ENTRY_PATH.matcher(line); + if (entry.matches()) { + path = entry.group(1); + continue; + } + Matcher note = NOTE.matcher(line); + Matcher blamed = UNANNOTATED_CLASS.matcher(line); + if (!note.matches() || !blamed.find()) { + continue; + } + List compared = new ArrayList<>(); + List steps = List.of(path.split(" -> ")); + for (int i = 1; i < steps.size(); i++) { + if (steps.get(i).equals(UPPER_BOUND_STEP) + && steps.get(i - 1).startsWith(TYPE_ARGUMENT_STEP)) { + String parameter = steps.get(i - 1).substring(TYPE_ARGUMENT_STEP.length()); + compared.add(parameter.substring(parameter.indexOf(" of ") + " of ".length())); + } + } + if (!steps.get(steps.size() - 1).equals(UPPER_BOUND_STEP)) { + violations.add( + "a note that says the bound is @Nullable must belong to a mismatch at the bound itself," + + " got:\n" + + message); + } + if (!compared.contains(blamed.group(1))) { + violations.add( + String.format( + "a note must blame only a class whose type parameter's bound the check compared," + + " one of %s, and it blames %s:%n%s", + compared, blamed.group(1), message)); + } + int citation = note.group(1).indexOf(CITATION); + String bound = citation < 0 ? null : statedBound(note.group(1).substring(0, citation)); + if (bound == null || !isTopLevelNullable(bound)) { + violations.add( + "a note that says the bound is @Nullable must state a @Nullable bound, got:\n" + + message); + } + } + return violations; + } + + /** + * Whether {@code printed}, a printed type, is {@code @Nullable} at its top level, where the + * printer puts that annotation: before a class type, before the last simple name of an inner + * class type ({@code Outer.@Nullable Inner}), or, for an array type, on its last + * dimension, which the printer writes outermost last ({@code String @Nullable []}); an annotation + * anywhere else in an array type is on a component. + */ + static boolean isTopLevelNullable(String printed) { + if (printed.endsWith("[]")) { + return printed.endsWith(" @Nullable []"); + } + if (printed.startsWith("@Nullable ")) { + return true; + } + // a qualified name is annotated at its innermost class where the last "." outside every type + // argument list starts ".@Nullable " + int depth = 0; + int last = -1; + for (int i = 0; i < printed.length(); i++) { + char c = printed.charAt(i); + if (c == '<') { + depth++; + } else if (c == '>') { + depth--; + } else if (depth == 0 && c == '.') { + last = printed.startsWith(".@Nullable ", i) ? i : -1; + } + } + return last >= 0; + } + + /** + * Whether {@code printed}, a printed type, is an intersection: it holds {@code &} outside the + * angle brackets of every type argument list. + */ + private static boolean isIntersection(String printed) { + int depth = 0; + for (int i = 0; i < printed.length(); i++) { + char c = printed.charAt(i); + if (c == '<') { + depth++; + } else if (c == '>') { + depth--; + } else if (c == '&' && depth == 0) { + return true; + } + } + return false; + } + + /** A line that prints a type: the source, the supertype of it the check compared, the target. */ + private static final Pattern TYPE_LINE = + Pattern.compile("^ (source supertype|source|target): "); + + /** A row of carets under a type line. */ + private static final Pattern CARET_ROW = Pattern.compile("^ +[\\^ ]*\\^[\\^ ]*$"); + + /** A row of mismatch numbers under a row of carets. */ + private static final Pattern NUMBER_ROW = Pattern.compile("^ +[0-9][0-9, ]*$"); + + /** A run of carets in a caret row. */ + private static final Pattern CARET_RUN = Pattern.compile("\\^+"); + + /** + * Returns why {@code message} breaks these invariants, or an empty list where it holds them: + * + *

    + *
  • a {@code source supertype} line carries a caret, since a caret is what it is printed for; + *
  • a message with one mismatch puts at most one caret run under each type line, and in a + * numbered message each number appears at most once under each type line, and at most once + * under the two source lines together, so one position gets one mark; + *
  • in a numbered message, every numbered entry has its number under the {@code target} line, + * except where the target is an intersection, which has no caret yet (#2202). + *
+ * + * @param message the text of one diagnostic, without the {@code [NullAway]} prefix and the link + * line + */ + static List checkCarets(String message) { + List violations = new ArrayList<>(); + String[] lines = message.split("\n", -1); + int entries = 0; + for (String line : lines) { + if (ENTRY_PATH.matcher(line).matches()) { + entries++; + } + } + List sourceNumbers = new ArrayList<>(); + for (int i = 0; i < lines.length; i++) { + Matcher typeLine = TYPE_LINE.matcher(lines[i]); + if (!typeLine.find()) { + continue; + } + String label = typeLine.group(1); + int runs = 0; + List numbers = new ArrayList<>(); + for (int j = i + 1; j < lines.length; j++) { + if (CARET_ROW.matcher(lines[j]).matches()) { + Matcher run = CARET_RUN.matcher(lines[j]); + while (run.find()) { + runs++; + } + } else if (NUMBER_ROW.matcher(lines[j]).matches()) { + for (String number : lines[j].trim().split("[ ,]+")) { + numbers.add(number); + } + } else { + break; + } + } + if (label.equals("source supertype") && runs == 0) { + violations.add("a source supertype line must carry a caret, got:\n" + message); + } + if (entries == 0 && runs > 1) { + violations.add( + String.format( + "the %s line of a message with one mismatch must carry one caret run, got %d:%n%s", + label, runs, message)); + } + if (numbers.size() != new LinkedHashSet<>(numbers).size()) { + violations.add( + String.format( + "each number must mark one position under the %s line, got %s:%n%s", + label, numbers, message)); + } + if (label.startsWith("source")) { + sourceNumbers.addAll(numbers); + } else if (isIntersection(lines[i].substring(typeLine.end()))) { + // known gap #2202: the target line of an intersection has no caret under either component + if (!numbers.isEmpty()) { + violations.add( + "an intersection target now carries numbers; drop the #2202 exception, got:\n" + + message); + } + } else { + for (int number = 1; number <= entries; number++) { + if (!numbers.contains(Integer.toString(number))) { + violations.add( + String.format( + "entry %d must have its caret under the target line, got %s:%n%s", + number, numbers, message)); + } + } + } + } + if (sourceNumbers.size() != new LinkedHashSet<>(sourceNumbers).size()) { + violations.add( + String.format( + "each number must mark one position on the source lines together, got %s:%n%s", + sourceNumbers, message)); + } + return violations; + } + /** * 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. What {@link #checkNotes} - * finds wrong in a diagnostic it is shown goes to {@code violations}, and where that is {@code - * null}, fails the test at once. + * marked line matches it, so {@link #toString} is the expected message. What {@link + * #checkInvariants} finds wrong in a diagnostic it is shown goes to {@code violations}, and where + * that is {@code null}, fails the test at once. */ private record MessageIs(String expected, @Nullable Set violations) implements Predicate { @@ -199,7 +450,7 @@ public boolean test(String diagnostic) { } int link = diagnostic.length() - LINK_LINE.length(); String message = diagnostic.substring(PREFIX.length(), link); - List broken = checkNotes(message); + List broken = checkInvariants(message); if (violations != null) { violations.addAll(broken); } else if (!broken.isEmpty()) { 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 20358f7c2a..3fa40cff67 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 @@ -266,9 +266,9 @@ void test(List[]> l) { } // SubBox and SubSubBox bound T by a non-null Object, while the check compares the @Nullable - // bound of Box and reports a false positive (#2206), so CAPTURED_IN_A_SUBCLASS and - // CAPTURED_TWO_SUBCLASSES_DOWN get no note, as a note naming their own T would contradict the - // first line. + // bound of Box and reports a false positive (#2206). CAPTURED_IN_A_SUBCLASS and + // CAPTURED_TWO_SUBCLASSES_DOWN get no note, since it would attribute the bound the check compared + // to a T that declares another. @Test public void aCapturedWildcardNamesTheTypeParameterOnlyWhereItInstantiatesIt() { assertMessages( @@ -280,7 +280,7 @@ public void aCapturedWildcardNamesTheTypeParameterOnlyWhereItInstantiatesIt() { ^^^^^^^^^^^^ target: Legacy ^^^^^^ - note: capture of ? is the captured type argument for T of Legacy, whose upper bound is @Nullable Object (JLS 5.1.10), and Legacy is unannotated + note: capture of ? is the captured type argument for T of Legacy, whose upper bound is @Nullable Object (JLS 5.1.10); the bound is @Nullable because Legacy is unannotated """, "CAPTURED_IN_A_SUBCLASS", """ @@ -335,6 +335,24 @@ public void aCapturedWildcardNamesTheTypeParameterOnlyWhereItInstantiatesIt() { target: Map> ^^^^^^^ """, + "SUBSTITUTED_WITH_A_BOUND_ON_A_METHOD_TYPE_VARIABLE", + """ + incompatible nullability in type argument for V of Map -> upper bound of wildcard: source has @Nullable List where target requires List + source: Map + ^^^^^^^^^^^^ + target: Map> + ^^^^^^^ + note: capture of ? is a captured wildcard whose upper bound is @Nullable List (JLS 5.1.10) + """, + "SUBSTITUTED_WITH_A_BOUND_ON_A_TYPE_VARIABLE_OF_A_CLASS_NOT_PRINTED", + """ + incompatible nullability in type argument for V of Map -> upper bound of wildcard: source has @Nullable List where target requires List + source: Map + ^^^^^^^^^^^^ + target: Map> + ^^^^^^^ + note: capture of ? is a captured wildcard whose upper bound is @Nullable List (JLS 5.1.10) + """, "EARLIER_VIEW", """ incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object @@ -421,6 +439,16 @@ void substitutedWithABoundOnAnotherCapture() { // BUG: Diagnostic matches: SUBSTITUTED_WITH_A_BOUND_ON_ANOTHER_CAPTURE takeMapOfLists(toMap(makeDep())); } + void substitutedWithABoundOnAMethodTypeVariable(Dep d) { + // BUG: Diagnostic matches: SUBSTITUTED_WITH_A_BOUND_ON_A_METHOD_TYPE_VARIABLE + takeMapOfLists(toMap(d)); + } + static class Host { + void substitutedWithABoundOnATypeVariableOfAClassNotPrinted(Dep d) { + // BUG: Diagnostic matches: SUBSTITUTED_WITH_A_BOUND_ON_A_TYPE_VARIABLE_OF_A_CLASS_NOT_PRINTED + takeMapOfLists(toMap(d)); + } + } static void takeCollection(Collection c) {} void substitutedAfterAnEarlierView(List l) { // BUG: Diagnostic matches: EARLIER_VIEW @@ -432,54 +460,189 @@ void substitutedAfterAnEarlierView(List l) { } @Test - public void aNoteSaysTheClassOfTheTypeParameterItNamesIsUnannotatedForEveryKindOfWildcard() { + public void aNoteSaysTheBoundIsNullableBecauseTheClassWhoseBoundTheCheckComparedIsUnannotated() { assertMessages( - Map.of( - "UNBOUNDED", - """ - incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Legacy - ^ - target: Legacy - ^^^^^^ - note: the unbounded wildcard ? in Legacy has the upper bound of type parameter T of Legacy, which is @Nullable Object (JLS 5.1.10), and Legacy is unannotated - """, - "UNBOUNDED_IN_AN_ASSIGNMENT", - """ - incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Legacy - ^ - target: Legacy - ^^^^^^ - note: the unbounded wildcard ? in Legacy has the upper bound of type parameter T of Legacy, which is @Nullable Object (JLS 5.1.10), and Legacy is unannotated - """, - "SUPER_BOUNDED", - """ - incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Legacy - ^^^^^^^^^^^^^^ - target: Legacy - ^^^^^^ - note: the wildcard ? super String in Legacy has no upper bound of its own; its upper bound is the bound of type parameter T of Legacy, which is @Nullable Object (JLS 5.1.10), and Legacy is unannotated - """, - "CAPTURED", - """ - incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Legacy - ^^^^^^^^^^^^ - target: Legacy - ^^^^^^ - note: capture of ? is the captured type argument for T of Legacy, whose upper bound is @Nullable Object (JLS 5.1.10), and Legacy is unannotated - """, - "ANNOTATED", - """ - incompatible nullability in type argument for T of Box -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Box - ^ - target: Box - ^^^^^^ - note: the unbounded wildcard ? in Box has the upper bound of type parameter T of Box, which is @Nullable Object (JLS 5.1.10) - """), + Map.ofEntries( + Map.entry( + "UNANNOTATED_SUBCLASS_OF_AN_ANNOTATED_CLASS", + """ + incompatible nullability in type argument for T of Box -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: LegacySub + ^ + target: Box + ^^^^^^ + note: the unbounded wildcard ? in LegacySub has the upper bound of type parameter T of LegacySub, which is @Nullable Object (JLS 5.1.10) + """), + Map.entry( + "CAPTURED_IN_AN_UNANNOTATED_SUBCLASS_OF_AN_ANNOTATED_CLASS", + """ + incompatible nullability in type argument for T of Box -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: LegacySub + ^^^^^^^^^^^^ + target: Box + ^^^^^^ + note: capture of ? is the captured type argument for T of LegacySub, whose upper bound is @Nullable Object (JLS 5.1.10) + """), + Map.entry( + "UNANNOTATED_SUBCLASS_WITH_A_PARAMETERIZED_BOUND", + """ + incompatible nullability in type argument for T of ListBox -> upper bound of wildcard: source has @Nullable List where target requires List + source: LegacyListSub + ^ + target: ListBox> + ^^^^^^^^^^^^ + note: the unbounded wildcard ? in LegacyListSub has the upper bound of type parameter T of LegacyListSub, which is @Nullable List (JLS 5.1.10) + """), + Map.entry( + "ANNOTATED_SUBCLASS_OF_AN_UNANNOTATED_CLASS", + """ + incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: NullableSub + ^ + target: Legacy + ^^^^^^ + note: the unbounded wildcard ? in NullableSub has the upper bound of type parameter T of NullableSub, which is @Nullable Object (JLS 5.1.10) + """), + Map.entry( + "UNANNOTATED_SUBCLASS_OF_AN_UNANNOTATED_CLASS", + """ + incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: LegacySubOfLegacy + ^ + target: Legacy + ^^^^^^ + note: the unbounded wildcard ? in LegacySubOfLegacy has the upper bound of type parameter T of LegacySubOfLegacy, which is @Nullable Object (JLS 5.1.10); the bound is @Nullable because Legacy is unannotated + """), + Map.entry( + "UNANNOTATED_CLASS_WITH_AN_EXPLICITLY_NULLABLE_BOUND", + """ + incompatible nullability in type argument for T of ExplicitLegacy -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: ExplicitLegacy + ^ + target: ExplicitLegacy + ^^^^^^ + note: the unbounded wildcard ? in ExplicitLegacy has the upper bound of type parameter T of ExplicitLegacy, which is @Nullable Object (JLS 5.1.10) + """), + Map.entry( + "UNANNOTATED_SUBCLASS_WITH_AN_EXPLICITLY_NULLABLE_BOUND", + """ + incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: ExplicitLegacySub + ^ + target: Legacy + ^^^^^^ + note: the unbounded wildcard ? in ExplicitLegacySub has the upper bound of type parameter T of ExplicitLegacySub, which is @Nullable Object (JLS 5.1.10) + """), + Map.entry( + "UNANNOTATED_CLASS_WITH_AN_IMPLICITLY_NULLABLE_INNER_CLASS_BOUND", + """ + incompatible nullability in type argument for T of InnerLegacy -> upper bound of wildcard: source has Outer.@Nullable Inner where target requires Outer.Inner + source: InnerLegacy + ^ + target: InnerLegacy + ^^^^^^^^^^^ + note: the unbounded wildcard ? in InnerLegacy has the upper bound of type parameter T of InnerLegacy, which is Outer.@Nullable Inner (JLS 5.1.10); the bound is @Nullable because InnerLegacy is unannotated + """), + Map.entry( + "UNANNOTATED_CLASS_WITH_A_BOUND_ON_A_NULLABLE_TYPE_ARGUMENT", + """ + incompatible nullability in type argument for B of DepLegacy -> upper bound of wildcard: source has @Nullable String where target requires Object + source: DepLegacy<@Nullable String, capture of ?> + ^^^^^^^^^^^^ + target: DepLegacy + ^^^^^^ + note: capture of ? is the captured type argument for B of DepLegacy, whose upper bound is @Nullable String (JLS 5.1.10) + """), + Map.entry( + "UNANNOTATED_CLASS_WITH_A_BOUND_IN_A_GENERIC_ENCLOSING_TYPE", + """ + incompatible nullability in type argument for T of GenericInnerLegacy -> upper bound of wildcard: source has GenericOuter.@Nullable Inner where target requires GenericOuter.Inner + source: GenericInnerLegacy + ^ + target: GenericInnerLegacy.Inner> + ^^^^^^^^^^^^^^^^^^^^^^^^^^ + note: the unbounded wildcard ? in GenericInnerLegacy has the upper bound of type parameter T of GenericInnerLegacy, which is GenericOuter.@Nullable Inner (JLS 5.1.10); the bound is @Nullable because GenericInnerLegacy is unannotated + """), + Map.entry( + "UNANNOTATED_CLASS_WITH_A_NON_NULL_BOUND", + """ + incompatible nullability in type argument for T of NonNullLegacy -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: NonNullLegacy + ^ + target: NonNullLegacy> + ^^^^^^ + note: the unbounded wildcard ? in NonNullLegacy has the upper bound of type parameter T of NonNullLegacy, which is List<@Nullable String> (JLS 5.1.10) + """), + Map.entry( + "UNBOUNDED", + """ + incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Legacy + ^ + target: Legacy + ^^^^^^ + note: the unbounded wildcard ? in Legacy has the upper bound of type parameter T of Legacy, which is @Nullable Object (JLS 5.1.10); the bound is @Nullable because Legacy is unannotated + """), + Map.entry( + "UNBOUNDED_IN_AN_ASSIGNMENT", + """ + incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Legacy + ^ + target: Legacy + ^^^^^^ + note: the unbounded wildcard ? in Legacy has the upper bound of type parameter T of Legacy, which is @Nullable Object (JLS 5.1.10); the bound is @Nullable because Legacy is unannotated + """), + Map.entry( + "SUPER_BOUNDED", + """ + incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Legacy + ^^^^^^^^^^^^^^ + target: Legacy + ^^^^^^ + note: the wildcard ? super String in Legacy has no upper bound of its own; its upper bound is the bound of type parameter T of Legacy, which is @Nullable Object (JLS 5.1.10); the bound is @Nullable because Legacy is unannotated + """), + Map.entry( + "CAPTURED", + """ + incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Legacy + ^^^^^^^^^^^^ + target: Legacy + ^^^^^^ + note: capture of ? is the captured type argument for T of Legacy, whose upper bound is @Nullable Object (JLS 5.1.10); the bound is @Nullable because Legacy is unannotated + """), + Map.entry( + "UNANNOTATED_CLASS_DIFFERING_BELOW_ITS_IMPLICITLY_NULLABLE_BOUND", + """ + incompatible nullability in type argument for T of NestedLegacy -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: NestedLegacy + ^ + target: NestedLegacy> + ^^^^^^ + note: the unbounded wildcard ? in NestedLegacy has the upper bound of type parameter T of NestedLegacy, which is @Nullable List<@Nullable String> (JLS 5.1.10) + """), + Map.entry( + "CAPTURED_IN_AN_UNANNOTATED_CLASS_DIFFERING_BELOW_ITS_IMPLICITLY_NULLABLE_BOUND", + """ + incompatible nullability in type argument for T of NestedLegacy -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: NestedLegacy + ^^^^^^^^^^^^ + target: NestedLegacy> + ^^^^^^ + note: capture of ? is the captured type argument for T of NestedLegacy, whose upper bound is @Nullable List<@Nullable String> (JLS 5.1.10) + """), + Map.entry( + "ANNOTATED", + """ + incompatible nullability in type argument for T of Box -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Box + ^ + target: Box + ^^^^^^ + note: the unbounded wildcard ? in Box has the upper bound of type parameter T of Box, which is @Nullable Object (JLS 5.1.10) + """)), """ @NullUnmarked static class Legacy {} @@ -511,6 +674,105 @@ void annotated(Box b) { // BUG: Diagnostic matches: ANNOTATED takeBox(b); } + @NullUnmarked + static class LegacySub extends Box {} + void unannotatedSubclassOfAnAnnotatedClass(LegacySub s) { + // BUG: Diagnostic matches: UNANNOTATED_SUBCLASS_OF_AN_ANNOTATED_CLASS + takeBox(s); + } + @NullUnmarked + static LegacySub makeLegacySub() { + throw new RuntimeException(); + } + void capturedInAnUnannotatedSubclassOfAnAnnotatedClass() { + // BUG: Diagnostic matches: CAPTURED_IN_AN_UNANNOTATED_SUBCLASS_OF_AN_ANNOTATED_CLASS + takeBox(makeLegacySub()); + } + static class ListBox> {} + @NullUnmarked + static class LegacyListSub> extends ListBox {} + static void takeListBox(ListBox> b) {} + void unannotatedSubclassWithAParameterizedBound(LegacyListSub s) { + // BUG: Diagnostic matches: UNANNOTATED_SUBCLASS_WITH_A_PARAMETERIZED_BOUND + takeListBox(s); + } + static class NullableSub extends Legacy {} + void annotatedSubclassOfAnUnannotatedClass(NullableSub s) { + // BUG: Diagnostic matches: ANNOTATED_SUBCLASS_OF_AN_UNANNOTATED_CLASS + takeLegacy(s); + } + @NullUnmarked + static class LegacySubOfLegacy extends Legacy {} + @NullUnmarked + static class NonNullLegacy> {} + static void takeNonNullLegacy(NonNullLegacy> l) {} + @NullUnmarked + static class ExplicitLegacy {} + static void takeExplicitLegacy(ExplicitLegacy l) {} + void unannotatedClassWithAnExplicitlyNullableBound(ExplicitLegacy l) { + // BUG: Diagnostic matches: UNANNOTATED_CLASS_WITH_AN_EXPLICITLY_NULLABLE_BOUND + takeExplicitLegacy(l); + } + @NullUnmarked + static class ExplicitLegacySub extends Legacy {} + void unannotatedSubclassWithAnExplicitlyNullableBound(ExplicitLegacySub s) { + // BUG: Diagnostic matches: UNANNOTATED_SUBCLASS_WITH_AN_EXPLICITLY_NULLABLE_BOUND + takeLegacy(s); + } + static class Outer { + class Inner {} + } + @NullUnmarked + static class InnerLegacy {} + static void takeInnerLegacy(InnerLegacy l) {} + void unannotatedClassWithAnImplicitlyNullableInnerClassBound(InnerLegacy l) { + // BUG: Diagnostic matches: UNANNOTATED_CLASS_WITH_AN_IMPLICITLY_NULLABLE_INNER_CLASS_BOUND + takeInnerLegacy(l); + } + @NullUnmarked + static class DepLegacy {} + static DepLegacy<@Nullable String, ?> makeDepLegacy() { + throw new RuntimeException(); + } + static void takeDepLegacy(DepLegacy d) {} + void unannotatedClassWithABoundOnANullableTypeArgument() { + // BUG: Diagnostic matches: UNANNOTATED_CLASS_WITH_A_BOUND_ON_A_NULLABLE_TYPE_ARGUMENT + takeDepLegacy(makeDepLegacy()); + } + static class GenericOuter { + class Inner {} + } + @NullUnmarked + static class GenericInnerLegacy.Inner> {} + static void takeGenericInnerLegacy( + GenericInnerLegacy.Inner> l) {} + void unannotatedClassWithABoundInAGenericEnclosingType(GenericInnerLegacy l) { + // BUG: Diagnostic matches: UNANNOTATED_CLASS_WITH_A_BOUND_IN_A_GENERIC_ENCLOSING_TYPE + takeGenericInnerLegacy(l); + } + void unannotatedClassWithANonNullBound(NonNullLegacy l) { + // BUG: Diagnostic matches: UNANNOTATED_CLASS_WITH_A_NON_NULL_BOUND + takeNonNullLegacy(l); + } + void unannotatedSubclassOfAnUnannotatedClass(LegacySubOfLegacy s) { + // BUG: Diagnostic matches: UNANNOTATED_SUBCLASS_OF_AN_UNANNOTATED_CLASS + takeLegacy(s); + } + @NullUnmarked + static class NestedLegacy> {} + @NullUnmarked + static NestedLegacy makeNestedLegacy() { + throw new RuntimeException(); + } + static void takeNestedLegacy(NestedLegacy> l) {} + void unannotatedClassDifferingBelowItsImplicitlyNullableBound(NestedLegacy l) { + // BUG: Diagnostic matches: UNANNOTATED_CLASS_DIFFERING_BELOW_ITS_IMPLICITLY_NULLABLE_BOUND + takeNestedLegacy(l); + } + void capturedInAnUnannotatedClassDifferingBelowItsImplicitlyNullableBound() { + // BUG: Diagnostic matches: CAPTURED_IN_AN_UNANNOTATED_CLASS_DIFFERING_BELOW_ITS_IMPLICITLY_NULLABLE_BOUND + takeNestedLegacy(makeNestedLegacy()); + } """); } @@ -759,101 +1021,157 @@ void captureInAnEnclosingTypeInBound() { """); } - // The check views SubL as Base, where U is @Nullable, and reports a false positive (#2206); a - // note giving the bound T of SubL declares would contradict the first line. - // NO_NOTE_BELOW_AN_ENCLOSING_TYPE_OF_A_SUBCLASS_BOUND pins a known gap: the bound TopNested, - // viewed as Nested, does hold @Nullable String at X, but the walk to the note takes the enclosing - // type of TopNested itself, which has none, so no note is printed (#2224). + // The check views SubL as Base and compares the @Nullable bound of U, so it reports a false + // positive (#2206). There is a note naming the holder's own type parameter only where its bound + // prints as the compared bound does at every node, once the compared class's type parameters are + // replaced by the type arguments the holder's class passes to it. + // A subtype of the compared bound with the same nullness, such as @Nullable List for + // @Nullable Object, gets no note, so TopSub, whose bound TopNested hides the @Nullable type + // argument of Enclosing, gets none either (#2224). @Test public void aHolderNoteIsPrintedOnlyWhereItsBoundHasTheNullnessTheCheckCompared() { assertMessages( - Map.of( - "SUBCLASS_BOUND_IS_NON_NULL", - """ - incompatible nullability in type argument for U of Base -> upper bound of wildcard: source has @Nullable Object where target requires List - source: SubL - ^ - target: Base> - ^^^^^^^^^^^^ - """, - "SUBCLASS_BOUND_INSIDE_A_LIST", - """ - incompatible nullability in type argument for U of Base -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: SubW - ^ - target: Base> - ^^^^^^ - """, - "BOUND_HOLDS_A_WILDCARD", - """ - incompatible nullability in type argument for T of Wild -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Wild - ^ - target: Wild> - ^^^^^^ - note: the unbounded wildcard ? in Wild has the upper bound of type parameter T of Wild, which is List (JLS 5.1.10) - """, - "BOUND_HOLDS_AN_ARRAY", - """ - incompatible nullability in type argument for T of Arr -> upper bound of wildcard -> type argument for E of List -> component type -> type argument for E of List: source has @Nullable String where target requires String - source: Arr - ^ - target: Arr []>> - ^^^^^^ - note: the unbounded wildcard ? in Arr has the upper bound of type parameter T of Arr, which is List []> (JLS 5.1.10) - """, - "BOUND_HOLDS_A_LOWER_BOUND", - """ - incompatible nullability in type argument for T of Low -> upper bound of wildcard -> type argument for E of List -> lower bound of wildcard: source has String where target requires a supertype of @Nullable String - source: Low - ^ - target: Low> - ^^^^^^^^^^^^^^^^ - note: the unbounded wildcard ? in Low has the upper bound of type parameter T of Low, which is List (JLS 5.1.10) - """, - "BOUND_HOLDS_AN_INNER_CLASS", - """ - incompatible nullability in type argument for T of In -> upper bound of wildcard -> enclosing type -> type argument for E of Outer: source has @Nullable String where target requires String - source: In - ^ - target: In.Inner> - ^^^^^^ - note: the unbounded wildcard ? in In has the upper bound of type parameter T of In, which is Test.Outer<@Nullable String>.Inner (JLS 5.1.10) - """, - "BOUND_IS_A_SUBCLASS_OF_THE_COMPARED_CLASS", - """ - incompatible nullability in type argument for U of Coll -> upper bound of wildcard -> type argument for V of Map: source has @Nullable String where target requires String - source: SubColl + Map.ofEntries( + Map.entry( + "SUBCLASS_BOUND_IS_NON_NULL", + """ + incompatible nullability in type argument for U of Base -> upper bound of wildcard: source has @Nullable Object where target requires List + source: SubL + ^ + target: Base> + ^^^^^^^^^^^^ + """), + Map.entry( + "SUBCLASS_BOUND_INSIDE_A_LIST", + """ + incompatible nullability in type argument for U of Base -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: SubW + ^ + target: Base> + ^^^^^^ + """), + Map.entry( + "BOUND_HOLDS_A_WILDCARD", + """ + incompatible nullability in type argument for T of Wild -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Wild + ^ + target: Wild> + ^^^^^^ + note: the unbounded wildcard ? in Wild has the upper bound of type parameter T of Wild, which is List (JLS 5.1.10) + """), + Map.entry( + "BOUND_HOLDS_AN_ARRAY", + """ + incompatible nullability in type argument for T of Arr -> upper bound of wildcard -> type argument for E of List -> component type -> type argument for E of List: source has @Nullable String where target requires String + source: Arr ^ - target: Coll> - ^^^^^^ - note: the unbounded wildcard ? in SubColl has the upper bound of type parameter T of SubColl, which is Reversed<@Nullable String, String> (JLS 5.1.10) - """, - "SUBCLASS_BOUND_STATES_A_TYPE_ARGUMENT", - """ - incompatible nullability in type argument for U of Wide -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Narrow - ^ - target: Wide> - ^^^^^^ - """, - "SUBCLASS_BOUND_IS_NULLABLE", - """ - incompatible nullability in type argument for U of Base -> upper bound of wildcard: source has @Nullable Object where target requires Object - source: Sub - ^ - target: Base - ^^^^^^ - note: the unbounded wildcard ? in Sub has the upper bound of type parameter T of Sub, which is @Nullable Object (JLS 5.1.10) - """, - "NO_NOTE_BELOW_AN_ENCLOSING_TYPE_OF_A_SUBCLASS_BOUND", - """ - incompatible nullability in type argument for T of Holder -> upper bound of wildcard -> enclosing type -> type argument for X of Enclosing: source has @Nullable String where target requires String - source: TopSub + target: Arr []>> + ^^^^^^ + note: the unbounded wildcard ? in Arr has the upper bound of type parameter T of Arr, which is List []> (JLS 5.1.10) + """), + Map.entry( + "BOUND_HOLDS_A_LOWER_BOUND", + """ + incompatible nullability in type argument for T of Low -> upper bound of wildcard -> type argument for E of List -> lower bound of wildcard: source has String where target requires a supertype of @Nullable String + source: Low + ^ + target: Low> + ^^^^^^^^^^^^^^^^ + note: the unbounded wildcard ? in Low has the upper bound of type parameter T of Low, which is List (JLS 5.1.10) + """), + Map.entry( + "BOUND_HOLDS_AN_INNER_CLASS", + """ + incompatible nullability in type argument for T of In -> upper bound of wildcard -> enclosing type -> type argument for E of Outer: source has @Nullable String where target requires String + source: In ^ - target: Holder.Nested> - ^^^^^^ - """), + target: In.Inner> + ^^^^^^ + note: the unbounded wildcard ? in In has the upper bound of type parameter T of In, which is Test.Outer<@Nullable String>.Inner (JLS 5.1.10) + """), + Map.entry( + "BOUND_IS_A_SUBCLASS_OF_THE_COMPARED_CLASS", + """ + incompatible nullability in type argument for U of Coll -> upper bound of wildcard -> type argument for V of Map: source has @Nullable String where target requires String + source: SubColl + ^ + target: Coll> + ^^^^^^ + """), + Map.entry( + "SUBCLASS_BOUND_STATES_A_TYPE_ARGUMENT", + """ + incompatible nullability in type argument for U of Wide -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Narrow + ^ + target: Wide> + ^^^^^^ + """), + Map.entry( + "SUBCLASS_BOUND_IS_A_SUBTYPE_WITH_THE_SAME_NULLNESS", + """ + incompatible nullability in type argument for U of Base -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: NullableListSub + ^ + target: Base + ^^^^^^ + """), + Map.entry( + "SUBCLASS_TWO_LEVELS_DOWN_BOUND_IS_A_SUBTYPE_WITH_THE_SAME_NULLNESS", + """ + incompatible nullability in type argument for U of Base -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: NullableListSubSub + ^ + target: Base + ^^^^^^ + """), + Map.entry( + "SUPER_BOUNDED_IN_A_SUBCLASS_WHOSE_BOUND_IS_A_SUBTYPE", + """ + incompatible nullability in type argument for U of Base -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: NullableListSub> + ^^^^^^^^^^^^^^^^^^^^^^^^^ + target: Base + ^^^^^^ + """), + Map.entry( + "SUBCLASS_BOUND_IS_A_SUBCLASS_OF_AN_INNER_CLASS_BOUND", + """ + incompatible nullability in type argument for T of InnerBase -> upper bound of wildcard: source has InnerOuter.@Nullable Inner where target requires InnerOuter.Inner + source: InnerSub + ^ + target: InnerBase + ^^^^^^^^^^^^^^^^ + """), + Map.entry( + "SUBCLASS_BOUND_DIFFERS_IN_A_NESTED_ANNOTATION", + """ + incompatible nullability in type argument for M of MapBase -> upper bound of wildcard: source has @Nullable Map<@Nullable String, String> where target requires Object + source: MapSub + ^ + target: MapBase + ^^^^^^ + """), + Map.entry( + "SUBCLASS_BOUND_IS_NULLABLE", + """ + incompatible nullability in type argument for U of Base -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Sub + ^ + target: Base + ^^^^^^ + note: the unbounded wildcard ? in Sub has the upper bound of type parameter T of Sub, which is @Nullable Object (JLS 5.1.10) + """), + Map.entry( + "SUBCLASS_BOUND_IS_A_SUBCLASS_OF_THE_COMPARED_BOUND", + """ + incompatible nullability in type argument for T of Holder -> upper bound of wildcard -> enclosing type -> type argument for X of Enclosing: source has @Nullable String where target requires String + source: TopSub + ^ + target: Holder.Nested> + ^^^^^^ + """)), """ static class Base {} static class SubL> extends Base {} @@ -913,6 +1231,42 @@ void subclassBoundIsNullable(Sub s) { // BUG: Diagnostic matches: SUBCLASS_BOUND_IS_NULLABLE takeNonNull(s); } + static class NullableListSub> extends Base {} + static class NullableListSubSub> extends NullableListSub {} + void subclassBoundIsASubtypeWithTheSameNullness(NullableListSub s) { + // BUG: Diagnostic matches: SUBCLASS_BOUND_IS_A_SUBTYPE_WITH_THE_SAME_NULLNESS + takeNonNull(s); + } + void subclassTwoLevelsDownBoundIsASubtypeWithTheSameNullness(NullableListSubSub s) { + // BUG: Diagnostic matches: SUBCLASS_TWO_LEVELS_DOWN_BOUND_IS_A_SUBTYPE_WITH_THE_SAME_NULLNESS + takeNonNull(s); + } + void superBoundedInASubclassWhoseBoundIsASubtype(NullableListSub> s) { + // BUG: Diagnostic matches: SUPER_BOUNDED_IN_A_SUBCLASS_WHOSE_BOUND_IS_A_SUBTYPE + takeNonNull(s); + } + static class InnerOuter { + class Inner {} + } + static class SubInnerOfOuter extends InnerOuter.Inner { + SubInnerOfOuter(InnerOuter o) { + o.super(); + } + } + static class InnerBase {} + static class InnerSub extends InnerBase {} + static void takeInnerBase(InnerBase b) {} + void subclassBoundIsASubclassOfAnInnerClassBound(InnerSub s) { + // BUG: Diagnostic matches: SUBCLASS_BOUND_IS_A_SUBCLASS_OF_AN_INNER_CLASS_BOUND + takeInnerBase(s); + } + static class MapBase> {} + static class MapSub> extends MapBase {} + static void takeMapBase(MapBase b) {} + void subclassBoundDiffersInANestedAnnotation(MapSub s) { + // BUG: Diagnostic matches: SUBCLASS_BOUND_DIFFERS_IN_A_NESTED_ANNOTATION + takeMapBase(s); + } static class Enclosing { class Nested {} } @@ -924,7 +1278,7 @@ static class TopNested extends Enclosing<@Nullable String>.Nested { static class Holder.Nested> {} static class TopSub extends Holder {} void subclassBoundHasNoEnclosingType(TopSub s) { - // BUG: Diagnostic matches: NO_NOTE_BELOW_AN_ENCLOSING_TYPE_OF_A_SUBCLASS_BOUND + // BUG: Diagnostic matches: SUBCLASS_BOUND_IS_A_SUBCLASS_OF_THE_COMPARED_BOUND Holder.Nested> h = s; } """); diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TopLevelNullableTest.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TopLevelNullableTest.java new file mode 100644 index 0000000000..dcac7804c4 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TopLevelNullableTest.java @@ -0,0 +1,34 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import static com.google.common.truth.Truth.assertWithMessage; + +import java.util.Map; +import org.junit.Test; + +public class TopLevelNullableTest { + + @Test + public void aPrintedTypeIsNullableAtItsTopLevelOnlyWhereThePrinterPutsThatAnnotation() { + Map expected = + Map.ofEntries( + Map.entry("@Nullable String", true), + Map.entry("String", false), + Map.entry("List<@Nullable String>", false), + Map.entry("@Nullable List", true), + Map.entry("Outer.@Nullable Inner", true), + Map.entry("Outer.@Nullable Inner", true), + Map.entry("Outer.@Nullable Inner>", true), + Map.entry("Outer.@Nullable Middle.Inner", false), + Map.entry("Outer.Inner", false), + Map.entry("String @Nullable []", true), + Map.entry("String @Nullable [] []", false), + Map.entry("@Nullable String []", false), + Map.entry("Outer.@Nullable Inner []", false), + Map.entry("@Nullable String @Nullable []", true)); + expected.forEach( + (printed, nullable) -> + assertWithMessage("top-level @Nullable of %s", printed) + .that(MismatchMessageTestBase.isTopLevelNullable(printed)) + .isEqualTo(nullable)); + } +} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java index 483ee0b87d..103cf657f4 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java @@ -128,14 +128,17 @@ public void aRejectedComparisonReachedAlongManyPathsIsWalkedOnce() { 3. path: type argument for T of L24 -> upper bound of wildcard -> type argument for A of P -> type argument for T of L23 -> upper bound of wildcard -> type argument for A of P -> type argument for X of L22 source: @Nullable String target: String + note: the unbounded wildcard ? in L24<@Nullable String, ?> has the upper bound of type parameter T of L24, which is P, L23<@Nullable String, ?>> (JLS 5.1.10) \s 4. path: type argument for T of L24 -> upper bound of wildcard -> type argument for A of P -> type argument for T of L23 -> upper bound of wildcard -> type argument for A of P -> type argument for T of L22 -> upper bound of wildcard -> type argument for A of P -> type argument for X of L21 source: @Nullable String target: String + note: the unbounded wildcard ? in L24<@Nullable String, ?> has the upper bound of type parameter T of L24, which is P, L23<@Nullable String, ?>> (JLS 5.1.10) \s 5. path: type argument for T of L24 -> upper bound of wildcard -> type argument for A of P -> type argument for T of L23 -> upper bound of wildcard -> type argument for A of P -> type argument for T of L22 -> upper bound of wildcard -> type argument for A of P -> type argument for T of L21 -> upper bound of wildcard -> type argument for A of P -> type argument for X of L20 source: @Nullable String target: String + note: the unbounded wildcard ? in L24<@Nullable String, ?> has the upper bound of type parameter T of L24, which is P, L23<@Nullable String, ?>> (JLS 5.1.10) \s and 90 more differing positions, not listed """, 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 a0b2feaf2e..43a55e4728 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 @@ -851,4 +851,79 @@ void threeDeep(Thrice<@Nullable List<@Nullable List<@Nullable String>>> s) { } """); } + + @Test + public void aSupertypeLineIsPrintedOnlyWhereItCarriesACaret() { + assertMessages( + Map.of( + "WRITTEN_NODE_AND_A_NODE_OF_A_NESTED_CLASS", + """ + incompatible nullability in type argument for A of Base -> type argument for E of List and 1 other differing position: source has @Nullable String where target requires String + source: Sub> + ^^^^^^^^^^^^^^^^ + 1 + target: Base, ? extends Inner>> + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: type argument for A of Base -> type argument for E of List + source: @Nullable String + target: String + \s + 2. path: type argument for B of Base -> upper bound of wildcard -> type argument for Y of Inner -> type argument for E of List + source: @Nullable String + target: String + """, + "ONLY_A_NODE_OF_A_NESTED_CLASS", + """ + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for Y of Inner -> type argument for E of List: source has @Nullable String where target requires String + source: Sub> + target: Base>> + ^^^^^^ + """, + "ONLY_A_NODE_OF_A_NESTED_CLASS_BELOW_A_LIST", + """ + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard -> type argument for Y of Inner -> type argument for E of List: source has @Nullable String where target requires String + source: ListSub + target: Base>>> + ^^^^^^ + """, + "A_NODE_OF_THE_SUBCLASS_DECLARATION", + """ + incompatible nullability in type argument for B of Base -> type argument for E of List: source has @Nullable String where target requires String + source: Declared + source supertype: Base> + ^^^^^^^^^^^^^^^^ + target: Base> + ^^^^^^ + """), + """ + static class Base
{} + static class Inner {} + static class SubInner extends Inner> {} + static class Sub extends Base {} + static void take(Base, ? extends Inner>> b) {} + static void takeOne(Base>> b) {} + void writtenNodeAndANodeOfANestedClass(Sub> s) { + // BUG: Diagnostic matches: WRITTEN_NODE_AND_A_NODE_OF_A_NESTED_CLASS + take(s); + } + void onlyANodeOfANestedClass(Sub> s) { + // BUG: Diagnostic matches: ONLY_A_NODE_OF_A_NESTED_CLASS + takeOne(s); + } + static class ListSub extends Base> {} + static void takeList(Base>>> b) {} + void onlyANodeOfANestedClassBelowAList(ListSub s) { + // BUG: Diagnostic matches: ONLY_A_NODE_OF_A_NESTED_CLASS_BELOW_A_LIST + takeList(s); + } + static class Declared extends Base> {} + static void takeDeclared(Base> b) {} + void aNodeOfTheSubclassDeclaration(Declared d) { + // BUG: Diagnostic matches: A_NODE_OF_THE_SUBCLASS_DECLARATION + takeDeclared(d); + } + """); + } }

The bound of a capture refers to the captures the class holds as its type arguments, its own * included where the type parameter's bound refers to it, as in {@code Self> {} + static Dep makeDep() { + throw new RuntimeException(); + } + static > Map toMap(Dep d) { + throw new RuntimeException(); + } + static void takeMapOfLists(Map> m) {} + void substitutedWithABoundOnAnotherCapture() { + // BUG: Diagnostic matches: SUBSTITUTED_WITH_A_BOUND_ON_ANOTHER_CAPTURE + takeMapOfLists(toMap(makeDep())); + } static void takeCollection(Collection c) {} void substitutedAfterAnEarlierView(List l) { // BUG: Diagnostic matches: EARLIER_VIEW @@ -392,6 +431,89 @@ void substitutedAfterAnEarlierView(List l) { """); } + @Test + public void aNoteSaysTheClassOfTheTypeParameterItNamesIsUnannotatedForEveryKindOfWildcard() { + assertMessages( + Map.of( + "UNBOUNDED", + """ + incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Legacy + ^ + target: Legacy + ^^^^^^ + note: the unbounded wildcard ? in Legacy has the upper bound of type parameter T of Legacy, which is @Nullable Object (JLS 5.1.10), and Legacy is unannotated + """, + "UNBOUNDED_IN_AN_ASSIGNMENT", + """ + incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Legacy + ^ + target: Legacy + ^^^^^^ + note: the unbounded wildcard ? in Legacy has the upper bound of type parameter T of Legacy, which is @Nullable Object (JLS 5.1.10), and Legacy is unannotated + """, + "SUPER_BOUNDED", + """ + incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Legacy + ^^^^^^^^^^^^^^ + target: Legacy + ^^^^^^ + note: the wildcard ? super String in Legacy has no upper bound of its own; its upper bound is the bound of type parameter T of Legacy, which is @Nullable Object (JLS 5.1.10), and Legacy is unannotated + """, + "CAPTURED", + """ + incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Legacy + ^^^^^^^^^^^^ + target: Legacy + ^^^^^^ + note: capture of ? is the captured type argument for T of Legacy, whose upper bound is @Nullable Object (JLS 5.1.10), and Legacy is unannotated + """, + "ANNOTATED", + """ + incompatible nullability in type argument for T of Box -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Box + ^ + target: Box + ^^^^^^ + note: the unbounded wildcard ? in Box has the upper bound of type parameter T of Box, which is @Nullable Object (JLS 5.1.10) + """), + """ + @NullUnmarked + static class Legacy {} + @NullUnmarked + static Legacy makeLegacy() { + throw new RuntimeException(); + } + static void takeLegacy(Legacy l) {} + void unbounded(Legacy l) { + // BUG: Diagnostic matches: UNBOUNDED + takeLegacy(l); + } + void unboundedInAnAssignment(Legacy l) { + // BUG: Diagnostic matches: UNBOUNDED_IN_AN_ASSIGNMENT + Legacy x = l; + x.hashCode(); + } + void superBounded(Legacy l) { + // BUG: Diagnostic matches: SUPER_BOUNDED + takeLegacy(l); + } + void captured() { + // BUG: Diagnostic matches: CAPTURED + takeLegacy(makeLegacy()); + } + static class Box {} + static void takeBox(Box b) {} + void annotated(Box b) { + // BUG: Diagnostic matches: ANNOTATED + takeBox(b); + } + """); + } + @Test public void aCapturedWildcardsBoundNamesTypeParametersRatherThanCaptures() { assertMessages( @@ -555,6 +677,88 @@ void captureOfAnotherTypeInBound() { """); } + @Test + public void + aCapturedWildcardGetsNoNoteWhereItsBoundWouldPrintACaptureInsideAnArrayOrAnEnclosingType() { + assertMessages( + Map.of( + "TYPE_PARAMETER_IN_AN_ARRAY", + """ + incompatible nullability in type argument for B of ArrayDep -> upper bound of wildcard: source has @Nullable List where target requires List + source: ArrayDep + ^^^^^^^^^^^^ + target: ArrayDep> + ^^^^^^^ + note: capture of ? is the captured type argument for B of ArrayDep, whose upper bound is @Nullable List (JLS 5.1.10) + """, + "CAPTURE_IN_AN_ARRAY", + """ + incompatible nullability in type argument for B of ArrayDep -> upper bound of wildcard: source has @Nullable List []> where target requires List + source: ArrayDep, capture of ?> + ^^^^^^^^^^^^ + target: ArrayDep> + ^^^^^^^ + """, + "CAPTURE_IN_A_TWO_DIMENSIONAL_ARRAY", + """ + incompatible nullability in type argument for B of Array2Dep -> upper bound of wildcard: source has @Nullable List [] []> where target requires List + source: Array2Dep, capture of ?> + ^^^^^^^^^^^^ + target: Array2Dep> + ^^^^^^^ + """, + "CAPTURE_IN_AN_ENCLOSING_TYPE", + """ + incompatible nullability in type argument for B of Dep2 -> upper bound of wildcard: source has Outer2>.@Nullable In where target requires Outer2.In + source: Dep2, capture of ?> + ^^^^^^^^^^^^ + target: Dep2.In> + ^^^^^^^^^^^^ + """), + """ + static class ArrayDep> {} + static ArrayDep makeArrayDep() { + throw new RuntimeException(); + } + static void takeArrayDep(ArrayDep> d) {} + void typeParameterInAnArray() { + // BUG: Diagnostic matches: TYPE_PARAMETER_IN_AN_ARRAY + takeArrayDep(makeArrayDep()); + } + static List makeList() { + throw new RuntimeException(); + } + static ArrayDep arrayDepOf(T t) { + throw new RuntimeException(); + } + void captureInAnArrayInBound() { + // BUG: Diagnostic matches: CAPTURE_IN_AN_ARRAY + takeArrayDep(arrayDepOf(makeList())); + } + static class Array2Dep> {} + static Array2Dep array2DepOf(T t) { + throw new RuntimeException(); + } + static void takeArray2Dep(Array2Dep> d) {} + void captureInATwoDimensionalArrayInBound() { + // BUG: Diagnostic matches: CAPTURE_IN_A_TWO_DIMENSIONAL_ARRAY + takeArray2Dep(array2DepOf(makeList())); + } + static class Outer2 { + class In {} + } + static class Dep2.@Nullable In> {} + static Dep2 dep2Of(T t) { + throw new RuntimeException(); + } + static void takeDep2(Dep2.In> d) {} + void captureInAnEnclosingTypeInBound() { + // BUG: Diagnostic matches: CAPTURE_IN_AN_ENCLOSING_TYPE + takeDep2(dep2Of(makeList())); + } + """); + } + // The check views SubL as Base, where U is @Nullable, and reports a false positive (#2206); a // note giving the bound T of SubL declares would contradict the first line. // NO_NOTE_BELOW_AN_ENCLOSING_TYPE_OF_A_SUBCLASS_BOUND pins a known gap: the bound TopNested, 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 712cec49b0..a0b2feaf2e 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 @@ -322,6 +322,123 @@ static void test(Object o) { """); } + // The target lines of INTERSECTION and INTERSECTION_REVERSED have no caret (#2202). + @Test + public void aDifferenceIsMarkedOnTheWrittenSourceWhereItHoldsTheNodeAndOnTheSupertypeOtherwise() { + assertMessages( + Map.of( + "SPLIT", + """ + incompatible nullability in type argument for A of Pair and 1 other differing position: source has @Nullable String where target requires String + source: Sub<@Nullable String> + ^^^^^^^^^^^^^^^^ + 1 + source supertype: Pair<@Nullable String, List<@Nullable String>> + ^^^^^^^^^^^^^^^^ + 2 + target: Pair> + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: type argument for A of Pair + source: @Nullable String + target: String + \s + 2. path: type argument for B of Pair -> type argument for E of List + source: @Nullable String + target: String + """, + "SPLIT_ONE_LEVEL_DOWN", + """ + incompatible nullability in type argument for A of Pair -> type argument for E of List and 1 other differing position: source has @Nullable String where target requires String + source: ListSub<@Nullable String> + ^^^^^^^^^^^^^^^^ + 1 + source supertype: Pair, List<@Nullable String>> + ^^^^^^^^^^^^^^^^ + 2 + target: Pair, List> + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: type argument for A of Pair -> type argument for E of List + source: @Nullable String + target: String + \s + 2. path: type argument for B of Pair -> type argument for E of List + source: @Nullable String + target: String + """, + "INTERSECTION", + """ + incompatible nullability in type argument for T of A and 1 other differing position: source has @Nullable String where target requires String + source: B<@Nullable String> + ^^^^^^^^^^^^^^^^ + 1 + source supertype: D<@Nullable String> + ^^^^^^^^^^^^^^^^ + 2 + target: A & D + \s + 1. path: type argument for T of A + source: @Nullable String + target: String + \s + 2. path: type argument for T of D + source: @Nullable String + target: String + """, + "INTERSECTION_REVERSED", + """ + incompatible nullability in type argument for T of D and 1 other differing position: source has @Nullable String where target requires String + source: C<@Nullable String> + ^^^^^^^^^^^^^^^^ + 2 + source supertype: D<@Nullable String> + ^^^^^^^^^^^^^^^^ + 1 + target: D & A + \s + 1. path: type argument for T of D + source: @Nullable String + target: String + \s + 2. path: type argument for T of A + source: @Nullable String + target: String + """), + """ + interface Pair {} + static class Sub implements Pair> {} + static void takePair(Pair> p) {} + void split(Sub<@Nullable String> s) { + // BUG: Diagnostic matches: SPLIT + takePair(s); + } + static class ListSub + implements Pair, List<@Nullable String>> {} + static void takeListPair(Pair, List> p) {} + void splitOneLevelDown(ListSub<@Nullable String> s) { + // BUG: Diagnostic matches: SPLIT_ONE_LEVEL_DOWN + takeListPair(s); + } + interface A {} + interface D {} + static class B implements A, D<@Nullable String> {} + static class C implements D<@Nullable String>, A {} + static void intersection(Object o) { + var x = (A & D) o; + // BUG: Diagnostic matches: INTERSECTION + x = new B<@Nullable String>(); + } + static void intersectionReversed(Object o) { + var x = (D & A) o; + // BUG: Diagnostic matches: INTERSECTION_REVERSED + x = new C<@Nullable String>(); + } + """); + } + // The written source is the capture of ? extends A<@Nullable String>, while the comparison steps // into B; the type argument of A is not the one compared, so the source line gets no caret. @Test @@ -351,8 +468,11 @@ static void test(Factory factory) { """); } - // Below the root of the type, the source line of BELOW_ROOT gets no caret and no source supertype - // line (#2197). + // Below the root of the type, the source lines of the BELOW_ROOT keys get no caret and no + // source supertype line (#2197). + // The check compares the bound of BELOW_THE_IMPLICIT_BOUND_OF_A_SUBCLASS and + // BELOW_ROOT_BELOW_THE_IMPLICIT_BOUND_OF_A_SUBCLASS as Holder declares it, where NonNullHolder + // declares a non-null one, and reports a false positive (#2206). @Test public void aWildcardFromTheSubclassDeclarationIsNamedOnlyWhereALinePrintsIt() { assertMessages( @@ -384,6 +504,50 @@ public void aWildcardFromTheSubclassDeclarationIsNamedOnlyWhereALinePrintsIt() { target: List>> ^^^^^^ note: the unbounded wildcard ? in the source has the upper bound @Nullable Object (JLS 5.1.10) + """, + "BELOW_THE_IMPLICIT_BOUND", + """ + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for E of Holder -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: HolderSub + source supertype: Base> + ^ + target: Base>> + ^^^^^^ + note: the unbounded wildcard ? in Holder has the upper bound of type parameter E of Holder, which is List<@Nullable String> (JLS 5.1.10) + """, + "BELOW_THE_IMPLICIT_BOUND_INSIDE_A_MAP", + """ + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for V of Map -> upper bound of wildcard -> type argument for E of Holder -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: MapOfHolderSub + source supertype: Base>> + ^ + target: Base>>> + ^^^^^^ + note: the unbounded wildcard ? in Holder has the upper bound of type parameter E of Holder, which is List<@Nullable String> (JLS 5.1.10) + """, + "BELOW_THE_IMPLICIT_BOUND_OF_A_SUBCLASS", + """ + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for E of Holder -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: NonNullHolderSub + source supertype: Base> + ^ + target: Base>> + ^^^^^^ + """, + "BELOW_ROOT_BELOW_THE_IMPLICIT_BOUND", + """ + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for B of Base -> upper bound of wildcard -> type argument for E of Holder -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: List + target: List>>> + ^^^^^^ + note: the unbounded wildcard ? in the source has the upper bound List<@Nullable String> (JLS 5.1.10) + """, + "BELOW_ROOT_BELOW_THE_IMPLICIT_BOUND_OF_A_SUBCLASS", + """ + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for B of Base -> upper bound of wildcard -> type argument for E of Holder -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: List + target: List>>> + ^^^^^^ """), """ static class Base {} @@ -404,6 +568,35 @@ void belowRoot(List l) { // BUG: Diagnostic matches: BELOW_ROOT takeList(l); } + static class Holder> {} + static class HolderSub extends Base> {} + static void takeHolder(Base>> b) {} + void belowTheImplicitBound(HolderSub s) { + // BUG: Diagnostic matches: BELOW_THE_IMPLICIT_BOUND + takeHolder(s); + } + static class MapOfHolderSub extends Base>> {} + static void takeMapOfHolder( + Base>>> b) {} + void belowTheImplicitBoundInsideAMap(MapOfHolderSub s) { + // BUG: Diagnostic matches: BELOW_THE_IMPLICIT_BOUND_INSIDE_A_MAP + takeMapOfHolder(s); + } + static class NonNullHolder> extends Holder {} + static class NonNullHolderSub extends Base> {} + void belowTheImplicitBoundOfASubclass(NonNullHolderSub s) { + // BUG: Diagnostic matches: BELOW_THE_IMPLICIT_BOUND_OF_A_SUBCLASS + takeHolder(s); + } + static void takeListOfHolder(List>>> l) {} + void belowRootBelowTheImplicitBound(List l) { + // BUG: Diagnostic matches: BELOW_ROOT_BELOW_THE_IMPLICIT_BOUND + takeListOfHolder(l); + } + void belowRootBelowTheImplicitBoundOfASubclass(List l) { + // BUG: Diagnostic matches: BELOW_ROOT_BELOW_THE_IMPLICIT_BOUND_OF_A_SUBCLASS + takeListOfHolder(l); + } """); } From ce35094a756b0787e2f1aa31aaab99bbaf826732 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Tue, 1 Dec 2026 13:44:33 +0300 Subject: [PATCH 43/43] Name a bound's type parameter only where it declares the compared bound A note named the wildcard's own type parameter wherever its bound had the compared bound's nullness at one node, so SubL> got a note stating a bound the check did not compare (#2206). The note now names that type parameter only where its declared bound prints as the compared bound does at every node, after substituting the type arguments the holder's class passes; otherwise there is no note. TopSub, whose bound is a subclass of the compared one, loses its note (#2224). The "the bound is @Nullable because X is unannotated" ending now names the class whose bound the check compared, and appears only where the types differ at the bound itself and both that bound and the named type parameter's bound carry NullAway's synthetic @Nullable for unannotated code, not one written in the source or substituted by capture conversion. A source supertype line is printed only where it carries a caret, and a type line carries one run of carets. HIDDEN tracks and hidden bounds are decided by one predicate. The test invariants now match the four-space type lines they were meant to check, and require that a note with the unannotated ending states a top-level @Nullable bound under a path that ends at the wildcard's upper bound. User-visible: SubL passed as Base, where SubL> extends Base, prints no note. @NullUnmarked NestedLegacy> passed as NestedLegacy> prints its note without "; the bound is @Nullable because NestedLegacy is unannotated". Assisted-by: Claude Code (claude-opus-5-5) --- .../GenericTypePrettyPrintingVisitor.java | 53 +- .../uber/nullaway/generics/GenericsUtils.java | 17 + .../generics/NullabilityMismatchMessage.java | 306 +++++---- .../generics/NullabilityMismatches.java | 51 +- .../jspecify/mismatchmessage/CaretTests.java | 44 ++ .../MismatchMessageTestBase.java | 269 +++++++- .../jspecify/mismatchmessage/NoteTests.java | 638 ++++++++++++++---- .../mismatchmessage/TopLevelNullableTest.java | 34 + .../mismatchmessage/TraversalCostTests.java | 3 + .../mismatchmessage/ViewedSourceTests.java | 75 ++ 10 files changed, 1174 insertions(+), 316 deletions(-) create mode 100644 nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TopLevelNullableTest.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 c76711ccb3..12f299a53a 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java @@ -59,6 +59,13 @@ final class GenericTypePrettyPrintingVisitor /** The position of the node being printed, maintained as the visitor descends. */ private TypePath currentPath = TypePath.root(); + /** + * Whether the type being printed is a part of the node at {@link #currentPath}, such as a + * component of an intersection or the wildcard a capture captured, printed at that node's path. + * The node takes the one bracket for its path, so a part is not bracketed. + */ + private boolean printingPart = false; + GenericTypePrettyPrintingVisitor(VisitorState state) { this(state, List.of()); } @@ -73,8 +80,14 @@ final class GenericTypePrettyPrintingVisitor this.markedPaths = markedPaths; } - /** Brackets {@code printed} when the node being printed sits at one of the requested paths. */ + /** + * Brackets {@code printed} when the node being printed sits at one of the requested paths and is + * not a part of another node printed at that path. + */ private String mark(String printed) { + if (printingPart) { + return printed; + } StringBuilder indices = new StringBuilder(); for (int i = 0; i < markedPaths.size(); i++) { TypePath markedPath = markedPaths.get(i); @@ -87,25 +100,31 @@ private String mark(String printed) { : MARK_START + indices.toString() + MARK_TEXT + printed + MARK_END; } - /** Strips the bracket around {@code printed}, where the whole of it is one marked node. */ - private static String withoutOuterMark(String printed) { - int text = printed.indexOf(MARK_TEXT); - return printed.length() > 2 - && printed.charAt(0) == MARK_START - && text > 0 - && printed.charAt(printed.length() - 1) == MARK_END - ? printed.substring(text + 1, 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; + boolean enclosingIsPart = printingPart; currentPath = enclosingPath.then(step); + printingPart = false; try { return child.accept(this, null); } finally { currentPath = enclosingPath; + printingPart = enclosingIsPart; + } + } + + /** + * Prints {@code part}, a part of the node being printed that no step reaches, at that node's path + * and without a bracket of its own; a node below {@code part} is bracketed as usual. + */ + private String printPart(Type part) { + boolean enclosingIsPart = printingPart; + printingPart = true; + try { + return part.accept(this, null); + } finally { + printingPart = enclosingIsPart; } } @@ -181,9 +200,7 @@ public String visitTypeVar(Type.TypeVar t, @Nullable Void unused) { } private String prettyIntersectionType(Type.IntersectionClassType t) { - return t.getBounds().stream() - .map(type -> ((Type) type).accept(this, null)) - .collect(joining(" & ")); + return t.getBounds().stream().map(type -> printPart((Type) type)).collect(joining(" & ")); } @Override @@ -192,9 +209,9 @@ public String visitCapturedType(Type.CapturedType t, @Nullable Void s) { appendNullableAnnotationIfPresent(t, sb); sb.append("capture of "); // 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))); + // GenericsUtils.asWildcard reads them, so the two agree on what a path addresses. The bracket + // of that node covers the annotation printed above + sb.append(printPart(t.wildcard)); return mark(sb.toString()); } 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 a53e34d1cf..35aaadd422 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java @@ -8,6 +8,7 @@ import com.google.errorprone.suppliers.Suppliers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.MemberReferenceTree; +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; @@ -387,6 +388,22 @@ private static Type applyDeclarationUpperBoundNullabilityIfApplicable( return upperBound; } + /** + * Whether {@code type} is {@code @Nullable} at its top level by an annotation NullAway added + * rather than one written in the source, as {@link + * #applyDeclarationUpperBoundNullabilityIfApplicable} adds to the upper bound of a type variable + * of unannotated code that carries no nullness annotation of its own. + */ + static boolean hasSyntheticNullable(Type type, VisitorState state) { + Symbol.TypeSymbol synthetic = GenericsChecks.getSyntheticNullableAnnotType(state).tsym; + for (Attribute.TypeCompound annotation : type.getAnnotationMirrors()) { + if (annotation.type.tsym.equals(synthetic)) { + return true; + } + } + return false; + } + private static boolean hasNullnessAnnotation(Type type, Config config) { return isAnnotatedAsNonNull(type, config) || isAnnotatedAsNullable(type, config); } 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 0d400435e6..543c7ce777 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -68,7 +68,9 @@ * node to be a supertype of the target node, the target side reads {@code a supertype of} the * target node. That holds at the lower bound of a {@code ? super} wildcard and at the positions * compared inside it, as for {@code List>} against {@code List>}; inside a second {@code ? super} the sides turn back. + * super Box<@Nullable String>>}. Inside a second {@code ? super} the relation is swapped back: the + * check again requires the source node to be a subtype of the target node, and the target side + * names the target node itself. * *

A note explains itself in the entities the message already shows. Where the source wildcard is * marked on a printed type, the type the reader wrote or the {@code source supertype} line, the @@ -133,6 +139,12 @@ final class NullabilityMismatchMessage { */ private static final int TYPE_LABEL_WIDTH = SOURCE_LABEL.length(); + /** + * Called each time {@link #build} starts, or {@code null} where nobody listens. A test sets it to + * count the messages built, since building one reruns the nullability check over both types. + */ + static @Nullable Runnable buildListener; + /** * Builds the diagnostic for an assignment, a return, or an argument the nullability check * rejected. @@ -141,6 +153,10 @@ final class NullabilityMismatchMessage { * @param sourceType the type of the value assigned */ String build(Type targetType, Type sourceType) { + Runnable listener = buildListener; + if (listener != null) { + listener.run(); + } NullabilityMismatches recorded = new NullabilityMismatches(targetType, sourceType, state.getTypes(), config); new CheckIdenticalNullabilityVisitor(state, checks, config, handler, recorded) @@ -303,57 +319,71 @@ private MarkedType markedTypeLines( String label, int labelWidth, 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(); + // marks nest where a marked node holds another, so each open mark waits on a stack for its end + ArrayDeque open = new ArrayDeque<>(); + List spans = new ArrayList<>(); 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; - } - // one node may carry several indices, where two mismatches share its caret - List indices = new ArrayList<>(); - i++; - while (i < printed.length() - && printed.charAt(i) != GenericTypePrettyPrintingVisitor.MARK_TEXT) { - indices.add(Integer.toString(printed.charAt(i) - '0' + 1)); + if (c == GenericTypePrettyPrintingVisitor.MARK_START) { + // one node may carry several indices, where two mismatches share its caret + List indices = new ArrayList<>(); i++; + while (i < printed.length() + && printed.charAt(i) != GenericTypePrettyPrintingVisitor.MARK_TEXT) { + indices.add(Integer.toString(printed.charAt(i) - '0' + 1)); + i++; + } + // the loop's own i++ steps over MARK_TEXT + open.push(new OpenMark(stripped.length(), indices)); + marks += indices.size(); + } else if (c == GenericTypePrettyPrintingVisitor.MARK_END) { + // the printer closes every mark it opens, inside the mark around it + OpenMark mark = open.pop(); + spans.add(new MarkSpan(mark.start(), stripped.length(), open.size(), mark.indices())); + } else { + stripped.append(c); } i++; - int start = stripped.length(); - while (i < printed.length() - && printed.charAt(i) != GenericTypePrettyPrintingVisitor.MARK_END) { - stripped.append(printed.charAt(i)); - i++; + } + // one caret row, and one number row where numbered, for each depth of nesting, outermost + // first, so a node marked inside a marked node still gets a run of its own + spans.sort(Comparator.comparingInt(MarkSpan::depth).thenComparingInt(MarkSpan::start)); + List rows = new ArrayList<>(); + StringBuilder carets = new StringBuilder(); + StringBuilder numbers = new StringBuilder(); + int depth = -1; + for (MarkSpan span : spans) { + if (span.depth() != depth) { + depth = span.depth(); + carets = new StringBuilder(); + numbers = new StringBuilder(); + rows.add(carets); + if (numbered) { + rows.add(numbers); + } } - i++; - padTo(carets, start).append("^".repeat(Math.max(stripped.length() - start, 1))); - padTo(numbers, start).append(String.join(",", indices)); - marks += indices.size(); + padTo(carets, span.start()).append("^".repeat(Math.max(span.end() - span.start(), 1))); + padTo(numbers, span.start()).append(String.join(",", span.indices())); } String prefix = " " + padTo(new StringBuilder(label + ":"), labelWidth + 1) + " "; - // 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_TEXT), "") - .replace(String.valueOf(GenericTypePrettyPrintingVisitor.MARK_END), ""); - if (carets.length() > 0) { - line += "\n" + " ".repeat(prefix.length()) + carets; - if (numbered) { - line += "\n" + " ".repeat(prefix.length()) + numbers; - } + String line = "\n" + prefix + stripped; + for (StringBuilder row : rows) { + line += "\n" + " ".repeat(prefix.length()) + row; } return new MarkedType(line, marks); } + /** A mark whose start the parse has passed and whose end it has not reached yet. */ + private record OpenMark(int start, List indices) {} + + /** + * The columns of one marked node in the printed type, from {@code start} to {@code end}, the + * number of marked nodes around it, and the one-based numbers of the mismatches it marks. + */ + private record MarkSpan(int start, int end, int depth, List indices) {} + /** * A printed type and the number of requested positions the printer marked in it, counting a node * that carries several of them once for each. @@ -448,15 +478,14 @@ private String mismatchDetail( caret = printedViewCaret(mismatch, printedView); printed = printedView; } - TypePath.Step reachingStep = - caret == null || caret.isRoot() ? null : caret.steps().get(caret.steps().size() - 1); + TypePath.Step reachingStep = caret == null ? null : caret.lastStep(); // the class the wildcard is a type argument of, printed so the reader can find that ? PrintedHolder holder = null; if (printed != null && caret != null && reachingStep != null && reachingStep.kind() == TypePath.Step.Kind.TYPE_ARGUMENT - && nodeAt(printed, caret.steps().subList(0, caret.steps().size() - 1)) + && nodeAt(printed, Objects.requireNonNull(caret.parent()).steps()) instanceof Type.ClassType holderClass) { holder = new PrintedHolder( 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 4212f9638c..e0691165c5 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java @@ -2,6 +2,8 @@ import com.google.common.collect.ImmutableList; import com.sun.tools.javac.code.Type; +import java.util.Objects; +import java.util.function.IntConsumer; import java.util.stream.Collectors; import org.jspecify.annotations.Nullable; @@ -86,12 +88,28 @@ String describe() { } } - private static final TypePath ROOT = new TypePath(ImmutableList.of()); + private static final TypePath ROOT = new TypePath(null, null, 0); - private final ImmutableList steps; + /** + * Called with the number of {@link Step} references each {@link #then} stores in the path it + * returns, or {@code null} where nobody listens. A test sets it to show that descending one level + * stores one step, not a copy of every step above it. + */ + static @Nullable IntConsumer stepsStoredListener; + + /** The path this one extends by {@link #last}, or {@code null} for the root. */ + private final @Nullable TypePath parent; + + /** The last descent of this path, or {@code null} for the root. */ + private final @Nullable Step last; - private TypePath(ImmutableList steps) { - this.steps = steps; + /** The number of steps from the root. */ + private final int depth; + + private TypePath(@Nullable TypePath parent, @Nullable Step last, int depth) { + this.parent = parent; + this.last = last; + this.depth = depth; } /** The path of the type itself, which no step has descended from. */ @@ -99,29 +117,56 @@ static TypePath root() { return ROOT; } - /** Returns this path extended by {@code step}. */ + /** + * Returns this path extended by {@code step}. The new path shares this one rather than copying + * it, so descending one level of a type costs the same at any depth. + */ TypePath then(Step step) { - return new TypePath(ImmutableList.builder().addAll(steps).add(step).build()); + IntConsumer listener = stepsStoredListener; + if (listener != null) { + listener.accept(1); + } + return new TypePath(this, step, depth + 1); } /** Returns the descents from the root, in order. */ ImmutableList steps() { - return steps; + Step[] steps = new Step[depth]; + TypePath path = this; + for (int i = depth - 1; i >= 0; i--) { + steps[i] = Objects.requireNonNull(path.last); + path = Objects.requireNonNull(path.parent); + } + return ImmutableList.copyOf(steps); + } + + /** Returns the last descent of this path, or {@code null} for the root. */ + @Nullable Step lastStep() { + return last; + } + + /** Returns the path this one extends by its last step, or {@code null} for the root. */ + @Nullable TypePath parent() { + return parent; } boolean isRoot() { - return steps.isEmpty(); + return depth == 0; } /** Whether this path and {@code other} address the same node. */ boolean reachesSameNodeAs(TypePath other) { - if (steps.size() != other.steps.size()) { + if (depth != other.depth) { return false; } - for (int i = 0; i < steps.size(); i++) { - if (!steps.get(i).reachesSameNodeAs(other.steps.get(i))) { + TypePath path = this; + TypePath otherPath = other; + while (path.last != null && otherPath.last != null) { + if (!path.last.reachesSameNodeAs(otherPath.last)) { return false; } + path = Objects.requireNonNull(path.parent); + otherPath = Objects.requireNonNull(otherPath.parent); } return true; } @@ -132,6 +177,6 @@ boolean reachesSameNodeAs(TypePath other) { * encoding that has no arrow character. */ String describe() { - return steps.stream().map(Step::describe).collect(Collectors.joining(" -> ")); + return steps().stream().map(Step::describe).collect(Collectors.joining(" -> ")); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java new file mode 100644 index 0000000000..ba2b5736f6 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java @@ -0,0 +1,94 @@ +package com.uber.nullaway.generics; + +import static com.google.common.truth.Truth.assertWithMessage; + +import com.google.errorprone.CompilationTestHelper; +import com.uber.nullaway.NullAway; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.IntStream; +import org.junit.Test; + +/** + * Building a generic nullability mismatch message reruns the check over both types, so it is + * skipped for a mismatch whose error is suppressed, and the paths it follows cost one stored step + * per level of a type, however deep. + */ +public class MismatchMessageWorkTests { + + @Test + public void aMismatchInAnExcludedNestedClassBuildsNoMessage() { + AtomicInteger builds = new AtomicInteger(); + NullabilityMismatchMessage.buildListener = builds::incrementAndGet; + try { + CompilationTestHelper.newInstance(NullAway.class, getClass()) + .setArgs( + JSpecifyJavacConfig.withJSpecifyModeArgs( + List.of( + "-XepOpt:NullAway:OnlyNullMarked=true", + "-XepOpt:NullAway:ExcludedClassAnnotations=Test.Excluded"))) + .addSourceLines( + "Test.java", + """ + import java.util.Collection; + import java.util.List; + import org.jspecify.annotations.NullMarked; + @NullMarked + class Test { + @interface Excluded {} + static void take(Collection c) {} + static List make() { + throw new RuntimeException(); + } + @Excluded + static class Inner { + void assignment() { + List l = make(); + Collection c = l; + } + void argument() { + take(make()); + } + Collection returned() { + return make(); + } + } + void reported() { + // BUG: Diagnostic contains: incompatible nullability in type argument for E of Collection + take(make()); + } + } + """) + .doTest(); + } finally { + NullabilityMismatchMessage.buildListener = null; + } + assertWithMessage( + "NullAway checks an excluded nested class and drops its errors as suppressed, so only" + + " the mismatch outside it builds a message") + .that(builds.get()) + .isEqualTo(1); + } + + @Test + public void eachDescentStoresOneStepHoweverDeepThePath() { + int depth = 50; + AtomicInteger stored = new AtomicInteger(); + TypePath.stepsStoredListener = stored::addAndGet; + TypePath path = TypePath.root(); + try { + for (int i = 0; i < depth; i++) { + path = path.then(TypePath.Step.typeArgument(i, null)); + } + } finally { + TypePath.stepsStoredListener = null; + } + assertWithMessage("steps stored to reach depth %s, one per descent", depth) + .that(stored.get()) + .isEqualTo(depth); + assertWithMessage("type argument indices of the steps, root first") + .that(path.steps().stream().map(TypePath.Step::index).toList()) + .containsExactlyElementsIn(IntStream.range(0, depth).boxed().toList()) + .inOrder(); + } +} 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 34a415f955..ff8ab9615d 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 @@ -477,4 +477,102 @@ void test(Outer<@Nullable String>.SubInner s) { } """); } + + @Test + public void eachOfTwoNestedNodesTheViewMarksGetsItsOwnCaretRow() { + assertMessages( + Map.of( + "NESTED_PAIR", + """ + incompatible nullability in type argument for A of Pair -> upper bound of wildcard and 1 other differing position: source has @Nullable List<@Nullable String> where target requires List<@Nullable String> + source: Same<@Nullable List<@Nullable String>> + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 1 + ^^^^^^^^^^^^^^^^ + 2 + target: Pair, ? extends @Nullable List> + ^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: type argument for A of Pair -> upper bound of wildcard + source: @Nullable List<@Nullable String> + target: List<@Nullable String> + \s + 2. path: type argument for B of Pair -> upper bound of wildcard -> type argument for E of List + source: @Nullable String + target: String + """, + "SIBLING_AFTER_A_NESTED_PAIR", + """ + incompatible nullability in type argument for A of Triple -> upper bound of wildcard and 2 other differing positions: source has @Nullable List<@Nullable String> where target requires List<@Nullable String> + source: SameThenOther<@Nullable List<@Nullable String>, @Nullable String> + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ + 1 3 + ^^^^^^^^^^^^^^^^ + 2 + target: Triple, ? extends @Nullable List, String> + ^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^ ^^^^^^ + 1 2 3 + \s + 1. path: type argument for A of Triple -> upper bound of wildcard + source: @Nullable List<@Nullable String> + target: List<@Nullable String> + \s + 2. path: type argument for B of Triple -> upper bound of wildcard -> type argument for E of List + source: @Nullable String + target: String + \s + 3. path: type argument for C of Triple + source: @Nullable String + target: String + """, + "THREE_DEEP", + """ + incompatible nullability in type argument for A of Triple -> upper bound of wildcard and 2 other differing positions: source has @Nullable List<@Nullable List<@Nullable String>> where target requires List<@Nullable List<@Nullable String>> + source: Thrice<@Nullable List<@Nullable List<@Nullable String>>> + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 1 + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 2 + ^^^^^^^^^^^^^^^^ + 3 + target: Triple>, ? extends @Nullable List>, ? extends @Nullable List<@Nullable List>> + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^ + 1 2 3 + \s + 1. path: type argument for A of Triple -> upper bound of wildcard + source: @Nullable List<@Nullable List<@Nullable String>> + target: List<@Nullable List<@Nullable String>> + \s + 2. path: type argument for B of Triple -> upper bound of wildcard -> type argument for E of List + source: @Nullable List<@Nullable String> + target: List<@Nullable String> + \s + 3. path: type argument for C of Triple -> upper bound of wildcard -> type argument for E of List -> type argument for E of List + source: @Nullable String + target: String + """), + """ + interface Pair {} + interface Triple {} + interface Same extends Pair {} + interface SameThenOther extends Triple {} + interface Thrice extends Triple {} + static void takePair(Pair, ? extends @Nullable List> p) {} + static void takeTriple(Triple, ? extends @Nullable List, String> t) {} + static void takeThrice(Triple>, ? extends @Nullable List>, ? extends @Nullable List<@Nullable List>> t) {} + void nestedPair(Same<@Nullable List<@Nullable String>> s) { + // BUG: Diagnostic matches: NESTED_PAIR + takePair(s); + } + void siblingAfterANestedPair(SameThenOther<@Nullable List<@Nullable String>, @Nullable String> s) { + // BUG: Diagnostic matches: SIBLING_AFTER_A_NESTED_PAIR + takeTriple(s); + } + void threeDeep(Thrice<@Nullable List<@Nullable List<@Nullable String>>> s) { + // BUG: Diagnostic matches: THREE_DEEP + takeThrice(s); + } + """); + } } From 9e5c423bf1cac998a3d8dbf8496ada6866271d79 Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Mon, 30 Nov 2026 18:35:13 +0300 Subject: [PATCH 37/43] Put a caret number that would collide on its own row Each caret's number started under the first column of its caret, on one row per level of nesting. Where a number was wider than the gap to the next caret, the two ran together. For `ThreeAndTwo`, whose wildcards hide three and two differences, the row read `1,2,34,5`. A number now goes on the first number row of its level that leaves a space before it, and a new row opens where none does. A level's number rows all come before the next level's caret row. Output where no numbers collide is unchanged. The test that `TypePath.then` shares its parent counted `then` calls through a hook that always reported one stored step, so a `then` that copied the path still passed it. The hook is gone. The test now checks that each new path's parent is the path it extends, and that `TypePath` has no instance fields but its parent, its last step, and its depth. User-visible: On a numbered `source:` or `target:` line, a caret number that would run into the one before it is printed on another row under its caret. Assisted-by: Claude Code (claude-opus-5-5) --- .../generics/NullabilityMismatchMessage.java | 49 +++++-- .../com/uber/nullaway/generics/TypePath.java | 12 -- .../generics/MismatchMessageWorkTests.java | 45 +++--- .../jspecify/mismatchmessage/CaretTests.java | 128 ++++++++++++++++++ 4 files changed, 195 insertions(+), 39 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 fa8ee33382..078e98457b 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -83,7 +83,9 @@ * no source caret. Two differences below one printed node share its caret, numbered for each. Where * a marked node holds another marked node, as where a supertype view puts one type argument of the * source at two positions, each node gets its own caret run, on one row per level of nesting with - * the outermost row first, and its number in a row below its run. + * the outermost row first, and its number in a row below its run. A number starts under the first + * column of its run, and where it would run into the number before it, it goes on another row + * below, still above the carets of the next level. * *

The first lookup in a compilation unit walks it once and indexes every local variable * declaration it holds; later lookups in the same unit read the index, so a unit with many - * diagnostics is walked once rather than once per diagnostic. {@link #clear} drops the index, which - * otherwise keeps the trees of the unit alive. + * diagnostics is walked once rather than once per diagnostic. The same walk notes the declarations + * that share their type tree with another variable, as each variable of {@code List a, b;} does. + * {@link #clear} drops the index, which otherwise keeps the trees of the unit alive. */ final class LocalVariableDeclarations { @@ -34,6 +39,12 @@ final class LocalVariableDeclarations { private final Map paths = new HashMap<>(); + /** The first variable declared with each type tree of the indexed unit. */ + private final IdentityHashMap firstByTypeTree = new IdentityHashMap<>(); + + /** The declarations of the indexed unit whose type tree another variable also has. */ + private final Set sharingTypeTree = Sets.newIdentityHashSet(); + /** * Returns the path to the declaration of {@code variable} in {@code compilationUnit}, or {@code * null} where {@code variable} is not a local variable declared there. @@ -48,10 +59,20 @@ final class LocalVariableDeclarations { return paths.get(variable); } + /** + * Whether {@code declaration}, a local variable declaration of the compilation unit last passed + * to {@link #find}, shares its type tree with another variable. + */ + boolean sharesTypeTree(VariableTree declaration) { + return sharingTypeTree.contains(declaration); + } + /** Forgets the indexed compilation unit. */ void clear() { unit = null; paths.clear(); + firstByTypeTree.clear(); + sharingTypeTree.clear(); } private void index(CompilationUnitTree compilationUnit) { @@ -59,7 +80,7 @@ private void index(CompilationUnitTree compilationUnit) { if (listener != null) { listener.accept(compilationUnit); } - paths.clear(); + clear(); unit = compilationUnit; new TreePathScanner<@Nullable Void, @Nullable Void>() { @Override @@ -67,6 +88,14 @@ private void index(CompilationUnitTree compilationUnit) { Symbol symbol = ASTHelpers.getSymbol(variable); if (symbol != null && symbol.getKind() == ElementKind.LOCAL_VARIABLE) { paths.put(symbol, getCurrentPath()); + Tree typeTree = variable.getType(); + if (typeTree != null) { + VariableTree first = firstByTypeTree.putIfAbsent(typeTree, variable); + if (first != null) { + sharingTypeTree.add(first); + sharingTypeTree.add(variable); + } + } } return super.visitVariable(variable, 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 index f7154a2e17..aff7b44b9b 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -11,7 +11,6 @@ import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; -import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Attribute; import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Symbol; @@ -303,7 +302,7 @@ private void appendFix( if (typeTree == null || ASTHelpers.hasImplicitType(declaration, state)) { return; // diff-coverage: ignore -- javac versions differ in whether var gets a type tree } - if (sharesTypeTree(declarationPath)) { + if (checks.localVariableDeclarations().sharesTypeTree(declaration)) { return; } SuggestedFix.Builder fix = SuggestedFix.builder(); @@ -313,29 +312,6 @@ private void appendFix( fixes.add(fix.replace(typeTree, printed).build()); } - /** - * Whether the declaration at {@code declarationPath} shares its type tree with another variable, - * as each variable of {@code List a, b;} does. - */ - private static boolean sharesTypeTree(TreePath declarationPath) { - VariableTree declaration = (VariableTree) declarationPath.getLeaf(); - Tree typeTree = declaration.getType(); - Boolean shared = - new TreeScanner() { - @Override - public Boolean visitVariable(VariableTree variable, @Nullable Void unused) { - return (variable != declaration && variable.getType() == typeTree) - || Boolean.TRUE.equals(super.visitVariable(variable, null)); - } - - @Override - public Boolean reduce(@Nullable Boolean left, @Nullable Boolean right) { - return Boolean.TRUE.equals(left) || Boolean.TRUE.equals(right); - } - }.scan(declarationPath.getParentPath().getLeaf(), null); - return Boolean.TRUE.equals(shared); - } - /** * Whether {@code declaration} writes a nullable annotation among its modifiers, where a type-use * annotation applies to the base type and lies outside the type tree. 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 cff7082437..ad79ec3dee 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java @@ -240,21 +240,29 @@ Frame enterClassComparison(Type rhs, Type rhsView) { /** * Returns {@code track} for a comparison that views {@code rhs}, the node {@code track} stands - * at, as {@code rhsView}: where that is another class, the comparison goes on in the supertype - * the written class declares. + * at, as {@code rhsView}: where that is another class, the comparison goes on in the supertype of + * {@code rhsView}'s class that the written class declares. A track that stands in a declared + * supertype at a node of the class of {@code rhs} goes on in that node's own supertype, so a view + * nested inside another, as {@code ArrayList} viewed as {@code List} inside {@code Sub + * implements Base>}, still reaches the type argument the reader wrote. */ private Track viewedAs(Track track, Type rhs, Type rhsView) { - if (track.state() != Track.State.LOCATED - || !(track.node() instanceof Type.ClassType written) - || !written.tsym.equals(rhs.tsym) - || written.tsym.equals(rhsView.tsym) - || !(rhsView.tsym instanceof Symbol.ClassSymbol viewClass)) { + if (rhs.tsym.equals(rhsView.tsym) || !(rhsView.tsym instanceof Symbol.ClassSymbol viewClass)) { return track; } - Type declared = TypeSubstitutionUtils.asSuper(types, written.tsym.type, viewClass, config); - return declared == null + Type declared = + switch (track.state()) { + case LOCATED -> track.node() instanceof Type.ClassType written ? written.tsym.type : null; + case DECLARED -> track.declared(); + case HIDDEN, LOST -> null; + }; + if (declared == null || !declared.tsym.equals(rhs.tsym)) { + return track; + } + Type view = TypeSubstitutionUtils.asSuper(types, declared, viewClass, config); + return view == null ? Track.lost(track) // diff-coverage: ignore -- a view is a supertype - : new Track(Track.State.DECLARED, written, track.path(), declared); + : new Track(Track.State.DECLARED, track.node(), track.path(), view); } /** Steps into type argument {@code index} of {@code lhs} and of {@code rhsView}. */ @@ -494,10 +502,19 @@ private static Track follow(Track track, Step step) { /** * Follows {@code step} in the supertype the written class of {@code track} declares. Where the * step reaches one of the class's own type variables, written without an annotation, the view - * holds the written type argument for it, and the track is located there. + * holds the written type argument for it, and the track is located there. A type variable written + * with an annotation, as in {@code Base>}, keeps the track in the declared + * supertype, since the annotation is not written at the argument; a step below it goes on from + * the written type argument. */ private static Track followDeclared(Track track, Step step) { Type declared = castToNonNull(track.declared()); + if (declared instanceof Type.TypeVar typeVariable && !(declared instanceof Type.CapturedType)) { + Track written = writtenArgumentFor(typeVariable, (Type.ClassType) track.node(), track.path()); + if (written != null) { + return follow(written, step); + } + } Type child = switch (step.kind()) { case TYPE_ARGUMENT -> diff --git a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java index bbad939376..ff7bb78bfb 100644 --- a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java @@ -21,10 +21,9 @@ public class MismatchMessageWorkTests { public void oneWalkOfTheCompilationUnitServesEveryLocalFix() { List walks = walksWhileCompiling( -""" + """ import java.util.Collection; import java.util.List; -import java.util.stream.Stream; import org.jspecify.annotations.NullMarked; @NullMarked class Test { @@ -86,10 +85,9 @@ void field() { public void aMismatchInAnExcludedNestedClassCostsNoWalk() { List walks = walksWhileCompiling( -""" + """ import java.util.Collection; import java.util.List; -import java.util.stream.Stream; import org.jspecify.annotations.NullMarked; @NullMarked class Test { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java index 5c8c1caa5c..26ba03305d 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FixTests.java @@ -500,9 +500,63 @@ void several() { take(first); take(second); } + void loop() { + for (List first = new ArrayList<>(), second = first; ; ) { + take(first); + } + } + void oldStyleCase(int k) { + switch (k) { + case 1: + List first = new ArrayList<>(), second = new ArrayList<>(); + take(first); + break; + default: + } + } + void besideSeveral() { + List first = new ArrayList<>(), second = new ArrayList<>(); + List alone = first; + take(alone); + } + } + """) + .addOutputLines( + "Test.java", + """ + import java.util.ArrayList; + import java.util.Collection; + import java.util.List; + import org.jspecify.annotations.NullMarked; + @NullMarked + class Test { + static void take(Collection c) {} + void several() { + List first = new ArrayList<>(), second = new ArrayList<>(); + take(first); + take(second); + } + void loop() { + for (List first = new ArrayList<>(), second = first; ; ) { + take(first); + } + } + void oldStyleCase(int k) { + switch (k) { + case 1: + List first = new ArrayList<>(), second = new ArrayList<>(); + take(first); + break; + default: + } + } + void besideSeveral() { + List first = new ArrayList<>(), second = new ArrayList<>(); + List alone = first; + take(alone); + } } """) - .expectUnchanged() .doTest(); } } 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 b314b3305d..dbc195b0fa 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 @@ -177,6 +177,57 @@ void passed(Elements<@Nullable String> e) { """); } + @Test + public void aViewNestedInADeclaredSupertypeStillReachesTheWrittenArgument() { + assertMessages( + Map.of( + "PASSED", + """ + incompatible nullability in Base type argument B -> wildcard upper bound -> List type argument E: source has @Nullable String where target requires String + source: Sub<@Nullable String> + ^^^^^^^^^^^^^^^^ + target: Base> + ^^^^^^ + """, + "BELOW_ANNOTATED", + """ + incompatible nullability in Base type argument B -> wildcard upper bound -> List type argument E -> List type argument E: source has @Nullable String where target requires String + source: Annotated> + ^^^^^^^^^^^^^^^^ + target: Base>> + ^^^^^^ + """, + "WRITTEN", + """ + incompatible nullability in Base type argument B -> wildcard upper bound -> List type argument E: source has @Nullable String where target requires String + source: Strings + source viewed as: Base> + ^^^^^^^^^^^^^^^^ + target: Base> + ^^^^^^ + """), + """ + interface Base {} + static final class Sub implements Base> {} + static final class Strings implements Base> {} + static void take(Base> b) {} + void passed(Sub<@Nullable String> s) { + // BUG: Diagnostic matches: PASSED + take(s); + } + static final class Annotated implements Base> {} + static void takeNested(Base>> b) {} + void belowAnnotated(Annotated> a) { + // BUG: Diagnostic matches: BELOW_ANNOTATED + takeNested(a); + } + void written(Strings s) { + // BUG: Diagnostic matches: WRITTEN + take(s); + } + """); + } + @Test public void eachComponentOfAnIntersectionTargetIsComparedUnderItsOwnView() { assertMessage( From 014cd5d5a927e9ae00f6581add9385fa06e1ce9e Mon Sep 17 00:00:00 2001 From: Vladimir Sitnikov Date: Sat, 28 Nov 2026 23:26:01 +0300 Subject: [PATCH 17/43] Withhold the declaration edit where brackets follow the name For `List a[] = many();` the declaration edit replaced the type tree javac builds for `a`, which spans the name and its brackets, so patch mode wrote `List[] = many();` without the name, and the result did not parse. The edit is now withheld where the type tree ends after the start of the name. In `List a = one(), b[] = many();` the two declarators have different type trees around one element type, so the index did not see that they share it, and the edit for `a` also rewrote `b`; the index now keys each local on its element type tree. A track that stands at a type variable of the written class in a declared supertype now goes on from the written type argument at a class comparison as well as at a step, so `Annotated implements Base>` passed as `Annotated>` keeps the caret on the written source. Assisted-by: Claude Code (claude-opus-5-5) --- .../generics/LocalVariableDeclarations.java | 31 +++++++++++++--- .../generics/NullabilityMismatchMessage.java | 5 ++- .../generics/NullabilityMismatches.java | 32 ++++++++++++---- .../jspecify/mismatchmessage/FixTests.java | 37 +++++++++++++++++++ .../mismatchmessage/ViewedSourceTests.java | 13 +++++++ 5 files changed, 103 insertions(+), 15 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java b/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java index 4e39c111e4..76292d8580 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/LocalVariableDeclarations.java @@ -3,6 +3,8 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Sets; import com.google.errorprone.util.ASTHelpers; +import com.sun.source.tree.AnnotatedTypeTree; +import com.sun.source.tree.ArrayTypeTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; @@ -23,8 +25,9 @@ *

A visitor given a {@link NullabilityMismatches} records every comparison it rejects there, and + * goes on comparing after a rejection rather than returning at the first, so that a diagnostic can + * name each position the check rejects. Its result is the same as without one. */ public class CheckIdenticalNullabilityVisitor extends Types.DefaultTypeVisitor { private final VisitorState state; @@ -32,6 +36,9 @@ public class CheckIdenticalNullabilityVisitor extends Types.DefaultTypeVisitor successfulWildcardComparisons; @@ -102,10 +109,91 @@ private record ContainmentKey( CheckIdenticalNullabilityVisitor( VisitorState state, GenericsChecks genericsChecks, Config config, Handler handler) { + this(state, genericsChecks, config, handler, null); + } + + /** + * Creates a visitor that records every comparison it rejects in {@code mismatches}, where that is + * not {@code null}. + */ + CheckIdenticalNullabilityVisitor( + VisitorState state, + GenericsChecks genericsChecks, + Config config, + Handler handler, + @Nullable NullabilityMismatches mismatches) { this.state = state; this.genericsChecks = genericsChecks; this.config = config; this.handler = handler; + this.mismatches = mismatches; + } + + /** + * Returns whether {@code rhsType} may be assigned to {@code lhsType} as far as the nullability of + * their type arguments goes. The nullness of the two types themselves is not compared. An array + * is covariant in the nullness of its elements at every dimension, so an array of non-null + * references is a subtype of an array of {@code @Nullable} ones; see jspecify/jspecify#65. + * + * @param lhsType type for the lhs of the assignment + * @param rhsType type for the rhs of the assignment + */ + boolean isSubtype(Type lhsType, Type rhsType) { + if (lhsType.isRaw()) { + return true; + } + if (lhsType instanceof Type.ArrayType lhsArrayType + && rhsType instanceof Type.ArrayType rhsArrayType) { + NullabilityMismatches.Frame saved = + mismatches == null ? null : mismatches.enterArrayElement(lhsArrayType, rhsArrayType); + try { + Type lhsComponentType = lhsArrayType.getComponentType(); + Type rhsComponentType = rhsArrayType.getComponentType(); + // an array of @Nullable references is _not_ a subtype of an array of @NonNull references + if (genericsChecks.isNullableAnnotated(rhsComponentType) + && !genericsChecks.isNullableAnnotated(lhsComponentType)) { + reject(NullabilityMismatches.Relation.SUBTYPE, lhsComponentType, rhsComponentType); + return false; + } + if (lhsComponentType instanceof Type.ArrayType + && rhsComponentType instanceof Type.ArrayType) { + // covariance applies at every dimension of a multi-dimensional array. An array nested + // inside a type argument is compared by visitArrayType, since generics are not covariant + return isSubtype(lhsComponentType, rhsComponentType); + } + return haveIdenticalNestedNullability(lhsComponentType, rhsComponentType); + } finally { + restore(saved); + } + } + return haveIdenticalNestedNullability(lhsType, rhsType); + } + + /** + * Returns whether the type arguments of {@code lhsType} and {@code rhsType} have identical + * nullability, without comparing the nullness of the two types themselves. + */ + @SuppressWarnings({"ReferenceEquality", "TypeEquals"}) // deliberate reference equality check + private boolean haveIdenticalNestedNullability(Type lhsType, Type rhsType) { + if (lhsType == rhsType) { + return true; + } + return lhsType.accept(this, rhsType); + } + + /** Records a rejected comparison, where this visitor records them. */ + private void reject(NullabilityMismatches.Relation relation, Type lhsNode, Type rhsNode) { + if (mismatches != null) { + mismatches.reject(relation, lhsNode, rhsNode); + } + } + + /** Puts back the frame an {@code enter} method of {@link #mismatches} returned. */ + private void restore(NullabilityMismatches.@Nullable Frame saved) { + if (mismatches != null && saved != null) { + mismatches.restore(saved); + } } /** @@ -137,7 +225,15 @@ public Boolean visitClassType(Type.ClassType lhsType, Type rhsType) { // Bail out if resolving the upper bound did not produce a usable concrete bound. return true; } - rhsType = rhsUpperBound; + NullabilityMismatches.Frame saved = + mismatches == null + ? null + : mismatches.enterUpperBounds(null, lhsType, rhsType, rhsUpperBound); + try { + return visitClassType(lhsType, rhsUpperBound); + } finally { + restore(saved); + } } if (lhsType.isIntersection()) { return handleIntersectionType((Type.IntersectionClassType) lhsType, rhsType); @@ -164,33 +260,47 @@ public Boolean visitClassType(Type.ClassType lhsType, Type rhsType) { throw new RuntimeException( "Number of types arguments in " + rhsTypeAsSuper + " does not match " + lhsType); } + Type.ClassType rhsClassTypeAsSuper = (Type.ClassType) rhsTypeAsSuper; List lhsUpperBounds = lhsTypeArguments; List rhsUpperBounds = rhsTypeArguments; ParameterizationKey lhsParameterization = null; ParameterizationKey rhsParameterization = null; if (config.handleWildcardGenerics()) { lhsParameterization = new ParameterizationKey(lhsType); - rhsParameterization = new ParameterizationKey((Type.ClassType) rhsTypeAsSuper); + rhsParameterization = new ParameterizationKey(rhsClassTypeAsSuper); lhsUpperBounds = GenericsUtils.effectiveUpperBoundsForTypeArguments(lhsType, state, config, handler); rhsUpperBounds = GenericsUtils.effectiveUpperBoundsForTypeArguments( - (Type.ClassType) rhsTypeAsSuper, state, config, handler); + rhsClassTypeAsSuper, state, config, handler); } + if (mismatches != null) { + mismatches.enterClassComparison(rhsType, rhsClassTypeAsSuper); + } + boolean contained = true; for (int i = 0; i < lhsTypeArguments.size(); i++) { Type lhsTypeArgument = lhsTypeArguments.get(i); Type lhsUpperBound = lhsUpperBounds.get(i); Type rhsTypeArgument = rhsTypeArguments.get(i); Type rhsUpperBound = rhsUpperBounds.get(i); - if (!typeArgumentContainedBy( - lhsTypeArgument, - rhsTypeArgument, - lhsUpperBound, - rhsUpperBound, - i, - lhsParameterization, - rhsParameterization)) { - return false; + NullabilityMismatches.Frame saved = + mismatches == null ? null : mismatches.enterTypeArgument(i, lhsType, rhsClassTypeAsSuper); + try { + if (!typeArgumentContainedBy( + lhsTypeArgument, + rhsTypeArgument, + lhsUpperBound, + rhsUpperBound, + i, + lhsParameterization, + rhsParameterization)) { + if (mismatches == null) { + return false; + } + contained = false; + } + } finally { + restore(saved); } } // If there is an enclosing type (for non-static inner classes), its type argument nullability @@ -198,14 +308,32 @@ public Boolean visitClassType(Type.ClassType lhsType, Type rhsType) { // object, which gets handled by the fallback visitType() method // We use rhsTypeAsSuper here rather than rhsType, since rhsType may be a captured type // variable, whose getEnclosingType() returns null. - return lhsType.getEnclosingType().accept(this, rhsTypeAsSuper.getEnclosingType()); + NullabilityMismatches.Frame saved = + mismatches == null ? null : mismatches.enterEnclosingType(lhsType, rhsClassTypeAsSuper); + try { + return lhsType.getEnclosingType().accept(this, rhsTypeAsSuper.getEnclosingType()) + && contained; + } finally { + restore(saved); + } } /** Check identical nullability for every type in the intersection */ private Boolean handleIntersectionType( Type.IntersectionClassType intersectionType, Type rhsType) { - return intersectionType.getBounds().stream() - .allMatch(type -> ((Type) type).accept(this, rhsType)); + boolean contained = true; + for (Type bound : intersectionType.getExplicitComponents()) { + if (!bound.accept(this, rhsType)) { + if (mismatches == null) { + return false; // diff-coverage: ignore -- no test reaches an intersection target that + // fails, here or on master + } + contained = + false; // diff-coverage: ignore -- no test reaches an intersection target that fails, + // here or on master + } + } + return contained; } @Override @@ -219,7 +347,13 @@ public Boolean visitArrayType(Type.ArrayType lhsType, Type rhsType) { return true; } Type rhsComponentType = rhsArrayType.getComponentType(); - return haveIdenticalNullability(lhsComponentType, rhsComponentType); + NullabilityMismatches.Frame saved = + mismatches == null ? null : mismatches.enterArrayElement(lhsType, rhsArrayType); + try { + return haveIdenticalNullability(lhsComponentType, rhsComponentType); + } finally { + restore(saved); + } } @Override @@ -303,6 +437,7 @@ private boolean haveIdenticalNullability(Type lhsType, Type rhsType) { boolean isLHSNullableAnnotated = genericsChecks.isNullableAnnotated(lhsType); boolean isRHSNullableAnnotated = genericsChecks.isNullableAnnotated(rhsType); if (isLHSNullableAnnotated != isRHSNullableAnnotated) { + reject(NullabilityMismatches.Relation.SAME, lhsType, rhsType); return false; } return lhsType.accept(this, rhsType); @@ -358,11 +493,14 @@ private boolean wildcardContains( try { boolean result = switch (lhsWildcard.kind) { - case UNBOUND, EXTENDS -> typeArgumentSubtype(lhsUpperBound, rhsUpperBound); + case UNBOUND, EXTENDS -> + upperBoundContains(lhsWildcard, lhsUpperBound, rhsTypeArgument, rhsUpperBound); case SUPER -> superWildcardContains(lhsWildcard, rhsTypeArgument); }; // A nested success may rely on an unfinished check, so cache results only after the outer - // check passes. A failure ends the traversal immediately; there is no failed result to reuse. + // check passes. A failed result is not cached: without a recorder the failure ends the + // check, and with one the provisional entry keeps the traversal from entering the same + // comparison twice within the outer check, so recording stays linear in the bound graph. if (outermost && result) { if (successfulWildcardComparisons == null) { successfulWildcardComparisons = new HashSet<>(); @@ -381,6 +519,27 @@ private boolean wildcardContains( } } + /** + * Returns whether the upper bound of the actual type argument on the right is a subtype of the + * upper bound of the formal {@code ? extends S} or {@code ?} on the left. + */ + private boolean upperBoundContains( + Type.WildcardType lhsWildcard, Type lhsUpperBound, Type rhsTypeArgument, Type rhsUpperBound) { + NullabilityMismatches.Frame saved = + mismatches == null + ? null + : mismatches.enterUpperBounds( + lhsWildcard, + lhsUpperBound, + GenericsUtils.asWildcard(rhsTypeArgument) == null ? null : rhsTypeArgument, + rhsUpperBound); + try { + return typeArgumentSubtype(lhsUpperBound, rhsUpperBound); + } finally { + restore(saved); + } + } + /** * 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,24 +558,40 @@ private boolean superWildcardContains(Type.WildcardType lhsWildcard, Type rhsTyp return true; } Type rhsBound = castToNonNull(rhsWildcard.getSuperBound()); - return typeArgumentSubtype(rhsBound, lhsBound); + NullabilityMismatches.Frame saved = + mismatches == null + ? null + : mismatches.enterLowerBounds(lhsWildcard, lhsBound, rhsTypeArgument, rhsBound); + try { + return typeArgumentSubtype(rhsBound, lhsBound); + } finally { + restore(saved); + } + } + NullabilityMismatches.Frame saved = + mismatches == null + ? null + : mismatches.enterLowerBounds(lhsWildcard, lhsBound, null, rhsTypeArgument); + try { + return typeArgumentSubtype(rhsTypeArgument, lhsBound); + } finally { + restore(saved); } - return typeArgumentSubtype(rhsTypeArgument, 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. + * the top level of the type argument, then compares the nested nullability with {@link + * #isSubtype}. */ private boolean typeArgumentSubtype(Type lhsType, Type rhsType) { boolean isLHSNullableAnnotated = genericsChecks.isNullableAnnotated(lhsType); boolean isRHSNullableAnnotated = genericsChecks.isNullableAnnotated(rhsType); if (isRHSNullableAnnotated && !isLHSNullableAnnotated) { + reject(NullabilityMismatches.Relation.SUBTYPE, lhsType, rhsType); return false; } - return genericsChecks.subtypeParameterNullability(lhsType, rhsType, state, this); + return isSubtype(lhsType, rhsType); } } 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 09021e5ca0..b369fc10f2 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java @@ -3,9 +3,12 @@ import static java.util.stream.Collectors.joining; import com.google.errorprone.VisitorState; +import com.google.errorprone.fixes.SuggestedFix; +import com.google.errorprone.fixes.SuggestedFixes; 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.Type; import com.sun.tools.javac.code.Types; import java.util.List; @@ -16,10 +19,11 @@ * use in error messages. * *