forked from openjdk/amber
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFlow.java
3677 lines (3321 loc) · 147 KB
/
Flow.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, 2025, 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.
*/
//todo: one might eliminate uninits.andSets when monotonic
package com.sun.tools.javac.comp;
import java.util.Map;
import java.util.Map.Entry;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.LambdaExpressionTree.BodyKind;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Scope.WriteableScope;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.resources.CompilerProperties.LintWarnings;
import com.sun.tools.javac.resources.CompilerProperties.Warnings;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javac.util.JCDiagnostic.Error;
import com.sun.tools.javac.util.JCDiagnostic.Warning;
import com.sun.tools.javac.code.Symbol.*;
import com.sun.tools.javac.tree.JCTree.*;
import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javac.code.Flags.BLOCK;
import com.sun.tools.javac.code.Kinds.Kind;
import static com.sun.tools.javac.code.Kinds.Kind.*;
import com.sun.tools.javac.code.Type.TypeVar;
import static com.sun.tools.javac.code.TypeTag.BOOLEAN;
import static com.sun.tools.javac.code.TypeTag.VOID;
import com.sun.tools.javac.resources.CompilerProperties.Fragments;
import static com.sun.tools.javac.tree.JCTree.Tag.*;
import com.sun.tools.javac.util.JCDiagnostic.Fragment;
import java.util.Arrays;
import java.util.Iterator;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.groupingBy;
/** This pass implements dataflow analysis for Java programs though
* different AST visitor steps. Liveness analysis (see AliveAnalyzer) checks that
* every statement is reachable. Exception analysis (see FlowAnalyzer) ensures that
* every checked exception that is thrown is declared or caught. Definite assignment analysis
* (see AssignAnalyzer) ensures that each variable is assigned when used. Definite
* unassignment analysis (see AssignAnalyzer) in ensures that no final variable
* is assigned more than once. Finally, local variable capture analysis (see CaptureAnalyzer)
* determines that local variables accessed within the scope of an inner class/lambda
* are either final or effectively-final.
*
* <p>The JLS has a number of problems in the
* specification of these flow analysis problems. This implementation
* attempts to address those issues.
*
* <p>First, there is no accommodation for a finally clause that cannot
* complete normally. For liveness analysis, an intervening finally
* clause can cause a break, continue, or return not to reach its
* target. For exception analysis, an intervening finally clause can
* cause any exception to be "caught". For DA/DU analysis, the finally
* clause can prevent a transfer of control from propagating DA/DU
* state to the target. In addition, code in the finally clause can
* affect the DA/DU status of variables.
*
* <p>For try statements, we introduce the idea of a variable being
* definitely unassigned "everywhere" in a block. A variable V is
* "unassigned everywhere" in a block iff it is unassigned at the
* beginning of the block and there is no reachable assignment to V
* in the block. An assignment V=e is reachable iff V is not DA
* after e. Then we can say that V is DU at the beginning of the
* catch block iff V is DU everywhere in the try block. Similarly, V
* is DU at the beginning of the finally block iff V is DU everywhere
* in the try block and in every catch block. Specifically, the
* following bullet is added to 16.2.2
* <pre>
* V is <em>unassigned everywhere</em> in a block if it is
* unassigned before the block and there is no reachable
* assignment to V within the block.
* </pre>
* <p>In 16.2.15, the third bullet (and all of its sub-bullets) for all
* try blocks is changed to
* <pre>
* V is definitely unassigned before a catch block iff V is
* definitely unassigned everywhere in the try block.
* </pre>
* <p>The last bullet (and all of its sub-bullets) for try blocks that
* have a finally block is changed to
* <pre>
* V is definitely unassigned before the finally block iff
* V is definitely unassigned everywhere in the try block
* and everywhere in each catch block of the try statement.
* </pre>
* <p>In addition,
* <pre>
* V is definitely assigned at the end of a constructor iff
* V is definitely assigned after the block that is the body
* of the constructor and V is definitely assigned at every
* return that can return from the constructor.
* </pre>
* <p>In addition, each continue statement with the loop as its target
* is treated as a jump to the end of the loop body, and "intervening"
* finally clauses are treated as follows: V is DA "due to the
* continue" iff V is DA before the continue statement or V is DA at
* the end of any intervening finally block. V is DU "due to the
* continue" iff any intervening finally cannot complete normally or V
* is DU at the end of every intervening finally block. This "due to
* the continue" concept is then used in the spec for the loops.
*
* <p>Similarly, break statements must consider intervening finally
* blocks. For liveness analysis, a break statement for which any
* intervening finally cannot complete normally is not considered to
* cause the target statement to be able to complete normally. Then
* we say V is DA "due to the break" iff V is DA before the break or
* V is DA at the end of any intervening finally block. V is DU "due
* to the break" iff any intervening finally cannot complete normally
* or V is DU at the break and at the end of every intervening
* finally block. (I suspect this latter condition can be
* simplified.) This "due to the break" is then used in the spec for
* all statements that can be "broken".
*
* <p>The return statement is treated similarly. V is DA "due to a
* return statement" iff V is DA before the return statement or V is
* DA at the end of any intervening finally block. Note that we
* don't have to worry about the return expression because this
* concept is only used for constructors.
*
* <p>There is no spec in the JLS for when a variable is definitely
* assigned at the end of a constructor, which is needed for final
* fields (8.3.1.2). We implement the rule that V is DA at the end
* of the constructor iff it is DA and the end of the body of the
* constructor and V is DA "due to" every return of the constructor.
*
* <p>Intervening finally blocks similarly affect exception analysis. An
* intervening finally that cannot complete normally allows us to ignore
* an otherwise uncaught exception.
*
* <p>To implement the semantics of intervening finally clauses, all
* nonlocal transfers (break, continue, return, throw, method call that
* can throw a checked exception, and a constructor invocation that can
* thrown a checked exception) are recorded in a queue, and removed
* from the queue when we complete processing the target of the
* nonlocal transfer. This allows us to modify the queue in accordance
* with the above rules when we encounter a finally clause. The only
* exception to this [no pun intended] is that checked exceptions that
* are known to be caught or declared to be caught in the enclosing
* method are not recorded in the queue, but instead are recorded in a
* global variable "{@code Set<Type> thrown}" that records the type of all
* exceptions that can be thrown.
*
* <p>Other minor issues the treatment of members of other classes
* (always considered DA except that within an anonymous class
* constructor, where DA status from the enclosing scope is
* preserved), treatment of the case expression (V is DA before the
* case expression iff V is DA after the switch expression),
* treatment of variables declared in a switch block (the implied
* DA/DU status after the switch expression is DU and not DA for
* variables defined in a switch block), the treatment of boolean ?:
* expressions (The JLS rules only handle b and c non-boolean; the
* new rule is that if b and c are boolean valued, then V is
* (un)assigned after a?b:c when true/false iff V is (un)assigned
* after b when true/false and V is (un)assigned after c when
* true/false).
*
* <p>There is the remaining question of what syntactic forms constitute a
* reference to a variable. It is conventional to allow this.x on the
* left-hand-side to initialize a final instance field named x, yet
* this.x isn't considered a "use" when appearing on a right-hand-side
* in most implementations. Should parentheses affect what is
* considered a variable reference? The simplest rule would be to
* allow unqualified forms only, parentheses optional, and phase out
* support for assigning to a final field via this.x.
*
* <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 Flow {
protected static final Context.Key<Flow> flowKey = new Context.Key<>();
private final Names names;
private final Log log;
private final Symtab syms;
private final Types types;
private final Check chk;
private TreeMaker make;
private final Resolve rs;
private final JCDiagnostic.Factory diags;
private Env<AttrContext> attrEnv;
private Lint lint;
private final Infer infer;
public static Flow instance(Context context) {
Flow instance = context.get(flowKey);
if (instance == null)
instance = new Flow(context);
return instance;
}
public void analyzeTree(Env<AttrContext> env, TreeMaker make) {
new AliveAnalyzer().analyzeTree(env, make);
new AssignAnalyzer().analyzeTree(env, make);
new FlowAnalyzer().analyzeTree(env, make);
new CaptureAnalyzer().analyzeTree(env, make);
}
public void analyzeLambda(Env<AttrContext> env, JCLambda that, TreeMaker make, boolean speculative) {
Log.DiagnosticHandler diagHandler = null;
//we need to disable diagnostics temporarily; the problem is that if
//a lambda expression contains e.g. an unreachable statement, an error
//message will be reported and will cause compilation to skip the flow analysis
//step - if we suppress diagnostics, we won't stop at Attr for flow-analysis
//related errors, which will allow for more errors to be detected
if (!speculative) {
diagHandler = new Log.DiscardDiagnosticHandler(log);
}
try {
new LambdaAliveAnalyzer().analyzeTree(env, that, make);
} finally {
if (!speculative) {
log.popDiagnosticHandler(diagHandler);
}
}
}
public List<Type> analyzeLambdaThrownTypes(final Env<AttrContext> env,
JCLambda that, TreeMaker make) {
//we need to disable diagnostics temporarily; the problem is that if
//a lambda expression contains e.g. an unreachable statement, an error
//message will be reported and will cause compilation to skip the flow analysis
//step - if we suppress diagnostics, we won't stop at Attr for flow-analysis
//related errors, which will allow for more errors to be detected
Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
try {
new LambdaAssignAnalyzer(env).analyzeTree(env, that, make);
LambdaFlowAnalyzer flowAnalyzer = new LambdaFlowAnalyzer();
flowAnalyzer.analyzeTree(env, that, make);
return flowAnalyzer.inferredThrownTypes;
} finally {
log.popDiagnosticHandler(diagHandler);
}
}
public boolean aliveAfter(Env<AttrContext> env, JCTree that, TreeMaker make) {
//we need to disable diagnostics temporarily; the problem is that if
//"that" contains e.g. an unreachable statement, an error
//message will be reported and will cause compilation to skip the flow analysis
//step - if we suppress diagnostics, we won't stop at Attr for flow-analysis
//related errors, which will allow for more errors to be detected
Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
try {
SnippetAliveAnalyzer analyzer = new SnippetAliveAnalyzer();
analyzer.analyzeTree(env, that, make);
return analyzer.isAlive();
} finally {
log.popDiagnosticHandler(diagHandler);
}
}
public boolean breaksToTree(Env<AttrContext> env, JCTree breakTo, JCTree body, TreeMaker make) {
//we need to disable diagnostics temporarily; the problem is that if
//"that" contains e.g. an unreachable statement, an error
//message will be reported and will cause compilation to skip the flow analysis
//step - if we suppress diagnostics, we won't stop at Attr for flow-analysis
//related errors, which will allow for more errors to be detected
Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
try {
SnippetBreakToAnalyzer analyzer = new SnippetBreakToAnalyzer(breakTo);
analyzer.analyzeTree(env, body, make);
return analyzer.breaksTo();
} finally {
log.popDiagnosticHandler(diagHandler);
}
}
/**
* Definite assignment scan mode
*/
enum FlowKind {
/**
* This is the normal DA/DU analysis mode
*/
NORMAL("var.might.already.be.assigned", false),
/**
* This is the speculative DA/DU analysis mode used to speculatively
* derive assertions within loop bodies
*/
SPECULATIVE_LOOP("var.might.be.assigned.in.loop", true);
final String errKey;
final boolean isFinal;
FlowKind(String errKey, boolean isFinal) {
this.errKey = errKey;
this.isFinal = isFinal;
}
boolean isFinal() {
return isFinal;
}
}
@SuppressWarnings("this-escape")
protected Flow(Context context) {
context.put(flowKey, this);
names = Names.instance(context);
log = Log.instance(context);
syms = Symtab.instance(context);
types = Types.instance(context);
chk = Check.instance(context);
lint = Lint.instance(context);
infer = Infer.instance(context);
rs = Resolve.instance(context);
diags = JCDiagnostic.Factory.instance(context);
Source source = Source.instance(context);
}
/**
* Base visitor class for all visitors implementing dataflow analysis logic.
* This class define the shared logic for handling jumps (break/continue statements).
*/
abstract static class BaseAnalyzer extends TreeScanner {
enum JumpKind {
BREAK(JCTree.Tag.BREAK) {
@Override
JCTree getTarget(JCTree tree) {
return ((JCBreak)tree).target;
}
},
CONTINUE(JCTree.Tag.CONTINUE) {
@Override
JCTree getTarget(JCTree tree) {
return ((JCContinue)tree).target;
}
},
YIELD(JCTree.Tag.YIELD) {
@Override
JCTree getTarget(JCTree tree) {
return ((JCYield)tree).target;
}
};
final JCTree.Tag treeTag;
private JumpKind(Tag treeTag) {
this.treeTag = treeTag;
}
abstract JCTree getTarget(JCTree tree);
}
/** The currently pending exits that go from current inner blocks
* to an enclosing block, in source order.
*/
ListBuffer<PendingExit> pendingExits;
/** A class whose initializers we are scanning. Because initializer
* scans can be triggered out of sequence when visiting certain nodes
* (e.g., super()), we protect against infinite loops that could be
* triggered by incorrect code (e.g., super() inside initializer).
*/
JCClassDecl initScanClass;
/** A pending exit. These are the statements return, break,
* continue. In addition, exception-throwing expressions or
* statements are put here when not known to be caught.
* In the case of pattern declarations match is also put here. This
* will typically result in an error unless it is within a
* try-finally whose finally block cannot complete normally.
*/
static class PendingExit {
JCTree tree;
PendingExit(JCTree tree) {
this.tree = tree;
}
void resolveJump() {
//do nothing
}
}
abstract void markDead();
/** Record an outward transfer of control. */
void recordExit(PendingExit pe) {
pendingExits.append(pe);
markDead();
}
/** Resolve all jumps of this statement. */
private Liveness resolveJump(JCTree tree,
ListBuffer<PendingExit> oldPendingExits,
JumpKind jk) {
boolean resolved = false;
List<PendingExit> exits = pendingExits.toList();
pendingExits = oldPendingExits;
for (; exits.nonEmpty(); exits = exits.tail) {
PendingExit exit = exits.head;
if (exit.tree.hasTag(jk.treeTag) &&
jk.getTarget(exit.tree) == tree) {
exit.resolveJump();
resolved = true;
} else {
pendingExits.append(exit);
}
}
return Liveness.from(resolved);
}
/** Resolve all continues of this statement. */
Liveness resolveContinues(JCTree tree) {
return resolveJump(tree, new ListBuffer<PendingExit>(), JumpKind.CONTINUE);
}
/** Resolve all breaks of this statement. */
Liveness resolveBreaks(JCTree tree, ListBuffer<PendingExit> oldPendingExits) {
return resolveJump(tree, oldPendingExits, JumpKind.BREAK);
}
/** Resolve all yields of this statement. */
Liveness resolveYields(JCTree tree, ListBuffer<PendingExit> oldPendingExits) {
return resolveJump(tree, oldPendingExits, JumpKind.YIELD);
}
@Override
public void scan(JCTree tree) {
if (tree != null && (
tree.type == null ||
tree.type != Type.stuckType)) {
super.scan(tree);
}
}
public void visitPackageDef(JCPackageDecl tree) {
// Do nothing for PackageDecl
}
protected void scanSyntheticBreak(TreeMaker make, JCTree swtch) {
if (swtch.hasTag(SWITCH_EXPRESSION)) {
JCYield brk = make.at(Position.NOPOS).Yield(make.Erroneous()
.setType(swtch.type));
brk.target = swtch;
scan(brk);
} else {
JCBreak brk = make.at(Position.NOPOS).Break(null);
brk.target = swtch;
scan(brk);
}
}
// Do something with all static or non-static field initializers and initialization blocks.
protected void forEachInitializer(JCClassDecl classDef, boolean isStatic, Consumer<? super JCTree> handler) {
if (classDef == initScanClass) // avoid infinite loops
return;
JCClassDecl initScanClassPrev = initScanClass;
initScanClass = classDef;
try {
for (List<JCTree> defs = classDef.defs; defs.nonEmpty(); defs = defs.tail) {
JCTree def = defs.head;
// Don't recurse into nested classes
if (def.hasTag(CLASSDEF))
continue;
/* we need to check for flags in the symbol too as there could be cases for which implicit flags are
* represented in the symbol but not in the tree modifiers as they were not originally in the source
* code
*/
boolean isDefStatic = ((TreeInfo.flags(def) | (TreeInfo.symbolFor(def) == null ? 0 : TreeInfo.symbolFor(def).flags_field)) & STATIC) != 0;
if (!def.hasTag(METHODDEF) && (isDefStatic == isStatic))
handler.accept(def);
}
} finally {
initScanClass = initScanClassPrev;
}
}
}
/**
* This pass implements the first step of the dataflow analysis, namely
* the liveness analysis check. This checks that every statement is reachable.
* The output of this analysis pass are used by other analyzers. This analyzer
* sets the 'finallyCanCompleteNormally' field in the JCTry class.
*/
class AliveAnalyzer extends BaseAnalyzer {
/** A flag that indicates whether the last statement could
* complete normally.
*/
private Liveness alive;
@Override
void markDead() {
alive = Liveness.DEAD;
}
/* ***********************************************************************
* Visitor methods for statements and definitions
*************************************************************************/
/** Analyze a definition.
*/
void scanDef(JCTree tree) {
scanStat(tree);
if (tree != null && tree.hasTag(JCTree.Tag.BLOCK) && alive == Liveness.DEAD) {
log.error(tree.pos(),
Errors.InitializerMustBeAbleToCompleteNormally);
}
}
/** Analyze a statement. Check that statement is reachable.
*/
void scanStat(JCTree tree) {
if (alive == Liveness.DEAD && tree != null) {
log.error(tree.pos(), Errors.UnreachableStmt);
if (!tree.hasTag(SKIP)) alive = Liveness.RECOVERY;
}
scan(tree);
}
/** Analyze list of statements.
*/
void scanStats(List<? extends JCStatement> trees) {
if (trees != null)
for (List<? extends JCStatement> l = trees; l.nonEmpty(); l = l.tail)
scanStat(l.head);
}
/* ------------ Visitor methods for various sorts of trees -------------*/
public void visitClassDef(JCClassDecl tree) {
if (tree.sym == null) return;
Liveness alivePrev = alive;
ListBuffer<PendingExit> pendingExitsPrev = pendingExits;
Lint lintPrev = lint;
pendingExits = new ListBuffer<>();
lint = lint.augment(tree.sym);
try {
// process all the nested classes
for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
if (l.head.hasTag(CLASSDEF)) {
scan(l.head);
}
}
// process all the static initializers
forEachInitializer(tree, true, def -> {
scanDef(def);
clearPendingExits(false);
});
// process all the instance initializers
forEachInitializer(tree, false, def -> {
scanDef(def);
clearPendingExits(false);
});
// process all the methods
for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) {
if (l.head.hasTag(METHODDEF)) {
scan(l.head);
}
}
} finally {
pendingExits = pendingExitsPrev;
alive = alivePrev;
lint = lintPrev;
}
}
public void visitMethodDef(JCMethodDecl tree) {
if (tree.body == null) return;
Lint lintPrev = lint;
lint = lint.augment(tree.sym);
Assert.check(pendingExits.isEmpty());
try {
alive = Liveness.ALIVE;
scanStat(tree.body);
tree.completesNormally = alive != Liveness.DEAD;
if (alive == Liveness.ALIVE && (tree.sym.flags() & PATTERN) != 0) {
log.error(TreeInfo.diagEndPos(tree.body), Errors.MissingMatchStmt);
} else if (alive == Liveness.ALIVE && !tree.sym.type.getReturnType().hasTag(VOID)) {
log.error(TreeInfo.diagEndPos(tree.body), Errors.MissingRetStmt);
}
clearPendingExits(true);
} finally {
lint = lintPrev;
}
}
private void clearPendingExits(boolean inMethod) {
List<PendingExit> exits = pendingExits.toList();
pendingExits = new ListBuffer<>();
while (exits.nonEmpty()) {
PendingExit exit = exits.head;
exits = exits.tail;
Assert.check((inMethod && (exit.tree.hasTag(RETURN) || exit.tree.hasTag(MATCH) || exit.tree.hasTag(MATCHFAIL))) ||
log.hasErrorOn(exit.tree.pos()));
}
}
public void visitVarDef(JCVariableDecl tree) {
if (tree.init != null) {
Lint lintPrev = lint;
lint = lint.augment(tree.sym);
try{
scan(tree.init);
} finally {
lint = lintPrev;
}
}
}
public void visitBlock(JCBlock tree) {
scanStats(tree.stats);
}
public void visitDoLoop(JCDoWhileLoop tree) {
ListBuffer<PendingExit> prevPendingExits = pendingExits;
pendingExits = new ListBuffer<>();
scanStat(tree.body);
alive = alive.or(resolveContinues(tree));
scan(tree.cond);
alive = alive.and(!tree.cond.type.isTrue());
alive = alive.or(resolveBreaks(tree, prevPendingExits));
}
public void visitWhileLoop(JCWhileLoop tree) {
ListBuffer<PendingExit> prevPendingExits = pendingExits;
pendingExits = new ListBuffer<>();
scan(tree.cond);
alive = Liveness.from(!tree.cond.type.isFalse());
scanStat(tree.body);
alive = alive.or(resolveContinues(tree));
alive = resolveBreaks(tree, prevPendingExits).or(
!tree.cond.type.isTrue());
}
public void visitForLoop(JCForLoop tree) {
ListBuffer<PendingExit> prevPendingExits = pendingExits;
scanStats(tree.init);
pendingExits = new ListBuffer<>();
if (tree.cond != null) {
scan(tree.cond);
alive = Liveness.from(!tree.cond.type.isFalse());
} else {
alive = Liveness.ALIVE;
}
scanStat(tree.body);
alive = alive.or(resolveContinues(tree));
scan(tree.step);
alive = resolveBreaks(tree, prevPendingExits).or(
tree.cond != null && !tree.cond.type.isTrue());
}
public void visitMatch(JCMatch tree) {
scan(tree.args);
recordExit(new PendingExit(tree));
}
public void visitTypeTestStatement(JCInstanceOfStatement tree) {
ListBuffer<PendingExit> prevPendingExits = pendingExits;
pendingExits = new ListBuffer<>();
if (tree.pattern instanceof JCRecordPattern rp) {
visitRecordPattern(rp);
}
List<JCCase> singletonCaseList = List.of(make.Case(
CaseTree.CaseKind.STATEMENT,
List.of(make.PatternCaseLabel(tree.pattern)),
null,
List.nil(),
null)
);
boolean isExhaustive =
exhausts(tree.expr, singletonCaseList);
if (!isExhaustive) {
log.error(tree, Errors.NotExhaustiveStatement); // TODO replace with instanceof-related error since this refers to switch
}
scan(tree.expr);
alive = alive.or(resolveBreaks(tree, prevPendingExits));
}
public void visitMatchFail(JCMatchFail tree) {
recordExit(new PendingExit(tree));
}
public void visitForeachLoop(JCEnhancedForLoop tree) {
visitVarDef(tree.var);
ListBuffer<PendingExit> prevPendingExits = pendingExits;
scan(tree.expr);
pendingExits = new ListBuffer<>();
scanStat(tree.body);
alive = alive.or(resolveContinues(tree));
resolveBreaks(tree, prevPendingExits);
alive = Liveness.ALIVE;
}
public void visitLabelled(JCLabeledStatement tree) {
ListBuffer<PendingExit> prevPendingExits = pendingExits;
pendingExits = new ListBuffer<>();
scanStat(tree.body);
alive = alive.or(resolveBreaks(tree, prevPendingExits));
}
public void visitSwitch(JCSwitch tree) {
ListBuffer<PendingExit> prevPendingExits = pendingExits;
pendingExits = new ListBuffer<>();
scan(tree.selector);
boolean exhaustiveSwitch = TreeInfo.expectedExhaustive(tree);
for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
alive = Liveness.ALIVE;
JCCase c = l.head;
for (JCCaseLabel pat : c.labels) {
scan(pat);
}
scanStats(c.stats);
if (alive != Liveness.DEAD && c.caseKind == JCCase.RULE) {
scanSyntheticBreak(make, tree);
alive = Liveness.DEAD;
}
// Warn about fall-through if lint switch fallthrough enabled.
if (alive == Liveness.ALIVE &&
c.stats.nonEmpty() && l.tail.nonEmpty())
lint.logIfEnabled(log, l.tail.head.pos(),
LintWarnings.PossibleFallThroughIntoCase);
}
tree.isExhaustive = tree.hasUnconditionalPattern ||
TreeInfo.isErrorEnumSwitch(tree.selector, tree.cases);
if (exhaustiveSwitch) {
tree.isExhaustive |= exhausts(tree.selector, tree.cases);
if (!tree.isExhaustive) {
log.error(tree, Errors.NotExhaustiveStatement);
}
}
if (!tree.hasUnconditionalPattern && !exhaustiveSwitch) {
alive = Liveness.ALIVE;
}
alive = alive.or(resolveBreaks(tree, prevPendingExits));
}
@Override
public void visitSwitchExpression(JCSwitchExpression tree) {
ListBuffer<PendingExit> prevPendingExits = pendingExits;
pendingExits = new ListBuffer<>();
scan(tree.selector);
Liveness prevAlive = alive;
for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) {
alive = Liveness.ALIVE;
JCCase c = l.head;
for (JCCaseLabel pat : c.labels) {
scan(pat);
}
scanStats(c.stats);
if (alive == Liveness.ALIVE) {
if (c.caseKind == JCCase.RULE) {
log.error(TreeInfo.diagEndPos(c.body),
Errors.RuleCompletesNormally);
} else if (l.tail.isEmpty()) {
log.error(TreeInfo.diagEndPos(tree),
Errors.SwitchExpressionCompletesNormally);
}
}
}
if (tree.hasUnconditionalPattern ||
TreeInfo.isErrorEnumSwitch(tree.selector, tree.cases)) {
tree.isExhaustive = true;
} else {
tree.isExhaustive = exhausts(tree.selector, tree.cases);
}
if (!tree.isExhaustive) {
log.error(tree, Errors.NotExhaustive);
}
alive = prevAlive;
alive = alive.or(resolveYields(tree, prevPendingExits));
}
private boolean exhausts(JCExpression selector, List<JCCase> cases) {
Set<PatternDescription> patternSet = new HashSet<>();
Map<Symbol, Set<Symbol>> enum2Constants = new HashMap<>();
Set<Object> booleanLiterals = new HashSet<>(Set.of(0, 1));
for (JCCase c : cases) {
if (!TreeInfo.unguardedCase(c))
continue;
for (var l : c.labels) {
if (l instanceof JCPatternCaseLabel patternLabel) {
if (patternLabel.pat instanceof JCRecordPattern rec &&
rec.patternDeclaration != null &&
!rec.patternDeclaration.patternFlags.contains(PatternFlags.TOTAL)) {
continue;
}
for (Type component : components(selector.type)) {
patternSet.add(makePatternDescription(component, patternLabel.pat));
}
} else if (l instanceof JCConstantCaseLabel constantLabel) {
if (types.unboxedTypeOrType(selector.type).hasTag(TypeTag.BOOLEAN)) {
Object value = ((JCLiteral) constantLabel.expr).value;
booleanLiterals.remove(value);
} else {
Symbol s = TreeInfo.symbol(constantLabel.expr);
if (s != null && s.isEnum()) {
enum2Constants.computeIfAbsent(s.owner, x -> {
Set<Symbol> result = new HashSet<>();
s.owner.members()
.getSymbols(sym -> sym.kind == Kind.VAR && sym.isEnum())
.forEach(result::add);
return result;
}).remove(s);
}
}
}
}
}
if (types.unboxedTypeOrType(selector.type).hasTag(TypeTag.BOOLEAN) && booleanLiterals.isEmpty()) {
return true;
}
for (Entry<Symbol, Set<Symbol>> e : enum2Constants.entrySet()) {
if (e.getValue().isEmpty()) {
patternSet.add(new BindingPattern(e.getKey().type));
}
}
Set<PatternDescription> patterns = patternSet;
boolean useHashes = true;
try {
boolean repeat = true;
while (repeat) {
Set<PatternDescription> updatedPatterns;
updatedPatterns = reduceBindingPatterns(selector.type, patterns);
updatedPatterns = reduceNestedPatterns(updatedPatterns, useHashes);
updatedPatterns = reduceRecordPatterns(updatedPatterns);
updatedPatterns = removeCoveredRecordPatterns(updatedPatterns);
repeat = !updatedPatterns.equals(patterns);
if (checkCovered(selector.type, patterns)) {
return true;
}
if (!repeat) {
//there may be situation like:
//class B permits S1, S2
//patterns: R(S1, B), R(S2, S2)
//this might be joined to R(B, S2), as B could be rewritten to S2
//but hashing in reduceNestedPatterns will not allow that
//disable the use of hashing, and use subtyping in
//reduceNestedPatterns to handle situations like this:
repeat = useHashes;
useHashes = false;
} else {
//if a reduction happened, make sure hashing in reduceNestedPatterns
//is enabled, as the hashing speeds up the process significantly:
useHashes = true;
}
patterns = updatedPatterns;
}
return checkCovered(selector.type, patterns);
} catch (CompletionFailure cf) {
chk.completionError(selector.pos(), cf);
return true; //error recovery
}
}
private boolean checkCovered(Type seltype, Iterable<PatternDescription> patterns) {
for (Type seltypeComponent : components(seltype)) {
for (PatternDescription pd : patterns) {
if(isBpCovered(seltypeComponent, pd)) {
return true;
}
}
}
return false;
}
private List<Type> components(Type seltype) {
return switch (seltype.getTag()) {
case CLASS -> {
if (seltype.isCompound()) {
if (seltype.isIntersection()) {
yield ((Type.IntersectionClassType) seltype).getComponents()
.stream()
.flatMap(t -> components(t).stream())
.collect(List.collector());
}
yield List.nil();
}
yield List.of(types.erasure(seltype));
}
case TYPEVAR -> components(((TypeVar) seltype).getUpperBound());
default -> List.of(types.erasure(seltype));
};
}
/* In a set of patterns, search for a sub-set of binding patterns that
* in combination exhaust their sealed supertype. If such a sub-set
* is found, it is removed, and replaced with a binding pattern
* for the sealed supertype.
*/
private Set<PatternDescription> reduceBindingPatterns(Type selectorType, Set<PatternDescription> patterns) {
Set<Symbol> existingBindings = patterns.stream()
.filter(pd -> pd instanceof BindingPattern)
.map(pd -> ((BindingPattern) pd).type.tsym)
.collect(Collectors.toSet());
for (PatternDescription pdOne : patterns) {
if (pdOne instanceof BindingPattern bpOne) {
Set<PatternDescription> toAdd = new HashSet<>();
for (Type sup : types.directSupertypes(bpOne.type)) {
ClassSymbol clazz = (ClassSymbol) types.erasure(sup).tsym;
clazz.complete();
if (clazz.isSealed() && clazz.isAbstract() &&
//if a binding pattern for clazz already exists, no need to analyze it again:
!existingBindings.contains(clazz)) {
ListBuffer<PatternDescription> bindings = new ListBuffer<>();
//do not reduce to types unrelated to the selector type:
Type clazzErasure = types.erasure(clazz.type);
if (components(selectorType).stream()
.map(types::erasure)
.noneMatch(c -> types.isSubtype(clazzErasure, c))) {
continue;
}
Set<Symbol> permitted = allPermittedSubTypes(clazz, csym -> {
Type instantiated;
if (csym.type.allparams().isEmpty()) {
instantiated = csym.type;
} else {
instantiated = infer.instantiatePatternType(selectorType, csym);
}
return instantiated != null && types.isCastable(selectorType, instantiated);
});
for (PatternDescription pdOther : patterns) {
if (pdOther instanceof BindingPattern bpOther) {
Set<Symbol> currentPermittedSubTypes =
allPermittedSubTypes(bpOther.type.tsym, s -> true);
PERMITTED: for (Iterator<Symbol> it = permitted.iterator(); it.hasNext();) {
Symbol perm = it.next();
for (Symbol currentPermitted : currentPermittedSubTypes) {
if (types.isSubtype(types.erasure(currentPermitted.type),
types.erasure(perm.type))) {
it.remove();
continue PERMITTED;
}
}
if (types.isSubtype(types.erasure(perm.type),
types.erasure(bpOther.type))) {
it.remove();
}