-
Notifications
You must be signed in to change notification settings - Fork 108
/
TypeDeclaration.java
1945 lines (1830 loc) · 74.4 KB
/
TypeDeclaration.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
/*******************************************************************************
* Copyright (c) 2000, 2020 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
* Stephan Herrmann - Contributions for
* Bug 360328 - [compiler][null] detect null problems in nested code (local class inside a loop)
* Bug 388630 - @NonNull diagnostics at line 0
* Bug 392099 - [1.8][compiler][null] Apply null annotation on types for null analysis
* Bug 416176 - [1.8][compiler][null] null type annotations cause grief on type variables
* Bug 424727 - [compiler][null] NullPointerException in nullAnnotationUnsupportedLocation(ProblemReporter.java:5708)
* Bug 457210 - [1.8][compiler][null] Wrong Nullness errors given on full build build but not on incremental build?
* Keigo Imai - Contribution for bug 388903 - Cannot extend inner class as an anonymous class when it extends the outer class
* Pierre-Yves B. <pyvesdev@gmail.com> - Contributions for
* Bug 542520 - [JUnit 5] Warning The method xxx from the type X is never used locally is shown when using MethodSource
* Bug 546084 - Using Junit 5s MethodSource leads to ClassCastException
*******************************************************************************/
package org.eclipse.jdt.internal.compiler.ast;
import java.util.ArrayList;
import java.util.Arrays;
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 org.eclipse.jdt.core.compiler.*;
import org.eclipse.jdt.internal.compiler.*;
import org.eclipse.jdt.internal.compiler.impl.*;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.eclipse.jdt.internal.compiler.codegen.*;
import org.eclipse.jdt.internal.compiler.flow.*;
import org.eclipse.jdt.internal.compiler.lookup.*;
import org.eclipse.jdt.internal.compiler.parser.*;
import org.eclipse.jdt.internal.compiler.problem.*;
import org.eclipse.jdt.internal.compiler.util.SimpleSetOfCharArray;
import org.eclipse.jdt.internal.compiler.util.Util;
public class TypeDeclaration extends Statement implements ProblemSeverities, ReferenceContext {
// Type decl kinds
public static final int CLASS_DECL = 1;
public static final int INTERFACE_DECL = 2;
public static final int ENUM_DECL = 3;
public static final int ANNOTATION_TYPE_DECL = 4;
/*
* @noreference This field is not intended to be referenced by clients as it is a part of Java preview feature.
*/
public static final int RECORD_DECL = 5;
public int modifiers = ClassFileConstants.AccDefault;
public int modifiersSourceStart;
public int functionalExpressionsCount = 0;
public Annotation[] annotations;
public char[] name;
public TypeReference superclass;
public TypeReference[] superInterfaces;
public FieldDeclaration[] fields;
public AbstractMethodDeclaration[] methods;
public TypeDeclaration[] memberTypes;
public SourceTypeBinding binding;
public ClassScope scope;
public MethodScope initializerScope;
public MethodScope staticInitializerScope;
public boolean ignoreFurtherInvestigation = false;
public int maxFieldCount;
public int declarationSourceStart;
public int declarationSourceEnd;
public int restrictedIdentifierStart = -1; // used only for record and permits restricted keywords.
public int bodyStart;
public int bodyEnd; // doesn't include the trailing comment if any.
public CompilationResult compilationResult;
public MethodDeclaration[] missingAbstractMethods;
public Javadoc javadoc;
public QualifiedAllocationExpression allocation; // for anonymous only
public TypeDeclaration enclosingType; // for member types only
public FieldBinding enumValuesSyntheticfield; // for enum
public int enumConstantsCounter;
// 1.5 support
public TypeParameter[] typeParameters;
// 14 Records preview support
public RecordComponent[] recordComponents;
public int nRecordComponents;
public static Set<String> disallowedComponentNames;
// 15 Sealed Type preview support
public TypeReference[] permittedTypes;
static {
disallowedComponentNames = new HashSet<>(6);
disallowedComponentNames.add("clone"); //$NON-NLS-1$
disallowedComponentNames.add("finalize"); //$NON-NLS-1$
disallowedComponentNames.add("getClass"); //$NON-NLS-1$
disallowedComponentNames.add("hashCode"); //$NON-NLS-1$
disallowedComponentNames.add("notify"); //$NON-NLS-1$
disallowedComponentNames.add("notifyAll");//$NON-NLS-1$
disallowedComponentNames.add("toString"); //$NON-NLS-1$
disallowedComponentNames.add("wait"); //$NON-NLS-1$
}
public TypeDeclaration(CompilationResult compilationResult){
this.compilationResult = compilationResult;
}
/*
* We cause the compilation task to abort to a given extent.
*/
@Override
public void abort(int abortLevel, CategorizedProblem problem) {
switch (abortLevel) {
case AbortCompilation :
throw new AbortCompilation(this.compilationResult, problem);
case AbortCompilationUnit :
throw new AbortCompilationUnit(this.compilationResult, problem);
case AbortMethod :
throw new AbortMethod(this.compilationResult, problem);
default :
throw new AbortType(this.compilationResult, problem);
}
}
/**
* This method is responsible for adding a {@code <clinit>} method declaration to the type method collections.
* Note that this implementation is inserting it in first place (as VAJ or javac), and that this
* impacts the behavior of the method ConstantPool.resetForClinit(int. int), in so far as
* the latter will have to reset the constant pool state accordingly (if it was added first, it does
* not need to preserve some of the method specific cached entries since this will be the first method).
* inserts the clinit method declaration in the first position.
*
* @see org.eclipse.jdt.internal.compiler.codegen.ConstantPool#resetForClinit(int, int)
*/
public final void addClinit() {
//see comment on needClassInitMethod
if (needClassInitMethod()) {
int length;
AbstractMethodDeclaration[] methodDeclarations;
if ((methodDeclarations = this.methods) == null) {
length = 0;
methodDeclarations = new AbstractMethodDeclaration[1];
} else {
length = methodDeclarations.length;
System.arraycopy(
methodDeclarations,
0,
(methodDeclarations = new AbstractMethodDeclaration[length + 1]),
1,
length);
}
Clinit clinit = new Clinit(this.compilationResult);
methodDeclarations[0] = clinit;
// clinit is added in first location, so as to minimize the use of ldcw (big consumer of constant inits)
clinit.declarationSourceStart = clinit.sourceStart = this.sourceStart;
clinit.declarationSourceEnd = clinit.sourceEnd = this.sourceEnd;
clinit.bodyEnd = this.sourceEnd;
this.methods = methodDeclarations;
}
}
/*
* INTERNAL USE ONLY - Creates a fake method declaration for the corresponding binding.
* It is used to report errors for missing abstract methods.
*/
public MethodDeclaration addMissingAbstractMethodFor(MethodBinding methodBinding) {
TypeBinding[] argumentTypes = methodBinding.parameters;
int argumentsLength = argumentTypes.length;
//the constructor
MethodDeclaration methodDeclaration = new MethodDeclaration(this.compilationResult);
methodDeclaration.selector = methodBinding.selector;
methodDeclaration.sourceStart = this.sourceStart;
methodDeclaration.sourceEnd = this.sourceEnd;
methodDeclaration.modifiers = methodBinding.getAccessFlags() & ~ClassFileConstants.AccAbstract;
if (argumentsLength > 0) {
String baseName = "arg";//$NON-NLS-1$
Argument[] arguments = (methodDeclaration.arguments = new Argument[argumentsLength]);
for (int i = argumentsLength; --i >= 0;) {
arguments[i] = new Argument((baseName + i).toCharArray(), 0L, null /*type ref*/, ClassFileConstants.AccDefault);
}
}
//adding the constructor in the methods list
if (this.missingAbstractMethods == null) {
this.missingAbstractMethods = new MethodDeclaration[] { methodDeclaration };
} else {
MethodDeclaration[] newMethods;
System.arraycopy(
this.missingAbstractMethods,
0,
newMethods = new MethodDeclaration[this.missingAbstractMethods.length + 1],
1,
this.missingAbstractMethods.length);
newMethods[0] = methodDeclaration;
this.missingAbstractMethods = newMethods;
}
//============BINDING UPDATE==========================
methodDeclaration.binding = new MethodBinding(
methodDeclaration.modifiers | ClassFileConstants.AccSynthetic, //methodDeclaration
methodBinding.selector,
methodBinding.returnType,
argumentsLength == 0 ? Binding.NO_PARAMETERS : argumentTypes, //arguments bindings
methodBinding.thrownExceptions, //exceptions
this.binding); //declaringClass
methodDeclaration.scope = new MethodScope(this.scope, methodDeclaration, true);
methodDeclaration.bindArguments();
/* if (binding.methods == null) {
binding.methods = new MethodBinding[] { methodDeclaration.binding };
} else {
MethodBinding[] newMethods;
System.arraycopy(
binding.methods,
0,
newMethods = new MethodBinding[binding.methods.length + 1],
1,
binding.methods.length);
newMethods[0] = methodDeclaration.binding;
binding.methods = newMethods;
}*/
//===================================================
return methodDeclaration;
}
/**
* Flow analysis for a local innertype
*/
@Override
public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
if (this.ignoreFurtherInvestigation)
return flowInfo;
try {
if ((flowInfo.tagBits & FlowInfo.UNREACHABLE_OR_DEAD) == 0) {
this.bits |= ASTNode.IsReachable;
LocalTypeBinding localType = (LocalTypeBinding) this.binding;
localType.setConstantPoolName(currentScope.compilationUnitScope().computeConstantPoolName(localType));
}
manageEnclosingInstanceAccessIfNecessary(currentScope, flowInfo);
updateMaxFieldCount(); // propagate down the max field count
internalAnalyseCode(flowContext, flowInfo);
} catch (AbortType e) {
this.ignoreFurtherInvestigation = true;
}
return flowInfo;
}
/**
* Flow analysis for a member innertype
*/
public void analyseCode(ClassScope enclosingClassScope) {
if (this.ignoreFurtherInvestigation)
return;
try {
// propagate down the max field count
updateMaxFieldCount();
internalAnalyseCode(null, FlowInfo.initial(this.maxFieldCount));
} catch (AbortType e) {
this.ignoreFurtherInvestigation = true;
}
}
/**
* Flow analysis for a local member innertype
*/
public void analyseCode(ClassScope currentScope, FlowContext flowContext, FlowInfo flowInfo) {
if (this.ignoreFurtherInvestigation)
return;
try {
if ((flowInfo.tagBits & FlowInfo.UNREACHABLE_OR_DEAD) == 0) {
this.bits |= ASTNode.IsReachable;
LocalTypeBinding localType = (LocalTypeBinding) this.binding;
localType.setConstantPoolName(currentScope.compilationUnitScope().computeConstantPoolName(localType));
}
manageEnclosingInstanceAccessIfNecessary(currentScope, flowInfo);
updateMaxFieldCount(); // propagate down the max field count
internalAnalyseCode(flowContext, flowInfo);
} catch (AbortType e) {
this.ignoreFurtherInvestigation = true;
}
}
/**
* Flow analysis for a package member type
*/
public void analyseCode(CompilationUnitScope unitScope) {
if (this.ignoreFurtherInvestigation)
return;
try {
internalAnalyseCode(null, FlowInfo.initial(this.maxFieldCount));
} catch (AbortType e) {
this.ignoreFurtherInvestigation = true;
}
}
/**
* Check for constructor vs. method with no return type.
* Answers true if at least one constructor is defined
*/
public boolean checkConstructors(Parser parser) {
//if a constructor has not the name of the type,
//convert it into a method with 'null' as its return type
boolean hasConstructor = false;
if (this.methods != null) {
for (int i = this.methods.length; --i >= 0;) {
AbstractMethodDeclaration am;
if ((am = this.methods[i]).isConstructor()) {
if (!CharOperation.equals(am.selector, this.name)) {
// the constructor was in fact a method with no return type
// unless an explicit constructor call was supplied
ConstructorDeclaration c = (ConstructorDeclaration) am;
if (c.constructorCall == null || c.constructorCall.isImplicitSuper()) { //changed to a method
MethodDeclaration m = parser.convertToMethodDeclaration(c, this.compilationResult);
this.methods[i] = m;
}
} else {
switch (kind(this.modifiers)) {
case TypeDeclaration.INTERFACE_DECL :
// report the problem and continue the parsing
parser.problemReporter().interfaceCannotHaveConstructors((ConstructorDeclaration) am);
break;
case TypeDeclaration.ANNOTATION_TYPE_DECL :
// report the problem and continue the parsing
parser.problemReporter().annotationTypeDeclarationCannotHaveConstructor((ConstructorDeclaration) am);
break;
}
hasConstructor = true;
}
}
}
}
return hasConstructor;
}
@Override
public CompilationResult compilationResult() {
return this.compilationResult;
}
public ConstructorDeclaration createDefaultConstructorForRecord(boolean needExplicitConstructorCall, boolean needToInsert) {
//Add to method'set, the default constuctor that just recall the
//super constructor with no arguments
//The arguments' type will be positionned by the TC so just use
//the default int instead of just null (consistency purpose)
ConstructorDeclaration constructor = new ConstructorDeclaration(this.compilationResult);
constructor.bits |= ASTNode.IsCanonicalConstructor | ASTNode.IsImplicit;
constructor.selector = this.name;
constructor.modifiers = this.modifiers & ExtraCompilerModifiers.AccVisibilityMASK;
// constructor.modifiers = this.modifiers & ClassFileConstants.AccPublic;
// constructor.modifiers |= ClassFileConstants.AccPublic; // JLS 14 8.10.5
constructor.arguments = getArgumentsFromComponents(this.recordComponents);
for (Argument argument : constructor.arguments) {
if ((argument.bits & ASTNode.HasTypeAnnotations) != 0) {
constructor.bits |= ASTNode.HasTypeAnnotations;
break;
}
}
constructor.declarationSourceStart = constructor.sourceStart =
constructor.bodyStart = this.sourceStart;
constructor.declarationSourceEnd =
constructor.sourceEnd = constructor.bodyEnd = this.sourceStart - 1;
//the super call inside the constructor
if (needExplicitConstructorCall) {
constructor.constructorCall = SuperReference.implicitSuperConstructorCall();
constructor.constructorCall.sourceStart = this.sourceStart;
constructor.constructorCall.sourceEnd = this.sourceEnd;
}
/* The body of the implicitly declared canonical constructor initializes each field corresponding
* to a record component with the corresponding formal parameter in the order that they appear
* in the record component list.*/
List<Statement> statements = new ArrayList<>();
int l = this.recordComponents != null ? this.recordComponents.length : 0;
if (l > 0 && this.fields != null) {
List<String> fNames = Arrays.stream(this.fields)
.filter(f -> f.isARecordComponent)
.map(f ->new String(f.name))
.collect(Collectors.toList());
for (int i = 0; i < l; ++i) {
RecordComponent component = this.recordComponents[i];
if (!fNames.contains(new String(component.name)))
continue;
FieldReference lhs = new FieldReference(component.name, 0);
lhs.receiver = ThisReference.implicitThis();
statements.add(new Assignment(lhs, new SingleNameReference(component.name, 0), 0));
}
}
constructor.statements = statements.toArray(new Statement[0]);
//adding the constructor in the methods list: rank is not critical since bindings will be sorted
if (needToInsert) {
if (this.methods == null) {
this.methods = new AbstractMethodDeclaration[] { constructor };
} else {
AbstractMethodDeclaration[] newMethods;
System.arraycopy(
this.methods,
0,
newMethods = new AbstractMethodDeclaration[this.methods.length + 1],
1,
this.methods.length);
newMethods[0] = constructor;
this.methods = newMethods;
}
}
return constructor;
}
private Argument[] getArgumentsFromComponents(RecordComponent[] comps) {
Argument[] args2 = comps == null || comps.length == 0 ? ASTNode.NO_ARGUMENTS :
new Argument[comps.length];
int count = 0;
for (RecordComponent comp : comps) {
Argument argument = new Argument(comp.name, ((long)comp.sourceStart) << 32 | comp.sourceEnd,
comp.type, 0); // no modifiers allowed for record components - enforce
args2[count++] = argument;
}
return args2;
}
public ConstructorDeclaration createDefaultConstructor( boolean needExplicitConstructorCall, boolean needToInsert) {
if (this.isRecord())
return createDefaultConstructorForRecord(needExplicitConstructorCall, needToInsert);
//Add to method'set, the default constuctor that just recall the
//super constructor with no arguments
//The arguments' type will be positionned by the TC so just use
//the default int instead of just null (consistency purpose)
//the constructor
ConstructorDeclaration constructor = new ConstructorDeclaration(this.compilationResult);
constructor.bits |= ASTNode.IsDefaultConstructor;
constructor.selector = this.name;
constructor.modifiers = this.modifiers & ExtraCompilerModifiers.AccVisibilityMASK;
//if you change this setting, please update the
//SourceIndexer2.buildTypeDeclaration(TypeDeclaration,char[]) method
constructor.declarationSourceStart = constructor.sourceStart = this.sourceStart;
constructor.declarationSourceEnd =
constructor.sourceEnd = constructor.bodyEnd = this.sourceEnd;
//the super call inside the constructor
if (needExplicitConstructorCall) {
constructor.constructorCall = SuperReference.implicitSuperConstructorCall();
constructor.constructorCall.sourceStart = this.sourceStart;
constructor.constructorCall.sourceEnd = this.sourceEnd;
}
//adding the constructor in the methods list: rank is not critical since bindings will be sorted
if (needToInsert) {
if (this.methods == null) {
this.methods = new AbstractMethodDeclaration[] { constructor };
} else {
AbstractMethodDeclaration[] newMethods;
System.arraycopy(
this.methods,
0,
newMethods = new AbstractMethodDeclaration[this.methods.length + 1],
1,
this.methods.length);
newMethods[0] = constructor;
this.methods = newMethods;
}
}
return constructor;
}
// anonymous type constructor creation: rank is important since bindings already got sorted
public MethodBinding createDefaultConstructorWithBinding(MethodBinding inheritedConstructorBinding, boolean eraseThrownExceptions) {
//Add to method'set, the default constuctor that just recall the
//super constructor with the same arguments
String baseName = "$anonymous"; //$NON-NLS-1$
TypeBinding[] argumentTypes = inheritedConstructorBinding.parameters;
int argumentsLength = argumentTypes.length;
//the constructor
ConstructorDeclaration constructor = new ConstructorDeclaration(this.compilationResult);
constructor.selector = new char[] { 'x' }; //no maining
constructor.sourceStart = this.sourceStart;
constructor.sourceEnd = this.sourceEnd;
int newModifiers = this.modifiers & ExtraCompilerModifiers.AccVisibilityMASK;
if (inheritedConstructorBinding.isVarargs()) {
newModifiers |= ClassFileConstants.AccVarargs;
}
constructor.modifiers = newModifiers;
constructor.bits |= ASTNode.IsDefaultConstructor;
if (argumentsLength > 0) {
Argument[] arguments = (constructor.arguments = new Argument[argumentsLength]);
for (int i = argumentsLength; --i >= 0;) {
arguments[i] = new Argument((baseName + i).toCharArray(), 0L, null /*type ref*/, ClassFileConstants.AccDefault);
}
}
//the super call inside the constructor
constructor.constructorCall = SuperReference.implicitSuperConstructorCall();
constructor.constructorCall.sourceStart = this.sourceStart;
constructor.constructorCall.sourceEnd = this.sourceEnd;
if (argumentsLength > 0) {
Expression[] args1;
args1 = constructor.constructorCall.arguments = new Expression[argumentsLength];
for (int i = argumentsLength; --i >= 0;) {
args1[i] = new SingleNameReference((baseName + i).toCharArray(), 0L);
}
}
//adding the constructor in the methods list
if (this.methods == null) {
this.methods = new AbstractMethodDeclaration[] { constructor };
} else {
AbstractMethodDeclaration[] newMethods;
System.arraycopy(this.methods, 0, newMethods = new AbstractMethodDeclaration[this.methods.length + 1], 1, this.methods.length);
newMethods[0] = constructor;
this.methods = newMethods;
}
//============BINDING UPDATE==========================
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=277643, align with javac on JLS 15.12.2.6
ReferenceBinding[] thrownExceptions = eraseThrownExceptions
? this.scope.environment().convertToRawTypes(inheritedConstructorBinding.thrownExceptions, true, true)
: inheritedConstructorBinding.thrownExceptions;
SourceTypeBinding sourceType = this.binding;
constructor.binding = new MethodBinding(
constructor.modifiers, //methodDeclaration
argumentsLength == 0 ? Binding.NO_PARAMETERS : argumentTypes, //arguments bindings
thrownExceptions, //exceptions
sourceType); //declaringClass
constructor.binding.tagBits |= (inheritedConstructorBinding.tagBits & TagBits.HasMissingType);
constructor.binding.modifiers |= ExtraCompilerModifiers.AccIsDefaultConstructor;
if (inheritedConstructorBinding.parameterFlowBits != null // this implies that annotation based null/resource analysis is enabled
&& argumentsLength > 0)
{
// copy flowbits from inherited constructor to the new constructor:
int len = inheritedConstructorBinding.parameterFlowBits.length;
System.arraycopy(inheritedConstructorBinding.parameterFlowBits, 0,
constructor.binding.parameterFlowBits = new byte[len], 0, len);
}
// TODO(stephan): do argument types already carry sufficient info about type annotations?
constructor.scope = new MethodScope(this.scope, constructor, true);
constructor.bindArguments();
constructor.constructorCall.resolve(constructor.scope);
MethodBinding[] methodBindings = sourceType.methods(); // trigger sorting
int length;
System.arraycopy(methodBindings, 0, methodBindings = new MethodBinding[(length = methodBindings.length) + 1], 1, length);
methodBindings[0] = constructor.binding;
if (++length > 1)
ReferenceBinding.sortMethods(methodBindings, 0, length); // need to resort, since could be valid methods ahead (140643) - DOM needs eager sorting
sourceType.setMethods(methodBindings);
//===================================================
return constructor.binding;
}
/**
* Find the matching parse node, answers null if nothing found
*/
public FieldDeclaration declarationOf(FieldBinding fieldBinding) {
if (fieldBinding != null && this.fields != null) {
for (FieldDeclaration field : this.fields) {
FieldDeclaration fieldDecl;
if ((fieldDecl = field).binding == fieldBinding)
return fieldDecl;
}
}
return null;
}
/**
* Find the matching parse node, answers null if nothing found
*/
public TypeDeclaration declarationOf(MemberTypeBinding memberTypeBinding) {
if (memberTypeBinding != null && this.memberTypes != null) {
for (TypeDeclaration memberType : this.memberTypes) {
TypeDeclaration memberTypeDecl;
if (TypeBinding.equalsEquals((memberTypeDecl = memberType).binding, memberTypeBinding))
return memberTypeDecl;
}
}
return null;
}
/**
* Find the matching parse node, answers null if nothing found
*/
public AbstractMethodDeclaration declarationOf(MethodBinding methodBinding) {
if (methodBinding != null && this.methods != null) {
for (AbstractMethodDeclaration method : this.methods) {
AbstractMethodDeclaration methodDecl;
if ((methodDecl = method).binding == methodBinding)
return methodDecl;
}
}
return null;
}
/**
* Find the matching parse node, answers null if nothing found
*/
public RecordComponent declarationOf(RecordComponentBinding recordComponentBinding) {
if (recordComponentBinding != null && this.recordComponents != null) {
for (RecordComponent recordComponent : this.recordComponents) {
if (recordComponent.binding == recordComponentBinding)
return recordComponent;
}
}
return null;
}
/**
* Finds the matching type amoung this type's member types.
* Returns null if no type with this name is found.
* The type name is a compound name relative to this type
* e.g. if this type is X and we're looking for Y.X.A.B
* then a type name would be {X, A, B}
*/
public TypeDeclaration declarationOfType(char[][] typeName) {
int typeNameLength = typeName.length;
if (typeNameLength < 1 || !CharOperation.equals(typeName[0], this.name)) {
return null;
}
if (typeNameLength == 1) {
return this;
}
char[][] subTypeName = new char[typeNameLength - 1][];
System.arraycopy(typeName, 1, subTypeName, 0, typeNameLength - 1);
for (TypeDeclaration memberType : this.memberTypes) {
TypeDeclaration typeDecl = memberType.declarationOfType(subTypeName);
if (typeDecl != null) {
return typeDecl;
}
}
return null;
}
@Override
public CompilationUnitDeclaration getCompilationUnitDeclaration() {
if (this.scope != null) {
return this.scope.compilationUnitScope().referenceContext;
}
return null;
}
/**
* This is applicable only for records - ideally get the canonical constructor, if not
* get a constructor and at the client side tentatively marked as canonical constructor
* which gets checked at the binding time. If there are no constructors, then null is returned.
**/
public ConstructorDeclaration getConstructor(Parser parser) {
ConstructorDeclaration cd = null;
if (this.methods != null) {
for (int i = this.methods.length; --i >= 0;) {
AbstractMethodDeclaration am;
if ((am = this.methods[i]).isConstructor()) {
if (!CharOperation.equals(am.selector, this.name)) {
// the constructor was in fact a method with no return type
// unless an explicit constructor call was supplied
ConstructorDeclaration c = (ConstructorDeclaration) am;
if (c.constructorCall == null || c.constructorCall.isImplicitSuper()) { //changed to a method
MethodDeclaration m = parser.convertToMethodDeclaration(c, this.compilationResult);
this.methods[i] = m;
}
} else {
if (am instanceof CompactConstructorDeclaration) {
CompactConstructorDeclaration ccd = (CompactConstructorDeclaration) am;
ccd.recordDeclaration = this;
if (ccd.arguments == null)
ccd.arguments = getArgumentsFromComponents(this.recordComponents);
return ccd;
}
// now we are looking at a "normal" constructor
if ((this.recordComponents == null || this.recordComponents.length == 0)
&& am.arguments == null)
return (ConstructorDeclaration) am;
cd = (ConstructorDeclaration) am; // just return the last constructor
}
}
}
}
// /* At this point we can only say that there is high possibility that there is a constructor
// * If it is a CCD, then definitely it is there (except for empty one); else we need to check
// * the bindings to say that there is a canonical constructor. To take care at binding resolution time.
// */
return cd; // the last constructor
}
/**
* Generic bytecode generation for type
*/
public void generateCode(ClassFile enclosingClassFile) {
if ((this.bits & ASTNode.HasBeenGenerated) != 0)
return;
this.bits |= ASTNode.HasBeenGenerated;
if (this.ignoreFurtherInvestigation) {
if (this.binding == null)
return;
ClassFile.createProblemType(
this,
this.scope.referenceCompilationUnit().compilationResult);
return;
}
try {
// create the result for a compiled type
ClassFile classFile = ClassFile.getNewInstance(this.binding);
classFile.initialize(this.binding, enclosingClassFile, false);
if (this.binding.isMemberType()) {
classFile.recordInnerClasses(this.binding);
} else if (this.binding.isLocalType()) {
enclosingClassFile.recordInnerClasses(this.binding);
classFile.recordInnerClasses(this.binding);
}
SourceTypeBinding nestHost = this.binding.getNestHost();
if (nestHost != null && !TypeBinding.equalsEquals(nestHost, this.binding)) {
ClassFile ocf = enclosingClassFile.outerMostEnclosingClassFile();
if (ocf != null)
ocf.recordNestMember(this.binding);
}
TypeVariableBinding[] typeVariables = this.binding.typeVariables();
for (TypeVariableBinding typeVariableBinding : typeVariables) {
if ((typeVariableBinding.tagBits & TagBits.ContainsNestedTypeReferences) != 0) {
Util.recordNestedType(classFile, typeVariableBinding);
}
}
// generate all fiels
classFile.addFieldInfos();
if (this.memberTypes != null) {
for (TypeDeclaration memberType : this.memberTypes) {
classFile.recordInnerClasses(memberType.binding);
memberType.generateCode(this.scope, classFile);
}
}
// generate all methods
classFile.setForMethodInfos();
if (this.methods != null) {
for (AbstractMethodDeclaration method : this.methods) {
method.generateCode(this.scope, classFile);
}
}
// generate all synthetic and abstract methods
classFile.addSpecialMethods(this);
if (this.ignoreFurtherInvestigation) { // trigger problem type generation for code gen errors
throw new AbortType(this.scope.referenceCompilationUnit().compilationResult, null);
}
// finalize the compiled type result
classFile.addAttributes();
this.scope.referenceCompilationUnit().compilationResult.record(
this.binding.constantPoolName(),
classFile);
} catch (AbortType e) {
if (this.binding == null)
return;
ClassFile.createProblemType(
this,
this.scope.referenceCompilationUnit().compilationResult);
}
}
/**
* Bytecode generation for a local inner type (API as a normal statement code gen)
*/
@Override
public void generateCode(BlockScope blockScope, CodeStream codeStream) {
if ((this.bits & ASTNode.IsReachable) == 0) {
return;
}
if ((this.bits & ASTNode.HasBeenGenerated) != 0) return;
int pc = codeStream.position;
if (this.binding != null) {
SyntheticArgumentBinding[] enclosingInstances = ((NestedTypeBinding) this.binding).syntheticEnclosingInstances();
for (int i = 0, slotSize = 0, count = enclosingInstances == null ? 0 : enclosingInstances.length; i < count; i++){
SyntheticArgumentBinding enclosingInstance = enclosingInstances[i];
enclosingInstance.resolvedPosition = ++slotSize; // shift by 1 to leave room for aload0==this
if (slotSize > 0xFF) { // no more than 255 words of arguments
blockScope.problemReporter().noMoreAvailableSpaceForArgument(enclosingInstance, blockScope.referenceType());
}
}
}
generateCode(codeStream.classFile);
codeStream.recordPositionsFrom(pc, this.sourceStart);
}
/**
* Bytecode generation for a member inner type
*/
public void generateCode(ClassScope classScope, ClassFile enclosingClassFile) {
if ((this.bits & ASTNode.HasBeenGenerated) != 0) return;
if (this.binding != null) {
SyntheticArgumentBinding[] enclosingInstances = ((NestedTypeBinding) this.binding).syntheticEnclosingInstances();
for (int i = 0, slotSize = 0, count = enclosingInstances == null ? 0 : enclosingInstances.length; i < count; i++){
SyntheticArgumentBinding enclosingInstance = enclosingInstances[i];
enclosingInstance.resolvedPosition = ++slotSize; // shift by 1 to leave room for aload0==this
if (slotSize > 0xFF) { // no more than 255 words of arguments
classScope.problemReporter().noMoreAvailableSpaceForArgument(enclosingInstance, classScope.referenceType());
}
}
}
generateCode(enclosingClassFile);
}
/**
* Bytecode generation for a package member
*/
public void generateCode(CompilationUnitScope unitScope) {
generateCode((ClassFile) null);
}
@Override
public boolean hasErrors() {
return this.ignoreFurtherInvestigation;
}
/**
* Common flow analysis for all types
*/
private void internalAnalyseCode(FlowContext flowContext, FlowInfo flowInfo) {
if (CharOperation.equals(this.name, TypeConstants.YIELD)) {
this.scope.problemReporter().validateRestrictedKeywords(this.name, this);
}
if (!this.binding.isUsed() && this.binding.isOrEnclosedByPrivateType()) {
if (!this.scope.referenceCompilationUnit().compilationResult.hasSyntaxError) {
this.scope.problemReporter().unusedPrivateType(this);
}
}
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=385780
if (this.typeParameters != null &&
!this.scope.referenceCompilationUnit().compilationResult.hasSyntaxError) {
for (TypeParameter typeParameter : this.typeParameters) {
if ((typeParameter.binding.modifiers & ExtraCompilerModifiers.AccLocallyUsed) == 0) {
this.scope.problemReporter().unusedTypeParameter(typeParameter);
}
}
}
boolean useOwningAnnotations = this.scope.compilerOptions().isAnnotationBasedResourceAnalysisEnabled;
boolean isCloseable = this.binding.hasTypeBit(TypeIds.BitAutoCloseable|TypeIds.BitCloseable);
FieldDeclaration fieldNeedingClose = null;
// for local classes we use the flowContext as our parent, but never use an initialization context for this purpose
// see Bug 360328 - [compiler][null] detect null problems in nested code (local class inside a loop)
FlowContext parentContext = (flowContext instanceof InitializationFlowContext) ? null : flowContext;
InitializationFlowContext initializerContext = new InitializationFlowContext(parentContext, this, flowInfo, flowContext, this.initializerScope);
// no static initializer in local classes, thus no need to set parent:
InitializationFlowContext staticInitializerContext = new InitializationFlowContext(null, this, flowInfo, flowContext, this.staticInitializerScope);
FlowInfo nonStaticFieldInfo = flowInfo.unconditionalFieldLessCopy();
FlowInfo staticFieldInfo = flowInfo.unconditionalFieldLessCopy();
if (this.fields != null) {
for (FieldDeclaration field : this.fields) {
if (field.isStatic()) {
if ((staticFieldInfo.tagBits & FlowInfo.UNREACHABLE_OR_DEAD) != 0)
field.bits &= ~ASTNode.IsReachable;
/*if (field.isField()){
staticInitializerContext.handledExceptions = NoExceptions; // no exception is allowed jls8.3.2
} else {*/
staticInitializerContext.handledExceptions = Binding.ANY_EXCEPTION; // tolerate them all, and record them
/*}*/
staticFieldInfo = field.analyseCode(this.staticInitializerScope, staticInitializerContext, staticFieldInfo);
// in case the initializer is not reachable, use a reinitialized flowInfo and enter a fake reachable
// branch, since the previous initializer already got the blame.
if (staticFieldInfo == FlowInfo.DEAD_END) {
this.staticInitializerScope.problemReporter().initializerMustCompleteNormally(field);
staticFieldInfo = FlowInfo.initial(this.maxFieldCount).setReachMode(FlowInfo.UNREACHABLE_OR_DEAD);
}
} else {
if ((nonStaticFieldInfo.tagBits & FlowInfo.UNREACHABLE_OR_DEAD) != 0)
field.bits &= ~ASTNode.IsReachable;
/*if (field.isField()){
initializerContext.handledExceptions = NoExceptions; // no exception is allowed jls8.3.2
} else {*/
initializerContext.handledExceptions = Binding.ANY_EXCEPTION; // tolerate them all, and record them
/*}*/
nonStaticFieldInfo = field.analyseCode(this.initializerScope, initializerContext, nonStaticFieldInfo);
// in case the initializer is not reachable, use a reinitialized flowInfo and enter a fake reachable
// branch, since the previous initializer already got the blame.
if (nonStaticFieldInfo == FlowInfo.DEAD_END) {
this.initializerScope.problemReporter().initializerMustCompleteNormally(field);
nonStaticFieldInfo = FlowInfo.initial(this.maxFieldCount).setReachMode(FlowInfo.UNREACHABLE_OR_DEAD);
}
if (fieldNeedingClose == null && useOwningAnnotations && isCloseable && (field.binding.tagBits & TagBits.AnnotationOwning) != 0) {
fieldNeedingClose = field;
}
}
}
}
if (this.memberTypes != null) {
for (TypeDeclaration memberType : this.memberTypes) {
if (flowContext != null){ // local type
memberType.analyseCode(this.scope, flowContext, nonStaticFieldInfo.copy().setReachMode(flowInfo.reachMode())); // reset reach mode in case initializers did abrupt completely
} else {
memberType.analyseCode(this.scope);
}
}
}
if (this.scope.compilerOptions().complianceLevel >= ClassFileConstants.JDK9) {
// synthesize <clinit> if one is not present. Required to initialize
// synthetic final fields as modifying final fields outside of a <clinit>
// is disallowed in Java 9
if (this.methods == null || !this.methods[0].isClinit()) {
Clinit clinit = new Clinit(this.compilationResult);
clinit.declarationSourceStart = clinit.sourceStart = this.sourceStart;
clinit.declarationSourceEnd = clinit.sourceEnd = this.sourceEnd;
clinit.bodyEnd = this.sourceEnd;
int length = this.methods == null ? 0 : this.methods.length;
AbstractMethodDeclaration[] methodDeclarations = new AbstractMethodDeclaration[length + 1];
methodDeclarations[0] = clinit;
if (this.methods != null)
System.arraycopy(this.methods, 0, methodDeclarations, 1, length);
}
}
if (this.methods != null) {
UnconditionalFlowInfo outerInfo = flowInfo.unconditionalFieldLessCopy();
FlowInfo constructorInfo = nonStaticFieldInfo.unconditionalInits().discardNonFieldInitializations().addInitializationsFrom(outerInfo);
SimpleSetOfCharArray jUnitMethodSourceValues = getJUnitMethodSourceValues();
for (AbstractMethodDeclaration method : this.methods) {
if (method.ignoreFurtherInvestigation)
continue;
if (method.isInitializationMethod()) {
// pass down the appropriate initializerContext:
if (method.isStatic()) { // <clinit>
((Clinit)method).analyseCode(
this.scope,
staticInitializerContext,
staticFieldInfo.unconditionalInits().discardNonFieldInitializations().addInitializationsFrom(outerInfo));
} else { // constructor
((ConstructorDeclaration)method).analyseCode(this.scope, initializerContext, constructorInfo.copy(), flowInfo.reachMode());
}
} else { // regular method
// JUnit 5 only accepts methods without arguments for method sources
if (method.arguments == null && jUnitMethodSourceValues.includes(method.selector) && method.binding != null) {
method.binding.modifiers |= ExtraCompilerModifiers.AccLocallyUsed;
}
// pass down the parentContext (NOT an initializer context, see above):
((MethodDeclaration)method).analyseCode(this.scope, parentContext, flowInfo.copy());
if (fieldNeedingClose != null && CharOperation.equals(TypeConstants.CLOSE, method.selector) && method.arguments == null) {
fieldNeedingClose = null;
}
}
}
}
if (fieldNeedingClose != null) {
this.scope.problemReporter().missingImplementationOfClose(fieldNeedingClose);
}
// enable enum support ?
if (this.binding.isEnum() && !this.binding.isAnonymousType()) {
this.enumValuesSyntheticfield = this.binding.addSyntheticFieldForEnumValues();
}
}
private SimpleSetOfCharArray getJUnitMethodSourceValues() {
SimpleSetOfCharArray junitMethodSourceValues = new SimpleSetOfCharArray();
for (AbstractMethodDeclaration methodDeclaration : this.methods) {
if (methodDeclaration.annotations != null) {
for (Annotation annotation : methodDeclaration.annotations) {
if (annotation.resolvedType != null && annotation.resolvedType.id == TypeIds.T_OrgJunitJupiterParamsProviderMethodSource) {
addJUnitMethodSourceValues(junitMethodSourceValues, annotation, methodDeclaration.selector);
}
}
}
}
return junitMethodSourceValues;
}
private void addJUnitMethodSourceValues(SimpleSetOfCharArray junitMethodSourceValues, Annotation annotation, char[] methodName) {
for (MemberValuePair memberValuePair : annotation.memberValuePairs()) {
if (CharOperation.equals(memberValuePair.name, TypeConstants.VALUE)) {
Expression value = memberValuePair.value;
if (value instanceof ArrayInitializer) { // e.g. @MethodSource({ "someMethod" })
ArrayInitializer arrayInitializer = (ArrayInitializer) value;
for (Expression arrayValue : arrayInitializer.expressions) {
junitMethodSourceValues.add(getValueAsChars(arrayValue));
}
} else {
junitMethodSourceValues.add(getValueAsChars(value));
}
return;