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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ subprojects { project ->
project.apply plugin: "com.diffplug.spotless"
spotless {
java {
googleJavaFormat(libs.versions.google.java.format.get())
googleJavaFormat()
}
}
}
Expand All @@ -180,7 +180,7 @@ spotless {
}
}
spotlessPredeclare {
java { googleJavaFormat(libs.versions.google.java.format.get()) }
java { googleJavaFormat() }
groovyGradle {
greclipse()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,12 +133,11 @@ private Set<Integer> computeDerefParamList(int numParam, int firstParamIndex) {
Map<ISSABasicBlock, Set<Integer>> blockToDerefSetMap = new HashMap<>();

// find which params are treated as being non-null inside each basic block
prunedCFG.forEach(
basicBlock -> {
Set<Integer> derefParamSet = new HashSet<>();
blockToDerefSetMap.put(basicBlock, derefParamSet);
checkForUseOfParams(derefParamSet, numParam, firstParamIndex, basicBlock);
});
prunedCFG.forEach(basicBlock -> {
Set<Integer> 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -776,19 +776,18 @@ private Map<String, List<ClassInfo>> getParsedJSON() {
return stream
.filter(path -> path.toString().endsWith(".json"))
.findFirst()
.<Map<String, List<ClassInfo>>>map(
path -> {
try {
return new GsonBuilder()
.registerTypeAdapter(ImmutableList.class, immutableListAdapter)
.create()
.fromJson(
new String(Files.readAllBytes(path), StandardCharsets.UTF_8),
new TypeToken<Map<String, List<ClassInfo>>>() {}.getType());
} catch (IOException e) {
throw new RuntimeException(e);
}
})
.<Map<String, List<ClassInfo>>>map(path -> {
try {
return new GsonBuilder()
.registerTypeAdapter(ImmutableList.class, immutableListAdapter)
.create()
.fromJson(
new String(Files.readAllBytes(path), StandardCharsets.UTF_8),
new TypeToken<Map<String, List<ClassInfo>>>() {}.getType());
} catch (IOException e) {
throw new RuntimeException(e);
}
})
.orElseThrow();
} catch (IOException e) {
throw new RuntimeException(e);
Expand Down
7 changes: 3 additions & 4 deletions nullaway/src/main/java/com/uber/nullaway/ErrorBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
132 changes: 65 additions & 67 deletions nullaway/src/main/java/com/uber/nullaway/NullAway.java
Original file line number Diff line number Diff line change
Expand Up @@ -1406,21 +1406,20 @@ private GenericsChecks.ValueTarget lambdaReturnTarget(
VisitorState callState = state.withPath(parentPath);
List<GenericsChecks.ValueTarget> 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);
}
Expand Down Expand Up @@ -2012,7 +2011,7 @@ private ImmutableMultimap<Tree, Element> 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) {
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -2942,7 +2940,7 @@ private SetMultimap<MethodTree, Symbol> 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);
}

Expand Down
46 changes: 21 additions & 25 deletions nullaway/src/main/java/com/uber/nullaway/NullabilityUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ public static boolean hasAnyAnnotationMatching(Symbol symbol, Predicate<String>
if (elem.getSimpleName().contentEquals("value")) {
@SuppressWarnings("unchecked")
List<AnnotationValue> values = (List<AnnotationValue>) 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;
Expand Down Expand Up @@ -378,11 +378,10 @@ public static Stream<? extends AnnotationMirror> 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);
}
Expand Down Expand Up @@ -413,16 +412,14 @@ private static Stream<Attribute.TypeCompound> 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)));
}
}

Expand Down Expand Up @@ -742,17 +739,16 @@ private static boolean checkArrayElementAnnotations(
BiPredicate<String, Config> typeUseCheck,
BiPredicate<Symbol, Config> 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<TypePathEntry> 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<TypePathEntry> 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -317,41 +317,38 @@ private static NullnessStore getAccessPathsForNestedMethod(
}
Predicate<AccessPath> handlerPredicate =
handler.getAccessPathPredicateForNestedMethod(pathToNestedMethodNode, state);
return store.filterAccessPaths(
(ap) -> {
boolean allAPNonRootElementsAreFinalFields = true;
ImmutableList<AccessPathElement> 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<AccessPathElement> 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) {
Expand Down
Loading
Loading