From 6c2805b882b2bb64de891b4903d18406a5604fe4 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Thu, 29 Oct 2026 21:16:21 -0700 Subject: [PATCH 01/73] splitAssignments omits sides whose value an assignment might change --- .../nullness/AssignmentInComparison.java | 58 +++++++++++++++++++ .../framework/flow/CFAbstractTransfer.java | 56 +++++++++++++++--- 2 files changed, 105 insertions(+), 9 deletions(-) create mode 100644 checker/tests/nullness/AssignmentInComparison.java diff --git a/checker/tests/nullness/AssignmentInComparison.java b/checker/tests/nullness/AssignmentInComparison.java new file mode 100644 index 000000000000..fbdf5cff4363 --- /dev/null +++ b/checker/tests/nullness/AssignmentInComparison.java @@ -0,0 +1,58 @@ +import org.checkerframework.checker.nullness.qual.Nullable; + +// A comparison of an assignment refines only the sides that have the assigned value afterward. +public class AssignmentInComparison { + + @Nullable AssignmentInComparison next; + + @Nullable AssignmentInComparison other; + + static void localTarget(@Nullable AssignmentInComparison n) { + if (n == null) { + return; + } + if ((n = n.next) != null) { + n.toString(); + // After the assignment, `n.next` is a field of a different object. + // :: error: [dereference.of.nullable] + n.next.toString(); + } + } + + static void localTargetNull(@Nullable AssignmentInComparison m, AssignmentInComparison n) { + if ((m = n.next) != null) { + m.toString(); + n.next.toString(); + } + } + + static void fieldTarget(AssignmentInComparison n, AssignmentInComparison o) { + if ((n.next = o.other) != null) { + n.next.toString(); + // The assignment to `n.next` might change `o.other`, if `n` and `o` alias. + // :: error: [dereference.of.nullable] + o.other.toString(); + } + } + + static void fieldTargetLocalRhs(AssignmentInComparison n, @Nullable AssignmentInComparison o) { + if ((n.next = o) != null) { + n.next.toString(); + o.toString(); + } + } + + static void receiverReassigned( + @Nullable AssignmentInComparison n, @Nullable AssignmentInComparison o) { + if (n == null) { + return; + } + if ((n.next = (n = o)) != null) { + n.toString(); + o.toString(); + // After the assignment, `n.next` is a field of a different object. + // :: error: [dereference.of.nullable] + n.next.toString(); + } + } +} diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index af7633e08228..3fa14eb1772c 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -12,7 +12,6 @@ import com.sun.source.util.TreePath; import com.sun.tools.javac.code.Symbol.ClassSymbol; import java.util.ArrayList; -import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.List; @@ -66,6 +65,7 @@ import org.checkerframework.dataflow.cfg.node.ThisNode; import org.checkerframework.dataflow.cfg.node.VariableDeclarationNode; import org.checkerframework.dataflow.cfg.node.WideningConversionNode; +import org.checkerframework.dataflow.expression.ArrayAccess; import org.checkerframework.dataflow.expression.FieldAccess; import org.checkerframework.dataflow.expression.JavaExpression; import org.checkerframework.dataflow.expression.JavaExpressionParseException; @@ -959,20 +959,58 @@ protected TransferResult strengthenAnnotationOfEqualTo( * the rhs -- that is, it is possible that the rhs does not appear in the result, but rather its * lhs and rhs do). * + *

The result omits each side that, after the assignment, might have a different value than the + * assignment. For example, the result for {@code n = n.next} is just {@code n}, because after the + * assignment {@code n.next} is a field of a different object. + * * @param node possibly an assignment node - * @return a list containing all the right- and left-hand sides in the given assignment node; it - * contains just the node itself if it is not an assignment) + * @return a list containing the right- and left-hand sides in the given assignment node that have + * the value of the assignment after it executes; it contains just the node itself if it is + * not an assignment */ @SideEffectFree protected List splitAssignments(Node node) { - if (node instanceof AssignmentNode a) { - List result = new ArrayList<>(2); + List result = new ArrayList<>(); + List targets = new ArrayList<>(); + while (node instanceof AssignmentNode a) { result.add(a.getTarget()); - result.addAll(splitAssignments(a.getExpression())); - return result; - } else { - return Collections.singletonList(node); + targets.add(JavaExpression.fromNode(a.getTarget())); + node = a.getExpression(); + } + result.add(node); + result.removeIf(part -> mayBeChangedByAssignment(JavaExpression.fromNode(part), targets)); + return result; + } + + /** + * Returns true if an assignment to one of the given targets might change the value of the given + * expression, other than by the expression being that target. + * + *

An assignment to a local variable changes only expressions that contain the variable. An + * assignment to a field or an array element might change any expression that reads the heap. + * + * @param expr an expression + * @param targets the left-hand sides of assignments + * @return true if an assignment to one of {@code targets} might change the value of {@code expr} + */ + @Pure + protected static boolean mayBeChangedByAssignment( + JavaExpression expr, List targets) { + for (JavaExpression target : targets) { + if (expr.syntacticEquals(target)) { + continue; + } + if (target instanceof LocalVariable) { + if (expr.containsSyntacticEqualJavaExpression(target)) { + return true; + } + } else if (expr.containsOfClass(FieldAccess.class) + || expr.containsOfClass(ArrayAccess.class) + || expr.containsOfClass(MethodCall.class)) { + return true; + } } + return false; } @Override From cc3d25e37b46233185dfdac1c53aee30e12dbecc Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 30 Oct 2026 08:29:21 -0700 Subject: [PATCH 02/73] splitAssignments: account for nested assignments; ignore writes to a side's own location --- .../nullness/AssignmentInComparison.java | 93 ++++++++++++++- .../framework/flow/CFAbstractTransfer.java | 111 +++++++++++++++--- 2 files changed, 184 insertions(+), 20 deletions(-) diff --git a/checker/tests/nullness/AssignmentInComparison.java b/checker/tests/nullness/AssignmentInComparison.java index fbdf5cff4363..01b2179150c8 100644 --- a/checker/tests/nullness/AssignmentInComparison.java +++ b/checker/tests/nullness/AssignmentInComparison.java @@ -1,4 +1,5 @@ import org.checkerframework.checker.nullness.qual.Nullable; +import org.checkerframework.dataflow.qual.Pure; // A comparison of an assignment refines only the sides that have the assigned value afterward. public class AssignmentInComparison { @@ -7,6 +8,18 @@ public class AssignmentInComparison { @Nullable AssignmentInComparison other; + static @Nullable AssignmentInComparison global; + + @Pure + @Nullable AssignmentInComparison getNext() { + return next; + } + + @Pure + static @Nullable AssignmentInComparison id(@Nullable AssignmentInComparison n) { + return n; + } + static void localTarget(@Nullable AssignmentInComparison n) { if (n == null) { return; @@ -29,12 +42,64 @@ static void localTargetNull(@Nullable AssignmentInComparison m, AssignmentInComp static void fieldTarget(AssignmentInComparison n, AssignmentInComparison o) { if ((n.next = o.other) != null) { n.next.toString(); - // The assignment to `n.next` might change `o.other`, if `n` and `o` alias. - // :: error: [dereference.of.nullable] + // The assignment to `n.next` does not change `o.other`, which is a different field. o.other.toString(); } } + static void fieldTargetSameField(AssignmentInComparison n, AssignmentInComparison o) { + if ((n.next = o.next) != null) { + n.next.toString(); + // If `n` and `o` alias, the assignment stores into `o.next` the value it already has. + o.next.toString(); + } + } + + static void fieldTargetChangesRhsReceiver(AssignmentInComparison n, AssignmentInComparison o) { + if (o.next == null) { + return; + } + if ((n.next = o.next.other) != null) { + n.next.toString(); + // The assignment to `n.next` might change `o.next`, if `n` and `o` alias. + // :: error: [dereference.of.nullable] + // :: error: [dereference.of.nullable] + o.next.other.toString(); + } + } + + static void fieldTargetMethodCallRhs(AssignmentInComparison n, AssignmentInComparison o) { + if ((n.next = o.getNext()) != null) { + n.next.toString(); + // The assignment to `n.next` might change the result of `o.getNext()`. + // :: error: [dereference.of.nullable] + o.getNext().toString(); + } + } + + static void staticFieldRhs(AssignmentInComparison n) { + if ((n.next = global) != null) { + n.next.toString(); + global.toString(); + } + } + + void chainOfFieldTargets(@Nullable AssignmentInComparison o) { + if ((this.next = this.other = o) != null) { + this.next.toString(); + this.other.toString(); + o.toString(); + } + } + + static void arrayTarget(@Nullable Object[] a, @Nullable Object[] b) { + if ((a[0] = b[1]) != null) { + a[0].toString(); + // If `a` and `b` alias, the assignment stores into `b[1]` the value it already has. + b[1].toString(); + } + } + static void fieldTargetLocalRhs(AssignmentInComparison n, @Nullable AssignmentInComparison o) { if ((n.next = o) != null) { n.next.toString(); @@ -55,4 +120,28 @@ static void receiverReassigned( n.next.toString(); } } + + static void receiverReassignedInRhsReceiver( + @Nullable AssignmentInComparison n, AssignmentInComparison o) { + if (n == null) { + return; + } + if ((n.next = (n = o).other) != null) { + // After the assignment, `n.next` is a field of a different object. + // :: error: [dereference.of.nullable] + n.next.toString(); + } + } + + static void receiverReassignedInArgument( + @Nullable AssignmentInComparison n, AssignmentInComparison o) { + if (n == null) { + return; + } + if ((n.next = id(n = o)) != null) { + // After the assignment, `n.next` is a field of a different object. + // :: error: [dereference.of.nullable] + n.next.toString(); + } + } } diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 3fa14eb1772c..9e8392171faa 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -12,6 +12,7 @@ import com.sun.source.util.TreePath; import com.sun.tools.javac.code.Symbol.ClassSymbol; import java.util.ArrayList; +import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.List; @@ -66,11 +67,18 @@ import org.checkerframework.dataflow.cfg.node.VariableDeclarationNode; import org.checkerframework.dataflow.cfg.node.WideningConversionNode; import org.checkerframework.dataflow.expression.ArrayAccess; +import org.checkerframework.dataflow.expression.BinaryOperation; +import org.checkerframework.dataflow.expression.ClassName; import org.checkerframework.dataflow.expression.FieldAccess; +import org.checkerframework.dataflow.expression.FormalParameter; import org.checkerframework.dataflow.expression.JavaExpression; import org.checkerframework.dataflow.expression.JavaExpressionParseException; import org.checkerframework.dataflow.expression.LocalVariable; import org.checkerframework.dataflow.expression.MethodCall; +import org.checkerframework.dataflow.expression.SuperReference; +import org.checkerframework.dataflow.expression.ThisReference; +import org.checkerframework.dataflow.expression.UnaryOperation; +import org.checkerframework.dataflow.expression.ValueLiteral; import org.checkerframework.dataflow.qual.Pure; import org.checkerframework.dataflow.qual.SideEffectFree; import org.checkerframework.dataflow.util.NodeUtils; @@ -961,7 +969,9 @@ protected TransferResult strengthenAnnotationOfEqualTo( * *

The result omits each side that, after the assignment, might have a different value than the * assignment. For example, the result for {@code n = n.next} is just {@code n}, because after the - * assignment {@code n.next} is a field of a different object. + * assignment {@code n.next} is a field of a different object. The same holds for an assignment + * nested anywhere within {@code node}: the result for {@code n.next = (n = o).other} omits {@code + * n.next}. * * @param node possibly an assignment node * @return a list containing the right- and left-hand sides in the given assignment node that have @@ -970,11 +980,22 @@ protected TransferResult strengthenAnnotationOfEqualTo( */ @SideEffectFree protected List splitAssignments(Node node) { - List result = new ArrayList<>(); List targets = new ArrayList<>(); + for (Node n : node.getTransitiveOperands()) { + if (n instanceof AssignmentNode a) { + targets.add(JavaExpression.fromNode(a.getTarget())); + } + } + if (node instanceof AssignmentNode a) { + targets.add(JavaExpression.fromNode(a.getTarget())); + } + if (targets.isEmpty()) { + return Collections.singletonList(node); + } + + List result = new ArrayList<>(); while (node instanceof AssignmentNode a) { result.add(a.getTarget()); - targets.add(JavaExpression.fromNode(a.getTarget())); node = a.getExpression(); } result.add(node); @@ -983,36 +1004,90 @@ protected List splitAssignments(Node node) { } /** - * Returns true if an assignment to one of the given targets might change the value of the given - * expression, other than by the expression being that target. + * Returns true if an assignment to one of the given targets might make {@code expr} evaluate to a + * different value than the value of the assignment whose side {@code expr} is. * - *

An assignment to a local variable changes only expressions that contain the variable. An - * assignment to a field or an array element might change any expression that reads the heap. + *

If {@code expr} is a variable, field access, or array access, then an assignment to the + * location that {@code expr} denotes does not matter: an assignment in the same chain stores the + * same value, and a nested assignment executes before the location is written or read. Only an + * assignment that changes which location {@code expr} denotes (that is, its receiver or index) + * matters. * - * @param expr an expression - * @param targets the left-hand sides of assignments + * @param expr a side of an assignment + * @param targets the left-hand sides of all the assignments in an expression that contains {@code + * expr} * @return true if an assignment to one of {@code targets} might change the value of {@code expr} */ @Pure protected static boolean mayBeChangedByAssignment( JavaExpression expr, List targets) { for (JavaExpression target : targets) { - if (expr.syntacticEquals(target)) { - continue; + boolean mayBeChanged; + if (expr instanceof LocalVariable) { + mayBeChanged = false; + } else if (expr instanceof FieldAccess fa) { + mayBeChanged = assignmentMayChange(target, fa.getReceiver()); + } else if (expr instanceof ArrayAccess aa) { + mayBeChanged = + assignmentMayChange(target, aa.getArray()) + || assignmentMayChange(target, aa.getIndex()); + } else { + mayBeChanged = assignmentMayChange(target, expr); } - if (target instanceof LocalVariable) { - if (expr.containsSyntacticEqualJavaExpression(target)) { - return true; - } - } else if (expr.containsOfClass(FieldAccess.class) - || expr.containsOfClass(ArrayAccess.class) - || expr.containsOfClass(MethodCall.class)) { + if (mayBeChanged) { return true; } } return false; } + /** + * Returns true if an assignment to {@code target} might change the value of {@code expr}. + * + *

An assignment to a local variable changes only expressions that contain the variable. An + * assignment to a field changes only accesses of the same field and method calls. An assignment + * to an array element changes only array accesses and method calls. + * + * @param target the left-hand side of an assignment + * @param expr an expression + * @return true if an assignment to {@code target} might change the value of {@code expr} + */ + @Pure + private static boolean assignmentMayChange(JavaExpression target, JavaExpression expr) { + if (expr instanceof LocalVariable) { + return expr.syntacticEquals(target); + } else if (expr instanceof FieldAccess fa) { + return (target instanceof FieldAccess targetFa && targetFa.getField().equals(fa.getField())) + || assignmentMayChange(target, fa.getReceiver()); + } else if (expr instanceof ArrayAccess aa) { + return target instanceof ArrayAccess + || assignmentMayChange(target, aa.getArray()) + || assignmentMayChange(target, aa.getIndex()); + } else if (expr instanceof MethodCall mc) { + if (!(target instanceof LocalVariable) || assignmentMayChange(target, mc.getReceiver())) { + return true; + } + for (JavaExpression arg : mc.getArguments()) { + if (assignmentMayChange(target, arg)) { + return true; + } + } + return false; + } else if (expr instanceof UnaryOperation uo) { + return assignmentMayChange(target, uo.getOperand()); + } else if (expr instanceof BinaryOperation bo) { + return assignmentMayChange(target, bo.getLeft()) + || assignmentMayChange(target, bo.getRight()); + } else { + // An Unknown or ArrayCreation might be changed. + return !(expr instanceof ClassName + || expr instanceof FormalParameter + || expr instanceof SuperReference + || expr instanceof ThisReference + || expr instanceof ValueLiteral); + } + } + @Override public TransferResult visitAssignment(AssignmentNode n, TransferInput in) { Node lhs = n.getTarget(); From 847ddebfff3fed2ad851c1f9a6cae3a441182fda Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 30 Oct 2026 08:37:48 -0700 Subject: [PATCH 03/73] splitAssignments: reuse store aliasing, restore fast path, fix Javadoc, add Index and Value tests --- .../tests/index/AssignmentInComparison.java | 37 ++++++++++++++ .../nullness/AssignmentInComparison.java | 2 +- .../dataflow/expression/JavaExpression.java | 3 ++ .../framework/flow/CFAbstractStore.java | 14 +++++- .../framework/flow/CFAbstractTransfer.java | 50 ++++++++++++------- .../tests/value/AssignmentInComparison.java | 39 +++++++++++++++ 6 files changed, 126 insertions(+), 19 deletions(-) create mode 100644 checker/tests/index/AssignmentInComparison.java create mode 100644 framework/tests/value/AssignmentInComparison.java diff --git a/checker/tests/index/AssignmentInComparison.java b/checker/tests/index/AssignmentInComparison.java new file mode 100644 index 000000000000..f65f3cccc57a --- /dev/null +++ b/checker/tests/index/AssignmentInComparison.java @@ -0,0 +1,37 @@ +import org.checkerframework.checker.index.qual.NonNegative; +import org.checkerframework.checker.index.qual.Positive; +import org.checkerframework.dataflow.qual.Pure; + +// A comparison of an assignment refines only the sides that have the assigned value afterward. +public class AssignmentInComparison { + + @NonNegative int f; + + @Pure + @NonNegative int size() { + return f; + } + + static void localTarget(@NonNegative int i, @NonNegative int j) { + if ((i = j) > 0) { + @Positive int x = i; + @Positive int y = j; + } + } + + static void localTargetMethodCallRhs(@NonNegative int i, AssignmentInComparison n) { + if ((i = n.size()) > 0) { + @Positive int x = i; + @Positive int y = n.size(); + } + } + + static void fieldTargetMethodCallRhs(AssignmentInComparison n) { + if ((n.f = n.size()) > 0) { + @Positive int x = n.f; + // The assignment to `n.f` might change the result of `n.size()`. + // :: error: [assignment] + @Positive int y = n.size(); + } + } +} diff --git a/checker/tests/nullness/AssignmentInComparison.java b/checker/tests/nullness/AssignmentInComparison.java index 01b2179150c8..e969d85b003c 100644 --- a/checker/tests/nullness/AssignmentInComparison.java +++ b/checker/tests/nullness/AssignmentInComparison.java @@ -32,7 +32,7 @@ static void localTarget(@Nullable AssignmentInComparison n) { } } - static void localTargetNull(@Nullable AssignmentInComparison m, AssignmentInComparison n) { + static void localTargetFieldRhs(@Nullable AssignmentInComparison m, AssignmentInComparison n) { if ((m = n.next) != null) { m.toString(); n.next.toString(); diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java b/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java index c138482f81d2..0d614130838f 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java @@ -442,6 +442,7 @@ public String toStringDebug() { * @param node the FieldAccessNode to convert to a JavaExpression * @return the {@link FieldAccess} or {@link ClassName} that corresponds to {@code node} */ + @SideEffectFree public static JavaExpression fromNodeFieldAccess(FieldAccessNode node) { Node receiverNode = node.getReceiver(); String fieldName = node.getFieldName(); @@ -470,6 +471,7 @@ public static JavaExpression fromNodeFieldAccess(FieldAccessNode node) { * @return the internal representation (as an {@link ArrayAccess}) of a {@link ArrayAccessNode}. * Can contain {@link Unknown} as receiver. */ + @SideEffectFree public static ArrayAccess fromArrayAccess(ArrayAccessNode node) { JavaExpression array = fromNode(node.getArray()); JavaExpression index = fromNode(node.getIndex()); @@ -482,6 +484,7 @@ public static ArrayAccess fromArrayAccess(ArrayAccessNode node) { * @param receiverNode a node to convert to a JavaExpression * @return the internal representation of the given node. Might contain {@link Unknown}. */ + @SideEffectFree public static JavaExpression fromNode(Node receiverNode) { JavaExpression result = null; if (receiverNode instanceof FieldAccessNode fieldAccessNode) { diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java index 5f0fbb691342..d5b34e705f5d 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java @@ -1266,9 +1266,21 @@ protected void removeConflicting(LocalVariable var) { */ @Override public boolean canAlias(JavaExpression a, JavaExpression b) { + return canAlias(analysis.getTypes(), a, b); + } + + /** + * Can the objects {@code a} and {@code b} be aliases? Returns a conservative answer (i.e., + * returns {@code true} if not enough information is available to determine aliasing). + * + * @param types the type utilities + * @param a an expression + * @param b an expression + * @return true if {@code a} and {@code b} might be aliases + */ + public static boolean canAlias(Types types, JavaExpression a, JavaExpression b) { TypeMirror tb = b.getType(); TypeMirror ta = a.getType(); - Types types = analysis.getTypes(); return types.isSubtype(ta, tb) || types.isSubtype(tb, ta); } diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 9e8392171faa..6747d4aecc62 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -25,6 +25,7 @@ import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; +import javax.lang.model.util.Types; import org.checkerframework.checker.interning.qual.InternedDistinct; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.PolyNull; @@ -78,6 +79,7 @@ import org.checkerframework.dataflow.expression.SuperReference; import org.checkerframework.dataflow.expression.ThisReference; import org.checkerframework.dataflow.expression.UnaryOperation; +import org.checkerframework.dataflow.expression.Unknown; import org.checkerframework.dataflow.expression.ValueLiteral; import org.checkerframework.dataflow.qual.Pure; import org.checkerframework.dataflow.qual.SideEffectFree; @@ -916,7 +918,9 @@ public TransferResult visitNotEqual(NotEqualNode n, TransferInput p) * *

Note that when overriding this method, when a new type is inserted into the store, {@link * #splitAssignments} should be called, and the new type should be inserted into the store for - * each of the resulting nodes. + * each of the resulting nodes. The result of {@link #splitAssignments} omits each side of an + * assignment that might not have the assignment's value; do not insert the new type for such a + * side. * * @param firstNode the node that might be more precise * @param secondNode the node whose type to possibly refine @@ -963,9 +967,10 @@ protected TransferResult strengthenAnnotationOfEqualTo( /** * Takes a node, and either returns the node itself again (as a singleton list), or if the node is - * an assignment node, returns the lhs and rhs (where splitAssignments is applied recursively to + * an assignment node, returns the sides of the assignment that have the assignment's value after + * it executes. The sides are the lhs and rhs, where splitAssignments is applied recursively to * the rhs -- that is, it is possible that the rhs does not appear in the result, but rather its - * lhs and rhs do). + * lhs and rhs do. * *

The result omits each side that, after the assignment, might have a different value than the * assignment. For example, the result for {@code n = n.next} is just {@code n}, because after the @@ -973,6 +978,10 @@ protected TransferResult strengthenAnnotationOfEqualTo( * nested anywhere within {@code node}: the result for {@code n.next = (n = o).other} omits {@code * n.next}. * + *

A node that is not an assignment is returned even if it contains an assignment, as in {@code + * x + (x = 1)}. {@link JavaExpression#fromNode} converts such a node to an expression that + * contains {@link Unknown}, which no store holds a value for. + * * @param node possibly an assignment node * @return a list containing the right- and left-hand sides in the given assignment node that have * the value of the assignment after it executes; it contains just the node itself if it is @@ -980,19 +989,17 @@ protected TransferResult strengthenAnnotationOfEqualTo( */ @SideEffectFree protected List splitAssignments(Node node) { + if (!(node instanceof AssignmentNode assignment)) { + return Collections.singletonList(node); + } + List targets = new ArrayList<>(); + targets.add(JavaExpression.fromNode(assignment.getTarget())); for (Node n : node.getTransitiveOperands()) { if (n instanceof AssignmentNode a) { targets.add(JavaExpression.fromNode(a.getTarget())); } } - if (node instanceof AssignmentNode a) { - targets.add(JavaExpression.fromNode(a.getTarget())); - } - if (targets.isEmpty()) { - return Collections.singletonList(node); - } - List result = new ArrayList<>(); while (node instanceof AssignmentNode a) { result.add(a.getTarget()); @@ -1019,8 +1026,7 @@ protected List splitAssignments(Node node) { * @return true if an assignment to one of {@code targets} might change the value of {@code expr} */ @Pure - protected static boolean mayBeChangedByAssignment( - JavaExpression expr, List targets) { + protected boolean mayBeChangedByAssignment(JavaExpression expr, List targets) { for (JavaExpression target : targets) { boolean mayBeChanged; if (expr instanceof LocalVariable) { @@ -1045,22 +1051,32 @@ protected static boolean mayBeChangedByAssignment( * Returns true if an assignment to {@code target} might change the value of {@code expr}. * *

An assignment to a local variable changes only expressions that contain the variable. An - * assignment to a field changes only accesses of the same field and method calls. An assignment - * to an array element changes only array accesses and method calls. + * assignment to a field changes only accesses of the same field whose receiver might alias the + * target's receiver, and method calls. An assignment to an array element changes only accesses of + * arrays that might alias the target's array, and method calls. Aliasing is determined by {@link + * CFAbstractStore#canAlias(Types, JavaExpression, JavaExpression)}, as when the store handles an + * assignment. * * @param target the left-hand side of an assignment * @param expr an expression * @return true if an assignment to {@code target} might change the value of {@code expr} */ @Pure - private static boolean assignmentMayChange(JavaExpression target, JavaExpression expr) { + private boolean assignmentMayChange(JavaExpression target, JavaExpression expr) { + Types types = analysis.getTypes(); if (expr instanceof LocalVariable) { return expr.syntacticEquals(target); } else if (expr instanceof FieldAccess fa) { - return (target instanceof FieldAccess targetFa && targetFa.getField().equals(fa.getField())) + // The receiver of a static field access is the class through which it is accessed, which + // does not determine the field's location. + return (target instanceof FieldAccess targetFa + && targetFa.getField().equals(fa.getField()) + && (fa.isStatic() + || CFAbstractStore.canAlias(types, targetFa.getReceiver(), fa.getReceiver()))) || assignmentMayChange(target, fa.getReceiver()); } else if (expr instanceof ArrayAccess aa) { - return target instanceof ArrayAccess + return (target instanceof ArrayAccess targetAa + && CFAbstractStore.canAlias(types, targetAa.getArray(), aa.getArray())) || assignmentMayChange(target, aa.getArray()) || assignmentMayChange(target, aa.getIndex()); } else if (expr instanceof MethodCall mc) { diff --git a/framework/tests/value/AssignmentInComparison.java b/framework/tests/value/AssignmentInComparison.java new file mode 100644 index 000000000000..d4fc457fda62 --- /dev/null +++ b/framework/tests/value/AssignmentInComparison.java @@ -0,0 +1,39 @@ +import org.checkerframework.common.value.qual.IntVal; + +// A comparison of an assignment refines only the sides that have the assigned value afterward. +public class AssignmentInComparison { + + static void localTarget(int i, int j) { + if ((i = j) == 3) { + @IntVal(3) int x = i; + @IntVal(3) int y = j; + } + } + + static void indexReassigned(int i, int[] a) { + if ((i = a[i]) == 3) { + @IntVal(3) int x = i; + // After the assignment, `a[i]` is a different element of `a`. + // :: error: [assignment] + @IntVal(3) int y = a[i]; + } + } + + static void arrayTargetOtherArrayType(int[] a, long[] b, int[] idx) { + // An assignment to an element of `b` does not change `idx[0]`, because `b` and `idx` cannot + // alias. + if ((b[0] = a[idx[0]]) == 3) { + @IntVal(3) long x = b[0]; + @IntVal(3) int y = a[idx[0]]; + } + } + + static void arrayTargetSameArrayType(int[] a, int[] b, int[] idx) { + if ((b[0] = a[idx[0]]) == 3) { + @IntVal(3) int x = b[0]; + // The assignment to `b[0]` might change `idx[0]`, if `b` and `idx` alias. + // :: error: [assignment] + @IntVal(3) int y = a[idx[0]]; + } + } +} From a90af0cf65fbeb6623a92cee77474e9a0e64b09c Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 30 Oct 2026 08:53:58 -0700 Subject: [PATCH 04/73] splitAssignments: find all assignments in the tree, sound array aliasing, keep non-insertable sides --- .../nullness/AssignmentInComparison.java | 22 +++ .../framework/flow/CFAbstractStore.java | 14 +- .../framework/flow/CFAbstractTransfer.java | 167 +++++++++++------- 3 files changed, 131 insertions(+), 72 deletions(-) diff --git a/checker/tests/nullness/AssignmentInComparison.java b/checker/tests/nullness/AssignmentInComparison.java index e969d85b003c..85ec89160fdc 100644 --- a/checker/tests/nullness/AssignmentInComparison.java +++ b/checker/tests/nullness/AssignmentInComparison.java @@ -144,4 +144,26 @@ static void receiverReassignedInArgument( n.next.toString(); } } + + static void indexIncrementedInRhs(@Nullable Object[] a, int i, Object o) { + if ((a[i] = id2(i++, o)) != null) { + // After the assignment, `a[i]` is a different element of `a`. + // :: error: [dereference.of.nullable] + a[i].toString(); + } + } + + @Pure + static @Nullable Object id2(int i, @Nullable Object o) { + return o; + } + + static void arrayTargetTypeVariable(@Nullable T[] ts, @Nullable String[][] ss) { + if ((ts[0] = (T) ss[0][0]) != null) { + ts[0].toString(); + // The assignment to `ts[0]` might change `ss[0]`, if `ts` and `ss` alias. + // :: error: [dereference.of.nullable] + ss[0][0].toString(); + } + } } diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java index d5b34e705f5d..5f0fbb691342 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java @@ -1266,21 +1266,9 @@ protected void removeConflicting(LocalVariable var) { */ @Override public boolean canAlias(JavaExpression a, JavaExpression b) { - return canAlias(analysis.getTypes(), a, b); - } - - /** - * Can the objects {@code a} and {@code b} be aliases? Returns a conservative answer (i.e., - * returns {@code true} if not enough information is available to determine aliasing). - * - * @param types the type utilities - * @param a an expression - * @param b an expression - * @return true if {@code a} and {@code b} might be aliases - */ - public static boolean canAlias(Types types, JavaExpression a, JavaExpression b) { TypeMirror tb = b.getType(); TypeMirror ta = a.getType(); + Types types = analysis.getTypes(); return types.isSubtype(ta, tb) || types.isSubtype(tb, ta); } diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 6747d4aecc62..fc0f692940f8 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -1,15 +1,19 @@ package org.checkerframework.framework.flow; import com.sun.source.tree.AnnotatedTypeTree; +import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.ClassTree; +import com.sun.source.tree.CompoundAssignmentTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.Tree; +import com.sun.source.tree.UnaryTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; +import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol.ClassSymbol; import java.util.ArrayList; import java.util.Collections; @@ -24,8 +28,8 @@ import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; +import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; -import javax.lang.model.util.Types; import org.checkerframework.checker.interning.qual.InternedDistinct; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.PolyNull; @@ -972,11 +976,12 @@ protected TransferResult strengthenAnnotationOfEqualTo( * the rhs -- that is, it is possible that the rhs does not appear in the result, but rather its * lhs and rhs do. * - *

The result omits each side that, after the assignment, might have a different value than the - * assignment. For example, the result for {@code n = n.next} is just {@code n}, because after the - * assignment {@code n.next} is a field of a different object. The same holds for an assignment - * nested anywhere within {@code node}: the result for {@code n.next = (n = o).other} omits {@code - * n.next}. + *

The result omits each side that a store can hold a value for (see {@link + * CFAbstractStore#canInsertJavaExpression}) and that, after the assignment, might have a + * different value than the assignment. For example, the result for {@code n = n.next} is just + * {@code n}, because after the assignment {@code n.next} is a field of a different object. The + * same holds for an assignment, compound assignment, increment, or decrement nested anywhere + * within {@code node}: the result for {@code n.next = (n = o).other} omits {@code n.next}. * *

A node that is not an assignment is returned even if it contains an assignment, as in {@code * x + (x = 1)}. {@link JavaExpression#fromNode} converts such a node to an expression that @@ -994,12 +999,7 @@ protected List splitAssignments(Node node) { } List targets = new ArrayList<>(); - targets.add(JavaExpression.fromNode(assignment.getTarget())); - for (Node n : node.getTransitiveOperands()) { - if (n instanceof AssignmentNode a) { - targets.add(JavaExpression.fromNode(a.getTarget())); - } - } + new AssignmentTargetScanner().scan(assignment.getTree(), targets); List result = new ArrayList<>(); while (node instanceof AssignmentNode a) { result.add(a.getTarget()); @@ -1010,37 +1010,66 @@ protected List splitAssignments(Node node) { return result; } + /** + * Collects the variables that a tree assigns: the left-hand sides of its assignments and compound + * assignments, and the operands of its increments and decrements. It does not descend into lambda + * bodies or class bodies, which do not execute when the tree is evaluated. + */ + private static class AssignmentTargetScanner extends TreeScanner> { + + /** Creates an AssignmentTargetScanner. */ + AssignmentTargetScanner() {} + + @Override + public Void visitAssignment(AssignmentTree tree, List targets) { + targets.add(JavaExpression.fromTree(tree.getVariable())); + return super.visitAssignment(tree, targets); + } + + @Override + public Void visitCompoundAssignment(CompoundAssignmentTree tree, List targets) { + targets.add(JavaExpression.fromTree(tree.getVariable())); + return super.visitCompoundAssignment(tree, targets); + } + + @Override + public Void visitUnary(UnaryTree tree, List targets) { + switch (tree.getKind()) { + case PREFIX_INCREMENT, PREFIX_DECREMENT, POSTFIX_INCREMENT, POSTFIX_DECREMENT -> + targets.add(JavaExpression.fromTree(tree.getExpression())); + default -> {} + } + return super.visitUnary(tree, targets); + } + + @Override + public Void visitLambdaExpression(LambdaExpressionTree tree, List targets) { + return null; + } + + @Override + public Void visitClass(ClassTree tree, List targets) { + return null; + } + } + /** * Returns true if an assignment to one of the given targets might make {@code expr} evaluate to a - * different value than the value of the assignment whose side {@code expr} is. - * - *

If {@code expr} is a variable, field access, or array access, then an assignment to the - * location that {@code expr} denotes does not matter: an assignment in the same chain stores the - * same value, and a nested assignment executes before the location is written or read. Only an - * assignment that changes which location {@code expr} denotes (that is, its receiver or index) - * matters. + * different value than the value of the assignment whose side {@code expr} is. Returns false if + * no store can hold a value for {@code expr}. * * @param expr a side of an assignment - * @param targets the left-hand sides of all the assignments in an expression that contains {@code - * expr} + * @param targets the variables that an expression that contains {@code expr} assigns * @return true if an assignment to one of {@code targets} might change the value of {@code expr} */ @Pure - protected boolean mayBeChangedByAssignment(JavaExpression expr, List targets) { + private static boolean mayBeChangedByAssignment( + JavaExpression expr, List targets) { + if (!CFAbstractStore.canInsertJavaExpression(expr)) { + return false; + } for (JavaExpression target : targets) { - boolean mayBeChanged; - if (expr instanceof LocalVariable) { - mayBeChanged = false; - } else if (expr instanceof FieldAccess fa) { - mayBeChanged = assignmentMayChange(target, fa.getReceiver()); - } else if (expr instanceof ArrayAccess aa) { - mayBeChanged = - assignmentMayChange(target, aa.getArray()) - || assignmentMayChange(target, aa.getIndex()); - } else { - mayBeChanged = assignmentMayChange(target, expr); - } - if (mayBeChanged) { + if (assignmentMayChange(target, expr, true)) { return true; } } @@ -1051,49 +1080,54 @@ protected boolean mayBeChangedByAssignment(JavaExpression expr, ListAn assignment to a local variable changes only expressions that contain the variable. An - * assignment to a field changes only accesses of the same field whose receiver might alias the - * target's receiver, and method calls. An assignment to an array element changes only accesses of - * arrays that might alias the target's array, and method calls. Aliasing is determined by {@link - * CFAbstractStore#canAlias(Types, JavaExpression, JavaExpression)}, as when the store handles an - * assignment. + * assignment to a field changes only accesses of the same field, and method calls. An assignment + * to an array element changes only accesses of arrays that might alias the target's array, and + * method calls. + * + *

If {@code ignoreOwnLocation} is true and {@code expr} is a variable, field access, or array + * access, then an assignment to the location that {@code expr} denotes does not matter: an + * assignment in the same chain as {@code expr} stores the same value, and a nested assignment + * executes before the location is written or read. Only an assignment that changes which location + * {@code expr} denotes (that is, its receiver or index) matters. * * @param target the left-hand side of an assignment * @param expr an expression + * @param ignoreOwnLocation if true, ignore an assignment to the location that {@code expr} + * denotes * @return true if an assignment to {@code target} might change the value of {@code expr} */ @Pure - private boolean assignmentMayChange(JavaExpression target, JavaExpression expr) { - Types types = analysis.getTypes(); + private static boolean assignmentMayChange( + JavaExpression target, JavaExpression expr, boolean ignoreOwnLocation) { if (expr instanceof LocalVariable) { - return expr.syntacticEquals(target); + return !ignoreOwnLocation && expr.syntacticEquals(target); } else if (expr instanceof FieldAccess fa) { - // The receiver of a static field access is the class through which it is accessed, which - // does not determine the field's location. - return (target instanceof FieldAccess targetFa - && targetFa.getField().equals(fa.getField()) - && (fa.isStatic() - || CFAbstractStore.canAlias(types, targetFa.getReceiver(), fa.getReceiver()))) - || assignmentMayChange(target, fa.getReceiver()); + return (!ignoreOwnLocation + && target instanceof FieldAccess targetFa + && targetFa.getField().equals(fa.getField())) + || assignmentMayChange(target, fa.getReceiver(), false); } else if (expr instanceof ArrayAccess aa) { - return (target instanceof ArrayAccess targetAa - && CFAbstractStore.canAlias(types, targetAa.getArray(), aa.getArray())) - || assignmentMayChange(target, aa.getArray()) - || assignmentMayChange(target, aa.getIndex()); + return (!ignoreOwnLocation + && target instanceof ArrayAccess targetAa + && arraysMayAlias(targetAa, aa)) + || assignmentMayChange(target, aa.getArray(), false) + || assignmentMayChange(target, aa.getIndex(), false); } else if (expr instanceof MethodCall mc) { - if (!(target instanceof LocalVariable) || assignmentMayChange(target, mc.getReceiver())) { + if (!(target instanceof LocalVariable) + || assignmentMayChange(target, mc.getReceiver(), false)) { return true; } for (JavaExpression arg : mc.getArguments()) { - if (assignmentMayChange(target, arg)) { + if (assignmentMayChange(target, arg, false)) { return true; } } return false; } else if (expr instanceof UnaryOperation uo) { - return assignmentMayChange(target, uo.getOperand()); + return assignmentMayChange(target, uo.getOperand(), false); } else if (expr instanceof BinaryOperation bo) { - return assignmentMayChange(target, bo.getLeft()) - || assignmentMayChange(target, bo.getRight()); + return assignmentMayChange(target, bo.getLeft(), false) + || assignmentMayChange(target, bo.getRight(), false); } else { // An Unknown or ArrayCreation might be changed. return !(expr instanceof ClassName @@ -1104,6 +1138,21 @@ private boolean assignmentMayChange(JavaExpression target, JavaExpression expr) } } + /** + * Returns true if the arrays of the given array accesses might be the same array. They cannot be + * if their component types differ and at least one of the component types is primitive. + * + * @param a1 an array access + * @param a2 an array access + * @return true if the arrays of {@code a1} and {@code a2} might be the same array + */ + @Pure + private static boolean arraysMayAlias(ArrayAccess a1, ArrayAccess a2) { + TypeKind kind1 = a1.getType().getKind(); + TypeKind kind2 = a2.getType().getKind(); + return kind1 == kind2 || !(kind1.isPrimitive() || kind2.isPrimitive()); + } + @Override public TransferResult visitAssignment(AssignmentNode n, TransferInput in) { Node lhs = n.getTarget(); From 6d0da35e4fa141d94f36f73beb90f6059f105a70 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 30 Oct 2026 09:06:09 -0700 Subject: [PATCH 05/73] Test assignment in comparison with generic receivers that are not subtypes --- .../nullness/AssignmentInComparison.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/checker/tests/nullness/AssignmentInComparison.java b/checker/tests/nullness/AssignmentInComparison.java index 85ec89160fdc..a8d2076143f1 100644 --- a/checker/tests/nullness/AssignmentInComparison.java +++ b/checker/tests/nullness/AssignmentInComparison.java @@ -68,6 +68,26 @@ static void fieldTargetChangesRhsReceiver(AssignmentInComparison n, AssignmentIn } } + static class Box { + @Nullable Box next; + @Nullable Box other; + } + + static void fieldTargetChangesRhsReceiverGeneric( + Box a, Box b) { + if (b.next == null) { + return; + } + if ((a.next = b.next.other) != null) { + a.next.toString(); + // Neither receiver type is a subtype of the other, but a `Box` can be both. The + // assignment to `a.next` might change `b.next`, if `a` and `b` alias. + // :: error: [dereference.of.nullable] + // :: error: [dereference.of.nullable] + b.next.other.toString(); + } + } + static void fieldTargetMethodCallRhs(AssignmentInComparison n, AssignmentInComparison o) { if ((n.next = o.getNext()) != null) { n.next.toString(); From e535d62ebf63e5454934a00cdca6499809f0b574 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 1 Nov 2026 14:27:11 -0800 Subject: [PATCH 06/73] Suppress unchecked-cast warning in AssignmentInComparison test --- checker/tests/nullness/AssignmentInComparison.java | 1 + 1 file changed, 1 insertion(+) diff --git a/checker/tests/nullness/AssignmentInComparison.java b/checker/tests/nullness/AssignmentInComparison.java index a8d2076143f1..fa27b4a0512c 100644 --- a/checker/tests/nullness/AssignmentInComparison.java +++ b/checker/tests/nullness/AssignmentInComparison.java @@ -178,6 +178,7 @@ static void indexIncrementedInRhs(@Nullable Object[] a, int i, Object o) { return o; } + @SuppressWarnings("unchecked") // cast to T static void arrayTargetTypeVariable(@Nullable T[] ts, @Nullable String[][] ss) { if ((ts[0] = (T) ss[0][0]) != null) { ts[0].toString(); From 90444491926d9eaf10516eb2fb976d3e7afbd19a Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 2 Nov 2026 21:54:12 -0800 Subject: [PATCH 07/73] Handle parenthesized and unrecognized assignment targets in splitAssignments Strip parentheses from an assignment target before converting it to a JavaExpression, and treat an Unknown target as possibly changing every expression. --- .../nullness/AssignmentInComparison.java | 12 ++++++++++ .../framework/flow/CFAbstractTransfer.java | 23 ++++++++++++++++--- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/checker/tests/nullness/AssignmentInComparison.java b/checker/tests/nullness/AssignmentInComparison.java index fa27b4a0512c..13bc30bda185 100644 --- a/checker/tests/nullness/AssignmentInComparison.java +++ b/checker/tests/nullness/AssignmentInComparison.java @@ -32,6 +32,18 @@ static void localTarget(@Nullable AssignmentInComparison n) { } } + static void parenthesizedLocalTarget(@Nullable AssignmentInComparison n) { + if (n == null) { + return; + } + if (((n) = n.next) != null) { + n.toString(); + // After the assignment, `n.next` is a field of a different object. + // :: error: [dereference.of.nullable] + n.next.toString(); + } + } + static void localTargetFieldRhs(@Nullable AssignmentInComparison m, AssignmentInComparison n) { if ((m = n.next) != null) { m.toString(); diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index fc0f692940f8..efce936120ba 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -1020,15 +1020,28 @@ private static class AssignmentTargetScanner extends TreeScanner targets) { - targets.add(JavaExpression.fromTree(tree.getVariable())); + targets.add(targetExpression(tree.getVariable())); return super.visitAssignment(tree, targets); } @Override public Void visitCompoundAssignment(CompoundAssignmentTree tree, List targets) { - targets.add(JavaExpression.fromTree(tree.getVariable())); + targets.add(targetExpression(tree.getVariable())); return super.visitCompoundAssignment(tree, targets); } @@ -1036,7 +1049,7 @@ public Void visitCompoundAssignment(CompoundAssignmentTree tree, List targets) { switch (tree.getKind()) { case PREFIX_INCREMENT, PREFIX_DECREMENT, POSTFIX_INCREMENT, POSTFIX_DECREMENT -> - targets.add(JavaExpression.fromTree(tree.getExpression())); + targets.add(targetExpression(tree.getExpression())); default -> {} } return super.visitUnary(tree, targets); @@ -1099,6 +1112,10 @@ private static boolean mayBeChangedByAssignment( @Pure private static boolean assignmentMayChange( JavaExpression target, JavaExpression expr, boolean ignoreOwnLocation) { + if (target instanceof Unknown) { + // The target is not understood, so it might be any location. + return true; + } if (expr instanceof LocalVariable) { return !ignoreOwnLocation && expr.syntacticEquals(target); } else if (expr instanceof FieldAccess fa) { From ec913668be5f9652c5efb48e645637082730e722 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 7 Nov 2026 19:53:39 -0800 Subject: [PATCH 08/73] splitAssignments: scan anonymous class initializers; add tests AssignmentTargetScanner now collects assignments in the initializer blocks and field initializers of an anonymous class body, which execute when the enclosing `new` expression is evaluated. Also add tests of a parenthesized target, of an assignment in an array target's index, and of an assignment in a field target's receiver. --- .../nullness/AssignmentInComparison.java | 63 +++++++++++++++++++ .../framework/flow/CFAbstractTransfer.java | 18 +++++- 2 files changed, 80 insertions(+), 1 deletion(-) diff --git a/checker/tests/nullness/AssignmentInComparison.java b/checker/tests/nullness/AssignmentInComparison.java index 13bc30bda185..f2ed91e28134 100644 --- a/checker/tests/nullness/AssignmentInComparison.java +++ b/checker/tests/nullness/AssignmentInComparison.java @@ -116,6 +116,40 @@ static void staticFieldRhs(AssignmentInComparison n) { } } + static void anonymousClassInitializerReassignsReceiver(AssignmentInComparison other) { + if (global == null) { + return; + } + if ((global.next = + id( + new AssignmentInComparison() { + { + global = other; + } + })) + != null) { + // After the assignment, `global.next` is a field of a different object. + // :: error: [dereference.of.nullable] + global.next.toString(); + } + } + + static void anonymousClassFieldInitializerReassignsReceiver(AssignmentInComparison other) { + if (global == null) { + return; + } + if ((global.next = + id( + new AssignmentInComparison() { + @Nullable Object f = (global = other); + })) + != null) { + // After the assignment, `global.next` is a field of a different object. + // :: error: [dereference.of.nullable] + global.next.toString(); + } + } + void chainOfFieldTargets(@Nullable AssignmentInComparison o) { if ((this.next = this.other = o) != null) { this.next.toString(); @@ -153,6 +187,20 @@ static void receiverReassigned( } } + static void receiverReassignedParenthesized( + @Nullable AssignmentInComparison n, @Nullable AssignmentInComparison o) { + if (n == null) { + return; + } + if ((n.next = ((n) = o)) != null) { + n.toString(); + o.toString(); + // After the assignment, `n.next` is a field of a different object. + // :: error: [dereference.of.nullable] + n.next.toString(); + } + } + static void receiverReassignedInRhsReceiver( @Nullable AssignmentInComparison n, AssignmentInComparison o) { if (n == null) { @@ -185,6 +233,21 @@ static void indexIncrementedInRhs(@Nullable Object[] a, int i, Object o) { } } + static void arrayTargetWithAssignmentInIndex(@Nullable Object[] a, int i, @Nullable Object o) { + if ((a[i = 0] = o) != null) { + // The assignment to an element of `a` does not change the local variable `o`. + o.toString(); + } + } + + static void fieldTargetWithAssignmentInReceiver( + AssignmentInComparison n, AssignmentInComparison m, @Nullable AssignmentInComparison o) { + if (((n = m).next = o) != null) { + // The assignment to a `next` field does not change the local variable `o`. + o.toString(); + } + } + @Pure static @Nullable Object id2(int i, @Nullable Object o) { return o; diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index efce936120ba..94cdf6f32035 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -2,6 +2,7 @@ import com.sun.source.tree.AnnotatedTypeTree; import com.sun.source.tree.AssignmentTree; +import com.sun.source.tree.BlockTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompoundAssignmentTree; import com.sun.source.tree.ExpressionTree; @@ -1013,7 +1014,9 @@ protected List splitAssignments(Node node) { /** * Collects the variables that a tree assigns: the left-hand sides of its assignments and compound * assignments, and the operands of its increments and decrements. It does not descend into lambda - * bodies or class bodies, which do not execute when the tree is evaluated. + * bodies, method bodies, or named class declarations, which do not execute when the tree is + * evaluated. It does descend into the initializer blocks and field initializers of an anonymous + * class body, which execute when the enclosing {@code new} expression is evaluated. */ private static class AssignmentTargetScanner extends TreeScanner> { @@ -1062,6 +1065,19 @@ public Void visitLambdaExpression(LambdaExpressionTree tree, List targets) { + if (!tree.getSimpleName().isEmpty()) { + // A named (local) class declaration does not execute. + return null; + } + // An anonymous class body: its initializers execute when the `new` expression is evaluated. + for (Tree member : tree.getMembers()) { + if (member instanceof BlockTree block) { + scan(block, targets); + } else if (member instanceof VariableTree field) { + scan(field.getInitializer(), targets); + } + // Skip methods and nested class declarations. + } return null; } } From cb80e70508381ba809573f617379938213f489b4 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 8 Nov 2026 07:21:21 -0800 Subject: [PATCH 09/73] Don't refine a left operand that the right operand might reassign For example, x == nonNull(x = null) says nothing about the value of x after the assignment. Moved from #8462. --- .../nullness/AssignmentInComparison.java | 27 ++++++ .../framework/flow/CFAbstractTransfer.java | 83 +++++++++++++++---- 2 files changed, 94 insertions(+), 16 deletions(-) diff --git a/checker/tests/nullness/AssignmentInComparison.java b/checker/tests/nullness/AssignmentInComparison.java index f2ed91e28134..ec8659155306 100644 --- a/checker/tests/nullness/AssignmentInComparison.java +++ b/checker/tests/nullness/AssignmentInComparison.java @@ -262,4 +262,31 @@ static void arrayTargetTypeVariable(@Nullable T[] ts, @Nullable String[][] s ss[0][0].toString(); } } + + static Object nonNull(@Nullable Object o) { + return ""; + } + + // The right operand assigns `x` after the left operand reads it, so the comparison says nothing + // about the new value of `x`. + void assignmentInRightOperand(@Nullable Object x) { + if (x == nonNull(x = null)) { + // :: error: [dereference.of.nullable] + x.toString(); + } + } + + void assignmentInParenthesizedRightOperand(@Nullable Object x) { + if ((x) == (nonNull(x = null))) { + // :: error: [dereference.of.nullable] + x.toString(); + } + } + + // The left operand assigns `x` before the right operand reads it, so refining `x` is sound. + void assignmentInLeftOperand(@Nullable Object x) { + if (nonNull(x = null) == x) { + x.toString(); + } + } } diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 94cdf6f32035..1a7e00e62faa 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -2,6 +2,7 @@ import com.sun.source.tree.AnnotatedTypeTree; import com.sun.source.tree.AssignmentTree; +import com.sun.source.tree.BinaryTree; import com.sun.source.tree.BlockTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompoundAssignmentTree; @@ -10,6 +11,7 @@ import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewClassTree; +import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.Tree; import com.sun.source.tree.UnaryTree; import com.sun.source.tree.VariableTree; @@ -988,6 +990,12 @@ protected TransferResult strengthenAnnotationOfEqualTo( * x + (x = 1)}. {@link JavaExpression#fromNode} converts such a node to an expression that * contains {@link Unknown}, which no store holds a value for. * + *

If {@code node} is the left operand of a binary operation, then the right operand is + * evaluated after {@code node}, but before the operation's result is known. The result omits each + * part whose value an assignment in the right operand might change. For example, the result for + * the left operand of {@code x == nonNull(x = null)} is empty, because the comparison says + * nothing about the value of {@code x} after the assignment. + * * @param node possibly an assignment node * @return a list containing the right- and left-hand sides in the given assignment node that have * the value of the assignment after it executes; it contains just the node itself if it is @@ -995,22 +1003,63 @@ protected TransferResult strengthenAnnotationOfEqualTo( */ @SideEffectFree protected List splitAssignments(Node node) { - if (!(node instanceof AssignmentNode assignment)) { - return Collections.singletonList(node); + List result = new ArrayList<>(); + if (node instanceof AssignmentNode assignment) { + List targets = new ArrayList<>(); + new AssignmentTargetScanner().scan(assignment.getTree(), targets); + Node part = node; + while (part instanceof AssignmentNode a) { + result.add(a.getTarget()); + part = a.getExpression(); + } + result.add(part); + result.removeIf(p -> mayBeChangedByAssignment(JavaExpression.fromNode(p), targets, true)); + } else { + result.add(node); } - List targets = new ArrayList<>(); - new AssignmentTargetScanner().scan(assignment.getTree(), targets); - List result = new ArrayList<>(); - while (node instanceof AssignmentNode a) { - result.add(a.getTarget()); - node = a.getExpression(); + List laterTargets = assignmentTargetsOfLaterOperand(node); + if (!laterTargets.isEmpty()) { + result.removeIf( + p -> mayBeChangedByAssignment(JavaExpression.fromNode(p), laterTargets, false)); } - result.add(node); - result.removeIf(part -> mayBeChangedByAssignment(JavaExpression.fromNode(part), targets)); return result; } + /** + * If {@code node} is the left operand of a binary operation, returns the variables that the right + * operand assigns. The right operand is evaluated after {@code node}, so its assignments might + * change the value of {@code node}'s parts before the binary operation's result is known. + * Otherwise, returns the empty list. + * + * @param node a node + * @return the variables that the operand evaluated after {@code node} assigns, or the empty list + */ + private List assignmentTargetsOfLaterOperand(Node node) { + Tree tree = node.getTree(); + if (tree == null) { + return Collections.emptyList(); + } + TreePath path = analysis.atypeFactory.getPath(tree); + if (path == null) { + return Collections.emptyList(); + } + Tree child = path.getLeaf(); + TreePath parentPath = path.getParentPath(); + while (parentPath != null && parentPath.getLeaf() instanceof ParenthesizedTree) { + child = parentPath.getLeaf(); + parentPath = parentPath.getParentPath(); + } + if (parentPath == null + || !(parentPath.getLeaf() instanceof BinaryTree binary) + || binary.getLeftOperand() != child) { + return Collections.emptyList(); + } + List targets = new ArrayList<>(); + new AssignmentTargetScanner().scan(binary.getRightOperand(), targets); + return targets; + } + /** * Collects the variables that a tree assigns: the left-hand sides of its assignments and compound * assignments, and the operands of its increments and decrements. It does not descend into lambda @@ -1084,21 +1133,23 @@ public Void visitClass(ClassTree tree, List targets) { /** * Returns true if an assignment to one of the given targets might make {@code expr} evaluate to a - * different value than the value of the assignment whose side {@code expr} is. Returns false if - * no store can hold a value for {@code expr}. + * different value than the value that {@code expr} had when it was evaluated. Returns false if no + * store can hold a value for {@code expr}. * - * @param expr a side of an assignment - * @param targets the variables that an expression that contains {@code expr} assigns + * @param expr a side of an assignment, or an operand of a binary operation + * @param targets the variables that an expression that contains or follows {@code expr} assigns + * @param ignoreOwnLocation if true, ignore an assignment to the location that {@code expr} + * denotes; see {@link #assignmentMayChange} * @return true if an assignment to one of {@code targets} might change the value of {@code expr} */ @Pure private static boolean mayBeChangedByAssignment( - JavaExpression expr, List targets) { + JavaExpression expr, List targets, boolean ignoreOwnLocation) { if (!CFAbstractStore.canInsertJavaExpression(expr)) { return false; } for (JavaExpression target : targets) { - if (assignmentMayChange(target, expr, true)) { + if (assignmentMayChange(target, expr, ignoreOwnLocation)) { return true; } } From c4ea38ddf7e52d27456677ee4fd6eb6cfa06c841 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 8 Nov 2026 08:40:42 -0800 Subject: [PATCH 10/73] Move the treatment of a right operand that reassigns the left operand to a separate branch The fix for x == nonNull(x = null) moves to branch split-assignments-later-operand, which builds on this branch. --- .../nullness/AssignmentInComparison.java | 27 ------ .../framework/flow/CFAbstractTransfer.java | 83 ++++--------------- 2 files changed, 16 insertions(+), 94 deletions(-) diff --git a/checker/tests/nullness/AssignmentInComparison.java b/checker/tests/nullness/AssignmentInComparison.java index ec8659155306..f2ed91e28134 100644 --- a/checker/tests/nullness/AssignmentInComparison.java +++ b/checker/tests/nullness/AssignmentInComparison.java @@ -262,31 +262,4 @@ static void arrayTargetTypeVariable(@Nullable T[] ts, @Nullable String[][] s ss[0][0].toString(); } } - - static Object nonNull(@Nullable Object o) { - return ""; - } - - // The right operand assigns `x` after the left operand reads it, so the comparison says nothing - // about the new value of `x`. - void assignmentInRightOperand(@Nullable Object x) { - if (x == nonNull(x = null)) { - // :: error: [dereference.of.nullable] - x.toString(); - } - } - - void assignmentInParenthesizedRightOperand(@Nullable Object x) { - if ((x) == (nonNull(x = null))) { - // :: error: [dereference.of.nullable] - x.toString(); - } - } - - // The left operand assigns `x` before the right operand reads it, so refining `x` is sound. - void assignmentInLeftOperand(@Nullable Object x) { - if (nonNull(x = null) == x) { - x.toString(); - } - } } diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 1a7e00e62faa..94cdf6f32035 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -2,7 +2,6 @@ import com.sun.source.tree.AnnotatedTypeTree; import com.sun.source.tree.AssignmentTree; -import com.sun.source.tree.BinaryTree; import com.sun.source.tree.BlockTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompoundAssignmentTree; @@ -11,7 +10,6 @@ import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewClassTree; -import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.Tree; import com.sun.source.tree.UnaryTree; import com.sun.source.tree.VariableTree; @@ -990,12 +988,6 @@ protected TransferResult strengthenAnnotationOfEqualTo( * x + (x = 1)}. {@link JavaExpression#fromNode} converts such a node to an expression that * contains {@link Unknown}, which no store holds a value for. * - *

If {@code node} is the left operand of a binary operation, then the right operand is - * evaluated after {@code node}, but before the operation's result is known. The result omits each - * part whose value an assignment in the right operand might change. For example, the result for - * the left operand of {@code x == nonNull(x = null)} is empty, because the comparison says - * nothing about the value of {@code x} after the assignment. - * * @param node possibly an assignment node * @return a list containing the right- and left-hand sides in the given assignment node that have * the value of the assignment after it executes; it contains just the node itself if it is @@ -1003,63 +995,22 @@ protected TransferResult strengthenAnnotationOfEqualTo( */ @SideEffectFree protected List splitAssignments(Node node) { - List result = new ArrayList<>(); - if (node instanceof AssignmentNode assignment) { - List targets = new ArrayList<>(); - new AssignmentTargetScanner().scan(assignment.getTree(), targets); - Node part = node; - while (part instanceof AssignmentNode a) { - result.add(a.getTarget()); - part = a.getExpression(); - } - result.add(part); - result.removeIf(p -> mayBeChangedByAssignment(JavaExpression.fromNode(p), targets, true)); - } else { - result.add(node); + if (!(node instanceof AssignmentNode assignment)) { + return Collections.singletonList(node); } - List laterTargets = assignmentTargetsOfLaterOperand(node); - if (!laterTargets.isEmpty()) { - result.removeIf( - p -> mayBeChangedByAssignment(JavaExpression.fromNode(p), laterTargets, false)); + List targets = new ArrayList<>(); + new AssignmentTargetScanner().scan(assignment.getTree(), targets); + List result = new ArrayList<>(); + while (node instanceof AssignmentNode a) { + result.add(a.getTarget()); + node = a.getExpression(); } + result.add(node); + result.removeIf(part -> mayBeChangedByAssignment(JavaExpression.fromNode(part), targets)); return result; } - /** - * If {@code node} is the left operand of a binary operation, returns the variables that the right - * operand assigns. The right operand is evaluated after {@code node}, so its assignments might - * change the value of {@code node}'s parts before the binary operation's result is known. - * Otherwise, returns the empty list. - * - * @param node a node - * @return the variables that the operand evaluated after {@code node} assigns, or the empty list - */ - private List assignmentTargetsOfLaterOperand(Node node) { - Tree tree = node.getTree(); - if (tree == null) { - return Collections.emptyList(); - } - TreePath path = analysis.atypeFactory.getPath(tree); - if (path == null) { - return Collections.emptyList(); - } - Tree child = path.getLeaf(); - TreePath parentPath = path.getParentPath(); - while (parentPath != null && parentPath.getLeaf() instanceof ParenthesizedTree) { - child = parentPath.getLeaf(); - parentPath = parentPath.getParentPath(); - } - if (parentPath == null - || !(parentPath.getLeaf() instanceof BinaryTree binary) - || binary.getLeftOperand() != child) { - return Collections.emptyList(); - } - List targets = new ArrayList<>(); - new AssignmentTargetScanner().scan(binary.getRightOperand(), targets); - return targets; - } - /** * Collects the variables that a tree assigns: the left-hand sides of its assignments and compound * assignments, and the operands of its increments and decrements. It does not descend into lambda @@ -1133,23 +1084,21 @@ public Void visitClass(ClassTree tree, List targets) { /** * Returns true if an assignment to one of the given targets might make {@code expr} evaluate to a - * different value than the value that {@code expr} had when it was evaluated. Returns false if no - * store can hold a value for {@code expr}. + * different value than the value of the assignment whose side {@code expr} is. Returns false if + * no store can hold a value for {@code expr}. * - * @param expr a side of an assignment, or an operand of a binary operation - * @param targets the variables that an expression that contains or follows {@code expr} assigns - * @param ignoreOwnLocation if true, ignore an assignment to the location that {@code expr} - * denotes; see {@link #assignmentMayChange} + * @param expr a side of an assignment + * @param targets the variables that an expression that contains {@code expr} assigns * @return true if an assignment to one of {@code targets} might change the value of {@code expr} */ @Pure private static boolean mayBeChangedByAssignment( - JavaExpression expr, List targets, boolean ignoreOwnLocation) { + JavaExpression expr, List targets) { if (!CFAbstractStore.canInsertJavaExpression(expr)) { return false; } for (JavaExpression target : targets) { - if (assignmentMayChange(target, expr, ignoreOwnLocation)) { + if (assignmentMayChange(target, expr, true)) { return true; } } From dd4e21112d055eaceb714529577ce1860254836a Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Wed, 11 Nov 2026 17:21:35 -0800 Subject: [PATCH 11/73] AssignmentTargetScanner does not descend into annotations Javac represents an annotation argument as an assignment, as in `@IntVal(value = {0, 1})`, but it does not assign a variable. Treating it as one crashed in JavaExpression.fromTree. --- .../tests/nullness/AssignmentInComparison.java | 10 ++++++++++ .../framework/flow/CFAbstractTransfer.java | 16 ++++++++++++---- .../tests/value/AssignmentInComparison.java | 7 +++++++ 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/checker/tests/nullness/AssignmentInComparison.java b/checker/tests/nullness/AssignmentInComparison.java index f2ed91e28134..11ffa415b9ff 100644 --- a/checker/tests/nullness/AssignmentInComparison.java +++ b/checker/tests/nullness/AssignmentInComparison.java @@ -1,3 +1,6 @@ +import java.util.ArrayList; +import java.util.Map; +import org.checkerframework.checker.nullness.qual.KeyFor; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.dataflow.qual.Pure; @@ -262,4 +265,11 @@ static void arrayTargetTypeVariable(@Nullable T[] ts, @Nullable String[][] s ss[0][0].toString(); } } + + static void annotationArgumentInRhs(@Nullable Object o, Map m) { + // The annotation argument `"m"` is not an assignment to a variable. + if ((o = new ArrayList<@KeyFor("m") String>()) != null) { + o.toString(); + } + } } diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 94cdf6f32035..0155fdc46b9b 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -1,6 +1,7 @@ package org.checkerframework.framework.flow; import com.sun.source.tree.AnnotatedTypeTree; +import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.BlockTree; import com.sun.source.tree.ClassTree; @@ -1013,10 +1014,12 @@ protected List splitAssignments(Node node) { /** * Collects the variables that a tree assigns: the left-hand sides of its assignments and compound - * assignments, and the operands of its increments and decrements. It does not descend into lambda - * bodies, method bodies, or named class declarations, which do not execute when the tree is - * evaluated. It does descend into the initializer blocks and field initializers of an anonymous - * class body, which execute when the enclosing {@code new} expression is evaluated. + * assignments, and the operands of its increments and decrements. It does not descend into + * annotations, lambda bodies, method bodies, or named class declarations, which do not execute + * when the tree is evaluated. (Javac represents an annotation argument as an assignment, as in + * {@code @IntVal(value = {0, 1})}, but it does not assign a variable.) It does descend into the + * initializer blocks and field initializers of an anonymous class body, which execute when the + * enclosing {@code new} expression is evaluated. */ private static class AssignmentTargetScanner extends TreeScanner> { @@ -1058,6 +1061,11 @@ public Void visitUnary(UnaryTree tree, List targets) { return super.visitUnary(tree, targets); } + @Override + public Void visitAnnotation(AnnotationTree tree, List targets) { + return null; + } + @Override public Void visitLambdaExpression(LambdaExpressionTree tree, List targets) { return null; diff --git a/framework/tests/value/AssignmentInComparison.java b/framework/tests/value/AssignmentInComparison.java index d4fc457fda62..6dc2bb6efb46 100644 --- a/framework/tests/value/AssignmentInComparison.java +++ b/framework/tests/value/AssignmentInComparison.java @@ -36,4 +36,11 @@ static void arrayTargetSameArrayType(int[] a, int[] b, int[] idx) { @IntVal(3) int y = a[idx[0]]; } } + + static void annotationArgumentInRhs(int[] a, int[] b) { + // The annotation argument `{0, 1}` is not an assignment to a variable. + if ((a = new @IntVal({0, 1}) int[] {0, 1}) != b) { + @IntVal({0, 1}) int x = a[0]; + } + } } From bc5f20981e7e4b13eb7b4f55479b8bbd256b97aa Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Wed, 11 Nov 2026 17:36:08 -0800 Subject: [PATCH 12/73] Strengthen the regression tests for annotation arguments --- checker/tests/nullness/AssignmentInComparison.java | 7 ++++--- framework/tests/value/AssignmentInComparison.java | 5 +++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/checker/tests/nullness/AssignmentInComparison.java b/checker/tests/nullness/AssignmentInComparison.java index 11ffa415b9ff..a9d43483cde2 100644 --- a/checker/tests/nullness/AssignmentInComparison.java +++ b/checker/tests/nullness/AssignmentInComparison.java @@ -266,10 +266,11 @@ static void arrayTargetTypeVariable(@Nullable T[] ts, @Nullable String[][] s } } - static void annotationArgumentInRhs(@Nullable Object o, Map m) { + static void annotationArgumentInRhs( + @Nullable Object o, @Nullable Object p, Map m) { // The annotation argument `"m"` is not an assignment to a variable. - if ((o = new ArrayList<@KeyFor("m") String>()) != null) { - o.toString(); + if ((o = new ArrayList<@KeyFor("m") String>()) == p) { + p.toString(); } } } diff --git a/framework/tests/value/AssignmentInComparison.java b/framework/tests/value/AssignmentInComparison.java index 6dc2bb6efb46..8af22cd94a60 100644 --- a/framework/tests/value/AssignmentInComparison.java +++ b/framework/tests/value/AssignmentInComparison.java @@ -1,3 +1,4 @@ +import org.checkerframework.common.value.qual.ArrayLen; import org.checkerframework.common.value.qual.IntVal; // A comparison of an assignment refines only the sides that have the assigned value afterward. @@ -39,8 +40,8 @@ static void arrayTargetSameArrayType(int[] a, int[] b, int[] idx) { static void annotationArgumentInRhs(int[] a, int[] b) { // The annotation argument `{0, 1}` is not an assignment to a variable. - if ((a = new @IntVal({0, 1}) int[] {0, 1}) != b) { - @IntVal({0, 1}) int x = a[0]; + if ((a = new @IntVal({0, 1}) int[] {0, 1}) == b) { + int @ArrayLen(2) [] x = b; } } } From 9970220d0f07513b1eb7705fd05c38b36ff954ad Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Wed, 11 Nov 2026 22:42:21 -0800 Subject: [PATCH 13/73] splitAssignments: account for evaluation order, method calls, and the other operand - Omit a side that the right operand of the comparison can change, as in `n.next == (n = o)`. - Treat a method call or object creation that is not side-effect-free as a write to any field or array element; this covers lambda bodies and anonymous class bodies, which are no longer scanned. - Consider only the writes that are evaluated after a side, so `b[i]` in `a[i = 0] = b[i]` is kept. - Use the store's `canAlias` (now comparing erasures, which is sound for differently-parameterized generic types) and the new `CFAbstractStore.isSideEffectFree`. - Handle parentheses in `JavaExpression.fromTree`. - Cache the result per node for each control flow graph. --- .../nullness/AssignmentInComparison.java | 88 +++ .../dataflow/expression/JavaExpression.java | 4 + .../framework/flow/CFAbstractAnalysis.java | 12 + .../framework/flow/CFAbstractStore.java | 29 +- .../framework/flow/CFAbstractTransfer.java | 514 ++++++++++++------ .../tests/value/AssignmentInComparison.java | 16 + 6 files changed, 494 insertions(+), 169 deletions(-) diff --git a/checker/tests/nullness/AssignmentInComparison.java b/checker/tests/nullness/AssignmentInComparison.java index a9d43483cde2..3d3f4c4cf5e4 100644 --- a/checker/tests/nullness/AssignmentInComparison.java +++ b/checker/tests/nullness/AssignmentInComparison.java @@ -1,6 +1,8 @@ import java.util.ArrayList; import java.util.Map; +import java.util.function.Supplier; import org.checkerframework.checker.nullness.qual.KeyFor; +import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.dataflow.qual.Pure; @@ -13,6 +15,10 @@ public class AssignmentInComparison { static @Nullable AssignmentInComparison global; + @MonotonicNonNull AssignmentInComparison mono; + + static @MonotonicNonNull AssignmentInComparison monoGlobal; + @Pure @Nullable AssignmentInComparison getNext() { return next; @@ -47,6 +53,22 @@ static void parenthesizedLocalTarget(@Nullable AssignmentInComparison n) { } } + static void otherOperandReassignsReceiver(AssignmentInComparison n, AssignmentInComparison o) { + if (n.next == (n = o)) { + // The left operand is the `next` field of the old `n`, but `n.next` is now `o.next`. + // :: error: [dereference.of.nullable] + n.next.toString(); + } + } + + static void assignmentInLeftOperand( + @Nullable AssignmentInComparison n, AssignmentInComparison o) { + if ((n = o) == n.next) { + // The right operand is evaluated after the assignment. + n.next.toString(); + } + } + static void localTargetFieldRhs(@Nullable AssignmentInComparison m, AssignmentInComparison n) { if ((m = n.next) != null) { m.toString(); @@ -153,6 +175,65 @@ static void anonymousClassFieldInitializerReassignsReceiver(AssignmentInComparis } } + static void anonymousClassInitializerCallsMethod(AssignmentInComparison replacement) { + if (global == null) { + return; + } + if ((global.next = + id( + new AssignmentInComparison() { + { + helper(replacement); + } + + static void helper(AssignmentInComparison r) { + global = r; + } + })) + != null) { + // After the assignment, `global.next` is a field of a different object. + // :: error: [dereference.of.nullable] + global.next.toString(); + } + } + + @Nullable AssignmentInComparison advance(AssignmentInComparison o) { + mono = new AssignmentInComparison(); + return o; + } + + void methodCallReassignsReceiver(AssignmentInComparison o) { + if (mono == null) { + return; + } + if ((mono.next = advance(o)) != null) { + // After the assignment, `mono.next` is a field of a different object. + // :: error: [dereference.of.nullable] + mono.next.toString(); + } + } + + static @Nullable T call(Supplier s) { + return s.get(); + } + + static void lambdaReassignsReceiver(AssignmentInComparison other, AssignmentInComparison o) { + if (monoGlobal == null) { + return; + } + if ((monoGlobal.next = + call( + () -> { + monoGlobal = other; + return o; + })) + != null) { + // After the assignment, `monoGlobal.next` is a field of a different object. + // :: error: [dereference.of.nullable] + monoGlobal.next.toString(); + } + } + void chainOfFieldTargets(@Nullable AssignmentInComparison o) { if ((this.next = this.other = o) != null) { this.next.toString(); @@ -243,6 +324,13 @@ static void arrayTargetWithAssignmentInIndex(@Nullable Object[] a, int i, @Nulla } } + static void assignmentInTargetIndexBeforeRhs(@Nullable Object[] a, @Nullable Object[] b, int i) { + if ((a[i = 0] = b[i]) != null) { + // `b[i]` is evaluated after `i = 0`, so it has the assigned value. + b[i].toString(); + } + } + static void fieldTargetWithAssignmentInReceiver( AssignmentInComparison n, AssignmentInComparison m, @Nullable AssignmentInComparison o) { if (((n = m).next = o) != null) { diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java b/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java index 0d614130838f..f694214b480c 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java @@ -10,6 +10,7 @@ import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewArrayTree; import com.sun.source.tree.NewClassTree; +import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.Tree; import com.sun.source.tree.UnaryTree; import com.sun.source.tree.VariableTree; @@ -641,6 +642,9 @@ public static JavaExpression fromTree(ExpressionTree tree) { result = fromVariableElement(typeOfId, (VariableElement) ele, identifierTree); } } + case PARENTHESIZED -> { + return fromTree(((ParenthesizedTree) tree).getExpression()); + } case UNARY_PLUS -> { return fromTree(((UnaryTree) tree).getExpression()); } diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java index 3c9e84dd2db7..c433bd34410a 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java @@ -114,6 +114,17 @@ public record FieldInitialValue>( private final IdentityHashMap> sideEffectsOnlyExpressionsCache = new IdentityHashMap<>(); + /** + * Cache for {@link CFAbstractTransfer#splitAssignments}, whose result depends only on its + * argument and on the trees around the argument's tree, but which would otherwise be recomputed + * once per dataflow iteration per comparison. + * + *

The keys are nodes of a single control flow graph, so {@link #performAnalysis} clears this. + * This is an {@link IdentityHashMap} because the result depends on the trees around the node, but + * {@link Node#equals} can be true for nodes that represent different trees. + */ + final IdentityHashMap> splitAssignmentsCache = new IdentityHashMap<>(); + /** * Cache for {@link StringToJavaExpression#atMethodDecl}, as called by {@link * #computeSideEffectsOnlyExpressions}. Parsing an expression in the scope of the method that @@ -193,6 +204,7 @@ public void performAnalysis(ControlFlowGraph cfg, List> fie this.fieldValues.addAll(fieldValues); // The cache's keys are nodes of the control flow graph that was analyzed previously. sideEffectsOnlyExpressionsCache.clear(); + splitAssignmentsCache.clear(); super.performAnalysis(cfg); } diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java index acd80c3cf263..4457f7ffd409 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java @@ -206,6 +206,21 @@ public void initializeThisValue(AnnotationMirror a, TypeMirror underlyingType) { /* Handling of fields */ /* --------------------------------------------------------- */ + /** + * Returns true if a call to the given method or constructor does not change any field or array + * element, according to the method's annotations (such as {@link + * org.checkerframework.dataflow.qual.SideEffectFree}) and the command-line options {@code + * -AassumeSideEffectFree}, {@code -AassumePure}, and {@code -AassumePureGetters}. + * + * @param method a method or constructor + * @return true if a call to {@code method} does not change any field or array element + */ + public boolean isSideEffectFree(ExecutableElement method) { + return assumeSideEffectFree + || (assumePureGetters && ElementUtils.isGetter(method)) + || analysis.atypeFactory.isSideEffectFree(method); + } + /** * Remove any information that might not be valid any more after a method call, and add * information guaranteed by the method. @@ -236,11 +251,7 @@ public void updateForMethodCall(MethodInvocationNode methodInvocationNode, @Null GenericAnnotatedTypeFactory atypeFactory = analysis.atypeFactory; // Case 1: The method is side-effect-free. - boolean hasSideEffect = - !(assumeSideEffectFree - || (assumePureGetters && ElementUtils.isGetter(method)) - || atypeFactory.isSideEffectFree(method)); - if (hasSideEffect) { + if (!isSideEffectFree(method)) { boolean sideEffectsUnrefineAliases = atypeFactory.sideEffectsUnrefineAliases; Node receiver = methodInvocationNode.getTarget().getReceiver(); @@ -1356,12 +1367,16 @@ protected void removeConflicting(LocalVariable var) { /** * Can the objects {@code a} and {@code b} be aliases? Returns a conservative answer (i.e., * returns {@code true} if not enough information is available to determine aliasing). + * + *

This compares the erasures of the types, because two parameterizations of a generic type can + * denote the same object even if neither is a subtype of the other. For example, a {@code + * Box} is both a {@code Box} and a {@code Box}. */ @Override public boolean canAlias(JavaExpression a, JavaExpression b) { - TypeMirror tb = b.getType(); - TypeMirror ta = a.getType(); Types types = analysis.getTypes(); + TypeMirror ta = types.erasure(a.getType()); + TypeMirror tb = types.erasure(b.getType()); return types.isSubtype(ta, tb) || types.isSubtype(tb, ta); } diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 0155fdc46b9b..d96053a669e6 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -3,7 +3,7 @@ import com.sun.source.tree.AnnotatedTypeTree; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.AssignmentTree; -import com.sun.source.tree.BlockTree; +import com.sun.source.tree.BinaryTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompoundAssignmentTree; import com.sun.source.tree.ExpressionTree; @@ -11,6 +11,7 @@ import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewClassTree; +import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.Tree; import com.sun.source.tree.UnaryTree; import com.sun.source.tree.VariableTree; @@ -30,9 +31,9 @@ import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; -import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import org.checkerframework.checker.interning.qual.InternedDistinct; +import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.PolyNull; import org.checkerframework.common.aliasing.AliasingAnnotatedTypeFactory; @@ -144,6 +145,9 @@ public abstract class CFAbstractTransfer< /** Indicates that the whole-program inference is on. */ private final boolean infer; + /** An empty store, which {@link #getEmptyStore} creates on first use. */ + private @MonotonicNonNull S emptyStore; + /** * Create a CFAbstractTransfer. * @@ -924,9 +928,9 @@ public TransferResult visitNotEqual(NotEqualNode n, TransferInput p) * *

Note that when overriding this method, when a new type is inserted into the store, {@link * #splitAssignments} should be called, and the new type should be inserted into the store for - * each of the resulting nodes. The result of {@link #splitAssignments} omits each side of an - * assignment that might not have the assignment's value; do not insert the new type for such a - * side. + * each of the resulting nodes. The result of {@link #splitAssignments} omits each node that might + * not have the value of {@code secondNode} when the comparison completes; do not insert the new + * type for such a node. * * @param firstNode the node that might be more precise * @param secondNode the node whose type to possibly refine @@ -973,227 +977,413 @@ protected TransferResult strengthenAnnotationOfEqualTo( /** * Takes a node, and either returns the node itself again (as a singleton list), or if the node is - * an assignment node, returns the sides of the assignment that have the assignment's value after - * it executes. The sides are the lhs and rhs, where splitAssignments is applied recursively to - * the rhs -- that is, it is possible that the rhs does not appear in the result, but rather its - * lhs and rhs do. + * an assignment node, returns the sides of the assignment. The sides are the lhs and rhs, where + * splitAssignments is applied recursively to the rhs -- that is, it is possible that the rhs does + * not appear in the result, but rather its lhs and rhs do. + * + *

{@code node} is an operand of a comparison, such as {@code ==} or {@code <}, and the caller + * refines each node in the result according to the outcome of the comparison. Therefore, the + * result omits each node that a store can hold a value for (see {@link + * CFAbstractStore#canInsertJavaExpression}) and that, when the comparison completes, might have a + * different value than {@code node} had when it was evaluated. A node's value can change when + * code that is evaluated after the node writes a variable, field, or array element that the node + * reads. That code is the rest of the assignment, and the right operand of the comparison if + * {@code node} is its left operand. For example: + * + *

* - *

The result omits each side that a store can hold a value for (see {@link - * CFAbstractStore#canInsertJavaExpression}) and that, after the assignment, might have a - * different value than the assignment. For example, the result for {@code n = n.next} is just - * {@code n}, because after the assignment {@code n.next} is a field of a different object. The - * same holds for an assignment, compound assignment, increment, or decrement nested anywhere - * within {@code node}: the result for {@code n.next = (n = o).other} omits {@code n.next}. + * A method call or object creation might write any field or array element, unless the method or + * constructor is side-effect-free (see {@link CFAbstractStore#isSideEffectFree}). * *

A node that is not an assignment is returned even if it contains an assignment, as in {@code * x + (x = 1)}. {@link JavaExpression#fromNode} converts such a node to an expression that * contains {@link Unknown}, which no store holds a value for. * + *

Clients must not modify the result, which is cached. + * * @param node possibly an assignment node * @return a list containing the right- and left-hand sides in the given assignment node that have - * the value of the assignment after it executes; it contains just the node itself if it is - * not an assignment + * the value of the assignment when the comparison completes; if {@code node} is not an + * assignment, a list containing just {@code node}, or an empty list if {@code node} might + * have a different value when the comparison completes */ - @SideEffectFree protected List splitAssignments(Node node) { - if (!(node instanceof AssignmentNode assignment)) { - return Collections.singletonList(node); + List result = analysis.splitAssignmentsCache.get(node); + if (result == null) { + result = Collections.unmodifiableList(computeSplitAssignments(node)); + analysis.splitAssignmentsCache.put(node, result); + } + return result; + } + + /** + * Returns the result of {@link #splitAssignments}, without using the cache. + * + * @param node possibly an assignment node + * @return the result of {@link #splitAssignments} for {@code node} + */ + private List computeSplitAssignments(Node node) { + Writes laterWrites = new Writes(); + ExpressionTree laterOperand = laterOperand(node); + if (laterOperand != null) { + laterWrites.scan(laterOperand, null); + } + + if (!(node instanceof AssignmentNode)) { + return mayBeChanged(node, new Writes(), laterWrites) + ? Collections.emptyList() + : Collections.singletonList(node); + } + + List chain = new ArrayList<>(); + Node rhs = node; + while (rhs instanceof AssignmentNode a) { + chain.add(a); + rhs = a.getExpression(); + } + + // Javac evaluates the receivers and indices of the targets from left to right, then the rhs, + // and then it stores into the targets from right to left. Visit the sides in reverse order of + // evaluation, so that `writes` contains the writes that happen after the side is evaluated. + Writes writes = new Writes(); + for (AssignmentNode a : chain) { + writes.add(JavaExpression.fromNode(a.getTarget())); + } + ExpressionTree rhsTree = rhsTree(chain.get(chain.size() - 1)); + if (rhsTree != null) { + writes.scan(rhsTree, null); + } + Node[] sides = new Node[chain.size() + 1]; + int numKept = 0; + if (!mayBeChanged(rhs, writes, laterWrites)) { + sides[chain.size()] = rhs; + numKept++; + } + for (int i = chain.size() - 1; i >= 0; i--) { + Node target = chain.get(i).getTarget(); + writes.scan(target.getTree(), null); + if (!mayBeChanged(target, writes, laterWrites)) { + sides[i] = target; + numKept++; + } } - List targets = new ArrayList<>(); - new AssignmentTargetScanner().scan(assignment.getTree(), targets); - List result = new ArrayList<>(); - while (node instanceof AssignmentNode a) { - result.add(a.getTarget()); - node = a.getExpression(); + List result = new ArrayList<>(numKept); + for (Node side : sides) { + if (side != null) { + result.add(side); + } } - result.add(node); - result.removeIf(part -> mayBeChangedByAssignment(JavaExpression.fromNode(part), targets)); return result; } /** - * Collects the variables that a tree assigns: the left-hand sides of its assignments and compound - * assignments, and the operands of its increments and decrements. It does not descend into - * annotations, lambda bodies, method bodies, or named class declarations, which do not execute - * when the tree is evaluated. (Javac represents an annotation argument as an assignment, as in - * {@code @IntVal(value = {0, 1})}, but it does not assign a variable.) It does descend into the - * initializer blocks and field initializers of an anonymous class body, which execute when the - * enclosing {@code new} expression is evaluated. + * Returns true if a store can hold a value for the given side of an assignment, and the side + * might be changed by the given writes. + * + * @param side a side of an assignment, or a node that is not an assignment + * @param writes the writes that happen after {@code side} is evaluated and before the assignment + * stores into its targets; they do not change the location that {@code side} denotes, because + * the assignment stores the value of {@code side} into that location or reads it afterward + * @param laterWrites the writes that happen after the assignment completes + * @return true if a store can hold a value for {@code side} and the writes might change its value + */ + private boolean mayBeChanged(Node side, Writes writes, Writes laterWrites) { + JavaExpression expr = JavaExpression.fromNode(side); + return CFAbstractStore.canInsertJavaExpression(expr) + && (writes.mayChange(expr, true) || laterWrites.mayChange(expr, false)); + } + + /** + * Returns the tree for the value that the given assignment node assigns: the rhs of an assignment + * or compound assignment, or the initializer of a variable declaration. Returns null for an + * increment or decrement. + * + * @param assignment an assignment node + * @return the tree for the value that {@code assignment} assigns, or null if there is none + */ + private static @Nullable ExpressionTree rhsTree(AssignmentNode assignment) { + Tree tree = assignment.getTree(); + if (tree instanceof AssignmentTree assignmentTree) { + return assignmentTree.getExpression(); + } else if (tree instanceof CompoundAssignmentTree compoundAssignmentTree) { + return compoundAssignmentTree.getExpression(); + } else if (tree instanceof VariableTree variableTree) { + return variableTree.getInitializer(); + } else { + return null; + } + } + + /** + * Returns the right operand of the binary operation, such as a comparison, whose left operand is + * {@code node}, ignoring parentheses. Javac evaluates the right operand after {@code node} and + * before the binary operation. + * + * @param node a node + * @return the right operand of the binary operation whose left operand is {@code node}, or null + * if {@code node} is not the left operand of a binary operation + */ + private @Nullable ExpressionTree laterOperand(Node node) { + TreePath path = sourcePath(node); + if (path == null) { + return null; + } + Tree tree = path.getLeaf(); + TreePath parentPath = path.getParentPath(); + while (parentPath != null && parentPath.getLeaf() instanceof ParenthesizedTree) { + tree = parentPath.getLeaf(); + parentPath = parentPath.getParentPath(); + } + if (parentPath != null + && parentPath.getLeaf() instanceof BinaryTree binaryTree + && binaryTree.getLeftOperand() == tree) { + return binaryTree.getRightOperand(); + } + return null; + } + + /** + * Returns the path to the tree of the given node. If the node's tree is artificial, as for an + * unboxing conversion, returns the path to the tree of the node's first operand that has one, + * recursively. + * + * @param node a node + * @return the path to the source tree that {@code node} represents, or null if there is none */ - private static class AssignmentTargetScanner extends TreeScanner> { + private @Nullable TreePath sourcePath(Node node) { + Tree tree = node.getTree(); + if (tree != null) { + TreePath path = analysis.atypeFactory.getPath(tree); + if (path != null) { + return path; + } + } + for (Node operand : node.getOperands()) { + TreePath path = sourcePath(operand); + if (path != null) { + return path; + } + } + return null; + } - /** Creates an AssignmentTargetScanner. */ - AssignmentTargetScanner() {} + /** + * Returns an empty store, which {@link Writes} uses for the store's aliasing and purity rules. + * + * @return an empty store + */ + private S getEmptyStore() { + if (emptyStore == null) { + emptyStore = analysis.createEmptyStore(sequentialSemantics); + } + return emptyStore; + } + + /** + * The locations that the evaluation of some code might write. {@link #add} adds a write to a + * given location, and {@link #scan} adds the writes that evaluating a tree might perform: its + * assignments, compound assignments, increments, decrements, method calls, and object creations. + * A method call or object creation might write any field or array element, unless the method or + * constructor is side-effect-free. + * + *

{@link #scan} does not descend into lambda bodies or class bodies, which do not execute when + * the tree is evaluated. A method call or object creation that might execute them is a write to + * any field or array element, and they cannot assign a local variable that is visible outside + * them. {@link #scan} does not descend into annotations either: javac represents an annotation + * argument as an assignment, as in {@code @IntVal(value = {0, 1})}, but it does not assign a + * variable. + * + *

{@link #mayChange} uses the store's rules for aliasing and purity (see {@link + * CFAbstractStore#canAlias} and {@link CFAbstractStore#isSideEffectFree}). + */ + private final class Writes extends TreeScanner { + + /** The local variables that might be written. */ + private final List locals = new ArrayList<>(); + + /** The fields that might be written. */ + private final List fields = new ArrayList<>(); + + /** The array elements that might be written. */ + private final List arrayElements = new ArrayList<>(); + + /** True if any non-final field and any array element might be written. */ + private boolean anyHeapLocation = false; + + /** Creates an empty set of writes. */ + Writes() {} /** - * Returns the JavaExpression for the given assignment target. Javac retains parentheses around - * a target, as in {@code (n) = o}, but {@link JavaExpression#fromTree} does not handle them, so - * this method removes them. + * Adds a write to the given location. * - * @param target the variable that an assignment, compound assignment, increment, or decrement - * assigns - * @return the JavaExpression for {@code target} + * @param target a location that is written */ - private static JavaExpression targetExpression(ExpressionTree target) { - return JavaExpression.fromTree(TreeUtils.withoutParens(target)); + void add(JavaExpression target) { + if (target instanceof LocalVariable localVariable) { + locals.add(localVariable); + } else if (target instanceof FieldAccess fieldAccess) { + fields.add(fieldAccess); + } else if (target instanceof ArrayAccess arrayAccess) { + arrayElements.add(arrayAccess); + } else { + // Every local variable converts to a LocalVariable, so `target` is a field or an array + // element. + anyHeapLocation = true; + } } @Override - public Void visitAssignment(AssignmentTree tree, List targets) { - targets.add(targetExpression(tree.getVariable())); - return super.visitAssignment(tree, targets); + public Void visitAssignment(AssignmentTree tree, Void p) { + add(JavaExpression.fromTree(tree.getVariable())); + return super.visitAssignment(tree, p); } @Override - public Void visitCompoundAssignment(CompoundAssignmentTree tree, List targets) { - targets.add(targetExpression(tree.getVariable())); - return super.visitCompoundAssignment(tree, targets); + public Void visitCompoundAssignment(CompoundAssignmentTree tree, Void p) { + add(JavaExpression.fromTree(tree.getVariable())); + return super.visitCompoundAssignment(tree, p); } @Override - public Void visitUnary(UnaryTree tree, List targets) { + public Void visitUnary(UnaryTree tree, Void p) { switch (tree.getKind()) { case PREFIX_INCREMENT, PREFIX_DECREMENT, POSTFIX_INCREMENT, POSTFIX_DECREMENT -> - targets.add(targetExpression(tree.getExpression())); + add(JavaExpression.fromTree(tree.getExpression())); default -> {} } - return super.visitUnary(tree, targets); + return super.visitUnary(tree, p); + } + + @Override + public Void visitMethodInvocation(MethodInvocationTree tree, Void p) { + if (!getEmptyStore().isSideEffectFree(TreeUtils.elementFromUse(tree))) { + anyHeapLocation = true; + } + return super.visitMethodInvocation(tree, p); + } + + @Override + public Void visitNewClass(NewClassTree tree, Void p) { + // For an anonymous class, this is the constructor of the anonymous class, which executes its + // initializers. + if (!getEmptyStore().isSideEffectFree(TreeUtils.elementFromUse(tree))) { + anyHeapLocation = true; + } + return super.visitNewClass(tree, p); } @Override - public Void visitAnnotation(AnnotationTree tree, List targets) { + public Void visitAnnotation(AnnotationTree tree, Void p) { return null; } @Override - public Void visitLambdaExpression(LambdaExpressionTree tree, List targets) { + public Void visitLambdaExpression(LambdaExpressionTree tree, Void p) { return null; } @Override - public Void visitClass(ClassTree tree, List targets) { - if (!tree.getSimpleName().isEmpty()) { - // A named (local) class declaration does not execute. - return null; - } - // An anonymous class body: its initializers execute when the `new` expression is evaluated. - for (Tree member : tree.getMembers()) { - if (member instanceof BlockTree block) { - scan(block, targets); - } else if (member instanceof VariableTree field) { - scan(field.getInitializer(), targets); - } - // Skip methods and nested class declarations. - } + public Void visitClass(ClassTree tree, Void p) { return null; } - } - /** - * Returns true if an assignment to one of the given targets might make {@code expr} evaluate to a - * different value than the value of the assignment whose side {@code expr} is. Returns false if - * no store can hold a value for {@code expr}. - * - * @param expr a side of an assignment - * @param targets the variables that an expression that contains {@code expr} assigns - * @return true if an assignment to one of {@code targets} might change the value of {@code expr} - */ - @Pure - private static boolean mayBeChangedByAssignment( - JavaExpression expr, List targets) { - if (!CFAbstractStore.canInsertJavaExpression(expr)) { - return false; + /** + * Returns true if these writes might change the value of {@code expr}. + * + *

A write to a local variable changes only expressions that contain the variable. A write to + * a field changes only accesses of the same field, and method calls. A write to an array + * element changes only accesses of arrays that might alias the written array, and method calls. + * + * @param expr an expression + * @param ignoreOwnLocation true if a write to the location that {@code expr} denotes (if it is + * a variable, field access, or array access) does not matter, but a write that changes + * which location {@code expr} denotes (that is, a write to its receiver or index) does + * @return true if these writes might change the value of {@code expr} + */ + boolean mayChange(JavaExpression expr, boolean ignoreOwnLocation) { + if (expr instanceof LocalVariable) { + return !ignoreOwnLocation && locals.contains(expr); + } else if (expr instanceof FieldAccess fa) { + return (!ignoreOwnLocation && mayWriteField(fa)) || mayChange(fa.getReceiver(), false); + } else if (expr instanceof ArrayAccess aa) { + return (!ignoreOwnLocation && mayWriteArrayElement(aa)) + || mayChange(aa.getArray(), false) + || mayChange(aa.getIndex(), false); + } else if (expr instanceof MethodCall mc) { + if (anyHeapLocation + || !fields.isEmpty() + || !arrayElements.isEmpty() + || mayChange(mc.getReceiver(), false)) { + return true; + } + for (JavaExpression arg : mc.getArguments()) { + if (mayChange(arg, false)) { + return true; + } + } + return false; + } else if (expr instanceof UnaryOperation uo) { + return mayChange(uo.getOperand(), false); + } else if (expr instanceof BinaryOperation bo) { + return mayChange(bo.getLeft(), false) || mayChange(bo.getRight(), false); + } else { + // An Unknown or ArrayCreation might be changed. + return !(expr instanceof ClassName + || expr instanceof FormalParameter + || expr instanceof SuperReference + || expr instanceof ThisReference + || expr instanceof ValueLiteral); + } } - for (JavaExpression target : targets) { - if (assignmentMayChange(target, expr, true)) { + + /** + * Returns true if these writes might write the field that {@code fa} denotes. + * + * @param fa a field access + * @return true if these writes might write the field that {@code fa} denotes + */ + private boolean mayWriteField(FieldAccess fa) { + if (anyHeapLocation && !fa.isFinal()) { return true; } + S store = getEmptyStore(); + for (FieldAccess field : fields) { + if (field.getField().equals(fa.getField()) + && store.canAlias(field.getReceiver(), fa.getReceiver())) { + return true; + } + } + return false; } - return false; - } - /** - * Returns true if an assignment to {@code target} might change the value of {@code expr}. - * - *

An assignment to a local variable changes only expressions that contain the variable. An - * assignment to a field changes only accesses of the same field, and method calls. An assignment - * to an array element changes only accesses of arrays that might alias the target's array, and - * method calls. - * - *

If {@code ignoreOwnLocation} is true and {@code expr} is a variable, field access, or array - * access, then an assignment to the location that {@code expr} denotes does not matter: an - * assignment in the same chain as {@code expr} stores the same value, and a nested assignment - * executes before the location is written or read. Only an assignment that changes which location - * {@code expr} denotes (that is, its receiver or index) matters. - * - * @param target the left-hand side of an assignment - * @param expr an expression - * @param ignoreOwnLocation if true, ignore an assignment to the location that {@code expr} - * denotes - * @return true if an assignment to {@code target} might change the value of {@code expr} - */ - @Pure - private static boolean assignmentMayChange( - JavaExpression target, JavaExpression expr, boolean ignoreOwnLocation) { - if (target instanceof Unknown) { - // The target is not understood, so it might be any location. - return true; - } - if (expr instanceof LocalVariable) { - return !ignoreOwnLocation && expr.syntacticEquals(target); - } else if (expr instanceof FieldAccess fa) { - return (!ignoreOwnLocation - && target instanceof FieldAccess targetFa - && targetFa.getField().equals(fa.getField())) - || assignmentMayChange(target, fa.getReceiver(), false); - } else if (expr instanceof ArrayAccess aa) { - return (!ignoreOwnLocation - && target instanceof ArrayAccess targetAa - && arraysMayAlias(targetAa, aa)) - || assignmentMayChange(target, aa.getArray(), false) - || assignmentMayChange(target, aa.getIndex(), false); - } else if (expr instanceof MethodCall mc) { - if (!(target instanceof LocalVariable) - || assignmentMayChange(target, mc.getReceiver(), false)) { + /** + * Returns true if these writes might write the array element that {@code aa} denotes. + * + * @param aa an array access + * @return true if these writes might write the array element that {@code aa} denotes + */ + private boolean mayWriteArrayElement(ArrayAccess aa) { + if (anyHeapLocation) { return true; } - for (JavaExpression arg : mc.getArguments()) { - if (assignmentMayChange(target, arg, false)) { + S store = getEmptyStore(); + for (ArrayAccess arrayElement : arrayElements) { + if (store.canAlias(arrayElement.getArray(), aa.getArray())) { return true; } } return false; - } else if (expr instanceof UnaryOperation uo) { - return assignmentMayChange(target, uo.getOperand(), false); - } else if (expr instanceof BinaryOperation bo) { - return assignmentMayChange(target, bo.getLeft(), false) - || assignmentMayChange(target, bo.getRight(), false); - } else { - // An Unknown or ArrayCreation might be changed. - return !(expr instanceof ClassName - || expr instanceof FormalParameter - || expr instanceof SuperReference - || expr instanceof ThisReference - || expr instanceof ValueLiteral); } } - /** - * Returns true if the arrays of the given array accesses might be the same array. They cannot be - * if their component types differ and at least one of the component types is primitive. - * - * @param a1 an array access - * @param a2 an array access - * @return true if the arrays of {@code a1} and {@code a2} might be the same array - */ - @Pure - private static boolean arraysMayAlias(ArrayAccess a1, ArrayAccess a2) { - TypeKind kind1 = a1.getType().getKind(); - TypeKind kind2 = a2.getType().getKind(); - return kind1 == kind2 || !(kind1.isPrimitive() || kind2.isPrimitive()); - } - @Override public TransferResult visitAssignment(AssignmentNode n, TransferInput in) { Node lhs = n.getTarget(); diff --git a/framework/tests/value/AssignmentInComparison.java b/framework/tests/value/AssignmentInComparison.java index 8af22cd94a60..2ea3d0bcd5bc 100644 --- a/framework/tests/value/AssignmentInComparison.java +++ b/framework/tests/value/AssignmentInComparison.java @@ -20,6 +20,22 @@ static void indexReassigned(int i, int[] a) { } } + static void otherOperandReassignsIndex(int[] a, int i) { + if (a[i] == (i = 5)) { + @IntVal(5) int x = i; + // The left operand is an element of `a` at the old index `i`. + // :: error: [assignment] + @IntVal(5) int y = a[i]; + } + } + + static void assignmentInTargetIndexBeforeRhs(int[] a, int[] b, int i) { + if ((a[i = 0] = b[i]) == 3) { + // `b[i]` is evaluated after `i = 0`, so it has the assigned value. + @IntVal(3) int x = b[i]; + } + } + static void arrayTargetOtherArrayType(int[] a, long[] b, int[] idx) { // An assignment to an element of `b` does not change `idx[0]`, because `b` and `idx` cannot // alias. From 1b027a1efb0ad40af9f56f6ab4c9a26d9be0397e Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Thu, 12 Nov 2026 08:19:05 -0800 Subject: [PATCH 14/73] Suppress Interning Checker warning about reference equality of AST nodes --- .../org/checkerframework/framework/flow/CFAbstractTransfer.java | 1 + 1 file changed, 1 insertion(+) diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index d96053a669e6..12615538057d 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -1131,6 +1131,7 @@ private boolean mayBeChanged(Node side, Writes writes, Writes laterWrites) { * @return the right operand of the binary operation whose left operand is {@code node}, or null * if {@code node} is not the left operand of a binary operation */ + @SuppressWarnings("interning:not.interned") // reference equality of AST nodes private @Nullable ExpressionTree laterOperand(Node node) { TreePath path = sourcePath(node); if (path == null) { From db8868025ae542fcd1ceb1a5affee6407259db7f Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Thu, 12 Nov 2026 08:47:10 -0800 Subject: [PATCH 15/73] splitAssignments: account for all later writes in the comparison; fix canAlias for intersection bounds * canAlias compares every bound of a type variable or intersection type, not just the first bound that erasure keeps. * The Index Checker's comparison refinements go through splitAssignments. * splitAssignments considers the writes of all code that is evaluated after the node and before the enclosing comparison completes, including the enclosing expressions' own writes and implicit toString() calls. * splitAssignments finds those writes only when a side could be omitted. * isSideEffectFree and canAlias move to CFAbstractAnalysis, which removes the empty store that the transfer function used for them. * Writes mirrors the store's rule for checkers whose side effects unrefine aliases. --- .../checker/index/IndexAbstractTransfer.java | 15 + .../index/lowerbound/LowerBoundTransfer.java | 26 +- .../searchindex/SearchIndexTransfer.java | 3 +- .../index/upperbound/UpperBoundTransfer.java | 42 +-- .../tests/index/AssignmentInComparison.java | 24 ++ .../ArrayAliasingIntersectionBound.java | 32 ++ .../framework/flow/CFAbstractAnalysis.java | 94 ++++++ .../framework/flow/CFAbstractStore.java | 41 +-- .../framework/flow/CFAbstractTransfer.java | 295 +++++++++++++----- 9 files changed, 401 insertions(+), 171 deletions(-) create mode 100644 checker/tests/nullness/ArrayAliasingIntersectionBound.java diff --git a/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java index 5e1eda172976..9e6baafddb88 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java @@ -8,6 +8,7 @@ import org.checkerframework.dataflow.cfg.node.LessThanNode; import org.checkerframework.dataflow.cfg.node.LessThanOrEqualNode; import org.checkerframework.dataflow.cfg.node.Node; +import org.checkerframework.dataflow.expression.JavaExpression; import org.checkerframework.framework.flow.CFAnalysis; import org.checkerframework.framework.flow.CFStore; import org.checkerframework.framework.flow.CFTransfer; @@ -97,6 +98,20 @@ public TransferResult visitLessThan( return rfi.newResult; } + /** + * Inserts the given annotation into the store for each expression that has the value of the given + * node when the comparison that contains the node completes (see {@link #splitAssignments}). + * + * @param store the store to modify + * @param node a node in an operand of a comparison + * @param anno the annotation to insert for each expression that has the value of {@code node} + */ + protected void insertValueForComparedNode(CFStore store, Node node, AnnotationMirror anno) { + for (Node internal : splitAssignments(node)) { + store.insertValue(JavaExpression.fromNode(internal), anno); + } + } + protected abstract void refineGT( Node left, AnnotationMirror leftAnno, diff --git a/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java index a2a68f41964c..74acc06bb904 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java @@ -211,19 +211,11 @@ private void notEqualToValue( if (intLiteral == 0) { if (atypeFactory.areSameByClass(otherAnno, NonNegative.class)) { - List internals = splitAssignments(otherNode); - for (Node internal : internals) { - JavaExpression je = JavaExpression.fromNode(internal); - store.insertValue(je, POS); - } + insertValueForComparedNode(store, otherNode, POS); } } else if (intLiteral == -1) { if (atypeFactory.areSameByClass(otherAnno, GTENegativeOne.class)) { - List internals = splitAssignments(otherNode); - for (Node internal : internals) { - JavaExpression je = JavaExpression.fromNode(internal); - store.insertValue(je, NN); - } + insertValueForComparedNode(store, otherNode, NN); } } } @@ -275,7 +267,7 @@ private void notEqualsLessThan( if (atypeFactory .getLessThanAnnotatedTypeFactory() .isLessThanOrEqual(leftNode.getTree(), otherJe.toString())) { - store.insertValue(otherJe, POS); + insertValueForComparedNode(store, otherNode, POS); } } @@ -301,18 +293,16 @@ protected void refineGT( return; } - JavaExpression leftJe = JavaExpression.fromNode(left); - if (AnnotationUtils.areSame(rightAnno, GTEN1)) { - store.insertValue(leftJe, NN); + insertValueForComparedNode(store, left, NN); return; } if (AnnotationUtils.areSame(rightAnno, NN)) { - store.insertValue(leftJe, POS); + insertValueForComparedNode(store, left, POS); return; } if (AnnotationUtils.areSame(rightAnno, POS)) { - store.insertValue(leftJe, POS); + insertValueForComparedNode(store, left, POS); return; } } @@ -338,14 +328,12 @@ protected void refineGTE( return; } - JavaExpression leftJe = JavaExpression.fromNode(left); - AnnotationMirror newLBType = atypeFactory .getQualifierHierarchy() .greatestLowerBoundShallow(rightAnno, left.getType(), leftAnno, right.getType()); - store.insertValue(leftJe, newLBType); + insertValueForComparedNode(store, left, newLBType); } /** diff --git a/checker/src/main/java/org/checkerframework/checker/index/searchindex/SearchIndexTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/searchindex/SearchIndexTransfer.java index 7804370c67cd..268facad5a38 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/searchindex/SearchIndexTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/searchindex/SearchIndexTransfer.java @@ -8,7 +8,6 @@ import org.checkerframework.common.value.ValueCheckerUtils; import org.checkerframework.dataflow.analysis.TransferInput; import org.checkerframework.dataflow.cfg.node.Node; -import org.checkerframework.dataflow.expression.JavaExpression; import org.checkerframework.framework.flow.CFAnalysis; import org.checkerframework.framework.flow.CFStore; import org.checkerframework.framework.flow.CFValue; @@ -71,7 +70,7 @@ private void refineSearchIndexToNegativeIndexFor( AnnotationUtils.getElementValueArray( rightSIF, atypeFactory.searchIndexForValueElement, String.class); AnnotationMirror nif = atypeFactory.createNegativeIndexFor(arrays); - store.insertValue(JavaExpression.fromNode(right), nif); + insertValueForComparedNode(store, right, nif); } } } diff --git a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java index 0dce5c45a110..edb5b06997c7 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java @@ -233,8 +233,7 @@ private void propagateToMultiplicationOperand( } UBQualifier qual = getUBQualifier(node, in); UBQualifier newQual = qual.glb(typeOfMultiplication); - JavaExpression je = JavaExpression.fromNode(node); - store.insertValue(je, atypeFactory.convertUBQualifierToAnnotation(newQual)); + insertValueForComparedNode(store, node, atypeFactory.convertUBQualifierToAnnotation(newQual)); } } @@ -262,8 +261,8 @@ private void propagateToSubtractionOperands( UBQualifier newInfo = typeOfSubtraction.minusOffset(node.getRightOperand(), atypeFactory); UBQualifier newLeft = left.glb(newInfo); - JavaExpression leftJe = JavaExpression.fromNode(node.getLeftOperand()); - store.insertValue(leftJe, atypeFactory.convertUBQualifierToAnnotation(newLeft)); + insertValueForComparedNode( + store, node.getLeftOperand(), atypeFactory.convertUBQualifierToAnnotation(newLeft)); } /** @@ -293,8 +292,8 @@ private void propagateToAdditionOperand( } else if (atypeFactory.hasLowerBoundTypeByClass(other, NonNegative.class)) { newQual = newQual.glb(typeOfAddition); } - JavaExpression operandJe = JavaExpression.fromNode(operand); - store.insertValue(operandJe, atypeFactory.convertUBQualifierToAnnotation(newQual)); + insertValueForComparedNode( + store, operand, atypeFactory.convertUBQualifierToAnnotation(newQual)); } /** @@ -324,8 +323,8 @@ protected void refineGT( refineSubtrahendWithOffset(larger, smaller, true, in, store); - JavaExpression rightJe = JavaExpression.fromNode(smaller); - store.insertValue(rightJe, atypeFactory.convertUBQualifierToAnnotation(refinedRight)); + insertValueForComparedNode( + store, smaller, atypeFactory.convertUBQualifierToAnnotation(refinedRight)); } /** @@ -352,8 +351,8 @@ protected void refineGTE( refineSubtrahendWithOffset(left, right, false, in, store); - JavaExpression rightJe = JavaExpression.fromNode(right); - store.insertValue(rightJe, atypeFactory.convertUBQualifierToAnnotation(refinedRight)); + insertValueForComparedNode( + store, right, atypeFactory.convertUBQualifierToAnnotation(refinedRight)); } /** @@ -388,8 +387,8 @@ private void refineSubtrahendWithOffset( UBQualifier newQual = subtrahendQual.glb( minuendQual.plusOffset(offsetNode, atypeFactory).plusOffset(offsetAddOne ? 1 : 0)); - JavaExpression subtrahendJe = JavaExpression.fromNode(subtrahend); - store.insertValue(subtrahendJe, atypeFactory.convertUBQualifierToAnnotation(newQual)); + insertValueForComparedNode( + store, subtrahend, atypeFactory.convertUBQualifierToAnnotation(newQual)); } } @@ -430,17 +429,8 @@ private void refineEq( UBQualifier glb = rightQualifier.glb(leftQualifier); AnnotationMirror glbAnno = atypeFactory.convertUBQualifierToAnnotation(glb); - List internalsRight = splitAssignments(right); - for (Node internal : internalsRight) { - JavaExpression rightJe = JavaExpression.fromNode(internal); - store.insertValue(rightJe, glbAnno); - } - - List internalsLeft = splitAssignments(left); - for (Node internal : internalsLeft) { - JavaExpression leftJe = JavaExpression.fromNode(internal); - store.insertValue(leftJe, glbAnno); - } + insertValueForComparedNode(store, right, glbAnno); + insertValueForComparedNode(store, left, glbAnno); } /** @@ -495,10 +485,8 @@ private void refineNeqSequenceLength( UBQualifier newQualifier = UBQualifier.createUBQualifier(sequence, Integer.toString(lengthOffset)); otherQualifier = otherQualifier.glb(newQualifier); - for (Node internal : splitAssignments(otherNode)) { - JavaExpression leftJe = JavaExpression.fromNode(internal); - store.insertValue(leftJe, atypeFactory.convertUBQualifierToAnnotation(otherQualifier)); - } + insertValueForComparedNode( + store, otherNode, atypeFactory.convertUBQualifierToAnnotation(otherQualifier)); } } } diff --git a/checker/tests/index/AssignmentInComparison.java b/checker/tests/index/AssignmentInComparison.java index f65f3cccc57a..3436565b2c31 100644 --- a/checker/tests/index/AssignmentInComparison.java +++ b/checker/tests/index/AssignmentInComparison.java @@ -1,5 +1,6 @@ import org.checkerframework.checker.index.qual.NonNegative; import org.checkerframework.checker.index.qual.Positive; +import org.checkerframework.checker.index.qual.SameLen; import org.checkerframework.dataflow.qual.Pure; // A comparison of an assignment refines only the sides that have the assigned value afterward. @@ -7,6 +8,13 @@ public class AssignmentInComparison { @NonNegative int f; + int[] arr = new int[0]; + + int[] setArr(int[] c) { + arr = c; + return c; + } + @Pure @NonNegative int size() { return f; @@ -34,4 +42,20 @@ static void fieldTargetMethodCallRhs(AssignmentInComparison n) { @Positive int y = n.size(); } } + + static void otherOperandReassignsLeftOperand(@NonNegative int i) { + if (i > (i = 0)) { + // `i` is 0, not the value that was compared. + // :: error: [assignment] + @Positive int x = i; + } + } + + void otherOperandReassignsLengthReceiver(int[] b, int[] c) { + if ((this.arr = b).length == setArr(c).length) { + // `setArr` sets `this.arr` to `c`, which might not have the same length as `b`. + // :: error: [assignment] + int @SameLen("b") [] x = this.arr; + } + } } diff --git a/checker/tests/nullness/ArrayAliasingIntersectionBound.java b/checker/tests/nullness/ArrayAliasingIntersectionBound.java new file mode 100644 index 000000000000..eeb4d8d81236 --- /dev/null +++ b/checker/tests/nullness/ArrayAliasingIntersectionBound.java @@ -0,0 +1,32 @@ +import org.checkerframework.checker.nullness.qual.Nullable; + +// Arrays whose element types are a type variable and one of its bounds can be the same array. +public class ArrayAliasingIntersectionBound { + + static > void writeThroughTypeVariable( + @Nullable T[] ts, @Nullable Comparable[] cs, T t) { + if (cs[0] != null) { + ts[0] = null; + // If `ts` and `cs` are the same array, the assignment to `ts[0]` sets `cs[0]` to null. + // :: error: [dereference.of.nullable] + cs[0].compareTo(t); + } + } + + static > void writeThroughBound( + @Nullable T[] ts, @Nullable Comparable[] cs, T t) { + if (ts[0] != null) { + cs[0] = null; + // If `ts` and `cs` are the same array, the assignment to `cs[0]` sets `ts[0]` to null. + // :: error: [dereference.of.nullable] + ts[0].intValue(); + } + } + + static void unrelatedArrays(@Nullable Integer[] is, @Nullable String[] ss) { + if (is[0] != null) { + ss[0] = null; + is[0].intValue(); + } + } +} diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java index c433bd34410a..b0e2436613a4 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java @@ -2,6 +2,7 @@ import com.sun.source.tree.CompilationUnitTree; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.List; @@ -9,8 +10,11 @@ import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; +import javax.lang.model.type.ArrayType; +import javax.lang.model.type.IntersectionType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; +import javax.lang.model.type.TypeVariable; import javax.lang.model.util.Types; import javax.tools.Diagnostic; import org.checkerframework.checker.nullness.qual.Nullable; @@ -97,6 +101,12 @@ public record FieldInitialValue>( /** Instance of the types utility. */ protected final Types types; + /** True if -AassumeSideEffectFree or -AassumePure was passed on the command line. */ + private final boolean assumeSideEffectFree; + + /** True if -AassumePureGetters was passed on the command line. */ + private final boolean assumePureGetters; + /** * Cache for {@link #getSideEffectsOnlyExpressions}, which would otherwise re-parse the * annotation's expressions once per dataflow iteration per call site. A key that is mapped to @@ -172,6 +182,9 @@ protected CFAbstractAnalysis( dependentTypesHelper = factory.getDependentTypesHelper(); this.atypeFactory = factory; this.checker = checker; + this.assumeSideEffectFree = + checker.hasOption("assumeSideEffectFree") || checker.hasOption("assumePure"); + this.assumePureGetters = checker.hasOption("assumePureGetters"); this.transferFunction = createTransferFunction(); this.fieldValues = new ArrayList<>(); } @@ -516,4 +529,85 @@ public Types getTypes() { public ProcessingEnvironment getEnv() { return env; } + + /** + * Returns true if a call to the given method or constructor does not change any field or array + * element, according to the method's annotations (such as {@link + * org.checkerframework.dataflow.qual.SideEffectFree}) and the command-line options {@code + * -AassumeSideEffectFree}, {@code -AassumePure}, and {@code -AassumePureGetters}. + * + * @param method a method or constructor + * @return true if a call to {@code method} does not change any field or array element + */ + public boolean isSideEffectFree(ExecutableElement method) { + return assumeSideEffectFree + || (assumePureGetters && ElementUtils.isGetter(method)) + || atypeFactory.isSideEffectFree(method); + } + + /** + * Returns true if the given expressions might evaluate to the same object, judging by their + * types. Returns a conservative answer: true unless their types show that no object has both of + * them. + * + *

This compares the erasures of the types, because two parameterizations of a generic type can + * denote the same object even if neither is a subtype of the other. For example, a {@code + * Box} is both a {@code Box} and a {@code Box}. It + * compares every bound of a type variable or intersection type, because the erasure of such a + * type is the erasure of only its first bound. For example, a {@code T[]} where {@code T extends + * Number & Comparable} can be the same array as a {@code Comparable[]}, though {@code + * Number[]} and {@code Comparable[]} are unrelated. + * + * @param a an expression + * @param b another expression + * @return true if {@code a} and {@code b} might evaluate to the same object + */ + public boolean canAlias(JavaExpression a, JavaExpression b) { + List erasuresA = erasedBounds(a.getType()); + List erasuresB = erasedBounds(b.getType()); + for (TypeMirror ta : erasuresA) { + for (TypeMirror tb : erasuresB) { + if (types.isSubtype(ta, tb) || types.isSubtype(tb, ta)) { + return true; + } + } + } + return false; + } + + /** + * Returns the erasures of the bounds of the given type: for a type variable or intersection type, + * the erasure of each of its bounds, such as {@code Number} and {@code Comparable} for a type + * variable that extends {@code Number & Comparable}; for an array type, an array of each + * erased bound of its component type; and otherwise, the erasure of the type. Every value of the + * type has each of the returned types. + * + * @param type a type + * @return the erasures of the bounds of {@code type} + */ + private List erasedBounds(TypeMirror type) { + switch (type.getKind()) { + case TYPEVAR -> { + return erasedBounds(((TypeVariable) type).getUpperBound()); + } + case INTERSECTION -> { + List result = new ArrayList<>(); + for (TypeMirror bound : ((IntersectionType) type).getBounds()) { + result.addAll(erasedBounds(bound)); + } + return result; + } + case ARRAY -> { + List componentBounds = erasedBounds(((ArrayType) type).getComponentType()); + List result = new ArrayList<>(componentBounds.size()); + for (TypeMirror componentBound : componentBounds) { + result.add(types.getArrayType(componentBound)); + } + return result; + } + default -> { + return Collections.singletonList(types.erasure(type)); + } + } + } } diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java index 4457f7ffd409..d9ba8d084117 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java @@ -17,7 +17,6 @@ import javax.lang.model.element.Name; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; -import javax.lang.model.util.Types; import org.checkerframework.checker.nullness.qual.EnsuresNonNullIf; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.dataflow.analysis.Store; @@ -46,7 +45,6 @@ import org.checkerframework.javacutil.AnnotationBuilder; import org.checkerframework.javacutil.AnnotationUtils; import org.checkerframework.javacutil.BugInCF; -import org.checkerframework.javacutil.ElementUtils; import org.plumelib.util.CollectionsP; import org.plumelib.util.MapsP; import org.plumelib.util.ToStringComparator; @@ -119,12 +117,6 @@ public Map getFieldValues() { */ protected final boolean sequentialSemantics; - /** True if -AassumeSideEffectFree or -AassumePure was passed on the command line. */ - private final boolean assumeSideEffectFree; - - /** True if -AassumePureGetters was passed on the command line. */ - private final boolean assumePureGetters; - /** The unique ID for the next-created object. */ private static final AtomicLong nextUid = new AtomicLong(0); @@ -156,10 +148,6 @@ protected CFAbstractStore(CFAbstractAnalysis analysis, boolean sequenti this.arrayValues = new HashMap<>(); this.classValues = new HashMap<>(); this.sequentialSemantics = sequentialSemantics; - this.assumeSideEffectFree = - analysis.checker.hasOption("assumeSideEffectFree") - || analysis.checker.hasOption("assumePure"); - this.assumePureGetters = analysis.checker.hasOption("assumePureGetters"); } /** @@ -177,8 +165,6 @@ protected CFAbstractStore(CFAbstractStore other) { this.arrayValues = new HashMap<>(other.arrayValues); this.classValues = new HashMap<>(other.classValues); this.sequentialSemantics = other.sequentialSemantics; - this.assumeSideEffectFree = other.assumeSideEffectFree; - this.assumePureGetters = other.assumePureGetters; } /** @@ -206,21 +192,6 @@ public void initializeThisValue(AnnotationMirror a, TypeMirror underlyingType) { /* Handling of fields */ /* --------------------------------------------------------- */ - /** - * Returns true if a call to the given method or constructor does not change any field or array - * element, according to the method's annotations (such as {@link - * org.checkerframework.dataflow.qual.SideEffectFree}) and the command-line options {@code - * -AassumeSideEffectFree}, {@code -AassumePure}, and {@code -AassumePureGetters}. - * - * @param method a method or constructor - * @return true if a call to {@code method} does not change any field or array element - */ - public boolean isSideEffectFree(ExecutableElement method) { - return assumeSideEffectFree - || (assumePureGetters && ElementUtils.isGetter(method)) - || analysis.atypeFactory.isSideEffectFree(method); - } - /** * Remove any information that might not be valid any more after a method call, and add * information guaranteed by the method. @@ -251,7 +222,7 @@ public void updateForMethodCall(MethodInvocationNode methodInvocationNode, @Null GenericAnnotatedTypeFactory atypeFactory = analysis.atypeFactory; // Case 1: The method is side-effect-free. - if (!isSideEffectFree(method)) { + if (!analysis.isSideEffectFree(method)) { boolean sideEffectsUnrefineAliases = atypeFactory.sideEffectsUnrefineAliases; Node receiver = methodInvocationNode.getTarget().getReceiver(); @@ -1368,16 +1339,12 @@ protected void removeConflicting(LocalVariable var) { * Can the objects {@code a} and {@code b} be aliases? Returns a conservative answer (i.e., * returns {@code true} if not enough information is available to determine aliasing). * - *

This compares the erasures of the types, because two parameterizations of a generic type can - * denote the same object even if neither is a subtype of the other. For example, a {@code - * Box} is both a {@code Box} and a {@code Box}. + *

This implementation does not depend on the contents of the store; see {@link + * CFAbstractAnalysis#canAlias}. */ @Override public boolean canAlias(JavaExpression a, JavaExpression b) { - Types types = analysis.getTypes(); - TypeMirror ta = types.erasure(a.getType()); - TypeMirror tb = types.erasure(b.getType()); - return types.isSubtype(ta, tb) || types.isSubtype(tb, ta); + return analysis.canAlias(a, b); } /* --------------------------------------------------------- */ diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 12615538057d..f8142e70be79 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -11,7 +11,7 @@ import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewClassTree; -import com.sun.source.tree.ParenthesizedTree; +import com.sun.source.tree.SwitchExpressionTree; import com.sun.source.tree.Tree; import com.sun.source.tree.UnaryTree; import com.sun.source.tree.VariableTree; @@ -31,9 +31,9 @@ import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; +import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import org.checkerframework.checker.interning.qual.InternedDistinct; -import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.PolyNull; import org.checkerframework.common.aliasing.AliasingAnnotatedTypeFactory; @@ -113,6 +113,7 @@ import org.checkerframework.javacutil.TreePathUtil; import org.checkerframework.javacutil.TreeUtils; import org.checkerframework.javacutil.TreeUtilsAfterJava17.PatternCaseLabelUtils; +import org.checkerframework.javacutil.TypesUtils; /** * The default analysis transfer function for the Checker Framework. It propagates information @@ -145,8 +146,8 @@ public abstract class CFAbstractTransfer< /** Indicates that the whole-program inference is on. */ private final boolean infer; - /** An empty store, which {@link #getEmptyStore} creates on first use. */ - private @MonotonicNonNull S emptyStore; + /** The method {@code Object.toString()}, which a string conversion calls. */ + private final ExecutableElement objectToString; /** * Create a CFAbstractTransfer. @@ -172,6 +173,7 @@ protected CFAbstractTransfer( this.sequentialSemantics = !(forceConcurrentSemantics || analysis.checker.hasOption("concurrentSemantics")); this.infer = analysis.checker.hasOption("infer"); + this.objectToString = TreeUtils.getMethod("java.lang.Object", "toString", 0, analysis.getEnv()); } /** @@ -987,8 +989,9 @@ protected TransferResult strengthenAnnotationOfEqualTo( * CFAbstractStore#canInsertJavaExpression}) and that, when the comparison completes, might have a * different value than {@code node} had when it was evaluated. A node's value can change when * code that is evaluated after the node writes a variable, field, or array element that the node - * reads. That code is the rest of the assignment, and the right operand of the comparison if - * {@code node} is its left operand. For example: + * reads. That code is the rest of the assignment, and the code in the enclosing expressions that + * is evaluated after {@code node} and before the comparison completes, such as the right operand + * of the comparison if {@code node} is in its left operand. For example: * *

* - * A method call or object creation might write any field or array element, unless the method or - * constructor is side-effect-free (see {@link CFAbstractStore#isSideEffectFree}). + * A method call, object creation, or string conversion (which calls {@code toString()}) might + * write any field or array element, unless the method or constructor is side-effect-free (see + * {@link CFAbstractAnalysis#isSideEffectFree}). The result omits a field that such a call might + * write even when the store would keep the field's refinement across the call, as it does for a + * refinement to the target of a monotonic qualifier (see {@link + * org.checkerframework.framework.qual.MonotonicQualifier}): whether the store keeps a refinement + * depends on the refined value, which this method does not know. * *

A node that is not an assignment is returned even if it contains an assignment, as in {@code * x + (x = 1)}. {@link JavaExpression#fromNode} converts such a node to an expression that @@ -1030,20 +1038,42 @@ protected List splitAssignments(Node node) { * @return the result of {@link #splitAssignments} for {@code node} */ private List computeSplitAssignments(Node node) { - Writes laterWrites = new Writes(); - ExpressionTree laterOperand = laterOperand(node); - if (laterOperand != null) { - laterWrites.scan(laterOperand, null); - } - - if (!(node instanceof AssignmentNode)) { - return mayBeChanged(node, new Writes(), laterWrites) - ? Collections.emptyList() - : Collections.singletonList(node); + List sides = + node instanceof AssignmentNode assignment + ? sidesOfAssignment(assignment) + : Collections.singletonList(node); + // Find the later writes only if a side might be omitted because of them, because finding them + // requires the path to the tree of `node`, which can be costly to compute. + Writes laterWrites = null; + List result = new ArrayList<>(sides.size()); + for (Node side : sides) { + JavaExpression expr = JavaExpression.fromNode(side); + if (CFAbstractStore.canInsertJavaExpression(expr)) { + if (laterWrites == null) { + laterWrites = laterWrites(node); + } + if (laterWrites.mayChange(expr, false)) { + continue; + } + } + result.add(side); } + return result; + } + /** + * Returns the sides of the given assignment that have the value of the assignment when the + * assignment completes. The sides are the targets of the chain of assignments that starts with + * {@code assignment}, such as {@code a} and {@code b} in {@code a = b = c}, and the rhs of the + * last assignment in the chain, such as {@code c}. The result omits each side that a store can + * hold a value for and that the rest of the assignment might change. + * + * @param assignment an assignment node + * @return the sides of {@code assignment} that have its value when it completes, in source order + */ + private List sidesOfAssignment(AssignmentNode assignment) { List chain = new ArrayList<>(); - Node rhs = node; + Node rhs = assignment; while (rhs instanceof AssignmentNode a) { chain.add(a); rhs = a.getExpression(); @@ -1062,14 +1092,14 @@ private List computeSplitAssignments(Node node) { } Node[] sides = new Node[chain.size() + 1]; int numKept = 0; - if (!mayBeChanged(rhs, writes, laterWrites)) { + if (!mayBeChanged(rhs, writes)) { sides[chain.size()] = rhs; numKept++; } for (int i = chain.size() - 1; i >= 0; i--) { Node target = chain.get(i).getTarget(); writes.scan(target.getTree(), null); - if (!mayBeChanged(target, writes, laterWrites)) { + if (!mayBeChanged(target, writes)) { sides[i] = target; numKept++; } @@ -1088,17 +1118,15 @@ private List computeSplitAssignments(Node node) { * Returns true if a store can hold a value for the given side of an assignment, and the side * might be changed by the given writes. * - * @param side a side of an assignment, or a node that is not an assignment + * @param side a side of an assignment * @param writes the writes that happen after {@code side} is evaluated and before the assignment * stores into its targets; they do not change the location that {@code side} denotes, because * the assignment stores the value of {@code side} into that location or reads it afterward - * @param laterWrites the writes that happen after the assignment completes * @return true if a store can hold a value for {@code side} and the writes might change its value */ - private boolean mayBeChanged(Node side, Writes writes, Writes laterWrites) { + private boolean mayBeChanged(Node side, Writes writes) { JavaExpression expr = JavaExpression.fromNode(side); - return CFAbstractStore.canInsertJavaExpression(expr) - && (writes.mayChange(expr, true) || laterWrites.mayChange(expr, false)); + return CFAbstractStore.canInsertJavaExpression(expr) && writes.mayChange(expr, true); } /** @@ -1123,32 +1151,44 @@ private boolean mayBeChanged(Node side, Writes writes, Writes laterWrites) { } /** - * Returns the right operand of the binary operation, such as a comparison, whose left operand is - * {@code node}, ignoring parentheses. Javac evaluates the right operand after {@code node} and - * before the binary operation. + * Returns the writes that happen after the given node is evaluated and before the comparison + * (such as {@code ==} or {@code <}) that contains it completes. They are the writes of the code + * in the enclosing expressions that is evaluated after the node, and of those enclosing + * expressions themselves. For example, if {@code node} is {@code x} in {@code foo(x).f == y}, + * they are the writes of the call to {@code foo} and of {@code y}. + * + *

If no comparison encloses the node, the result contains the writes up to the outermost + * enclosing expression, or up to an enclosing lambda or switch expression. * * @param node a node - * @return the right operand of the binary operation whose left operand is {@code node}, or null - * if {@code node} is not the left operand of a binary operation + * @return the writes that happen after {@code node} is evaluated and before the comparison that + * contains it completes */ - @SuppressWarnings("interning:not.interned") // reference equality of AST nodes - private @Nullable ExpressionTree laterOperand(Node node) { + private Writes laterWrites(Node node) { + Writes result = new Writes(); TreePath path = sourcePath(node); if (path == null) { - return null; + return result; } - Tree tree = path.getLeaf(); TreePath parentPath = path.getParentPath(); - while (parentPath != null && parentPath.getLeaf() instanceof ParenthesizedTree) { - tree = parentPath.getLeaf(); - parentPath = parentPath.getParentPath(); - } - if (parentPath != null - && parentPath.getLeaf() instanceof BinaryTree binaryTree - && binaryTree.getLeftOperand() == tree) { - return binaryTree.getRightOperand(); + while (parentPath != null) { + Tree parent = parentPath.getLeaf(); + // The body of a lambda expression is not evaluated with the enclosing expression, and the + // cases of a switch expression are compared to its selector one at a time. + if (!(parent instanceof ExpressionTree) + || parent instanceof LambdaExpressionTree + || parent instanceof SwitchExpressionTree) { + break; + } + result.scanLaterSubtrees(parent, path.getLeaf()); + if (parent instanceof BinaryTree binaryTree && TreeUtils.isBinaryComparison(binaryTree)) { + break; + } + result.addOwnWrites(parent); + path = parentPath; + parentPath = path.getParentPath(); } - return null; + return result; } /** @@ -1177,23 +1217,36 @@ private boolean mayBeChanged(Node side, Writes writes, Writes laterWrites) { } /** - * Returns an empty store, which {@link Writes} uses for the store's aliasing and purity rules. + * Returns the direct subtrees of the given tree, in the order in which a {@link TreeScanner} + * visits them. For an expression, that is the order in which Java evaluates them; for example, + * the receiver and then the arguments of a method call. * - * @return an empty store + * @param tree a tree + * @return the direct subtrees of {@code tree} */ - private S getEmptyStore() { - if (emptyStore == null) { - emptyStore = analysis.createEmptyStore(sequentialSemantics); - } - return emptyStore; + private static List directSubtrees(Tree tree) { + List result = new ArrayList<>(); + tree.accept( + new TreeScanner() { + @Override + public Void scan(@Nullable Tree subtree, Void p) { + if (subtree != null) { + result.add(subtree); + } + return null; + } + }, + null); + return result; } /** * The locations that the evaluation of some code might write. {@link #add} adds a write to a * given location, and {@link #scan} adds the writes that evaluating a tree might perform: its - * assignments, compound assignments, increments, decrements, method calls, and object creations. - * A method call or object creation might write any field or array element, unless the method or - * constructor is side-effect-free. + * assignments, compound assignments, increments, decrements, method calls, object creations, and + * string conversions. A method call, object creation, or string conversion (which calls {@code + * toString()}) might write any field or array element, unless the method or constructor is + * side-effect-free. * *

{@link #scan} does not descend into lambda bodies or class bodies, which do not execute when * the tree is evaluated. A method call or object creation that might execute them is a write to @@ -1202,8 +1255,8 @@ private S getEmptyStore() { * argument as an assignment, as in {@code @IntVal(value = {0, 1})}, but it does not assign a * variable. * - *

{@link #mayChange} uses the store's rules for aliasing and purity (see {@link - * CFAbstractStore#canAlias} and {@link CFAbstractStore#isSideEffectFree}). + *

{@link #mayChange} uses the analysis's rules for aliasing and purity (see {@link + * CFAbstractAnalysis#canAlias} and {@link CFAbstractAnalysis#isSideEffectFree}). */ private final class Writes extends TreeScanner { @@ -1241,44 +1294,105 @@ void add(JavaExpression target) { } } - @Override - public Void visitAssignment(AssignmentTree tree, Void p) { - add(JavaExpression.fromTree(tree.getVariable())); - return super.visitAssignment(tree, p); + /** + * Adds the writes that the given tree performs itself, after its subtrees are evaluated: the + * write of an assignment, compound assignment, increment, or decrement, and the writes of a + * method call, object creation, or string conversion. Does not add the writes of the subtrees. + * + * @param tree a tree + */ + void addOwnWrites(Tree tree) { + if (tree instanceof AssignmentTree assignmentTree) { + add(JavaExpression.fromTree(assignmentTree.getVariable())); + } else if (tree instanceof CompoundAssignmentTree compoundAssignmentTree) { + add(JavaExpression.fromTree(compoundAssignmentTree.getVariable())); + if (tree.getKind() == Tree.Kind.PLUS_ASSIGNMENT) { + addStringConversions( + compoundAssignmentTree.getVariable(), compoundAssignmentTree.getExpression()); + } + } else if (tree instanceof UnaryTree unaryTree) { + switch (tree.getKind()) { + case PREFIX_INCREMENT, PREFIX_DECREMENT, POSTFIX_INCREMENT, POSTFIX_DECREMENT -> + add(JavaExpression.fromTree(unaryTree.getExpression())); + default -> {} + } + } else if (tree instanceof MethodInvocationTree methodInvocationTree) { + addCall(TreeUtils.elementFromUse(methodInvocationTree)); + } else if (tree instanceof NewClassTree newClassTree) { + // For an anonymous class, this is the constructor of the anonymous class, which executes + // its initializers. + addCall(TreeUtils.elementFromUse(newClassTree)); + } else if (tree instanceof BinaryTree binaryTree && tree.getKind() == Tree.Kind.PLUS) { + addStringConversions(binaryTree.getLeftOperand(), binaryTree.getRightOperand()); + } } - @Override - public Void visitCompoundAssignment(CompoundAssignmentTree tree, Void p) { - add(JavaExpression.fromTree(tree.getVariable())); - return super.visitCompoundAssignment(tree, p); + /** + * Adds the writes of a call to the given method or constructor. + * + * @param method a method or constructor that is called + */ + private void addCall(ExecutableElement method) { + if (!analysis.isSideEffectFree(method)) { + anyHeapLocation = true; + } } - @Override - public Void visitUnary(UnaryTree tree, Void p) { - switch (tree.getKind()) { - case PREFIX_INCREMENT, PREFIX_DECREMENT, POSTFIX_INCREMENT, POSTFIX_DECREMENT -> - add(JavaExpression.fromTree(tree.getExpression())); - default -> {} + /** + * Adds the writes of the string conversions of the given operands of a {@code +} or {@code +=} + * operator, if it is a string concatenation. A string conversion of a reference that is not a + * {@code String} calls its {@code toString()} method. + * + * @param left the left operand of a {@code +} or {@code +=} operator + * @param right the right operand of the operator + */ + private void addStringConversions(ExpressionTree left, ExpressionTree right) { + TypeMirror leftType = TreeUtils.typeOf(left); + TypeMirror rightType = TreeUtils.typeOf(right); + if ((TypesUtils.isString(leftType) || TypesUtils.isString(rightType)) + && (callsToString(leftType) || callsToString(rightType))) { + // Every override of `toString()` has the purity annotations of `Object.toString()`. + addCall(objectToString); } - return super.visitUnary(tree, p); } - @Override - public Void visitMethodInvocation(MethodInvocationTree tree, Void p) { - if (!getEmptyStore().isSideEffectFree(TreeUtils.elementFromUse(tree))) { - anyHeapLocation = true; + /** + * Returns true if a string conversion of a value of the given type calls {@code toString()}. + * + * @param type the type of an operand of a string concatenation + * @return true if a string conversion of a value of {@code type} calls {@code toString()} + */ + private boolean callsToString(TypeMirror type) { + return !type.getKind().isPrimitive() + && type.getKind() != TypeKind.NULL + && !TypesUtils.isString(type); + } + + /** + * Adds the writes of the direct subtrees of {@code parent} that are evaluated after {@code + * child}. + * + * @param parent an expression + * @param child a direct subtree of {@code parent} + */ + @SuppressWarnings("interning:not.interned") // reference equality of AST nodes + void scanLaterSubtrees(Tree parent, Tree child) { + boolean afterChild = false; + for (Tree subtree : directSubtrees(parent)) { + if (afterChild) { + scan(subtree, null); + } else if (subtree == child) { + afterChild = true; + } } - return super.visitMethodInvocation(tree, p); } @Override - public Void visitNewClass(NewClassTree tree, Void p) { - // For an anonymous class, this is the constructor of the anonymous class, which executes its - // initializers. - if (!getEmptyStore().isSideEffectFree(TreeUtils.elementFromUse(tree))) { - anyHeapLocation = true; + public Void scan(@Nullable Tree tree, Void p) { + if (tree != null) { + addOwnWrites(tree); } - return super.visitNewClass(tree, p); + return super.scan(tree, p); } @Override @@ -1302,6 +1416,10 @@ public Void visitClass(ClassTree tree, Void p) { *

A write to a local variable changes only expressions that contain the variable. A write to * a field changes only accesses of the same field, and method calls. A write to an array * element changes only accesses of arrays that might alias the written array, and method calls. + * If side effects unrefine aliases (see {@link + * GenericAnnotatedTypeFactory#sideEffectsUnrefineAliases}), then a write to any field or array + * element also changes every expression whose abstract value other code can modify (see {@link + * JavaExpression#isModifiableByOtherCode}). * * @param expr an expression * @param ignoreOwnLocation true if a write to the location that {@code expr} denotes (if it is @@ -1310,6 +1428,13 @@ public Void visitClass(ClassTree tree, Void p) { * @return true if these writes might change the value of {@code expr} */ boolean mayChange(JavaExpression expr, boolean ignoreOwnLocation) { + if (anyHeapLocation + && analysis.atypeFactory.sideEffectsUnrefineAliases + && expr.isModifiableByOtherCode()) { + // As in CFAbstractStore#updateForMethodCall, a write might change the abstract value of + // the object that `expr` denotes, even if `expr` still denotes the same object. + return true; + } if (expr instanceof LocalVariable) { return !ignoreOwnLocation && locals.contains(expr); } else if (expr instanceof FieldAccess fa) { @@ -1355,10 +1480,9 @@ private boolean mayWriteField(FieldAccess fa) { if (anyHeapLocation && !fa.isFinal()) { return true; } - S store = getEmptyStore(); for (FieldAccess field : fields) { if (field.getField().equals(fa.getField()) - && store.canAlias(field.getReceiver(), fa.getReceiver())) { + && analysis.canAlias(field.getReceiver(), fa.getReceiver())) { return true; } } @@ -1375,9 +1499,8 @@ private boolean mayWriteArrayElement(ArrayAccess aa) { if (anyHeapLocation) { return true; } - S store = getEmptyStore(); for (ArrayAccess arrayElement : arrayElements) { - if (store.canAlias(arrayElement.getArray(), aa.getArray())) { + if (analysis.canAlias(arrayElement.getArray(), aa.getArray())) { return true; } } From 34b5d4e31e7cfde1594668ba5a113f5f1423a378 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Thu, 12 Nov 2026 11:54:27 -0800 Subject: [PATCH 16/73] Fix CI: document refineGT and refineGTE; handle nullable values in LowerBoundTransfer; suppress a nullness warning --- .../checker/index/IndexAbstractTransfer.java | 22 +++++++++++++++++++ .../index/lowerbound/LowerBoundTransfer.java | 10 +++++++-- .../framework/flow/CFAbstractAnalysis.java | 5 ++++- 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java index 9e6baafddb88..81dde967e937 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java @@ -112,6 +112,17 @@ protected void insertValueForComparedNode(CFStore store, Node node, AnnotationMi } } + /** + * Refines the given store, assuming that the value of {@code left} is greater than the value of + * {@code right}. + * + * @param left the larger operand of a comparison + * @param leftAnno the annotation of {@code left} + * @param right the smaller operand of the comparison + * @param rightAnno the annotation of {@code right} + * @param store the store to refine + * @param in the input to the transfer function for the comparison + */ protected abstract void refineGT( Node left, AnnotationMirror leftAnno, @@ -120,6 +131,17 @@ protected abstract void refineGT( CFStore store, TransferInput in); + /** + * Refines the given store, assuming that the value of {@code left} is greater than or equal to + * the value of {@code right}. + * + * @param left the larger-or-equal operand of a comparison + * @param leftAnno the annotation of {@code left} + * @param right the smaller-or-equal operand of the comparison + * @param rightAnno the annotation of {@code right} + * @param store the store to refine + * @param in the input to the transfer function for the comparison + */ protected abstract void refineGTE( Node left, AnnotationMirror leftAnno, diff --git a/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java index 74acc06bb904..adb160cb083e 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java @@ -263,10 +263,14 @@ private void notEqualsLessThan( if (!isNonNegative(leftAnno) || !isNonNegative(otherAnno)) { return; } + Tree leftTree = leftNode.getTree(); + if (leftTree == null) { + return; + } JavaExpression otherJe = JavaExpression.fromNode(otherNode); if (atypeFactory .getLessThanAnnotatedTypeFactory() - .isLessThanOrEqual(leftNode.getTree(), otherJe.toString())) { + .isLessThanOrEqual(leftTree, otherJe.toString())) { insertValueForComparedNode(store, otherNode, POS); } } @@ -333,7 +337,9 @@ protected void refineGTE( .getQualifierHierarchy() .greatestLowerBoundShallow(rightAnno, left.getType(), leftAnno, right.getType()); - insertValueForComparedNode(store, left, newLBType); + if (newLBType != null) { + insertValueForComparedNode(store, left, newLBType); + } } /** diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java index b0e2436613a4..46721153c5dd 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java @@ -169,7 +169,10 @@ private record SeOnlyParseCacheKey(ExecutableElement declaringMethod, String exp * @param factory an annotated type factory to introduce type and dataflow rules * @param maxCountBeforeWidening number of times a block can be analyzed before widening */ - @SuppressWarnings("this-escape") + @SuppressWarnings({ + "this-escape", + "nullness:method.invocation" // calls createTransferFunction() on a partly-initialized object + }) protected CFAbstractAnalysis( BaseTypeChecker checker, GenericAnnotatedTypeFactory> factory, From d6f3bc36632a8b7890905d8b4c36532866d26659 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 13 Nov 2026 09:49:05 -0800 Subject: [PATCH 17/73] Rename splitAssignments to nodesWithValueOf; clarify documentation Deprecate CFAbstractTransfer.splitAssignments() in favor of nodesWithValueOf(), whose name reflects that its result omits nodes whose value might change before the enclosing comparison completes. Rename laterWrites to writesUntilComparison. Clarify the documentation of nodesWithValueOf, sidesOfAssignment, mayBeChanged, sourcePath, Writes, and canAlias (whose answer is not conservative for interface types; see #8558). --- .../checker/index/IndexAbstractTransfer.java | 4 +- .../index/samelen/SameLenTransfer.java | 4 +- .../checker/nullness/NullnessTransfer.java | 2 +- docs/CHANGELOG.md | 6 + .../common/value/ValueTransfer.java | 4 +- .../framework/flow/CFAbstractAnalysis.java | 15 +- .../framework/flow/CFAbstractTransfer.java | 208 +++++++++++------- 7 files changed, 147 insertions(+), 96 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java index 81dde967e937..52e4bb2e4027 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java @@ -100,14 +100,14 @@ public TransferResult visitLessThan( /** * Inserts the given annotation into the store for each expression that has the value of the given - * node when the comparison that contains the node completes (see {@link #splitAssignments}). + * node when the comparison that contains the node completes (see {@link #nodesWithValueOf}). * * @param store the store to modify * @param node a node in an operand of a comparison * @param anno the annotation to insert for each expression that has the value of {@code node} */ protected void insertValueForComparedNode(CFStore store, Node node, AnnotationMirror anno) { - for (Node internal : splitAssignments(node)) { + for (Node internal : nodesWithValueOf(node)) { store.insertValue(JavaExpression.fromNode(internal), anno); } } diff --git a/checker/src/main/java/org/checkerframework/checker/index/samelen/SameLenTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/samelen/SameLenTransfer.java index c7047fe0ee54..43cae7e3aecc 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/samelen/SameLenTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/samelen/SameLenTransfer.java @@ -192,11 +192,11 @@ private boolean isArrayLengthAccess(Node node) { private void refineEq(Node left, Node right, CFStore store) { List exprs = new ArrayList<>(2); List annos = new ArrayList<>(2); - for (Node internal : splitAssignments(left)) { + for (Node internal : nodesWithValueOf(left)) { exprs.add(JavaExpression.fromNode(internal)); annos.add(getAnno(internal)); } - for (Node internal : splitAssignments(right)) { + for (Node internal : nodesWithValueOf(right)) { exprs.add(JavaExpression.fromNode(internal)); annos.add(getAnno(internal)); } diff --git a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java index 0ed2111d69ed..ce2d0c6e63d1 100644 --- a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java @@ -237,7 +237,7 @@ protected TransferResult strengthenAnnotationOfEqu NullnessStore thenStore = res.getThenStore(); NullnessStore elseStore = res.getElseStore(); - List secondParts = splitAssignments(secondNode); + List secondParts = nodesWithValueOf(secondNode); for (Node secondPart : secondParts) { JavaExpression secondInternal = JavaExpression.fromNode(secondPart); if (CFAbstractStore.canInsertJavaExpression(secondInternal)) { diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 488e0fc491f1..5996adf3c1d5 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -9,6 +9,12 @@ ### Changes for type system implementers +Renamed `CFAbstractTransfer.splitAssignments()` to `nodesWithValueOf()`. Its +result omits each node that might have a different value by the time the +enclosing comparison completes, such as `n.next` in `n.next == (n = o)`, so the +result can be empty. A subclass that overrides `splitAssignments()` must +override `nodesWithValueOf()` instead. + ### Closed issues ## Version 4.4.0 (2026-11-02) diff --git a/framework/src/main/java/org/checkerframework/common/value/ValueTransfer.java b/framework/src/main/java/org/checkerframework/common/value/ValueTransfer.java index c3f8a1005dc5..7125557ed182 100644 --- a/framework/src/main/java/org/checkerframework/common/value/ValueTransfer.java +++ b/framework/src/main/java/org/checkerframework/common/value/ValueTransfer.java @@ -1404,8 +1404,8 @@ private void createAnnotationFromRangeAndAddToStore(CFStore store, Range range, * @param node the node whose value to update in the store */ private void addAnnotationToStore(CFStore store, AnnotationMirror anno, Node node) { - // If node is assignment, iterate over lhs and rhs; otherwise, iterator contains just node. - for (Node internal : splitAssignments(node)) { + // Refine each node that has the value of `node` when the comparison completes. + for (Node internal : nodesWithValueOf(node)) { JavaExpression je = JavaExpression.fromNode(internal); CFValue currentValueFromStore; if (CFAbstractStore.canInsertJavaExpression(je)) { diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java index 12985ca95b80..dd2a57002f78 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java @@ -129,7 +129,7 @@ public record FieldInitialValue>( sideEffectsOnlyExpressionsCache = new IdentityHashMap<>(); /** - * Cache for {@link CFAbstractTransfer#splitAssignments}, whose result depends only on its + * Cache for {@link CFAbstractTransfer#nodesWithValueOf}, whose result depends only on its * argument and on the trees around the argument's tree, but which would otherwise be recomputed * once per dataflow iteration per comparison. * @@ -137,7 +137,7 @@ public record FieldInitialValue>( * This is an {@link IdentityHashMap} because the result depends on the trees around the node, but * {@link Node#equals} can be true for nodes that represent different trees. */ - final IdentityHashMap> splitAssignmentsCache = new IdentityHashMap<>(); + final IdentityHashMap> nodesWithValueOfCache = new IdentityHashMap<>(); /** * Cache for {@link StringToJavaExpression#atMethodDecl}, as called by {@link @@ -224,7 +224,7 @@ public void performAnalysis(ControlFlowGraph cfg, List> fie this.fieldValues.addAll(fieldValues); // The cache's keys are nodes of the control flow graph that was analyzed previously. sideEffectsOnlyExpressionsCache.clear(); - splitAssignmentsCache.clear(); + nodesWithValueOfCache.clear(); super.performAnalysis(cfg); } @@ -554,8 +554,13 @@ public boolean isSideEffectFree(ExecutableElement method) { /** * Returns true if the given expressions might evaluate to the same object, judging by their - * types. Returns a conservative answer: true unless their types show that no object has both of - * them. + * types: that is, true if the erasure of some bound of one expression's type is a subtype of the + * erasure of some bound of the other expression's type, as described below. + * + *

The answer is not conservative when an interface type is involved. One object can have two + * unrelated interface types, such as {@code Runnable} and {@code Serializable}, or a class type + * and an unrelated interface type, but this method returns false for expressions of such types. + * See https://github.com/typetools/checker-framework/issues/8558. * *

This compares the erasures of the types, because two parameterizations of a generic type can * denote the same object even if neither is a subtype of the other. For example, a {@code diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 9c51bc0cbff1..b8416c8e0d79 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -929,11 +929,10 @@ public TransferResult visitNotEqual(NotEqualNode n, TransferInput p) * is tracked by the store (e.g., a local variable or a field). Clients usually call this twice * with {@code firstNode} and {@code secondNode} reversed, to refine each of them. * - *

Note that when overriding this method, when a new type is inserted into the store, {@link - * #splitAssignments} should be called, and the new type should be inserted into the store for - * each of the resulting nodes. The result of {@link #splitAssignments} omits each node that might - * not have the value of {@code secondNode} when the comparison completes; do not insert the new - * type for such a node. + *

An overriding method that inserts a new type into the store should insert it for each node + * in the result of {@link #nodesWithValueOf nodesWithValueOf(secondNode)}, rather than for {@code + * secondNode}. The result omits each node that might not have the value of {@code secondNode} + * when the comparison completes; do not insert the new type for such a node. * * @param firstNode the node that might be more precise * @param secondNode the node whose type to possibly refine @@ -954,7 +953,7 @@ protected TransferResult strengthenAnnotationOfEqualTo( if (firstValue != null) { // Only need to insert if the second value is actually different. if (!firstValue.equals(secondValue)) { - List secondParts = splitAssignments(secondNode); + List secondParts = nodesWithValueOf(secondNode); for (Node secondPart : secondParts) { JavaExpression secondInternal = JavaExpression.fromNode(secondPart); if (!secondInternal.isDeterministic(analysis.atypeFactory)) { @@ -979,26 +978,30 @@ protected TransferResult strengthenAnnotationOfEqualTo( } /** - * Takes a node, and either returns the node itself again (as a singleton list), or if the node is - * an assignment node, returns the sides of the assignment. The sides are the lhs and rhs, where - * splitAssignments is applied recursively to the rhs -- that is, it is possible that the rhs does - * not appear in the result, but rather its lhs and rhs do. - * - *

{@code node} is an operand of a comparison, such as {@code ==} or {@code <}, and the caller - * refines each node in the result according to the outcome of the comparison. Therefore, the - * result omits each node that a store can hold a value for (see {@link + * Returns the nodes that have the value of the given node when the comparison that contains the + * node completes. The comparison is a binary comparison such as {@code ==} or {@code <}, and the + * caller refines each node in the result according to the outcome of the comparison. + * + *

If {@code node} is an assignment, the candidates are its sides: the target of each + * assignment in {@code node}'s chain of nested assignments, and the rhs of the innermost one. For + * example, the sides of {@code a = b = c}, which is parsed as {@code a = (b = c)}, are {@code a}, + * {@code b}, and {@code c}. Otherwise, the only candidate is {@code node} itself. + * + *

The result omits each candidate that a store can hold a value for (see {@link * CFAbstractStore#canInsertJavaExpression}) and that, when the comparison completes, might have a - * different value than {@code node} had when it was evaluated. A node's value can change when - * code that is evaluated after the node writes a variable, field, or array element that the node - * reads. That code is the rest of the assignment, and the code in the enclosing expressions that - * is evaluated after {@code node} and before the comparison completes, such as the right operand - * of the comparison if {@code node} is in its left operand. For example: + * different value than {@code node} had when it was evaluated. A candidate's value can change + * when code that is evaluated after the candidate writes a variable, field, or array element that + * the candidate reads. That code is the rest of the assignment, and the code in the enclosing + * expressions that is evaluated after {@code node} and before the comparison completes, such as + * the right operand of the comparison if {@code node} is in its left operand. For example: * *

@@ -1011,68 +1014,86 @@ protected TransferResult strengthenAnnotationOfEqualTo( * org.checkerframework.framework.qual.MonotonicQualifier}): whether the store keeps a refinement * depends on the refined value, which this method does not know. * - *

A node that is not an assignment is returned even if it contains an assignment, as in {@code - * x + (x = 1)}. {@link JavaExpression#fromNode} converts such a node to an expression that + *

A node that is not an assignment is a candidate even if it contains an assignment, as in + * {@code x + (x = 1)}. {@link JavaExpression#fromNode} converts such a node to an expression that * contains {@link Unknown}, which no store holds a value for. * *

Clients must not modify the result, which is cached. * - * @param node possibly an assignment node - * @return a list containing the right- and left-hand sides in the given assignment node that have - * the value of the assignment when the comparison completes; if {@code node} is not an - * assignment, a list containing just {@code node}, or an empty list if {@code node} might - * have a different value when the comparison completes + * @param node a node in an operand of a comparison, possibly an assignment + * @return the nodes that have the value of {@code node} when the comparison completes: the sides + * of {@code node} if it is an assignment, and otherwise {@code node} itself, except for those + * that might have a different value by then */ - protected List splitAssignments(Node node) { - List result = analysis.splitAssignmentsCache.get(node); + protected List nodesWithValueOf(Node node) { + List result = analysis.nodesWithValueOfCache.get(node); if (result == null) { - result = Collections.unmodifiableList(computeSplitAssignments(node)); - analysis.splitAssignmentsCache.put(node, result); + result = Collections.unmodifiableList(computeNodesWithValueOf(node)); + analysis.nodesWithValueOfCache.put(node, result); } return result; } /** - * Returns the result of {@link #splitAssignments}, without using the cache. + * Returns the nodes that have the value of the given node when the comparison that contains the + * node completes. + * + * @param node a node in an operand of a comparison, possibly an assignment + * @return the nodes that have the value of {@code node} when the comparison completes + * @deprecated use {@link #nodesWithValueOf} + */ + @Deprecated // 2026-11-13 + protected List splitAssignments(Node node) { + return nodesWithValueOf(node); + } + + /** + * Returns the result of {@link #nodesWithValueOf}, without using the cache. * - * @param node possibly an assignment node - * @return the result of {@link #splitAssignments} for {@code node} + * @param node a node in an operand of a comparison, possibly an assignment + * @return the result of {@link #nodesWithValueOf} for {@code node} */ - private List computeSplitAssignments(Node node) { - List sides = + private List computeNodesWithValueOf(Node node) { + List candidates = node instanceof AssignmentNode assignment ? sidesOfAssignment(assignment) : Collections.singletonList(node); - // Find the later writes only if a side might be omitted because of them, because finding them + // Find the writes only if a candidate might be omitted because of them, because finding them // requires the path to the tree of `node`, which can be costly to compute. - Writes laterWrites = null; - List result = new ArrayList<>(sides.size()); - for (Node side : sides) { - JavaExpression expr = JavaExpression.fromNode(side); + Writes writesUntilComparison = null; + List result = new ArrayList<>(candidates.size()); + for (Node candidate : candidates) { + JavaExpression expr = JavaExpression.fromNode(candidate); if (CFAbstractStore.canInsertJavaExpression(expr)) { - if (laterWrites == null) { - laterWrites = laterWrites(node); + if (writesUntilComparison == null) { + writesUntilComparison = writesUntilComparison(node); } - if (laterWrites.mayChange(expr, false)) { + if (writesUntilComparison.mayChange(expr, false)) { continue; } } - result.add(side); + result.add(candidate); } return result; } /** * Returns the sides of the given assignment that have the value of the assignment when the - * assignment completes. The sides are the targets of the chain of assignments that starts with - * {@code assignment}, such as {@code a} and {@code b} in {@code a = b = c}, and the rhs of the - * last assignment in the chain, such as {@code c}. The result omits each side that a store can - * hold a value for and that the rest of the assignment might change. + * assignment completes. + * + *

The chain of assignments that starts with {@code assignment} is {@code assignment}, followed + * by its rhs if that is an assignment, followed by that assignment's rhs if that is an + * assignment, and so on. For example, {@code a = b = c} is parsed as {@code a = (b = c)}, and its + * chain is {@code a = (b = c)} and {@code b = c}. The sides are the targets of the assignments in + * the chain, such as {@code a} and {@code b}, and the rhs of the last assignment in the chain, + * such as {@code c}. The result omits each side that a store can hold a value for and whose value + * the rest of the chain might change. * * @param assignment an assignment node * @return the sides of {@code assignment} that have its value when it completes, in source order */ private List sidesOfAssignment(AssignmentNode assignment) { + // The chain of assignments that starts with `assignment`, outermost first. List chain = new ArrayList<>(); Node rhs = assignment; while (rhs instanceof AssignmentNode a) { @@ -1080,9 +1101,11 @@ private List sidesOfAssignment(AssignmentNode assignment) { rhs = a.getExpression(); } - // Javac evaluates the receivers and indices of the targets from left to right, then the rhs, - // and then it stores into the targets from right to left. Visit the sides in reverse order of - // evaluation, so that `writes` contains the writes that happen after the side is evaluated. + // Java evaluates the receivers and indices of the targets of the assignments in `chain` from + // left to right, then `rhs` (the rhs of the last assignment in `chain`), and then it stores + // into the targets from right to left. Visit the sides (`rhs`, and then the targets from last + // to first) in reverse order of evaluation, so that `writes` contains the writes that happen + // while or after each side is evaluated. Writes writes = new Writes(); for (AssignmentNode a : chain) { writes.add(JavaExpression.fromNode(a.getTarget())); @@ -1091,22 +1114,26 @@ private List sidesOfAssignment(AssignmentNode assignment) { if (rhsTree != null) { writes.scan(rhsTree, null); } + // The sides that the result contains, in source order: `sides[i]` is the target of + // `chain.get(i)`, and `sides[chain.size()]` is `rhs`. An element is null if the result omits + // that side. Node[] sides = new Node[chain.size() + 1]; - int numKept = 0; + // The number of non-null elements of `sides`, which is the size of the result. + int resultSize = 0; if (!mayBeChanged(rhs, writes)) { sides[chain.size()] = rhs; - numKept++; + resultSize++; } for (int i = chain.size() - 1; i >= 0; i--) { Node target = chain.get(i).getTarget(); writes.scan(target.getTree(), null); if (!mayBeChanged(target, writes)) { sides[i] = target; - numKept++; + resultSize++; } } - List result = new ArrayList<>(numKept); + List result = new ArrayList<>(resultSize); for (Node side : sides) { if (side != null) { result.add(side); @@ -1116,13 +1143,18 @@ private List sidesOfAssignment(AssignmentNode assignment) { } /** - * Returns true if a store can hold a value for the given side of an assignment, and the side - * might be changed by the given writes. + * Returns true if a store can hold a value for the given side of a chain of assignments, and the + * given writes might change the side's value. * - * @param side a side of an assignment - * @param writes the writes that happen after {@code side} is evaluated and before the assignment - * stores into its targets; they do not change the location that {@code side} denotes, because - * the assignment stores the value of {@code side} into that location or reads it afterward + * @param side a side of a chain of assignments (see {@link #sidesOfAssignment}): an entire + * target, such as {@code a[i]} (not {@code a} or {@code i}), or the entire rhs of the last + * assignment in the chain + * @param writes the writes that happen while or after {@code side} is evaluated, up to and + * including the stores into the targets of the chain. A write to the location that {@code + * side} denotes does not change the value of {@code side} when the chain completes: if {@code + * side} is a target, the chain later stores its value into that location, and if {@code side} + * is the rhs, the write either happens before {@code side} reads the location or stores the + * value that {@code side} read. * @return true if a store can hold a value for {@code side} and the writes might change its value */ private boolean mayBeChanged(Node side, Writes writes) { @@ -1165,7 +1197,7 @@ private boolean mayBeChanged(Node side, Writes writes) { * @return the writes that happen after {@code node} is evaluated and before the comparison that * contains it completes */ - private Writes laterWrites(Node node) { + private Writes writesUntilComparison(Node node) { Writes result = new Writes(); TreePath path = sourcePath(node); if (path == null) { @@ -1193,9 +1225,9 @@ private Writes laterWrites(Node node) { } /** - * Returns the path to the tree of the given node. If the node's tree is artificial, as for an - * unboxing conversion, returns the path to the tree of the node's first operand that has one, - * recursively. + * Returns the path to the tree of the given node. If the node has no tree, or if its tree is not + * in the compilation unit (as for the artificial tree of an unboxing conversion), returns the + * result of this method for the first operand of the node for which that result is non-null. * * @param node a node * @return the path to the source tree that {@code node} represents, or null if there is none @@ -1242,19 +1274,20 @@ public Void scan(@Nullable Tree subtree, Void p) { } /** - * The locations that the evaluation of some code might write. {@link #add} adds a write to a - * given location, and {@link #scan} adds the writes that evaluating a tree might perform: its - * assignments, compound assignments, increments, decrements, method calls, object creations, and - * string conversions. A method call, object creation, or string conversion (which calls {@code - * toString()}) might write any field or array element, unless the method or constructor is - * side-effect-free. - * - *

{@link #scan} does not descend into lambda bodies or class bodies, which do not execute when - * the tree is evaluated. A method call or object creation that might execute them is a write to - * any field or array element, and they cannot assign a local variable that is visible outside - * them. {@link #scan} does not descend into annotations either: javac represents an annotation - * argument as an assignment, as in {@code @IntVal(value = {0, 1})}, but it does not assign a - * variable. + * The locations that the evaluation of some code might write. A location is a local variable, a + * field, or an array element, such as {@code x}, {@code o.f}, or {@code a[i]}. {@link #add} adds + * a write to a given location, and {@link #scan} adds the writes that evaluating a tree might + * perform: its assignments, compound assignments, increments, decrements, method calls, object + * creations, and string conversions. A method call, object creation, or string conversion (which + * calls {@code toString()}) might write every non-final field and every array element, unless the + * method or constructor is side-effect-free; {@link #anyHeapLocation} records that. + * + *

{@link #scan} does not descend into lambda bodies or class bodies, because they do not + * execute when the tree is evaluated. The writes of such a body to fields and array elements are + * accounted for by the method call or object creation that executes the body, and such a body + * cannot assign a local variable that is declared outside the body. {@link #scan} does not + * descend into annotations either: javac represents an annotation argument as an assignment, as + * in {@code @IntVal(value = {0, 1})}, but it does not assign a variable. * *

{@link #mayChange} uses the analysis's rules for aliasing and purity (see {@link * CFAbstractAnalysis#canAlias} and {@link CFAbstractAnalysis#isSideEffectFree}). @@ -1270,7 +1303,10 @@ private final class Writes extends TreeScanner { /** The array elements that might be written. */ private final List arrayElements = new ArrayList<>(); - /** True if any non-final field and any array element might be written. */ + /** + * True if every non-final field and every array element might be written, as by a call to a + * method that is not side-effect-free. + */ private boolean anyHeapLocation = false; /** Creates an empty set of writes. */ @@ -1289,8 +1325,9 @@ void add(JavaExpression target) { } else if (target instanceof ArrayAccess arrayAccess) { arrayElements.add(arrayAccess); } else { - // Every local variable converts to a LocalVariable, so `target` is a field or an array - // element. + // `target` is not represented precisely, as when it is an `Unknown`. A local variable is + // always represented as a `LocalVariable`, so `target` is a field or an array element, and + // a write to every field and array element includes it. anyHeapLocation = true; } } @@ -1412,7 +1449,8 @@ public Void visitClass(ClassTree tree, Void p) { } /** - * Returns true if these writes might change the value of {@code expr}. + * Returns true if these writes might change the value of {@code expr}: that is, if evaluating + * {@code expr} after the writes might yield a different value than evaluating it before them. * *

A write to a local variable changes only expressions that contain the variable. A write to * a field changes only accesses of the same field, and method calls. A write to an array @@ -1426,7 +1464,9 @@ public Void visitClass(ClassTree tree, Void p) { * @param ignoreOwnLocation true if a write to the location that {@code expr} denotes (if it is * a variable, field access, or array access) does not matter, but a write that changes * which location {@code expr} denotes (that is, a write to its receiver or index) does - * @return true if these writes might change the value of {@code expr} + * matter + * @return true if evaluating {@code expr} after these writes might yield a different value than + * evaluating it before them */ boolean mayChange(JavaExpression expr, boolean ignoreOwnLocation) { if (anyHeapLocation From 675642e302d4efd5ee647bba0d148f03e7090420 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 13 Nov 2026 09:50:18 -0800 Subject: [PATCH 18/73] Rename Writes to WrittenLocations Also rename writesUntilComparison to locationsWrittenUntilComparison, and the local variable writes to written. --- .../framework/flow/CFAbstractTransfer.java | 88 ++++++++++--------- 1 file changed, 45 insertions(+), 43 deletions(-) diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index b8416c8e0d79..d5bb380e5947 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -1058,17 +1058,17 @@ private List computeNodesWithValueOf(Node node) { node instanceof AssignmentNode assignment ? sidesOfAssignment(assignment) : Collections.singletonList(node); - // Find the writes only if a candidate might be omitted because of them, because finding them - // requires the path to the tree of `node`, which can be costly to compute. - Writes writesUntilComparison = null; + // Find the written locations only if a candidate might be omitted because of them, because + // finding them requires the path to the tree of `node`, which can be costly to compute. + WrittenLocations locationsWrittenUntilComparison = null; List result = new ArrayList<>(candidates.size()); for (Node candidate : candidates) { JavaExpression expr = JavaExpression.fromNode(candidate); if (CFAbstractStore.canInsertJavaExpression(expr)) { - if (writesUntilComparison == null) { - writesUntilComparison = writesUntilComparison(node); + if (locationsWrittenUntilComparison == null) { + locationsWrittenUntilComparison = locationsWrittenUntilComparison(node); } - if (writesUntilComparison.mayChange(expr, false)) { + if (locationsWrittenUntilComparison.mayChange(expr, false)) { continue; } } @@ -1104,15 +1104,15 @@ private List sidesOfAssignment(AssignmentNode assignment) { // Java evaluates the receivers and indices of the targets of the assignments in `chain` from // left to right, then `rhs` (the rhs of the last assignment in `chain`), and then it stores // into the targets from right to left. Visit the sides (`rhs`, and then the targets from last - // to first) in reverse order of evaluation, so that `writes` contains the writes that happen - // while or after each side is evaluated. - Writes writes = new Writes(); + // to first) in reverse order of evaluation, so that `written` contains the locations that are + // written while or after each side is evaluated. + WrittenLocations written = new WrittenLocations(); for (AssignmentNode a : chain) { - writes.add(JavaExpression.fromNode(a.getTarget())); + written.add(JavaExpression.fromNode(a.getTarget())); } ExpressionTree rhsTree = rhsTree(chain.get(chain.size() - 1)); if (rhsTree != null) { - writes.scan(rhsTree, null); + written.scan(rhsTree, null); } // The sides that the result contains, in source order: `sides[i]` is the target of // `chain.get(i)`, and `sides[chain.size()]` is `rhs`. An element is null if the result omits @@ -1120,14 +1120,14 @@ private List sidesOfAssignment(AssignmentNode assignment) { Node[] sides = new Node[chain.size() + 1]; // The number of non-null elements of `sides`, which is the size of the result. int resultSize = 0; - if (!mayBeChanged(rhs, writes)) { + if (!mayBeChanged(rhs, written)) { sides[chain.size()] = rhs; resultSize++; } for (int i = chain.size() - 1; i >= 0; i--) { Node target = chain.get(i).getTarget(); - writes.scan(target.getTree(), null); - if (!mayBeChanged(target, writes)) { + written.scan(target.getTree(), null); + if (!mayBeChanged(target, written)) { sides[i] = target; resultSize++; } @@ -1143,23 +1143,24 @@ private List sidesOfAssignment(AssignmentNode assignment) { } /** - * Returns true if a store can hold a value for the given side of a chain of assignments, and the - * given writes might change the side's value. + * Returns true if a store can hold a value for the given side of a chain of assignments, and + * writing the given locations might change the side's value. * * @param side a side of a chain of assignments (see {@link #sidesOfAssignment}): an entire * target, such as {@code a[i]} (not {@code a} or {@code i}), or the entire rhs of the last * assignment in the chain - * @param writes the writes that happen while or after {@code side} is evaluated, up to and - * including the stores into the targets of the chain. A write to the location that {@code + * @param written the locations that are written while or after {@code side} is evaluated, up to + * and including the stores into the targets of the chain. A write to the location that {@code * side} denotes does not change the value of {@code side} when the chain completes: if {@code * side} is a target, the chain later stores its value into that location, and if {@code side} * is the rhs, the write either happens before {@code side} reads the location or stores the * value that {@code side} read. - * @return true if a store can hold a value for {@code side} and the writes might change its value + * @return true if a store can hold a value for {@code side} and writing {@code written} might + * change its value */ - private boolean mayBeChanged(Node side, Writes writes) { + private boolean mayBeChanged(Node side, WrittenLocations written) { JavaExpression expr = JavaExpression.fromNode(side); - return CFAbstractStore.canInsertJavaExpression(expr) && writes.mayChange(expr, true); + return CFAbstractStore.canInsertJavaExpression(expr) && written.mayChange(expr, true); } /** @@ -1184,21 +1185,21 @@ private boolean mayBeChanged(Node side, Writes writes) { } /** - * Returns the writes that happen after the given node is evaluated and before the comparison - * (such as {@code ==} or {@code <}) that contains it completes. They are the writes of the code - * in the enclosing expressions that is evaluated after the node, and of those enclosing - * expressions themselves. For example, if {@code node} is {@code x} in {@code foo(x).f == y}, - * they are the writes of the call to {@code foo} and of {@code y}. + * Returns the locations that are written after the given node is evaluated and before the + * comparison (such as {@code ==} or {@code <}) that contains it completes. They are the locations + * written by the code in the enclosing expressions that is evaluated after the node, and by those + * enclosing expressions themselves. For example, if {@code node} is {@code x} in {@code foo(x).f + * == y}, they are the locations written by the call to {@code foo} and by {@code y}. * - *

If no comparison encloses the node, the result contains the writes up to the outermost - * enclosing expression, or up to an enclosing lambda or switch expression. + *

If no comparison encloses the node, the result contains the locations written up to the + * outermost enclosing expression, or up to an enclosing lambda or switch expression. * * @param node a node - * @return the writes that happen after {@code node} is evaluated and before the comparison that - * contains it completes + * @return the locations that are written after {@code node} is evaluated and before the + * comparison that contains it completes */ - private Writes writesUntilComparison(Node node) { - Writes result = new Writes(); + private WrittenLocations locationsWrittenUntilComparison(Node node) { + WrittenLocations result = new WrittenLocations(); TreePath path = sourcePath(node); if (path == null) { return result; @@ -1292,7 +1293,7 @@ public Void scan(@Nullable Tree subtree, Void p) { *

{@link #mayChange} uses the analysis's rules for aliasing and purity (see {@link * CFAbstractAnalysis#canAlias} and {@link CFAbstractAnalysis#isSideEffectFree}). */ - private final class Writes extends TreeScanner { + private final class WrittenLocations extends TreeScanner { /** The local variables that might be written. */ private final List locals = new ArrayList<>(); @@ -1309,8 +1310,8 @@ private final class Writes extends TreeScanner { */ private boolean anyHeapLocation = false; - /** Creates an empty set of writes. */ - Writes() {} + /** Creates an empty set of locations. */ + WrittenLocations() {} /** * Adds a write to the given location. @@ -1449,8 +1450,9 @@ public Void visitClass(ClassTree tree, Void p) { } /** - * Returns true if these writes might change the value of {@code expr}: that is, if evaluating - * {@code expr} after the writes might yield a different value than evaluating it before them. + * Returns true if writing these locations might change the value of {@code expr}: that is, if + * evaluating {@code expr} after the writes might yield a different value than evaluating it + * before them. * *

A write to a local variable changes only expressions that contain the variable. A write to * a field changes only accesses of the same field, and method calls. A write to an array @@ -1465,8 +1467,8 @@ public Void visitClass(ClassTree tree, Void p) { * a variable, field access, or array access) does not matter, but a write that changes * which location {@code expr} denotes (that is, a write to its receiver or index) does * matter - * @return true if evaluating {@code expr} after these writes might yield a different value than - * evaluating it before them + * @return true if evaluating {@code expr} after writing these locations might yield a different + * value than evaluating it before */ boolean mayChange(JavaExpression expr, boolean ignoreOwnLocation) { if (anyHeapLocation @@ -1512,10 +1514,10 @@ boolean mayChange(JavaExpression expr, boolean ignoreOwnLocation) { } /** - * Returns true if these writes might write the field that {@code fa} denotes. + * Returns true if these locations might include the field that {@code fa} denotes. * * @param fa a field access - * @return true if these writes might write the field that {@code fa} denotes + * @return true if these locations might include the field that {@code fa} denotes */ private boolean mayWriteField(FieldAccess fa) { if (anyHeapLocation && !fa.isFinal()) { @@ -1531,10 +1533,10 @@ private boolean mayWriteField(FieldAccess fa) { } /** - * Returns true if these writes might write the array element that {@code aa} denotes. + * Returns true if these locations might include the array element that {@code aa} denotes. * * @param aa an array access - * @return true if these writes might write the array element that {@code aa} denotes + * @return true if these locations might include the array element that {@code aa} denotes */ private boolean mayWriteArrayElement(ArrayAccess aa) { if (anyHeapLocation) { From 56f80091ce2dc7aa526bcf5e0681a7752ba5e62a Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 13 Nov 2026 10:04:03 -0800 Subject: [PATCH 19/73] canAlias compares erased types and every bound; move canAlias and isSideEffectFree to CFAbstractAnalysis Two parameterizations of a generic type can denote the same object even if neither is a subtype of the other, so canAlias compares erasures. It compares every bound of a type variable or intersection type, because erasure keeps only the first bound. --- .../ArrayAliasingIntersectionBound.java | 32 ++++++ .../ArrayAliasingParameterizations.java | 17 +++ .../framework/flow/CFAbstractAnalysis.java | 104 +++++++++++++++++- .../framework/flow/CFAbstractStore.java | 28 +---- 4 files changed, 157 insertions(+), 24 deletions(-) create mode 100644 checker/tests/nullness/ArrayAliasingIntersectionBound.java create mode 100644 checker/tests/nullness/ArrayAliasingParameterizations.java diff --git a/checker/tests/nullness/ArrayAliasingIntersectionBound.java b/checker/tests/nullness/ArrayAliasingIntersectionBound.java new file mode 100644 index 000000000000..eeb4d8d81236 --- /dev/null +++ b/checker/tests/nullness/ArrayAliasingIntersectionBound.java @@ -0,0 +1,32 @@ +import org.checkerframework.checker.nullness.qual.Nullable; + +// Arrays whose element types are a type variable and one of its bounds can be the same array. +public class ArrayAliasingIntersectionBound { + + static > void writeThroughTypeVariable( + @Nullable T[] ts, @Nullable Comparable[] cs, T t) { + if (cs[0] != null) { + ts[0] = null; + // If `ts` and `cs` are the same array, the assignment to `ts[0]` sets `cs[0]` to null. + // :: error: [dereference.of.nullable] + cs[0].compareTo(t); + } + } + + static > void writeThroughBound( + @Nullable T[] ts, @Nullable Comparable[] cs, T t) { + if (ts[0] != null) { + cs[0] = null; + // If `ts` and `cs` are the same array, the assignment to `cs[0]` sets `ts[0]` to null. + // :: error: [dereference.of.nullable] + ts[0].intValue(); + } + } + + static void unrelatedArrays(@Nullable Integer[] is, @Nullable String[] ss) { + if (is[0] != null) { + ss[0] = null; + is[0].intValue(); + } + } +} diff --git a/checker/tests/nullness/ArrayAliasingParameterizations.java b/checker/tests/nullness/ArrayAliasingParameterizations.java new file mode 100644 index 000000000000..c28d6b2c9883 --- /dev/null +++ b/checker/tests/nullness/ArrayAliasingParameterizations.java @@ -0,0 +1,17 @@ +import java.util.List; +import org.checkerframework.checker.nullness.qual.Nullable; + +// Arrays whose element types are two parameterizations of a generic type can be the same array, +// even if neither parameterization is a subtype of the other. +public class ArrayAliasingParameterizations { + + static void elementOfWildcardLists( + @Nullable List[] xs, @Nullable List[] ys) { + if (xs[0] != null) { + ys[0] = null; + // If `xs` and `ys` are the same array, the assignment to `ys[0]` sets `xs[0]` to null. + // :: error: [dereference.of.nullable] + xs[0].size(); + } + } +} diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java index 7c271f6af25e..f4ad130f8ca8 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java @@ -2,6 +2,7 @@ import com.sun.source.tree.CompilationUnitTree; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.List; @@ -9,8 +10,11 @@ import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; +import javax.lang.model.type.ArrayType; +import javax.lang.model.type.IntersectionType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; +import javax.lang.model.type.TypeVariable; import javax.lang.model.util.Types; import javax.tools.Diagnostic; import org.checkerframework.checker.nullness.qual.Nullable; @@ -101,6 +105,12 @@ public record FieldInitialValue>( /** Instance of the types utility. */ protected final Types types; + /** True if -AassumeSideEffectFree or -AassumePure was passed on the command line. */ + private final boolean assumeSideEffectFree; + + /** True if -AassumePureGetters was passed on the command line. */ + private final boolean assumePureGetters; + /** * Cache for {@link #getSideEffectsOnlyExpressions}, which would otherwise re-parse the * annotation's expressions once per dataflow iteration per call site. A key that is mapped to @@ -152,7 +162,10 @@ private record SeOnlyParseCacheKey(ExecutableElement declaringMethod, String exp * @param factory an annotated type factory to introduce type and dataflow rules * @param maxCountBeforeWidening number of times a block can be analyzed before widening */ - @SuppressWarnings("this-escape") + @SuppressWarnings({ + "this-escape", + "nullness:method.invocation" // calls createTransferFunction() on a partly-initialized object + }) protected CFAbstractAnalysis( BaseTypeChecker checker, GenericAnnotatedTypeFactory> factory, @@ -165,6 +178,9 @@ protected CFAbstractAnalysis( dependentTypesHelper = factory.getDependentTypesHelper(); this.atypeFactory = factory; this.checker = checker; + this.assumeSideEffectFree = + checker.hasOption("assumeSideEffectFree") || checker.hasOption("assumePure"); + this.assumePureGetters = checker.hasOption("assumePureGetters"); this.transferFunction = createTransferFunction(); this.fieldValues = new ArrayList<>(); } @@ -508,4 +524,90 @@ public Types getTypes() { public ProcessingEnvironment getEnv() { return env; } + + /** + * Returns true if a call to the given method or constructor does not change any field or array + * element, according to the method's annotations (such as {@link + * org.checkerframework.dataflow.qual.SideEffectFree}) and the command-line options {@code + * -AassumeSideEffectFree}, {@code -AassumePure}, and {@code -AassumePureGetters}. + * + * @param method a method or constructor + * @return true if a call to {@code method} does not change any field or array element + */ + public boolean isSideEffectFree(ExecutableElement method) { + return assumeSideEffectFree + || (assumePureGetters && ElementUtils.isGetter(method)) + || atypeFactory.isSideEffectFree(method); + } + + /** + * Returns true if the given expressions might evaluate to the same object, judging by their + * types: that is, true if the erasure of some bound of one expression's type is a subtype of the + * erasure of some bound of the other expression's type, as described below. + * + *

The answer is not conservative when an interface type is involved. One object can have two + * unrelated interface types, such as {@code Runnable} and {@code Serializable}, or a class type + * and an unrelated interface type, but this method returns false for expressions of such types. + * See https://github.com/typetools/checker-framework/issues/8558. + * + *

This compares the erasures of the types, because two parameterizations of a generic type can + * denote the same object even if neither is a subtype of the other. For example, a {@code + * Box} is both a {@code Box} and a {@code Box}. It + * compares every bound of a type variable or intersection type, because the erasure of such a + * type is the erasure of only its first bound. For example, a {@code T[]} where {@code T extends + * Number & Comparable} can be the same array as a {@code Comparable[]}, though {@code + * Number[]} and {@code Comparable[]} are unrelated. + * + * @param a an expression + * @param b another expression + * @return true if {@code a} and {@code b} might evaluate to the same object + */ + public boolean canAlias(JavaExpression a, JavaExpression b) { + List erasuresA = erasedBounds(a.getType()); + List erasuresB = erasedBounds(b.getType()); + for (TypeMirror ta : erasuresA) { + for (TypeMirror tb : erasuresB) { + if (types.isSubtype(ta, tb) || types.isSubtype(tb, ta)) { + return true; + } + } + } + return false; + } + + /** + * Returns the erasures of the bounds of the given type: for a type variable or intersection type, + * the erasure of each of its bounds, such as {@code Number} and {@code Comparable} for a type + * variable that extends {@code Number & Comparable}; for an array type, an array of each + * erased bound of its component type; and otherwise, the erasure of the type. Every value of the + * type has each of the returned types. + * + * @param type a type + * @return the erasures of the bounds of {@code type} + */ + private List erasedBounds(TypeMirror type) { + switch (type.getKind()) { + case TYPEVAR -> { + return erasedBounds(((TypeVariable) type).getUpperBound()); + } + case INTERSECTION -> { + List result = new ArrayList<>(); + for (TypeMirror bound : ((IntersectionType) type).getBounds()) { + result.addAll(erasedBounds(bound)); + } + return result; + } + case ARRAY -> { + List componentBounds = erasedBounds(((ArrayType) type).getComponentType()); + List result = new ArrayList<>(componentBounds.size()); + for (TypeMirror componentBound : componentBounds) { + result.add(types.getArrayType(componentBound)); + } + return result; + } + default -> { + return Collections.singletonList(types.erasure(type)); + } + } + } } diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java index 672e04802537..8874d324bd7d 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java @@ -17,7 +17,6 @@ import javax.lang.model.element.Name; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; -import javax.lang.model.util.Types; import org.checkerframework.checker.nullness.qual.EnsuresNonNullIf; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.dataflow.analysis.Store; @@ -46,7 +45,6 @@ import org.checkerframework.javacutil.AnnotationBuilder; import org.checkerframework.javacutil.AnnotationUtils; import org.checkerframework.javacutil.BugInCF; -import org.checkerframework.javacutil.ElementUtils; import org.plumelib.util.CollectionsP; import org.plumelib.util.MapsP; import org.plumelib.util.ToStringComparator; @@ -119,12 +117,6 @@ public Map getFieldValues() { */ protected final boolean sequentialSemantics; - /** True if -AassumeSideEffectFree or -AassumePure was passed on the command line. */ - private final boolean assumeSideEffectFree; - - /** True if -AassumePureGetters was passed on the command line. */ - private final boolean assumePureGetters; - /** The unique ID for the next-created object. */ private static final AtomicLong nextUid = new AtomicLong(0); @@ -156,10 +148,6 @@ protected CFAbstractStore(CFAbstractAnalysis analysis, boolean sequenti this.arrayValues = new HashMap<>(); this.classValues = new HashMap<>(); this.sequentialSemantics = sequentialSemantics; - this.assumeSideEffectFree = - analysis.checker.hasOption("assumeSideEffectFree") - || analysis.checker.hasOption("assumePure"); - this.assumePureGetters = analysis.checker.hasOption("assumePureGetters"); } /** @@ -177,8 +165,6 @@ protected CFAbstractStore(CFAbstractStore other) { this.arrayValues = new HashMap<>(other.arrayValues); this.classValues = new HashMap<>(other.classValues); this.sequentialSemantics = other.sequentialSemantics; - this.assumeSideEffectFree = other.assumeSideEffectFree; - this.assumePureGetters = other.assumePureGetters; } /** @@ -236,11 +222,7 @@ public void updateForMethodCall(MethodInvocationNode methodInvocationNode, @Null GenericAnnotatedTypeFactory atypeFactory = analysis.atypeFactory; // Case 1: The method is side-effect-free. - boolean hasSideEffect = - !(assumeSideEffectFree - || (assumePureGetters && ElementUtils.isGetter(method)) - || atypeFactory.isSideEffectFree(method)); - if (hasSideEffect) { + if (!analysis.isSideEffectFree(method)) { boolean sideEffectsUnrefineAliases = atypeFactory.sideEffectsUnrefineAliases; Node receiver = methodInvocationNode.getTarget().getReceiver(); @@ -1367,13 +1349,13 @@ protected void removeConflicting(LocalVariable var) { * Returns true if the objects {@code a} and {@code b} can be aliases. Returns a conservative * answer (i.e., returns {@code true} if not enough information is available to determine * aliasing). + * + *

This implementation does not depend on the contents of the store; see {@link + * CFAbstractAnalysis#canAlias}. */ @Override public boolean canAlias(JavaExpression a, JavaExpression b) { - TypeMirror tb = b.getType(); - TypeMirror ta = a.getType(); - Types types = analysis.getTypes(); - return types.isSubtype(ta, tb) || types.isSubtype(tb, ta); + return analysis.canAlias(a, b); } /* --------------------------------------------------------- */ From 666211a884427aed967f08eee9d5e6283e200a42 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 13 Nov 2026 10:04:37 -0800 Subject: [PATCH 20/73] JavaExpression.fromTree looks through parentheses Also annotate fromNode, fromNodeFieldAccess, and fromArrayAccess as @SideEffectFree. --- .../dataflow/expression/JavaExpression.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java b/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java index 56109d01a895..0954dfb144d3 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java @@ -10,6 +10,7 @@ import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewArrayTree; import com.sun.source.tree.NewClassTree; +import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.Tree; import com.sun.source.tree.UnaryTree; import com.sun.source.tree.VariableTree; @@ -442,6 +443,7 @@ public String toStringDebug() { * @param node the FieldAccessNode to convert to a JavaExpression * @return the {@link FieldAccess} or {@link ClassName} that corresponds to {@code node} */ + @SideEffectFree public static JavaExpression fromNodeFieldAccess(FieldAccessNode node) { Node receiverNode = node.getReceiver(); String fieldName = node.getFieldName(); @@ -470,6 +472,7 @@ public static JavaExpression fromNodeFieldAccess(FieldAccessNode node) { * @return the internal representation (as an {@link ArrayAccess}) of an {@link ArrayAccessNode}. * Can contain {@link Unknown} as receiver. */ + @SideEffectFree public static ArrayAccess fromArrayAccess(ArrayAccessNode node) { JavaExpression array = fromNode(node.getArray()); JavaExpression index = fromNode(node.getIndex()); @@ -482,6 +485,7 @@ public static ArrayAccess fromArrayAccess(ArrayAccessNode node) { * @param receiverNode a node to convert to a JavaExpression * @return the internal representation of the given node. Might contain {@link Unknown}. */ + @SideEffectFree public static JavaExpression fromNode(Node receiverNode) { JavaExpression result = null; if (receiverNode instanceof FieldAccessNode fieldAccessNode) { @@ -638,6 +642,9 @@ public static JavaExpression fromTree(ExpressionTree tree) { result = fromVariableElement(typeOfId, (VariableElement) ele, identifierTree); } } + case PARENTHESIZED -> { + return fromTree(((ParenthesizedTree) tree).getExpression()); + } case UNARY_PLUS -> { return fromTree(((UnaryTree) tree).getExpression()); } From 7e9ab4f130919d3bb33940b87afdf3fc29fc6dc9 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 13 Nov 2026 10:04:59 -0800 Subject: [PATCH 21/73] Move the Index Checker's use of nodesWithValueOf to a separate pull request The Index Checker changes move to branch index-nodes-with-value-of. The Index Checker's existing calls keep the new name nodesWithValueOf. --- .../checker/index/IndexAbstractTransfer.java | 37 ----------- .../index/lowerbound/LowerBoundTransfer.java | 34 ++++++----- .../searchindex/SearchIndexTransfer.java | 3 +- .../index/upperbound/UpperBoundTransfer.java | 42 ++++++++----- .../tests/index/AssignmentInComparison.java | 61 ------------------- 5 files changed, 49 insertions(+), 128 deletions(-) delete mode 100644 checker/tests/index/AssignmentInComparison.java diff --git a/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java index 52e4bb2e4027..5e1eda172976 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java @@ -8,7 +8,6 @@ import org.checkerframework.dataflow.cfg.node.LessThanNode; import org.checkerframework.dataflow.cfg.node.LessThanOrEqualNode; import org.checkerframework.dataflow.cfg.node.Node; -import org.checkerframework.dataflow.expression.JavaExpression; import org.checkerframework.framework.flow.CFAnalysis; import org.checkerframework.framework.flow.CFStore; import org.checkerframework.framework.flow.CFTransfer; @@ -98,31 +97,6 @@ public TransferResult visitLessThan( return rfi.newResult; } - /** - * Inserts the given annotation into the store for each expression that has the value of the given - * node when the comparison that contains the node completes (see {@link #nodesWithValueOf}). - * - * @param store the store to modify - * @param node a node in an operand of a comparison - * @param anno the annotation to insert for each expression that has the value of {@code node} - */ - protected void insertValueForComparedNode(CFStore store, Node node, AnnotationMirror anno) { - for (Node internal : nodesWithValueOf(node)) { - store.insertValue(JavaExpression.fromNode(internal), anno); - } - } - - /** - * Refines the given store, assuming that the value of {@code left} is greater than the value of - * {@code right}. - * - * @param left the larger operand of a comparison - * @param leftAnno the annotation of {@code left} - * @param right the smaller operand of the comparison - * @param rightAnno the annotation of {@code right} - * @param store the store to refine - * @param in the input to the transfer function for the comparison - */ protected abstract void refineGT( Node left, AnnotationMirror leftAnno, @@ -131,17 +105,6 @@ protected abstract void refineGT( CFStore store, TransferInput in); - /** - * Refines the given store, assuming that the value of {@code left} is greater than or equal to - * the value of {@code right}. - * - * @param left the larger-or-equal operand of a comparison - * @param leftAnno the annotation of {@code left} - * @param right the smaller-or-equal operand of the comparison - * @param rightAnno the annotation of {@code right} - * @param store the store to refine - * @param in the input to the transfer function for the comparison - */ protected abstract void refineGTE( Node left, AnnotationMirror leftAnno, diff --git a/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java index df015a4382d4..c0d36f4a6010 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java @@ -211,11 +211,19 @@ private void notEqualToValue( if (intLiteral == 0) { if (atypeFactory.areSameByClass(otherAnno, NonNegative.class)) { - insertValueForComparedNode(store, otherNode, POS); + List internals = nodesWithValueOf(otherNode); + for (Node internal : internals) { + JavaExpression je = JavaExpression.fromNode(internal); + store.insertValue(je, POS); + } } } else if (intLiteral == -1) { if (atypeFactory.areSameByClass(otherAnno, GTENegativeOne.class)) { - insertValueForComparedNode(store, otherNode, NN); + List internals = nodesWithValueOf(otherNode); + for (Node internal : internals) { + JavaExpression je = JavaExpression.fromNode(internal); + store.insertValue(je, NN); + } } } } @@ -263,15 +271,11 @@ private void notEqualsLessThan( if (!isNonNegative(leftAnno) || !isNonNegative(otherAnno)) { return; } - Tree leftTree = leftNode.getTree(); - if (leftTree == null) { - return; - } JavaExpression otherJe = JavaExpression.fromNode(otherNode); if (atypeFactory .getLessThanAnnotatedTypeFactory() - .isLessThanOrEqual(leftTree, otherJe.toString())) { - insertValueForComparedNode(store, otherNode, POS); + .isLessThanOrEqual(leftNode.getTree(), otherJe.toString())) { + store.insertValue(otherJe, POS); } } @@ -297,16 +301,18 @@ protected void refineGT( return; } + JavaExpression leftJe = JavaExpression.fromNode(left); + if (AnnotationUtils.areSame(rightAnno, GTEN1)) { - insertValueForComparedNode(store, left, NN); + store.insertValue(leftJe, NN); return; } if (AnnotationUtils.areSame(rightAnno, NN)) { - insertValueForComparedNode(store, left, POS); + store.insertValue(leftJe, POS); return; } if (AnnotationUtils.areSame(rightAnno, POS)) { - insertValueForComparedNode(store, left, POS); + store.insertValue(leftJe, POS); return; } } @@ -332,14 +338,14 @@ protected void refineGTE( return; } + JavaExpression leftJe = JavaExpression.fromNode(left); + AnnotationMirror newLBType = atypeFactory .getQualifierHierarchy() .greatestLowerBoundShallow(rightAnno, left.getType(), leftAnno, right.getType()); - if (newLBType != null) { - insertValueForComparedNode(store, left, newLBType); - } + store.insertValue(leftJe, newLBType); } /** diff --git a/checker/src/main/java/org/checkerframework/checker/index/searchindex/SearchIndexTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/searchindex/SearchIndexTransfer.java index 268facad5a38..7804370c67cd 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/searchindex/SearchIndexTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/searchindex/SearchIndexTransfer.java @@ -8,6 +8,7 @@ import org.checkerframework.common.value.ValueCheckerUtils; import org.checkerframework.dataflow.analysis.TransferInput; import org.checkerframework.dataflow.cfg.node.Node; +import org.checkerframework.dataflow.expression.JavaExpression; import org.checkerframework.framework.flow.CFAnalysis; import org.checkerframework.framework.flow.CFStore; import org.checkerframework.framework.flow.CFValue; @@ -70,7 +71,7 @@ private void refineSearchIndexToNegativeIndexFor( AnnotationUtils.getElementValueArray( rightSIF, atypeFactory.searchIndexForValueElement, String.class); AnnotationMirror nif = atypeFactory.createNegativeIndexFor(arrays); - insertValueForComparedNode(store, right, nif); + store.insertValue(JavaExpression.fromNode(right), nif); } } } diff --git a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java index a4206adc010a..c15fb409668b 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java @@ -233,7 +233,8 @@ private void propagateToMultiplicationOperand( } UBQualifier qual = getUBQualifier(node, in); UBQualifier newQual = qual.glb(typeOfMultiplication); - insertValueForComparedNode(store, node, atypeFactory.convertUBQualifierToAnnotation(newQual)); + JavaExpression je = JavaExpression.fromNode(node); + store.insertValue(je, atypeFactory.convertUBQualifierToAnnotation(newQual)); } } @@ -261,8 +262,8 @@ private void propagateToSubtractionOperands( UBQualifier newInfo = typeOfSubtraction.minusOffset(node.getRightOperand(), atypeFactory); UBQualifier newLeft = left.glb(newInfo); - insertValueForComparedNode( - store, node.getLeftOperand(), atypeFactory.convertUBQualifierToAnnotation(newLeft)); + JavaExpression leftJe = JavaExpression.fromNode(node.getLeftOperand()); + store.insertValue(leftJe, atypeFactory.convertUBQualifierToAnnotation(newLeft)); } /** @@ -292,8 +293,8 @@ private void propagateToAdditionOperand( } else if (atypeFactory.hasLowerBoundTypeByClass(other, NonNegative.class)) { newQual = newQual.glb(typeOfAddition); } - insertValueForComparedNode( - store, operand, atypeFactory.convertUBQualifierToAnnotation(newQual)); + JavaExpression operandJe = JavaExpression.fromNode(operand); + store.insertValue(operandJe, atypeFactory.convertUBQualifierToAnnotation(newQual)); } /** @@ -323,8 +324,8 @@ protected void refineGT( refineSubtrahendWithOffset(larger, smaller, true, in, store); - insertValueForComparedNode( - store, smaller, atypeFactory.convertUBQualifierToAnnotation(refinedRight)); + JavaExpression rightJe = JavaExpression.fromNode(smaller); + store.insertValue(rightJe, atypeFactory.convertUBQualifierToAnnotation(refinedRight)); } /** @@ -351,8 +352,8 @@ protected void refineGTE( refineSubtrahendWithOffset(left, right, false, in, store); - insertValueForComparedNode( - store, right, atypeFactory.convertUBQualifierToAnnotation(refinedRight)); + JavaExpression rightJe = JavaExpression.fromNode(right); + store.insertValue(rightJe, atypeFactory.convertUBQualifierToAnnotation(refinedRight)); } /** @@ -387,8 +388,8 @@ private void refineSubtrahendWithOffset( UBQualifier newQual = subtrahendQual.glb( minuendQual.plusOffset(offsetNode, atypeFactory).plusOffset(offsetAddOne ? 1 : 0)); - insertValueForComparedNode( - store, subtrahend, atypeFactory.convertUBQualifierToAnnotation(newQual)); + JavaExpression subtrahendJe = JavaExpression.fromNode(subtrahend); + store.insertValue(subtrahendJe, atypeFactory.convertUBQualifierToAnnotation(newQual)); } } @@ -429,8 +430,17 @@ private void refineEq( UBQualifier glb = rightQualifier.glb(leftQualifier); AnnotationMirror glbAnno = atypeFactory.convertUBQualifierToAnnotation(glb); - insertValueForComparedNode(store, right, glbAnno); - insertValueForComparedNode(store, left, glbAnno); + List internalsRight = nodesWithValueOf(right); + for (Node internal : internalsRight) { + JavaExpression rightJe = JavaExpression.fromNode(internal); + store.insertValue(rightJe, glbAnno); + } + + List internalsLeft = nodesWithValueOf(left); + for (Node internal : internalsLeft) { + JavaExpression leftJe = JavaExpression.fromNode(internal); + store.insertValue(leftJe, glbAnno); + } } /** @@ -485,8 +495,10 @@ private void refineNeqSequenceLength( UBQualifier newQualifier = UBQualifier.createUBQualifier(sequence, Integer.toString(lengthOffset)); otherQualifier = otherQualifier.glb(newQualifier); - insertValueForComparedNode( - store, otherNode, atypeFactory.convertUBQualifierToAnnotation(otherQualifier)); + for (Node internal : nodesWithValueOf(otherNode)) { + JavaExpression leftJe = JavaExpression.fromNode(internal); + store.insertValue(leftJe, atypeFactory.convertUBQualifierToAnnotation(otherQualifier)); + } } } } diff --git a/checker/tests/index/AssignmentInComparison.java b/checker/tests/index/AssignmentInComparison.java deleted file mode 100644 index 3436565b2c31..000000000000 --- a/checker/tests/index/AssignmentInComparison.java +++ /dev/null @@ -1,61 +0,0 @@ -import org.checkerframework.checker.index.qual.NonNegative; -import org.checkerframework.checker.index.qual.Positive; -import org.checkerframework.checker.index.qual.SameLen; -import org.checkerframework.dataflow.qual.Pure; - -// A comparison of an assignment refines only the sides that have the assigned value afterward. -public class AssignmentInComparison { - - @NonNegative int f; - - int[] arr = new int[0]; - - int[] setArr(int[] c) { - arr = c; - return c; - } - - @Pure - @NonNegative int size() { - return f; - } - - static void localTarget(@NonNegative int i, @NonNegative int j) { - if ((i = j) > 0) { - @Positive int x = i; - @Positive int y = j; - } - } - - static void localTargetMethodCallRhs(@NonNegative int i, AssignmentInComparison n) { - if ((i = n.size()) > 0) { - @Positive int x = i; - @Positive int y = n.size(); - } - } - - static void fieldTargetMethodCallRhs(AssignmentInComparison n) { - if ((n.f = n.size()) > 0) { - @Positive int x = n.f; - // The assignment to `n.f` might change the result of `n.size()`. - // :: error: [assignment] - @Positive int y = n.size(); - } - } - - static void otherOperandReassignsLeftOperand(@NonNegative int i) { - if (i > (i = 0)) { - // `i` is 0, not the value that was compared. - // :: error: [assignment] - @Positive int x = i; - } - } - - void otherOperandReassignsLengthReceiver(int[] b, int[] c) { - if ((this.arr = b).length == setArr(c).length) { - // `setArr` sets `this.arr` to `c`, which might not have the same length as `b`. - // :: error: [assignment] - int @SameLen("b") [] x = this.arr; - } - } -} From 8506546dd8f910068db7688b883eff0c596ed6d7 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 13 Nov 2026 10:05:17 -0800 Subject: [PATCH 22/73] Index Checker: refine comparison operands via nodesWithValueOf The Index Checker's comparison refinements go through the new IndexAbstractTransfer.insertValueForComparedNode, which refines each node that has the value of the compared node when the comparison completes. So `i > (i = 0)` no longer refines `i` to @Positive. --- .../checker/index/IndexAbstractTransfer.java | 37 +++++++++++ .../index/lowerbound/LowerBoundTransfer.java | 34 +++++------ .../searchindex/SearchIndexTransfer.java | 3 +- .../index/upperbound/UpperBoundTransfer.java | 42 +++++-------- .../tests/index/AssignmentInComparison.java | 61 +++++++++++++++++++ 5 files changed, 128 insertions(+), 49 deletions(-) create mode 100644 checker/tests/index/AssignmentInComparison.java diff --git a/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java index 5e1eda172976..52e4bb2e4027 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java @@ -8,6 +8,7 @@ import org.checkerframework.dataflow.cfg.node.LessThanNode; import org.checkerframework.dataflow.cfg.node.LessThanOrEqualNode; import org.checkerframework.dataflow.cfg.node.Node; +import org.checkerframework.dataflow.expression.JavaExpression; import org.checkerframework.framework.flow.CFAnalysis; import org.checkerframework.framework.flow.CFStore; import org.checkerframework.framework.flow.CFTransfer; @@ -97,6 +98,31 @@ public TransferResult visitLessThan( return rfi.newResult; } + /** + * Inserts the given annotation into the store for each expression that has the value of the given + * node when the comparison that contains the node completes (see {@link #nodesWithValueOf}). + * + * @param store the store to modify + * @param node a node in an operand of a comparison + * @param anno the annotation to insert for each expression that has the value of {@code node} + */ + protected void insertValueForComparedNode(CFStore store, Node node, AnnotationMirror anno) { + for (Node internal : nodesWithValueOf(node)) { + store.insertValue(JavaExpression.fromNode(internal), anno); + } + } + + /** + * Refines the given store, assuming that the value of {@code left} is greater than the value of + * {@code right}. + * + * @param left the larger operand of a comparison + * @param leftAnno the annotation of {@code left} + * @param right the smaller operand of the comparison + * @param rightAnno the annotation of {@code right} + * @param store the store to refine + * @param in the input to the transfer function for the comparison + */ protected abstract void refineGT( Node left, AnnotationMirror leftAnno, @@ -105,6 +131,17 @@ protected abstract void refineGT( CFStore store, TransferInput in); + /** + * Refines the given store, assuming that the value of {@code left} is greater than or equal to + * the value of {@code right}. + * + * @param left the larger-or-equal operand of a comparison + * @param leftAnno the annotation of {@code left} + * @param right the smaller-or-equal operand of the comparison + * @param rightAnno the annotation of {@code right} + * @param store the store to refine + * @param in the input to the transfer function for the comparison + */ protected abstract void refineGTE( Node left, AnnotationMirror leftAnno, diff --git a/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java index c0d36f4a6010..df015a4382d4 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java @@ -211,19 +211,11 @@ private void notEqualToValue( if (intLiteral == 0) { if (atypeFactory.areSameByClass(otherAnno, NonNegative.class)) { - List internals = nodesWithValueOf(otherNode); - for (Node internal : internals) { - JavaExpression je = JavaExpression.fromNode(internal); - store.insertValue(je, POS); - } + insertValueForComparedNode(store, otherNode, POS); } } else if (intLiteral == -1) { if (atypeFactory.areSameByClass(otherAnno, GTENegativeOne.class)) { - List internals = nodesWithValueOf(otherNode); - for (Node internal : internals) { - JavaExpression je = JavaExpression.fromNode(internal); - store.insertValue(je, NN); - } + insertValueForComparedNode(store, otherNode, NN); } } } @@ -271,11 +263,15 @@ private void notEqualsLessThan( if (!isNonNegative(leftAnno) || !isNonNegative(otherAnno)) { return; } + Tree leftTree = leftNode.getTree(); + if (leftTree == null) { + return; + } JavaExpression otherJe = JavaExpression.fromNode(otherNode); if (atypeFactory .getLessThanAnnotatedTypeFactory() - .isLessThanOrEqual(leftNode.getTree(), otherJe.toString())) { - store.insertValue(otherJe, POS); + .isLessThanOrEqual(leftTree, otherJe.toString())) { + insertValueForComparedNode(store, otherNode, POS); } } @@ -301,18 +297,16 @@ protected void refineGT( return; } - JavaExpression leftJe = JavaExpression.fromNode(left); - if (AnnotationUtils.areSame(rightAnno, GTEN1)) { - store.insertValue(leftJe, NN); + insertValueForComparedNode(store, left, NN); return; } if (AnnotationUtils.areSame(rightAnno, NN)) { - store.insertValue(leftJe, POS); + insertValueForComparedNode(store, left, POS); return; } if (AnnotationUtils.areSame(rightAnno, POS)) { - store.insertValue(leftJe, POS); + insertValueForComparedNode(store, left, POS); return; } } @@ -338,14 +332,14 @@ protected void refineGTE( return; } - JavaExpression leftJe = JavaExpression.fromNode(left); - AnnotationMirror newLBType = atypeFactory .getQualifierHierarchy() .greatestLowerBoundShallow(rightAnno, left.getType(), leftAnno, right.getType()); - store.insertValue(leftJe, newLBType); + if (newLBType != null) { + insertValueForComparedNode(store, left, newLBType); + } } /** diff --git a/checker/src/main/java/org/checkerframework/checker/index/searchindex/SearchIndexTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/searchindex/SearchIndexTransfer.java index 7804370c67cd..268facad5a38 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/searchindex/SearchIndexTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/searchindex/SearchIndexTransfer.java @@ -8,7 +8,6 @@ import org.checkerframework.common.value.ValueCheckerUtils; import org.checkerframework.dataflow.analysis.TransferInput; import org.checkerframework.dataflow.cfg.node.Node; -import org.checkerframework.dataflow.expression.JavaExpression; import org.checkerframework.framework.flow.CFAnalysis; import org.checkerframework.framework.flow.CFStore; import org.checkerframework.framework.flow.CFValue; @@ -71,7 +70,7 @@ private void refineSearchIndexToNegativeIndexFor( AnnotationUtils.getElementValueArray( rightSIF, atypeFactory.searchIndexForValueElement, String.class); AnnotationMirror nif = atypeFactory.createNegativeIndexFor(arrays); - store.insertValue(JavaExpression.fromNode(right), nif); + insertValueForComparedNode(store, right, nif); } } } diff --git a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java index c15fb409668b..a4206adc010a 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java @@ -233,8 +233,7 @@ private void propagateToMultiplicationOperand( } UBQualifier qual = getUBQualifier(node, in); UBQualifier newQual = qual.glb(typeOfMultiplication); - JavaExpression je = JavaExpression.fromNode(node); - store.insertValue(je, atypeFactory.convertUBQualifierToAnnotation(newQual)); + insertValueForComparedNode(store, node, atypeFactory.convertUBQualifierToAnnotation(newQual)); } } @@ -262,8 +261,8 @@ private void propagateToSubtractionOperands( UBQualifier newInfo = typeOfSubtraction.minusOffset(node.getRightOperand(), atypeFactory); UBQualifier newLeft = left.glb(newInfo); - JavaExpression leftJe = JavaExpression.fromNode(node.getLeftOperand()); - store.insertValue(leftJe, atypeFactory.convertUBQualifierToAnnotation(newLeft)); + insertValueForComparedNode( + store, node.getLeftOperand(), atypeFactory.convertUBQualifierToAnnotation(newLeft)); } /** @@ -293,8 +292,8 @@ private void propagateToAdditionOperand( } else if (atypeFactory.hasLowerBoundTypeByClass(other, NonNegative.class)) { newQual = newQual.glb(typeOfAddition); } - JavaExpression operandJe = JavaExpression.fromNode(operand); - store.insertValue(operandJe, atypeFactory.convertUBQualifierToAnnotation(newQual)); + insertValueForComparedNode( + store, operand, atypeFactory.convertUBQualifierToAnnotation(newQual)); } /** @@ -324,8 +323,8 @@ protected void refineGT( refineSubtrahendWithOffset(larger, smaller, true, in, store); - JavaExpression rightJe = JavaExpression.fromNode(smaller); - store.insertValue(rightJe, atypeFactory.convertUBQualifierToAnnotation(refinedRight)); + insertValueForComparedNode( + store, smaller, atypeFactory.convertUBQualifierToAnnotation(refinedRight)); } /** @@ -352,8 +351,8 @@ protected void refineGTE( refineSubtrahendWithOffset(left, right, false, in, store); - JavaExpression rightJe = JavaExpression.fromNode(right); - store.insertValue(rightJe, atypeFactory.convertUBQualifierToAnnotation(refinedRight)); + insertValueForComparedNode( + store, right, atypeFactory.convertUBQualifierToAnnotation(refinedRight)); } /** @@ -388,8 +387,8 @@ private void refineSubtrahendWithOffset( UBQualifier newQual = subtrahendQual.glb( minuendQual.plusOffset(offsetNode, atypeFactory).plusOffset(offsetAddOne ? 1 : 0)); - JavaExpression subtrahendJe = JavaExpression.fromNode(subtrahend); - store.insertValue(subtrahendJe, atypeFactory.convertUBQualifierToAnnotation(newQual)); + insertValueForComparedNode( + store, subtrahend, atypeFactory.convertUBQualifierToAnnotation(newQual)); } } @@ -430,17 +429,8 @@ private void refineEq( UBQualifier glb = rightQualifier.glb(leftQualifier); AnnotationMirror glbAnno = atypeFactory.convertUBQualifierToAnnotation(glb); - List internalsRight = nodesWithValueOf(right); - for (Node internal : internalsRight) { - JavaExpression rightJe = JavaExpression.fromNode(internal); - store.insertValue(rightJe, glbAnno); - } - - List internalsLeft = nodesWithValueOf(left); - for (Node internal : internalsLeft) { - JavaExpression leftJe = JavaExpression.fromNode(internal); - store.insertValue(leftJe, glbAnno); - } + insertValueForComparedNode(store, right, glbAnno); + insertValueForComparedNode(store, left, glbAnno); } /** @@ -495,10 +485,8 @@ private void refineNeqSequenceLength( UBQualifier newQualifier = UBQualifier.createUBQualifier(sequence, Integer.toString(lengthOffset)); otherQualifier = otherQualifier.glb(newQualifier); - for (Node internal : nodesWithValueOf(otherNode)) { - JavaExpression leftJe = JavaExpression.fromNode(internal); - store.insertValue(leftJe, atypeFactory.convertUBQualifierToAnnotation(otherQualifier)); - } + insertValueForComparedNode( + store, otherNode, atypeFactory.convertUBQualifierToAnnotation(otherQualifier)); } } } diff --git a/checker/tests/index/AssignmentInComparison.java b/checker/tests/index/AssignmentInComparison.java new file mode 100644 index 000000000000..3436565b2c31 --- /dev/null +++ b/checker/tests/index/AssignmentInComparison.java @@ -0,0 +1,61 @@ +import org.checkerframework.checker.index.qual.NonNegative; +import org.checkerframework.checker.index.qual.Positive; +import org.checkerframework.checker.index.qual.SameLen; +import org.checkerframework.dataflow.qual.Pure; + +// A comparison of an assignment refines only the sides that have the assigned value afterward. +public class AssignmentInComparison { + + @NonNegative int f; + + int[] arr = new int[0]; + + int[] setArr(int[] c) { + arr = c; + return c; + } + + @Pure + @NonNegative int size() { + return f; + } + + static void localTarget(@NonNegative int i, @NonNegative int j) { + if ((i = j) > 0) { + @Positive int x = i; + @Positive int y = j; + } + } + + static void localTargetMethodCallRhs(@NonNegative int i, AssignmentInComparison n) { + if ((i = n.size()) > 0) { + @Positive int x = i; + @Positive int y = n.size(); + } + } + + static void fieldTargetMethodCallRhs(AssignmentInComparison n) { + if ((n.f = n.size()) > 0) { + @Positive int x = n.f; + // The assignment to `n.f` might change the result of `n.size()`. + // :: error: [assignment] + @Positive int y = n.size(); + } + } + + static void otherOperandReassignsLeftOperand(@NonNegative int i) { + if (i > (i = 0)) { + // `i` is 0, not the value that was compared. + // :: error: [assignment] + @Positive int x = i; + } + } + + void otherOperandReassignsLengthReceiver(int[] b, int[] c) { + if ((this.arr = b).length == setArr(c).length) { + // `setArr` sets `this.arr` to `c`, which might not have the same length as `b`. + // :: error: [assignment] + int @SameLen("b") [] x = this.arr; + } + } +} From e47dcbc155c78db57781176ce32d4395933ce44e Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 13 Nov 2026 11:10:28 -0800 Subject: [PATCH 23/73] Parenthesize operands in BinaryOperation and UnaryOperation toString; add tests Also annotate fromTree, fromVariableTree, fromMemberSelect, and getReceiver as @SideEffectFree. --- .../tests/index/ArrayAccessParenthesized.java | 20 ++++++ .../index/SameLenParenthesizedOperand.java | 31 ++++++++++ .../ParenthesizedAssignment.java | 62 +++++++++++++++++++ .../dataflow/expression/BinaryOperation.java | 38 +++++++++++- .../dataflow/expression/JavaExpression.java | 4 ++ .../dataflow/expression/UnaryOperation.java | 29 +++++++-- 6 files changed, 179 insertions(+), 5 deletions(-) create mode 100644 checker/tests/index/ArrayAccessParenthesized.java create mode 100644 checker/tests/index/SameLenParenthesizedOperand.java create mode 100644 checker/tests/sideeffectsonly/ParenthesizedAssignment.java diff --git a/checker/tests/index/ArrayAccessParenthesized.java b/checker/tests/index/ArrayAccessParenthesized.java new file mode 100644 index 000000000000..5559ada848f0 --- /dev/null +++ b/checker/tests/index/ArrayAccessParenthesized.java @@ -0,0 +1,20 @@ +// A parenthesized array has the same length as the unparenthesized array. + +import org.checkerframework.checker.index.qual.IndexFor; + +public class ArrayAccessParenthesized { + + int[] field = new int[10]; + + int local(int[] a, @IndexFor("#1") int i) { + return (a)[i]; + } + + int field(@IndexFor("field") int i) { + return (field)[i]; + } + + int thisField(@IndexFor("this.field") int i) { + return (this.field)[i]; + } +} diff --git a/checker/tests/index/SameLenParenthesizedOperand.java b/checker/tests/index/SameLenParenthesizedOperand.java new file mode 100644 index 000000000000..7c64b3c86d38 --- /dev/null +++ b/checker/tests/index/SameLenParenthesizedOperand.java @@ -0,0 +1,31 @@ +// A parenthesized operand must not be confused with the same operands grouped differently: +// "x" + (i + j) and "x" + i + j can differ in length. + +public class SameLenParenthesizedOperand { + + void binary(int i, int j) { + String s = "x" + (i + j); + String u = "x" + i + j; + for (int k = 0; k < s.length(); k++) { + // :: error: (argument) + u.charAt(k); + } + } + + void unary(int i, int j) { + String s = "x" + -(i + j); + String u = "x" + -i + j; + for (int k = 0; k < s.length(); k++) { + // :: error: (argument) + u.charAt(k); + } + } + + void sameGrouping(int i, int j) { + String s = "x" + (i + j); + String u = "x" + (i + j); + for (int k = 0; k < s.length(); k++) { + u.charAt(k); + } + } +} diff --git a/checker/tests/sideeffectsonly/ParenthesizedAssignment.java b/checker/tests/sideeffectsonly/ParenthesizedAssignment.java new file mode 100644 index 000000000000..559bc9251d0c --- /dev/null +++ b/checker/tests/sideeffectsonly/ParenthesizedAssignment.java @@ -0,0 +1,62 @@ +// A parenthesized assignment target or receiver denotes the same location as the unparenthesized +// one. + +import org.checkerframework.dataflow.qual.SideEffectsOnly; + +public class ParenthesizedAssignment { + + int f; + int g; + ParenthesizedAssignment other; + + @SideEffectsOnly("this") + ParenthesizedAssignment() {} + + @SideEffectsOnly("this.f") + void assignsLocal() { + int x; + (x) = 1; + } + + @SideEffectsOnly("this.f") + void assignsPermittedField() { + (this.f) = 1; + (f) = 2; + (this).f = 3; + } + + @SideEffectsOnly("this.f") + void assignsOtherField() { + // :: error: (purity.incorrect.sideeffectsonly) + (this.g) = 1; + // :: error: (purity.incorrect.sideeffectsonly) + (g) = 2; + // :: error: (purity.incorrect.sideeffectsonly) + (this).g = 3; + } + + @SideEffectsOnly("this.f") + void assignsFieldOfFreshObject() { + ParenthesizedAssignment fresh = new ParenthesizedAssignment(); + (fresh).g = 1; + (fresh.g) = 2; + } + + @SideEffectsOnly("this.f") + void assignsFieldOfExistingObject(ParenthesizedAssignment p) { + // :: error: (purity.incorrect.sideeffectsonly) + (p).g = 1; + // :: error: (purity.incorrect.sideeffectsonly) + (p.g) = 2; + // :: error: (purity.incorrect.sideeffectsonly) + (this.other).f = 3; + } + + @SideEffectsOnly("this.f") + void assignsFieldOfReassignedLocal(ParenthesizedAssignment p) { + ParenthesizedAssignment fresh = new ParenthesizedAssignment(); + (fresh) = p; + // :: error: (purity.incorrect.sideeffectsonly) + (fresh).g = 1; + } +} diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/expression/BinaryOperation.java b/dataflow/src/main/java/org/checkerframework/dataflow/expression/BinaryOperation.java index 5acb8d7333c3..94cc2ddc0389 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/expression/BinaryOperation.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/expression/BinaryOperation.java @@ -166,7 +166,43 @@ private boolean isCommutative() { @Override public String toString() { - return left.toString() + " " + operationKindToString(operationKind) + " " + right.toString(); + int precedence = precedence(operationKind); + String leftString = left.toString(); + // Binary operators are left-associative, so a left operand needs parentheses only if its + // operator binds less tightly, but a right operand also needs them if its operator binds + // equally tightly: "a - (b - c)" differs from "a - b - c". + if (left instanceof BinaryOperation leftOp && precedence(leftOp.operationKind) < precedence) { + leftString = "(" + leftString + ")"; + } + String rightString = right.toString(); + if (right instanceof BinaryOperation rightOp + && precedence(rightOp.operationKind) <= precedence) { + rightString = "(" + rightString + ")"; + } + return leftString + " " + operationKindToString(operationKind) + " " + rightString; + } + + /** + * Returns the precedence of the given binary operator. A larger number means that the operator + * binds more tightly. + * + * @param operationKind a binary operation kind + * @return the precedence of the given binary operator + */ + private static int precedence(Tree.Kind operationKind) { + return switch (operationKind) { + case MULTIPLY, DIVIDE, REMAINDER -> 10; + case PLUS, MINUS -> 9; + case LEFT_SHIFT, RIGHT_SHIFT, UNSIGNED_RIGHT_SHIFT -> 8; + case LESS_THAN, GREATER_THAN, LESS_THAN_EQUAL, GREATER_THAN_EQUAL -> 7; + case EQUAL_TO, NOT_EQUAL_TO -> 6; + case AND -> 5; + case XOR -> 4; + case OR -> 3; + case CONDITIONAL_AND -> 2; + case CONDITIONAL_OR -> 1; + default -> throw new BugInCF("unhandled " + operationKind); + }; } /** diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java b/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java index 0954dfb144d3..6cc60c0d583d 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java @@ -559,6 +559,7 @@ public static JavaExpression fromNode(Node receiverNode) { * @param tree a javac tree * @return a JavaExpression for the given javac tree */ + @SideEffectFree public static JavaExpression fromTree(ExpressionTree tree) { JavaExpression result; switch (tree.getKind()) { @@ -696,6 +697,7 @@ public static JavaExpression fromTree(ExpressionTree tree) { * @param tree a variable tree * @return a JavaExpression for {@code tree} */ + @SideEffectFree public static JavaExpression fromVariableTree(VariableTree tree) { return fromVariableElement( TreeUtils.typeOf(tree), TreeUtils.elementFromDeclaration(tree), tree); @@ -742,6 +744,7 @@ private static JavaExpression fromVariableElement( * @param memberSelectTree tree * @return a JavaExpression for {@code memberSelectTree} */ + @SideEffectFree private static JavaExpression fromMemberSelect(MemberSelectTree memberSelectTree) { TypeMirror expressionType = TreeUtils.typeOf(memberSelectTree.getExpression()); if (TreeUtils.isClassLiteral(memberSelectTree)) { @@ -810,6 +813,7 @@ public static List getFormalParameters(ExecutableElement method * @param accessTree a method or constructor invocation * @return the receiver of the given invocation */ + @SideEffectFree public static JavaExpression getReceiver(ExpressionTree accessTree) { // TODO: Handle field accesses too? assert accessTree instanceof MethodInvocationTree || accessTree instanceof NewClassTree; diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/expression/UnaryOperation.java b/dataflow/src/main/java/org/checkerframework/dataflow/expression/UnaryOperation.java index 2607d79fe768..29db7e683812 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/expression/UnaryOperation.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/expression/UnaryOperation.java @@ -117,19 +117,40 @@ public boolean containsModifiableAliasOf(Store store, JavaExpression other) { @Override public String toString() { String operandString = operand.toString(); + // Every unary operator binds more tightly than every binary operator. + if (operand instanceof BinaryOperation) { + operandString = "(" + operandString + ")"; + } return switch (operationKind) { case BITWISE_COMPLEMENT -> "~" + operandString; case LOGICAL_COMPLEMENT -> "!" + operandString; case POSTFIX_DECREMENT -> operandString + "--"; case POSTFIX_INCREMENT -> operandString + "++"; - case PREFIX_DECREMENT -> "--" + operandString; - case PREFIX_INCREMENT -> "++" + operandString; - case UNARY_MINUS -> "-" + operandString; - case UNARY_PLUS -> "+" + operandString; + case PREFIX_DECREMENT -> prefix("--", operandString); + case PREFIX_INCREMENT -> prefix("++", operandString); + case UNARY_MINUS -> prefix("-", operandString); + case UNARY_PLUS -> prefix("+", operandString); default -> throw new BugInCF("Unrecognized unary operation kind " + operationKind); }; } + /** + * Returns the given prefix operator, which is one of "+", "++", "-", and "--", followed by the + * given operand. Parenthesizes the operand if juxtaposing the two would form a different token: + * for example, returns "-(-x)" rather than "--x", which is a prefix decrement. + * + * @param operator a prefix operator, which ends with "+" or "-" + * @param operandString the operand, as a string + * @return the operator followed by the operand + */ + private static String prefix(String operator, String operandString) { + if (!operandString.isEmpty() + && operandString.charAt(0) == operator.charAt(operator.length() - 1)) { + return operator + "(" + operandString + ")"; + } + return operator + operandString; + } + @Override public R accept(JavaExpressionVisitor visitor, P p) { return visitor.visitUnaryOperation(this, p); From cf8c09359ac7dc65a8b2f5f207d78580fa1f3f91 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 13 Nov 2026 11:15:59 -0800 Subject: [PATCH 24/73] Leave isSideEffectFree in the store; document canAlias's non-conservative answer; test field receivers Remove an unneeded suppression. --- .../FieldAliasingParameterizations.java | 19 ++++++++++++ .../framework/flow/CFAbstractAnalysis.java | 29 +------------------ .../framework/flow/CFAbstractStore.java | 29 +++++++++++++++---- 3 files changed, 43 insertions(+), 34 deletions(-) create mode 100644 checker/tests/nullness/FieldAliasingParameterizations.java diff --git a/checker/tests/nullness/FieldAliasingParameterizations.java b/checker/tests/nullness/FieldAliasingParameterizations.java new file mode 100644 index 000000000000..1c6a659dcad3 --- /dev/null +++ b/checker/tests/nullness/FieldAliasingParameterizations.java @@ -0,0 +1,19 @@ +import org.checkerframework.checker.nullness.qual.Nullable; + +// Receivers whose types are two parameterizations of a generic type can be the same object, even if +// neither parameterization is a subtype of the other. +public class FieldAliasingParameterizations { + + static class Box { + @Nullable String f; + } + + static void fieldOfWildcardBoxes(Box x, Box y) { + if (x.f != null) { + y.f = null; + // If `x` and `y` are the same object, the assignment to `y.f` sets `x.f` to null. + // :: error: [dereference.of.nullable] + x.f.length(); + } + } +} diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java index f4ad130f8ca8..6bf911cd43a6 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java @@ -105,12 +105,6 @@ public record FieldInitialValue>( /** Instance of the types utility. */ protected final Types types; - /** True if -AassumeSideEffectFree or -AassumePure was passed on the command line. */ - private final boolean assumeSideEffectFree; - - /** True if -AassumePureGetters was passed on the command line. */ - private final boolean assumePureGetters; - /** * Cache for {@link #getSideEffectsOnlyExpressions}, which would otherwise re-parse the * annotation's expressions once per dataflow iteration per call site. A key that is mapped to @@ -162,10 +156,7 @@ private record SeOnlyParseCacheKey(ExecutableElement declaringMethod, String exp * @param factory an annotated type factory to introduce type and dataflow rules * @param maxCountBeforeWidening number of times a block can be analyzed before widening */ - @SuppressWarnings({ - "this-escape", - "nullness:method.invocation" // calls createTransferFunction() on a partly-initialized object - }) + @SuppressWarnings("this-escape") protected CFAbstractAnalysis( BaseTypeChecker checker, GenericAnnotatedTypeFactory> factory, @@ -178,9 +169,6 @@ protected CFAbstractAnalysis( dependentTypesHelper = factory.getDependentTypesHelper(); this.atypeFactory = factory; this.checker = checker; - this.assumeSideEffectFree = - checker.hasOption("assumeSideEffectFree") || checker.hasOption("assumePure"); - this.assumePureGetters = checker.hasOption("assumePureGetters"); this.transferFunction = createTransferFunction(); this.fieldValues = new ArrayList<>(); } @@ -525,21 +513,6 @@ public ProcessingEnvironment getEnv() { return env; } - /** - * Returns true if a call to the given method or constructor does not change any field or array - * element, according to the method's annotations (such as {@link - * org.checkerframework.dataflow.qual.SideEffectFree}) and the command-line options {@code - * -AassumeSideEffectFree}, {@code -AassumePure}, and {@code -AassumePureGetters}. - * - * @param method a method or constructor - * @return true if a call to {@code method} does not change any field or array element - */ - public boolean isSideEffectFree(ExecutableElement method) { - return assumeSideEffectFree - || (assumePureGetters && ElementUtils.isGetter(method)) - || atypeFactory.isSideEffectFree(method); - } - /** * Returns true if the given expressions might evaluate to the same object, judging by their * types: that is, true if the erasure of some bound of one expression's type is a subtype of the diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java index 8874d324bd7d..fe8307436ee9 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java @@ -45,6 +45,7 @@ import org.checkerframework.javacutil.AnnotationBuilder; import org.checkerframework.javacutil.AnnotationUtils; import org.checkerframework.javacutil.BugInCF; +import org.checkerframework.javacutil.ElementUtils; import org.plumelib.util.CollectionsP; import org.plumelib.util.MapsP; import org.plumelib.util.ToStringComparator; @@ -117,6 +118,12 @@ public Map getFieldValues() { */ protected final boolean sequentialSemantics; + /** True if -AassumeSideEffectFree or -AassumePure was passed on the command line. */ + private final boolean assumeSideEffectFree; + + /** True if -AassumePureGetters was passed on the command line. */ + private final boolean assumePureGetters; + /** The unique ID for the next-created object. */ private static final AtomicLong nextUid = new AtomicLong(0); @@ -148,6 +155,10 @@ protected CFAbstractStore(CFAbstractAnalysis analysis, boolean sequenti this.arrayValues = new HashMap<>(); this.classValues = new HashMap<>(); this.sequentialSemantics = sequentialSemantics; + this.assumeSideEffectFree = + analysis.checker.hasOption("assumeSideEffectFree") + || analysis.checker.hasOption("assumePure"); + this.assumePureGetters = analysis.checker.hasOption("assumePureGetters"); } /** @@ -165,6 +176,8 @@ protected CFAbstractStore(CFAbstractStore other) { this.arrayValues = new HashMap<>(other.arrayValues); this.classValues = new HashMap<>(other.classValues); this.sequentialSemantics = other.sequentialSemantics; + this.assumeSideEffectFree = other.assumeSideEffectFree; + this.assumePureGetters = other.assumePureGetters; } /** @@ -222,7 +235,11 @@ public void updateForMethodCall(MethodInvocationNode methodInvocationNode, @Null GenericAnnotatedTypeFactory atypeFactory = analysis.atypeFactory; // Case 1: The method is side-effect-free. - if (!analysis.isSideEffectFree(method)) { + boolean hasSideEffect = + !(assumeSideEffectFree + || (assumePureGetters && ElementUtils.isGetter(method)) + || atypeFactory.isSideEffectFree(method)); + if (hasSideEffect) { boolean sideEffectsUnrefineAliases = atypeFactory.sideEffectsUnrefineAliases; Node receiver = methodInvocationNode.getTarget().getReceiver(); @@ -1346,12 +1363,12 @@ protected void removeConflicting(LocalVariable var) { } /** - * Returns true if the objects {@code a} and {@code b} can be aliases. Returns a conservative - * answer (i.e., returns {@code true} if not enough information is available to determine - * aliasing). - * - *

This implementation does not depend on the contents of the store; see {@link + * Returns true if the objects {@code a} and {@code b} can be aliases, judging by their types. + * This implementation does not depend on the contents of the store; see {@link * CFAbstractAnalysis#canAlias}. + * + *

Contrary to the specification of {@link Store#canAlias}, the answer is not conservative when + * an interface type is involved. See https://github.com/typetools/checker-framework/issues/8558. */ @Override public boolean canAlias(JavaExpression a, JavaExpression b) { From b228a6508d176aeaf459c1a03b47750d19a675c3 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 13 Nov 2026 11:59:50 -0800 Subject: [PATCH 25/73] Use the factory's isSideEffectFree, which CFAbstractAnalysis no longer provides --- .../checkerframework/framework/flow/CFAbstractTransfer.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index d5bb380e5947..754b76e8e4d1 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -1008,7 +1008,7 @@ protected TransferResult strengthenAnnotationOfEqualTo( * * A method call, object creation, or string conversion (which calls {@code toString()}) might * write any field or array element, unless the method or constructor is side-effect-free (see - * {@link CFAbstractAnalysis#isSideEffectFree}). The result omits a field that such a call might + * {@link AnnotatedTypeFactory#isSideEffectFree}). The result omits a field that such a call might * write even when the store would keep the field's refinement across the call, as it does for a * refinement to the target of a monotonic qualifier (see {@link * org.checkerframework.framework.qual.MonotonicQualifier}): whether the store keeps a refinement @@ -1291,7 +1291,7 @@ public Void scan(@Nullable Tree subtree, Void p) { * in {@code @IntVal(value = {0, 1})}, but it does not assign a variable. * *

{@link #mayChange} uses the analysis's rules for aliasing and purity (see {@link - * CFAbstractAnalysis#canAlias} and {@link CFAbstractAnalysis#isSideEffectFree}). + * CFAbstractAnalysis#canAlias} and {@link AnnotatedTypeFactory#isSideEffectFree}). */ private final class WrittenLocations extends TreeScanner { @@ -1372,7 +1372,7 @@ void addOwnWrites(Tree tree) { * @param method a method or constructor that is called */ private void addCall(ExecutableElement method) { - if (!analysis.isSideEffectFree(method)) { + if (!analysis.getTypeFactory().isSideEffectFree(method)) { anyHeapLocation = true; } } From 3add1ec2c2d363fcd47b17bbb739ea327ee7f310 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 13 Nov 2026 12:27:49 -0800 Subject: [PATCH 26/73] Match writes to a static field regardless of receiver; document canAlias on arrays --- .../nullness/AssignmentInComparison.java | 20 +++++++++++++++++++ .../framework/flow/CFAbstractAnalysis.java | 3 ++- .../framework/flow/CFAbstractTransfer.java | 5 ++++- 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/checker/tests/nullness/AssignmentInComparison.java b/checker/tests/nullness/AssignmentInComparison.java index 3d3f4c4cf5e4..6f31e778797d 100644 --- a/checker/tests/nullness/AssignmentInComparison.java +++ b/checker/tests/nullness/AssignmentInComparison.java @@ -141,6 +141,26 @@ static void staticFieldRhs(AssignmentInComparison n) { } } + static class Base { + static @Nullable AssignmentInComparison current; + } + + static class Left extends Base {} + + static class Right extends Base {} + + static void staticFieldThroughSiblingSubclasses() { + if (Right.current == null) { + return; + } + if ((Left.current = Right.current.next) != null) { + // `Left.current` and `Right.current` are the same field, so after the assignment + // `Right.current.next` is a field of a different object. + // :: error: [dereference.of.nullable] + Right.current.next.toString(); + } + } + static void anonymousClassInitializerReassignsReceiver(AssignmentInComparison other) { if (global == null) { return; diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java index c10f811beb86..4f4c34140703 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java @@ -533,7 +533,8 @@ public ProcessingEnvironment getEnv() { *

The answer is not conservative when an interface type is involved. One object can have two * unrelated interface types, such as {@code Runnable} and {@code Serializable}, or a class type * and an unrelated interface type, but this method returns false for expressions of such types. - * See https://github.com/typetools/checker-framework/issues/8558. + * The same holds for arrays whose component types are such types: one {@code Integer[]} can be + * both a {@code Number[]} and a {@code Comparable[]}. See https://github.com/typetools/checker-framework/issues/8558. * *

This compares the erasures of the types, because two parameterizations of a generic type can * denote the same object even if neither is a subtype of the other. For example, a {@code diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 754b76e8e4d1..0a6d48125e9f 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -1524,8 +1524,11 @@ private boolean mayWriteField(FieldAccess fa) { return true; } for (FieldAccess field : fields) { + // A static field is the same location regardless of the receiver. Do not check whether + // the receivers can alias: two subclasses that inherit the static field, such as `Left` + // in `Left.f` and `Right` in `Right.f`, are not related by subtyping. if (field.getField().equals(fa.getField()) - && analysis.canAlias(field.getReceiver(), fa.getReceiver())) { + && (fa.isStatic() || analysis.canAlias(field.getReceiver(), fa.getReceiver()))) { return true; } } From 9162e0ea832f165e13287bb47a9945389f5bb581 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 13 Nov 2026 12:55:16 -0800 Subject: [PATCH 27/73] Test canAlias on arrays of type variables bounded by Object --- .../nullness/ArrayAliasingTypeVariables.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 checker/tests/nullness/ArrayAliasingTypeVariables.java diff --git a/checker/tests/nullness/ArrayAliasingTypeVariables.java b/checker/tests/nullness/ArrayAliasingTypeVariables.java new file mode 100644 index 000000000000..f27b920d2f2f --- /dev/null +++ b/checker/tests/nullness/ArrayAliasingTypeVariables.java @@ -0,0 +1,24 @@ +import org.checkerframework.checker.nullness.qual.Nullable; + +// An array whose element type is a type variable bounded by Object can be the same array as an +// array of any reference type, because a caller can instantiate the type variable to that type. +public class ArrayAliasingTypeVariables { + + static void typeVariableAndClass(@Nullable T[] ts, @Nullable String[] ss) { + if (ss[0] != null) { + ts[0] = null; + // If `ts` and `ss` are the same array, the assignment to `ts[0]` sets `ss[0]` to null. + // :: error: [dereference.of.nullable] + ss[0].length(); + } + } + + static void twoTypeVariables(@Nullable T[] ts, @Nullable S[] ss) { + if (ss[0] != null) { + ts[0] = null; + // If `ts` and `ss` are the same array, the assignment to `ts[0]` sets `ss[0]` to null. + // :: error: [dereference.of.nullable] + ss[0].toString(); + } + } +} From 79d69490ecfebd74b257b6c8a42d583becc17ca7 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 13 Nov 2026 22:40:10 -0800 Subject: [PATCH 28/73] Move canAlias logic to TypesUtils; handle union types and wildcards; add a fast path --- .../nullness/FieldAliasingUnionReceiver.java | 50 ++++++ .../framework/flow/CFAbstractAnalysis.java | 68 +------ .../javacutil/TypesUtils.java | 112 ++++++++++++ .../javacutil/TypesUtilsCanAliasTest.java | 168 ++++++++++++++++++ 4 files changed, 333 insertions(+), 65 deletions(-) create mode 100644 checker/tests/nullness/FieldAliasingUnionReceiver.java create mode 100644 javacutil/src/test/java/org/checkerframework/javacutil/TypesUtilsCanAliasTest.java diff --git a/checker/tests/nullness/FieldAliasingUnionReceiver.java b/checker/tests/nullness/FieldAliasingUnionReceiver.java new file mode 100644 index 000000000000..df693e618a27 --- /dev/null +++ b/checker/tests/nullness/FieldAliasingUnionReceiver.java @@ -0,0 +1,50 @@ +import org.checkerframework.checker.nullness.qual.Nullable; + +// A multi-catch exception parameter can be the same object as an expression whose type is related +// to one of the alternatives, but not as an expression whose type is unrelated to every +// alternative. +public class FieldAliasingUnionReceiver { + + static class Base extends Exception { + @Nullable String f; + } + + static class E1 extends Base {} + + static class E2 extends Base {} + + static class E3 extends Base {} + + static void throwSomething(boolean b) throws E1, E2 { + if (b) { + throw new E1(); + } else { + throw new E2(); + } + } + + static void relatedToAlternative(E1 x, boolean b) { + try { + throwSomething(b); + } catch (E1 | E2 e) { + if (x.f != null) { + e.f = null; + // If `e` and `x` are the same object, the assignment to `e.f` sets `x.f` to null. + // :: error: [dereference.of.nullable] + x.f.length(); + } + } + } + + static void unrelatedToEveryAlternative(E3 x, boolean b) { + try { + throwSomething(b); + } catch (E1 | E2 e) { + if (x.f != null) { + e.f = null; + // `e` is an `E1` or an `E2`, so it is not the same object as `x`, which is an `E3`. + x.f.length(); + } + } + } +} diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java index 6bf911cd43a6..20c6a39ee85c 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java @@ -2,7 +2,6 @@ import com.sun.source.tree.CompilationUnitTree; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.List; @@ -10,11 +9,8 @@ import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; -import javax.lang.model.type.ArrayType; -import javax.lang.model.type.IntersectionType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; -import javax.lang.model.type.TypeVariable; import javax.lang.model.util.Types; import javax.tools.Diagnostic; import org.checkerframework.checker.nullness.qual.Nullable; @@ -515,72 +511,14 @@ public ProcessingEnvironment getEnv() { /** * Returns true if the given expressions might evaluate to the same object, judging by their - * types: that is, true if the erasure of some bound of one expression's type is a subtype of the - * erasure of some bound of the other expression's type, as described below. - * - *

The answer is not conservative when an interface type is involved. One object can have two - * unrelated interface types, such as {@code Runnable} and {@code Serializable}, or a class type - * and an unrelated interface type, but this method returns false for expressions of such types. - * See https://github.com/typetools/checker-framework/issues/8558. - * - *

This compares the erasures of the types, because two parameterizations of a generic type can - * denote the same object even if neither is a subtype of the other. For example, a {@code - * Box} is both a {@code Box} and a {@code Box}. It - * compares every bound of a type variable or intersection type, because the erasure of such a - * type is the erasure of only its first bound. For example, a {@code T[]} where {@code T extends - * Number & Comparable} can be the same array as a {@code Comparable[]}, though {@code - * Number[]} and {@code Comparable[]} are unrelated. + * types. See {@link TypesUtils#canAlias} for details, including the cases in which the answer is + * not conservative. * * @param a an expression * @param b another expression * @return true if {@code a} and {@code b} might evaluate to the same object */ public boolean canAlias(JavaExpression a, JavaExpression b) { - List erasuresA = erasedBounds(a.getType()); - List erasuresB = erasedBounds(b.getType()); - for (TypeMirror ta : erasuresA) { - for (TypeMirror tb : erasuresB) { - if (types.isSubtype(ta, tb) || types.isSubtype(tb, ta)) { - return true; - } - } - } - return false; - } - - /** - * Returns the erasures of the bounds of the given type: for a type variable or intersection type, - * the erasure of each of its bounds, such as {@code Number} and {@code Comparable} for a type - * variable that extends {@code Number & Comparable}; for an array type, an array of each - * erased bound of its component type; and otherwise, the erasure of the type. Every value of the - * type has each of the returned types. - * - * @param type a type - * @return the erasures of the bounds of {@code type} - */ - private List erasedBounds(TypeMirror type) { - switch (type.getKind()) { - case TYPEVAR -> { - return erasedBounds(((TypeVariable) type).getUpperBound()); - } - case INTERSECTION -> { - List result = new ArrayList<>(); - for (TypeMirror bound : ((IntersectionType) type).getBounds()) { - result.addAll(erasedBounds(bound)); - } - return result; - } - case ARRAY -> { - List componentBounds = erasedBounds(((ArrayType) type).getComponentType()); - List result = new ArrayList<>(componentBounds.size()); - for (TypeMirror componentBound : componentBounds) { - result.add(types.getArrayType(componentBound)); - } - return result; - } - default -> { - return Collections.singletonList(types.erasure(type)); - } - } + return TypesUtils.canAlias(a.getType(), b.getType(), types); } } diff --git a/javacutil/src/main/java/org/checkerframework/javacutil/TypesUtils.java b/javacutil/src/main/java/org/checkerframework/javacutil/TypesUtils.java index da7000a8ba92..0ddb7d0a0ffa 100644 --- a/javacutil/src/main/java/org/checkerframework/javacutil/TypesUtils.java +++ b/javacutil/src/main/java/org/checkerframework/javacutil/TypesUtils.java @@ -966,6 +966,118 @@ public static boolean isErasedSubtype(TypeMirror subtype, TypeMirror supertype, return types.isSubtype(types.erasure(subtype), types.erasure(supertype)); } + /** + * Returns true if an expression of type {@code a} and an expression of type {@code b} might + * evaluate to the same object, judging by the types: that is, true if some erased bound of {@code + * a} is a subtype or a supertype of some erased bound of {@code b}. The erased bounds of a type + * variable or wildcard are those of its upper bound; of an intersection type, those of each of + * its bounds; of a union type, those of each of its alternatives; of an array type, an array of + * each erased bound of its component type; and of any other type, its erasure. + * + *

The answer is not conservative when an interface type is involved. One object can have two + * unrelated interface types, such as {@code Runnable} and {@code Serializable}, or a class type + * and an unrelated interface type, but this method returns false for such types. See + * https://github.com/typetools/checker-framework/issues/8558. + * + *

This compares the erasures of the types, because two parameterizations of a generic type can + * denote the same object even if neither is a subtype of the other. For example, a {@code + * Box} is both a {@code Box} and a {@code Box}. + * + *

It compares every bound of a type variable, wildcard, or intersection type, because the + * erasure of such a type is the erasure of only its first bound. For example, a {@code T[]} where + * {@code T extends Number & Comparable} can be the same array as a {@code Comparable[]}, + * though {@code Number[]} and {@code Comparable[]} are unrelated. + * + *

It compares every alternative of a union type, because the erasure of a union type is the + * erasure of the first bound of the alternatives' least upper bound, which is less precise. For + * example, if {@code E1}, {@code E2}, and {@code E3} are subclasses of {@code Base}, then the + * exception parameter {@code e} of {@code catch (E1 | E2 e)} cannot be the same object as an + * expression of type {@code E3}, though the erasure of the type of {@code e} is {@code Base}. + * + * @param a the type of an expression + * @param b the type of another expression + * @param types the type utilities + * @return true if an expression of type {@code a} and an expression of type {@code b} might + * evaluate to the same object + */ + public static boolean canAlias(TypeMirror a, TypeMirror b, Types types) { + if (hasOneErasedBound(a) && hasOneErasedBound(b)) { + // This is the common case. It is equivalent to the general case below, but faster. + TypeMirror erasureA = types.erasure(a); + TypeMirror erasureB = types.erasure(b); + return types.isSubtype(erasureA, erasureB) || types.isSubtype(erasureB, erasureA); + } + List boundsA = erasedBounds(a, types); + List boundsB = erasedBounds(b, types); + for (TypeMirror boundA : boundsA) { + for (TypeMirror boundB : boundsB) { + if (types.isSubtype(boundA, boundB) || types.isSubtype(boundB, boundA)) { + return true; + } + } + } + return false; + } + + /** + * Returns the erased bounds of the given type, as defined in {@link #canAlias}. For example, the + * erased bounds of {@code Number & Comparable} are {@code Number} and {@code Comparable}, and + * those of {@code IOException | SQLException} are {@code IOException} and {@code SQLException}. + * + *

If the given type is a union type, every value of the type has at least one of the returned + * types. Otherwise, every value of the type has each of the returned types. + * + * @param type a type + * @param types the type utilities + * @return the erased bounds of {@code type} + */ + private static List erasedBounds(TypeMirror type, Types types) { + TypeMirror upperBound = upperBound(type); + switch (upperBound.getKind()) { + case INTERSECTION -> { + List result = new ArrayList<>(); + for (TypeMirror bound : ((IntersectionType) upperBound).getBounds()) { + result.addAll(erasedBounds(bound, types)); + } + return result; + } + case UNION -> { + List result = new ArrayList<>(); + for (TypeMirror alternative : ((UnionType) upperBound).getAlternatives()) { + result.addAll(erasedBounds(alternative, types)); + } + return result; + } + case ARRAY -> { + List componentBounds = + erasedBounds(((ArrayType) upperBound).getComponentType(), types); + List result = new ArrayList<>(componentBounds.size()); + for (TypeMirror componentBound : componentBounds) { + result.add(types.getArrayType(componentBound)); + } + return result; + } + default -> { + return List.of(types.erasure(upperBound)); + } + } + } + + /** + * Returns true if the only erased bound of the given type is its erasure. + * + * @param type a type + * @return true if {@link #erasedBounds} returns only the erasure of {@code type} + */ + private static boolean hasOneErasedBound(TypeMirror type) { + TypeMirror upperBound = upperBound(type); + while (upperBound.getKind() == TypeKind.ARRAY) { + upperBound = upperBound(((ArrayType) upperBound).getComponentType()); + } + TypeKind kind = upperBound.getKind(); + return kind != TypeKind.INTERSECTION && kind != TypeKind.UNION; + } + /** * Returns true if unchecked conversion is necessary for {@code source} to be compatible with * {@code target} in a loose invocation context (JLS 5.3). Ignores annotations. diff --git a/javacutil/src/test/java/org/checkerframework/javacutil/TypesUtilsCanAliasTest.java b/javacutil/src/test/java/org/checkerframework/javacutil/TypesUtilsCanAliasTest.java new file mode 100644 index 000000000000..8bbff000f485 --- /dev/null +++ b/javacutil/src/test/java/org/checkerframework/javacutil/TypesUtilsCanAliasTest.java @@ -0,0 +1,168 @@ +package org.checkerframework.javacutil; + +import com.sun.tools.javac.code.Symtab; +import com.sun.tools.javac.code.Type; +import com.sun.tools.javac.code.Type.ClassType; +import com.sun.tools.javac.code.Type.TypeVar; +import com.sun.tools.javac.code.Type.UnionClassType; +import com.sun.tools.javac.main.JavaCompiler; +import com.sun.tools.javac.processing.JavacProcessingEnvironment; +import com.sun.tools.javac.util.Context; +import com.sun.tools.javac.util.Names; +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.type.TypeMirror; +import javax.lang.model.util.Types; +import org.junit.Assert; +import org.junit.Test; + +/** Tests for {@link TypesUtils#canAlias}. */ +public class TypesUtilsCanAliasTest { + + /** Creates a new TypesUtilsCanAliasTest. */ + public TypesUtilsCanAliasTest() {} + + /** The processing environment. All the tests share one, because setting one up is slow. */ + private static final ProcessingEnvironment env; + + /** The javac type utilities, which create intersection types and least upper bounds. */ + private static final com.sun.tools.javac.code.Types javacTypes; + + /** The type utilities. */ + private static final Types types; + + /** The javac name table, which creates the name of a type variable. */ + private static final Names names; + + /** The javac symbol table, which supplies the owner and lower bound of a type variable. */ + private static final Symtab symtab; + + static { + Context context = new Context(); + env = JavacProcessingEnvironment.instance(context); + JavaCompiler javac = JavaCompiler.instance(context); + // The list of modules must be initialized before entering symbols. + javac.initModules(com.sun.tools.javac.util.List.nil()); + javac.enterDone(); + javacTypes = com.sun.tools.javac.code.Types.instance(context); + types = env.getTypeUtils(); + names = Names.instance(context); + symtab = Symtab.instance(context); + } + + /** + * Returns the type of the given class or interface, such as {@code java.lang.Integer}. + * + * @param canonicalName the canonical name of a class or interface + * @return the type of the given class or interface + */ + private static Type type(String canonicalName) { + return (Type) env.getElementUtils().getTypeElement(canonicalName).asType(); + } + + /** + * Returns the intersection of the given types. + * + * @param first the first bound of the intersection type + * @param second the second bound of the intersection type + * @return the intersection type {@code first & second} + */ + private static Type intersection(Type first, Type second) { + return javacTypes.makeIntersectionType(com.sun.tools.javac.util.List.of(first, second)); + } + + /** + * Returns the union of the given types, which is the type of a multi-catch exception parameter. + * + * @param first the first alternative of the union type + * @param second the second alternative of the union type + * @return the union type {@code first | second} + */ + private static TypeMirror union(Type first, Type second) { + ClassType lub = (ClassType) javacTypes.lub(first, second); + return new UnionClassType(lub, com.sun.tools.javac.util.List.of(first, second)); + } + + /** + * Asserts that {@link TypesUtils#canAlias} returns the expected result for the given types, in + * either order. + * + * @param expected the expected result + * @param a a type + * @param b another type + */ + private static void assertCanAlias(boolean expected, TypeMirror a, TypeMirror b) { + Assert.assertEquals(a + " and " + b, expected, TypesUtils.canAlias(a, b, types)); + Assert.assertEquals(b + " and " + a, expected, TypesUtils.canAlias(b, a, types)); + } + + /** Declared types can alias exactly when one is a subtype of the other. */ + @Test + public void declaredTypes() { + assertCanAlias(true, type("java.lang.Integer"), type("java.lang.Number")); + assertCanAlias(false, type("java.lang.Integer"), type("java.lang.String")); + } + + /** + * A union type can alias a type that is related to one of its alternatives, but not a type that + * is unrelated to every alternative, even if that type is related to the alternatives' least + * upper bound. + */ + @Test + public void unionType() { + TypeMirror integerOrLong = union(type("java.lang.Integer"), type("java.lang.Long")); + assertCanAlias(true, integerOrLong, type("java.lang.Integer")); + assertCanAlias(true, integerOrLong, type("java.lang.Number")); + assertCanAlias(true, integerOrLong, type("java.lang.Object")); + // The least upper bound of Integer and Long is Number & Comparable<...> & ..., whose erasure + // is Number, which is a supertype of Double. + assertCanAlias(false, integerOrLong, type("java.lang.Double")); + } + + /** + * Returns a type variable {@code T extends Number & Runnable}. The erasure of {@code T} is {@code + * Number}, which is unrelated to {@code Runnable}. + * + * @return a type variable whose upper bound is {@code Number & Runnable} + */ + private static TypeVar numberAndRunnableTypeVariable() { + TypeVar result = new TypeVar(names.fromString("T"), symtab.noSymbol, symtab.botType); + result.setUpperBound(intersection(type("java.lang.Number"), type("java.lang.Runnable"))); + return result; + } + + /** A type variable can alias a type that is related to any of its bounds. */ + @Test + public void typeVariableWithIntersectionBound() { + TypeMirror typeVariable = numberAndRunnableTypeVariable(); + assertCanAlias(true, typeVariable, type("java.lang.Runnable")); + assertCanAlias(true, typeVariable, type("java.lang.Integer")); + assertCanAlias(false, typeVariable, type("java.lang.String")); + } + + /** A wildcard can alias a type that is related to any bound of its upper bound. */ + @Test + public void wildcardWithIntersectionBound() { + TypeMirror wildcard = types.getWildcardType(numberAndRunnableTypeVariable(), null); + assertCanAlias(true, wildcard, type("java.lang.Runnable")); + assertCanAlias(true, wildcard, type("java.lang.Integer")); + assertCanAlias(false, wildcard, type("java.lang.String")); + } + + /** A wildcard that has no upper bound can alias any reference type. */ + @Test + public void unboundedWildcards() { + TypeMirror unbounded = types.getWildcardType(null, null); + TypeMirror superInteger = types.getWildcardType(null, type("java.lang.Integer")); + assertCanAlias(true, unbounded, type("java.lang.String")); + assertCanAlias(true, superInteger, type("java.lang.String")); + } + + /** An array of a type variable can alias an array of any of the type variable's bounds. */ + @Test + public void arrayOfTypeVariableWithIntersectionBound() { + TypeMirror array = types.getArrayType(numberAndRunnableTypeVariable()); + assertCanAlias(true, array, types.getArrayType(type("java.lang.Runnable"))); + assertCanAlias(true, array, types.getArrayType(type("java.lang.Integer"))); + assertCanAlias(false, array, types.getArrayType(type("java.lang.String"))); + } +} From c3c07b8694974ff0e3a7cb66e3616090900c3bc1 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 13 Nov 2026 23:19:32 -0800 Subject: [PATCH 29/73] Document that canAlias is not conservative for arrays of unrelated types --- .../main/java/org/checkerframework/javacutil/TypesUtils.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/javacutil/src/main/java/org/checkerframework/javacutil/TypesUtils.java b/javacutil/src/main/java/org/checkerframework/javacutil/TypesUtils.java index 0ddb7d0a0ffa..fb62675aaacb 100644 --- a/javacutil/src/main/java/org/checkerframework/javacutil/TypesUtils.java +++ b/javacutil/src/main/java/org/checkerframework/javacutil/TypesUtils.java @@ -976,7 +976,9 @@ public static boolean isErasedSubtype(TypeMirror subtype, TypeMirror supertype, * *

The answer is not conservative when an interface type is involved. One object can have two * unrelated interface types, such as {@code Runnable} and {@code Serializable}, or a class type - * and an unrelated interface type, but this method returns false for such types. See + * and an unrelated interface type, but this method returns false for such types. The same holds + * for arrays whose component types are such types: one {@code Integer[]} can be both a {@code + * Number[]} and a {@code Comparable[]}. See * https://github.com/typetools/checker-framework/issues/8558. * *

This compares the erasures of the types, because two parameterizations of a generic type can From f80904b16e6507668daff5127236e9766b810ef4 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 15 Nov 2026 09:03:00 -0800 Subject: [PATCH 30/73] Parenthesize an operation receiver in MethodCall.toString; nodesWithValueOf omits operations that might change nodesWithValueOf now applies its might-change check to unary and binary operations, not only to expressions that a store can hold. The SameLen Checker relates such operations (e.g., "x" + i) to other expressions, so an operation whose value changes later in the comparison must be omitted. --- .../SameLenComparisonChangesOperand.java | 25 +++++++++++++++++++ .../SameLenMethodCallOnBinaryOperation.java | 23 +++++++++++++++++ .../dataflow/expression/MethodCall.java | 3 +++ .../framework/flow/CFAbstractTransfer.java | 19 ++++++++------ 4 files changed, 63 insertions(+), 7 deletions(-) create mode 100644 checker/tests/index/SameLenComparisonChangesOperand.java create mode 100644 checker/tests/index/SameLenMethodCallOnBinaryOperation.java diff --git a/checker/tests/index/SameLenComparisonChangesOperand.java b/checker/tests/index/SameLenComparisonChangesOperand.java new file mode 100644 index 000000000000..8c88fb87c141 --- /dev/null +++ b/checker/tests/index/SameLenComparisonChangesOperand.java @@ -0,0 +1,25 @@ +// An operand of a length comparison must not be related to the other operand if the comparison +// changes the operand's value after evaluating it. For example, if i is 12, then after the +// comparison in changedLater, s is "ab3" but "x" + i is "x3". + +public class SameLenComparisonChangesOperand { + + void changedLater(int i, String s) { + if (("x" + i).length() == (s = "ab" + (i = 3)).length()) { + String u = "x" + i; + for (int k = 0; k < s.length(); k++) { + // :: error: (argument) + u.charAt(k); + } + } + } + + void unchanged(int i, String s) { + if (("x" + i).length() == s.length()) { + String u = "x" + i; + for (int k = 0; k < s.length(); k++) { + u.charAt(k); + } + } + } +} diff --git a/checker/tests/index/SameLenMethodCallOnBinaryOperation.java b/checker/tests/index/SameLenMethodCallOnBinaryOperation.java new file mode 100644 index 000000000000..1491014fdf31 --- /dev/null +++ b/checker/tests/index/SameLenMethodCallOnBinaryOperation.java @@ -0,0 +1,23 @@ +// A method call whose receiver is a binary operation must not be confused with the binary +// operation whose right operand is the method call: (a + b).trim() and a + b.trim() can differ in +// length. + +public class SameLenMethodCallOnBinaryOperation { + + void differentGrouping(String a, String b) { + String s = (a + b).trim(); + String u = a + b.trim(); + for (int k = 0; k < s.length(); k++) { + // :: error: (argument) + u.charAt(k); + } + } + + void sameGrouping(String a, String b) { + String s = (a + b).trim(); + String u = (a + b).trim(); + for (int k = 0; k < s.length(); k++) { + u.charAt(k); + } + } +} diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/expression/MethodCall.java b/dataflow/src/main/java/org/checkerframework/dataflow/expression/MethodCall.java index e6ee441fbf8e..cb5aa5bb7e85 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/expression/MethodCall.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/expression/MethodCall.java @@ -191,6 +191,9 @@ public String toString() { StringBuilder preParen = new StringBuilder(); if (receiver instanceof ClassName) { preParen.append(receiver.getType()); + } else if (receiver instanceof BinaryOperation || receiver instanceof UnaryOperation) { + // Without parentheses, "(a + b).trim()" would print as "a + b.trim()". + preParen.append('(').append(receiver).append(')'); } else { preParen.append(receiver); } diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 0a6d48125e9f..a02c0001d38b 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -988,12 +988,15 @@ protected TransferResult strengthenAnnotationOfEqualTo( * {@code b}, and {@code c}. Otherwise, the only candidate is {@code node} itself. * *

The result omits each candidate that a store can hold a value for (see {@link - * CFAbstractStore#canInsertJavaExpression}) and that, when the comparison completes, might have a - * different value than {@code node} had when it was evaluated. A candidate's value can change - * when code that is evaluated after the candidate writes a variable, field, or array element that - * the candidate reads. That code is the rest of the assignment, and the code in the enclosing - * expressions that is evaluated after {@code node} and before the comparison completes, such as - * the right operand of the comparison if {@code node} is in its left operand. For example: + * CFAbstractStore#canInsertJavaExpression}), or that is a unary or binary operation, and that, + * when the comparison completes, might have a different value than {@code node} had when it was + * evaluated. (A client such as the SameLen Checker can relate an operation such as {@code "x" + + * i} to other expressions, even though no store holds a value for it.) A candidate's value can + * change when code that is evaluated after the candidate writes a variable, field, or array + * element that the candidate reads. That code is the rest of the assignment, and the code in the + * enclosing expressions that is evaluated after {@code node} and before the comparison completes, + * such as the right operand of the comparison if {@code node} is in its left operand. For + * example: * *

    *
  • The result for {@code n = n.next} is just {@code n}, because after the assignment {@code @@ -1064,7 +1067,9 @@ private List computeNodesWithValueOf(Node node) { List result = new ArrayList<>(candidates.size()); for (Node candidate : candidates) { JavaExpression expr = JavaExpression.fromNode(candidate); - if (CFAbstractStore.canInsertJavaExpression(expr)) { + if (CFAbstractStore.canInsertJavaExpression(expr) + || ((expr instanceof UnaryOperation || expr instanceof BinaryOperation) + && !expr.containsUnknown())) { if (locationsWrittenUntilComparison == null) { locationsWrittenUntilComparison = locationsWrittenUntilComparison(node); } From bf4aa9b8325c916dcf48fa18e7019cd3871da38c Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 15 Nov 2026 17:49:05 -0800 Subject: [PATCH 31/73] canAlias compares the bounds of a wildcard's type parameter; CFAbstractStore.canAlias is final Also fix test Javadoc and rename a misnamed test. --- docs/CHANGELOG.md | 3 + .../framework/flow/CFAbstractAnalysis.java | 4 ++ .../framework/flow/CFAbstractStore.java | 7 +- .../javacutil/TypesUtils.java | 72 +++++++++++++++---- .../javacutil/TypesUtilsCanAliasTest.java | 62 ++++++++++++++-- 5 files changed, 124 insertions(+), 24 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 488e0fc491f1..94f4c75649f3 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -9,6 +9,9 @@ ### Changes for type system implementers +`CFAbstractStore.canAlias` is final. To change the aliasing judgment, override +the new method `CFAbstractAnalysis.canAlias` instead. + ### Closed issues ## Version 4.4.0 (2026-11-02) diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java index 20c6a39ee85c..675703a7824e 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java @@ -514,6 +514,10 @@ public ProcessingEnvironment getEnv() { * types. See {@link TypesUtils#canAlias} for details, including the cases in which the answer is * not conservative. * + *

    {@link CFAbstractStore#canAlias} calls this method, and so does code that has no store. A + * checker that changes the aliasing judgment overrides this method, not {@link + * CFAbstractStore#canAlias}. + * * @param a an expression * @param b another expression * @return true if {@code a} and {@code b} might evaluate to the same object diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java index fe8307436ee9..82b74a708e4e 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractStore.java @@ -1364,14 +1364,15 @@ protected void removeConflicting(LocalVariable var) { /** * Returns true if the objects {@code a} and {@code b} can be aliases, judging by their types. - * This implementation does not depend on the contents of the store; see {@link - * CFAbstractAnalysis#canAlias}. + * This method returns the result of {@link CFAbstractAnalysis#canAlias}, which does not depend on + * the contents of the store. It is final so that every client gets the same answer; a checker + * that changes the aliasing judgment overrides {@link CFAbstractAnalysis#canAlias}. * *

    Contrary to the specification of {@link Store#canAlias}, the answer is not conservative when * an interface type is involved. See https://github.com/typetools/checker-framework/issues/8558. */ @Override - public boolean canAlias(JavaExpression a, JavaExpression b) { + public final boolean canAlias(JavaExpression a, JavaExpression b) { return analysis.canAlias(a, b); } diff --git a/javacutil/src/main/java/org/checkerframework/javacutil/TypesUtils.java b/javacutil/src/main/java/org/checkerframework/javacutil/TypesUtils.java index fb62675aaacb..7a7374b0a8d0 100644 --- a/javacutil/src/main/java/org/checkerframework/javacutil/TypesUtils.java +++ b/javacutil/src/main/java/org/checkerframework/javacutil/TypesUtils.java @@ -970,9 +970,11 @@ public static boolean isErasedSubtype(TypeMirror subtype, TypeMirror supertype, * Returns true if an expression of type {@code a} and an expression of type {@code b} might * evaluate to the same object, judging by the types: that is, true if some erased bound of {@code * a} is a subtype or a supertype of some erased bound of {@code b}. The erased bounds of a type - * variable or wildcard are those of its upper bound; of an intersection type, those of each of - * its bounds; of a union type, those of each of its alternatives; of an array type, an array of - * each erased bound of its component type; and of any other type, its erasure. + * variable are those of its upper bound; of a wildcard, those of its extends bound and those of + * the type parameter that it is a type argument for (or {@code Object}, if neither is known); of + * an intersection type, those of each of its bounds; of a union type, those of each of its + * alternatives; of an array type, an array of each erased bound of its component type; and of any + * other type, its erasure. * *

    The answer is not conservative when an interface type is involved. One object can have two * unrelated interface types, such as {@code Runnable} and {@code Serializable}, or a class type @@ -990,6 +992,11 @@ public static boolean isErasedSubtype(TypeMirror subtype, TypeMirror supertype, * {@code T extends Number & Comparable} can be the same array as a {@code Comparable[]}, * though {@code Number[]} and {@code Comparable[]} are unrelated. * + *

    It compares the bounds of the type parameter that a wildcard is a type argument for, because + * a value of the wildcard has those types too. For example, if {@code Box} is declared as {@code + * class Box}, then the {@code ?} in {@code Box} or in {@code + * Box} can be the same object as a {@code Runnable}. + * *

    It compares every alternative of a union type, because the erasure of a union type is the * erasure of the first bound of the alternatives' least upper bound, which is less precise. For * example, if {@code E1}, {@code E2}, and {@code E3} are subclasses of {@code Base}, then the @@ -1034,25 +1041,47 @@ public static boolean canAlias(TypeMirror a, TypeMirror b, Types types) { * @return the erased bounds of {@code type} */ private static List erasedBounds(TypeMirror type, Types types) { - TypeMirror upperBound = upperBound(type); - switch (upperBound.getKind()) { + switch (type.getKind()) { + case TYPEVAR -> { + TypeMirror upperBound = ((TypeVariable) type).getUpperBound(); + if (upperBound == null) { + return List.of(types.erasure(type)); + } + return erasedBounds(upperBound, types); + } + case WILDCARD -> { + List result = new ArrayList<>(); + TypeMirror extendsBound = ((WildcardType) type).getExtendsBound(); + if (extendsBound != null) { + result.addAll(erasedBounds(extendsBound, types)); + } + // The type parameter is null if the wildcard is from bytecode. + TypeVariable typeParameter = ((Type.WildcardType) type).bound; + if (typeParameter != null) { + result.addAll(erasedBounds(typeParameter, types)); + } + if (result.isEmpty()) { + result.add(types.erasure(type)); + } + return result; + } case INTERSECTION -> { List result = new ArrayList<>(); - for (TypeMirror bound : ((IntersectionType) upperBound).getBounds()) { + for (TypeMirror bound : ((IntersectionType) type).getBounds()) { result.addAll(erasedBounds(bound, types)); } return result; } case UNION -> { List result = new ArrayList<>(); - for (TypeMirror alternative : ((UnionType) upperBound).getAlternatives()) { + for (TypeMirror alternative : ((UnionType) type).getAlternatives()) { result.addAll(erasedBounds(alternative, types)); } return result; } case ARRAY -> { List componentBounds = - erasedBounds(((ArrayType) upperBound).getComponentType(), types); + erasedBounds(((ArrayType) type).getComponentType(), types); List result = new ArrayList<>(componentBounds.size()); for (TypeMirror componentBound : componentBounds) { result.add(types.getArrayType(componentBound)); @@ -1060,24 +1089,37 @@ private static List erasedBounds(TypeMirror type, Types types) { return result; } default -> { - return List.of(types.erasure(upperBound)); + return List.of(types.erasure(type)); } } } /** - * Returns true if the only erased bound of the given type is its erasure. + * Returns true if {@link #erasedBounds} returns only the erasure of the given type. A false + * result means that it might return something else. * * @param type a type * @return true if {@link #erasedBounds} returns only the erasure of {@code type} */ private static boolean hasOneErasedBound(TypeMirror type) { - TypeMirror upperBound = upperBound(type); - while (upperBound.getKind() == TypeKind.ARRAY) { - upperBound = upperBound(((ArrayType) upperBound).getComponentType()); + while (true) { + switch (type.getKind()) { + case TYPEVAR -> { + TypeMirror upperBound = ((TypeVariable) type).getUpperBound(); + if (upperBound == null) { + return true; + } + type = upperBound; + } + case ARRAY -> type = ((ArrayType) type).getComponentType(); + case WILDCARD, INTERSECTION, UNION -> { + return false; + } + default -> { + return true; + } + } } - TypeKind kind = upperBound.getKind(); - return kind != TypeKind.INTERSECTION && kind != TypeKind.UNION; } /** diff --git a/javacutil/src/test/java/org/checkerframework/javacutil/TypesUtilsCanAliasTest.java b/javacutil/src/test/java/org/checkerframework/javacutil/TypesUtilsCanAliasTest.java index 8bbff000f485..c57882a0fb97 100644 --- a/javacutil/src/test/java/org/checkerframework/javacutil/TypesUtilsCanAliasTest.java +++ b/javacutil/src/test/java/org/checkerframework/javacutil/TypesUtilsCanAliasTest.java @@ -1,5 +1,6 @@ package org.checkerframework.javacutil; +import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.ClassType; @@ -62,8 +63,8 @@ private static Type type(String canonicalName) { /** * Returns the intersection of the given types. * - * @param first the first bound of the intersection type - * @param second the second bound of the intersection type + * @param first a type, which becomes the first bound of the intersection type + * @param second another type, which becomes the second bound of the intersection type * @return the intersection type {@code first & second} */ private static Type intersection(Type first, Type second) { @@ -73,8 +74,8 @@ private static Type intersection(Type first, Type second) { /** * Returns the union of the given types, which is the type of a multi-catch exception parameter. * - * @param first the first alternative of the union type - * @param second the second alternative of the union type + * @param first an exception type, which becomes the first alternative of the union type + * @param second another exception type, which becomes the second alternative of the union type * @return the union type {@code first | second} */ private static TypeMirror union(Type first, Type second) { @@ -139,15 +140,64 @@ public void typeVariableWithIntersectionBound() { assertCanAlias(false, typeVariable, type("java.lang.String")); } - /** A wildcard can alias a type that is related to any bound of its upper bound. */ + /** + * A wildcard whose extends bound is a type variable can alias a type that is related to any bound + * of the type variable. + */ @Test - public void wildcardWithIntersectionBound() { + public void wildcardExtendingTypeVariableWithIntersectionBound() { TypeMirror wildcard = types.getWildcardType(numberAndRunnableTypeVariable(), null); assertCanAlias(true, wildcard, type("java.lang.Runnable")); assertCanAlias(true, wildcard, type("java.lang.Integer")); assertCanAlias(false, wildcard, type("java.lang.String")); } + /** + * Returns a wildcard that is a type argument for a type parameter {@code T extends Number & + * Runnable}, as the {@code ?} in {@code Box} is if {@code Box} is declared as {@code class + * Box}. + * + * @param kind a kind of wildcard + * @param bound the extends bound or super bound of the wildcard, or {@code Object} if {@code + * kind} is {@link BoundKind#UNBOUND} + * @return a wildcard whose type parameter's upper bound is {@code Number & Runnable} + */ + private static TypeMirror wildcardForNumberAndRunnableTypeParameter(BoundKind kind, Type bound) { + return new Type.WildcardType(bound, kind, symtab.boundClass, numberAndRunnableTypeVariable()); + } + + /** + * A wildcard that has no extends bound can alias a type that is related to any bound of the type + * parameter that the wildcard is a type argument for. + */ + @Test + public void wildcardWithoutExtendsBoundForTypeParameterWithIntersectionBound() { + TypeMirror unbounded = + wildcardForNumberAndRunnableTypeParameter(BoundKind.UNBOUND, symtab.objectType); + TypeMirror superInteger = + wildcardForNumberAndRunnableTypeParameter(BoundKind.SUPER, type("java.lang.Integer")); + for (TypeMirror wildcard : new TypeMirror[] {unbounded, superInteger}) { + assertCanAlias(true, wildcard, type("java.lang.Runnable")); + assertCanAlias(true, wildcard, type("java.lang.Integer")); + assertCanAlias(false, wildcard, type("java.lang.String")); + } + } + + /** + * A wildcard that has an extends bound can alias a type that is related to the extends bound or + * to any bound of the type parameter that the wildcard is a type argument for. + */ + @Test + public void wildcardWithExtendsBoundForTypeParameterWithIntersectionBound() { + TypeMirror wildcard = + wildcardForNumberAndRunnableTypeParameter( + BoundKind.EXTENDS, type("java.lang.CharSequence")); + assertCanAlias(true, wildcard, type("java.lang.CharSequence")); + assertCanAlias(true, wildcard, type("java.lang.Runnable")); + assertCanAlias(true, wildcard, type("java.lang.Integer")); + assertCanAlias(false, wildcard, type("java.lang.Boolean")); + } + /** A wildcard that has no upper bound can alias any reference type. */ @Test public void unboundedWildcards() { From ade4c68caee6a39a995ae06bb66e6a6727c65327 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 16 Nov 2026 18:44:02 -0800 Subject: [PATCH 32/73] Describe canAlias's comparison of erased types in the changelog --- docs/CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 28a52d6f868d..16f5090fd7f8 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -12,6 +12,12 @@ `CFAbstractStore.canAlias` is final. To change the aliasing judgment, override the new method `CFAbstractAnalysis.canAlias` instead. +`canAlias(a, b)` compares the erasures of the types of `a` and `b`, and every +bound of a type variable, wildcard, or intersection type. It previously +required one type to be a subtype of the other, so it returned false for some +values that can be the same object, such as values whose types are two +different type variables or two parameterizations of a generic class. + New method `GenericAnnotatedTypeFactory.getInput()` returns the transfer input of a block. From 6dd0f64b915085c7ea126b62d09f617727d39e04 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 16 Nov 2026 18:48:49 -0800 Subject: [PATCH 33/73] A write before an assignment's store does not change the target's stored value --- .../nonempty/AssignmentInComparison.java | 22 +++++++++++++++++++ .../framework/flow/CFAbstractTransfer.java | 7 ++++-- 2 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 checker/tests/nonempty/AssignmentInComparison.java diff --git a/checker/tests/nonempty/AssignmentInComparison.java b/checker/tests/nonempty/AssignmentInComparison.java new file mode 100644 index 000000000000..5f31bd64008b --- /dev/null +++ b/checker/tests/nonempty/AssignmentInComparison.java @@ -0,0 +1,22 @@ +import java.util.ArrayList; +import java.util.List; +import org.checkerframework.checker.nonempty.qual.NonEmpty; + +// The Non-Empty Checker unrefines aliases at a side effect. A call in the right-hand side of an +// assignment does not change the value that the assignment stores, so comparing the assignment +// refines its target. +class AssignmentInComparison { + + List list = new ArrayList<>(); + + // Not side-effect-free. + List newList() { + return new ArrayList<>(); + } + + static void callInRhs(AssignmentInComparison h, @NonEmpty List ne) { + if ((h.list = h.newList()) == ne) { + @NonEmpty List l = h.list; + } + } +} diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 39511a9bb82a..7f92f13d9669 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -1476,11 +1476,14 @@ public Void visitClass(ClassTree tree, Void p) { * value than evaluating it before */ boolean mayChange(JavaExpression expr, boolean ignoreOwnLocation) { - if (anyHeapLocation + if (!ignoreOwnLocation + && anyHeapLocation && analysis.atypeFactory.sideEffectsUnrefineAliases && expr.isModifiableByOtherCode()) { // As in CFAbstractStore#updateForMethodCall, a write might change the abstract value of - // the object that `expr` denotes, even if `expr` still denotes the same object. + // the object that `expr` denotes, even if `expr` still denotes the same object. If + // `ignoreOwnLocation` is true, the value of `expr` is stored into its location after these + // writes, so its abstract value is the one that was stored. return true; } if (expr instanceof LocalVariable) { From 0cca2ccb5c10ce929649ebba5d59c063c32bdd6b Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 16 Nov 2026 18:50:42 -0800 Subject: [PATCH 34/73] Test comparisons whose later operand changes the earlier one --- .../nullness/AssignmentInComparison.java | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/checker/tests/nullness/AssignmentInComparison.java b/checker/tests/nullness/AssignmentInComparison.java index 6f31e778797d..eb294b39e528 100644 --- a/checker/tests/nullness/AssignmentInComparison.java +++ b/checker/tests/nullness/AssignmentInComparison.java @@ -374,6 +374,92 @@ static void arrayTargetTypeVariable(@Nullable T[] ts, @Nullable String[][] s } } + static Object nonNull(@Nullable Object o) { + return ""; + } + + // The right operand assigns `x` after the left operand reads it, so the comparison says nothing + // about the new value of `x`. + void assignmentInRightOperand(@Nullable Object x) { + if (x == nonNull(x = null)) { + // :: error: [dereference.of.nullable] + x.toString(); + } + } + + void assignmentInParenthesizedRightOperand(@Nullable Object x) { + if ((x) == (nonNull(x = null))) { + // :: error: [dereference.of.nullable] + x.toString(); + } + } + + void fieldAssignmentInRightOperand(AssignmentInComparison n) { + if (n.next == nonNull(n.next = null)) { + // :: error: [dereference.of.nullable] + n.next.toString(); + } + } + + void aliasedFieldAssignmentInRightOperand(AssignmentInComparison n, AssignmentInComparison o) { + // If `n` and `o` alias, the right operand assigns `n.next`. + if (n.next == nonNull(o.next = null)) { + // :: error: [dereference.of.nullable] + n.next.toString(); + } + } + + void aliasedArrayAssignmentInRightOperand(@Nullable Object[] a, @Nullable Object[] b) { + // If `a` and `b` alias, the right operand assigns `a[0]`. + if (a[0] == nonNull(b[0] = null)) { + // :: error: [dereference.of.nullable] + a[0].toString(); + } + } + + // The left operand assigns `x` before the right operand reads it, so refining `x` is sound. + void assignmentInLeftOperand(@Nullable Object x) { + if (nonNull(x = null) == x) { + x.toString(); + } + } + + @Nullable String f; + + // Sets `f` to null and returns its old value, or a non-null value. + String reset() { + String result = (f == null) ? "" : f; + f = null; + return result; + } + + @Pure + String constant() { + return ""; + } + + // The right operand calls a method that might change `f` after the left operand reads it. + void methodWithSideEffectsInRightOperand() { + if (f == reset()) { + // :: error: [dereference.of.nullable] + f.toString(); + } + } + + // A method call cannot change a local variable. + void methodWithSideEffectsInRightOperandLocal(@Nullable String s) { + if (s == reset()) { + s.toString(); + } + } + + // A side-effect-free call in the right operand does not change `f`. + void sideEffectFreeCallInRightOperand() { + if (f == constant()) { + f.toString(); + } + } + static void annotationArgumentInRhs( @Nullable Object o, @Nullable Object p, Map m) { // The annotation argument `"m"` is not an assignment to a variable. From fe5ca1abb1d9c735b0b1bdbf9d71e9f3ada20b83 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 16 Nov 2026 18:54:54 -0800 Subject: [PATCH 35/73] MethodCall.toString parenthesizes a receiver that is a unary or binary operation --- .../SameLenMethodCallOnBinaryOperation.java | 23 +++++++++++++++++++ .../dataflow/expression/MethodCall.java | 3 +++ 2 files changed, 26 insertions(+) create mode 100644 checker/tests/index/SameLenMethodCallOnBinaryOperation.java diff --git a/checker/tests/index/SameLenMethodCallOnBinaryOperation.java b/checker/tests/index/SameLenMethodCallOnBinaryOperation.java new file mode 100644 index 000000000000..1491014fdf31 --- /dev/null +++ b/checker/tests/index/SameLenMethodCallOnBinaryOperation.java @@ -0,0 +1,23 @@ +// A method call whose receiver is a binary operation must not be confused with the binary +// operation whose right operand is the method call: (a + b).trim() and a + b.trim() can differ in +// length. + +public class SameLenMethodCallOnBinaryOperation { + + void differentGrouping(String a, String b) { + String s = (a + b).trim(); + String u = a + b.trim(); + for (int k = 0; k < s.length(); k++) { + // :: error: (argument) + u.charAt(k); + } + } + + void sameGrouping(String a, String b) { + String s = (a + b).trim(); + String u = (a + b).trim(); + for (int k = 0; k < s.length(); k++) { + u.charAt(k); + } + } +} diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/expression/MethodCall.java b/dataflow/src/main/java/org/checkerframework/dataflow/expression/MethodCall.java index e6ee441fbf8e..2af060a80f8b 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/expression/MethodCall.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/expression/MethodCall.java @@ -191,6 +191,9 @@ public String toString() { StringBuilder preParen = new StringBuilder(); if (receiver instanceof ClassName) { preParen.append(receiver.getType()); + } else if (receiver instanceof BinaryOperation || receiver instanceof UnaryOperation) { + // Without parentheses, `("a" + s).length()` would be printed as `"a" + s.length()`. + preParen.append('(').append(receiver).append(')'); } else { preParen.append(receiver); } From ac967f545f5e187091282e1643ba55e543c6775e Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 16 Nov 2026 20:05:41 -0800 Subject: [PATCH 36/73] Test the target-value guard with a local variable target --- checker/tests/nonempty/AssignmentInComparison.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/checker/tests/nonempty/AssignmentInComparison.java b/checker/tests/nonempty/AssignmentInComparison.java index 5f31bd64008b..33cc42ff6c2b 100644 --- a/checker/tests/nonempty/AssignmentInComparison.java +++ b/checker/tests/nonempty/AssignmentInComparison.java @@ -7,16 +7,15 @@ // refines its target. class AssignmentInComparison { - List list = new ArrayList<>(); - // Not side-effect-free. List newList() { return new ArrayList<>(); } - static void callInRhs(AssignmentInComparison h, @NonEmpty List ne) { - if ((h.list = h.newList()) == ne) { - @NonEmpty List l = h.list; + void callInRhs(@NonEmpty List ne) { + List l; + if ((l = newList()) == ne) { + @NonEmpty List m = l; } } } From d5db43c8ea1468385afb2d142dac4a3905eecbc1 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Tue, 17 Nov 2026 08:24:02 -0800 Subject: [PATCH 37/73] Check operation sides of an assignment chain and symbolic offsets for later writes sidesOfAssignment omits a unary or binary rhs that the chain changes, as in (s = "x" + s), matching nodesWithValueOf. The Upper Bound transfer uses a symbolic offset only if its node keeps its value until the comparison completes; otherwise it uses the offset's constant value, if any. --- .../index/upperbound/UpperBoundTransfer.java | 42 +++++++++++++++++-- .../tests/index/AssignmentInComparison.java | 16 +++++++ .../SameLenComparisonChangesOperand.java | 14 +++++++ .../framework/flow/CFAbstractTransfer.java | 36 +++++++++++----- 4 files changed, 95 insertions(+), 13 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java index a4206adc010a..9de070a5909b 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java @@ -258,7 +258,7 @@ private void propagateToSubtractionOperands( TransferInput in, CFStore store) { UBQualifier left = getUBQualifier(node.getLeftOperand(), in); - UBQualifier newInfo = typeOfSubtraction.minusOffset(node.getRightOperand(), atypeFactory); + UBQualifier newInfo = offsetByComparedNode(typeOfSubtraction, node.getRightOperand(), '-'); UBQualifier newLeft = left.glb(newInfo); insertValueForComparedNode( @@ -284,7 +284,7 @@ private void propagateToAdditionOperand( TransferInput in, CFStore store) { UBQualifier operandQual = getUBQualifier(operand, in); - UBQualifier newQual = operandQual.glb(typeOfAddition.plusOffset(other, atypeFactory)); + UBQualifier newQual = operandQual.glb(offsetByComparedNode(typeOfAddition, other, '+')); // If the node is NonNegative, add an LTEL to the qual. If Positive, add an LTL. if (atypeFactory.hasLowerBoundTypeByClass(other, Positive.class)) { @@ -296,6 +296,42 @@ private void propagateToAdditionOperand( store, operand, atypeFactory.convertUBQualifierToAnnotation(newQual)); } + /** + * Returns {@code qualifier} plus or minus the value of {@code offsetNode}, for a qualifier that + * will be inserted into the store after the comparison that contains {@code offsetNode} + * completes. + * + *

    A symbolic offset such as {@code z} denotes the value of {@code z} at the point where the + * store is used, but the fact being recorded is about the value that {@code offsetNode} had when + * it was evaluated. If that value might change before the comparison completes, as {@code z} + * does in {@code (x = y) + z < (z = a.length)}, then this method uses only the compile-time + * constant value of {@code offsetNode}, if there is one, and otherwise returns UNKNOWN. + * + * @param qualifier the qualifier to offset + * @param offsetNode a node in an operand of a comparison, whose value is the offset + * @param op '+' to add the value of {@code offsetNode}, or '-' to subtract it + * @return {@code qualifier} plus or minus the value of {@code offsetNode} + */ + private UBQualifier offsetByComparedNode(UBQualifier qualifier, Node offsetNode, char op) { + if (nodesWithValueOf(offsetNode).contains(offsetNode)) { + return op == '+' + ? qualifier.plusOffset(offsetNode, atypeFactory) + : qualifier.minusOffset(offsetNode, atypeFactory); + } + Tree offsetTree = offsetNode.getTree(); + if (offsetTree == null || !TreeUtils.isExpressionTree(offsetTree)) { + return UpperBoundUnknownQualifier.UNKNOWN; + } + Long value = + ValueCheckerUtils.getExactValue(offsetTree, atypeFactory.getValueAnnotatedTypeFactory()); + if (value == null || value <= Integer.MIN_VALUE || value > Integer.MAX_VALUE) { + return UpperBoundUnknownQualifier.UNKNOWN; + } + return op == '+' + ? qualifier.plusOffset(value.intValue()) + : qualifier.minusOffset(value.intValue()); + } + /** * Case 8: if x < y, and y has a type that is related to the length of an array, then x has the * same type, with an offset that is one less. @@ -386,7 +422,7 @@ private void refineSubtrahendWithOffset( UBQualifier newQual = subtrahendQual.glb( - minuendQual.plusOffset(offsetNode, atypeFactory).plusOffset(offsetAddOne ? 1 : 0)); + offsetByComparedNode(minuendQual, offsetNode, '+').plusOffset(offsetAddOne ? 1 : 0)); insertValueForComparedNode( store, subtrahend, atypeFactory.convertUBQualifierToAnnotation(newQual)); } diff --git a/checker/tests/index/AssignmentInComparison.java b/checker/tests/index/AssignmentInComparison.java index 3436565b2c31..421734852945 100644 --- a/checker/tests/index/AssignmentInComparison.java +++ b/checker/tests/index/AssignmentInComparison.java @@ -1,3 +1,4 @@ +import org.checkerframework.checker.index.qual.LTLengthOf; import org.checkerframework.checker.index.qual.NonNegative; import org.checkerframework.checker.index.qual.Positive; import org.checkerframework.checker.index.qual.SameLen; @@ -51,6 +52,21 @@ static void otherOperandReassignsLeftOperand(@NonNegative int i) { } } + static void otherOperandReassignsOffset(int[] a, int x, int y, int z) { + if ((x = y) + z < (z = a.length)) { + // `z` is `a.length`, not the value that was added to `x`. + // :: error: [assignment] + @LTLengthOf(value = "a", offset = "z") int w = x; + } + } + + static void offsetUnchanged(int[] a, int x, int y, int z) { + if ((x = y) + z < a.length) { + @LTLengthOf(value = "a", offset = "z") int w = x; + @LTLengthOf(value = "a", offset = "z") int v = y; + } + } + void otherOperandReassignsLengthReceiver(int[] b, int[] c) { if ((this.arr = b).length == setArr(c).length) { // `setArr` sets `this.arr` to `c`, which might not have the same length as `b`. diff --git a/checker/tests/index/SameLenComparisonChangesOperand.java b/checker/tests/index/SameLenComparisonChangesOperand.java index 8c88fb87c141..8843c6d3ea03 100644 --- a/checker/tests/index/SameLenComparisonChangesOperand.java +++ b/checker/tests/index/SameLenComparisonChangesOperand.java @@ -14,6 +14,20 @@ void changedLater(int i, String s) { } } + // If s is "a" and t is "bb", then after the comparison s is "xa", but "x" + s is "xxa". + void assignmentChangesItsRhs(String s, String t) { + if ((s = "x" + s).length() == t.length()) { + String u = "x" + s; + for (int k = 0; k < u.length(); k++) { + // :: error: (argument) + t.charAt(k); + } + for (int k = 0; k < s.length(); k++) { + t.charAt(k); + } + } + } + void unchanged(int i, String s) { if (("x" + i).length() == s.length()) { String u = "x" + i; diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 7f92f13d9669..0be3a9e08f1b 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -1067,9 +1067,7 @@ private List computeNodesWithValueOf(Node node) { List result = new ArrayList<>(candidates.size()); for (Node candidate : candidates) { JavaExpression expr = JavaExpression.fromNode(candidate); - if (CFAbstractStore.canInsertJavaExpression(expr) - || ((expr instanceof UnaryOperation || expr instanceof BinaryOperation) - && !expr.containsUnknown())) { + if (isCheckedForChanges(expr)) { if (locationsWrittenUntilComparison == null) { locationsWrittenUntilComparison = locationsWrittenUntilComparison(node); } @@ -1091,8 +1089,9 @@ private List computeNodesWithValueOf(Node node) { * assignment, and so on. For example, {@code a = b = c} is parsed as {@code a = (b = c)}, and its * chain is {@code a = (b = c)} and {@code b = c}. The sides are the targets of the assignments in * the chain, such as {@code a} and {@code b}, and the rhs of the last assignment in the chain, - * such as {@code c}. The result omits each side that a store can hold a value for and whose value - * the rest of the chain might change. + * such as {@code c}. The result omits each side whose value the rest of the chain might change + * and that a store can hold a value for or that is a unary or binary operation (see {@link + * #mayBeChanged}). For example, the result for {@code s = "x" + s} is just {@code s}. * * @param assignment an assignment node * @return the sides of {@code assignment} that have its value when it completes, in source order @@ -1148,8 +1147,11 @@ private List sidesOfAssignment(AssignmentNode assignment) { } /** - * Returns true if a store can hold a value for the given side of a chain of assignments, and - * writing the given locations might change the side's value. + * Returns true if a store can hold a value for the given side of a chain of assignments, or the + * side is a unary or binary operation that does not contain {@link Unknown}, and writing the + * given locations might change the side's value. As in {@link #computeNodesWithValueOf}, an + * operation is checked because a client such as the SameLen Checker can relate it to other + * expressions. * * @param side a side of a chain of assignments (see {@link #sidesOfAssignment}): an entire * target, such as {@code a[i]} (not {@code a} or {@code i}), or the entire rhs of the last @@ -1160,12 +1162,26 @@ private List sidesOfAssignment(AssignmentNode assignment) { * side} is a target, the chain later stores its value into that location, and if {@code side} * is the rhs, the write either happens before {@code side} reads the location or stores the * value that {@code side} read. - * @return true if a store can hold a value for {@code side} and writing {@code written} might - * change its value + * @return true if a store can hold a value for {@code side} or it is an operation that does not + * contain {@link Unknown}, and writing {@code written} might change its value */ private boolean mayBeChanged(Node side, WrittenLocations written) { JavaExpression expr = JavaExpression.fromNode(side); - return CFAbstractStore.canInsertJavaExpression(expr) && written.mayChange(expr, true); + return isCheckedForChanges(expr) && written.mayChange(expr, true); + } + + /** + * Returns true if {@link #nodesWithValueOf} omits the given expression when its value might + * change: that is, if a store can hold a value for it, or it is a unary or binary operation that + * does not contain {@link Unknown}. + * + * @param expr an expression + * @return true if {@link #nodesWithValueOf} omits {@code expr} when its value might change + */ + private static boolean isCheckedForChanges(JavaExpression expr) { + return CFAbstractStore.canInsertJavaExpression(expr) + || ((expr instanceof UnaryOperation || expr instanceof BinaryOperation) + && !expr.containsUnknown()); } /** From a483d6076c56dfd1e74bf29d6e0c236f46e79f63 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 20 Nov 2026 12:10:40 -0800 Subject: [PATCH 38/73] Require deterministic symbolic offsets; account for record accessor calls; strengthen array aliasing test --- .../index/upperbound/UpperBoundTransfer.java | 9 ++- .../tests/index/AssignmentInComparison.java | 25 +++++++ .../nullness/AssignmentInComparison.java | 5 +- .../ComparisonRecordPatternAccessor.java | 73 +++++++++++++++++++ .../framework/flow/CFAbstractTransfer.java | 41 +++++++++-- 5 files changed, 141 insertions(+), 12 deletions(-) create mode 100644 checker/tests/nullness/java21/ComparisonRecordPatternAccessor.java diff --git a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java index 9de070a5909b..1c8ce8e34f09 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java @@ -304,8 +304,10 @@ private void propagateToAdditionOperand( *

    A symbolic offset such as {@code z} denotes the value of {@code z} at the point where the * store is used, but the fact being recorded is about the value that {@code offsetNode} had when * it was evaluated. If that value might change before the comparison completes, as {@code z} - * does in {@code (x = y) + z < (z = a.length)}, then this method uses only the compile-time - * constant value of {@code offsetNode}, if there is one, and otherwise returns UNKNOWN. + * does in {@code (x = y) + z < (z = a.length)}, or if it is not deterministic, as {@code choose()} + * is in {@code (x = y) + choose() < a.length} for a nondeterministic method {@code choose}, then + * this method uses only the compile-time constant value of {@code offsetNode}, if there is one, + * and otherwise returns UNKNOWN. * * @param qualifier the qualifier to offset * @param offsetNode a node in an operand of a comparison, whose value is the offset @@ -313,7 +315,8 @@ private void propagateToAdditionOperand( * @return {@code qualifier} plus or minus the value of {@code offsetNode} */ private UBQualifier offsetByComparedNode(UBQualifier qualifier, Node offsetNode, char op) { - if (nodesWithValueOf(offsetNode).contains(offsetNode)) { + if (nodesWithValueOf(offsetNode).contains(offsetNode) + && JavaExpression.fromNode(offsetNode).isDeterministic(atypeFactory)) { return op == '+' ? qualifier.plusOffset(offsetNode, atypeFactory) : qualifier.minusOffset(offsetNode, atypeFactory); diff --git a/checker/tests/index/AssignmentInComparison.java b/checker/tests/index/AssignmentInComparison.java index 421734852945..d255ba1cda0e 100644 --- a/checker/tests/index/AssignmentInComparison.java +++ b/checker/tests/index/AssignmentInComparison.java @@ -3,6 +3,7 @@ import org.checkerframework.checker.index.qual.Positive; import org.checkerframework.checker.index.qual.SameLen; import org.checkerframework.dataflow.qual.Pure; +import org.checkerframework.dataflow.qual.SideEffectFree; // A comparison of an assignment refines only the sides that have the assigned value afterward. public class AssignmentInComparison { @@ -67,6 +68,30 @@ static void offsetUnchanged(int[] a, int x, int y, int z) { } } + @SideEffectFree + static int choose() { + return (int) System.nanoTime(); + } + + @Pure + static int deterministic() { + return 1; + } + + static void nondeterministicOffset(int[] a, int x, int y) { + if ((x = y) + choose() < a.length) { + // Another call to `choose()` might return a different value than the one added to `x`. + // :: error: [assignment] + @LTLengthOf(value = "a", offset = "choose()") int w = x; + } + } + + static void deterministicOffset(int[] a, int x, int y) { + if ((x = y) + deterministic() < a.length) { + @LTLengthOf(value = "a", offset = "deterministic()") int w = x; + } + } + void otherOperandReassignsLengthReceiver(int[] b, int[] c) { if ((this.arr = b).length == setArr(c).length) { // `setArr` sets `this.arr` to `c`, which might not have the same length as `b`. diff --git a/checker/tests/nullness/AssignmentInComparison.java b/checker/tests/nullness/AssignmentInComparison.java index eb294b39e528..6747eaf65db0 100644 --- a/checker/tests/nullness/AssignmentInComparison.java +++ b/checker/tests/nullness/AssignmentInComparison.java @@ -364,9 +364,8 @@ static void fieldTargetWithAssignmentInReceiver( return o; } - @SuppressWarnings("unchecked") // cast to T - static void arrayTargetTypeVariable(@Nullable T[] ts, @Nullable String[][] ss) { - if ((ts[0] = (T) ss[0][0]) != null) { + static void arrayTargetTypeVariable(@Nullable T[] ts, @Nullable T[][] ss) { + if ((ts[0] = ss[0][0]) != null) { ts[0].toString(); // The assignment to `ts[0]` might change `ss[0]`, if `ts` and `ss` alias. // :: error: [dereference.of.nullable] diff --git a/checker/tests/nullness/java21/ComparisonRecordPatternAccessor.java b/checker/tests/nullness/java21/ComparisonRecordPatternAccessor.java new file mode 100644 index 000000000000..7fbd2d4f6d26 --- /dev/null +++ b/checker/tests/nullness/java21/ComparisonRecordPatternAccessor.java @@ -0,0 +1,73 @@ +// @below-java21-jdk-skip-test + +// None of the WPI formats supports the new Java 21 language features, so skip inference until they +// do. +// @infer-jaifs-skip-test +// @infer-ajava-skip-test +// @infer-stubs-skip-test + +import org.checkerframework.checker.nullness.qual.Nullable; +import org.checkerframework.dataflow.qual.Pure; + +// Matching a record pattern calls the record's component accessors, which might write fields. +public class ComparisonRecordPatternAccessor { + + static @Nullable String g; + + record Impure(String x) { + public String x() { + g = null; + return x; + } + } + + record Pure1(String x) { + @Pure + public String x() { + return x; + } + } + + record Outer(Impure inner) { + @Pure + public Impure inner() { + return inner; + } + } + + void impureAccessorInSwitch(Impure r, String expected) { + if (g == (switch (r) { + case Impure(var x) -> expected; + })) { + // The accessor `x()` is called after `g` is read, and it sets `g` to null. + // :: error: [dereference.of.nullable] + g.toString(); + } + } + + void impureAccessorInInstanceof(Object o) { + if (g == (o instanceof Impure(var x) ? "a" : "b")) { + // The accessor `x()` is called after `g` is read, and it sets `g` to null. + // :: error: [dereference.of.nullable] + g.toString(); + } + } + + void impureAccessorInNestedPattern(Outer o, String expected) { + if (g == (switch (o) { + case Outer(Impure(var x)) -> expected; + })) { + // The accessor `x()` is called after `g` is read, and it sets `g` to null. + // :: error: [dereference.of.nullable] + g.toString(); + } + } + + void pureAccessor(Pure1 r, String expected) { + if (g == (switch (r) { + case Pure1(var x) -> expected; + })) { + g.toString(); + } + } +} diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 0be3a9e08f1b..743aac9756b2 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -29,6 +29,7 @@ import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.RecordComponentElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeKind; @@ -1009,8 +1010,9 @@ protected TransferResult strengthenAnnotationOfEqualTo( * evaluated before {@code b[i]}. *

* - * A method call, object creation, or string conversion (which calls {@code toString()}) might - * write any field or array element, unless the method or constructor is side-effect-free (see + * A method call, object creation, string conversion (which calls {@code toString()}), or record + * pattern (which calls record component accessors) might write any field or array element, unless + * the method or constructor is side-effect-free (see * {@link AnnotatedTypeFactory#isSideEffectFree}). The result omits a field that such a call might * write even when the store would keep the field's refinement across the call, as it does for a * refinement to the target of a monotonic qualifier (see {@link @@ -1300,9 +1302,10 @@ public Void scan(@Nullable Tree subtree, Void p) { * field, or an array element, such as {@code x}, {@code o.f}, or {@code a[i]}. {@link #add} adds * a write to a given location, and {@link #scan} adds the writes that evaluating a tree might * perform: its assignments, compound assignments, increments, decrements, method calls, object - * creations, and string conversions. A method call, object creation, or string conversion (which - * calls {@code toString()}) might write every non-final field and every array element, unless the - * method or constructor is side-effect-free; {@link #anyHeapLocation} records that. + * creations, string conversions, and record patterns. A method call, object creation, string + * conversion (which calls {@code toString()}), or record pattern (which calls record component + * accessors) might write every non-final field and every array element, unless the method or + * constructor is side-effect-free; {@link #anyHeapLocation} records that. * *

{@link #scan} does not descend into lambda bodies or class bodies, because they do not * execute when the tree is evaluated. The writes of such a body to fields and array elements are @@ -1357,7 +1360,8 @@ void add(JavaExpression target) { /** * Adds the writes that the given tree performs itself, after its subtrees are evaluated: the * write of an assignment, compound assignment, increment, or decrement, and the writes of a - * method call, object creation, or string conversion. Does not add the writes of the subtrees. + * method call, object creation, string conversion, or record pattern. Does not add the writes + * of the subtrees. * * @param tree a tree */ @@ -1384,6 +1388,31 @@ void addOwnWrites(Tree tree) { addCall(TreeUtils.elementFromUse(newClassTree)); } else if (tree instanceof BinaryTree binaryTree && tree.getKind() == Tree.Kind.PLUS) { addStringConversions(binaryTree.getLeftOperand(), binaryTree.getRightOperand()); + } else if (TreeUtils.isDeconstructionPatternTree(tree)) { + addRecordAccessorCalls(tree); + } + } + + /** + * Adds the writes of the calls to record component accessors that matching the given record + * pattern performs, such as the call to {@code x()} when matching {@code R(var x)}. The writes + * of nested record patterns are added when they are scanned. + * + * @param deconstructionPattern a record pattern (a {@code DeconstructionPatternTree}) + */ + private void addRecordAccessorCalls(Tree deconstructionPattern) { + TypeElement record = TypesUtils.getTypeElement(TreeUtils.typeOf(deconstructionPattern)); + if (record == null || record.getKind() != ElementKind.RECORD) { + anyHeapLocation = true; + return; + } + for (RecordComponentElement component : record.getRecordComponents()) { + ExecutableElement accessor = component.getAccessor(); + if (accessor == null) { + anyHeapLocation = true; + } else { + addCall(accessor); + } } } From c0cb6b341711b2d4878ea268afb9d209228eac16 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 20 Nov 2026 20:38:53 -0800 Subject: [PATCH 39/73] Clarify canAlias documentation and changelog entry; test a union type against Comparable --- docs/CHANGELOG.md | 12 +-- .../javacutil/TypesUtils.java | 93 +++++++++++-------- .../javacutil/TypesUtilsCanAliasTest.java | 3 + 3 files changed, 62 insertions(+), 46 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 16f5090fd7f8..1d479bf355a1 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -9,14 +9,10 @@ ### Changes for type system implementers -`CFAbstractStore.canAlias` is final. To change the aliasing judgment, override -the new method `CFAbstractAnalysis.canAlias` instead. - -`canAlias(a, b)` compares the erasures of the types of `a` and `b`, and every -bound of a type variable, wildcard, or intersection type. It previously -required one type to be a subtype of the other, so it returned false for some -values that can be the same object, such as values whose types are two -different type variables or two parameterizations of a generic class. +`CFAbstractStore.canAlias()` is now final. It calls the new method +`CFAbstractAnalysis.canAlias()`, which calls the new method +`TypesUtils.canAlias()`. To change the aliasing judgment, override +`CFAbstractAnalysis.canAlias()`. New method `GenericAnnotatedTypeFactory.getInput()` returns the transfer input of a block. diff --git a/javacutil/src/main/java/org/checkerframework/javacutil/TypesUtils.java b/javacutil/src/main/java/org/checkerframework/javacutil/TypesUtils.java index 5836101a0e78..05eea49d5948 100644 --- a/javacutil/src/main/java/org/checkerframework/javacutil/TypesUtils.java +++ b/javacutil/src/main/java/org/checkerframework/javacutil/TypesUtils.java @@ -981,39 +981,30 @@ public static boolean isErasedSubtype(TypeMirror subtype, TypeMirror supertype, /** * Returns true if an expression of type {@code a} and an expression of type {@code b} might * evaluate to the same object, judging by the types: that is, true if some erased bound of {@code - * a} is a subtype or a supertype of some erased bound of {@code b}. The erased bounds of a type - * variable are those of its upper bound; of a wildcard, those of its extends bound and those of - * the type parameter that it is a type argument for (or {@code Object}, if neither is known); of - * an intersection type, those of each of its bounds; of a union type, those of each of its - * alternatives; of an array type, an array of each erased bound of its component type; and of any - * other type, its erasure. - * - *

The answer is not conservative when an interface type is involved. One object can have two - * unrelated interface types, such as {@code Runnable} and {@code Serializable}, or a class type - * and an unrelated interface type, but this method returns false for such types. The same holds - * for arrays whose component types are such types: one {@code Integer[]} can be both a {@code - * Number[]} and a {@code Comparable[]}. See - * https://github.com/typetools/checker-framework/issues/8558. - * - *

This compares the erasures of the types, because two parameterizations of a generic type can - * denote the same object even if neither is a subtype of the other. For example, a {@code - * Box} is both a {@code Box} and a {@code Box}. - * - *

It compares every bound of a type variable, wildcard, or intersection type, because the - * erasure of such a type is the erasure of only its first bound. For example, a {@code T[]} where - * {@code T extends Number & Comparable} can be the same array as a {@code Comparable[]}, - * though {@code Number[]} and {@code Comparable[]} are unrelated. - * - *

It compares the bounds of the type parameter that a wildcard is a type argument for, because - * a value of the wildcard has those types too. For example, if {@code Box} is declared as {@code - * class Box}, then the {@code ?} in {@code Box} or in {@code - * Box} can be the same object as a {@code Runnable}. - * - *

It compares every alternative of a union type, because the erasure of a union type is the - * erasure of the first bound of the alternatives' least upper bound, which is less precise. For - * example, if {@code E1}, {@code E2}, and {@code E3} are subclasses of {@code Base}, then the - * exception parameter {@code e} of {@code catch (E1 | E2 e)} cannot be the same object as an - * expression of type {@code E3}, though the erasure of the type of {@code e} is {@code Base}. + * a} is a subtype or a supertype of some erased bound of {@code b}. + * + *

This method compares the erasures of the types, because two parameterizations of a generic + * type, such as {@code List} and {@code List}, can denote the + * same object even if neither is a subtype of the other. For example, an object of type {@code + * List} has both of those types, so the method returns true for them. Their erasures are + * both {@code List}. + * + *

See {@link #erasedBounds} for the definition of erased bounds. + * + *

The answer is not conservative when an interface type is involved. This method returns false + * for two types if no erased bound of one is related by subtyping to an erased bound of the + * other, but one object can have two such types if at least one of them is an interface type. For + * example, this method returns false for {@code Number} and {@code Comparable}, but an object of + * type {@code Integer} is both a {@code Number} and a {@code Comparable}. Likewise, it returns + * false for {@code Runnable} and {@code Serializable}, but an object of a class that implements + * both interfaces has both types. The same holds for arrays whose component types are such types: + * it returns false for {@code Number[]} and {@code Comparable[]}, but one {@code Integer[]} is + * both. See https://github.com/typetools/checker-framework/issues/8558. + * + *

This method compares the bounds of the type parameter that a wildcard is a type argument + * for, because a value of the wildcard has those types too. For example, if {@code Box} is + * declared as {@code class Box}, then the {@code ?} in {@code + * Box} or in {@code Box} can be the same object as a {@code Runnable}. * * @param a the type of an expression * @param b the type of another expression @@ -1028,6 +1019,24 @@ public static boolean canAlias(TypeMirror a, TypeMirror b, Types types) { TypeMirror erasureB = types.erasure(b); return types.isSubtype(erasureA, erasureB) || types.isSubtype(erasureB, erasureA); } + + // Use `erasedBounds()` rather than `erasure()`, because the `erasure()` of a type is the + // erasure of only its first bound (for a type variable, wildcard, or intersection type, or an + // array of such a type), or of the alternatives' least upper bound (for a union type). + // + // For a type variable, wildcard, or intersection type, using `erasure()` would make this + // method unsound: it would return false for some types that can denote the same object. For + // example, a `T[]` where `T extends Number & Comparable` can be the same array as a + // `Comparable[]`, though `Number[]` and `Comparable[]` are unrelated. + // + // For a union type, using `erasure()` would make this method imprecise: it would return true + // for some types that cannot denote the same object. For example, if `E1`, `E2`, and `E3` are + // unrelated subclasses of `Base`, then the exception parameter `e` of `catch (E1 | E2 e)` + // cannot be the same object as an expression of type `E3`, though the erasure of the type of + // `e` is `Base`. When the alternatives' least upper bound is an intersection type, using + // `erasure()` would also make this method unsound, as for an intersection type. For example, + // the erasure of `Integer | Long` is `Number`, which is unrelated to `Comparable`, but a value + // of type `Integer | Long` is a `Comparable`. List boundsA = erasedBounds(a, types); List boundsB = erasedBounds(b, types); for (TypeMirror boundA : boundsA) { @@ -1041,9 +1050,17 @@ public static boolean canAlias(TypeMirror a, TypeMirror b, Types types) { } /** - * Returns the erased bounds of the given type, as defined in {@link #canAlias}. For example, the - * erased bounds of {@code Number & Comparable} are {@code Number} and {@code Comparable}, and - * those of {@code IOException | SQLException} are {@code IOException} and {@code SQLException}. + * Returns the erased bounds of the given type. The erased bounds of a type variable are those of + * its upper bound; of a wildcard, those of its extends bound and those of the type parameter that + * it is a type argument for (or {@code Object}, if neither is known); of an intersection type, + * those of each of its bounds; of a union type, those of each of its alternatives; of an array + * type, an array of each erased bound of its component type; and of any other type, its erasure. + * For example, the erased bounds of {@code Number & Comparable} are {@code Number} and {@code + * Comparable}, and those of {@code IOException | SQLException} are {@code IOException} and {@code + * SQLException}. + * + *

{@link #canAlias} uses the erased bounds to judge whether two expressions might evaluate to + * the same object. * *

If the given type is a union type, every value of the type has at least one of the returned * types. Otherwise, every value of the type has each of the returned types. @@ -1107,8 +1124,8 @@ private static List erasedBounds(TypeMirror type, Types types) { } /** - * Returns true if {@link #erasedBounds} returns only the erasure of the given type. A false - * result means that it might return something else. + * Returns true if {@link #erasedBounds} returns a singleton list containing only the erasure of + * the given type. A false result means that it might return something else. * * @param type a type * @return true if {@link #erasedBounds} returns only the erasure of {@code type} diff --git a/javacutil/src/test/java/org/checkerframework/javacutil/TypesUtilsCanAliasTest.java b/javacutil/src/test/java/org/checkerframework/javacutil/TypesUtilsCanAliasTest.java index c57882a0fb97..b21b91e245e1 100644 --- a/javacutil/src/test/java/org/checkerframework/javacutil/TypesUtilsCanAliasTest.java +++ b/javacutil/src/test/java/org/checkerframework/javacutil/TypesUtilsCanAliasTest.java @@ -114,6 +114,9 @@ public void unionType() { assertCanAlias(true, integerOrLong, type("java.lang.Integer")); assertCanAlias(true, integerOrLong, type("java.lang.Number")); assertCanAlias(true, integerOrLong, type("java.lang.Object")); + // The erasure of the union type is Number, which is unrelated to Comparable, but Integer and + // Long are both Comparable. + assertCanAlias(true, integerOrLong, type("java.lang.Comparable")); // The least upper bound of Integer and Long is Number & Comparable<...> & ..., whose erasure // is Number, which is a supertype of Double. assertCanAlias(false, integerOrLong, type("java.lang.Double")); From 4cf7a6478e18725f8e143fc15d6632d01d63ae07 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 20 Nov 2026 22:14:02 -0800 Subject: [PATCH 40/73] Do not refine with an operand's qualifier that names a location the comparison later writes In `x > (i = (arr = c).length)`, the type `@LTLengthOf("arr")` of `x` is about the array that `arr` referred to before the right operand reassigned `arr`, so it does not imply that `i` is less than the length of the new array. The Upper Bound Checker now treats such a qualifier as unknown when it uses one node's qualifier to refine another node. Also apply spotless formatting, which CI's spotlessCheck requires. --- .../index/upperbound/UpperBoundTransfer.java | 38 ++++++++++-- .../tests/index/AssignmentInComparison.java | 35 ++++++++++- .../ComparisonRecordPatternAccessor.java | 9 ++- .../framework/flow/CFAbstractTransfer.java | 62 ++++++++++++++++++- 4 files changed, 130 insertions(+), 14 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java index 1c8ce8e34f09..8e662ecac035 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java @@ -303,9 +303,9 @@ private void propagateToAdditionOperand( * *

A symbolic offset such as {@code z} denotes the value of {@code z} at the point where the * store is used, but the fact being recorded is about the value that {@code offsetNode} had when - * it was evaluated. If that value might change before the comparison completes, as {@code z} - * does in {@code (x = y) + z < (z = a.length)}, or if it is not deterministic, as {@code choose()} - * is in {@code (x = y) + choose() < a.length} for a nondeterministic method {@code choose}, then + * it was evaluated. If that value might change before the comparison completes, as {@code z} does + * in {@code (x = y) + z < (z = a.length)}, or if it is not deterministic, as {@code choose()} is + * in {@code (x = y) + choose() < a.length} for a nondeterministic method {@code choose}, then * this method uses only the compile-time constant value of {@code offsetNode}, if there is one, * and otherwise returns UNKNOWN. * @@ -349,7 +349,10 @@ protected void refineGT( TransferInput in) { // larger > smaller UBQualifier largerQual = - UBQualifier.createUBQualifier(largerAnno, (UpperBoundChecker) atypeFactory.getChecker()); + qualifierWhenComparisonCompletes( + UBQualifier.createUBQualifier( + largerAnno, (UpperBoundChecker) atypeFactory.getChecker()), + larger); // larger + 1 >= smaller UBQualifier largerQualPlus1 = largerQual.plusOffset(1); UBQualifier rightQualifier = @@ -379,7 +382,9 @@ protected void refineGTE( CFStore store, TransferInput in) { UBQualifier leftQualifier = - UBQualifier.createUBQualifier(leftAnno, (UpperBoundChecker) atypeFactory.getChecker()); + qualifierWhenComparisonCompletes( + UBQualifier.createUBQualifier(leftAnno, (UpperBoundChecker) atypeFactory.getChecker()), + left); UBQualifier rightQualifier = UBQualifier.createUBQualifier(rightAnno, (UpperBoundChecker) atypeFactory.getChecker()); UBQualifier refinedRight = rightQualifier.glb(leftQualifier); @@ -419,7 +424,8 @@ private void refineSubtrahendWithOffset( if (gtNode instanceof NumericalSubtractionNode subtractionNode) { Node minuend = subtractionNode.getLeftOperand(); - UBQualifier minuendQual = getUBQualifier(minuend, in); + UBQualifier minuendQual = + qualifierWhenComparisonCompletes(getUBQualifier(minuend, in), minuend); Node subtrahend = subtractionNode.getRightOperand(); UBQualifier subtrahendQual = getUBQualifier(subtrahend, in); @@ -431,6 +437,26 @@ private void refineSubtrahendWithOffset( } } + /** + * Returns the given qualifier of the given node, or UNKNOWN if the qualifier might not hold when + * the comparison that contains the node completes, because it contains an expression whose value + * might change after the node is evaluated (see {@link + * #containsExpressionChangedBeforeComparisonCompletes}). Call this method on a qualifier of one + * node that is used to refine a different node. + * + * @param qualifier a qualifier of {@code node} + * @param node a node in an operand of a comparison + * @return {@code qualifier}, or UNKNOWN if it might not hold when the comparison completes + */ + private UBQualifier qualifierWhenComparisonCompletes(UBQualifier qualifier, Node node) { + if (qualifier.isLessThanLengthQualifier() + && containsExpressionChangedBeforeComparisonCompletes( + atypeFactory.convertUBQualifierToAnnotation(qualifier), node)) { + return UpperBoundUnknownQualifier.UNKNOWN; + } + return qualifier; + } + /** Implements case 11. */ @Override protected TransferResult strengthenAnnotationOfEqualTo( diff --git a/checker/tests/index/AssignmentInComparison.java b/checker/tests/index/AssignmentInComparison.java index d255ba1cda0e..4244a5ea82ee 100644 --- a/checker/tests/index/AssignmentInComparison.java +++ b/checker/tests/index/AssignmentInComparison.java @@ -17,6 +17,11 @@ int[] setArr(int[] c) { return c; } + @NonNegative int resetArr(int[] c) { + arr = c; + return 0; + } + @Pure @NonNegative int size() { return f; @@ -82,13 +87,15 @@ static void nondeterministicOffset(int[] a, int x, int y) { if ((x = y) + choose() < a.length) { // Another call to `choose()` might return a different value than the one added to `x`. // :: error: [assignment] - @LTLengthOf(value = "a", offset = "choose()") int w = x; + @LTLengthOf(value = "a", offset = "choose()") + int w = x; } } static void deterministicOffset(int[] a, int x, int y) { if ((x = y) + deterministic() < a.length) { - @LTLengthOf(value = "a", offset = "deterministic()") int w = x; + @LTLengthOf(value = "a", offset = "deterministic()") + int w = x; } } @@ -99,4 +106,28 @@ void otherOperandReassignsLengthReceiver(int[] b, int[] c) { int @SameLen("b") [] x = this.arr; } } + + void otherOperandReassignsArrayOfGreater(@LTLengthOf("arr") int x, int i, int[] c) { + if (x > (i = (arr = c).length)) { + // `x` is less than the length of the array that `arr` referred to before the right operand + // reassigned `arr`. `i` is the length of the new array. + // :: error: [assignment] + @LTLengthOf("arr") int y = i; + } + } + + void otherOperandReassignsArrayOfGreaterOrEqual(@LTLengthOf("arr") int x, int i, int[] c) { + if (x >= (i = (arr = c).length)) { + // :: error: [assignment] + @LTLengthOf("arr") int y = i; + } + } + + void otherOperandCallReassignsArray(@LTLengthOf("arr") int x, @NonNegative int i, int[] c) { + if (x > i + resetArr(c)) { + // `resetArr` reassigns `arr`, so `i` might not be less than the length of the new array. + // :: error: [assignment] + @LTLengthOf("arr") int y = i; + } + } } diff --git a/checker/tests/nullness/java21/ComparisonRecordPatternAccessor.java b/checker/tests/nullness/java21/ComparisonRecordPatternAccessor.java index 7fbd2d4f6d26..55861645aa4b 100644 --- a/checker/tests/nullness/java21/ComparisonRecordPatternAccessor.java +++ b/checker/tests/nullness/java21/ComparisonRecordPatternAccessor.java @@ -36,7 +36,8 @@ public Impure inner() { } void impureAccessorInSwitch(Impure r, String expected) { - if (g == (switch (r) { + if (g + == (switch (r) { case Impure(var x) -> expected; })) { // The accessor `x()` is called after `g` is read, and it sets `g` to null. @@ -54,7 +55,8 @@ void impureAccessorInInstanceof(Object o) { } void impureAccessorInNestedPattern(Outer o, String expected) { - if (g == (switch (o) { + if (g + == (switch (o) { case Outer(Impure(var x)) -> expected; })) { // The accessor `x()` is called after `g` is read, and it sets `g` to null. @@ -64,7 +66,8 @@ void impureAccessorInNestedPattern(Outer o, String expected) { } void pureAccessor(Pure1 r, String expected) { - if (g == (switch (r) { + if (g + == (switch (r) { case Pure1(var x) -> expected; })) { g.toString(); diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 743aac9756b2..1cb7c5684103 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -108,6 +108,7 @@ import org.checkerframework.framework.util.Contract.Precondition; import org.checkerframework.framework.util.ContractsFromMethod; import org.checkerframework.framework.util.StringToJavaExpression; +import org.checkerframework.framework.util.dependenttypes.DependentTypesHelper; import org.checkerframework.javacutil.AnnotationMirrorSet; import org.checkerframework.javacutil.BugInCF; import org.checkerframework.javacutil.ElementUtils; @@ -1012,9 +1013,9 @@ protected TransferResult strengthenAnnotationOfEqualTo( * * A method call, object creation, string conversion (which calls {@code toString()}), or record * pattern (which calls record component accessors) might write any field or array element, unless - * the method or constructor is side-effect-free (see - * {@link AnnotatedTypeFactory#isSideEffectFree}). The result omits a field that such a call might - * write even when the store would keep the field's refinement across the call, as it does for a + * the method or constructor is side-effect-free (see {@link + * AnnotatedTypeFactory#isSideEffectFree}). The result omits a field that such a call might write + * even when the store would keep the field's refinement across the call, as it does for a * refinement to the target of a monotonic qualifier (see {@link * org.checkerframework.framework.qual.MonotonicQualifier}): whether the store keeps a refinement * depends on the refined value, which this method does not know. @@ -1248,6 +1249,52 @@ private WrittenLocations locationsWrittenUntilComparison(Node node) { return result; } + /** + * Returns true if the given annotation contains a Java expression whose value might change after + * the given node is evaluated and before the comparison (such as {@code ==} or {@code <}) that + * contains the node completes. The Java expressions in an annotation are the strings that {@link + * DependentTypesHelper} parses, such as {@code "a"} in {@code @LTLengthOf("a")}. + * + *

An annotation of {@code node} describes the values that the expressions in the annotation + * had when {@code node} was evaluated. A client that uses the annotation to refine a different + * node according to the outcome of the comparison can call this method to discard an annotation + * that might no longer hold when the comparison completes. For example, in {@code x > (i = (b = + * c).length)}, the type {@code @IndexFor("b")} of {@code x} is about the array that {@code b} + * referred to before the right operand reassigned {@code b}, so it does not imply that {@code i} + * is an index for {@code b} afterward. + * + * @param anno an annotation of {@code node} + * @param node a node in an operand of a comparison + * @return true if {@code anno} contains a Java expression whose value might change after {@code + * node} is evaluated and before the comparison completes + */ + protected boolean containsExpressionChangedBeforeComparisonCompletes( + AnnotationMirror anno, Node node) { + DependentTypesHelper dependentTypesHelper = analysis.atypeFactory.getDependentTypesHelper(); + if (!dependentTypesHelper.hasDependentAnnotations()) { + return false; + } + TreePath path = sourcePath(node); + if (path == null) { + return false; + } + WrittenLocations written = locationsWrittenUntilComparison(node); + if (written.isEmpty()) { + return false; + } + boolean[] result = {false}; + dependentTypesHelper.convertAnnotationMirror( + expression -> { + JavaExpression expr = analysis.atypeFactory.parseJavaExpressionString(expression, path); + if (written.mayChange(expr, false)) { + result[0] = true; + } + return expr; + }, + anno); + return result[0]; + } + /** * Returns the path to the tree of the given node. If the node has no tree, or if its tree is not * in the compilation unit (as for the artificial tree of an unboxing conversion), returns the @@ -1337,6 +1384,15 @@ private final class WrittenLocations extends TreeScanner { /** Creates an empty set of locations. */ WrittenLocations() {} + /** + * Returns true if no location might be written. + * + * @return true if no location might be written + */ + boolean isEmpty() { + return locals.isEmpty() && fields.isEmpty() && arrayElements.isEmpty() && !anyHeapLocation; + } + /** * Adds a write to the given location. * From 0d5276ef706a064a24cfd731b5d0f91c4f484e13 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 20 Nov 2026 22:33:05 -0800 Subject: [PATCH 41/73] Fix the expected-error location after reformatting; compare with a field in the reassignment tests The formatter put `@LTLengthOf(...)` on its own line, so the expected-error comment preceded the annotation rather than the declaration that the error is reported on. The reassignment tests compare `arr`'s reassignment with a field rather than a parameter, so that the Less Than Checker does not refine `i` to be less than it. Otherwise the tests would depend on typetools/checker-framework#8621. --- checker/tests/index/AssignmentInComparison.java | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/checker/tests/index/AssignmentInComparison.java b/checker/tests/index/AssignmentInComparison.java index 4244a5ea82ee..08010fd434f9 100644 --- a/checker/tests/index/AssignmentInComparison.java +++ b/checker/tests/index/AssignmentInComparison.java @@ -12,6 +12,9 @@ public class AssignmentInComparison { int[] arr = new int[0]; + // A field, so that the Less Than Checker does not refine an expression to be less than it. + @LTLengthOf("arr") int lessThanArrLength; + int[] setArr(int[] c) { arr = c; return c; @@ -86,8 +89,8 @@ static int deterministic() { static void nondeterministicOffset(int[] a, int x, int y) { if ((x = y) + choose() < a.length) { // Another call to `choose()` might return a different value than the one added to `x`. - // :: error: [assignment] @LTLengthOf(value = "a", offset = "choose()") + // :: error: [assignment] int w = x; } } @@ -107,17 +110,17 @@ void otherOperandReassignsLengthReceiver(int[] b, int[] c) { } } - void otherOperandReassignsArrayOfGreater(@LTLengthOf("arr") int x, int i, int[] c) { - if (x > (i = (arr = c).length)) { - // `x` is less than the length of the array that `arr` referred to before the right operand - // reassigned `arr`. `i` is the length of the new array. + void otherOperandReassignsArrayOfGreater(int i, int[] c) { + if (lessThanArrLength > (i = (arr = c).length)) { + // `lessThanArrLength` is less than the length of the array that `arr` referred to before the + // right operand reassigned `arr`. `i` is the length of the new array. // :: error: [assignment] @LTLengthOf("arr") int y = i; } } - void otherOperandReassignsArrayOfGreaterOrEqual(@LTLengthOf("arr") int x, int i, int[] c) { - if (x >= (i = (arr = c).length)) { + void otherOperandReassignsArrayOfGreaterOrEqual(int i, int[] c) { + if (lessThanArrLength >= (i = (arr = c).length)) { // :: error: [assignment] @LTLengthOf("arr") int y = i; } From dd2a2769a10017ba26aea7a87b38f68831307ca1 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 21 Nov 2026 12:02:05 -0800 Subject: [PATCH 42/73] Parenthesize every postfix operand that a postfix operation could regroup Add JavaExpression.toStringAsPostfixOperand, used for the receiver of a method call and the array of an array access. It also handles casts, conditional expressions, numeric literals, and array creations. Run the dataflow JUnit tests. --- dataflow/build.gradle | 4 +- .../dataflow/expression/ArrayAccess.java | 2 +- .../dataflow/expression/JavaExpression.java | 40 +++++ .../dataflow/expression/MethodCall.java | 5 +- .../JavaExpressionToStringTest.java | 162 ++++++++++++++++++ 5 files changed, 206 insertions(+), 7 deletions(-) create mode 100644 dataflow/src/test/java/org/checkerframework/dataflow/expression/JavaExpressionToStringTest.java diff --git a/dataflow/build.gradle b/dataflow/build.gradle index 488e9a3d5a52..c08fbf1c3e34 100644 --- a/dataflow/build.gradle +++ b/dataflow/build.gradle @@ -172,8 +172,8 @@ if (rootProject.ext.testJdkVersion >= 22) { } test { - // The tests are run by allDataflowTests. - exclude("**/*") + // The dataflow analysis tests are run by allDataflowTests. This task runs only the JUnit tests. + include("org/checkerframework/dataflow/expression/**") } apply from: rootProject.file("gradle-mvn-push.gradle") diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/expression/ArrayAccess.java b/dataflow/src/main/java/org/checkerframework/dataflow/expression/ArrayAccess.java index d16fe1c70a7e..6d432a0805a5 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/expression/ArrayAccess.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/expression/ArrayAccess.java @@ -114,7 +114,7 @@ public boolean containsModifiableAliasOf(Store store, JavaExpression other) { @Override public String toString() { StringBuilder result = new StringBuilder(); - result.append(array.toString()); + result.append(array.toStringAsPostfixOperand()); result.append('['); result.append(index.toString()); result.append(']'); diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java b/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java index 4ddd446c14b8..3c360bc46c51 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java @@ -406,6 +406,46 @@ public JavaExpression atConstructorInvocation(NewClassTree newClassTree) { return ViewpointAdaptJavaExpression.viewpointAdapt(this, receiverJe, argumentsJe); } + // + // Printing + // + + /** + * Returns the printed form of this expression, as it should appear immediately before a postfix + * operation, such as a method call {@code .m()} or an array access {@code [i]}. The result is + * parenthesized unless this is an expression that the postfix operation cannot regroup. For + * example, the binary operation {@code a + b} yields {@code (a + b)}, so that a method call on it + * prints as {@code (a + b).trim()} rather than as {@code a + b.trim()}, which means something + * different; and the numeric literal {@code 5} yields {@code (5)}, because {@code 5.intValue()} + * does not parse. + * + * @return the printed form of this expression, parenthesized if a postfix operation could regroup + * it + */ + @Pure + public String toStringAsPostfixOperand() { + boolean needsParentheses; + if (this instanceof LocalVariable + || this instanceof FormalParameter + || this instanceof FieldAccess + || this instanceof MethodCall + || this instanceof ArrayAccess + || this instanceof ThisReference + || this instanceof SuperReference + || this instanceof ClassName) { + needsParentheses = false; + } else if (this instanceof ValueLiteral valueLiteral) { + // A numeric literal can be negative, as in `-1.intValue()`, or can absorb the dot, as in + // `5.intValue()`. Other literals, such as `"abc"`, `'c'`, `true`, and `null`, are atomic. + needsParentheses = valueLiteral.getValue() instanceof Number; + } else { + // For example, a binary or unary operation, an array creation, or an unknown expression such + // as a cast or a conditional expression. + needsParentheses = true; + } + return needsParentheses ? "(" + this + ")" : toString(); + } + // // Visitor and debugging // diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/expression/MethodCall.java b/dataflow/src/main/java/org/checkerframework/dataflow/expression/MethodCall.java index 2af060a80f8b..44cd95cf6283 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/expression/MethodCall.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/expression/MethodCall.java @@ -191,11 +191,8 @@ public String toString() { StringBuilder preParen = new StringBuilder(); if (receiver instanceof ClassName) { preParen.append(receiver.getType()); - } else if (receiver instanceof BinaryOperation || receiver instanceof UnaryOperation) { - // Without parentheses, `("a" + s).length()` would be printed as `"a" + s.length()`. - preParen.append('(').append(receiver).append(')'); } else { - preParen.append(receiver); + preParen.append(receiver.toStringAsPostfixOperand()); } preParen.append('.'); String methodName = method.getSimpleName().toString(); diff --git a/dataflow/src/test/java/org/checkerframework/dataflow/expression/JavaExpressionToStringTest.java b/dataflow/src/test/java/org/checkerframework/dataflow/expression/JavaExpressionToStringTest.java new file mode 100644 index 000000000000..912645a05dfd --- /dev/null +++ b/dataflow/src/test/java/org/checkerframework/dataflow/expression/JavaExpressionToStringTest.java @@ -0,0 +1,162 @@ +package org.checkerframework.dataflow.expression; + +import com.sun.source.tree.Tree; +import com.sun.tools.javac.main.JavaCompiler; +import com.sun.tools.javac.main.Option; +import com.sun.tools.javac.processing.JavacProcessingEnvironment; +import com.sun.tools.javac.util.Context; +import com.sun.tools.javac.util.Options; +import java.util.Collections; +import java.util.List; +import javax.annotation.processing.ProcessingEnvironment; +import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.TypeElement; +import javax.lang.model.type.TypeKind; +import javax.lang.model.type.TypeMirror; +import javax.lang.model.util.ElementFilter; +import javax.lang.model.util.Types; +import org.checkerframework.checker.nullness.qual.Nullable; +import org.junit.Assert; +import org.junit.Test; + +/** + * Tests that {@link JavaExpression#toString} parenthesizes an operand of a postfix operation, such + * as the receiver of a method call or the array of an array access, when necessary. + */ +public class JavaExpressionToStringTest { + + /** The type utilities. */ + private final Types types; + + /** The type {@code String}. */ + private final TypeMirror stringType; + + /** The type {@code Integer}. */ + private final TypeMirror integerType; + + /** The type {@code int}. */ + private final TypeMirror intType; + + /** The method {@code String.trim()}. */ + private final ExecutableElement trimMethod; + + /** The method {@code Integer.intValue()}. */ + private final ExecutableElement intValueMethod; + + /** Creates a JavaExpressionToStringTest. */ + public JavaExpressionToStringTest() { + Context context = new Context(); + Options options = Options.instance(context); + options.put(Option.SOURCE, "8"); + options.put(Option.TARGET, "8"); + ProcessingEnvironment env = JavacProcessingEnvironment.instance(context); + JavaCompiler javac = JavaCompiler.instance(context); + javac.initModules(com.sun.tools.javac.util.List.nil()); + javac.enterDone(); + + types = env.getTypeUtils(); + TypeElement stringElement = env.getElementUtils().getTypeElement("java.lang.String"); + TypeElement integerElement = env.getElementUtils().getTypeElement("java.lang.Integer"); + stringType = stringElement.asType(); + integerType = integerElement.asType(); + intType = types.getPrimitiveType(TypeKind.INT); + trimMethod = getMethod(stringElement, "trim"); + intValueMethod = getMethod(integerElement, "intValue"); + } + + /** + * Returns the method with the given name and no parameters, declared in the given type. + * + * @param type a type + * @param name the name of a method in the type + * @return the method with the given name and no parameters, declared in the type + */ + private static ExecutableElement getMethod(TypeElement type, String name) { + for (ExecutableElement method : ElementFilter.methodsIn(type.getEnclosedElements())) { + if (method.getSimpleName().contentEquals(name) && method.getParameters().isEmpty()) { + return method; + } + } + throw new Error("No method " + name + "() in " + type); + } + + /** + * Returns a call to {@code String.trim()} on the given receiver. + * + * @param receiver a receiver of type String + * @return a call to {@code trim()} on the receiver + */ + private MethodCall trim(JavaExpression receiver) { + return new MethodCall(stringType, trimMethod, receiver, Collections.emptyList()); + } + + /** + * Returns a call to {@code Integer.intValue()} on the given receiver. + * + * @param receiver a receiver of type Integer + * @return a call to {@code intValue()} on the receiver + */ + private MethodCall intValue(JavaExpression receiver) { + return new MethodCall(intType, intValueMethod, receiver, Collections.emptyList()); + } + + /** + * Returns an int literal. + * + * @param value the value of the literal + * @return an int literal for the value + */ + private ValueLiteral intLiteral(int value) { + return new ValueLiteral(intType, value); + } + + @Test + public void methodCallOnAtomicReceiver() { + ValueLiteral abc = new ValueLiteral(stringType, "abc"); + Assert.assertEquals("\"abc\".trim()", trim(abc).toString()); + Assert.assertEquals("\"abc\".trim().trim()", trim(trim(abc)).toString()); + } + + @Test + public void methodCallOnBinaryOperation() { + BinaryOperation concatenation = + new BinaryOperation( + stringType, + Tree.Kind.PLUS, + new ValueLiteral(stringType, "a"), + new ValueLiteral(stringType, "b")); + Assert.assertEquals("(\"a\" + \"b\").trim()", trim(concatenation).toString()); + } + + @Test + public void methodCallOnUnaryOperation() { + UnaryOperation negation = new UnaryOperation(integerType, Tree.Kind.UNARY_MINUS, intLiteral(5)); + Assert.assertEquals("(-5).intValue()", intValue(negation).toString()); + } + + @Test + public void methodCallOnNumericLiteral() { + Assert.assertEquals("(5).intValue()", intValue(intLiteral(5)).toString()); + Assert.assertEquals("(-1).intValue()", intValue(intLiteral(-1)).toString()); + } + + @Test + public void methodCallOnUnknown() { + Assert.assertEquals( + "((String) o).trim()", trim(new Unknown(stringType, "(String) o")).toString()); + Assert.assertEquals( + "(b ? x : y).trim()", trim(new Unknown(stringType, "b ? x : y")).toString()); + } + + @Test + public void arrayAccessOnArrayCreation() { + TypeMirror intArrayType = types.getArrayType(intType); + TypeMirror intArrayArrayType = types.getArrayType(intArrayType); + List<@Nullable JavaExpression> dimensions = List.of(intLiteral(3), intLiteral(4)); + ArrayCreation creation = + new ArrayCreation(intArrayArrayType, dimensions, Collections.emptyList()); + Assert.assertEquals("new int[3][4]", creation.toString()); + ArrayAccess access = new ArrayAccess(intArrayType, creation, intLiteral(0)); + Assert.assertEquals("(new int[3][4])[0]", access.toString()); + } +} From 3696c7d6273d06982d3b200aac45deaf564f7366 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 21 Nov 2026 12:23:57 -0800 Subject: [PATCH 43/73] Print a static field access as Foo.f, not Foo.class.f Also parenthesize a field access's receiver when necessary. --- .../LexicallyNestedType.ajava.goal | 2 +- .../RelevantNestedType.ajava.goal | 4 +- .../RelevantSubtype.ajava.goal | 2 +- .../ainfer-relevance/RelevantTypes.ajava.goal | 2 +- .../SamePackageShadows.ajava.goal | 4 +- .../dataflow/expression/FieldAccess.java | 6 ++- .../JavaExpressionToStringTest.java | 37 +++++++++++++++++++ 7 files changed, 48 insertions(+), 9 deletions(-) diff --git a/checker/tests/ainfer-relevance/LexicallyNestedType.ajava.goal b/checker/tests/ainfer-relevance/LexicallyNestedType.ajava.goal index 9c24905a55f5..e263486216d9 100644 --- a/checker/tests/ainfer-relevance/LexicallyNestedType.ajava.goal +++ b/checker/tests/ainfer-relevance/LexicallyNestedType.ajava.goal @@ -14,7 +14,7 @@ public class LexicallyNestedType { static @org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1 Number nestedNumber; - @org.checkerframework.framework.qual.EnsuresQualifier(expression = { "LexicallyNestedType.class.nestedNumber" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) + @org.checkerframework.framework.qual.EnsuresQualifier(expression = { "LexicallyNestedType.nestedNumber" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) @org.checkerframework.dataflow.qual.Impure static void assignField() { nestedNumber = getSibling1(); diff --git a/checker/tests/ainfer-relevance/RelevantNestedType.ajava.goal b/checker/tests/ainfer-relevance/RelevantNestedType.ajava.goal index 16a5e7f5c3b7..9114d18efff1 100644 --- a/checker/tests/ainfer-relevance/RelevantNestedType.ajava.goal +++ b/checker/tests/ainfer-relevance/RelevantNestedType.ajava.goal @@ -22,7 +22,7 @@ public class RelevantNestedType { // "AbstractMap.SimpleEntry" does not appear in the checker's `@RelevantJavaTypes`. static AbstractMap.@org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1 SimpleEntry subtype; - @org.checkerframework.framework.qual.EnsuresQualifier(expression = { "RelevantNestedType.class.subtype" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) + @org.checkerframework.framework.qual.EnsuresQualifier(expression = { "RelevantNestedType.subtype" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) @org.checkerframework.dataflow.qual.Impure static void assignFields() { nestedName = getSibling1(); @@ -57,7 +57,7 @@ public class RelevantNestedType { return null; } - @org.checkerframework.framework.qual.RequiresQualifier(expression = { "RelevantNestedType.class.rawName" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) + @org.checkerframework.framework.qual.RequiresQualifier(expression = { "RelevantNestedType.rawName" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) @org.checkerframework.dataflow.qual.Pure static AbstractMap.SimpleEntry getSibling1Subtype() { return null; diff --git a/checker/tests/ainfer-relevance/RelevantSubtype.ajava.goal b/checker/tests/ainfer-relevance/RelevantSubtype.ajava.goal index 3d44a476ea85..ce31794eed39 100644 --- a/checker/tests/ainfer-relevance/RelevantSubtype.ajava.goal +++ b/checker/tests/ainfer-relevance/RelevantSubtype.ajava.goal @@ -26,7 +26,7 @@ public class RelevantSubtype implements CharSequence { static @org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1 RelevantSubtype field; - @org.checkerframework.framework.qual.EnsuresQualifier(expression = { "RelevantSubtype.class.field" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) + @org.checkerframework.framework.qual.EnsuresQualifier(expression = { "RelevantSubtype.field" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) @org.checkerframework.dataflow.qual.Impure static void assignField() { field = getSibling1(); diff --git a/checker/tests/ainfer-relevance/RelevantTypes.ajava.goal b/checker/tests/ainfer-relevance/RelevantTypes.ajava.goal index 1a3e10b5e757..ba5b5640cc3d 100644 --- a/checker/tests/ainfer-relevance/RelevantTypes.ajava.goal +++ b/checker/tests/ainfer-relevance/RelevantTypes.ajava.goal @@ -15,7 +15,7 @@ public class RelevantTypes { static @org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1 CharSequence charSequenceField; - @org.checkerframework.framework.qual.EnsuresQualifier(expression = { "RelevantTypes.class.charSequenceField" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) + @org.checkerframework.framework.qual.EnsuresQualifier(expression = { "RelevantTypes.charSequenceField" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) @org.checkerframework.dataflow.qual.Impure static void assignFields() { intField = getSibling1Int(); diff --git a/checker/tests/ainfer-relevance/SamePackageShadows.ajava.goal b/checker/tests/ainfer-relevance/SamePackageShadows.ajava.goal index f3cb627ee823..bbcc004f03a1 100644 --- a/checker/tests/ainfer-relevance/SamePackageShadows.ajava.goal +++ b/checker/tests/ainfer-relevance/SamePackageShadows.ajava.goal @@ -17,7 +17,7 @@ public class SamePackageShadows { static @org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1 List listField; - @org.checkerframework.framework.qual.EnsuresQualifier(expression = { "SamePackageShadows.class.listField" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) + @org.checkerframework.framework.qual.EnsuresQualifier(expression = { "SamePackageShadows.listField" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) @org.checkerframework.dataflow.qual.Impure static void assignFields() { runnableField = getSibling1Runnable(); @@ -45,7 +45,7 @@ public class SamePackageShadows { return null; } - @org.checkerframework.framework.qual.RequiresQualifier(expression = { "SamePackageShadows.class.runnableField" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) + @org.checkerframework.framework.qual.RequiresQualifier(expression = { "SamePackageShadows.runnableField" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) @org.checkerframework.dataflow.qual.Pure static List getSibling1List() { return null; diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/expression/FieldAccess.java b/dataflow/src/main/java/org/checkerframework/dataflow/expression/FieldAccess.java index 63837e8acf8f..1cf48ccc6b11 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/expression/FieldAccess.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/expression/FieldAccess.java @@ -154,11 +154,13 @@ public boolean containsModifiableAliasOf(Store store, JavaExpression other) { @Override public String toString() { String receiverString = - (receiver instanceof ClassName) ? receiver.getType().toString() : receiver.toString(); + (receiver instanceof ClassName) + ? receiver.getType().toString() + : receiver.toStringAsPostfixOperand(); if (Node.disambiguateOwner) { return receiverString + "." + field + "{owner=" + ((Symbol) field).owner + "}"; } else { - return receiver + "." + field; + return receiverString + "." + field; } } diff --git a/dataflow/src/test/java/org/checkerframework/dataflow/expression/JavaExpressionToStringTest.java b/dataflow/src/test/java/org/checkerframework/dataflow/expression/JavaExpressionToStringTest.java index 912645a05dfd..17fafb06b041 100644 --- a/dataflow/src/test/java/org/checkerframework/dataflow/expression/JavaExpressionToStringTest.java +++ b/dataflow/src/test/java/org/checkerframework/dataflow/expression/JavaExpressionToStringTest.java @@ -11,6 +11,7 @@ import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; +import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.ElementFilter; @@ -43,6 +44,12 @@ public class JavaExpressionToStringTest { /** The method {@code Integer.intValue()}. */ private final ExecutableElement intValueMethod; + /** The static field {@code Integer.MAX_VALUE}. */ + private final VariableElement maxValueField; + + /** The instance field {@code Integer.value}. */ + private final VariableElement valueField; + /** Creates a JavaExpressionToStringTest. */ public JavaExpressionToStringTest() { Context context = new Context(); @@ -62,6 +69,8 @@ public JavaExpressionToStringTest() { intType = types.getPrimitiveType(TypeKind.INT); trimMethod = getMethod(stringElement, "trim"); intValueMethod = getMethod(integerElement, "intValue"); + maxValueField = getField(integerElement, "MAX_VALUE"); + valueField = getField(integerElement, "value"); } /** @@ -80,6 +89,22 @@ private static ExecutableElement getMethod(TypeElement type, String name) { throw new Error("No method " + name + "() in " + type); } + /** + * Returns the field with the given name, declared in the given type. + * + * @param type a type + * @param name the name of a field in the type + * @return the field with the given name, declared in the type + */ + private static VariableElement getField(TypeElement type, String name) { + for (VariableElement field : ElementFilter.fieldsIn(type.getEnclosedElements())) { + if (field.getSimpleName().contentEquals(name)) { + return field; + } + } + throw new Error("No field " + name + " in " + type); + } + /** * Returns a call to {@code String.trim()} on the given receiver. * @@ -148,6 +173,18 @@ public void methodCallOnUnknown() { "(b ? x : y).trim()", trim(new Unknown(stringType, "b ? x : y")).toString()); } + @Test + public void fieldAccessOnClassName() { + FieldAccess access = new FieldAccess(new ClassName(integerType), maxValueField); + Assert.assertEquals("java.lang.Integer.MAX_VALUE", access.toString()); + } + + @Test + public void fieldAccessOnUnknown() { + FieldAccess access = new FieldAccess(new Unknown(integerType, "(Integer) o"), valueField); + Assert.assertEquals("((Integer) o).value", access.toString()); + } + @Test public void arrayAccessOnArrayCreation() { TypeMirror intArrayType = types.getArrayType(intType); From 0785febf56b0c2dbbd5989749ac41fceae1ddcfe Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 21 Nov 2026 12:28:36 -0800 Subject: [PATCH 44/73] Do not change dataflow/build.gradle in this pull request --- dataflow/build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dataflow/build.gradle b/dataflow/build.gradle index c08fbf1c3e34..488e9a3d5a52 100644 --- a/dataflow/build.gradle +++ b/dataflow/build.gradle @@ -172,8 +172,8 @@ if (rootProject.ext.testJdkVersion >= 22) { } test { - // The dataflow analysis tests are run by allDataflowTests. This task runs only the JUnit tests. - include("org/checkerframework/dataflow/expression/**") + // The tests are run by allDataflowTests. + exclude("**/*") } apply from: rootProject.file("gradle-mvn-push.gradle") From cd93fac1100a0dc0fa2d9ce62cdea7d14c862e4c Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 21 Nov 2026 18:33:37 -0800 Subject: [PATCH 45/73] Discard refinements that a comparison invalidates - An assignment's rhs that is a unary or binary operation is omitted from nodesWithValueOf if the assignment changes its inputs, as in s = s + "x". - SameLen drops names from an operand's @SameLen type that the comparison might change. - LowerBound's relational refinements refine only nodesWithValueOf. - Clear the per-CFG caches in initFields, so performAnalysis(cfg) clears them. --- .../index/lowerbound/LowerBoundTransfer.java | 48 ++++++------- .../index/samelen/SameLenTransfer.java | 72 ++++++++++++++++--- .../LowerBoundComparisonChangesOperand.java | 42 +++++++++++ .../SameLenComparisonChangesOperand.java | 47 ++++++++++++ .../framework/flow/CFAbstractAnalysis.java | 17 +++-- .../framework/flow/CFAbstractTransfer.java | 61 +++++++++++++--- 6 files changed, 241 insertions(+), 46 deletions(-) create mode 100644 checker/tests/index/LowerBoundComparisonChangesOperand.java diff --git a/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java index c0d36f4a6010..f025f7adc2f7 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java @@ -211,19 +211,11 @@ private void notEqualToValue( if (intLiteral == 0) { if (atypeFactory.areSameByClass(otherAnno, NonNegative.class)) { - List internals = nodesWithValueOf(otherNode); - for (Node internal : internals) { - JavaExpression je = JavaExpression.fromNode(internal); - store.insertValue(je, POS); - } + insertForNodesWithValueOf(otherNode, POS, store); } } else if (intLiteral == -1) { if (atypeFactory.areSameByClass(otherAnno, GTENegativeOne.class)) { - List internals = nodesWithValueOf(otherNode); - for (Node internal : internals) { - JavaExpression je = JavaExpression.fromNode(internal); - store.insertValue(je, NN); - } + insertForNodesWithValueOf(otherNode, NN, store); } } } @@ -275,7 +267,7 @@ private void notEqualsLessThan( if (atypeFactory .getLessThanAnnotatedTypeFactory() .isLessThanOrEqual(leftNode.getTree(), otherJe.toString())) { - store.insertValue(otherJe, POS); + insertForNodesWithValueOf(otherNode, POS, store); } } @@ -301,19 +293,29 @@ protected void refineGT( return; } - JavaExpression leftJe = JavaExpression.fromNode(left); - + AnnotationMirror newLBType; if (AnnotationUtils.areSame(rightAnno, GTEN1)) { - store.insertValue(leftJe, NN); - return; - } - if (AnnotationUtils.areSame(rightAnno, NN)) { - store.insertValue(leftJe, POS); + newLBType = NN; + } else if (AnnotationUtils.areSame(rightAnno, NN) || AnnotationUtils.areSame(rightAnno, POS)) { + newLBType = POS; + } else { return; } - if (AnnotationUtils.areSame(rightAnno, POS)) { - store.insertValue(leftJe, POS); - return; + insertForNodesWithValueOf(left, newLBType, store); + } + + /** + * Inserts the given annotation into the store for each node that has the value of {@code node} + * when the comparison that contains it completes. Does not insert it for {@code node} if a later + * part of the comparison might change its value, as in {@code i > (i = 0)}. + * + * @param node an operand of a comparison + * @param anno the annotation to insert + * @param store the store to modify + */ + private void insertForNodesWithValueOf(Node node, AnnotationMirror anno, CFStore store) { + for (Node internal : nodesWithValueOf(node)) { + store.insertValue(JavaExpression.fromNode(internal), anno); } } @@ -338,14 +340,12 @@ protected void refineGTE( return; } - JavaExpression leftJe = JavaExpression.fromNode(left); - AnnotationMirror newLBType = atypeFactory .getQualifierHierarchy() .greatestLowerBoundShallow(rightAnno, left.getType(), leftAnno, right.getType()); - store.insertValue(leftJe, newLBType); + insertForNodesWithValueOf(left, newLBType, store); } /** diff --git a/checker/src/main/java/org/checkerframework/checker/index/samelen/SameLenTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/samelen/SameLenTransfer.java index 43cae7e3aecc..bd87ee379a83 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/samelen/SameLenTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/samelen/SameLenTransfer.java @@ -7,6 +7,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.function.Predicate; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import javax.lang.model.type.TypeKind; @@ -190,22 +191,77 @@ private boolean isArrayLengthAccess(Node node) { * @param store the store in which to perform refinement */ private void refineEq(Node left, Node right, CFStore store) { + TreePath currentPath = atypeFactory.getPath(left.getTree()); + if (currentPath == null) { + // propagateCombinedSameLen would do nothing. + return; + } List exprs = new ArrayList<>(2); List annos = new ArrayList<>(2); - for (Node internal : nodesWithValueOf(left)) { - exprs.add(JavaExpression.fromNode(internal)); - annos.add(getAnno(internal)); - } - for (Node internal : nodesWithValueOf(right)) { - exprs.add(JavaExpression.fromNode(internal)); - annos.add(getAnno(internal)); - } + addOperandSameLens(left, currentPath, exprs, annos); + addOperandSameLens(right, currentPath, exprs, annos); AnnotationMirror combinedSameLen = atypeFactory.createCombinedSameLen(exprs, annos); propagateCombinedSameLen(combinedSameLen, left, store); } + /** + * Adds to {@code exprs} the expressions that have the value of {@code operand} when the + * comparison completes, and adds their SameLen annotations to {@code annos}. + * + *

Each annotation was computed when its expression was evaluated. It omits each name whose + * expression {@code operand} or the rest of the comparison might change, because such a name + * might not have the same length when the comparison completes. For example, in {@code a.length + * == f(c = new int[0], b).length}, if the type of {@code a} is {@code @SameLen("c")}, the + * annotation that this method adds for {@code a} omits {@code c}. + * + * @param operand an operand of a comparison, possibly an assignment + * @param currentPath the path at which to parse the expressions in SameLen annotations + * @param exprs the list of expressions to add to + * @param annos the list of annotations to add to, in parallel with {@code exprs} + */ + private void addOperandSameLens( + Node operand, + TreePath currentPath, + List exprs, + List annos) { + // Computed lazily, because computing it can be costly and most annotations name nothing. + Predicate mayBeChanged = null; + for (Node internal : nodesWithValueOf(operand)) { + exprs.add(JavaExpression.fromNode(internal)); + AnnotationMirror anno = getAnno(internal); + if (anno != null && atypeFactory.areSameByClass(anno, SameLen.class)) { + List names = + AnnotationUtils.getElementValueArray( + anno, atypeFactory.sameLenValueElement, String.class); + if (!names.isEmpty()) { + if (mayBeChanged == null) { + mayBeChanged = mayBeChangedByOrAfter(operand); + } + List unchangedNames = new ArrayList<>(names.size()); + for (String name : names) { + JavaExpression je; + try { + je = atypeFactory.parseJavaExpressionString(name, currentPath); + } catch (JavaExpressionParseException e) { + // The name cannot be checked, and propagateCombinedSameLen would skip it anyway. + continue; + } + if (!mayBeChanged.test(je)) { + unchangedNames.add(name); + } + } + if (unchangedNames.size() != names.size()) { + // `unchangedNames` is a sublist of `names`, so it is in alphabetical order. + anno = atypeFactory.createSameLen(unchangedNames); + } + } + } + annos.add(anno); + } + } + /** * Returns {@code n}'s annotation from the SameLen hierarchy. * diff --git a/checker/tests/index/LowerBoundComparisonChangesOperand.java b/checker/tests/index/LowerBoundComparisonChangesOperand.java new file mode 100644 index 000000000000..1e28e3895db0 --- /dev/null +++ b/checker/tests/index/LowerBoundComparisonChangesOperand.java @@ -0,0 +1,42 @@ +// A relational comparison must not refine an operand that a later part of the comparison changes. +// For example, if i is 1, then i > (i = 0) is true, but afterward i is 0. + +import org.checkerframework.checker.index.qual.NonNegative; +import org.checkerframework.checker.index.qual.Positive; + +public class LowerBoundComparisonChangesOperand { + + void gtChangedLater(@NonNegative int i) { + if (i > (i = 0)) { + // :: error: (assignment) + @Positive int p = i; + } + } + + void gtUnchanged(@NonNegative int i, int j) { + if (i > (j = 0)) { + @Positive int p = i; + } + } + + void gteChangedLater(int i) { + if (i >= (i = -1) + 1) { + // :: error: (assignment) + @NonNegative int n = i; + } + } + + void gteUnchanged(int i, int m) { + if (i >= (m = -1) + 1) { + @NonNegative int n = i; + } + } + + // Both sides of an assignment have the value of the operand. + void gtAssignment(int i, int j) { + if ((i = j) > 0) { + @Positive int p = i; + @Positive int q = j; + } + } +} diff --git a/checker/tests/index/SameLenComparisonChangesOperand.java b/checker/tests/index/SameLenComparisonChangesOperand.java index 8c88fb87c141..2dff7199a8bb 100644 --- a/checker/tests/index/SameLenComparisonChangesOperand.java +++ b/checker/tests/index/SameLenComparisonChangesOperand.java @@ -2,6 +2,8 @@ // changes the operand's value after evaluating it. For example, if i is 12, then after the // comparison in changedLater, s is "ab3" but "x" + i is "x3". +import org.checkerframework.dataflow.qual.Pure; + public class SameLenComparisonChangesOperand { void changedLater(int i, String s) { @@ -22,4 +24,49 @@ void unchanged(int i, String s) { } } } + + // After the assignment, s + "x" is one character longer than t. + void changedInAssignment(String s, String t) { + if ((s = s + "x").length() == t.length()) { + String u = s + "x"; + for (int k = 0; k < u.length(); k++) { + // :: error: (argument) + t.charAt(k); + } + } + } + + void unchangedInAssignment(String s, String t, String v) { + if ((s = v + "x").length() == t.length()) { + String u = v + "x"; + for (int k = 0; k < u.length(); k++) { + t.charAt(k); + } + } + } + + @Pure + static int[] keepSecond(int[] x, int[] y) { + return y; + } + + // The type of a is @SameLen("c") when a is evaluated, but the right operand then reassigns c. + void staleNameInType(int[] a, int[] b) { + int[] c = a; + if (a.length == keepSecond(c = new int[0], b).length) { + for (int k = 0; k < a.length; k++) { + // :: error: (array.access.unsafe.high) + c[k] = 0; + } + } + } + + void unchangedNameInType(int[] a, int[] b, int[] d) { + int[] c = a; + if (a.length == keepSecond(d = new int[0], b).length) { + for (int k = 0; k < a.length; k++) { + c[k] = 0; + } + } + } } diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java index 7c5be3c46551..b748519e3436 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java @@ -13,6 +13,7 @@ import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Types; import javax.tools.Diagnostic; +import org.checkerframework.checker.nullness.qual.EnsuresNonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.common.basetype.BaseTypeChecker; import org.checkerframework.common.basetype.BaseTypeVisitor; @@ -107,7 +108,7 @@ public record FieldInitialValue>( * null stands for the null result, so test membership with {@link Map#containsKey} rather than * comparing the result of {@link Map#get} to null. * - *

The keys are nodes of a single control flow graph, so {@link #performAnalysis} clears this. + *

The keys are nodes of a single control flow graph, so {@link #initFields} clears this. * *

This is an {@link IdentityHashMap} because the cached values are viewpoint-adapted to a * particular call site, but {@link MethodInvocationNode#equals} compares only the target and the @@ -123,7 +124,7 @@ public record FieldInitialValue>( * argument and on the trees around the argument's tree, but which would otherwise be recomputed * once per dataflow iteration per comparison. * - *

The keys are nodes of a single control flow graph, so {@link #performAnalysis} clears this. + *

The keys are nodes of a single control flow graph, so {@link #initFields} clears this. * This is an {@link IdentityHashMap} because the result depends on the trees around the node, but * {@link Node#equals} can be true for nodes that represent different trees. */ @@ -206,10 +207,18 @@ public void performAnalysis(ControlFlowGraph cfg, List> fie } this.fieldValues.clear(); this.fieldValues.addAll(fieldValues); - // The cache's keys are nodes of the control flow graph that was analyzed previously. + super.performAnalysis(cfg); + } + + @Override + @EnsuresNonNull("this.cfg") + protected void initFields(ControlFlowGraph cfg) { + // The caches' keys are nodes of the control flow graph that was analyzed previously. Clear + // them here rather than in `performAnalysis(cfg, fieldValues)`, so that the inherited + // `performAnalysis(cfg)` clears them too. sideEffectsOnlyExpressionsCache.clear(); nodesWithValueOfCache.clear(); - super.performAnalysis(cfg); + super.initFields(cfg); } /** diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 7f92f13d9669..a477ceb3ea07 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -25,6 +25,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.function.Predicate; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; @@ -1067,9 +1068,7 @@ private List computeNodesWithValueOf(Node node) { List result = new ArrayList<>(candidates.size()); for (Node candidate : candidates) { JavaExpression expr = JavaExpression.fromNode(candidate); - if (CFAbstractStore.canInsertJavaExpression(expr) - || ((expr instanceof UnaryOperation || expr instanceof BinaryOperation) - && !expr.containsUnknown())) { + if (isCheckedCandidate(expr)) { if (locationsWrittenUntilComparison == null) { locationsWrittenUntilComparison = locationsWrittenUntilComparison(node); } @@ -1082,6 +1081,46 @@ private List computeNodesWithValueOf(Node node) { return result; } + /** + * Returns true if {@link #nodesWithValueOf} omits a candidate whose expression is {@code expr} + * when a write might change the candidate's value: that is, if a store can hold a value for + * {@code expr} (see {@link CFAbstractStore#canInsertJavaExpression}), or if {@code expr} is a + * unary or binary operation that does not contain {@link Unknown}. + * + * @param expr the expression for a candidate of {@link #nodesWithValueOf} + * @return true if a candidate whose expression is {@code expr} is omitted when a write might + * change its value + */ + private static boolean isCheckedCandidate(JavaExpression expr) { + return CFAbstractStore.canInsertJavaExpression(expr) + || ((expr instanceof UnaryOperation || expr instanceof BinaryOperation) + && !expr.containsUnknown()); + } + + /** + * Returns a predicate that is true of each expression whose value, when the comparison that + * contains {@code node} completes, might differ from its value before {@code node} was evaluated. + * The value can differ if {@code node} itself, or the code that is evaluated after {@code node} + * and before the comparison completes, writes a variable, field, or array element that the + * expression reads. See {@link #nodesWithValueOf} for details. + * + *

A client can use this to discard information, computed when {@code node} was evaluated, + * that mentions other expressions. For example, the SameLen Checker uses it to discard the names + * in the {@code @SameLen} type of an operand that are not valid when the comparison completes. + * + * @param node a node in an operand of a comparison, possibly an assignment + * @return a predicate that is true of each expression that evaluating {@code node} and the rest + * of the comparison might change + */ + protected Predicate mayBeChangedByOrAfter(Node node) { + WrittenLocations written = locationsWrittenUntilComparison(node); + TreePath path = sourcePath(node); + if (path != null) { + written.scan(path.getLeaf(), null); + } + return expr -> written.mayChange(expr, false); + } + /** * Returns the sides of the given assignment that have the value of the assignment when the * assignment completes. @@ -1091,8 +1130,9 @@ private List computeNodesWithValueOf(Node node) { * assignment, and so on. For example, {@code a = b = c} is parsed as {@code a = (b = c)}, and its * chain is {@code a = (b = c)} and {@code b = c}. The sides are the targets of the assignments in * the chain, such as {@code a} and {@code b}, and the rhs of the last assignment in the chain, - * such as {@code c}. The result omits each side that a store can hold a value for and whose value - * the rest of the chain might change. + * such as {@code c}. The result omits each side that a store can hold a value for, or that is a + * unary or binary operation (see {@link #isCheckedCandidate}), and whose value the rest of the + * chain might change. For example, the result for {@code s = s + "x"} omits {@code s + "x"}. * * @param assignment an assignment node * @return the sides of {@code assignment} that have its value when it completes, in source order @@ -1148,8 +1188,9 @@ private List sidesOfAssignment(AssignmentNode assignment) { } /** - * Returns true if a store can hold a value for the given side of a chain of assignments, and - * writing the given locations might change the side's value. + * Returns true if the given side of a chain of assignments is a candidate that {@link + * #nodesWithValueOf} checks (see {@link #isCheckedCandidate}), and writing the given locations + * might change the side's value. * * @param side a side of a chain of assignments (see {@link #sidesOfAssignment}): an entire * target, such as {@code a[i]} (not {@code a} or {@code i}), or the entire rhs of the last @@ -1160,12 +1201,12 @@ private List sidesOfAssignment(AssignmentNode assignment) { * side} is a target, the chain later stores its value into that location, and if {@code side} * is the rhs, the write either happens before {@code side} reads the location or stores the * value that {@code side} read. - * @return true if a store can hold a value for {@code side} and writing {@code written} might - * change its value + * @return true if {@code side} is a checked candidate and writing {@code written} might change + * its value */ private boolean mayBeChanged(Node side, WrittenLocations written) { JavaExpression expr = JavaExpression.fromNode(side); - return CFAbstractStore.canInsertJavaExpression(expr) && written.mayChange(expr, true); + return isCheckedCandidate(expr) && written.mayChange(expr, true); } /** From d37faa75891f459f26143479eae4a8a22cdf1f0e Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 21 Nov 2026 20:35:57 -0800 Subject: [PATCH 46/73] Do not change how a static field access prints in this pull request --- .../ainfer-relevance/LexicallyNestedType.ajava.goal | 2 +- .../ainfer-relevance/RelevantNestedType.ajava.goal | 4 ++-- .../tests/ainfer-relevance/RelevantSubtype.ajava.goal | 2 +- .../tests/ainfer-relevance/RelevantTypes.ajava.goal | 2 +- .../ainfer-relevance/SamePackageShadows.ajava.goal | 4 ++-- .../dataflow/expression/FieldAccess.java | 2 +- .../expression/JavaExpressionToStringTest.java | 10 ---------- 7 files changed, 8 insertions(+), 18 deletions(-) diff --git a/checker/tests/ainfer-relevance/LexicallyNestedType.ajava.goal b/checker/tests/ainfer-relevance/LexicallyNestedType.ajava.goal index e263486216d9..9c24905a55f5 100644 --- a/checker/tests/ainfer-relevance/LexicallyNestedType.ajava.goal +++ b/checker/tests/ainfer-relevance/LexicallyNestedType.ajava.goal @@ -14,7 +14,7 @@ public class LexicallyNestedType { static @org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1 Number nestedNumber; - @org.checkerframework.framework.qual.EnsuresQualifier(expression = { "LexicallyNestedType.nestedNumber" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) + @org.checkerframework.framework.qual.EnsuresQualifier(expression = { "LexicallyNestedType.class.nestedNumber" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) @org.checkerframework.dataflow.qual.Impure static void assignField() { nestedNumber = getSibling1(); diff --git a/checker/tests/ainfer-relevance/RelevantNestedType.ajava.goal b/checker/tests/ainfer-relevance/RelevantNestedType.ajava.goal index 9114d18efff1..16a5e7f5c3b7 100644 --- a/checker/tests/ainfer-relevance/RelevantNestedType.ajava.goal +++ b/checker/tests/ainfer-relevance/RelevantNestedType.ajava.goal @@ -22,7 +22,7 @@ public class RelevantNestedType { // "AbstractMap.SimpleEntry" does not appear in the checker's `@RelevantJavaTypes`. static AbstractMap.@org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1 SimpleEntry subtype; - @org.checkerframework.framework.qual.EnsuresQualifier(expression = { "RelevantNestedType.subtype" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) + @org.checkerframework.framework.qual.EnsuresQualifier(expression = { "RelevantNestedType.class.subtype" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) @org.checkerframework.dataflow.qual.Impure static void assignFields() { nestedName = getSibling1(); @@ -57,7 +57,7 @@ public class RelevantNestedType { return null; } - @org.checkerframework.framework.qual.RequiresQualifier(expression = { "RelevantNestedType.rawName" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) + @org.checkerframework.framework.qual.RequiresQualifier(expression = { "RelevantNestedType.class.rawName" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) @org.checkerframework.dataflow.qual.Pure static AbstractMap.SimpleEntry getSibling1Subtype() { return null; diff --git a/checker/tests/ainfer-relevance/RelevantSubtype.ajava.goal b/checker/tests/ainfer-relevance/RelevantSubtype.ajava.goal index ce31794eed39..3d44a476ea85 100644 --- a/checker/tests/ainfer-relevance/RelevantSubtype.ajava.goal +++ b/checker/tests/ainfer-relevance/RelevantSubtype.ajava.goal @@ -26,7 +26,7 @@ public class RelevantSubtype implements CharSequence { static @org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1 RelevantSubtype field; - @org.checkerframework.framework.qual.EnsuresQualifier(expression = { "RelevantSubtype.field" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) + @org.checkerframework.framework.qual.EnsuresQualifier(expression = { "RelevantSubtype.class.field" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) @org.checkerframework.dataflow.qual.Impure static void assignField() { field = getSibling1(); diff --git a/checker/tests/ainfer-relevance/RelevantTypes.ajava.goal b/checker/tests/ainfer-relevance/RelevantTypes.ajava.goal index ba5b5640cc3d..1a3e10b5e757 100644 --- a/checker/tests/ainfer-relevance/RelevantTypes.ajava.goal +++ b/checker/tests/ainfer-relevance/RelevantTypes.ajava.goal @@ -15,7 +15,7 @@ public class RelevantTypes { static @org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1 CharSequence charSequenceField; - @org.checkerframework.framework.qual.EnsuresQualifier(expression = { "RelevantTypes.charSequenceField" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) + @org.checkerframework.framework.qual.EnsuresQualifier(expression = { "RelevantTypes.class.charSequenceField" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) @org.checkerframework.dataflow.qual.Impure static void assignFields() { intField = getSibling1Int(); diff --git a/checker/tests/ainfer-relevance/SamePackageShadows.ajava.goal b/checker/tests/ainfer-relevance/SamePackageShadows.ajava.goal index bbcc004f03a1..f3cb627ee823 100644 --- a/checker/tests/ainfer-relevance/SamePackageShadows.ajava.goal +++ b/checker/tests/ainfer-relevance/SamePackageShadows.ajava.goal @@ -17,7 +17,7 @@ public class SamePackageShadows { static @org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1 List listField; - @org.checkerframework.framework.qual.EnsuresQualifier(expression = { "SamePackageShadows.listField" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) + @org.checkerframework.framework.qual.EnsuresQualifier(expression = { "SamePackageShadows.class.listField" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) @org.checkerframework.dataflow.qual.Impure static void assignFields() { runnableField = getSibling1Runnable(); @@ -45,7 +45,7 @@ public class SamePackageShadows { return null; } - @org.checkerframework.framework.qual.RequiresQualifier(expression = { "SamePackageShadows.runnableField" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) + @org.checkerframework.framework.qual.RequiresQualifier(expression = { "SamePackageShadows.class.runnableField" }, qualifier = org.checkerframework.checker.testchecker.ainfer.qual.AinferSibling1.class) @org.checkerframework.dataflow.qual.Pure static List getSibling1List() { return null; diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/expression/FieldAccess.java b/dataflow/src/main/java/org/checkerframework/dataflow/expression/FieldAccess.java index 1cf48ccc6b11..0c3e7436ca23 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/expression/FieldAccess.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/expression/FieldAccess.java @@ -160,7 +160,7 @@ public String toString() { if (Node.disambiguateOwner) { return receiverString + "." + field + "{owner=" + ((Symbol) field).owner + "}"; } else { - return receiverString + "." + field; + return receiver.toStringAsPostfixOperand() + "." + field; } } diff --git a/dataflow/src/test/java/org/checkerframework/dataflow/expression/JavaExpressionToStringTest.java b/dataflow/src/test/java/org/checkerframework/dataflow/expression/JavaExpressionToStringTest.java index 17fafb06b041..6fd9c063e20a 100644 --- a/dataflow/src/test/java/org/checkerframework/dataflow/expression/JavaExpressionToStringTest.java +++ b/dataflow/src/test/java/org/checkerframework/dataflow/expression/JavaExpressionToStringTest.java @@ -44,9 +44,6 @@ public class JavaExpressionToStringTest { /** The method {@code Integer.intValue()}. */ private final ExecutableElement intValueMethod; - /** The static field {@code Integer.MAX_VALUE}. */ - private final VariableElement maxValueField; - /** The instance field {@code Integer.value}. */ private final VariableElement valueField; @@ -69,7 +66,6 @@ public JavaExpressionToStringTest() { intType = types.getPrimitiveType(TypeKind.INT); trimMethod = getMethod(stringElement, "trim"); intValueMethod = getMethod(integerElement, "intValue"); - maxValueField = getField(integerElement, "MAX_VALUE"); valueField = getField(integerElement, "value"); } @@ -173,12 +169,6 @@ public void methodCallOnUnknown() { "(b ? x : y).trim()", trim(new Unknown(stringType, "b ? x : y")).toString()); } - @Test - public void fieldAccessOnClassName() { - FieldAccess access = new FieldAccess(new ClassName(integerType), maxValueField); - Assert.assertEquals("java.lang.Integer.MAX_VALUE", access.toString()); - } - @Test public void fieldAccessOnUnknown() { FieldAccess access = new FieldAccess(new Unknown(integerType, "(Integer) o"), valueField); From 7b4921f1385879c74324eaeb940ea290221a3a80 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 21 Nov 2026 20:48:13 -0800 Subject: [PATCH 47/73] Move comparison-specific Index refinements to later pull requests; account for record patterns and String.length() --- .../index/lowerbound/LowerBoundTransfer.java | 48 +++++------ .../index/samelen/SameLenTransfer.java | 72 ++-------------- .../LowerBoundComparisonChangesOperand.java | 42 ---------- .../SameLenComparisonChangesOperand.java | 27 ------ .../nullness/AssignmentInComparison.java | 5 +- .../ComparisonRecordPatternAccessor.java | 76 +++++++++++++++++ .../framework/flow/CFAbstractAnalysis.java | 4 +- .../framework/flow/CFAbstractTransfer.java | 83 +++++++++++-------- .../tests/value/AssignmentInComparison.java | 19 +++++ 9 files changed, 180 insertions(+), 196 deletions(-) delete mode 100644 checker/tests/index/LowerBoundComparisonChangesOperand.java create mode 100644 checker/tests/nullness/java21/ComparisonRecordPatternAccessor.java diff --git a/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java index f025f7adc2f7..c0d36f4a6010 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java @@ -211,11 +211,19 @@ private void notEqualToValue( if (intLiteral == 0) { if (atypeFactory.areSameByClass(otherAnno, NonNegative.class)) { - insertForNodesWithValueOf(otherNode, POS, store); + List internals = nodesWithValueOf(otherNode); + for (Node internal : internals) { + JavaExpression je = JavaExpression.fromNode(internal); + store.insertValue(je, POS); + } } } else if (intLiteral == -1) { if (atypeFactory.areSameByClass(otherAnno, GTENegativeOne.class)) { - insertForNodesWithValueOf(otherNode, NN, store); + List internals = nodesWithValueOf(otherNode); + for (Node internal : internals) { + JavaExpression je = JavaExpression.fromNode(internal); + store.insertValue(je, NN); + } } } } @@ -267,7 +275,7 @@ private void notEqualsLessThan( if (atypeFactory .getLessThanAnnotatedTypeFactory() .isLessThanOrEqual(leftNode.getTree(), otherJe.toString())) { - insertForNodesWithValueOf(otherNode, POS, store); + store.insertValue(otherJe, POS); } } @@ -293,29 +301,19 @@ protected void refineGT( return; } - AnnotationMirror newLBType; + JavaExpression leftJe = JavaExpression.fromNode(left); + if (AnnotationUtils.areSame(rightAnno, GTEN1)) { - newLBType = NN; - } else if (AnnotationUtils.areSame(rightAnno, NN) || AnnotationUtils.areSame(rightAnno, POS)) { - newLBType = POS; - } else { + store.insertValue(leftJe, NN); return; } - insertForNodesWithValueOf(left, newLBType, store); - } - - /** - * Inserts the given annotation into the store for each node that has the value of {@code node} - * when the comparison that contains it completes. Does not insert it for {@code node} if a later - * part of the comparison might change its value, as in {@code i > (i = 0)}. - * - * @param node an operand of a comparison - * @param anno the annotation to insert - * @param store the store to modify - */ - private void insertForNodesWithValueOf(Node node, AnnotationMirror anno, CFStore store) { - for (Node internal : nodesWithValueOf(node)) { - store.insertValue(JavaExpression.fromNode(internal), anno); + if (AnnotationUtils.areSame(rightAnno, NN)) { + store.insertValue(leftJe, POS); + return; + } + if (AnnotationUtils.areSame(rightAnno, POS)) { + store.insertValue(leftJe, POS); + return; } } @@ -340,12 +338,14 @@ protected void refineGTE( return; } + JavaExpression leftJe = JavaExpression.fromNode(left); + AnnotationMirror newLBType = atypeFactory .getQualifierHierarchy() .greatestLowerBoundShallow(rightAnno, left.getType(), leftAnno, right.getType()); - insertForNodesWithValueOf(left, newLBType, store); + store.insertValue(leftJe, newLBType); } /** diff --git a/checker/src/main/java/org/checkerframework/checker/index/samelen/SameLenTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/samelen/SameLenTransfer.java index bd87ee379a83..43cae7e3aecc 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/samelen/SameLenTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/samelen/SameLenTransfer.java @@ -7,7 +7,6 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -import java.util.function.Predicate; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import javax.lang.model.type.TypeKind; @@ -191,77 +190,22 @@ private boolean isArrayLengthAccess(Node node) { * @param store the store in which to perform refinement */ private void refineEq(Node left, Node right, CFStore store) { - TreePath currentPath = atypeFactory.getPath(left.getTree()); - if (currentPath == null) { - // propagateCombinedSameLen would do nothing. - return; - } List exprs = new ArrayList<>(2); List annos = new ArrayList<>(2); - addOperandSameLens(left, currentPath, exprs, annos); - addOperandSameLens(right, currentPath, exprs, annos); + for (Node internal : nodesWithValueOf(left)) { + exprs.add(JavaExpression.fromNode(internal)); + annos.add(getAnno(internal)); + } + for (Node internal : nodesWithValueOf(right)) { + exprs.add(JavaExpression.fromNode(internal)); + annos.add(getAnno(internal)); + } AnnotationMirror combinedSameLen = atypeFactory.createCombinedSameLen(exprs, annos); propagateCombinedSameLen(combinedSameLen, left, store); } - /** - * Adds to {@code exprs} the expressions that have the value of {@code operand} when the - * comparison completes, and adds their SameLen annotations to {@code annos}. - * - *

Each annotation was computed when its expression was evaluated. It omits each name whose - * expression {@code operand} or the rest of the comparison might change, because such a name - * might not have the same length when the comparison completes. For example, in {@code a.length - * == f(c = new int[0], b).length}, if the type of {@code a} is {@code @SameLen("c")}, the - * annotation that this method adds for {@code a} omits {@code c}. - * - * @param operand an operand of a comparison, possibly an assignment - * @param currentPath the path at which to parse the expressions in SameLen annotations - * @param exprs the list of expressions to add to - * @param annos the list of annotations to add to, in parallel with {@code exprs} - */ - private void addOperandSameLens( - Node operand, - TreePath currentPath, - List exprs, - List annos) { - // Computed lazily, because computing it can be costly and most annotations name nothing. - Predicate mayBeChanged = null; - for (Node internal : nodesWithValueOf(operand)) { - exprs.add(JavaExpression.fromNode(internal)); - AnnotationMirror anno = getAnno(internal); - if (anno != null && atypeFactory.areSameByClass(anno, SameLen.class)) { - List names = - AnnotationUtils.getElementValueArray( - anno, atypeFactory.sameLenValueElement, String.class); - if (!names.isEmpty()) { - if (mayBeChanged == null) { - mayBeChanged = mayBeChangedByOrAfter(operand); - } - List unchangedNames = new ArrayList<>(names.size()); - for (String name : names) { - JavaExpression je; - try { - je = atypeFactory.parseJavaExpressionString(name, currentPath); - } catch (JavaExpressionParseException e) { - // The name cannot be checked, and propagateCombinedSameLen would skip it anyway. - continue; - } - if (!mayBeChanged.test(je)) { - unchangedNames.add(name); - } - } - if (unchangedNames.size() != names.size()) { - // `unchangedNames` is a sublist of `names`, so it is in alphabetical order. - anno = atypeFactory.createSameLen(unchangedNames); - } - } - } - annos.add(anno); - } - } - /** * Returns {@code n}'s annotation from the SameLen hierarchy. * diff --git a/checker/tests/index/LowerBoundComparisonChangesOperand.java b/checker/tests/index/LowerBoundComparisonChangesOperand.java deleted file mode 100644 index 1e28e3895db0..000000000000 --- a/checker/tests/index/LowerBoundComparisonChangesOperand.java +++ /dev/null @@ -1,42 +0,0 @@ -// A relational comparison must not refine an operand that a later part of the comparison changes. -// For example, if i is 1, then i > (i = 0) is true, but afterward i is 0. - -import org.checkerframework.checker.index.qual.NonNegative; -import org.checkerframework.checker.index.qual.Positive; - -public class LowerBoundComparisonChangesOperand { - - void gtChangedLater(@NonNegative int i) { - if (i > (i = 0)) { - // :: error: (assignment) - @Positive int p = i; - } - } - - void gtUnchanged(@NonNegative int i, int j) { - if (i > (j = 0)) { - @Positive int p = i; - } - } - - void gteChangedLater(int i) { - if (i >= (i = -1) + 1) { - // :: error: (assignment) - @NonNegative int n = i; - } - } - - void gteUnchanged(int i, int m) { - if (i >= (m = -1) + 1) { - @NonNegative int n = i; - } - } - - // Both sides of an assignment have the value of the operand. - void gtAssignment(int i, int j) { - if ((i = j) > 0) { - @Positive int p = i; - @Positive int q = j; - } - } -} diff --git a/checker/tests/index/SameLenComparisonChangesOperand.java b/checker/tests/index/SameLenComparisonChangesOperand.java index 2dff7199a8bb..eb16b141485f 100644 --- a/checker/tests/index/SameLenComparisonChangesOperand.java +++ b/checker/tests/index/SameLenComparisonChangesOperand.java @@ -2,8 +2,6 @@ // changes the operand's value after evaluating it. For example, if i is 12, then after the // comparison in changedLater, s is "ab3" but "x" + i is "x3". -import org.checkerframework.dataflow.qual.Pure; - public class SameLenComparisonChangesOperand { void changedLater(int i, String s) { @@ -44,29 +42,4 @@ void unchangedInAssignment(String s, String t, String v) { } } } - - @Pure - static int[] keepSecond(int[] x, int[] y) { - return y; - } - - // The type of a is @SameLen("c") when a is evaluated, but the right operand then reassigns c. - void staleNameInType(int[] a, int[] b) { - int[] c = a; - if (a.length == keepSecond(c = new int[0], b).length) { - for (int k = 0; k < a.length; k++) { - // :: error: (array.access.unsafe.high) - c[k] = 0; - } - } - } - - void unchangedNameInType(int[] a, int[] b, int[] d) { - int[] c = a; - if (a.length == keepSecond(d = new int[0], b).length) { - for (int k = 0; k < a.length; k++) { - c[k] = 0; - } - } - } } diff --git a/checker/tests/nullness/AssignmentInComparison.java b/checker/tests/nullness/AssignmentInComparison.java index eb294b39e528..6747eaf65db0 100644 --- a/checker/tests/nullness/AssignmentInComparison.java +++ b/checker/tests/nullness/AssignmentInComparison.java @@ -364,9 +364,8 @@ static void fieldTargetWithAssignmentInReceiver( return o; } - @SuppressWarnings("unchecked") // cast to T - static void arrayTargetTypeVariable(@Nullable T[] ts, @Nullable String[][] ss) { - if ((ts[0] = (T) ss[0][0]) != null) { + static void arrayTargetTypeVariable(@Nullable T[] ts, @Nullable T[][] ss) { + if ((ts[0] = ss[0][0]) != null) { ts[0].toString(); // The assignment to `ts[0]` might change `ss[0]`, if `ts` and `ss` alias. // :: error: [dereference.of.nullable] diff --git a/checker/tests/nullness/java21/ComparisonRecordPatternAccessor.java b/checker/tests/nullness/java21/ComparisonRecordPatternAccessor.java new file mode 100644 index 000000000000..55861645aa4b --- /dev/null +++ b/checker/tests/nullness/java21/ComparisonRecordPatternAccessor.java @@ -0,0 +1,76 @@ +// @below-java21-jdk-skip-test + +// None of the WPI formats supports the new Java 21 language features, so skip inference until they +// do. +// @infer-jaifs-skip-test +// @infer-ajava-skip-test +// @infer-stubs-skip-test + +import org.checkerframework.checker.nullness.qual.Nullable; +import org.checkerframework.dataflow.qual.Pure; + +// Matching a record pattern calls the record's component accessors, which might write fields. +public class ComparisonRecordPatternAccessor { + + static @Nullable String g; + + record Impure(String x) { + public String x() { + g = null; + return x; + } + } + + record Pure1(String x) { + @Pure + public String x() { + return x; + } + } + + record Outer(Impure inner) { + @Pure + public Impure inner() { + return inner; + } + } + + void impureAccessorInSwitch(Impure r, String expected) { + if (g + == (switch (r) { + case Impure(var x) -> expected; + })) { + // The accessor `x()` is called after `g` is read, and it sets `g` to null. + // :: error: [dereference.of.nullable] + g.toString(); + } + } + + void impureAccessorInInstanceof(Object o) { + if (g == (o instanceof Impure(var x) ? "a" : "b")) { + // The accessor `x()` is called after `g` is read, and it sets `g` to null. + // :: error: [dereference.of.nullable] + g.toString(); + } + } + + void impureAccessorInNestedPattern(Outer o, String expected) { + if (g + == (switch (o) { + case Outer(Impure(var x)) -> expected; + })) { + // The accessor `x()` is called after `g` is read, and it sets `g` to null. + // :: error: [dereference.of.nullable] + g.toString(); + } + } + + void pureAccessor(Pure1 r, String expected) { + if (g + == (switch (r) { + case Pure1(var x) -> expected; + })) { + g.toString(); + } + } +} diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java index b748519e3436..34d86f821722 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractAnalysis.java @@ -124,8 +124,8 @@ public record FieldInitialValue>( * argument and on the trees around the argument's tree, but which would otherwise be recomputed * once per dataflow iteration per comparison. * - *

The keys are nodes of a single control flow graph, so {@link #initFields} clears this. - * This is an {@link IdentityHashMap} because the result depends on the trees around the node, but + *

The keys are nodes of a single control flow graph, so {@link #initFields} clears this. This + * is an {@link IdentityHashMap} because the result depends on the trees around the node, but * {@link Node#equals} can be true for nodes that represent different trees. */ final IdentityHashMap> nodesWithValueOfCache = new IdentityHashMap<>(); diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index a477ceb3ea07..44a5972cb9d8 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -25,11 +25,11 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.function.Predicate; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; +import javax.lang.model.element.RecordComponentElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeKind; @@ -150,6 +150,12 @@ public abstract class CFAbstractTransfer< /** The method {@code Object.toString()}, which a string conversion calls. */ private final ExecutableElement objectToString; + /** + * The method {@code String.length()}, whose result depends only on its receiver, because a {@code + * String} is immutable. + */ + private final ExecutableElement stringLength; + /** * Creates a CFAbstractTransfer. * @@ -175,6 +181,7 @@ protected CFAbstractTransfer( !(forceConcurrentSemantics || analysis.checker.hasOption("concurrentSemantics")); this.infer = analysis.checker.hasOption("infer"); this.objectToString = TreeUtils.getMethod("java.lang.Object", "toString", 0, analysis.getEnv()); + this.stringLength = TreeUtils.getMethod("java.lang.String", "length", 0, analysis.getEnv()); } /** @@ -1010,10 +1017,11 @@ protected TransferResult strengthenAnnotationOfEqualTo( * evaluated before {@code b[i]}. * * - * A method call, object creation, or string conversion (which calls {@code toString()}) might - * write any field or array element, unless the method or constructor is side-effect-free (see - * {@link AnnotatedTypeFactory#isSideEffectFree}). The result omits a field that such a call might - * write even when the store would keep the field's refinement across the call, as it does for a + * A method call, object creation, string conversion (which calls {@code toString()}), or record + * pattern (which calls record component accessors) might write any field or array element, unless + * the method or constructor is side-effect-free (see {@link + * AnnotatedTypeFactory#isSideEffectFree}). The result omits a field that such a call might write + * even when the store would keep the field's refinement across the call, as it does for a * refinement to the target of a monotonic qualifier (see {@link * org.checkerframework.framework.qual.MonotonicQualifier}): whether the store keeps a refinement * depends on the refined value, which this method does not know. @@ -1097,30 +1105,6 @@ private static boolean isCheckedCandidate(JavaExpression expr) { && !expr.containsUnknown()); } - /** - * Returns a predicate that is true of each expression whose value, when the comparison that - * contains {@code node} completes, might differ from its value before {@code node} was evaluated. - * The value can differ if {@code node} itself, or the code that is evaluated after {@code node} - * and before the comparison completes, writes a variable, field, or array element that the - * expression reads. See {@link #nodesWithValueOf} for details. - * - *

A client can use this to discard information, computed when {@code node} was evaluated, - * that mentions other expressions. For example, the SameLen Checker uses it to discard the names - * in the {@code @SameLen} type of an operand that are not valid when the comparison completes. - * - * @param node a node in an operand of a comparison, possibly an assignment - * @return a predicate that is true of each expression that evaluating {@code node} and the rest - * of the comparison might change - */ - protected Predicate mayBeChangedByOrAfter(Node node) { - WrittenLocations written = locationsWrittenUntilComparison(node); - TreePath path = sourcePath(node); - if (path != null) { - written.scan(path.getLeaf(), null); - } - return expr -> written.mayChange(expr, false); - } - /** * Returns the sides of the given assignment that have the value of the assignment when the * assignment completes. @@ -1325,9 +1309,10 @@ public Void scan(@Nullable Tree subtree, Void p) { * field, or an array element, such as {@code x}, {@code o.f}, or {@code a[i]}. {@link #add} adds * a write to a given location, and {@link #scan} adds the writes that evaluating a tree might * perform: its assignments, compound assignments, increments, decrements, method calls, object - * creations, and string conversions. A method call, object creation, or string conversion (which - * calls {@code toString()}) might write every non-final field and every array element, unless the - * method or constructor is side-effect-free; {@link #anyHeapLocation} records that. + * creations, string conversions, and record patterns. A method call, object creation, string + * conversion (which calls {@code toString()}), or record pattern (which calls record component + * accessors) might write every non-final field and every array element, unless the method or + * constructor is side-effect-free; {@link #anyHeapLocation} records that. * *

{@link #scan} does not descend into lambda bodies or class bodies, because they do not * execute when the tree is evaluated. The writes of such a body to fields and array elements are @@ -1382,7 +1367,8 @@ void add(JavaExpression target) { /** * Adds the writes that the given tree performs itself, after its subtrees are evaluated: the * write of an assignment, compound assignment, increment, or decrement, and the writes of a - * method call, object creation, or string conversion. Does not add the writes of the subtrees. + * method call, object creation, string conversion, or record pattern. Does not add the writes + * of the subtrees. * * @param tree a tree */ @@ -1409,6 +1395,31 @@ void addOwnWrites(Tree tree) { addCall(TreeUtils.elementFromUse(newClassTree)); } else if (tree instanceof BinaryTree binaryTree && tree.getKind() == Tree.Kind.PLUS) { addStringConversions(binaryTree.getLeftOperand(), binaryTree.getRightOperand()); + } else if (TreeUtils.isDeconstructionPatternTree(tree)) { + addRecordAccessorCalls(tree); + } + } + + /** + * Adds the writes of the calls to record component accessors that matching the given record + * pattern performs, such as the call to {@code x()} when matching {@code R(var x)}. The writes + * of nested record patterns are added when they are scanned. + * + * @param deconstructionPattern a record pattern (a {@code DeconstructionPatternTree}) + */ + private void addRecordAccessorCalls(Tree deconstructionPattern) { + TypeElement record = TypesUtils.getTypeElement(TreeUtils.typeOf(deconstructionPattern)); + if (record == null || record.getKind() != ElementKind.RECORD) { + anyHeapLocation = true; + return; + } + for (RecordComponentElement component : record.getRecordComponents()) { + ExecutableElement accessor = component.getAccessor(); + if (accessor == null) { + anyHeapLocation = true; + } else { + addCall(accessor); + } } } @@ -1503,7 +1514,8 @@ public Void visitClass(ClassTree tree, Void p) { *

A write to a local variable changes only expressions that contain the variable. A write to * a field changes only accesses of the same field, and method calls. A write to an array * element changes only accesses of arrays that might alias the written array, and method calls. - * If side effects unrefine aliases (see {@link + * A call to {@code String.length()} changes only if its receiver changes, because a {@code + * String} is immutable. If side effects unrefine aliases (see {@link * GenericAnnotatedTypeFactory#sideEffectsUnrefineAliases}), then a write to any field or array * element also changes every expression whose abstract value other code can modify (see {@link * JavaExpression#isModifiableByOtherCode}). @@ -1536,6 +1548,9 @@ boolean mayChange(JavaExpression expr, boolean ignoreOwnLocation) { || mayChange(aa.getArray(), false) || mayChange(aa.getIndex(), false); } else if (expr instanceof MethodCall mc) { + if (mc.getElement().equals(stringLength)) { + return mayChange(mc.getReceiver(), false); + } if (anyHeapLocation || !fields.isEmpty() || !arrayElements.isEmpty() diff --git a/framework/tests/value/AssignmentInComparison.java b/framework/tests/value/AssignmentInComparison.java index 2ea3d0bcd5bc..46618b0a184f 100644 --- a/framework/tests/value/AssignmentInComparison.java +++ b/framework/tests/value/AssignmentInComparison.java @@ -54,6 +54,25 @@ static void arrayTargetSameArrayType(int[] a, int[] b, int[] idx) { } } + static class Box { + int f; + } + + static void stringLengthAcrossFieldWrite(String s, Box box) { + // The write to `box.f` cannot change `s.length()`. + if (s.length() == (box.f = 3)) { + @ArrayLen(3) String exact = s; + } + } + + static void stringLengthOfReassignedReceiver(String s, String t) { + if (s.length() == ((s = t) == null ? 3 : 3)) { + // `s` refers to `t` now, not to the string whose length is 3. + // :: error: [assignment] + @ArrayLen(3) String exact = s; + } + } + static void annotationArgumentInRhs(int[] a, int[] b) { // The annotation argument `{0, 1}` is not an assignment to a variable. if ((a = new @IntVal({0, 1}) int[] {0, 1}) == b) { From d356f6a41c18e7a2fad6bf8b96cbf5e96c9108f9 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 22 Nov 2026 21:36:14 -0800 Subject: [PATCH 48/73] Do not propagate a qualifier that a later call might invalidate; account for += string conversion; make test helper pure --- .../SameLenComparisonChangesOperand.java | 25 ++++++++++ .../nonempty/AssignmentInComparison.java | 31 ++++++++++++ .../nullness/AssignmentInComparison.java | 3 ++ .../framework/flow/CFAbstractTransfer.java | 47 ++++++++++++++++++- 4 files changed, 105 insertions(+), 1 deletion(-) diff --git a/checker/tests/index/SameLenComparisonChangesOperand.java b/checker/tests/index/SameLenComparisonChangesOperand.java index eb16b141485f..876b138fafed 100644 --- a/checker/tests/index/SameLenComparisonChangesOperand.java +++ b/checker/tests/index/SameLenComparisonChangesOperand.java @@ -42,4 +42,29 @@ void unchangedInAssignment(String s, String t, String v) { } } } + + static class Holder { + String text = ""; + } + + static Holder current = new Holder(); + + static class Swapper { + @Override + public String toString() { + current = new Holder(); + return ""; + } + } + + // The `+=` evaluates `current` before it converts `sw` to a string, and that conversion + // reassigns `current`. So the assignment stores into the `text` field of the old `current`. + void stringConversionInCompoundAssignmentReassignsReceiver(String peer, Swapper sw) { + if ((current.text += sw).length() == peer.length()) { + for (int k = 0; k < peer.length(); k++) { + // :: error: (argument) + current.text.charAt(k); + } + } + } } diff --git a/checker/tests/nonempty/AssignmentInComparison.java b/checker/tests/nonempty/AssignmentInComparison.java index 33cc42ff6c2b..c330199f6732 100644 --- a/checker/tests/nonempty/AssignmentInComparison.java +++ b/checker/tests/nonempty/AssignmentInComparison.java @@ -18,4 +18,35 @@ void callInRhs(@NonEmpty List ne) { @NonEmpty List m = l; } } + + // Not side-effect-free. + static List clearAndReturn(List l) { + l.clear(); + return l; + } + + // The call in the right operand might empty the list that `a` denotes, after the left operand + // reads `a`. The qualifier that `a` had when it was read does not hold for `b`. + void callInRightOperandChangesLeftOperand(List a) { + if (a.isEmpty()) { + return; + } + List b; + if (a == (b = clearAndReturn(a))) { + // :: error: [assignment] + @NonEmpty List m = b; + } + } + + // A reassignment of `a` in the right operand does not change the list that `a` denoted when the + // left operand read it. + void reassignmentInRightOperand(List a, List c) { + if (a.isEmpty()) { + return; + } + List b; + if (a == (b = (a = c))) { + @NonEmpty List m = b; + } + } } diff --git a/checker/tests/nullness/AssignmentInComparison.java b/checker/tests/nullness/AssignmentInComparison.java index 6747eaf65db0..d23533cf07d4 100644 --- a/checker/tests/nullness/AssignmentInComparison.java +++ b/checker/tests/nullness/AssignmentInComparison.java @@ -373,6 +373,9 @@ static void arrayTargetTypeVariable(@Nullable T[] ts, @Nullable T[][] ss) { } } + // Side-effect-free, so that a test of an aliased write in an argument does not depend on the + // writes of the call. + @Pure static Object nonNull(@Nullable Object o) { return ""; } diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 44a5972cb9d8..3ca92794c1ca 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -942,6 +942,11 @@ public TransferResult visitNotEqual(NotEqualNode n, TransferInput p) * secondNode}. The result omits each node that might not have the value of {@code secondNode} * when the comparison completes; do not insert the new type for such a node. * + *

This method does nothing if {@code firstValue} might not hold for the value of {@code + * firstNode} when the comparison completes. That is possible if side effects unrefine aliases + * (see {@link GenericAnnotatedTypeFactory#sideEffectsUnrefineAliases}), as in {@code a == (b = + * clear(a))}. + * * @param firstNode the node that might be more precise * @param secondNode the node whose type to possibly refine * @param firstValue the abstract value that might be more precise @@ -960,7 +965,7 @@ protected TransferResult strengthenAnnotationOfEqualTo( boolean notEqualTo) { if (firstValue != null) { // Only need to insert if the second value is actually different. - if (!firstValue.equals(secondValue)) { + if (!firstValue.equals(secondValue) && !abstractValueMayChangeBeforeComparison(firstNode)) { List secondParts = nodesWithValueOf(secondNode); for (Node secondPart : secondParts) { JavaExpression secondInternal = JavaExpression.fromNode(secondPart); @@ -985,6 +990,28 @@ protected TransferResult strengthenAnnotationOfEqualTo( return res; } + /** + * Returns true if the abstract value that the given operand of a comparison had when it was + * evaluated might not hold for the value it denotes when the comparison completes. This is + * possible only if side effects unrefine aliases (see {@link + * GenericAnnotatedTypeFactory#sideEffectsUnrefineAliases}): then a call that is evaluated after + * the operand and before the comparison completes might change the abstract value of the object + * that the operand denotes, as in {@code a == (b = clear(a))}. A write that only reassigns a + * variable, field, or array element that the operand reads does not matter, because it does not + * change the object that the operand evaluated to. + * + * @param node an operand of a comparison, possibly an assignment + * @return true if the abstract value of {@code node} might not hold for its value when the + * comparison completes + */ + private boolean abstractValueMayChangeBeforeComparison(Node node) { + if (!analysis.atypeFactory.sideEffectsUnrefineAliases + || !JavaExpression.fromNode(node).isModifiableByOtherCode()) { + return false; + } + return locationsWrittenUntilComparison(node).mayWriteAnyHeapLocation(); + } + /** * Returns the nodes that have the value of the given node when the comparison that contains the * node completes. The comparison is a binary comparison such as {@code ==} or {@code <}, and the @@ -1143,6 +1170,14 @@ private List sidesOfAssignment(AssignmentNode assignment) { if (rhsTree != null) { written.scan(rhsTree, null); } + // The string conversion of a `+=` in `chain` (which calls `toString()`) happens after `rhs` is + // evaluated and after the receivers and indices of the targets are evaluated. + for (AssignmentNode a : chain) { + Tree tree = a.getTree(); + if (tree != null) { + written.addOwnWrites(tree); + } + } // The sides that the result contains, in source order: `sides[i]` is the target of // `chain.get(i)`, and `sides[chain.size()]` is `rhs`. An element is null if the result omits // that side. @@ -1344,6 +1379,16 @@ private final class WrittenLocations extends TreeScanner { /** Creates an empty set of locations. */ WrittenLocations() {} + /** + * Returns true if every non-final field and every array element might be written, as by a call + * to a method that is not side-effect-free. + * + * @return true if every non-final field and every array element might be written + */ + boolean mayWriteAnyHeapLocation() { + return anyHeapLocation; + } + /** * Adds a write to the given location. * From bad0810f27f59c24a454bdb9f6bd3619c65395ac Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 23 Nov 2026 07:38:32 -0800 Subject: [PATCH 49/73] Do not parenthesize an IteratedCollectionElement receiver; fix test Javadoc articles --- .../dataflow/expression/JavaExpression.java | 1 + .../expression/JavaExpressionToStringTest.java | 14 +++++++------- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java b/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java index 3c360bc46c51..c5dd864f1d44 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java @@ -430,6 +430,7 @@ public String toStringAsPostfixOperand() { || this instanceof FieldAccess || this instanceof MethodCall || this instanceof ArrayAccess + || this instanceof IteratedCollectionElement || this instanceof ThisReference || this instanceof SuperReference || this instanceof ClassName) { diff --git a/dataflow/src/test/java/org/checkerframework/dataflow/expression/JavaExpressionToStringTest.java b/dataflow/src/test/java/org/checkerframework/dataflow/expression/JavaExpressionToStringTest.java index 6fd9c063e20a..7819c142bfb4 100644 --- a/dataflow/src/test/java/org/checkerframework/dataflow/expression/JavaExpressionToStringTest.java +++ b/dataflow/src/test/java/org/checkerframework/dataflow/expression/JavaExpressionToStringTest.java @@ -102,30 +102,30 @@ private static VariableElement getField(TypeElement type, String name) { } /** - * Returns a call to {@code String.trim()} on the given receiver. + * Returns the call to {@code String.trim()} on the given receiver. * * @param receiver a receiver of type String - * @return a call to {@code trim()} on the receiver + * @return the call to {@code trim()} on the receiver */ private MethodCall trim(JavaExpression receiver) { return new MethodCall(stringType, trimMethod, receiver, Collections.emptyList()); } /** - * Returns a call to {@code Integer.intValue()} on the given receiver. + * Returns the call to {@code Integer.intValue()} on the given receiver. * * @param receiver a receiver of type Integer - * @return a call to {@code intValue()} on the receiver + * @return the call to {@code intValue()} on the receiver */ private MethodCall intValue(JavaExpression receiver) { return new MethodCall(intType, intValueMethod, receiver, Collections.emptyList()); } /** - * Returns an int literal. + * Returns the int literal for the given value. * - * @param value the value of the literal - * @return an int literal for the value + * @param value an int + * @return the int literal for the value */ private ValueLiteral intLiteral(int value) { return new ValueLiteral(intType, value); From cde73f71dfea4da07b6955bcac06f9dd5bcb6405 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 23 Nov 2026 17:21:14 -0800 Subject: [PATCH 50/73] Give one reason for parenthesizing a postfix operand: regrouping or failing to parse --- .../dataflow/expression/JavaExpression.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java b/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java index c5dd864f1d44..8fe55af14080 100644 --- a/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java +++ b/dataflow/src/main/java/org/checkerframework/dataflow/expression/JavaExpression.java @@ -413,14 +413,14 @@ public JavaExpression atConstructorInvocation(NewClassTree newClassTree) { /** * Returns the printed form of this expression, as it should appear immediately before a postfix * operation, such as a method call {@code .m()} or an array access {@code [i]}. The result is - * parenthesized unless this is an expression that the postfix operation cannot regroup. For - * example, the binary operation {@code a + b} yields {@code (a + b)}, so that a method call on it - * prints as {@code (a + b).trim()} rather than as {@code a + b.trim()}, which means something - * different; and the numeric literal {@code 5} yields {@code (5)}, because {@code 5.intValue()} - * does not parse. - * - * @return the printed form of this expression, parenthesized if a postfix operation could regroup - * it + * parenthesized if appending a postfix operation to the unparenthesized form could regroup it or + * could yield text that does not parse. For example, the binary operation {@code a + b} yields + * {@code (a + b)}, so that a method call on it prints as {@code (a + b).trim()} rather than as + * {@code a + b.trim()}, which means something different; and the numeric literal {@code 5} yields + * {@code (5)}, because {@code 5.intValue()} does not parse. + * + * @return the printed form of this expression, parenthesized if appending a postfix operation to + * the unparenthesized form could regroup it or could yield text that does not parse */ @Pure public String toStringAsPostfixOperand() { From a668b0831259f15c4d4a9dee7e6da4115b067985 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Wed, 25 Nov 2026 11:39:22 -0800 Subject: [PATCH 51/73] Address review: stale sequence bounds, string conversion, array-reference abstract values - UpperBoundTransfer: in refineEq and refineNeqSequenceLength, drop bounds of an operand whose sequence or offset might change before the comparison completes, and do not refine against a length whose sequence might change. - CFAbstractTransfer: add mayChangeAfterOperand(); check only the value (not the abstract value) of receivers, indices, arguments, and operands in mayChange; treat string concatenation of a possibly mutable object as reading the heap. --- .../index/upperbound/OffsetEquation.java | 21 +++ .../checker/index/upperbound/UBQualifier.java | 33 +++++ .../index/upperbound/UpperBoundTransfer.java | 71 +++++++++- .../SameLenComparisonChangesOperand.java | 36 +++++ .../UpperBoundComparisonChangesSequence.java | 55 ++++++++ .../nonempty/AssignmentInComparison.java | 8 ++ docs/CHANGELOG.md | 4 +- .../framework/flow/CFAbstractTransfer.java | 124 ++++++++++++++++-- 8 files changed, 333 insertions(+), 19 deletions(-) create mode 100644 checker/tests/index/UpperBoundComparisonChangesSequence.java diff --git a/checker/src/main/java/org/checkerframework/checker/index/upperbound/OffsetEquation.java b/checker/src/main/java/org/checkerframework/checker/index/upperbound/OffsetEquation.java index 38860e4bcaba..adcb5f75a6a6 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/upperbound/OffsetEquation.java +++ b/checker/src/main/java/org/checkerframework/checker/index/upperbound/OffsetEquation.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.Objects; import java.util.Set; +import java.util.function.Predicate; import java.util.regex.Pattern; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.common.value.ValueAnnotatedTypeFactory; @@ -150,6 +151,26 @@ public String toString() { return terms; } + /** + * Returns true if the given predicate is true for any added or subtracted term of this. + * + * @param p a predicate on Java expression strings + * @return true if {@code p} is true for any term of this + */ + public boolean anyTermMatches(Predicate p) { + for (String term : addedTerms) { + if (p.test(term)) { + return true; + } + } + for (String term : subtractedTerms) { + if (p.test(term)) { + return true; + } + } + return false; + } + /** * Makes a copy of this offset and removes any added terms that are accesses to the length of the * listed sequences. If any terms were removed, then the copy is returned. Otherwise, null is diff --git a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UBQualifier.java b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UBQualifier.java index ba8f1ab5d262..58edeb1a7bd0 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UBQualifier.java +++ b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UBQualifier.java @@ -8,6 +8,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.function.Predicate; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import org.checkerframework.checker.index.qual.LTEqLengthOf; @@ -1218,6 +1219,38 @@ public Iterable getSequences() { return map.keySet(); } + /** + * Returns a copy of this qualifier without each (sequence, offset) pair for which {@code + * mayChange} is true of the sequence or of a term of the offset. Returns UNKNOWN if no pair + * remains. + * + * @param mayChange a predicate on Java expression strings: true if the expression might no + * longer have the value that this qualifier refers to + * @return a copy of this qualifier without the pairs that depend on an expression for which + * {@code mayChange} is true + */ + public UBQualifier removeDependentsOf(Predicate mayChange) { + Map> newMap = new HashMap<>(map.size()); + for (Map.Entry> entry : map.entrySet()) { + if (mayChange.test(entry.getKey())) { + continue; + } + Set offsets = new HashSet<>(entry.getValue().size()); + for (OffsetEquation eq : entry.getValue()) { + if (!eq.anyTermMatches(mayChange)) { + offsets.add(eq); + } + } + if (!offsets.isEmpty()) { + newMap.put(entry.getKey(), offsets); + } + } + if (newMap.isEmpty()) { + return UpperBoundUnknownQualifier.UNKNOWN; + } + return new LessThanLengthOf(newMap); + } + /** * Generates a new UBQualifier without the given (sequence, offset) pair. Other occurrences of * the sequence and the offset might remain in the result, but not together. diff --git a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java index c15fb409668b..5a07ff806175 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java @@ -6,6 +6,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.function.Predicate; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import javax.lang.model.type.TypeKind; @@ -420,13 +421,22 @@ protected TransferResult strengthenAnnotationOfEqualTo( return rfi.newResult; } - /** Refines the type of the left and right node to glb of the left and right annotation. */ + /** + * Refines the type of the left and right node to glb of the left and right annotation. + * + *

Each annotation omits the bounds that might not hold when the comparison completes (see + * {@link #removeBoundsChangedAfter}). + */ private void refineEq( Node left, AnnotationMirror leftAnno, Node right, AnnotationMirror rightAnno, CFStore store) { UBQualifier leftQualifier = - UBQualifier.createUBQualifier(leftAnno, (UpperBoundChecker) atypeFactory.getChecker()); + removeBoundsChangedAfter( + UBQualifier.createUBQualifier(leftAnno, (UpperBoundChecker) atypeFactory.getChecker()), + left); UBQualifier rightQualifier = - UBQualifier.createUBQualifier(rightAnno, (UpperBoundChecker) atypeFactory.getChecker()); + removeBoundsChangedAfter( + UBQualifier.createUBQualifier(rightAnno, (UpperBoundChecker) atypeFactory.getChecker()), + right); UBQualifier glb = rightQualifier.glb(leftQualifier); AnnotationMirror glbAnno = atypeFactory.convertUBQualifierToAnnotation(glb); @@ -448,9 +458,21 @@ private void refineEq( * offset subtracted) and the other node is less than or equal to that sequence length (minus the * offset), then refine the other node's type to less than the sequence length (minus the offset). * This is case 12. + * + *

Does nothing if the sequence might change after {@code lengthAccess} is evaluated and before + * the comparison completes, because then the comparison does not relate the other node to the + * length of the sequence that the new type refers to. Omits the bounds of the other node's type + * that might not hold when the comparison completes (see {@link #removeBoundsChangedAfter}). + * + * @param lengthAccess an operand of a comparison + * @param otherNode the other operand of the comparison + * @param otherNodeAnno the upper bound annotation of {@code otherNode} + * @param store the store to refine */ private void refineNeqSequenceLength( Node lengthAccess, Node otherNode, AnnotationMirror otherNodeAnno, CFStore store) { + // The operand of the comparison, before any subtraction of a constant is stripped. + Node lengthAccessOperand = lengthAccess; // If lengthAccess is "receiver.length - c" where c is an integer constant, // then lengthOffset is "c". @@ -485,9 +507,16 @@ private void refineNeqSequenceLength( } if (receiver != null && !receiver.containsUnknown()) { + Predicate mayChange = mayChangeAfterOperand(lengthAccessOperand); + if (mayChange != null && mayChange.test(receiver)) { + // The comparison used the length of the sequence before it changed. + return; + } UBQualifier otherQualifier = - UBQualifier.createUBQualifier( - otherNodeAnno, (UpperBoundChecker) atypeFactory.getChecker()); + removeBoundsChangedAfter( + UBQualifier.createUBQualifier( + otherNodeAnno, (UpperBoundChecker) atypeFactory.getChecker()), + otherNode); String sequence = receiver.toString(); // Check if otherNode + c - 1 < receiver.length if (otherQualifier.hasSequenceWithOffset(sequence, lengthOffset - 1)) { @@ -503,6 +532,38 @@ private void refineNeqSequenceLength( } } + /** + * Returns the given qualifier of an operand of a comparison, without each bound whose sequence or + * offset might change after the operand produces its value and before the comparison completes. + * Such a bound described the operand's value when the operand was evaluated, but it might not + * hold when the comparison completes. For example, in {@code this.a.length == (i = replaceA())}, + * the bound {@code @LTEqLengthOf("this.a")} of {@code this.a.length} does not hold after {@code + * replaceA()} reassigns {@code this.a}. + * + * @param qualifier the qualifier of {@code operand} + * @param operand an operand of a comparison + * @return {@code qualifier}, without the bounds that might not hold when the comparison completes + */ + private UBQualifier removeBoundsChangedAfter(UBQualifier qualifier, Node operand) { + if (!(qualifier instanceof LessThanLengthOf ltl)) { + return qualifier; + } + Predicate mayChange = mayChangeAfterOperand(operand); + if (mayChange == null) { + return qualifier; + } + TreePath path = sourcePath(operand); + if (path == null) { + return UpperBoundUnknownQualifier.UNKNOWN; + } + return ltl.removeDependentsOf( + s -> { + JavaExpression je = UpperBoundVisitor.parseJavaExpressionString(s, atypeFactory, path); + // Conservatively assume that an expression that cannot be parsed might change. + return je == null || mayChange.test(je); + }); + } + /** * If some Node a is known to be less than the length of some array, x, then the type of a + b * is @LTLengthOf(value="x", offset="-b"). If b is known to be less than the length of some other diff --git a/checker/tests/index/SameLenComparisonChangesOperand.java b/checker/tests/index/SameLenComparisonChangesOperand.java index 876b138fafed..cb6a34135182 100644 --- a/checker/tests/index/SameLenComparisonChangesOperand.java +++ b/checker/tests/index/SameLenComparisonChangesOperand.java @@ -67,4 +67,40 @@ void stringConversionInCompoundAssignmentReassignsReceiver(String peer, Swapper } } } + + static class Box { + String text = ""; + + @Override + public String toString() { + return text; + } + } + + // Not side-effect-free. + static String setText(Box box, String t) { + box.text = t; + return t; + } + + // The string conversion of `box` calls `box.toString()`, whose result the call to `setText` + // changes. So after the comparison, "p" + box might be longer than s. + void changedByToString(Box box, String s) { + if (("p" + box).length() == (s = setText(box, "abc")).length()) { + String u = "p" + box; + for (int k = 0; k < u.length(); k++) { + // :: error: (argument) + s.charAt(k); + } + } + } + + void unchangedByToString(Box box, String s, String t) { + if (("p" + box).length() == (s = t).length()) { + String u = "p" + box; + for (int k = 0; k < u.length(); k++) { + s.charAt(k); + } + } + } } diff --git a/checker/tests/index/UpperBoundComparisonChangesSequence.java b/checker/tests/index/UpperBoundComparisonChangesSequence.java new file mode 100644 index 000000000000..023062a57463 --- /dev/null +++ b/checker/tests/index/UpperBoundComparisonChangesSequence.java @@ -0,0 +1,55 @@ +import org.checkerframework.checker.index.qual.LTEqLengthOf; + +// A bound in the type of an operand of a comparison refers to a sequence as it was when the operand +// was evaluated. If the other operand reassigns the sequence, the bound must not be used to refine +// the types of expressions after the comparison. + +public class UpperBoundComparisonChangesSequence { + + int[] a = new int[2]; + + // Not side-effect-free. + int replaceAndReturnTwo() { + a = new int[0]; + return 2; + } + + // Not side-effect-free. + @LTEqLengthOf("this.a") int shrink() { + a = new int[1]; + return 1; + } + + // If this.a has length 2 before the call, then i is 2 but this.a has length 0 after the call. + void eqChanged() { + int i; + if (this.a.length == (i = replaceAndReturnTwo())) { + // :: error: (assignment) + @LTEqLengthOf("this.a") int j = i; + } + } + + void eqUnchanged(int k) { + int i; + if (this.a.length == (i = k)) { + @LTEqLengthOf("this.a") int j = i; + } + } + + // If this.a has length 2 before the call, then the comparison is 2 != 1, but i is 1 and this.a + // has length 1 after the call. + void neqChanged() { + int i; + if (this.a.length != (i = shrink())) { + // :: error: (array.access.unsafe.high) + int x = this.a[i]; + } + } + + void neqUnchanged(@LTEqLengthOf("this.a") int k) { + int i; + if (this.a.length != (i = k)) { + int x = this.a[i]; + } + } +} diff --git a/checker/tests/nonempty/AssignmentInComparison.java b/checker/tests/nonempty/AssignmentInComparison.java index c330199f6732..faee201769f7 100644 --- a/checker/tests/nonempty/AssignmentInComparison.java +++ b/checker/tests/nonempty/AssignmentInComparison.java @@ -19,6 +19,14 @@ void callInRhs(@NonEmpty List ne) { } } + // The call in the rhs might change the abstract value of the list that `slots` denotes, but not + // which array `slots` denotes, so it does not change which element the assignment stores into. + void callInRhsArrayElementTarget(List[] slots, @NonEmpty List ne) { + if ((slots[0] = newList()) == ne) { + @NonEmpty List m = slots[0]; + } + } + // Not side-effect-free. static List clearAndReturn(List l) { l.clear(); diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index a05f67a7499e..ccbe3f97e085 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -13,7 +13,9 @@ Renamed `CFAbstractTransfer.splitAssignments()` to `nodesWithValueOf()`. Its result omits each node that might have a different value by the time the enclosing comparison completes, such as `n.next` in `n.next == (n = o)`, so the result can be empty. A subclass that overrides `splitAssignments()` must -override `nodesWithValueOf()` instead. +override `nodesWithValueOf()` instead. New method +`CFAbstractTransfer.mayChangeAfterOperand()` tells whether an expression that an +operand's type depends on might change before the comparison completes. `CFAbstractStore.canAlias()` is now final. It calls the new method `CFAbstractAnalysis.canAlias()`, which calls the new method diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 3ca92794c1ca..1adb68022640 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -25,6 +25,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.function.Predicate; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; @@ -1012,6 +1013,44 @@ private boolean abstractValueMayChangeBeforeComparison(Node node) { return locationsWrittenUntilComparison(node).mayWriteAnyHeapLocation(); } + /** + * Returns a test for expressions whose values might change after the given operand of a + * comparison produces its value and before the comparison completes. Returns null if no + * variable, field, or array element is written in that time. + * + *

A client uses the test for an expression that the abstract value of the operand depends on, + * such as {@code a} in {@code @LTLengthOf("a")}. If the test returns true, the abstract value + * might not be valid when the comparison completes. For example, in {@code a.length == (i = + * replaceA())}, the abstract value of {@code a.length} depends on {@code a}, which {@code + * replaceA()} might write. + * + *

If {@code operand} is an assignment, the writes include those of its targets, which happen + * after its value is computed. The test does not consider changes to the abstract value of the + * object that an expression denotes. + * + * @param operand an operand of a comparison + * @return a test for whether the value of an expression might change after {@code operand} + * produces its value and before the comparison completes, or null if no location is written + * in that time + */ + protected @Nullable Predicate mayChangeAfterOperand(Node operand) { + WrittenLocations written = locationsWrittenUntilComparison(operand); + Node n = operand; + while (n instanceof AssignmentNode assignment) { + written.add(JavaExpression.fromNode(assignment.getTarget())); + Tree tree = assignment.getTree(); + if (tree != null) { + // A compound assignment `+=` might perform a string conversion. + written.addOwnWrites(tree); + } + n = assignment.getExpression(); + } + if (written.isEmpty()) { + return null; + } + return expr -> written.valueMayChange(expr, false); + } + /** * Returns the nodes that have the value of the given node when the comparison that contains the * node completes. The comparison is a binary comparison such as {@code ==} or {@code <}, and the @@ -1298,7 +1337,7 @@ private WrittenLocations locationsWrittenUntilComparison(Node node) { * @param node a node * @return the path to the source tree that {@code node} represents, or null if there is none */ - private @Nullable TreePath sourcePath(Node node) { + protected @Nullable TreePath sourcePath(Node node) { Tree tree = node.getTree(); if (tree != null) { TreePath path = analysis.atypeFactory.getPath(tree); @@ -1560,7 +1599,10 @@ public Void visitClass(ClassTree tree, Void p) { * a field changes only accesses of the same field, and method calls. A write to an array * element changes only accesses of arrays that might alias the written array, and method calls. * A call to {@code String.length()} changes only if its receiver changes, because a {@code - * String} is immutable. If side effects unrefine aliases (see {@link + * String} is immutable. A string concatenation with an operand whose string conversion calls + * {@code toString()} on a possibly mutable object, as in {@code "p" + box}, changes like a + * method call. A change to the abstract value of a receiver, index, argument, or operand does + * not matter (see {@link #valueMayChange}). If side effects unrefine aliases (see {@link * GenericAnnotatedTypeFactory#sideEffectsUnrefineAliases}), then a write to any field or array * element also changes every expression whose abstract value other code can modify (see {@link * JavaExpression#isModifiableByOtherCode}). @@ -1584,34 +1626,60 @@ boolean mayChange(JavaExpression expr, boolean ignoreOwnLocation) { // writes, so its abstract value is the one that was stored. return true; } + return valueMayChange(expr, ignoreOwnLocation); + } + + /** + * Returns true if writing these locations might change the value of {@code expr}, as for {@link + * #mayChange}, but ignoring changes to the abstract value of the object that {@code expr} + * denotes. For example, if {@code expr} is {@code a}, a write to {@code a} changes it, but a + * write to {@code a.f} or {@code a[0]} does not. + * + *

This is the right check for a subexpression of a candidate, such as the receiver or index + * of an array access: only the value of the subexpression determines which location the + * candidate denotes, so a change to its abstract value does not matter. + * + * @param expr an expression + * @param ignoreOwnLocation true if a write to the location that {@code expr} denotes does not + * matter; see {@link #mayChange} + * @return true if evaluating {@code expr} after writing these locations might yield a different + * value than evaluating it before + */ + boolean valueMayChange(JavaExpression expr, boolean ignoreOwnLocation) { if (expr instanceof LocalVariable) { return !ignoreOwnLocation && locals.contains(expr); } else if (expr instanceof FieldAccess fa) { - return (!ignoreOwnLocation && mayWriteField(fa)) || mayChange(fa.getReceiver(), false); + return (!ignoreOwnLocation && mayWriteField(fa)) || valueMayChange(fa.getReceiver(), false); } else if (expr instanceof ArrayAccess aa) { return (!ignoreOwnLocation && mayWriteArrayElement(aa)) - || mayChange(aa.getArray(), false) - || mayChange(aa.getIndex(), false); + || valueMayChange(aa.getArray(), false) + || valueMayChange(aa.getIndex(), false); } else if (expr instanceof MethodCall mc) { if (mc.getElement().equals(stringLength)) { - return mayChange(mc.getReceiver(), false); + return valueMayChange(mc.getReceiver(), false); } - if (anyHeapLocation - || !fields.isEmpty() - || !arrayElements.isEmpty() - || mayChange(mc.getReceiver(), false)) { + if (mayWriteHeap() || valueMayChange(mc.getReceiver(), false)) { return true; } for (JavaExpression arg : mc.getArguments()) { - if (mayChange(arg, false)) { + if (valueMayChange(arg, false)) { return true; } } return false; } else if (expr instanceof UnaryOperation uo) { - return mayChange(uo.getOperand(), false); + return valueMayChange(uo.getOperand(), false); } else if (expr instanceof BinaryOperation bo) { - return mayChange(bo.getLeft(), false) || mayChange(bo.getRight(), false); + if (bo.getOperationKind() == Tree.Kind.PLUS + && TypesUtils.isString(bo.getType()) + && (toStringMayReadHeap(bo.getLeft().getType()) + || toStringMayReadHeap(bo.getRight().getType())) + && mayWriteHeap()) { + // The string conversion of an operand calls its `toString()` method, whose result might + // depend on any field or array element, as for a method call. + return true; + } + return valueMayChange(bo.getLeft(), false) || valueMayChange(bo.getRight(), false); } else { // An Unknown or ArrayCreation might be changed. return !(expr instanceof ClassName @@ -1622,6 +1690,36 @@ boolean mayChange(JavaExpression expr, boolean ignoreOwnLocation) { } } + /** + * Returns true if these locations might include a field or an array element. + * + * @return true if these locations might include a field or an array element + */ + private boolean mayWriteHeap() { + return anyHeapLocation || !fields.isEmpty() || !arrayElements.isEmpty(); + } + + /** + * Returns true if no location is written. + * + * @return true if no location is written + */ + boolean isEmpty() { + return !anyHeapLocation && locals.isEmpty() && fields.isEmpty() && arrayElements.isEmpty(); + } + + /** + * Returns true if the result of the string conversion of a value of the given type might depend + * on a field or an array element. That is the case if the conversion calls {@code toString()} + * on an object that might be mutable: not a {@code String} or a boxed primitive. + * + * @param type the type of an operand of a string concatenation + * @return true if the string conversion of a value of {@code type} might read the heap + */ + private boolean toStringMayReadHeap(TypeMirror type) { + return callsToString(type) && !TypesUtils.isBoxedPrimitive(type); + } + /** * Returns true if these locations might include the field that {@code fa} denotes. * From 350791fded5a78218e888963880f3d53285aecac Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Wed, 25 Nov 2026 22:11:54 -0800 Subject: [PATCH 52/73] Reformat --- .../checkerframework/framework/flow/CFAbstractTransfer.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 1adb68022640..0e57c528ff21 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -1015,8 +1015,8 @@ private boolean abstractValueMayChangeBeforeComparison(Node node) { /** * Returns a test for expressions whose values might change after the given operand of a - * comparison produces its value and before the comparison completes. Returns null if no - * variable, field, or array element is written in that time. + * comparison produces its value and before the comparison completes. Returns null if no variable, + * field, or array element is written in that time. * *

A client uses the test for an expression that the abstract value of the operand depends on, * such as {@code a} in {@code @LTLengthOf("a")}. If the test returns true, the abstract value From c358f4024d75aa164d4111a8daf881f2b75e4d7b Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Thu, 26 Nov 2026 22:30:51 -0800 Subject: [PATCH 53/73] Address review: stale bounds in Each annotation omits the bounds that might not hold when the comparison completes (see + * {@link #removeBoundsChangedAfter}). */ @Override protected void refineGT( @@ -349,12 +352,10 @@ protected void refineGT( CFStore store, TransferInput in) { // larger > smaller - UBQualifier largerQual = - UBQualifier.createUBQualifier(largerAnno, (UpperBoundChecker) atypeFactory.getChecker()); + UBQualifier largerQual = qualifierWhenComparisonCompletes(largerAnno, larger); // larger + 1 >= smaller UBQualifier largerQualPlus1 = largerQual.plusOffset(1); - UBQualifier rightQualifier = - UBQualifier.createUBQualifier(smallerAnno, (UpperBoundChecker) atypeFactory.getChecker()); + UBQualifier rightQualifier = qualifierWhenComparisonCompletes(smallerAnno, smaller); UBQualifier refinedRight = rightQualifier.glb(largerQualPlus1); if (largerQualPlus1.isLessThanLengthQualifier()) { @@ -370,6 +371,9 @@ protected void refineGT( /** * Case 9: if x ≤ y, and y has a type that is related to the length of an array, then x has the * same type. + * + *

Each annotation omits the bounds that might not hold when the comparison completes (see + * {@link #removeBoundsChangedAfter}). */ @Override protected void refineGTE( @@ -379,10 +383,8 @@ protected void refineGTE( AnnotationMirror rightAnno, CFStore store, TransferInput in) { - UBQualifier leftQualifier = - UBQualifier.createUBQualifier(leftAnno, (UpperBoundChecker) atypeFactory.getChecker()); - UBQualifier rightQualifier = - UBQualifier.createUBQualifier(rightAnno, (UpperBoundChecker) atypeFactory.getChecker()); + UBQualifier leftQualifier = qualifierWhenComparisonCompletes(leftAnno, left); + UBQualifier rightQualifier = qualifierWhenComparisonCompletes(rightAnno, right); UBQualifier refinedRight = rightQualifier.glb(leftQualifier); if (leftQualifier.isLessThanLengthQualifier()) { @@ -420,7 +422,7 @@ private void refineSubtrahendWithOffset( if (gtNode instanceof NumericalSubtractionNode subtractionNode) { Node minuend = subtractionNode.getLeftOperand(); - UBQualifier minuendQual = getUBQualifier(minuend, in); + UBQualifier minuendQual = removeBoundsChangedAfter(getUBQualifier(minuend, in), minuend); Node subtrahend = subtractionNode.getRightOperand(); UBQualifier subtrahendQual = getUBQualifier(subtrahend, in); @@ -467,14 +469,8 @@ protected TransferResult strengthenAnnotationOfEqualTo( */ private void refineEq( Node left, AnnotationMirror leftAnno, Node right, AnnotationMirror rightAnno, CFStore store) { - UBQualifier leftQualifier = - removeBoundsChangedAfter( - UBQualifier.createUBQualifier(leftAnno, (UpperBoundChecker) atypeFactory.getChecker()), - left); - UBQualifier rightQualifier = - removeBoundsChangedAfter( - UBQualifier.createUBQualifier(rightAnno, (UpperBoundChecker) atypeFactory.getChecker()), - right); + UBQualifier leftQualifier = qualifierWhenComparisonCompletes(leftAnno, left); + UBQualifier rightQualifier = qualifierWhenComparisonCompletes(rightAnno, right); UBQualifier glb = rightQualifier.glb(leftQualifier); AnnotationMirror glbAnno = atypeFactory.convertUBQualifierToAnnotation(glb); @@ -541,11 +537,7 @@ private void refineNeqSequenceLength( // The comparison used the length of the sequence before it changed. return; } - UBQualifier otherQualifier = - removeBoundsChangedAfter( - UBQualifier.createUBQualifier( - otherNodeAnno, (UpperBoundChecker) atypeFactory.getChecker()), - otherNode); + UBQualifier otherQualifier = qualifierWhenComparisonCompletes(otherNodeAnno, otherNode); String sequence = receiver.toString(); // Check if otherNode + c - 1 < receiver.length if (otherQualifier.hasSequenceWithOffset(sequence, lengthOffset - 1)) { @@ -559,6 +551,21 @@ private void refineNeqSequenceLength( } } + /** + * Returns the qualifier for the given annotation of an operand of a comparison, without the bounds + * that might not hold when the comparison completes (see {@link #removeBoundsChangedAfter}). + * + * @param anno the upper bound annotation of {@code operand} + * @param operand an operand of a comparison + * @return the qualifier for {@code anno}, without the bounds that might not hold when the + * comparison completes + */ + private UBQualifier qualifierWhenComparisonCompletes(AnnotationMirror anno, Node operand) { + return removeBoundsChangedAfter( + UBQualifier.createUBQualifier(anno, (UpperBoundChecker) atypeFactory.getChecker()), + operand); + } + /** * Returns the given qualifier of an operand of a comparison, without each bound whose sequence or * offset might change after the operand produces its value and before the comparison completes. diff --git a/checker/tests/index/SameLenComparisonChangesOperand.java b/checker/tests/index/SameLenComparisonChangesOperand.java index cb6a34135182..646d94fae577 100644 --- a/checker/tests/index/SameLenComparisonChangesOperand.java +++ b/checker/tests/index/SameLenComparisonChangesOperand.java @@ -1,3 +1,5 @@ +import org.checkerframework.dataflow.qual.SideEffectFree; + // An operand of a length comparison must not be related to the other operand if the comparison // changes the operand's value after evaluating it. For example, if i is 12, then after the // comparison in changedLater, s is "ab3" but "x" + i is "x3". @@ -72,6 +74,7 @@ static class Box { String text = ""; @Override + @SideEffectFree public String toString() { return text; } @@ -103,4 +106,26 @@ void unchangedByToString(Box box, String s, String t) { } } } + + static String prefix = ""; + + static class PrefixSetter { + @Override + public String toString() { + prefix = "long"; + return "x"; + } + } + + // The concatenation reads `prefix` before its string conversion of `setter` reassigns `prefix`. + // So after the comparison, prefix + setter might be longer than t. + void concatenationChangesOperand(PrefixSetter setter, String t) { + if ((prefix + setter).length() == t.length()) { + String u = prefix + setter; + for (int k = 0; k < u.length(); k++) { + // :: error: (argument) + t.charAt(k); + } + } + } } diff --git a/checker/tests/index/UpperBoundComparisonChangesSequence.java b/checker/tests/index/UpperBoundComparisonChangesSequence.java index 023062a57463..1cd76103403c 100644 --- a/checker/tests/index/UpperBoundComparisonChangesSequence.java +++ b/checker/tests/index/UpperBoundComparisonChangesSequence.java @@ -52,4 +52,38 @@ void neqUnchanged(@LTEqLengthOf("this.a") int k) { int x = this.a[i]; } } + + // If a has length 10 and b has length 1, then the comparison is 10 > 1, but x is 1 and a has + // length 1 after the comparison. + void gtChanged(int[] a, int[] b) { + int x; + if (a.length > (x = (a = b).length)) { + // :: error: (array.access.unsafe.high) + int y = a[x]; + } + } + + void gtUnchanged(int[] a, int[] b) { + int x; + if (a.length > (x = b.length)) { + int y = a[x]; + } + } + + // If a has length 10 and b has length 1, then the comparison is 10 >= 1, but x is 1 and a has + // length 1 after the comparison. + void gteChanged(int[] a, int[] b) { + int x; + if (a.length >= (x = (a = b).length + 1)) { + // :: error: (assignment) + @LTEqLengthOf("a") int y = x; + } + } + + void gteUnchanged(int[] a, int[] b) { + int x; + if (a.length >= (x = b.length + 1)) { + @LTEqLengthOf("a") int y = x; + } + } } diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 0e57c528ff21..4aa81433b659 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -35,6 +35,7 @@ import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; +import javax.lang.model.util.ElementFilter; import org.checkerframework.checker.interning.qual.InternedDistinct; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.PolyNull; @@ -148,7 +149,10 @@ public abstract class CFAbstractTransfer< /** True if whole-program inference is on. */ private final boolean infer; - /** The method {@code Object.toString()}, which a string conversion calls. */ + /** + * The method {@code Object.toString()}, which a string conversion calls if no more specific + * override is known. + */ private final ExecutableElement objectToString; /** @@ -1067,10 +1071,11 @@ private boolean abstractValueMayChangeBeforeComparison(Node node) { * evaluated. (A client such as the SameLen Checker can relate an operation such as {@code "x" + * i} to other expressions, even though no store holds a value for it.) A candidate's value can * change when code that is evaluated after the candidate writes a variable, field, or array - * element that the candidate reads. That code is the rest of the assignment, and the code in the + * element that the candidate reads. That code is the rest of the assignment; the code in the * enclosing expressions that is evaluated after {@code node} and before the comparison completes, - * such as the right operand of the comparison if {@code node} is in its left operand. For - * example: + * such as the right operand of the comparison if {@code node} is in its left operand; and, if + * {@code node} is a unary or binary operation, the code in {@code node} itself, such as the call + * to {@code obj.toString()} in {@code prefix + obj}. For example: * *

    *
  • The result for {@code n = n.next} is just {@code n}, because after the assignment {@code @@ -1113,16 +1118,31 @@ protected List nodesWithValueOf(Node node) { } /** - * Returns the nodes that have the value of the given node when the comparison that contains the - * node completes. - * - * @param node a node in an operand of a comparison, possibly an assignment - * @return the nodes that have the value of {@code node} when the comparison completes + * Takes a node, and either returns the node itself again (as a singleton list), or if the node is + * an assignment node, returns the lhs and rhs (where splitAssignments is applied recursively to + * the rhs -- that is, it is possible that the rhs does not appear in the result, but rather its + * lhs and rhs do). + * + *

    The result is purely structural: it may contain a node that does not have the value of + * {@code node} when an enclosing comparison completes, such as {@code a[i]} in {@code i = a[i]}. + * To refine the operands of a comparison, use {@link #nodesWithValueOf} instead. + * + * @param node possibly an assignment node + * @return a list containing all the right- and left-hand sides in the given assignment node; it + * contains just the node itself if it is not an assignment * @deprecated use {@link #nodesWithValueOf} */ @Deprecated // 2026-11-13 + @SideEffectFree protected List splitAssignments(Node node) { - return nodesWithValueOf(node); + if (node instanceof AssignmentNode a) { + List result = new ArrayList<>(2); + result.add(a.getTarget()); + result.addAll(splitAssignments(a.getExpression())); + return result; + } else { + return Collections.singletonList(node); + } } /** @@ -1145,6 +1165,15 @@ private List computeNodesWithValueOf(Node node) { if (isCheckedCandidate(expr)) { if (locationsWrittenUntilComparison == null) { locationsWrittenUntilComparison = locationsWrittenUntilComparison(node); + // If `node` is a unary or binary operation, it is the only candidate, and it might write + // a location after reading it, as in `prefix + obj` where `obj.toString()` writes + // `prefix`. Scanning all of `node` also includes writes that precede the reads, which + // is conservative. + Tree tree = node.getTree(); + if (!(node instanceof AssignmentNode) + && (tree instanceof BinaryTree || tree instanceof UnaryTree)) { + locationsWrittenUntilComparison.scan(tree, null); + } } if (locationsWrittenUntilComparison.mayChange(expr, false)) { continue; @@ -1529,11 +1558,47 @@ private void addCall(ExecutableElement method) { private void addStringConversions(ExpressionTree left, ExpressionTree right) { TypeMirror leftType = TreeUtils.typeOf(left); TypeMirror rightType = TreeUtils.typeOf(right); - if ((TypesUtils.isString(leftType) || TypesUtils.isString(rightType)) - && (callsToString(leftType) || callsToString(rightType))) { - // Every override of `toString()` has the purity annotations of `Object.toString()`. - addCall(objectToString); + if (TypesUtils.isString(leftType) || TypesUtils.isString(rightType)) { + addStringConversion(leftType); + addStringConversion(rightType); + } + } + + /** + * Adds the writes of the string conversion of a value of the given type, which is an operand of + * a string concatenation. + * + * @param type the type of an operand of a string concatenation + */ + private void addStringConversion(TypeMirror type) { + // The `toString()` method of a boxed primitive, whose class is final, has no side effects. + if (callsToString(type) && !TypesUtils.isBoxedPrimitive(type)) { + addCall(toStringMethod(type)); + } + } + + /** + * Returns the {@code toString()} method that a string conversion of a value of the given type + * calls, as far as is known statically: the most specific declaration of {@code toString()} in + * the erasure of {@code type} or its superclasses. An override in a subclass of {@code type} is + * assumed to have the purity annotations of the returned method. + * + * @param type a reference type that is not {@code String} + * @return the {@code toString()} method that a string conversion of {@code type} calls + */ + private ExecutableElement toStringMethod(TypeMirror type) { + TypeElement element = TypesUtils.getTypeElement(analysis.getTypes().erasure(type)); + while (element != null) { + for (ExecutableElement method : ElementFilter.methodsIn(element.getEnclosedElements())) { + if (method.getSimpleName().contentEquals("toString") + && method.getParameters().isEmpty() + && !ElementUtils.isStatic(method)) { + return method; + } + } + element = TypesUtils.getTypeElement(element.getSuperclass()); } + return objectToString; } /** From c329d0ead8d5e3769c79ab6c6e1720f0bba53467 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 27 Nov 2026 12:06:11 -0800 Subject: [PATCH 54/73] Reformat --- .../checker/index/upperbound/UpperBoundTransfer.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java index 9afd2658be0e..c9baa5841de9 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java @@ -552,8 +552,9 @@ private void refineNeqSequenceLength( } /** - * Returns the qualifier for the given annotation of an operand of a comparison, without the bounds - * that might not hold when the comparison completes (see {@link #removeBoundsChangedAfter}). + * Returns the qualifier for the given annotation of an operand of a comparison, without the + * bounds that might not hold when the comparison completes (see {@link + * #removeBoundsChangedAfter}). * * @param anno the upper bound annotation of {@code operand} * @param operand an operand of a comparison From 919fbc16ab5b2f959370b6e7365cfb33edd57790 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 27 Nov 2026 14:43:00 -0800 Subject: [PATCH 55/73] Index tests: give the test helpers lower bounds; reassign a += receiver by a method call, not by toString() --- .../SameLenComparisonChangesOperand.java | 20 +++++++++---------- .../UpperBoundComparisonChangesSequence.java | 5 +++-- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/checker/tests/index/SameLenComparisonChangesOperand.java b/checker/tests/index/SameLenComparisonChangesOperand.java index cb6a34135182..954361d938a7 100644 --- a/checker/tests/index/SameLenComparisonChangesOperand.java +++ b/checker/tests/index/SameLenComparisonChangesOperand.java @@ -49,18 +49,18 @@ static class Holder { static Holder current = new Holder(); - static class Swapper { - @Override - public String toString() { - current = new Holder(); - return ""; - } + // Not side-effect-free. + static String swap() { + current = new Holder(); + return ""; } - // The `+=` evaluates `current` before it converts `sw` to a string, and that conversion - // reassigns `current`. So the assignment stores into the `text` field of the old `current`. - void stringConversionInCompoundAssignmentReassignsReceiver(String peer, Swapper sw) { - if ((current.text += sw).length() == peer.length()) { + // The `+=` evaluates `current` before it evaluates `swap()`, which reassigns `current`. So the + // assignment stores into the `text` field of the old `current`. (A string conversion cannot + // reassign `current` this way: the analysis assumes that every `toString()` method is + // side-effect-free, like `Object.toString()`.) + void compoundAssignmentReassignsReceiver(String peer) { + if ((current.text += swap()).length() == peer.length()) { for (int k = 0; k < peer.length(); k++) { // :: error: (argument) current.text.charAt(k); diff --git a/checker/tests/index/UpperBoundComparisonChangesSequence.java b/checker/tests/index/UpperBoundComparisonChangesSequence.java index 023062a57463..0a429b49c817 100644 --- a/checker/tests/index/UpperBoundComparisonChangesSequence.java +++ b/checker/tests/index/UpperBoundComparisonChangesSequence.java @@ -1,4 +1,5 @@ import org.checkerframework.checker.index.qual.LTEqLengthOf; +import org.checkerframework.checker.index.qual.NonNegative; // A bound in the type of an operand of a comparison refers to a sequence as it was when the operand // was evaluated. If the other operand reassigns the sequence, the bound must not be used to refine @@ -15,7 +16,7 @@ int replaceAndReturnTwo() { } // Not side-effect-free. - @LTEqLengthOf("this.a") int shrink() { + @NonNegative @LTEqLengthOf("this.a") int shrink() { a = new int[1]; return 1; } @@ -46,7 +47,7 @@ void neqChanged() { } } - void neqUnchanged(@LTEqLengthOf("this.a") int k) { + void neqUnchanged(@NonNegative @LTEqLengthOf("this.a") int k) { int i; if (this.a.length != (i = k)) { int x = this.a[i]; From 131db9dc778c04ea1e5a2c40634fd009661ff26e Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 27 Nov 2026 14:43:14 -0800 Subject: [PATCH 56/73] Expect array.access.unsafe.high.range for an index with a range --- checker/tests/index/UpperBoundComparisonChangesSequence.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/checker/tests/index/UpperBoundComparisonChangesSequence.java b/checker/tests/index/UpperBoundComparisonChangesSequence.java index 1cd76103403c..6e718c761d71 100644 --- a/checker/tests/index/UpperBoundComparisonChangesSequence.java +++ b/checker/tests/index/UpperBoundComparisonChangesSequence.java @@ -58,7 +58,7 @@ void neqUnchanged(@LTEqLengthOf("this.a") int k) { void gtChanged(int[] a, int[] b) { int x; if (a.length > (x = (a = b).length)) { - // :: error: (array.access.unsafe.high) + // :: error: (array.access.unsafe.high.range) int y = a[x]; } } From 1250c62c483bd9a316458d8659815e0b55d05689 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 27 Nov 2026 14:49:21 -0800 Subject: [PATCH 57/73] Move the eqChanged test to the pull request that makes it pass --- .../UpperBoundComparisonChangesSequence.java | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/checker/tests/index/UpperBoundComparisonChangesSequence.java b/checker/tests/index/UpperBoundComparisonChangesSequence.java index 0a429b49c817..f6868378536d 100644 --- a/checker/tests/index/UpperBoundComparisonChangesSequence.java +++ b/checker/tests/index/UpperBoundComparisonChangesSequence.java @@ -9,27 +9,12 @@ public class UpperBoundComparisonChangesSequence { int[] a = new int[2]; - // Not side-effect-free. - int replaceAndReturnTwo() { - a = new int[0]; - return 2; - } - // Not side-effect-free. @NonNegative @LTEqLengthOf("this.a") int shrink() { a = new int[1]; return 1; } - // If this.a has length 2 before the call, then i is 2 but this.a has length 0 after the call. - void eqChanged() { - int i; - if (this.a.length == (i = replaceAndReturnTwo())) { - // :: error: (assignment) - @LTEqLengthOf("this.a") int j = i; - } - } - void eqUnchanged(int k) { int i; if (this.a.length == (i = k)) { From 4483a764d7e23c96f067af940eae2d01b5d467f8 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 27 Nov 2026 14:49:22 -0800 Subject: [PATCH 58/73] Remove a test that a side-effecting toString() override makes a concatenation stale; every toString() is assumed side-effect-free --- .../SameLenComparisonChangesOperand.java | 22 ------------------- .../framework/flow/CFAbstractTransfer.java | 7 +++--- 2 files changed, 3 insertions(+), 26 deletions(-) diff --git a/checker/tests/index/SameLenComparisonChangesOperand.java b/checker/tests/index/SameLenComparisonChangesOperand.java index 646d94fae577..a045537bd9c5 100644 --- a/checker/tests/index/SameLenComparisonChangesOperand.java +++ b/checker/tests/index/SameLenComparisonChangesOperand.java @@ -106,26 +106,4 @@ void unchangedByToString(Box box, String s, String t) { } } } - - static String prefix = ""; - - static class PrefixSetter { - @Override - public String toString() { - prefix = "long"; - return "x"; - } - } - - // The concatenation reads `prefix` before its string conversion of `setter` reassigns `prefix`. - // So after the comparison, prefix + setter might be longer than t. - void concatenationChangesOperand(PrefixSetter setter, String t) { - if ((prefix + setter).length() == t.length()) { - String u = prefix + setter; - for (int k = 0; k < u.length(); k++) { - // :: error: (argument) - t.charAt(k); - } - } - } } diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 4aa81433b659..4228e4b65766 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -1075,7 +1075,7 @@ private boolean abstractValueMayChangeBeforeComparison(Node node) { * enclosing expressions that is evaluated after {@code node} and before the comparison completes, * such as the right operand of the comparison if {@code node} is in its left operand; and, if * {@code node} is a unary or binary operation, the code in {@code node} itself, such as the call - * to {@code obj.toString()} in {@code prefix + obj}. For example: + * to {@code f()} in {@code i + f()}. For example: * *

      *
    • The result for {@code n = n.next} is just {@code n}, because after the assignment {@code @@ -1166,9 +1166,8 @@ private List computeNodesWithValueOf(Node node) { if (locationsWrittenUntilComparison == null) { locationsWrittenUntilComparison = locationsWrittenUntilComparison(node); // If `node` is a unary or binary operation, it is the only candidate, and it might write - // a location after reading it, as in `prefix + obj` where `obj.toString()` writes - // `prefix`. Scanning all of `node` also includes writes that precede the reads, which - // is conservative. + // a location after reading it, as in `i + f()` where `f()` writes `i`. Scanning all of + // `node` also includes writes that precede the reads, which is conservative. Tree tree = node.getTree(); if (!(node instanceof AssignmentNode) && (tree instanceof BinaryTree || tree instanceof UnaryTree)) { From cbbe62d9c5160542a84218e597b447f28c03e05b Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Fri, 27 Nov 2026 22:58:58 -0800 Subject: [PATCH 59/73] Address review: bracketed offsets, writes in a subtracted offset, postfix temporaries - OffsetEquation: do not split an offset at a + or - inside parentheses or brackets, so offsets[i - 1] is one term. - UpperBoundTransfer.refineNeqSequenceLength: check whether the sequence may change starting from the length access, so writes in the subtracted offset count. - CFAbstractTransfer: find the source path of the temporary for a postfix increment or decrement, and include its write; if no source path is found, assume every location may be written instead of none. --- .../index/upperbound/OffsetEquation.java | 31 +++++--- .../index/upperbound/UpperBoundTransfer.java | 14 ++-- .../UpperBoundComparisonChangesSequence.java | 39 ++++++++++ .../framework/flow/CFAbstractTransfer.java | 77 ++++++++++++++++++- 4 files changed, 139 insertions(+), 22 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/index/upperbound/OffsetEquation.java b/checker/src/main/java/org/checkerframework/checker/index/upperbound/OffsetEquation.java index adcb5f75a6a6..70eece7be474 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/upperbound/OffsetEquation.java +++ b/checker/src/main/java/org/checkerframework/checker/index/upperbound/OffsetEquation.java @@ -378,8 +378,9 @@ public static OffsetEquation createOffsetForInt(int value) { /** * Creates an offset equation from the expressionEquation. The expressionEquation can be several * Java expressions added or subtracted from each other. The expressionEquation can also start - * with + or -. If the expressionEquation is the empty string, then the offset equation returned - * is zero. + * with + or -. A + or - within parentheses or brackets, as in {@code offsets[i - 1]}, does not + * separate terms. If the expressionEquation is the empty string, then the offset equation + * returned is zero. * * @param expressionEquation a Java expression made up of sums and differences * @return an offset equation created from expressionEquation @@ -440,24 +441,30 @@ private static boolean isIntLiteral(String string) { /** * Returns the first index of a or b in string, at or after index, or -1 if neither char occurs in - * string at or after index. + * string at or after index. Ignores occurrences within parentheses or brackets that start at or + * after index, so that an expression such as {@code offsets[i - 1]} or {@code f(x + 1)} is not + * split. * * @param string the string to search in * @param a a character to search for * @param b another character to search for * @param index the index at which to start the search - * @return the first index of a or b in string at or after index, or -1 if neither char occurs + * @return the first index of a or b in string at or after index and outside parentheses and + * brackets, or -1 if neither char occurs there */ private static int indexOfEither(String string, char a, char b, int index) { - int aIndex = string.indexOf(a, index); - int bIndex = string.indexOf(b, index); - if (aIndex == -1) { - return bIndex; - } else if (bIndex == -1) { - return aIndex; - } else { - return Math.min(aIndex, bIndex); + int depth = 0; + for (int i = index; i < string.length(); i++) { + char c = string.charAt(i); + if (c == '(' || c == '[') { + depth++; + } else if ((c == ')' || c == ']') && depth > 0) { + depth--; + } else if (depth == 0 && (c == a || c == b)) { + return i; + } } + return -1; } /** diff --git a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java index 5a07ff806175..0e4ffefa3fb3 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java @@ -459,9 +459,9 @@ private void refineEq( * offset), then refine the other node's type to less than the sequence length (minus the offset). * This is case 12. * - *

      Does nothing if the sequence might change after {@code lengthAccess} is evaluated and before - * the comparison completes, because then the comparison does not relate the other node to the - * length of the sequence that the new type refers to. Omits the bounds of the other node's type + *

      Does nothing if the sequence might change after its length is read and before the + * comparison completes (including by the subtracted offset), because then the comparison does + * not relate the other node to the length of the sequence that the new type refers to. Omits the bounds of the other node's type * that might not hold when the comparison completes (see {@link #removeBoundsChangedAfter}). * * @param lengthAccess an operand of a comparison @@ -471,9 +471,6 @@ private void refineEq( */ private void refineNeqSequenceLength( Node lengthAccess, Node otherNode, AnnotationMirror otherNodeAnno, CFStore store) { - // The operand of the comparison, before any subtraction of a constant is stripped. - Node lengthAccessOperand = lengthAccess; - // If lengthAccess is "receiver.length - c" where c is an integer constant, // then lengthOffset is "c". int lengthOffset = 0; @@ -507,7 +504,10 @@ private void refineNeqSequenceLength( } if (receiver != null && !receiver.containsUnknown()) { - Predicate mayChange = mayChangeAfterOperand(lengthAccessOperand); + // Use the length access itself, not the entire operand: the subtracted constant, as in + // `a.length - reset()` where `reset()` has a known value, is evaluated after the length is + // read and might change the sequence. + Predicate mayChange = mayChangeAfterOperand(lengthAccess); if (mayChange != null && mayChange.test(receiver)) { // The comparison used the length of the sequence before it changed. return; diff --git a/checker/tests/index/UpperBoundComparisonChangesSequence.java b/checker/tests/index/UpperBoundComparisonChangesSequence.java index f6868378536d..64eeec6728c7 100644 --- a/checker/tests/index/UpperBoundComparisonChangesSequence.java +++ b/checker/tests/index/UpperBoundComparisonChangesSequence.java @@ -1,5 +1,7 @@ import org.checkerframework.checker.index.qual.LTEqLengthOf; +import org.checkerframework.checker.index.qual.LTLengthOf; import org.checkerframework.checker.index.qual.NonNegative; +import org.checkerframework.common.value.qual.IntVal; // A bound in the type of an operand of a comparison refers to a sequence as it was when the operand // was evaluated. If the other operand reassigns the sequence, the bound must not be used to refine @@ -38,4 +40,41 @@ void neqUnchanged(@NonNegative @LTEqLengthOf("this.a") int k) { int x = this.a[i]; } } + + // Not side-effect-free. Returns 0, so `this.a.length - reset()` has a known offset. + @IntVal(0) int reset() { + a = new int[1]; + return 0; + } + + // If this.a has length 2 before the call, then the comparison is 2 != 1, but i is 1 and this.a + // has length 1 after the call. + void neqChangedByOffset() { + int i; + if (this.a.length - reset() != (i = this.a.length)) { + // :: error: (array.access.unsafe.high) + int x = this.a[i]; + } + } + + @NonNegative int keepSecond(Object o, @NonNegative int x) { + return x; + } + + // If i is 0 and this.a has length 1 before the comparison, the comparison is 0 == 0, but this.a + // is empty after it. + void postfixChanged(@NonNegative @LTLengthOf("this.a") int i) { + int j; + if (i++ == (j = keepSecond(this.a = new int[0], 0))) { + // :: error: (array.access.unsafe.high) + int x = this.a[j]; + } + } + + void postfixUnchanged(@NonNegative @LTLengthOf("this.a") int i, @NonNegative int k) { + int j; + if (i++ == (j = k)) { + int x = this.a[j]; + } + } } diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 0e57c528ff21..3d168d5790d8 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -50,6 +50,7 @@ import org.checkerframework.dataflow.cfg.UnderlyingAST; import org.checkerframework.dataflow.cfg.UnderlyingAST.CFGLambda; import org.checkerframework.dataflow.cfg.UnderlyingAST.CFGMethod; +import org.checkerframework.dataflow.cfg.block.Block; import org.checkerframework.dataflow.cfg.node.AbstractNodeVisitor; import org.checkerframework.dataflow.cfg.node.AnyPatternNode; import org.checkerframework.dataflow.cfg.node.ArrayAccessNode; @@ -1298,6 +1299,9 @@ private boolean mayBeChanged(Node side, WrittenLocations written) { *

      If no comparison encloses the node, the result contains the locations written up to the * outermost enclosing expression, or up to an enclosing lambda or switch expression. * + *

      If the source tree of the node cannot be found, the result contains every location, because + * the writes are unknown. + * * @param node a node * @return the locations that are written after {@code node} is evaluated and before the * comparison that contains it completes @@ -1306,8 +1310,15 @@ private WrittenLocations locationsWrittenUntilComparison(Node node) { WrittenLocations result = new WrittenLocations(); TreePath path = sourcePath(node); if (path == null) { + result.addEveryLocation(); return result; } + UnaryTree postfixTree = postfixTreeOfTemporary(node); + if (postfixTree != null) { + // The temporary holds the value of the operand before the increment or decrement, which + // writes the operand afterward. + result.addOwnWrites(postfixTree); + } TreePath parentPath = path.getParentPath(); while (parentPath != null) { Tree parent = parentPath.getLeaf(); @@ -1332,7 +1343,9 @@ private WrittenLocations locationsWrittenUntilComparison(Node node) { /** * Returns the path to the tree of the given node. If the node has no tree, or if its tree is not * in the compilation unit (as for the artificial tree of an unboxing conversion), returns the - * result of this method for the first operand of the node for which that result is non-null. + * path to the postfix increment or decrement if the node is the temporary variable that holds its + * value (see {@link #postfixTreeOfTemporary}), and otherwise the result of this method for the + * first operand of the node for which that result is non-null. * * @param node a node * @return the path to the source tree that {@code node} represents, or null if there is none @@ -1345,6 +1358,10 @@ private WrittenLocations locationsWrittenUntilComparison(Node node) { return path; } } + UnaryTree postfixTree = postfixTreeOfTemporary(node); + if (postfixTree != null) { + return analysis.atypeFactory.getPath(postfixTree); + } for (Node operand : node.getOperands()) { TreePath path = sourcePath(operand); if (path != null) { @@ -1354,6 +1371,44 @@ private WrittenLocations locationsWrittenUntilComparison(Node node) { return null; } + /** + * If the given node is the artificial temporary variable that the CFG uses for the value of a + * postfix increment or decrement such as {@code i++}, returns the postfix tree. Otherwise, + * returns null. + * + *

      The CFG translates {@code i++} to an assignment {@code tempPostfix = i}, whose tree is the + * postfix tree, immediately followed by a use of {@code tempPostfix}, which is the value of the + * postfix expression. + * + * @param node a node + * @return the postfix increment or decrement whose value {@code node} holds, or null + */ + @SuppressWarnings("interning:not.interned") // reference equality of CFG nodes + private static @Nullable UnaryTree postfixTreeOfTemporary(Node node) { + if (!(node instanceof LocalVariableNode local) || node.getInSource()) { + return null; + } + Block block = node.getBlock(); + if (block == null) { + return null; + } + List blockNodes = block.getNodes(); + for (int i = 1; i < blockNodes.size(); i++) { + if (blockNodes.get(i) == node) { + if (blockNodes.get(i - 1) instanceof AssignmentNode assignment + && assignment.getTree() instanceof UnaryTree unaryTree + && (unaryTree.getKind() == Tree.Kind.POSTFIX_INCREMENT + || unaryTree.getKind() == Tree.Kind.POSTFIX_DECREMENT) + && assignment.getTarget() instanceof LocalVariableNode target + && target.getName().equals(local.getName())) { + return unaryTree; + } + return null; + } + } + return null; + } + /** * Returns the direct subtrees of the given tree, in the order in which a {@link TreeScanner} * visits them. For an expression, that is the order in which Java evaluates them; for example, @@ -1415,9 +1470,21 @@ private final class WrittenLocations extends TreeScanner { */ private boolean anyHeapLocation = false; + /** + * True if every local variable might be written, as when the writes are unknown. If true, then + * {@link #anyHeapLocation} is also true. + */ + private boolean anyLocal = false; + /** Creates an empty set of locations. */ WrittenLocations() {} + /** Adds a write to every location: every local variable, field, and array element. */ + void addEveryLocation() { + anyLocal = true; + anyHeapLocation = true; + } + /** * Returns true if every non-final field and every array element might be written, as by a call * to a method that is not side-effect-free. @@ -1647,7 +1714,7 @@ boolean mayChange(JavaExpression expr, boolean ignoreOwnLocation) { */ boolean valueMayChange(JavaExpression expr, boolean ignoreOwnLocation) { if (expr instanceof LocalVariable) { - return !ignoreOwnLocation && locals.contains(expr); + return !ignoreOwnLocation && (anyLocal || locals.contains(expr)); } else if (expr instanceof FieldAccess fa) { return (!ignoreOwnLocation && mayWriteField(fa)) || valueMayChange(fa.getReceiver(), false); } else if (expr instanceof ArrayAccess aa) { @@ -1705,7 +1772,11 @@ private boolean mayWriteHeap() { * @return true if no location is written */ boolean isEmpty() { - return !anyHeapLocation && locals.isEmpty() && fields.isEmpty() && arrayElements.isEmpty(); + return !anyHeapLocation + && !anyLocal + && locals.isEmpty() + && fields.isEmpty() + && arrayElements.isEmpty(); } /** From ca4f0d21e60920c9d899e1aa4fb683485f749d71 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 28 Nov 2026 00:52:04 -0800 Subject: [PATCH 60/73] Reformat --- .../checker/index/upperbound/UpperBoundTransfer.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java index 0e4ffefa3fb3..b1662f4f2e51 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java @@ -459,10 +459,11 @@ private void refineEq( * offset), then refine the other node's type to less than the sequence length (minus the offset). * This is case 12. * - *

      Does nothing if the sequence might change after its length is read and before the - * comparison completes (including by the subtracted offset), because then the comparison does - * not relate the other node to the length of the sequence that the new type refers to. Omits the bounds of the other node's type - * that might not hold when the comparison completes (see {@link #removeBoundsChangedAfter}). + *

      Does nothing if the sequence might change after its length is read and before the comparison + * completes (including by the subtracted offset), because then the comparison does not relate the + * other node to the length of the sequence that the new type refers to. Omits the bounds of the + * other node's type that might not hold when the comparison completes (see {@link + * #removeBoundsChangedAfter}). * * @param lengthAccess an operand of a comparison * @param otherNode the other operand of the comparison From 2a3dc0dbdeb5504b9977170256b133b6dc545315 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 28 Nov 2026 10:05:50 -0800 Subject: [PATCH 61/73] Address review: quoted delimiters in offsets, writes in any candidate, filter superclass equality refinement - OffsetEquation: ignore parentheses, brackets, + and - inside string and character literals, as in s.indexOf('(') + n. - CFAbstractTransfer.computeNodesWithValueOf: scan the tree of every candidate that is not an assignment, not just unary and binary operations, so writes in a[f()] or g(x, f()) are found. - UpperBoundTransfer.strengthenAnnotationOfEqualTo: omit bounds that might not hold when the comparison completes before the superclass inserts the value, as for the postfix temporary in postfixChanged. --- .../index/upperbound/OffsetEquation.java | 21 +++++++-- .../index/upperbound/UpperBoundTransfer.java | 44 ++++++++++++++++++- .../framework/flow/CFAbstractTransfer.java | 13 +++--- 3 files changed, 65 insertions(+), 13 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/index/upperbound/OffsetEquation.java b/checker/src/main/java/org/checkerframework/checker/index/upperbound/OffsetEquation.java index 70eece7be474..8cc1981447ea 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/upperbound/OffsetEquation.java +++ b/checker/src/main/java/org/checkerframework/checker/index/upperbound/OffsetEquation.java @@ -443,20 +443,33 @@ private static boolean isIntLiteral(String string) { * Returns the first index of a or b in string, at or after index, or -1 if neither char occurs in * string at or after index. Ignores occurrences within parentheses or brackets that start at or * after index, so that an expression such as {@code offsets[i - 1]} or {@code f(x + 1)} is not - * split. + * split. Also ignores occurrences within string and character literals, and does not count + * parentheses or brackets within them, as in {@code s.indexOf('(') + n}. * * @param string the string to search in * @param a a character to search for * @param b another character to search for * @param index the index at which to start the search - * @return the first index of a or b in string at or after index and outside parentheses and - * brackets, or -1 if neither char occurs there + * @return the first index of a or b in string at or after index and outside parentheses, + * brackets, and literals, or -1 if neither char occurs there */ private static int indexOfEither(String string, char a, char b, int index) { int depth = 0; + // The quote character of the string or character literal that contains the current + // character, or 0 if it is not in a literal. + char quote = 0; for (int i = index; i < string.length(); i++) { char c = string.charAt(i); - if (c == '(' || c == '[') { + if (quote != 0) { + if (c == '\\') { + // Skip the escaped character. + i++; + } else if (c == quote) { + quote = 0; + } + } else if (c == '"' || c == '\'') { + quote = c; + } else if (c == '(' || c == '[') { depth++; } else if ((c == ')' || c == ']') && depth > 0) { depth--; diff --git a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java index 2c9129562674..825a72e3ece9 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java @@ -434,7 +434,14 @@ private void refineSubtrahendWithOffset( } } - /** Implements case 11. */ + /** + * Implements case 11. + * + *

      The superclass inserts {@code firstValue} for {@code secondNode}. This method first omits + * from {@code firstValue} the bounds that might not hold when the comparison completes (see + * {@link #removeBoundsChangedAfter}), because the store keeps the more precise of an existing + * value and an inserted value, so a later insertion of a filtered value could not remove them. + */ @Override protected TransferResult strengthenAnnotationOfEqualTo( TransferResult res, @@ -445,7 +452,12 @@ protected TransferResult strengthenAnnotationOfEqualTo( boolean notEqualTo) { TransferResult result = super.strengthenAnnotationOfEqualTo( - res, firstNode, secondNode, firstValue, secondValue, notEqualTo); + res, + firstNode, + secondNode, + valueWhenComparisonCompletes(firstValue, firstNode), + secondValue, + notEqualTo); IndexRefinementInfo rfi = new IndexRefinementInfo(result, analysis, firstNode, secondNode); if (rfi.leftAnno == null || rfi.rightAnno == null) { return result; @@ -568,6 +580,34 @@ private UBQualifier qualifierWhenComparisonCompletes(AnnotationMirror anno, Node operand); } + /** + * Returns the given abstract value of an operand of a comparison, without the upper bounds that + * might not hold when the comparison completes (see {@link #removeBoundsChangedAfter}). + * + * @param value the abstract value of {@code operand}, or null + * @param operand an operand of a comparison + * @return {@code value}, without the upper bounds that might not hold when the comparison + * completes, or null if {@code value} is null + */ + private @Nullable CFValue valueWhenComparisonCompletes(@Nullable CFValue value, Node operand) { + if (value == null) { + return null; + } + AnnotationMirror anno = + atypeFactory + .getQualifierHierarchy() + .findAnnotationInHierarchy(value.getAnnotations(), atypeFactory.UNKNOWN); + if (anno == null) { + return value; + } + UBQualifier filtered = qualifierWhenComparisonCompletes(anno, operand); + AnnotationMirror filteredAnno = atypeFactory.convertUBQualifierToAnnotation(filtered); + if (AnnotationUtils.areSame(anno, filteredAnno)) { + return value; + } + return analysis.createSingleAnnotationValue(filteredAnno, value.getUnderlyingType()); + } + /** * Returns the given qualifier of an operand of a comparison, without each bound whose sequence or * offset might change after the operand produces its value and before the comparison completes. diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index e24bcdf1d1e6..fdb7ba3cb8bf 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -1075,8 +1075,8 @@ private boolean abstractValueMayChangeBeforeComparison(Node node) { * element that the candidate reads. That code is the rest of the assignment; the code in the * enclosing expressions that is evaluated after {@code node} and before the comparison completes, * such as the right operand of the comparison if {@code node} is in its left operand; and, if - * {@code node} is a unary or binary operation, the code in {@code node} itself, such as the call - * to {@code f()} in {@code i + f()}. For example: + * {@code node} is not an assignment, the code in {@code node} itself, such as the call to {@code + * f()} in {@code i + f()} or {@code a[f()]}. For example: * *

        *
      • The result for {@code n = n.next} is just {@code n}, because after the assignment {@code @@ -1166,12 +1166,11 @@ private List computeNodesWithValueOf(Node node) { if (isCheckedCandidate(expr)) { if (locationsWrittenUntilComparison == null) { locationsWrittenUntilComparison = locationsWrittenUntilComparison(node); - // If `node` is a unary or binary operation, it is the only candidate, and it might write - // a location after reading it, as in `i + f()` where `f()` writes `i`. Scanning all of - // `node` also includes writes that precede the reads, which is conservative. + // If `node` is not an assignment, it is the only candidate, and it might write a location + // after reading it, as in `i + f()` or `a[f()]` where `f()` writes `i` or `a`. Scanning + // all of `node` also includes writes that precede the reads, which is conservative. Tree tree = node.getTree(); - if (!(node instanceof AssignmentNode) - && (tree instanceof BinaryTree || tree instanceof UnaryTree)) { + if (!(node instanceof AssignmentNode) && tree != null) { locationsWrittenUntilComparison.scan(tree, null); } } From dc1566bc78a0028470ed7e33210f97ff8f68452c Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 28 Nov 2026 18:03:34 -0800 Subject: [PATCH 62/73] Make splitAssignments structural and final; check writes in a candidate's own tree - splitAssignments() is again purely structural, and it is final. - nodesWithValueOf accounts for the writes in a non-assignment candidate's own tree, as in i + f() or a[f()]. - Upper Bound Checker: do not filter bounds that might change before the comparison completes, which is a separate change. --- .../index/upperbound/OffsetEquation.java | 52 +++------ .../checker/index/upperbound/UBQualifier.java | 33 ------ .../index/upperbound/UpperBoundTransfer.java | 74 ++----------- .../UpperBoundComparisonChangesSequence.java | 80 -------------- docs/CHANGELOG.md | 6 +- .../framework/flow/CFAbstractTransfer.java | 100 +++++++----------- 6 files changed, 56 insertions(+), 289 deletions(-) delete mode 100644 checker/tests/index/UpperBoundComparisonChangesSequence.java diff --git a/checker/src/main/java/org/checkerframework/checker/index/upperbound/OffsetEquation.java b/checker/src/main/java/org/checkerframework/checker/index/upperbound/OffsetEquation.java index 70eece7be474..38860e4bcaba 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/upperbound/OffsetEquation.java +++ b/checker/src/main/java/org/checkerframework/checker/index/upperbound/OffsetEquation.java @@ -5,7 +5,6 @@ import java.util.List; import java.util.Objects; import java.util.Set; -import java.util.function.Predicate; import java.util.regex.Pattern; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.common.value.ValueAnnotatedTypeFactory; @@ -151,26 +150,6 @@ public String toString() { return terms; } - /** - * Returns true if the given predicate is true for any added or subtracted term of this. - * - * @param p a predicate on Java expression strings - * @return true if {@code p} is true for any term of this - */ - public boolean anyTermMatches(Predicate p) { - for (String term : addedTerms) { - if (p.test(term)) { - return true; - } - } - for (String term : subtractedTerms) { - if (p.test(term)) { - return true; - } - } - return false; - } - /** * Makes a copy of this offset and removes any added terms that are accesses to the length of the * listed sequences. If any terms were removed, then the copy is returned. Otherwise, null is @@ -378,9 +357,8 @@ public static OffsetEquation createOffsetForInt(int value) { /** * Creates an offset equation from the expressionEquation. The expressionEquation can be several * Java expressions added or subtracted from each other. The expressionEquation can also start - * with + or -. A + or - within parentheses or brackets, as in {@code offsets[i - 1]}, does not - * separate terms. If the expressionEquation is the empty string, then the offset equation - * returned is zero. + * with + or -. If the expressionEquation is the empty string, then the offset equation returned + * is zero. * * @param expressionEquation a Java expression made up of sums and differences * @return an offset equation created from expressionEquation @@ -441,30 +419,24 @@ private static boolean isIntLiteral(String string) { /** * Returns the first index of a or b in string, at or after index, or -1 if neither char occurs in - * string at or after index. Ignores occurrences within parentheses or brackets that start at or - * after index, so that an expression such as {@code offsets[i - 1]} or {@code f(x + 1)} is not - * split. + * string at or after index. * * @param string the string to search in * @param a a character to search for * @param b another character to search for * @param index the index at which to start the search - * @return the first index of a or b in string at or after index and outside parentheses and - * brackets, or -1 if neither char occurs there + * @return the first index of a or b in string at or after index, or -1 if neither char occurs */ private static int indexOfEither(String string, char a, char b, int index) { - int depth = 0; - for (int i = index; i < string.length(); i++) { - char c = string.charAt(i); - if (c == '(' || c == '[') { - depth++; - } else if ((c == ')' || c == ']') && depth > 0) { - depth--; - } else if (depth == 0 && (c == a || c == b)) { - return i; - } + int aIndex = string.indexOf(a, index); + int bIndex = string.indexOf(b, index); + if (aIndex == -1) { + return bIndex; + } else if (bIndex == -1) { + return aIndex; + } else { + return Math.min(aIndex, bIndex); } - return -1; } /** diff --git a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UBQualifier.java b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UBQualifier.java index 58edeb1a7bd0..ba8f1ab5d262 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UBQualifier.java +++ b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UBQualifier.java @@ -8,7 +8,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.function.Predicate; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import org.checkerframework.checker.index.qual.LTEqLengthOf; @@ -1219,38 +1218,6 @@ public Iterable getSequences() { return map.keySet(); } - /** - * Returns a copy of this qualifier without each (sequence, offset) pair for which {@code - * mayChange} is true of the sequence or of a term of the offset. Returns UNKNOWN if no pair - * remains. - * - * @param mayChange a predicate on Java expression strings: true if the expression might no - * longer have the value that this qualifier refers to - * @return a copy of this qualifier without the pairs that depend on an expression for which - * {@code mayChange} is true - */ - public UBQualifier removeDependentsOf(Predicate mayChange) { - Map> newMap = new HashMap<>(map.size()); - for (Map.Entry> entry : map.entrySet()) { - if (mayChange.test(entry.getKey())) { - continue; - } - Set offsets = new HashSet<>(entry.getValue().size()); - for (OffsetEquation eq : entry.getValue()) { - if (!eq.anyTermMatches(mayChange)) { - offsets.add(eq); - } - } - if (!offsets.isEmpty()) { - newMap.put(entry.getKey(), offsets); - } - } - if (newMap.isEmpty()) { - return UpperBoundUnknownQualifier.UNKNOWN; - } - return new LessThanLengthOf(newMap); - } - /** * Generates a new UBQualifier without the given (sequence, offset) pair. Other occurrences of * the sequence and the offset might remain in the result, but not together. diff --git a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java index b1662f4f2e51..c15fb409668b 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/upperbound/UpperBoundTransfer.java @@ -6,7 +6,6 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import java.util.function.Predicate; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import javax.lang.model.type.TypeKind; @@ -421,22 +420,13 @@ protected TransferResult strengthenAnnotationOfEqualTo( return rfi.newResult; } - /** - * Refines the type of the left and right node to glb of the left and right annotation. - * - *

        Each annotation omits the bounds that might not hold when the comparison completes (see - * {@link #removeBoundsChangedAfter}). - */ + /** Refines the type of the left and right node to glb of the left and right annotation. */ private void refineEq( Node left, AnnotationMirror leftAnno, Node right, AnnotationMirror rightAnno, CFStore store) { UBQualifier leftQualifier = - removeBoundsChangedAfter( - UBQualifier.createUBQualifier(leftAnno, (UpperBoundChecker) atypeFactory.getChecker()), - left); + UBQualifier.createUBQualifier(leftAnno, (UpperBoundChecker) atypeFactory.getChecker()); UBQualifier rightQualifier = - removeBoundsChangedAfter( - UBQualifier.createUBQualifier(rightAnno, (UpperBoundChecker) atypeFactory.getChecker()), - right); + UBQualifier.createUBQualifier(rightAnno, (UpperBoundChecker) atypeFactory.getChecker()); UBQualifier glb = rightQualifier.glb(leftQualifier); AnnotationMirror glbAnno = atypeFactory.convertUBQualifierToAnnotation(glb); @@ -458,20 +448,10 @@ private void refineEq( * offset subtracted) and the other node is less than or equal to that sequence length (minus the * offset), then refine the other node's type to less than the sequence length (minus the offset). * This is case 12. - * - *

        Does nothing if the sequence might change after its length is read and before the comparison - * completes (including by the subtracted offset), because then the comparison does not relate the - * other node to the length of the sequence that the new type refers to. Omits the bounds of the - * other node's type that might not hold when the comparison completes (see {@link - * #removeBoundsChangedAfter}). - * - * @param lengthAccess an operand of a comparison - * @param otherNode the other operand of the comparison - * @param otherNodeAnno the upper bound annotation of {@code otherNode} - * @param store the store to refine */ private void refineNeqSequenceLength( Node lengthAccess, Node otherNode, AnnotationMirror otherNodeAnno, CFStore store) { + // If lengthAccess is "receiver.length - c" where c is an integer constant, // then lengthOffset is "c". int lengthOffset = 0; @@ -505,19 +485,9 @@ private void refineNeqSequenceLength( } if (receiver != null && !receiver.containsUnknown()) { - // Use the length access itself, not the entire operand: the subtracted constant, as in - // `a.length - reset()` where `reset()` has a known value, is evaluated after the length is - // read and might change the sequence. - Predicate mayChange = mayChangeAfterOperand(lengthAccess); - if (mayChange != null && mayChange.test(receiver)) { - // The comparison used the length of the sequence before it changed. - return; - } UBQualifier otherQualifier = - removeBoundsChangedAfter( - UBQualifier.createUBQualifier( - otherNodeAnno, (UpperBoundChecker) atypeFactory.getChecker()), - otherNode); + UBQualifier.createUBQualifier( + otherNodeAnno, (UpperBoundChecker) atypeFactory.getChecker()); String sequence = receiver.toString(); // Check if otherNode + c - 1 < receiver.length if (otherQualifier.hasSequenceWithOffset(sequence, lengthOffset - 1)) { @@ -533,38 +503,6 @@ private void refineNeqSequenceLength( } } - /** - * Returns the given qualifier of an operand of a comparison, without each bound whose sequence or - * offset might change after the operand produces its value and before the comparison completes. - * Such a bound described the operand's value when the operand was evaluated, but it might not - * hold when the comparison completes. For example, in {@code this.a.length == (i = replaceA())}, - * the bound {@code @LTEqLengthOf("this.a")} of {@code this.a.length} does not hold after {@code - * replaceA()} reassigns {@code this.a}. - * - * @param qualifier the qualifier of {@code operand} - * @param operand an operand of a comparison - * @return {@code qualifier}, without the bounds that might not hold when the comparison completes - */ - private UBQualifier removeBoundsChangedAfter(UBQualifier qualifier, Node operand) { - if (!(qualifier instanceof LessThanLengthOf ltl)) { - return qualifier; - } - Predicate mayChange = mayChangeAfterOperand(operand); - if (mayChange == null) { - return qualifier; - } - TreePath path = sourcePath(operand); - if (path == null) { - return UpperBoundUnknownQualifier.UNKNOWN; - } - return ltl.removeDependentsOf( - s -> { - JavaExpression je = UpperBoundVisitor.parseJavaExpressionString(s, atypeFactory, path); - // Conservatively assume that an expression that cannot be parsed might change. - return je == null || mayChange.test(je); - }); - } - /** * If some Node a is known to be less than the length of some array, x, then the type of a + b * is @LTLengthOf(value="x", offset="-b"). If b is known to be less than the length of some other diff --git a/checker/tests/index/UpperBoundComparisonChangesSequence.java b/checker/tests/index/UpperBoundComparisonChangesSequence.java deleted file mode 100644 index 64eeec6728c7..000000000000 --- a/checker/tests/index/UpperBoundComparisonChangesSequence.java +++ /dev/null @@ -1,80 +0,0 @@ -import org.checkerframework.checker.index.qual.LTEqLengthOf; -import org.checkerframework.checker.index.qual.LTLengthOf; -import org.checkerframework.checker.index.qual.NonNegative; -import org.checkerframework.common.value.qual.IntVal; - -// A bound in the type of an operand of a comparison refers to a sequence as it was when the operand -// was evaluated. If the other operand reassigns the sequence, the bound must not be used to refine -// the types of expressions after the comparison. - -public class UpperBoundComparisonChangesSequence { - - int[] a = new int[2]; - - // Not side-effect-free. - @NonNegative @LTEqLengthOf("this.a") int shrink() { - a = new int[1]; - return 1; - } - - void eqUnchanged(int k) { - int i; - if (this.a.length == (i = k)) { - @LTEqLengthOf("this.a") int j = i; - } - } - - // If this.a has length 2 before the call, then the comparison is 2 != 1, but i is 1 and this.a - // has length 1 after the call. - void neqChanged() { - int i; - if (this.a.length != (i = shrink())) { - // :: error: (array.access.unsafe.high) - int x = this.a[i]; - } - } - - void neqUnchanged(@NonNegative @LTEqLengthOf("this.a") int k) { - int i; - if (this.a.length != (i = k)) { - int x = this.a[i]; - } - } - - // Not side-effect-free. Returns 0, so `this.a.length - reset()` has a known offset. - @IntVal(0) int reset() { - a = new int[1]; - return 0; - } - - // If this.a has length 2 before the call, then the comparison is 2 != 1, but i is 1 and this.a - // has length 1 after the call. - void neqChangedByOffset() { - int i; - if (this.a.length - reset() != (i = this.a.length)) { - // :: error: (array.access.unsafe.high) - int x = this.a[i]; - } - } - - @NonNegative int keepSecond(Object o, @NonNegative int x) { - return x; - } - - // If i is 0 and this.a has length 1 before the comparison, the comparison is 0 == 0, but this.a - // is empty after it. - void postfixChanged(@NonNegative @LTLengthOf("this.a") int i) { - int j; - if (i++ == (j = keepSecond(this.a = new int[0], 0))) { - // :: error: (array.access.unsafe.high) - int x = this.a[j]; - } - } - - void postfixUnchanged(@NonNegative @LTLengthOf("this.a") int i, @NonNegative int k) { - int j; - if (i++ == (j = k)) { - int x = this.a[j]; - } - } -} diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 81672d311423..b81264abe535 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -12,10 +12,8 @@ Renamed `CFAbstractTransfer.splitAssignments()` to `nodesWithValueOf()`. Its result omits each node that might have a different value by the time the enclosing comparison completes, such as `n.next` in `n.next == (n = o)`, so the -result can be empty. A subclass that overrides `splitAssignments()` must -override `nodesWithValueOf()` instead. New method -`CFAbstractTransfer.mayChangeAfterOperand()` tells whether an expression that an -operand's type depends on might change before the comparison completes. +result can be empty. `splitAssignments()` is deprecated and final; a subclass +that overrides it must override `nodesWithValueOf()` instead. `CFAbstractStore.canAlias()` is now final. It calls the new method `CFAbstractAnalysis.canAlias()`, which calls the new method diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 3d168d5790d8..23973428f63b 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -25,7 +25,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.function.Predicate; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; @@ -1014,44 +1013,6 @@ private boolean abstractValueMayChangeBeforeComparison(Node node) { return locationsWrittenUntilComparison(node).mayWriteAnyHeapLocation(); } - /** - * Returns a test for expressions whose values might change after the given operand of a - * comparison produces its value and before the comparison completes. Returns null if no variable, - * field, or array element is written in that time. - * - *

        A client uses the test for an expression that the abstract value of the operand depends on, - * such as {@code a} in {@code @LTLengthOf("a")}. If the test returns true, the abstract value - * might not be valid when the comparison completes. For example, in {@code a.length == (i = - * replaceA())}, the abstract value of {@code a.length} depends on {@code a}, which {@code - * replaceA()} might write. - * - *

        If {@code operand} is an assignment, the writes include those of its targets, which happen - * after its value is computed. The test does not consider changes to the abstract value of the - * object that an expression denotes. - * - * @param operand an operand of a comparison - * @return a test for whether the value of an expression might change after {@code operand} - * produces its value and before the comparison completes, or null if no location is written - * in that time - */ - protected @Nullable Predicate mayChangeAfterOperand(Node operand) { - WrittenLocations written = locationsWrittenUntilComparison(operand); - Node n = operand; - while (n instanceof AssignmentNode assignment) { - written.add(JavaExpression.fromNode(assignment.getTarget())); - Tree tree = assignment.getTree(); - if (tree != null) { - // A compound assignment `+=` might perform a string conversion. - written.addOwnWrites(tree); - } - n = assignment.getExpression(); - } - if (written.isEmpty()) { - return null; - } - return expr -> written.valueMayChange(expr, false); - } - /** * Returns the nodes that have the value of the given node when the comparison that contains the * node completes. The comparison is a binary comparison such as {@code ==} or {@code <}, and the @@ -1068,10 +1029,11 @@ private boolean abstractValueMayChangeBeforeComparison(Node node) { * evaluated. (A client such as the SameLen Checker can relate an operation such as {@code "x" + * i} to other expressions, even though no store holds a value for it.) A candidate's value can * change when code that is evaluated after the candidate writes a variable, field, or array - * element that the candidate reads. That code is the rest of the assignment, and the code in the + * element that the candidate reads. That code is the rest of the assignment; the code in the * enclosing expressions that is evaluated after {@code node} and before the comparison completes, - * such as the right operand of the comparison if {@code node} is in its left operand. For - * example: + * such as the right operand of the comparison if {@code node} is in its left operand; and, if + * {@code node} is not an assignment, the code in {@code node} itself, such as the call to {@code + * f()} in {@code i + f()} or {@code a[f()]}. For example: * *

          *
        • The result for {@code n = n.next} is just {@code n}, because after the assignment {@code @@ -1114,16 +1076,32 @@ protected List nodesWithValueOf(Node node) { } /** - * Returns the nodes that have the value of the given node when the comparison that contains the - * node completes. - * - * @param node a node in an operand of a comparison, possibly an assignment - * @return the nodes that have the value of {@code node} when the comparison completes - * @deprecated use {@link #nodesWithValueOf} + * Takes a node, and either returns the node itself again (as a singleton list), or if the node is + * an assignment node, returns the lhs and rhs (where splitAssignments is applied recursively to + * the rhs -- that is, it is possible that the rhs does not appear in the result, but rather its + * lhs and rhs do). + * + *

          The result is purely structural: it may contain a node that does not have the value of + * {@code node} when an enclosing comparison completes, such as {@code a[i]} in {@code i = a[i]}. + * To refine the operands of a comparison, use {@link #nodesWithValueOf} instead. + * + * @param node possibly an assignment node + * @return a list containing all the right- and left-hand sides in the given assignment node; it + * contains just the node itself if it is not an assignment + * @deprecated use {@link #nodesWithValueOf}. This method is final, because the framework does not + * call it; override {@link #nodesWithValueOf} instead. */ @Deprecated // 2026-11-13 - protected List splitAssignments(Node node) { - return nodesWithValueOf(node); + @SideEffectFree + protected final List splitAssignments(Node node) { + if (node instanceof AssignmentNode a) { + List result = new ArrayList<>(2); + result.add(a.getTarget()); + result.addAll(splitAssignments(a.getExpression())); + return result; + } else { + return Collections.singletonList(node); + } } /** @@ -1146,6 +1124,13 @@ private List computeNodesWithValueOf(Node node) { if (isCheckedCandidate(expr)) { if (locationsWrittenUntilComparison == null) { locationsWrittenUntilComparison = locationsWrittenUntilComparison(node); + // If `node` is not an assignment, it is the only candidate, and it might write a location + // after reading it, as in `i + f()` or `a[f()]` where `f()` writes `i` or `a`. Scanning + // all of `node` also includes writes that precede the reads, which is conservative. + Tree tree = node.getTree(); + if (!(node instanceof AssignmentNode) && tree != null) { + locationsWrittenUntilComparison.scan(tree, null); + } } if (locationsWrittenUntilComparison.mayChange(expr, false)) { continue; @@ -1350,7 +1335,7 @@ private WrittenLocations locationsWrittenUntilComparison(Node node) { * @param node a node * @return the path to the source tree that {@code node} represents, or null if there is none */ - protected @Nullable TreePath sourcePath(Node node) { + private @Nullable TreePath sourcePath(Node node) { Tree tree = node.getTree(); if (tree != null) { TreePath path = analysis.atypeFactory.getPath(tree); @@ -1766,19 +1751,6 @@ private boolean mayWriteHeap() { return anyHeapLocation || !fields.isEmpty() || !arrayElements.isEmpty(); } - /** - * Returns true if no location is written. - * - * @return true if no location is written - */ - boolean isEmpty() { - return !anyHeapLocation - && !anyLocal - && locals.isEmpty() - && fields.isEmpty() - && arrayElements.isEmpty(); - } - /** * Returns true if the result of the string conversion of a value of the given type might depend * on a field or an array element. That is the case if the conversion calls {@code toString()} From e27e32221924019c82b91cbbe23d751a103b5ea5 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sat, 28 Nov 2026 18:46:55 -0800 Subject: [PATCH 63/73] nodesWithValueOf does not count the writes of a candidate's own call A call's own side effects precede its result, as for any refinement of the result of a call, such as of a @Deterministic method in StorePure.java. --- .../framework/flow/CFAbstractTransfer.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 23973428f63b..e9f4d7649d6d 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -1032,8 +1032,8 @@ private boolean abstractValueMayChangeBeforeComparison(Node node) { * element that the candidate reads. That code is the rest of the assignment; the code in the * enclosing expressions that is evaluated after {@code node} and before the comparison completes, * such as the right operand of the comparison if {@code node} is in its left operand; and, if - * {@code node} is not an assignment, the code in {@code node} itself, such as the call to {@code - * f()} in {@code i + f()} or {@code a[f()]}. For example: + * {@code node} is not an assignment, the code in the subexpressions of {@code node}, such as the + * call to {@code f()} in {@code i + f()} or {@code a[f()]}. For example: * *

            *
          • The result for {@code n = n.next} is just {@code n}, because after the assignment {@code @@ -1124,12 +1124,14 @@ private List computeNodesWithValueOf(Node node) { if (isCheckedCandidate(expr)) { if (locationsWrittenUntilComparison == null) { locationsWrittenUntilComparison = locationsWrittenUntilComparison(node); - // If `node` is not an assignment, it is the only candidate, and it might write a location - // after reading it, as in `i + f()` or `a[f()]` where `f()` writes `i` or `a`. Scanning - // all of `node` also includes writes that precede the reads, which is conservative. + // If `node` is not an assignment, it is the only candidate, and its subexpressions might + // write a location after it is read, as in `i + f()` or `a[f()]` where `f()` writes `i` + // or `a`. Scanning all the subexpressions also includes writes that precede the reads, + // which is conservative. The writes of `node` itself, such as those of the call in + // `g()`, precede its value, as for any refinement of the result of a call. Tree tree = node.getTree(); if (!(node instanceof AssignmentNode) && tree != null) { - locationsWrittenUntilComparison.scan(tree, null); + tree.accept(locationsWrittenUntilComparison, null); } } if (locationsWrittenUntilComparison.mayChange(expr, false)) { From 92eafec6f0c2ac44599fc4bc8c8bd448fefa8828 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 29 Nov 2026 09:47:51 -0800 Subject: [PATCH 64/73] A write to an array element at a different constant index does not change another element --- .../nullness/AssignmentInComparison.java | 14 ++++++++++ .../framework/flow/CFAbstractTransfer.java | 28 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/checker/tests/nullness/AssignmentInComparison.java b/checker/tests/nullness/AssignmentInComparison.java index d23533cf07d4..1da76a7c114f 100644 --- a/checker/tests/nullness/AssignmentInComparison.java +++ b/checker/tests/nullness/AssignmentInComparison.java @@ -419,6 +419,20 @@ void aliasedArrayAssignmentInRightOperand(@Nullable Object[] a, @Nullable Object } } + // Even if `a` and `b` alias, the right operand assigns a different element than `a[0]`. + void arrayAssignmentAtDifferentIndexInRightOperand(@Nullable Object[] a, @Nullable Object[] b) { + if (a[0] == nonNull(b[1] = null)) { + a[0].toString(); + } + } + + void distinctConstantIndexAssignmentInRightOperand(@Nullable Object[] a, Object value) { + // The right operand assigns `a[1]`, which is a different element than `a[0]`. + if (a[0] == (a[1] = value)) { + a[0].toString(); + } + } + // The left operand assigns `x` before the right operand reads it, so refining `x` is sound. void assignmentInLeftOperand(@Nullable Object x) { if (nonNull(x = null) == x) { diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index e9f4d7649d6d..a3d35bbbafc0 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -1797,13 +1797,41 @@ private boolean mayWriteArrayElement(ArrayAccess aa) { if (anyHeapLocation) { return true; } + Long index = constantIndex(aa.getIndex()); for (ArrayAccess arrayElement : arrayElements) { + Long writtenIndex = constantIndex(arrayElement.getIndex()); + if (index != null && writtenIndex != null && !index.equals(writtenIndex)) { + // Distinct constant indices denote distinct elements, even of the same array. + continue; + } if (analysis.canAlias(arrayElement.getArray(), aa.getArray())) { return true; } } return false; } + + /** + * Returns the value of the given array index if it is an integral or character literal, or null + * otherwise. + * + * @param index an array index + * @return the value of {@code index} if it is a literal, or null + */ + private @Nullable Long constantIndex(JavaExpression index) { + if (index instanceof ValueLiteral literal) { + Object value = literal.getValue(); + if (value instanceof Integer + || value instanceof Long + || value instanceof Short + || value instanceof Byte) { + return ((Number) value).longValue(); + } else if (value instanceof Character c) { + return (long) c.charValue(); + } + } + return null; + } } @Override From c89ae52878812362f18a7e101dc3f12848a9a015 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 29 Nov 2026 10:18:05 -0800 Subject: [PATCH 65/73] Less Than Checker: a floating-point comparison does not imply an integral bound --- .../checker/index/IndexAbstractTransfer.java | 35 +++++++++------ .../index/inequality/LessThanTransfer.java | 6 +++ .../tests/index/LessThanFloatComparison.java | 45 +++++++++++++++++++ 3 files changed, 73 insertions(+), 13 deletions(-) create mode 100644 checker/tests/index/LessThanFloatComparison.java diff --git a/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java index edcbc4190c4a..a992d22a63bd 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java @@ -39,7 +39,7 @@ public TransferResult visitGreaterThan( // Refine the else branch, which is the inverse of the then branch, unless an operand might be // NaN. - if (!isFloatingPointComparison(rfi)) { + if (!isFloatingPointComparison(rfi.left, rfi.right)) { refineGTE(rfi.right, rfi.rightAnno, rfi.left, rfi.leftAnno, rfi.elseStore, in); } @@ -60,7 +60,7 @@ public TransferResult visitGreaterThanOrEqual( refineGTE(rfi.left, rfi.leftAnno, rfi.right, rfi.rightAnno, rfi.thenStore, in); // Refine the else branch, unless an operand might be NaN. - if (!isFloatingPointComparison(rfi)) { + if (!isFloatingPointComparison(rfi.left, rfi.right)) { refineGT(rfi.right, rfi.rightAnno, rfi.left, rfi.leftAnno, rfi.elseStore, in); } @@ -81,7 +81,7 @@ public TransferResult visitLessThanOrEqual( refineGTE(rfi.right, rfi.rightAnno, rfi.left, rfi.leftAnno, rfi.thenStore, in); // Refine the else branch, unless an operand might be NaN. - if (!isFloatingPointComparison(rfi)) { + if (!isFloatingPointComparison(rfi.left, rfi.right)) { refineGT(rfi.left, rfi.leftAnno, rfi.right, rfi.rightAnno, rfi.elseStore, in); } return rfi.newResult; @@ -101,24 +101,33 @@ public TransferResult visitLessThan( refineGT(rfi.right, rfi.rightAnno, rfi.left, rfi.leftAnno, rfi.thenStore, in); // Refine the else branch, unless an operand might be NaN. - if (!isFloatingPointComparison(rfi)) { + if (!isFloatingPointComparison(rfi.left, rfi.right)) { refineGTE(rfi.left, rfi.leftAnno, rfi.right, rfi.rightAnno, rfi.elseStore, in); } return rfi.newResult; } /** - * Returns true if the given comparison is a floating-point comparison: that is, if an operand has - * a floating-point type, primitive or boxed. An operand of such a comparison might be NaN. Every - * comparison with NaN is false, so the else branch of such a comparison does not imply the - * inverse comparison: if {@code d} is NaN, then both {@code i > d} and {@code i <= d} are false. + * Returns true if the comparison of the given operands is a floating-point comparison: that is, + * if an operand has a floating-point type, primitive or boxed. Such a comparison does not imply + * an integral bound, for two reasons. * - * @param rfi refinement information for a numerical comparison - * @return true if the comparison is a floating-point comparison + *
              + *
            • An operand of such a comparison might be NaN. Every comparison with NaN is false, so the + * else branch of such a comparison does not imply the inverse comparison: if {@code d} is + * NaN, then both {@code i > d} and {@code i <= d} are false. + *
            • The comparison converts an integral operand to a floating-point type, which might round + * it. If the {@code float} {@code f} is 16777216.0f and the {@code int} {@code i} is + * 16777217, then {@code f >= i} is true, because {@code i} rounds to 16777216.0f. + *
            + * + * @param left the left operand of a numerical comparison + * @param right the right operand of the comparison + * @return true if the comparison of {@code left} and {@code right} is a floating-point comparison */ - private static boolean isFloatingPointComparison(IndexRefinementInfo rfi) { - return TypesUtils.isFloatingPoint(rfi.left.getType()) - || TypesUtils.isFloatingPoint(rfi.right.getType()); + protected static boolean isFloatingPointComparison(Node left, Node right) { + return TypesUtils.isFloatingPoint(left.getType()) + || TypesUtils.isFloatingPoint(right.getType()); } /** diff --git a/checker/src/main/java/org/checkerframework/checker/index/inequality/LessThanTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/inequality/LessThanTransfer.java index 114a6fe5ef6a..60ab2e7b021b 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/inequality/LessThanTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/inequality/LessThanTransfer.java @@ -48,6 +48,9 @@ protected void refineGT( TransferInput in) { // left > right so right < left // Refine right to @LessThan("left") + if (isFloatingPointComparison(left, right)) { + return; + } JavaExpression leftJe = JavaExpression.fromNode(left); if (leftJe != null && !leftJe.isAssignableByOtherCode()) { if (isDoubleOrFloatLiteral(leftJe)) { @@ -83,6 +86,9 @@ protected void refineGTE( // left > right so right is less than left // Refine right to @LessThan("left") + if (isFloatingPointComparison(left, right)) { + return; + } JavaExpression leftJe = JavaExpression.fromNode(left); if (leftJe != null && !leftJe.isAssignableByOtherCode()) { if (isDoubleOrFloatLiteral(leftJe)) { diff --git a/checker/tests/index/LessThanFloatComparison.java b/checker/tests/index/LessThanFloatComparison.java new file mode 100644 index 000000000000..c2db722face2 --- /dev/null +++ b/checker/tests/index/LessThanFloatComparison.java @@ -0,0 +1,45 @@ +import org.checkerframework.checker.index.qual.LessThan; + +// A comparison that is performed in floating point does not imply an integral bound, because +// converting an integral operand to a floating-point type might round it. +class LessThanFloatComparison { + + // If `limit` is 16777216 and `i` is 16777217, then both round to 16777216.0f, so + // `limit >= (f = i)` is true, but `i < limit + 1` is false. + void rounding(int limit, int i) { + float f; + if (limit >= (f = i)) { + // :: error: [assignment] + @LessThan("limit + 1") int j = i; + } + } + + void roundingExample() { + rounding(16777216, 16777217); + } + + // If `limit` is 16777216 and `i` is 16777217, then `f` is 16777216.0f and `f >= i` is true, + // because `i` rounds to 16777216.0f. But `i < f + 1` is false. + void floatRounding(int limit, int i) { + float f = limit; + if (f >= i) { + // :: error: [assignment] + @LessThan("f + 1") int j = i; + } + } + + // If `limit` is 2^53 and `i` is 2^53 + 1, then `d >= i` is true, because `i` rounds to 2^53. + void doubleRounding(long limit, long i) { + double d = limit; + if (d >= i) { + // :: error: [assignment] + @LessThan("d + 1") long j = i; + } + } + + void intComparison(int limit, int i) { + if (limit >= i) { + @LessThan("limit + 1") int j = i; + } + } +} From 3963ac41b2e1caa2acb8f6fc3bb2033149beeb25 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 29 Nov 2026 10:26:50 -0800 Subject: [PATCH 66/73] Document that a write at one constant index does not change another element --- .../framework/flow/CFAbstractTransfer.java | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index a3d35bbbafc0..46e513e299c3 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -1651,12 +1651,13 @@ public Void visitClass(ClassTree tree, Void p) { * *

            A write to a local variable changes only expressions that contain the variable. A write to * a field changes only accesses of the same field, and method calls. A write to an array - * element changes only accesses of arrays that might alias the written array, and method calls. - * A call to {@code String.length()} changes only if its receiver changes, because a {@code - * String} is immutable. A string concatenation with an operand whose string conversion calls - * {@code toString()} on a possibly mutable object, as in {@code "p" + box}, changes like a - * method call. A change to the abstract value of a receiver, index, argument, or operand does - * not matter (see {@link #valueMayChange}). If side effects unrefine aliases (see {@link + * element changes only accesses of arrays that might alias the written array (except at a + * different constant index), and method calls. A call to {@code String.length()} changes only + * if its receiver changes, because a {@code String} is immutable. A string concatenation with + * an operand whose string conversion calls {@code toString()} on a possibly mutable object, as + * in {@code "p" + box}, changes like a method call. A change to the abstract value of a + * receiver, index, argument, or operand does not matter (see {@link #valueMayChange}). If side + * effects unrefine aliases (see {@link * GenericAnnotatedTypeFactory#sideEffectsUnrefineAliases}), then a write to any field or array * element also changes every expression whose abstract value other code can modify (see {@link * JavaExpression#isModifiableByOtherCode}). From d0fcfb8591618f48db63dbb0e99c3e587be42c66 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 29 Nov 2026 10:44:50 -0800 Subject: [PATCH 67/73] Keep the refinement of a strict floating-point comparison; fix comments and tests --- .../checker/index/IndexAbstractTransfer.java | 8 +++-- .../index/inequality/LessThanTransfer.java | 9 ++--- .../tests/index/LessThanFloatComparison.java | 34 ++++++++++--------- 3 files changed, 25 insertions(+), 26 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java index a992d22a63bd..4d28973c0209 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/IndexAbstractTransfer.java @@ -109,8 +109,8 @@ public TransferResult visitLessThan( /** * Returns true if the comparison of the given operands is a floating-point comparison: that is, - * if an operand has a floating-point type, primitive or boxed. Such a comparison does not imply - * an integral bound, for two reasons. + * if an operand has a floating-point type, primitive or boxed. Such a comparison differs from an + * integral comparison in two ways. * *

              *
            • An operand of such a comparison might be NaN. Every comparison with NaN is false, so the @@ -118,7 +118,9 @@ public TransferResult visitLessThan( * NaN, then both {@code i > d} and {@code i <= d} are false. *
            • The comparison converts an integral operand to a floating-point type, which might round * it. If the {@code float} {@code f} is 16777216.0f and the {@code int} {@code i} is - * 16777217, then {@code f >= i} is true, because {@code i} rounds to 16777216.0f. + * 16777217, then {@code f >= i} is true, because {@code i} rounds to 16777216.0f, but + * {@code i < f + 1} is false. A strict comparison is not affected, because rounding is + * monotonic: if {@code f > i} is true, then so is {@code i < f}. *
            * * @param left the left operand of a numerical comparison diff --git a/checker/src/main/java/org/checkerframework/checker/index/inequality/LessThanTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/inequality/LessThanTransfer.java index 60ab2e7b021b..1e010f3285c9 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/inequality/LessThanTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/inequality/LessThanTransfer.java @@ -25,7 +25,8 @@ * *
              *
            • 1. if left > right, right has type {@code @LessThan("left")} - *
            • 2. if left ≥ right, right has type {@code @LessThan("left + 1")} + *
            • 2. if left ≥ right, right has type {@code @LessThan("left + 1")}, unless the comparison + * is a floating-point comparison (see {@link #isFloatingPointComparison}) *
            • 3. if {@code 0 < right}, {@code left - right} has type {@code @LessThan("left")} *
            * @@ -48,9 +49,6 @@ protected void refineGT( TransferInput in) { // left > right so right < left // Refine right to @LessThan("left") - if (isFloatingPointComparison(left, right)) { - return; - } JavaExpression leftJe = JavaExpression.fromNode(left); if (leftJe != null && !leftJe.isAssignableByOtherCode()) { if (isDoubleOrFloatLiteral(leftJe)) { @@ -83,9 +81,6 @@ protected void refineGTE( TransferInput in) { // left >= right so right is less than left // Refine right to @LessThan("left + 1") - - // left > right so right is less than left - // Refine right to @LessThan("left") if (isFloatingPointComparison(left, right)) { return; } diff --git a/checker/tests/index/LessThanFloatComparison.java b/checker/tests/index/LessThanFloatComparison.java index c2db722face2..e66c7ddccdc3 100644 --- a/checker/tests/index/LessThanFloatComparison.java +++ b/checker/tests/index/LessThanFloatComparison.java @@ -1,23 +1,10 @@ import org.checkerframework.checker.index.qual.LessThan; -// A comparison that is performed in floating point does not imply an integral bound, because -// converting an integral operand to a floating-point type might round it. +// A non-strict comparison that is performed in floating point does not imply an integral bound, +// because converting an integral operand to a floating-point type might round it. A strict +// comparison does imply a bound, because rounding is monotonic. class LessThanFloatComparison { - // If `limit` is 16777216 and `i` is 16777217, then both round to 16777216.0f, so - // `limit >= (f = i)` is true, but `i < limit + 1` is false. - void rounding(int limit, int i) { - float f; - if (limit >= (f = i)) { - // :: error: [assignment] - @LessThan("limit + 1") int j = i; - } - } - - void roundingExample() { - rounding(16777216, 16777217); - } - // If `limit` is 16777216 and `i` is 16777217, then `f` is 16777216.0f and `f >= i` is true, // because `i` rounds to 16777216.0f. But `i < f + 1` is false. void floatRounding(int limit, int i) { @@ -37,6 +24,21 @@ void doubleRounding(long limit, long i) { } } + void floatStrict(float f, int i) { + if (f > i) { + @LessThan("f") int j = i; + } + if (i < f) { + @LessThan("f") int j = i; + } + } + + void doubleStrict(double d, long i) { + if (d > i) { + @LessThan("d") long j = i; + } + } + void intComparison(int limit, int i) { if (limit >= i) { @LessThan("limit + 1") int j = i; From aa998c6823538c7ac8362c78b8b404ca5b40f50a Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Sun, 29 Nov 2026 14:20:06 -0800 Subject: [PATCH 68/73] Count the calls of an enhanced for loop and a try-with-resources statement as writes --- .../nullness/AssignmentInComparison.java | 43 +++++++++++++++++++ .../framework/flow/CFAbstractTransfer.java | 27 +++++++++--- 2 files changed, 64 insertions(+), 6 deletions(-) diff --git a/checker/tests/nullness/AssignmentInComparison.java b/checker/tests/nullness/AssignmentInComparison.java index 1da76a7c114f..57bcd019464a 100644 --- a/checker/tests/nullness/AssignmentInComparison.java +++ b/checker/tests/nullness/AssignmentInComparison.java @@ -476,6 +476,49 @@ void sideEffectFreeCallInRightOperand() { } } + // The loop in the right operand calls `items.iterator()`, which might change `f`. + void enhancedForInRightOperand(Iterable items, String value) { + if (f + == switch (value.length()) { + default -> { + for (Object unused : items) {} + yield value; + } + }) { + // :: error: [dereference.of.nullable] + f.toString(); + } + } + + // A loop over an array calls no method. + void enhancedForOverArrayInRightOperand(Object[] items, String value) { + if (f + == switch (value.length()) { + default -> { + for (Object unused : items) {} + yield value; + } + }) { + f.toString(); + } + } + + // The try statement in the right operand calls `resource.close()`, which might change `f`. + void tryWithResourcesInRightOperand(AutoCloseable resource, String value) { + if (f + == switch (value.length()) { + default -> { + try (resource) { + } catch (Exception e) { + } + yield value; + } + }) { + // :: error: [dereference.of.nullable] + f.toString(); + } + } + static void annotationArgumentInRhs( @Nullable Object o, @Nullable Object p, Map m) { // The annotation argument `"m"` is not an assignment to a variable. diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index 46e513e299c3..b768ebe64020 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -6,6 +6,7 @@ import com.sun.source.tree.BinaryTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompoundAssignmentTree; +import com.sun.source.tree.EnhancedForLoopTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MethodInvocationTree; @@ -13,6 +14,7 @@ import com.sun.source.tree.NewClassTree; import com.sun.source.tree.SwitchExpressionTree; import com.sun.source.tree.Tree; +import com.sun.source.tree.TryTree; import com.sun.source.tree.UnaryTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; @@ -1425,10 +1427,13 @@ public Void scan(@Nullable Tree subtree, Void p) { * field, or an array element, such as {@code x}, {@code o.f}, or {@code a[i]}. {@link #add} adds * a write to a given location, and {@link #scan} adds the writes that evaluating a tree might * perform: its assignments, compound assignments, increments, decrements, method calls, object - * creations, string conversions, and record patterns. A method call, object creation, string - * conversion (which calls {@code toString()}), or record pattern (which calls record component - * accessors) might write every non-final field and every array element, unless the method or - * constructor is side-effect-free; {@link #anyHeapLocation} records that. + * creations, string conversions, record patterns, enhanced {@code for} loops over an {@code + * Iterable}, and try-with-resources statements. A method call, object creation, string conversion + * (which calls {@code toString()}), record pattern (which calls record component accessors), + * enhanced {@code for} loop over an {@code Iterable} (which calls {@code iterator()}), or + * try-with-resources statement (which calls {@code close()}) might write every non-final field + * and every array element, unless the method or constructor is side-effect-free; {@link + * #anyHeapLocation} records that. * *

            {@link #scan} does not descend into lambda bodies or class bodies, because they do not * execute when the tree is evaluated. The writes of such a body to fields and array elements are @@ -1505,8 +1510,9 @@ void add(JavaExpression target) { /** * Adds the writes that the given tree performs itself, after its subtrees are evaluated: the * write of an assignment, compound assignment, increment, or decrement, and the writes of a - * method call, object creation, string conversion, or record pattern. Does not add the writes - * of the subtrees. + * method call, object creation, string conversion, record pattern, enhanced {@code for} loop + * over an {@code Iterable}, or try-with-resources statement. Does not add the writes of the + * subtrees. * * @param tree a tree */ @@ -1535,6 +1541,15 @@ void addOwnWrites(Tree tree) { addStringConversions(binaryTree.getLeftOperand(), binaryTree.getRightOperand()); } else if (TreeUtils.isDeconstructionPatternTree(tree)) { addRecordAccessorCalls(tree); + } else if (tree instanceof EnhancedForLoopTree enhancedForLoopTree + && TreeUtils.typeOf(enhancedForLoopTree.getExpression()).getKind() != TypeKind.ARRAY) { + // A loop over an `Iterable` calls `iterator()`, `hasNext()`, and `next()`, whose + // implementations are not known statically. A loop over an array calls no method. + anyHeapLocation = true; + } else if (tree instanceof TryTree tryTree && !tryTree.getResources().isEmpty()) { + // A try-with-resources statement implicitly calls `close()` on each resource, whose + // implementation is not known statically. + anyHeapLocation = true; } } From 8b1aa28689b6bdf6c51d563eb43c100aba85affc Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 30 Nov 2026 15:56:08 -0800 Subject: [PATCH 69/73] nodesWithValueOf: a node with no source tree is not changed by a write to a local variable Such a node is a use of a variable that the CFG introduces (as for a switch selector) or a use that the CFG adds (as in the null test before a try-with-resources statement's close() call). Omitting it lost the refinements of switch cases and of that null test, which made ValueTest fail on Switch.java and the Resource Leak Checker report false positives. --- .../framework/flow/CFAbstractTransfer.java | 29 +++++++++---------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java index b768ebe64020..d1dfe6562527 100644 --- a/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java +++ b/framework/src/main/java/org/checkerframework/framework/flow/CFAbstractTransfer.java @@ -1288,8 +1288,8 @@ private boolean mayBeChanged(Node side, WrittenLocations written) { *

            If no comparison encloses the node, the result contains the locations written up to the * outermost enclosing expression, or up to an enclosing lambda or switch expression. * - *

            If the source tree of the node cannot be found, the result contains every location, because - * the writes are unknown. + *

            If the node has no source tree, the result contains every non-final field and every array + * element, but no local variable. * * @param node a node * @return the locations that are written after {@code node} is evaluated and before the @@ -1299,7 +1299,16 @@ private WrittenLocations locationsWrittenUntilComparison(Node node) { WrittenLocations result = new WrittenLocations(); TreePath path = sourcePath(node); if (path == null) { - result.addEveryLocation(); + // `node` has no source tree only if it is a use of a variable that the CFG introduces, such + // as the variable that holds the value of a switch selector, or a use that the CFG adds, such + // as the use of a resource variable in the null test that precedes the implicit call to + // `close()` in a try-with-resources statement. Source code does not write a variable that + // the CFG introduces, and the CFG does not write one between a use of it and the completion + // of the comparison that contains the use. The CFG adds no code between a use that it adds + // and the comparison that it adds. But a comparison in the source code can use a variable + // that the CFG introduces, as in `switch (x) { ... } == f()`, and `f()` might write any + // non-final field or array element. + result.anyHeapLocation = true; return result; } UnaryTree postfixTree = postfixTreeOfTemporary(node); @@ -1462,21 +1471,9 @@ private final class WrittenLocations extends TreeScanner { */ private boolean anyHeapLocation = false; - /** - * True if every local variable might be written, as when the writes are unknown. If true, then - * {@link #anyHeapLocation} is also true. - */ - private boolean anyLocal = false; - /** Creates an empty set of locations. */ WrittenLocations() {} - /** Adds a write to every location: every local variable, field, and array element. */ - void addEveryLocation() { - anyLocal = true; - anyHeapLocation = true; - } - /** * Returns true if every non-final field and every array element might be written, as by a call * to a method that is not side-effect-free. @@ -1717,7 +1714,7 @@ boolean mayChange(JavaExpression expr, boolean ignoreOwnLocation) { */ boolean valueMayChange(JavaExpression expr, boolean ignoreOwnLocation) { if (expr instanceof LocalVariable) { - return !ignoreOwnLocation && (anyLocal || locals.contains(expr)); + return !ignoreOwnLocation && locals.contains(expr); } else if (expr instanceof FieldAccess fa) { return (!ignoreOwnLocation && mayWriteField(fa)) || valueMayChange(fa.getReceiver(), false); } else if (expr instanceof ArrayAccess aa) { From 31e4df15fa66043648e128ae91c13f6e1297c956 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 30 Nov 2026 22:43:06 -0800 Subject: [PATCH 70/73] Lower Bound Checker: do not refine a floating-point value to @Positive because it is non-zero --- .../index/lowerbound/LowerBoundTransfer.java | 25 ++++++++++- .../index/FloatingPointNotEqualZero.java | 42 +++++++++++++++++++ 2 files changed, 65 insertions(+), 2 deletions(-) create mode 100644 checker/tests/index/FloatingPointNotEqualZero.java diff --git a/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java index df015a4382d4..9aa47b16358d 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java @@ -38,6 +38,7 @@ import org.checkerframework.javacutil.AnnotationUtils; import org.checkerframework.javacutil.BugInCF; import org.checkerframework.javacutil.TreeUtils; +import org.checkerframework.javacutil.TypesUtils; /** * Implements dataflow refinement rules based on tests: <, >, ==, and their derivatives. @@ -211,7 +212,7 @@ private void notEqualToValue( if (intLiteral == 0) { if (atypeFactory.areSameByClass(otherAnno, NonNegative.class)) { - insertValueForComparedNode(store, otherNode, POS); + insertPositiveForComparedNode(store, otherNode); } } else if (intLiteral == -1) { if (atypeFactory.areSameByClass(otherAnno, GTENegativeOne.class)) { @@ -271,7 +272,27 @@ private void notEqualsLessThan( if (atypeFactory .getLessThanAnnotatedTypeFactory() .isLessThanOrEqual(leftTree, otherJe.toString())) { - insertValueForComparedNode(store, otherNode, POS); + insertPositiveForComparedNode(store, otherNode); + } + } + + /** + * Inserts {@code @Positive} into the store for each integral expression that has the value of the + * given node when the comparison that contains the node completes (see {@link + * #nodesWithValueOf}). The caller has established that the value is non-negative and non-zero. + * That implies {@code @Positive} (at least 1) only for an integral expression: a floating-point + * value such as 0.5 is non-negative and non-zero but is less than 1. This method checks the type + * of each expression rather than of {@code node}, because {@code node} might be a + * value-preserving cast such as {@code (double) i}, whose operand is integral. + * + * @param store the store to modify + * @param node a node in an operand of a comparison, whose value is non-negative and non-zero + */ + private void insertPositiveForComparedNode(CFStore store, Node node) { + for (Node internal : nodesWithValueOf(node)) { + if (!TypesUtils.isFloatingPoint(internal.getType())) { + store.insertValue(JavaExpression.fromNode(internal), POS); + } } } diff --git a/checker/tests/index/FloatingPointNotEqualZero.java b/checker/tests/index/FloatingPointNotEqualZero.java new file mode 100644 index 000000000000..76c082ff2a61 --- /dev/null +++ b/checker/tests/index/FloatingPointNotEqualZero.java @@ -0,0 +1,42 @@ +import org.checkerframework.checker.index.qual.NonNegative; +import org.checkerframework.checker.index.qual.Positive; + +// A non-negative value that is not equal to 0 is @Positive (at least 1) only if it is integral: a +// floating-point value such as 0.5 is non-negative and non-zero but is less than 1. +public class FloatingPointNotEqualZero { + + void doubleNotEqualZero(@NonNegative double d) { + if (d != 0) { + // :: error: (assignment) + @Positive double p = d; + } + } + + void doubleEqualZero(@NonNegative double d) { + if (d == 0) { + } else { + // :: error: (assignment) + @Positive double p = d; + } + } + + void floatNotEqualZero(@NonNegative float f) { + if (f != 0) { + // :: error: (assignment) + @Positive float p = f; + } + } + + void castDoubleNotEqualZero(@NonNegative double d) { + if ((double) d != 0) { + // :: error: (assignment) + @Positive double p = d; + } + } + + void intNotEqualZero(@NonNegative int i) { + if (i != 0) { + @Positive int p = i; + } + } +} From 6c9be16435c1f46b175336faa6834f830f62fd47 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 30 Nov 2026 23:02:38 -0800 Subject: [PATCH 71/73] Make the aliased-receiver tests detect a missed .other diagnostic; changelog: nodesWithValueOf replaces splitAssignments --- .../nullness/AssignmentInComparison.java | 20 +++++++++++-------- docs/CHANGELOG.md | 9 +++++---- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/checker/tests/nullness/AssignmentInComparison.java b/checker/tests/nullness/AssignmentInComparison.java index 57bcd019464a..486fb892c1da 100644 --- a/checker/tests/nullness/AssignmentInComparison.java +++ b/checker/tests/nullness/AssignmentInComparison.java @@ -98,10 +98,12 @@ static void fieldTargetChangesRhsReceiver(AssignmentInComparison n, AssignmentIn } if ((n.next = o.next.other) != null) { n.next.toString(); - // The assignment to `n.next` might change `o.next`, if `n` and `o` alias. - // :: error: [dereference.of.nullable] - // :: error: [dereference.of.nullable] - o.next.other.toString(); + // The assignment to `n.next` might change `o.next`, if `n` and `o` alias. Then `o.next` is + // non-null, but `o.next.other` might be null. + if (o.next != null) { + // :: error: [dereference.of.nullable] + o.next.other.toString(); + } } } @@ -118,10 +120,12 @@ static void fieldTargetChangesRhsReceiverGeneric( if ((a.next = b.next.other) != null) { a.next.toString(); // Neither receiver type is a subtype of the other, but a `Box` can be both. The - // assignment to `a.next` might change `b.next`, if `a` and `b` alias. - // :: error: [dereference.of.nullable] - // :: error: [dereference.of.nullable] - b.next.other.toString(); + // assignment to `a.next` might change `b.next`, if `a` and `b` alias. Then `b.next` is + // non-null, but `b.next.other` might be null. + if (b.next != null) { + // :: error: [dereference.of.nullable] + b.next.other.toString(); + } } } diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 3ec6b6688ef8..60ccafa58ad4 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -18,10 +18,11 @@ workaround. ### Changes for type system implementers -Renamed `CFAbstractTransfer.splitAssignments()` to `nodesWithValueOf()`. Its -result omits each node that might have a different value by the time the -enclosing comparison completes, such as `n.next` in `n.next == (n = o)`, so the -result can be empty. `splitAssignments()` is deprecated and final; a subclass +New method `CFAbstractTransfer.nodesWithValueOf()` replaces +`splitAssignments()`. Its result omits each node that might have a different +value by the time the enclosing comparison completes, such as `n.next` in +`n.next == (n = o)`, so the result can be empty. `splitAssignments()` is +deprecated and final, and its result is still purely structural; a subclass that overrides it must override `nodesWithValueOf()` instead. `CFAbstractStore.canAlias()` is now final. It calls the new method From e874f186c6b456d8b51b127b0457cf1d31588400 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 30 Nov 2026 23:02:44 -0800 Subject: [PATCH 72/73] Lower Bound Checker: x > -1 or x > 0 promotes x only if x is integral --- .../index/lowerbound/LowerBoundTransfer.java | 58 ++++++++++---- .../tests/index/FloatingPointGreaterThan.java | 79 +++++++++++++++++++ 2 files changed, 123 insertions(+), 14 deletions(-) create mode 100644 checker/tests/index/FloatingPointGreaterThan.java diff --git a/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java index 9aa47b16358d..bf22082bf17a 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java @@ -216,7 +216,7 @@ private void notEqualToValue( } } else if (intLiteral == -1) { if (atypeFactory.areSameByClass(otherAnno, GTENegativeOne.class)) { - insertValueForComparedNode(store, otherNode, NN); + insertNonNegativeForComparedNode(store, otherNode); } } } @@ -277,22 +277,50 @@ private void notEqualsLessThan( } /** - * Inserts {@code @Positive} into the store for each integral expression that has the value of the - * given node when the comparison that contains the node completes (see {@link - * #nodesWithValueOf}). The caller has established that the value is non-negative and non-zero. - * That implies {@code @Positive} (at least 1) only for an integral expression: a floating-point - * value such as 0.5 is non-negative and non-zero but is less than 1. This method checks the type - * of each expression rather than of {@code node}, because {@code node} might be a - * value-preserving cast such as {@code (double) i}, whose operand is integral. + * Refines each expression that has the value of the given node when the comparison that contains + * the node completes (see {@link #nodesWithValueOf}), given that the value is greater than 0. That + * implies {@code @Positive} (at least 1) for an integral expression, but only {@code + * @NonNegative} for a floating-point expression: a value such as 0.5 is greater than 0 but is less + * than 1. * * @param store the store to modify - * @param node a node in an operand of a comparison, whose value is non-negative and non-zero + * @param node a node in an operand of a comparison, whose value is greater than 0 */ private void insertPositiveForComparedNode(CFStore store, Node node) { + insertValueForComparedNode(store, node, POS, NN); + } + + /** + * Refines each expression that has the value of the given node when the comparison that contains + * the node completes (see {@link #nodesWithValueOf}), given that the value is greater than -1. + * That implies {@code @NonNegative} (at least 0) for an integral expression, but only + * {@code @GTENegativeOne} for a floating-point expression: a value such as -0.5 is greater than + * -1 but is less than 0. + * + * @param store the store to modify + * @param node a node in an operand of a comparison, whose value is greater than -1 + */ + private void insertNonNegativeForComparedNode(CFStore store, Node node) { + insertValueForComparedNode(store, node, NN, GTEN1); + } + + /** + * Inserts an annotation into the store for each expression that has the value of the given node + * when the comparison that contains the node completes (see {@link #nodesWithValueOf}). This + * method checks the type of each expression rather than of {@code node}, because {@code node} + * might be a value-preserving cast such as {@code (double) i}, whose operand is integral. + * + * @param store the store to modify + * @param node a node in an operand of a comparison + * @param integralAnno the annotation to insert for an integral expression + * @param floatingPointAnno the annotation to insert for a floating-point expression + */ + private void insertValueForComparedNode( + CFStore store, Node node, AnnotationMirror integralAnno, AnnotationMirror floatingPointAnno) { for (Node internal : nodesWithValueOf(node)) { - if (!TypesUtils.isFloatingPoint(internal.getType())) { - store.insertValue(JavaExpression.fromNode(internal), POS); - } + AnnotationMirror anno = + TypesUtils.isFloatingPoint(internal.getType()) ? floatingPointAnno : integralAnno; + store.insertValue(JavaExpression.fromNode(internal), anno); } } @@ -318,14 +346,16 @@ protected void refineGT( return; } + // left > -1 implies left >= 0, and left > 0 implies left >= 1, only if left is integral. if (AnnotationUtils.areSame(rightAnno, GTEN1)) { - insertValueForComparedNode(store, left, NN); + insertNonNegativeForComparedNode(store, left); return; } if (AnnotationUtils.areSame(rightAnno, NN)) { - insertValueForComparedNode(store, left, POS); + insertPositiveForComparedNode(store, left); return; } + // left > right >= 1 implies left >= 1, even if left is a floating-point value. if (AnnotationUtils.areSame(rightAnno, POS)) { insertValueForComparedNode(store, left, POS); return; diff --git a/checker/tests/index/FloatingPointGreaterThan.java b/checker/tests/index/FloatingPointGreaterThan.java new file mode 100644 index 000000000000..37bd94233fea --- /dev/null +++ b/checker/tests/index/FloatingPointGreaterThan.java @@ -0,0 +1,79 @@ +import org.checkerframework.checker.index.qual.GTENegativeOne; +import org.checkerframework.checker.index.qual.NonNegative; +import org.checkerframework.checker.index.qual.Positive; + +// A value that is greater than -1 is @NonNegative (at least 0), and a value that is greater than 0 +// is @Positive (at least 1), only if it is integral: a floating-point value such as -0.5 is greater +// than -1 but is less than 0, and 0.5 is greater than 0 but is less than 1. +public class FloatingPointGreaterThan { + + void doubleGreaterThanGten1(double d, @GTENegativeOne int limit) { + if (d > limit) { + @GTENegativeOne double g = d; + // :: error: (assignment) + @NonNegative double n = d; + } + } + + void castDoubleGreaterThanGten1(double d, @GTENegativeOne int limit) { + if ((double) d > limit) { + // :: error: (assignment) + @NonNegative double n = d; + } + } + + // If d is -0.5, limit is -1, and i is 0, then both comparisons hold. + void castDoubleGreaterThanGten1ThenInt(double d, @GTENegativeOne int limit, int i) { + if ((double) d > limit && i > d) { + // :: error: (assignment) + @Positive int p = i; + } + } + + void intGreaterThanGten1(int i, @GTENegativeOne int limit) { + if (i > limit) { + @NonNegative int n = i; + } + } + + void doubleGreaterThanNonNegative(double d, @NonNegative int limit) { + if (d > limit) { + @NonNegative double n = d; + // :: error: (assignment) + @Positive double p = d; + } + } + + void castDoubleGreaterThanNonNegative(double d, @NonNegative int limit) { + if ((double) d > limit) { + // :: error: (assignment) + @Positive double p = d; + } + } + + void intGreaterThanNonNegative(int i, @NonNegative int limit) { + if (i > limit) { + @Positive int p = i; + } + } + + // A value that is greater than a value that is at least 1 is at least 1. + void doubleGreaterThanPositive(double d, @Positive int limit) { + if (d > limit) { + @Positive double p = d; + } + } + + void doubleNotEqualNegativeOne(@GTENegativeOne double d) { + if (d != -1) { + // :: error: (assignment) + @NonNegative double n = d; + } + } + + void intNotEqualNegativeOne(@GTENegativeOne int i) { + if (i != -1) { + @NonNegative int n = i; + } + } +} From d0870217a771cd1df3fe642be0055ee894425a34 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Mon, 30 Nov 2026 23:13:05 -0800 Subject: [PATCH 73/73] Reformat --- .../checker/index/lowerbound/LowerBoundTransfer.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java b/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java index bf22082bf17a..9b0d517c3783 100644 --- a/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/index/lowerbound/LowerBoundTransfer.java @@ -278,10 +278,10 @@ private void notEqualsLessThan( /** * Refines each expression that has the value of the given node when the comparison that contains - * the node completes (see {@link #nodesWithValueOf}), given that the value is greater than 0. That - * implies {@code @Positive} (at least 1) for an integral expression, but only {@code - * @NonNegative} for a floating-point expression: a value such as 0.5 is greater than 0 but is less - * than 1. + * the node completes (see {@link #nodesWithValueOf}), given that the value is greater than 0. + * That implies {@code @Positive} (at least 1) for an integral expression, but only + * {@code @NonNegative} for a floating-point expression: a value such as 0.5 is greater than 0 but + * is less than 1. * * @param store the store to modify * @param node a node in an operand of a comparison, whose value is greater than 0