1 import jdk.incubator.code.*;
2 import jdk.incubator.code.dialect.core.CoreOp;
3 import jdk.incubator.code.dialect.core.FunctionType;
4 import jdk.incubator.code.dialect.java.JavaType;
5 import org.junit.jupiter.api.Assertions;
6 import org.junit.jupiter.api.Test;
7
8 import java.lang.reflect.Method;
9 import java.util.ArrayList;
10 import java.util.List;
11 import java.util.function.IntUnaryOperator;
12
13 /*
14 * @test
15 * @modules jdk.incubator.code
16 * @run junit TestSealOp
17 */
18 public class TestSealOp {
19
20 @CodeReflection
21 static List<Integer> f(int i) {
22 return new ArrayList<>(i);
23 }
24
25 @Test
26 void test0() throws NoSuchMethodException {
27 Method m = this.getClass().getDeclaredMethod("f", int.class);
28 CoreOp.FuncOp f = Op.ofMethod(m).get();
29 assertOpIsCopiedWhenAddedToBlock(f);
30 }
31
32 @Test
33 void test1() {
34 Quotable q = (IntUnaryOperator & Quotable) i -> i / 2;
35 Quoted quoted = Op.ofQuotable(q).get();
36 CoreOp.QuotedOp quotedOp = (CoreOp.QuotedOp) quoted.op().ancestorBody().ancestorOp();
37 CoreOp.FuncOp funcOp = (CoreOp.FuncOp) quotedOp.ancestorBody().ancestorOp();
38 assertOpIsCopiedWhenAddedToBlock(funcOp);
39 }
40
41 @Test
42 void test2() {
43 CoreOp.ConstantOp constant = CoreOp.constant(JavaType.INT, 7);
44 constant.seal();
45 assertOpIsCopiedWhenAddedToBlock(constant);
46 }
47
48 @Test
49 void test3() {
50 CoreOp.FuncOp funcOp = CoreOp.func("f", FunctionType.FUNCTION_TYPE_VOID).body(b -> {
51 b.op(CoreOp.return_());
52 });
53 funcOp.seal();
54 funcOp.seal();
55 }
56
57 @Test
58 void test4() {
59 Quoted q = (int a, int b) -> {
60 return a + b;
61 };
62 CoreOp.QuotedOp quotedOp = (CoreOp.QuotedOp) q.op().ancestorBody().ancestorOp();
63 CoreOp.FuncOp funcOp = (CoreOp.FuncOp) quotedOp.ancestorBody().ancestorOp();
64 Assertions.assertTrue(funcOp.isSealed());
65 assertOpIsCopiedWhenAddedToBlock(funcOp);
66 }
67
68 @Test
69 void test5() { // freezing an already bound op should throw
70 Body.Builder body = Body.Builder.of(null, FunctionType.FUNCTION_TYPE_VOID);
71 Op.Result r = body.entryBlock().op(CoreOp.constant(JavaType.DOUBLE, 1d));
72 Assertions.assertThrows(IllegalStateException.class, () -> r.op().seal());
73 }
74
75 @Test
76 void test6() {
77 CoreOp.ConstantOp cop = CoreOp.constant(JavaType.LONG, 1L);
78 cop.setLocation(Location.NO_LOCATION);
79 cop.seal();
80 Assertions.assertThrows(IllegalStateException.class, () -> cop.setLocation(Location.NO_LOCATION));
81 }
82
83 void assertOpIsCopiedWhenAddedToBlock(Op op) {
84 Body.Builder body = Body.Builder.of(null, FunctionType.FUNCTION_TYPE_VOID);
85 body.entryBlock().op(op);
86 body.entryBlock().op(CoreOp.return_());
87 CoreOp.FuncOp funcOp = CoreOp.func("t", body);
88 boolean b = funcOp.body().entryBlock().ops().stream().allMatch(o -> o != op);
89 Assertions.assertTrue(b);
90 }
91 }