1 /*
2 * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24 /*
25 * @test
26 * @modules jdk.incubator.code
27 * @run junit TestValueCast
28 * @run junit/othervm -Dbabylon.ssa=cytron TestValueCast
29 */
30
31 import jdk.incubator.code.*;
32 import jdk.incubator.code.dialect.java.JavaOp;
33 import org.junit.jupiter.api.Assertions;
34 import org.junit.jupiter.api.Test;
35
36 import java.util.function.IntBinaryOperator;
37 import java.util.stream.Stream;
38
39 public class TestValueCast {
40
41 public JavaOp.LambdaOp f() {
42 IntBinaryOperator ibo = (@Reflect IntBinaryOperator) (a, b) -> {
43 if (a > b) {
44 a *= 2;
45 return a % b;
46 }
47 return a + b;
48 };
49 return (JavaOp.LambdaOp) Op.ofQuotable(ibo).get().op();
50 }
51
52 static Stream<Value> values(CodeElement<?, ?> r) {
53 return r.elements().mapMulti((e, c) -> {
54 switch (e) {
55 case Block block -> block.parameters().forEach(c);
56 case Op op -> c.accept(op.result());
57 case Body _ -> { }
58 }
59 });
60 }
61
62 @Test
63 public void testCast() {
64 JavaOp.LambdaOp f = f();
65 Stream<Value> stream = values(f);
66 stream.forEach(v -> {
67 switch (v) {
68 case Op.Result r -> Assertions.assertEquals(r, v.result());
69 case Block.Parameter p -> Assertions.assertEquals(p, v.parameter());
70 }
71 });
72 }
73
74 @Test
75 public void testExceptions() {
76 JavaOp.LambdaOp f = f();
77 Stream<Value> stream = values(f);
78 stream.forEach(v -> {
79 switch (v) {
80 case Op.Result r -> Assertions.assertThrows(IllegalStateException.class, () -> v.parameter());
81 case Block.Parameter p -> Assertions.assertThrows(IllegalStateException.class, () -> v.result());
82 }
83 });
84 }
85 }