1 /*
2 * Copyright (c) 2024, 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. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 package jdk.incubator.code.dialect.java;
27
28 import jdk.incubator.code.*;
29 import jdk.incubator.code.dialect.core.*;
30 import jdk.incubator.code.extern.DialectFactory;
31 import jdk.incubator.code.extern.ExternalizedOp;
32 import jdk.incubator.code.extern.OpFactory;
33 import jdk.incubator.code.internal.BranchTarget;
34 import jdk.incubator.code.internal.ConstantValueAnalysis;
35 import jdk.incubator.code.internal.OpDeclaration;
36
37 import java.util.*;
38 import java.util.concurrent.atomic.AtomicBoolean;
39 import java.util.function.BiFunction;
40 import java.util.function.Consumer;
41 import java.util.function.Function;
42 import java.util.function.Predicate;
43
44 import static jdk.incubator.code.Op.Lowerable.loweringTransformer;
45 import static jdk.incubator.code.dialect.core.CoreOp.*;
46 import static jdk.incubator.code.dialect.java.JavaType.*;
47 import static jdk.incubator.code.internal.StructuralPreconditions.*;
48
49 /**
50 * The interface marking all Java operations and declaring factory methods for constructing Java operations.
51 * <p>
52 * A code model, produced by the Java compiler from Java program source, may consist of core operations and Java
53 * operations. Such a model represents the same Java program and preserves the program meaning as defined by the
54 * Java Language Specification.
55 * <p>
56 * Java operations model specific Java language constructs or Java program behavior. Some Java operations model
57 * structured control flow and nested code. These operations are transformable, commonly referred to as lowering, into
58 * a sequence of other core or Java operations. Those that implement {@link Op.Lowerable} can transform themselves and
59 * will transform associated operations that are not explicitly lowerable.
60 * <p>
61 * A code model, produced by the Java compiler from source, and consisting of core operations and Java operations
62 * can be transformed to one consisting only of non-lowerable operations, where all lowerable operations are lowered.
63 * This transformation preserves programming meaning. The resulting lowered code model also represents the same Java
64 * program.
65 */
66 public sealed interface JavaOp extends ExternalizedOp.Externalizable {
67
68 @Override
69 default String externalizeOpName() {
70 OpDeclaration opDecl = this.getClass().getDeclaredAnnotation(OpDeclaration.class);
71 assert opDecl != null : this.getClass().getName();
72 return opDecl.value();
73 }
74
75 /**
76 * An operation that models a Java expression
77 *
78 * @jls 15 Expressions
79 */
80 public sealed interface JavaExpression permits
81 ArithmeticOperation,
82 ArrayAccessOp.ArrayLoadOp,
83 ArrayAccessOp.ArrayStoreOp,
84 ArrayLengthOp,
85 CastOp,
86 ConvOp,
87 ConcatOp,
88 ConstantOp,
89 FieldAccessOp.FieldLoadOp,
90 FieldAccessOp.FieldStoreOp,
91 InstanceOfOp,
92 InvokeOp,
93 LambdaOp,
94 NewOp,
95 VarAccessOp.VarLoadOp,
96 VarAccessOp.VarStoreOp,
97 ConditionalExpressionOp,
98 ConditionalOp,
99 SwitchExpressionOp {
100
101 /**
102 * Evaluates an operation result whose operation models a constant expression.
103 *
104 * @apiNote {@linkplain jdk.incubator.code##java-code-models-heading Java code models} will model access to a constant
105 * variable as a constant operation whose constant value is the same as the constant variable's value.
106 *
107 * @param v the value to evaluate
108 * @return an {@code Optional} containing the evaluated result, otherwise an empty {@code Optional} if the value
109 * is not an instance of {@link Op.Result} or the operation does not model a constant expression
110 * @jls 15.29 Constant Expressions
111 */
112 static Optional<Object> evaluate(Value v) {
113 return new ConstantValueAnalysis().evaluate(v);
114 }
115
116 /**
117 * Evaluates an operation that models a constant expression.
118 *
119 * @apiNote {@linkplain jdk.incubator.code##java-code-models-heading Java code models} will model access to a constant
120 * variable as a constant operation whose constant value is the same as the constant variable's value.
121 *
122 * @param op the operation to evaluate
123 * @param <T> the type of the operation
124 * @return an {@code Optional} containing the evaluated result, otherwise an empty {@code Optional} if the
125 * operation does not model a constant expression
126 * @jls 15.29 Constant Expressions
127 */
128 static <T extends Op & JavaExpression> Optional<Object> evaluate(T op) {
129 return new ConstantValueAnalysis().evaluate(op.result());
130 }
131
132 }
133
134 /**
135 * An operation that models a Java statement.
136 *
137 * @jls 14.5 Statements
138 */
139 public sealed interface JavaStatement permits
140 ArrayAccessOp.ArrayStoreOp,
141 AssertOp,
142 FieldAccessOp.FieldStoreOp,
143 InvokeOp,
144 NewOp,
145 ReturnOp,
146 ThrowOp,
147 VarAccessOp.VarStoreOp,
148 VarOp,
149 BlockOp,
150 DoWhileOp,
151 EnhancedForOp,
152 ForOp,
153 IfOp,
154 StatementTargetingOp,
155 LabeledOp,
156 SynchronizedOp,
157 TryOp,
158 WhileOp,
159 YieldOp,
160 SwitchStatementOp {
161 }
162
163 /**
164 * An operation characteristic indicating the operation's behavior may be emulated using Java reflection.
165 * A reference is derived from or declared by the operation that can be resolved at runtime to
166 * an instance of a reflective handle or member. That handle or member can be operated on to
167 * emulate the operation's behavior, specifically as bytecode behavior.
168 */
169 public sealed interface ReflectiveOp {
170 }
171
172 /**
173 * An operation that performs access.
174 */
175 public sealed interface AccessOp permits
176 CoreOp.VarAccessOp,
177 FieldAccessOp,
178 ArrayAccessOp {
179 }
180
181 /**
182 * An operation characteristic for a body terminating operation that targets an ancestor operation for its control
183 * flow behavior.
184 */
185 public sealed interface TargetingOp
186 permits StatementTargetingOp, YieldOp, ReturnOp, TryOp.AbstractStagedTargetingOp {
187 /**
188 * {@return the target operation, which is an ancestor of this operation}
189 */
190 Op target();
191
192 /**
193 * Tests whether this operation targets or attempts to exit the given operation.
194 * <p>
195 * More specifically, this method tests whether the given operation is encountered when traversing this
196 * operation's ancestor operations up to and including the target operation.
197 *
198 * @apiNote
199 * A successful test may indicate that the given operation completes abruptly when control is passed from this
200 * operation to the target operation. For example, consider the following code, in which a {@code break}
201 * statement targets the labeled {@code for} statement in the middle of two other {@code for} statements:
202 * {@snippet lang = java:
203 * for (int i = 0; i < 10; i++) {
204 * middle:
205 * for (int j = 0; j < 10; j++) {
206 * for (int k = 0; k < 10; k++) {
207 * if (i * j * k < 200) {
208 * break middle;
209 * }
210 * }
211 * }
212 * }
213 * }
214 * The Java code model for the above code contains a break operation modeling the {@code break} statement. Its
215 * target is the {@code for} operation modeling the labeled {@code for} statement.
216 * This method will return {@code true} if the operation to test is the operation modeling the innermost
217 * {@code for} statement, and will return {@code false} if the operation to test is the operation modeling the
218 * outermost {@code for} statement.
219 *
220 * @param op the operation to test
221 * @return {@code true} if this operation targets or attempts to exit the given operation.
222 */
223 default boolean targetsOrAttemptsToExit(Op op) {
224 Op target = target();
225 return target == op || (target.isAncestorOf(op) && op.isAncestorOf((Op) this));
226 }
227 }
228
229
230 /**
231 * The lambda operation, that can model Java language lambda expressions.
232 * <p>
233 * Lambda operations are associated with a {@linkplain #functionalInterface() functional interface type}.
234 * They feature one body, the {@linkplain #body() function body}.
235 * The result type of a lambda operation is its functional interface type.
236 * <p>
237 * The function body takes as many arguments as the function type associated with the functional interface type.
238 * The function body yields a value if that function type has a non-{@linkplain JavaType#VOID void} return type.
239 * <p>
240 * Lambda operations can also model Java language method reference expressions. A method reference is modeled as a
241 * lambda operation whose function body forwards its parameters to a corresponding {@link InvokeOp}, and that
242 * yields the result (if any) of that operation.
243 * <p>
244 * Some lambda operations are <em>reflectable</em> (see {@link Reflect}), meaning their code model is persisted at
245 * runtime.
246 *
247 * @jls 15.27 Lambda Expressions
248 * @jls 15.13 Method Reference Expressions
249 * @jls 9.8 Functional Interfaces
250 * @jls 9.9 Function Types
251 */
252 @OpDeclaration(LambdaOp.NAME)
253 public static final class LambdaOp extends AbstractOp
254 implements JavaOp, Op.Invokable, Op.Lowerable, JavaExpression {
255
256 /**
257 * A builder for constructing a lambda operation.
258 */
259 public static class Builder {
260 final Body.Builder connectedAncestorBody;
261 final FunctionType signature;
262 final CodeType functionalInterface;
263 final List<CodeType> additionalInterfaces;
264 final boolean isReflectable;
265
266 Builder(Body.Builder connectedAncestorBody, FunctionType signature, CodeType functionalInterface) {
267 this.connectedAncestorBody = connectedAncestorBody;
268 this.signature = signature;
269 this.functionalInterface = functionalInterface;
270 this.additionalInterfaces = List.of();
271 this.isReflectable = false;
272 }
273
274 Builder(Body.Builder connectedAncestorBody, FunctionType signature, CodeType functionalInterface,
275 List<CodeType> additionalInterfaces, boolean isReflectable) {
276 this.connectedAncestorBody = connectedAncestorBody;
277 this.signature = signature;
278 this.functionalInterface = functionalInterface;
279 this.additionalInterfaces = List.copyOf(additionalInterfaces);
280 this.isReflectable = isReflectable;
281 }
282
283 /**
284 * Completes the lambda operation by adding the function body.
285 *
286 * @param c a consumer that populates the function body
287 * @return the completed lambda operation
288 */
289 public LambdaOp body(Consumer<Block.Builder> c) {
290 Body.Builder body = Body.Builder.of(connectedAncestorBody, signature);
291 c.accept(body.entryBlock());
292 return new LambdaOp(functionalInterface, body, additionalInterfaces, isReflectable);
293 }
294
295 /**
296 * Adds an additional interface to a lambda operation.
297 *
298 * @param additionalInterface lambda operation's additional interface type
299 * @return the new builder
300 */
301 public Builder additionalInterface(CodeType additionalInterface) {
302 List<CodeType> interfaces = new ArrayList<>(additionalInterfaces);
303 interfaces.add(additionalInterface);
304 return new Builder(connectedAncestorBody, signature, functionalInterface, interfaces, isReflectable);
305 }
306
307 /**
308 * Returns a builder that constructs a reflectable lambda operation.
309 *
310 * @return the new builder
311 * @see Reflect
312 */
313 public Builder reflectable() {
314 return new Builder(connectedAncestorBody, signature, functionalInterface, additionalInterfaces, true);
315 }
316 }
317
318 static final String NAME = "lambda";
319 static final String ATTRIBUTE_LAMBDA_ADDITIONAL_INTERFACES = NAME + ".additionalInterfaces";
320 static final String ATTRIBUTE_LAMBDA_IS_REFLECTABLE = NAME + ".isReflectable";
321
322 final CodeType functionalInterface;
323 final Body body;
324 final List<CodeType> additionalInterfaces;
325 final boolean isReflectable;
326
327 LambdaOp(ExternalizedOp def) {
328 this(def.resultType(),
329 requireSingleBody(def),
330 optionalAttribute(def, ATTRIBUTE_LAMBDA_ADDITIONAL_INTERFACES, false, TupleType.class)
331 .map(TupleType::componentTypes).orElse(List.of()),
332 optionalBooleanAttribute(def, ATTRIBUTE_LAMBDA_IS_REFLECTABLE));
333 }
334
335 LambdaOp(LambdaOp that, CodeContext cc, CodeTransformer ct) {
336 super(that, cc);
337
338 this.functionalInterface = that.functionalInterface;
339 this.body = that.body.transform(cc, ct).build(this);
340 this.additionalInterfaces = that.additionalInterfaces;
341 this.isReflectable = that.isReflectable;
342 }
343
344 @Override
345 public LambdaOp transform(CodeContext cc, CodeTransformer ct) {
346 return new LambdaOp(this, cc, ct);
347 }
348
349 LambdaOp(CodeType functionalInterface, Body.Builder bodyC, List<? extends CodeType> additionalInterfaces,
350 boolean isReflectable) {
351 super(List.of());
352
353 this.functionalInterface = functionalInterface;
354 this.additionalInterfaces = List.copyOf(additionalInterfaces);
355 this.body = bodyC.build(this);
356 this.isReflectable = isReflectable;
357 }
358
359 @Override
360 public List<Body> bodies() {
361 return List.of(body);
362 }
363
364 /**
365 * {@return the functional interface type modeled by this lambda operation}
366 */
367 public CodeType functionalInterface() {
368 return functionalInterface;
369 }
370
371 /**
372 * {@return the additional interface types modeled by this lambda operation}
373 */
374 public List<CodeType> additionalInterfaces() {
375 return additionalInterfaces;
376 }
377
378 @Override
379 public Body body() {
380 return body;
381 }
382
383 @Override
384 public Block.Builder lower(Block.Builder b, BiFunction<Block.Builder, Op, Block.Builder> _ignore) {
385 // Isolate body with respect to ancestor transformations
386 b.withContextAndTransformer(b.context(), CodeTransformer.LOWERING_TRANSFORMER).add(this);
387 return b;
388 }
389
390 @Override
391 public CodeType resultType() {
392 return functionalInterface();
393 }
394
395 /**
396 * {@return whether this lambda operation is reflectable}
397 * @see Reflect
398 */
399 public boolean isReflectable() {
400 return isReflectable;
401 }
402
403 @Override
404 public Map<String, Object> externalize() {
405 return additionalInterfaces.isEmpty()
406 ? Map.of(ATTRIBUTE_LAMBDA_IS_REFLECTABLE, isReflectable)
407 : Map.of(ATTRIBUTE_LAMBDA_ADDITIONAL_INTERFACES, CoreType.tupleType(additionalInterfaces),
408 ATTRIBUTE_LAMBDA_IS_REFLECTABLE, isReflectable);
409 }
410
411 /**
412 * Determines if this lambda operation could have originated from a
413 * method reference declared in Java source code.
414 * <p>
415 * Such a lambda operation is one with the following constraints:
416 * <ol>
417 * <li>Zero or one captured value (assuming correspondence to the {@code this} variable).
418 * <li>A body with only one (entry) block that contains only variable declaration
419 * operations, variable load operations, invoke operations to box or unbox
420 * primitive values, a single invoke operation to the method that is
421 * referenced, and a return operation.
422 * <li>if the return operation returns a non-void result then that result is,
423 * or uniquely depends on, the result of the referencing invoke operation.
424 * <li>If the lambda operation captures one value then the first operand corresponds
425 * to captured the value, and subsequent operands of the referencing invocation
426 * operation are, or uniquely depend on, the lambda operation's parameters, in order.
427 * Otherwise, the first and subsequent operands of the referencing invocation
428 * operation are, or uniquely depend on, the lambda operation's parameters, in order.
429 * </ol>
430 * A value, V2, uniquely depends on another value, V1, if the graph of what V2 depends on
431 * contains only nodes with single edges terminating in V1, and the graph of what depends on V1
432 * is bidirectionally equal to the graph of what V2 depends on.
433 *
434 * @return the invocation operation to the method referenced by the lambda
435 * operation, otherwise empty.
436 */
437 public Optional<InvokeOp> methodReference() {
438 // Single block
439 if (body().blocks().size() > 1) {
440 return Optional.empty();
441 }
442
443 // Zero or one (this) capture
444 List<Value> cvs = capturedValues();
445 if (cvs.size() > 1) {
446 return Optional.empty();
447 }
448
449 Map<Value, Value> valueMapping = new HashMap<>();
450 InvokeOp methodRefInvokeOp = extractMethodInvoke(valueMapping, body().entryBlock().ops());
451 if (methodRefInvokeOp == null) {
452 return Optional.empty();
453 }
454
455 // Lambda's parameters map in encounter order with the invocation's operands
456 List<Value> lambdaParameters = new ArrayList<>();
457 if (cvs.size() == 1) {
458 lambdaParameters.add(cvs.getFirst());
459 }
460 lambdaParameters.addAll(parameters());
461 List<Value> methodRefOperands = methodRefInvokeOp.operands().stream().map(valueMapping::get).toList();
462 if (!lambdaParameters.equals(methodRefOperands)) {
463 return Optional.empty();
464 }
465
466 return Optional.of(methodRefInvokeOp);
467 }
468
469 /**
470 * Determines if this lambda operation contains a direct invocation of a method.
471 * <p>
472 * Such a lambda operation is one with the following constraints:
473 * <ol>
474 * <li>A body with only one (entry) block that contains only variable declaration
475 * operations, variable load operations, invoke operations to box or unbox
476 * primitive values, a single invoke operation to the method that is
477 * referenced, and a return operation.
478 * <li>if the return operation returns a non-void result then that result is,
479 * or uniquely depends on, the result of the referencing invoke operation.
480 * </ol>
481 * A value, V2, uniquely depends on another value, V1, if the graph of what V2 depends on
482 * contains only nodes with single edges terminating in V1, and the graph of what depends on V1
483 * is bidirectionally equal to the graph of what V2 depends on.
484 *
485 * @return the invocation operation to the method referenced by the lambda
486 * operation, otherwise empty.
487 */
488 public Optional<InvokeOp> directInvocation() {
489 // Single block
490 if (body().blocks().size() > 1) {
491 return Optional.empty();
492 }
493
494 Map<Value, Value> valueMapping = new HashMap<>();
495 InvokeOp methodRefInvokeOp = extractMethodInvoke(valueMapping, body().entryBlock().ops());
496 if (methodRefInvokeOp == null) {
497 return Optional.empty();
498 }
499
500 return Optional.of(methodRefInvokeOp);
501 }
502
503 /**
504 * Converts this lambda operation to an equivalent function operation.
505 *
506 * @param lambdaName the name to use for the resulting function (may be empty, or {@code null})
507 * @return a function operation that models this lambda
508 */
509 public CoreOp.FuncOp toFuncOp(String lambdaName) {
510 if (lambdaName == null) lambdaName = "";
511 List<CodeType> parameters = new ArrayList<>(this.invokableSignature().parameterTypes());
512 for (Value v : this.capturedValues()) {
513 CodeType capturedType = v.type() instanceof VarType varType ? varType.valueType() : v.type();
514 parameters.add(capturedType);
515 }
516 return CoreOp.func(lambdaName, CoreType.functionType(this.invokableSignature().returnType(), parameters)).body(builder -> {
517 int idx = this.invokableSignature().parameterTypes().size();
518 for (Value v : capturedValues()) {
519 Block.Parameter p = builder.parameters().get(idx++);
520 Value functionValue = v.type() instanceof VarType ? builder.add(CoreOp.var(p)) : p;
521 builder.context().mapValue(v, functionValue);
522 }
523 List<Block.Parameter> outputValues = builder.parameters().subList(0, this.invokableSignature().parameterTypes().size());
524 builder.transformBody(this.body(), outputValues, CodeTransformer.COPYING_TRANSFORMER);
525 });
526 }
527
528 static InvokeOp extractMethodInvoke(Map<Value, Value> valueMapping, List<Op> ops) {
529 InvokeOp methodRefInvokeOp = null;
530 for (Op op : ops) {
531 switch (op) {
532 case VarOp varOp -> {
533 if (isValueUsedWithOp(varOp.result(), o -> o instanceof VarAccessOp.VarStoreOp)) {
534 return null;
535 }
536 }
537 case VarAccessOp.VarLoadOp varLoadOp -> {
538 Value v = varLoadOp.varOp().operands().getFirst();
539 valueMapping.put(varLoadOp.result(), valueMapping.getOrDefault(v, v));
540 }
541 case InvokeOp iop when isBoxOrUnboxInvocation(iop) -> {
542 Value v = iop.operands().getFirst();
543 valueMapping.put(iop.result(), valueMapping.getOrDefault(v, v));
544 }
545 case InvokeOp iop -> {
546 if (methodRefInvokeOp != null) {
547 return null;
548 }
549
550 for (Value o : iop.operands()) {
551 valueMapping.put(o, valueMapping.getOrDefault(o, o));
552 }
553 methodRefInvokeOp = iop;
554 }
555 case ReturnOp rop -> {
556 if (methodRefInvokeOp == null) {
557 return null;
558 }
559 Value r = rop.returnValue();
560 if (r == null) break;
561 if (!(valueMapping.getOrDefault(r, r) instanceof Result invokeResult)) {
562 return null;
563 }
564 if (invokeResult.op() != methodRefInvokeOp) {
565 return null;
566 }
567 assert methodRefInvokeOp.result().uses().size() == 1;
568 }
569 default -> {
570 return null;
571 }
572 }
573 }
574
575 return methodRefInvokeOp;
576 }
577
578 private static boolean isValueUsedWithOp(Value value, Predicate<Op> opPredicate) {
579 for (Result user : value.uses()) {
580 if (opPredicate.test(user.op())) {
581 return true;
582 }
583 }
584 return false;
585 }
586
587 // @@@ Move to functionality on JavaType(s)
588 static final Set<String> UNBOX_NAMES = Set.of(
589 "byteValue",
590 "shortValue",
591 "charValue",
592 "intValue",
593 "longValue",
594 "floatValue",
595 "doubleValue",
596 "booleanValue");
597
598 private static boolean isBoxOrUnboxInvocation(InvokeOp iop) {
599 MethodRef mr = iop.invokeReference();
600 return mr.refType() instanceof ClassType ct && ct.unbox().isPresent() &&
601 (UNBOX_NAMES.contains(mr.name()) || mr.name().equals("valueOf"));
602 }
603 }
604
605 /**
606 * The throw operation, that can model the Java language throw statement.
607 * <p>
608 * A throw operation is a body terminating operation that features one operand, the value being thrown.
609 * <p>
610 * The result type of a throw operation is {@link JavaType#VOID}.
611 *
612 * @jls 14.18 The throw Statement
613 */
614 @OpDeclaration(ThrowOp.NAME)
615 public static final class ThrowOp extends AbstractOp.Terminating
616 implements JavaOp, JavaStatement {
617 static final String NAME = "throw";
618
619 ThrowOp(ExternalizedOp def) {
620 this(requireSingleOperand(def));
621 }
622
623 ThrowOp(ThrowOp that, CodeContext cc) {
624 super(that, cc);
625 }
626
627 @Override
628 public ThrowOp transform(CodeContext cc, CodeTransformer ct) {
629 return new ThrowOp(this, cc);
630 }
631
632 ThrowOp(Value e) {
633 super(List.of(e));
634 }
635
636 /**
637 * {@return the value being thrown}
638 */
639 public Value argumentOperand() {
640 return operands().get(0);
641 }
642
643 @Override
644 public CodeType resultType() {
645 return VOID;
646 }
647 }
648
649 /**
650 * The assertion operation, that can model Java language assert statements.
651 * <p>
652 * Assert operations feature one or two bodies. The first body, called the <em>predicate body</em>, models the
653 * assertion condition. If present, the second body, called the <em>details body</em>, models the detail
654 * expression.
655 * <p>
656 * The predicate body should accept no arguments and yield a {@link JavaType#BOOLEAN} value.
657 * If present, the details body should accept no arguments and yield a value.
658 * <p>
659 * The result type of an assert operation is {@link JavaType#VOID}.
660 *
661 * @jls 14.10 The assert Statement
662 */
663 @OpDeclaration(AssertOp.NAME)
664 public static final class AssertOp extends AbstractOp
665 implements JavaOp, Op.Nested, Op.Lowerable, JavaStatement {
666 static final String NAME = "assert";
667
668 private final List<Body> bodies;
669
670 AssertOp(ExternalizedOp def) {
671 this(def.bodyDefinitions());
672 }
673
674 AssertOp(List<Body.Builder> bodies) {
675 if (bodies.size() != 1 && bodies.size() != 2) {
676 throw structuralException(NAME, "requires 1 or 2 bodies, found %d".formatted(bodies.size()));
677 }
678 requireBodySignature(NAME + " predicate", bodies.get(0), CoreType.functionType(BOOLEAN));
679 if (bodies.size() > 1) {
680 requireNonVoidReturnType(NAME + " details", bodies.get(1), 0);
681 }
682 super(List.of());
683 this.bodies = bodies.stream().map(b -> b.build(this)).toList();
684 }
685
686 AssertOp(AssertOp that, CodeContext cc, CodeTransformer ct) {
687 super(that, cc);
688 this.bodies = that.bodies.stream().map(b -> b.transform(cc, ct).build(this)).toList();
689 }
690
691 @Override
692 public Op transform(CodeContext cc, CodeTransformer ct) {
693 return new AssertOp(this, cc, ct);
694 }
695
696 @Override
697 public CodeType resultType() {
698 return VOID;
699 }
700
701 @Override
702 public List<Body> bodies() {
703 return bodies;
704 }
705
706 /**
707 * {@return the predicate body}
708 */
709 public Body predicateBody() {
710 return bodies.get(0);
711 }
712
713 /**
714 * {@return the details body, or {@code null} if not present}
715 */
716 public Body detailsBody() {
717 return bodies.size() == 2 ? bodies.get(1) : null;
718 }
719
720 @Override
721 public Block.Builder lower(Block.Builder b, BiFunction<Block.Builder, Op, Block.Builder> inherited) {
722 Block.Builder exit = b.block();
723 Block.Builder throwBlock = b.block();
724
725 ControlFlowBooleanExpressionOp.lowerBooleanBody(b, predicateBody(), List.of(),
726 new ControlFlowBooleanExpressionOp.ConditionalBranchContinuation(exit.reference(), throwBlock.reference()),
727 inherited);
728
729 Body detailsBody = detailsBody();
730 if (detailsBody != null) {
731 throwBlock.transformBody(detailsBody, List.of(), loweringTransformer(inherited, (block, op) -> {
732 if (op instanceof CoreOp.YieldOp yo) {
733 Value detailValue = block.context().getValue(yo.yieldValue());
734 MethodRef assertConstructor = MethodRef.constructor(type(AssertionError.class),
735 switch (detailValue.type()) {
736 case PrimitiveType pt -> {
737 if (pt == BYTE || pt == SHORT) {
738 detailValue = block.add(conv(INT, detailValue));
739 yield INT;
740 }
741 yield pt;
742 }
743 default -> J_L_OBJECT;
744 });
745 block.add(throw_(block.add(new_(assertConstructor, detailValue))
746 ));
747 return block;
748 } else {
749 return null;
750 }
751 }));
752 } else {
753 throwBlock.add(throw_(
754 throwBlock.add(new_(MethodRef.constructor(AssertionError.class)))
755 ));
756 }
757
758 return exit;
759 }
760 }
761
762 /**
763 * A monitor operation.
764 */
765 public sealed abstract static class MonitorOp extends AbstractOp
766 implements JavaOp {
767 MonitorOp(MonitorOp that, CodeContext cc) {
768 super(that, cc);
769 }
770
771 MonitorOp(Value monitor) {
772 super(List.of(monitor));
773 }
774
775 /**
776 * {@return the monitor value}
777 */
778 public Value monitorOperand() {
779 return operands().getFirst();
780 }
781
782 @Override
783 public CodeType resultType() {
784 return VOID;
785 }
786
787 /**
788 * The monitor enter operation.
789 */
790 @OpDeclaration(MonitorEnterOp.NAME)
791 public static final class MonitorEnterOp extends MonitorOp {
792 static final String NAME = "monitor.enter";
793
794 MonitorEnterOp(ExternalizedOp def) {
795 this(requireSingleOperand(def));
796 }
797
798 MonitorEnterOp(MonitorEnterOp that, CodeContext cc) {
799 super(that, cc);
800 }
801
802 @Override
803 public MonitorEnterOp transform(CodeContext cc, CodeTransformer ct) {
804 return new MonitorEnterOp(this, cc);
805 }
806
807 MonitorEnterOp(Value monitor) {
808 super(monitor);
809 }
810 }
811
812 /**
813 * The monitor exit operation.
814 */
815 @OpDeclaration(MonitorExitOp.NAME)
816 public static final class MonitorExitOp extends MonitorOp {
817 static final String NAME = "monitor.exit";
818
819 MonitorExitOp(ExternalizedOp def) {
820 this(requireSingleOperand(def));
821 }
822
823 MonitorExitOp(MonitorExitOp that, CodeContext cc) {
824 super(that, cc);
825 }
826
827 @Override
828 public MonitorExitOp transform(CodeContext cc, CodeTransformer ct) {
829 return new MonitorExitOp(this, cc);
830 }
831
832 MonitorExitOp(Value monitor) {
833 super(monitor);
834 }
835 }
836 }
837
838 /**
839 * The invoke operation, that can model Java language method invocation expressions.
840 * <p>
841 * The method invoked by an invoke operation is specified using a
842 * {@linkplain MethodRef method reference}.
843 * The operands of an invoke operation are specified as follows:
844 * <ul>
845 * <li>For {@linkplain InvokeKind#STATIC static} invocations, operands are the invocation arguments.</li>
846 * <li>For {@linkplain InvokeKind#INSTANCE instance} and {@linkplain InvokeKind#SUPER super} invocations, the first
847 * operand is the receiver and the remaining operands are the invocation arguments.</li>
848 * </ul>
849 *
850 * @jls 15.12 Method Invocation Expressions
851 */
852 @OpDeclaration(InvokeOp.NAME)
853 public static final class InvokeOp extends AbstractOp
854 implements JavaOp, ReflectiveOp, JavaExpression, JavaStatement {
855
856 /**
857 * The kind of invocation.
858 */
859 public enum InvokeKind {
860 /**
861 * An invocation on a class (static) method.
862 */
863 STATIC,
864 /**
865 * An invocation on an instance method.
866 */
867 INSTANCE,
868 /**
869 * A super invocation on an instance method.
870 */
871 SUPER
872 }
873
874 static final String NAME = "invoke";
875 /** The externalized attribute key for a method invocation reference. */
876 static final String ATTRIBUTE_INVOKE_REF = NAME + ".ref";
877 /** The externalized attribute key indicating the invocation kind. */
878 static final String ATTRIBUTE_INVOKE_KIND = NAME + ".kind";
879 /** The externalized attribute key for marking a varargs invocation. */
880 static final String ATTRIBUTE_INVOKE_VARARGS = NAME + ".varargs";
881
882 final InvokeKind invokeKind;
883 final boolean isVarArgs;
884 final MethodRef invokeReference;
885 final CodeType resultType;
886
887 InvokeOp(ExternalizedOp def) {
888 // Required attribute
889 MethodRef invokeRef = requireAttribute(def, ATTRIBUTE_INVOKE_REF, true, MethodRef.class);
890
891 // If not present defaults to false
892 boolean isVarArgs = optionalBooleanAttribute(def, ATTRIBUTE_INVOKE_VARARGS);
893
894 // If not present and is not varargs defaults to class or instance invocation
895 // based on number of operands and parameters
896 InvokeKind ik = optionalAttribute(def, ATTRIBUTE_INVOKE_KIND, false, Object.class).map(v ->
897 switch (v) {
898 case String s -> InvokeKind.valueOf(s);
899 case InvokeKind k -> k;
900 default -> throw unsupportedAttributeValueException(def, ATTRIBUTE_INVOKE_KIND, v);
901 }).orElseGet(() -> {
902 if (isVarArgs) {
903 // If varargs then we cannot infer invoke kind
904 throw unsupportedAttributeValueException(def, ATTRIBUTE_INVOKE_KIND, null);
905 }
906 int paramCount = invokeRef.signature().parameterTypes().size();
907 int argCount = def.operands().size();
908 return (argCount == paramCount + 1)
909 ? InvokeKind.INSTANCE
910 : InvokeKind.STATIC;
911 });
912
913
914 this(ik, isVarArgs, def.resultType(), invokeRef, def.operands());
915 }
916
917 InvokeOp(InvokeOp that, CodeContext cc) {
918 super(that, cc);
919
920 this.invokeKind = that.invokeKind;
921 this.isVarArgs = that.isVarArgs;
922 this.invokeReference = that.invokeReference;
923 this.resultType = that.resultType;
924 }
925
926 @Override
927 public InvokeOp transform(CodeContext cc, CodeTransformer ct) {
928 return new InvokeOp(this, cc);
929 }
930
931 InvokeOp(InvokeKind invokeKind, boolean isVarArgs, CodeType resultType, MethodRef invokeReference, List<Value> args) {
932 super(args);
933
934 validateArgCount(invokeKind, isVarArgs, invokeReference, args);
935
936 this.invokeKind = invokeKind;
937 this.isVarArgs = isVarArgs;
938 this.invokeReference = invokeReference;
939 this.resultType = resultType;
940 }
941
942 static void validateArgCount(InvokeKind invokeKind, boolean isVarArgs, MethodRef invokeRef, List<Value> operands) {
943 int paramCount = invokeRef.signature().parameterTypes().size();
944 int argCount = operands.size() - (invokeKind == InvokeKind.STATIC ? 0 : 1);
945 if ((!isVarArgs && argCount != paramCount)
946 || argCount < paramCount - 1) {
947 throw structuralException(NAME, "kind=%s, varargs=%s, requires %s%d operands, found %d".formatted(
948 invokeKind,
949 isVarArgs,
950 isVarArgs ? "at least " : "",
951 isVarArgs ? paramCount - 1 : paramCount,
952 argCount));
953 }
954 }
955
956 @Override
957 public Map<String, Object> externalize() {
958 HashMap<String, Object> m = new HashMap<>();
959 m.put("", invokeReference);
960 if (isVarArgs) {
961 // If varargs then we need to declare the invoke.kind attribute
962 // Given a method `A::m(A... more)` and an invocation with one
963 // operand, we don't know if that operand corresponds to the
964 // receiver or a method argument
965 m.put(ATTRIBUTE_INVOKE_KIND, invokeKind);
966 m.put(ATTRIBUTE_INVOKE_VARARGS, isVarArgs);
967 } else if (invokeKind == InvokeKind.SUPER) {
968 m.put(ATTRIBUTE_INVOKE_KIND, invokeKind);
969 }
970 return Collections.unmodifiableMap(m);
971 }
972
973 /**
974 * {@return the invocation kind}
975 */
976 public InvokeKind invokeKind() {
977 return invokeKind;
978 }
979
980 /**
981 * {@return {@code true} if this invocation uses a variable number of arguments}
982 */
983 public boolean isVarArgs() {
984 return isVarArgs;
985 }
986
987 /**
988 * {@return the method invocation reference}
989 */
990 public MethodRef invokeReference() {
991 return invokeReference;
992 }
993
994 /**
995 * {@return {@code true} if this invocation refers to an instance method)}
996 */
997 public boolean hasReceiver() {
998 return invokeKind != InvokeKind.STATIC;
999 }
1000
1001 /**
1002 * {@return the receiver, otherwise {@code null} if no receiver}
1003 */
1004 public Value receiverOperand() {
1005 return hasReceiver() ? operands().getFirst() : null;
1006 }
1007
1008 /**
1009 * {@return the operands used as varargs, if this is a varargs invocation,
1010 * or {@code null}}
1011 */
1012 public List<Value> varArgOperands() {
1013 if (!isVarArgs) {
1014 return null;
1015 }
1016
1017 int operandCount = operands().size();
1018 int argCount = operandCount - (invokeKind == InvokeKind.STATIC ? 0 : 1);
1019 int paramCount = invokeReference.signature().parameterTypes().size();
1020 int varArgCount = argCount - (paramCount - 1);
1021 return operands().subList(operandCount - varArgCount, operandCount);
1022 }
1023
1024 /**
1025 * {@return the method invocation arguments, including the receiver as the first argument if present}
1026 */
1027 public List<Value> argOperands() {
1028 if (!isVarArgs) {
1029 return operands();
1030 }
1031 int paramCount = invokeReference().signature().parameterTypes().size();
1032 int argOperandsCount = paramCount - (invokeKind() == InvokeKind.STATIC ? 1 : 0);
1033 return operands().subList(0, argOperandsCount);
1034 }
1035
1036 @Override
1037 public CodeType resultType() {
1038 return resultType;
1039 }
1040 }
1041
1042 /**
1043 * The conversion operation, that can model Java language cast expressions
1044 * for numerical conversion, or such implicit conversion.
1045 * <p>
1046 * Conversion operations feature one operand, the value to convert.
1047 *
1048 * @jls 15.16 Cast Expressions
1049 * @jls 5.1.2 Widening Primitive Conversion
1050 * @jls 5.1.3 Narrowing Primitive Conversion
1051 */
1052 @OpDeclaration(ConvOp.NAME)
1053 public static final class ConvOp extends AbstractOp
1054 implements JavaOp, JavaExpression {
1055 static final String NAME = "conv";
1056
1057 final CodeType resultType;
1058
1059 ConvOp(ExternalizedOp def) {
1060 this(def.resultType(), requireSingleOperand(def));
1061 }
1062
1063 ConvOp(ConvOp that, CodeContext cc) {
1064 super(that, cc);
1065
1066 this.resultType = that.resultType;
1067 }
1068
1069 @Override
1070 public Op transform(CodeContext cc, CodeTransformer ct) {
1071 return new ConvOp(this, cc);
1072 }
1073
1074 ConvOp(CodeType resultType, Value arg) {
1075 super(List.of(arg));
1076
1077 this.resultType = resultType;
1078 }
1079
1080 /**
1081 * {@return the value to convert}
1082 */
1083 public Value valueOperand() {
1084 return operands().getFirst();
1085 }
1086
1087 @Override
1088 public CodeType resultType() {
1089 return resultType;
1090 }
1091 }
1092
1093 /**
1094 * The new operation, that can model Java language instance creation expressions and array creation expressions.
1095 * <p>
1096 * The constructor invoked by a new operation is specified using a
1097 * {@linkplain MethodRef constructor reference}.
1098 * New operations feature operands corresponding to the constructor arguments.
1099 *
1100 * @jls 15.9 Class Instance Creation Expressions
1101 * @jls 15.10.1 Array Creation Expressions
1102 */
1103 @OpDeclaration(NewOp.NAME)
1104 public static final class NewOp extends AbstractOp
1105 implements JavaOp, ReflectiveOp, JavaExpression, JavaStatement {
1106
1107 static final String NAME = "new";
1108 /**
1109 * The externalized attribute key for a constructor reference in a new operation.
1110 */
1111 static final String ATTRIBUTE_NEW_REF = NAME + ".ref";
1112 /**
1113 * The externalized attribute key indicating a varargs constructor in a new operation.
1114 */
1115 static final String ATTRIBUTE_NEW_VARARGS = NAME + ".varargs";
1116
1117 final boolean isVarArgs;
1118 final MethodRef constructorReference;
1119 final CodeType resultType;
1120
1121 NewOp(ExternalizedOp def) {
1122 this(optionalBooleanAttribute(def, ATTRIBUTE_NEW_VARARGS),
1123 def.resultType(),
1124 requireAttribute(def, ATTRIBUTE_NEW_REF, true, MethodRef.class),
1125 def.operands());
1126 }
1127
1128 NewOp(NewOp that, CodeContext cc) {
1129 super(that, cc);
1130
1131 this.isVarArgs = that.isVarArgs;
1132 this.constructorReference = that.constructorReference;
1133 this.resultType = that.resultType;
1134 }
1135
1136 @Override
1137 public NewOp transform(CodeContext cc, CodeTransformer ct) {
1138 return new NewOp(this, cc);
1139 }
1140
1141 NewOp(boolean isVarargs, CodeType resultType, MethodRef ctorRef, List<Value> args) {
1142 validateArgCount(isVarargs, ctorRef, args);
1143 if (!ctorRef.isConstructor()) {
1144 throw structuralException(NAME, "requires a constructor reference, found %s".formatted(ctorRef));
1145 }
1146 super(args);
1147 this.isVarArgs = isVarargs;
1148 this.constructorReference = ctorRef;
1149 this.resultType = resultType;
1150 }
1151
1152 static void validateArgCount(boolean isVarArgs, MethodRef ctorRef, List<Value> operands) {
1153 int paramCount = ctorRef.signature().parameterTypes().size();
1154 int argCount = operands.size();
1155 if ((!isVarArgs && argCount != paramCount)
1156 || argCount < paramCount - 1) {
1157 throw structuralException(NAME, "varargs=%s, requires %s%d operands, found %d".formatted(
1158 isVarArgs,
1159 isVarArgs ? "at least " : "",
1160 isVarArgs ? paramCount - 1 : paramCount,
1161 argCount));
1162 }
1163 }
1164
1165 @Override
1166 public Map<String, Object> externalize() {
1167 HashMap<String, Object> m = new HashMap<>();
1168 m.put("", constructorReference);
1169 if (isVarArgs) {
1170 m.put(ATTRIBUTE_NEW_VARARGS, isVarArgs);
1171 }
1172 return Collections.unmodifiableMap(m);
1173 }
1174
1175 /**
1176 * {@return {@code true}, if this instance creation operation is a varargs constructor call}
1177 */
1178 public boolean isVarargs() {
1179 return isVarArgs;
1180 }
1181
1182 /**
1183 * {@return the constructor reference for this instance creation operation}
1184 */
1185 public MethodRef constructorReference() {
1186 return constructorReference;
1187 }
1188
1189 @Override
1190 public CodeType resultType() {
1191 return resultType;
1192 }
1193 }
1194
1195 /**
1196 * A field access operation, that can model Java language field access expressions.
1197 * <p>
1198 * The field accessed by a field access operation is specified using a {@linkplain FieldRef field
1199 * reference}.
1200 * <p>
1201 * Instance field accesses feature a receiver operand. Static field accesses have no receiver operand.
1202 *
1203 * @see CoreOp.VarAccessOp
1204 * @jls 15.11 Field Access Expressions
1205 */
1206 public sealed abstract static class FieldAccessOp extends AbstractOp
1207 implements JavaOp, AccessOp, ReflectiveOp {
1208 /**
1209 * The externalized attribute modeling the field reference.
1210 */
1211 static final String ATTRIBUTE_FIELD_REF = "field.ref";
1212
1213 final FieldRef fieldReference;
1214
1215 FieldAccessOp(FieldAccessOp that, CodeContext cc) {
1216 super(that, cc);
1217 this.fieldReference = that.fieldReference;
1218 }
1219
1220 FieldAccessOp(List<Value> operands,
1221 FieldRef fieldReference) {
1222 super(operands);
1223
1224 this.fieldReference = fieldReference;
1225 }
1226
1227 @Override
1228 public Map<String, Object> externalize() {
1229 return Map.of("", fieldReference);
1230 }
1231
1232 /**
1233 * {@return the reference to the accessed field}
1234 */
1235 public final FieldRef fieldReference() {
1236 return fieldReference;
1237 }
1238
1239 /**
1240 * {@return the value of the receiver, or {@code null} if no receiver}
1241 */
1242 public Value receiverOperand() {
1243 return operands().isEmpty() ? null : operands().getFirst();
1244 }
1245
1246 /**
1247 * The field load operation, that can model Java language field access expressions used to read a field value.
1248 *
1249 * @see CoreOp.VarAccessOp.VarLoadOp
1250 * @jls 15.11 Field Access Expressions
1251 */
1252 @OpDeclaration(FieldLoadOp.NAME)
1253 public static final class FieldLoadOp extends FieldAccessOp
1254 implements JavaExpression {
1255 static final String NAME = "field.load";
1256
1257 final CodeType resultType;
1258
1259 FieldLoadOp(ExternalizedOp def) {
1260 super(requireOperands(def, 0, 1), requireAttribute(def, ATTRIBUTE_FIELD_REF, true, FieldRef.class));
1261 this.resultType = def.resultType();
1262 }
1263
1264 FieldLoadOp(FieldLoadOp that, CodeContext cc) {
1265 super(that, cc);
1266
1267 resultType = that.resultType();
1268 }
1269
1270 @Override
1271 public FieldLoadOp transform(CodeContext cc, CodeTransformer ct) {
1272 return new FieldLoadOp(this, cc);
1273 }
1274
1275 // instance
1276 FieldLoadOp(CodeType resultType, FieldRef fieldRef, Value receiver) {
1277 super(List.of(receiver), fieldRef);
1278
1279 this.resultType = resultType;
1280 }
1281
1282 // static
1283 FieldLoadOp(CodeType resultType, FieldRef fieldRef) {
1284 super(List.of(), fieldRef);
1285
1286 this.resultType = resultType;
1287 }
1288
1289 @Override
1290 public CodeType resultType() {
1291 return resultType;
1292 }
1293 }
1294
1295 /**
1296 * The field store operation, that can model Java language field access expressions used to write a field value.
1297 * <p>
1298 * The result type is always {@link JavaType#VOID}.
1299 *
1300 * @see CoreOp.VarAccessOp.VarStoreOp
1301 * @jls 15.11 Field Access Expressions
1302 */
1303 @OpDeclaration(FieldStoreOp.NAME)
1304 public static final class FieldStoreOp extends FieldAccessOp
1305 implements JavaExpression, JavaStatement {
1306 static final String NAME = "field.store";
1307
1308 FieldStoreOp(ExternalizedOp def) {
1309 super(requireOperands(def, 1, 2), requireAttribute(def, ATTRIBUTE_FIELD_REF, true, FieldRef.class));
1310 }
1311
1312 FieldStoreOp(FieldStoreOp that, CodeContext cc) {
1313 super(that, cc);
1314 }
1315
1316 @Override
1317 public FieldStoreOp transform(CodeContext cc, CodeTransformer ct) {
1318 return new FieldStoreOp(this, cc);
1319 }
1320
1321 // instance
1322 FieldStoreOp(FieldRef fieldRef, Value receiver, Value v) {
1323 super(List.of(receiver, v), fieldRef);
1324 }
1325
1326 // static
1327 FieldStoreOp(FieldRef fieldRef, Value v) {
1328 super(List.of(v), fieldRef);
1329 }
1330
1331 /**
1332 * {@return the value to store}
1333 */
1334 public Value valueOperand() {
1335 return operands().get(operands().size() - 1);
1336 }
1337
1338 @Override
1339 public CodeType resultType() {
1340 return VOID;
1341 }
1342 }
1343 }
1344
1345 /**
1346 * The array length operation, that can model Java language field access expressions to the length field of an
1347 * array.
1348 * <p>
1349 * Array length operations feature one operand, the array value.
1350 * The result type of an array length operation is {@link JavaType#INT}.
1351 *
1352 * @jls 15.11 Field Access Expressions
1353 */
1354 @OpDeclaration(ArrayLengthOp.NAME)
1355 public static final class ArrayLengthOp extends AbstractOp
1356 implements JavaOp, ReflectiveOp, JavaExpression {
1357 static final String NAME = "array.length";
1358
1359 ArrayLengthOp(ExternalizedOp def) {
1360 this(requireSingleOperand(def));
1361 }
1362
1363 ArrayLengthOp(ArrayLengthOp that, CodeContext cc) {
1364 super(that, cc);
1365 }
1366
1367 @Override
1368 public ArrayLengthOp transform(CodeContext cc, CodeTransformer ct) {
1369 return new ArrayLengthOp(this, cc);
1370 }
1371
1372 ArrayLengthOp(Value array) {
1373 super(List.of(array));
1374 }
1375
1376 /**
1377 * {@return the larray}
1378 */
1379 public Value arrayOperand() {
1380 return operands().getFirst();
1381 }
1382
1383 @Override
1384 public CodeType resultType() {
1385 return INT;
1386 }
1387 }
1388
1389 /**
1390 * The array access operation, that can model Java language array access expressions.
1391 * <p>
1392 * Array load operations feature two operands, the array value and the index value.
1393 * Array store operations feature an additional operand, the stored value.
1394 *
1395 * @jls 15.10.3 Array Access Expressions
1396 */
1397 public sealed abstract static class ArrayAccessOp extends AbstractOp
1398 implements JavaOp, AccessOp, ReflectiveOp {
1399
1400 ArrayAccessOp(ArrayAccessOp that, CodeContext cc) {
1401 super(that, cc);
1402 }
1403
1404 ArrayAccessOp(List<Value> operands) {
1405 super(operands);
1406 }
1407
1408 /**
1409 * {@return the array}
1410 */
1411 public Value arrayOperand() {
1412 return operands().get(0);
1413 }
1414
1415 /**
1416 * {@return the array index}
1417 */
1418 public Value indexOperand() {
1419 return operands().get(1);
1420 }
1421
1422 /**
1423 * The array load operation, that can model Java language array expressions combined with load access to the
1424 * components of an array.
1425 *
1426 * @jls 15.10.3 Array Access Expressions
1427 */
1428 @OpDeclaration(ArrayLoadOp.NAME)
1429 public static final class ArrayLoadOp extends ArrayAccessOp
1430 implements JavaExpression {
1431 static final String NAME = "array.load";
1432 final CodeType componentType;
1433
1434 ArrayLoadOp(ExternalizedOp def) {
1435 super(requireOperands(def, 2));
1436 this.componentType = def.resultType();
1437 }
1438
1439 ArrayLoadOp(ArrayLoadOp that, CodeContext cc) {
1440 super(that, cc);
1441 this.componentType = that.componentType;
1442 }
1443
1444 @Override
1445 public ArrayLoadOp transform(CodeContext cc, CodeTransformer ct) {
1446 return new ArrayLoadOp(this, cc);
1447 }
1448
1449 ArrayLoadOp(Value array, Value index) {
1450 // @@@ revisit this when the component type is not explicitly given (see VarOp.resultType as an example)
1451 this(array, index, ((ArrayType)array.type()).componentType());
1452 }
1453
1454 ArrayLoadOp(Value array, Value index, CodeType componentType) {
1455 super(List.of(array, index));
1456 this.componentType = componentType;
1457 }
1458
1459 @Override
1460 public CodeType resultType() {
1461 return componentType;
1462 }
1463 }
1464
1465 /**
1466 * The array store operation, that can model Java language array expressions combined with store access to the
1467 * components of an array.
1468 * <p>
1469 * The result type of an array store operation is {@link JavaType#VOID}.
1470 *
1471 * @jls 15.10.3 Array Access Expressions
1472 */
1473 @OpDeclaration(ArrayStoreOp.NAME)
1474 public static final class ArrayStoreOp extends ArrayAccessOp
1475 implements JavaExpression, JavaStatement {
1476 static final String NAME = "array.store";
1477
1478 ArrayStoreOp(ExternalizedOp def) {
1479 List<Value> operands = requireOperands(def, 3);
1480 this(operands.get(0), operands.get(1), operands.get(2));
1481 }
1482
1483 ArrayStoreOp(ArrayStoreOp that, CodeContext cc) {
1484 super(that, cc);
1485 }
1486
1487 @Override
1488 public ArrayStoreOp transform(CodeContext cc, CodeTransformer ct) {
1489 return new ArrayStoreOp(this, cc);
1490 }
1491
1492 ArrayStoreOp(Value array, Value index, Value v) {
1493 super(List.of(array, index, v));
1494 }
1495
1496 /**
1497 * {@return the value to store}
1498 */
1499 public Value valueOperand() {
1500 return operands().get(2);
1501 }
1502
1503 @Override
1504 public CodeType resultType() {
1505 return VOID;
1506 }
1507 }
1508 }
1509
1510 /**
1511 * The instanceof operation, that can model Java language instanceof expressions that use the
1512 * {@code instanceof} keyword as the <em>type comparison operator</em>.
1513 * <p>
1514 * Instanceof operations feature one operand, the value being tested, and are associated with a
1515 * {@linkplain JavaType type} modeling the target type of the type comparison operator.
1516 *
1517 * @jls 15.20.2 The instanceof Operator
1518 */
1519 @OpDeclaration(InstanceOfOp.NAME)
1520 public static final class InstanceOfOp extends AbstractOp
1521 implements JavaOp, ReflectiveOp, JavaExpression {
1522 static final String NAME = "instanceof";
1523 /** The externalized attribute key for the code type modeling the instanceof target type. */
1524 static final String ATTRIBUTE_INSTANCEOF_TYPE = NAME + ".type";
1525
1526 final CodeType targetType;
1527
1528 InstanceOfOp(ExternalizedOp def) {
1529 this(requireAttribute(def, ATTRIBUTE_INSTANCEOF_TYPE, true, JavaType.class), requireSingleOperand(def));
1530 }
1531
1532 InstanceOfOp(InstanceOfOp that, CodeContext cc) {
1533 super(that, cc);
1534
1535 this.targetType = that.targetType;
1536 }
1537
1538 @Override
1539 public InstanceOfOp transform(CodeContext cc, CodeTransformer ct) {
1540 return new InstanceOfOp(this, cc);
1541 }
1542
1543 InstanceOfOp(CodeType t, Value v) {
1544 super(List.of(v));
1545
1546 this.targetType = t;
1547 }
1548
1549 @Override
1550 public Map<String, Object> externalize() {
1551 return Map.of("", targetType);
1552 }
1553
1554 /**
1555 * {@return the value to test}
1556 */
1557 public Value valueOperand() {
1558 return operands().getFirst();
1559 }
1560
1561 /**
1562 * {@return the code type modeling the target type of this instanceof operation}
1563 */
1564 public CodeType targetType() {
1565 return targetType;
1566 }
1567
1568 @Override
1569 public CodeType resultType() {
1570 return BOOLEAN;
1571 }
1572 }
1573
1574 /**
1575 * The cast operation, that can model Java language cast expressions for reference types.
1576 * <p>
1577 * Cast operations feature one operand, the value being cast, and are associated with a
1578 * {@linkplain JavaType type} modeling the target type of the cast.
1579 *
1580 * @jls 15.16 Cast Expressions
1581 */
1582 @OpDeclaration(CastOp.NAME)
1583 public static final class CastOp extends AbstractOp
1584 implements JavaOp, ReflectiveOp, JavaExpression {
1585 static final String NAME = "cast";
1586 /** The externalized attribute key for the code type modeling the target type of the cast. */
1587 static final String ATTRIBUTE_CAST_TYPE = NAME + ".type";
1588
1589 final CodeType resultType;
1590 final CodeType targetType;
1591
1592 CastOp(ExternalizedOp def) {
1593 this(def.resultType(), requireAttribute(def, ATTRIBUTE_CAST_TYPE, true, JavaType.class), requireSingleOperand(def));
1594 }
1595
1596 CastOp(CastOp that, CodeContext cc) {
1597 super(that, cc);
1598
1599 this.resultType = that.resultType;
1600 this.targetType = that.targetType;
1601 }
1602
1603 @Override
1604 public CastOp transform(CodeContext cc, CodeTransformer ct) {
1605 return new CastOp(this, cc);
1606 }
1607
1608 CastOp(CodeType resultType, CodeType t, Value v) {
1609 super(List.of(v));
1610
1611 this.resultType = resultType;
1612 this.targetType = t;
1613 }
1614
1615 @Override
1616 public Map<String, Object> externalize() {
1617 return Map.of("", targetType);
1618 }
1619
1620 /**
1621 * {@return the value to cast}
1622 */
1623 public Value valueOperand() {
1624 return operands().get(0);
1625 }
1626
1627 /**
1628 * {@return the code type modeling the target type of this cast operation}
1629 */
1630 public CodeType targetType() {
1631 return targetType;
1632 }
1633
1634 @Override
1635 public CodeType resultType() {
1636 return resultType;
1637 }
1638 }
1639
1640 /**
1641 * The exception region start operation, that can model entry into an exception region.
1642 * <p>
1643 * An exception region start operation is a block terminating operation whose first successor is the starting
1644 * block of the exception region, and whose remaining successors are the catch blocks for that region.
1645 * Each successor argument corresponding to a catch block's parameter,
1646 * modeling exceptions that are caught by the catch block, is ignored and is never assigned to the parameter.
1647 */
1648 @OpDeclaration(ExceptionRegionEnter.NAME)
1649 public static final class ExceptionRegionEnter extends AbstractOp.Terminating
1650 implements JavaOp {
1651 static final String NAME = "exception.region.enter";
1652 static final String ATTRIBUTE_CATCH_TYPES = NAME + ".catchTypes";
1653
1654 final List<CodeType> explicitCatchTypes;
1655
1656 // First successor is the non-exceptional successor whose target indicates
1657 // the first block in the exception region.
1658 // One or more subsequent successors target the exception catching blocks
1659 // each of which have one block argument whose type is an exception type.
1660
1661 ExceptionRegionEnter(ExternalizedOp def) {
1662 this(optionalAttribute(def, ATTRIBUTE_CATCH_TYPES, true, TupleType.class)
1663 .map(TupleType::componentTypes).orElse(null),
1664 def.successors());
1665 }
1666
1667 ExceptionRegionEnter(ExceptionRegionEnter that, CodeContext cc) {
1668 super(that, cc);
1669 this.explicitCatchTypes = that.explicitCatchTypes;
1670 }
1671
1672 @Override
1673 public ExceptionRegionEnter transform(CodeContext cc, CodeTransformer ct) {
1674 return new ExceptionRegionEnter(this, cc);
1675 }
1676
1677 ExceptionRegionEnter(List<CodeType> catchTypes, List<Block.Reference> references) {
1678 if (references.size() < 2) {
1679 throw structuralException(NAME, "requires at least 2 successors, found %d".formatted(references.size()));
1680 }
1681 if (catchTypes != null && catchTypes.size() != references.size() - 1) {
1682 throw structuralException(NAME, "catch types %s require %d catch references, found %d"
1683 .formatted(catchTypes, catchTypes.size(), references.size() - 1));
1684 }
1685 super(List.of(), references);
1686 this.explicitCatchTypes = catchTypes == null ? null : List.copyOf(catchTypes);
1687 }
1688
1689 @Override
1690 public Map<String, Object> externalize() {
1691 // avoid storing explicit catch types if they all match the handlers
1692 return explicitCatchTypes == null || explicitCatchTypes.equals(implicitCatchTypes())
1693 ? Map.of()
1694 : Map.of("", CoreType.tupleType(explicitCatchTypes));
1695 }
1696
1697 /**
1698 * {@return the starting block reference of this exception region}
1699 */
1700 public Block.Reference startReference() {
1701 return successors().get(0);
1702 }
1703
1704 /**
1705 * {@return the catch block references of this exception region}
1706 */
1707 public List<Block.Reference> catchReferences() {
1708 return successors().subList(1, successors().size());
1709 }
1710
1711 /**
1712 * {@return the catch types}
1713 */
1714 public List<CodeType> catchTypes() {
1715 return explicitCatchTypes == null ? implicitCatchTypes() : explicitCatchTypes;
1716 }
1717
1718 private List<CodeType> implicitCatchTypes() {
1719 return catchReferences().stream().map(r -> r.targetBlock().parameterTypes().getFirst()).toList();
1720 }
1721
1722 @Override
1723 public CodeType resultType() {
1724 return VOID;
1725 }
1726 }
1727
1728 /**
1729 * The exception region end operation, that can model exit from an exception region.
1730 * <p>
1731 * An exception region end operation is a block terminating operation with one operand and one successor.
1732 * The operand is the result of the dominant {@link ExceptionRegionEnter}. The successor is the block that
1733 * follows the exception region.
1734 */
1735 @OpDeclaration(ExceptionRegionExit.NAME)
1736 public static final class ExceptionRegionExit extends AbstractOp.Terminating
1737 implements JavaOp {
1738 static final String NAME = "exception.region.exit";
1739
1740 ExceptionRegionExit(ExternalizedOp def) {
1741 this(requireSingleOperand(def), requireSingleSuccessor(def));
1742 }
1743
1744 ExceptionRegionExit(ExceptionRegionExit that, CodeContext cc) {
1745 super(that, cc);
1746 }
1747
1748 @Override
1749 public ExceptionRegionExit transform(CodeContext cc, CodeTransformer ct) {
1750 return new ExceptionRegionExit(this, cc);
1751 }
1752
1753 // Non-exceptional successor
1754 ExceptionRegionExit(Value enter, Block.Reference end) {
1755 if (!(enter instanceof Op.Result or && or.op() instanceof ExceptionRegionEnter)) {
1756 throw structuralException(NAME, "operand is not an exception region entry: " + enter);
1757 }
1758 super(List.of(enter), List.of(end));
1759 }
1760
1761 /**
1762 * {@return the block reference reached after exiting this exception region}
1763 */
1764 public Block.Reference endReference() {
1765 return successors().get(0);
1766 }
1767
1768 /**
1769 * {@return the dominant exception region enter operation}
1770 */
1771 public ExceptionRegionEnter enterOp() {
1772 return (ExceptionRegionEnter)operands().getFirst().asResult().op();
1773 }
1774
1775 @Override
1776 public CodeType resultType() {
1777 return VOID;
1778 }
1779 }
1780
1781 /**
1782 * The string concatenation operation, that can model the Java language string concatenation operator
1783 * {@code +}.
1784 * <p>
1785 * Concatenation operations feature two operands.
1786 * The result type of a string concatenation operation is {@linkplain JavaType#J_L_STRING java.lang.String}.
1787 *
1788 * @jls 15.18.1 String Concatenation Operator +
1789 */
1790 @OpDeclaration(ConcatOp.NAME)
1791 public static final class ConcatOp extends AbstractOp
1792 implements JavaOp, JavaExpression {
1793 static final String NAME = "concat";
1794
1795 ConcatOp(ConcatOp that, CodeContext cc) {
1796 super(that, cc);
1797 }
1798
1799 ConcatOp(ExternalizedOp def) {
1800 List<Value> operands = requireOperands(def, 2);
1801 this(operands.get(0), operands.get(1));
1802 }
1803
1804 ConcatOp(Value lhs, Value rhs) {
1805 super(List.of(lhs, rhs));
1806 }
1807
1808 @Override
1809 public Op transform(CodeContext cc, CodeTransformer ct) {
1810 return new ConcatOp(this, cc);
1811 }
1812
1813 /**
1814 * {@return the left hand operand}
1815 */
1816 public Value lhsOperand() {
1817 return operands().get(0);
1818 }
1819
1820 /**
1821 * {@return the right hand operand}
1822 */
1823 public Value rhsOperand() {
1824 return operands().get(1);
1825 }
1826
1827 @Override
1828 public CodeType resultType() {
1829 return J_L_STRING;
1830 }
1831 }
1832
1833 /**
1834 * The arithmetic operation.
1835 */
1836 public sealed static abstract class ArithmeticOperation extends AbstractOp
1837 implements JavaOp, JavaExpression {
1838 ArithmeticOperation(ArithmeticOperation that, CodeContext cc) {
1839 super(that, cc);
1840 }
1841
1842 ArithmeticOperation(List<Value> operands) {
1843 super(operands);
1844 }
1845 }
1846
1847 /**
1848 * A binary arithmetic operation.
1849 * <p>
1850 * Binary arithmetic operations feature two operands. Usually, both operands have the same type,
1851 * although that is not always the case. The result type of a binary arithmetic operation is
1852 * the type of the first operand.
1853 */
1854 public sealed static abstract class BinaryOp extends ArithmeticOperation {
1855 BinaryOp(BinaryOp that, CodeContext cc) {
1856 super(that, cc);
1857 }
1858
1859 BinaryOp(ExternalizedOp def) {
1860 super(requireOperands(def, 2));
1861 }
1862
1863 BinaryOp(Value lhs, Value rhs) {
1864 super(List.of(lhs, rhs));
1865 }
1866
1867 /**
1868 * {@return the left hand operand}
1869 */
1870 public Value lhsOperand() {
1871 return operands().get(0);
1872 }
1873
1874 /**
1875 * {@return the right hand operand}
1876 */
1877 public Value rhsOperand() {
1878 return operands().get(1);
1879 }
1880
1881 @Override
1882 public CodeType resultType() {
1883 return operands().get(0).type();
1884 }
1885 }
1886
1887 /**
1888 * The unary arithmetic operation.
1889 * <p>
1890 * Unary arithmetic operations feature one operand.
1891 * The result type of a unary arithmetic operation is the type of its operand.
1892 */
1893 public sealed static abstract class UnaryOp extends ArithmeticOperation {
1894 UnaryOp(UnaryOp that, CodeContext cc) {
1895 super(that, cc);
1896 }
1897
1898 UnaryOp(ExternalizedOp def) {
1899 super(requireOperands(def, 1));
1900 }
1901
1902 UnaryOp(Value v) {
1903 super(List.of(v));
1904 }
1905
1906 /**
1907 * {@return the operand}
1908 */
1909 public Value operand() {
1910 return operands().get(0);
1911 }
1912
1913 @Override
1914 public CodeType resultType() {
1915 return operands().get(0).type();
1916 }
1917 }
1918
1919 /**
1920 * The compare operation.
1921 * <p>
1922 * Compare operations feature two operands, and yield a {@link JavaType#BOOLEAN} value.
1923 */
1924 public sealed static abstract class CompareOp extends ArithmeticOperation {
1925 CompareOp(CompareOp that, CodeContext cc) {
1926 super(that, cc);
1927 }
1928
1929 CompareOp(ExternalizedOp def) {
1930 super(requireOperands(def, 2));
1931 }
1932
1933 CompareOp(Value lhs, Value rhs) {
1934 super(List.of(lhs, rhs));
1935 }
1936
1937 /**
1938 * {@return the left hand operand}
1939 */
1940 public Value lhsOperand() {
1941 return operands().get(0);
1942 }
1943
1944 /**
1945 * {@return the right hand operand}
1946 */
1947 public Value rhsOperand() {
1948 return operands().get(1);
1949 }
1950
1951 @Override
1952 public CodeType resultType() {
1953 return BOOLEAN;
1954 }
1955 }
1956
1957 /**
1958 * The add operation, that can model the Java language binary {@code +} operator for numeric types
1959 *
1960 * @jls 15.18.2 Additive Operators (+ and -) for Numeric Types
1961 */
1962 @OpDeclaration(AddOp.NAME)
1963 public static final class AddOp extends BinaryOp {
1964 static final String NAME = "add";
1965
1966 AddOp(ExternalizedOp def) {
1967 super(def);
1968 }
1969
1970 AddOp(AddOp that, CodeContext cc) {
1971 super(that, cc);
1972 }
1973
1974 @Override
1975 public AddOp transform(CodeContext cc, CodeTransformer ct) {
1976 return new AddOp(this, cc);
1977 }
1978
1979 AddOp(Value lhs, Value rhs) {
1980 super(lhs, rhs);
1981 }
1982 }
1983
1984 /**
1985 * The sub operation, that can model the Java language binary {@code -} operator for numeric types
1986 *
1987 * @jls 15.18.2 Additive Operators (+ and -) for Numeric Types
1988 */
1989 @OpDeclaration(SubOp.NAME)
1990 public static final class SubOp extends BinaryOp {
1991 static final String NAME = "sub";
1992
1993 SubOp(ExternalizedOp def) {
1994 super(def);
1995 }
1996
1997 SubOp(SubOp that, CodeContext cc) {
1998 super(that, cc);
1999 }
2000
2001 @Override
2002 public SubOp transform(CodeContext cc, CodeTransformer ct) {
2003 return new SubOp(this, cc);
2004 }
2005
2006 SubOp(Value lhs, Value rhs) {
2007 super(lhs, rhs);
2008 }
2009 }
2010
2011 /**
2012 * The mul operation, that can model the Java language binary {@code *} operator for numeric types
2013 *
2014 * @jls 15.17.1 Multiplication Operator *
2015 */
2016 @OpDeclaration(MulOp.NAME)
2017 public static final class MulOp extends BinaryOp {
2018 static final String NAME = "mul";
2019
2020 MulOp(ExternalizedOp def) {
2021 super(def);
2022 }
2023
2024 MulOp(MulOp that, CodeContext cc) {
2025 super(that, cc);
2026 }
2027
2028 @Override
2029 public MulOp transform(CodeContext cc, CodeTransformer ct) {
2030 return new MulOp(this, cc);
2031 }
2032
2033 MulOp(Value lhs, Value rhs) {
2034 super(lhs, rhs);
2035 }
2036 }
2037
2038 /**
2039 * The div operation, that can model the Java language binary {@code /} operator for numeric types
2040 *
2041 * @jls 15.17.2 Division Operator /
2042 */
2043 @OpDeclaration(DivOp.NAME)
2044 public static final class DivOp extends BinaryOp {
2045 static final String NAME = "div";
2046
2047 DivOp(ExternalizedOp def) {
2048 super(def);
2049 }
2050
2051 DivOp(DivOp that, CodeContext cc) {
2052 super(that, cc);
2053 }
2054
2055 @Override
2056 public DivOp transform(CodeContext cc, CodeTransformer ct) {
2057 return new DivOp(this, cc);
2058 }
2059
2060 DivOp(Value lhs, Value rhs) {
2061 super(lhs, rhs);
2062 }
2063 }
2064
2065 /**
2066 * The mod operation, that can model the Java language binary {@code %} operator for numeric types
2067 *
2068 * @jls 15.17.3 Remainder Operator %
2069 */
2070 @OpDeclaration(ModOp.NAME)
2071 public static final class ModOp extends BinaryOp {
2072 static final String NAME = "mod";
2073
2074 ModOp(ExternalizedOp def) {
2075 super(def);
2076 }
2077
2078 ModOp(ModOp that, CodeContext cc) {
2079 super(that, cc);
2080 }
2081
2082 @Override
2083 public ModOp transform(CodeContext cc, CodeTransformer ct) {
2084 return new ModOp(this, cc);
2085 }
2086
2087 ModOp(Value lhs, Value rhs) {
2088 super(lhs, rhs);
2089 }
2090 }
2091
2092 /**
2093 * The bitwise/logical or operation, that can model the Java language binary {@code |} operator for integral types
2094 * and booleans
2095 *
2096 * @jls 15.22 Bitwise and Logical Operators
2097 */
2098 @OpDeclaration(OrOp.NAME)
2099 public static final class OrOp extends BinaryOp {
2100 static final String NAME = "or";
2101
2102 OrOp(ExternalizedOp def) {
2103 super(def);
2104 }
2105
2106 OrOp(OrOp that, CodeContext cc) {
2107 super(that, cc);
2108 }
2109
2110 @Override
2111 public OrOp transform(CodeContext cc, CodeTransformer ct) {
2112 return new OrOp(this, cc);
2113 }
2114
2115 OrOp(Value lhs, Value rhs) {
2116 super(lhs, rhs);
2117 }
2118 }
2119
2120 /**
2121 * The bitwise/logical and operation, that can model the Java language binary {@code &} operator for integral types
2122 * and booleans
2123 *
2124 * @jls 15.22 Bitwise and Logical Operators
2125 */
2126 @OpDeclaration(AndOp.NAME)
2127 public static final class AndOp extends BinaryOp {
2128 static final String NAME = "and";
2129
2130 AndOp(ExternalizedOp def) {
2131 super(def);
2132 }
2133
2134 AndOp(AndOp that, CodeContext cc) {
2135 super(that, cc);
2136 }
2137
2138 @Override
2139 public AndOp transform(CodeContext cc, CodeTransformer ct) {
2140 return new AndOp(this, cc);
2141 }
2142
2143 AndOp(Value lhs, Value rhs) {
2144 super(lhs, rhs);
2145 }
2146 }
2147
2148 /**
2149 * The xor operation, that can model the Java language binary {@code ^} operator for integral types
2150 * and booleans
2151 *
2152 * @jls 15.22 Bitwise and Logical Operators
2153 */
2154 @OpDeclaration(XorOp.NAME)
2155 public static final class XorOp extends BinaryOp {
2156 static final String NAME = "xor";
2157
2158 XorOp(ExternalizedOp def) {
2159 super(def);
2160 }
2161
2162 XorOp(XorOp that, CodeContext cc) {
2163 super(that, cc);
2164 }
2165
2166 @Override
2167 public XorOp transform(CodeContext cc, CodeTransformer ct) {
2168 return new XorOp(this, cc);
2169 }
2170
2171 XorOp(Value lhs, Value rhs) {
2172 super(lhs, rhs);
2173 }
2174 }
2175
2176 /**
2177 * The (logical) shift left operation, that can model the Java language binary {@code <<} operator for integral types
2178 *
2179 * @jls 15.19 Shift Operators
2180 */
2181 @OpDeclaration(LshlOp.NAME)
2182 public static final class LshlOp extends BinaryOp {
2183 static final String NAME = "lshl";
2184
2185 LshlOp(ExternalizedOp def) {
2186 super(def);
2187 }
2188
2189 LshlOp(LshlOp that, CodeContext cc) {
2190 super(that, cc);
2191 }
2192
2193 @Override
2194 public LshlOp transform(CodeContext cc, CodeTransformer ct) {
2195 return new LshlOp(this, cc);
2196 }
2197
2198 LshlOp(Value lhs, Value rhs) {
2199 super(lhs, rhs);
2200 }
2201 }
2202
2203 /**
2204 * The (arithmetic) shift right operation, that can model the Java language binary {@code >>} operator for integral types
2205 *
2206 * @jls 15.19 Shift Operators
2207 */
2208 @OpDeclaration(AshrOp.NAME)
2209 public static final class AshrOp extends BinaryOp {
2210 static final String NAME = "ashr";
2211
2212 AshrOp(ExternalizedOp def) {
2213 super(def);
2214 }
2215
2216 AshrOp(AshrOp that, CodeContext cc) {
2217 super(that, cc);
2218 }
2219
2220 @Override
2221 public AshrOp transform(CodeContext cc, CodeTransformer ct) {
2222 return new AshrOp(this, cc);
2223 }
2224
2225 AshrOp(Value lhs, Value rhs) {
2226 super(lhs, rhs);
2227 }
2228 }
2229
2230 /**
2231 * The unsigned (logical) shift right operation, that can model the Java language binary {@code >>>} operator for integral types
2232 *
2233 * @jls 15.19 Shift Operators
2234 */
2235 @OpDeclaration(LshrOp.NAME)
2236 public static final class LshrOp extends BinaryOp {
2237 static final String NAME = "lshr";
2238
2239 LshrOp(ExternalizedOp def) {
2240 super(def);
2241 }
2242
2243 LshrOp(LshrOp that, CodeContext cc) {
2244 super(that, cc);
2245 }
2246
2247 @Override
2248 public LshrOp transform(CodeContext cc, CodeTransformer ct) {
2249 return new LshrOp(this, cc);
2250 }
2251
2252 LshrOp(Value lhs, Value rhs) {
2253 super(lhs, rhs);
2254 }
2255 }
2256
2257 /**
2258 * The neg operation, that can model the Java language unary {@code -} operator for numeric types
2259 *
2260 * @jls 15.15.4 Unary Minus Operator {@code -}
2261 */
2262 @OpDeclaration(NegOp.NAME)
2263 public static final class NegOp extends UnaryOp {
2264 static final String NAME = "neg";
2265
2266 NegOp(ExternalizedOp def) {
2267 super(def);
2268 }
2269
2270 NegOp(NegOp that, CodeContext cc) {
2271 super(that, cc);
2272 }
2273
2274 @Override
2275 public NegOp transform(CodeContext cc, CodeTransformer ct) {
2276 return new NegOp(this, cc);
2277 }
2278
2279 NegOp(Value v) {
2280 super(v);
2281 }
2282 }
2283
2284 /**
2285 * The pos operation, that can model the Java language unary {@code +} operator for numeric types
2286 *
2287 * @jls 15.15.3 Unary Plus Operator {@code +}
2288 */
2289 @OpDeclaration(PosOp.NAME)
2290 public static final class PosOp extends UnaryOp {
2291 static final String NAME = "pos";
2292
2293 PosOp(ExternalizedOp def) {
2294 super(def);
2295 }
2296
2297 PosOp(PosOp that, CodeContext cc) {
2298 super(that, cc);
2299 }
2300
2301 @Override
2302 public PosOp transform(CodeContext cc, CodeTransformer ct) {
2303 return new PosOp(this, cc);
2304 }
2305
2306 PosOp(Value v) {
2307 super(v);
2308 }
2309 }
2310
2311 /**
2312 * The bitwise complement operation, that can model the Java language unary {@code ~} operator for integral types
2313 *
2314 * @jls 15.15.5 Bitwise Complement Operator {@code ~}
2315 */
2316 @OpDeclaration(ComplOp.NAME)
2317 public static final class ComplOp extends UnaryOp {
2318 static final String NAME = "compl";
2319
2320 ComplOp(ExternalizedOp def) {
2321 super(def);
2322 }
2323
2324 ComplOp(ComplOp that, CodeContext cc) {
2325 super(that, cc);
2326 }
2327
2328 @Override
2329 public ComplOp transform(CodeContext cc, CodeTransformer ct) {
2330 return new ComplOp(this, cc);
2331 }
2332
2333 ComplOp(Value v) {
2334 super(v);
2335 }
2336 }
2337
2338 /**
2339 * The not operation, that can model the Java language unary {@code !} operator for boolean types
2340 *
2341 * @jls 15.15.6 Logical Complement Operator {@code !}
2342 */
2343 @OpDeclaration(NotOp.NAME)
2344 public static final class NotOp extends UnaryOp {
2345 static final String NAME = "not";
2346
2347 NotOp(ExternalizedOp def) {
2348 super(def);
2349 }
2350
2351 NotOp(NotOp that, CodeContext cc) {
2352 super(that, cc);
2353 }
2354
2355 @Override
2356 public NotOp transform(CodeContext cc, CodeTransformer ct) {
2357 return new NotOp(this, cc);
2358 }
2359
2360 NotOp(Value v) {
2361 super(v);
2362 }
2363 }
2364
2365 /**
2366 * The equals operation, that can model the Java language equality {@code ==} operator for numeric, boolean
2367 * and reference types
2368 *
2369 * @jls 15.21 Equality Operators
2370 */
2371 @OpDeclaration(EqOp.NAME)
2372 public static final class EqOp extends CompareOp {
2373 static final String NAME = "eq";
2374
2375 EqOp(ExternalizedOp def) {
2376 super(def);
2377 }
2378
2379 EqOp(EqOp that, CodeContext cc) {
2380 super(that, cc);
2381 }
2382
2383 @Override
2384 public EqOp transform(CodeContext cc, CodeTransformer ct) {
2385 return new EqOp(this, cc);
2386 }
2387
2388 EqOp(Value lhs, Value rhs) {
2389 super(lhs, rhs);
2390 }
2391 }
2392
2393 /**
2394 * The not equals operation, that can model the Java language equality {@code !=} operator for numeric, boolean
2395 * and reference types
2396 *
2397 * @jls 15.21 Equality Operators
2398 */
2399 @OpDeclaration(NeqOp.NAME)
2400 public static final class NeqOp extends CompareOp {
2401 static final String NAME = "neq";
2402
2403 NeqOp(ExternalizedOp def) {
2404 super(def);
2405 }
2406
2407 NeqOp(NeqOp that, CodeContext cc) {
2408 super(that, cc);
2409 }
2410
2411 @Override
2412 public NeqOp transform(CodeContext cc, CodeTransformer ct) {
2413 return new NeqOp(this, cc);
2414 }
2415
2416 NeqOp(Value lhs, Value rhs) {
2417 super(lhs, rhs);
2418 }
2419 }
2420
2421 /**
2422 * The greater than operation, that can model the Java language relational {@code >} operator for numeric types
2423 *
2424 * @jls 15.20.1 Numerical Comparison Operators {@code <}, {@code <=}, {@code >}, and {@code >=}
2425 */
2426 @OpDeclaration(GtOp.NAME)
2427 public static final class GtOp extends CompareOp {
2428 static final String NAME = "gt";
2429
2430 GtOp(ExternalizedOp def) {
2431 super(def);
2432 }
2433
2434 GtOp(GtOp that, CodeContext cc) {
2435 super(that, cc);
2436 }
2437
2438 @Override
2439 public GtOp transform(CodeContext cc, CodeTransformer ct) {
2440 return new GtOp(this, cc);
2441 }
2442
2443 GtOp(Value lhs, Value rhs) {
2444 super(lhs, rhs);
2445 }
2446 }
2447
2448 /**
2449 * The greater than or equal to operation, that can model the Java language relational {@code >=} operator for
2450 * numeric types
2451 *
2452 * @jls 15.20.1 Numerical Comparison Operators {@code <}, {@code <=}, {@code >}, and {@code >=}
2453 */
2454 @OpDeclaration(GeOp.NAME)
2455 public static final class GeOp extends CompareOp {
2456 static final String NAME = "ge";
2457
2458 GeOp(ExternalizedOp def) {
2459 super(def);
2460 }
2461
2462 GeOp(GeOp that, CodeContext cc) {
2463 super(that, cc);
2464 }
2465
2466 @Override
2467 public GeOp transform(CodeContext cc, CodeTransformer ct) {
2468 return new GeOp(this, cc);
2469 }
2470
2471 GeOp(Value lhs, Value rhs) {
2472 super(lhs, rhs);
2473 }
2474 }
2475
2476 /**
2477 * The less than operation, that can model the Java language relational {@code <} operator for
2478 * numeric types
2479 *
2480 * @jls 15.20.1 Numerical Comparison Operators {@code <}, {@code <=}, {@code >}, and {@code >=}
2481 */
2482 @OpDeclaration(LtOp.NAME)
2483 public static final class LtOp extends CompareOp {
2484 static final String NAME = "lt";
2485
2486 LtOp(ExternalizedOp def) {
2487 super(def);
2488 }
2489
2490 LtOp(LtOp that, CodeContext cc) {
2491 super(that, cc);
2492 }
2493
2494 @Override
2495 public LtOp transform(CodeContext cc, CodeTransformer ct) {
2496 return new LtOp(this, cc);
2497 }
2498
2499 LtOp(Value lhs, Value rhs) {
2500 super(lhs, rhs);
2501 }
2502 }
2503
2504 /**
2505 * The less than or equal to operation, that can model the Java language relational {@code <=} operator for
2506 * numeric types
2507 *
2508 * @jls 15.20.1 Numerical Comparison Operators {@code <}, {@code <=}, {@code >}, and {@code >=}
2509 */
2510 @OpDeclaration(LeOp.NAME)
2511 public static final class LeOp extends CompareOp {
2512 static final String NAME = "le";
2513
2514 LeOp(ExternalizedOp def) {
2515 super(def);
2516 }
2517
2518 LeOp(LeOp that, CodeContext cc) {
2519 super(that, cc);
2520 }
2521
2522 @Override
2523 public LeOp transform(CodeContext cc, CodeTransformer ct) {
2524 return new LeOp(this, cc);
2525 }
2526
2527 LeOp(Value lhs, Value rhs) {
2528 super(lhs, rhs);
2529 }
2530 }
2531
2532 /**
2533 * A statement targeting operation, that can model Java language statements associated with label identifiers.
2534 * <p>
2535 * A statement targeting operation is a body terminating operation that features zero or one operand, the label
2536 * identifier. If present, the label identifier is modeled as a {@link ConstantOp} value.
2537 * <p>
2538 * The result type of a statement targeting operation is {@link JavaType#VOID}.
2539 *
2540 * @jls 14.15 The break Statement
2541 * @jls 14.16 The continue Statement
2542 */
2543 public sealed static abstract class StatementTargetingOp extends AbstractOp.Terminating
2544 implements JavaOp, Op.Lowerable, JavaStatement, TargetingOp {
2545
2546 StatementTargetingOp(StatementTargetingOp that, CodeContext cc) {
2547 super(that, cc);
2548 }
2549
2550 StatementTargetingOp(ExternalizedOp def) {
2551 super(requireOperands(def, 0, 1));
2552 }
2553
2554 StatementTargetingOp(Value label) {
2555 super(checkLabel(label));
2556 }
2557
2558 static List<Value> checkLabel(Value label) {
2559 return label == null ? List.of() : List.of(label);
2560 }
2561
2562 Op innerMostEnclosingTarget() {
2563 /*
2564 A break statement with no label attempts to transfer control to the
2565 innermost enclosing switch, while, do, or for statement; this enclosing statement,
2566 which is called the break target, then immediately completes normally.
2567
2568 A break statement with label Identifier attempts to transfer control to the
2569 enclosing labeled statement (14.7) that has the same Identifier as its label;
2570 this enclosing statement, which is called the break target, then immediately completes normally.
2571 In this case, the break target need not be a switch, while, do, or for statement.
2572 */
2573
2574 // No label
2575 // For a break statement get the innermost enclosing loop operation or switch statement operation
2576 // For a continue statement get the innermost enclosing loop operation
2577
2578 Predicate<Op> targetPred = this instanceof BreakOp
2579 ? op -> op instanceof Loop || op instanceof SwitchStatementOp
2580 : op -> op instanceof Loop;
2581 Op op = this;
2582 Body body;
2583 do {
2584 body = op.ancestorBody();
2585 op = body.ancestorOp();
2586 } while (op != null && !targetPred.test(op));
2587
2588 return switch (op) {
2589 case Loop lop -> lop.loopBody() == body ? op : null;
2590 case SwitchStatementOp _ -> op; // all bodies for switch op are valid
2591 case null, default -> throw new IllegalStateException("No enclosing loop or switch statement");
2592 };
2593 }
2594
2595 boolean isUnlabeled() {
2596 return operands().isEmpty();
2597 }
2598
2599 @Override
2600 public Op target() {
2601 // If unlabeled then find the nearest enclosing op
2602 // Otherwise obtain the label target
2603 if (isUnlabeled()) {
2604 return innerMostEnclosingTarget();
2605 }
2606
2607 Value value = operands().get(0);
2608 if (value instanceof Result r && r.op().ancestorOp() instanceof LabeledOp lop) {
2609 return lop.target();
2610 } else {
2611 throw new IllegalStateException("Bad label value: " + value + " " + ((Result) value).op());
2612 }
2613 }
2614
2615 Block.Builder lower(Block.Builder b, Function<BranchTarget, Block.Builder> f) {
2616 Op opt = target();
2617 BranchTarget t = BranchTarget.getBranchTarget(b.context(), opt);
2618 if (t != null) {
2619 b.add(branch(f.apply(t).reference()));
2620 } else {
2621 throw new IllegalStateException("No branch target for operation: " + opt);
2622 }
2623 return b;
2624 }
2625
2626 /**
2627 * {@return the label identifier, otherwise {@code null} if no label}
2628 */
2629 public Value labelOperand() {
2630 return operands().isEmpty() ? null : operands().getFirst();
2631 }
2632
2633 @Override
2634 public CodeType resultType() {
2635 return VOID;
2636 }
2637 }
2638
2639 /**
2640 * The break operation, that can model Java language break statements.
2641 * <p>
2642 * A break operation is a body-terminating statement targeting operation.
2643 *
2644 * @jls 14.15 The break Statement
2645 */
2646 @OpDeclaration(BreakOp.NAME)
2647 public static final class BreakOp extends StatementTargetingOp {
2648 static final String NAME = "java.break";
2649
2650 BreakOp(ExternalizedOp def) {
2651 super(def);
2652 }
2653
2654 BreakOp(BreakOp that, CodeContext cc) {
2655 super(that, cc);
2656 }
2657
2658 @Override
2659 public BreakOp transform(CodeContext cc, CodeTransformer ct) {
2660 return new BreakOp(this, cc);
2661 }
2662
2663 BreakOp(Value label) {
2664 super(label);
2665 }
2666
2667 @Override
2668 public Block.Builder lower(Block.Builder b, BiFunction<Block.Builder, Op, Block.Builder> inherited) {
2669 return lower(b, BranchTarget::breakBlock);
2670 }
2671 }
2672
2673 /**
2674 * The continue operation, that can model Java language continue statements.
2675 * <p>
2676 * A continue operation is a body-terminating statement targeting operation.
2677 *
2678 * @jls 14.16 The continue Statement
2679 */
2680 @OpDeclaration(ContinueOp.NAME)
2681 public static final class ContinueOp extends StatementTargetingOp {
2682 static final String NAME = "java.continue";
2683
2684 ContinueOp(ExternalizedOp def) {
2685 super(def);
2686 }
2687
2688 ContinueOp(ContinueOp that, CodeContext cc) {
2689 super(that, cc);
2690 }
2691
2692 @Override
2693 public ContinueOp transform(CodeContext cc, CodeTransformer ct) {
2694 return new ContinueOp(this, cc);
2695 }
2696
2697 ContinueOp(Value label) {
2698 super(label);
2699 }
2700
2701 @Override
2702 public Block.Builder lower(Block.Builder b, BiFunction<Block.Builder, Op, Block.Builder> inherited) {
2703 return lower(b, BranchTarget::continueBlock);
2704 }
2705 }
2706
2707 /**
2708 * The yield operation, that can model Java language yield statements.
2709 * <p>
2710 * A yield operation is a body terminating operation that features one operand, the yielded value.
2711 * <p>
2712 * The result type of a yield operation is {@link JavaType#VOID}.
2713 *
2714 * @jls 14.21 The yield Statement
2715 */
2716 @OpDeclaration(YieldOp.NAME)
2717 public static final class YieldOp extends AbstractOp.Terminating
2718 implements JavaOp, JavaStatement, Op.Lowerable, TargetingOp {
2719 static final String NAME = "java.yield";
2720
2721 YieldOp(ExternalizedOp def) {
2722 this(requireSingleOperand(def));
2723 }
2724
2725 YieldOp(YieldOp that, CodeContext cc) {
2726 super(that, cc);
2727 }
2728
2729 @Override
2730 public YieldOp transform(CodeContext cc, CodeTransformer ct) {
2731 return new YieldOp(this, cc);
2732 }
2733
2734 YieldOp(Value operand) {
2735 super(List.of(Objects.requireNonNull(operand)));
2736 }
2737
2738 /**
2739 * {@return the yielded value}
2740 */
2741 public Value yieldOperand() {
2742 return operands().get(0);
2743 }
2744
2745 @Override
2746 public CodeType resultType() {
2747 return VOID;
2748 }
2749
2750 @Override
2751 public Block.Builder lower(Block.Builder b, BiFunction<Block.Builder, Op, Block.Builder> inherited) {
2752 // for now, we will use breakBlock field to indicate java.yield target block
2753 return lower(b, BranchTarget::breakBlock);
2754 }
2755
2756 Block.Builder lower(Block.Builder b, Function<BranchTarget, Block.Builder> f) {
2757 Op opt = target();
2758 BranchTarget t = BranchTarget.getBranchTarget(b.context(), opt);
2759 if (t != null) {
2760 b.add(branch(f.apply(t).reference(b.context().getValue(yieldOperand()))));
2761 } else {
2762 throw new IllegalStateException("No branch target for operation: " + opt);
2763 }
2764 return b;
2765 }
2766
2767 @Override
2768 public Op target() {
2769 return innerMostEnclosingTarget();
2770 }
2771
2772 Op innerMostEnclosingTarget() {
2773 Op op = this;
2774 Body b;
2775 do {
2776 b = op.ancestorBody();
2777 op = b.ancestorOp();
2778 if (op == null) {
2779 throw new IllegalStateException("No enclosing switch");
2780 }
2781 } while (!(op instanceof SwitchExpressionOp));
2782 return op;
2783 }
2784 }
2785
2786 /**
2787 * The block operation, that can model Java language blocks.
2788 * <p>
2789 * Block operations feature one statements body, modeling the list of statements enclosed by the Java block.
2790 * The statements body should accept no arguments and yield {@linkplain JavaType#VOID no value}.
2791 * <p>
2792 * The result type of a block operation is {@link JavaType#VOID}.
2793 *
2794 * @jls 14.2 Blocks
2795 */
2796 @OpDeclaration(BlockOp.NAME)
2797 public static final class BlockOp extends AbstractOp
2798 implements JavaOp, Op.Nested, Op.Lowerable, JavaStatement {
2799 static final String NAME = "java.block";
2800
2801 final Body body;
2802
2803 BlockOp(ExternalizedOp def) {
2804 this(requireSingleBody(def));
2805 }
2806
2807 BlockOp(BlockOp that, CodeContext cc, CodeTransformer ct) {
2808 super(that, cc);
2809
2810 // Copy body
2811 this.body = that.body.transform(cc, ct).build(this);
2812 }
2813
2814 @Override
2815 public BlockOp transform(CodeContext cc, CodeTransformer ct) {
2816 return new BlockOp(this, cc, ct);
2817 }
2818
2819 BlockOp(Body.Builder bodyC) {
2820 super(List.of());
2821 this.body = requireVoidBodySignature(NAME, bodyC).build(this);
2822 }
2823
2824 @Override
2825 public List<Body> bodies() {
2826 return List.of(body);
2827 }
2828
2829 /**
2830 * {@return the block operation body}
2831 */
2832 public Body body() {
2833 return body;
2834 }
2835
2836 @Override
2837 public Block.Builder lower(Block.Builder b, BiFunction<Block.Builder, Op, Block.Builder> inherited) {
2838 Block.Builder exit = b.block();
2839 BranchTarget.setBranchTarget(b.context(), this, exit, null);
2840
2841 b.transformBody(body, List.of(), loweringTransformer(inherited, (block, op) -> {
2842 if (op instanceof CoreOp.YieldOp) {
2843 block.add(branch(exit.reference()));
2844 return block;
2845 } else {
2846 return null;
2847 }
2848 }));
2849
2850 return exit;
2851 }
2852
2853 @Override
2854 public CodeType resultType() {
2855 return VOID;
2856 }
2857 }
2858
2859 /**
2860 * The synchronized operation, that can model Java synchronized statements.
2861 * <p>
2862 * Synchronized operations feature two bodies. The <em>expression body</em> accepts no arguments
2863 * and yields a value, the object associated with the monitor that will be acquired by the synchronized
2864 * operation. The <em>block body</em> models the statements to execute while holding the monitor,
2865 * and yields {@linkplain JavaType#VOID no value}.
2866 * <p>
2867 * The result type of a synchronized operation is {@link JavaType#VOID}.
2868 *
2869 * @jls 14.19 The synchronized Statement
2870 */
2871 @OpDeclaration(SynchronizedOp.NAME)
2872 public static final class SynchronizedOp extends AbstractOp
2873 implements JavaOp, Op.Nested, Op.Lowerable, JavaStatement {
2874 static final String NAME = "java.synchronized";
2875
2876 final Body exprBody;
2877 final Body blockBody;
2878
2879 SynchronizedOp(ExternalizedOp def) {
2880 List<Body.Builder> bodies = requireBodies(def, 2);
2881 this(bodies.get(0), bodies.get(1));
2882 }
2883
2884 SynchronizedOp(SynchronizedOp that, CodeContext cc, CodeTransformer ct) {
2885 super(that, cc);
2886
2887 // Copy bodies
2888 this.exprBody = that.exprBody.transform(cc, ct).build(this);
2889 this.blockBody = that.blockBody.transform(cc, ct).build(this);
2890 }
2891
2892 @Override
2893 public SynchronizedOp transform(CodeContext cc, CodeTransformer ct) {
2894 return new SynchronizedOp(this, cc, ct);
2895 }
2896
2897 // @@@: builder?
2898 SynchronizedOp(Body.Builder exprC, Body.Builder bodyC) {
2899 super(List.of());
2900 this.exprBody = requireNonVoidReturnType(NAME + " expression", exprC, 0).build(this);
2901 this.blockBody = requireVoidBodySignature(NAME + " block", bodyC).build(this);
2902 }
2903
2904 @Override
2905 public List<Body> bodies() {
2906 return List.of(exprBody, blockBody);
2907 }
2908
2909 /**
2910 * {@return the expression body whose result is the monitor object for synchronization}
2911 */
2912 public Body exprBody() {
2913 return exprBody;
2914 }
2915
2916 /**
2917 * {@return the body that is executed within the synchronized block}
2918 */
2919 public Body blockBody() {
2920 return blockBody;
2921 }
2922
2923 @Override
2924 public Block.Builder lower(Block.Builder b, BiFunction<Block.Builder, Op, Block.Builder> inherited) {
2925 // Lower the expression body, yielding a monitor target
2926 b = lowerExpr(b, inherited);
2927 Value monitorTarget = b.parameters().get(0);
2928
2929 // Monitor enter
2930 b.add(monitorEnter(monitorTarget));
2931
2932 Block.Builder exit = b.block();
2933 BranchTarget.setBranchTarget(b.context(), this, exit, null);
2934
2935 // Exception region for the body
2936 Block.Builder syncRegionEnter = b.block();
2937 Block.Builder catcherFinally = b.block();
2938 Op.Result enter = b.add(exceptionRegionEnter(
2939 syncRegionEnter.reference(), catcherFinally.reference(b.add(constant(type(Throwable.class), null)))));
2940
2941 BiFunction<Block.Builder, Op, Block.Builder> syncExitTransformer = composeFirst(inherited, (block, op) -> {
2942 if (op instanceof TargetingOp top && top.targetsOrAttemptsToExit(this)) {
2943 // Monitor exit
2944 block.add(monitorExit(monitorTarget));
2945 // Exit the exception region
2946 Block.Builder exitRegion = block.block();
2947 block.add(exceptionRegionExit(enter, exitRegion.reference()));
2948 return exitRegion;
2949 } else {
2950 return block;
2951 }
2952 });
2953
2954 syncRegionEnter.transformBody(blockBody, List.of(), loweringTransformer(syncExitTransformer, (block, op) -> {
2955 if (op instanceof CoreOp.YieldOp) {
2956 // Monitor exit
2957 block.add(monitorExit(monitorTarget));
2958 // Exit the exception region
2959 block.add(exceptionRegionExit(enter, exit.reference()));
2960 return block;
2961 } else {
2962 return null;
2963 }
2964 }));
2965
2966 // The catcher, with an exception region back branching to itself
2967 Block.Builder catcherFinallyRegionEnter = b.block();
2968 Op.Result catcherEnter = catcherFinally.add(exceptionRegionEnter(
2969 catcherFinallyRegionEnter.reference(),
2970 catcherFinally.reference(catcherFinally.add(constant(type(Throwable.class), null)))));
2971
2972 // Monitor exit
2973 catcherFinallyRegionEnter.add(monitorExit(monitorTarget));
2974 Block.Builder catcherFinallyRegionExit = b.block();
2975 // Exit the exception region
2976 catcherFinallyRegionEnter.add(exceptionRegionExit(
2977 catcherEnter, catcherFinallyRegionExit.reference()));
2978 // Rethrow outside of region
2979 Block.Parameter t = catcherFinally.parameter(type(Throwable.class));
2980 catcherFinallyRegionExit.add(throw_(t));
2981
2982 return exit;
2983 }
2984
2985 Block.Builder lowerExpr(Block.Builder b, BiFunction<Block.Builder, Op, Block.Builder> inherited) {
2986 Block.Builder exprExit = b.block(exprBody.bodySignature().returnType());
2987 b.transformBody(exprBody, List.of(), loweringTransformer(inherited, (block, op) -> {
2988 if (op instanceof CoreOp.YieldOp yop) {
2989 Value monitorTarget = block.context().getValue(yop.yieldValue());
2990 block.add(branch(exprExit.reference(monitorTarget)));
2991 return block;
2992 } else {
2993 return null;
2994 }
2995 }));
2996 return exprExit;
2997 }
2998
2999 @Override
3000 public CodeType resultType() {
3001 return VOID;
3002 }
3003 }
3004
3005 /**
3006 * The labeled operation, that can model Java language labeled statements.
3007 * <p>
3008 * Labeled operations feature one body, the labeled body. The labeled body accepts no arguments and
3009 * yield {@linkplain JavaType#VOID no value}.
3010 * <p>
3011 * The entry block of the labeled body always begins with a {@linkplain ConstantOp} constant modeling
3012 * the label associated with the labeled statement, followed by the statement being labeled.
3013 * <p>
3014 * The result type of a labeled operation is {@link JavaType#VOID}.
3015 *
3016 * @jls 14.7 Labeled Statements
3017 */
3018 @OpDeclaration(LabeledOp.NAME)
3019 public static final class LabeledOp extends AbstractOp
3020 implements JavaOp, Op.Nested, Op.Lowerable, JavaStatement {
3021 static final String NAME = "java.labeled";
3022
3023 final Body body;
3024
3025 LabeledOp(ExternalizedOp def) {
3026 requireNoOperands(def);
3027 this(requireSingleBody(def));
3028 }
3029
3030 LabeledOp(LabeledOp that, CodeContext cc, CodeTransformer ct) {
3031 super(that, cc);
3032
3033 // Copy body
3034 this.body = that.body.transform(cc, ct).build(this);
3035 }
3036
3037 @Override
3038 public LabeledOp transform(CodeContext cc, CodeTransformer ct) {
3039 return new LabeledOp(this, cc, ct);
3040 }
3041
3042 LabeledOp(Body.Builder bodyC) {
3043 super(List.of());
3044 this.body = requireVoidBodySignature(NAME, bodyC).build(this);
3045 }
3046
3047 @Override
3048 public List<Body> bodies() {
3049 return List.of(body);
3050 }
3051
3052 /**
3053 * {@return the labeled body}
3054 */
3055 public Body body() {
3056 return body;
3057 }
3058
3059 /**
3060 * {@return the label associated with this labeled operation}
3061 */
3062 public Op label() {
3063 return body.entryBlock().firstOp();
3064 }
3065
3066 /**
3067 * {@return the label identifier, the operation result of the label}
3068 */
3069 public Op.Result labelIdentifier() {
3070 return label().result();
3071 }
3072
3073 /**
3074 * {@return the first operation associated with this labeled operation}
3075 */
3076 public Op target() {
3077 return body.entryBlock().nextOp(label());
3078 }
3079
3080 @Override
3081 public Block.Builder lower(Block.Builder b, BiFunction<Block.Builder, Op, Block.Builder> inherited) {
3082 Block.Builder exit = b.block();
3083 BranchTarget.setBranchTarget(b.context(), this, exit, null);
3084
3085 AtomicBoolean first = new AtomicBoolean();
3086 b.transformBody(body, List.of(), loweringTransformer(inherited, (block, op) -> {
3087 // Drop first operation that corresponds to the label
3088 if (!first.get()) {
3089 first.set(true);
3090 return block;
3091 }
3092
3093 if (op instanceof CoreOp.YieldOp) {
3094 block.add(branch(exit.reference()));
3095 return block;
3096 } else {
3097 return null;
3098 }
3099 }));
3100
3101 return exit;
3102 }
3103
3104 @Override
3105 public CodeType resultType() {
3106 return VOID;
3107 }
3108 }
3109
3110 /**
3111 * The if operation, that can model Java language if statements.
3112 * <p>
3113 * If operations feature multiple bodies. Some bodies, called <em>predicate bodies</em>, model conditions that
3114 * determine which execution path the evaluation of the if operation should take. Other bodies, called
3115 * <em>action bodies</em>, model the statements to be executed when the preceding predicate is satisfied.
3116 * <p>
3117 * Each predicate body has a corresponding action body, and there may be a trailing action body with no
3118 * predicate, modeling the code after the Java {@code else} keyword.
3119 * <p>
3120 * Predicate bodies should accept no arguments and yield a {@link JavaType#BOOLEAN} value.
3121 * Action bodies similarly accept no arguments, and yield {@linkplain JavaType#VOID no value}.
3122 * <p>
3123 * The result type of an if operation is {@link JavaType#VOID}.
3124 *
3125 * @jls 14.9 The if Statement
3126 */
3127 @OpDeclaration(IfOp.NAME)
3128 public static final class IfOp extends AbstractOp
3129 implements JavaOp, Op.Nested, Op.Lowerable, JavaStatement {
3130
3131 static final FunctionType PREDICATE_SIGNATURE = CoreType.functionType(BOOLEAN);
3132
3133 static final FunctionType ACTION_SIGNATURE = CoreType.FUNCTION_TYPE_VOID;
3134
3135 /**
3136 * Builder for the initial predicate body of an if operation.
3137 */
3138 public static class IfBuilder {
3139 final Body.Builder connectedAncestorBody;
3140 final List<Body.Builder> bodies;
3141
3142 IfBuilder(Body.Builder connectedAncestorBody) {
3143 this.connectedAncestorBody = connectedAncestorBody;
3144 this.bodies = new ArrayList<>();
3145 }
3146
3147 /**
3148 * Begins an if operation by adding the initial predicate body.
3149 *
3150 * @param c a consumer that populates the predicate body
3151 * @return a builder to add an action body to the if operation
3152 */
3153 public ThenBuilder if_(Consumer<Block.Builder> c) {
3154 Body.Builder body = Body.Builder.of(connectedAncestorBody, PREDICATE_SIGNATURE);
3155 c.accept(body.entryBlock());
3156 bodies.add(body);
3157
3158 return new ThenBuilder(connectedAncestorBody, bodies);
3159 }
3160 }
3161
3162 /**
3163 * Builder for the action body of an if operation.
3164 */
3165 public static class ThenBuilder {
3166 final Body.Builder connectedAncestorBody;
3167 final List<Body.Builder> bodies;
3168
3169 ThenBuilder(Body.Builder connectedAncestorBody, List<Body.Builder> bodies) {
3170 this.connectedAncestorBody = connectedAncestorBody;
3171 this.bodies = bodies;
3172 }
3173
3174 /**
3175 * Adds an action body to the if operation.
3176 *
3177 * @param c a consumer that populates the action body
3178 * @return a builder for further predicate and action bodies
3179 */
3180 public ElseIfBuilder then(Consumer<Block.Builder> c) {
3181 Body.Builder body = Body.Builder.of(connectedAncestorBody, ACTION_SIGNATURE);
3182 c.accept(body.entryBlock());
3183 bodies.add(body);
3184
3185 return new ElseIfBuilder(connectedAncestorBody, bodies);
3186 }
3187
3188 /**
3189 * Adds an empty action body to the if operation.
3190 * @return a builder for further predicate and action bodies
3191 */
3192 public ElseIfBuilder then() {
3193 Body.Builder body = Body.Builder.of(connectedAncestorBody, ACTION_SIGNATURE);
3194 body.entryBlock().add(core_yield());
3195 bodies.add(body);
3196
3197 return new ElseIfBuilder(connectedAncestorBody, bodies);
3198 }
3199 }
3200
3201 /**
3202 * Builder for additional predicate and action bodies of an if operation.
3203 */
3204 public static class ElseIfBuilder {
3205 final Body.Builder connectedAncestorBody;
3206 final List<Body.Builder> bodies;
3207
3208 ElseIfBuilder(Body.Builder connectedAncestorBody, List<Body.Builder> bodies) {
3209 this.connectedAncestorBody = connectedAncestorBody;
3210 this.bodies = bodies;
3211 }
3212
3213 /**
3214 * Adds a predicate body to the if operation.
3215 *
3216 * @param c a consumer that populates the predicate body
3217 * @return a builder to add an action body to the if operation
3218 */
3219 public ThenBuilder elseif(Consumer<Block.Builder> c) {
3220 Body.Builder body = Body.Builder.of(connectedAncestorBody, PREDICATE_SIGNATURE);
3221 c.accept(body.entryBlock());
3222 bodies.add(body);
3223
3224 return new ThenBuilder(connectedAncestorBody, bodies);
3225 }
3226
3227 /**
3228 * Completes the if operation by adding the final action body.
3229 *
3230 * @param c a consumer that populates the action body
3231 * @return the completed if operation
3232 */
3233 public IfOp else_(Consumer<Block.Builder> c) {
3234 Body.Builder body = Body.Builder.of(connectedAncestorBody, ACTION_SIGNATURE);
3235 c.accept(body.entryBlock());
3236 bodies.add(body);
3237
3238 return new IfOp(bodies);
3239 }
3240
3241 /**
3242 * Completes the if operation with no final action body.
3243 * @return the completed if operation
3244 */
3245 public IfOp noElse() {
3246 return new IfOp(bodies);
3247 }
3248 }
3249
3250 static final String NAME = "java.if";
3251
3252 final List<Body> bodies;
3253
3254 IfOp(ExternalizedOp def) {
3255 requireNoOperands(def);
3256 this(def.bodyDefinitions());
3257 }
3258
3259 IfOp(IfOp that, CodeContext cc, CodeTransformer ct) {
3260 super(that, cc);
3261
3262 // Copy body
3263 this.bodies = that.bodies.stream()
3264 .map(b -> b.transform(cc, ct).build(this)).toList();
3265 }
3266
3267 @Override
3268 public IfOp transform(CodeContext cc, CodeTransformer ct) {
3269 return new IfOp(this, cc, ct);
3270 }
3271
3272 IfOp(List<Body.Builder> bodyCs) {
3273 if (bodyCs.size() < 2) {
3274 throw structuralException(NAME, "requires 2 or more bodies, found %d".formatted(bodyCs.size()));
3275 }
3276 for (int i = 0; i < bodyCs.size(); i++) {
3277 requireBodySignature("%s body[%d]".formatted(NAME, i), bodyCs.get(i), i % 2 == 0 && i < bodyCs.size() - 1 ? PREDICATE_SIGNATURE : ACTION_SIGNATURE);
3278 }
3279 super(List.of());
3280
3281 this.bodies = bodyCs.stream().map(bc -> bc.build(this)).toList();
3282 }
3283
3284 @Override
3285 public List<Body> bodies() {
3286 return bodies;
3287 }
3288
3289 static boolean isEmptyBodyAction(Body body) {
3290 Block block = body.entryBlock();
3291 return body.blocks().size() == 1
3292 && block.ops().size() == 1
3293 && block.terminatingOp() instanceof CoreOp.YieldOp;
3294 }
3295
3296 @Override
3297 public Block.Builder lower(Block.Builder b, BiFunction<Block.Builder, Op, Block.Builder> inherited) {
3298 Block.Builder exit = b.block();
3299 BranchTarget.setBranchTarget(b.context(), this, exit, null);
3300
3301 // Create predicate and action blocks
3302 List<Block.Builder> builders = new ArrayList<>();
3303 for (int i = 0; i < bodies.size(); i += 2) {
3304 if (i == bodies.size() - 1) {
3305 builders.add(b.block());
3306 } else {
3307 builders.add(i == 0 ? b : b.block());
3308 builders.add(b.block());
3309 }
3310 }
3311
3312 for (int i = 0; i < bodies.size(); i += 2) {
3313 Body actionBody;
3314 Block.Builder action;
3315 if (i == bodies.size() - 1) {
3316 actionBody = bodies.get(i);
3317 action = builders.get(i);
3318 } else {
3319 Body predBody = bodies.get(i);
3320 actionBody = bodies.get(i + 1);
3321
3322 Block.Builder pred = builders.get(i);
3323 action = builders.get(i + 1);
3324 Block.Builder nextAction = i + 2 < builders.size() ? builders.get(i + 2) : exit;
3325
3326 ControlFlowBooleanExpressionOp.lowerBooleanBody(pred, predBody, List.of(),
3327 new ControlFlowBooleanExpressionOp.ConditionalBranchContinuation(action.reference(), nextAction.reference()),
3328 inherited);
3329 }
3330
3331 action.transformBody(actionBody, List.of(), loweringTransformer(inherited, (block, op) -> {
3332 if (op instanceof CoreOp.YieldOp) {
3333 block.add(branch(exit.reference()));
3334 return block;
3335 } else {
3336 return null;
3337 }
3338 }));
3339 }
3340
3341 return exit;
3342 }
3343
3344 @Override
3345 public CodeType resultType() {
3346 return VOID;
3347 }
3348 }
3349
3350 /**
3351 * An operation modeling a Java switch statement or expression.
3352 * <p>
3353 * Switch operations are parameterized by a selector value.
3354 * They feature a sequence of case bodies, each modeled as a pair of bodies: a <em>predicate body</em> and an
3355 * <em>action body</em>.
3356 * <p>
3357 * Each predicate body accepts one argument, the selector value, and yields a {@link JavaType#BOOLEAN} value.
3358 * Each action body yields a value of the same type {@code T}. For switch statement operations, {@code T} is
3359 * {@code void}. For switch expression operations, {@code T} is the switch expression type.
3360 *
3361 * @jls 14.11 The switch Statement
3362 * @jls 15.28 {@code switch} Expressions
3363 */
3364 public abstract static sealed class SwitchOp extends AbstractOp
3365 implements JavaOp, Op.Nested, Op.Lowerable
3366 permits SwitchStatementOp, SwitchExpressionOp {
3367
3368 final List<Body> bodies;
3369
3370 SwitchOp(SwitchOp that, CodeContext cc, CodeTransformer ct) {
3371 super(that, cc);
3372
3373 // Copy body
3374 this.bodies = that.bodies.stream()
3375 .map(b -> b.transform(cc, ct).build(this)).toList();
3376 }
3377
3378 /*
3379 Grammar for switch statements and expressions
3380 SwitchStatement:
3381 switch ( Expression ) SwitchBlock
3382
3383 SwitchExpression:
3384 switch ( Expression ) SwitchBlock
3385
3386 SwitchBlock:
3387 { SwitchRule {SwitchRule} }
3388 { {SwitchBlockStatementGroup} {SwitchLabel :} }
3389
3390 SwitchRule:
3391 SwitchLabel -> Expression ;
3392 SwitchLabel -> Block
3393 SwitchLabel -> ThrowStatement
3394
3395 SwitchBlockStatementGroup:
3396 SwitchLabel : {SwitchLabel :} BlockStatements
3397
3398 SwitchLabel:
3399 case CaseConstant {, CaseConstant}
3400 case null [, default]
3401 case CasePattern {, CasePattern} [Guard]
3402 default
3403
3404 CaseConstant:
3405 ConditionalExpression
3406
3407 CasePattern:
3408 Pattern
3409
3410 Guard:
3411 when Expression
3412
3413 A SwitchLabel is modeled as a body yielding a boolean value.
3414
3415 If the SwitchLabel is "default" or "case null, default" the predicate body is modeled as one that yields
3416 true, and the body has no parameters. Otherwise, the body has one parameter that models the result of the
3417 switch selector expression and its content models "case CaseConstant {, CaseConstant}" and
3418 "case CasePattern {, CasePattern} [Guard]".
3419
3420 If the SwitchLabel is "case null" the predicate body is modeled as one that yields the result of comparing
3421 the body's parameter with null.
3422
3423 For a SwitchLabel containing a sequence of two or more CaseConstant or CasePattern, the predicate body
3424 yields the result of the logical-or of all the predicate bodies modeling each CaseConstant or CasePattern.
3425 For a SwitchLabel containing a CasePattern with a Guard, the predicate body yields the result of the
3426 logical-and of the predicate body produced for the sequence of CasePattern and the boolean yielding body
3427 modeling the Guard expression.
3428
3429 An Expression, Block, ThrowStatement, or BlockStatements, associated with a SwitchLabel is modeled as an action
3430 body yielding the result of the switch expression or void for a switch statement. The body has no parameters.
3431
3432 A SwitchBlock is modeled as a sequence of pairs of bodies, in general, the first body in a pair, the predicate
3433 body, models the SwitchLabel, and the second body, the action body, models the Expression, Block,
3434 ThrowStatement, or BlockStatements. A SwitchLabel, of a SwitchBlockStatementGroup, with no associated
3435 BlockStatements is also modeled as a pair of bodies, the first body in a pair, the predicate body, models the
3436 SwitchLabel, and the second synthesized body, the action body, models fall-through to the next action body.
3437
3438 If the SwitchBlock contains a SwitchLabel of "case null [, default]" then the switch operation indicates that
3439 null values are accepted for results of the selector expression.
3440
3441 For a switch expression or enhanced switch statement whose SwitchBlock contains no "default",
3442 "case null, default", or "case CasePattern" for an unconditional pattern label, a synthesized pair of bodies
3443 occurs at the end of the sequence of bodies. The first synthesized body in the pair, the predicate body, has
3444 the same form as the predicate body modeling "default", and the second synthesized body, the action body,
3445 models the throwing of a MatchException.
3446 */
3447
3448 SwitchOp(Value target, List<Body.Builder> bodyCs) {
3449 super(List.of(target));
3450
3451 this.bodies = bodyCs.stream().map(bc -> bc.build(this)).toList();
3452 }
3453
3454 @Override
3455 public List<Body> bodies() {
3456 return bodies;
3457 }
3458
3459 boolean hasYieldStatements() {
3460 return this.elements().anyMatch(
3461 e -> e instanceof JavaOp.YieldOp yop && yop.targetsOrAttemptsToExit(this));
3462 }
3463
3464 static boolean isNullLabel(Body labelBody) {
3465 //@@@ when op pattern matching is ready, we can use it
3466 return labelBody != null &&
3467 labelBody.blocks().size() == 1 &&
3468 labelBody.entryBlock().terminatingOp() instanceof CoreOp.YieldOp yieldOp &&
3469 yieldOp.yieldValue() instanceof Result opr &&
3470 opr.op() instanceof EqOp eqOp &&
3471 eqOp.operands().stream().anyMatch(v -> v instanceof Result r && r.op() instanceof ConstantOp cop
3472 && cop.value() == null);
3473 }
3474
3475 static boolean isDefaultLabel(Body labelBody) {
3476 return labelBody != null &&
3477 labelBody.blocks().size() == 1 &&
3478 labelBody.entryBlock().parameters().isEmpty() &&
3479 labelBody.entryBlock().terminatingOp() instanceof CoreOp.YieldOp yop &&
3480 yop.yieldValue().declaringElement() instanceof ConstantOp cop &&
3481 cop.resultType().equals(BOOLEAN) &&
3482 cop.value() instanceof Boolean trueValue && trueValue;
3483 }
3484
3485 private int findDefLabelIdx() {
3486 for (int i = 0; i < bodies.size(); i += 2) {
3487 if (isDefaultLabel(bodies.get(i))) {
3488 return i;
3489 }
3490 }
3491 return -1;
3492 }
3493
3494 private int findNullLabelIdx() {
3495 for (int i = 0; i < bodies.size(); i += 2) {
3496 if (isNullLabel(bodies.get(i))) {
3497 return i;
3498 }
3499 }
3500 return -1;
3501 }
3502
3503 @Override
3504 public Block.Builder lower(Block.Builder b, BiFunction<Block.Builder, Op, Block.Builder> inherited) {
3505 // map bodies to blocks
3506 List<Block.Builder> blocks = new ArrayList<>();
3507 int defLabelIdx = findDefLabelIdx();
3508 int nullLabelIdx = findNullLabelIdx();
3509 Value selectorExpression = b.context().getValue(operands().getFirst());
3510 boolean selectorCanBeNull = !(selectorExpression.type() instanceof PrimitiveType);
3511 // decide which label will use the incoming block
3512 // if selector can be null the incoming block will be used for null check
3513 int reuseIdx = -1;
3514 if (!selectorCanBeNull) {
3515 int i = 0;
3516 if (i == defLabelIdx) {
3517 i += 2;
3518 if (i > bodies.size() - 1) { // sw has default only
3519 i = defLabelIdx + 1;
3520 }
3521 }
3522 reuseIdx = i;
3523 }
3524 for (int i = 0; i < bodies.size(); i++) {
3525 if (i == defLabelIdx || i == nullLabelIdx) {
3526 blocks.add(null);
3527 } else if (i == reuseIdx) {
3528 blocks.add(b);
3529 } else {
3530 blocks.add(b.block());
3531 }
3532 }
3533
3534 // setup for fallthrough
3535 for (int i = 1; i < bodies.size() - 2; i += 2) {
3536 Body actionBody = bodies().get(i);
3537 Block.Builder nextActionBlock = blocks.get(i + 2);
3538 BranchTarget.setBranchTarget(b.context(), actionBody, null, nextActionBlock);
3539 }
3540
3541 boolean hasYieldStatements = hasYieldStatements();
3542 boolean isBooleanExpression = resultType().equals(BOOLEAN);
3543 // Poll for implicit boolean continuation parameter
3544 ControlFlowBooleanExpressionOp.BooleanResultContinuation continuation = isBooleanExpression
3545 ? ControlFlowBooleanExpressionOp.BOOLEAN_CONTINUATION_ARG.poll(b.context())
3546 : null;
3547 Block.Builder exit;
3548 if (isBooleanExpression) {
3549 if (continuation == null) {
3550 exit = b.block();
3551 b.context().mapValue(result(), exit.parameter(resultType()));
3552 continuation = new ControlFlowBooleanExpressionOp.BranchWithArgumentContinuation(exit);
3553 } else if (hasYieldStatements) {
3554 exit = b.block();
3555 Value value = exit.parameter(resultType());
3556 continuation.continueWith(exit, value);
3557 } else {
3558 exit = b;
3559 }
3560
3561 if (hasYieldStatements) {
3562 BranchTarget.setBranchTarget(b.context(), this, exit, null);
3563 }
3564 } else if (!bodies.isEmpty()) {
3565 exit = b.block();
3566 if (resultType() != VOID) {
3567 Value r = exit.parameter(resultType());
3568 exit.context().mapValue(result(), r);
3569 }
3570 BranchTarget.setBranchTarget(b.context(), this, exit, null);
3571 } else {
3572 exit = selectorCanBeNull ? b.block() : b;
3573 }
3574
3575 // null check
3576 if (selectorCanBeNull) {
3577 Block.Builder nullAction;
3578 if (nullLabelIdx != -1) {
3579 nullAction = blocks.get(nullLabelIdx + 1);
3580 } else {
3581 nullAction = b.block();
3582 nullAction.add(throw_(nullAction.add(new_(MethodRef.constructor(NullPointerException.class)))));
3583 }
3584 Block.Builder noMatch = nextPredicate(0, blocks, exit, defLabelIdx, nullLabelIdx);
3585
3586 Result cnull = b.add(constant(selectorExpression.type(), null));
3587 Result p = b.add(eq(selectorExpression, cnull));
3588 b.add(conditionalBranch(p, nullAction.reference(), noMatch.reference()));
3589 }
3590
3591 // lower predicates
3592 for (int i = 0; i < bodies.size(); i += 2) {
3593 if (i == defLabelIdx || i == nullLabelIdx) {
3594 continue;
3595 }
3596 Body predBody = bodies.get(i);
3597 Block.Builder predBlock = blocks.get(i);
3598 Block.Builder actionBlock = blocks.get(i + 1);
3599 Block.Builder noMatch = nextPredicate(i + 2, blocks, exit, defLabelIdx, nullLabelIdx);
3600 ControlFlowBooleanExpressionOp.lowerBooleanBody(predBlock, predBody, List.of(selectorExpression),
3601 new ControlFlowBooleanExpressionOp.ConditionalBranchContinuation(actionBlock.reference(),
3602 noMatch.reference()), inherited);
3603 }
3604
3605 // lower actions
3606 for (int i = 1; i < bodies.size(); i += 2) {
3607 Body actionBody = bodies.get(i);
3608 Block.Builder actionBlock = blocks.get(i);
3609 if (isBooleanExpression) {
3610 ControlFlowBooleanExpressionOp.lowerBooleanBody(actionBlock, actionBody, List.of(), continuation, inherited);
3611 } else {
3612 actionBlock.transformBody(actionBody, List.of(), loweringTransformer(inherited,
3613 (block, op) -> switch (op) {
3614 case CoreOp.YieldOp yop -> {
3615 List<Value> args = yop.yieldValue() == null
3616 ? List.of()
3617 : List.of(block.context().getValue(yop.yieldValue()));
3618 block.add(branch(exit.reference(args)));
3619 yield block;
3620 }
3621 default -> null;
3622 }));
3623 }
3624 }
3625 return exit;
3626 }
3627
3628 Block.Builder nextPredicate(int startPos, List<Block.Builder> blocks, Block.Builder exit, int defLabelIdx,
3629 int nullLabelIdx) {
3630 // look for the next predicate starting from the position indicated by startPos param
3631 // this logic is needed when lowering a predicate body
3632 // more specifically when lowering the yield of the boolean value to cond_branch %p action_block next_predicate
3633 int i = startPos;
3634 while (i == defLabelIdx || i == nullLabelIdx) {
3635 i += 2;
3636 }
3637 if (i > bodies.size() - 1) {
3638 if (defLabelIdx != -1) {
3639 return blocks.get(defLabelIdx + 1);
3640 } else if (this instanceof SwitchStatementOp) {
3641 return exit;
3642 } else {
3643 Block.Builder block = exit.block();
3644 block.add(unreachable());
3645 return block;
3646 }
3647 } else {
3648 return blocks.get(i);
3649 }
3650 }
3651 }
3652
3653 /**
3654 * The switch expression operation, that can model Java language switch expressions.
3655 * <p>
3656 * For switch expression operations, action bodies yield a value of type {@code T}, where {@code T} is also the
3657 * type of the switch expression operation.
3658 *
3659 * @jls 15.28 {@code switch} Expressions
3660 */
3661 @OpDeclaration(SwitchExpressionOp.NAME)
3662 public static final class SwitchExpressionOp extends SwitchOp
3663 implements ControlFlowBooleanExpressionOp, JavaExpression {
3664 static final String NAME = "java.switch.expression";
3665
3666 final CodeType resultType;
3667
3668 SwitchExpressionOp(ExternalizedOp def) {
3669 this(def.resultType(), requireSingleOperand(def), def.bodyDefinitions());
3670 }
3671
3672 SwitchExpressionOp(SwitchExpressionOp that, CodeContext cc, CodeTransformer ct) {
3673 super(that, cc, ct);
3674
3675 this.resultType = that.resultType;
3676 }
3677
3678 @Override
3679 public SwitchExpressionOp transform(CodeContext cc, CodeTransformer ct) {
3680 return new SwitchExpressionOp(this, cc, ct);
3681 }
3682
3683 SwitchExpressionOp(CodeType resultType, Value target, List<Body.Builder> bodyCs) {
3684 super(target, requireBodyPairs(NAME, requireMinBodies(NAME, bodyCs, 2)));
3685 this.resultType = resultType == null ? bodies.get(1).yieldType() : resultType;
3686 }
3687
3688 @Override
3689 public CodeType resultType() {
3690 return resultType;
3691 }
3692 }
3693
3694 /**
3695 * The switch statement operation, that can model Java language switch statement.
3696 * <p>
3697 * For switch statement operations, action bodies yield {@linkplain JavaType#VOID no value}.
3698 * <p>
3699 * The result type of a switch statement operation is {@link JavaType#VOID}.
3700 *
3701 * @jls 14.11 The switch Statement
3702 */
3703 @OpDeclaration(SwitchStatementOp.NAME)
3704 public static final class SwitchStatementOp extends SwitchOp
3705 implements JavaStatement {
3706 static final String NAME = "java.switch.statement";
3707
3708 SwitchStatementOp(ExternalizedOp def) {
3709 this(requireSingleOperand(def), def.bodyDefinitions());
3710 }
3711
3712 SwitchStatementOp(SwitchStatementOp that, CodeContext cc, CodeTransformer ct) {
3713 super(that, cc, ct);
3714 }
3715
3716 @Override
3717 public SwitchStatementOp transform(CodeContext cc, CodeTransformer ct) {
3718 return new SwitchStatementOp(this, cc, ct);
3719 }
3720
3721 SwitchStatementOp(Value target, List<Body.Builder> bodyCs) {
3722 // min number of bodies for a switch statement depends on whether the switch statement is enhanced or not
3723 // non-enhanced switch statement may have zero bodies
3724 // e.g.
3725 // Integer i = ...;
3726 // switch (i) {
3727 // }
3728 // enhanced switch statement must be exhaustive, so it require two bodies representing
3729 // implicit/explicit default
3730 // e.g.
3731 // Object o = ...;
3732 // switch(o) {
3733 // default;;
3734 // }
3735 // switch(o) {
3736 // case Object:;
3737 // }
3738
3739 // for now, we relax the validation by allowing zero bodies in all cases
3740
3741 super(target, requireBodyPairs(NAME, requireMinBodies(NAME, bodyCs, 0)));
3742 }
3743
3744 @Override
3745 public CodeType resultType() {
3746 return VOID;
3747 }
3748 }
3749
3750 /**
3751 * The switch fall-through operation, that can model fall-through to the next statement in the switch block after
3752 * the last statement of the current switch label.
3753 * <p>
3754 * A switch fall-through operation is a body terminating operation.
3755 */
3756 @OpDeclaration(SwitchFallthroughOp.NAME)
3757 public static final class SwitchFallthroughOp extends AbstractOp.Terminating
3758 implements JavaOp, Op.Lowerable {
3759 static final String NAME = "java.switch.fallthrough";
3760
3761 SwitchFallthroughOp(ExternalizedOp def) {
3762 this();
3763 }
3764
3765 SwitchFallthroughOp(SwitchFallthroughOp that, CodeContext cc) {
3766 super(that, cc);
3767 }
3768
3769 @Override
3770 public SwitchFallthroughOp transform(CodeContext cc, CodeTransformer ct) {
3771 return new SwitchFallthroughOp(this, cc);
3772 }
3773
3774 SwitchFallthroughOp() {
3775 super(List.of());
3776 }
3777
3778 @Override
3779 public CodeType resultType() {
3780 return VOID;
3781 }
3782
3783 @Override
3784 public Block.Builder lower(Block.Builder b, BiFunction<Block.Builder, Op, Block.Builder> inherited) {
3785 return lower(b, BranchTarget::continueBlock);
3786 }
3787
3788 Block.Builder lower(Block.Builder b, Function<BranchTarget, Block.Builder> f) {
3789 BranchTarget t = BranchTarget.getBranchTarget(b.context(), ancestorBody());
3790 if (t != null) {
3791 b.add(branch(f.apply(t).reference()));
3792 } else {
3793 throw new IllegalStateException("No branch target for operation: " + this);
3794 }
3795 return b;
3796 }
3797 }
3798
3799 /**
3800 * The for operation, that can model a Java language basic for statement.
3801 * <p>
3802 * For operations feature four bodies that model a basic {@code for} statement:
3803 * an <em>initialization body</em>, a <em>predicate body</em>, an <em>update body</em>, and a <em>loop body</em>.
3804 * <p>
3805 * The initialization body accepts no arguments and yields the loop state, of type {@code S}. For instance,
3806 * a loop with a single loop variable of type {@code T} might use a loop state of type {@code T}.
3807 * A loop with two loop variables of type {@code X} and {@code Y} might use a loop state whose type is
3808 * a {@linkplain TupleType tuple type}, such as {@code (X, Y)}. A loop with no loop variables might use
3809 * a loop state of type {@link JavaType#VOID}, and have its initialization body yield no value.
3810 * <p>
3811 * The predicate body accepts an argument of type {@code S} and yields a {@link JavaType#BOOLEAN} value.
3812 * The update and loop bodies accept an argument of type {@code S} and yield {@linkplain JavaType#VOID no value}.
3813 * <p>
3814 * The result type of a for operation is {@link JavaType#VOID}.
3815 *
3816 * @jls 14.14.1 The basic for Statement
3817 */
3818 @OpDeclaration(ForOp.NAME)
3819 public static final class ForOp extends AbstractOp
3820 implements JavaOp, Op.Loop, Op.Lowerable, JavaStatement {
3821
3822 /**
3823 * Builder for the initialization body of a for operation.
3824 */
3825 public static final class InitBuilder {
3826 final Body.Builder connectedAncestorBody;
3827 final List<? extends CodeType> initTypes;
3828
3829 InitBuilder(Body.Builder connectedAncestorBody,
3830 List<? extends CodeType> initTypes) {
3831 this.connectedAncestorBody = connectedAncestorBody;
3832 this.initTypes = initTypes.stream().map(CoreType::varType).toList();
3833 }
3834
3835 /**
3836 * Builds the initialization body of a for-loop.
3837 *
3838 * @param c a consumer that populates the initialization body
3839 * @return a builder for specifying the loop predicate body
3840 */
3841 public ForOp.CondBuilder init(Consumer<Block.Builder> c) {
3842 Body.Builder init = Body.Builder.of(connectedAncestorBody,
3843 CoreType.functionType(CoreType.tupleType(initTypes)));
3844 c.accept(init.entryBlock());
3845
3846 return new CondBuilder(connectedAncestorBody, initTypes, init);
3847 }
3848 }
3849
3850 /**
3851 * Builder for the predicate body of a for operation.
3852 */
3853 public static final class CondBuilder {
3854 final Body.Builder connectedAncestorBody;
3855 final List<? extends CodeType> initTypes;
3856 final Body.Builder init;
3857
3858 CondBuilder(Body.Builder connectedAncestorBody,
3859 List<? extends CodeType> initTypes,
3860 Body.Builder init) {
3861 this.connectedAncestorBody = connectedAncestorBody;
3862 this.initTypes = initTypes;
3863 this.init = init;
3864 }
3865
3866 /**
3867 * Builds the predicate body of a for-loop.
3868 *
3869 * @param c a consumer that populates the predicate body
3870 * @return a builder for specifying the update body
3871 */
3872 public ForOp.UpdateBuilder cond(Consumer<Block.Builder> c) {
3873 Body.Builder cond = Body.Builder.of(connectedAncestorBody,
3874 CoreType.functionType(BOOLEAN, initTypes));
3875 c.accept(cond.entryBlock());
3876
3877 return new UpdateBuilder(connectedAncestorBody, initTypes, init, cond);
3878 }
3879 }
3880
3881 /**
3882 * Builder for the update body of a for operation.
3883 */
3884 public static final class UpdateBuilder {
3885 final Body.Builder connectedAncestorBody;
3886 final List<? extends CodeType> initTypes;
3887 final Body.Builder init;
3888 final Body.Builder cond;
3889
3890 UpdateBuilder(Body.Builder connectedAncestorBody,
3891 List<? extends CodeType> initTypes,
3892 Body.Builder init, Body.Builder cond) {
3893 this.connectedAncestorBody = connectedAncestorBody;
3894 this.initTypes = initTypes;
3895 this.init = init;
3896 this.cond = cond;
3897 }
3898
3899 /**
3900 * Builds the update body of a for-loop.
3901 *
3902 * @param c a consumer that populates the update body
3903 * @return a builder for specifying the loop body
3904 */
3905 public ForOp.BodyBuilder update(Consumer<Block.Builder> c) {
3906 Body.Builder update = Body.Builder.of(connectedAncestorBody,
3907 CoreType.functionType(VOID, initTypes));
3908 c.accept(update.entryBlock());
3909
3910 return new BodyBuilder(connectedAncestorBody, initTypes, init, cond, update);
3911 }
3912 }
3913
3914 /**
3915 * Builder for the body (main logic) portion of a for-loop.
3916 */
3917 public static final class BodyBuilder {
3918 final Body.Builder connectedAncestorBody;
3919 final List<? extends CodeType> initTypes;
3920 final Body.Builder init;
3921 final Body.Builder cond;
3922 final Body.Builder update;
3923
3924 BodyBuilder(Body.Builder connectedAncestorBody,
3925 List<? extends CodeType> initTypes,
3926 Body.Builder init, Body.Builder cond, Body.Builder update) {
3927 this.connectedAncestorBody = connectedAncestorBody;
3928 this.initTypes = initTypes;
3929 this.init = init;
3930 this.cond = cond;
3931 this.update = update;
3932 }
3933
3934 /**
3935 * Completes for operation by adding the loop body.
3936 *
3937 * @param c a consumer that populates the loop body
3938 * @return the completed for-loop operation
3939 */
3940 public ForOp body(Consumer<Block.Builder> c) {
3941 Body.Builder body = Body.Builder.of(connectedAncestorBody,
3942 CoreType.functionType(VOID, initTypes));
3943 c.accept(body.entryBlock());
3944
3945 return new ForOp(init, cond, update, body);
3946 }
3947 }
3948
3949 static final String NAME = "java.for";
3950
3951 final Body initBody;
3952 final Body condBody;
3953 final Body updateBody;
3954 final Body loopBody;
3955
3956 ForOp(ExternalizedOp def) {
3957 List<Body.Builder> bodies = requireBodies(def, 4);
3958 this(bodies.get(0), bodies.get(1), bodies.get(2), bodies.get(3));
3959 }
3960
3961 ForOp(ForOp that, CodeContext cc, CodeTransformer ct) {
3962 super(that, cc);
3963
3964 this.initBody = that.initBody.transform(cc, ct).build(this);
3965 this.condBody = that.condBody.transform(cc, ct).build(this);
3966 this.updateBody = that.updateBody.transform(cc, ct).build(this);
3967 this.loopBody = that.loopBody.transform(cc, ct).build(this);
3968 }
3969
3970 @Override
3971 public ForOp transform(CodeContext cc, CodeTransformer ct) {
3972 return new ForOp(this, cc, ct);
3973 }
3974
3975 ForOp(Body.Builder initC,
3976 Body.Builder condC,
3977 Body.Builder updateC,
3978 Body.Builder bodyC) {
3979 super(List.of());
3980
3981 List<CodeType> varTypes = switch (initC.bodySignature().returnType()) {
3982 case TupleType tt -> tt.componentTypes();
3983 case PrimitiveType pt when pt.equals(VOID) -> List.of();
3984 case CodeType t -> List.of(t);
3985 };
3986 FunctionType condType = CoreType.functionType(BOOLEAN, varTypes);
3987 FunctionType bodyType = CoreType.functionType(VOID, varTypes);
3988
3989 this.initBody = requireNoParameters(NAME + " init", initC).build(this);
3990 this.condBody = requireBodySignature(NAME + " predicate", condC, condType).build(this);
3991 this.updateBody = requireBodySignature(NAME + " update", updateC, bodyType).build(this);
3992 this.loopBody = requireBodySignature(NAME + " loop", bodyC, bodyType).build(this);
3993 }
3994
3995 @Override
3996 public List<Body> bodies() {
3997 return List.of(initBody, condBody, updateBody, loopBody);
3998 }
3999
4000 /**
4001 * {@return the initialization body}
4002 */
4003 public Body initBody() {
4004 return initBody;
4005 }
4006
4007 /**
4008 * {@return the loop condition (predicate) body}
4009 */
4010 public Body condBody() {
4011 return condBody;
4012 }
4013
4014 /**
4015 * {@return the update body}
4016 */
4017 public Body updateBody() {
4018 return updateBody;
4019 }
4020
4021 @Override
4022 public Body loopBody() {
4023 return loopBody;
4024 }
4025
4026 @Override
4027 public Block.Builder lower(Block.Builder b, BiFunction<Block.Builder, Op, Block.Builder> inherited) {
4028 Block.Builder header = b.block();
4029 Block.Builder body = b.block();
4030 Block.Builder update = b.block();
4031 Block.Builder exit = b.block();
4032
4033 List<Value> initValues = new ArrayList<>();
4034 // @@@ Init body has one yield operation yielding
4035 // void, a single variable, or a tuple of one or more variables
4036 b.transformBody(initBody, List.of(), loweringTransformer(inherited, (block, op) -> switch (op) {
4037 case TupleOp _ -> {
4038 // Drop Tuple if a yielded
4039 boolean isResult = op.result().uses().size() == 1 &&
4040 op.result().uses().stream().allMatch(r -> r.op() instanceof CoreOp.YieldOp);
4041 if (!isResult) {
4042 block.add(op);
4043 }
4044 yield block;
4045 }
4046 case CoreOp.YieldOp yop -> {
4047 if (yop.yieldValue() == null) {
4048 block.add(branch(header.reference()));
4049 yield block;
4050 } else if (yop.yieldValue() instanceof Result or) {
4051 if (or.op() instanceof TupleOp top) {
4052 initValues.addAll(block.context().getValues(top.operands()));
4053 } else {
4054 initValues.addAll(block.context().getValues(yop.operands()));
4055 }
4056 block.add(branch(header.reference()));
4057 yield block;
4058 }
4059
4060 throw new IllegalStateException("Bad yield operation");
4061 }
4062 default -> null;
4063 }));
4064
4065 ControlFlowBooleanExpressionOp.lowerBooleanBody(header, condBody, initValues,
4066 new ControlFlowBooleanExpressionOp.ConditionalBranchContinuation(body.reference(), exit.reference()),
4067 inherited);
4068
4069 BranchTarget.setBranchTarget(b.context(), this, exit, update);
4070
4071 body.transformBody(loopBody, initValues, loweringTransformer(inherited, (_, _) -> null));
4072
4073 update.transformBody(updateBody, initValues, loweringTransformer(inherited, (block, op) -> {
4074 if (op instanceof CoreOp.YieldOp) {
4075 block.add(branch(header.reference()));
4076 return block;
4077 } else {
4078 return null;
4079 }
4080 }));
4081
4082 return exit;
4083 }
4084
4085 @Override
4086 public CodeType resultType() {
4087 return VOID;
4088 }
4089 }
4090
4091 /**
4092 * The enhanced for operation, that can model a Java language enhanced for statement.
4093 * <p>
4094 * Enhanced-for operations feature three bodies. The <em>expression body</em> models the expression to be
4095 * iterated. The <em>definition body</em> models the definition of the loop variable. The <em>loop body</em>
4096 * models the statements to execute.
4097 * <p>
4098 * The expression body accepts no arguments and yields a value of type {@code I}, corresponding to the type of the
4099 * expression to be iterated. The definition body accepts one argument of type {@code E}, corresponding to an element
4100 * type derived from {@code I}, and yields a value of type {@code V}, the type of the loop variable. Finally, the loop
4101 * body accepts that value and yields {@linkplain JavaType#VOID no value}.
4102 * <p>
4103 * The result type of an enhanced-for operation is {@link JavaType#VOID}.
4104 *
4105 * @jls 14.14.2 The enhanced for statement
4106 */
4107 @OpDeclaration(EnhancedForOp.NAME)
4108 public static final class EnhancedForOp extends AbstractOp
4109 implements JavaOp, Op.Loop, Op.Lowerable, JavaStatement {
4110
4111 /**
4112 * Builder for the expression body of an enhanced-for operation.
4113 */
4114 public static final class ExpressionBuilder {
4115 final Body.Builder connectedAncestorBody;
4116 final CodeType iterableType;
4117 final CodeType elementType;
4118
4119 ExpressionBuilder(Body.Builder connectedAncestorBody,
4120 CodeType iterableType, CodeType elementType) {
4121 this.connectedAncestorBody = connectedAncestorBody;
4122 this.iterableType = iterableType;
4123 this.elementType = elementType;
4124 }
4125
4126 /**
4127 * Builds the expression body of an enhanced-for operation.
4128 *
4129 * @param c a consumer that populates the expression body
4130 * @return a builder for specifying the definition body
4131 */
4132 public DefinitionBuilder expression(Consumer<Block.Builder> c) {
4133 Body.Builder expression = Body.Builder.of(connectedAncestorBody,
4134 CoreType.functionType(iterableType));
4135 c.accept(expression.entryBlock());
4136
4137 return new DefinitionBuilder(connectedAncestorBody, elementType, expression);
4138 }
4139 }
4140
4141 /**
4142 * Builder for the definition body of an enhanced-for operation.
4143 */
4144 public static final class DefinitionBuilder {
4145 final Body.Builder connectedAncestorBody;
4146 final CodeType elementType;
4147 final Body.Builder expression;
4148
4149 DefinitionBuilder(Body.Builder connectedAncestorBody,
4150 CodeType elementType, Body.Builder expression) {
4151 this.connectedAncestorBody = connectedAncestorBody;
4152 this.elementType = elementType;
4153 this.expression = expression;
4154 }
4155
4156 /**
4157 * Builds the definition body of an enhanced-for operation, using a type derived from the type
4158 * of the loop expression.
4159 *
4160 * @param c a consumer that populates the definition body
4161 * @return a builder for specifying the loop body
4162 */
4163 public BodyBuilder definition(Consumer<Block.Builder> c) {
4164 return definition(elementType, c);
4165 }
4166
4167 /**
4168 * Builds the definition body of an enhanced-for operation with the provided type.
4169 *
4170 * @param bodyElementType the type to provide to the loop body
4171 * @param c a consumer that populates the definition body
4172 * @return a builder for specifying the loop body
4173 */
4174 public BodyBuilder definition(CodeType bodyElementType, Consumer<Block.Builder> c) {
4175 Body.Builder definition = Body.Builder.of(connectedAncestorBody,
4176 CoreType.functionType(bodyElementType, elementType));
4177 c.accept(definition.entryBlock());
4178
4179 return new BodyBuilder(connectedAncestorBody, elementType, expression, definition);
4180 }
4181 }
4182
4183 /**
4184 * Builder for the loop body of an enhanced-for operation.
4185 */
4186 public static final class BodyBuilder {
4187 final Body.Builder connectedAncestorBody;
4188 final CodeType elementType;
4189 final Body.Builder expression;
4190 final Body.Builder definition;
4191
4192 BodyBuilder(Body.Builder connectedAncestorBody,
4193 CodeType elementType, Body.Builder expression, Body.Builder definition) {
4194 this.connectedAncestorBody = connectedAncestorBody;
4195 this.elementType = elementType;
4196 this.expression = expression;
4197 this.definition = definition;
4198 }
4199
4200 /**
4201 * Completes the enhanced-for operation by adding the loop body.
4202 *
4203 * @param c a consumer that populates the loop body
4204 * @return the completed enhanced-for operation
4205 */
4206 public EnhancedForOp body(Consumer<Block.Builder> c) {
4207 Body.Builder body = Body.Builder.of(connectedAncestorBody,
4208 CoreType.functionType(VOID, elementType));
4209 c.accept(body.entryBlock());
4210
4211 return new EnhancedForOp(expression, definition, body);
4212 }
4213 }
4214
4215 static final String NAME = "java.enhancedFor";
4216
4217 final Body exprBody;
4218 final Body initBody;
4219 final Body loopBody;
4220
4221 EnhancedForOp(ExternalizedOp def) {
4222 List<Body.Builder> bodies = requireBodies(def, 3);
4223 this(bodies.get(0), bodies.get(1), bodies.get(2));
4224 }
4225
4226 EnhancedForOp(EnhancedForOp that, CodeContext cc, CodeTransformer ct) {
4227 super(that, cc);
4228
4229 this.exprBody = that.exprBody.transform(cc, ct).build(this);
4230 this.initBody = that.initBody.transform(cc, ct).build(this);
4231 this.loopBody = that.loopBody.transform(cc, ct).build(this);
4232 }
4233
4234 @Override
4235 public EnhancedForOp transform(CodeContext cc, CodeTransformer ct) {
4236 return new EnhancedForOp(this, cc, ct);
4237 }
4238
4239 EnhancedForOp(Body.Builder expressionC, Body.Builder initC, Body.Builder bodyC) {
4240 super(List.of());
4241
4242 this.exprBody = requireNonVoidReturnType(NAME + " expression", expressionC, 0).build(this);
4243 this.initBody = requireNonVoidReturnType(NAME + " initialization", initC, 1).build(this);
4244 this.loopBody = requireVoidReturnType(NAME + " loop", bodyC, 1).build(this);
4245 }
4246
4247 @Override
4248 public List<Body> bodies() {
4249 return List.of(exprBody, initBody, loopBody);
4250 }
4251
4252 /**
4253 * {@return the expression body}
4254 */
4255 public Body exprBody() {
4256 return exprBody;
4257 }
4258
4259 /**
4260 * {@return the initialization body}
4261 */
4262 public Body initBody() {
4263 return initBody;
4264 }
4265
4266 @Override
4267 public Body loopBody() {
4268 return loopBody;
4269 }
4270
4271 static final MethodRef ITERABLE_ITERATOR = MethodRef.method(Iterable.class, "iterator", Iterator.class);
4272 static final MethodRef ITERATOR_HAS_NEXT = MethodRef.method(Iterator.class, "hasNext", boolean.class);
4273 static final MethodRef ITERATOR_NEXT = MethodRef.method(Iterator.class, "next", Object.class);
4274
4275 @Override
4276 public Block.Builder lower(Block.Builder b, BiFunction<Block.Builder, Op, Block.Builder> inherited) {
4277 JavaType elementType = (JavaType) initBody.entryBlock().parameters().get(0).type();
4278 boolean isArray = exprBody.bodySignature().returnType() instanceof ArrayType;
4279
4280 Block.Builder preHeader = b.block(exprBody.bodySignature().returnType());
4281 Block.Builder header = b.block(isArray ? List.of(INT) : List.of());
4282 Block.Builder init = b.block();
4283 Block.Builder body = b.block();
4284 Block.Builder exit = b.block();
4285
4286 b.transformBody(exprBody, List.of(), loweringTransformer(inherited, (block, op) -> {
4287 if (op instanceof CoreOp.YieldOp yop) {
4288 Value loopSource = block.context().getValue(yop.yieldValue());
4289 block.add(branch(preHeader.reference(loopSource)));
4290 return block;
4291 } else {
4292 return null;
4293 }
4294 }));
4295
4296 if (isArray) {
4297 Value array = preHeader.parameters().get(0);
4298 Value arrayLength = preHeader.add(arrayLength(array));
4299 Value i = preHeader.add(constant(INT, 0));
4300 preHeader.add(branch(header.reference(i)));
4301
4302 i = header.parameters().get(0);
4303 Value p = header.add(lt(i, arrayLength));
4304 header.add(conditionalBranch(p, init.reference(), exit.reference()));
4305
4306 Value e = init.add(arrayLoadOp(array, i));
4307 List<Value> initValues = new ArrayList<>();
4308 init.transformBody(this.initBody, List.of(e), loweringTransformer(inherited, (block, op) -> {
4309 if (op instanceof CoreOp.YieldOp yop) {
4310 initValues.addAll(block.context().getValues(yop.operands()));
4311 block.add(branch(body.reference()));
4312 return block;
4313 } else {
4314 return null;
4315 }
4316 }));
4317
4318 Block.Builder update = b.block();
4319 BranchTarget.setBranchTarget(b.context(), this, exit, update);
4320
4321 body.transformBody(this.loopBody, initValues, loweringTransformer(inherited, (_, _) -> null));
4322
4323 i = update.add(add(i, update.add(constant(INT, 1))));
4324 update.add(branch(header.reference(i)));
4325 } else {
4326 JavaType iterable = parameterized(type(Iterator.class), elementType);
4327 Value iterator = preHeader.add(invoke(iterable, ITERABLE_ITERATOR, preHeader.parameters().get(0)));
4328 preHeader.add(branch(header.reference()));
4329
4330 Value p = header.add(invoke(ITERATOR_HAS_NEXT, iterator));
4331 header.add(conditionalBranch(p, init.reference(), exit.reference()));
4332
4333 Value e = init.add(invoke(elementType, ITERATOR_NEXT, iterator));
4334 List<Value> initValues = new ArrayList<>();
4335 init.transformBody(this.initBody, List.of(e), loweringTransformer(inherited, (block, op) -> {
4336 if (op instanceof CoreOp.YieldOp yop) {
4337 initValues.addAll(block.context().getValues(yop.operands()));
4338 block.add(branch(body.reference()));
4339 return block;
4340 } else {
4341 return null;
4342 }
4343 }));
4344
4345 BranchTarget.setBranchTarget(b.context(), this, exit, header);
4346
4347 body.transformBody(this.loopBody, initValues, loweringTransformer(inherited, (_, _) -> null));
4348 }
4349
4350 return exit;
4351 }
4352
4353 @Override
4354 public CodeType resultType() {
4355 return VOID;
4356 }
4357 }
4358
4359 /**
4360 * The while operation, that can model a Java language while statement.
4361 * <p>
4362 * While operations feature two bodies. The <em>predicate body</em> models the loop condition.
4363 * The <em>loop body</em> models the statements to execute.
4364 * <p>
4365 * The predicate body should accept no arguments and yield a {@link JavaType#BOOLEAN} value.
4366 * The loop body should accept no arguments, and yield {@linkplain JavaType#VOID no value}.
4367 * <p>
4368 * The result type of a while operation is {@link JavaType#VOID}.
4369 *
4370 * @jls 14.12 The while Statement
4371 */
4372 @OpDeclaration(WhileOp.NAME)
4373 public static final class WhileOp extends AbstractOp
4374 implements JavaOp, Op.Loop, Op.Lowerable, JavaStatement {
4375
4376 /**
4377 * Builder for the predicate body of a while operation.
4378 */
4379 public static class PredicateBuilder {
4380 final Body.Builder connectedAncestorBody;
4381
4382 PredicateBuilder(Body.Builder connectedAncestorBody) {
4383 this.connectedAncestorBody = connectedAncestorBody;
4384 }
4385
4386 /**
4387 * Builds the predicate body of a while operation.
4388 *
4389 * @param c a consumer that populates the predicate body
4390 * @return a builder for specifying the loop body
4391 */
4392 public WhileOp.BodyBuilder predicate(Consumer<Block.Builder> c) {
4393 Body.Builder body = Body.Builder.of(connectedAncestorBody, CoreType.functionType(BOOLEAN));
4394 c.accept(body.entryBlock());
4395
4396 return new WhileOp.BodyBuilder(connectedAncestorBody, body);
4397 }
4398 }
4399
4400 /**
4401 * Builder for the loop body of a while operation.
4402 */
4403 public static class BodyBuilder {
4404 final Body.Builder connectedAncestorBody;
4405 private final Body.Builder predicate;
4406
4407 BodyBuilder(Body.Builder connectedAncestorBody, Body.Builder predicate) {
4408 this.connectedAncestorBody = connectedAncestorBody;
4409 this.predicate = predicate;
4410 }
4411
4412 /**
4413 * Completes the while operation by adding the loop body.
4414 *
4415 * @param c a consumer that populates the loop body
4416 * @return the completed while operation
4417 */
4418 public WhileOp body(Consumer<Block.Builder> c) {
4419 Body.Builder body = Body.Builder.of(connectedAncestorBody, CoreType.FUNCTION_TYPE_VOID);
4420 c.accept(body.entryBlock());
4421
4422 return new WhileOp(predicate, body);
4423 }
4424 }
4425
4426 private static final String NAME = "java.while";
4427
4428 private final List<Body> bodies;
4429
4430 WhileOp(ExternalizedOp def) {
4431 List<Body.Builder> bodies = requireBodies(def, 2);
4432 this(bodies.get(0), bodies.get(1));
4433 }
4434
4435 WhileOp(Body.Builder predicate, Body.Builder body) {
4436 super(List.of());
4437 this.bodies = List.of(requireBodySignature(NAME + " predicate", predicate, CoreType.functionType(BOOLEAN)).build(this),
4438 requireVoidBodySignature(NAME + " body", body).build(this));
4439 }
4440
4441 WhileOp(WhileOp that, CodeContext cc, CodeTransformer ct) {
4442 super(that, cc);
4443
4444 this.bodies = that.bodies.stream()
4445 .map(b -> b.transform(cc, ct).build(this)).toList();
4446 }
4447
4448 @Override
4449 public WhileOp transform(CodeContext cc, CodeTransformer ct) {
4450 return new WhileOp(this, cc, ct);
4451 }
4452
4453 @Override
4454 public List<Body> bodies() {
4455 return bodies;
4456 }
4457
4458 /**
4459 * {@return the loop condition body}
4460 */
4461 public Body predicateBody() {
4462 return bodies.get(0);
4463 }
4464
4465 @Override
4466 public Body loopBody() {
4467 return bodies.get(1);
4468 }
4469
4470 @Override
4471 public Block.Builder lower(Block.Builder b, BiFunction<Block.Builder, Op, Block.Builder> inherited) {
4472 Block.Builder header = b.block();
4473 Block.Builder body = b.block();
4474 Block.Builder exit = b.block();
4475
4476 b.add(branch(header.reference()));
4477
4478 ControlFlowBooleanExpressionOp.lowerBooleanBody(header, predicateBody(), List.of(),
4479 new ControlFlowBooleanExpressionOp.ConditionalBranchContinuation(body.reference(), exit.reference()),
4480 inherited);
4481
4482 BranchTarget.setBranchTarget(b.context(), this, exit, header);
4483
4484 body.transformBody(loopBody(), List.of(), loweringTransformer(inherited, (_, _) -> null));
4485
4486 return exit;
4487 }
4488
4489 @Override
4490 public CodeType resultType() {
4491 return VOID;
4492 }
4493 }
4494
4495 /**
4496 * The do-while operation, that can model a Java language do statement.
4497 * <p>
4498 * Do-while operations feature two bodies. The <em>loop body</em> models the statements to execute.
4499 * The <em>predicate body</em> models the loop condition.
4500 * <p>
4501 * The loop body should accept no arguments, and yield {@linkplain JavaType#VOID no value}. The predicate body
4502 * should accept no arguments, and yield a {@link JavaType#BOOLEAN} value.
4503 * <p>
4504 * The result type of a do-while operation is {@link JavaType#VOID}.
4505 *
4506 * @jls 14.13 The do Statement
4507 */
4508 // @@@ Unify JavaDoWhileOp and JavaWhileOp with common abstract superclass
4509 @OpDeclaration(DoWhileOp.NAME)
4510 public static final class DoWhileOp extends AbstractOp
4511 implements JavaOp, Op.Loop, Op.Lowerable, JavaStatement {
4512
4513 /**
4514 * Builder for the predicate body of a do-while operation.
4515 */
4516 public static class PredicateBuilder {
4517 final Body.Builder connectedAncestorBody;
4518 private final Body.Builder body;
4519
4520 PredicateBuilder(Body.Builder connectedAncestorBody, Body.Builder body) {
4521 this.connectedAncestorBody = connectedAncestorBody;
4522 this.body = body;
4523 }
4524
4525 /**
4526 * Completes the do-while operation by adding the predicate body.
4527 *
4528 * @param c a consumer that populates the predicate body
4529 * @return the completed do-while operation
4530 */
4531 public DoWhileOp predicate(Consumer<Block.Builder> c) {
4532 Body.Builder predicate = Body.Builder.of(connectedAncestorBody, CoreType.functionType(BOOLEAN));
4533 c.accept(predicate.entryBlock());
4534 return new DoWhileOp(body, predicate);
4535 }
4536 }
4537
4538 /**
4539 * Builder for the loop body of a do-while operation.
4540 */
4541 public static class BodyBuilder {
4542 final Body.Builder connectedAncestorBody;
4543
4544 BodyBuilder(Body.Builder connectedAncestorBody) {
4545 this.connectedAncestorBody = connectedAncestorBody;
4546 }
4547
4548 /**
4549 * Builds the loop body of a do-while operation.
4550 *
4551 * @param c a consumer that populates the loop body
4552 * @return a builder for specifying the predicate body
4553 */
4554 public DoWhileOp.PredicateBuilder body(Consumer<Block.Builder> c) {
4555 Body.Builder body = Body.Builder.of(connectedAncestorBody, CoreType.FUNCTION_TYPE_VOID);
4556 c.accept(body.entryBlock());
4557
4558 return new DoWhileOp.PredicateBuilder(connectedAncestorBody, body);
4559 }
4560 }
4561
4562 private static final String NAME = "java.do.while";
4563
4564 private final List<Body> bodies;
4565
4566 DoWhileOp(ExternalizedOp def) {
4567 List<Body.Builder> bodies = requireBodies(def, 2);
4568 this(bodies.get(0), bodies.get(1));
4569 }
4570
4571 DoWhileOp(Body.Builder body, Body.Builder predicate) {
4572 super(List.of());
4573
4574 Objects.requireNonNull(body);
4575
4576 this.bodies = List.of(requireVoidBodySignature(NAME + " body", body).build(this),
4577 requireBodySignature(NAME + " predicate", predicate, CoreType.functionType(BOOLEAN)).build(this));
4578 }
4579
4580 DoWhileOp(DoWhileOp that, CodeContext cc, CodeTransformer ct) {
4581 super(that, cc);
4582
4583 this.bodies = that.bodies.stream()
4584 .map(b -> b.transform(cc, ct).build(this)).toList();
4585 }
4586
4587 @Override
4588 public DoWhileOp transform(CodeContext cc, CodeTransformer ct) {
4589 return new DoWhileOp(this, cc, ct);
4590 }
4591
4592 @Override
4593 public List<Body> bodies() {
4594 return bodies;
4595 }
4596
4597 /**
4598 * {@return the predicate body for the do-while operation}
4599 */
4600 public Body predicateBody() {
4601 return bodies.get(1);
4602 }
4603
4604 @Override
4605 public Body loopBody() {
4606 return bodies.get(0);
4607 }
4608
4609 @Override
4610 public Block.Builder lower(Block.Builder b, BiFunction<Block.Builder, Op, Block.Builder> inherited) {
4611 Block.Builder body = b.block();
4612 Block.Builder header = b.block();
4613 Block.Builder exit = b.block();
4614
4615 b.add(branch(body.reference()));
4616
4617 BranchTarget.setBranchTarget(b.context(), this, exit, header);
4618
4619 body.transformBody(loopBody(), List.of(), loweringTransformer(inherited, (_, _) -> null));
4620
4621 ControlFlowBooleanExpressionOp.lowerBooleanBody(header, predicateBody(), List.of(),
4622 new ControlFlowBooleanExpressionOp.ConditionalBranchContinuation(body.reference(), exit.reference()),
4623 inherited);
4624
4625 return exit;
4626 }
4627
4628 @Override
4629 public CodeType resultType() {
4630 return VOID;
4631 }
4632 }
4633
4634 /**
4635 * The conditional operation, that can model Java language conditional-and and conditional-or expressions.
4636 * <p>
4637 * Conditional operations feature two or more predicate bodies, each yielding a {@link JavaType#BOOLEAN} value.
4638 *
4639 * @jls 15.23 Conditional-And Operator {@code &&}
4640 * @jls 15.24 Conditional-Or Operator {@code ||}
4641 */
4642 public sealed static abstract class ConditionalOp extends AbstractOp
4643 implements JavaOp, Op.Nested, ControlFlowBooleanExpressionOp, JavaExpression
4644 permits ConditionalAndOp, ConditionalOrOp {
4645
4646 static final FunctionType BODY_TYPE = CoreType.functionType(BOOLEAN);
4647
4648 // 2 or more bodies
4649 // See use for modeling multi-label cases of switch statements/expressions
4650 final List<Body> bodies;
4651
4652 ConditionalOp(ConditionalOp that, CodeContext cc, CodeTransformer ct) {
4653 super(that, cc);
4654
4655 this.bodies = that.bodies.stream().map(b -> b.transform(cc, ct).build(this)).toList();
4656 }
4657
4658 ConditionalOp(List<Body.Builder> bodyCs) {
4659 super(List.of());
4660
4661 this.bodies = bodyCs.stream().map(bc -> bc.build(this)).toList();
4662 }
4663
4664 @Override
4665 public List<Body> bodies() {
4666 return bodies;
4667 }
4668
4669 @Override
4670 public CodeType resultType() {
4671 return BOOLEAN;
4672 }
4673
4674 @Override
4675 public Block.Builder lower(Block.Builder lhs, BiFunction<Block.Builder, Op, Block.Builder> inherited) {
4676 // Poll for implicit boolean continuation parameter
4677 BooleanResultContinuation continuation = BOOLEAN_CONTINUATION_ARG.poll(lhs.context());
4678 Block.Builder exit = lhs;
4679 if (continuation == null) {
4680 exit = lhs.block();
4681 lhs.context().mapValue(result(), exit.parameter(resultType()));
4682 continuation = new BranchWithArgumentContinuation(exit);
4683 }
4684 lowerTo(lhs, inherited, continuation);
4685 return exit;
4686 }
4687
4688 void lowerTo(Block.Builder lhs, BiFunction<Block.Builder, Op, Block.Builder> inherited,
4689 BooleanResultContinuation continuation) {
4690 boolean isAnd = this instanceof ConditionalAndOp;
4691 Block.Reference shortCircuitRef = continuation.referenceFor(lhs, !isAnd);
4692
4693 // Lower all but the last body
4694 for (int i = 0; i < bodies().size() - 1; i++) {
4695 Block.Builder rhs = lhs.block();
4696
4697 ConditionalBranchContinuation bodyContinuation = isAnd
4698 ? new ConditionalBranchContinuation(rhs.reference(), shortCircuitRef)
4699 : new ConditionalBranchContinuation(shortCircuitRef, rhs.reference());
4700
4701 ControlFlowBooleanExpressionOp.lowerBooleanBody(lhs, bodies().get(i), List.of(), bodyContinuation, inherited);
4702
4703 lhs = rhs;
4704 }
4705
4706 // Lower the last body
4707 ControlFlowBooleanExpressionOp.lowerBooleanBody(lhs, bodies().getLast(),List.of(), continuation, inherited);
4708 }
4709 }
4710
4711 /**
4712 * The conditional-and operation, that can model Java language conditional-and expressions.
4713 *
4714 * @jls 15.23 Conditional-And Operator {@code &&}
4715 */
4716 @OpDeclaration(ConditionalAndOp.NAME)
4717 public static final class ConditionalAndOp extends ConditionalOp {
4718
4719 /**
4720 * Builder for conditional-and operations.
4721 */
4722 public static class Builder {
4723 final Body.Builder connectedAncestorBody;
4724 final List<Body.Builder> bodies;
4725
4726 Builder(Body.Builder connectedAncestorBody, Consumer<Block.Builder> lhs, Consumer<Block.Builder> rhs) {
4727 this.connectedAncestorBody = connectedAncestorBody;
4728 this.bodies = new ArrayList<>();
4729 and(lhs);
4730 and(rhs);
4731 }
4732
4733 /**
4734 * Adds a predicate body to this conditional-and operation.
4735 *
4736 * @param c a consumer that populates the predicate body
4737 * @return this builder
4738 */
4739 public Builder and(Consumer<Block.Builder> c) {
4740 Body.Builder body = Body.Builder.of(connectedAncestorBody, CoreType.functionType(BOOLEAN));
4741 c.accept(body.entryBlock());
4742 bodies.add(body);
4743
4744 return this;
4745 }
4746
4747 /**
4748 * {@return the completed conditional-and operation}
4749 */
4750 public ConditionalAndOp build() {
4751 return new ConditionalAndOp(bodies);
4752 }
4753 }
4754
4755 static final String NAME = "java.cand";
4756
4757 ConditionalAndOp(ExternalizedOp def) {
4758 this(def.bodyDefinitions());
4759 }
4760
4761 ConditionalAndOp(ConditionalAndOp that, CodeContext cc, CodeTransformer ct) {
4762 super(that, cc, ct);
4763 }
4764
4765 @Override
4766 public ConditionalAndOp transform(CodeContext cc, CodeTransformer ct) {
4767 return new ConditionalAndOp(this, cc, ct);
4768 }
4769
4770 ConditionalAndOp(List<Body.Builder> bodyCs) {
4771 bodyCs.forEach(b -> requireBodySignature(NAME, b, BODY_TYPE));
4772 super(requireMinBodies(NAME, bodyCs, 2));
4773 }
4774 }
4775
4776 /**
4777 * The conditional-or operation, that can model Java language conditional-or expressions.
4778 *
4779 * @jls 15.24 Conditional-Or Operator {@code ||}
4780 */
4781 @OpDeclaration(ConditionalOrOp.NAME)
4782 public static final class ConditionalOrOp extends ConditionalOp {
4783
4784 /**
4785 * Builder for conditional-or operations.
4786 */
4787 public static class Builder {
4788 final Body.Builder connectedAncestorBody;
4789 final List<Body.Builder> bodies;
4790
4791 Builder(Body.Builder connectedAncestorBody, Consumer<Block.Builder> lhs, Consumer<Block.Builder> rhs) {
4792 this.connectedAncestorBody = connectedAncestorBody;
4793 this.bodies = new ArrayList<>();
4794 or(lhs);
4795 or(rhs);
4796 }
4797
4798 /**
4799 * Adds a predicate body to this conditional-or operation.
4800 *
4801 * @param c a consumer that populates the predicate body
4802 * @return this builder
4803 */
4804 public Builder or(Consumer<Block.Builder> c) {
4805 Body.Builder body = Body.Builder.of(connectedAncestorBody, CoreType.functionType(BOOLEAN));
4806 c.accept(body.entryBlock());
4807 bodies.add(body);
4808
4809 return this;
4810 }
4811
4812 /**
4813 * {@return the completed conditional-or operation}
4814 */
4815 public ConditionalOrOp build() {
4816 return new ConditionalOrOp(bodies);
4817 }
4818 }
4819
4820 static final String NAME = "java.cor";
4821
4822 ConditionalOrOp(ExternalizedOp def) {
4823 this(def.bodyDefinitions());
4824 }
4825
4826 ConditionalOrOp(ConditionalOrOp that, CodeContext cc, CodeTransformer ct) {
4827 super(that, cc, ct);
4828 }
4829
4830 @Override
4831 public ConditionalOrOp transform(CodeContext cc, CodeTransformer ct) {
4832 return new ConditionalOrOp(this, cc, ct);
4833 }
4834
4835 ConditionalOrOp(List<Body.Builder> bodyCs) {
4836 bodyCs.forEach(b -> requireBodySignature(NAME, b, BODY_TYPE));
4837 super(requireMinBodies(NAME, bodyCs, 2));
4838 }
4839 }
4840
4841 /**
4842 * The conditional operation, that can model Java language conditional operator {@code ?} expressions.
4843 * <p>
4844 * Conditional expression operations feature three bodies: the predicate body, the true body, and the false body.
4845 * <p>
4846 * The predicate body accepts no arguments and yields a {@link JavaType#BOOLEAN} value.
4847 * The true and false bodies accepts no arguments and yield a value.
4848 *
4849 * @jls 15.25 Conditional Operator {@code ? :}
4850 */
4851 @OpDeclaration(ConditionalExpressionOp.NAME)
4852 public static final class ConditionalExpressionOp extends AbstractOp
4853 implements JavaOp, Op.Nested, ControlFlowBooleanExpressionOp, JavaExpression {
4854
4855 static final String NAME = "java.cexpression";
4856
4857 final CodeType resultType;
4858 // {cond, truepart, falsepart}
4859 final List<Body> bodies;
4860
4861 ConditionalExpressionOp(ExternalizedOp def) {
4862 List<Body.Builder> bodies = requireBodies(def, 3);
4863 this(def.resultType(), bodies.get(0), bodies.get(1), bodies.get(2));
4864 }
4865
4866 ConditionalExpressionOp(ConditionalExpressionOp that, CodeContext cc, CodeTransformer ct) {
4867 super(that, cc);
4868
4869 // Copy body
4870 this.bodies = that.bodies.stream()
4871 .map(b -> b.transform(cc, ct).build(this)).toList();
4872 this.resultType = that.resultType;
4873 }
4874
4875 @Override
4876 public ConditionalExpressionOp transform(CodeContext cc, CodeTransformer ct) {
4877 return new ConditionalExpressionOp(this, cc, ct);
4878 }
4879
4880 ConditionalExpressionOp(CodeType expressionType, Body.Builder predicateBody, Body.Builder trueBody, Body.Builder falseBody) {
4881 super(List.of());
4882
4883 this.bodies = List.of(requireBodySignature(NAME + " predicate", predicateBody, CoreType.functionType(BOOLEAN)).build(this),
4884 requireNoParameters(NAME + " true body", trueBody).build(this),
4885 requireNoParameters(NAME + " false body", falseBody).build(this));
4886 // @@@ when expressionType is null, we assume truepart and falsepart have the same yieldType
4887 this.resultType = expressionType == null ? bodies.get(1).yieldType() : expressionType;
4888 }
4889
4890 @Override
4891 public List<Body> bodies() {
4892 return bodies;
4893 }
4894
4895 /**
4896 * {@return the predicate body}
4897 */
4898 public Body predicateBody() {
4899 return bodies.get(0);
4900 }
4901
4902 /**
4903 * {@return the true body}
4904 */
4905 public Body trueBody() {
4906 return bodies.get(1);
4907 }
4908
4909 /**
4910 * {@return the false body}
4911 */
4912 public Body falseBody() {
4913 return bodies.get(2);
4914 }
4915
4916 @Override
4917 public Block.Builder lower(Block.Builder b, BiFunction<Block.Builder, Op, Block.Builder> inherited) {
4918 boolean isBooleanExpression = resultType().equals(BOOLEAN);
4919 // Poll for implicit boolean continuation parameter
4920 BooleanResultContinuation continuation = isBooleanExpression
4921 ? BOOLEAN_CONTINUATION_ARG.poll(b.context())
4922 : null;
4923
4924 // Lower predicate body
4925 Block.Builder trueBlock = b.block();
4926 Block.Builder falseBlock = b.block();
4927 ControlFlowBooleanExpressionOp.lowerBooleanBody(b, predicateBody(), List.of(),
4928 new ConditionalBranchContinuation(trueBlock.reference(), falseBlock.reference()),
4929 inherited);
4930
4931 // Lower true/false bodies depending on if a boolean expression or a value expression
4932 if (isBooleanExpression) {
4933 Block.Builder exit;
4934 if (continuation == null) {
4935 exit = b.block();
4936 b.context().mapValue(result(), exit.parameter(resultType()));
4937 continuation = new BranchWithArgumentContinuation(exit);
4938 } else {
4939 exit = b;
4940 }
4941
4942 ControlFlowBooleanExpressionOp.lowerBooleanBody(trueBlock, trueBody(), List.of(), continuation, inherited);
4943 ControlFlowBooleanExpressionOp.lowerBooleanBody(falseBlock, falseBody(), List.of(), continuation, inherited);
4944 return exit;
4945 } else {
4946 Block.Builder exit = b.block();
4947 b.context().mapValue(result(), exit.parameter(resultType()));
4948
4949 BranchTarget.setBranchTarget(b.context(), this, exit, null);
4950
4951 CodeTransformer exitTransformer = loweringTransformer(inherited, (block, op) -> {
4952 if (op instanceof CoreOp.YieldOp yop) {
4953 block.add(branch(exit.reference(block.context().getValue(yop.yieldValue()))));
4954 return block;
4955 } else {
4956 return null;
4957 }
4958 });
4959 trueBlock.transformBody(trueBody(), List.of(), exitTransformer);
4960 falseBlock.transformBody(falseBody(), List.of(), exitTransformer);
4961 return exit;
4962 }
4963 }
4964
4965 @Override
4966 public CodeType resultType() {
4967 return resultType;
4968 }
4969 }
4970
4971 /**
4972 * The try operation, that can model Java language try statements.
4973 * <p>
4974 * Try operations feature a <em>try body</em>, zero or more <em>catch bodies</em>, and an optional
4975 * <em>finally body</em>. Try operations may also feature zero or more <em>resources bodies</em>, modeling a
4976 * try-with-resources statement.
4977 * <p>
4978 * Each resource body yields a value. The first resource body accepts no arguments. A second resource body accepts
4979 * an argument whose type is the same as the yield type of the first resource body. A subsequent resource accepts,
4980 * in order, arguments whose types are the same as all the prior resource body yield types.
4981 * <p>
4982 * The try body yields {@linkplain JavaType#VOID no value}. If one or more resources bodies are present then
4983 * the try body accepts, in order, arguments whose types are the same as the resource bodies yield types.
4984 * <p>
4985 * Each catch body should accept an exception value and yield {@linkplain JavaType#VOID no value}. The
4986 * finally body, if present, should accept no arguments and yield {@linkplain JavaType#VOID no value}.
4987 * <p>
4988 * The result type of a try operation is {@link JavaType#VOID}.
4989 *
4990 * @jls 14.20 The try statement
4991 * @jls 14.20.3 try-with-resources
4992 */
4993 @OpDeclaration(TryOp.NAME)
4994 public static final class TryOp extends AbstractOp
4995 implements JavaOp, Op.Nested, Op.Lowerable, JavaStatement {
4996
4997 // Represents a source targeting operation in a staged model, where the source targeting operation is not in
4998 // the staged model.
4999 // A staged model is a synthetic function operation that contains a normalized try operation extracted from a
5000 // source model.
5001 // The translation that produces the staged model translates a source targeting operation to a staged targeting
5002 // operation when the source targeting operation attempts to exit the extracted try operation. Therefore, a
5003 // staged targeting operation attempts to exit all of its ancestor operations.
5004 // The lowering of a staged targeting operation behaves almost identically to the lowering of its source,
5005 // except that where necessary the staged operation is unstaged to an equivalent source operation and the source
5006 // target is used to obtain branch targets.
5007 private static abstract sealed class AbstractStagedTargetingOp<T extends Op & TargetingOp> extends Terminating
5008 implements JavaOp, Lowerable, TargetingOp
5009 permits StagedReturnOp, StagedYieldOp, StagedStatementTargetingOp {
5010 // The source targeting operation in the source model
5011 // ReturnOp | YieldOp | ContinueOp | BreakOp
5012 final T source;
5013
5014 AbstractStagedTargetingOp(T source, List<Value> operands) {
5015 super(operands);
5016
5017 assert source instanceof ReturnOp || source instanceof YieldOp || source instanceof StatementTargetingOp;
5018 this.source = source;
5019 }
5020
5021 AbstractStagedTargetingOp(AbstractStagedTargetingOp<T> that, CodeContext cc) {
5022 super(that, cc);
5023
5024 this.source = that.source;
5025 }
5026
5027 @Override
5028 public final Op target() {
5029 return source.target();
5030 }
5031
5032 @Override
5033 public final boolean targetsOrAttemptsToExit(Op op) {
5034 // If the given operation is an ancestor of this staged targeting operation, then the staged targeting
5035 // operation attempts to exit the given operation
5036 // Otherwise, the given operation is in the source model, so test the given operation against the
5037 // source. This can occur for an ancestor try operation that is not normalized, or an ancestor
5038 // synchronized operation. Specifically, when lowering such an operation all descendant targeting
5039 // operations that attempt to exit the operation need to be processed. Some of those descendant
5040 // targeting operations may be staged.
5041 return op.isAncestorOf(this) || source.targetsOrAttemptsToExit(op);
5042 }
5043
5044 @Override
5045 public final CodeType resultType() {
5046 return VOID;
5047 }
5048 }
5049
5050 @OpDeclaration("staged.return")
5051 private static final class StagedReturnOp extends AbstractStagedTargetingOp<ReturnOp> {
5052 StagedReturnOp(ReturnOp delegate, Value returnValue) {
5053 super(delegate, returnValue == null ? List.of() : List.of(returnValue));
5054 }
5055
5056 StagedReturnOp(StagedReturnOp that, CodeContext cc) {
5057 super(that, cc);
5058 }
5059
5060 @Override
5061 public StagedReturnOp transform(CodeContext cc, CodeTransformer ct) {
5062 return new StagedReturnOp(this, cc);
5063 }
5064
5065 @Override
5066 public Block.Builder lower(Block.Builder b, BiFunction<Block.Builder, Op, Block.Builder> inherited) {
5067 if (operands().isEmpty()) {
5068 b.add(CoreOp.return_());
5069 } else {
5070 b.add(CoreOp.return_(b.context().getValue(operands().getFirst())));
5071 }
5072 return b;
5073 }
5074 }
5075
5076 @OpDeclaration("staged.java.yield")
5077 private static final class StagedYieldOp extends AbstractStagedTargetingOp<YieldOp> {
5078 StagedYieldOp(YieldOp delegate, Value operand) {
5079 super(delegate, List.of(Objects.requireNonNull(operand)));
5080 }
5081
5082 StagedYieldOp(StagedYieldOp that, CodeContext cc) {
5083 super(that, cc);
5084 }
5085
5086 @Override
5087 public StagedYieldOp transform(CodeContext cc, CodeTransformer ct) {
5088 return new StagedYieldOp(this, cc);
5089 }
5090
5091 @Override
5092 public Block.Builder lower(Block.Builder b, BiFunction<Block.Builder, Op, Block.Builder> inherited) {
5093 // for now, we will use breakBlock field to indicate java.yield target block
5094 return lower(b, BranchTarget::breakBlock);
5095 }
5096
5097 Block.Builder lower(Block.Builder b, Function<BranchTarget, Block.Builder> f) {
5098 Op opt = target();
5099 BranchTarget t = BranchTarget.getBranchTarget(b.context(), opt);
5100 if (t != null) {
5101 b.add(branch(f.apply(t).reference(b.context().getValue(operands().getFirst()))));
5102 } else {
5103 throw new IllegalStateException("No branch target for operation: " + opt);
5104 }
5105 return b;
5106 }
5107 }
5108
5109 @OpDeclaration("staged.java.statement")
5110 private static final class StagedStatementTargetingOp extends AbstractStagedTargetingOp<StatementTargetingOp> {
5111 StagedStatementTargetingOp(StatementTargetingOp delegate) {
5112 super(delegate, List.of());
5113 }
5114
5115 StagedStatementTargetingOp(StagedStatementTargetingOp that, CodeContext cc) {
5116 super(that, cc);
5117 }
5118
5119 @Override
5120 public StagedStatementTargetingOp transform(CodeContext cc, CodeTransformer ct) {
5121 return new StagedStatementTargetingOp(this, cc);
5122 }
5123
5124 @Override
5125 public Block.Builder lower(Block.Builder b, BiFunction<Block.Builder, Op, Block.Builder> inherited) {
5126 return source.lower(b, inherited);
5127 }
5128 }
5129
5130 /**
5131 * Builder for the resource bodies and the try body of a try operation.
5132 */
5133 public static final class BodyBuilder {
5134 final Body.Builder connectedAncestorBody;
5135 final List<Body.Builder> resources;
5136
5137 BodyBuilder(Body.Builder connectedAncestorBody) {
5138 this.connectedAncestorBody = connectedAncestorBody;
5139 this.resources = new ArrayList<>();
5140 }
5141
5142 /**
5143 * Adds a resource body to a try-with-resources operation.
5144 *
5145 * @param yieldType the resource type for a resource expression, or the Var type for a resource declaration
5146 * @param c a consumer that populates the resource body
5147 * @return this builder
5148 */
5149 public BodyBuilder resource(CodeType yieldType, Consumer<Block.Builder> c) {
5150 List<CodeType> paramTypes = resources.stream().map(r -> r.bodySignature().returnType()).toList();
5151 Body.Builder resource = Body.Builder.of(connectedAncestorBody,
5152 CoreType.functionType(yieldType, paramTypes));
5153 c.accept(resource.entryBlock());
5154 resources.add(resource);
5155 return this;
5156 }
5157
5158 /**
5159 * Builds the try body of the try operation.
5160 *
5161 * @param c a consumer that populates the try body
5162 * @return a builder for specifying catch bodies and an optional finalizer
5163 */
5164 public CatchBuilder body(Consumer<Block.Builder> c) {
5165 Body.Builder body = Body.Builder.of(connectedAncestorBody,
5166 CoreType.functionType(VOID, resources.stream().map(bb -> bb.bodySignature().returnType()).toList()));
5167 c.accept(body.entryBlock());
5168
5169 return new CatchBuilder(connectedAncestorBody, resources, body);
5170 }
5171 }
5172
5173 /**
5174 * Builder for specifying catch bodies and an optional finalizer body of a try operation.
5175 */
5176 public static final class CatchBuilder {
5177 final Body.Builder connectedAncestorBody;
5178 final List<Body.Builder> resources;
5179 final Body.Builder body;
5180 final List<CodeType> catchTypes;
5181 final List<Body.Builder> handlers;
5182
5183 CatchBuilder(Body.Builder connectedAncestorBody, List<Body.Builder> resources, Body.Builder body) {
5184 this.connectedAncestorBody = connectedAncestorBody;
5185 this.resources = resources;
5186 this.body = body;
5187 this.catchTypes = new ArrayList<>();
5188 this.handlers = new ArrayList<>();
5189 }
5190
5191 /**
5192 * Adds a catch body for handling exceptions of a specific type.
5193 *
5194 * @param handlerExceptionType the type of exception handled
5195 * @param c a consumer that populates the catch body
5196 * @return this builder
5197 */
5198 public CatchBuilder catch_(CodeType handlerExceptionType, Consumer<Block.Builder> c) {
5199 return catch_(handlerExceptionType, handlerExceptionType, c);
5200 }
5201
5202 /**
5203 * Adds a catch body for handling exceptions of a specific catch type and a handler type.
5204 *
5205 * @param catchType the type of exception(s) caught, use {@link TupleType} for a multi-catch
5206 * @param handlerExceptionType the type of exception handled by the catch body
5207 * @param c a consumer that populates the catch body
5208 * @return this builder
5209 */
5210 public CatchBuilder catch_(CodeType catchType, CodeType handlerExceptionType, Consumer<Block.Builder> c) {
5211 Body.Builder _catch = Body.Builder.of(connectedAncestorBody,
5212 CoreType.functionType(VOID, handlerExceptionType));
5213 c.accept(_catch.entryBlock());
5214 handlers.add(_catch);
5215 catchTypes.add(catchType);
5216 return this;
5217 }
5218
5219 /**
5220 * Completes the try operation by adding the finalizer body.
5221 *
5222 * @param c a consumer that populates the finalizer body
5223 * @return the completed try operation
5224 */
5225 public TryOp finally_(Consumer<Block.Builder> c) {
5226 Body.Builder _finally = Body.Builder.of(connectedAncestorBody, CoreType.FUNCTION_TYPE_VOID);
5227 c.accept(_finally.entryBlock());
5228
5229 return new TryOp(resources, body, catchTypes, handlers, _finally);
5230 }
5231
5232 /**
5233 * Completes the try operation without a finalizer body.
5234 *
5235 * @return the completed try operation
5236 */
5237 public TryOp noFinalizer() {
5238 return new TryOp(resources, body, catchTypes, handlers, null);
5239 }
5240 }
5241
5242 static final String NAME = "java.try";
5243 static final String ATTRIBUTE_CATCH_TYPES = NAME + ".catchTypes";
5244 static final MethodRef AUTO_CLOSEABLE_CLOSE_METHOD = MethodRef.method(AutoCloseable.class, "close", void.class);
5245 static final MethodRef THROWABLE_ADD_SUPPRESSED_METHOD = MethodRef.method(Throwable.class, "addSuppressed", void.class, Throwable.class);
5246
5247 final List<Body> resourcesBodies;
5248 final Body body;
5249 final List<CodeType> explicitCatchTypes;
5250 final List<Body> handlers;
5251 final Body finallyBody;
5252
5253 TryOp(ExternalizedOp def) {
5254 List<Body.Builder> bodies = def.bodyDefinitions();
5255 if (bodies.size() < 1) {
5256 throw structuralException(def.name(), "requires at least 1 body");
5257 }
5258 int bodyIndex = 0;
5259 while (bodyIndex < bodies.size() && !bodies.get(bodyIndex).bodySignature().returnType().equals(VOID)) {
5260 bodyIndex++;
5261 }
5262 if (bodyIndex == bodies.size()) {
5263 throw structuralException(def.name(), "no void try body found");
5264 }
5265 List<Body.Builder> resources = bodies.subList(0, bodyIndex);
5266 Body.Builder body = bodies.get(bodyIndex);
5267 Body.Builder last = bodies.getLast();
5268 Body.Builder finalizer;
5269 if (last != body && last.bodySignature().parameterTypes().isEmpty()) {
5270 finalizer = last;
5271 } else {
5272 finalizer = null;
5273 }
5274 List<CodeType> catchTypes = optionalAttribute(def, ATTRIBUTE_CATCH_TYPES, true, TupleType.class)
5275 .map(TupleType::componentTypes).orElse(null);
5276 List<Body.Builder> handlers = bodies.subList(
5277 bodyIndex + 1,
5278 bodies.size() - (finalizer == null ? 0 : 1));
5279
5280 this(resources, body, catchTypes, handlers, finalizer);
5281 }
5282
5283 TryOp(TryOp that, CodeContext cc, CodeTransformer ct) {
5284 super(that, cc);
5285
5286 this.resourcesBodies = that.resourcesBodies.stream()
5287 .map(b -> b.transform(cc, ct).build(this))
5288 .toList();
5289 this.body = that.body.transform(cc, ct).build(this);
5290 this.explicitCatchTypes = that.explicitCatchTypes;
5291 this.handlers = that.handlers.stream()
5292 .map(b -> b.transform(cc, ct).build(this))
5293 .toList();
5294 if (that.finallyBody != null) {
5295 this.finallyBody = that.finallyBody.transform(cc, ct).build(this);
5296 } else {
5297 this.finallyBody = null;
5298 }
5299 }
5300
5301 @Override
5302 public TryOp transform(CodeContext cc, CodeTransformer ct) {
5303 return new TryOp(this, cc, ct);
5304 }
5305
5306 TryOp(List<Body.Builder> resourcesC,
5307 Body.Builder bodyC,
5308 List<CodeType> catchTypes,
5309 List<Body.Builder> handlersC,
5310 Body.Builder finalizerC) {
5311 super(List.of());
5312
5313 List<CodeType> resourceTypes = new ArrayList<>();
5314 for (Body.Builder _resource : resourcesC) {
5315 requireNonVoidReturnType(NAME + " resource", _resource, resourceTypes.size());
5316 if (!_resource.bodySignature().parameterTypes().equals(resourceTypes)) {
5317 throw structuralException(NAME, "resource #%d requires %s parameter types, found %s"
5318 .formatted(resourceTypes.size(), resourceTypes, _resource.bodySignature().parameterTypes()));
5319 }
5320 resourceTypes.add(_resource.bodySignature().returnType());
5321 }
5322 this.resourcesBodies = resourcesC.stream().map(r -> r.build(this)).toList();
5323 this.body = requireBodySignature(NAME + " try",
5324 bodyC, CoreType.functionType(VOID, resourceTypes)).build(this);
5325 this.explicitCatchTypes = catchTypes == null ? null : List.copyOf(catchTypes);
5326 this.handlers = handlersC.stream().map(
5327 c -> requireVoidReturnType(NAME + " catch", c, 1).build(this)).toList();
5328 if (explicitCatchTypes != null && explicitCatchTypes.size() != handlers.size()) {
5329 throw structuralException(NAME, "catch types %s require %d catch bodies, found %d"
5330 .formatted(explicitCatchTypes, explicitCatchTypes.size(), handlers.size()));
5331 }
5332 if (finalizerC != null) {
5333 this.finallyBody = requireVoidBodySignature(NAME + " finalizer", finalizerC).build(this);
5334 } else {
5335 this.finallyBody = null;
5336 }
5337 }
5338
5339 @Override
5340 public Map<String, Object> externalize() {
5341 // avoid storing explicit catch types if they all match the handlers
5342 return explicitCatchTypes == null || explicitCatchTypes.equals(implicitCatchTypes())
5343 ? Map.of()
5344 : Map.of("", CoreType.tupleType(explicitCatchTypes));
5345 }
5346
5347 @Override
5348 public List<Body> bodies() {
5349 ArrayList<Body> bodies = new ArrayList<>();
5350 bodies.addAll(resourcesBodies);
5351 bodies.add(body);
5352 bodies.addAll(handlers);
5353 if (finallyBody != null) {
5354 bodies.add(finallyBody);
5355 }
5356 return bodies;
5357 }
5358
5359 /**
5360 * {@return the resources bodies}
5361 */
5362 public List<Body> resourceBodies() {
5363 return resourcesBodies;
5364 }
5365
5366 /**
5367 * {@return the body of the try operation}
5368 */
5369 public Body body() {
5370 return body;
5371 }
5372
5373 /**
5374 * {@return the catch types}
5375 */
5376 public List<CodeType> catchTypes() {
5377 return explicitCatchTypes == null ? implicitCatchTypes() : explicitCatchTypes;
5378 }
5379
5380 private List<CodeType> implicitCatchTypes() {
5381 return handlers.stream().map(h -> h.entryBlock().parameterTypes().getFirst()).toList();
5382 }
5383
5384 /**
5385 * {@return the catch bodies}
5386 */
5387 public List<Body> catchBodies() {
5388 return handlers;
5389 }
5390
5391 /**
5392 * {@return the finally body, or {@code null} if this try operation has no finally body}
5393 */
5394 public Body finallyBody() {
5395 return finallyBody;
5396 }
5397
5398 @Override
5399 public Block.Builder lower(Block.Builder b, final BiFunction<Block.Builder, Op, Block.Builder> inherited) {
5400 Block.Builder exit = b.block();
5401 BranchTarget.setBranchTarget(b.context(), this, exit, null);
5402
5403 if (!resourcesBodies.isEmpty()) {
5404 List<Value> captures = normalizationCaptures();
5405 Op normalized = normalize(captures);
5406 CodeContext ctx = CodeContext.create(b.context());
5407 ctx.mapValues(normalized.ancestorBody().entryBlock().parameters(), b.context().getValues(captures));
5408 CodeTransformer lowering = loweringTransformer(inherited, (_, _) -> null);
5409 // acceptOp invokes TryOp.lower, but only with normalized try ops so it should never enter here again
5410 lowering.acceptOp(b.withContextAndTransformer(ctx, lowering), normalized)
5411 .add(branch(exit.reference()));
5412 return exit;
5413 }
5414
5415 // Simple case with no catch and finally bodies
5416 if (handlers.isEmpty() && finallyBody == null) {
5417 b.transformBody(body, List.of(), loweringTransformer(inherited, (block, op) -> {
5418 if (op instanceof CoreOp.YieldOp) {
5419 block.add(branch(exit.reference()));
5420 return block;
5421 } else {
5422 return null;
5423 }
5424 }));
5425 return exit;
5426 }
5427
5428 Block.Builder tryRegionEnter = b.block();
5429 Block.Builder tryRegionExit = b.block();
5430
5431 // Construct the catcher block builders
5432 List<Block.Builder> catchers = catchBodies().stream()
5433 .map(catcher -> b.block())
5434 .toList();
5435 List<Block.Reference> exitHandlers = new ArrayList<>();
5436 for (int i = 0; i < catchers.size(); i++) {
5437 Value arg = b.add(constant(catchBodies().get(i).bodySignature().parameterTypes().getFirst(), null));
5438 exitHandlers.add(catchers.get(i).reference(arg));
5439 }
5440 List<CodeType> catchTypes = catchTypes();
5441 Block.Builder catcherFinally;
5442 Op.Result nullThrowable;
5443 if (finallyBody == null) {
5444 catcherFinally = null;
5445 nullThrowable = null;
5446 } else {
5447 catcherFinally = b.block();
5448 catchers = new ArrayList<>(catchers);
5449 catchers.add(catcherFinally);
5450 nullThrowable = b.add(constant(type(Throwable.class), null));
5451 exitHandlers.add(catcherFinally.reference(nullThrowable));
5452 catchTypes = new ArrayList<>(catchTypes);
5453 catchTypes.add(VOID);
5454 }
5455
5456 // Enter the try exception region
5457 Op.Result enter = b.add(exceptionRegionEnter(
5458 catchTypes.reversed(), tryRegionEnter.reference(), exitHandlers.reversed()));
5459
5460 BiFunction<Block.Builder, Op, Block.Builder> tryExitTransformer;
5461 if (finallyBody != null) {
5462 tryExitTransformer = composeFirst(inherited, (block, op) -> {
5463 if (op instanceof TargetingOp top && top.targetsOrAttemptsToExit(this)) {
5464 return inlineFinalizer(block, enter, inherited);
5465 } else {
5466 return block;
5467 }
5468 });
5469 } else {
5470 tryExitTransformer = composeFirst(inherited, (block, op) -> {
5471 if (op instanceof TargetingOp top && top.targetsOrAttemptsToExit(this)) {
5472 Block.Builder tryRegionReturnExit = block.block();
5473 block.add(exceptionRegionExit(enter, tryRegionReturnExit.reference()));
5474 return tryRegionReturnExit;
5475 } else {
5476 return block;
5477 }
5478 });
5479 }
5480 // Inline the try body
5481 AtomicBoolean hasTryRegionExit = new AtomicBoolean();
5482 tryRegionEnter.transformBody(body, List.of(), loweringTransformer(tryExitTransformer, (block, op) -> {
5483 if (op instanceof CoreOp.YieldOp) {
5484 hasTryRegionExit.set(true);
5485 block.add(branch(tryRegionExit.reference()));
5486 return block;
5487 } else {
5488 return null;
5489 }
5490 }));
5491
5492 Block.Builder finallyEnter = null;
5493 if (finallyBody != null) {
5494 finallyEnter = b.block();
5495 if (hasTryRegionExit.get()) {
5496 // Exit the try exception region
5497 tryRegionExit.add(exceptionRegionExit(enter, finallyEnter.reference()));
5498 }
5499 } else if (hasTryRegionExit.get()) {
5500 // Exit the try exception region
5501 tryRegionExit.add(exceptionRegionExit(enter, exit.reference()));
5502 }
5503
5504 // Inline the catch bodies
5505 for (int i = 0; i < this.handlers.size(); i++) {
5506 Block.Builder catcher = catchers.get(i);
5507 Body catcherBody = this.handlers.get(i);
5508 // Create the throwable argument
5509 Block.Parameter t = catcher.parameter(catcherBody.bodySignature().parameterTypes().get(0));
5510
5511 if (finallyBody != null) {
5512 Block.Builder catchRegionEnter = b.block();
5513 Block.Builder catchRegionExit = b.block();
5514
5515 // Enter the catch exception region
5516 Result catchExceptionRegion = catcher.add(
5517 exceptionRegionEnter(catchRegionEnter.reference(),
5518 catcherFinally.reference(nullThrowable)));
5519
5520 BiFunction<Block.Builder, Op, Block.Builder> catchExitTransformer = composeFirst(inherited, (block, op) -> {
5521 if (op instanceof TargetingOp top && top.targetsOrAttemptsToExit(this)) {
5522 return inlineFinalizer(block, catchExceptionRegion, inherited);
5523 } else {
5524 return block;
5525 }
5526 });
5527
5528 // Inline the catch body
5529 AtomicBoolean hasCatchRegionExit = new AtomicBoolean();
5530 catchRegionEnter.transformBody(catcherBody, List.of(t), loweringTransformer(catchExitTransformer, (block, op) -> {
5531 if (op instanceof CoreOp.YieldOp) {
5532 hasCatchRegionExit.set(true);
5533 block.add(branch(catchRegionExit.reference()));
5534 return block;
5535 } else {
5536 return null;
5537 }
5538 }));
5539
5540 // Exit the catch exception region
5541 if (hasCatchRegionExit.get()) {
5542 hasTryRegionExit.set(true);
5543 catchRegionExit.add(exceptionRegionExit(catchExceptionRegion, finallyEnter.reference()));
5544 }
5545 } else {
5546 // Inline the catch body for normal completion
5547 catcher.transformBody(catcherBody, List.of(t), loweringTransformer(inherited, (block, op) -> {
5548 if (op instanceof CoreOp.YieldOp) {
5549 block.add(branch(exit.reference()));
5550 return block;
5551 } else {
5552 return null;
5553 }
5554 }));
5555 }
5556 }
5557
5558 // Inline the finally body as a catcher of Throwable and adjusting to throw
5559 if (finallyBody != null && hasTryRegionExit.get()) {
5560 // Inline the finally body for exceptional completion and rethrow
5561 finallyEnter.transformBody(finallyBody, List.of(), loweringTransformer(inherited, (block, op) -> {
5562 if (op instanceof CoreOp.YieldOp) {
5563 block.add(branch(exit.reference()));
5564 return block;
5565 } else {
5566 return null;
5567 }
5568 }));
5569 }
5570
5571 if (finallyBody != null) {
5572 // Inline the finally body for exceptional completion and rethrow
5573 Block.Parameter t = catcherFinally.parameter(type(Throwable.class));
5574 catcherFinally.transformBody(finallyBody, List.of(), loweringTransformer(inherited, (block, op) -> {
5575 if (op instanceof CoreOp.YieldOp) {
5576 block.add(throw_(t));
5577 return block;
5578 } else {
5579 return null;
5580 }
5581 }));
5582 }
5583 return exit;
5584 }
5585
5586 /// Normalize try-with-resources in two stages.
5587 ///
5588 /// First normalize an extended form to nested basic forms, one resource per
5589 /// level, left to right.
5590 ///
5591 /// ```
5592 /// extended TWR -> basic TWR -> try/catch/finally
5593 /// ```
5594 Op normalize(List<Value> captures) {
5595 Body.Builder body = Body.Builder.of(null, CoreType.functionType(VOID, captures.stream().map(Value::type).toList()));
5596 Block.Builder entry = body.entryBlock();
5597 entry.context().mapValues(captures, entry.parameters());
5598 entry.context().mapBlock(ancestorBody().entryBlock(), entry);
5599 entry.withContextAndTransformer(entry.context(), this::stageTargetingOps).add(this);
5600 entry.add(return_());
5601
5602 CoreOp.FuncOp root = func("$", body);
5603 root = normalize(root, TryOp::isExtendedTryWithResources, TryOp::normalizeExtendedTryWithResources);
5604 root = normalize(root, TryOp::isBasicTryWithResources, TryOp::normalizeBasicTryWithResources);
5605
5606 return root.body().entryBlock().ops().getFirst();
5607 }
5608
5609 static CoreOp.FuncOp normalize(CoreOp.FuncOp root,
5610 Predicate<TryOp> requiresNormalization,
5611 BiFunction<TryOp, Block.Builder, Op.Result> normalizer) {
5612 // normalization repeats until no operations left to normalize
5613 while (root.elements().anyMatch(element -> element instanceof TryOp tryOp && requiresNormalization.test(tryOp))) {
5614 root = root.transform(CodeContext.create(), (block, op) -> {
5615 if (op instanceof TryOp tryOp && requiresNormalization.test(tryOp)) {
5616 block.context().mapValue(tryOp.result(), normalizer.apply(tryOp, block));
5617 } else {
5618 block.add(op);
5619 }
5620 return block;
5621 });
5622 }
5623 return root;
5624 }
5625
5626 boolean isExtendedTryWithResources() {
5627 return !resourcesBodies.isEmpty() && (resourcesBodies.size() != 1 || !handlers.isEmpty() || finallyBody != null);
5628 }
5629
5630 boolean isBasicTryWithResources() {
5631 return resourcesBodies.size() == 1 && handlers.isEmpty() && finallyBody == null;
5632 }
5633
5634 /// Normalize an extended try-with-resources form to nested basic forms, one resource per level.
5635 ///
5636 /// ```
5637 /// try (r1; r2; ...; rn) { body } catch (...) { catches } finally { finalizer }
5638 ///
5639 /// =>
5640 ///
5641 /// try (r1) {
5642 /// try (r2) {
5643 /// ...
5644 /// try (rn) { body }
5645 /// ...
5646 /// }
5647 /// } catch (...) {
5648 /// catches
5649 /// } finally {
5650 /// finalizer
5651 /// }
5652 /// ```
5653 ///
5654 /// @jls 14.20.3 try-with-resources
5655 /// @jls 14.20.3.2 Extended try-with-resources
5656 Op.Result normalizeExtendedTryWithResources(Block.Builder b) {
5657 if (handlers.isEmpty() && finallyBody == null) {
5658 return b.add(normalizeExtendedTryWithResources(b.parentBody(), new ArrayList<>()));
5659 }
5660
5661 CatchBuilder catchBuilder = try_(b.parentBody(), tryBlock -> {
5662 tryBlock.add(normalizeExtendedTryWithResources(tryBlock.parentBody(), new ArrayList<>()));
5663 tryBlock.add(core_yield());
5664 });
5665 List<CodeType> catchTypes = catchTypes();
5666 for (int i = 0; i < handlers.size(); i++) {
5667 Body catcher = handlers.get(i);
5668 catchBuilder.catch_(catchTypes.get(i), catcher.bodySignature().parameterTypes().getFirst(), catchBlock ->
5669 catchBlock.transformBody(catcher, catchBlock.parameters()));
5670 }
5671 return b.add(finallyBody == null
5672 ? catchBuilder.noFinalizer()
5673 : catchBuilder.finally_(finallyBlock ->
5674 finallyBlock.transformBody(finallyBody, List.of())));
5675 }
5676
5677 /// Recursive step for extended try-with-resources.
5678 ///
5679 /// The next resource becomes the current outer basic try-with-resources.
5680 ///
5681 /// @jls 14.20.3.2 Extended try-with-resources
5682 TryOp normalizeExtendedTryWithResources(Body.Builder anc, List<Value> res) {
5683 Body resource = resourcesBodies.get(res.size());
5684 Body.Builder resourceBody = Body.Builder.of(anc, CoreType.functionType(resource.yieldType()));
5685 resourceBody.entryBlock().transformBody(resource, res, resourceBody.entryBlock().context(), resourceBody.entryBlock().transformer());
5686 Body.Builder basicBody = Body.Builder.of(anc, CoreType.functionType(VOID, List.of(resource.yieldType())));
5687 Block.Builder bodyBlock = basicBody.entryBlock();
5688 res.add(bodyBlock.parameters().getFirst());
5689 if (res.size() < resourcesBodies.size()) {
5690 bodyBlock.add(normalizeExtendedTryWithResources(basicBody, res));
5691 bodyBlock.add(core_yield());
5692 } else {
5693 bodyBlock.transformBody(body, res, bodyBlock.context(), bodyBlock.transformer());
5694 }
5695 return try_(List.of(resourceBody), basicBody, List.of(), null);
5696 }
5697
5698 /// Normalize basic try-with-resources to `try / catch / finally`.
5699 ///
5700 /// ```
5701 /// resource = acquire()
5702 /// primary = null
5703 /// try {
5704 /// body(resources)
5705 /// } catch (e) {
5706 /// primary = e
5707 /// throw t
5708 /// } finally {
5709 /// if (resource != null) {
5710 /// if (primary != null) {
5711 /// try { resource.close(); }
5712 /// catch (closeExc) { primary.addSuppressed(closeExc); }
5713 /// } else {
5714 /// resource.close();
5715 /// }
5716 /// }
5717 /// }
5718 /// ```
5719 ///
5720 /// @jls 14.20.3.1 Basic try-with-resources
5721 Op.Result normalizeBasicTryWithResources(Block.Builder b) {
5722 assert resourcesBodies.size() == 1;
5723 Body.Builder normalizedBody = Body.Builder.of(b.parentBody(), CoreType.functionType(VOID));
5724 Block.Builder entryBlock = normalizedBody.entryBlock();
5725 Body resourceBody = resourcesBodies.getFirst();
5726 entryBlock.transformBody(resourceBody, List.of(), entryBlock.context(), (block, op) -> {
5727 if (!(op instanceof CoreOp.YieldOp yield) || op.ancestorBody() != resourceBody) {
5728 block.add(op);
5729 return block;
5730 }
5731 Value resourceArgument = block.context().getValue(yield.yieldValue());
5732 // resource may be a var value if a resource declaration such as
5733 // try (AutoCloseable resource = open()) { ... }
5734 // or a value if an existing resource such as
5735 // AutoCloseable resource = open()
5736 // try (resource) { ... }
5737 // Operations in the resource need to distinguish between them and require
5738 // a load operation for the former
5739 Value primaryExceptionVar = block.add(var(block.add(constant(type(Throwable.class), null))));
5740 // @@@ following builder code may be refactored into a reflected template method transformation
5741 block.add(try_(entryBlock.parentBody(), tryEntry -> {
5742 tryEntry.transformBody(body, List.of(resourceArgument), tryEntry.context(), tryEntry.transformer());
5743 }).catch_(type(Throwable.class), catchB -> {
5744 Block.Parameter thrown = catchB.parameters().getFirst();
5745 catchB.add(varStore(primaryExceptionVar, thrown));
5746 catchB.add(throw_(thrown));
5747 }).finally_(finB -> {
5748 Value nullObj = finB.add(constant(J_L_OBJECT, null));
5749 Value resource = resourceArgument.type() instanceof VarType
5750 ? finB.add(varLoad(resourceArgument))
5751 : resourceArgument;
5752 finB.add(if_(finB.parentBody()).if_(predB -> {
5753 predB.add(core_yield(predB.add(neq(resource, nullObj))));
5754 }).then(closeB -> {
5755 Value primaryException = closeB.add(varLoad(primaryExceptionVar));
5756 closeB.add(if_(closeB.parentBody()).if_(predB -> {
5757 predB.add(core_yield(predB.add(neq(primaryException, nullObj))));
5758 }).then(suppB -> {
5759 suppB.add(try_(suppB.parentBody(), tryB -> {
5760 tryB.add(invoke(AUTO_CLOSEABLE_CLOSE_METHOD, resource));
5761 tryB.add(core_yield());
5762 }).catch_(type(Throwable.class), catchB -> {
5763 Block.Parameter closeException = catchB.parameters().getFirst();
5764 catchB.add(invoke(THROWABLE_ADD_SUPPRESSED_METHOD, primaryException, closeException));
5765 catchB.add(core_yield());
5766 }).noFinalizer());
5767 suppB.add(core_yield());
5768 }).else_(normB -> {
5769 normB.add(invoke(AUTO_CLOSEABLE_CLOSE_METHOD, resource));
5770 normB.add(core_yield());
5771 }));
5772 closeB.add(core_yield());
5773 }).noElse());
5774 finB.add(core_yield());
5775 }));
5776 block.add(core_yield());
5777 return block;
5778 });
5779 return b.add(try_(List.of(), normalizedBody, List.of(), null));
5780 }
5781
5782 // Replace targeting operations whose targets are outside the staged model with staged forms.
5783 private Block.Builder stageTargetingOps(Block.Builder block, Op op) {
5784 block.add(switch (op) {
5785 case StatementTargetingOp st when st.targetsOrAttemptsToExit(this) ->
5786 new StagedStatementTargetingOp(st);
5787 case JavaOp.YieldOp yop when yop.targetsOrAttemptsToExit(this) ->
5788 new StagedYieldOp(yop, block.context().getValue(yop.yieldOperand()));
5789 case CoreOp.ReturnOp rop when rop.targetsOrAttemptsToExit(this) -> {
5790 Value returnValue = rop.returnValue() != null
5791 ? block.context().getValue(rop.returnValue())
5792 : null;
5793 yield new StagedReturnOp(rop, returnValue);
5794 }
5795 default -> op;
5796 });
5797 return block;
5798 }
5799
5800 private List<Value> normalizationCaptures() {
5801 return capturedValues().stream()
5802 .filter(value -> !(value instanceof Result result
5803 && result.op().ancestorOp() instanceof LabeledOp labeled
5804 && labeled.labelIdentifier() == result))
5805 .toList();
5806 }
5807
5808 Block.Builder inlineFinalizer(Block.Builder block1, Value enter, BiFunction<Block.Builder, Op, Block.Builder> inherited) {
5809 Block.Builder finallyEnter = block1.block();
5810 Block.Builder finallyExit = block1.block();
5811
5812 block1.add(exceptionRegionExit(enter, finallyEnter.reference()));
5813
5814 // Inline the finally body
5815 finallyEnter.transformBody(finallyBody, List.of(), loweringTransformer(inherited, (block2, op2) -> {
5816 if (op2 instanceof CoreOp.YieldOp) {
5817 block2.add(branch(finallyExit.reference()));
5818 return block2;
5819 } else {
5820 return null;
5821 }
5822 }));
5823
5824 return finallyExit;
5825 }
5826
5827 @Override
5828 public CodeType resultType() {
5829 return VOID;
5830 }
5831 }
5832
5833 //
5834 // Patterns
5835
5836 // Reified pattern nodes
5837
5838 /**
5839 * Synthetic pattern types
5840 * // @@@ Replace with types extending from CodeType
5841 */
5842 public sealed interface Pattern {
5843
5844 /**
5845 * Synthetic type pattern type.
5846 *
5847 * @param <T> the type of values that are bound
5848 */
5849 final class Type<T> implements Pattern {
5850 Type() {
5851 }
5852 }
5853
5854 /**
5855 * Synthetic record pattern type.
5856 *
5857 * @param <T> the type of records that are bound
5858 */
5859 final class Record<T> implements Pattern {
5860 Record() {
5861 }
5862 }
5863
5864 /**
5865 * A synthetic match-all pattern type representing an unconditional pattern.
5866 */
5867 final class MatchAll implements Pattern {
5868 MatchAll() {
5869 }
5870 }
5871
5872 // @@@ Pattern types
5873
5874 /** The synthetic type of a type test pattern. */
5875 JavaType PATTERN_BINDING_TYPE = JavaType.type(Type.class);
5876
5877 /** The synthetic type of a record pattern. */
5878 JavaType PATTERN_RECORD_TYPE = JavaType.type(Record.class);
5879
5880 /** The synthetic type of an unconditional pattern. */
5881 JavaType PATTERN_MATCH_ALL_TYPE = JavaType.type(MatchAll.class);
5882
5883 /**
5884 * {@return a synthetic type for a type test pattern with the provided type}
5885 * @param t the type of the type test pattern
5886 */
5887 static JavaType bindingType(CodeType t) {
5888 return parameterized(PATTERN_BINDING_TYPE, (JavaType) t);
5889 }
5890
5891 /**
5892 * {@return a synthetic type for a record pattern with the provided record type}
5893 * @param t the record type
5894 */
5895 static JavaType recordType(CodeType t) {
5896 return parameterized(PATTERN_RECORD_TYPE, (JavaType) t);
5897 }
5898
5899 /**
5900 * {@return a synthetic type for an unconditional pattern}
5901 */
5902 static JavaType matchAllType() {
5903 return PATTERN_MATCH_ALL_TYPE;
5904 }
5905
5906 /**
5907 * {@return the type bound by a synthetic type test/record pattern}
5908 * @param t the synthetic pattern type
5909 */
5910 static CodeType targetType(CodeType t) {
5911 return ((ClassType) t).typeArguments().get(0);
5912 }
5913 }
5914
5915 /**
5916 * Pattern operations.
5917 *
5918 * @jls 14.30 Patterns
5919 */
5920 public static final class PatternOps {
5921 PatternOps() {
5922 }
5923
5924 /**
5925 * The pattern operation.
5926 * <p>
5927 * The result type of a pattern operation is a synthetic {@linkplain Pattern pattern type}.
5928 * Pattern operations are used in pattern bodies of {@link MatchOp} and as nested pattern operands of
5929 * {@link RecordPatternOp}.
5930 */
5931 public sealed static abstract class PatternOp extends AbstractOp
5932 implements JavaOp {
5933 PatternOp(PatternOp that, CodeContext cc) {
5934 super(that, cc);
5935 }
5936
5937 PatternOp(List<Value> operands) {
5938 super(operands);
5939 }
5940 }
5941
5942 /**
5943 * The type pattern operation, that can model Java language type test patterns.
5944 * <p>
5945 * Type pattern operations are associated with a target type (a {@link JavaType})
5946 * and an optional binding name.
5947 *
5948 * @jls 14.30.1 Kinds of Patterns
5949 * @jls 15.20.2 The instanceof Operator
5950 */
5951 @OpDeclaration(TypePatternOp.NAME)
5952 public static final class TypePatternOp extends PatternOp {
5953 static final String NAME = "pattern.type";
5954
5955 /**
5956 * The externalized attribute key for a pattern binding name in a type pattern operation.
5957 */
5958 static final String ATTRIBUTE_BINDING_NAME = NAME + ".binding.name";
5959
5960 final CodeType resultType;
5961 final String bindingName;
5962
5963 TypePatternOp(ExternalizedOp def) {
5964 super(List.of());
5965 this.bindingName = optionalAttribute(def, ATTRIBUTE_BINDING_NAME, true, String.class).orElse(null);
5966 // @@@ Cannot use canonical constructor because it wraps the given type
5967 this.resultType = def.resultType();
5968 }
5969
5970 TypePatternOp(TypePatternOp that, CodeContext cc) {
5971 super(that, cc);
5972
5973 this.bindingName = that.bindingName;
5974 this.resultType = that.resultType;
5975 }
5976
5977 @Override
5978 public TypePatternOp transform(CodeContext cc, CodeTransformer ct) {
5979 return new TypePatternOp(this, cc);
5980 }
5981
5982 TypePatternOp(CodeType targetType, String bindingName) {
5983 super(List.of());
5984
5985 this.bindingName = bindingName;
5986 this.resultType = Pattern.bindingType(targetType);
5987 }
5988
5989 @Override
5990 public Map<String, Object> externalize() {
5991 return bindingName == null ? Map.of() : Map.of("", bindingName);
5992 }
5993
5994 /**
5995 * {@return the variable name bound by this type test pattern, or {@code null} if none}
5996 */
5997 public String bindingName() {
5998 return bindingName;
5999 }
6000
6001 /**
6002 * {@return the type matched by this type test pattern}
6003 */
6004 public CodeType targetType() {
6005 return Pattern.targetType(resultType());
6006 }
6007
6008 @Override
6009 public CodeType resultType() {
6010 return resultType;
6011 }
6012 }
6013
6014 /**
6015 * The record pattern operation, that can model Java language record patterns.
6016 * <p>
6017 * Record pattern operations are associated with a {@linkplain RecordTypeRef record reference}.
6018 * The operands are nested pattern values.
6019 *
6020 * @jls 14.30.1 Kinds of Patterns
6021 */
6022 @OpDeclaration(RecordPatternOp.NAME)
6023 public static final class RecordPatternOp extends PatternOp {
6024 static final String NAME = "pattern.record";
6025
6026 /**
6027 * The externalized attribute key for a record reference in a record pattern operation.
6028 */
6029 static final String ATTRIBUTE_RECORD_REF = NAME + ".ref";
6030
6031 final RecordTypeRef recordReference;
6032
6033 RecordPatternOp(ExternalizedOp def) {
6034 this(requireAttribute(def, ATTRIBUTE_RECORD_REF, true, RecordTypeRef.class), def.operands());
6035 }
6036
6037 RecordPatternOp(RecordPatternOp that, CodeContext cc) {
6038 super(that, cc);
6039
6040 this.recordReference = that.recordReference;
6041 }
6042
6043 @Override
6044 public RecordPatternOp transform(CodeContext cc, CodeTransformer ct) {
6045 return new RecordPatternOp(this, cc);
6046 }
6047
6048 RecordPatternOp(RecordTypeRef recordReference, List<Value> nestedPatterns) {
6049 // The type of each value is a subtype of Pattern
6050 // The number of values corresponds to the number of components of the record
6051 if (recordReference.components().size() != nestedPatterns.size()) {
6052 throw structuralException(NAME, "requires %d nested pattern operands, found %d".formatted(recordReference.components().size(), nestedPatterns.size()));
6053 }
6054 super(List.copyOf(nestedPatterns));
6055
6056 this.recordReference = recordReference;
6057 }
6058
6059 @Override
6060 public Map<String, Object> externalize() {
6061 return Map.of("", recordReference());
6062 }
6063
6064 /**
6065 * {@return the record reference associated with this record pattern}
6066 */
6067 public RecordTypeRef recordReference() {
6068 return recordReference;
6069 }
6070
6071 /**
6072 * {@return the type matched by this record pattern}
6073 */
6074 public CodeType targetType() {
6075 return Pattern.targetType(resultType());
6076 }
6077
6078 @Override
6079 public CodeType resultType() {
6080 return Pattern.recordType(recordReference.recordType());
6081 }
6082 }
6083
6084 /**
6085 * A pattern operation representing a match-all (unconditional) pattern.
6086 *
6087 * @jls 14.30.1 Kinds of Patterns
6088 */
6089 @OpDeclaration(MatchAllPatternOp.NAME)
6090 public static final class MatchAllPatternOp extends PatternOp {
6091
6092 // @@@ we may need to add info about the type of the record component
6093 // this info can be used when lowering
6094
6095 static final String NAME = "pattern.match.all";
6096
6097 MatchAllPatternOp(ExternalizedOp def) {
6098 this();
6099 }
6100
6101 MatchAllPatternOp(MatchAllPatternOp that, CodeContext cc) {
6102 super(that, cc);
6103 }
6104
6105 MatchAllPatternOp() {
6106 super(List.of());
6107 }
6108
6109 @Override
6110 public Op transform(CodeContext cc, CodeTransformer ct) {
6111 return new MatchAllPatternOp(this, cc);
6112 }
6113
6114 @Override
6115 public CodeType resultType() {
6116 return Pattern.matchAllType();
6117 }
6118 }
6119
6120 /**
6121 * The match operation, that can model Java language pattern matching.
6122 * <p>
6123 * Match operations can be used to model instanceof expressions with a pattern match operator, or
6124 * case labels with case patterns in switch statements and switch expressions.
6125 * <p>
6126 * Match operations feature one operand, the target value being matched, and two bodies: the pattern body and
6127 * the match body.
6128 * <p>
6129 * The pattern body should accept no arguments and yield a pattern value.
6130 * The match body accepts the values bound by the pattern body and yields {@linkplain JavaType#VOID no value}.
6131 * The result type of a match operation is {@link JavaType#BOOLEAN}.
6132 *
6133 * @jls 14.30.2 Pattern Matching
6134 * @jls 14.11 The switch Statement
6135 * @jls 15.28 switch Expressions
6136 * @jls 15.20.2 The instanceof Operator
6137 */
6138 @OpDeclaration(MatchOp.NAME)
6139 public static final class MatchOp extends AbstractOp
6140 implements JavaOp, Op.Isolated, ControlFlowBooleanExpressionOp {
6141 static final String NAME = "pattern.match";
6142
6143 final Body patternBody;
6144 final Body matchBody;
6145
6146 MatchOp(ExternalizedOp def) {
6147 List<Body.Builder> bodies = requireBodies(def, 2);
6148 this(requireSingleOperand(def), bodies.get(0), bodies.get(1));
6149 }
6150
6151 MatchOp(MatchOp that, CodeContext cc, CodeTransformer ct) {
6152 super(that, cc);
6153
6154 this.patternBody = that.patternBody.transform(cc, ct).build(this);
6155 this.matchBody = that.matchBody.transform(cc, ct).build(this);
6156 }
6157
6158 @Override
6159 public MatchOp transform(CodeContext cc, CodeTransformer ct) {
6160 return new MatchOp(this, cc, ct);
6161 }
6162
6163 MatchOp(Value target, Body.Builder patternC, Body.Builder matchC) {
6164 super(List.of(target));
6165
6166 this.patternBody = requireNoParameters(NAME + " pattern", patternC).build(this);
6167 this.matchBody = matchC.build(this);
6168 }
6169
6170 @Override
6171 public List<Body> bodies() {
6172 return List.of(patternBody, matchBody);
6173 }
6174
6175 /**
6176 * Returns the pattern body for this match operation.
6177 *
6178 * @return the pattern body
6179 */
6180 public Body patternBody() {
6181 return patternBody;
6182 }
6183
6184 /**
6185 * Returns the match body for this match operation.
6186 *
6187 * @return the match body
6188 */
6189 public Body matchBody() {
6190 return matchBody;
6191 }
6192
6193 /**
6194 * Returns the target value being matched in this match operation.
6195 *
6196 * @return the match target value
6197 */
6198 public Value targetOperand() {
6199 return operands().get(0);
6200 }
6201
6202 @Override
6203 public Block.Builder lower(Block.Builder b, BiFunction<Block.Builder, Op, Block.Builder> inherited) {
6204 // Poll for implicit boolean continuation parameter
6205 BooleanResultContinuation continuation = BOOLEAN_CONTINUATION_ARG.poll(b.context());
6206 Block.Builder exit = b;
6207 if (continuation == null) {
6208 exit = b.block();
6209 b.context().mapValue(result(), exit.parameter(resultType()));
6210 continuation = new BranchWithArgumentContinuation(exit);
6211 }
6212 lowerTo(b, inherited, continuation);
6213 return exit;
6214 }
6215
6216 void lowerTo(Block.Builder b, BiFunction<Block.Builder, Op, Block.Builder> inherited,
6217 BooleanResultContinuation continuation) {
6218 Block.Reference trueRef = continuation.referenceFor(b, true);
6219 Block.Reference falseRef = continuation.referenceFor(b, false);
6220
6221 List<Value> patternValues = new ArrayList<>();
6222 Op patternYieldOp = patternBody.entryBlock().terminatingOp();
6223 Op.Result rootPatternValue = (Op.Result) patternYieldOp.operands().get(0);
6224 Block.Builder matchedBlock = lower(
6225 falseRef,
6226 b,
6227 patternValues,
6228 rootPatternValue.op(),
6229 b.context().getValue(targetOperand()));
6230
6231 matchedBlock.transformBody(matchBody, patternValues, loweringTransformer(inherited, (block, op) -> {
6232 if (op instanceof CoreOp.YieldOp) {
6233 block.add(branch(trueRef));
6234 return block;
6235 } else {
6236 return null;
6237 }
6238 }));
6239 }
6240
6241 static Block.Builder lower(Block.Reference falseRef, Block.Builder currentBlock,
6242 List<Value> bindings,
6243 Op pattern, Value target) {
6244 return switch (pattern) {
6245 case RecordPatternOp rp -> lowerRecordPattern(falseRef, currentBlock, bindings, rp, target);
6246 case TypePatternOp tp -> lowerTypePattern(falseRef, currentBlock, bindings, tp, target);
6247 case MatchAllPatternOp map -> lowerMatchAllPattern(currentBlock);
6248 case null, default -> throw new UnsupportedOperationException("Unknown pattern op: " + pattern);
6249 };
6250 }
6251
6252 static Block.Builder lowerRecordPattern(Block.Reference falseRef, Block.Builder currentBlock,
6253 List<Value> bindings,
6254 JavaOp.PatternOps.RecordPatternOp rpOp, Value target) {
6255 CodeType targetType = rpOp.targetType();
6256
6257 Block.Builder nextBlock = currentBlock.block();
6258
6259 // Check if instance of target type
6260 Op.Result isInstance = currentBlock.add(instanceOf(targetType, target));
6261 currentBlock.add(conditionalBranch(isInstance, nextBlock.reference(), falseRef));
6262
6263 currentBlock = nextBlock;
6264
6265 target = currentBlock.add(cast(targetType, target));
6266
6267 // Access component values of record and match on each as nested target
6268 List<Value> dArgs = rpOp.operands();
6269 for (int i = 0; i < dArgs.size(); i++) {
6270 Op.Result nestedPattern = (Op.Result) dArgs.get(i);
6271 // @@@ Handle exceptions?
6272 Value nestedTarget = currentBlock.add(invoke(rpOp.recordReference().methodForComponent(i), target));
6273
6274 currentBlock = lower(falseRef, currentBlock, bindings, nestedPattern.op(), nestedTarget);
6275 }
6276
6277 return currentBlock;
6278 }
6279
6280 static Block.Builder lowerTypePattern(Block.Reference falseRef, Block.Builder currentBlock,
6281 List<Value> bindings,
6282 TypePatternOp tpOp, Value target) {
6283 CodeType s = target.type();
6284 CodeType t = tpOp.targetType();
6285 if (s instanceof PrimitiveType) {
6286 // must be identity
6287 if (!t.equals(s)) {
6288 throw new UnsupportedOperationException("Primitive patterns are only allowed in identity form");
6289 }
6290 } else if (t instanceof PrimitiveType) {
6291 throw new UnsupportedOperationException("Non-primitive value can't be matched against a primitive type");
6292 } else {
6293 // for s == t, we still need to do the instanceof check as the value of s might be null
6294 currentBlock = appendTypeTestOp(instanceOf(t, target), currentBlock, falseRef);
6295 target = currentBlock.add(cast(t, target));
6296 }
6297
6298 bindings.add(target);
6299
6300 return currentBlock;
6301 }
6302
6303 private static Block.Builder appendTypeTestOp(Op p, Block.Builder b, Block.Reference falseBlock) {
6304 Block.Builder trueBlock = b.block();
6305 b.add(conditionalBranch(b.add(p), trueBlock.reference(), falseBlock));
6306 return trueBlock;
6307 }
6308
6309 static Block.Builder lowerMatchAllPattern(Block.Builder currentBlock) {
6310 return currentBlock;
6311 }
6312
6313 @Override
6314 public CodeType resultType() {
6315 return BOOLEAN;
6316 }
6317 }
6318 }
6319
6320 /**
6321 * Returns a composed function that composes {@code g} into the first argument of {@code f}.
6322 * <p>
6323 * if {@code f} is {@code null} then this method returns {@code g}.
6324 *
6325 * @param f the outer function
6326 * @param g the inner function
6327 * @return the composed
6328 */
6329 private static <T, U> BiFunction<T, U, T> composeFirst(
6330 BiFunction<T, U, T> f,
6331 BiFunction<T, U, T> g) {
6332 Objects.requireNonNull(g);
6333 return f == null
6334 ? g
6335 : (builder, op) -> f.apply(g.apply(builder, op), op);
6336 }
6337
6338 private static Op createOp(ExternalizedOp def) {
6339 Op op = switch (def.name()) {
6340 case "add" -> new AddOp(def);
6341 case "and" -> new AndOp(def);
6342 case "array.length" -> new ArrayLengthOp(def);
6343 case "array.load" -> new ArrayAccessOp.ArrayLoadOp(def);
6344 case "array.store" -> new ArrayAccessOp.ArrayStoreOp(def);
6345 case "ashr" -> new AshrOp(def);
6346 case "assert" -> new AssertOp(def);
6347 case "cast" -> new CastOp(def);
6348 case "compl" -> new ComplOp(def);
6349 case "concat" -> new ConcatOp(def);
6350 case "conv" -> new ConvOp(def);
6351 case "div" -> new DivOp(def);
6352 case "eq" -> new EqOp(def);
6353 case "exception.region.enter" -> new ExceptionRegionEnter(def);
6354 case "exception.region.exit" -> new ExceptionRegionExit(def);
6355 case "field.load" -> new FieldAccessOp.FieldLoadOp(def);
6356 case "field.store" -> new FieldAccessOp.FieldStoreOp(def);
6357 case "ge" -> new GeOp(def);
6358 case "gt" -> new GtOp(def);
6359 case "instanceof" -> new InstanceOfOp(def);
6360 case "invoke" -> new InvokeOp(def);
6361 case "java.block" -> new BlockOp(def);
6362 case "java.break" -> new BreakOp(def);
6363 case "java.cand" -> new ConditionalAndOp(def);
6364 case "java.cexpression" -> new ConditionalExpressionOp(def);
6365 case "java.continue" -> new ContinueOp(def);
6366 case "java.cor" -> new ConditionalOrOp(def);
6367 case "java.do.while" -> new DoWhileOp(def);
6368 case "java.enhancedFor" -> new EnhancedForOp(def);
6369 case "java.for" -> new ForOp(def);
6370 case "java.if" -> new IfOp(def);
6371 case "java.labeled" -> new LabeledOp(def);
6372 case "java.switch.expression" -> new SwitchExpressionOp(def);
6373 case "java.switch.fallthrough" -> new SwitchFallthroughOp(def);
6374 case "java.switch.statement" -> new SwitchStatementOp(def);
6375 case "java.synchronized" -> new SynchronizedOp(def);
6376 case "java.try" -> new TryOp(def);
6377 case "java.while" -> new WhileOp(def);
6378 case "java.yield" -> new YieldOp(def);
6379 case "lambda" -> new LambdaOp(def);
6380 case "le" -> new LeOp(def);
6381 case "lshl" -> new LshlOp(def);
6382 case "lshr" -> new LshrOp(def);
6383 case "lt" -> new LtOp(def);
6384 case "mod" -> new ModOp(def);
6385 case "monitor.enter" -> new MonitorOp.MonitorEnterOp(def);
6386 case "monitor.exit" -> new MonitorOp.MonitorExitOp(def);
6387 case "mul" -> new MulOp(def);
6388 case "neg" -> new NegOp(def);
6389 case "pos" -> new PosOp(def);
6390 case "neq" -> new NeqOp(def);
6391 case "new" -> new NewOp(def);
6392 case "not" -> new NotOp(def);
6393 case "or" -> new OrOp(def);
6394 case "pattern.match" -> new PatternOps.MatchOp(def);
6395 case "pattern.match.all" -> new PatternOps.MatchAllPatternOp(def);
6396 case "pattern.record" -> new PatternOps.RecordPatternOp(def);
6397 case "pattern.type" -> new PatternOps.TypePatternOp(def);
6398 case "sub" -> new SubOp(def);
6399 case "throw" -> new ThrowOp(def);
6400 case "xor" -> new XorOp(def);
6401 default -> null;
6402 };
6403 if (op != null) {
6404 op.setLocation(def.location());
6405 }
6406 return op;
6407 }
6408
6409 /**
6410 * An operation factory for core operations composed with Java operations.
6411 */
6412 public static final OpFactory JAVA_OP_FACTORY = CoreOp.CORE_OP_FACTORY.andThen(JavaOp::createOp);
6413
6414 /**
6415 * A Java dialect factory, for constructing core and Java operations and constructing
6416 * core types and Java types, where the core types can refer to Java
6417 * types.
6418 */
6419 public static final DialectFactory JAVA_DIALECT_FACTORY = new DialectFactory(
6420 JAVA_OP_FACTORY,
6421 JAVA_TYPE_FACTORY);
6422
6423 /**
6424 * Creates a lambda operation.
6425 *
6426 * @param connectedAncestorBody the nearest ancestor body builder to which body builders for this operation are
6427 * connected, or {@code null} if they are isolated
6428 * @param signature the lambda operation's signature, represented as a function type
6429 * @param functionalInterface the lambda operation's functional interface type
6430 * @return the lambda operation
6431 */
6432 public static LambdaOp.Builder lambda(Body.Builder connectedAncestorBody,
6433 FunctionType signature, CodeType functionalInterface) {
6434 return new LambdaOp.Builder(connectedAncestorBody, signature, functionalInterface);
6435 }
6436
6437 /**
6438 * Creates a lambda operation.
6439 *
6440 * @param functionalInterface the lambda operation's functional interface type
6441 * @param body the body of the lambda operation
6442 * @return the lambda operation
6443 */
6444 public static LambdaOp lambda(CodeType functionalInterface, Body.Builder body) {
6445 return new LambdaOp(functionalInterface, body, List.of(), false);
6446 }
6447
6448 /**
6449 * Creates a lambda operation.
6450 *
6451 * @param functionalInterface the lambda operation's functional interface type
6452 * @param body the body of the lambda operation
6453 * @param isReflectable true if the lambda is reflectable
6454 * @return the lambda operation
6455 */
6456 public static LambdaOp lambda(CodeType functionalInterface, Body.Builder body, boolean isReflectable) {
6457 return new LambdaOp(functionalInterface, body, List.of(), isReflectable);
6458 }
6459
6460 /**
6461 * Creates a lambda operation.
6462 *
6463 * @param functionalInterface the lambda operation's functional interface type
6464 * @param body the body of the lambda operation
6465 * @param additionalInterfaces the lambda operation's additional interface types
6466 * @param isReflectable true if the lambda is reflectable
6467 * @return the lambda operation
6468 */
6469 public static LambdaOp lambda(CodeType functionalInterface, Body.Builder body,
6470 List<? extends CodeType> additionalInterfaces,
6471 boolean isReflectable) {
6472 return new LambdaOp(functionalInterface, body, additionalInterfaces, isReflectable);
6473 }
6474
6475 /**
6476 * Creates an exception region enter operation
6477 *
6478 * @param start the reference to the block that enters the exception region
6479 * @param catchers the references to blocks handling exceptions thrown by blocks within the exception region
6480 * @return the exception region enter operation
6481 */
6482 public static ExceptionRegionEnter exceptionRegionEnter(Block.Reference start, Block.Reference... catchers) {
6483 return exceptionRegionEnter(null, start, List.of(catchers));
6484 }
6485
6486 /**
6487 * Creates an exception region enter operation
6488 *
6489 * @param start the reference to the block that enters the exception region
6490 * @param catchers the references to blocks handling exceptions thrown by blocks within the exception region
6491 * @return the exception region enter operation
6492 */
6493 public static ExceptionRegionEnter exceptionRegionEnter(Block.Reference start, List<Block.Reference> catchers) {
6494 return exceptionRegionEnter(null, start, catchers);
6495 }
6496
6497 /**
6498 * Creates an exception region enter operation
6499 *
6500 * @param catchTypes the explicit catch types, may be {@code null}
6501 * @param start the reference to the block that enters the exception region
6502 * @param catchers the references to blocks handling exceptions thrown by blocks within the exception region
6503 * @return the exception region enter operation
6504 */
6505 public static ExceptionRegionEnter exceptionRegionEnter(List<CodeType> catchTypes,
6506 Block.Reference start,
6507 List<Block.Reference> catchers) {
6508 List<Block.Reference> s = new ArrayList<>();
6509 s.add(start);
6510 s.addAll(catchers);
6511 return new ExceptionRegionEnter(catchTypes, s);
6512 }
6513
6514 /**
6515 * Creates an exception region exit operation
6516 *
6517 * @param enter the result of the dominant {@link ExceptionRegionEnter}
6518 * @param end the reference to the block reached after exiting the exception region
6519 * @return the exception region exit operation
6520 */
6521 public static ExceptionRegionExit exceptionRegionExit(Value enter, Block.Reference end) {
6522 return new ExceptionRegionExit(enter, end);
6523 }
6524
6525 /**
6526 * Creates a throw operation.
6527 *
6528 * @param exceptionValue the thrown value
6529 * @return the throw operation
6530 */
6531 public static ThrowOp throw_(Value exceptionValue) {
6532 return new ThrowOp(exceptionValue);
6533 }
6534
6535 /**
6536 * Creates an assert operation.
6537 *
6538 * @param bodies the nested bodies
6539 * @return the assert operation
6540 */
6541 public static AssertOp assert_(List<Body.Builder> bodies) {
6542 return new AssertOp(bodies);
6543 }
6544
6545 /**
6546 * Creates a monitor enter operation.
6547 * @param monitor the monitor value
6548 * @return the monitor enter operation
6549 */
6550 public static MonitorOp.MonitorEnterOp monitorEnter(Value monitor) {
6551 return new MonitorOp.MonitorEnterOp(monitor);
6552 }
6553
6554 /**
6555 * Creates a monitor exit operation.
6556 * @param monitor the monitor value
6557 * @return the monitor exit operation
6558 */
6559 public static MonitorOp.MonitorExitOp monitorExit(Value monitor) {
6560 return new MonitorOp.MonitorExitOp(monitor);
6561 }
6562
6563 /**
6564 * Creates an invoke operation modeling an invocation to an
6565 * instance or static (class) method with no variable arguments.
6566 * <p>
6567 * The invoke kind of the invoke operation is determined by
6568 * comparing the argument count with the method reference's
6569 * parameter count. If they are equal then the invoke kind is
6570 * {@link InvokeOp.InvokeKind#STATIC static}. If the parameter count
6571 * plus one is equal to the argument count then the invoke kind
6572 * is {@link InvokeOp.InvokeKind#INSTANCE instance}.
6573 * <p>
6574 * The result type of the invoke operation is the method reference's return type.
6575 *
6576 * @param invokeRef the method reference
6577 * @param args the invoke arguments
6578 * @return the invoke operation
6579 */
6580 public static InvokeOp invoke(MethodRef invokeRef, Value... args) {
6581 return invoke(invokeRef, List.of(args));
6582 }
6583
6584 /**
6585 * Creates an invoke operation modeling an invocation to an
6586 * instance or static (class) method with no variable arguments.
6587 * <p>
6588 * The invoke kind of the invoke operation is determined by
6589 * comparing the argument count with the method reference's
6590 * parameter count. If they are equal then the invoke kind is
6591 * {@link InvokeOp.InvokeKind#STATIC static}. If the parameter count
6592 * plus one is equal to the argument count then the invoke kind
6593 * is {@link InvokeOp.InvokeKind#INSTANCE instance}.
6594 * <p>
6595 * The result type of the invoke operation is the method reference's return type.
6596 *
6597 * @param invokeRef the method reference
6598 * @param args the invoke arguments
6599 * @return the invoke operation
6600 */
6601 public static InvokeOp invoke(MethodRef invokeRef, List<Value> args) {
6602 return invoke(invokeRef.signature().returnType(), invokeRef, args);
6603 }
6604
6605 /**
6606 * Creates an invoke operation modeling an invocation to an
6607 * instance or static (class) method with no variable arguments.
6608 * <p>
6609 * The invoke kind of the invoke operation is determined by
6610 * comparing the argument count with the method reference's
6611 * parameter count. If they are equal then the invoke kind is
6612 * {@link InvokeOp.InvokeKind#STATIC static}. If the parameter count
6613 * plus one is equal to the argument count then the invoke kind
6614 * is {@link InvokeOp.InvokeKind#INSTANCE instance}.
6615 *
6616 * @param returnType the result type of the invoke operation
6617 * @param invokeRef the method reference
6618 * @param args the invoke arguments
6619 * @return the invoke operation
6620 */
6621 public static InvokeOp invoke(CodeType returnType, MethodRef invokeRef, Value... args) {
6622 return invoke(returnType, invokeRef, List.of(args));
6623 }
6624
6625 /**
6626 * Creates an invoke operation modeling an invocation to an
6627 * instance or static (class) method with no variable arguments.
6628 * <p>
6629 * The invoke kind of the invoke operation is determined by
6630 * comparing the argument count with the method reference's
6631 * parameter count. If they are equal then the invoke kind is
6632 * {@link InvokeOp.InvokeKind#STATIC static}. If the parameter count
6633 * plus one is equal to the argument count then the invoke kind
6634 * is {@link InvokeOp.InvokeKind#INSTANCE instance}.
6635 *
6636 * @param returnType the result type of the invoke operation
6637 * @param invokeRef the method reference
6638 * @param args the invoke arguments
6639 * @return the invoke super operation
6640 */
6641 public static InvokeOp invoke(CodeType returnType, MethodRef invokeRef, List<Value> args) {
6642 int paramCount = invokeRef.signature().parameterTypes().size();
6643 int argCount = args.size();
6644 InvokeOp.InvokeKind ik = (argCount == paramCount + 1)
6645 ? InvokeOp.InvokeKind.INSTANCE
6646 : InvokeOp.InvokeKind.STATIC;
6647 return new InvokeOp(ik, false, returnType, invokeRef, args);
6648 }
6649
6650 /**
6651 * Creates an invoke operation modeling an invocation to a method.
6652 *
6653 * @param invokeKind the invoke kind
6654 * @param isVarArgs true if an invocation to a variable argument method
6655 * @param returnType the result type of the invoke operation
6656 * @param invokeRef the method reference
6657 * @param args the invoke arguments
6658 * @return the invoke operation
6659 * @throws IllegalArgumentException if there is a mismatch between the argument count
6660 * and the method reference's parameter count.
6661 */
6662 public static InvokeOp invoke(InvokeOp.InvokeKind invokeKind, boolean isVarArgs,
6663 CodeType returnType, MethodRef invokeRef, Value... args) {
6664 return new InvokeOp(invokeKind, isVarArgs, returnType, invokeRef, List.of(args));
6665 }
6666
6667 /**
6668 * Creates an invoke operation modeling an invocation to a method.
6669 *
6670 * @param invokeKind the invoke kind
6671 * @param isVarArgs true if an invocation to a variable argument method
6672 * @param returnType the result type of the invoke operation
6673 * @param invokeRef the method reference
6674 * @param args the invoke arguments
6675 * @return the invoke operation
6676 * @throws IllegalArgumentException if there is a mismatch between the argument count
6677 * and the method reference's parameter count.
6678 */
6679 public static InvokeOp invoke(InvokeOp.InvokeKind invokeKind, boolean isVarArgs,
6680 CodeType returnType, MethodRef invokeRef, List<Value> args) {
6681 return new InvokeOp(invokeKind, isVarArgs, returnType, invokeRef, args);
6682 }
6683
6684 /**
6685 * Creates a conversion operation.
6686 *
6687 * @param to the conversion target type
6688 * @param from the value to be converted
6689 * @return the conversion operation
6690 */
6691 public static ConvOp conv(CodeType to, Value from) {
6692 return new ConvOp(to, from);
6693 }
6694
6695 /**
6696 * Creates an instance creation operation.
6697 *
6698 * @param constructorRef the constructor reference
6699 * @param args the constructor arguments
6700 * @return the instance creation operation
6701 */
6702 public static NewOp new_(MethodRef constructorRef, Value... args) {
6703 return new_(constructorRef, List.of(args));
6704 }
6705
6706 /**
6707 * Creates an instance creation operation.
6708 *
6709 * @param constructorRef the constructor reference
6710 * @param args the constructor arguments
6711 * @return the instance creation operation
6712 */
6713 public static NewOp new_(MethodRef constructorRef, List<Value> args) {
6714 return new NewOp(false, constructorRef.refType(), constructorRef, args);
6715 }
6716
6717 /**
6718 * Creates an instance creation operation.
6719 *
6720 * @param returnType the result type of the instance creation operation
6721 * @param constructorRef the constructor reference
6722 * @param args the constructor arguments
6723 * @return the instance creation operation
6724 */
6725 public static NewOp new_(CodeType returnType, MethodRef constructorRef,
6726 Value... args) {
6727 return new_(returnType, constructorRef, List.of(args));
6728 }
6729
6730 /**
6731 * Creates an instance creation operation.
6732 *
6733 * @param returnType the result type of the instance creation operation
6734 * @param constructorRef the constructor reference
6735 * @param args the constructor arguments
6736 * @return the instance creation operation
6737 */
6738 public static NewOp new_(CodeType returnType, MethodRef constructorRef,
6739 List<Value> args) {
6740 return new NewOp(false, returnType, constructorRef, args);
6741 }
6742
6743 /**
6744 * Creates an instance creation operation.
6745 *
6746 * @param isVarargs {@code true} if calling a varargs constructor
6747 * @param returnType the result type of the instance creation operation
6748 * @param constructorRef the constructor reference
6749 * @param args the constructor arguments
6750 * @return the instance creation operation
6751 */
6752 public static NewOp new_(boolean isVarargs, CodeType returnType, MethodRef constructorRef,
6753 List<Value> args) {
6754 return new NewOp(isVarargs, returnType, constructorRef, args);
6755 }
6756
6757 /**
6758 * Creates an array creation operation.
6759 *
6760 * @param arrayType the array type
6761 * @param length the array size
6762 * @return the array creation operation
6763 */
6764 public static NewOp newArray(CodeType arrayType, Value length) {
6765 MethodRef constructorRef = MethodRef.constructor(arrayType, INT);
6766 return new_(constructorRef, length);
6767 }
6768
6769 /**
6770 * Creates a field load operation to a non-static field.
6771 *
6772 * @param fieldRef the field reference
6773 * @param receiver the receiver value
6774 * @return the field load operation
6775 */
6776 public static FieldAccessOp.FieldLoadOp fieldLoad(FieldRef fieldRef, Value receiver) {
6777 return new FieldAccessOp.FieldLoadOp(fieldRef.type(), fieldRef, receiver);
6778 }
6779
6780 /**
6781 * Creates a field load operation to a non-static field.
6782 *
6783 * @param resultType the result type of the operation
6784 * @param fieldRef the field reference
6785 * @param receiver the receiver value
6786 * @return the field load operation
6787 */
6788 public static FieldAccessOp.FieldLoadOp fieldLoad(CodeType resultType, FieldRef fieldRef, Value receiver) {
6789 return new FieldAccessOp.FieldLoadOp(resultType, fieldRef, receiver);
6790 }
6791
6792 /**
6793 * Creates a field load operation to a static field.
6794 *
6795 * @param fieldRef the field reference
6796 * @return the field load operation
6797 */
6798 public static FieldAccessOp.FieldLoadOp fieldLoad(FieldRef fieldRef) {
6799 return new FieldAccessOp.FieldLoadOp(fieldRef.type(), fieldRef);
6800 }
6801
6802 /**
6803 * Creates a field load operation to a static field.
6804 *
6805 * @param resultType the result type of the operation
6806 * @param fieldRef the field reference
6807 * @return the field load operation
6808 */
6809 public static FieldAccessOp.FieldLoadOp fieldLoad(CodeType resultType, FieldRef fieldRef) {
6810 return new FieldAccessOp.FieldLoadOp(resultType, fieldRef);
6811 }
6812
6813 /**
6814 * Creates a field store operation to a non-static field.
6815 *
6816 * @param fieldRef the field reference
6817 * @param receiver the receiver value
6818 * @param v the value to store
6819 * @return the field store operation
6820 */
6821 public static FieldAccessOp.FieldStoreOp fieldStore(FieldRef fieldRef, Value receiver, Value v) {
6822 return new FieldAccessOp.FieldStoreOp(fieldRef, receiver, v);
6823 }
6824
6825 /**
6826 * Creates a field load operation to a static field.
6827 *
6828 * @param fieldRef the field reference
6829 * @param v the value to store
6830 * @return the field store operation
6831 */
6832 public static FieldAccessOp.FieldStoreOp fieldStore(FieldRef fieldRef, Value v) {
6833 return new FieldAccessOp.FieldStoreOp(fieldRef, v);
6834 }
6835
6836 /**
6837 * Creates an array length operation.
6838 *
6839 * @param array the array value
6840 * @return the array length operation
6841 */
6842 public static ArrayLengthOp arrayLength(Value array) {
6843 return new ArrayLengthOp(array);
6844 }
6845
6846 /**
6847 * Creates an array load operation.
6848 *
6849 * @param array the array value
6850 * @param index the index value
6851 * @return the array load operation
6852 */
6853 public static ArrayAccessOp.ArrayLoadOp arrayLoadOp(Value array, Value index) {
6854 return new ArrayAccessOp.ArrayLoadOp(array, index);
6855 }
6856
6857 /**
6858 * Creates an array load operation.
6859 *
6860 * @param array the array value
6861 * @param index the index value
6862 * @param componentType the type of the array component
6863 * @return the array load operation
6864 */
6865 public static ArrayAccessOp.ArrayLoadOp arrayLoadOp(Value array, Value index, CodeType componentType) {
6866 return new ArrayAccessOp.ArrayLoadOp(array, index, componentType);
6867 }
6868
6869 /**
6870 * Creates an array store operation.
6871 *
6872 * @param array the array value
6873 * @param index the index value
6874 * @param v the value to store
6875 * @return the array store operation
6876 */
6877 public static ArrayAccessOp.ArrayStoreOp arrayStoreOp(Value array, Value index, Value v) {
6878 return new ArrayAccessOp.ArrayStoreOp(array, index, v);
6879 }
6880
6881 /**
6882 * Creates an instanceof operation.
6883 *
6884 * @param t the type to test against
6885 * @param v the value to test
6886 * @return the instanceof operation
6887 */
6888 public static InstanceOfOp instanceOf(CodeType t, Value v) {
6889 return new InstanceOfOp(t, v);
6890 }
6891
6892 /**
6893 * Creates a cast operation.
6894 *
6895 * @param resultType the result type of the operation
6896 * @param v the value to cast
6897 * @return the cast operation
6898 */
6899 public static CastOp cast(CodeType resultType, Value v) {
6900 return new CastOp(resultType, resultType, v);
6901 }
6902
6903 /**
6904 * Creates a cast operation.
6905 *
6906 * @param resultType the result type of the operation
6907 * @param t the type to cast to
6908 * @param v the value to cast
6909 * @return the cast operation
6910 */
6911 public static CastOp cast(CodeType resultType, JavaType t, Value v) {
6912 return new CastOp(resultType, t, v);
6913 }
6914
6915 /**
6916 * Creates an add operation.
6917 *
6918 * @param lhs the first operand
6919 * @param rhs the second operand
6920 * @return the add operation
6921 */
6922 public static AddOp add(Value lhs, Value rhs) {
6923 return new AddOp(lhs, rhs);
6924 }
6925
6926 /**
6927 * Creates a sub operation.
6928 *
6929 * @param lhs the first operand
6930 * @param rhs the second operand
6931 * @return the sub operation
6932 */
6933 public static SubOp sub(Value lhs, Value rhs) {
6934 return new SubOp(lhs, rhs);
6935 }
6936
6937 /**
6938 * Creates a mul operation.
6939 *
6940 * @param lhs the first operand
6941 * @param rhs the second operand
6942 * @return the mul operation
6943 */
6944 public static MulOp mul(Value lhs, Value rhs) {
6945 return new MulOp(lhs, rhs);
6946 }
6947
6948 /**
6949 * Creates a div operation.
6950 *
6951 * @param lhs the first operand
6952 * @param rhs the second operand
6953 * @return the div operation
6954 */
6955 public static DivOp div(Value lhs, Value rhs) {
6956 return new DivOp(lhs, rhs);
6957 }
6958
6959 /**
6960 * Creates a mod operation.
6961 *
6962 * @param lhs the first operand
6963 * @param rhs the second operand
6964 * @return the mod operation
6965 */
6966 public static ModOp mod(Value lhs, Value rhs) {
6967 return new ModOp(lhs, rhs);
6968 }
6969
6970 /**
6971 * Creates a bitwise/logical or operation.
6972 *
6973 * @param lhs the first operand
6974 * @param rhs the second operand
6975 * @return the or operation
6976 */
6977 public static OrOp or(Value lhs, Value rhs) {
6978 return new OrOp(lhs, rhs);
6979 }
6980
6981 /**
6982 * Creates a bitwise/logical and operation.
6983 *
6984 * @param lhs the first operand
6985 * @param rhs the second operand
6986 * @return the and operation
6987 */
6988 public static AndOp and(Value lhs, Value rhs) {
6989 return new AndOp(lhs, rhs);
6990 }
6991
6992 /**
6993 * Creates a bitwise/logical xor operation.
6994 *
6995 * @param lhs the first operand
6996 * @param rhs the second operand
6997 * @return the xor operation
6998 */
6999 public static XorOp xor(Value lhs, Value rhs) {
7000 return new XorOp(lhs, rhs);
7001 }
7002
7003 /**
7004 * Creates a left shift operation.
7005 *
7006 * @param lhs the first operand
7007 * @param rhs the second operand
7008 * @return the left shift operation
7009 */
7010 public static LshlOp lshl(Value lhs, Value rhs) {
7011 return new LshlOp(lhs, rhs);
7012 }
7013
7014 /**
7015 * Creates a right shift operation.
7016 *
7017 * @param lhs the first operand
7018 * @param rhs the second operand
7019 * @return the right shift operation
7020 */
7021 public static AshrOp ashr(Value lhs, Value rhs) {
7022 return new AshrOp(lhs, rhs);
7023 }
7024
7025 /**
7026 * Creates an unsigned right shift operation.
7027 *
7028 * @param lhs the first operand
7029 * @param rhs the second operand
7030 * @return the unsigned right shift operation
7031 */
7032 public static LshrOp lshr(Value lhs, Value rhs) {
7033 return new LshrOp(lhs, rhs);
7034 }
7035
7036 /**
7037 * Creates a neg operation.
7038 *
7039 * @param v the operand
7040 * @return the neg operation
7041 */
7042 public static NegOp neg(Value v) {
7043 return new NegOp(v);
7044 }
7045
7046 /**
7047 * Creates a pos operation.
7048 *
7049 * @param v the operand
7050 * @return the pos operation
7051 */
7052 public static PosOp pos(Value v) {
7053 return new PosOp(v);
7054 }
7055
7056 /**
7057 * Creates a bitwise complement operation.
7058 *
7059 * @param v the operand
7060 * @return the bitwise complement operation
7061 */
7062 public static ComplOp compl(Value v) {
7063 return new ComplOp(v);
7064 }
7065
7066 /**
7067 * Creates a not operation.
7068 *
7069 * @param v the operand
7070 * @return the not operation
7071 */
7072 public static NotOp not(Value v) {
7073 return new NotOp(v);
7074 }
7075
7076 /**
7077 * Creates an equals comparison operation.
7078 *
7079 * @param lhs the first operand
7080 * @param rhs the second operand
7081 * @return the equals comparison operation
7082 */
7083 public static EqOp eq(Value lhs, Value rhs) {
7084 return new EqOp(lhs, rhs);
7085 }
7086
7087 /**
7088 * Creates a not equals comparison operation.
7089 *
7090 * @param lhs the first operand
7091 * @param rhs the second operand
7092 * @return the not equals comparison operation
7093 */
7094 public static NeqOp neq(Value lhs, Value rhs) {
7095 return new NeqOp(lhs, rhs);
7096 }
7097
7098 /**
7099 * Creates a greater than comparison operation.
7100 *
7101 * @param lhs the first operand
7102 * @param rhs the second operand
7103 * @return the greater than comparison operation
7104 */
7105 public static GtOp gt(Value lhs, Value rhs) {
7106 return new GtOp(lhs, rhs);
7107 }
7108
7109 /**
7110 * Creates a greater than or equals to comparison operation.
7111 *
7112 * @param lhs the first operand
7113 * @param rhs the second operand
7114 * @return the greater than or equals to comparison operation
7115 */
7116 public static GeOp ge(Value lhs, Value rhs) {
7117 return new GeOp(lhs, rhs);
7118 }
7119
7120 /**
7121 * Creates a less than comparison operation.
7122 *
7123 * @param lhs the first operand
7124 * @param rhs the second operand
7125 * @return the less than comparison operation
7126 */
7127 public static LtOp lt(Value lhs, Value rhs) {
7128 return new LtOp(lhs, rhs);
7129 }
7130
7131 /**
7132 * Creates a less than or equals to comparison operation.
7133 *
7134 * @param lhs the first operand
7135 * @param rhs the second operand
7136 * @return the less than or equals to comparison operation
7137 */
7138 public static LeOp le(Value lhs, Value rhs) {
7139 return new LeOp(lhs, rhs);
7140 }
7141
7142 /**
7143 * Creates a string concatenation operation.
7144 *
7145 * @param lhs the first operand
7146 * @param rhs the second operand
7147 * @return the string concatenation operation
7148 */
7149 public static ConcatOp concat(Value lhs, Value rhs) {
7150 return new ConcatOp(lhs, rhs);
7151 }
7152
7153 /**
7154 * Creates a continue operation.
7155 *
7156 * @return the continue operation
7157 */
7158 public static ContinueOp continue_() {
7159 return continue_(null);
7160 }
7161
7162 /**
7163 * Creates a continue operation.
7164 *
7165 * @param label the value associated with where to continue from
7166 * @return the continue operation
7167 */
7168 public static ContinueOp continue_(Value label) {
7169 return new ContinueOp(label);
7170 }
7171
7172 /**
7173 * Creates a break operation.
7174 *
7175 * @return the break operation
7176 */
7177 public static BreakOp break_() {
7178 return break_(null);
7179 }
7180
7181 /**
7182 * Creates a break operation.
7183 *
7184 * @param label the label identifier
7185 * @return the break operation
7186 */
7187 public static BreakOp break_(Value label) {
7188 return new BreakOp(label);
7189 }
7190
7191 /**
7192 * Creates a yield operation.
7193 *
7194 * @param operand the value to yield
7195 * @return the yield operation
7196 */
7197 public static YieldOp java_yield(Value operand) {
7198 return new YieldOp(operand);
7199 }
7200
7201 /**
7202 * Creates a block operation.
7203 *
7204 * @param body the statements body builder
7205 * @return the block operation
7206 */
7207 public static BlockOp block(Body.Builder body) {
7208 return new BlockOp(body);
7209 }
7210
7211 /**
7212 * Creates a synchronized operation.
7213 *
7214 * @param expr the expression body builder
7215 * @param blockBody the block body builder
7216 * @return the synchronized operation
7217 */
7218 public static SynchronizedOp synchronized_(Body.Builder expr, Body.Builder blockBody) {
7219 return new SynchronizedOp(expr, blockBody);
7220 }
7221
7222 /**
7223 * Creates a labeled operation.
7224 *
7225 * @param body the labeled body builder
7226 * @return the labeled operation
7227 */
7228 public static LabeledOp labeled(Body.Builder body) {
7229 return new LabeledOp(body);
7230 }
7231
7232 /**
7233 * Creates an if operation builder.
7234 *
7235 * @param connectedAncestorBody the nearest ancestor body builder to which body builders for this operation are
7236 * connected, or {@code null} if they are isolated
7237 * @return the if operation builder
7238 */
7239 public static IfOp.IfBuilder if_(Body.Builder connectedAncestorBody) {
7240 return new IfOp.IfBuilder(connectedAncestorBody);
7241 }
7242
7243 // Pairs of
7244 // predicate ()boolean, body ()void
7245 // And one optional body ()void at the end
7246
7247 /**
7248 * Creates an if operation.
7249 *
7250 * @param bodies the body builders for the predicate and action bodies
7251 * @return the if operation
7252 */
7253 public static IfOp if_(List<Body.Builder> bodies) {
7254 return new IfOp(bodies);
7255 }
7256
7257 /**
7258 * Creates a switch expression operation.
7259 * <p>
7260 * Case bodies are provided as pairs of bodies, where the first body of each pair is the predicate body and the
7261 * second is the corresponding action body. The result type of the operation will be derived from the yield type of
7262 * the first action body.
7263 *
7264 * @param target the switch target value
7265 * @param bodies the body builders for the predicate and action bodies
7266 * @return the switch expression operation
7267 */
7268 public static SwitchExpressionOp switchExpression(Value target, List<Body.Builder> bodies) {
7269 return new SwitchExpressionOp(null, target, bodies);
7270 }
7271
7272 /**
7273 * Creates a switch expression operation.
7274 * <p>
7275 * Case bodies are provided as pairs of bodies, where the first body of each pair is the predicate body and the
7276 * second is the corresponding action body.
7277 *
7278 * @param resultType the result type of the expression
7279 * @param target the switch target value
7280 * @param bodies the body builders for the predicate and action bodies
7281 * @return the switch expression operation
7282 */
7283 public static SwitchExpressionOp switchExpression(CodeType resultType, Value target,
7284 List<Body.Builder> bodies) {
7285 Objects.requireNonNull(resultType);
7286 return new SwitchExpressionOp(resultType, target, bodies);
7287 }
7288
7289 /**
7290 * Creates a switch statement operation.
7291 * <p>
7292 * Case bodies are provided as pairs of bodies, where the first body of each pair is the predicate body and the
7293 * second is the corresponding action body.
7294 *
7295 * @param target the switch target value
7296 * @param bodies the body builders for the predicate and action bodies
7297 * @return the switch statement operation
7298 */
7299 public static SwitchStatementOp switchStatement(Value target, List<Body.Builder> bodies) {
7300 return new SwitchStatementOp(target, bodies);
7301 }
7302
7303 /**
7304 * Creates a switch fallthrough operation.
7305 *
7306 * @return the switch fallthrough operation
7307 */
7308 public static SwitchFallthroughOp switchFallthroughOp() {
7309 return new SwitchFallthroughOp();
7310 }
7311
7312 /**
7313 * Creates a for operation builder.
7314 *
7315 * @param connectedAncestorBody the nearest ancestor body builder to which body builders for this operation are
7316 * connected, or {@code null} if they are isolated
7317 * @param initTypes the types of initialized variables
7318 * @return the for operation builder
7319 */
7320 public static ForOp.InitBuilder for_(Body.Builder connectedAncestorBody, CodeType... initTypes) {
7321 return for_(connectedAncestorBody, List.of(initTypes));
7322 }
7323
7324 /**
7325 * Creates a for operation builder.
7326 *
7327 * @param connectedAncestorBody the nearest ancestor body builder to which body builders for this operation are
7328 * connected, or {@code null} if they are isolated
7329 * @param initTypes the types of initialized variables
7330 * @return the for operation builder
7331 */
7332 public static ForOp.InitBuilder for_(Body.Builder connectedAncestorBody, List<? extends CodeType> initTypes) {
7333 return new ForOp.InitBuilder(connectedAncestorBody, initTypes);
7334 }
7335
7336
7337 /**
7338 * Creates a for operation.
7339 *
7340 * @param initBody the initialization body builder
7341 * @param condBody the predicate body builder
7342 * @param updateBody the update body builder
7343 * @param loopBody the loop body builder
7344 * @return the for operation
7345 */
7346 // initBody ()Tuple<Var<T1>, Var<T2>, ..., Var<TN>>, or initBody ()Var<T1>, or initBody ()void
7347 // condBody (Var<T1>, Var<T2>, ..., Var<TN>)boolean
7348 // updateBody (Var<T1>, Var<T2>, ..., Var<TN>)void
7349 // loopBody (Var<T1>, Var<T2>, ..., Var<TN>)void
7350 public static ForOp for_(Body.Builder initBody,
7351 Body.Builder condBody,
7352 Body.Builder updateBody,
7353 Body.Builder loopBody) {
7354 return new ForOp(initBody, condBody, updateBody, loopBody);
7355 }
7356
7357 /**
7358 * Creates an enhanced for operation builder.
7359 *
7360 * @param connectedAncestorBody the nearest ancestor body builder to which body builders for this operation are
7361 * connected, or {@code null} if they are isolated
7362 * @param iterableType the iterable type
7363 * @param elementType the element type
7364 * @return the enhanced for operation builder
7365 */
7366 public static EnhancedForOp.ExpressionBuilder enhancedFor(Body.Builder connectedAncestorBody,
7367 CodeType iterableType, CodeType elementType) {
7368 return new EnhancedForOp.ExpressionBuilder(connectedAncestorBody, iterableType, elementType);
7369 }
7370
7371 /**
7372 * Creates an enhanced for operation.
7373 *
7374 * @param exprBody the expression body builder
7375 * @param initBody the initialization body builder
7376 * @param loopBody the loop body builder
7377 * @return the enhanced for operation
7378 */
7379 // expression ()I<E>
7380 // init (E )Var<T>
7381 // body (Var<T> )void
7382 public static EnhancedForOp enhancedFor(Body.Builder exprBody,
7383 Body.Builder initBody,
7384 Body.Builder loopBody) {
7385 return new EnhancedForOp(exprBody, initBody, loopBody);
7386 }
7387
7388 /**
7389 * Creates a while operation builder.
7390 *
7391 * @param connectedAncestorBody the nearest ancestor body builder to which body builders for this operation are
7392 * connected, or {@code null} if they are isolated
7393 * @return the while operation builder
7394 */
7395 public static WhileOp.PredicateBuilder while_(Body.Builder connectedAncestorBody) {
7396 return new WhileOp.PredicateBuilder(connectedAncestorBody);
7397 }
7398
7399 /**
7400 * Creates a while operation.
7401 *
7402 * @param predicateBody the predicate body builder
7403 * @param loopBody the loop body builder
7404 * @return the while operation
7405 */
7406 // predicateBody, ()boolean, may be null for predicateBody returning true
7407 // loopBody, ()void
7408 public static WhileOp while_(Body.Builder predicateBody, Body.Builder loopBody) {
7409 return new WhileOp(predicateBody, loopBody);
7410 }
7411
7412 /**
7413 * Creates a do operation builder.
7414 *
7415 * @param connectedAncestorBody the nearest ancestor body builder to which body builders for this operation are
7416 * connected, or {@code null} if they are isolated
7417 * @return the do operation builder
7418 */
7419 public static DoWhileOp.BodyBuilder doWhile(Body.Builder connectedAncestorBody) {
7420 return new DoWhileOp.BodyBuilder(connectedAncestorBody);
7421 }
7422
7423 /**
7424 * Creates a do operation.
7425 *
7426 * @param loopBody the loop body builder
7427 * @param predicateBody the predicate body builder
7428 * @return the do operation
7429 */
7430 public static DoWhileOp doWhile(Body.Builder loopBody, Body.Builder predicateBody) {
7431 return new DoWhileOp(loopBody, predicateBody);
7432 }
7433
7434 /**
7435 * Creates a conditional-and operation builder.
7436 *
7437 * @param connectedAncestorBody the nearest ancestor body builder to which body builders for this operation are
7438 * connected, or {@code null} if they are isolated
7439 * @param lhs a consumer that populates the first predicate body
7440 * @param rhs a consumer that populates the second predicate body
7441 * @return the conditional-and operation builder
7442 */
7443 public static ConditionalAndOp.Builder conditionalAnd(Body.Builder connectedAncestorBody,
7444 Consumer<Block.Builder> lhs, Consumer<Block.Builder> rhs) {
7445 return new ConditionalAndOp.Builder(connectedAncestorBody, lhs, rhs);
7446 }
7447
7448 /**
7449 * Creates a conditional-or operation builder.
7450 *
7451 * @param connectedAncestorBody the nearest ancestor body builder to which body builders for this operation are
7452 * connected, or {@code null} if they are isolated
7453 * @param lhs a consumer that populates the first predicate body
7454 * @param rhs a consumer that populates the second predicate body
7455 * @return the conditional-or operation builder
7456 */
7457 public static ConditionalOrOp.Builder conditionalOr(Body.Builder connectedAncestorBody,
7458 Consumer<Block.Builder> lhs, Consumer<Block.Builder> rhs) {
7459 return new ConditionalOrOp.Builder(connectedAncestorBody, lhs, rhs);
7460 }
7461
7462 /**
7463 * Creates a conditional-and operation
7464 *
7465 * @param bodies the body builders for the predicate bodies
7466 * @return the conditional-and operation
7467 */
7468 // predicates, ()boolean
7469 public static ConditionalAndOp conditionalAnd(List<Body.Builder> bodies) {
7470 return new ConditionalAndOp(bodies);
7471 }
7472
7473 /**
7474 * Creates a conditional-or operation
7475 *
7476 * @param bodies the body builders for the predicate bodies
7477 * @return the conditional-or operation
7478 */
7479 // predicates, ()boolean
7480 public static ConditionalOrOp conditionalOr(List<Body.Builder> bodies) {
7481 return new ConditionalOrOp(bodies);
7482 }
7483
7484 /**
7485 * Creates a conditional operation
7486 *
7487 * @param expressionType the result type of the expression
7488 * @param predicateBody the body builder for the predicate body
7489 * @param trueBody the body builder for the true body
7490 * @param falseBody the body builder for the false body
7491 * @return the conditional operation
7492 */
7493 public static ConditionalExpressionOp conditionalExpression(CodeType expressionType,
7494 Body.Builder predicateBody,
7495 Body.Builder trueBody,
7496 Body.Builder falseBody) {
7497 Objects.requireNonNull(expressionType);
7498 return new ConditionalExpressionOp(expressionType, predicateBody, trueBody, falseBody);
7499 }
7500
7501 /**
7502 * Creates a conditional operation
7503 * <p>
7504 * The result type of the operation will be derived from the yield type of the true body.
7505 *
7506 * @param predicateBody the body builder for the predicate body
7507 * @param trueBody the body builder for the true body
7508 * @param falseBody the body builder for the false body
7509 * @return the conditional operation
7510 */
7511 public static ConditionalExpressionOp conditionalExpression(Body.Builder predicateBody,
7512 Body.Builder trueBody,
7513 Body.Builder falseBody) {
7514 return new ConditionalExpressionOp(null, predicateBody, trueBody, falseBody);
7515 }
7516
7517 /**
7518 * Creates try operation builder.
7519 *
7520 * @param connectedAncestorBody the nearest ancestor body builder to which body builders for this operation are
7521 * connected, or {@code null} if they are isolated
7522 * @param c a consumer that populates the try body
7523 * @return the try operation builder
7524 */
7525 public static TryOp.CatchBuilder try_(Body.Builder connectedAncestorBody, Consumer<Block.Builder> c) {
7526 Body.Builder _try = Body.Builder.of(connectedAncestorBody, CoreType.FUNCTION_TYPE_VOID);
7527 c.accept(_try.entryBlock());
7528 return new TryOp.CatchBuilder(connectedAncestorBody, List.of(), _try);
7529 }
7530
7531 /**
7532 * Creates try-with-resources operation builder.
7533 *
7534 * @param connectedAncestorBody the nearest ancestor body builder to which body builders for this operation are
7535 * connected, or {@code null} if they are isolated
7536 * @return the try-with-resources operation builder
7537 */
7538 public static TryOp.BodyBuilder tryWithResources(Body.Builder connectedAncestorBody) {
7539 return new TryOp.BodyBuilder(connectedAncestorBody);
7540 }
7541
7542 // resources: ()T1, (T1)T2, ..., (T1, T2, ..., T{N-1})TN, or empty
7543 // Ti is Ri for a resource expression, or Var<Ri> for a resource declaration
7544 // try (T1, T2, ..., TN)void, or try ()void
7545 // catch (E )void, where E <: Throwable
7546 // finally ()void, or null
7547
7548 /**
7549 * Creates a try or try-with-resources operation.
7550 *
7551 * @param resourceBodies the resources body builders
7552 * @param body the try body builder
7553 * @param catchBodies the catch body builders
7554 * @param finallyBody the finalizer body builder, may be {@code null}
7555 * @return the try or try-with-resources operation
7556 */
7557 public static TryOp try_(List<Body.Builder> resourceBodies,
7558 Body.Builder body,
7559 List<Body.Builder> catchBodies,
7560 Body.Builder finallyBody) {
7561 return try_(resourceBodies, body, null, catchBodies, finallyBody);
7562 }
7563
7564 /**
7565 * Creates a try or try-with-resources operation.
7566 *
7567 * @param resourceBodies the resources body builders
7568 * @param body the try body builder
7569 * @param catchTypes the explicit catch types, may be {@code null}
7570 * @param catchBodies the catch body builders
7571 * @param finallyBody the finalizer body builder, may be {@code null}
7572 * @return the try or try-with-resources operation
7573 */
7574 public static TryOp try_(List<Body.Builder> resourceBodies,
7575 Body.Builder body,
7576 List<CodeType> catchTypes,
7577 List<Body.Builder> catchBodies,
7578 Body.Builder finallyBody) {
7579 return new TryOp(resourceBodies, body, catchTypes, catchBodies, finallyBody);
7580 }
7581
7582 //
7583 // Patterns
7584
7585 /**
7586 * Creates a pattern match operation.
7587 *
7588 * @param target the target value
7589 * @param patternBody the pattern body builder
7590 * @param matchBody the match body builder
7591 * @return the pattern match operation
7592 */
7593 public static PatternOps.MatchOp match(Value target,
7594 Body.Builder patternBody, Body.Builder matchBody) {
7595 return new PatternOps.MatchOp(target, patternBody, matchBody);
7596 }
7597
7598 /**
7599 * Creates a pattern binding operation.
7600 *
7601 * @param type the type of value to be bound
7602 * @param bindingName the binding name
7603 * @return the pattern binding operation
7604 */
7605 public static PatternOps.TypePatternOp typePattern(CodeType type, String bindingName) {
7606 return new PatternOps.TypePatternOp(type, bindingName);
7607 }
7608
7609 /**
7610 * Creates a record pattern operation.
7611 *
7612 * @param recordRef the record reference
7613 * @param nestedPatterns the nested pattern values
7614 * @return the record pattern operation
7615 */
7616 public static PatternOps.RecordPatternOp recordPattern(RecordTypeRef recordRef, Value... nestedPatterns) {
7617 return recordPattern(recordRef, List.of(nestedPatterns));
7618 }
7619
7620 /**
7621 * Creates a record pattern operation.
7622 *
7623 * @param recordRef the record reference
7624 * @param nestedPatterns the nested pattern values
7625 * @return the record pattern operation
7626 */
7627 public static PatternOps.RecordPatternOp recordPattern(RecordTypeRef recordRef, List<Value> nestedPatterns) {
7628 return new PatternOps.RecordPatternOp(recordRef, nestedPatterns);
7629 }
7630
7631 /**
7632 * Creates a match-all pattern operation.
7633 *
7634 * @return a match-all pattern
7635 */
7636 public static PatternOps.MatchAllPatternOp matchAllPattern() {
7637 return new PatternOps.MatchAllPatternOp();
7638 }
7639 }