1
1
/*
2
- * Copyright (c) 2017, 2019 , Oracle and/or its affiliates. All rights reserved.
2
+ * Copyright (c) 2017, 2021 , Oracle and/or its affiliates. All rights reserved.
3
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
4
*
5
5
* This code is free software; you can redistribute it and/or modify it
23
23
24
24
/*
25
25
* @test
26
- * @bug 8262891
26
+ * @bug 8262891 8268663
27
27
* @summary Check guards implementation.
28
28
* @compile --enable-preview -source ${jdk.version} Guards.java
29
29
* @run main/othervm --enable-preview Guards
@@ -43,6 +43,9 @@ void run() {
43
43
run (this ::testBooleanSwitchExpression );
44
44
assertEquals ("a" , testPatternInGuard ("a" ));
45
45
assertEquals (null , testPatternInGuard (1 ));
46
+ runIfTrue (this ::typeGuardIfTrueIfStatement );
47
+ runIfTrue (this ::typeGuardIfTrueSwitchExpression );
48
+ runIfTrue (this ::typeGuardIfTrueSwitchStatement );
46
49
}
47
50
48
51
void run (Function <Object , String > convert ) {
@@ -52,6 +55,12 @@ void run(Function<Object, String> convert) {
52
55
assertEquals ("any" , convert .apply ("" ));
53
56
}
54
57
58
+ void runIfTrue (Function <Object , String > convert ) {
59
+ assertEquals ("true" , convert .apply (0 ));
60
+ assertEquals ("second" , convert .apply (2 ));
61
+ assertEquals ("any" , convert .apply ("" ));
62
+ }
63
+
55
64
String typeTestPatternSwitchTest (Object o ) {
56
65
switch (o ) {
57
66
case Integer i && i == 0 : return "zero" ;
@@ -84,6 +93,35 @@ String testBooleanSwitchExpression(Object o) {
84
93
}
85
94
}
86
95
96
+ String typeGuardIfTrueSwitchStatement (Object o ) {
97
+ Object o2 = "" ;
98
+ switch (o ) {
99
+ case Integer i && i == 0 && i < 1 && o2 instanceof String s : o = s + String .valueOf (i ); return "true" ;
100
+ case Integer i && i == 0 || i > 1 : o = String .valueOf (i ); return "second" ;
101
+ case Object x : return "any" ;
102
+ }
103
+ }
104
+
105
+ String typeGuardIfTrueSwitchExpression (Object o ) {
106
+ Object o2 = "" ;
107
+ return switch (o ) {
108
+ case Integer i && i == 0 && i < 1 && o2 instanceof String s : o = s + String .valueOf (i ); yield "true" ;
109
+ case Integer i && i == 0 || i > 1 : o = String .valueOf (i ); yield "second" ;
110
+ case Object x : yield "any" ;
111
+ };
112
+ }
113
+
114
+ String typeGuardIfTrueIfStatement (Object o ) {
115
+ Object o2 = "" ;
116
+ if (o != null && o instanceof (Integer i && i == 0 && i < 1 ) && (o = i ) != null && o2 instanceof String s ) {
117
+ return s != null ? "true" : null ;
118
+ } else if (o != null && o instanceof (Integer i && i == 0 || i > 1 ) && (o = i ) != null ) {
119
+ return "second" ;
120
+ } else {
121
+ return "any" ;
122
+ }
123
+ }
124
+
87
125
String testPatternInGuard (Object o ) {
88
126
if (o instanceof (CharSequence cs && cs instanceof String s )) {
89
127
return s ;
0 commit comments