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.internal;
  27 
  28 import com.sun.source.tree.LambdaExpressionTree;
  29 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
  30 import com.sun.tools.javac.code.Kinds.Kind;
  31 import com.sun.tools.javac.code.Symbol;
  32 import com.sun.tools.javac.code.Symbol.ClassSymbol;
  33 import com.sun.tools.javac.code.Symbol.MethodSymbol;
  34 import com.sun.tools.javac.code.Symbol.VarSymbol;
  35 import com.sun.tools.javac.code.Symtab;
  36 import com.sun.tools.javac.code.Type;
  37 import com.sun.tools.javac.code.Type.ArrayType;
  38 import com.sun.tools.javac.code.Type.CapturedType;
  39 import com.sun.tools.javac.code.Type.IntersectionClassType;
  40 import com.sun.tools.javac.code.Type.MethodType;
  41 import com.sun.tools.javac.code.Type.StructuralTypeMapping;
  42 import com.sun.tools.javac.code.Type.UnionClassType;
  43 import com.sun.tools.javac.code.TypeTag;
  44 import com.sun.tools.javac.code.Types;
  45 import com.sun.tools.javac.comp.Attr;
  46 import com.sun.tools.javac.comp.AttrContext;
  47 import com.sun.tools.javac.comp.CaptureScanner;
  48 import com.sun.tools.javac.comp.DeferredAttr.FilterScanner;
  49 import com.sun.tools.javac.comp.Env;
  50 import com.sun.tools.javac.comp.Flow;
  51 import com.sun.tools.javac.comp.Lower;
  52 import com.sun.tools.javac.comp.CodeReflectionTransformer;
  53 import com.sun.tools.javac.comp.TypeEnvs;
  54 import com.sun.tools.javac.file.PathFileObject;
  55 import com.sun.tools.javac.jvm.ByteCodes;
  56 import com.sun.tools.javac.jvm.Gen;
  57 import com.sun.tools.javac.resources.CompilerProperties.*;
  58 import com.sun.tools.javac.tree.JCTree;
  59 import com.sun.tools.javac.tree.JCTree.JCAnnotation;
  60 import com.sun.tools.javac.tree.JCTree.JCArrayAccess;
  61 import com.sun.tools.javac.tree.JCTree.JCAssign;
  62 import com.sun.tools.javac.tree.JCTree.JCBinary;
  63 import com.sun.tools.javac.tree.JCTree.JCBlock;
  64 import com.sun.tools.javac.tree.JCTree.JCCaseLabel;
  65 import com.sun.tools.javac.tree.JCTree.JCClassDecl;
  66 import com.sun.tools.javac.tree.JCTree.JCConstantCaseLabel;
  67 import com.sun.tools.javac.tree.JCTree.JCDefaultCaseLabel;
  68 import com.sun.tools.javac.tree.JCTree.JCExpression;
  69 import com.sun.tools.javac.tree.JCTree.JCExpressionStatement;
  70 import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
  71 import com.sun.tools.javac.tree.JCTree.JCFunctionalExpression;
  72 import com.sun.tools.javac.tree.JCTree.JCFunctionalExpression.CodeReflectionInfo;
  73 import com.sun.tools.javac.tree.JCTree.JCIdent;
  74 import com.sun.tools.javac.tree.JCTree.JCLambda;
  75 import com.sun.tools.javac.tree.JCTree.JCLiteral;
  76 import com.sun.tools.javac.tree.JCTree.JCMemberReference;
  77 import com.sun.tools.javac.tree.JCTree.JCMemberReference.ReferenceKind;
  78 import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
  79 import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
  80 import com.sun.tools.javac.tree.JCTree.JCModuleDecl;
  81 import com.sun.tools.javac.tree.JCTree.JCNewArray;
  82 import com.sun.tools.javac.tree.JCTree.JCNewClass;
  83 import com.sun.tools.javac.tree.JCTree.JCReturn;
  84 import com.sun.tools.javac.tree.JCTree.JCStatement;
  85 import com.sun.tools.javac.tree.JCTree.JCTypeCast;
  86 import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
  87 import com.sun.tools.javac.tree.JCTree.JCAssert;
  88 import com.sun.tools.javac.tree.JCTree.Tag;
  89 import com.sun.tools.javac.tree.TreeInfo;
  90 import com.sun.tools.javac.tree.TreeMaker;
  91 import com.sun.tools.javac.tree.TreeScanner;
  92 import com.sun.tools.javac.util.Assert;
  93 import com.sun.tools.javac.util.Constants;
  94 import com.sun.tools.javac.util.Context;
  95 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  96 import com.sun.tools.javac.util.ListBuffer;
  97 import com.sun.tools.javac.util.Log;
  98 import com.sun.tools.javac.util.Name;
  99 import com.sun.tools.javac.util.Names;
 100 import com.sun.tools.javac.util.Options;
 101 import jdk.incubator.code.*;
 102 import jdk.incubator.code.extern.DialectFactory;
 103 import jdk.incubator.code.dialect.core.*;
 104 import jdk.incubator.code.dialect.java.*;
 105 import jdk.incubator.code.dialect.java.WildcardType.BoundKind;
 106 
 107 import javax.lang.model.element.Modifier;
 108 import javax.tools.JavaFileObject;
 109 import java.lang.constant.ClassDesc;
 110 import java.util.*;
 111 import java.util.List;
 112 import java.util.function.Function;
 113 import java.util.function.Supplier;
 114 
 115 import static com.sun.tools.javac.code.Flags.*;
 116 import static com.sun.tools.javac.code.Kinds.Kind.MTH;
 117 import static com.sun.tools.javac.code.Kinds.Kind.TYP;
 118 import static com.sun.tools.javac.code.Kinds.Kind.VAR;
 119 import static com.sun.tools.javac.code.TypeTag.BOT;
 120 import static com.sun.tools.javac.code.TypeTag.CLASS;
 121 import static com.sun.tools.javac.code.TypeTag.INT;
 122 import static com.sun.tools.javac.code.TypeTag.METHOD;
 123 import static com.sun.tools.javac.code.TypeTag.NONE;
 124 import static com.sun.tools.javac.main.Option.G_CUSTOM;
 125 
 126 import java.io.IOException;
 127 import java.io.OutputStream;
 128 import java.lang.classfile.ClassFile;
 129 import java.lang.classfile.ClassTransform;
 130 import java.lang.classfile.attribute.InnerClassInfo;
 131 import java.lang.classfile.attribute.InnerClassesAttribute;
 132 import java.lang.classfile.attribute.NestHostAttribute;
 133 import java.lang.invoke.MethodHandles;
 134 import javax.tools.JavaFileManager;
 135 import javax.tools.StandardLocation;
 136 import jdk.incubator.code.bytecode.BytecodeGenerator;
 137 
 138 /**
 139  * This a tree translator that adds the code model to all method declaration marked
 140  * with the {@code Reflect} annotation. The model is expressed using the code
 141  * reflection API (see {@code jdk.incubator.code}).
 142  */
 143 public class ReflectMethods extends TreeTranslatorPrev {
 144     protected static final Context.Key<ReflectMethods> reflectMethodsKey = new Context.Key<>();
 145 
 146     public static ReflectMethods instance(Context context) {
 147         ReflectMethods instance = context.get(reflectMethodsKey);
 148         if (instance == null)
 149             instance = new ReflectMethods(context);
 150         return instance;
 151     }
 152 
 153     private final Types types;
 154     private final Names names;
 155     private final Symtab syms;
 156     private final Gen gen;
 157     private final Log log;
 158     private final Lower lower;
 159     private final TypeEnvs typeEnvs;
 160     private final Attr attr;
 161     private final Flow flow;
 162     private final CodeReflectionSymbols crSyms;
 163     private final boolean dumpIR;
 164     private final boolean lineDebugInfo;
 165     private final boolean reflectAll;
 166 
 167     private TreeMaker make;
 168     private SequencedMap<Op, Name> ops;
 169     private Symbol.ClassSymbol currentClassSym;
 170     private boolean codeReflectionEnabled = false;
 171     private final Map<Symbol, List<Symbol>> localCaptures = new HashMap<>();
 172 
 173     @SuppressWarnings("this-escape")
 174     protected ReflectMethods(Context context) {
 175         context.put(reflectMethodsKey, this);
 176         Options options = Options.instance(context);
 177         dumpIR = options.isSet("dumpIR");
 178         lineDebugInfo =
 179                 options.isUnset(G_CUSTOM) ||
 180                         options.isSet(G_CUSTOM, "lines");
 181         reflectAll = options.isSet("reflectAll");
 182         names = Names.instance(context);
 183         syms = Symtab.instance(context);
 184         types = Types.instance(context);
 185         gen = Gen.instance(context);
 186         log = Log.instance(context);
 187         lower = Lower.instance(context);
 188         typeEnvs = TypeEnvs.instance(context);
 189         attr = Attr.instance(context);
 190         flow = Flow.instance(context);
 191         crSyms = CodeReflectionSymbols.instance(context);
 192     }
 193 
 194     @Override
 195     public void visitVarDef(JCVariableDecl tree) {
 196         boolean prevCodeReflectionEnabled = codeReflectionEnabled;
 197         try {
 198             codeReflectionEnabled = codeReflectionEnabled ||
 199                     tree.sym.attribute(crSyms.codeReflectionType.tsym) != null;
 200             super.visitVarDef(tree);
 201         } finally {
 202             codeReflectionEnabled = prevCodeReflectionEnabled;
 203         }
 204     }
 205 
 206     boolean isInsideInnerOrLocalClass() {
 207         return currentClassSym.type.getEnclosingType().hasTag(CLASS) ||
 208                 currentClassSym.isDirectlyOrIndirectlyLocal();
 209     }
 210 
 211     @Override
 212     public void visitMethodDef(JCMethodDecl tree) {
 213         boolean isReflectable = !tree.sym.isConstructor() && isReflectable(tree);
 214         if (isReflectable) {
 215             if (isInsideInnerOrLocalClass()) {
 216                 // Reflectable methods in local classes are not supported
 217                 log.warning(tree, Warnings.ReflectableMethodInnerClass(currentClassSym.enclClass()));
 218                 super.visitMethodDef(tree);
 219                 return;
 220             } else {
 221                 // if the method is annotated, scan it
 222                 BodyScanner bodyScanner = new BodyScanner(tree);
 223                 CoreOp.FuncOp funcOp = bodyScanner.scanMethod();
 224                 if (dumpIR) {
 225                     // dump the method IR if requested
 226                     log.note(Notes.ReflectableMethodIrDump(tree.sym.enclClass(), tree.sym, funcOp.toText()));
 227                 }
 228                 if (ops == null) ops = new LinkedHashMap<>();
 229                 ops.put(funcOp, methodName(symbolToErasedMethodRef(tree.sym)));
 230             }
 231         }
 232         boolean prevCodeReflectionEnabled = codeReflectionEnabled;
 233         try {
 234             codeReflectionEnabled = isReflectable;
 235             super.visitMethodDef(tree);
 236         } finally {
 237             codeReflectionEnabled = prevCodeReflectionEnabled;
 238         }
 239     }
 240 
 241     @Override
 242     public void visitModuleDef(JCModuleDecl that) {
 243         // do nothing
 244     }
 245 
 246     @Override
 247     public void visitClassDef(JCClassDecl tree) {
 248         SequencedMap<Op, Name> prevOps = ops;
 249         Symbol.ClassSymbol prevClassSym = currentClassSym;
 250         JavaFileObject prev = log.useSource(tree.sym.sourcefile);
 251         computeCapturesIfNeeded(tree);
 252         try {
 253             currentClassSym = tree.sym;
 254             ops = null;
 255             super.visitClassDef(tree);
 256             if (ops != null) {
 257                 tree = new JCReflectMethodsClassDecl(tree, ops);
 258                 // store the tree for later phases
 259                 Env<AttrContext> classEnv = typeEnvs.get(tree.sym);
 260                 classEnv.tree = tree;
 261                 classEnv.enclClass = tree;
 262             }
 263         } finally {
 264             ops = prevOps;
 265             currentClassSym = prevClassSym;
 266             result = tree;
 267             log.useSource(prev);
 268         }
 269     }
 270 
 271     void computeCapturesIfNeeded(JCClassDecl tree) {
 272         if (tree.sym.isDirectlyOrIndirectlyLocal() && !localCaptures.containsKey(tree.sym)) {
 273             // we need to keep track of captured locals using same strategy as Lower
 274             class FreeVarScanner extends Lower.FreeVarCollector {
 275                 FreeVarScanner() {
 276                     lower.super(tree);
 277                 }
 278 
 279                 @Override
 280                 protected void addFreeVars(ClassSymbol c) {
 281                     localCaptures.getOrDefault(c, List.of())
 282                             .forEach(s -> addFreeVar((VarSymbol)s));
 283                 }
 284             }
 285             FreeVarScanner fvs = new FreeVarScanner();
 286             localCaptures.put(tree.sym, List.copyOf(fvs.analyzeCaptures()));
 287         }
 288     }
 289 
 290     @Override
 291     public void visitLambda(JCLambda tree) {
 292         boolean isReflectable = isReflectable(tree);
 293         if (isReflectable) {
 294             if (isInsideInnerOrLocalClass()) {
 295                 // Reflectable lambdas in local classes are not supported
 296                 log.warning(tree, Warnings.ReflectableLambdaInnerClass(currentClassSym.enclClass()));
 297                 super.visitLambda(tree);
 298                 return;
 299             }
 300 
 301             // quoted lambda - scan it
 302             BodyScanner bodyScanner = new BodyScanner(tree);
 303             CoreOp.FuncOp funcOp = bodyScanner.scanLambda();
 304             if (dumpIR) {
 305                 // dump the method IR if requested
 306                 log.note(Notes.ReflectableLambdaIrDump(funcOp.toText()));
 307             }
 308             tree.codeReflectionInfo = reflectLambda(funcOp);
 309         }
 310         boolean prevCodeReflectionEnabled = codeReflectionEnabled;
 311         try {
 312             codeReflectionEnabled = isReflectable;
 313             super.visitLambda(tree);
 314         } finally {
 315             codeReflectionEnabled = prevCodeReflectionEnabled;
 316         }
 317     }
 318 
 319     @Override
 320     public void visitReference(JCMemberReference tree) {
 321         MemberReferenceToLambda memberReferenceToLambda = new MemberReferenceToLambda(tree, currentClassSym);
 322         JCLambda lambdaTree = memberReferenceToLambda.lambda();
 323 
 324         if (isReflectable(tree)) {
 325             if (isInsideInnerOrLocalClass()) {
 326                 // Reflectable method references in local classes are not supported
 327                 log.warning(tree, Warnings.ReflectableMrefInnerClass(currentClassSym.enclClass()));
 328                 super.visitReference(tree);
 329                 return;
 330             }
 331 
 332             // quoted lambda - scan it
 333             BodyScanner bodyScanner = new BodyScanner(lambdaTree);
 334             CoreOp.FuncOp funcOp = bodyScanner.scanLambda();
 335             if (dumpIR) {
 336                 // dump the method IR if requested
 337                 log.note(Notes.ReflectableMrefIrDump(funcOp.toText()));
 338             }
 339             tree.codeReflectionInfo = reflectLambda(funcOp);
 340         }
 341         super.visitReference(tree);
 342     }
 343 
 344     CodeReflectionInfo reflectLambda(Op op) {
 345         if (ops == null) ops = new LinkedHashMap<>();
 346         var snapshot = ops;
 347         return new CodeReflectionInfo(name -> snapshot.put(op, names.fromString("op$").append(name)), crSyms.reflectableLambdaMetafactory);
 348     }
 349 
 350     Name methodName(MethodRef method) {
 351         char[] sigCh = method.toString().toCharArray();
 352         for (int i = 0; i < sigCh.length; i++) {
 353             switch (sigCh[i]) {
 354                 case '.', ';', '[', '/' -> sigCh[i] = '$';
 355             }
 356         }
 357         return names.fromChars(sigCh, 0, sigCh.length);
 358     }
 359 
 360     // @@@ Retain enum for when we might add another storage to test
 361     // and compare
 362     private enum CodeModelStorageOption {
 363         CODE_BUILDER;
 364 
 365         public static CodeModelStorageOption parse(String s) {
 366             if (s == null) {
 367                 return CodeModelStorageOption.CODE_BUILDER;
 368             }
 369             return CodeModelStorageOption.valueOf(s);
 370         }
 371     }
 372 
 373     public JCTree translateTopLevelClass(JCTree cdef, TreeMaker make) {
 374         // note that this method does NOT support recursion.
 375         this.make = make;
 376         return translate(cdef);
 377     }
 378 
 379     public CoreOp.FuncOp getMethodBody(Symbol.ClassSymbol classSym, JCMethodDecl methodDecl, JCBlock attributedBody, TreeMaker make) {
 380         // if the method is annotated, scan it
 381         // Called from JavacElements::getBody
 382         try {
 383             this.make = make;
 384             currentClassSym = classSym;
 385             // same checks as in ReflectMethods::visitMethodDef
 386             boolean isReflectable = !methodDecl.sym.isConstructor() && isReflectable(methodDecl);
 387             if (isReflectable && !isInsideInnerOrLocalClass()) {
 388                 BodyScanner bodyScanner = new BodyScanner(methodDecl);
 389                 return bodyScanner.scanMethod(attributedBody);
 390             } else {
 391                 return null;
 392             }
 393         } finally {
 394             currentClassSym = null;
 395             this.make = null;
 396         }
 397     }
 398 
 399     static class BodyStack {
 400         final BodyStack parent;
 401 
 402         // Tree associated with body
 403         final JCTree tree;
 404 
 405         // Body to add blocks
 406         final Body.Builder body;
 407         // Current block to add operations
 408         Block.Builder block;
 409 
 410         // Map of symbols (method arguments and local variables) to varOp or local constant initializer values
 411         final Map<Symbol, Value> localToOp;
 412 
 413         // Label
 414         Map.Entry<String, Op.Result> label;
 415 
 416         BodyStack(BodyStack parent, JCTree tree, FunctionType bodySignature) {
 417             this.parent = parent;
 418 
 419             this.tree = tree;
 420 
 421             this.body = Body.Builder.of(parent != null ? parent.body : null, bodySignature);
 422             this.block = body.entryBlock();
 423 
 424             this.localToOp = new LinkedHashMap<>(); // order is important for captured values
 425         }
 426 
 427         public void setLabel(String labelName, Op.Result labelValue) {
 428             if (label != null) {
 429                 throw new IllegalStateException("Label already defined: " + labelName);
 430             }
 431             label = Map.entry(labelName, labelValue);
 432         }
 433     }
 434 
 435     class BodyScanner extends TreeScannerPrev {
 436         private final JCTree tree;
 437         private final Name name;
 438         private final BodyStack top;
 439         private BodyStack stack;
 440         private Op lastOp;
 441         private Value result;
 442         private Type pt = Type.noType;
 443         private final boolean isLambdaReflectable;
 444         private Type bodyTarget;
 445 
 446         BodyScanner(JCMethodDecl tree) {
 447             this.tree = tree;
 448             this.name = tree.name;
 449             this.isLambdaReflectable = false;
 450 
 451             List<CodeType> parameters = new ArrayList<>();
 452             int blockArgOffset = 0;
 453             // Instance methods model "this" as an additional argument occurring
 454             // before all other arguments.
 455             // @@@ Inner classes.
 456             // We need to capture all "this", in nested order, as arguments.
 457             if (!tree.getModifiers().getFlags().contains(Modifier.STATIC)) {
 458                 parameters.add(typeToCodeType(tree.sym.owner.type));
 459                 blockArgOffset++;
 460             }
 461             tree.sym.type.getParameterTypes().stream().map(ReflectMethods.this::typeToCodeType).forEach(parameters::add);
 462 
 463             FunctionType bodySignature = CoreType.functionType(
 464                     typeToCodeType(tree.sym.type.getReturnType()), parameters);
 465 
 466             this.stack = this.top = new BodyStack(null, tree.body, bodySignature);
 467 
 468             // @@@ this as local variable? (it can never be stored to)
 469             for (int i = 0 ; i < tree.params.size() ; i++) {
 470                 Op.Result paramOp = append(CoreOp.var(
 471                         tree.params.get(i).name.toString(),
 472                         top.block.parameters().get(blockArgOffset + i)));
 473                 top.localToOp.put(tree.params.get(i).sym, paramOp);
 474             }
 475 
 476             bodyTarget = tree.sym.type.getReturnType();
 477         }
 478 
 479         BodyScanner(JCLambda tree) {
 480             this.tree = tree;
 481             this.name = names.fromString("quotedLambda");
 482             this.isLambdaReflectable = true;
 483 
 484             ReflectableLambdaCaptureScanner lambdaCaptureScanner =
 485                     new ReflectableLambdaCaptureScanner(tree);
 486 
 487             List<VarSymbol> capturedSymbols = lambdaCaptureScanner.analyzeCaptures();
 488             int blockParamOffset = 0;
 489 
 490             ListBuffer<Type> capturedTypes = new ListBuffer<>();
 491             if (lambdaCaptureScanner.capturesThis) {
 492                 capturedTypes.add(currentClassSym.type);
 493                 blockParamOffset++;
 494             }
 495             for (Symbol s : capturedSymbols) {
 496                 capturedTypes.add(s.type);
 497             }
 498 
 499             FunctionType mtDesc = CoreType.functionType(CoreOp.QuotedOp.QUOTED_OP_TYPE,
 500                     capturedTypes.toList().map(ReflectMethods.this::typeToCodeType));
 501 
 502             this.stack = this.top = new BodyStack(null, tree.body, mtDesc);
 503 
 504             // add captured variables mappings
 505             for (int i = 0 ; i < capturedSymbols.size() ; i++) {
 506                 Symbol capturedSymbol = capturedSymbols.get(i);
 507                 var capturedArg = top.block.parameters().get(blockParamOffset + i);
 508                 top.localToOp.put(capturedSymbol,
 509                         append(CoreOp.var(capturedSymbol.name.toString(), capturedArg)));
 510             }
 511 
 512             // add captured constant mappings
 513             for (Map.Entry<Symbol, Object> constantCapture : lambdaCaptureScanner.constantCaptures.entrySet()) {
 514                 Symbol capturedSymbol = constantCapture.getKey();
 515                 top.localToOp.put(capturedSymbol,
 516                         append(CoreOp.constant(typeToCodeType(capturedSymbol.type),
 517                                 constantCapture.getValue())));
 518             }
 519 
 520             bodyTarget = tree.target.getReturnType();
 521         }
 522 
 523         /**
 524          * Compute the set of local variables captured by a reflectable lambda expression.
 525          * Inspired from LambdaToMethod's LambdaCaptureScanner.
 526          */
 527         class ReflectableLambdaCaptureScanner extends CaptureScanner {
 528             boolean capturesThis;
 529             Set<ClassSymbol> seenClasses = new HashSet<>();
 530             Map<Symbol, Object> constantCaptures = new LinkedHashMap<>();
 531 
 532             ReflectableLambdaCaptureScanner(JCLambda ownerTree) {
 533                 super(ownerTree);
 534             }
 535 
 536             @Override
 537             public void visitClassDef(JCClassDecl tree) {
 538                 computeCapturesIfNeeded(tree);
 539                 seenClasses.add(tree.sym);
 540                 super.visitClassDef(tree);
 541             }
 542 
 543             @Override
 544             public void visitIdent(JCIdent tree) {
 545                 if (!tree.sym.isStatic() &&
 546                         tree.sym.owner.kind == TYP &&
 547                         (tree.sym.kind == VAR || tree.sym.kind == MTH) &&
 548                         !seenClasses.contains(tree.sym.owner)) {
 549                     // a reference to an enclosing field or method, we need to capture 'this'
 550                     capturesThis = true;
 551                 } else if (tree.sym instanceof VarSymbol vsym &&
 552                         vsym.getConstValue() != null &&
 553                         vsym.owner.kind == MTH &&
 554                         !isVarSeen(vsym)) {
 555                     // record the constant value associated with this
 556                     constantCaptures.put(tree.sym, vsym.getConstValue());
 557                 } else {
 558                     // might be a local capture
 559                     super.visitIdent(tree);
 560                 }
 561             }
 562 
 563             @Override
 564             public void visitSelect(JCFieldAccess tree) {
 565                 if (tree.sym.kind == VAR &&
 566                         (tree.sym.name == names._this ||
 567                                 tree.sym.name == names._super) &&
 568                         !seenClasses.contains(tree.sym.type.tsym)) {
 569                     capturesThis = true;
 570                 }
 571                 super.visitSelect(tree);
 572             }
 573 
 574             @Override
 575             public void visitNewClass(JCNewClass tree) {
 576                 super.visitNewClass(tree); // this might scan an anon class def, so we need to do that first
 577                 if (tree.type.tsym.isDirectlyOrIndirectlyLocal()) {
 578                     for (Symbol c : localCaptures.get(tree.type.tsym)) {
 579                         addFreeVar((VarSymbol) c);
 580                     }
 581                 }
 582                 if (tree.encl == null && tree.type.tsym.hasOuterInstance()) {
 583                     capturesThis = true;
 584                 }
 585             }
 586 
 587             @Override
 588             public void visitAnnotation(JCAnnotation tree) {
 589                 // do nothing (annotation values look like captured instance fields)
 590             }
 591         }
 592 
 593         void pushBody(JCTree tree, FunctionType bodySignature) {
 594             stack = new BodyStack(stack, tree, bodySignature);
 595             lastOp = null; // reset
 596         }
 597 
 598         void popBody() {
 599             stack = stack.parent;
 600         }
 601 
 602         Value getVarValue(Symbol sym) {
 603             Value value = getValue(sym);
 604             Assert.check(value.type() instanceof VarType);
 605             return value;
 606         }
 607 
 608         Value getValue(Symbol sym) {
 609             BodyStack s = stack;
 610             while (s != null) {
 611                 Value v = s.localToOp.get(sym);
 612                 if (v != null) {
 613                     return v;
 614                 }
 615                 s = s.parent;
 616             }
 617             throw new NoSuchElementException(sym.toString());
 618         }
 619 
 620         Value thisValue() { // @@@: outer this?
 621             return top.block.parameters().get(0);
 622         }
 623 
 624         Value getLabel(String labelName) {
 625             BodyStack s = stack;
 626             while (s != null) {
 627                 if (s.label != null && s.label.getKey().equals(labelName)) {
 628                     return s.label.getValue();
 629                 }
 630                 s = s.parent;
 631             }
 632             throw new NoSuchElementException(labelName);
 633         }
 634 
 635         private DiagnosticPosition pos() {
 636             JCTree current = currentNode();
 637             return current != null ? current : tree;
 638         }
 639 
 640         private Op.Result append(Op op) {
 641             return append(op, generateLocation(pos(), false), stack);
 642         }
 643 
 644         private Op.Result append(Op op, Op.Location l) {
 645             return append(op, l, stack);
 646         }
 647 
 648         private Op.Result append(Op op, Op.Location l, BodyStack stack) {
 649             lastOp = op;
 650             op.setLocation(l);
 651             return stack.block.add(op);
 652         }
 653 
 654         Op.Location generateLocation(DiagnosticPosition pos, boolean includeSourceReference) {
 655             if (!lineDebugInfo) {
 656                 return Op.Location.NO_LOCATION;
 657             }
 658 
 659             int startPos = pos.getStartPosition();
 660             int line = log.currentSource().getLineNumber(startPos);
 661             int col = log.currentSource().getColumnNumber(startPos, false);
 662             String path;
 663             if (includeSourceReference) {
 664                 path = PathFileObject.getSimpleName(log.currentSourceFile());
 665             } else {
 666                 path = null;
 667             }
 668             return new Op.Location(path, line, col);
 669         }
 670 
 671         private void appendReturnOrUnreachable(JCTree body) {
 672             // Append only if an existing terminating operation is not present
 673             if (lastOp == null || !(lastOp instanceof Op.Terminating)) {
 674                 // If control can continue after the body append return.
 675                 // Otherwise, append unreachable.
 676                 if (isAliveAfter(body)) {
 677                     append(CoreOp.return_());
 678                 } else {
 679                     append(CoreOp.unreachable());
 680                 }
 681             }
 682         }
 683 
 684         private boolean isAliveAfter(JCTree node) {
 685             return flow.aliveAfter(typeEnvs.get(currentClassSym), node, make);
 686         }
 687 
 688         private void appendTerminating(Supplier<Op.Terminating> sop) {
 689             // Append only if an existing terminating operation is not present
 690             if (lastOp == null || !(lastOp instanceof Op.Terminating)) {
 691                 append(sop.get());
 692             }
 693         }
 694 
 695         public Value toValue(JCExpression expression, Type targetType) {
 696             result = null; // reset
 697             Type prevPt = pt;
 698             try {
 699                 pt = targetType;
 700                 scan(expression);
 701                 return (result == null || targetType.hasTag(TypeTag.VOID) || targetType.hasTag(NONE)) ?
 702                         result : coerce(result, expression.type, targetType);
 703             } finally {
 704                 pt = prevPt;
 705             }
 706         }
 707 
 708         public Value toValue(JCExpression expression) {
 709             return toValue(expression, Type.noType);
 710         }
 711 
 712         public Value toValue(JCTree.JCStatement statement) {
 713             result = null; // reset
 714             scan(statement);
 715             return result;
 716         }
 717 
 718         Value coerce(Value sourceValue, Type sourceType, Type targetType) {
 719             // primitive target requires care: if target is "int", but source
 720             // expression has (after type subst) type "Integer", we should still
 721             // emit a synthetic cast to "Integer" (if needed)
 722             Type refTarget = targetType.isPrimitive() ?
 723                     codeTypeToType(sourceValue.type()) :
 724                     targetType;
 725 
 726             if (sourceType.isReference() && refTarget.isReference() &&
 727                     !types.isSubtype(types.erasure(sourceType), types.erasure(refTarget))) {
 728                 // the generated synthetic cast uses a raw type as type operand,
 729                 // but preserves full static type info in the result type
 730                 sourceValue = append(JavaOp.cast(typeToCodeType(refTarget),
 731                         typeToCodeType(types.erasure(refTarget)), sourceValue));
 732             }
 733             return convert(sourceValue, targetType);
 734         }
 735 
 736         Value boxIfNeeded(Value exprVal) {
 737             Type source = codeTypeToType(exprVal.type());
 738             return source.hasTag(NONE) ?
 739                     exprVal : convert(exprVal, types.boxedTypeOrType(source));
 740         }
 741 
 742         Value unboxIfNeeded(Value exprVal) {
 743             Type source = codeTypeToType(exprVal.type());
 744             return source.hasTag(NONE) ?
 745                     exprVal : convert(exprVal, types.unboxedTypeOrType(source));
 746         }
 747 
 748         Value convert(Value exprVal, Type target) {
 749             Type source = codeTypeToType(exprVal.type());
 750             boolean sourcePrimitive = source.isPrimitive();
 751             boolean targetPrimitive = target.isPrimitive();
 752             if (target.hasTag(NONE)) {
 753                 return exprVal;
 754             } else if (sourcePrimitive == targetPrimitive) {
 755                 if (!sourcePrimitive || types.isSameType(source, target)) {
 756                     return exprVal;
 757                 } else {
 758                     // implicit primitive conversion
 759                     return append(JavaOp.conv(typeToCodeType(target), exprVal));
 760                 }
 761             } else if (sourcePrimitive) {
 762                 // we need to box
 763                 Type unboxedTarget = types.unboxedType(target);
 764                 if (!unboxedTarget.hasTag(NONE)) {
 765                     // non-Object target
 766                     if (!types.isConvertible(source, unboxedTarget)) {
 767                         exprVal = convert(exprVal, unboxedTarget);
 768                     }
 769                     return box(exprVal, target);
 770                 } else {
 771                     // Object target
 772                     return box(exprVal, types.boxedClass(source).type);
 773                 }
 774             } else {
 775                 // we need to unbox
 776                 Value unboxedVal = unbox(exprVal, source, target, types.unboxedType(source));
 777                 return convert(unboxedVal, target); // to perform necessary widening conversion if needed
 778             }
 779         }
 780 
 781         Value box(Value valueExpr, Type box) {
 782             // Boxing is a static method e.g., java.lang.Integer::valueOf(int)java.lang.Integer
 783             MethodRef boxMethod = MethodRef.method(typeToCodeType(box), names.valueOf.toString(),
 784                     CoreType.functionType(typeToCodeType(box), typeToCodeType(types.unboxedType(box))));
 785             return append(JavaOp.invoke(boxMethod, valueExpr));
 786         }
 787 
 788         Value unbox(Value valueExpr, Type box, Type primitive, Type unboxedType) {
 789             if (unboxedType.hasTag(NONE)) {
 790                 // Object target, first downcast to correct wrapper type
 791                 unboxedType = primitive;
 792                 box = types.boxedClass(unboxedType).type;
 793                 valueExpr = append(JavaOp.cast(typeToCodeType(box), valueExpr));
 794             }
 795             // Unboxing is a virtual method e.g., java.lang.Integer::intValue()int
 796             MethodRef unboxMethod = MethodRef.method(typeToCodeType(box),
 797                     unboxedType.tsym.name.append(names.Value).toString(),
 798                     CoreType.functionType(typeToCodeType(unboxedType)));
 799             return append(JavaOp.invoke(unboxMethod, valueExpr));
 800         }
 801 
 802         @Override
 803         public void visitVarDef(JCVariableDecl tree) {
 804             JavaType javaType = typeToCodeType(tree.type);
 805             if (tree.init != null) {
 806                 Value initOp = toValue(tree.init, tree.type);
 807                 // constant locals bind to the initializer result
 808                 result = tree.sym.getConstantValue() != null
 809                         ? initOp : append(CoreOp.var(tree.name.toString(), javaType, initOp));
 810             } else {
 811                 // Uninitialized
 812                 result = append(CoreOp.var(tree.name.toString(), javaType));
 813             }
 814             stack.localToOp.put(tree.sym, result);
 815         }
 816 
 817         @Override
 818         public void visitAssign(JCAssign tree) {
 819             // Consume top node that applies to write access
 820             JCTree lhs = TreeInfo.skipParens(tree.lhs);
 821             Type target = tree.lhs.type;
 822             switch (lhs.getTag()) {
 823                 case IDENT: {
 824                     JCIdent assign = (JCIdent) lhs;
 825 
 826                     // Scan the rhs, the assign expression result is its input
 827                     result = toValue(tree.rhs, target);
 828 
 829                     Symbol sym = assign.sym;
 830                     switch (sym.getKind()) {
 831                         case LOCAL_VARIABLE, BINDING_VARIABLE, PARAMETER, EXCEPTION_PARAMETER -> {
 832                             Value varOp = getVarValue(sym);
 833                             append(CoreOp.varStore(varOp, result));
 834                         }
 835                         case FIELD -> {
 836                             FieldRef fd = symbolToErasedFieldRef(sym, symbolSiteType(sym));
 837                             if (sym.isStatic()) {
 838                                 append(JavaOp.fieldStore(fd, result));
 839                             } else {
 840                                 append(JavaOp.fieldStore(fd, thisValue(), result));
 841                             }
 842                         }
 843                         default -> throw unreachable();
 844                     }
 845                     break;
 846                 }
 847                 case SELECT: {
 848                     JCFieldAccess assign = (JCFieldAccess) lhs;
 849 
 850                     Value receiver = toValue(assign.selected);
 851 
 852                     // Scan the rhs, the assign expression result is its input
 853                     result = toValue(tree.rhs, target);
 854 
 855                     Symbol sym = assign.sym;
 856                     FieldRef fr = symbolToErasedFieldRef(sym, assign.selected.type);
 857                     if (sym.isStatic()) {
 858                         append(JavaOp.fieldStore(fr, result));
 859                     } else {
 860                         append(JavaOp.fieldStore(fr, receiver, result));
 861                     }
 862                     break;
 863                 }
 864                 case INDEXED: {
 865                     JCArrayAccess assign = (JCArrayAccess) lhs;
 866 
 867                     Value array = toValue(assign.indexed);
 868                     Value index = toValue(assign.index, syms.intType);
 869 
 870                     // Scan the rhs, the assign expression result is its input
 871                     result = toValue(tree.rhs, target);
 872 
 873                     append(JavaOp.arrayStoreOp(array, index, result));
 874                     break;
 875                 }
 876                 default:
 877                     throw unreachable();
 878             }
 879         }
 880 
 881         @Override
 882         public void visitAssignop(JCTree.JCAssignOp tree) {
 883             if (tree.operator.opcode == ByteCodes.string_add) {
 884                 // string concat
 885                 applyCompoundAssign(tree.lhs, lhs -> {
 886                     Type rhsType = tree.rhs.type;
 887                     Value rhs = toValue(tree.rhs,
 888                             rhsType.hasTag(BOT) ? syms.stringType : rhsType);
 889                     // lhs cannot have null type, no target type needed
 890                     Value assignOpResult = append(JavaOp.concat(lhs, rhs));
 891                     return result = convert(assignOpResult, tree.type);
 892                 });
 893             } else {
 894                 // arithmetic op
 895                 applyCompoundAssign(tree.lhs, lhs -> {
 896                     Type lhsType = tree.operator.type.getParameterTypes().head;
 897                     Type rhsType = tree.operator.type.getParameterTypes().tail.head;
 898 
 899                     // We need to first convert LHS, then process RHS
 900                     // as described in JLS 15.26.2
 901                     lhs = convert(lhs, lhsType);
 902                     Value rhs = toValue(tree.rhs, rhsType);
 903 
 904                     Value assignOpResult = switch (tree.getTag()) {
 905 
 906                         // Arithmetic operations
 907                         case PLUS_ASG -> append(JavaOp.add(lhs, rhs));
 908                         case MINUS_ASG -> append(JavaOp.sub(lhs, rhs));
 909                         case MUL_ASG -> append(JavaOp.mul(lhs, rhs));
 910                         case DIV_ASG -> append(JavaOp.div(lhs, rhs));
 911                         case MOD_ASG -> append(JavaOp.mod(lhs, rhs));
 912 
 913                         // Bitwise operations (including their boolean variants)
 914                         case BITOR_ASG -> append(JavaOp.or(lhs, rhs));
 915                         case BITAND_ASG -> append(JavaOp.and(lhs, rhs));
 916                         case BITXOR_ASG -> append(JavaOp.xor(lhs, rhs));
 917 
 918                         // Shift operations
 919                         case SL_ASG -> append(JavaOp.lshl(lhs, rhs));
 920                         case SR_ASG -> append(JavaOp.ashr(lhs, rhs));
 921                         case USR_ASG -> append(JavaOp.lshr(lhs, rhs));
 922 
 923 
 924                         default -> throw unreachable();
 925                     };
 926                     return result = convert(assignOpResult, tree.type);
 927                 });
 928             }
 929         }
 930 
 931         void applyCompoundAssign(JCTree.JCExpression lhs, Function<Value, Value> scanRhs) {
 932             // Consume top node that applies to access
 933             lhs = TreeInfo.skipParens(lhs);
 934             switch (lhs.getTag()) {
 935                 case IDENT -> {
 936                     JCIdent assign = (JCIdent) lhs;
 937 
 938                     Symbol sym = assign.sym;
 939                     switch (sym.getKind()) {
 940                         case LOCAL_VARIABLE, BINDING_VARIABLE, PARAMETER -> { // exception parameters not valid here!
 941                             Value varOp = getVarValue(sym);
 942 
 943                             Op.Result lhsOpValue = append(CoreOp.varLoad(varOp));
 944                             // Scan the rhs
 945                             Value r = scanRhs.apply(lhsOpValue);
 946 
 947                             append(CoreOp.varStore(varOp, r));
 948                         }
 949                         case FIELD -> {
 950                             FieldRef fr = symbolToErasedFieldRef(sym, symbolSiteType(sym));
 951 
 952                             Op.Result lhsOpValue;
 953                             CodeType resultType = typeToCodeType(assign.type);
 954                             if (sym.isStatic()) {
 955                                 lhsOpValue = append(JavaOp.fieldLoad(resultType, fr));
 956                             } else {
 957                                 lhsOpValue = append(JavaOp.fieldLoad(resultType, fr, thisValue()));
 958                             }
 959                             // Scan the rhs
 960                             Value r = scanRhs.apply(lhsOpValue);
 961 
 962                             if (sym.isStatic()) {
 963                                 append(JavaOp.fieldStore(fr, r));
 964                             } else {
 965                                 append(JavaOp.fieldStore(fr, thisValue(), r));
 966                             }
 967                         }
 968                         default -> throw unreachable();
 969                     }
 970                 }
 971                 case SELECT -> {
 972                     JCFieldAccess assign = (JCFieldAccess) lhs;
 973 
 974                     Value receiver = toValue(assign.selected);
 975 
 976                     Symbol sym = assign.sym;
 977                     FieldRef fr = symbolToErasedFieldRef(sym, assign.selected.type);
 978 
 979                     Op.Result lhsOpValue;
 980                     CodeType resultType = typeToCodeType(assign.type);
 981                     if (sym.isStatic()) {
 982                         lhsOpValue = append(JavaOp.fieldLoad(resultType, fr));
 983                     } else {
 984                         lhsOpValue = append(JavaOp.fieldLoad(resultType, fr, receiver));
 985                     }
 986                     // Scan the rhs
 987                     Value r = scanRhs.apply(lhsOpValue);
 988 
 989                     if (sym.isStatic()) {
 990                         append(JavaOp.fieldStore(fr, r));
 991                     } else {
 992                         append(JavaOp.fieldStore(fr, receiver, r));
 993                     }
 994                 }
 995                 case INDEXED -> {
 996                     JCArrayAccess assign = (JCArrayAccess) lhs;
 997 
 998                     Value array = toValue(assign.indexed);
 999                     Value index = toValue(assign.index, syms.intType);
1000 
1001                     Op.Result lhsOpValue = append(JavaOp.arrayLoadOp(array, index));
1002                     // Scan the rhs
1003                     Value r = scanRhs.apply(lhsOpValue);
1004 
1005                     append(JavaOp.arrayStoreOp(array, index, r));
1006                 }
1007                 default -> throw unreachable();
1008             }
1009         }
1010 
1011         @Override
1012         public void visitIdent(JCIdent tree) {
1013             // Visited only for read access
1014 
1015             Symbol sym = tree.sym;
1016             switch (sym.getKind()) {
1017                 case LOCAL_VARIABLE -> {
1018                     if (sym instanceof VarSymbol variable && variable.getConstantValue() != null) {
1019                         result = getValue(sym);
1020                         Assert.check(!(result.type() instanceof VarType));
1021                     } else {
1022                         result = loadVar(sym);
1023                     }
1024                 }
1025                 case RESOURCE_VARIABLE, BINDING_VARIABLE, PARAMETER, EXCEPTION_PARAMETER ->
1026                         result = loadVar(sym);
1027                 case FIELD, ENUM_CONSTANT -> {
1028                     if (sym.name.equals(names._this) || sym.name.equals(names._super)) {
1029                         result = thisValue();
1030                     } else if (top.localToOp.containsKey(sym)) {
1031                         // if field symbol is a key in top.localToOp
1032                         // we expect that we're producing the model of a lambda
1033                         // we also expect that the field is a constant capture and sym was mapped to VarOp result
1034                         Assert.check(isLambdaReflectable);
1035                         Assert.check(sym.isStatic());
1036                         Assert.check(sym.isFinal());
1037                         result = loadVar(sym);
1038                     } else if (sym instanceof VarSymbol variable && variable.getConstantValue() != null) {
1039                         result = append(CoreOp.constant(typeToCodeType(tree.type), variable.getConstantValue()));
1040                     } else {
1041                         FieldRef fr = symbolToErasedFieldRef(sym, symbolSiteType(sym));
1042                         CodeType resultType = typeToCodeType(tree.type);
1043                         if (sym.isStatic()) {
1044                             result = append(JavaOp.fieldLoad(resultType, fr));
1045                         } else {
1046                             result = append(JavaOp.fieldLoad(resultType, fr, thisValue()));
1047                         }
1048                     }
1049                 }
1050                 case PACKAGE, INTERFACE, CLASS, ANNOTATION_TYPE, RECORD, ENUM -> {
1051                     result = null;
1052                 }
1053                 default -> throw unreachable();
1054             }
1055         }
1056 
1057         private Value loadVar(Symbol sym) {
1058             Value varOp = getVarValue(sym);
1059             return append(CoreOp.varLoad(varOp));
1060         }
1061 
1062         @Override
1063         public void visitTypeIdent(JCTree.JCPrimitiveTypeTree tree) {
1064             result = null;
1065         }
1066 
1067         @Override
1068         public void visitTypeArray(JCTree.JCArrayTypeTree tree) {
1069             result = null; // MyType[].class is handled in visitSelect just as MyType.class
1070         }
1071 
1072         @Override
1073         public void visitSelect(JCFieldAccess tree) {
1074             // Visited only for read access
1075 
1076             Type qualifierTarget = qualifierTarget(tree);
1077             // @@@: might cause redundant load if accessed symbol is static but the qualifier is not a type
1078             Value receiver = toValue(tree.selected);
1079 
1080             if (tree.name.equals(names._class)) {
1081                 result = append(CoreOp.constant(JavaType.J_L_CLASS, typeToCodeType(tree.selected.type)));
1082             } else if (types.isArray(tree.selected.type)) {
1083                 if (tree.sym.equals(syms.lengthVar)) {
1084                     result = append(JavaOp.arrayLength(receiver));
1085                 } else {
1086                     throw unreachable();
1087                 }
1088             } else {
1089                 Symbol sym = tree.sym;
1090                 switch (sym.getKind()) {
1091                     case FIELD, ENUM_CONSTANT -> {
1092                         if (sym.name.equals(names._this) || sym.name.equals(names._super)) {
1093                             result = thisValue();
1094                         } else if (sym instanceof VarSymbol variable && variable.getConstantValue() != null) {
1095                             if (!sym.isStatic()) {
1096                                 // receiver null check
1097                                 MethodRef ref = MethodRef.method(Objects.class, "requireNonNull", Object.class, Object.class);
1098                                 append(JavaOp.invoke(JavaOp.InvokeOp.InvokeKind.STATIC, false, JavaType.J_L_OBJECT, ref, receiver));
1099                             }
1100                             result = append(CoreOp.constant(typeToCodeType(tree.type), variable.getConstantValue()));
1101                         } else {
1102                             FieldRef fr = symbolToErasedFieldRef(sym, qualifierTarget.hasTag(NONE) ?
1103                                     tree.selected.type : qualifierTarget);
1104                             CodeType resultType = typeToCodeType(tree.type);
1105                             if (sym.isStatic()) {
1106                                 result = append(JavaOp.fieldLoad(resultType, fr));
1107                             } else {
1108                                 result = append(JavaOp.fieldLoad(resultType, fr, receiver));
1109                             }
1110                         }
1111                     }
1112                     case PACKAGE, INTERFACE, CLASS, ANNOTATION_TYPE, RECORD, ENUM -> {
1113                         result = null;
1114                     }
1115                     default -> throw unreachable();
1116                 }
1117             }
1118         }
1119 
1120         @Override
1121         public void visitIndexed(JCArrayAccess tree) {
1122             // Visited only for read access
1123 
1124             Value array = toValue(tree.indexed);
1125 
1126             Value index = toValue(tree.index, syms.intType);
1127 
1128             result = append(JavaOp.arrayLoadOp(array, index));
1129         }
1130 
1131         @Override
1132         public void visitApply(JCTree.JCMethodInvocation tree) {
1133             // @@@ Symbol.externalType, for use with inner classes
1134 
1135             // @@@ this.xyz(...) calls in a constructor
1136 
1137             JCTree meth = TreeInfo.skipParens(tree.meth);
1138             switch (meth.getTag()) {
1139                 case IDENT: {
1140                     JCIdent access = (JCIdent) meth;
1141 
1142                     Symbol sym = access.sym;
1143                     List<Value> args = new ArrayList<>();
1144                     JavaOp.InvokeOp.InvokeKind ik;
1145                     if (!sym.isStatic()) {
1146                         ik = JavaOp.InvokeOp.InvokeKind.INSTANCE;
1147                         args.add(thisValue());
1148                     } else {
1149                         ik = JavaOp.InvokeOp.InvokeKind.STATIC;
1150                     }
1151 
1152                     args.addAll(scanMethodArguments(tree.args, tree.meth.type, tree.varargsElement));
1153 
1154                     MethodRef mr = symbolToErasedMethodRef(sym, symbolSiteType(sym));
1155 
1156                     JavaType resultType = typeToCodeType(tree.type);
1157                     JavaOp.InvokeOp iop = JavaOp.invoke(ik, tree.varargsElement != null,
1158                             resultType, mr, args);
1159                     Value res = append(iop);
1160                     if (sym.type.getReturnType().getTag() != TypeTag.VOID) {
1161                         result = res;
1162                     }
1163                     break;
1164                 }
1165                 case SELECT: {
1166                     JCFieldAccess access = (JCFieldAccess) meth;
1167 
1168                     Type qualifierTarget = qualifierTarget(access);
1169                     Value receiver = toValue(access.selected, qualifierTarget);
1170 
1171                     Symbol sym = access.sym;
1172                     List<Value> args = new ArrayList<>();
1173                     JavaOp.InvokeOp.InvokeKind ik;
1174                     if (!sym.isStatic()) {
1175                         args.add(receiver);
1176                         // @@@ expr.super(...) for inner class super constructor calls
1177                         ik = switch (access.selected) {
1178                             case JCIdent i when i.sym.name.equals(names._super) -> JavaOp.InvokeOp.InvokeKind.SUPER;
1179                             case JCFieldAccess fa when fa.sym.name.equals(names._super) -> JavaOp.InvokeOp.InvokeKind.SUPER;
1180                             default -> JavaOp.InvokeOp.InvokeKind.INSTANCE;
1181                         };
1182                     } else {
1183                         ik = JavaOp.InvokeOp.InvokeKind.STATIC;
1184                     }
1185 
1186                     args.addAll(scanMethodArguments(tree.args, tree.meth.type, tree.varargsElement));
1187 
1188                     MethodRef mr;
1189                     if (sym.owner == syms.arrayClass && sym.name == names.clone) {
1190                         // For array.clone use the erased selected type as the reference type,
1191                         // which will be an array
1192                         mr = MethodRef.method(
1193                                 typeToCodeType(types.erasure(access.selected.type)),
1194                                 names.clone.toString(),
1195                                 JavaType.J_L_OBJECT);
1196                     } else {
1197                         Type t = qualifierTarget.hasTag(NONE) || types.isSubtype(types.erasure(access.selected.type), types.erasure(qualifierTarget))
1198                                 ? access.selected.type : qualifierTarget;
1199                         mr = symbolToErasedMethodRef(sym, t);
1200                     }
1201 
1202                     // Use the actual type of the expression, tree.type, rather than meth.type.getReturnType()
1203                     // This ensures invocation expressions to clone on arrays and getClass are modeled
1204                     // with the correct result type
1205                     JavaType resultType = typeToCodeType(tree.type);
1206                     JavaOp.InvokeOp iop = JavaOp.invoke(ik, tree.varargsElement != null,
1207                             resultType, mr, args);
1208                     Value res = append(iop);
1209                     if (sym.type.getReturnType().getTag() != TypeTag.VOID) {
1210                         result = res;
1211                     }
1212                     break;
1213                 }
1214                 default:
1215                     throw unreachable();
1216             }
1217         }
1218 
1219         List<Value> scanMethodArguments(List<JCExpression> args, Type methodType, Type varargsElement) {
1220             ListBuffer<Value> argValues = new ListBuffer<>();
1221             com.sun.tools.javac.util.List<Type> targetTypes = methodType.getParameterTypes();
1222             if (varargsElement != null) {
1223                 targetTypes = targetTypes.reverse().tail;
1224                 for (int i = 0 ; i < args.size() - (methodType.getParameterTypes().size() - 1) ; i++) {
1225                     targetTypes = targetTypes.prepend(varargsElement);
1226                 }
1227                 targetTypes = targetTypes.reverse();
1228             }
1229 
1230             for (JCTree.JCExpression arg : args) {
1231                 argValues.add(toValue(arg, targetTypes.head));
1232                 targetTypes = targetTypes.tail;
1233             }
1234             return argValues.toList();
1235         }
1236 
1237         @Override
1238         public void visitReference(JCTree.JCMemberReference tree) {
1239             MemberReferenceToLambda memberReferenceToLambda = new MemberReferenceToLambda(tree, currentClassSym);
1240             JCVariableDecl recv = memberReferenceToLambda.receiverVar();
1241             if (recv != null) {
1242                 scan(recv);
1243             }
1244             scan(memberReferenceToLambda.lambda());
1245         }
1246 
1247         Type qualifierTarget(JCFieldAccess tree) {
1248             Type selectedType = types.skipTypeVars(tree.selected.type, true);
1249             return selectedType.isCompound() ?
1250                     tree.sym.owner.type :
1251                     Type.noType;
1252         }
1253 
1254         @Override
1255         public void visitTypeCast(JCTree.JCTypeCast tree) {
1256             Type castTarget = tree.type;
1257             List<Type> additionalTargets = new ArrayList<>();
1258             if (tree.type instanceof Type.IntersectionClassType ict) {
1259                 // TransTypes emits a component casts following source order,
1260                 // but leaves the first component (the erasure of the intersection) last.
1261                 Type principalComponent = ict.getExplicitComponents().head;
1262                 castTarget = ict.getExplicitComponents().tail.head;
1263                 additionalTargets = ict.getExplicitComponents()
1264                         .tail.tail.append(principalComponent);
1265             }
1266             if (tree.expr.type.hasTag(BOT)) {
1267                 Value v = toValue(tree.expr);
1268                 result = append(JavaOp.cast(
1269                         typeToCodeType(tree.type),
1270                         typeToCodeType(types.erasure(castTarget)),
1271                         v));
1272             } else {
1273                 result = toValue(tree.expr, castTarget);
1274             }
1275             for (Type t : additionalTargets) {
1276                 Type ec = types.erasure(t);
1277                 if (!types.isSameType(ec, types.erasure(pt))) {
1278                     // TransTypes skip components that have same erasure
1279                     // as the outer target type
1280                     result = coerce(result, codeTypeToType(result.type()), ec);
1281                 }
1282             }
1283         }
1284 
1285         @Override
1286         public void visitTypeTest(JCTree.JCInstanceOf tree) {
1287             Value target = toValue(tree.expr);
1288             JCTree.JCPattern pattern = tree.getPattern();
1289             if (pattern != null) {
1290                 result = scanPattern(pattern, target);
1291             } else {
1292                 result = append(JavaOp.instanceOf(typeToCodeType(tree.pattern.type), target));
1293             }
1294         }
1295 
1296         Body.Builder scanPatternAsBody(JCTree.JCPattern pattern, Value target) {
1297             pushBody(pattern, CoreType.functionType(JavaType.BOOLEAN));
1298             Value localTarget = boxIfNeeded(target);
1299             Value patVal = scanPattern(pattern, localTarget);
1300             append(CoreOp.core_yield(patVal));
1301             Body.Builder patternBody = stack.body;
1302             popBody();
1303             return patternBody;
1304         }
1305 
1306         Value scanPattern(JCTree.JCPattern pattern, Value target) {
1307             // Type of pattern
1308             JavaType patternType;
1309             if (pattern instanceof JCTree.JCBindingPattern p) {
1310                 patternType = JavaOp.Pattern.bindingType(typeToCodeType(p.type));
1311             } else if (pattern instanceof JCTree.JCRecordPattern p) {
1312                 patternType = JavaOp.Pattern.recordType(typeToCodeType(p.record.type));
1313             } else {
1314                 throw unreachable(); // toplevel patterns are type test/record
1315             }
1316 
1317             // Push pattern body
1318             pushBody(pattern, CoreType.functionType(patternType));
1319 
1320             // @@@ Assumes just pattern nodes, likely will change when method patterns are supported
1321             //     that have expressions for any arguments (which perhaps in turn may have pattern expressions)
1322             List<JCVariableDecl> variables = new ArrayList<>();
1323             class PatternScanner extends FilterScanner {
1324 
1325                 private Value result;
1326 
1327                 public PatternScanner() {
1328                     super(Set.of(Tag.BINDINGPATTERN, Tag.RECORDPATTERN, Tag.ANYPATTERN));
1329                 }
1330 
1331                 @Override
1332                 public void visitBindingPattern(JCTree.JCBindingPattern binding) {
1333                     JCVariableDecl var = binding.var;
1334                     variables.add(var);
1335                     boolean unnamedPatternVariable = var.name.isEmpty();
1336                     String bindingName = unnamedPatternVariable ? null : var.name.toString();
1337                     result = append(JavaOp.typePattern(typeToCodeType(var.type), bindingName));
1338                 }
1339 
1340                 @Override
1341                 public void visitRecordPattern(JCTree.JCRecordPattern record) {
1342                     // @@@ Is always Identifier to record?
1343                     // scan(record.deconstructor);
1344 
1345                     List<Value> nestedValues = new ArrayList<>();
1346                     for (JCTree.JCPattern jcPattern : record.nested) {
1347                         // @@@ when we support ANYPATTERN, we must add result of toValue only if it's non-null
1348                         // because passing null to recordPattern methods will cause an error
1349                         nestedValues.add(toValue(jcPattern));
1350                     }
1351 
1352                     result = append(JavaOp.recordPattern(symbolToRecordTypeRef(record.record), nestedValues));
1353                 }
1354 
1355                 @Override
1356                 public void visitAnyPattern(JCTree.JCAnyPattern anyPattern) {
1357                     result = append(JavaOp.matchAllPattern());
1358                 }
1359 
1360                 Value toValue(JCTree tree) {
1361                     result = null;
1362                     scan(tree);
1363                     return result;
1364                 }
1365             }
1366             // Scan pattern
1367             Value patternValue = new PatternScanner().toValue(pattern);
1368             append(CoreOp.core_yield(patternValue));
1369             Body.Builder patternBody = stack.body;
1370 
1371             // Pop body
1372             popBody();
1373 
1374             // Find nearest ancestor body stack element associated with a statement tree
1375             // @@@ Strengthen check of tree?
1376             BodyStack _variablesStack = stack;
1377             while (!(_variablesStack.tree instanceof JCLambda)
1378                     && !(_variablesStack.tree instanceof JCTree.JCStatement)) {
1379                 _variablesStack = _variablesStack.parent;
1380             }
1381             BodyStack variablesStack = _variablesStack;
1382 
1383             // Create pattern var ops for pattern variables using the
1384             // builder associated with the nearest statement tree
1385             BodyStack previous = stack;
1386             // Temporarily position the stack to where the pattern variables are to be declared
1387             stack = variablesStack;
1388             try {
1389                 for (JCVariableDecl jcVar : variables) {
1390                     Op.Result op = append(CoreOp.var(jcVar.name.toString(), typeToCodeType(jcVar.type)));
1391                     stack.localToOp.put(jcVar.sym, op);
1392                 }
1393             } finally {
1394                 stack = previous;
1395             }
1396 
1397             // Create pattern descriptor
1398             List<JavaType> patternDescParams = variables.stream().map(var -> typeToCodeType(var.type)).toList();
1399             FunctionType matchFuncType = CoreType.functionType(JavaType.VOID, patternDescParams);
1400 
1401             // Create the match body, assigning pattern values to pattern variables
1402             Body.Builder matchBody = Body.Builder.of(patternBody.connectedAncestorBody(), matchFuncType);
1403             Block.Builder matchBuilder = matchBody.entryBlock();
1404             for (int i = 0; i < variables.size(); i++) {
1405                 Value v = matchBuilder.parameters().get(i);
1406                 Value var = variablesStack.localToOp.get(variables.get(i).sym);
1407                 matchBuilder.add(CoreOp.varStore(var, v));
1408             }
1409             matchBuilder.add(CoreOp.core_yield());
1410 
1411             // Create the match operation
1412             return append(JavaOp.match(target, patternBody, matchBody));
1413         }
1414 
1415         @Override
1416         public void visitExec(JCExpressionStatement tree) {
1417             toValue(tree.expr); // no target
1418             result = null;
1419         }
1420 
1421         @Override
1422         public void visitNewClass(JCTree.JCNewClass tree) {
1423             if (tree.def != null) {
1424                 scan(tree.def);
1425             }
1426 
1427             List<CodeType> argtypes = new ArrayList<>();
1428             Type type = tree.type;
1429             List<Value> args = new ArrayList<>();
1430             if (type.tsym.hasOuterInstance()) {
1431                 // Obtain outer value for inner class, and add as first argument
1432                 Value outerInstance;
1433                 if (tree.encl == null || tree.def != null) {
1434                     outerInstance = thisValue();
1435                 } else {
1436                     outerInstance = toValue(attr.makeNullCheck(tree.encl));
1437                 }
1438                 args.add(outerInstance);
1439                 JavaType outerType = typeToCodeType(tree.constructor.innermostAccessibleEnclosingClass().erasure(types));
1440                 argtypes.add(outerType);
1441             }
1442 
1443             MethodRef methodRef = symbolToErasedMethodRef(tree.constructor);
1444             argtypes.addAll(methodRef.signature().parameterTypes());
1445             // If an anonymous class is created with a qualified new expression,
1446             // prepend the qualifier to the argument list, as TransTypes normally does
1447             List<JCExpression> treeArgs = tree.encl != null && tree.def != null ? tree.args.prepend(attr.makeNullCheck(tree.encl)) : tree.args;
1448             args.addAll(scanMethodArguments(treeArgs, tree.constructorType, tree.varargsElement));
1449 
1450             if (tree.type.tsym.isDirectlyOrIndirectlyLocal()) {
1451                 for (Symbol c : localCaptures.get(tree.type.tsym)) {
1452                     args.add(loadVar(c));
1453                     argtypes.add(symbolToErasedDesc(c));
1454                 }
1455             }
1456 
1457             // Create erased method type reference for constructor, where
1458             // the return type declares the class to instantiate
1459             // We need to manually construct the constructor reference,
1460             // as the signature of the constructor symbol is not augmented
1461             // with enclosing this and captured params.
1462             FunctionType constructorSignature = CoreType.functionType(
1463                     symbolToErasedDesc(tree.constructor.owner),
1464                     argtypes);
1465             MethodRef constructorRef = MethodRef.constructor(constructorSignature);
1466 
1467             result = append(JavaOp.new_(tree.varargsElement != null, typeToCodeType(type), constructorRef, args));
1468         }
1469 
1470         @Override
1471         public void visitNewArray(JCTree.JCNewArray tree) {
1472             if (tree.elems != null) {
1473                 int length = tree.elems.size();
1474                 Op.Result a = append(JavaOp.newArray(
1475                         typeToCodeType(tree.type),
1476                         append(CoreOp.constant(JavaType.INT, length))));
1477                 int i = 0;
1478                 for (JCExpression elem : tree.elems) {
1479                     Value element = toValue(elem, types.elemtype(tree.type));
1480                     append(JavaOp.arrayStoreOp(
1481                             a,
1482                             append(CoreOp.constant(JavaType.INT, i)),
1483                             element));
1484                     i++;
1485                 }
1486 
1487                 result = a;
1488             } else {
1489                 List<Value> indexes = new ArrayList<>();
1490                 for (JCTree.JCExpression dim : tree.dims) {
1491                     indexes.add(toValue(dim));
1492                 }
1493 
1494                 JavaType arrayType = typeToCodeType(tree.type);
1495                 MethodRef constructorRef = MethodRef.constructor(arrayType,
1496                         indexes.stream().map(Value::type).toList());
1497                 result = append(JavaOp.new_(constructorRef, indexes));
1498             }
1499         }
1500 
1501         @Override
1502         public void visitLambda(JCTree.JCLambda tree) {
1503             final Type descriptorType = types.findDescriptorType(tree.target);
1504             final FunctionType lambdaType = typeToFunctionType(descriptorType);
1505 
1506             // Push quoted body for a reflectable lambda
1507 
1508             // A reflectable lambda is going to have its model wrapped in QuotedOp
1509             // only when we are producing the model of the lambda, thus the condition (isReflectable ...)
1510             // also, a lambda contained in a reflectable lambda, will not have its model wrapped in QuotedOp,
1511             // thus the condition (... body == tree)
1512             boolean toQuote = (isLambdaReflectable && this.tree == tree);
1513             if (toQuote) {
1514                 pushBody(tree.body, CoreType.FUNCTION_TYPE_VOID);
1515             }
1516 
1517             // Push lambda body
1518             // for expression lambda, the body stack need to be mapped to the JCLambda tree
1519             // this ensures the logic for computing pattern variable stack, works correctly
1520             pushBody(tree.getBodyKind() == LambdaExpressionTree.BodyKind.EXPRESSION ? tree : tree.body, lambdaType);
1521 
1522             // Map lambda parameters to varOp values
1523             for (int i = 0; i < tree.params.size(); i++) {
1524                 JCVariableDecl p = tree.params.get(i);
1525                 Op.Result paramOp = append(CoreOp.var(
1526                         p.name.toString(),
1527                         stack.block.parameters().get(i)));
1528                 stack.localToOp.put(p.sym, paramOp);
1529             }
1530 
1531             // Scan the lambda body
1532             Type lambdaReturnType = descriptorType.getReturnType();
1533             if (tree.getBodyKind() == LambdaExpressionTree.BodyKind.EXPRESSION) {
1534                 Value exprVal = toValue(((JCExpression) tree.body), lambdaReturnType);
1535                 if (!lambdaReturnType.hasTag(TypeTag.VOID)) {
1536                     append(CoreOp.return_(exprVal));
1537                 } else {
1538                     appendTerminating(CoreOp::return_);
1539                 }
1540             } else {
1541                 Type prevBodyTarget = bodyTarget;
1542                 try {
1543                     bodyTarget = lambdaReturnType;
1544                     toValue(((JCTree.JCStatement) tree.body));
1545                     appendReturnOrUnreachable(tree.body);
1546                 } finally {
1547                     bodyTarget = prevBodyTarget;
1548                 }
1549             }
1550 
1551             // Get the functional interface type
1552             Type fiType = tree.target;
1553             List<Type> miTypes = new ArrayList<>();
1554             if (fiType.isIntersection()) {
1555                 Symbol descriptor = types.findDescriptorSymbol(fiType.tsym);
1556                 fiType = types.asSuper(tree.target, descriptor.owner);
1557                 for (Type t : types.directSupertypes(tree.target)) {
1558                     if (t.tsym != fiType.tsym && t.tsym != syms.objectType.tsym) {
1559                         miTypes.add(t);
1560                     }
1561                 }
1562             }
1563             // build functional lambda
1564             Op lambdaOp = JavaOp.lambda(typeToCodeType(fiType), stack.body,
1565                     miTypes.stream().map(t -> typeToCodeType(t)).toList(),
1566                     true);
1567 
1568             // Pop lambda body
1569             popBody();
1570 
1571             Value lambdaResult;
1572             if (toQuote) {
1573                 lambdaResult = append(lambdaOp, generateLocation(tree, true));
1574             } else {
1575                 lambdaResult = append(lambdaOp);
1576             }
1577 
1578             if (toQuote) {
1579                 append(CoreOp.core_yield(lambdaResult));
1580                 CoreOp.QuotedOp quotedOp = CoreOp.quoted(stack.body);
1581 
1582                 // Pop quoted body
1583                 popBody();
1584 
1585                 lambdaResult = append(quotedOp);
1586             }
1587 
1588             result = lambdaResult;
1589         }
1590 
1591         @Override
1592         public void visitIf(JCTree.JCIf tree) {
1593             List<Body.Builder> bodies = new ArrayList<>();
1594 
1595             while (tree != null) {
1596                 JCTree.JCExpression cond = TreeInfo.skipParens(tree.cond);
1597 
1598                 // Push if condition
1599                 pushBody(cond,
1600                         CoreType.functionType(JavaType.BOOLEAN));
1601                 Value last = toValue(cond, syms.booleanType);
1602                 // Yield the boolean result of the condition
1603                 append(CoreOp.core_yield(last));
1604                 bodies.add(stack.body);
1605 
1606                 // Pop if condition
1607                 popBody();
1608 
1609                 // Push if body
1610                 pushBody(tree.thenpart, CoreType.FUNCTION_TYPE_VOID);
1611 
1612                 scan(tree.thenpart);
1613                 appendTerminating(CoreOp::core_yield);
1614                 bodies.add(stack.body);
1615 
1616                 // Pop if body
1617                 popBody();
1618 
1619                 JCTree.JCStatement elsepart = tree.elsepart;
1620                 if (elsepart == null) {
1621                     tree = null;
1622                 } else if (elsepart.getTag() == Tag.IF) {
1623                     tree = (JCTree.JCIf) elsepart;
1624                 } else {
1625                     // Push else body
1626                     pushBody(elsepart, CoreType.FUNCTION_TYPE_VOID);
1627 
1628                     scan(elsepart);
1629                     appendTerminating(CoreOp::core_yield);
1630                     bodies.add(stack.body);
1631 
1632                     // Pop else body
1633                     popBody();
1634 
1635                     tree = null;
1636                 }
1637             }
1638 
1639             append(JavaOp.if_(bodies));
1640             result = null;
1641         }
1642 
1643         @Override
1644         public void visitSwitchExpression(JCTree.JCSwitchExpression tree) {
1645             Value target = toValue(tree.selector);
1646 
1647             Type switchType = adaptBottom(tree.type);
1648             FunctionType caseBodyType = CoreType.functionType(typeToCodeType(switchType));
1649 
1650             List<Body.Builder> bodies = visitSwitchStatAndExpr(tree, tree.selector, target, tree.cases, caseBodyType,
1651                     !tree.hasUnconditionalPattern);
1652 
1653             result = append(JavaOp.switchExpression(caseBodyType.returnType(), target, bodies));
1654         }
1655 
1656         @Override
1657         public void visitSwitch(JCTree.JCSwitch tree) {
1658             Value target = toValue(tree.selector);
1659 
1660             FunctionType actionType = CoreType.FUNCTION_TYPE_VOID;
1661 
1662             List<Body.Builder> bodies = visitSwitchStatAndExpr(tree, tree.selector, target, tree.cases, actionType,
1663                     tree.patternSwitch && !tree.hasUnconditionalPattern);
1664 
1665             result = append(JavaOp.switchStatement(target, bodies));
1666         }
1667 
1668         private List<Body.Builder> visitSwitchStatAndExpr(JCTree tree, JCExpression selector, Value target,
1669                                                           List<JCTree.JCCase> cases, FunctionType caseBodyType,
1670                                                           boolean isDefaultCaseNeeded) {
1671             List<Body.Builder> bodies = new ArrayList<>();
1672             Map<Symbol, JCVariableDecl> prevCaseVars = new LinkedHashMap<>();
1673             boolean hasDefaultCase = false;
1674 
1675             for (JCTree.JCCase c : cases) {
1676                 if (isDefault(c)) {
1677                     hasDefaultCase = true;
1678                 }
1679                 if (c.labels.size() == 2 && c.labels.getFirst() instanceof JCConstantCaseLabel ccl &&
1680                         TreeInfo.isNull(ccl.expr) && c.labels.last() instanceof JCDefaultCaseLabel) {
1681                     // case null, default is modeled as case null that fallthrough to default
1682                     // case null label body
1683                     pushBody(ccl, CoreType.functionType(JavaType.BOOLEAN, target.type()));
1684                     Block.Parameter localTarget = stack.body.entryBlock().parameters().getFirst();
1685                     Op.Result nullConstant = append(CoreOp.constant(target.type(), null));
1686                     Op.Result p = append(JavaOp.eq(localTarget, nullConstant));
1687                     append(CoreOp.core_yield(p));
1688                     Body.Builder caseNullLabel = stack.body;
1689                     popBody();
1690 
1691                     // case null action body
1692                     pushBody(c.body, caseBodyType);
1693                     append(JavaOp.switchFallthroughOp());
1694                     Body.Builder caseNullBody = stack.body;
1695                     popBody();
1696 
1697                     bodies.add(caseNullLabel);
1698                     bodies.add(caseNullBody);
1699                     // we let the default case to be handled by the below code
1700                 }
1701                 Body.Builder caseLabel = visitCaseLabel(tree, target, c);
1702                 Body.Builder caseBody = visitCaseBody(tree, c, prevCaseVars, caseBodyType, cases.getLast() == c);
1703                 addVars(c.stats, prevCaseVars);
1704                 bodies.add(caseLabel);
1705                 bodies.add(caseBody);
1706             }
1707 
1708             if (!hasDefaultCase && isDefaultCaseNeeded) {
1709                 // label
1710                 pushBody(tree, CoreType.functionType(JavaType.BOOLEAN));
1711                 append(CoreOp.core_yield(append(CoreOp.constant(JavaType.BOOLEAN, true))));
1712                 bodies.add(stack.body);
1713                 popBody();
1714 
1715                 // body
1716                 pushBody(tree, caseBodyType);
1717                 MethodRef matchException = MethodRef.constructor(MatchException.class, String.class, Throwable.class);
1718                 Value message = append(CoreOp.constant(JavaType.J_L_STRING, null));
1719                 Value cause = append(CoreOp.constant(JavaType.type(Throwable.class), null));
1720                 MethodRef.constructor(MatchException.class, String.class, Throwable.class);
1721                 append(JavaOp.throw_(
1722                         append(JavaOp.new_(matchException, message, cause))
1723                 ));
1724                 bodies.add(stack.body);
1725                 popBody();
1726             }
1727 
1728             return bodies;
1729         }
1730 
1731         private static void addVars(com.sun.tools.javac.util.List<JCStatement> stats, Map<Symbol, JCVariableDecl> vars) {
1732             for (; stats.nonEmpty(); stats = stats.tail) {
1733                 JCTree stat = stats.head;
1734                 if (stat.hasTag(Tag.VARDEF)) {
1735                     vars.put(((JCVariableDecl) stat).sym, (JCVariableDecl) stat);
1736                 }
1737             }
1738         }
1739 
1740         boolean handlesNull(JCTree.JCCase caseTree) {
1741             return caseTree.labels.stream().anyMatch(l -> l instanceof JCConstantCaseLabel constLabel &&
1742                     TreeInfo.isNull(constLabel.expr));
1743         }
1744 
1745         boolean isDefault(JCTree.JCCase caseTree) {
1746             return caseTree.labels.stream().anyMatch(l -> l instanceof JCDefaultCaseLabel);
1747         }
1748 
1749         private Value processConstantLabel(Value target, JCTree.JCConstantCaseLabel label) {
1750             if (target.type().equals(JavaType.J_L_STRING)) {
1751                 return append(JavaOp.invoke(
1752                         MethodRef.method(Objects.class, "equals", boolean.class, Object.class, Object.class),
1753                         target, toValue(label.expr)));
1754             } else {
1755                 // target is primitive wrapper, primitive or enum
1756                 // if target of type Character, Byte, Short or Integer, unbox it
1757                 if (target.type().equals(JavaType.J_L_CHARACTER) || target.type().equals(JavaType.J_L_BYTE) ||
1758                         target.type().equals(JavaType.J_L_SHORT) || target.type().equals(JavaType.J_L_INTEGER)) {
1759                     PrimitiveType pt = ((ClassType) target.type()).unbox().get();
1760                     target = convert(target, codeTypeToType(pt));
1761                 }
1762                 Object constant = label.expr.type.constValue();
1763                 Value expr;
1764                 if (constant != null && (target.type().equals(JavaType.BYTE) || target.type().equals(JavaType.SHORT) ||
1765                         target.type().equals(JavaType.CHAR) || target.type().equals(JavaType.INT))) {
1766                     // conversion for primitive, e.g. label (byte) 1 and selector of type int
1767                     expr = append(CoreOp.constant(target.type(), Constants.decode(constant, codeTypeToType(target.type()))));
1768                 } else {
1769                     expr = toValue(label.expr);
1770                     expr = convert(expr, codeTypeToType(target.type()));
1771                 }
1772                 return append(JavaOp.eq(target, expr));
1773             }
1774         }
1775 
1776         private Body.Builder visitCaseLabel(JCTree tree, Value target, JCTree.JCCase c) {
1777             Body.Builder body;
1778             FunctionType caseLabelType = CoreType.functionType(JavaType.BOOLEAN, target.type());
1779 
1780             JCTree.JCCaseLabel headCl = c.labels.head;
1781             if (isDefault(c)) {
1782                 // @@@ Do we need to model the default label body?
1783                 pushBody(headCl, CoreType.functionType(JavaType.BOOLEAN));
1784 
1785                 append(CoreOp.core_yield(append(CoreOp.constant(JavaType.BOOLEAN, true))));
1786                 body = stack.body;
1787 
1788                 // Pop label
1789                 popBody();
1790             } else if (headCl instanceof JCTree.JCPatternCaseLabel pcl) {
1791                 boolean isMultiLabel = c.labels.size() > 1;
1792 
1793                 pushBody(pcl, caseLabelType);
1794 
1795                 Value localTarget = stack.block.parameters().get(0);
1796                 final Value localResult;
1797                 if (c.guard != null) {
1798                     List<Body.Builder> clBodies = new ArrayList<>();
1799 
1800                     if (isMultiLabel) {
1801                         // push a body for or-ing the patterns
1802                         pushBody(pcl, CoreType.functionType(JavaType.BOOLEAN));
1803                     }
1804 
1805                     for (JCCaseLabel l : c.labels) {
1806                         JCTree.JCPatternCaseLabel pat = (JCTree.JCPatternCaseLabel)l;
1807                         clBodies.add(scanPatternAsBody(pat.pat, localTarget));
1808                     }
1809 
1810                     if (isMultiLabel) {
1811                         // or the pattern bodies and replace clBodies with a single body
1812                         Value patternOrResult = append(JavaOp.conditionalOr(clBodies));
1813                         append(CoreOp.core_yield(patternOrResult));
1814                         clBodies.clear();
1815                         clBodies.add(stack.body);
1816                         popBody();
1817                     }
1818 
1819                     pushBody(c.guard, CoreType.functionType(JavaType.BOOLEAN));
1820                     append(CoreOp.core_yield(toValue(c.guard, syms.booleanType)));
1821                     clBodies.add(stack.body);
1822                     popBody();
1823 
1824                     localResult = append(JavaOp.conditionalAnd(clBodies));
1825                 } else if (isMultiLabel) {
1826                     List<Body.Builder> clBodies = new ArrayList<>();
1827                     for (JCCaseLabel l : c.labels) {
1828                         JCTree.JCPatternCaseLabel pat = (JCTree.JCPatternCaseLabel)l;
1829                         clBodies.add(scanPatternAsBody(pat.pat, localTarget));
1830                     }
1831                     localResult = append(JavaOp.conditionalOr(clBodies));
1832                 } else {
1833                     localTarget = boxIfNeeded(localTarget);
1834                     localResult = scanPattern(pcl.pat, localTarget);
1835                 }
1836                 // Yield the boolean result of the condition
1837                 append(CoreOp.core_yield(localResult));
1838                 body = stack.body;
1839 
1840                 // Pop label
1841                 popBody();
1842             } else if (headCl instanceof JCTree.JCConstantCaseLabel ccl) {
1843                 pushBody(headCl, caseLabelType);
1844 
1845                 Value localTarget = stack.block.parameters().get(0);
1846                 final Value localResult;
1847                 if (c.labels.size() == 1) {
1848                     if (TreeInfo.isNull(ccl.expr)) {
1849                         localResult = append(JavaOp.eq(localTarget, append(CoreOp.constant(localTarget.type(), null))));
1850                     } else {
1851                         localResult = processConstantLabel(localTarget, ccl);
1852                     }
1853                 } else {
1854                     List<Body.Builder> clBodies = new ArrayList<>();
1855                     for (JCTree.JCCaseLabel cl : c.labels) {
1856                         ccl = (JCTree.JCConstantCaseLabel) cl;
1857                         pushBody(ccl, CoreType.functionType(JavaType.BOOLEAN));
1858 
1859                         final Value labelResult = processConstantLabel(localTarget, ccl);
1860 
1861                         append(CoreOp.core_yield(labelResult));
1862                         clBodies.add(stack.body);
1863 
1864                         // Pop label
1865                         popBody();
1866                     }
1867 
1868                     localResult = append(JavaOp.conditionalOr(clBodies));
1869                 }
1870 
1871                 append(CoreOp.core_yield(localResult));
1872                 body = stack.body;
1873 
1874                 // Pop labels
1875                 popBody();
1876             } else {
1877                 throw unreachable();
1878             }
1879 
1880             return body;
1881         }
1882 
1883         private Body.Builder visitCaseBody(JCTree tree, JCTree.JCCase c, Map<Symbol, JCVariableDecl> prevCaseVars, FunctionType caseBodyType, boolean isLastCase) {
1884             Body.Builder body = null;
1885 
1886             switch (c.caseKind) {
1887                 case RULE -> {
1888                     pushBody(c.body, caseBodyType);
1889 
1890                     if (c.body instanceof JCTree.JCExpression e) {
1891                         Type yieldType = adaptBottom(tree.type);
1892                         Value bodyVal = toValue(e, yieldType);
1893                         append(CoreOp.core_yield(bodyVal));
1894                     } else if (c.body instanceof JCTree.JCStatement s) { // this includes Block
1895                         // Otherwise there is a yield statement
1896                         toValue(s);
1897                         appendTerminating(c.completesNormally ? CoreOp::core_yield : CoreOp::unreachable);
1898                     }
1899                     body = stack.body;
1900 
1901                     // Pop block
1902                     popBody();
1903                 }
1904                 case STATEMENT -> {
1905                     // @@@ Avoid nesting for a single block? Goes against "say what you see"
1906                     // boolean oneBlock = c.stats.size() == 1 && c.stats.head instanceof JCBlock;
1907                     pushBody(c, caseBodyType);
1908 
1909                     for (JCVariableDecl var : assignedIn(prevCaseVars, c.stats)) {
1910                         result = append(CoreOp.var(var.name.toString(), typeToCodeType(var.type)), generateLocation(var, false));
1911                         stack.localToOp.put(var.sym, result);
1912                     }
1913 
1914                     scan(c.stats);
1915 
1916                     appendTerminating(c.completesNormally
1917                             ? isLastCase ? CoreOp::core_yield : JavaOp::switchFallthroughOp
1918                             : CoreOp::unreachable);
1919 
1920                     body = stack.body;
1921 
1922                     // Pop block
1923                     popBody();
1924                 }
1925             }
1926             return body;
1927         }
1928 
1929         private Set<JCVariableDecl> assignedIn(Map<Symbol, JCVariableDecl> vars, com.sun.tools.javac.util.List<JCStatement> stats) {
1930             final Set<JCVariableDecl> initVars = new LinkedHashSet<>();
1931             new TreeScanner() {
1932                 @Override
1933                 public void visitAssign(JCAssign tree) {
1934                     JCVariableDecl var = vars.get(TreeInfo.symbol(TreeInfo.skipParens(tree.lhs)));
1935                     if (var != null) {
1936                         initVars.add(var);
1937                     }
1938                     super.visitAssign(tree);
1939                 }
1940                 @Override
1941                 public void visitLambda(JCLambda tree) {
1942                 }
1943                 @Override
1944                 public void visitClassDef(JCClassDecl tree) {
1945                 }
1946             }.scan(stats);
1947             return initVars;
1948         }
1949 
1950         @Override
1951         public void visitYield(JCTree.JCYield tree) {
1952             Type yieldType = adaptBottom(tree.target.type);
1953             Value retVal = toValue(tree.value, yieldType);
1954             result = append(JavaOp.java_yield(retVal));
1955         }
1956 
1957         @Override
1958         public void visitWhileLoop(JCTree.JCWhileLoop tree) {
1959             // @@@ Patterns
1960             JCTree.JCExpression cond = TreeInfo.skipParens(tree.cond);
1961 
1962             // Push while condition
1963             pushBody(cond, CoreType.functionType(JavaType.BOOLEAN));
1964             Value last = toValue(cond, syms.booleanType);
1965             // Yield the boolean result of the condition
1966             append(CoreOp.core_yield(last));
1967             Body.Builder condition = stack.body;
1968 
1969             // Pop while condition
1970             popBody();
1971 
1972             // Push while body
1973             pushBody(tree.body, CoreType.FUNCTION_TYPE_VOID);
1974             scan(tree.body);
1975             appendTerminating(JavaOp::continue_);
1976             Body.Builder body = stack.body;
1977 
1978             // Pop while body
1979             popBody();
1980 
1981             append(JavaOp.while_(condition, body));
1982             result = null;
1983         }
1984 
1985         @Override
1986         public void visitDoLoop(JCTree.JCDoWhileLoop tree) {
1987             // @@@ Patterns
1988             JCTree.JCExpression cond = TreeInfo.skipParens(tree.cond);
1989 
1990             // Push while body
1991             pushBody(tree.body, CoreType.FUNCTION_TYPE_VOID);
1992             scan(tree.body);
1993             appendTerminating(JavaOp::continue_);
1994             Body.Builder body = stack.body;
1995 
1996             // Pop while body
1997             popBody();
1998 
1999             // Push while condition
2000             pushBody(cond, CoreType.functionType(JavaType.BOOLEAN));
2001             Value last = toValue(cond, syms.booleanType);
2002             // Yield the boolean result of the condition
2003             append(CoreOp.core_yield(last));
2004             Body.Builder condition = stack.body;
2005 
2006             // Pop while condition
2007             popBody();
2008 
2009             append(JavaOp.doWhile(body, condition));
2010             result = null;
2011         }
2012 
2013         @Override
2014         public void visitForeachLoop(JCTree.JCEnhancedForLoop tree) {
2015             // Push expression
2016             pushBody(tree.expr, CoreType.functionType(typeToCodeType(tree.expr.type)));
2017             Value last = toValue(tree.expr);
2018             // Yield the Iterable result of the expression
2019             append(CoreOp.core_yield(last));
2020             Body.Builder expression = stack.body;
2021 
2022             // Pop expression
2023             popBody();
2024 
2025             JCVariableDecl var = tree.getVariable();
2026             VarType varEType = CoreType.varType(typeToCodeType(var.type));
2027 
2028             // Push init
2029             // @@@ When lhs assignment is a pattern we embed the pattern match into the init body and
2030             // return the bound variables
2031             Type exprType = types.cvarUpperBound(tree.expr.type);
2032             Type elemtype = types.elemtype(exprType); // perhaps expr is an array?
2033             if (elemtype == null) {
2034                 Type iterableType = types.asSuper(tree.expr.type, syms.iterableType.tsym);
2035                 com.sun.tools.javac.util.List<Type> iterableParams = iterableType.allparams();
2036                 elemtype = iterableParams.isEmpty()
2037                         ? syms.objectType
2038                         : types.wildUpperBound(iterableParams.head);
2039             }
2040             pushBody(var, CoreType.functionType(varEType, typeToCodeType(elemtype)));
2041             var initVarExpr = convert(stack.block.parameters().get(0), var.type);
2042             Op.Result varEResult = append(CoreOp.var(var.name.toString(), initVarExpr));
2043             append(CoreOp.core_yield(varEResult));
2044             Body.Builder init = stack.body;
2045             // Pop init
2046             popBody();
2047 
2048             // Push body
2049             pushBody(tree.body, CoreType.functionType(JavaType.VOID, varEType));
2050             stack.localToOp.put(var.sym, stack.block.parameters().get(0));
2051 
2052             scan(tree.body);
2053             appendTerminating(JavaOp::continue_);
2054             Body.Builder body = stack.body;
2055             // Pop body
2056             popBody();
2057 
2058             append(JavaOp.enhancedFor(expression, init, body));
2059             result = null;
2060         }
2061 
2062         @Override
2063         public void visitForLoop(JCTree.JCForLoop tree) {
2064             class VarDefScanner extends FilterScanner {
2065                 final List<JCVariableDecl> decls;
2066 
2067                 public VarDefScanner() {
2068                     super(Set.of(Tag.VARDEF));
2069                     this.decls = new ArrayList<>();
2070                 }
2071 
2072                 @Override
2073                 public void visitVarDef(JCVariableDecl tree) {
2074                     // only non-constants enter the loop's variable state
2075                     if (tree.sym.getConstantValue() == null) decls.add(tree);
2076                 }
2077 
2078                 void mapVarsToBlockArguments() {
2079                     for (int i = 0; i < decls.size(); i++) {
2080                         stack.localToOp.put(decls.get(i).sym, stack.block.parameters().get(i));
2081                     }
2082                 }
2083 
2084                 List<VarType> varTypes() {
2085                     return decls.stream()
2086                             .map(t -> CoreType.varType(typeToCodeType(t.type)))
2087                             .toList();
2088                 }
2089 
2090                 List<Value> varValues() {
2091                     return decls.stream()
2092                             .map(t -> stack.localToOp.get(t.sym))
2093                             .toList();
2094                 }
2095             }
2096 
2097             // Scan local variable declarations
2098             VarDefScanner vds = new VarDefScanner();
2099             vds.scan(tree.init);
2100             List<VarType> varTypes = vds.varTypes();
2101 
2102             // Push init
2103             if (varTypes.size() > 1) {
2104                 pushBody(null, CoreType.functionType(CoreType.tupleType(varTypes)));
2105                 scan(tree.init);
2106 
2107                 // Capture all local variable declarations in tuple
2108                 append(CoreOp.core_yield(append(CoreOp.tuple(vds.varValues()))));
2109             } else if (varTypes.size() == 1) {
2110                 pushBody(null, CoreType.functionType(varTypes.get(0)));
2111                 scan(tree.init);
2112 
2113                 append(CoreOp.core_yield(vds.varValues().get(0)));
2114             } else {
2115                 pushBody(null, CoreType.FUNCTION_TYPE_VOID);
2116                 scan(tree.init);
2117 
2118                 append(CoreOp.core_yield());
2119             }
2120             Body.Builder init = stack.body;
2121 
2122             // Pop init
2123             popBody();
2124 
2125             // Push cond
2126             pushBody(tree.cond, CoreType.functionType(JavaType.BOOLEAN, varTypes));
2127             if (tree.cond != null) {
2128                 vds.mapVarsToBlockArguments();
2129 
2130                 Value last = toValue(tree.cond, syms.booleanType);
2131                 // Yield the boolean result of the condition
2132                 append(CoreOp.core_yield(last));
2133             } else {
2134                 append(CoreOp.core_yield(append(CoreOp.constant(JavaType.BOOLEAN, true))));
2135             }
2136             Body.Builder cond = stack.body;
2137 
2138             // Pop cond
2139             popBody();
2140 
2141             // Push update
2142             // @@@ tree.step is a List<JCStatement>
2143             pushBody(null, CoreType.functionType(JavaType.VOID, varTypes));
2144             if (!tree.step.isEmpty()) {
2145                 vds.mapVarsToBlockArguments();
2146 
2147                 scan(tree.step);
2148             }
2149             append(CoreOp.core_yield());
2150             Body.Builder update = stack.body;
2151 
2152             // Pop update
2153             popBody();
2154 
2155             // Push body
2156             pushBody(tree.body, CoreType.functionType(JavaType.VOID, varTypes));
2157             if (tree.body != null) {
2158                 vds.mapVarsToBlockArguments();
2159 
2160                 scan(tree.body);
2161             }
2162             appendTerminating(JavaOp::continue_);
2163             Body.Builder body = stack.body;
2164 
2165             // Pop update
2166             popBody();
2167 
2168             append(JavaOp.for_(init, cond, update, body));
2169             result = null;
2170         }
2171 
2172         @Override
2173         public void visitConditional(JCTree.JCConditional tree) {
2174             JCTree.JCExpression cond = TreeInfo.skipParens(tree.cond);
2175 
2176             // Push condition
2177             pushBody(cond,
2178                     CoreType.functionType(JavaType.BOOLEAN));
2179             Value condVal = toValue(cond, syms.booleanType);
2180             // Yield the boolean result of the condition
2181             append(CoreOp.core_yield(condVal));
2182             Body.Builder predicateBody = stack.body;
2183 
2184             // Pop condition
2185             popBody();
2186 
2187             JCTree.JCExpression truepart = TreeInfo.skipParens(tree.truepart);
2188 
2189             Type condType = adaptBottom(tree.type);
2190 
2191             // Push true body
2192             pushBody(truepart,
2193                     CoreType.functionType(typeToCodeType(condType)));
2194 
2195             Value trueVal = toValue(truepart, condType);
2196             // Yield the result
2197             append(CoreOp.core_yield(trueVal));
2198             Body.Builder trueBody = stack.body;
2199 
2200             // Pop true body
2201             popBody();
2202 
2203             JCTree.JCExpression falsepart = TreeInfo.skipParens(tree.falsepart);
2204 
2205             // Push false body
2206             pushBody(falsepart,
2207                     CoreType.functionType(typeToCodeType(condType)));
2208 
2209             Value falseVal = toValue(falsepart, condType);
2210             // Yield the result
2211             append(CoreOp.core_yield(falseVal));
2212             Body.Builder falseBody = stack.body;
2213 
2214             // Pop false body
2215             popBody();
2216 
2217             result = append(JavaOp.conditionalExpression(typeToCodeType(condType), predicateBody, trueBody, falseBody));
2218         }
2219 
2220         private Type adaptBottom(Type type) {
2221             return type.hasTag(BOT) ?
2222                     (pt.hasTag(NONE) ? syms.objectType : pt) :
2223                     type;
2224         }
2225 
2226         @Override
2227         public void visitAssert(JCAssert tree) {
2228             // assert <cond:body1> [detail:body2]
2229 
2230             List<Body.Builder> bodies = new ArrayList<>();
2231             JCTree.JCExpression cond = TreeInfo.skipParens(tree.cond);
2232 
2233             // Push condition
2234             pushBody(cond,
2235                     CoreType.functionType(JavaType.BOOLEAN));
2236             Value condVal = toValue(cond, syms.booleanType);
2237 
2238             // Yield the boolean result of the condition
2239             append(CoreOp.core_yield(condVal));
2240             bodies.add(stack.body);
2241 
2242             // Pop condition
2243             popBody();
2244 
2245             if (tree.detail != null) {
2246                 JCTree.JCExpression detail = TreeInfo.skipParens(tree.detail);
2247 
2248                 pushBody(detail,
2249                         CoreType.functionType(typeToCodeType(tree.detail.type)));
2250                 Value detailVal = toValue(detail);
2251 
2252                 append(CoreOp.core_yield(detailVal));
2253                 bodies.add(stack.body);
2254 
2255                 //Pop detail
2256                 popBody();
2257             }
2258 
2259             result = append(JavaOp.assert_(bodies));
2260 
2261         }
2262 
2263         @Override
2264         public void visitBlock(JCTree.JCBlock tree) {
2265             if (stack.tree == tree) {
2266                 // Block is associated with the visit of a parent structure
2267                 scan(tree.stats);
2268             } else {
2269                 // Otherwise, independent block structure
2270                 // Push block
2271                 pushBody(tree, CoreType.FUNCTION_TYPE_VOID);
2272                 scan(tree.stats);
2273                 appendTerminating(CoreOp::core_yield);
2274                 Body.Builder body = stack.body;
2275 
2276                 // Pop block
2277                 popBody();
2278 
2279                 append(JavaOp.block(body));
2280             }
2281             result = null;
2282         }
2283 
2284         @Override
2285         public void visitSynchronized(JCTree.JCSynchronized tree) {
2286             // Push expr
2287             pushBody(tree.lock, CoreType.functionType(typeToCodeType(tree.lock.type)));
2288             Value last = toValue(tree.lock);
2289             append(CoreOp.core_yield(last));
2290             Body.Builder expr = stack.body;
2291 
2292             // Pop expr
2293             popBody();
2294 
2295             // Push body block
2296             pushBody(tree.body, CoreType.FUNCTION_TYPE_VOID);
2297             // Scan body block statements
2298             scan(tree.body.stats);
2299             appendTerminating(CoreOp::core_yield);
2300             Body.Builder blockBody = stack.body;
2301 
2302             // Pop body block
2303             popBody();
2304 
2305             append(JavaOp.synchronized_(expr, blockBody));
2306         }
2307 
2308         @Override
2309         public void visitLabelled(JCTree.JCLabeledStatement tree) {
2310             // Push block
2311             pushBody(tree, CoreType.FUNCTION_TYPE_VOID);
2312             // Create constant for label
2313             String labelName = tree.label.toString();
2314             Op.Result label = append(CoreOp.constant(JavaType.J_L_STRING, labelName));
2315             // Set label on body stack
2316             stack.setLabel(labelName, label);
2317             scan(tree.body);
2318             appendTerminating(CoreOp::core_yield);
2319             Body.Builder body = stack.body;
2320 
2321             // Pop block
2322             popBody();
2323 
2324             result = append(JavaOp.labeled(body));
2325         }
2326 
2327         @Override
2328         public void visitTry(JCTree.JCTry tree) {
2329             List<Symbol> rVariableDecls = new ArrayList<>();
2330             List<CodeType> rTypes = new ArrayList<>();
2331             List<Body.Builder> resources = new ArrayList<>();
2332             if (!tree.resources.isEmpty()) {
2333                 // Resources bodies return the resource variables/values in order of declaration
2334                 for (JCTree resource : tree.resources) {
2335                     CodeType rType;
2336                     if (resource instanceof JCVariableDecl vdecl) {
2337                         rType = CoreType.varType(typeToCodeType(vdecl.type));
2338                     } else {
2339                         rType = typeToCodeType(resource.type);
2340                     }
2341 
2342                     // Push resources body
2343                     pushBody(null, CoreType.functionType(rType, rTypes));
2344                     for (int i = 0; i < rVariableDecls.size(); i++) {
2345                         Symbol rVariableDecl = rVariableDecls.get(i);
2346                         if (rVariableDecl != null) {
2347                             stack.localToOp.put(rVariableDecl, stack.block.parameters().get(i));
2348                         }
2349                     }
2350 
2351                     if (resource instanceof JCTree.JCExpression e) {
2352                         append(CoreOp.core_yield(toValue(e)));
2353                     } else if (resource instanceof JCTree.JCStatement s) {
2354                         append(CoreOp.core_yield(toValue(s)));
2355                     }
2356 
2357                     resources.add(stack.body);
2358 
2359                     // Pop resources body
2360                     popBody();
2361 
2362                     // Null entries preserve positions for resource expressions, which have no variable declaration.
2363                     rVariableDecls.add(resource instanceof JCVariableDecl vdecl ? vdecl.sym : null);
2364                     rTypes.add(rType);
2365                 }
2366             }
2367 
2368             // Push body
2369             // Try body accepts the resource variables (in order of declaration).
2370             pushBody(tree.body, CoreType.functionType(JavaType.VOID, rTypes));
2371             for (int i = 0; i < rVariableDecls.size(); i++) {
2372                 stack.localToOp.put(rVariableDecls.get(i), stack.block.parameters().get(i));
2373             }
2374             scan(tree.body);
2375             appendTerminating(CoreOp::core_yield);
2376             Body.Builder body = stack.body;
2377 
2378             // Pop block
2379             popBody();
2380 
2381             List<CodeType> catchTypes = new ArrayList<>();
2382             List<Body.Builder> catchers = new ArrayList<>();
2383             for (JCTree.JCCatch catcher : tree.catchers) {
2384 
2385                 catchTypes.add(TreeInfo.isMultiCatch(catcher)
2386                         ? CoreType.tupleType(((JCTree.JCTypeUnion) catcher.param.vartype).alternatives.stream()
2387                                 .map(a -> typeToCodeType(a.type)).toList())
2388                         : typeToCodeType(catcher.param.vartype.type));
2389 
2390                 // Push body
2391                 pushBody(catcher.body, CoreType.functionType(JavaType.VOID, typeToCodeType(catcher.param.type)));
2392                 Op.Result exVariable = append(CoreOp.var(
2393                         catcher.param.name.toString(),
2394                         stack.block.parameters().get(0)));
2395                 stack.localToOp.put(catcher.param.sym, exVariable);
2396                 scan(catcher.body);
2397                 appendTerminating(CoreOp::core_yield);
2398                 catchers.add(stack.body);
2399 
2400                 // Pop block
2401                 popBody();
2402             }
2403 
2404             Body.Builder finalizer;
2405             if (tree.finalizer != null) {
2406                 // Push body
2407                 pushBody(tree.finalizer, CoreType.FUNCTION_TYPE_VOID);
2408                 scan(tree.finalizer);
2409                 appendTerminating(CoreOp::core_yield);
2410                 finalizer = stack.body;
2411 
2412                 // Pop block
2413                 popBody();
2414             }
2415             else {
2416                 finalizer = null;
2417             }
2418 
2419             result = append(JavaOp.try_(resources, body, catchTypes, catchers, finalizer));
2420         }
2421 
2422         @Override
2423         public void visitUnary(JCTree.JCUnary tree) {
2424             Tag tag = tree.getTag();
2425             switch (tag) {
2426                 case POSTINC, POSTDEC, PREINC, PREDEC -> {
2427                     // Capture applying rhs and operation
2428                     Function<Value, Value> scanRhs = (lhs) -> {
2429                         // arithmetic operators are all of kind (T, T)T
2430                         Type opType = tree.operator.type.getReturnType();
2431                         if (!opType.hasTag(INT) &&
2432                                 opType.getTag().isSubRangeOf(INT)) {
2433                             // unary ++/-- can use sub-int operator types,
2434                             // which doesn't make sense for the model
2435                             opType = syms.intType;
2436                         }
2437 
2438                         // We first convert LHS, then process RHS
2439                         // While JLS doesn't require this, javac generates bytecode this way
2440                         Value lhsConv = convert(lhs, opType);
2441                         Value one = append(numericOneValue(opType));
2442 
2443                         Value lhsPlusOne = (tag == Tag.PREINC || tag ==  Tag.POSTINC) ?
2444                             append(JavaOp.add(lhsConv, one)) :
2445                             append(JavaOp.sub(lhsConv, one));
2446                         lhsPlusOne = convert(lhsPlusOne, tree.type);
2447 
2448                         // Assign expression result
2449                         result = (tag == Tag.POSTINC || tag == Tag.POSTDEC) ?
2450                                 lhs : lhsPlusOne;
2451                         return lhsPlusOne;
2452                     };
2453 
2454                     applyCompoundAssign(tree.arg, scanRhs);
2455                 }
2456                 case NEG -> {
2457                     Value rhs = toValue(tree.arg, tree.type);
2458                     result = append(JavaOp.neg(rhs));
2459                 }
2460                 case NOT -> {
2461                     Value rhs = toValue(tree.arg, tree.type);
2462                     result = append(JavaOp.not(rhs));
2463                 }
2464                 case COMPL -> {
2465                     Value rhs = toValue(tree.arg, tree.type);
2466                     result = append(JavaOp.compl(rhs));
2467                 }
2468                 case POS -> {
2469                     Value rhs = toValue(tree.arg, tree.type);
2470                     result = append(JavaOp.pos(rhs));
2471                 }
2472                 case NULLCHK -> {
2473                     result = toValue(tree.arg, tree.type);
2474                     MethodRef ref = MethodRef.method(Objects.class, "requireNonNull", Object.class, Object.class);
2475                     append(JavaOp.invoke(JavaOp.InvokeOp.InvokeKind.STATIC, false, JavaType.J_L_OBJECT, ref, result));
2476                 }
2477                 default -> throw unreachable();
2478             }
2479         }
2480 
2481         @Override
2482         public void visitBinary(JCBinary tree) {
2483             Tag tag = tree.getTag();
2484             if (tag == Tag.AND || tag == Tag.OR) {
2485                 // Logical operations
2486                 // @@@ Flatten nested sequences
2487 
2488                 // Push lhs
2489                 pushBody(tree.lhs, CoreType.functionType(JavaType.BOOLEAN));
2490                 Value lhs = toValue(tree.lhs, syms.booleanType);
2491                 // Yield the boolean result of the condition
2492                 append(CoreOp.core_yield(lhs));
2493                 Body.Builder bodyLhs = stack.body;
2494 
2495                 // Pop lhs
2496                 popBody();
2497 
2498                 // Push rhs
2499                 pushBody(tree.rhs, CoreType.functionType(JavaType.BOOLEAN));
2500                 Value rhs = toValue(tree.rhs, syms.booleanType);
2501                 // Yield the boolean result of the condition
2502                 append(CoreOp.core_yield(rhs));
2503                 Body.Builder bodyRhs = stack.body;
2504 
2505                 // Pop lhs
2506                 popBody();
2507 
2508                 List<Body.Builder> bodies = List.of(bodyLhs, bodyRhs);
2509                 result = append(tag == Tag.AND
2510                         ? JavaOp.conditionalAnd(bodies)
2511                         : JavaOp.conditionalOr(bodies));
2512             } else if (tag == Tag.PLUS && tree.operator.opcode == ByteCodes.string_add) {
2513                 //Ignore the operator and query both subexpressions for their type with concats
2514                 Type lhsType = tree.lhs.type;
2515                 Type rhsType = tree.rhs.type;
2516 
2517                 Value lhs = toValue(tree.lhs, lhsType.hasTag(BOT) ? syms.stringType : lhsType);
2518                 Value rhs = toValue(tree.rhs, rhsType.hasTag(BOT) ? syms.stringType : rhsType);
2519 
2520                 result = append(tree.type.constValue() instanceof String constant
2521                         // Preserve interned String identity
2522                         ? CoreOp.constant(JavaType.J_L_STRING, constant)
2523                         : JavaOp.concat(lhs, rhs));
2524             }
2525             else {
2526                 Type lhsType = tree.operator.type.getParameterTypes().head;
2527                 Type rhsType = tree.operator.type.getParameterTypes().tail.head;
2528                 Value lhs = toValue(tree.lhs, lhsType);
2529                 Value rhs = toValue(tree.rhs, rhsType);
2530 
2531                 result = switch (tag) {
2532                     // Arithmetic operations
2533                     case PLUS -> append(JavaOp.add(lhs, rhs));
2534                     case MINUS -> append(JavaOp.sub(lhs, rhs));
2535                     case MUL -> append(JavaOp.mul(lhs, rhs));
2536                     case DIV -> append(JavaOp.div(lhs, rhs));
2537                     case MOD -> append(JavaOp.mod(lhs, rhs));
2538 
2539                     // Test operations
2540                     case EQ -> append(JavaOp.eq(lhs, rhs));
2541                     case NE -> append(JavaOp.neq(lhs, rhs));
2542                     //
2543                     case LT -> append(JavaOp.lt(lhs, rhs));
2544                     case LE -> append(JavaOp.le(lhs, rhs));
2545                     case GT -> append(JavaOp.gt(lhs, rhs));
2546                     case GE -> append(JavaOp.ge(lhs, rhs));
2547 
2548                     // Bitwise operations (including their boolean variants)
2549                     case BITOR -> append(JavaOp.or(lhs, rhs));
2550                     case BITAND -> append(JavaOp.and(lhs, rhs));
2551                     case BITXOR -> append(JavaOp.xor(lhs, rhs));
2552 
2553                     // Shift operations
2554                     case SL -> append(JavaOp.lshl(lhs, rhs));
2555                     case SR -> append(JavaOp.ashr(lhs, rhs));
2556                     case USR -> append(JavaOp.lshr(lhs, rhs));
2557 
2558                     default -> throw unreachable();
2559                 };
2560             }
2561         }
2562 
2563         @Override
2564         public void visitLiteral(JCLiteral tree) {
2565             Object value = switch (tree.type.getTag()) {
2566                 case BOOLEAN -> tree.value instanceof Integer i && i == 1;
2567                 case CHAR -> (char) (int) tree.value;
2568                 default -> tree.value;
2569             };
2570             Type constantType = adaptBottom(tree.type);
2571             result = append(CoreOp.constant(typeToCodeType(constantType), value));
2572         }
2573 
2574         @Override
2575         public void visitReturn(JCReturn tree) {
2576             Value retVal = toValue(tree.expr, bodyTarget);
2577             if (retVal == null) {
2578                 result = append(CoreOp.return_());
2579             } else {
2580                 result = append(CoreOp.return_(retVal));
2581             }
2582         }
2583 
2584         @Override
2585         public void visitThrow(JCTree.JCThrow tree) {
2586             Value throwVal = toValue(tree.expr);
2587             result = append(JavaOp.throw_(throwVal));
2588         }
2589 
2590         @Override
2591         public void visitBreak(JCTree.JCBreak tree) {
2592             Value label = tree.label != null
2593                     ? getLabel(tree.label.toString())
2594                     : null;
2595             result = append(JavaOp.break_(label));
2596         }
2597 
2598         @Override
2599         public void visitContinue(JCTree.JCContinue tree) {
2600             Value label = tree.label != null
2601                     ? getLabel(tree.label.toString())
2602                     : null;
2603             result = append(JavaOp.continue_(label));
2604         }
2605 
2606         @Override
2607         public void visitClassDef(JCClassDecl tree) {
2608             computeCapturesIfNeeded(tree);
2609         }
2610 
2611         AssertionError unreachable() {
2612             return new AssertionError("Should not reach here!");
2613         }
2614 
2615         CoreOp.FuncOp scanMethod(JCBlock body) {
2616             scan(body, ReflectMethods.this.currentNode());
2617             appendReturnOrUnreachable(body);
2618             MethodRef sourceRef = symbolToMethodRef(((JCMethodDecl) tree).sym);
2619             CoreOp.FuncOp func = CoreOp.func(sourceRef, stack.body);
2620             func.setLocation(generateLocation(tree, true));
2621             return func;
2622         }
2623 
2624         CoreOp.FuncOp scanMethod() {
2625             return scanMethod(((JCMethodDecl)tree).body);
2626         }
2627 
2628         CoreOp.FuncOp scanLambda() {
2629             scan(tree, ReflectMethods.this.prevNode());
2630             // Return the quoted result
2631             append(CoreOp.return_(result));
2632             return CoreOp.func(name.toString(), stack.body);
2633         }
2634 
2635         Op defaultValue(Type t) {
2636             return switch (t.getTag()) {
2637                 case BYTE, SHORT, INT -> CoreOp.constant(JavaType.INT, 0);
2638                 case CHAR -> CoreOp.constant(typeToCodeType(t), (char)0);
2639                 case BOOLEAN -> CoreOp.constant(typeToCodeType(t), false);
2640                 case FLOAT -> CoreOp.constant(typeToCodeType(t), 0f);
2641                 case LONG -> CoreOp.constant(typeToCodeType(t), 0L);
2642                 case DOUBLE -> CoreOp.constant(typeToCodeType(t), 0d);
2643                 default -> CoreOp.constant(typeToCodeType(t), null);
2644             };
2645         }
2646 
2647         Op numericOneValue(Type t) {
2648             return switch (t.getTag()) {
2649                 case BYTE, SHORT, INT -> CoreOp.constant(JavaType.INT, 1);
2650                 case CHAR -> CoreOp.constant(typeToCodeType(t), (char)1);
2651                 case FLOAT -> CoreOp.constant(typeToCodeType(t), 1f);
2652                 case LONG -> CoreOp.constant(typeToCodeType(t), 1L);
2653                 case DOUBLE -> CoreOp.constant(typeToCodeType(t), 1d);
2654                 default -> throw new UnsupportedOperationException(t.toString());
2655             };
2656         }
2657     }
2658 
2659     boolean isReflectable(JCMethodDecl tree) {
2660         return codeReflectionEnabled ||
2661                 (tree.body != null &&
2662                 (reflectAll || tree.sym.attribute(crSyms.codeReflectionType.tsym) != null));
2663     }
2664 
2665     boolean isReflectable(JCFunctionalExpression expr) {
2666         return reflectAll || codeReflectionEnabled ||
2667                 (prevNode() instanceof JCTypeCast castTree && isReflectable(castTree.clazz.type));
2668     }
2669 
2670     boolean isReflectable(Type target) {
2671         if (target.isCompound()) {
2672             return ((IntersectionClassType)target).getComponents().stream()
2673                     .anyMatch(this::isReflectable);
2674         } else {
2675             return target.getAnnotationMirrors().stream()
2676                     .anyMatch(tc -> tc.type.tsym == crSyms.codeReflectionType.tsym);
2677         }
2678     }
2679 
2680     /*
2681      * Converts a method reference which cannot be used directly into a lambda.
2682      * This code has been derived from LambdaToMethod::MemberReferenceToLambda. The main
2683      * difference is that, while that code concerns with translation strategy, boxing
2684      * conversion and type erasure, this version does not and, as such, can remain
2685      * at a higher level. Note that this code needs to create a synthetic variable
2686      * declaration in case of a bounded method reference whose receiver expression
2687      * is other than 'this'/'super' (this is done to prevent the receiver expression
2688      * from being computed twice).
2689      */
2690     private class MemberReferenceToLambda {
2691 
2692         private final JCMemberReference tree;
2693         private final Symbol owner;
2694         private final ListBuffer<JCExpression> args = new ListBuffer<>();
2695         private final ListBuffer<JCVariableDecl> params = new ListBuffer<>();
2696         private JCVariableDecl receiverVar = null;
2697 
2698         MemberReferenceToLambda(JCMemberReference tree, Symbol currentClass) {
2699             this.tree = tree;
2700             this.owner = new MethodSymbol(0, names.lambda, tree.target, currentClass);
2701             if (tree.kind == ReferenceKind.BOUND && !TreeInfo.isThisQualifier(tree.getQualifierExpression())) {
2702                 // true bound method reference, hoist receiver expression out
2703                 Type recvType = tree.getQualifierExpression().type;
2704                 if (types.skipTypeVars(recvType, false).isCompound()) {
2705                     Type erasedRecvType = types.erasure(recvType);
2706                     Symbol sym = types.isSubtype(erasedRecvType, types.erasure(tree.sym.owner.type))
2707                             ? erasedRecvType.tsym
2708                             : tree.sym.owner;
2709                     recvType = types.asSuper(recvType, sym);
2710                 }
2711                 VarSymbol vsym = makeSyntheticVar("rec$", recvType);
2712                 receiverVar = make.VarDef(vsym, attr.makeNullCheck(tree.getQualifierExpression()));
2713             }
2714         }
2715 
2716         JCVariableDecl receiverVar() {
2717             return receiverVar;
2718         }
2719 
2720         JCLambda lambda() {
2721             int prevPos = make.pos;
2722             try {
2723                 make.at(tree);
2724 
2725                 //body generation - this can be either a method call or a
2726                 //new instance creation expression, depending on the member reference kind
2727                 VarSymbol rcvr = addParametersReturnReceiver();
2728                 JCExpression expr = (tree.getMode() == ReferenceMode.INVOKE)
2729                         ? expressionInvoke(rcvr)
2730                         : expressionNew();
2731 
2732                 JCLambda slam = make.Lambda(params.toList(), expr);
2733                 slam.target = tree.target;
2734                 slam.type = tree.type;
2735                 slam.pos = tree.pos;
2736                 return slam;
2737             } finally {
2738                 make.at(prevPos);
2739             }
2740         }
2741 
2742         /**
2743          * Generate the parameter list for the converted member reference.
2744          *
2745          * @return The receiver variable symbol, if any
2746          */
2747         VarSymbol addParametersReturnReceiver() {
2748             com.sun.tools.javac.util.List<Type> descPTypes = tree.getDescriptorType(types).getParameterTypes();
2749             VarSymbol receiverParam = null;
2750             switch (tree.kind) {
2751                 case BOUND:
2752                     if (receiverVar != null) {
2753                         receiverParam = receiverVar.sym;
2754                     }
2755                     break;
2756                 case UNBOUND:
2757                     // The receiver is the first parameter, extract it and
2758                     // adjust the SAM and unerased type lists accordingly
2759                     receiverParam = addParameter("rec$", descPTypes.head, false);
2760                     descPTypes = descPTypes.tail;
2761                     break;
2762             }
2763             for (int i = 0; descPTypes.nonEmpty(); ++i) {
2764                 // By default use the implementation method parameter type
2765                 Type parmType = descPTypes.head;
2766                 addParameter("x$" + i, parmType, true);
2767 
2768                 // Advance to the next parameter
2769                 descPTypes = descPTypes.tail;
2770             }
2771 
2772             return receiverParam;
2773         }
2774 
2775         /**
2776          * determine the receiver of the method call - the receiver can
2777          * be a type qualifier, the synthetic receiver parameter or 'super'.
2778          */
2779         private JCExpression expressionInvoke(VarSymbol receiverParam) {
2780             JCExpression qualifier = receiverParam != null ?
2781                     make.at(tree.pos).Ident(receiverParam) :
2782                     tree.getQualifierExpression();
2783 
2784             //create the qualifier expression
2785             JCFieldAccess select = make.Select(qualifier, tree.sym.name);
2786             select.sym = tree.sym;
2787             select.type = tree.referentType;
2788 
2789             //create the method call expression
2790             JCMethodInvocation apply = make.Apply(com.sun.tools.javac.util.List.nil(), select, args.toList()).
2791                     setType(tree.referentType.getReturnType());
2792 
2793             apply.varargsElement = tree.varargsElement;
2794             return apply;
2795         }
2796 
2797         /**
2798          * Lambda body to use for a 'new'.
2799          */
2800         private JCExpression expressionNew() {
2801             Type expectedType = tree.referentType.getReturnType().hasTag(TypeTag.VOID) ?
2802                     tree.expr.type : tree.referentType.getReturnType();
2803             if (tree.kind == ReferenceKind.ARRAY_CTOR) {
2804                 //create the array creation expression
2805                 JCNewArray newArr = make.NewArray(
2806                         make.Type(types.elemtype(expectedType)),
2807                         com.sun.tools.javac.util.List.of(make.Ident(params.first())),
2808                         null);
2809                 newArr.type = tree.getQualifierExpression().type;
2810                 return newArr;
2811             } else {
2812                 //create the instance creation expression
2813                 //note that method reference syntax does not allow an explicit
2814                 //enclosing class (so the enclosing class is null)
2815                 // but this may need to be patched up later with the proxy for the outer this
2816                 JCExpression newType = make.Type(types.erasure(expectedType));
2817                 if (expectedType.tsym.type.getTypeArguments().nonEmpty()) {
2818                     newType = make.TypeApply(newType, com.sun.tools.javac.util.List.nil());
2819                 }
2820                 JCNewClass newClass = make.NewClass(null,
2821                         com.sun.tools.javac.util.List.nil(),
2822                         newType,
2823                         args.toList(),
2824                         null);
2825                 newClass.constructor = tree.sym;
2826                 newClass.constructorType = tree.referentType;
2827                 newClass.type = expectedType;
2828                 newClass.varargsElement = tree.varargsElement;
2829                 return newClass;
2830             }
2831         }
2832 
2833         private VarSymbol makeSyntheticVar(String name, Type type) {
2834             VarSymbol vsym = new VarSymbol(PARAMETER | SYNTHETIC, names.fromString(name), type, owner);
2835             vsym.pos = tree.pos;
2836             return vsym;
2837         }
2838 
2839         private VarSymbol addParameter(String name, Type type, boolean genArg) {
2840             VarSymbol vsym = makeSyntheticVar(name, type);
2841             params.append(make.VarDef(vsym, null));
2842             if (genArg) {
2843                 args.append(make.Ident(vsym));
2844             }
2845             return vsym;
2846         }
2847     }
2848 
2849     static class JCReflectMethodsClassDecl extends JCClassDecl {
2850 
2851         SequencedMap<Op, Name> ops;
2852 
2853         JCReflectMethodsClassDecl(JCClassDecl cls, SequencedMap<Op, Name> ops) {
2854             super(cls.mods, cls.name, cls.typarams, cls.extending, cls.implementing, cls.permitting, cls.defs, cls.sym);
2855             this.pos = cls.pos;
2856             this.type = cls.type;
2857             this.ops = ops;
2858         }
2859     }
2860 
2861     public static class Provider implements CodeReflectionTransformer {
2862         @Override
2863         public JCTree translateTopLevelClass(Context context, JCTree tree, TreeMaker make) {
2864             return ReflectMethods.instance(context).translateTopLevelClass(tree, make);
2865         }
2866 
2867         @Override
2868         public void genCode(Context context, JCClassDecl cdef) throws IOException {
2869             if (cdef instanceof JCReflectMethodsClassDecl rmcdef) {
2870                 ClassSymbol codeModelsClassSym = new ClassSymbol(IDENTITY_TYPE | STATIC, Names.instance(context).fromString("$CM"), cdef.sym);
2871                 cdef.sym.members().enter(codeModelsClassSym);
2872 
2873                 JavaFileManager fileManager = context.get(JavaFileManager.class);
2874                 JavaFileManager.Location outLocn;
2875                 if (fileManager.hasLocation(StandardLocation.MODULE_SOURCE_PATH)) {
2876                     outLocn = fileManager.getLocationForModule(StandardLocation.CLASS_OUTPUT, cdef.sym.packge().modle.name.toString());
2877                 } else {
2878                     outLocn = StandardLocation.CLASS_OUTPUT;
2879                 }
2880                 String className = codeModelsClassSym.flatName().toString();
2881                 ClassDesc classDesc = ClassDesc.of(className);
2882                 JavaFileObject outFile = fileManager.getJavaFileForOutput(outLocn, className, JavaFileObject.Kind.CLASS, cdef.sym.sourcefile);
2883                 ClassDesc hostClass = ClassDesc.of(cdef.sym.flatName().toString());
2884 
2885                 MethodType getterType = CodeReflectionSymbols.instance(context).opGetterType;
2886                 TreeMaker make = TreeMaker.instance(context).forToplevel(null).at(cdef.pos());
2887                 var getters = new ListBuffer<JCTree>();
2888                 var ops = new LinkedHashMap<String, Op>();
2889                 for (var op : rmcdef.ops.sequencedEntrySet()) {
2890                     if (ops.putIfAbsent(op.getValue().toString(), op.getKey()) == null) {
2891                         var ms = new MethodSymbol(PRIVATE | STATIC | SYNTHETIC, op.getValue(), getterType, rmcdef.sym);
2892                         getters.add(make.MethodDef(ms, make.Block(0, com.sun.tools.javac.util.List.of(
2893                                 make.Return(make.App(make.Ident(
2894                                         new MethodSymbol(PRIVATE | STATIC | SYNTHETIC, op.getValue(), getterType, codeModelsClassSym))))))));
2895                         rmcdef.sym.members().enter(ms);
2896                     }
2897                 }
2898                 rmcdef.defs = rmcdef.defs.appendList(getters.toList());
2899 
2900                 CoreOp.ModuleOp module = OpBuilder.createBuilderFunctions(
2901                         ops,
2902                         b -> b.add(JavaOp.fieldLoad(
2903                                 FieldRef.field(JavaOp.class, "JAVA_DIALECT_FACTORY", DialectFactory.class))));
2904                 byte[] data = BytecodeGenerator.generateClassData(MethodHandles.lookup(), classDesc, module);
2905                 // inject InnerClassesAttribute and NestHostAttribute
2906                 var clm = ClassFile.of().parse(data);
2907                 data = ClassFile.of().transformClass(clm, ClassTransform.endHandler(clb ->
2908                         clb.with(InnerClassesAttribute.of(InnerClassInfo.of(classDesc,
2909                                                                             Optional.of(hostClass),
2910                                                                             Optional.of(codeModelsClassSym.name.toString()),
2911                                                                             ClassFile.ACC_STATIC)))
2912                            .with(NestHostAttribute.of(hostClass))));
2913                 try (OutputStream out = outFile.openOutputStream()) {
2914                     out.write(data);
2915                 }
2916             }
2917         }
2918     }
2919 
2920     // type and ref conversion utils
2921 
2922     JavaType symbolToErasedDesc(Symbol s) {
2923         return typeToCodeType(s.erasure(types));
2924     }
2925 
2926     JavaType typeToCodeType(Type t) {
2927         Assert.check(!t.hasTag(METHOD));
2928         t = asDenotable(t);
2929         return switch (t.getTag()) {
2930             case VOID -> JavaType.VOID;
2931             case CHAR -> JavaType.CHAR;
2932             case BOOLEAN -> JavaType.BOOLEAN;
2933             case BYTE -> JavaType.BYTE;
2934             case SHORT -> JavaType.SHORT;
2935             case INT -> JavaType.INT;
2936             case FLOAT -> JavaType.FLOAT;
2937             case LONG -> JavaType.LONG;
2938             case DOUBLE -> JavaType.DOUBLE;
2939             case ARRAY -> {
2940                 Type et = ((ArrayType)t).elemtype;
2941                 yield JavaType.array(typeToCodeType(et));
2942             }
2943             case WILDCARD -> {
2944                 Type.WildcardType wt = (Type.WildcardType)t;
2945                 yield wt.isUnbound() ?
2946                         JavaType.wildcard() :
2947                         JavaType.wildcard(wt.isExtendsBound() ? BoundKind.EXTENDS : BoundKind.SUPER, typeToCodeType(wt.type));
2948             }
2949             case TYPEVAR -> {
2950                 Type ub = t.getUpperBound();
2951                 if (ub.contains(t)) {
2952                     // @@@ stop infinite recursion, ex: <E extends Enum<E>>
2953                     ub = types.erasure(ub);
2954                 }
2955                 yield t.tsym.owner.kind == Kind.MTH ?
2956                     JavaType.typeVar(t.tsym.name.toString(), symbolToErasedMethodRef(t.tsym.owner),
2957                             typeToCodeType(ub)) :
2958                     JavaType.typeVar(t.tsym.name.toString(),
2959                             (jdk.incubator.code.dialect.java.ClassType)symbolToErasedDesc(t.tsym.owner),
2960                             typeToCodeType(ub));
2961             }
2962             case CLASS -> {
2963                 Assert.check(!t.isIntersection() && !t.isUnion());
2964                 JavaType typ;
2965                 if (t.getEnclosingType() != Type.noType) {
2966                     Name innerName = t.tsym.flatName().subName(t.getEnclosingType().tsym.flatName().length() + 1);
2967                     typ = JavaType.qualified(typeToCodeType(t.getEnclosingType()), innerName.toString());
2968                 } else {
2969                     typ = JavaType.type(ClassDesc.of(t.tsym.flatName().toString()));
2970                 }
2971 
2972                 List<JavaType> typeArguments;
2973                 if (t.getTypeArguments().nonEmpty()) {
2974                     typeArguments = new ArrayList<>();
2975                     for (Type ta : t.getTypeArguments()) {
2976                         typeArguments.add(typeToCodeType(ta));
2977                     }
2978                 } else {
2979                     typeArguments = List.of();
2980                 }
2981 
2982                 // Use flat name to ensure demarcation of nested classes
2983                 yield JavaType.parameterized(typ, typeArguments);
2984             }
2985             default -> throw new UnsupportedOperationException("Unsupported type: kind=" + t.getKind() + " type=" + t);
2986         };
2987     }
2988 
2989     Type codeTypeToType(CodeType jt) {
2990         return switch (jt) {
2991             case PrimitiveType pt when pt == JavaType.BOOLEAN -> syms.booleanType;
2992             case PrimitiveType pt when pt == JavaType.CHAR -> syms.charType;
2993             case PrimitiveType pt when pt == JavaType.BYTE -> syms.byteType;
2994             case PrimitiveType pt when pt == JavaType.SHORT -> syms.shortType;
2995             case PrimitiveType pt when pt == JavaType.INT -> syms.intType;
2996             case PrimitiveType pt when pt == JavaType.LONG -> syms.longType;
2997             case PrimitiveType pt when pt == JavaType.FLOAT -> syms.floatType;
2998             case PrimitiveType pt when pt == JavaType.DOUBLE -> syms.doubleType;
2999             case ClassType ct when ct.hasTypeArguments() -> {
3000                 Type enclosing = ct.enclosingType().map(this::codeTypeToType).orElse(Type.noType);
3001                 com.sun.tools.javac.util.List<Type> typeArgs = com.sun.tools.javac.util.List.from(ct.typeArguments()).map(this::codeTypeToType);
3002                 yield new Type.ClassType(enclosing, typeArgs, codeTypeToType(ct.rawType()).tsym);
3003             }
3004             case ClassType ct -> types.erasure(syms.enterClass(attrEnv().toplevel.modle, names.fromString(ct.toClassName())).type);
3005             case jdk.incubator.code.dialect.java.ArrayType at -> new Type.ArrayType(codeTypeToType(at.componentType()), syms.arrayClass);
3006             default -> Type.noType;
3007         };
3008     }
3009 
3010     Type symbolSiteType(Symbol s) {
3011         boolean isMember = s.owner == syms.predefClass ||
3012                 s.isMemberOf(currentClassSym, types);
3013         return isMember ? currentClassSym.type : s.owner.type;
3014     }
3015 
3016     FieldRef symbolToErasedFieldRef(Symbol s, Type site) {
3017         // @@@ Made Gen::binaryQualifier public, duplicate logic?
3018         // Ensure correct qualifying class is used in the reference, see JLS 13.1
3019         // https://docs.oracle.com/javase/specs/jls/se20/html/jls-13.html#jls-13.1
3020         return symbolErasedFieldRef(gen.binaryQualifier(s, types.erasure(site)));
3021     }
3022 
3023     FieldRef symbolErasedFieldRef(Symbol s) {
3024         Type erasedType = s.erasure(types);
3025         return FieldRef.field(
3026                 typeToCodeType(s.owner.erasure(types)),
3027                 s.name.toString(),
3028                 typeToCodeType(erasedType));
3029     }
3030 
3031     MethodRef symbolToErasedMethodRef(Symbol s, Type site) {
3032         // @@@ Made Gen::binaryQualifier public, duplicate logic?
3033         // Ensure correct qualifying class is used in the reference, see JLS 13.1
3034         // https://docs.oracle.com/javase/specs/jls/se20/html/jls-13.html#jls-13.1
3035         return symbolToErasedMethodRef(gen.binaryQualifier(s, types.erasure(site)));
3036     }
3037 
3038     MethodRef symbolToErasedMethodRef(Symbol s) {
3039         Type erasedType = s.erasure(types);
3040         return MethodRef.method(
3041                 typeToCodeType(s.owner.erasure(types)),
3042                 s.name.toString(),
3043                 typeToCodeType(erasedType.getReturnType()),
3044                 erasedType.getParameterTypes().stream().map(this::typeToCodeType).toArray(CodeType[]::new));
3045     }
3046 
3047     MethodRef symbolToMethodRef(Symbol sym) {
3048         return MethodRef.method(typeToCodeType(sym.owner.type),
3049                 sym.name.toString(),
3050                 typeToCodeType(sym.type.getReturnType()),
3051                 sym.type.getParameterTypes().stream().map(ReflectMethods.this::typeToCodeType).toList());
3052     }
3053 
3054     FunctionType typeToFunctionType(Type t) {
3055         return CoreType.functionType(
3056                 typeToCodeType(t.getReturnType()),
3057                 t.getParameterTypes().stream().map(this::typeToCodeType).toArray(CodeType[]::new));
3058     }
3059 
3060     RecordTypeRef symbolToRecordTypeRef(Symbol.ClassSymbol s) {
3061         CodeType recordType = symbolToErasedDesc(s);
3062         List<RecordTypeRef.ComponentRef> components = s.getRecordComponents().stream()
3063                 .map(rc ->
3064                         new RecordTypeRef.ComponentRef(symbolToErasedDesc(rc), rc.name.toString()))
3065                 .toList();
3066         return RecordTypeRef.recordType(recordType, components);
3067     }
3068 
3069     Env<AttrContext> attrEnv() {
3070         return typeEnvs.get(currentClassSym);
3071     }
3072 
3073     Type asDenotable(Type t) {
3074         // The goal of this type mapping is to replace occurrences of intersection and union types
3075         // with fresh type variables with appropriate upper bounds. For instance, consider the generic type
3076         // Foo<A & B & C>. We need to:
3077         // 1. replace A & B & C with a fresh type variable, so this becomes Foo<#1>, #1 <: A
3078         // 2. add #1 to the set of type-variables to be projected
3079         // 3. run upward projection on Foo<#1>, which gives Foo<? extends A>
3080         // In other words, by replacing intersection types with fresh type variables we make sure that the output
3081         // of this method is a type that is fully denotable -- e.g. can be fully represented in terms of the
3082         // CodeType API.
3083         class DenotableProjection extends StructuralTypeMapping<Void> {
3084             final ListBuffer<Type> tvars = new ListBuffer<>();
3085             final Map<CapturedType, CapturedType> pendingCaptures = new HashMap<>();
3086             final Type t;
3087 
3088             DenotableProjection(Type t) {
3089                 tvars.appendList(types.captures(t));
3090                 this.t = t;
3091             }
3092 
3093             Type asDenotable() {
3094                 return types.upward(apply(t), tvars.toList());
3095             }
3096 
3097             @Override
3098             public Type visitCapturedType(CapturedType t, Void _unused) {
3099                 CapturedType newVar = pendingCaptures.get(t);
3100                 if (newVar == null) {
3101                     newVar = addTypeVar(t.getUpperBound(), t.getLowerBound(), t.tsym.owner);
3102                     try {
3103                         pendingCaptures.put(t, newVar);
3104                         newVar.setUpperBound(apply(newVar.getUpperBound()));
3105                     } finally {
3106                         pendingCaptures.remove(t);
3107                     }
3108                     newVar.lower = apply(newVar.lower);
3109                 }
3110                 return newVar;
3111             }
3112 
3113             @Override
3114             public Type visitClassType(Type.ClassType t, Void unused) {
3115                 if (t.isIntersection()) {
3116                     Type bound = visit(((IntersectionClassType) t).getExplicitComponents().head, null);
3117                     return addTypeVar(bound, syms.botType, t.tsym);
3118                 } else if (t.isUnion()) {
3119                     Type bound = visit(((UnionClassType)t).getLub(), null);
3120                     return addTypeVar(bound, syms.botType, t.tsym);
3121                 } else {
3122                     return super.visitClassType(t, null);
3123                 }
3124             }
3125 
3126             CapturedType addTypeVar(Type upper, Type lower, Symbol owner) {
3127                 CapturedType newTvar = new CapturedType(names.empty, owner, upper, lower, null);
3128                 tvars.append(newTvar);
3129                 return newTvar;
3130             }
3131         }
3132 
3133         Type res = new DenotableProjection(t).asDenotable();
3134         return res.isIntersection() || res.isUnion() ? asDenotable(res) : res;
3135     }
3136 }