Skip to content

KeyFor Checker: Convert annotations with parse errors to top for method invocations. #7052

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Apr 28, 2025
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.checkerframework.checker.nullness;

import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.Tree;
import java.lang.annotation.Annotation;
Expand All @@ -10,6 +11,7 @@
import java.util.LinkedHashSet;
import java.util.Set;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import org.checkerframework.checker.nullness.qual.KeyFor;
import org.checkerframework.checker.nullness.qual.KeyForBottom;
Expand All @@ -18,14 +20,21 @@
import org.checkerframework.checker.signature.qual.CanonicalName;
import org.checkerframework.common.basetype.BaseTypeChecker;
import org.checkerframework.dataflow.cfg.node.Node;
import org.checkerframework.dataflow.expression.JavaExpression;
import org.checkerframework.dataflow.expression.Unknown;
import org.checkerframework.dataflow.util.NodeUtils;
import org.checkerframework.framework.flow.CFAbstractAnalysis;
import org.checkerframework.framework.type.AnnotatedTypeFactory;
import org.checkerframework.framework.type.AnnotatedTypeMirror;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType;
import org.checkerframework.framework.type.GenericAnnotatedTypeFactory;
import org.checkerframework.framework.type.QualifierHierarchy;
import org.checkerframework.framework.type.SubtypeIsSupersetQualifierHierarchy;
import org.checkerframework.framework.type.treeannotator.ListTreeAnnotator;
import org.checkerframework.framework.type.treeannotator.TreeAnnotator;
import org.checkerframework.framework.util.JavaExpressionParseUtil;
import org.checkerframework.framework.util.StringToJavaExpression;
import org.checkerframework.framework.util.dependenttypes.DependentTypesHelper;
import org.checkerframework.javacutil.AnnotationBuilder;
import org.checkerframework.javacutil.AnnotationUtils;
import org.checkerframework.javacutil.TreeUtils;
Expand Down Expand Up @@ -221,4 +230,61 @@ boolean isMapPut(Node node) {
public boolean shouldWarnIfStubRedundantWithBytecode() {
return false;
}

@Override
protected DependentTypesHelper createDependentTypesHelper() {
// Converts KeyFor annotations with errors into @UnknownKeyFor in the type of method
// invocations.
return new KeyForDependentTypesHelper(this);
}

/**
* Converts KeyFor annotations with errors into {@code @UnknownKeyFor} in the type of method
* invocations.
*/
static class KeyForDependentTypesHelper extends DependentTypesHelper {

/**
* Creates a {@code KeyForDependentTypesHelper}.
*
* @param factory annotated type factory
*/
public KeyForDependentTypesHelper(AnnotatedTypeFactory factory) {
super(factory);
}

@Override
public void atMethodInvocation(
AnnotatedExecutableType methodType, MethodInvocationTree methodInvocationTree) {
if (!hasDependentAnnotations()) {
return;
}
Element methodElt = TreeUtils.elementFromUse(methodInvocationTree);

// The annotations on `declaredMethodType` will be copied to `methodType`.
AnnotatedExecutableType declaredMethodType =
(AnnotatedExecutableType) factory.getAnnotatedType(methodElt);
if (!hasDependentType(declaredMethodType)) {
return;
}

StringToJavaExpression stringToJavaExpr;
stringToJavaExpr =
stringExpr -> {
JavaExpression result =
StringToJavaExpression.atMethodInvocation(
stringExpr, methodInvocationTree, factory.getChecker());
Unknown unknown = result.containedOfClass(Unknown.class);
if (unknown != null) {
throw JavaExpressionParseUtil.constructJavaExpressionParseError(
result.toString(), "Expression " + unknown.toString() + " is unparsable.");
}
return result;
};

convertAnnotatedTypeMirror(stringToJavaExpr, declaredMethodType);
this.viewpointAdaptedCopier.visit(declaredMethodType, methodType);
this.errorAnnoReplacer.visit(methodType.getReturnType());
}
}
}
2 changes: 1 addition & 1 deletion checker/tests/nullness/Issue2470.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ static void ok() {
static void buggy2() {
new Example()
.setS("test")
// :: error:(contracts.precondition)
// :: error: (contracts.precondition)
.print();
}

Expand Down
14 changes: 14 additions & 0 deletions checker/tests/nullness/Issue6520.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package open.falsepos;

import java.util.stream.Collectors;
import java.util.stream.Stream;

class Issue6520 {

private record Data(String value) {}

Issue6520(Stream<Data> data) {
data.collect(Collectors.groupingBy(Data::value)).entrySet().stream()
.filter(entry -> entry.getValue().size() > 1);
}
}
47 changes: 47 additions & 0 deletions checker/tests/nullness/Issue6750.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package open.falsepos;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.checkerframework.checker.nullness.qual.KeyFor;

public record Issue6750(String type) {

void needKeyFor(@KeyFor("#2") String s, Map<String, String> map) {
throw new RuntimeException();
}

@KeyFor("#1") String returnKeyFor(Map<String, String> map) {
throw new RuntimeException();
}

Map<String, String> getMap(Function<String, String> s) {
throw new RuntimeException();
}

void use() {
// :: error: (argument)
needKeyFor("", getMap(String::toString));
// :: error: (expression.unparsable) :: error: (assignment)
@KeyFor("getMap(String::toString)") String s = returnKeyFor(new HashMap<>(getMap(String::toString)));
}

void method(List<Issue6750> externals) {
externals.stream().collect(Collectors.groupingBy(Issue6750::type)).entrySet().stream()
.forEach(
values -> {
// :: error: (assignment)
@KeyFor({}) String b = values.getKey();
});
}

void test(List<Issue6750> externals) {
externals.stream().collect(Collectors.groupingBy(Issue6750::type)).entrySet().stream()
.forEach(
values -> {
throw new RuntimeException("");
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1221,7 +1221,7 @@ public boolean isFlowParseError() {
* @return a {@link JavaExpressionParseException} for the expression {@code expr} with explanation
* {@code explanation}.
*/
private static JavaExpressionParseException constructJavaExpressionParseError(
public static JavaExpressionParseException constructJavaExpressionParseError(
String expr, String explanation) {
if (expr == null) {
throw new BugInCF("Must have an expression.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType;
import org.checkerframework.framework.type.AnnotatedTypeParameterBounds;
import org.checkerframework.framework.type.QualifierHierarchy;
import org.checkerframework.framework.type.treeannotator.TreeAnnotator;
import org.checkerframework.framework.type.visitor.AnnotatedTypeScanner;
import org.checkerframework.framework.type.visitor.DoubleAnnotatedTypeScanner;
Expand Down Expand Up @@ -119,6 +120,12 @@ public class DependentTypesHelper {
/** This scans an annotated type and returns a list of {@link DependentTypesError}. */
private final ExpressionErrorCollector expressionErrorCollector = new ExpressionErrorCollector();

/**
* This scans the annotated type and replaces any dependent type annotation that has a parse error
* with the top annotation in the hierarchy.
*/
protected final ErrorAnnoReplacer errorAnnoReplacer;

/**
* A scanner that applies a function to each {@link AnnotationMirror} and replaces it in the given
* {@code AnnotatedTypeMirror}. (This side-effects the {@code AnnotatedTypeMirror}.)
Expand All @@ -129,7 +136,7 @@ public class DependentTypesHelper {
* Copies annotations that might have been viewpoint adapted from the visited type (the first
* formal parameter of {@code ViewpointAdaptedCopier#visit}) to the second formal parameter.
*/
private final ViewpointAdaptedCopier viewpointAdaptedCopier = new ViewpointAdaptedCopier();
protected final ViewpointAdaptedCopier viewpointAdaptedCopier = new ViewpointAdaptedCopier();

/** The type mirror for java.lang.Object. */
protected final TypeMirror objectTM;
Expand All @@ -141,7 +148,7 @@ public class DependentTypesHelper {
*/
public DependentTypesHelper(AnnotatedTypeFactory factory) {
this.factory = factory;

this.errorAnnoReplacer = new ErrorAnnoReplacer(factory.getQualifierHierarchy());
this.annoToElements = new HashMap<>();
for (Class<? extends Annotation> expressionAnno : factory.getSupportedTypeQualifiers()) {
List<ExecutableElement> elementList =
Expand Down Expand Up @@ -1198,6 +1205,35 @@ private ExpressionErrorCollector() {
}
}

/**
* Replaces a dependent type annotation with a parser error with the top qualifier in the
* hierarchy.
*/
protected class ErrorAnnoReplacer extends SimpleAnnotatedTypeScanner<Void, Void> {

/**
* Create ErrorAnnoReplacer
*
* @param qh qualifier hierarchy
*/
private ErrorAnnoReplacer(QualifierHierarchy qh) {
super(
(AnnotatedTypeMirror type, Void aVoid) -> {
AnnotationMirrorSet newAnnos = new AnnotationMirrorSet();
Copy link
Member

Choose a reason for hiding this comment

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

This does a lot of allocation. I suggest first determining whether creating a new AnnotationMirrorSet is necessary, and then doing the work only if so. This requires two passes over the set, but I think it's worth it given how often this will be called.

for (AnnotationMirror am : type.getPrimaryAnnotations()) {
if (isExpressionAnno(am) && !errorElements(am).isEmpty()) {
newAnnos.add(qh.getTopAnnotation(am));
} else {
newAnnos.add(am);
}
}
type.clearPrimaryAnnotations();
type.addAnnotations(newAnnos);
return null;
});
}
}

/**
* Appends list2 to list1 in a new list. If either list is empty, returns the other. Thus, the
* result may be aliased to one of the arguments and the client should only read, not write into,
Expand Down Expand Up @@ -1226,7 +1262,11 @@ private static List<DependentTypesError> concatenate(
* visited type to the second formal parameter except for annotations on types that have been
* substituted.
*/
private class ViewpointAdaptedCopier extends DoubleAnnotatedTypeScanner<Void> {
protected class ViewpointAdaptedCopier extends DoubleAnnotatedTypeScanner<Void> {

/** Create a ViewpointAdaptedCopier. */
private ViewpointAdaptedCopier() {}

@Override
protected Void scan(AnnotatedTypeMirror from, AnnotatedTypeMirror to) {
if (from == null || to == null) {
Expand All @@ -1241,6 +1281,7 @@ protected Void scan(AnnotatedTypeMirror from, AnnotatedTypeMirror to) {
}
}
to.replaceAnnotations(replacements);

if (from.getKind() != to.getKind()
|| (from.getKind() == TypeKind.TYPEVAR
&& TypesUtils.isCapturedTypeVariable(to.getUnderlyingType()))) {
Expand Down Expand Up @@ -1277,7 +1318,7 @@ protected Void defaultAction(AnnotatedTypeMirror type1, AnnotatedTypeMirror type
* @param atm a type
* @return true if {@code atm} has any dependent type annotations
*/
private boolean hasDependentType(AnnotatedTypeMirror atm) {
protected boolean hasDependentType(AnnotatedTypeMirror atm) {
if (atm == null) {
return false;
}
Expand Down