-
Notifications
You must be signed in to change notification settings - Fork 5.4k
/
Attr.java
5860 lines (5300 loc) · 257 KB
/
Attr.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) 1999, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.comp;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import javax.lang.model.element.ElementKind;
import javax.tools.JavaFileObject;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.TreeVisitor;
import com.sun.source.util.SimpleTreeVisitor;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Lint.LintCategory;
import com.sun.tools.javac.code.Scope.WriteableScope;
import com.sun.tools.javac.code.Source.Feature;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.code.Type.*;
import com.sun.tools.javac.code.TypeMetadata.Annotations;
import com.sun.tools.javac.code.Types.FunctionDescriptorLookupError;
import com.sun.tools.javac.comp.ArgumentAttr.LocalCacheContext;
import com.sun.tools.javac.comp.Check.CheckContext;
import com.sun.tools.javac.comp.DeferredAttr.AttrMode;
import com.sun.tools.javac.comp.MatchBindingsComputer.MatchBindings;
import com.sun.tools.javac.jvm.*;
import static com.sun.tools.javac.resources.CompilerProperties.Fragments.Diamond;
import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArg;
import static com.sun.tools.javac.resources.CompilerProperties.Fragments.DiamondInvalidArgs;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.resources.CompilerProperties.Fragments;
import com.sun.tools.javac.resources.CompilerProperties.Warnings;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.DefinedBy.Api;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javac.util.JCDiagnostic.Error;
import com.sun.tools.javac.util.JCDiagnostic.Fragment;
import com.sun.tools.javac.util.JCDiagnostic.Warning;
import com.sun.tools.javac.util.List;
import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javac.code.Flags.ANNOTATION;
import static com.sun.tools.javac.code.Flags.BLOCK;
import static com.sun.tools.javac.code.Kinds.*;
import static com.sun.tools.javac.code.Kinds.Kind.*;
import static com.sun.tools.javac.code.TypeTag.*;
import static com.sun.tools.javac.code.TypeTag.WILDCARD;
import static com.sun.tools.javac.tree.JCTree.Tag.*;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
/** This is the main context-dependent analysis phase in GJC. It
* encompasses name resolution, type checking and constant folding as
* subtasks. Some subtasks involve auxiliary classes.
* @see Check
* @see Resolve
* @see ConstFold
* @see Infer
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class Attr extends JCTree.Visitor {
protected static final Context.Key<Attr> attrKey = new Context.Key<>();
final Names names;
final Log log;
final Symtab syms;
final Resolve rs;
final Operators operators;
final Infer infer;
final Analyzer analyzer;
final DeferredAttr deferredAttr;
final Check chk;
final Flow flow;
final MemberEnter memberEnter;
final TypeEnter typeEnter;
final TreeMaker make;
final ConstFold cfolder;
final Enter enter;
final Target target;
final Types types;
final Preview preview;
final JCDiagnostic.Factory diags;
final TypeAnnotations typeAnnotations;
final DeferredLintHandler deferredLintHandler;
final TypeEnvs typeEnvs;
final Dependencies dependencies;
final Annotate annotate;
final ArgumentAttr argumentAttr;
final MatchBindingsComputer matchBindingsComputer;
final AttrRecover attrRecover;
public static Attr instance(Context context) {
Attr instance = context.get(attrKey);
if (instance == null)
instance = new Attr(context);
return instance;
}
protected Attr(Context context) {
context.put(attrKey, this);
names = Names.instance(context);
log = Log.instance(context);
syms = Symtab.instance(context);
rs = Resolve.instance(context);
operators = Operators.instance(context);
chk = Check.instance(context);
flow = Flow.instance(context);
memberEnter = MemberEnter.instance(context);
typeEnter = TypeEnter.instance(context);
make = TreeMaker.instance(context);
enter = Enter.instance(context);
infer = Infer.instance(context);
analyzer = Analyzer.instance(context);
deferredAttr = DeferredAttr.instance(context);
cfolder = ConstFold.instance(context);
target = Target.instance(context);
types = Types.instance(context);
preview = Preview.instance(context);
diags = JCDiagnostic.Factory.instance(context);
annotate = Annotate.instance(context);
typeAnnotations = TypeAnnotations.instance(context);
deferredLintHandler = DeferredLintHandler.instance(context);
typeEnvs = TypeEnvs.instance(context);
dependencies = Dependencies.instance(context);
argumentAttr = ArgumentAttr.instance(context);
matchBindingsComputer = MatchBindingsComputer.instance(context);
attrRecover = AttrRecover.instance(context);
Options options = Options.instance(context);
Source source = Source.instance(context);
allowPoly = Feature.POLY.allowedInSource(source);
allowTypeAnnos = Feature.TYPE_ANNOTATIONS.allowedInSource(source);
allowLambda = Feature.LAMBDA.allowedInSource(source);
allowDefaultMethods = Feature.DEFAULT_METHODS.allowedInSource(source);
allowStaticInterfaceMethods = Feature.STATIC_INTERFACE_METHODS.allowedInSource(source);
allowReifiableTypesInInstanceof =
Feature.REIFIABLE_TYPES_INSTANCEOF.allowedInSource(source) &&
(!preview.isPreview(Feature.REIFIABLE_TYPES_INSTANCEOF) || preview.isEnabled());
allowRecords = Feature.RECORDS.allowedInSource(source);
sourceName = source.name;
useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning");
statInfo = new ResultInfo(KindSelector.NIL, Type.noType);
varAssignmentInfo = new ResultInfo(KindSelector.ASG, Type.noType);
unknownExprInfo = new ResultInfo(KindSelector.VAL, Type.noType);
methodAttrInfo = new MethodAttrInfo();
unknownTypeInfo = new ResultInfo(KindSelector.TYP, Type.noType);
unknownTypeExprInfo = new ResultInfo(KindSelector.VAL_TYP, Type.noType);
recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext);
}
/** Switch: support target-typing inference
*/
boolean allowPoly;
/** Switch: support type annotations.
*/
boolean allowTypeAnnos;
/** Switch: support lambda expressions ?
*/
boolean allowLambda;
/** Switch: support default methods ?
*/
boolean allowDefaultMethods;
/** Switch: static interface methods enabled?
*/
boolean allowStaticInterfaceMethods;
/** Switch: reifiable types in instanceof enabled?
*/
boolean allowReifiableTypesInInstanceof;
/** Are records allowed
*/
private final boolean allowRecords;
/**
* Switch: warn about use of variable before declaration?
* RFE: 6425594
*/
boolean useBeforeDeclarationWarning;
/**
* Switch: name of source level; used for error reporting.
*/
String sourceName;
/** Check kind and type of given tree against protokind and prototype.
* If check succeeds, store type in tree and return it.
* If check fails, store errType in tree and return it.
* No checks are performed if the prototype is a method type.
* It is not necessary in this case since we know that kind and type
* are correct.
*
* @param tree The tree whose kind and type is checked
* @param found The computed type of the tree
* @param ownkind The computed kind of the tree
* @param resultInfo The expected result of the tree
*/
Type check(final JCTree tree,
final Type found,
final KindSelector ownkind,
final ResultInfo resultInfo) {
InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext();
Type owntype;
boolean shouldCheck = !found.hasTag(ERROR) &&
!resultInfo.pt.hasTag(METHOD) &&
!resultInfo.pt.hasTag(FORALL);
if (shouldCheck && !ownkind.subset(resultInfo.pkind)) {
log.error(tree.pos(),
Errors.UnexpectedType(resultInfo.pkind.kindNames(),
ownkind.kindNames()));
owntype = types.createErrorType(found);
} else if (allowPoly && inferenceContext.free(found)) {
//delay the check if there are inference variables in the found type
//this means we are dealing with a partially inferred poly expression
owntype = shouldCheck ? resultInfo.pt : found;
if (resultInfo.checkMode.installPostInferenceHook()) {
inferenceContext.addFreeTypeListener(List.of(found),
instantiatedContext -> {
ResultInfo pendingResult =
resultInfo.dup(inferenceContext.asInstType(resultInfo.pt));
check(tree, inferenceContext.asInstType(found), ownkind, pendingResult);
});
}
} else {
owntype = shouldCheck ?
resultInfo.check(tree, found) :
found;
}
if (resultInfo.checkMode.updateTreeType()) {
tree.type = owntype;
}
return owntype;
}
/** Is given blank final variable assignable, i.e. in a scope where it
* may be assigned to even though it is final?
* @param v The blank final variable.
* @param env The current environment.
*/
boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) {
Symbol owner = env.info.scope.owner;
// owner refers to the innermost variable, method or
// initializer block declaration at this point.
boolean isAssignable =
v.owner == owner
||
((owner.name == names.init || // i.e. we are in a constructor
owner.kind == VAR || // i.e. we are in a variable initializer
(owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block
&&
v.owner == owner.owner
&&
((v.flags() & STATIC) != 0) == Resolve.isStatic(env));
boolean insideCompactConstructor = env.enclMethod != null && TreeInfo.isCompactConstructor(env.enclMethod);
return isAssignable & !insideCompactConstructor;
}
/** Check that variable can be assigned to.
* @param pos The current source code position.
* @param v The assigned variable
* @param base If the variable is referred to in a Select, the part
* to the left of the `.', null otherwise.
* @param env The current environment.
*/
void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) {
if (v.name == names._this) {
log.error(pos, Errors.CantAssignValToThis);
} else if ((v.flags() & FINAL) != 0 &&
((v.flags() & HASINIT) != 0
||
!((base == null ||
TreeInfo.isThisQualifier(base)) &&
isAssignableAsBlankFinal(v, env)))) {
if (v.isResourceVariable()) { //TWR resource
log.error(pos, Errors.TryResourceMayNotBeAssigned(v));
} else {
log.error(pos, Errors.CantAssignValToFinalVar(v));
}
}
}
/** Does tree represent a static reference to an identifier?
* It is assumed that tree is either a SELECT or an IDENT.
* We have to weed out selects from non-type names here.
* @param tree The candidate tree.
*/
boolean isStaticReference(JCTree tree) {
if (tree.hasTag(SELECT)) {
Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected);
if (lsym == null || lsym.kind != TYP) {
return false;
}
}
return true;
}
/** Is this symbol a type?
*/
static boolean isType(Symbol sym) {
return sym != null && sym.kind == TYP;
}
/** The current `this' symbol.
* @param env The current environment.
*/
Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) {
return rs.resolveSelf(pos, env, env.enclClass.sym, names._this);
}
/** Attribute a parsed identifier.
* @param tree Parsed identifier name
* @param topLevel The toplevel to use
*/
public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) {
Env<AttrContext> localEnv = enter.topLevelEnv(topLevel);
localEnv.enclClass = make.ClassDef(make.Modifiers(0),
syms.errSymbol.name,
null, null, null, null);
localEnv.enclClass.sym = syms.errSymbol;
return attribIdent(tree, localEnv);
}
/** Attribute a parsed identifier.
* @param tree Parsed identifier name
* @param env The env to use
*/
public Symbol attribIdent(JCTree tree, Env<AttrContext> env) {
return tree.accept(identAttributer, env);
}
// where
private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer();
private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> {
@Override @DefinedBy(Api.COMPILER_TREE)
public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) {
Symbol site = visit(node.getExpression(), env);
if (site.kind == ERR || site.kind == ABSENT_TYP || site.kind == HIDDEN)
return site;
Name name = (Name)node.getIdentifier();
if (site.kind == PCK) {
env.toplevel.packge = (PackageSymbol)site;
return rs.findIdentInPackage(null, env, (TypeSymbol)site, name,
KindSelector.TYP_PCK);
} else {
env.enclClass.sym = (ClassSymbol)site;
return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site);
}
}
@Override @DefinedBy(Api.COMPILER_TREE)
public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) {
return rs.findIdent(null, env, (Name)node.getName(), KindSelector.TYP_PCK);
}
}
public Type coerce(Type etype, Type ttype) {
return cfolder.coerce(etype, ttype);
}
public Type attribType(JCTree node, TypeSymbol sym) {
Env<AttrContext> env = typeEnvs.get(sym);
Env<AttrContext> localEnv = env.dup(node, env.info.dup());
return attribTree(node, localEnv, unknownTypeInfo);
}
public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) {
// Attribute qualifying package or class.
JCFieldAccess s = (JCFieldAccess)tree.qualid;
return attribTree(s.selected, env,
new ResultInfo(tree.staticImport ?
KindSelector.TYP : KindSelector.TYP_PCK,
Type.noType));
}
public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) {
return attribToTree(expr, env, tree, unknownExprInfo);
}
public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) {
return attribToTree(stmt, env, tree, statInfo);
}
private Env<AttrContext> attribToTree(JCTree root, Env<AttrContext> env, JCTree tree, ResultInfo resultInfo) {
breakTree = tree;
JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
try {
deferredAttr.attribSpeculative(root, env, resultInfo,
null, DeferredAttr.AttributionMode.ATTRIB_TO_TREE,
argumentAttr.withLocalCacheContext());
attrRecover.doRecovery();
} catch (BreakAttr b) {
return b.env;
} catch (AssertionError ae) {
if (ae.getCause() instanceof BreakAttr) {
return ((BreakAttr)(ae.getCause())).env;
} else {
throw ae;
}
} finally {
breakTree = null;
log.useSource(prev);
}
return env;
}
private JCTree breakTree = null;
private static class BreakAttr extends RuntimeException {
static final long serialVersionUID = -6924771130405446405L;
private transient Env<AttrContext> env;
private BreakAttr(Env<AttrContext> env) {
this.env = env;
}
}
/**
* Mode controlling behavior of Attr.Check
*/
enum CheckMode {
NORMAL,
/**
* Mode signalling 'fake check' - skip tree update. A side-effect of this mode is
* that the captured var cache in {@code InferenceContext} will be used in read-only
* mode when performing inference checks.
*/
NO_TREE_UPDATE {
@Override
public boolean updateTreeType() {
return false;
}
},
/**
* Mode signalling that caller will manage free types in tree decorations.
*/
NO_INFERENCE_HOOK {
@Override
public boolean installPostInferenceHook() {
return false;
}
};
public boolean updateTreeType() {
return true;
}
public boolean installPostInferenceHook() {
return true;
}
}
class ResultInfo {
final KindSelector pkind;
final Type pt;
final CheckContext checkContext;
final CheckMode checkMode;
ResultInfo(KindSelector pkind, Type pt) {
this(pkind, pt, chk.basicHandler, CheckMode.NORMAL);
}
ResultInfo(KindSelector pkind, Type pt, CheckMode checkMode) {
this(pkind, pt, chk.basicHandler, checkMode);
}
protected ResultInfo(KindSelector pkind,
Type pt, CheckContext checkContext) {
this(pkind, pt, checkContext, CheckMode.NORMAL);
}
protected ResultInfo(KindSelector pkind,
Type pt, CheckContext checkContext, CheckMode checkMode) {
this.pkind = pkind;
this.pt = pt;
this.checkContext = checkContext;
this.checkMode = checkMode;
}
/**
* Should {@link Attr#attribTree} use the {@ArgumentAttr} visitor instead of this one?
* @param tree The tree to be type-checked.
* @return true if {@ArgumentAttr} should be used.
*/
protected boolean needsArgumentAttr(JCTree tree) { return false; }
protected Type check(final DiagnosticPosition pos, final Type found) {
return chk.checkType(pos, found, pt, checkContext);
}
protected ResultInfo dup(Type newPt) {
return new ResultInfo(pkind, newPt, checkContext, checkMode);
}
protected ResultInfo dup(CheckContext newContext) {
return new ResultInfo(pkind, pt, newContext, checkMode);
}
protected ResultInfo dup(Type newPt, CheckContext newContext) {
return new ResultInfo(pkind, newPt, newContext, checkMode);
}
protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) {
return new ResultInfo(pkind, newPt, newContext, newMode);
}
protected ResultInfo dup(CheckMode newMode) {
return new ResultInfo(pkind, pt, checkContext, newMode);
}
@Override
public String toString() {
if (pt != null) {
return pt.toString();
} else {
return "";
}
}
}
class MethodAttrInfo extends ResultInfo {
public MethodAttrInfo() {
this(chk.basicHandler);
}
public MethodAttrInfo(CheckContext checkContext) {
super(KindSelector.VAL, Infer.anyPoly, checkContext);
}
@Override
protected boolean needsArgumentAttr(JCTree tree) {
return true;
}
protected ResultInfo dup(Type newPt) {
throw new IllegalStateException();
}
protected ResultInfo dup(CheckContext newContext) {
return new MethodAttrInfo(newContext);
}
protected ResultInfo dup(Type newPt, CheckContext newContext) {
throw new IllegalStateException();
}
protected ResultInfo dup(Type newPt, CheckContext newContext, CheckMode newMode) {
throw new IllegalStateException();
}
protected ResultInfo dup(CheckMode newMode) {
throw new IllegalStateException();
}
}
class RecoveryInfo extends ResultInfo {
public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) {
this(deferredAttrContext, Type.recoveryType);
}
public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext, Type pt) {
super(KindSelector.VAL, pt, new Check.NestedCheckContext(chk.basicHandler) {
@Override
public DeferredAttr.DeferredAttrContext deferredAttrContext() {
return deferredAttrContext;
}
@Override
public boolean compatible(Type found, Type req, Warner warn) {
return true;
}
@Override
public void report(DiagnosticPosition pos, JCDiagnostic details) {
if (pt == Type.recoveryType) {
chk.basicHandler.report(pos, details);
}
}
});
}
}
final ResultInfo statInfo;
final ResultInfo varAssignmentInfo;
final ResultInfo methodAttrInfo;
final ResultInfo unknownExprInfo;
final ResultInfo unknownTypeInfo;
final ResultInfo unknownTypeExprInfo;
final ResultInfo recoveryInfo;
Type pt() {
return resultInfo.pt;
}
KindSelector pkind() {
return resultInfo.pkind;
}
/* ************************************************************************
* Visitor methods
*************************************************************************/
/** Visitor argument: the current environment.
*/
Env<AttrContext> env;
/** Visitor argument: the currently expected attribution result.
*/
ResultInfo resultInfo;
/** Visitor result: the computed type.
*/
Type result;
MatchBindings matchBindings = MatchBindingsComputer.EMPTY;
/** Visitor method: attribute a tree, catching any completion failure
* exceptions. Return the tree's type.
*
* @param tree The tree to be visited.
* @param env The environment visitor argument.
* @param resultInfo The result info visitor argument.
*/
Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) {
Env<AttrContext> prevEnv = this.env;
ResultInfo prevResult = this.resultInfo;
try {
this.env = env;
this.resultInfo = resultInfo;
if (resultInfo.needsArgumentAttr(tree)) {
result = argumentAttr.attribArg(tree, env);
} else {
tree.accept(this);
}
matchBindings = matchBindingsComputer.finishBindings(tree,
matchBindings);
if (tree == breakTree &&
resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
breakTreeFound(copyEnv(env));
}
return result;
} catch (CompletionFailure ex) {
tree.type = syms.errType;
return chk.completionError(tree.pos(), ex);
} finally {
this.env = prevEnv;
this.resultInfo = prevResult;
}
}
protected void breakTreeFound(Env<AttrContext> env) {
throw new BreakAttr(env);
}
Env<AttrContext> copyEnv(Env<AttrContext> env) {
Env<AttrContext> newEnv =
env.dup(env.tree, env.info.dup(copyScope(env.info.scope)));
if (newEnv.outer != null) {
newEnv.outer = copyEnv(newEnv.outer);
}
return newEnv;
}
WriteableScope copyScope(WriteableScope sc) {
WriteableScope newScope = WriteableScope.create(sc.owner);
List<Symbol> elemsList = List.nil();
for (Symbol sym : sc.getSymbols()) {
elemsList = elemsList.prepend(sym);
}
for (Symbol s : elemsList) {
newScope.enter(s);
}
return newScope;
}
/** Derived visitor method: attribute an expression tree.
*/
public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) {
return attribTree(tree, env, new ResultInfo(KindSelector.VAL, !pt.hasTag(ERROR) ? pt : Type.noType));
}
/** Derived visitor method: attribute an expression tree with
* no constraints on the computed type.
*/
public Type attribExpr(JCTree tree, Env<AttrContext> env) {
return attribTree(tree, env, unknownExprInfo);
}
/** Derived visitor method: attribute a type tree.
*/
public Type attribType(JCTree tree, Env<AttrContext> env) {
Type result = attribType(tree, env, Type.noType);
return result;
}
/** Derived visitor method: attribute a type tree.
*/
Type attribType(JCTree tree, Env<AttrContext> env, Type pt) {
Type result = attribTree(tree, env, new ResultInfo(KindSelector.TYP, pt));
return result;
}
/** Derived visitor method: attribute a statement or definition tree.
*/
public Type attribStat(JCTree tree, Env<AttrContext> env) {
Env<AttrContext> analyzeEnv = analyzer.copyEnvIfNeeded(tree, env);
Type result = attribTree(tree, env, statInfo);
analyzer.analyzeIfNeeded(tree, analyzeEnv);
attrRecover.doRecovery();
return result;
}
/** Attribute a list of expressions, returning a list of types.
*/
List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) {
ListBuffer<Type> ts = new ListBuffer<>();
for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
ts.append(attribExpr(l.head, env, pt));
return ts.toList();
}
/** Attribute a list of statements, returning nothing.
*/
<T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) {
for (List<T> l = trees; l.nonEmpty(); l = l.tail)
attribStat(l.head, env);
}
/** Attribute the arguments in a method call, returning the method kind.
*/
KindSelector attribArgs(KindSelector initialKind, List<JCExpression> trees, Env<AttrContext> env, ListBuffer<Type> argtypes) {
KindSelector kind = initialKind;
for (JCExpression arg : trees) {
Type argtype = chk.checkNonVoid(arg, attribTree(arg, env, allowPoly ? methodAttrInfo : unknownExprInfo));
if (argtype.hasTag(DEFERRED)) {
kind = KindSelector.of(KindSelector.POLY, kind);
}
argtypes.append(argtype);
}
return kind;
}
/** Attribute a type argument list, returning a list of types.
* Caller is responsible for calling checkRefTypes.
*/
List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) {
ListBuffer<Type> argtypes = new ListBuffer<>();
for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail)
argtypes.append(attribType(l.head, env));
return argtypes.toList();
}
/** Attribute a type argument list, returning a list of types.
* Check that all the types are references.
*/
List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) {
List<Type> types = attribAnyTypes(trees, env);
return chk.checkRefTypes(trees, types);
}
/**
* Attribute type variables (of generic classes or methods).
* Compound types are attributed later in attribBounds.
* @param typarams the type variables to enter
* @param env the current environment
*/
void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env, boolean checkCyclic) {
for (JCTypeParameter tvar : typarams) {
TypeVar a = (TypeVar)tvar.type;
a.tsym.flags_field |= UNATTRIBUTED;
a.setUpperBound(Type.noType);
if (!tvar.bounds.isEmpty()) {
List<Type> bounds = List.of(attribType(tvar.bounds.head, env));
for (JCExpression bound : tvar.bounds.tail)
bounds = bounds.prepend(attribType(bound, env));
types.setBounds(a, bounds.reverse());
} else {
// if no bounds are given, assume a single bound of
// java.lang.Object.
types.setBounds(a, List.of(syms.objectType));
}
a.tsym.flags_field &= ~UNATTRIBUTED;
}
if (checkCyclic) {
for (JCTypeParameter tvar : typarams) {
chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type);
}
}
}
/**
* Attribute the type references in a list of annotations.
*/
void attribAnnotationTypes(List<JCAnnotation> annotations,
Env<AttrContext> env) {
for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
JCAnnotation a = al.head;
attribType(a.annotationType, env);
}
}
/**
* Attribute a "lazy constant value".
* @param env The env for the const value
* @param variable The initializer for the const value
* @param type The expected type, or null
* @see VarSymbol#setLazyConstValue
*/
public Object attribLazyConstantValue(Env<AttrContext> env,
JCVariableDecl variable,
Type type) {
DiagnosticPosition prevLintPos
= deferredLintHandler.setPos(variable.pos());
final JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile);
try {
Type itype = attribExpr(variable.init, env, type);
if (variable.isImplicitlyTyped()) {
//fixup local variable type
type = variable.type = variable.sym.type = chk.checkLocalVarType(variable, itype.baseType(), variable.name);
}
if (itype.constValue() != null) {
return coerce(itype, type).constValue();
} else {
return null;
}
} finally {
log.useSource(prevSource);
deferredLintHandler.setPos(prevLintPos);
}
}
/** Attribute type reference in an `extends' or `implements' clause.
* Supertypes of anonymous inner classes are usually already attributed.
*
* @param tree The tree making up the type reference.
* @param env The environment current at the reference.
* @param classExpected true if only a class is expected here.
* @param interfaceExpected true if only an interface is expected here.
*/
Type attribBase(JCTree tree,
Env<AttrContext> env,
boolean classExpected,
boolean interfaceExpected,
boolean checkExtensible) {
Type t = tree.type != null ?
tree.type :
attribType(tree, env);
return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible);
}
Type checkBase(Type t,
JCTree tree,
Env<AttrContext> env,
boolean classExpected,
boolean interfaceExpected,
boolean checkExtensible) {
final DiagnosticPosition pos = tree.hasTag(TYPEAPPLY) ?
(((JCTypeApply) tree).clazz).pos() : tree.pos();
if (t.tsym.isAnonymous()) {
log.error(pos, Errors.CantInheritFromAnon);
return types.createErrorType(t);
}
if (t.isErroneous())
return t;
if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) {
// check that type variable is already visible
if (t.getUpperBound() == null) {
log.error(pos, Errors.IllegalForwardRef);
return types.createErrorType(t);
}
} else {
t = chk.checkClassType(pos, t, checkExtensible);
}
if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) {
log.error(pos, Errors.IntfExpectedHere);
// return errType is necessary since otherwise there might
// be undetected cycles which cause attribution to loop
return types.createErrorType(t);
} else if (checkExtensible &&
classExpected &&
(t.tsym.flags() & INTERFACE) != 0) {
log.error(pos, Errors.NoIntfExpectedHere);
return types.createErrorType(t);
}
if (checkExtensible &&
((t.tsym.flags() & FINAL) != 0)) {
log.error(pos,
Errors.CantInheritFromFinal(t.tsym));
}
chk.checkNonCyclic(pos, t);
return t;
}
Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) {
Assert.check((env.enclClass.sym.flags() & ENUM) != 0);
id.type = env.info.scope.owner.enclClass().type;
id.sym = env.info.scope.owner.enclClass();
return id.type;
}
public void visitClassDef(JCClassDecl tree) {
Optional<ArgumentAttr.LocalCacheContext> localCacheContext =
Optional.ofNullable(env.info.attributionMode.isSpeculative ?
argumentAttr.withLocalCacheContext() : null);
try {
// Local and anonymous classes have not been entered yet, so we need to
// do it now.
if (env.info.scope.owner.kind.matches(KindSelector.VAL_MTH)) {
enter.classEnter(tree, env);
} else {
// If this class declaration is part of a class level annotation,
// as in @MyAnno(new Object() {}) class MyClass {}, enter it in
// order to simplify later steps and allow for sensible error
// messages.
if (env.tree.hasTag(NEWCLASS) && TreeInfo.isInAnnotation(env, tree))
enter.classEnter(tree, env);
}
ClassSymbol c = tree.sym;
if (c == null) {
// exit in case something drastic went wrong during enter.
result = null;
} else {
// make sure class has been completed:
c.complete();
// If this class appears as an anonymous class
// in a superclass constructor call
// disable implicit outer instance from being passed.
// (This would be an illegal access to "this before super").
if (env.info.isSelfCall &&
env.tree.hasTag(NEWCLASS)) {
c.flags_field |= NOOUTERTHIS;
}
attribClass(tree.pos(), c);
result = tree.type = c.type;
}
} finally {
localCacheContext.ifPresent(LocalCacheContext::leave);
}
}
public void visitMethodDef(JCMethodDecl tree) {
MethodSymbol m = tree.sym;
boolean isDefaultMethod = (m.flags() & DEFAULT) != 0;
Lint lint = env.info.lint.augment(m);
Lint prevLint = chk.setLint(lint);
MethodSymbol prevMethod = chk.setMethod(m);
try {
deferredLintHandler.flush(tree.pos());
chk.checkDeprecatedAnnotation(tree.pos(), m);
// Create a new environment with local scope
// for attributing the method.
Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env);
localEnv.info.lint = lint;
attribStats(tree.typarams, localEnv);