-
Notifications
You must be signed in to change notification settings - Fork 350
/
WholeProgramInferenceJavaParserStorage.java
1924 lines (1748 loc) · 78.2 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.PackageDeclaration;
import com.github.javaparser.ast.body.AnnotationDeclaration;
import com.github.javaparser.ast.body.BodyDeclaration;
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.FieldDeclaration;
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.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import org.checkerframework.afu.scenelib.util.JVMNames;
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.AnnotationMirrorSet;
import org.checkerframework.javacutil.BugInCF;
import org.checkerframework.javacutil.CollectionUtils;
import org.checkerframework.javacutil.DeepCopyable;
import org.checkerframework.javacutil.ElementUtils;
import org.checkerframework.javacutil.Pair;
import org.checkerframework.javacutil.TreeUtils;
import org.plumelib.util.ArraySet;
import org.plumelib.util.CollectionsPlume;
/**
* 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 File AJAVA_FILES_PATH = new File("build", "whole-program-inference");
/** The type factory associated with this. */
protected final AnnotatedTypeFactory atypeFactory;
/** The element utilities for {@code atypeFactory}. */
protected final Elements elements;
/**
* 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<>();
/** Maps from binary class name to binary names of all supertypes. */
private Map<@BinaryName String, Set<@BinaryName String>> supertypesMap = new HashMap<>();
/** Maps from binary class name to binary names of all known subtypes. */
private Map<@BinaryName String, Set<@BinaryName String>> subtypesMap = 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<>();
/** Maps from binary class name to the source file that contains it. */
private Map<String, String> classToSource = 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.elements = atypeFactory.getElementUtils();
this.inferOutputOriginal = inferOutputOriginal;
}
@Override
public String getFileForElement(Element elt) {
return addClassesForElement(elt);
}
@Override
public void setFileModified(String path) {
modifiedFiles.add(path);
}
/**
* Set the source file as modified, for the given class.
*
* @param className the binary name of a class that should be written to disk
*/
private void setClassModified(@Nullable @BinaryName String className) {
if (className == null) {
return;
}
String path = classToSource.get(className);
if (path != null) {
setFileModified(path);
}
}
/**
* Set the source files as modified, for all the given classes.
*
* @param classNames the binary names of classes that should be written to disk
*/
private void setClassesModified(@Nullable Collection<@BinaryName String> classNames) {
if (classNames == null) {
return;
}
for (String className : classNames) {
setClassModified(className);
}
}
/**
* For every modified file, consider its subclasses and superclasses modified, too. The reason is
* that an annotation change in a class might require annotations in its superclasses and
* supclasses to be modified, in order to preserve behavioral subtyping. Setting it modified will
* cause it to be written out, and while writing out, the annotations will be made consistent
* across the class hierarchy by {@link #wpiPrepareCompilationUnitForWriting}.
*/
public void setSupertypesAndSubtypesModified() {
for (String path : modifiedFiles) {
CompilationUnitAnnos cuAnnos = sourceToAnnos.get(path);
for (ClassOrInterfaceAnnos classAnnos : cuAnnos.types) {
String className = classAnnos.className;
setClassesModified(supertypesMap.get(className));
setClassesModified(subtypesMap.get(className));
}
}
}
///
/// Reading stored annotations
///
@Override
public boolean hasStorageLocationForMethod(ExecutableElement methodElt) {
return getMethodAnnos(methodElt) != null;
}
@Override
public AnnotationMirrorSet getMethodDeclarationAnnotations(ExecutableElement methodElt) {
String className = ElementUtils.getEnclosingClassName(methodElt);
// Read in classes for the element.
getFileForElement(methodElt);
ClassOrInterfaceAnnos classAnnos = classToAnnos.get(className);
if (classAnnos == null) {
return AnnotationMirrorSet.emptySet();
}
CallableDeclarationAnnos methodAnnos =
classAnnos.callableDeclarations.get(JVMNames.getJVMMethodSignature(methodElt));
if (methodAnnos == null) {
return AnnotationMirrorSet.emptySet();
}
return methodAnnos.getDeclarationAnnotations();
}
/**
* 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 @Nullable FieldAnnos getFieldAnnos(VariableElement fieldElt) {
String className = ElementUtils.getEnclosingClassName(fieldElt);
// Read in classes for the element.
getFileForElement(fieldElt);
ClassOrInterfaceAnnos classAnnos = classToAnnos.get(className);
if (classAnnos == null) {
return null;
}
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 (classAnnos == null) {
return null;
}
// 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 removeMethodDeclarationAnnotation(ExecutableElement elt, AnnotationMirror anno) {
CallableDeclarationAnnos methodAnnos = getMethodAnnos(elt);
if (methodAnnos == null) {
// See the comment on the similar exception in #getParameterAnnotations, above.
return false;
}
return methodAnnos.removeDeclarationAnnotation(anno);
}
@Override
public boolean addFieldDeclarationAnnotation(VariableElement field, AnnotationMirror anno) {
FieldAnnos fieldAnnos = getFieldAnnos(field);
if (fieldAnnos == null) {
// See the comment on the similar exception in #getParameterAnnotations, above.
return false;
}
boolean isNewAnnotation = fieldAnnos != null && fieldAnnos.addDeclarationAnnotation(anno);
if (isNewAnnotation) {
modifiedFiles.add(getFileForElement(field));
}
return isNewAnnotation;
}
@Override
public boolean addDeclarationAnnotationToFormalParameter(
ExecutableElement methodElt, int index, AnnotationMirror anno) {
CallableDeclarationAnnos methodAnnos = getMethodAnnos(methodElt);
if (methodAnnos == null) {
// See the comment on the similar exception in #getParameterAnnotations, above.
return false;
}
boolean isNewAnnotation = methodAnnos.addDeclarationAnnotationToFormalParameter(anno, index);
if (isNewAnnotation) {
modifiedFiles.add(getFileForElement(methodElt));
}
return isNewAnnotation;
}
@Override
public boolean addClassDeclarationAnnotation(TypeElement classElt, AnnotationMirror anno) {
String className = ElementUtils.getBinaryName(classElt);
ClassOrInterfaceAnnos classAnnos = classToAnnos.get(className);
if (classAnnos == null) {
// See the comment on the similar exception in #getParameterAnnotations, above.
return false;
}
boolean isNewAnnotation = classAnnos.addAnnotationToClassDeclaration(anno);
if (isNewAnnotation) {
modifiedFiles.add(getFileForElement(classElt));
}
return isNewAnnotation;
}
@Override
public AnnotatedTypeMirror atmFromStorageLocation(
TypeMirror typeMirror, AnnotatedTypeMirror storageLocation) {
if (typeMirror.getKind() == TypeKind.TYPEVAR) {
// Only copy the primary annotation, because we don't currently have
// support for inferring type bounds. This avoids accidentally substituting the
// use of the type variable for its declaration when inferring annotations on
// fields with a type variable as their type.
AnnotatedTypeMirror asExpectedType =
AnnotatedTypeMirror.createType(typeMirror, atypeFactory, false);
asExpectedType.replaceAnnotations(storageLocation.getAnnotations());
return asExpectedType;
} else {
return storageLocation;
}
}
@Override
public void updateStorageLocationFromAtm(
AnnotatedTypeMirror newATM,
AnnotatedTypeMirror curATM,
AnnotatedTypeMirror typeToUpdate,
TypeUseLocation defLoc,
boolean ignoreIfAnnotated) {
// Only update the AnnotatedTypeMirror if there are no explicit annotations
if (curATM.getExplicitAnnotations().isEmpty() || !ignoreIfAnnotated) {
for (AnnotationMirror am : newATM.getAnnotations()) {
typeToUpdate.replaceAnnotation(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.replaceAnnotation(am);
}
}
// Need to check both newATM and curATM, because one might be a declared type
// even if the other is an array: it is permitted to assign e.g., a String[]
// to a location with static type Object **and vice-versa** (if a cast is used).
if (newATM.getKind() == TypeKind.ARRAY && curATM.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);
if (element == null) {
// TODO: There should be an element here, or there is nowhere to store inferences about
// `tree`.
return;
}
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);
Optional<PackageDeclaration> oPackageDecl = root.getPackageDeclaration();
String prefix = oPackageDecl.isPresent() ? oPackageDecl.get().getName().asString() + "." : "";
List<@BinaryName String> typeNames = new ArrayList<>();
for (TypeDeclaration<?> type : root.getTypes()) {
addDeclaredTypes(type, prefix, typeNames);
}
for (String typeName : typeNames) {
classToSource.put(typeName, path);
}
}
/**
* Computes the binary names of a type and all nested types.
*
* @param td a type declaration
* @param prefix the package, or package+outerclass, prefix in a binary name
* @param result a list to which to add the binary names of all classes defined in the compilation
* unit
*/
private static void addDeclaredTypes(
TypeDeclaration<?> td, String prefix, List<@BinaryName String> result) {
@SuppressWarnings("signature:assignment") // string concatenation
@BinaryName String typeName = prefix + td.getName().asString();
result.add(typeName);
for (BodyDeclaration<?> member : td.getMembers()) {
if (member.isTypeDeclaration()) {
addDeclaredTypes(member.asTypeDeclaration(), typeName + "$", result);
}
}
}
/**
* The first two arguments 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, javaParserNode);
}
@Override
public void processClass(ClassTree javacTree, EnumDeclaration javaParserNode) {
addClass(javacTree, javaParserNode);
}
@Override
public void processClass(ClassTree javacTree, RecordDeclaration javaParserNode) {
addClass(javacTree, javaParserNode);
}
@Override
public void processClass(ClassTree javacTree, AnnotationDeclaration javaParserNode) {
// TODO: consider supporting inferring annotations on annotation declarations.
// addClass(javacTree, javaParserNode);
}
@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.elementFromDeclaration(body);
if (classElt != null) {
addClass(body, null);
} 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, null);
}
}
}
/**
* 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 binary name of the element corresponding to {@code tree}
* @param javaParserNode the node corresponding to the declaration, which is used to place
* annotations on the class itself. Can be null, e.g. for an anonymous class.
*/
private void addClass(
ClassTree tree,
@Nullable @BinaryName String classNameKey,
@Nullable TypeDeclaration<?> javaParserNode) {
String className;
if (classNameKey == null) {
TypeElement classElt = TreeUtils.elementFromDeclaration(tree);
className = ElementUtils.getBinaryName(classElt);
for (TypeElement supertypeElement : ElementUtils.getSuperTypes(classElt, elements)) {
String supertypeName = ElementUtils.getBinaryName(supertypeElement);
@SuppressWarnings({"signature:assignment", "signature:return"}) // #979?
Set<String> supertypeSet =
supertypesMap.computeIfAbsent(className, k -> new TreeSet<>());
supertypeSet.add(supertypeName);
@SuppressWarnings({"signature:assignment", "signature:return"}) // #979?
Set<String> subtypeSet =
subtypesMap.computeIfAbsent(supertypeName, k -> new TreeSet<>());
subtypeSet.add(className);
}
} else {
className = classNameKey;
}
ClassOrInterfaceAnnos typeWrapper =
new ClassOrInterfaceAnnos(className, javaParserNode);
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}.
* @param javaParserNode the node corresponding to the declaration, which is used to place
* annotations on the class itself. Can be null, e.g. for an anonymous class.
*/
private void addClass(ClassTree tree, @Nullable TypeDeclaration<?> javaParserNode) {
addClass(tree, null, javaParserNode);
}
@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) {
ExecutableElement element = TreeUtils.elementFromDeclaration(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;
}
String className = ElementUtils.getEnclosingClassName(element);
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/se17/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();
ClassTree constructorClassBody = constructor.getClassBody();
if (constructorClassBody != null) {
// addClass assumes there is an element for its argument, but that is not always true!
if (TreeUtils.elementFromDeclaration(constructorClassBody) != null) {
addClass(constructorClassBody, null);
}
}
}
@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.elementFromDeclaration(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 (toplevelClass.getKind() == ElementKind.ANNOTATION_TYPE) {
// Inferring annotations on elements of annotation declarations is not supported.
// One issue with supporting inference on annotation declaration elements is that
// AnnotatedTypeFactory#declarationFromElement returns null for annotation declarations
// quite commonly (because Trees#getTree, which it delegates to, does as well).
// In this case, we return path here without actually attempting to create the wrappers
// for the annotation declaration. The rest of WholeProgramInferenceJavaParserStorage
// already needs to handle classes without entries in the various tables (because of the
// possibility of classes outside the current compilation unit), so this is safe.
return path;
}
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 wpiPrepareCompilationUnitForWriting(CompilationUnitAnnos compilationUnitAnnos) {
for (ClassOrInterfaceAnnos type : compilationUnitAnnos.types) {
wpiPrepareClassForWriting(
type, supertypesMap.get(type.className), subtypesMap.get(type.className));
}
}
/**
* Side-effects the class annotations to make any desired changes before writing to a file.
*
* <p>Because of the side effect, clients may want to pass a copy into this method.
*
* @param classAnnos the class annotations to modify
* @param supertypes the binary names of all supertypes; not side-effected
* @param subtypes the binary names of all subtypes; not side-effected
*/
public void wpiPrepareClassForWriting(
ClassOrInterfaceAnnos classAnnos,
Collection<@BinaryName String> supertypes,
Collection<@BinaryName String> subtypes) {
if (classAnnos.callableDeclarations.isEmpty()) {
return;
}
for (Map.Entry<String, CallableDeclarationAnnos> methodEntry :
classAnnos.callableDeclarations.entrySet()) {
String jvmSignature = methodEntry.getKey();
List<CallableDeclarationAnnos> inSupertypes =
findOverrides(jvmSignature, supertypesMap.get(classAnnos.className));
List<CallableDeclarationAnnos> inSubtypes =
findOverrides(jvmSignature, subtypesMap.get(classAnnos.className));
wpiPrepareMethodForWriting(methodEntry.getValue(), inSupertypes, inSubtypes);
}
}
/**
* Return all the CallableDeclarationAnnos for the given signature.
*
* @param jvmSignature the JVM signature
* @param typeNames a collection of type names
* @return the CallableDeclarationAnnos for the given signature, in all of the types
*/
private List<CallableDeclarationAnnos> findOverrides(
String jvmSignature, @Nullable Collection<@BinaryName String> typeNames) {
if (typeNames == null) {
return Collections.emptyList();
}
List<CallableDeclarationAnnos> result = new ArrayList<>();
for (String typeName : typeNames) {
ClassOrInterfaceAnnos classAnnos = classToAnnos.get(typeName);
if (classAnnos != null) {
CallableDeclarationAnnos callableAnnos = classAnnos.callableDeclarations.get(jvmSignature);
if (callableAnnos != null) {
result.add(callableAnnos);
}
}
}
return result;
}
/**