From e88109d21652b7ffc3313c92fedcf074a3420b33 Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Fri, 4 Dec 2026 18:36:00 -0800 Subject: [PATCH] Switch to default GJF version for Spotless --- build.gradle | 4 +- .../jarinfer/DefinitelyDerefedParams.java | 11 +- .../NullnessAnnotationSerializerTest.java | 25 +- .../java/com/uber/nullaway/ErrorBuilder.java | 7 +- .../main/java/com/uber/nullaway/NullAway.java | 132 +++++---- .../com/uber/nullaway/NullabilityUtil.java | 46 ++- .../dataflow/AccessPathNullnessAnalysis.java | 61 ++-- .../adapters/SerializationV3Adapter.java | 15 +- .../scanners/OriginScanner.java | 21 +- .../generics/ConstraintSolverImpl.java | 30 +- .../nullaway/generics/GenericsChecks.java | 267 +++++++++--------- ...estedTypeVarSubstitutionRepairVisitor.java | 2 +- .../handlers/LibraryModelsHandler.java | 2 +- .../uber/nullaway/handlers/LombokHandler.java | 7 +- .../com/uber/nullaway/ContractsTests.java | 28 +- .../uber/nullaway/DummyOptionsConfigTest.java | 2 +- .../uber/nullaway/EnsuresNonNullTests.java | 34 +-- .../com/uber/nullaway/FrameworkTests.java | 132 ++++----- .../uber/nullaway/JSpecifyJDKModelsTest.java | 6 +- .../com/uber/nullaway/NullAwayTestsBase.java | 5 +- ...CheckIdenticalNullabilityVisitorTests.java | 68 ++--- ...enericMethodLambdaOrMethodRefArgTests.java | 12 +- .../jspecify/JSpecifyLibraryModelsTests.java | 20 +- .../jspecify/VarDeclaredLocalTests.java | 6 +- .../uber/nullaway/jspecify/WildcardTests.java | 18 +- .../tools/SerializationTestHelper.java | 17 +- .../src/main/java/com/uber/mylib/Lambdas.java | 8 +- 27 files changed, 489 insertions(+), 497 deletions(-) diff --git a/build.gradle b/build.gradle index 4cfc8b5778..134c8d8a8f 100644 --- a/build.gradle +++ b/build.gradle @@ -163,7 +163,7 @@ subprojects { project -> project.apply plugin: "com.diffplug.spotless" spotless { java { - googleJavaFormat(libs.versions.google.java.format.get()) + googleJavaFormat() } } } @@ -180,7 +180,7 @@ spotless { } } spotlessPredeclare { - java { googleJavaFormat(libs.versions.google.java.format.get()) } + java { googleJavaFormat() } groovyGradle { greclipse() } diff --git a/jar-infer/jar-infer-lib/src/main/java/com/uber/nullaway/jarinfer/DefinitelyDerefedParams.java b/jar-infer/jar-infer-lib/src/main/java/com/uber/nullaway/jarinfer/DefinitelyDerefedParams.java index a94d70bd68..041628c9f8 100644 --- a/jar-infer/jar-infer-lib/src/main/java/com/uber/nullaway/jarinfer/DefinitelyDerefedParams.java +++ b/jar-infer/jar-infer-lib/src/main/java/com/uber/nullaway/jarinfer/DefinitelyDerefedParams.java @@ -133,12 +133,11 @@ private Set computeDerefParamList(int numParam, int firstParamIndex) { Map> blockToDerefSetMap = new HashMap<>(); // find which params are treated as being non-null inside each basic block - prunedCFG.forEach( - basicBlock -> { - Set derefParamSet = new HashSet<>(); - blockToDerefSetMap.put(basicBlock, derefParamSet); - checkForUseOfParams(derefParamSet, numParam, firstParamIndex, basicBlock); - }); + prunedCFG.forEach(basicBlock -> { + Set derefParamSet = new HashSet<>(); + blockToDerefSetMap.put(basicBlock, derefParamSet); + checkForUseOfParams(derefParamSet, numParam, firstParamIndex, basicBlock); + }); // For each param p, if no path exists from the entry block to the exit block which traverses // only basic blocks which do not require p being non-null (e.g. by dereferencing it), then diff --git a/jdk-javac-plugin/src/test/java/com/uber/nullaway/javacplugin/NullnessAnnotationSerializerTest.java b/jdk-javac-plugin/src/test/java/com/uber/nullaway/javacplugin/NullnessAnnotationSerializerTest.java index 0af6433648..45a1da15c9 100644 --- a/jdk-javac-plugin/src/test/java/com/uber/nullaway/javacplugin/NullnessAnnotationSerializerTest.java +++ b/jdk-javac-plugin/src/test/java/com/uber/nullaway/javacplugin/NullnessAnnotationSerializerTest.java @@ -776,19 +776,18 @@ private Map> getParsedJSON() { return stream .filter(path -> path.toString().endsWith(".json")) .findFirst() - .>>map( - path -> { - try { - return new GsonBuilder() - .registerTypeAdapter(ImmutableList.class, immutableListAdapter) - .create() - .fromJson( - new String(Files.readAllBytes(path), StandardCharsets.UTF_8), - new TypeToken>>() {}.getType()); - } catch (IOException e) { - throw new RuntimeException(e); - } - }) + .>>map(path -> { + try { + return new GsonBuilder() + .registerTypeAdapter(ImmutableList.class, immutableListAdapter) + .create() + .fromJson( + new String(Files.readAllBytes(path), StandardCharsets.UTF_8), + new TypeToken>>() {}.getType()); + } catch (IOException e) { + throw new RuntimeException(e); + } + }) .orElseThrow(); } catch (IOException e) { throw new RuntimeException(e); diff --git a/nullaway/src/main/java/com/uber/nullaway/ErrorBuilder.java b/nullaway/src/main/java/com/uber/nullaway/ErrorBuilder.java index 50b36cbf10..0defce4021 100755 --- a/nullaway/src/main/java/com/uber/nullaway/ErrorBuilder.java +++ b/nullaway/src/main/java/com/uber/nullaway/ErrorBuilder.java @@ -337,10 +337,9 @@ private boolean hasPathSuppression(TreePath treePath, String subcheckerName) { .filter(ErrorBuilder::canHaveSuppressWarningsAnnotation) .map(ASTHelpers::getSymbol) .filter(Objects::nonNull) - .anyMatch( - symbol -> - symbolHasSuppressWarningsAnnotation(symbol, subcheckerName) - || symbolIsExcludedClassSymbol(symbol)); + .anyMatch(symbol -> + symbolHasSuppressWarningsAnnotation(symbol, subcheckerName) + || symbolIsExcludedClassSymbol(symbol)); } private Description.Builder addSuggestedSuppression( diff --git a/nullaway/src/main/java/com/uber/nullaway/NullAway.java b/nullaway/src/main/java/com/uber/nullaway/NullAway.java index 3d14539462..ba3998c813 100644 --- a/nullaway/src/main/java/com/uber/nullaway/NullAway.java +++ b/nullaway/src/main/java/com/uber/nullaway/NullAway.java @@ -1406,21 +1406,20 @@ private GenericsChecks.ValueTarget lambdaReturnTarget( VisitorState callState = state.withPath(parentPath); List targets = new ArrayList<>(1); new InvocationArguments(call, invokedMethodTypeAtCall(call, callee)) - .forEach( - (actual, argPos, formalParamType, varArgsPassedAsArray) -> { - if (ASTHelpers.stripParentheses(actual) == lambdaTree) { - int paramIndex = Math.min(argPos, callee.getParameters().size() - 1); - targets.add( - genericsChecks.getLambdaArgumentReturnTarget( - callee, - call, - formalParamType, - paramIndex, - isVarargsPosition(callee, paramIndex) && !varArgsPassedAsArray, - functionalInterfaceMethod, - callState)); - } - }); + .forEach((actual, argPos, formalParamType, varArgsPassedAsArray) -> { + if (ASTHelpers.stripParentheses(actual) == lambdaTree) { + int paramIndex = Math.min(argPos, callee.getParameters().size() - 1); + targets.add( + genericsChecks.getLambdaArgumentReturnTarget( + callee, + call, + formalParamType, + paramIndex, + isVarargsPosition(callee, paramIndex) && !varArgsPassedAsArray, + functionalInterfaceMethod, + callState)); + } + }); // diff-coverage: ignore -- the lambda is one of the call's arguments return targets.isEmpty() ? GenericsChecks.ValueTarget.EXCLUDES_NULL : targets.get(0); } @@ -2012,7 +2011,7 @@ private ImmutableMultimap computeTree2Init( } } // all the initializer blocks have run before any code inside a constructor - constructors.forEach((c) -> builder.putAll(c, initThusFar)); + constructors.forEach(c -> builder.putAll(c, initThusFar)); Symbol.ClassSymbol classSymbol = ASTHelpers.getSymbol(enclosingClass); FieldInitEntities entities = castToNonNull(class2Entities.get(classSymbol)); if (entities.instanceInitializerMethods().size() == 1) { @@ -2607,56 +2606,55 @@ private Description handleInvocation( // now actually check the arguments // NOTE: the case of an invocation on a possibly-null reference // is handled by matchMemberSelect() - invArgs.forEach( - (actual, argPos, formalParamType, varArgsPassedAsArray) -> { - // always do unboxing checks, whether or not the invoked method is annotated - if (formalParamType.isPrimitive()) { - doUnboxingCheck(state, actual); - return; - } - if (argPos >= formalParams.size()) { - // extra varargs argument; nullness info stored in the varargs parameter slot - argPos = formalParams.size() - 1; - } - // An array passed explicitly in the position of the varargs parameter has the nullness - // of the varargs array - Nullness paramNullness = - varArgsPassedAsArray - ? finalArgumentNullness.getVarargsArrayNullness() - : finalArgumentNullness.getParameterNullness(argPos); - if (paramNullness != Nullness.NONNULL) { - // Preserve the fast path for nullable and unannotated parameters. - return; - } - int paramIndex = argPos; - if (!isTopLevelNullnessCompatible( - actual, - () -> - varArgsPassedAsArray || finalArgumentNullness.wasSet(paramIndex) - ? GenericsChecks.ValueTarget.EXCLUDES_NULL - : genericsChecks.getParameterTarget( - methodSymbol, - tree, - formalParamType, - paramIndex, - isVarargsPosition(methodSymbol, paramIndex), - state), - Nullness.NONNULL, - state)) { - state.reportMatch( - errorBuilder.createErrorDescriptionForNullAssignment( - new ErrorMessage( - MessageTypes.PASS_NULLABLE, - "passing @Nullable parameter '" - + state.getSourceForNode(actual) - + "' where @NonNull is required"), - actual, - buildDescription(actual), - state, - formalParams.get(argPos), - actual)); - } - }); + invArgs.forEach((actual, argPos, formalParamType, varArgsPassedAsArray) -> { + // always do unboxing checks, whether or not the invoked method is annotated + if (formalParamType.isPrimitive()) { + doUnboxingCheck(state, actual); + return; + } + if (argPos >= formalParams.size()) { + // extra varargs argument; nullness info stored in the varargs parameter slot + argPos = formalParams.size() - 1; + } + // An array passed explicitly in the position of the varargs parameter has the nullness + // of the varargs array + Nullness paramNullness = + varArgsPassedAsArray + ? finalArgumentNullness.getVarargsArrayNullness() + : finalArgumentNullness.getParameterNullness(argPos); + if (paramNullness != Nullness.NONNULL) { + // Preserve the fast path for nullable and unannotated parameters. + return; + } + int paramIndex = argPos; + if (!isTopLevelNullnessCompatible( + actual, + () -> + varArgsPassedAsArray || finalArgumentNullness.wasSet(paramIndex) + ? GenericsChecks.ValueTarget.EXCLUDES_NULL + : genericsChecks.getParameterTarget( + methodSymbol, + tree, + formalParamType, + paramIndex, + isVarargsPosition(methodSymbol, paramIndex), + state), + Nullness.NONNULL, + state)) { + state.reportMatch( + errorBuilder.createErrorDescriptionForNullAssignment( + new ErrorMessage( + MessageTypes.PASS_NULLABLE, + "passing @Nullable parameter '" + + state.getSourceForNode(actual) + + "' where @NonNull is required"), + actual, + buildDescription(actual), + state, + formalParams.get(argPos), + actual)); + } + }); // Check for @NonNull being passed to castToNonNull (if configured) return checkCastToNonNullTakesNullable(tree, state, methodSymbol, actualParams); } @@ -2942,7 +2940,7 @@ private SetMultimap reportableConstructorInitializationInfo( private boolean symbolHasExternalInitAnnotation(Symbol symbol) { return StreamSupport.stream(NullabilityUtil.getAllAnnotations(symbol).spliterator(), false) - .map((anno) -> anno.getAnnotationType().toString()) + .map(anno -> anno.getAnnotationType().toString()) .anyMatch(config::isExternalInitClassAnnotation); } diff --git a/nullaway/src/main/java/com/uber/nullaway/NullabilityUtil.java b/nullaway/src/main/java/com/uber/nullaway/NullabilityUtil.java index b82385e9ce..37df1df7e7 100644 --- a/nullaway/src/main/java/com/uber/nullaway/NullabilityUtil.java +++ b/nullaway/src/main/java/com/uber/nullaway/NullabilityUtil.java @@ -308,7 +308,7 @@ public static boolean hasAnyAnnotationMatching(Symbol symbol, Predicate if (elem.getSimpleName().contentEquals("value")) { @SuppressWarnings("unchecked") List values = (List) entry.getValue().getValue(); - return values.stream().map((av) -> ((String) av.getValue())).collect(Collectors.toSet()); + return values.stream().map(av -> ((String) av.getValue())).collect(Collectors.toSet()); } } return null; @@ -378,11 +378,10 @@ public static Stream getAllAnnotationsForParameter( Stream.concat( varSymbol.type.getAnnotationMirrors().stream(), symbol.getRawTypeAttributes().stream() - .filter( - t -> - t.position.type.equals(TargetType.METHOD_FORMAL_PARAMETER) - && t.position.parameter_index == paramInd - && NullabilityUtil.isDirectTypeUseAnnotation(t, symbol))) + .filter(t -> + t.position.type.equals(TargetType.METHOD_FORMAL_PARAMETER) + && t.position.parameter_index == paramInd + && NullabilityUtil.isDirectTypeUseAnnotation(t, symbol))) .distinct(); return Stream.concat(varSymbol.getAnnotationMirrors().stream(), typeUseAnnotations); } @@ -413,16 +412,14 @@ private static Stream getTypeUseAnnotations( typeAnnotationOwner.getRawTypeAttributes().stream(); if (symbol instanceof Symbol.MethodSymbol) { // for methods, we want annotations on the return type - return rawTypeAttributes.filter( - (t) -> - t.position.type.equals(TargetType.METHOD_RETURN) - && (!onlyDirect || isDirectTypeUseAnnotation(t, symbol))); + return rawTypeAttributes.filter(t -> + t.position.type.equals(TargetType.METHOD_RETURN) + && (!onlyDirect || isDirectTypeUseAnnotation(t, symbol))); } else { // filter for annotations directly on the type - return rawTypeAttributes.filter( - t -> - targetTypeMatches(symbol, t.position) - && (!onlyDirect || isDirectTypeUseAnnotation(t, symbol))); + return rawTypeAttributes.filter(t -> + targetTypeMatches(symbol, t.position) + && (!onlyDirect || isDirectTypeUseAnnotation(t, symbol))); } } @@ -742,17 +739,16 @@ private static boolean checkArrayElementAnnotations( BiPredicate typeUseCheck, BiPredicate declarationCheck) { if (getTypeUseAnnotations(arraySymbol, /* onlyDirect= */ false) - .anyMatch( - t -> { - // the location list should be of length 1 and the entry tag should be ARRAY - com.sun.tools.javac.util.List location = t.position.location; - TypePathEntry head = location.head; - boolean singleElementList = head != null && location.tail.isEmpty(); - if (singleElementList && head.tag == TypeAnnotationPosition.TypePathEntryKind.ARRAY) { - return typeUseCheck.test(t.type.toString(), config); - } - return false; - })) { + .anyMatch(t -> { + // the location list should be of length 1 and the entry tag should be ARRAY + com.sun.tools.javac.util.List location = t.position.location; + TypePathEntry head = location.head; + boolean singleElementList = head != null && location.tail.isEmpty(); + if (singleElementList && head.tag == TypeAnnotationPosition.TypePathEntryKind.ARRAY) { + return typeUseCheck.test(t.type.toString(), config); + } + return false; + })) { return true; } // For varargs symbols we also check for declaration annotations on the parameter diff --git a/nullaway/src/main/java/com/uber/nullaway/dataflow/AccessPathNullnessAnalysis.java b/nullaway/src/main/java/com/uber/nullaway/dataflow/AccessPathNullnessAnalysis.java index bd7c308893..0416665d98 100644 --- a/nullaway/src/main/java/com/uber/nullaway/dataflow/AccessPathNullnessAnalysis.java +++ b/nullaway/src/main/java/com/uber/nullaway/dataflow/AccessPathNullnessAnalysis.java @@ -317,41 +317,38 @@ private static NullnessStore getAccessPathsForNestedMethod( } Predicate handlerPredicate = handler.getAccessPathPredicateForNestedMethod(pathToNestedMethodNode, state); - return store.filterAccessPaths( - (ap) -> { - boolean allAPNonRootElementsAreFinalFields = true; - ImmutableList elements = ap.getElements(); - for (int i = 0; i < elements.size(); i++) { - AccessPathElement ape = elements.get(i); - Element e = ape.getJavaElement(); - if (i != elements.size() - 1) { // "inner" elements of the access path - if (!e.getKind().equals(ElementKind.FIELD) - || !e.getModifiers().contains(Modifier.FINAL)) { - allAPNonRootElementsAreFinalFields = false; - break; - } - } else { // last element - // must be a field that is final or annotated with @MonotonicNonNull - if (!e.getKind().equals(ElementKind.FIELD) - || !(e.getModifiers().contains(Modifier.FINAL) - || hasMonotonicNonNullAnnotation(e))) { - allAPNonRootElementsAreFinalFields = false; - } - } + return store.filterAccessPaths(ap -> { + boolean allAPNonRootElementsAreFinalFields = true; + ImmutableList elements = ap.getElements(); + for (int i = 0; i < elements.size(); i++) { + AccessPathElement ape = elements.get(i); + Element e = ape.getJavaElement(); + if (i != elements.size() - 1) { // "inner" elements of the access path + if (!e.getKind().equals(ElementKind.FIELD) + || !e.getModifiers().contains(Modifier.FINAL)) { + allAPNonRootElementsAreFinalFields = false; + break; } - if (allAPNonRootElementsAreFinalFields) { - Element e = ap.getRoot(); - return e == null // This is the case for: this(.f)* where each f is a final field. - || e.getKind().equals(ElementKind.PARAMETER) - || e.getKind().equals(ElementKind.LOCAL_VARIABLE) - // rooted at a static field that is either final or annotated with @MonotonicNonNull - || (e.getKind().equals(ElementKind.FIELD) - && (e.getModifiers().contains(Modifier.FINAL) - || hasMonotonicNonNullAnnotation(e))); + } else { // last element + // must be a field that is final or annotated with @MonotonicNonNull + if (!e.getKind().equals(ElementKind.FIELD) + || !(e.getModifiers().contains(Modifier.FINAL) || hasMonotonicNonNullAnnotation(e))) { + allAPNonRootElementsAreFinalFields = false; } + } + } + if (allAPNonRootElementsAreFinalFields) { + Element e = ap.getRoot(); + return e == null // This is the case for: this(.f)* where each f is a final field. + || e.getKind().equals(ElementKind.PARAMETER) + || e.getKind().equals(ElementKind.LOCAL_VARIABLE) + // rooted at a static field that is either final or annotated with @MonotonicNonNull + || (e.getKind().equals(ElementKind.FIELD) + && (e.getModifiers().contains(Modifier.FINAL) || hasMonotonicNonNullAnnotation(e))); + } - return handlerPredicate.test(ap); - }); + return handlerPredicate.test(ap); + }); } private static boolean hasMonotonicNonNullAnnotation(Element e) { diff --git a/nullaway/src/main/java/com/uber/nullaway/fixserialization/adapters/SerializationV3Adapter.java b/nullaway/src/main/java/com/uber/nullaway/fixserialization/adapters/SerializationV3Adapter.java index 63fee68d85..5d8d899e99 100644 --- a/nullaway/src/main/java/com/uber/nullaway/fixserialization/adapters/SerializationV3Adapter.java +++ b/nullaway/src/main/java/com/uber/nullaway/fixserialization/adapters/SerializationV3Adapter.java @@ -113,14 +113,13 @@ public String serializeMethodSignature(Symbol.MethodSymbol methodSymbol) { } sb.append( methodSymbol.getParameters().stream() - .map( - parameter -> - // check if array - (parameter.type instanceof Type.ArrayType) - // if is array, get the element type and append "[]" - ? ((Type.ArrayType) parameter.type).elemtype.tsym + "[]" - // else, just get the type - : parameter.type.tsym.toString()) + .map(parameter -> + // check if array + (parameter.type instanceof Type.ArrayType) + // if is array, get the element type and append "[]" + ? ((Type.ArrayType) parameter.type).elemtype.tsym + "[]" + // else, just get the type + : parameter.type.tsym.toString()) .collect(joining(",", "(", ")"))); return sb.toString(); } diff --git a/nullaway/src/main/java/com/uber/nullaway/fixserialization/scanners/OriginScanner.java b/nullaway/src/main/java/com/uber/nullaway/fixserialization/scanners/OriginScanner.java index 413f2479a0..dba4f16220 100644 --- a/nullaway/src/main/java/com/uber/nullaway/fixserialization/scanners/OriginScanner.java +++ b/nullaway/src/main/java/com/uber/nullaway/fixserialization/scanners/OriginScanner.java @@ -180,17 +180,16 @@ public Set retrieveOrigins(@Nullable MethodTree tree, Symbol tar } visited.add(current); Set involvedSymbols = tree.accept(this, current); - involvedSymbols.forEach( - location -> { - Symbol origin = location.origin(); - if (isOriginal(origin)) { - result.add(location); - } else { - if (!visited.contains(origin)) { - queue.add(origin); - } - } - }); + involvedSymbols.forEach(location -> { + Symbol origin = location.origin(); + if (isOriginal(origin)) { + result.add(location); + } else { + if (!visited.contains(origin)) { + queue.add(origin); + } + } + }); } return result; } diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java index 54d263f405..899ca74e59 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java @@ -380,12 +380,11 @@ public Map solve() } /* ---------- work-list propagation of nullability ---------- */ Deque work = new ArrayDeque<>(); - vars.forEach( - (inferenceVar, st) -> { - if (st.nullness != NullnessState.UNKNOWN) { - work.add(inferenceVar); - } - }); + vars.forEach((inferenceVar, st) -> { + if (st.nullness != NullnessState.UNKNOWN) { + work.add(inferenceVar); + } + }); while (!work.isEmpty()) { InferenceVariable inferenceVar = work.removeFirst(); @@ -417,16 +416,15 @@ public Map solve() /* ---------- build final solution map ---------- */ Map result = new LinkedHashMap<>(); - vars.forEach( - (inferenceVar, st) -> { - // Note: if the nullness state is UNKNOWN, we infer NONNULL arbitrarily - // TODO does this matter? should we use NULLABLE instead? - result.put( - inferenceVar, - st.nullness == NullnessState.NULLABLE - ? InferredNullability.NULLABLE - : InferredNullability.NONNULL); - }); + vars.forEach((inferenceVar, st) -> { + // Note: if the nullness state is UNKNOWN, we infer NONNULL arbitrarily + // TODO does this matter? should we use NULLABLE instead? + result.put( + inferenceVar, + st.nullness == NullnessState.NULLABLE + ? InferredNullability.NULLABLE + : InferredNullability.NONNULL); + }); return result; } 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 3faa023193..3b78dbc107 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -114,11 +114,10 @@ private InferenceSuccess( Map solution, IdentityHashMap polyNullnessByInvocation) { this.polyNullnessByInvocation = polyNullnessByInvocation; - solution.forEach( - (inferenceVar, nullability) -> - typeVarNullabilityBySite - .computeIfAbsent(inferenceVar.site(), unused -> new LinkedHashMap<>()) - .put(inferenceVar.typeVariable(), nullability)); + solution.forEach((inferenceVar, nullability) -> + typeVarNullabilityBySite + .computeIfAbsent(inferenceVar.site(), unused -> new LinkedHashMap<>()) + .put(inferenceVar.typeVariable(), nullability)); } /** @@ -1013,12 +1012,11 @@ private static boolean isQualifierOf(NewClassTree newClassTree, Tree tree) { Tree invocationTree, Type.MethodType invocationType, Tree argumentTree) { AtomicReference<@Nullable Type> formalParamTypeRef = new AtomicReference<>(); new InvocationArguments(invocationTree, invocationType) - .forEach( - (arg, pos, formalParamType, unused) -> { - if (ASTHelpers.stripParentheses(arg) == argumentTree) { - formalParamTypeRef.set(formalParamType); - } - }); + .forEach((arg, pos, formalParamType, unused) -> { + if (ASTHelpers.stripParentheses(arg) == argumentTree) { + formalParamTypeRef.set(formalParamType); + } + }); return formalParamTypeRef.get(); } @@ -1543,26 +1541,25 @@ private InferenceResult runInferenceForCall( callMethodType = executableType; } new InvocationArguments(callTree, callMethodType) - .forEach( - (argumentWithParentheses, argPos, formalParamType, unused) -> { - ExpressionTree argument = ASTHelpers.stripParentheses(argumentWithParentheses); - if (argument instanceof LambdaExpressionTree - || argument instanceof MemberReferenceTree) { - Type polyExprTreeType = ASTHelpers.getType(argument); - if (polyExprTreeType != null) { - Type formalParamGroundTargetType = - GenericsUtils.groundTargetType(formalParamType, state, config, handler); - Type typeWithInferredNullability = - TypeSubstitutionUtils.updateTypeWithInferredNullability( - polyExprTreeType, - formalParamGroundTargetType, - typeVarNullability, - state, - config); - inferredPolyExpressionTypes.put(argument, typeWithInferredNullability); - } - } - }); + .forEach((argumentWithParentheses, argPos, formalParamType, unused) -> { + ExpressionTree argument = ASTHelpers.stripParentheses(argumentWithParentheses); + if (argument instanceof LambdaExpressionTree + || argument instanceof MemberReferenceTree) { + Type polyExprTreeType = ASTHelpers.getType(argument); + if (polyExprTreeType != null) { + Type formalParamGroundTargetType = + GenericsUtils.groundTargetType(formalParamType, state, config, handler); + Type typeWithInferredNullability = + TypeSubstitutionUtils.updateTypeWithInferredNullability( + polyExprTreeType, + formalParamGroundTargetType, + typeVarNullability, + state, + config); + inferredPolyExpressionTypes.put(argument, typeWithInferredNullability); + } + } + }); } return successResult; } catch (UnsatisfiableConstraintsException e) { @@ -3021,102 +3018,101 @@ public void compareGenericTypeParameterNullabilityForCall( Type.MethodType finalMethodType = getInvokedMethodTypeAtCall(methodSymbol, tree, null, state, false); new InvocationArguments(tree, finalMethodType) - .forEach( - (currentActualParam, argPos, formalParameter, unused) -> { - if (formalParameter.isRaw()) { - // bail out of any checking involving raw types for now - return; - } + .forEach((currentActualParam, argPos, formalParameter, unused) -> { + if (formalParameter.isRaw()) { + // bail out of any checking involving raw types for now + return; + } - TreePath pathToParam = pathWithLeaf(state.getPath(), currentActualParam); - NullabilityUtil.ExprTreeAndState actualParameterAndState = - NullabilityUtil.stripParensAndUpdateTreePath( - currentActualParam, state.withPath(pathToParam)); - ExpressionTree actualParameterWithoutParentheses = actualParameterAndState.expr(); - if (actualParameterWithoutParentheses - instanceof MemberReferenceTree memberReferenceTree) { - // the type of the method reference tree provided by javac may not capture - // nullability of nested types. So, do explicit type checks based on the return - // and parameter types of the referenced method. Type arguments of an unmarked - // functional interface method have unspecified nullness and are not checked, as - // for the arguments of a call to an unmarked method. - if (!CodeAnnotationInfo.instance(state.context) - .isSymbolUnannotated( - NullabilityUtil.getFunctionalInterfaceMethod( - memberReferenceTree, state.getTypes()), - config, - handler)) { - Type groundFormalParameter = - GenericsUtils.groundTargetType(formalParameter, state, config, handler); - inferMethodReferenceTypeArguments( - memberReferenceTree, groundFormalParameter, actualParameterAndState.state()); - if (!hasReportedInferenceFailure(memberReferenceTree)) { - GenericsUtils.processMethodRefTypeRelations( - this, - groundFormalParameter, - memberReferenceTree, - actualParameterAndState.state(), - (subtype, supertype, relationKind) -> { - if (!subtypeParameterNullability(supertype, subtype, state)) { - if (relationKind == MethodRefTypeRelationKind.RETURN) { - reportInvalidMethodReferenceReturnTypeError( - memberReferenceTree, supertype, subtype, state); - } else { - reportInvalidMethodReferenceParameterTypeError( - memberReferenceTree, subtype, supertype, state); - } - } - }); - } - } - maybeStorePolyExpressionTypeFromTarget( - actualParameterWithoutParentheses, formalParameter, state); - return; + TreePath pathToParam = pathWithLeaf(state.getPath(), currentActualParam); + NullabilityUtil.ExprTreeAndState actualParameterAndState = + NullabilityUtil.stripParensAndUpdateTreePath( + currentActualParam, state.withPath(pathToParam)); + ExpressionTree actualParameterWithoutParentheses = actualParameterAndState.expr(); + if (actualParameterWithoutParentheses + instanceof MemberReferenceTree memberReferenceTree) { + // the type of the method reference tree provided by javac may not capture + // nullability of nested types. So, do explicit type checks based on the return + // and parameter types of the referenced method. Type arguments of an unmarked + // functional interface method have unspecified nullness and are not checked, as + // for the arguments of a call to an unmarked method. + if (!CodeAnnotationInfo.instance(state.context) + .isSymbolUnannotated( + NullabilityUtil.getFunctionalInterfaceMethod( + memberReferenceTree, state.getTypes()), + config, + handler)) { + Type groundFormalParameter = + GenericsUtils.groundTargetType(formalParameter, state, config, handler); + inferMethodReferenceTypeArguments( + memberReferenceTree, groundFormalParameter, actualParameterAndState.state()); + if (!hasReportedInferenceFailure(memberReferenceTree)) { + GenericsUtils.processMethodRefTypeRelations( + this, + groundFormalParameter, + memberReferenceTree, + actualParameterAndState.state(), + (subtype, supertype, relationKind) -> { + if (!subtypeParameterNullability(supertype, subtype, state)) { + if (relationKind == MethodRefTypeRelationKind.RETURN) { + reportInvalidMethodReferenceReturnTypeError( + memberReferenceTree, supertype, subtype, state); + } else { + reportInvalidMethodReferenceParameterTypeError( + memberReferenceTree, subtype, supertype, state); + } + } + }); } + } + maybeStorePolyExpressionTypeFromTarget( + actualParameterWithoutParentheses, formalParameter, state); + return; + } - Type actualParameterType; - if (actualParameterWithoutParentheses instanceof LambdaExpressionTree) { - maybeStorePolyExpressionTypeFromTarget( - actualParameterWithoutParentheses, formalParameter, state); - } - Type inferredPolyType = - inferredPolyExpressionTypes.get(actualParameterWithoutParentheses); - if (inferredPolyType != null) { - actualParameterType = inferredPolyType; - } else { - actualParameterType = getTreeType(currentActualParam, state.withPath(pathToParam)); - } - if (actualParameterType != null) { - if (isCallNeedingInference(currentActualParam)) { - // infer the type of the method call based on the assignment context - // and the formal parameter type - actualParameterType = - inferCallType( - state.withPath(pathToParam), - currentActualParam, - pathToParam, - formalParameter, - false, - false); - } else if (currentActualParam - instanceof ConditionalExpressionTree conditionalExpressionTree) { - actualParameterType = - inferConditionalExpressionType( - state.withPath(pathToParam), - conditionalExpressionTree, - pathToParam, - formalParameter, - false); - } - if (actualParameterType == null) { - return; - } - if (!subtypeParameterNullability(formalParameter, actualParameterType, state)) { - reportInvalidParametersNullabilityError( - formalParameter, actualParameterType, currentActualParam, state); - } - } - }); + Type actualParameterType; + if (actualParameterWithoutParentheses instanceof LambdaExpressionTree) { + maybeStorePolyExpressionTypeFromTarget( + actualParameterWithoutParentheses, formalParameter, state); + } + Type inferredPolyType = + inferredPolyExpressionTypes.get(actualParameterWithoutParentheses); + if (inferredPolyType != null) { + actualParameterType = inferredPolyType; + } else { + actualParameterType = getTreeType(currentActualParam, state.withPath(pathToParam)); + } + if (actualParameterType != null) { + if (isCallNeedingInference(currentActualParam)) { + // infer the type of the method call based on the assignment context + // and the formal parameter type + actualParameterType = + inferCallType( + state.withPath(pathToParam), + currentActualParam, + pathToParam, + formalParameter, + false, + false); + } else if (currentActualParam + instanceof ConditionalExpressionTree conditionalExpressionTree) { + actualParameterType = + inferConditionalExpressionType( + state.withPath(pathToParam), + conditionalExpressionTree, + pathToParam, + formalParameter, + false); + } + if (actualParameterType == null) { + return; + } + if (!subtypeParameterNullability(formalParameter, actualParameterType, state)) { + reportInvalidParametersNullabilityError( + formalParameter, actualParameterType, currentActualParam, state); + } + } + }); } /** @@ -4216,18 +4212,17 @@ private void generateArgumentConstraintsForCall( boolean calledFromDataflow) { TreePath pathToCall = path != null ? path : pathWithLeaf(state.getPath(), callTree); new InvocationArguments(callTree, methodType) - .forEach( - (argument, argPos, formalParamType, unused) -> { - TreePath pathToArgument = new TreePath(pathToCall, argument); - generateConstraintsForPseudoAssignment( - state.withPath(pathToArgument), - solver, - allInferenceSites, - argument, - formalParamType, - polyNullContexts, - calledFromDataflow); - }); + .forEach((argument, argPos, formalParamType, unused) -> { + TreePath pathToArgument = new TreePath(pathToCall, argument); + generateConstraintsForPseudoAssignment( + state.withPath(pathToArgument), + solver, + allInferenceSites, + argument, + formalParamType, + polyNullContexts, + calledFromDataflow); + }); } /** diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/NestedTypeVarSubstitutionRepairVisitor.java b/nullaway/src/main/java/com/uber/nullaway/generics/NestedTypeVarSubstitutionRepairVisitor.java index 72bb6bfced..daa0a4e35b 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/NestedTypeVarSubstitutionRepairVisitor.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NestedTypeVarSubstitutionRepairVisitor.java @@ -291,7 +291,7 @@ private Type repairTypeVarSubstitution( Symbol.TypeVariableSymbol typeVarSymbol = (Symbol.TypeVariableSymbol) typeVar.tsym; return repairedSubstitutions.computeIfAbsent( typeVarSymbol, - (unused) -> { + unused -> { Type repairedSubstitution = callSiteType; if (!actualArgType.isRaw() && !callSiteType.isRaw()) { repairedSubstitution = diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/LibraryModelsHandler.java b/nullaway/src/main/java/com/uber/nullaway/handlers/LibraryModelsHandler.java index 1134c7f2a9..7d5d33add7 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/LibraryModelsHandler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/LibraryModelsHandler.java @@ -1969,7 +1969,7 @@ private NameIndexedMap> makeOptimizedSetLookup( private NameIndexedMap makeOptimizedBoolLookup( Names names, ImmutableSet refs) { - return makeOptimizedLookup(names, refs, (ref) -> true); + return makeOptimizedLookup(names, refs, ref -> true); } private NameIndexedMap> diff --git a/nullaway/src/main/java/com/uber/nullaway/handlers/LombokHandler.java b/nullaway/src/main/java/com/uber/nullaway/handlers/LombokHandler.java index 8ddc6b9a20..8c7543edf0 100644 --- a/nullaway/src/main/java/com/uber/nullaway/handlers/LombokHandler.java +++ b/nullaway/src/main/java/com/uber/nullaway/handlers/LombokHandler.java @@ -44,10 +44,9 @@ private boolean isLombokMethodWithMissingNullableAnnotation( methodNameString.substring(LOMBOK_BUILDER_DEFAULT_METHOD_PREFIX.length()); ImmutableList matchingMembers = StreamSupport.stream(methodSymbol.enclClass().members().getSymbols().spliterator(), false) - .filter( - sym -> - sym.name.contentEquals(originalFieldName) - && sym.getKind().equals(ElementKind.FIELD)) + .filter(sym -> + sym.name.contentEquals(originalFieldName) + && sym.getKind().equals(ElementKind.FIELD)) .collect(ImmutableList.toImmutableList()); Preconditions.checkArgument( matchingMembers.size() == 1, diff --git a/nullaway/src/test/java/com/uber/nullaway/ContractsTests.java b/nullaway/src/test/java/com/uber/nullaway/ContractsTests.java index 18087fec68..dc50ed79ed 100644 --- a/nullaway/src/test/java/com/uber/nullaway/ContractsTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/ContractsTests.java @@ -1532,20 +1532,20 @@ public void delimiterOnlyContractReportsDiagnostic() { .addSourceLines( "Test.java", """ - package com.uber; - import org.jetbrains.annotations.Contract; - class Test { - @Contract("->") - // BUG: Diagnostic contains: unparseable clause: -> - Object delimiterOnly() { - return new Object(); - } - @Contract("-> !null") - Object validZeroArgumentContract() { - return new Object(); - } - } - """) + package com.uber; + import org.jetbrains.annotations.Contract; + class Test { + @Contract("->") + // BUG: Diagnostic contains: unparseable clause: -> + Object delimiterOnly() { + return new Object(); + } + @Contract("-> !null") + Object validZeroArgumentContract() { + return new Object(); + } + } + """) .doTest(); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/DummyOptionsConfigTest.java b/nullaway/src/test/java/com/uber/nullaway/DummyOptionsConfigTest.java index b803b94d12..6db471e9b5 100644 --- a/nullaway/src/test/java/com/uber/nullaway/DummyOptionsConfigTest.java +++ b/nullaway/src/test/java/com/uber/nullaway/DummyOptionsConfigTest.java @@ -36,7 +36,7 @@ public void allDeclaredMethodsThrowIllegalStateException() { continue; } Class[] parameterTypes = method.getParameterTypes(); - Object[] nullParams = Arrays.stream(parameterTypes).map((t) -> null).toArray(); + Object[] nullParams = Arrays.stream(parameterTypes).map(t -> null).toArray(); Exception reflectionException = assertThrows( InvocationTargetException.class, diff --git a/nullaway/src/test/java/com/uber/nullaway/EnsuresNonNullTests.java b/nullaway/src/test/java/com/uber/nullaway/EnsuresNonNullTests.java index 5cad4a4b42..2cec369731 100644 --- a/nullaway/src/test/java/com/uber/nullaway/EnsuresNonNullTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/EnsuresNonNullTests.java @@ -300,24 +300,24 @@ private void checkOpen() throws IOException { */ private static String readerWithThrowingGuard(String ensuresNonNullAnnotation, String readBody) { return """ - package com.uber; - import java.io.IOException; - import javax.annotation.Nullable; - import %s; - class Reader { - private int pos; - @Nullable private CharSequence seq; - @EnsuresNonNull("this.seq") - private void checkOpen() throws IOException { - if (seq == null) { - throw new IOException("Not open."); - } - } - public int read() throws IOException { - %s - } + package com.uber; + import java.io.IOException; + import javax.annotation.Nullable; + import %s; + class Reader { + private int pos; + @Nullable private CharSequence seq; + @EnsuresNonNull("this.seq") + private void checkOpen() throws IOException { + if (seq == null) { + throw new IOException("Not open."); } - """ + } + public int read() throws IOException { + %s + } + } + """ .formatted(ensuresNonNullAnnotation, readBody); } diff --git a/nullaway/src/test/java/com/uber/nullaway/FrameworkTests.java b/nullaway/src/test/java/com/uber/nullaway/FrameworkTests.java index bddf50fa67..bb743d0ac5 100644 --- a/nullaway/src/test/java/com/uber/nullaway/FrameworkTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/FrameworkTests.java @@ -1513,30 +1513,30 @@ private Stream test2(Stream stream) { */ private static String streamFilterThenMapLambda(String annotation, String expectation) { return """ - package com.uber; - import java.util.function.Predicate; - import java.util.stream.Stream; - import javax.annotation.Nullable; - import org.jspecify.annotations.NullUnmarked; - class Test { - static class Foo { - @Nullable String bar; - @Nullable String getBar() { return bar; } - } - Stream f(Stream s) { - return s.filter( - new Predicate() { - %s - @Override - public boolean test(Foo foo) { - return foo.getBar() != null; - } - }) - %s - .map(foo -> foo.getBar().length()); - } - } - """ + package com.uber; + import java.util.function.Predicate; + import java.util.stream.Stream; + import javax.annotation.Nullable; + import org.jspecify.annotations.NullUnmarked; + class Test { + static class Foo { + @Nullable String bar; + @Nullable String getBar() { return bar; } + } + Stream f(Stream s) { + return s.filter( + new Predicate() { + %s + @Override + public boolean test(Foo foo) { + return foo.getBar() != null; + } + }) + %s + .map(foo -> foo.getBar().length()); + } + } + """ .formatted(annotation, expectation); } @@ -1547,30 +1547,30 @@ public boolean test(Foo foo) { */ private static String rxFilterThenMap(String annotation, String mapCall) { return """ - package com.uber; - import io.reactivex.Observable; - import io.reactivex.functions.Function; - import io.reactivex.functions.Predicate; - import javax.annotation.Nullable; - import org.jspecify.annotations.NullUnmarked; - class Test { - static class Foo { - @Nullable String bar; - @Nullable String getBar() { return bar; } - } - Observable f(Observable o) { - return o.filter( - new Predicate() { - %s - @Override - public boolean test(Foo foo) throws Exception { - return foo.getBar() != null; - } - }) - %s; - } - } - """ + package com.uber; + import io.reactivex.Observable; + import io.reactivex.functions.Function; + import io.reactivex.functions.Predicate; + import javax.annotation.Nullable; + import org.jspecify.annotations.NullUnmarked; + class Test { + static class Foo { + @Nullable String bar; + @Nullable String getBar() { return bar; } + } + Observable f(Observable o) { + return o.filter( + new Predicate() { + %s + @Override + public boolean test(Foo foo) throws Exception { + return foo.getBar() != null; + } + }) + %s; + } + } + """ .formatted(annotation, mapCall); } @@ -1580,14 +1580,15 @@ public boolean test(Foo foo) throws Exception { */ private static String rxMapAnonymousFunction(String expectation) { return """ - .map( - new Function() { - @Override - public Integer apply(Foo foo) throws Exception { - %s - return foo.getBar().length(); - } - })""" + .map( + new Function() { + @Override + public Integer apply(Foo foo) throws Exception { + %s + return foo.getBar().length(); + } + })\ + """ .formatted(expectation); } @@ -1686,7 +1687,8 @@ public void rxMethodReferenceAfterNullUnmarkedFilterPredicateGetsNoFacts() { "@NullUnmarked", """ // BUG: Diagnostic contains: referenced method returns @Nullable - .map(Foo::getBar)""")) + .map(Foo::getBar)\ + """)) .doTest(); } @@ -2873,15 +2875,15 @@ public void defaultLibraryModelsMapRemove() { .addSourceLines( "Test.java", """ - package com.uber; - import java.util.Map; - class Test { - void testMapRemove(Map map) { - // BUG: Diagnostic contains: dereferenced expression 'map.remove("key")' is @Nullable - map.remove("key").toString(); + package com.uber; + import java.util.Map; + class Test { + void testMapRemove(Map map) { + // BUG: Diagnostic contains: dereferenced expression 'map.remove("key")' is @Nullable + map.remove("key").toString(); + } } - } - """) + """) .doTest(); } diff --git a/nullaway/src/test/java/com/uber/nullaway/JSpecifyJDKModelsTest.java b/nullaway/src/test/java/com/uber/nullaway/JSpecifyJDKModelsTest.java index ea8a80bb89..ecb057781b 100644 --- a/nullaway/src/test/java/com/uber/nullaway/JSpecifyJDKModelsTest.java +++ b/nullaway/src/test/java/com/uber/nullaway/JSpecifyJDKModelsTest.java @@ -358,7 +358,8 @@ static void test(List list) { s.hashCode(); }); } - }""") + }\ + """) .doTest(); } @@ -386,7 +387,8 @@ static List getValues(Map values, List keys) { .filter(Objects::nonNull) .toList(); } - }""") + }\ + """) .doTest(); } diff --git a/nullaway/src/test/java/com/uber/nullaway/NullAwayTestsBase.java b/nullaway/src/test/java/com/uber/nullaway/NullAwayTestsBase.java index 7546934efe..e110b94461 100644 --- a/nullaway/src/test/java/com/uber/nullaway/NullAwayTestsBase.java +++ b/nullaway/src/test/java/com/uber/nullaway/NullAwayTestsBase.java @@ -136,9 +136,8 @@ protected List compileAndReportDiagnostics( .that(compilationSucceeded) .isTrue(); return diagnosticCollector.getDiagnostics().stream() - .filter( - diagnostic -> - diagnostic.getSource() != null && diagnostic.getLineNumber() != Diagnostic.NOPOS) + .filter(diagnostic -> + diagnostic.getSource() != null && diagnostic.getLineNumber() != Diagnostic.NOPOS) .map(NullAwayTestsBase::render) .toList(); } diff --git a/nullaway/src/test/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitorTests.java b/nullaway/src/test/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitorTests.java index 77aee54f7f..a4f3aa9af7 100644 --- a/nullaway/src/test/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitorTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitorTests.java @@ -38,21 +38,21 @@ public void sharedBoundsHaveLinearDeterministicComparisonCounts() { compile( boundDeclarations(12) + """ - class Test { - void depthFour() { - // BUG: Diagnostic contains: depth4: first=34, repeat=1, fresh=34, afterInterrupt=34, accepted=true/true/true/true, interrupted=true - A4 depth4; - } - void depthEight() { - // BUG: Diagnostic contains: depth8: first=82, repeat=1, fresh=82, afterInterrupt=82, accepted=true/true/true/true, interrupted=true - A8 depth8; - } - void depthTwelve() { - // BUG: Diagnostic contains: depth12: first=130, repeat=1, fresh=130, afterInterrupt=130, accepted=true/true/true/true, interrupted=true - A12 depth12; - } - } - """); + class Test { + void depthFour() { + // BUG: Diagnostic contains: depth4: first=34, repeat=1, fresh=34, afterInterrupt=34, accepted=true/true/true/true, interrupted=true + A4 depth4; + } + void depthEight() { + // BUG: Diagnostic contains: depth8: first=82, repeat=1, fresh=82, afterInterrupt=82, accepted=true/true/true/true, interrupted=true + A8 depth8; + } + void depthTwelve() { + // BUG: Diagnostic contains: depth12: first=130, repeat=1, fresh=130, afterInterrupt=130, accepted=true/true/true/true, interrupted=true + A12 depth12; + } + } + """); } @Test(timeout = 30_000) @@ -60,17 +60,17 @@ public void assertionFailuresBecomeDiagnosticsAndDoNotStopLaterFixtures() { compile( boundDeclarations(4) + """ - class Test { - void assertionFailureCase() { - // BUG: Diagnostic contains: assertionFailure: expected fixture assertion - Object assertionFailure; - } - void subsequentFixtureCase() { - // BUG: Diagnostic contains: depth4: first=34, repeat=1, fresh=34, afterInterrupt=34, accepted=true/true/true/true, interrupted=true - A4 depth4; - } - } - """); + class Test { + void assertionFailureCase() { + // BUG: Diagnostic contains: assertionFailure: expected fixture assertion + Object assertionFailure; + } + void subsequentFixtureCase() { + // BUG: Diagnostic contains: depth4: first=34, repeat=1, fresh=34, afterInterrupt=34, accepted=true/true/true/true, interrupted=true + A4 depth4; + } + } + """); } @Test(timeout = 30_000) @@ -78,14 +78,14 @@ public void siblingWildcardArgumentsReuseSuccessfulComparisonsInOneAccept() { compile( boundDeclarations(8) + """ - interface Pair {} - class Test { - void siblingArgumentsCase() { - // BUG: Diagnostic contains: siblings: comparisons=84, accepted=true - Pair, A8> siblings; - } - } - """); + interface Pair {} + class Test { + void siblingArgumentsCase() { + // BUG: Diagnostic contains: siblings: comparisons=84, accepted=true + Pair, A8> siblings; + } + } + """); } @Test(timeout = 30_000) 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 97b42ecbeb..ef47307267 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java @@ -2870,7 +2870,8 @@ static void test() { // Function via wildcard upper bound Object x = invokeWithReturn(t -> null); } - }""") + }\ + """) .doTest(); } @@ -2905,7 +2906,8 @@ static void test(List list) { s.hashCode(); }); } - }""") + }\ + """) .doTest(); } @@ -2926,7 +2928,8 @@ static R invokeWithReturn(Function map static void test() { String x = invokeWithReturn(Test::m); } - }""") + }\ + """) .doTest(); } @@ -3069,7 +3072,8 @@ interface C { } interface E { } - }""") + }\ + """) .doTest(); } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/JSpecifyLibraryModelsTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/JSpecifyLibraryModelsTests.java index bc5ced5cdb..f1d9c5c2f5 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/JSpecifyLibraryModelsTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/JSpecifyLibraryModelsTests.java @@ -215,16 +215,16 @@ public void issue1611() { .addSourceLines( "Test.java", """ - import java.util.Optional; - import org.jspecify.annotations.*; - - @NullMarked - class Test { - static Optional getKey(@Nullable String key) { - return Optional.ofNullable(key).or(() -> Optional.ofNullable(System.getenv("DEFAULT_KEY"))); - } - } - """) + import java.util.Optional; + import org.jspecify.annotations.*; + + @NullMarked + class Test { + static Optional getKey(@Nullable String key) { + return Optional.ofNullable(key).or(() -> Optional.ofNullable(System.getenv("DEFAULT_KEY"))); + } + } + """) .doTest(); } 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..dc900342e7 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/VarDeclaredLocalTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/VarDeclaredLocalTests.java @@ -309,7 +309,8 @@ void test() { foo1.get().hashCode(); } } - }""") + }\ + """) .doTest(); } @@ -339,7 +340,8 @@ void test() { s = null; } } - }""") + }\ + """) .doTest(); } 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..10c52325a0 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -700,7 +700,8 @@ static void testNonNullSuperBound(Foo f) { // BUG: Diagnostic contains: passing @Nullable parameter 'null' f.set(null); } - }""") + }\ + """) .doTest(); } @@ -733,7 +734,8 @@ static void testNonNullSuperBound(Foo f) { // BUG: Diagnostic contains: dereferenced expression 'f.get()' is @Nullable f.get().hashCode(); } - }""") + }\ + """) .doTest(); } @@ -1008,7 +1010,8 @@ void test(Foo f) { f.get().hashCode(); } } - }""") + }\ + """) .doTest(); } @@ -1079,7 +1082,8 @@ static void testNonNullSuperBound(Foo f) { // BUG: Diagnostic contains: dereferenced expression 'x' is @Nullable x.hashCode(); } - }""") + }\ + """) .doTest(); } @@ -1451,7 +1455,8 @@ static void testNegative(List list) { list.stream().map(Test::mapToNull).forEach(Test::doNothing); list.stream().map(Test::id).forEach(Test::callHashCode); } - }""") + }\ + """) .doTest(); } @@ -1487,7 +1492,8 @@ public Foo or(Foo other) { // This works since ofNoWildcard does not use a lower-bounded wildcard in its parameter type static final Foo<@Nullable Void> FOO3 = Foo.ofNoWildcard(new Foo<@Nullable Void>()).or(new Foo<@Nullable Void>()); - }""") + }\ + """) .doTest(); } diff --git a/nullaway/src/test/java/com/uber/nullaway/tools/SerializationTestHelper.java b/nullaway/src/test/java/com/uber/nullaway/tools/SerializationTestHelper.java index 959d9bb0d0..ce08ac505d 100644 --- a/nullaway/src/test/java/com/uber/nullaway/tools/SerializationTestHelper.java +++ b/nullaway/src/test/java/com/uber/nullaway/tools/SerializationTestHelper.java @@ -197,15 +197,14 @@ public static String getRelativePathFromUnitTestTempDirectory(String pathInStrin AtomicReference relativePathStarted = new AtomicReference<>(false); Path path = Paths.get(pathInString); path.iterator() - .forEachRemaining( - remaining -> { - if (relativePathStarted.get()) { - relativePath.set(relativePath.get().resolve(remaining)); - } - if (remaining.toString().startsWith("com")) { - relativePathStarted.set(true); - } - }); + .forEachRemaining(remaining -> { + if (relativePathStarted.get()) { + relativePath.set(relativePath.get().resolve(remaining)); + } + if (remaining.toString().startsWith("com")) { + relativePathStarted.set(true); + } + }); return relativePath.get().toString(); } } diff --git a/sample/src/main/java/com/uber/mylib/Lambdas.java b/sample/src/main/java/com/uber/mylib/Lambdas.java index 0a10dd192d..8379d24de3 100644 --- a/sample/src/main/java/com/uber/mylib/Lambdas.java +++ b/sample/src/main/java/com/uber/mylib/Lambdas.java @@ -38,16 +38,16 @@ interface NullableParamFunction { } static void testNonNullParam() { - NonNullParamFunction n = (x) -> x.toString(); + NonNullParamFunction n = x -> x.toString(); NonNullParamFunction n2 = (@Nullable Object x) -> (x == null) ? "null" : x.toString(); NullableParamFunction n3 = (@Nullable Object x) -> (x == null) ? "null" : x.toString(); - NullableParamFunction n4 = (x) -> (x == null) ? "null" : x.toString(); + NullableParamFunction n4 = x -> (x == null) ? "null" : x.toString(); } static void testBuiltIn() { - java.util.function.Function foo = (x) -> x.toString(); + java.util.function.Function foo = x -> x.toString(); BiFunction bar = (x, y) -> x.toString() + y.toString(); - Function foo2 = (x) -> null; + Function foo2 = x -> null; } static class Size {