forked from typetools/checker-framework
-
Notifications
You must be signed in to change notification settings - Fork 2
/
WholeProgramInferenceJavaParserStorage.java
1430 lines (1290 loc) · 57.1 KB
/
WholeProgramInferenceJavaParserStorage.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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.checkerframework.common.wholeprograminference;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.CallableDeclaration;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.ConstructorDeclaration;
import com.github.javaparser.ast.body.EnumConstantDeclaration;
import com.github.javaparser.ast.body.EnumDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.Parameter;
import com.github.javaparser.ast.body.ReceiverParameter;
import com.github.javaparser.ast.body.RecordDeclaration;
import com.github.javaparser.ast.body.TypeDeclaration;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.MarkerAnnotationExpr;
import com.github.javaparser.ast.expr.NormalAnnotationExpr;
import com.github.javaparser.ast.expr.ObjectCreationExpr;
import com.github.javaparser.ast.expr.SingleMemberAnnotationExpr;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.type.Type;
import com.github.javaparser.ast.type.TypeParameter;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.printer.DefaultPrettyPrinter;
import com.github.javaparser.printer.DefaultPrettyPrinterVisitor;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.checker.signature.qual.BinaryName;
import org.checkerframework.common.basetype.BaseTypeChecker;
import org.checkerframework.common.wholeprograminference.WholeProgramInference.OutputFormat;
import org.checkerframework.dataflow.analysis.Analysis;
import org.checkerframework.framework.ajava.AnnotationMirrorToAnnotationExprConversion;
import org.checkerframework.framework.ajava.AnnotationTransferVisitor;
import org.checkerframework.framework.ajava.DefaultJointVisitor;
import org.checkerframework.framework.ajava.JointJavacJavaParserVisitor;
import org.checkerframework.framework.qual.InvisibleQualifier;
import org.checkerframework.framework.qual.TypeUseLocation;
import org.checkerframework.framework.type.AnnotatedTypeFactory;
import org.checkerframework.framework.type.AnnotatedTypeMirror;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedArrayType;
import org.checkerframework.framework.type.GenericAnnotatedTypeFactory;
import org.checkerframework.framework.util.JavaParserUtil;
import org.checkerframework.javacutil.AnnotationUtils;
import org.checkerframework.javacutil.BugInCF;
import org.checkerframework.javacutil.ElementUtils;
import org.checkerframework.javacutil.Pair;
import org.checkerframework.javacutil.TreeUtils;
import scenelib.annotations.util.JVMNames;
/**
* This is an implementation of {@link WholeProgramInferenceStorage} that stores annotations
* directly with the JavaParser node corresponding to the annotation's location. It outputs ajava
* files.
*/
public class WholeProgramInferenceJavaParserStorage
implements WholeProgramInferenceStorage<AnnotatedTypeMirror> {
/**
* Directory where .ajava files will be written to and read from. This directory is relative to
* where the javac command is executed.
*/
public static final String AJAVA_FILES_PATH =
"build" + File.separator + "whole-program-inference" + File.separator;
/** The type factory associated with this. */
protected final AnnotatedTypeFactory atypeFactory;
/**
* Maps from binary class name to the wrapper containing the class. Contains all classes in Java
* source files containing an Element for which an annotation has been inferred.
*/
private Map<@BinaryName String, ClassOrInterfaceAnnos> classToAnnos = new HashMap<>();
/**
* Files containing classes for which an annotation has been inferred since the last time files
* were written to disk.
*/
private Set<String> modifiedFiles = new HashSet<>();
/** Mapping from source file to the wrapper for the compilation unit parsed from that file. */
private Map<String, CompilationUnitAnnos> sourceToAnnos = new HashMap<>();
/** Whether the {@code -AinferOutputOriginal} option was supplied to the checker. */
private final boolean inferOutputOriginal;
/**
* Returns the names of all qualifiers that are marked with {@link InvisibleQualifier}, and that
* are supported by the given type factory.
*
* @param atypeFactory a type factory
* @return the names of every invisible qualifier supported by {@code atypeFactory}
*/
public static Set<String> getInvisibleQualifierNames(AnnotatedTypeFactory atypeFactory) {
return atypeFactory.getSupportedTypeQualifiers().stream()
.filter(WholeProgramInferenceJavaParserStorage::isInvisible)
.map(Class::getCanonicalName)
.collect(Collectors.toSet());
}
/**
* Is the definition of the given annotation class annotated with {@link InvisibleQualifier}?
*
* @param qual an annotation class
* @return true iff {@code qual} is meta-annotated with {@link InvisibleQualifier}
*/
public static boolean isInvisible(Class<? extends Annotation> qual) {
return Arrays.stream(qual.getAnnotations())
.anyMatch(anno -> anno.annotationType() == InvisibleQualifier.class);
}
/**
* Constructs a new {@code WholeProgramInferenceJavaParser} that has not yet inferred any
* annotations.
*
* @param atypeFactory the associated type factory
* @param inferOutputOriginal whether the -AinferOutputOriginal option was supplied to the checker
*/
public WholeProgramInferenceJavaParserStorage(
AnnotatedTypeFactory atypeFactory, boolean inferOutputOriginal) {
this.atypeFactory = atypeFactory;
this.inferOutputOriginal = inferOutputOriginal;
}
@Override
public String getFileForElement(Element elt) {
return addClassesForElement(elt);
}
@Override
public void setFileModified(String path) {
modifiedFiles.add(path);
}
///
/// Reading stored annotations
///
@Override
public boolean hasStorageLocationForMethod(ExecutableElement methodElt) {
return getMethodAnnos(methodElt) != null;
}
/**
* Get the annotations for a method or constructor.
*
* @param methodElt the method or constructor
* @return the annotations for a method or constructor
*/
private @Nullable CallableDeclarationAnnos getMethodAnnos(ExecutableElement methodElt) {
String className = ElementUtils.getEnclosingClassName(methodElt);
// Read in classes for the element.
getFileForElement(methodElt);
ClassOrInterfaceAnnos classAnnos = classToAnnos.get(className);
if (classAnnos == null) {
return null;
}
CallableDeclarationAnnos methodAnnos =
classAnnos.callableDeclarations.get(JVMNames.getJVMMethodSignature(methodElt));
return methodAnnos;
}
/**
* Get the annotations for a field.
*
* @param fieldElt a field
* @return the annotations for a field
*/
private FieldAnnos getFieldAnnos(Element fieldElt) {
String className = ElementUtils.getEnclosingClassName((VariableElement) fieldElt);
// Read in classes for the element.
getFileForElement(fieldElt);
ClassOrInterfaceAnnos classAnnos = classToAnnos.get(className);
FieldAnnos fieldAnnos = classAnnos.fields.get(fieldElt.getSimpleName().toString());
return fieldAnnos;
}
@Override
public AnnotatedTypeMirror getParameterAnnotations(
ExecutableElement methodElt,
int i,
AnnotatedTypeMirror paramATM,
VariableElement ve,
AnnotatedTypeFactory atypeFactory) {
CallableDeclarationAnnos methodAnnos = getMethodAnnos(methodElt);
if (methodAnnos == null) {
// When processing anonymous inner classes outside their compilation units,
// it might not have been possible to create an appropriate CallableDeclarationAnnos:
// no element would have been available, causing the computed method signature to
// be incorrect. In this case, abort looking up annotations -- inference will fail,
// because even if WPI inferred something, it couldn't be printed.
return paramATM;
}
return methodAnnos.getParameterTypeInitialized(paramATM, i, atypeFactory);
}
@Override
public AnnotatedTypeMirror getReceiverAnnotations(
ExecutableElement methodElt,
AnnotatedTypeMirror paramATM,
AnnotatedTypeFactory atypeFactory) {
CallableDeclarationAnnos methodAnnos = getMethodAnnos(methodElt);
if (methodAnnos == null) {
// See the comment on the similar exception in #getParameterAnnotations, above.
return paramATM;
}
return methodAnnos.getReceiverType(paramATM, atypeFactory);
}
@Override
public AnnotatedTypeMirror getReturnAnnotations(
ExecutableElement methodElt, AnnotatedTypeMirror atm, AnnotatedTypeFactory atypeFactory) {
CallableDeclarationAnnos methodAnnos = getMethodAnnos(methodElt);
if (methodAnnos == null) {
// See the comment on the similar exception in #getParameterAnnotations, above.
return atm;
}
return methodAnnos.getReturnType(atm, atypeFactory);
}
@Override
public @Nullable AnnotatedTypeMirror getFieldAnnotations(
Element element,
String fieldName,
AnnotatedTypeMirror lhsATM,
AnnotatedTypeFactory atypeFactory) {
ClassSymbol enclosingClass = ((VarSymbol) element).enclClass();
// Read in classes for the element.
getFileForElement(element);
@SuppressWarnings("signature") // https://tinyurl.com/cfissue/3094
@BinaryName String className = enclosingClass.flatname.toString();
ClassOrInterfaceAnnos classAnnos = classToAnnos.get(className);
// If it's an enum constant it won't appear as a field
// and it won't have extra annotations, so just return the basic type:
if (classAnnos.enumConstants.contains(fieldName)) {
return lhsATM;
} else if (classAnnos.fields.get(fieldName) == null) {
// There might not be a corresponding entry for the field name
// in an anonymous class, if the field and class were defined in
// another compilation unit (for the same reason that a method
// might not have an entry, as in #getParameterAnnotations, above).
return null;
} else {
return classAnnos.fields.get(fieldName).getType(lhsATM, atypeFactory);
}
}
@Override
public AnnotatedTypeMirror getPreOrPostconditions(
Analysis.BeforeOrAfter preOrPost,
ExecutableElement methodElement,
String expression,
AnnotatedTypeMirror declaredType,
AnnotatedTypeFactory atypeFactory) {
switch (preOrPost) {
case BEFORE:
return getPreconditionsForExpression(methodElement, expression, declaredType, atypeFactory);
case AFTER:
return getPostconditionsForExpression(
methodElement, expression, declaredType, atypeFactory);
default:
throw new BugInCF("Unexpected " + preOrPost);
}
}
/**
* Returns the precondition annotations for the given expression.
*
* @param methodElement the method
* @param expression the expression
* @param declaredType the declared type of the expression
* @param atypeFactory the type factory
* @return the precondition annotations for a field
*/
private AnnotatedTypeMirror getPreconditionsForExpression(
ExecutableElement methodElement,
String expression,
AnnotatedTypeMirror declaredType,
AnnotatedTypeFactory atypeFactory) {
CallableDeclarationAnnos methodAnnos = getMethodAnnos(methodElement);
if (methodAnnos == null) {
// See the comment on the similar exception in #getParameterAnnotations, above.
return declaredType;
}
return methodAnnos.getPreconditionsForExpression(expression, declaredType, atypeFactory);
}
/**
* Returns the postcondition annotations for an expression.
*
* @param methodElement the method
* @param expression the expression
* @param declaredType the declared type of the expression
* @param atypeFactory the type factory
* @return the postcondition annotations for a field
*/
private AnnotatedTypeMirror getPostconditionsForExpression(
ExecutableElement methodElement,
String expression,
AnnotatedTypeMirror declaredType,
AnnotatedTypeFactory atypeFactory) {
CallableDeclarationAnnos methodAnnos = getMethodAnnos(methodElement);
if (methodAnnos == null) {
// See the comment on the similar exception in #getParameterAnnotations, above.
return declaredType;
}
return methodAnnos.getPostconditionsForExpression(expression, declaredType, atypeFactory);
}
@Override
public boolean addMethodDeclarationAnnotation(
ExecutableElement methodElt, AnnotationMirror anno) {
CallableDeclarationAnnos methodAnnos = getMethodAnnos(methodElt);
if (methodAnnos == null) {
// See the comment on the similar exception in #getParameterAnnotations, above.
return false;
}
boolean isNewAnnotation = methodAnnos.addDeclarationAnnotation(anno);
if (isNewAnnotation) {
modifiedFiles.add(getFileForElement(methodElt));
}
return isNewAnnotation;
}
@Override
public boolean addFieldDeclarationAnnotation(Element field, AnnotationMirror anno) {
FieldAnnos fieldAnnos = getFieldAnnos(field);
boolean isNewAnnotation = fieldAnnos.addDeclarationAnnotation(anno);
if (isNewAnnotation) {
modifiedFiles.add(getFileForElement(field));
}
return isNewAnnotation;
}
@Override
public AnnotatedTypeMirror atmFromStorageLocation(
TypeMirror typeMirror, AnnotatedTypeMirror storageLocation) {
return storageLocation;
}
@Override
public void updateStorageLocationFromAtm(
AnnotatedTypeMirror newATM,
AnnotatedTypeMirror curATM,
AnnotatedTypeMirror typeToUpdate,
TypeUseLocation defLoc,
boolean ignoreIfAnnotated) {
// Clears only the annotations that are supported by atypeFactory.
// The others stay intact.
Set<AnnotationMirror> annosToRemove = AnnotationUtils.createAnnotationSet();
for (AnnotationMirror anno : typeToUpdate.getAnnotations()) {
if (atypeFactory.isSupportedQualifier(anno)) {
annosToRemove.add(anno);
}
}
// This method may be called consecutive times to modify the same AnnotatedTypeMirror.
// Each time it is called, the AnnotatedTypeMirror has a better type
// estimate for the modified AnnotatedTypeMirror. Therefore, it is not a problem to remove
// all annotations before inserting the new annotations.
typeToUpdate.removeAnnotations(annosToRemove);
// Only update the AnnotatedTypeMirror if there are no explicit annotations
if (curATM.getExplicitAnnotations().isEmpty() || !ignoreIfAnnotated) {
for (AnnotationMirror am : newATM.getAnnotations()) {
typeToUpdate.addAnnotation(am);
}
} else if (curATM.getKind() == TypeKind.TYPEVAR) {
// getExplicitAnnotations will be non-empty for type vars whose bounds are explicitly
// annotated. So instead, only insert the annotation if there is not primary annotation
// of the same hierarchy.
for (AnnotationMirror am : newATM.getAnnotations()) {
if (curATM.getAnnotationInHierarchy(am) != null) {
// Don't insert if the type is already has a primary annotation
// in the same hierarchy.
break;
}
typeToUpdate.addAnnotation(am);
}
}
if (newATM.getKind() == TypeKind.ARRAY) {
AnnotatedArrayType newAAT = (AnnotatedArrayType) newATM;
AnnotatedArrayType oldAAT = (AnnotatedArrayType) curATM;
AnnotatedArrayType aatToUpdate = (AnnotatedArrayType) typeToUpdate;
updateStorageLocationFromAtm(
newAAT.getComponentType(),
oldAAT.getComponentType(),
aatToUpdate.getComponentType(),
defLoc,
ignoreIfAnnotated);
}
}
///
/// Reading in files
///
@Override
public void preprocessClassTree(ClassTree classTree) {
addClassTree(classTree);
}
/**
* Reads in the source file containing {@code tree} and creates wrappers around all classes in the
* file. Stores the wrapper for the compilation unit in {@link #sourceToAnnos} and stores the
* wrappers of all classes in the file in {@link #classToAnnos}.
*
* @param tree tree for class to add
*/
private void addClassTree(ClassTree tree) {
TypeElement element = TreeUtils.elementFromDeclaration(tree);
String className = ElementUtils.getBinaryName(element);
if (classToAnnos.containsKey(className)) {
return;
}
TypeElement toplevelClass = ElementUtils.toplevelEnclosingTypeElement(element);
String path = ElementUtils.getSourceFilePath(toplevelClass);
addSourceFile(path);
CompilationUnitAnnos sourceAnnos = sourceToAnnos.get(path);
TypeDeclaration<?> javaParserNode =
sourceAnnos.getClassOrInterfaceDeclarationByName(toplevelClass.getSimpleName().toString());
ClassTree toplevelClassTree = atypeFactory.getTreeUtils().getTree(toplevelClass);
createWrappersForClass(toplevelClassTree, javaParserNode, sourceAnnos);
}
/**
* Reads in the file at {@code path} and creates a wrapper around its compilation unit. Stores the
* wrapper in {@link #sourceToAnnos}, but doesn't create wrappers around any classes in the file.
*
* @param path path to source file to read
*/
private void addSourceFile(String path) {
if (sourceToAnnos.containsKey(path)) {
return;
}
CompilationUnit root;
try {
root = JavaParserUtil.parseCompilationUnit(new File(path));
} catch (FileNotFoundException e) {
throw new BugInCF("Failed to read Java file " + path, e);
}
JavaParserUtil.concatenateAddedStringLiterals(root);
CompilationUnitAnnos sourceAnnos = new CompilationUnitAnnos(root);
sourceToAnnos.put(path, sourceAnnos);
}
/**
* The first two arugments are a javac tree and a JavaParser node representing the same class.
* This method creates wrappers around all the classes, fields, and methods in that class, and
* stores those wrappers in {@code sourceAnnos}.
*
* @param javacClass javac tree for class
* @param javaParserClass JavaParser node corresponding to the same class as {@code javacClass}
* @param sourceAnnos compilation unit wrapper to add new wrappers to
*/
private void createWrappersForClass(
ClassTree javacClass, TypeDeclaration<?> javaParserClass, CompilationUnitAnnos sourceAnnos) {
JointJavacJavaParserVisitor visitor =
new DefaultJointVisitor() {
/**
* The number of inner classes encountered, for use in computing their names as keys to
* various maps. This is an estimate only: an error might lead to inaccurate annotations
* being emitted, but that is ok: WPI should never be run without running the checker
* again afterwards to check the results. This field is only used when no element for the
* inner class is available, such as when it comes from another compilation unit.
*/
private int innerClassCount = 0;
@Override
public void processClass(
ClassTree javacTree, ClassOrInterfaceDeclaration javaParserNode) {
addClass(javacTree);
}
@Override
public void processClass(ClassTree javacTree, EnumDeclaration javaParserNode) {
addClass(javacTree);
}
@Override
public void processClass(ClassTree javacTree, RecordDeclaration javaParserNode) {
addClass(javacTree);
}
@Override
public void processNewClass(NewClassTree javacTree, ObjectCreationExpr javaParserNode) {
ClassTree body = javacTree.getClassBody();
if (body != null) {
// elementFromTree returns null instead of crashing when no element exists for
// the class tree, which can happen for certain kinds of anonymous classes, such as
// Ordering$1 in PolyCollectorTypeVar.java in the all-systems test suite.
// addClass(ClassTree) in the then branch just below assumes that such an element
// exists.
Element classElt = TreeUtils.elementFromTree(body);
if (classElt != null) {
addClass(body);
} else {
// If such an element does not exist, compute the name of the class, instead.
// This method of computing the name is not 100% guaranteed to be reliable,
// but it should be sufficient for WPI's purposes here: if the wrong name
// is computed, the worst outcome is a false positive because WPI inferred an
// untrue annotation.
@BinaryName String className;
if ("".contentEquals(body.getSimpleName())) {
@SuppressWarnings("signature:assignment") // computed from string concatenation
@BinaryName String computedName =
javaParserClass.getFullyQualifiedName().get() + "$" + ++innerClassCount;
className = computedName;
} else {
@SuppressWarnings("signature:assignment") // computed from string concatenation
@BinaryName String computedName =
javaParserClass.getFullyQualifiedName().get()
+ "$"
+ body.getSimpleName().toString();
className = computedName;
}
addClass(body, className);
}
}
}
/**
* Creates a wrapper around the class for {@code tree} and stores it in {@code
* sourceAnnos}.
*
* <p>This method assumes that there is an Element corresponding to {@code tree} if {@code
* classNameKey} is null.
*
* @param tree tree to add. Its corresponding element is used as the key for {@code
* classToAnnos} if {@code classNameKey} is null.
* @param classNameKey if non-null, used as the key for {@code classToAnnos} instead of
* the element corresponding to {@code tree}
*/
private void addClass(ClassTree tree, @Nullable @BinaryName String classNameKey) {
String className;
if (classNameKey == null) {
TypeElement classElt = TreeUtils.elementFromDeclaration(tree);
className = ElementUtils.getBinaryName(classElt);
} else {
className = classNameKey;
}
ClassOrInterfaceAnnos typeWrapper = new ClassOrInterfaceAnnos();
if (!classToAnnos.containsKey(className)) {
classToAnnos.put(className, typeWrapper);
}
sourceAnnos.types.add(typeWrapper);
}
/**
* Creates a wrapper around the class for {@code tree} and stores it in {@code
* sourceAnnos}.
*
* <p>This method assumes that there is an Element corresponding to {@code tree}.
*
* @param tree tree to add. Its corresponding element is used as the key for {@code
* classToAnnos}.
*/
private void addClass(ClassTree tree) {
addClass(tree, null);
}
@Override
public void processMethod(MethodTree javacTree, MethodDeclaration javaParserNode) {
addCallableDeclaration(javacTree, javaParserNode);
}
@Override
public void processMethod(MethodTree javacTree, ConstructorDeclaration javaParserNode) {
addCallableDeclaration(javacTree, javaParserNode);
}
/**
* Creates a wrapper around {@code javacTree} with the corresponding declaration {@code
* javaParserNode} and stores it in {@code sourceAnnos}.
*
* @param javacTree javac tree for declaration to add
* @param javaParserNode JavaParser node for the same class as {@code javacTree}
*/
private void addCallableDeclaration(
MethodTree javacTree, CallableDeclaration<?> javaParserNode) {
Element element = TreeUtils.elementFromTree(javacTree);
if (element == null) {
// element can be null if there is no element corresponding to the method,
// which happens for certain kinds of anonymous classes, such as Ordering$1 in
// PolyCollectorTypeVar.java in the all-systems test suite.
return;
}
// If elt is non-null, it is guaranteed to be an executable element.
ExecutableElement elt = (ExecutableElement) element;
String className = ElementUtils.getEnclosingClassName(elt);
ClassOrInterfaceAnnos enclosingClass = classToAnnos.get(className);
String executableSignature = JVMNames.getJVMMethodSignature(javacTree);
if (!enclosingClass.callableDeclarations.containsKey(executableSignature)) {
enclosingClass.callableDeclarations.put(
executableSignature, new CallableDeclarationAnnos(javaParserNode));
}
}
@Override
public void processVariable(
VariableTree javacTree, EnumConstantDeclaration javaParserNode) {
VariableElement elt = TreeUtils.elementFromDeclaration(javacTree);
if (!elt.getKind().isField()) {
throw new BugInCF(elt + " is not a field but a " + elt.getKind());
}
String enclosingClassName = ElementUtils.getEnclosingClassName(elt);
ClassOrInterfaceAnnos enclosingClass = classToAnnos.get(enclosingClassName);
String fieldName = javacTree.getName().toString();
enclosingClass.enumConstants.add(fieldName);
// Ensure that if an enum constant defines a class, that class gets registered properly.
// See e.g. https://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.9.1 for
// the specification of an enum constant, which does permit it to define an anonymous
// class.
NewClassTree constructor = (NewClassTree) javacTree.getInitializer();
if (constructor.getClassBody() != null) {
addClass(constructor.getClassBody());
}
}
@Override
public void processVariable(VariableTree javacTree, VariableDeclarator javaParserNode) {
// This seems to occur when javacTree is a local variable in the second
// class located in a source file. If this check returns false, then the
// below call to TreeUtils.elementFromDeclaration causes a crash.
if (TreeUtils.elementFromTree(javacTree) == null) {
return;
}
VariableElement elt = TreeUtils.elementFromDeclaration(javacTree);
if (!elt.getKind().isField()) {
return;
}
String enclosingClassName = ElementUtils.getEnclosingClassName(elt);
ClassOrInterfaceAnnos enclosingClass = classToAnnos.get(enclosingClassName);
String fieldName = javacTree.getName().toString();
if (!enclosingClass.fields.containsKey(fieldName)) {
enclosingClass.fields.put(fieldName, new FieldAnnos(javaParserNode));
}
}
};
visitor.visitClass(javacClass, javaParserClass);
}
/**
* Calls {@link #addSourceFile(String)} for the file containing the given element.
*
* @param element the element for the source file to add
* @return path of the file containing {@code element}
*/
private String addClassesForElement(Element element) {
if (!ElementUtils.isElementFromSourceCode(element)) {
throw new BugInCF("Called addClassesForElement for non-source element: " + element);
}
TypeElement toplevelClass = ElementUtils.toplevelEnclosingTypeElement(element);
String path = ElementUtils.getSourceFilePath(toplevelClass);
if (classToAnnos.containsKey(ElementUtils.getBinaryName(toplevelClass))) {
return path;
}
addSourceFile(path);
CompilationUnitAnnos sourceAnnos = sourceToAnnos.get(path);
ClassTree toplevelClassTree = (ClassTree) atypeFactory.declarationFromElement(toplevelClass);
TypeDeclaration<?> javaParserNode =
sourceAnnos.getClassOrInterfaceDeclarationByName(toplevelClass.getSimpleName().toString());
createWrappersForClass(toplevelClassTree, javaParserNode, sourceAnnos);
return path;
}
///
/// Writing to a file
///
// The prepare*ForWriting hooks are needed in addition to the postProcessClassTree hook because
// a scene may be modifed and written at any time, including before or after
// postProcessClassTree is called.
/**
* Side-effects the compilation unit annotations to make any desired changes before writing to a
* file.
*
* @param compilationUnitAnnos the compilation unit annotations to modify
*/
public void prepareCompilationUnitForWriting(CompilationUnitAnnos compilationUnitAnnos) {
for (ClassOrInterfaceAnnos type : compilationUnitAnnos.types) {
prepareClassForWriting(type);
}
}
/**
* Side-effects the class annotations to make any desired changes before writing to a file.
*
* @param classAnnos the class annotations to modify
*/
public void prepareClassForWriting(ClassOrInterfaceAnnos classAnnos) {
for (Map.Entry<String, CallableDeclarationAnnos> methodEntry :
classAnnos.callableDeclarations.entrySet()) {
prepareMethodForWriting(methodEntry.getValue());
}
}
/**
* Side-effects the method or constructor annotations to make any desired changes before writing
* to a file.
*
* @param methodAnnos the method or constructor annotations to modify
*/
public void prepareMethodForWriting(CallableDeclarationAnnos methodAnnos) {
atypeFactory.prepareMethodForWriting(methodAnnos);
}
@Override
public void writeResultsToFile(OutputFormat outputFormat, BaseTypeChecker checker) {
if (outputFormat != OutputFormat.AJAVA) {
throw new BugInCF("WholeProgramInferenceJavaParser used with format " + outputFormat);
}
File outputDir = new File(AJAVA_FILES_PATH);
if (!outputDir.exists()) {
outputDir.mkdirs();
}
for (String path : modifiedFiles) {
CompilationUnitAnnos root = sourceToAnnos.get(path);
prepareCompilationUnitForWriting(root);
String packageDir = AJAVA_FILES_PATH;
if (root.compilationUnit.getPackageDeclaration().isPresent()) {
packageDir +=
File.separator
+ root.compilationUnit
.getPackageDeclaration()
.get()
.getNameAsString()
.replaceAll("\\.", File.separator);
}
File packageDirFile = new File(packageDir);
if (!packageDirFile.exists()) {
packageDirFile.mkdirs();
}
String name = new File(path).getName();
if (name.endsWith(".java")) {
name = name.substring(0, name.length() - ".java".length());
}
String nameWithChecker = name + "-" + checker.getClass().getCanonicalName() + ".ajava";
String outputPath = packageDir + File.separator + nameWithChecker;
if (this.inferOutputOriginal) {
String outputPathNoCheckerName = packageDir + File.separator + name + ".ajava";
// Avoid re-writing this file for each checker that was run.
if (Files.notExists(Paths.get(outputPathNoCheckerName))) {
writeAjavaFile(outputPathNoCheckerName, root);
}
}
root.transferAnnotations(checker);
writeAjavaFile(outputPath, root);
}
modifiedFiles.clear();
}
/**
* Write an ajava file to disk.
*
* @param outputPath the path to which the ajava file should be written
* @param root the compilation unit to be written
*/
private void writeAjavaFile(String outputPath, CompilationUnitAnnos root) {
try {
FileWriter writer = new FileWriter(outputPath);
// JavaParser can output using lexical preserving printing, which writes the file such that
// its formatting is close to the original source file it was parsed from as
// possible. Currently, this feature is very buggy and crashes when adding annotations in
// certain locations. This implementation could be used instead if it's fixed in JavaParser.
// LexicalPreservingPrinter.print(root.declaration, writer);
// Do not print invisible qualifiers, to avoid cluttering the output.
Set<String> invisibleQualifierNames = getInvisibleQualifierNames(this.atypeFactory);
DefaultPrettyPrinter prettyPrinter =
new DefaultPrettyPrinter() {
@Override
public String print(Node node) {
VoidVisitor<Void> visitor =
new DefaultPrettyPrinterVisitor(getConfiguration()) {
@Override
public void visit(final MarkerAnnotationExpr n, final Void arg) {
if (invisibleQualifierNames.contains(n.getName().toString())) {
return;
}
super.visit(n, arg);
}
@Override
public void visit(final SingleMemberAnnotationExpr n, final Void arg) {
if (invisibleQualifierNames.contains(n.getName().toString())) {
return;
}
super.visit(n, arg);
}
@Override
public void visit(final NormalAnnotationExpr n, final Void arg) {
if (invisibleQualifierNames.contains(n.getName().toString())) {
return;
}
super.visit(n, arg);
}
};
node.accept(visitor, null);
return visitor.toString();
}
};
writer.write(prettyPrinter.print(root.compilationUnit));
writer.close();
} catch (IOException e) {
throw new BugInCF("Error while writing ajava file " + outputPath, e);
}
}
/**
* Adds an explicit receiver type to a JavaParser method declaration.
*
* @param methodDeclaration declaration to add a receiver to
*/
private static void addExplicitReceiver(MethodDeclaration methodDeclaration) {
if (methodDeclaration.getReceiverParameter().isPresent()) {
return;
}
com.github.javaparser.ast.Node parent = methodDeclaration.getParentNode().get();
if (!(parent instanceof TypeDeclaration)) {
return;
}
TypeDeclaration<?> parentDecl = (TypeDeclaration<?>) parent;
ClassOrInterfaceType receiver = new ClassOrInterfaceType();
receiver.setName(parentDecl.getName());
if (parentDecl.isClassOrInterfaceDeclaration()) {
ClassOrInterfaceDeclaration parentClassDecl = parentDecl.asClassOrInterfaceDeclaration();
if (!parentClassDecl.getTypeParameters().isEmpty()) {
NodeList<Type> typeArgs = new NodeList<>();
for (TypeParameter typeParam : parentClassDecl.getTypeParameters()) {
ClassOrInterfaceType typeArg = new ClassOrInterfaceType();
typeArg.setName(typeParam.getNameAsString());
typeArgs.add(typeArg);
}
receiver.setTypeArguments(typeArgs);
}
}
methodDeclaration.setReceiverParameter(new ReceiverParameter(receiver, "this"));
}
/**
* Transfers all annotations for {@code annotatedType} and its nested types to {@code target},
* which is the JavaParser node representing the same type. Does nothing if {@code annotatedType}
* is null (this may occur if there are no inferred annotations for the type).
*
* @param annotatedType type to transfer annotations from
* @param target the JavaParser type to transfer annotation to; must represent the same type as
* {@code annotatedType}
*/
private static void transferAnnotations(
@Nullable AnnotatedTypeMirror annotatedType, Type target) {
if (annotatedType == null) {
return;
}
target.accept(new AnnotationTransferVisitor(), annotatedType);
}
///
/// Storing annotations
///
/**
* Stores the JavaParser node for a compilation unit and the list of wrappers for the classes and
* interfaces in that compilation unit.
*/
private static class CompilationUnitAnnos {
/** Compilation unit being wrapped. */
public CompilationUnit compilationUnit;
/** Wrappers for classes and interfaces in {@code compilationUnit}. */
public List<ClassOrInterfaceAnnos> types;
/**
* Constructs a wrapper around the given compilation unit.
*
* @param compilationUnit compilation unit to wrap
*/
public CompilationUnitAnnos(CompilationUnit compilationUnit) {
this.compilationUnit = compilationUnit;
types = new ArrayList<>();
}
/**
* Transfers all annotations inferred by whole program inference for the wrapped compilation
* unit to their corresponding JavaParser locations.
*
* @param checker the checker who's name to include in the @AnnotatedFor annotation
*/
public void transferAnnotations(BaseTypeChecker checker) {
JavaParserUtil.clearAnnotations(compilationUnit);
for (TypeDeclaration<?> typeDecl : compilationUnit.getTypes()) {
typeDecl.addSingleMemberAnnotation(
"org.checkerframework.framework.qual.AnnotatedFor",
"\"" + checker.getClass().getCanonicalName() + "\"");
}
for (ClassOrInterfaceAnnos typeAnnos : types) {
typeAnnos.transferAnnotations();
}
}
/**
* Returns the top-level type declaration named {@code name} in the compilation unit.
*
* @param name name of type declaration
* @return the type declaration named {@code name} in the wrapped compilation unit
*/
public TypeDeclaration<?> getClassOrInterfaceDeclarationByName(String name) {
return JavaParserUtil.getTypeDeclarationByName(compilationUnit, name);
}
}
/**
* Stores wrappers for the locations where annotations may be inferred in a class or interface.
*/
private static class ClassOrInterfaceAnnos {
/**
* Mapping from JVM method signatures to the wrapper containing the corresponding executable.
*/
public Map<String, CallableDeclarationAnnos> callableDeclarations = new HashMap<>();
/** Mapping from field names to wrappers for those fields. */
public Map<String, FieldAnnos> fields = new HashMap<>(2);
/** Collection of declared enum constants (empty if not an enum). */
public Set<String> enumConstants = new HashSet<>(2);
/**
* Transfers all annotations inferred by whole program inference for the methods and fields in
* the wrapper class or interface to their corresponding JavaParser locations.
*/
public void transferAnnotations() {
for (CallableDeclarationAnnos callableAnnos : callableDeclarations.values()) {
callableAnnos.transferAnnotations();
}
for (FieldAnnos field : fields.values()) {
field.transferAnnotations();
}
}
@Override
public String toString() {
return "ClassOrInterfaceAnnos [callableDeclarations="