/
DefaultAnnotatedTypeFormatter.java
494 lines (441 loc) · 17.6 KB
/
DefaultAnnotatedTypeFormatter.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
package org.checkerframework.framework.type;
import com.sun.tools.javac.code.Type;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
import javax.lang.model.element.Element;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeVariable;
import org.checkerframework.dataflow.qual.SideEffectFree;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedArrayType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedDeclaredType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedExecutableType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedIntersectionType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedNoType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedNullType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedPrimitiveType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedTypeVariable;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedUnionType;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedWildcardType;
import org.checkerframework.framework.type.visitor.AnnotatedTypeVisitor;
import org.checkerframework.javacutil.AnnotationFormatter;
import org.checkerframework.javacutil.DefaultAnnotationFormatter;
import org.checkerframework.javacutil.TypeAnnotationUtils;
import org.checkerframework.javacutil.TypesUtils;
import org.plumelib.util.WeakIdentityHashMap;
/**
* An AnnotatedTypeFormatter used by default by all AnnotatedTypeFactory (and therefore all
* annotated types).
*
* @see org.checkerframework.framework.type.AnnotatedTypeFormatter
* @see org.checkerframework.framework.type.AnnotatedTypeMirror#toString
*/
public class DefaultAnnotatedTypeFormatter implements AnnotatedTypeFormatter {
/** The formatting visitor. */
protected final FormattingVisitor formattingVisitor;
/**
* Constructs a DefaultAnnotatedTypeFormatter that does not print invisible annotations by
* default.
*/
public DefaultAnnotatedTypeFormatter() {
this(new DefaultAnnotationFormatter(), true, false);
}
/**
* @param printVerboseGenerics for type parameters, their uses, and wildcards, print more
* information
* @param defaultPrintInvisibleAnnos whether or not this AnnotatedTypeFormatter should print
* invisible annotations
*/
public DefaultAnnotatedTypeFormatter(
boolean printVerboseGenerics, boolean defaultPrintInvisibleAnnos) {
this(new DefaultAnnotationFormatter(), printVerboseGenerics, defaultPrintInvisibleAnnos);
}
/**
* @param formatter an object that converts annotation mirrors to strings
* @param printVerboseGenerics for type parameters, their uses, and wildcards, print more
* information
* @param defaultPrintInvisibleAnnos whether or not this AnnotatedTypeFormatter should print
* invisible annotations
*/
public DefaultAnnotatedTypeFormatter(
AnnotationFormatter formatter,
boolean printVerboseGenerics,
boolean defaultPrintInvisibleAnnos) {
this(new FormattingVisitor(formatter, printVerboseGenerics, defaultPrintInvisibleAnnos));
}
/**
* Used by subclasses and other constructors to specify the underlying implementation of this
* DefaultAnnotatedTypeFormatter.
*/
protected DefaultAnnotatedTypeFormatter(FormattingVisitor visitor) {
this.formattingVisitor = visitor;
}
/**
* Maps from type variables to deterministic IDs. This is useful for comparing output across two
* runs of the Checker Framework.
*
* <p>This map is necessary for deterministic and informative output. javac might print two
* distinct capture-converted variables as "capture#222" if the second is created after the first
* is garbage-collected, or if they just happen to have the same hash code based on memory layout.
* Such javac output is misleading because it looks like the two printed representations refer to
* the same variable.
*
* <p>This map contains type variables that have been formatted. Therefore, the numbers may differ
* between Checker Framework runs if the different runs print different values (say, one of them
* prints more type variables than the other).
*/
protected static final Map<TypeVariable, Integer> captureConversionIds =
new WeakIdentityHashMap<>();
/** The last deterministic capture conversion ID that was used. */
protected static int prevCaptureConversionId = 0;
/**
* Returns a deterministic capture conversion ID for the given javac captured type.
*
* @param capturedType a type variable, which must be a capture-converted type variable
* @return a deterministic capture conversion ID
*/
static int getCaptureConversionId(TypeVariable capturedType) {
return captureConversionIds.computeIfAbsent(capturedType, key -> ++prevCaptureConversionId);
}
@Override
public String format(AnnotatedTypeMirror type) {
formattingVisitor.resetPrintVerboseSettings();
return formattingVisitor.visit(type);
}
@Override
public String format(AnnotatedTypeMirror type, boolean printVerbose) {
formattingVisitor.setVerboseSettings(printVerbose);
return formattingVisitor.visit(type);
}
/** A scanning visitor that prints the entire AnnotatedTypeMirror passed to visit. */
protected static class FormattingVisitor
implements AnnotatedTypeVisitor<String, Set<AnnotatedTypeMirror>> {
/** The object responsible for converting annotations to strings. */
protected final AnnotationFormatter annoFormatter;
/**
* Represents whether or not invisible annotations should be printed if the client of this class
* does not use the printInvisibleAnnos parameter.
*/
protected final boolean defaultInvisiblesSetting;
/**
* For a given call to format, this setting specifies whether or not to printInvisibles. If a
* user did not specify a printInvisible parameter in the call to format then this value will
* equal DefaultAnnotatedTypeFormatter.defaultInvisibleSettings for this object
*/
protected boolean currentPrintInvisibleSetting;
/** Default value of currentPrintVerboseGenerics. */
protected final boolean defaultPrintVerboseGenerics;
/**
* Prints type variables in a less ambiguous manner using [] to delimit them. Always prints both
* bounds even if they lower bound is an AnnotatedNull type.
*/
protected boolean currentPrintVerboseGenerics;
/** Whether the visitor is currently printing a raw type. */
protected boolean currentlyPrintingRaw;
/**
* Creates the visitor.
*
* @param annoFormatter formatter used for {@code AnnotationMirror}s
* @param printVerboseGenerics whether to verbosely print type variables and wildcards
* @param defaultInvisiblesSetting whether to print invisible qualifiers
*/
public FormattingVisitor(
AnnotationFormatter annoFormatter,
boolean printVerboseGenerics,
boolean defaultInvisiblesSetting) {
this.annoFormatter = annoFormatter;
this.defaultPrintVerboseGenerics = printVerboseGenerics;
this.currentPrintVerboseGenerics = printVerboseGenerics;
this.defaultInvisiblesSetting = defaultInvisiblesSetting;
this.currentPrintInvisibleSetting = false;
this.currentlyPrintingRaw = false;
}
/** Set the current verbose settings to use while printing. */
protected void setVerboseSettings(boolean printVerbose) {
this.currentPrintInvisibleSetting = printVerbose;
this.currentPrintVerboseGenerics = printVerbose;
}
/** Set verbose settings to the default. */
protected void resetPrintVerboseSettings() {
this.currentPrintInvisibleSetting = defaultInvisiblesSetting;
this.currentPrintVerboseGenerics = defaultPrintVerboseGenerics;
}
/**
* Print, to sb, {@code keyWord} followed by {@code field}. NULL types are substituted with
* their annotations followed by " Void"
*/
@SideEffectFree
protected void printBound(
String keyWord,
AnnotatedTypeMirror field,
Set<AnnotatedTypeMirror> visiting,
StringBuilder sb) {
if (!currentPrintVerboseGenerics && (field == null || field.getKind() == TypeKind.NULL)) {
return;
}
sb.append(" ");
sb.append(keyWord);
sb.append(" ");
if (field == null) {
sb.append("<null>");
} else if (field.getKind() != TypeKind.NULL) {
sb.append(visit(field, visiting));
} else {
sb.append(
annoFormatter.formatAnnotationString(
field.getPrimaryAnnotations(), currentPrintInvisibleSetting));
sb.append("Void");
}
}
@SideEffectFree
@Override
public String visit(AnnotatedTypeMirror type) {
return type.accept(this, Collections.newSetFromMap(new IdentityHashMap<>()));
}
@Override
public String visit(AnnotatedTypeMirror type, Set<AnnotatedTypeMirror> annotatedTypeVariables) {
return type.accept(this, annotatedTypeVariables);
}
@Override
public String visitDeclared(AnnotatedDeclaredType type, Set<AnnotatedTypeMirror> visiting) {
StringBuilder sb = new StringBuilder();
if (type.isDeclaration() && currentPrintInvisibleSetting) {
sb.append("/*DECL*/ ");
}
if (type.getEnclosingType() != null) {
sb.append(this.visit(type.getEnclosingType(), visiting));
sb.append('.');
}
Element typeElt = type.getUnderlyingType().asElement();
String smpl = typeElt.getSimpleName().toString();
if (smpl.isEmpty()) {
// For anonymous classes smpl is empty - toString
// of the element is more useful.
smpl = typeElt.toString();
}
sb.append(
annoFormatter.formatAnnotationString(
type.getPrimaryAnnotations(), currentPrintInvisibleSetting));
sb.append(smpl);
boolean oldPrintingRaw = currentlyPrintingRaw;
if (type.isUnderlyingTypeRaw()) {
currentlyPrintingRaw = true;
}
if (type.typeArgs != null) {
// getTypeArguments sets the field if it does not already exist.
List<AnnotatedTypeMirror> typeArgs = type.typeArgs;
if (!typeArgs.isEmpty()) {
StringJoiner sj = new StringJoiner(", ", "<", ">");
if (!currentPrintVerboseGenerics && currentlyPrintingRaw) {
sj.add("/*RAW*/");
} else {
for (AnnotatedTypeMirror typeArg : typeArgs) {
sj.add(visit(typeArg, visiting));
}
}
sb.append(sj);
}
}
currentlyPrintingRaw = oldPrintingRaw;
return sb.toString();
}
@Override
public String visitIntersection(
AnnotatedIntersectionType type, Set<AnnotatedTypeMirror> visiting) {
StringBuilder sb = new StringBuilder();
boolean isFirst = true;
for (AnnotatedTypeMirror bound : type.getBounds()) {
if (!isFirst) {
sb.append(" & ");
}
sb.append(visit(bound, visiting));
isFirst = false;
}
return sb.toString();
}
@Override
public String visitUnion(AnnotatedUnionType type, Set<AnnotatedTypeMirror> visiting) {
StringBuilder sb = new StringBuilder();
boolean isFirst = true;
for (AnnotatedDeclaredType adt : type.getAlternatives()) {
if (!isFirst) {
sb.append(" | ");
}
sb.append(visit(adt, visiting));
isFirst = false;
}
return sb.toString();
}
@Override
public String visitExecutable(AnnotatedExecutableType type, Set<AnnotatedTypeMirror> visiting) {
StringBuilder sb = new StringBuilder();
if (!type.getTypeVariables().isEmpty()) {
StringJoiner sj = new StringJoiner(", ", "<", "> ");
for (AnnotatedTypeVariable atv : type.getTypeVariables()) {
sj.add(visit(atv, visiting));
}
sb.append(sj.toString());
}
if (type.getReturnType() != null) {
sb.append(visit(type.getReturnType(), visiting));
} else {
sb.append("<UNKNOWNRETURN>");
}
sb.append(' ');
if (type.getElement() != null) {
sb.append(type.getElement().getSimpleName());
} else {
sb.append("METHOD");
}
sb.append('(');
AnnotatedDeclaredType rcv;
try {
rcv = type.getReceiverType();
} catch (NullPointerException e) {
sb.append("[[NPE in getReceiverType()]], ");
rcv = null;
}
if (rcv != null) {
sb.append(visit(rcv, visiting));
sb.append(" this");
}
if (!type.getParameterTypes().isEmpty()) {
int p = 0;
for (AnnotatedTypeMirror atm : type.getParameterTypes()) {
if (rcv != null || p > 0) {
sb.append(", ");
}
sb.append(visit(atm, visiting));
// Output some parameter names to make it look more like a method.
// TODO: go to the element and look up real parameter names, maybe.
sb.append(" p");
sb.append(p++);
}
}
sb.append(')');
if (!type.getThrownTypes().isEmpty()) {
sb.append(" throws ");
for (AnnotatedTypeMirror atm : type.getThrownTypes()) {
sb.append(visit(atm, visiting));
}
}
return sb.toString();
}
@Override
public String visitArray(AnnotatedArrayType type, Set<AnnotatedTypeMirror> visiting) {
StringBuilder sb = new StringBuilder();
AnnotatedArrayType array = type;
AnnotatedTypeMirror component;
while (true) {
component = array.getComponentType();
if (!array.getPrimaryAnnotations().isEmpty()) {
sb.append(' ');
sb.append(
annoFormatter.formatAnnotationString(
array.getPrimaryAnnotations(), currentPrintInvisibleSetting));
}
sb.append("[]");
if (!(component instanceof AnnotatedArrayType)) {
sb.insert(0, visit(component, visiting));
break;
}
array = (AnnotatedArrayType) component;
}
return sb.toString();
}
@Override
public String visitTypeVariable(AnnotatedTypeVariable type, Set<AnnotatedTypeMirror> visiting) {
StringBuilder sb = new StringBuilder();
if (TypesUtils.isCapturedTypeVariable(type.underlyingType)) {
// underlyingType.toString() has this form: "capture#826 of ? extends java.lang.Object".
// assert underlyingType.toString().startsWith("capture#");
// We output only the "capture#826" part.
// TODO: If deterministic output is not needed, we could avoid the use of
// getCaptureConversionId() by using this code instead:
// sb.append(underlyingType, 0, underlyingType.indexOf(" of "));
// The choice would be controlled by a command-line argument.
// We output a deterministic number; we prefix it by "0"
// so we know whether a number is deterministic or from javac.
sb.append("capture#0").append(getCaptureConversionId((TypeVariable) type.underlyingType));
} else {
sb.append(type.underlyingType);
}
if (!visiting.contains(type)) {
if (type.isDeclaration() && currentPrintInvisibleSetting) {
sb.append("/*DECL*/ ");
}
try {
visiting.add(type);
if (currentPrintVerboseGenerics) {
sb.append("[");
}
printBound("extends", type.getUpperBoundField(), visiting, sb);
printBound("super", type.getLowerBoundField(), visiting, sb);
if (currentPrintVerboseGenerics) {
sb.append("]");
}
} finally {
visiting.remove(type);
}
}
return sb.toString();
}
@SideEffectFree
@Override
public String visitPrimitive(AnnotatedPrimitiveType type, Set<AnnotatedTypeMirror> visiting) {
return formatFlatType(type);
}
@SideEffectFree
@Override
public String visitNoType(AnnotatedNoType type, Set<AnnotatedTypeMirror> visiting) {
return formatFlatType(type);
}
@SideEffectFree
@Override
public String visitNull(AnnotatedNullType type, Set<AnnotatedTypeMirror> visiting) {
return annoFormatter.formatAnnotationString(
type.getPrimaryAnnotations(), currentPrintInvisibleSetting)
+ "NullType";
}
@Override
public String visitWildcard(AnnotatedWildcardType type, Set<AnnotatedTypeMirror> visiting) {
StringBuilder sb = new StringBuilder();
if (type.isUninferredTypeArgument()) {
if (currentlyPrintingRaw) {
sb.append("/*RAW TYPE ARGUMENT:*/ ");
} else {
sb.append("/*INFERENCE FAILED for:*/ ");
}
}
sb.append(
annoFormatter.formatAnnotationString(
type.getPrimaryAnnotationsField(), currentPrintInvisibleSetting));
sb.append("?");
if (!visiting.contains(type)) {
try {
visiting.add(type);
if (currentPrintVerboseGenerics) {
sb.append("[");
}
printBound("extends", type.getExtendsBoundField(), visiting, sb);
printBound("super", type.getSuperBoundField(), visiting, sb);
if (currentPrintVerboseGenerics) {
sb.append("]");
}
} finally {
visiting.remove(type);
}
}
return sb.toString();
}
@SideEffectFree
protected String formatFlatType(AnnotatedTypeMirror flatType) {
return annoFormatter.formatAnnotationString(
flatType.getPrimaryAnnotations(), currentPrintInvisibleSetting)
+ TypeAnnotationUtils.unannotatedType((Type) flatType.getUnderlyingType());
}
}
}