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 4d28973c0209..dc3e327a6ea2 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; @@ -107,6 +108,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 #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); + } + } + /** * 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 differs from an 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 4ed708252809..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 @@ -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,19 +212,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); - } + insertPositiveForComparedNode(store, otherNode); } } 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); - } + insertNonNegativeForComparedNode(store, otherNode); } } } @@ -271,11 +264,63 @@ 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())) { + insertPositiveForComparedNode(store, otherNode); + } + } + + /** + * 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 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)) { + AnnotationMirror anno = + TypesUtils.isFloatingPoint(internal.getType()) ? floatingPointAnno : integralAnno; + store.insertValue(JavaExpression.fromNode(internal), anno); } } @@ -301,18 +346,18 @@ protected void refineGT( return; } - JavaExpression leftJe = JavaExpression.fromNode(left); - + // left > -1 implies left >= 0, and left > 0 implies left >= 1, only if left is integral. if (AnnotationUtils.areSame(rightAnno, GTEN1)) { - store.insertValue(leftJe, NN); + insertNonNegativeForComparedNode(store, left); return; } if (AnnotationUtils.areSame(rightAnno, NN)) { - store.insertValue(leftJe, POS); + insertPositiveForComparedNode(store, left); return; } + // left > right >= 1 implies left >= 1, even if left is a floating-point value. if (AnnotationUtils.areSame(rightAnno, POS)) { - store.insertValue(leftJe, POS); + insertValueForComparedNode(store, left, POS); return; } } @@ -338,14 +383,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/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/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 688a43346940..291ee8b4a38f 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)); } } @@ -259,11 +258,11 @@ 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); - JavaExpression leftJe = JavaExpression.fromNode(node.getLeftOperand()); - store.insertValue(leftJe, atypeFactory.convertUBQualifierToAnnotation(newLeft)); + insertValueForComparedNode( + store, node.getLeftOperand(), atypeFactory.convertUBQualifierToAnnotation(newLeft)); } /** @@ -285,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)) { @@ -293,8 +292,47 @@ 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)); + } + + /** + * 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)}, 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 + * @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) + && JavaExpression.fromNode(offsetNode).isDeterministic(atypeFactory)) { + 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()); } /** @@ -324,8 +362,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 +390,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)); } /** @@ -387,9 +425,9 @@ 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)); + offsetByComparedNode(minuendQual, offsetNode, '+').plusOffset(offsetAddOne ? 1 : 0)); + insertValueForComparedNode( + store, subtrahend, atypeFactory.convertUBQualifierToAnnotation(newQual)); } } @@ -430,17 +468,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 +524,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/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java index de99df0b058e..b352d4c3a0d2 100644 --- a/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java +++ b/checker/src/main/java/org/checkerframework/checker/nullness/NullnessTransfer.java @@ -236,7 +236,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/checker/tests/index/AssignmentInComparison.java b/checker/tests/index/AssignmentInComparison.java new file mode 100644 index 000000000000..f6a8e24b761a --- /dev/null +++ b/checker/tests/index/AssignmentInComparison.java @@ -0,0 +1,105 @@ +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; +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 { + + @NonNegative int f; + + int[] arr = new int[0]; + + int[] setArr(int[] c, int[] d) { + arr = c; + return d; + } + + // Assigning the result to `f` can change the result of the next call. + @Pure + @NonNegative int size() { + return f == 0 ? 1 : 0; + } + + 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; + } + } + + 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; + } + } + + @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`. + @LTLengthOf(value = "a", offset = "choose()") + // :: error: [assignment] + 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, int[] d) { + if ((this.arr = b).length == setArr(c, d).length) { + // `setArr` sets `this.arr` to `c`, which might not have the same length as `b` and `d`. + // :: error: [assignment] + int @SameLen("b") [] x = this.arr; + } + } +} 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; + } + } +} 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; + } + } +} 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 new file mode 100644 index 000000000000..954361d938a7 --- /dev/null +++ b/checker/tests/index/SameLenComparisonChangesOperand.java @@ -0,0 +1,106 @@ +// 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); + } + } + } + + // 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); + } + } + } + + static class Holder { + String text = ""; + } + + static Holder current = new Holder(); + + // Not side-effect-free. + static String swap() { + current = new Holder(); + return ""; + } + + // 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); + } + } + } + + 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/nonempty/AssignmentInComparison.java b/checker/tests/nonempty/AssignmentInComparison.java new file mode 100644 index 000000000000..faee201769f7 --- /dev/null +++ b/checker/tests/nonempty/AssignmentInComparison.java @@ -0,0 +1,60 @@ +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 { + + // Not side-effect-free. + List newList() { + return new ArrayList<>(); + } + + void callInRhs(@NonEmpty List ne) { + List l; + if ((l = newList()) == ne) { + @NonEmpty List m = l; + } + } + + // 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(); + 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/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/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(); + } + } +} diff --git a/checker/tests/nullness/AssignmentInComparison.java b/checker/tests/nullness/AssignmentInComparison.java new file mode 100644 index 000000000000..486fb892c1da --- /dev/null +++ b/checker/tests/nullness/AssignmentInComparison.java @@ -0,0 +1,533 @@ +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; + +// 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 @Nullable AssignmentInComparison global; + + @MonotonicNonNull AssignmentInComparison mono; + + static @MonotonicNonNull AssignmentInComparison monoGlobal; + + @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; + } + 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 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 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(); + n.next.toString(); + } + } + + static void fieldTarget(AssignmentInComparison n, AssignmentInComparison o) { + if ((n.next = o.other) != null) { + n.next.toString(); + // 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. 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(); + } + } + } + + 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. 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(); + } + } + } + + 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(); + } + } + + 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; + } + 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(); + } + } + + 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(); + 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(); + 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(); + } + } + + 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) { + 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(); + } + } + + 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(); + } + } + + 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 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) { + // 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; + } + + 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] + ss[0][0].toString(); + } + } + + // 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 ""; + } + + // 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(); + } + } + + // 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) { + 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(); + } + } + + // 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. + if ((o = new ArrayList<@KeyFor("m") String>()) == p) { + p.toString(); + } + } +} 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/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/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/docs/CHANGELOG.md b/docs/CHANGELOG.md index 27794ca8c071..60ccafa58ad4 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -18,6 +18,18 @@ workaround. ### Changes for type system implementers +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 +`CFAbstractAnalysis.canAlias()`, which calls the new method +`TypesUtils.canAlias()`. To change the aliasing judgment, override +`CFAbstractAnalysis.canAlias()`. + `AnnotatedTypeFactory.binaryTreeArgTypes(AnnotatedTypeMirror, AnnotatedTypeMirror)` takes an additional first argument, the operator. 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 b1fbaaa9df99..0c4425418db6 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 7c271f6af25e..34d86f821722 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 @@ -118,6 +119,17 @@ public record FieldInitialValue>( private final IdentityHashMap> sideEffectsOnlyExpressionsCache = new IdentityHashMap<>(); + /** + * 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. + * + *

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<>(); + /** * Cache for {@link StringToJavaExpression#atMethodDecl}, as called by {@link * #computeSideEffectsOnlyExpressions}. Parsing an expression in the scope of the method that @@ -195,11 +207,20 @@ 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. - sideEffectsOnlyExpressionsCache.clear(); 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.initFields(cfg); + } + /** * Returns the expressions that the invoked method side-effects (specified as arguments/elements * of {@code @SideEffectsOnly}), viewpoint-adapted to the given method invocation. Returns null if @@ -508,4 +529,21 @@ public Types getTypes() { public ProcessingEnvironment getEnv() { return env; } + + /** + * Returns true if the given expressions might evaluate to the same object, judging by their + * 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 + */ + public boolean canAlias(JavaExpression a, JavaExpression b) { + return TypesUtils.canAlias(a.getType(), b.getType(), types); + } } 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 a6929b4e1979..33f44111de11 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; @@ -1345,16 +1344,17 @@ 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). + * Returns true if the objects {@code a} and {@code b} can be aliases, judging by their types. + * 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) { - TypeMirror tb = b.getType(); - TypeMirror ta = a.getType(); - Types types = analysis.getTypes(); - return types.isSubtype(ta, tb) || types.isSubtype(tb, ta); + public final boolean canAlias(JavaExpression a, JavaExpression b) { + 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 1dd6b36f797a..d1dfe6562527 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,24 @@ 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.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; import com.sun.source.tree.MethodTree; 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; +import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol.ClassSymbol; import java.util.ArrayList; import java.util.Collections; @@ -22,8 +31,10 @@ 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; import javax.lang.model.type.TypeMirror; import org.checkerframework.checker.interning.qual.InternedDistinct; import org.checkerframework.checker.nullness.qual.Nullable; @@ -40,6 +51,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; @@ -66,11 +78,20 @@ 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.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.Unknown; +import org.checkerframework.dataflow.expression.ValueLiteral; import org.checkerframework.dataflow.qual.Pure; import org.checkerframework.dataflow.qual.SideEffectFree; import org.checkerframework.dataflow.util.NodeUtils; @@ -96,6 +117,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 @@ -128,6 +150,15 @@ 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. */ + 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. * @@ -152,6 +183,8 @@ 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()); + this.stringLength = TreeUtils.getMethod("java.lang.String", "length", 0, analysis.getEnv()); } /** @@ -907,9 +940,15 @@ 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. + *

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

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 @@ -929,8 +968,8 @@ protected TransferResult strengthenAnnotationOfEqualTo( boolean notEqualTo) { if (firstValue != null) { // Only need to insert if the second value is actually different. - if (!firstValue.equals(secondValue)) { - List secondParts = splitAssignments(secondNode); + if (!firstValue.equals(secondValue) && !abstractValueMayChangeBeforeComparison(firstNode)) { + List secondParts = nodesWithValueOf(secondNode); for (Node secondPart : secondParts) { JavaExpression secondInternal = JavaExpression.fromNode(secondPart); if (!secondInternal.isDeterministic(analysis.atypeFactory)) { @@ -954,18 +993,109 @@ 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 + * 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}), 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; 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 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 + * n.next} is a field of a different object. Likewise, the result for {@code n.next = (n = + * o).other} omits {@code n.next}. + *
  • The result for the left operand of {@code n.next == o} is {@code n.next}, but the result + * for the left operand of {@code n.next == (n = o)} is empty, because {@code n = o} is + * evaluated after {@code n.next}. + *
  • The result for {@code a[i = 0] = b[i]} contains {@code b[i]}, because {@code i = 0} is + * evaluated before {@code b[i]}. + *
+ * + * 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. + * + *

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 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 nodesWithValueOf(Node node) { + List result = analysis.nodesWithValueOfCache.get(node); + if (result == null) { + result = Collections.unmodifiableList(computeNodesWithValueOf(node)); + analysis.nodesWithValueOfCache.put(node, result); + } + return result; + } + /** * 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 @SideEffectFree - protected List splitAssignments(Node node) { + protected final List splitAssignments(Node node) { if (node instanceof AssignmentNode a) { List result = new ArrayList<>(2); result.add(a.getTarget()); @@ -976,6 +1106,747 @@ protected List splitAssignments(Node node) { } } + /** + * Returns the result of {@link #nodesWithValueOf}, without using the cache. + * + * @param node a node in an operand of a comparison, possibly an assignment + * @return the result of {@link #nodesWithValueOf} for {@code node} + */ + private List computeNodesWithValueOf(Node node) { + List candidates = + node instanceof AssignmentNode assignment + ? sidesOfAssignment(assignment) + : Collections.singletonList(node); + // 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 (isCheckedCandidate(expr)) { + if (locationsWrittenUntilComparison == null) { + locationsWrittenUntilComparison = locationsWrittenUntilComparison(node); + // 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) { + tree.accept(locationsWrittenUntilComparison, null); + } + } + if (locationsWrittenUntilComparison.mayChange(expr, false)) { + continue; + } + } + result.add(candidate); + } + 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 the sides of the given assignment that have the value of the assignment when the + * 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, 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 + */ + 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) { + chain.add(a); + rhs = a.getExpression(); + } + + // 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 `written` contains the locations that are + // written while or after each side is evaluated. + WrittenLocations written = new WrittenLocations(); + for (AssignmentNode a : chain) { + written.add(JavaExpression.fromNode(a.getTarget())); + } + ExpressionTree rhsTree = rhsTree(chain.get(chain.size() - 1)); + 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. + 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, written)) { + sides[chain.size()] = rhs; + resultSize++; + } + for (int i = chain.size() - 1; i >= 0; i--) { + Node target = chain.get(i).getTarget(); + written.scan(target.getTree(), null); + if (!mayBeChanged(target, written)) { + sides[i] = target; + resultSize++; + } + } + + List result = new ArrayList<>(resultSize); + for (Node side : sides) { + if (side != null) { + result.add(side); + } + } + return result; + } + + /** + * 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 + * assignment in the chain + * @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 {@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 isCheckedCandidate(expr) && written.mayChange(expr, true); + } + + /** + * 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 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 locations written up to the + * outermost enclosing expression, or up to an enclosing lambda or switch expression. + * + *

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 + * comparison that contains it completes + */ + private WrittenLocations locationsWrittenUntilComparison(Node node) { + WrittenLocations result = new WrittenLocations(); + TreePath path = sourcePath(node); + if (path == null) { + // `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); + 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(); + // 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 result; + } + + /** + * 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 + * 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 + */ + private @Nullable TreePath sourcePath(Node node) { + Tree tree = node.getTree(); + if (tree != null) { + TreePath path = analysis.atypeFactory.getPath(tree); + if (path != null) { + 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) { + return path; + } + } + 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, + * the receiver and then the arguments of a method call. + * + * @param tree a tree + * @return the direct subtrees of {@code tree} + */ + 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. 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, 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 + * 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 AnnotatedTypeFactory#isSideEffectFree}). + */ + private final class WrittenLocations 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 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 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. + * + * @param target a location that is written + */ + 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 { + // `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; + } + } + + /** + * 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, 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 + */ + 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()); + } 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; + } + } + + /** + * 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); + } + } + } + + /** + * 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.getTypeFactory().isSideEffectFree(method)) { + anyHeapLocation = true; + } + } + + /** + * 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); + } + } + + /** + * 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; + } + } + } + + @Override + public Void scan(@Nullable Tree tree, Void p) { + if (tree != null) { + addOwnWrites(tree); + } + return super.scan(tree, p); + } + + @Override + public Void visitAnnotation(AnnotationTree tree, Void p) { + return null; + } + + @Override + public Void visitLambdaExpression(LambdaExpressionTree tree, Void p) { + return null; + } + + @Override + public Void visitClass(ClassTree tree, Void p) { + return null; + } + + /** + * 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 + * 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}). + * + * @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 + * matter + * @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 (!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. 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; + } + 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)) || valueMayChange(fa.getReceiver(), false); + } else if (expr instanceof ArrayAccess aa) { + return (!ignoreOwnLocation && mayWriteArrayElement(aa)) + || valueMayChange(aa.getArray(), false) + || valueMayChange(aa.getIndex(), false); + } else if (expr instanceof MethodCall mc) { + if (mc.getElement().equals(stringLength)) { + return valueMayChange(mc.getReceiver(), false); + } + if (mayWriteHeap() || valueMayChange(mc.getReceiver(), false)) { + return true; + } + for (JavaExpression arg : mc.getArguments()) { + if (valueMayChange(arg, false)) { + return true; + } + } + return false; + } else if (expr instanceof UnaryOperation uo) { + return valueMayChange(uo.getOperand(), false); + } else if (expr instanceof BinaryOperation bo) { + 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 + || expr instanceof FormalParameter + || expr instanceof SuperReference + || expr instanceof ThisReference + || expr instanceof ValueLiteral); + } + } + + /** + * 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 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. + * + * @param fa a field access + * @return true if these locations might include the field that {@code fa} denotes + */ + private boolean mayWriteField(FieldAccess fa) { + if (anyHeapLocation && !fa.isFinal()) { + 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()) + && (fa.isStatic() || analysis.canAlias(field.getReceiver(), fa.getReceiver()))) { + return true; + } + } + return false; + } + + /** + * Returns true if these locations might include the array element that {@code aa} denotes. + * + * @param aa an array access + * @return true if these locations might include the array element that {@code aa} denotes + */ + 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 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 new file mode 100644 index 000000000000..46618b0a184f --- /dev/null +++ b/framework/tests/value/AssignmentInComparison.java @@ -0,0 +1,82 @@ +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. +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 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. + 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]]; + } + } + + 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) { + int @ArrayLen(2) [] x = b; + } + } +} diff --git a/javacutil/src/main/java/org/checkerframework/javacutil/TypesUtils.java b/javacutil/src/main/java/org/checkerframework/javacutil/TypesUtils.java index a314192daeb3..d9665a1c236e 100644 --- a/javacutil/src/main/java/org/checkerframework/javacutil/TypesUtils.java +++ b/javacutil/src/main/java/org/checkerframework/javacutil/TypesUtils.java @@ -990,6 +990,179 @@ 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}. + * + *

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 + * @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); + } + + // 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) { + 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. 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. + * + * @param type a type + * @param types the type utilities + * @return the erased bounds of {@code type} + */ + private static List erasedBounds(TypeMirror type, Types types) { + 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) type).getBounds()) { + result.addAll(erasedBounds(bound, types)); + } + return result; + } + case UNION -> { + List result = new ArrayList<>(); + for (TypeMirror alternative : ((UnionType) type).getAlternatives()) { + result.addAll(erasedBounds(alternative, types)); + } + return result; + } + case ARRAY -> { + List componentBounds = + erasedBounds(((ArrayType) type).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(type)); + } + } + } + + /** + * 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} + */ + private static boolean hasOneErasedBound(TypeMirror type) { + 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; + } + } + } + } + /** * 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..b21b91e245e1 --- /dev/null +++ b/javacutil/src/test/java/org/checkerframework/javacutil/TypesUtilsCanAliasTest.java @@ -0,0 +1,221 @@ +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; +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 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) { + 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 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) { + 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 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")); + } + + /** + * 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 whose extends bound is a type variable can alias a type that is related to any bound + * of the type variable. + */ + @Test + 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() { + 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"))); + } +}