forked from typetools/checker-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ValueVisitor.java
357 lines (328 loc) · 16.3 KB
/
ValueVisitor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
package org.checkerframework.common.value;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.TypeCastTree;
import java.util.Collections;
import java.util.List;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import org.checkerframework.checker.compilermsgs.qual.CompilerMessageKey;
import org.checkerframework.common.basetype.BaseTypeChecker;
import org.checkerframework.common.basetype.BaseTypeVisitor;
import org.checkerframework.common.value.qual.IntRangeFromGTENegativeOne;
import org.checkerframework.common.value.qual.IntRangeFromNonNegative;
import org.checkerframework.common.value.qual.IntRangeFromPositive;
import org.checkerframework.common.value.util.NumberUtils;
import org.checkerframework.common.value.util.Range;
import org.checkerframework.framework.type.AnnotatedTypeMirror;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType;
import org.checkerframework.framework.type.visitor.AnnotatedTypeScanner;
import org.checkerframework.javacutil.AnnotationUtils;
import org.checkerframework.javacutil.TreeUtils;
import org.checkerframework.javacutil.TypesUtils;
/** Visitor for the Constant Value type system. */
public class ValueVisitor extends BaseTypeVisitor<ValueAnnotatedTypeFactory> {
public ValueVisitor(BaseTypeChecker checker) {
super(checker);
}
/**
* ValueVisitor overrides this method so that it does not have to check variables annotated with
* the {@link IntRangeFromPositive} annotation, the {@link IntRangeFromNonNegative} annotation,
* or the {@link IntRangeFromGTENegativeOne} annotation. This annotation is only introduced by
* the Index Checker's lower bound annotations. It is safe to defer checking of these values to
* the Index Checker because this is only introduced for explicitly-written {@code
* org.checkerframework.checker.index.qual.Positive}, explicitly-written {@code
* org.checkerframework.checker.index.qual.NonNegative}, and explicitly-written {@code
* org.checkerframework.checker.index.qual.GTENegativeOne} annotations, which must be checked by
* the Lower Bound Checker.
*
* @param varType the annotated type of the lvalue (usually a variable)
* @param valueExp the AST node for the rvalue (the new value)
* @param errorKey the error message key to use if the check fails
* @param extraArgs arguments to the error message key, before "found" and "expected" types
*/
@Override
protected void commonAssignmentCheck(
AnnotatedTypeMirror varType,
ExpressionTree valueExp,
@CompilerMessageKey String errorKey,
Object... extraArgs) {
replaceSpecialIntRangeAnnotations(varType);
super.commonAssignmentCheck(varType, valueExp, errorKey, extraArgs);
}
@Override
protected void commonAssignmentCheck(
AnnotatedTypeMirror varType,
AnnotatedTypeMirror valueType,
Tree valueTree,
@CompilerMessageKey String errorKey,
Object... extraArgs) {
replaceSpecialIntRangeAnnotations(varType);
if (valueType.getKind() == TypeKind.CHAR
&& valueType.hasAnnotation(getTypeFactory().UNKNOWNVAL)) {
valueType.addAnnotation(
getTypeFactory().createIntRangeAnnotation(Range.CHAR_EVERYTHING));
}
if (valueTree.getKind() == Kind.METHOD_INVOCATION
&& TreeUtils.isArrayscopyOfMethodInvocation((MethodInvocationTree) valueTree)
&& valueType.getKind() == TypeKind.ARRAY) {
List<? extends ExpressionTree> args = ((MethodInvocationTree) valueTree).getArguments();
AnnotatedTypeMirror arrType = atypeFactory.getAnnotatedType(args.get(0));
if (args.size() == 2) {
if (TreeUtils.isArrayLengthAccess(args.get(1))) {
valueType = arrType;
}
}
}
super.commonAssignmentCheck(varType, valueType, valueTree, errorKey, extraArgs);
}
/**
* Return types for methods that are annotated with {@code @IntRangeFromX} annotations need to
* be replaced with {@code @UnknownVal}. See the documentation on {@link
* #commonAssignmentCheck(AnnotatedTypeMirror, ExpressionTree, String, Object[])
* commonAssignmentCheck}.
*
* <p>A separate override is necessary because checkOverride doesn't actually use the
* commonAssignmentCheck.
*/
@Override
protected boolean checkOverride(
MethodTree overriderTree,
AnnotatedTypeMirror.AnnotatedExecutableType overrider,
AnnotatedTypeMirror.AnnotatedDeclaredType overridingType,
AnnotatedTypeMirror.AnnotatedExecutableType overridden,
AnnotatedTypeMirror.AnnotatedDeclaredType overriddenType) {
replaceSpecialIntRangeAnnotations(overrider);
replaceSpecialIntRangeAnnotations(overridden);
return super.checkOverride(
overriderTree, overrider, overridingType, overridden, overriddenType);
}
/**
* Replaces any {@code IntRangeFromX} annotations with {@code @UnknownVal}. This is used to
* prevent these annotations from being required on the left hand side of assignments.
*
* @param varType an annotated type mirror that may contain IntRangeFromX annotations, which
* will be used on the lhs of an assignment or pseudo-assignment
*/
private void replaceSpecialIntRangeAnnotations(AnnotatedTypeMirror varType) {
AnnotatedTypeScanner<Void, Void> replaceSpecialIntRangeAnnotations =
new AnnotatedTypeScanner<Void, Void>() {
@Override
protected Void scan(AnnotatedTypeMirror type, Void p) {
if (type.hasAnnotation(IntRangeFromPositive.class)
|| type.hasAnnotation(IntRangeFromNonNegative.class)
|| type.hasAnnotation(IntRangeFromGTENegativeOne.class)) {
type.replaceAnnotation(atypeFactory.UNKNOWNVAL);
}
return super.scan(type, p);
}
@Override
public Void visitDeclared(AnnotatedDeclaredType type, Void p) {
// Don't call super so that the type arguments are not visited.
if (type.getEnclosingType() != null) {
scan(type.getEnclosingType(), p);
}
return null;
}
};
replaceSpecialIntRangeAnnotations.visit(varType);
}
@Override
protected ValueAnnotatedTypeFactory createTypeFactory() {
return new ValueAnnotatedTypeFactory(checker);
}
/**
* Warns about malformed constant-value annotations.
*
* <p>Issues an error if any @IntRange annotation has its 'from' value greater than 'to' value.
*
* <p>Issues an error if any constant-value annotation has no arguments.
*
* <p>Issues a warning if any constant-value annotation has > MAX_VALUES arguments.
*
* <p>Issues a warning if any @ArrayLen/@ArrayLenRange annotations contain a negative array
* length.
*/
/* Implementation note: the ValueAnnotatedTypeFactory replaces such invalid annotations with valid ones.
* Therefore, the usual validation in #validateType cannot perform this validation.
* These warnings cannot be issued in the ValueAnnotatedTypeFactory, because the conversions
* might happen multiple times.
* On the other hand, not all validations can happen here, because only the annotations are
* available, not the full types.
* Therefore, some validation is still done in #validateType below.
*/
@Override
public Void visitAnnotation(AnnotationTree node, Void p) {
List<? extends ExpressionTree> args = node.getArguments();
if (args.isEmpty()) {
// Nothing to do if there are no annotation arguments.
return super.visitAnnotation(node, p);
}
AnnotationMirror anno = TreeUtils.annotationFromAnnotationTree(node);
switch (AnnotationUtils.annotationName(anno)) {
case ValueAnnotatedTypeFactory.INTRANGE_NAME:
// If there are 2 arguments, issue an error if from.greater.than.to.
// If there are fewer than 2 arguments, we needn't worry about this problem because
// the other argument will be defaulted to Long.MIN_VALUE or Long.MAX_VALUE
// accordingly.
if (args.size() == 2) {
long from = AnnotationUtils.getElementValue(anno, "from", Long.class, true);
long to = AnnotationUtils.getElementValue(anno, "to", Long.class, true);
if (from > to) {
checker.reportError(node, "from.greater.than.to");
return null;
}
}
break;
case ValueAnnotatedTypeFactory.ARRAYLEN_NAME:
case ValueAnnotatedTypeFactory.BOOLVAL_NAME:
case ValueAnnotatedTypeFactory.DOUBLEVAL_NAME:
case ValueAnnotatedTypeFactory.INTVAL_NAME:
case ValueAnnotatedTypeFactory.STRINGVAL_NAME:
List<Object> values =
AnnotationUtils.getElementValueArray(anno, "value", Object.class, true);
if (values.isEmpty()) {
checker.reportWarning(node, "no.values.given");
return null;
} else if (values.size() > ValueAnnotatedTypeFactory.MAX_VALUES) {
checker.reportWarning(
node,
(AnnotationUtils.areSameByName(
anno, ValueAnnotatedTypeFactory.INTVAL_NAME)
? "too.many.values.given.int"
: "too.many.values.given"),
ValueAnnotatedTypeFactory.MAX_VALUES);
return null;
} else if (AnnotationUtils.areSameByName(
anno, ValueAnnotatedTypeFactory.ARRAYLEN_NAME)) {
List<Integer> arrayLens = ValueAnnotatedTypeFactory.getArrayLength(anno);
if (Collections.min(arrayLens) < 0) {
checker.reportWarning(
node, "negative.arraylen", Collections.min(arrayLens));
return null;
}
}
break;
case ValueAnnotatedTypeFactory.ARRAYLENRANGE_NAME:
int from = AnnotationUtils.getElementValue(anno, "from", Integer.class, true);
int to = AnnotationUtils.getElementValue(anno, "to", Integer.class, true);
if (from > to) {
checker.reportError(node, "from.greater.than.to");
return null;
} else if (from < 0) {
checker.reportWarning(node, "negative.arraylen", from);
return null;
}
break;
default:
// Do nothing.
}
return super.visitAnnotation(node, p);
}
@Override
public Void visitTypeCast(TypeCastTree node, Void p) {
if (node.getExpression().getKind() == Kind.NULL_LITERAL) {
return null;
}
AnnotatedTypeMirror castType = atypeFactory.getAnnotatedType(node);
AnnotationMirror castAnno = castType.getAnnotationInHierarchy(atypeFactory.UNKNOWNVAL);
AnnotationMirror exprAnno =
atypeFactory
.getAnnotatedType(node.getExpression())
.getAnnotationInHierarchy(atypeFactory.UNKNOWNVAL);
// It is always legal to cast to an IntRange type that includes all values
// of the underlying type. Do not warn about such casts.
// I.e. do not warn if an @IntRange(...) int is casted
// to a @IntRange(from = Byte.MIN_VALUE, to = Byte.MAX_VALUE byte).
if (castAnno != null
&& exprAnno != null
&& atypeFactory.isIntRange(castAnno)
&& atypeFactory.isIntRange(exprAnno)) {
final Range castRange = ValueAnnotatedTypeFactory.getRange(castAnno);
final TypeKind castTypeKind = castType.getKind();
if (castTypeKind == TypeKind.BYTE && castRange.isByteEverything()) {
return p;
}
if (castTypeKind == TypeKind.CHAR && castRange.isCharEverything()) {
return p;
}
if (castTypeKind == TypeKind.SHORT && castRange.isShortEverything()) {
return p;
}
if (castTypeKind == TypeKind.INT && castRange.isIntEverything()) {
return p;
}
if (castTypeKind == TypeKind.LONG && castRange.isLongEverything()) {
return p;
}
if (Range.ignoreOverflow) {
// Range.ignoreOverflow is only set if this checker is ignoring overflow.
// In that case, do not warn if the range of the expression encompasses
// the whole type being casted to (i.e. the warning is actually about overflow).
Range exprRange = ValueAnnotatedTypeFactory.getRange(exprAnno);
if (castTypeKind == TypeKind.BYTE
|| castTypeKind == TypeKind.CHAR
|| castTypeKind == TypeKind.SHORT
|| castTypeKind == TypeKind.INT) {
exprRange = NumberUtils.castRange(castType.getUnderlyingType(), exprRange);
}
if (castRange.equals(exprRange)) {
return p;
}
}
}
return super.visitTypeCast(node, p);
}
/**
* Overridden to issue errors at the appropriate place if an {@code IntRange} or {@code
* ArrayLenRange} annotation has {@code from > to}. {@code from > to} either indicates a user
* error when writing an annotation or an error in the checker's implementation, as {@code from}
* should always be {@code <= to}. Note that additional checks are performed in {@link
* #visitAnnotation(AnnotationTree, Void)}.
*
* @see #visitAnnotation(AnnotationTree, Void)
*/
@Override
public boolean validateType(Tree tree, AnnotatedTypeMirror type) {
replaceSpecialIntRangeAnnotations(type);
if (!super.validateType(tree, type)) {
return false;
}
AnnotationMirror anno = type.getAnnotationInHierarchy(atypeFactory.UNKNOWNVAL);
if (anno == null) {
return false;
}
if (AnnotationUtils.areSameByName(anno, ValueAnnotatedTypeFactory.INTRANGE_NAME)) {
if (NumberUtils.isIntegral(type.getUnderlyingType())) {
long from = atypeFactory.getFromValueFromIntRange(type);
long to = atypeFactory.getToValueFromIntRange(type);
if (from > to) {
checker.reportError(tree, "from.greater.than.to");
return false;
}
} else {
TypeMirror utype = type.getUnderlyingType();
if (!TypesUtils.isObject(utype)
&& !TypesUtils.isDeclaredOfName(utype, "java.lang.Number")
&& !NumberUtils.isFloatingPoint(utype)) {
checker.reportError(tree, "annotation.intrange.on.noninteger");
return false;
}
}
} else if (AnnotationUtils.areSameByName(
anno, ValueAnnotatedTypeFactory.ARRAYLENRANGE_NAME)) {
int from = AnnotationUtils.getElementValue(anno, "from", Integer.class, true);
int to = AnnotationUtils.getElementValue(anno, "to", Integer.class, true);
if (from > to) {
checker.reportError(tree, "from.greater.than.to");
return false;
}
}
return true;
}
}