1 /* 2 * Copyright (c) 1999, 2025, 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 com.sun.tools.javac.comp; 27 28 import java.util.*; 29 import java.util.stream.Collectors; 30 31 import com.sun.source.tree.LambdaExpressionTree.BodyKind; 32 import com.sun.tools.javac.code.*; 33 import com.sun.tools.javac.code.Kinds.KindSelector; 34 import com.sun.tools.javac.code.Scope.WriteableScope; 35 import com.sun.tools.javac.jvm.*; 36 import com.sun.tools.javac.jvm.PoolConstant.LoadableConstant; 37 import com.sun.tools.javac.main.Option.PkgInfo; 38 import com.sun.tools.javac.resources.CompilerProperties.Fragments; 39 import com.sun.tools.javac.tree.*; 40 import com.sun.tools.javac.util.*; 41 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 42 import com.sun.tools.javac.util.List; 43 44 import com.sun.tools.javac.code.Symbol.*; 45 import com.sun.tools.javac.code.Symbol.OperatorSymbol.AccessCode; 46 import com.sun.tools.javac.resources.CompilerProperties.Errors; 47 import com.sun.tools.javac.tree.JCTree.*; 48 import com.sun.tools.javac.code.Type.*; 49 50 import com.sun.tools.javac.jvm.Target; 51 52 import static com.sun.tools.javac.code.Flags.*; 53 import static com.sun.tools.javac.code.Flags.BLOCK; 54 import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE; 55 import static com.sun.tools.javac.code.TypeTag.*; 56 import static com.sun.tools.javac.code.Kinds.Kind.*; 57 import com.sun.tools.javac.code.Source.Feature; 58 import static com.sun.tools.javac.jvm.ByteCodes.*; 59 import com.sun.tools.javac.tree.JCTree.JCBreak; 60 import com.sun.tools.javac.tree.JCTree.JCCase; 61 import com.sun.tools.javac.tree.JCTree.JCExpression; 62 import com.sun.tools.javac.tree.JCTree.JCExpressionStatement; 63 64 import static com.sun.tools.javac.tree.JCTree.JCOperatorExpression.OperandPos.LEFT; 65 import com.sun.tools.javac.tree.JCTree.JCSwitchExpression; 66 67 import static com.sun.tools.javac.tree.JCTree.Tag.*; 68 69 /** This pass translates away some syntactic sugar: inner classes, 70 * class literals, assertions, foreach loops, etc. 71 * 72 * <p><b>This is NOT part of any supported API. 73 * If you write code that depends on this, you do so at your own risk. 74 * This code and its internal interfaces are subject to change or 75 * deletion without notice.</b> 76 */ 77 public class Lower extends TreeTranslator { 78 protected static final Context.Key<Lower> lowerKey = new Context.Key<>(); 79 80 public static Lower instance(Context context) { 81 Lower instance = context.get(lowerKey); 82 if (instance == null) 83 instance = new Lower(context); 84 return instance; 85 } 86 87 private final Names names; 88 private final Log log; 89 private final Symtab syms; 90 private final Resolve rs; 91 private final Operators operators; 92 private final Check chk; 93 private final Attr attr; 94 private TreeMaker make; 95 private DiagnosticPosition make_pos; 96 private final ConstFold cfolder; 97 private final Target target; 98 private final TypeEnvs typeEnvs; 99 private final Name dollarAssertionsDisabled; 100 private final Types types; 101 private final TransTypes transTypes; 102 private final boolean debugLower; 103 private final boolean disableProtectedAccessors; // experimental 104 private final PkgInfo pkginfoOpt; 105 private final boolean optimizeOuterThis; 106 private final boolean nullCheckOuterThis; 107 private final boolean useMatchException; 108 private final HashMap<TypePairs, String> typePairToName; 109 private int variableIndex = 0; 110 111 @SuppressWarnings("this-escape") 112 protected Lower(Context context) { 113 context.put(lowerKey, this); 114 names = Names.instance(context); 115 log = Log.instance(context); 116 syms = Symtab.instance(context); 117 rs = Resolve.instance(context); 118 operators = Operators.instance(context); 119 chk = Check.instance(context); 120 attr = Attr.instance(context); 121 make = TreeMaker.instance(context); 122 cfolder = ConstFold.instance(context); 123 target = Target.instance(context); 124 typeEnvs = TypeEnvs.instance(context); 125 dollarAssertionsDisabled = names. 126 fromString(target.syntheticNameChar() + "assertionsDisabled"); 127 128 types = Types.instance(context); 129 transTypes = TransTypes.instance(context); 130 Options options = Options.instance(context); 131 debugLower = options.isSet("debuglower"); 132 pkginfoOpt = PkgInfo.get(options); 133 optimizeOuterThis = 134 target.optimizeOuterThis() || 135 options.getBoolean("optimizeOuterThis", false); 136 nullCheckOuterThis = options.getBoolean("nullCheckOuterThis", 137 target.nullCheckOuterThisByDefault()); 138 disableProtectedAccessors = options.isSet("disableProtectedAccessors"); 139 Source source = Source.instance(context); 140 Preview preview = Preview.instance(context); 141 useMatchException = Feature.PATTERN_SWITCH.allowedInSource(source) && 142 (preview.isEnabled() || !preview.isPreview(Feature.PATTERN_SWITCH)); 143 typePairToName = TypePairs.initialize(syms); 144 } 145 146 /** The currently enclosing class. 147 */ 148 ClassSymbol currentClass; 149 150 /** A queue of all translated classes. 151 */ 152 ListBuffer<JCTree> translated; 153 154 /** Environment for symbol lookup, set by translateTopLevelClass. 155 */ 156 Env<AttrContext> attrEnv; 157 158 /* ************************************************************************ 159 * Global mappings 160 *************************************************************************/ 161 162 /** A hash table mapping local classes to their definitions. 163 */ 164 Map<ClassSymbol, JCClassDecl> classdefs; 165 166 /** A hash table mapping local classes to a list of pruned trees. 167 */ 168 public Map<ClassSymbol, List<JCTree>> prunedTree = new WeakHashMap<>(); 169 170 /** A hash table mapping virtual accessed symbols in outer subclasses 171 * to the actually referred symbol in superclasses. 172 */ 173 Map<Symbol,Symbol> actualSymbols; 174 175 /** 176 * The current expected return type. 177 */ 178 Type currentRestype; 179 180 /** The current method definition. 181 */ 182 JCMethodDecl currentMethodDef; 183 184 /** The current method symbol. 185 */ 186 MethodSymbol currentMethodSym; 187 188 /** The currently enclosing outermost class definition. 189 */ 190 JCClassDecl outermostClassDef; 191 192 /** The currently enclosing outermost member definition. 193 */ 194 JCTree outermostMemberDef; 195 196 /** A navigator class for assembling a mapping from local class symbols 197 * to class definition trees. 198 * There is only one case; all other cases simply traverse down the tree. 199 */ 200 class ClassMap extends TreeScanner { 201 202 /** All encountered class defs are entered into classdefs table. 203 */ 204 public void visitClassDef(JCClassDecl tree) { 205 classdefs.put(tree.sym, tree); 206 super.visitClassDef(tree); 207 } 208 } 209 ClassMap classMap = new ClassMap(); 210 211 /** Map a class symbol to its definition. 212 * @param c The class symbol of which we want to determine the definition. 213 */ 214 JCClassDecl classDef(ClassSymbol c) { 215 // First lookup the class in the classdefs table. 216 JCClassDecl def = classdefs.get(c); 217 if (def == null && outermostMemberDef != null) { 218 // If this fails, traverse outermost member definition, entering all 219 // local classes into classdefs, and try again. 220 classMap.scan(outermostMemberDef); 221 def = classdefs.get(c); 222 } 223 if (def == null) { 224 // If this fails, traverse outermost class definition, entering all 225 // local classes into classdefs, and try again. 226 classMap.scan(outermostClassDef); 227 def = classdefs.get(c); 228 } 229 return def; 230 } 231 232 /** 233 * Get the enum constants for the given enum class symbol, if known. 234 * They will only be found if they are defined within the same top-level 235 * class as the class being compiled, so it's safe to assume that they 236 * can't change at runtime due to a recompilation. 237 */ 238 List<Name> enumNamesFor(ClassSymbol c) { 239 240 // Find the class definition and verify it is an enum class 241 final JCClassDecl classDef = classDef(c); 242 if (classDef == null || 243 (classDef.mods.flags & ENUM) == 0 || 244 (types.supertype(currentClass.type).tsym.flags() & ENUM) != 0) { 245 return null; 246 } 247 248 // Gather the enum identifiers 249 ListBuffer<Name> idents = new ListBuffer<>(); 250 for (List<JCTree> defs = classDef.defs; defs.nonEmpty(); defs=defs.tail) { 251 if (defs.head.hasTag(VARDEF) && 252 (((JCVariableDecl) defs.head).mods.flags & ENUM) != 0) { 253 JCVariableDecl var = (JCVariableDecl)defs.head; 254 idents.append(var.name); 255 } 256 } 257 return idents.toList(); 258 } 259 260 /** A hash table mapping class symbols to lists of free variables. 261 * accessed by them. Only free variables of the method immediately containing 262 * a class are associated with that class. 263 */ 264 Map<ClassSymbol,List<VarSymbol>> freevarCache; 265 266 /** A navigator class for collecting the free variables accessed 267 * from a local class. 268 */ 269 class FreeVarCollector extends CaptureScanner { 270 271 FreeVarCollector(JCTree ownerTree) { 272 super(ownerTree); 273 } 274 275 void addFreeVars(ClassSymbol c) { 276 List<VarSymbol> fvs = freevarCache.get(c); 277 if (fvs != null) { 278 for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) { 279 addFreeVar(l.head); 280 } 281 } 282 } 283 284 /** If tree refers to a class instance creation expression 285 * add all free variables of the freshly created class. 286 */ 287 public void visitNewClass(JCNewClass tree) { 288 ClassSymbol c = (ClassSymbol)tree.constructor.owner; 289 addFreeVars(c); 290 super.visitNewClass(tree); 291 } 292 293 /** If tree refers to a superclass constructor call, 294 * add all free variables of the superclass. 295 */ 296 public void visitApply(JCMethodInvocation tree) { 297 if (TreeInfo.name(tree.meth) == names._super) { 298 addFreeVars((ClassSymbol) TreeInfo.symbol(tree.meth).owner); 299 } 300 super.visitApply(tree); 301 } 302 } 303 304 /** Return the variables accessed from within a local class, which 305 * are declared in the local class' owner. 306 * (in reverse order of first access). 307 */ 308 List<VarSymbol> freevars(ClassSymbol c) { 309 List<VarSymbol> fvs = freevarCache.get(c); 310 if (fvs != null) { 311 return fvs; 312 } 313 FreeVarCollector collector = new FreeVarCollector(classDef(c)); 314 fvs = collector.analyzeCaptures().reverse(); 315 freevarCache.put(c, fvs); 316 return fvs; 317 } 318 319 Map<TypeSymbol,EnumMapping> enumSwitchMap = new LinkedHashMap<>(); 320 321 EnumMapping mapForEnum(DiagnosticPosition pos, TypeSymbol enumClass) { 322 323 // If enum class is part of this compilation, just switch on ordinal value 324 if (enumClass.kind == TYP) { 325 final List<Name> idents = enumNamesFor((ClassSymbol)enumClass); 326 if (idents != null) 327 return new CompileTimeEnumMapping(idents); 328 } 329 330 // Map identifiers to ordinal values at runtime, and then switch on that 331 return enumSwitchMap.computeIfAbsent(enumClass, ec -> new RuntimeEnumMapping(pos, ec)); 332 } 333 334 /** Generates a test value and corresponding cases for a switch on an enum type. 335 */ 336 interface EnumMapping { 337 338 /** Given an expression for the enum value's ordinal, generate an expression for the switch statement. 339 */ 340 JCExpression switchValue(JCExpression ordinalExpr); 341 342 /** Generate the switch statement case value corresponding to the given enum value. 343 */ 344 JCLiteral caseValue(VarSymbol v); 345 346 default void translate() { 347 } 348 } 349 350 /** EnumMapping using compile-time constants. Only valid when compiling the enum class itself, 351 * because otherwise the ordinals we use could become obsolete if/when the enum class is recompiled. 352 */ 353 class CompileTimeEnumMapping implements EnumMapping { 354 355 final List<Name> enumNames; 356 357 CompileTimeEnumMapping(List<Name> enumNames) { 358 Assert.check(enumNames != null); 359 this.enumNames = enumNames; 360 } 361 362 @Override 363 public JCExpression switchValue(JCExpression ordinalExpr) { 364 return ordinalExpr; 365 } 366 367 @Override 368 public JCLiteral caseValue(VarSymbol v) { 369 final int ordinal = enumNames.indexOf(v.name); 370 Assert.check(ordinal != -1); 371 return make.Literal(ordinal); 372 } 373 } 374 375 /** EnumMapping using run-time ordinal lookup. 376 * 377 * This builds a translation table to be used for enum switches. 378 * 379 * <p>For each enum that appears as the type of a switch 380 * expression, we maintain an EnumMapping to assist in the 381 * translation, as exemplified by the following example: 382 * 383 * <p>we translate 384 * <pre> 385 * switch(colorExpression) { 386 * case red: stmt1; 387 * case green: stmt2; 388 * } 389 * </pre> 390 * into 391 * <pre> 392 * switch(Outer$0.$EnumMap$Color[colorExpression.ordinal()]) { 393 * case 1: stmt1; 394 * case 2: stmt2 395 * } 396 * </pre> 397 * with the auxiliary table initialized as follows: 398 * <pre> 399 * class Outer$0 { 400 * synthetic final int[] $EnumMap$Color = new int[Color.values().length]; 401 * static { 402 * try { $EnumMap$Color[red.ordinal()] = 1; } catch (NoSuchFieldError ex) {} 403 * try { $EnumMap$Color[green.ordinal()] = 2; } catch (NoSuchFieldError ex) {} 404 * } 405 * } 406 * </pre> 407 * class EnumMapping provides mapping data and support methods for this translation. 408 */ 409 class RuntimeEnumMapping implements EnumMapping { 410 RuntimeEnumMapping(DiagnosticPosition pos, TypeSymbol forEnum) { 411 this.forEnum = forEnum; 412 this.values = new LinkedHashMap<>(); 413 this.pos = pos; 414 Name varName = names 415 .fromString(target.syntheticNameChar() + 416 "SwitchMap" + 417 target.syntheticNameChar() + 418 ClassWriter.externalize(forEnum.type.tsym.flatName().toString()) 419 .replace('/', '.') 420 .replace('.', target.syntheticNameChar())); 421 ClassSymbol outerCacheClass = outerCacheClass(); 422 this.mapVar = new VarSymbol(STATIC | SYNTHETIC | FINAL, 423 varName, 424 new ArrayType(syms.intType, syms.arrayClass), 425 outerCacheClass); 426 enterSynthetic(pos, mapVar, outerCacheClass.members()); 427 } 428 429 DiagnosticPosition pos = null; 430 431 // the next value to use 432 int next = 1; // 0 (unused map elements) go to the default label 433 434 // the enum for which this is a map 435 final TypeSymbol forEnum; 436 437 // the field containing the map 438 final VarSymbol mapVar; 439 440 // the mapped values 441 final Map<VarSymbol,Integer> values; 442 443 @Override 444 public JCExpression switchValue(JCExpression ordinalExpr) { 445 return make.Indexed(mapVar, ordinalExpr); 446 } 447 448 @Override 449 public JCLiteral caseValue(VarSymbol v) { 450 Integer result = values.get(v); 451 if (result == null) 452 values.put(v, result = next++); 453 return make.Literal(result); 454 } 455 456 // generate the field initializer for the map 457 @Override 458 public void translate() { 459 boolean prevAllowProtectedAccess = attrEnv.info.allowProtectedAccess; 460 try { 461 make.at(pos.getStartPosition()); 462 attrEnv.info.allowProtectedAccess = true; 463 JCClassDecl owner = classDef((ClassSymbol)mapVar.owner); 464 465 // synthetic static final int[] $SwitchMap$Color = new int[Color.values().length]; 466 MethodSymbol valuesMethod = lookupMethod(pos, 467 names.values, 468 forEnum.type, 469 List.nil()); 470 JCExpression size = make // Color.values().length 471 .Select(make.App(make.QualIdent(valuesMethod)), 472 syms.lengthVar); 473 JCExpression mapVarInit = make 474 .NewArray(make.Type(syms.intType), List.of(size), null) 475 .setType(new ArrayType(syms.intType, syms.arrayClass)); 476 477 // try { $SwitchMap$Color[red.ordinal()] = 1; } catch (java.lang.NoSuchFieldError ex) {} 478 ListBuffer<JCStatement> stmts = new ListBuffer<>(); 479 Symbol ordinalMethod = lookupMethod(pos, 480 names.ordinal, 481 forEnum.type, 482 List.nil()); 483 List<JCCatch> catcher = List.<JCCatch>nil() 484 .prepend(make.Catch(make.VarDef(new VarSymbol(PARAMETER, names.ex, 485 syms.noSuchFieldErrorType, 486 syms.noSymbol), 487 null), 488 make.Block(0, List.nil()))); 489 for (Map.Entry<VarSymbol,Integer> e : values.entrySet()) { 490 VarSymbol enumerator = e.getKey(); 491 Integer mappedValue = e.getValue(); 492 JCExpression assign = make 493 .Assign(make.Indexed(mapVar, 494 make.App(make.Select(make.QualIdent(enumerator), 495 ordinalMethod))), 496 make.Literal(mappedValue)) 497 .setType(syms.intType); 498 JCStatement exec = make.Exec(assign); 499 JCStatement _try = make.Try(make.Block(0, List.of(exec)), catcher, null); 500 stmts.append(_try); 501 } 502 503 owner.defs = owner.defs 504 .prepend(make.Block(STATIC, stmts.toList())) 505 .prepend(make.VarDef(mapVar, mapVarInit)); 506 } finally { 507 attrEnv.info.allowProtectedAccess = prevAllowProtectedAccess; 508 } 509 } 510 } 511 512 513 /* ************************************************************************ 514 * Tree building blocks 515 *************************************************************************/ 516 517 /** Equivalent to make.at(pos.getStartPosition()) with side effect of caching 518 * pos as make_pos, for use in diagnostics. 519 **/ 520 TreeMaker make_at(DiagnosticPosition pos) { 521 make_pos = pos; 522 return make.at(pos); 523 } 524 525 /** Make an attributed tree representing a literal. This will be an 526 * Ident node in the case of boolean literals, a Literal node in all 527 * other cases. 528 * @param type The literal's type. 529 * @param value The literal's value. 530 */ 531 JCExpression makeLit(Type type, Object value) { 532 return make.Literal(type.getTag(), value).setType(type.constType(value)); 533 } 534 535 /** Make an attributed tree representing null. 536 */ 537 JCExpression makeNull() { 538 return makeLit(syms.botType, null); 539 } 540 541 /** Make an attributed class instance creation expression. 542 * @param ctype The class type. 543 * @param args The constructor arguments. 544 */ 545 JCNewClass makeNewClass(Type ctype, List<JCExpression> args) { 546 JCNewClass tree = make.NewClass(null, 547 null, make.QualIdent(ctype.tsym), args, null); 548 tree.constructor = rs.resolveConstructor( 549 make_pos, attrEnv, ctype, TreeInfo.types(args), List.nil()); 550 tree.type = ctype; 551 return tree; 552 } 553 554 /** Make an attributed unary expression. 555 * @param optag The operators tree tag. 556 * @param arg The operator's argument. 557 */ 558 JCUnary makeUnary(JCTree.Tag optag, JCExpression arg) { 559 JCUnary tree = make.Unary(optag, arg); 560 tree.operator = operators.resolveUnary(tree, optag, arg.type); 561 tree.type = tree.operator.type.getReturnType(); 562 return tree; 563 } 564 565 /** Make an attributed binary expression. 566 * @param optag The operators tree tag. 567 * @param lhs The operator's left argument. 568 * @param rhs The operator's right argument. 569 */ 570 JCBinary makeBinary(JCTree.Tag optag, JCExpression lhs, JCExpression rhs) { 571 JCBinary tree = make.Binary(optag, lhs, rhs); 572 tree.operator = operators.resolveBinary(tree, optag, lhs.type, rhs.type); 573 tree.type = tree.operator.type.getReturnType(); 574 return tree; 575 } 576 577 /** Make an attributed assignop expression. 578 * @param optag The operators tree tag. 579 * @param lhs The operator's left argument. 580 * @param rhs The operator's right argument. 581 */ 582 JCAssignOp makeAssignop(JCTree.Tag optag, JCTree lhs, JCTree rhs) { 583 JCAssignOp tree = make.Assignop(optag, lhs, rhs); 584 tree.operator = operators.resolveBinary(tree, tree.getTag().noAssignOp(), lhs.type, rhs.type); 585 tree.type = lhs.type; 586 return tree; 587 } 588 589 /** Convert tree into string object, unless it has already a 590 * reference type.. 591 */ 592 JCExpression makeString(JCExpression tree) { 593 if (!tree.type.isPrimitiveOrVoid()) { 594 return tree; 595 } else { 596 Symbol valueOfSym = lookupMethod(tree.pos(), 597 names.valueOf, 598 syms.stringType, 599 List.of(tree.type)); 600 return make.App(make.QualIdent(valueOfSym), List.of(tree)); 601 } 602 } 603 604 /** Create an empty anonymous class definition and enter and complete 605 * its symbol. Return the class definition's symbol. 606 * and create 607 * @param flags The class symbol's flags 608 * @param owner The class symbol's owner 609 */ 610 JCClassDecl makeEmptyClass(long flags, ClassSymbol owner) { 611 return makeEmptyClass(flags, owner, null, true); 612 } 613 614 JCClassDecl makeEmptyClass(long flags, ClassSymbol owner, Name flatname, 615 boolean addToDefs) { 616 // Create class symbol. 617 ClassSymbol c = syms.defineClass(names.empty, owner); 618 if (flatname != null) { 619 c.flatname = flatname; 620 } else { 621 c.flatname = chk.localClassName(c); 622 } 623 c.sourcefile = owner.sourcefile; 624 c.completer = Completer.NULL_COMPLETER; 625 c.members_field = WriteableScope.create(c); 626 c.flags_field = flags; 627 ClassType ctype = (ClassType) c.type; 628 ctype.supertype_field = syms.objectType; 629 ctype.interfaces_field = List.nil(); 630 631 JCClassDecl odef = classDef(owner); 632 633 // Enter class symbol in owner scope and compiled table. 634 enterSynthetic(odef.pos(), c, owner.members()); 635 chk.putCompiled(c); 636 637 // Create class definition tree. 638 JCClassDecl cdef = make.ClassDef( 639 make.Modifiers(flags), names.empty, 640 List.nil(), 641 null, List.nil(), List.nil()); 642 cdef.sym = c; 643 cdef.type = c.type; 644 645 // Append class definition tree to owner's definitions. 646 if (addToDefs) odef.defs = odef.defs.prepend(cdef); 647 return cdef; 648 } 649 650 /* ************************************************************************ 651 * Symbol manipulation utilities 652 *************************************************************************/ 653 654 /** Enter a synthetic symbol in a given scope, but complain if there was already one there. 655 * @param pos Position for error reporting. 656 * @param sym The symbol. 657 * @param s The scope. 658 */ 659 private void enterSynthetic(DiagnosticPosition pos, Symbol sym, WriteableScope s) { 660 s.enter(sym); 661 } 662 663 /** Create a fresh synthetic name within a given scope - the unique name is 664 * obtained by appending '$' chars at the end of the name until no match 665 * is found. 666 * 667 * @param name base name 668 * @param s scope in which the name has to be unique 669 * @return fresh synthetic name 670 */ 671 private Name makeSyntheticName(Name name, Scope s) { 672 do { 673 name = name.append( 674 target.syntheticNameChar(), 675 names.empty); 676 } while (lookupSynthetic(name, s) != null); 677 return name; 678 } 679 680 /** Check whether synthetic symbols generated during lowering conflict 681 * with user-defined symbols. 682 * 683 * @param translatedTrees lowered class trees 684 */ 685 void checkConflicts(List<JCTree> translatedTrees) { 686 for (JCTree t : translatedTrees) { 687 t.accept(conflictsChecker); 688 } 689 } 690 691 JCTree.Visitor conflictsChecker = new TreeScanner() { 692 693 TypeSymbol currentClass; 694 695 @Override 696 public void visitMethodDef(JCMethodDecl that) { 697 checkConflicts(that.pos(), that.sym, currentClass); 698 super.visitMethodDef(that); 699 } 700 701 @Override 702 public void visitVarDef(JCVariableDecl that) { 703 if (that.sym.owner.kind == TYP) { 704 checkConflicts(that.pos(), that.sym, currentClass); 705 } 706 super.visitVarDef(that); 707 } 708 709 @Override 710 public void visitClassDef(JCClassDecl that) { 711 TypeSymbol prevCurrentClass = currentClass; 712 currentClass = that.sym; 713 try { 714 super.visitClassDef(that); 715 } 716 finally { 717 currentClass = prevCurrentClass; 718 } 719 } 720 721 void checkConflicts(DiagnosticPosition pos, Symbol sym, TypeSymbol c) { 722 for (Type ct = c.type; ct != Type.noType ; ct = types.supertype(ct)) { 723 for (Symbol sym2 : ct.tsym.members().getSymbolsByName(sym.name, NON_RECURSIVE)) { 724 // VM allows methods and variables with differing types 725 if (sym.kind == sym2.kind && 726 types.isSameType(types.erasure(sym.type), types.erasure(sym2.type)) && 727 sym != sym2 && 728 (sym.flags() & Flags.SYNTHETIC) != (sym2.flags() & Flags.SYNTHETIC) && 729 (sym.flags() & BRIDGE) == 0 && (sym2.flags() & BRIDGE) == 0) { 730 syntheticError(pos, (sym2.flags() & SYNTHETIC) == 0 ? sym2 : sym); 731 return; 732 } 733 } 734 } 735 } 736 737 /** Report a conflict between a user symbol and a synthetic symbol. 738 */ 739 private void syntheticError(DiagnosticPosition pos, Symbol sym) { 740 if (!sym.type.isErroneous()) { 741 log.error(pos, Errors.CannotGenerateClass(sym.location(), Fragments.SyntheticNameConflict(sym, sym.location()))); 742 } 743 } 744 }; 745 746 /** Look up a synthetic name in a given scope. 747 * @param s The scope. 748 * @param name The name. 749 */ 750 private Symbol lookupSynthetic(Name name, Scope s) { 751 Symbol sym = s.findFirst(name); 752 return (sym==null || (sym.flags()&SYNTHETIC)==0) ? null : sym; 753 } 754 755 /** Look up a method in a given scope. 756 */ 757 private MethodSymbol lookupMethod(DiagnosticPosition pos, Name name, Type qual, List<Type> args) { 758 return rs.resolveInternalMethod(pos, attrEnv, qual, name, args, List.nil()); 759 } 760 761 /** Anon inner classes are used as access constructor tags. 762 * accessConstructorTag will use an existing anon class if one is available, 763 * and synthesize a class (with makeEmptyClass) if one is not available. 764 * However, there is a small possibility that an existing class will not 765 * be generated as expected if it is inside a conditional with a constant 766 * expression. If that is found to be the case, create an empty class tree here. 767 */ 768 private void checkAccessConstructorTags() { 769 for (List<ClassSymbol> l = accessConstrTags; l.nonEmpty(); l = l.tail) { 770 ClassSymbol c = l.head; 771 if (isTranslatedClassAvailable(c)) 772 continue; 773 // Create class definition tree. 774 JCClassDecl cdec = makeEmptyClass(STATIC | SYNTHETIC, 775 c.outermostClass(), c.flatname, false); 776 swapAccessConstructorTag(c, cdec.sym); 777 translated.append(cdec); 778 } 779 } 780 // where 781 private boolean isTranslatedClassAvailable(ClassSymbol c) { 782 for (JCTree tree: translated) { 783 if (tree.hasTag(CLASSDEF) 784 && ((JCClassDecl) tree).sym == c) { 785 return true; 786 } 787 } 788 return false; 789 } 790 791 void swapAccessConstructorTag(ClassSymbol oldCTag, ClassSymbol newCTag) { 792 for (MethodSymbol methodSymbol : accessConstrs.values()) { 793 Assert.check(methodSymbol.type.hasTag(METHOD)); 794 MethodType oldMethodType = 795 (MethodType)methodSymbol.type; 796 if (oldMethodType.argtypes.head.tsym == oldCTag) 797 methodSymbol.type = 798 types.createMethodTypeWithParameters(oldMethodType, 799 oldMethodType.getParameterTypes().tail 800 .prepend(newCTag.erasure(types))); 801 } 802 } 803 804 /* ************************************************************************ 805 * Access methods 806 *************************************************************************/ 807 808 /** A mapping from symbols to their access numbers. 809 */ 810 private Map<Symbol,Integer> accessNums; 811 812 /** A mapping from symbols to an array of access symbols, indexed by 813 * access code. 814 */ 815 private Map<Symbol,MethodSymbol[]> accessSyms; 816 817 /** A mapping from (constructor) symbols to access constructor symbols. 818 */ 819 private Map<Symbol,MethodSymbol> accessConstrs; 820 821 /** A list of all class symbols used for access constructor tags. 822 */ 823 private List<ClassSymbol> accessConstrTags; 824 825 /** A queue for all accessed symbols. 826 */ 827 private ListBuffer<Symbol> accessed; 828 829 /** return access code for identifier, 830 * @param tree The tree representing the identifier use. 831 * @param enclOp The closest enclosing operation node of tree, 832 * null if tree is not a subtree of an operation. 833 */ 834 private static int accessCode(JCTree tree, JCTree enclOp) { 835 if (enclOp == null) 836 return AccessCode.DEREF.code; 837 else if (enclOp.hasTag(ASSIGN) && 838 tree == TreeInfo.skipParens(((JCAssign) enclOp).lhs)) 839 return AccessCode.ASSIGN.code; 840 else if ((enclOp.getTag().isIncOrDecUnaryOp() || enclOp.getTag().isAssignop()) && 841 tree == TreeInfo.skipParens(((JCOperatorExpression) enclOp).getOperand(LEFT))) 842 return (((JCOperatorExpression) enclOp).operator).getAccessCode(enclOp.getTag()); 843 else 844 return AccessCode.DEREF.code; 845 } 846 847 /** Return binary operator that corresponds to given access code. 848 */ 849 private OperatorSymbol binaryAccessOperator(int acode, Tag tag) { 850 return operators.lookupBinaryOp(op -> op.getAccessCode(tag) == acode); 851 } 852 853 /** Return tree tag for assignment operation corresponding 854 * to given binary operator. 855 */ 856 private static JCTree.Tag treeTag(OperatorSymbol operator) { 857 switch (operator.opcode) { 858 case ByteCodes.ior: case ByteCodes.lor: 859 return BITOR_ASG; 860 case ByteCodes.ixor: case ByteCodes.lxor: 861 return BITXOR_ASG; 862 case ByteCodes.iand: case ByteCodes.land: 863 return BITAND_ASG; 864 case ByteCodes.ishl: case ByteCodes.lshl: 865 case ByteCodes.ishll: case ByteCodes.lshll: 866 return SL_ASG; 867 case ByteCodes.ishr: case ByteCodes.lshr: 868 case ByteCodes.ishrl: case ByteCodes.lshrl: 869 return SR_ASG; 870 case ByteCodes.iushr: case ByteCodes.lushr: 871 case ByteCodes.iushrl: case ByteCodes.lushrl: 872 return USR_ASG; 873 case ByteCodes.iadd: case ByteCodes.ladd: 874 case ByteCodes.fadd: case ByteCodes.dadd: 875 case ByteCodes.string_add: 876 return PLUS_ASG; 877 case ByteCodes.isub: case ByteCodes.lsub: 878 case ByteCodes.fsub: case ByteCodes.dsub: 879 return MINUS_ASG; 880 case ByteCodes.imul: case ByteCodes.lmul: 881 case ByteCodes.fmul: case ByteCodes.dmul: 882 return MUL_ASG; 883 case ByteCodes.idiv: case ByteCodes.ldiv: 884 case ByteCodes.fdiv: case ByteCodes.ddiv: 885 return DIV_ASG; 886 case ByteCodes.imod: case ByteCodes.lmod: 887 case ByteCodes.fmod: case ByteCodes.dmod: 888 return MOD_ASG; 889 default: 890 throw new AssertionError(); 891 } 892 } 893 894 /** The name of the access method with number `anum' and access code `acode'. 895 */ 896 Name accessName(int anum, int acode) { 897 return names.fromString( 898 "access" + target.syntheticNameChar() + anum + acode / 10 + acode % 10); 899 } 900 901 /** Return access symbol for a private or protected symbol from an inner class. 902 * @param sym The accessed private symbol. 903 * @param tree The accessing tree. 904 * @param enclOp The closest enclosing operation node of tree, 905 * null if tree is not a subtree of an operation. 906 * @param protAccess Is access to a protected symbol in another 907 * package? 908 * @param refSuper Is access via a (qualified) C.super? 909 */ 910 MethodSymbol accessSymbol(Symbol sym, JCTree tree, JCTree enclOp, 911 boolean protAccess, boolean refSuper) { 912 ClassSymbol accOwner = refSuper && protAccess 913 // For access via qualified super (T.super.x), place the 914 // access symbol on T. 915 ? (ClassSymbol)((JCFieldAccess) tree).selected.type.tsym 916 // Otherwise pretend that the owner of an accessed 917 // protected symbol is the enclosing class of the current 918 // class which is a subclass of the symbol's owner. 919 : accessClass(sym, protAccess, tree); 920 921 Symbol vsym = sym; 922 if (sym.owner != accOwner) { 923 vsym = sym.clone(accOwner); 924 actualSymbols.put(vsym, sym); 925 } 926 927 Integer anum // The access number of the access method. 928 = accessNums.get(vsym); 929 if (anum == null) { 930 anum = accessed.length(); 931 accessNums.put(vsym, anum); 932 accessSyms.put(vsym, new MethodSymbol[AccessCode.numberOfAccessCodes]); 933 accessed.append(vsym); 934 // System.out.println("accessing " + vsym + " in " + vsym.location()); 935 } 936 937 int acode; // The access code of the access method. 938 List<Type> argtypes; // The argument types of the access method. 939 Type restype; // The result type of the access method. 940 List<Type> thrown; // The thrown exceptions of the access method. 941 switch (vsym.kind) { 942 case VAR: 943 acode = accessCode(tree, enclOp); 944 if (acode >= AccessCode.FIRSTASGOP.code) { 945 OperatorSymbol operator = binaryAccessOperator(acode, enclOp.getTag()); 946 if (operator.opcode == string_add) 947 argtypes = List.of(syms.objectType); 948 else 949 argtypes = operator.type.getParameterTypes().tail; 950 } else if (acode == AccessCode.ASSIGN.code) 951 argtypes = List.of(vsym.erasure(types)); 952 else 953 argtypes = List.nil(); 954 restype = vsym.erasure(types); 955 thrown = List.nil(); 956 break; 957 case MTH: 958 acode = AccessCode.DEREF.code; 959 argtypes = vsym.erasure(types).getParameterTypes(); 960 restype = vsym.erasure(types).getReturnType(); 961 thrown = vsym.type.getThrownTypes(); 962 break; 963 default: 964 throw new AssertionError(); 965 } 966 967 // For references via qualified super, increment acode by one, 968 // making it odd. 969 if (protAccess && refSuper) acode++; 970 971 // Instance access methods get instance as first parameter. 972 // For protected symbols this needs to be the instance as a member 973 // of the type containing the accessed symbol, not the class 974 // containing the access method. 975 if ((vsym.flags() & STATIC) == 0) { 976 argtypes = argtypes.prepend(vsym.owner.erasure(types)); 977 } 978 MethodSymbol[] accessors = accessSyms.get(vsym); 979 MethodSymbol accessor = accessors[acode]; 980 if (accessor == null) { 981 accessor = new MethodSymbol( 982 STATIC | SYNTHETIC | (accOwner.isInterface() ? PUBLIC : 0), 983 accessName(anum.intValue(), acode), 984 new MethodType(argtypes, restype, thrown, syms.methodClass), 985 accOwner); 986 enterSynthetic(tree.pos(), accessor, accOwner.members()); 987 accessors[acode] = accessor; 988 } 989 return accessor; 990 } 991 992 /** The qualifier to be used for accessing a symbol in an outer class. 993 * This is either C.sym or C.this.sym, depending on whether or not 994 * sym is static. 995 * @param sym The accessed symbol. 996 */ 997 JCExpression accessBase(DiagnosticPosition pos, Symbol sym) { 998 return (sym.flags() & STATIC) != 0 999 ? access(make.at(pos.getStartPosition()).QualIdent(sym.owner)) 1000 : makeOwnerThis(pos, sym, true); 1001 } 1002 1003 /** Do we need an access method to reference private symbol? 1004 */ 1005 boolean needsPrivateAccess(Symbol sym) { 1006 if (target.hasNestmateAccess()) { 1007 return false; 1008 } 1009 if ((sym.flags() & PRIVATE) == 0 || sym.owner == currentClass) { 1010 return false; 1011 } else if (sym.name == names.init && sym.owner.isDirectlyOrIndirectlyLocal()) { 1012 // private constructor in local class: relax protection 1013 sym.flags_field &= ~PRIVATE; 1014 return false; 1015 } else { 1016 return true; 1017 } 1018 } 1019 1020 /** Do we need an access method to reference symbol in other package? 1021 */ 1022 boolean needsProtectedAccess(Symbol sym, JCTree tree) { 1023 if (disableProtectedAccessors) return false; 1024 if ((sym.flags() & PROTECTED) == 0 || 1025 sym.owner.owner == currentClass.owner || // fast special case 1026 sym.packge() == currentClass.packge()) 1027 return false; 1028 if (!currentClass.isSubClass(sym.owner, types)) 1029 return true; 1030 if ((sym.flags() & STATIC) != 0 || 1031 !tree.hasTag(SELECT) || 1032 TreeInfo.name(((JCFieldAccess) tree).selected) == names._super) 1033 return false; 1034 return !((JCFieldAccess) tree).selected.type.tsym.isSubClass(currentClass, types); 1035 } 1036 1037 /** The class in which an access method for given symbol goes. 1038 * @param sym The access symbol 1039 * @param protAccess Is access to a protected symbol in another 1040 * package? 1041 */ 1042 ClassSymbol accessClass(Symbol sym, boolean protAccess, JCTree tree) { 1043 if (protAccess) { 1044 Symbol qualifier = null; 1045 ClassSymbol c = currentClass; 1046 if (tree.hasTag(SELECT) && (sym.flags() & STATIC) == 0) { 1047 qualifier = ((JCFieldAccess) tree).selected.type.tsym; 1048 while (!qualifier.isSubClass(c, types)) { 1049 c = c.owner.enclClass(); 1050 } 1051 return c; 1052 } else { 1053 while (!c.isSubClass(sym.owner, types)) { 1054 c = c.owner.enclClass(); 1055 } 1056 } 1057 return c; 1058 } else { 1059 // the symbol is private 1060 return sym.owner.enclClass(); 1061 } 1062 } 1063 1064 private boolean noClassDefIn(JCTree tree) { 1065 var scanner = new TreeScanner() { 1066 boolean noClassDef = true; 1067 @Override 1068 public void visitClassDef(JCClassDecl tree) { 1069 noClassDef = false; 1070 } 1071 }; 1072 scanner.scan(tree); 1073 return scanner.noClassDef; 1074 } 1075 1076 private void addPrunedInfo(JCTree tree) { 1077 List<JCTree> infoList = prunedTree.get(currentClass); 1078 infoList = (infoList == null) ? List.of(tree) : infoList.prepend(tree); 1079 prunedTree.put(currentClass, infoList); 1080 } 1081 1082 /** Ensure that identifier is accessible, return tree accessing the identifier. 1083 * @param sym The accessed symbol. 1084 * @param tree The tree referring to the symbol. 1085 * @param enclOp The closest enclosing operation node of tree, 1086 * null if tree is not a subtree of an operation. 1087 * @param refSuper Is access via a (qualified) C.super? 1088 */ 1089 JCExpression access(Symbol sym, JCExpression tree, JCExpression enclOp, boolean refSuper) { 1090 // Access a free variable via its proxy, or its proxy's proxy 1091 while (sym.kind == VAR && sym.owner.kind == MTH && 1092 sym.owner.enclClass() != currentClass) { 1093 // A constant is replaced by its constant value. 1094 Object cv = ((VarSymbol)sym).getConstValue(); 1095 if (cv != null) { 1096 make.at(tree.pos); 1097 return makeLit(sym.type, cv); 1098 } 1099 // Otherwise replace the variable by its proxy. 1100 sym = proxies.get(sym); 1101 Assert.check(sym != null && (sym.flags_field & FINAL) != 0); 1102 tree = make.at(tree.pos).Ident(sym); 1103 } 1104 JCExpression base = (tree.hasTag(SELECT)) ? ((JCFieldAccess) tree).selected : null; 1105 switch (sym.kind) { 1106 case TYP: 1107 if (sym.owner.kind != PCK) { 1108 // Convert type idents to 1109 // <flat name> or <package name> . <flat name> 1110 Name flatname = Convert.shortName(sym.flatName()); 1111 while (base != null && 1112 TreeInfo.symbol(base) != null && 1113 TreeInfo.symbol(base).kind != PCK) { 1114 base = (base.hasTag(SELECT)) 1115 ? ((JCFieldAccess) base).selected 1116 : null; 1117 } 1118 if (tree.hasTag(IDENT)) { 1119 ((JCIdent) tree).name = flatname; 1120 } else if (base == null) { 1121 tree = make.at(tree.pos).Ident(sym); 1122 ((JCIdent) tree).name = flatname; 1123 } else { 1124 ((JCFieldAccess) tree).selected = base; 1125 ((JCFieldAccess) tree).name = flatname; 1126 } 1127 } 1128 break; 1129 case MTH: case VAR: 1130 if (sym.owner.kind == TYP) { 1131 1132 // Access methods are required for 1133 // - private members, 1134 // - protected members in a superclass of an 1135 // enclosing class contained in another package. 1136 // - all non-private members accessed via a qualified super. 1137 boolean protAccess = refSuper && !needsPrivateAccess(sym) 1138 || needsProtectedAccess(sym, tree); 1139 boolean accReq = protAccess || needsPrivateAccess(sym); 1140 1141 // A base has to be supplied for 1142 // - simple identifiers accessing variables in outer classes. 1143 boolean baseReq = 1144 base == null && 1145 sym.owner != syms.predefClass && 1146 !sym.isMemberOf(currentClass, types); 1147 1148 if (accReq || baseReq) { 1149 make.at(tree.pos); 1150 1151 // Constants are replaced by their constant value. 1152 if (sym.kind == VAR) { 1153 Object cv = ((VarSymbol)sym).getConstValue(); 1154 if (cv != null) { 1155 addPrunedInfo(tree); 1156 return makeLit(sym.type, cv); 1157 } 1158 } 1159 1160 // Private variables and methods are replaced by calls 1161 // to their access methods. 1162 if (accReq) { 1163 List<JCExpression> args = List.nil(); 1164 if ((sym.flags() & STATIC) == 0) { 1165 // Instance access methods get instance 1166 // as first parameter. 1167 if (base == null) 1168 base = makeOwnerThis(tree.pos(), sym, true); 1169 args = args.prepend(base); 1170 base = null; // so we don't duplicate code 1171 } 1172 Symbol access = accessSymbol(sym, tree, 1173 enclOp, protAccess, 1174 refSuper); 1175 JCExpression receiver = make.Select( 1176 base != null ? base : make.QualIdent(access.owner), 1177 access); 1178 return make.App(receiver, args); 1179 1180 // Other accesses to members of outer classes get a 1181 // qualifier. 1182 } else if (baseReq) { 1183 return make.at(tree.pos).Select( 1184 accessBase(tree.pos(), sym), sym).setType(tree.type); 1185 } 1186 } 1187 } 1188 } 1189 return tree; 1190 } 1191 1192 /** Ensure that identifier is accessible, return tree accessing the identifier. 1193 * @param tree The identifier tree. 1194 */ 1195 JCExpression access(JCExpression tree) { 1196 Symbol sym = TreeInfo.symbol(tree); 1197 return sym == null ? tree : access(sym, tree, null, false); 1198 } 1199 1200 /** Return access constructor for a private constructor, 1201 * or the constructor itself, if no access constructor is needed. 1202 * @param pos The position to report diagnostics, if any. 1203 * @param constr The private constructor. 1204 */ 1205 Symbol accessConstructor(DiagnosticPosition pos, Symbol constr) { 1206 if (needsPrivateAccess(constr)) { 1207 ClassSymbol accOwner = constr.owner.enclClass(); 1208 MethodSymbol aconstr = accessConstrs.get(constr); 1209 if (aconstr == null) { 1210 List<Type> argtypes = constr.type.getParameterTypes(); 1211 if ((accOwner.flags_field & ENUM) != 0) 1212 argtypes = argtypes 1213 .prepend(syms.intType) 1214 .prepend(syms.stringType); 1215 aconstr = new MethodSymbol( 1216 SYNTHETIC, 1217 names.init, 1218 new MethodType( 1219 argtypes.append( 1220 accessConstructorTag().erasure(types)), 1221 constr.type.getReturnType(), 1222 constr.type.getThrownTypes(), 1223 syms.methodClass), 1224 accOwner); 1225 enterSynthetic(pos, aconstr, accOwner.members()); 1226 accessConstrs.put(constr, aconstr); 1227 accessed.append(constr); 1228 } 1229 return aconstr; 1230 } else { 1231 return constr; 1232 } 1233 } 1234 1235 /** Return an anonymous class nested in this toplevel class. 1236 */ 1237 ClassSymbol accessConstructorTag() { 1238 ClassSymbol topClass = currentClass.outermostClass(); 1239 ModuleSymbol topModle = topClass.packge().modle; 1240 for (int i = 1; ; i++) { 1241 Name flatname = names.fromString("" + topClass.getQualifiedName() + 1242 target.syntheticNameChar() + 1243 i); 1244 ClassSymbol ctag = chk.getCompiled(topModle, flatname); 1245 if (ctag == null) 1246 ctag = makeEmptyClass(STATIC | SYNTHETIC, topClass).sym; 1247 else if (!ctag.isAnonymous()) 1248 continue; 1249 // keep a record of all tags, to verify that all are generated as required 1250 accessConstrTags = accessConstrTags.prepend(ctag); 1251 return ctag; 1252 } 1253 } 1254 1255 /** Add all required access methods for a private symbol to enclosing class. 1256 * @param sym The symbol. 1257 */ 1258 void makeAccessible(Symbol sym) { 1259 JCClassDecl cdef = classDef(sym.owner.enclClass()); 1260 if (cdef == null) Assert.error("class def not found: " + sym + " in " + sym.owner); 1261 if (sym.name == names.init) { 1262 cdef.defs = cdef.defs.prepend( 1263 accessConstructorDef(cdef.pos, sym, accessConstrs.get(sym))); 1264 } else { 1265 MethodSymbol[] accessors = accessSyms.get(sym); 1266 for (int i = 0; i < AccessCode.numberOfAccessCodes; i++) { 1267 if (accessors[i] != null) 1268 cdef.defs = cdef.defs.prepend( 1269 accessDef(cdef.pos, sym, accessors[i], i)); 1270 } 1271 } 1272 } 1273 1274 /** Construct definition of an access method. 1275 * @param pos The source code position of the definition. 1276 * @param vsym The private or protected symbol. 1277 * @param accessor The access method for the symbol. 1278 * @param acode The access code. 1279 */ 1280 JCTree accessDef(int pos, Symbol vsym, MethodSymbol accessor, int acode) { 1281 // System.err.println("access " + vsym + " with " + accessor);//DEBUG 1282 currentClass = vsym.owner.enclClass(); 1283 make.at(pos); 1284 JCMethodDecl md = make.MethodDef(accessor, null); 1285 1286 // Find actual symbol 1287 Symbol sym = actualSymbols.get(vsym); 1288 if (sym == null) sym = vsym; 1289 1290 JCExpression ref; // The tree referencing the private symbol. 1291 List<JCExpression> args; // Any additional arguments to be passed along. 1292 if ((sym.flags() & STATIC) != 0) { 1293 ref = make.Ident(sym); 1294 args = make.Idents(md.params); 1295 } else { 1296 JCExpression site = make.Ident(md.params.head); 1297 if (acode % 2 != 0) { 1298 //odd access codes represent qualified super accesses - need to 1299 //emit reference to the direct superclass, even if the referred 1300 //member is from an indirect superclass (JLS 13.1) 1301 site.setType(types.erasure(types.supertype(vsym.owner.enclClass().type))); 1302 } 1303 ref = make.Select(site, sym); 1304 args = make.Idents(md.params.tail); 1305 } 1306 JCStatement stat; // The statement accessing the private symbol. 1307 if (sym.kind == VAR) { 1308 // Normalize out all odd access codes by taking floor modulo 2: 1309 int acode1 = acode - (acode & 1); 1310 1311 JCExpression expr; // The access method's return value. 1312 AccessCode aCode = AccessCode.getFromCode(acode1); 1313 switch (aCode) { 1314 case DEREF: 1315 expr = ref; 1316 break; 1317 case ASSIGN: 1318 expr = make.Assign(ref, args.head); 1319 break; 1320 case PREINC: case POSTINC: case PREDEC: case POSTDEC: 1321 expr = makeUnary(aCode.tag, ref); 1322 break; 1323 default: 1324 expr = make.Assignop( 1325 treeTag(binaryAccessOperator(acode1, JCTree.Tag.NO_TAG)), ref, args.head); 1326 ((JCAssignOp) expr).operator = binaryAccessOperator(acode1, JCTree.Tag.NO_TAG); 1327 } 1328 stat = make.Return(expr.setType(sym.type)); 1329 } else { 1330 stat = make.Call(make.App(ref, args)); 1331 } 1332 md.body = make.Block(0, List.of(stat)); 1333 1334 // Make sure all parameters, result types and thrown exceptions 1335 // are accessible. 1336 for (List<JCVariableDecl> l = md.params; l.nonEmpty(); l = l.tail) 1337 l.head.vartype = access(l.head.vartype); 1338 md.restype = access(md.restype); 1339 for (List<JCExpression> l = md.thrown; l.nonEmpty(); l = l.tail) 1340 l.head = access(l.head); 1341 1342 return md; 1343 } 1344 1345 /** Construct definition of an access constructor. 1346 * @param pos The source code position of the definition. 1347 * @param constr The private constructor. 1348 * @param accessor The access method for the constructor. 1349 */ 1350 JCTree accessConstructorDef(int pos, Symbol constr, MethodSymbol accessor) { 1351 make.at(pos); 1352 JCMethodDecl md = make.MethodDef(accessor, 1353 accessor.externalType(types), 1354 null); 1355 JCIdent callee = make.Ident(names._this); 1356 callee.sym = constr; 1357 callee.type = constr.type; 1358 md.body = 1359 make.Block(0, List.of( 1360 make.Call( 1361 make.App( 1362 callee, 1363 make.Idents(md.params.reverse().tail.reverse()))))); 1364 return md; 1365 } 1366 1367 /* ************************************************************************ 1368 * Free variables proxies and this$n 1369 *************************************************************************/ 1370 1371 /** A map which allows to retrieve the translated proxy variable for any given symbol of an 1372 * enclosing scope that is accessed (the accessed symbol could be the synthetic 'this$n' symbol). 1373 * Inside a constructor, the map temporarily overrides entries corresponding to proxies and any 1374 * 'this$n' symbols, where they represent the constructor parameters. 1375 */ 1376 Map<Symbol, Symbol> proxies; 1377 1378 /** A scope containing all unnamed resource variables/saved 1379 * exception variables for translated TWR blocks 1380 */ 1381 WriteableScope twrVars; 1382 1383 /** A stack containing the this$n field of the currently translated 1384 * classes (if needed) in innermost first order. 1385 * Inside a constructor, proxies and any this$n symbol are duplicated 1386 * in an additional innermost scope, where they represent the constructor 1387 * parameters. 1388 */ 1389 List<VarSymbol> outerThisStack; 1390 1391 /** The name of a free variable proxy. 1392 */ 1393 Name proxyName(Name name, int index) { 1394 Name proxyName = names.fromString("val" + target.syntheticNameChar() + name); 1395 if (index > 0) { 1396 proxyName = proxyName.append(names.fromString("" + target.syntheticNameChar() + index)); 1397 } 1398 return proxyName; 1399 } 1400 1401 /** Proxy definitions for all free variables in given list, in reverse order. 1402 * @param pos The source code position of the definition. 1403 * @param freevars The free variables. 1404 * @param owner The class in which the definitions go. 1405 */ 1406 List<JCVariableDecl> freevarDefs(int pos, List<VarSymbol> freevars, Symbol owner) { 1407 return freevarDefs(pos, freevars, owner, LOCAL_CAPTURE_FIELD); 1408 } 1409 1410 List<JCVariableDecl> freevarDefs(int pos, List<VarSymbol> freevars, Symbol owner, 1411 long additionalFlags) { 1412 long flags = FINAL | SYNTHETIC | additionalFlags; 1413 List<JCVariableDecl> defs = List.nil(); 1414 Set<Name> proxyNames = new HashSet<>(); 1415 for (List<VarSymbol> l = freevars; l.nonEmpty(); l = l.tail) { 1416 VarSymbol v = l.head; 1417 int index = 0; 1418 Name proxyName; 1419 do { 1420 proxyName = proxyName(v.name, index++); 1421 } while (!proxyNames.add(proxyName)); 1422 VarSymbol proxy = new VarSymbol( 1423 flags, proxyName, v.erasure(types), owner) { 1424 @Override 1425 public Symbol baseSymbol() { 1426 return v; 1427 } 1428 }; 1429 proxies.put(v, proxy); 1430 JCVariableDecl vd = make.at(pos).VarDef(proxy, null); 1431 vd.vartype = access(vd.vartype); 1432 defs = defs.prepend(vd); 1433 } 1434 return defs; 1435 } 1436 1437 /** The name of a this$n field 1438 * @param type The class referenced by the this$n field 1439 */ 1440 Name outerThisName(Type type, Symbol owner) { 1441 Type t = type.getEnclosingType(); 1442 int nestingLevel = 0; 1443 while (t.hasTag(CLASS)) { 1444 t = t.getEnclosingType(); 1445 nestingLevel++; 1446 } 1447 Name result = names.fromString("this" + target.syntheticNameChar() + nestingLevel); 1448 while (owner.kind == TYP && ((ClassSymbol)owner).members().findFirst(result) != null) 1449 result = names.fromString(result.toString() + target.syntheticNameChar()); 1450 return result; 1451 } 1452 1453 private VarSymbol makeOuterThisVarSymbol(Symbol owner, long flags) { 1454 Type target = owner.innermostAccessibleEnclosingClass().erasure(types); 1455 // Set NOOUTERTHIS for all synthetic outer instance variables, and unset 1456 // it when the variable is accessed. If the variable is never accessed, 1457 // we skip creating an outer instance field and saving the constructor 1458 // parameter to it. 1459 VarSymbol outerThis = 1460 new VarSymbol(flags | NOOUTERTHIS, outerThisName(target, owner), target, owner); 1461 outerThisStack = outerThisStack.prepend(outerThis); 1462 return outerThis; 1463 } 1464 1465 private JCVariableDecl makeOuterThisVarDecl(int pos, VarSymbol sym) { 1466 JCVariableDecl vd = make.at(pos).VarDef(sym, null); 1467 vd.vartype = access(vd.vartype); 1468 return vd; 1469 } 1470 1471 /** Definition for this$n field. 1472 * @param pos The source code position of the definition. 1473 * @param owner The method in which the definition goes. 1474 */ 1475 JCVariableDecl outerThisDef(int pos, MethodSymbol owner) { 1476 ClassSymbol c = owner.enclClass(); 1477 boolean isMandated = 1478 // Anonymous constructors 1479 (owner.isConstructor() && owner.isAnonymous()) || 1480 // Constructors of non-private inner member classes 1481 (owner.isConstructor() && c.isInner() && 1482 !c.isPrivate() && !c.isStatic()); 1483 long flags = 1484 FINAL | (isMandated ? MANDATED : SYNTHETIC) | PARAMETER; 1485 VarSymbol outerThis = makeOuterThisVarSymbol(owner, flags); 1486 owner.extraParams = owner.extraParams.prepend(outerThis); 1487 return makeOuterThisVarDecl(pos, outerThis); 1488 } 1489 1490 /** Definition for this$n field. 1491 * @param pos The source code position of the definition. 1492 * @param owner The class in which the definition goes. 1493 */ 1494 JCVariableDecl outerThisDef(int pos, ClassSymbol owner) { 1495 VarSymbol outerThis = makeOuterThisVarSymbol(owner, FINAL | SYNTHETIC); 1496 return makeOuterThisVarDecl(pos, outerThis); 1497 } 1498 1499 /** Return a list of trees that load the free variables in given list, 1500 * in reverse order. 1501 * @param pos The source code position to be used for the trees. 1502 * @param freevars The list of free variables. 1503 */ 1504 List<JCExpression> loadFreevars(DiagnosticPosition pos, List<VarSymbol> freevars) { 1505 List<JCExpression> args = List.nil(); 1506 for (List<VarSymbol> l = freevars; l.nonEmpty(); l = l.tail) 1507 args = args.prepend(loadFreevar(pos, l.head)); 1508 return args; 1509 } 1510 //where 1511 JCExpression loadFreevar(DiagnosticPosition pos, VarSymbol v) { 1512 return access(v, make.at(pos).Ident(v), null, false); 1513 } 1514 1515 /** Construct a tree simulating the expression {@code C.this}. 1516 * @param pos The source code position to be used for the tree. 1517 * @param c The qualifier class. 1518 */ 1519 JCExpression makeThis(DiagnosticPosition pos, TypeSymbol c) { 1520 if (currentClass == c) { 1521 // in this case, `this' works fine 1522 return make.at(pos).This(c.erasure(types)); 1523 } else { 1524 // need to go via this$n 1525 return makeOuterThis(pos, c); 1526 } 1527 } 1528 1529 /** 1530 * Optionally replace a try statement with the desugaring of a 1531 * try-with-resources statement. The canonical desugaring of 1532 * 1533 * try ResourceSpecification 1534 * Block 1535 * 1536 * is 1537 * 1538 * { 1539 * final VariableModifiers_minus_final R #resource = Expression; 1540 * 1541 * try ResourceSpecificationtail 1542 * Block 1543 * } body-only-finally { 1544 * if (#resource != null) //nullcheck skipped if Expression is provably non-null 1545 * #resource.close(); 1546 * } catch (Throwable #primaryException) { 1547 * if (#resource != null) //nullcheck skipped if Expression is provably non-null 1548 * try { 1549 * #resource.close(); 1550 * } catch (Throwable #suppressedException) { 1551 * #primaryException.addSuppressed(#suppressedException); 1552 * } 1553 * throw #primaryException; 1554 * } 1555 * } 1556 * 1557 * @param tree The try statement to inspect. 1558 * @return a desugared try-with-resources tree, or the original 1559 * try block if there are no resources to manage. 1560 */ 1561 JCTree makeTwrTry(JCTry tree) { 1562 make_at(tree.pos()); 1563 twrVars = twrVars.dup(); 1564 JCBlock twrBlock = makeTwrBlock(tree.resources, tree.body, 0); 1565 if (tree.catchers.isEmpty() && tree.finalizer == null) 1566 result = translate(twrBlock); 1567 else 1568 result = translate(make.Try(twrBlock, tree.catchers, tree.finalizer)); 1569 twrVars = twrVars.leave(); 1570 return result; 1571 } 1572 1573 private JCBlock makeTwrBlock(List<JCTree> resources, JCBlock block, int depth) { 1574 if (resources.isEmpty()) 1575 return block; 1576 1577 // Add resource declaration or expression to block statements 1578 ListBuffer<JCStatement> stats = new ListBuffer<>(); 1579 JCTree resource = resources.head; 1580 JCExpression resourceUse; 1581 boolean resourceNonNull; 1582 if (resource instanceof JCVariableDecl variableDecl) { 1583 resourceUse = make.Ident(variableDecl.sym).setType(resource.type); 1584 resourceNonNull = variableDecl.init != null && TreeInfo.skipParens(variableDecl.init).hasTag(NEWCLASS); 1585 stats.add(variableDecl); 1586 } else { 1587 Assert.check(resource instanceof JCExpression); 1588 VarSymbol syntheticTwrVar = 1589 new VarSymbol(SYNTHETIC | FINAL, 1590 makeSyntheticName(names.fromString("twrVar" + 1591 depth), twrVars), 1592 (resource.type.hasTag(BOT)) ? 1593 syms.autoCloseableType : resource.type, 1594 currentMethodSym); 1595 twrVars.enter(syntheticTwrVar); 1596 JCVariableDecl syntheticTwrVarDecl = 1597 make.VarDef(syntheticTwrVar, (JCExpression)resource); 1598 resourceUse = (JCExpression)make.Ident(syntheticTwrVar); 1599 resourceNonNull = false; 1600 stats.add(syntheticTwrVarDecl); 1601 } 1602 1603 //create (semi-) finally block that will be copied into the main try body: 1604 int oldPos = make.pos; 1605 make.at(TreeInfo.endPos(block)); 1606 1607 // if (#resource != null) { #resource.close(); } 1608 JCStatement bodyCloseStatement = makeResourceCloseInvocation(resourceUse); 1609 1610 if (!resourceNonNull) { 1611 bodyCloseStatement = make.If(makeNonNullCheck(resourceUse), 1612 bodyCloseStatement, 1613 null); 1614 } 1615 1616 JCBlock finallyClause = make.Block(BODY_ONLY_FINALIZE, List.of(bodyCloseStatement)); 1617 make.at(oldPos); 1618 1619 // Create catch clause that saves exception, closes the resource and then rethrows the exception: 1620 VarSymbol primaryException = 1621 new VarSymbol(FINAL|SYNTHETIC, 1622 names.fromString("t" + 1623 target.syntheticNameChar()), 1624 syms.throwableType, 1625 currentMethodSym); 1626 JCVariableDecl primaryExceptionDecl = make.VarDef(primaryException, null); 1627 1628 // close resource: 1629 // try { 1630 // #resource.close(); 1631 // } catch (Throwable #suppressedException) { 1632 // #primaryException.addSuppressed(#suppressedException); 1633 // } 1634 VarSymbol suppressedException = 1635 new VarSymbol(SYNTHETIC, make.paramName(2), 1636 syms.throwableType, 1637 currentMethodSym); 1638 JCStatement addSuppressedStatement = 1639 make.Exec(makeCall(make.Ident(primaryException), 1640 names.addSuppressed, 1641 List.of(make.Ident(suppressedException)))); 1642 JCBlock closeResourceTryBlock = 1643 make.Block(0L, List.of(makeResourceCloseInvocation(resourceUse))); 1644 JCVariableDecl catchSuppressedDecl = make.VarDef(suppressedException, null); 1645 JCBlock catchSuppressedBlock = make.Block(0L, List.of(addSuppressedStatement)); 1646 List<JCCatch> catchSuppressedClauses = 1647 List.of(make.Catch(catchSuppressedDecl, catchSuppressedBlock)); 1648 JCTry closeResourceTry = make.Try(closeResourceTryBlock, catchSuppressedClauses, null); 1649 closeResourceTry.finallyCanCompleteNormally = true; 1650 1651 JCStatement exceptionalCloseStatement = closeResourceTry; 1652 1653 if (!resourceNonNull) { 1654 // if (#resource != null) { } 1655 exceptionalCloseStatement = make.If(makeNonNullCheck(resourceUse), 1656 exceptionalCloseStatement, 1657 null); 1658 } 1659 1660 JCStatement exceptionalRethrow = make.Throw(make.Ident(primaryException)); 1661 JCBlock exceptionalCloseBlock = make.Block(0L, List.of(exceptionalCloseStatement, exceptionalRethrow)); 1662 JCCatch exceptionalCatchClause = make.Catch(primaryExceptionDecl, exceptionalCloseBlock); 1663 1664 //create the main try statement with the close: 1665 JCTry outerTry = make.Try(makeTwrBlock(resources.tail, block, depth + 1), 1666 List.of(exceptionalCatchClause), 1667 finallyClause); 1668 1669 outerTry.finallyCanCompleteNormally = true; 1670 stats.add(outerTry); 1671 1672 JCBlock newBlock = make.Block(0L, stats.toList()); 1673 return newBlock; 1674 } 1675 1676 private JCStatement makeResourceCloseInvocation(JCExpression resource) { 1677 // convert to AutoCloseable if needed 1678 if (types.asSuper(resource.type, syms.autoCloseableType.tsym) == null) { 1679 resource = convert(resource, syms.autoCloseableType); 1680 } 1681 1682 // create resource.close() method invocation 1683 JCExpression resourceClose = makeCall(resource, 1684 names.close, 1685 List.nil()); 1686 return make.Exec(resourceClose); 1687 } 1688 1689 private JCExpression makeNonNullCheck(JCExpression expression) { 1690 return makeBinary(NE, expression, makeNull()); 1691 } 1692 1693 /** Construct a tree that represents the outer instance 1694 * {@code C.this}. Never pick the current `this'. 1695 * @param pos The source code position to be used for the tree. 1696 * @param c The qualifier class. 1697 */ 1698 JCExpression makeOuterThis(DiagnosticPosition pos, TypeSymbol c) { 1699 List<VarSymbol> ots = outerThisStack; 1700 if (ots.isEmpty()) { 1701 log.error(pos, Errors.NoEnclInstanceOfTypeInScope(c)); 1702 return makeNull(); 1703 } 1704 VarSymbol ot = ots.head; 1705 JCExpression tree = access(make.at(pos).Ident(ot)); 1706 ot.flags_field &= ~NOOUTERTHIS; 1707 TypeSymbol otc = ot.type.tsym; 1708 while (otc != c) { 1709 do { 1710 ots = ots.tail; 1711 if (ots.isEmpty()) { 1712 log.error(pos, Errors.NoEnclInstanceOfTypeInScope(c)); 1713 Assert.error(); // should have been caught in Attr 1714 return tree; 1715 } 1716 ot = ots.head; 1717 } while (ot.owner != otc); 1718 if (otc.owner.kind != PCK && !otc.hasOuterInstance()) { 1719 log.error(pos, Errors.NoEnclInstanceOfTypeInScope(c)); 1720 Assert.error(); // should have been caught in Attr 1721 return makeNull(); 1722 } 1723 tree = access(make.at(pos).Select(tree, ot)); 1724 ot.flags_field &= ~NOOUTERTHIS; 1725 otc = ot.type.tsym; 1726 } 1727 return tree; 1728 } 1729 1730 /** Construct a tree that represents the closest outer instance 1731 * {@code C.this} such that the given symbol is a member of C. 1732 * @param pos The source code position to be used for the tree. 1733 * @param sym The accessed symbol. 1734 * @param preciseMatch should we accept a type that is a subtype of 1735 * sym's owner, even if it doesn't contain sym 1736 * due to hiding, overriding, or non-inheritance 1737 * due to protection? 1738 */ 1739 JCExpression makeOwnerThis(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) { 1740 if (preciseMatch ? sym.isMemberOf(currentClass, types) 1741 : currentClass.isSubClass(sym.owner, types)) { 1742 // in this case, `this' works fine 1743 return make.at(pos).This(currentClass.erasure(types)); 1744 } else { 1745 // need to go via this$n 1746 return makeOwnerThisN(pos, sym, preciseMatch); 1747 } 1748 } 1749 1750 /** 1751 * Similar to makeOwnerThis but will never pick "this". 1752 */ 1753 JCExpression makeOwnerThisN(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) { 1754 Symbol c = sym.owner; 1755 List<VarSymbol> ots = outerThisStack; 1756 if (ots.isEmpty()) { 1757 log.error(pos, Errors.NoEnclInstanceOfTypeInScope(c)); 1758 return makeNull(); 1759 } 1760 VarSymbol ot = ots.head; 1761 JCExpression tree = access(make.at(pos).Ident(ot)); 1762 ot.flags_field &= ~NOOUTERTHIS; 1763 TypeSymbol otc = ot.type.tsym; 1764 while (!(preciseMatch ? sym.isMemberOf(otc, types) : otc.isSubClass(sym.owner, types))) { 1765 do { 1766 ots = ots.tail; 1767 if (ots.isEmpty()) { 1768 log.error(pos, Errors.NoEnclInstanceOfTypeInScope(c)); 1769 return tree; 1770 } 1771 ot = ots.head; 1772 } while (ot.owner != otc); 1773 tree = access(make.at(pos).Select(tree, ot)); 1774 ot.flags_field &= ~NOOUTERTHIS; 1775 otc = ot.type.tsym; 1776 } 1777 return tree; 1778 } 1779 1780 /** Return tree simulating the assignment {@code this.name = name}, where 1781 * name is the name of a free variable. 1782 */ 1783 JCStatement initField(int pos, Symbol rhs, Symbol lhs) { 1784 Assert.check(rhs.owner.kind == MTH); 1785 Assert.check(rhs.owner.owner == lhs.owner); 1786 make.at(pos); 1787 return 1788 make.Exec( 1789 make.Assign( 1790 make.Select(make.This(lhs.owner.erasure(types)), lhs), 1791 make.Ident(rhs)).setType(lhs.erasure(types))); 1792 } 1793 1794 /** 1795 * Return tree simulating null checking outer this and/or assigning. This is 1796 * called when a null check is required (nullCheckOuterThis), or a synthetic 1797 * field is generated (stores). 1798 */ 1799 JCStatement initOuterThis(int pos, VarSymbol rhs, boolean stores) { 1800 Assert.check(rhs.owner.kind == MTH); 1801 Assert.check(nullCheckOuterThis || stores); // One of the flags must be true 1802 make.at(pos); 1803 JCExpression expression = make.Ident(rhs); 1804 if (nullCheckOuterThis) { 1805 expression = attr.makeNullCheck(expression); 1806 } 1807 if (stores) { 1808 VarSymbol lhs = outerThisStack.head; 1809 Assert.check(rhs.owner.owner == lhs.owner); 1810 expression = make.Assign( 1811 make.Select(make.This(lhs.owner.erasure(types)), lhs), 1812 expression).setType(lhs.erasure(types)); 1813 } 1814 return make.Exec(expression); 1815 } 1816 1817 /* ************************************************************************ 1818 * Code for .class 1819 *************************************************************************/ 1820 1821 /** Return the symbol of a class to contain a cache of 1822 * compiler-generated statics such as class$ and the 1823 * $assertionsDisabled flag. We create an anonymous nested class 1824 * (unless one already exists) and return its symbol. However, 1825 * for backward compatibility in 1.4 and earlier we use the 1826 * top-level class itself. 1827 */ 1828 private ClassSymbol outerCacheClass() { 1829 ClassSymbol clazz = outermostClassDef.sym; 1830 Scope s = clazz.members(); 1831 for (Symbol sym : s.getSymbols(NON_RECURSIVE)) 1832 if (sym.kind == TYP && 1833 sym.name == names.empty && 1834 (sym.flags() & INTERFACE) == 0) return (ClassSymbol) sym; 1835 return makeEmptyClass(STATIC | SYNTHETIC, clazz).sym; 1836 } 1837 1838 /** Create an attributed tree of the form left.name(). */ 1839 private JCMethodInvocation makeCall(JCExpression left, Name name, List<JCExpression> args) { 1840 Assert.checkNonNull(left.type); 1841 Symbol funcsym = lookupMethod(make_pos, name, left.type, 1842 TreeInfo.types(args)); 1843 return make.App(make.Select(left, funcsym), args); 1844 } 1845 1846 /** The tree simulating a T.class expression. 1847 * @param clazz The tree identifying type T. 1848 */ 1849 private JCExpression classOf(JCTree clazz) { 1850 return classOfType(clazz.type, clazz.pos()); 1851 } 1852 1853 private JCExpression classOfType(Type type, DiagnosticPosition pos) { 1854 switch (type.getTag()) { 1855 case BYTE: case SHORT: case CHAR: case INT: case LONG: case FLOAT: 1856 case DOUBLE: case BOOLEAN: case VOID: 1857 // replace with <BoxedClass>.TYPE 1858 ClassSymbol c = types.boxedClass(type); 1859 Symbol typeSym = 1860 rs.accessBase( 1861 rs.findIdentInType(pos, attrEnv, c.type, names.TYPE, KindSelector.VAR), 1862 pos, c.type, names.TYPE, true); 1863 if (typeSym.kind == VAR) 1864 ((VarSymbol)typeSym).getConstValue(); // ensure initializer is evaluated 1865 return make.QualIdent(typeSym); 1866 case CLASS: case ARRAY: 1867 VarSymbol sym = new VarSymbol( 1868 STATIC | PUBLIC | FINAL, names._class, 1869 syms.classType, type.tsym); 1870 return make_at(pos).Select(make.Type(type), sym); 1871 default: 1872 throw new AssertionError(); 1873 } 1874 } 1875 1876 /* ************************************************************************ 1877 * Code for enabling/disabling assertions. 1878 *************************************************************************/ 1879 1880 private ClassSymbol assertionsDisabledClassCache; 1881 1882 /**Used to create an auxiliary class to hold $assertionsDisabled for interfaces. 1883 */ 1884 private ClassSymbol assertionsDisabledClass() { 1885 if (assertionsDisabledClassCache != null) return assertionsDisabledClassCache; 1886 1887 assertionsDisabledClassCache = makeEmptyClass(STATIC | SYNTHETIC, outermostClassDef.sym).sym; 1888 1889 return assertionsDisabledClassCache; 1890 } 1891 1892 // This code is not particularly robust if the user has 1893 // previously declared a member named '$assertionsDisabled'. 1894 // The same faulty idiom also appears in the translation of 1895 // class literals above. We should report an error if a 1896 // previous declaration is not synthetic. 1897 1898 private JCExpression assertFlagTest(DiagnosticPosition pos) { 1899 // Outermost class may be either true class or an interface. 1900 ClassSymbol outermostClass = outermostClassDef.sym; 1901 1902 //only classes can hold a non-public field, look for a usable one: 1903 ClassSymbol container = !currentClass.isInterface() ? currentClass : 1904 assertionsDisabledClass(); 1905 1906 VarSymbol assertDisabledSym = 1907 (VarSymbol)lookupSynthetic(dollarAssertionsDisabled, 1908 container.members()); 1909 if (assertDisabledSym == null) { 1910 assertDisabledSym = 1911 new VarSymbol(STATIC | FINAL | SYNTHETIC, 1912 dollarAssertionsDisabled, 1913 syms.booleanType, 1914 container); 1915 enterSynthetic(pos, assertDisabledSym, container.members()); 1916 Symbol desiredAssertionStatusSym = lookupMethod(pos, 1917 names.desiredAssertionStatus, 1918 types.erasure(syms.classType), 1919 List.nil()); 1920 JCClassDecl containerDef = classDef(container); 1921 make_at(containerDef.pos()); 1922 JCExpression notStatus = makeUnary(NOT, make.App(make.Select( 1923 classOfType(types.erasure(outermostClass.type), 1924 containerDef.pos()), 1925 desiredAssertionStatusSym))); 1926 JCVariableDecl assertDisabledDef = make.VarDef(assertDisabledSym, 1927 notStatus); 1928 containerDef.defs = containerDef.defs.prepend(assertDisabledDef); 1929 1930 if (currentClass.isInterface()) { 1931 //need to load the assertions enabled/disabled state while 1932 //initializing the interface: 1933 JCClassDecl currentClassDef = classDef(currentClass); 1934 make_at(currentClassDef.pos()); 1935 JCStatement dummy = make.If(make.QualIdent(assertDisabledSym), make.Skip(), null); 1936 JCBlock clinit = make.Block(STATIC, List.of(dummy)); 1937 currentClassDef.defs = currentClassDef.defs.prepend(clinit); 1938 } 1939 } 1940 make_at(pos); 1941 return makeUnary(NOT, make.Ident(assertDisabledSym)); 1942 } 1943 1944 1945 /* ************************************************************************ 1946 * Building blocks for let expressions 1947 *************************************************************************/ 1948 1949 interface TreeBuilder { 1950 JCExpression build(JCExpression arg); 1951 } 1952 1953 /** Construct an expression using the builder, with the given rval 1954 * expression as an argument to the builder. However, the rval 1955 * expression must be computed only once, even if used multiple 1956 * times in the result of the builder. We do that by 1957 * constructing a "let" expression that saves the rvalue into a 1958 * temporary variable and then uses the temporary variable in 1959 * place of the expression built by the builder. The complete 1960 * resulting expression is of the form 1961 * <pre> 1962 * (let <b>TYPE</b> <b>TEMP</b> = <b>RVAL</b>; 1963 * in (<b>BUILDER</b>(<b>TEMP</b>))) 1964 * </pre> 1965 * where <code><b>TEMP</b></code> is a newly declared variable 1966 * in the let expression. 1967 */ 1968 JCExpression abstractRval(JCExpression rval, Type type, TreeBuilder builder) { 1969 rval = TreeInfo.skipParens(rval); 1970 switch (rval.getTag()) { 1971 case LITERAL: 1972 return builder.build(rval); 1973 case IDENT: 1974 JCIdent id = (JCIdent) rval; 1975 if ((id.sym.flags() & FINAL) != 0 && id.sym.owner.kind == MTH) 1976 return builder.build(rval); 1977 } 1978 Name name = TreeInfo.name(rval); 1979 if (name == names._super || name == names._this) 1980 return builder.build(rval); 1981 VarSymbol var = 1982 new VarSymbol(FINAL|SYNTHETIC, 1983 names.fromString( 1984 target.syntheticNameChar() 1985 + "" + rval.hashCode()), 1986 type, 1987 currentMethodSym); 1988 rval = convert(rval,type); 1989 JCVariableDecl def = make.VarDef(var, rval); // XXX cast 1990 JCExpression built = builder.build(make.Ident(var)); 1991 JCExpression res = make.LetExpr(def, built); 1992 res.type = built.type; 1993 return res; 1994 } 1995 1996 // same as above, with the type of the temporary variable computed 1997 JCExpression abstractRval(JCExpression rval, TreeBuilder builder) { 1998 return abstractRval(rval, rval.type, builder); 1999 } 2000 2001 // same as above, but for an expression that may be used as either 2002 // an rvalue or an lvalue. This requires special handling for 2003 // Select expressions, where we place the left-hand-side of the 2004 // select in a temporary, and for Indexed expressions, where we 2005 // place both the indexed expression and the index value in temps. 2006 JCExpression abstractLval(JCExpression lval, final TreeBuilder builder) { 2007 lval = TreeInfo.skipParens(lval); 2008 switch (lval.getTag()) { 2009 case IDENT: 2010 return builder.build(lval); 2011 case SELECT: { 2012 final JCFieldAccess s = (JCFieldAccess)lval; 2013 Symbol lid = TreeInfo.symbol(s.selected); 2014 if (lid != null && lid.kind == TYP) return builder.build(lval); 2015 return abstractRval(s.selected, selected -> builder.build(make.Select(selected, s.sym))); 2016 } 2017 case INDEXED: { 2018 final JCArrayAccess i = (JCArrayAccess)lval; 2019 return abstractRval(i.indexed, indexed -> abstractRval(i.index, syms.intType, index -> { 2020 JCExpression newLval = make.Indexed(indexed, index); 2021 newLval.setType(i.type); 2022 return builder.build(newLval); 2023 })); 2024 } 2025 case TYPECAST: { 2026 return abstractLval(((JCTypeCast)lval).expr, builder); 2027 } 2028 } 2029 throw new AssertionError(lval); 2030 } 2031 2032 // evaluate and discard the first expression, then evaluate the second. 2033 JCExpression makeComma(final JCExpression expr1, final JCExpression expr2) { 2034 JCExpression res = make.LetExpr(List.of(make.Exec(expr1)), expr2); 2035 res.type = expr2.type; 2036 return res; 2037 } 2038 2039 /* ************************************************************************ 2040 * Translation methods 2041 *************************************************************************/ 2042 2043 /** Visitor argument: enclosing operator node. 2044 */ 2045 private JCExpression enclOp; 2046 2047 /** Visitor method: Translate a single node. 2048 * Attach the source position from the old tree to its replacement tree. 2049 */ 2050 @Override 2051 public <T extends JCTree> T translate(T tree) { 2052 if (tree == null) { 2053 return null; 2054 } else { 2055 make_at(tree.pos()); 2056 T result = super.translate(tree); 2057 if (result != null && result != tree) { 2058 result.endpos = tree.endpos; 2059 } 2060 return result; 2061 } 2062 } 2063 2064 /** Visitor method: Translate a single node, boxing or unboxing if needed. 2065 */ 2066 public <T extends JCExpression> T translate(T tree, Type type) { 2067 return (tree == null) ? null : boxIfNeeded(translate(tree), type); 2068 } 2069 2070 /** Visitor method: Translate tree. 2071 */ 2072 public <T extends JCTree> T translate(T tree, JCExpression enclOp) { 2073 JCExpression prevEnclOp = this.enclOp; 2074 this.enclOp = enclOp; 2075 T res = translate(tree); 2076 this.enclOp = prevEnclOp; 2077 return res; 2078 } 2079 2080 /** Visitor method: Translate list of trees. 2081 */ 2082 public <T extends JCExpression> List<T> translate(List<T> trees, Type type) { 2083 if (trees == null) return null; 2084 for (List<T> l = trees; l.nonEmpty(); l = l.tail) 2085 l.head = translate(l.head, type); 2086 return trees; 2087 } 2088 2089 public void visitPackageDef(JCPackageDecl tree) { 2090 if (!needPackageInfoClass(tree)) 2091 return; 2092 2093 long flags = Flags.ABSTRACT | Flags.INTERFACE; 2094 // package-info is marked SYNTHETIC in JDK 1.6 and later releases 2095 flags = flags | Flags.SYNTHETIC; 2096 ClassSymbol c = tree.packge.package_info; 2097 c.setAttributes(tree.packge); 2098 c.flags_field |= flags; 2099 ClassType ctype = (ClassType) c.type; 2100 ctype.supertype_field = syms.objectType; 2101 ctype.interfaces_field = List.nil(); 2102 createInfoClass(tree.annotations, c); 2103 } 2104 // where 2105 private boolean needPackageInfoClass(JCPackageDecl pd) { 2106 switch (pkginfoOpt) { 2107 case ALWAYS: 2108 return true; 2109 case LEGACY: 2110 return pd.getAnnotations().nonEmpty(); 2111 case NONEMPTY: 2112 for (Attribute.Compound a : 2113 pd.packge.getDeclarationAttributes()) { 2114 Attribute.RetentionPolicy p = types.getRetention(a); 2115 if (p != Attribute.RetentionPolicy.SOURCE) 2116 return true; 2117 } 2118 return false; 2119 } 2120 throw new AssertionError(); 2121 } 2122 2123 public void visitModuleDef(JCModuleDecl tree) { 2124 ModuleSymbol msym = tree.sym; 2125 ClassSymbol c = msym.module_info; 2126 c.setAttributes(msym); 2127 c.flags_field |= Flags.MODULE; 2128 createInfoClass(List.nil(), tree.sym.module_info); 2129 } 2130 2131 private void createInfoClass(List<JCAnnotation> annots, ClassSymbol c) { 2132 long flags = Flags.ABSTRACT | Flags.INTERFACE; 2133 JCClassDecl infoClass = 2134 make.ClassDef(make.Modifiers(flags, annots), 2135 c.name, List.nil(), 2136 null, List.nil(), List.nil()); 2137 infoClass.sym = c; 2138 translated.append(infoClass); 2139 } 2140 2141 public void visitClassDef(JCClassDecl tree) { 2142 Env<AttrContext> prevEnv = attrEnv; 2143 ClassSymbol currentClassPrev = currentClass; 2144 MethodSymbol currentMethodSymPrev = currentMethodSym; 2145 2146 currentClass = tree.sym; 2147 currentMethodSym = null; 2148 attrEnv = typeEnvs.remove(currentClass); 2149 if (attrEnv == null) 2150 attrEnv = prevEnv; 2151 2152 classdefs.put(currentClass, tree); 2153 2154 Map<Symbol, Symbol> prevProxies = proxies; 2155 proxies = new HashMap<>(proxies); 2156 List<VarSymbol> prevOuterThisStack = outerThisStack; 2157 2158 // If this is an enum definition 2159 if ((tree.mods.flags & ENUM) != 0 && 2160 (types.supertype(currentClass.type).tsym.flags() & ENUM) == 0) 2161 visitEnumDef(tree); 2162 2163 if ((tree.mods.flags & RECORD) != 0) { 2164 visitRecordDef(tree); 2165 } 2166 2167 // If this is a nested class, define a this$n field for 2168 // it and add to proxies. 2169 JCVariableDecl otdef = null; 2170 if (currentClass.hasOuterInstance()) 2171 otdef = outerThisDef(tree.pos, currentClass); 2172 2173 // If this is a local class, define proxies for all its free variables. 2174 List<JCVariableDecl> fvdefs = freevarDefs( 2175 tree.pos, freevars(currentClass), currentClass); 2176 2177 // Recursively translate superclass, interfaces. 2178 tree.extending = translate(tree.extending); 2179 tree.implementing = translate(tree.implementing); 2180 2181 if (currentClass.isDirectlyOrIndirectlyLocal()) { 2182 ClassSymbol encl = currentClass.owner.enclClass(); 2183 if (encl.trans_local == null) { 2184 encl.trans_local = List.nil(); 2185 } 2186 encl.trans_local = encl.trans_local.prepend(currentClass); 2187 } 2188 2189 // Recursively translate members, taking into account that new members 2190 // might be created during the translation and prepended to the member 2191 // list `tree.defs'. 2192 List<JCTree> seen = List.nil(); 2193 while (tree.defs != seen) { 2194 List<JCTree> unseen = tree.defs; 2195 for (List<JCTree> l = unseen; l.nonEmpty() && l != seen; l = l.tail) { 2196 JCTree outermostMemberDefPrev = outermostMemberDef; 2197 if (outermostMemberDefPrev == null) outermostMemberDef = l.head; 2198 l.head = translate(l.head); 2199 outermostMemberDef = outermostMemberDefPrev; 2200 } 2201 seen = unseen; 2202 } 2203 2204 // Convert a protected modifier to public, mask static modifier. 2205 if ((tree.mods.flags & PROTECTED) != 0) tree.mods.flags |= PUBLIC; 2206 tree.mods.flags &= ClassFlags; 2207 2208 // Convert name to flat representation, replacing '.' by '$'. 2209 tree.name = Convert.shortName(currentClass.flatName()); 2210 2211 // Add free variables proxy definitions to class. 2212 2213 for (List<JCVariableDecl> l = fvdefs; l.nonEmpty(); l = l.tail) { 2214 tree.defs = tree.defs.prepend(l.head); 2215 enterSynthetic(tree.pos(), l.head.sym, currentClass.members()); 2216 } 2217 // If this$n was accessed, add the field definition and prepend 2218 // initializer code to any super() invocation to initialize it 2219 // otherwise prepend enclosing instance null check code if required 2220 emitOuter: 2221 if (currentClass.hasOuterInstance()) { 2222 boolean storesThis = shouldEmitOuterThis(currentClass); 2223 if (storesThis) { 2224 tree.defs = tree.defs.prepend(otdef); 2225 enterSynthetic(tree.pos(), otdef.sym, currentClass.members()); 2226 } else if (!nullCheckOuterThis) { 2227 break emitOuter; 2228 } 2229 2230 for (JCTree def : tree.defs) { 2231 if (TreeInfo.isConstructor(def)) { 2232 JCMethodDecl mdef = (JCMethodDecl)def; 2233 if (TreeInfo.hasConstructorCall(mdef, names._super)) { 2234 List<JCStatement> initializer = List.of(initOuterThis(mdef.body.pos, mdef.params.head.sym, storesThis)) ; 2235 TreeInfo.mapSuperCalls(mdef.body, supercall -> make.Block(0, initializer.append(supercall))); 2236 } 2237 } 2238 } 2239 } 2240 2241 proxies = prevProxies; 2242 outerThisStack = prevOuterThisStack; 2243 2244 // Append translated tree to `translated' queue. 2245 translated.append(tree); 2246 2247 attrEnv = prevEnv; 2248 currentClass = currentClassPrev; 2249 currentMethodSym = currentMethodSymPrev; 2250 2251 // Return empty block {} as a placeholder for an inner class. 2252 result = make_at(tree.pos()).Block(SYNTHETIC, List.nil()); 2253 } 2254 2255 private boolean shouldEmitOuterThis(ClassSymbol sym) { 2256 if (!optimizeOuterThis) { 2257 // Optimization is disabled 2258 return true; 2259 } 2260 if ((outerThisStack.head.flags_field & NOOUTERTHIS) == 0) { 2261 // Enclosing instance field is used 2262 return true; 2263 } 2264 if (rs.isSerializable(sym.type)) { 2265 // Class is serializable 2266 return true; 2267 } 2268 return false; 2269 } 2270 2271 List<JCTree> generateMandatedAccessors(JCClassDecl tree) { 2272 List<JCVariableDecl> fields = TreeInfo.recordFields(tree); 2273 return tree.sym.getRecordComponents().stream() 2274 .filter(rc -> (rc.accessor.flags() & Flags.GENERATED_MEMBER) != 0) 2275 .map(rc -> { 2276 // we need to return the field not the record component 2277 JCVariableDecl field = fields.stream().filter(f -> f.name == rc.name).findAny().get(); 2278 make_at(tree.pos()); 2279 return make.MethodDef(rc.accessor, make.Block(0, 2280 List.of(make.Return(make.Ident(field))))); 2281 }).collect(List.collector()); 2282 } 2283 2284 /** Translate an enum class. */ 2285 private void visitEnumDef(JCClassDecl tree) { 2286 make_at(tree.pos()); 2287 2288 // add the supertype, if needed 2289 if (tree.extending == null) 2290 tree.extending = make.Type(types.supertype(tree.type)); 2291 2292 // classOfType adds a cache field to tree.defs 2293 JCExpression e_class = classOfType(tree.sym.type, tree.pos()). 2294 setType(types.erasure(syms.classType)); 2295 2296 // process each enumeration constant, adding implicit constructor parameters 2297 int nextOrdinal = 0; 2298 ListBuffer<JCExpression> values = new ListBuffer<>(); 2299 ListBuffer<JCTree> enumDefs = new ListBuffer<>(); 2300 ListBuffer<JCTree> otherDefs = new ListBuffer<>(); 2301 for (List<JCTree> defs = tree.defs; 2302 defs.nonEmpty(); 2303 defs=defs.tail) { 2304 if (defs.head.hasTag(VARDEF) && (((JCVariableDecl) defs.head).mods.flags & ENUM) != 0) { 2305 JCVariableDecl var = (JCVariableDecl)defs.head; 2306 visitEnumConstantDef(var, nextOrdinal++); 2307 values.append(make.QualIdent(var.sym)); 2308 enumDefs.append(var); 2309 } else { 2310 otherDefs.append(defs.head); 2311 } 2312 } 2313 2314 // synthetic private static T[] $values() { return new T[] { a, b, c }; } 2315 // synthetic private static final T[] $VALUES = $values(); 2316 Name valuesName = syntheticName(tree, "VALUES"); 2317 Type arrayType = new ArrayType(types.erasure(tree.type), syms.arrayClass); 2318 VarSymbol valuesVar = new VarSymbol(PRIVATE|FINAL|STATIC|SYNTHETIC, 2319 valuesName, 2320 arrayType, 2321 tree.type.tsym); 2322 JCNewArray newArray = make.NewArray(make.Type(types.erasure(tree.type)), 2323 List.nil(), 2324 values.toList()); 2325 newArray.type = arrayType; 2326 2327 MethodSymbol valuesMethod = new MethodSymbol(PRIVATE|STATIC|SYNTHETIC, 2328 syntheticName(tree, "values"), 2329 new MethodType(List.nil(), arrayType, List.nil(), tree.type.tsym), 2330 tree.type.tsym); 2331 enumDefs.append(make.MethodDef(valuesMethod, make.Block(0, List.of(make.Return(newArray))))); 2332 tree.sym.members().enter(valuesMethod); 2333 2334 enumDefs.append(make.VarDef(valuesVar, make.App(make.QualIdent(valuesMethod)))); 2335 tree.sym.members().enter(valuesVar); 2336 2337 MethodSymbol valuesSym = lookupMethod(tree.pos(), names.values, 2338 tree.type, List.nil()); 2339 List<JCStatement> valuesBody; 2340 if (useClone()) { 2341 // return (T[]) $VALUES.clone(); 2342 JCTypeCast valuesResult = 2343 make.TypeCast(valuesSym.type.getReturnType(), 2344 make.App(make.Select(make.Ident(valuesVar), 2345 syms.arrayCloneMethod))); 2346 valuesBody = List.of(make.Return(valuesResult)); 2347 } else { 2348 // template: T[] $result = new T[$values.length]; 2349 Name resultName = syntheticName(tree, "result"); 2350 VarSymbol resultVar = new VarSymbol(FINAL|SYNTHETIC, 2351 resultName, 2352 arrayType, 2353 valuesSym); 2354 JCNewArray resultArray = make.NewArray(make.Type(types.erasure(tree.type)), 2355 List.of(make.Select(make.Ident(valuesVar), syms.lengthVar)), 2356 null); 2357 resultArray.type = arrayType; 2358 JCVariableDecl decl = make.VarDef(resultVar, resultArray); 2359 2360 // template: System.arraycopy($VALUES, 0, $result, 0, $VALUES.length); 2361 if (systemArraycopyMethod == null) { 2362 systemArraycopyMethod = 2363 new MethodSymbol(PUBLIC | STATIC, 2364 names.fromString("arraycopy"), 2365 new MethodType(List.of(syms.objectType, 2366 syms.intType, 2367 syms.objectType, 2368 syms.intType, 2369 syms.intType), 2370 syms.voidType, 2371 List.nil(), 2372 syms.methodClass), 2373 syms.systemType.tsym); 2374 } 2375 JCStatement copy = 2376 make.Exec(make.App(make.Select(make.Ident(syms.systemType.tsym), 2377 systemArraycopyMethod), 2378 List.of(make.Ident(valuesVar), make.Literal(0), 2379 make.Ident(resultVar), make.Literal(0), 2380 make.Select(make.Ident(valuesVar), syms.lengthVar)))); 2381 2382 // template: return $result; 2383 JCStatement ret = make.Return(make.Ident(resultVar)); 2384 valuesBody = List.of(decl, copy, ret); 2385 } 2386 2387 JCMethodDecl valuesDef = 2388 make.MethodDef(valuesSym, make.Block(0, valuesBody)); 2389 2390 enumDefs.append(valuesDef); 2391 2392 if (debugLower) 2393 System.err.println(tree.sym + ".valuesDef = " + valuesDef); 2394 2395 /** The template for the following code is: 2396 * 2397 * public static E valueOf(String name) { 2398 * return (E)Enum.valueOf(E.class, name); 2399 * } 2400 * 2401 * where E is tree.sym 2402 */ 2403 MethodSymbol valueOfSym = lookupMethod(tree.pos(), 2404 names.valueOf, 2405 tree.sym.type, 2406 List.of(syms.stringType)); 2407 Assert.check((valueOfSym.flags() & STATIC) != 0); 2408 VarSymbol nameArgSym = valueOfSym.params.head; 2409 JCIdent nameVal = make.Ident(nameArgSym); 2410 JCStatement enum_ValueOf = 2411 make.Return(make.TypeCast(tree.sym.type, 2412 makeCall(make.Ident(syms.enumSym), 2413 names.valueOf, 2414 List.of(e_class, nameVal)))); 2415 JCMethodDecl valueOf = make.MethodDef(valueOfSym, 2416 make.Block(0, List.of(enum_ValueOf))); 2417 nameVal.sym = valueOf.params.head.sym; 2418 if (debugLower) 2419 System.err.println(tree.sym + ".valueOf = " + valueOf); 2420 enumDefs.append(valueOf); 2421 2422 enumDefs.appendList(otherDefs.toList()); 2423 tree.defs = enumDefs.toList(); 2424 } 2425 // where 2426 private MethodSymbol systemArraycopyMethod; 2427 private boolean useClone() { 2428 try { 2429 return syms.objectType.tsym.members().findFirst(names.clone) != null; 2430 } 2431 catch (CompletionFailure e) { 2432 return false; 2433 } 2434 } 2435 2436 private Name syntheticName(JCClassDecl tree, String baseName) { 2437 Name valuesName = names.fromString(target.syntheticNameChar() + baseName); 2438 while (tree.sym.members().findFirst(valuesName) != null) // avoid name clash 2439 valuesName = names.fromString(valuesName + "" + target.syntheticNameChar()); 2440 return valuesName; 2441 } 2442 2443 /** Translate an enumeration constant and its initializer. */ 2444 private void visitEnumConstantDef(JCVariableDecl var, int ordinal) { 2445 JCNewClass varDef = (JCNewClass)var.init; 2446 varDef.args = varDef.args. 2447 prepend(makeLit(syms.intType, ordinal)). 2448 prepend(makeLit(syms.stringType, var.name.toString())); 2449 } 2450 2451 private List<VarSymbol> recordVars(Type t) { 2452 List<VarSymbol> vars = List.nil(); 2453 while (!t.hasTag(NONE)) { 2454 if (t.hasTag(CLASS)) { 2455 for (Symbol s : t.tsym.members().getSymbols(s -> s.kind == VAR && (s.flags() & RECORD) != 0)) { 2456 vars = vars.prepend((VarSymbol)s); 2457 } 2458 } 2459 t = types.supertype(t); 2460 } 2461 return vars; 2462 } 2463 2464 /** Translate a record. */ 2465 private void visitRecordDef(JCClassDecl tree) { 2466 make_at(tree.pos()); 2467 List<VarSymbol> vars = recordVars(tree.type); 2468 MethodHandleSymbol[] getterMethHandles = new MethodHandleSymbol[vars.size()]; 2469 int index = 0; 2470 for (VarSymbol var : vars) { 2471 if (var.owner != tree.sym) { 2472 var = new VarSymbol(var.flags_field, var.name, var.type, tree.sym); 2473 } 2474 getterMethHandles[index] = var.asMethodHandle(true); 2475 index++; 2476 } 2477 2478 tree.defs = tree.defs.appendList(generateMandatedAccessors(tree)); 2479 tree.defs = tree.defs.appendList(List.of( 2480 generateRecordMethod(tree, names.toString, vars, getterMethHandles), 2481 generateRecordMethod(tree, names.hashCode, vars, getterMethHandles), 2482 generateRecordMethod(tree, names.equals, vars, getterMethHandles) 2483 )); 2484 } 2485 2486 JCTree generateRecordMethod(JCClassDecl tree, Name name, List<VarSymbol> vars, MethodHandleSymbol[] getterMethHandles) { 2487 make_at(tree.pos()); 2488 boolean isEquals = name == names.equals; 2489 MethodSymbol msym = lookupMethod(tree.pos(), 2490 name, 2491 tree.sym.type, 2492 isEquals ? List.of(syms.objectType) : List.nil()); 2493 // compiler generated methods have the record flag set, user defined ones dont 2494 if ((msym.flags() & RECORD) != 0) { 2495 /* class java.lang.runtime.ObjectMethods provides a common bootstrap that provides a customized implementation 2496 * for methods: toString, hashCode and equals. Here we just need to generate and indy call to: 2497 * java.lang.runtime.ObjectMethods::bootstrap and provide: the record class, the record component names and 2498 * the accessors. 2499 */ 2500 Name bootstrapName = names.bootstrap; 2501 LoadableConstant[] staticArgsValues = new LoadableConstant[2 + getterMethHandles.length]; 2502 staticArgsValues[0] = (ClassType)tree.sym.type; 2503 String concatNames = vars.stream() 2504 .map(v -> v.name) 2505 .collect(Collectors.joining(";", "", "")); 2506 staticArgsValues[1] = LoadableConstant.String(concatNames); 2507 int index = 2; 2508 for (MethodHandleSymbol mho : getterMethHandles) { 2509 staticArgsValues[index] = mho; 2510 index++; 2511 } 2512 2513 List<Type> staticArgTypes = List.of(syms.classType, 2514 syms.stringType, 2515 new ArrayType(syms.methodHandleType, syms.arrayClass)); 2516 2517 JCFieldAccess qualifier = makeIndyQualifier(syms.objectMethodsType, tree, msym, 2518 List.of(syms.methodHandleLookupType, 2519 syms.stringType, 2520 syms.typeDescriptorType).appendList(staticArgTypes), 2521 staticArgsValues, bootstrapName, name, false); 2522 2523 VarSymbol _this = new VarSymbol(SYNTHETIC, names._this, tree.sym.type, tree.sym); 2524 2525 JCMethodInvocation proxyCall; 2526 if (!isEquals) { 2527 proxyCall = make.Apply(List.nil(), qualifier, List.of(make.Ident(_this))); 2528 } else { 2529 VarSymbol o = msym.params.head; 2530 o.adr = 0; 2531 proxyCall = make.Apply(List.nil(), qualifier, List.of(make.Ident(_this), make.Ident(o))); 2532 } 2533 proxyCall.type = qualifier.type; 2534 return make.MethodDef(msym, make.Block(0, List.of(make.Return(proxyCall)))); 2535 } else { 2536 return make.Block(SYNTHETIC, List.nil()); 2537 } 2538 } 2539 2540 private String argsTypeSig(List<Type> typeList) { 2541 LowerSignatureGenerator sg = new LowerSignatureGenerator(); 2542 sg.assembleSig(typeList); 2543 return sg.toString(); 2544 } 2545 2546 /** 2547 * Signature Generation 2548 */ 2549 private class LowerSignatureGenerator extends Types.SignatureGenerator { 2550 2551 /** 2552 * An output buffer for type signatures. 2553 */ 2554 StringBuilder sb = new StringBuilder(); 2555 2556 LowerSignatureGenerator() { 2557 types.super(); 2558 } 2559 2560 @Override 2561 protected void append(char ch) { 2562 sb.append(ch); 2563 } 2564 2565 @Override 2566 protected void append(byte[] ba) { 2567 sb.append(new String(ba)); 2568 } 2569 2570 @Override 2571 protected void append(Name name) { 2572 sb.append(name.toString()); 2573 } 2574 2575 @Override 2576 public String toString() { 2577 return sb.toString(); 2578 } 2579 } 2580 2581 /** 2582 * Creates an indy qualifier, helpful to be part of an indy invocation 2583 * @param site the site 2584 * @param tree a class declaration tree 2585 * @param msym the method symbol 2586 * @param staticArgTypes the static argument types 2587 * @param staticArgValues the static argument values 2588 * @param bootstrapName the bootstrap name to look for 2589 * @param argName normally bootstraps receives a method name as second argument, if you want that name 2590 * to be different to that of the bootstrap name pass a different name here 2591 * @param isStatic is it static or not 2592 * @return a field access tree 2593 */ 2594 JCFieldAccess makeIndyQualifier( 2595 Type site, 2596 JCClassDecl tree, 2597 MethodSymbol msym, 2598 List<Type> staticArgTypes, 2599 LoadableConstant[] staticArgValues, 2600 Name bootstrapName, 2601 Name argName, 2602 boolean isStatic) { 2603 MethodSymbol bsm = rs.resolveInternalMethod(tree.pos(), attrEnv, site, 2604 bootstrapName, staticArgTypes, List.nil()); 2605 2606 MethodType indyType = msym.type.asMethodType(); 2607 indyType = new MethodType( 2608 isStatic ? List.nil() : indyType.argtypes.prepend(tree.sym.type), 2609 indyType.restype, 2610 indyType.thrown, 2611 syms.methodClass 2612 ); 2613 DynamicMethodSymbol dynSym = new DynamicMethodSymbol(argName, 2614 syms.noSymbol, 2615 bsm.asHandle(), 2616 indyType, 2617 staticArgValues); 2618 JCFieldAccess qualifier = make.Select(make.QualIdent(site.tsym), argName); 2619 qualifier.sym = dynSym; 2620 qualifier.type = msym.type.asMethodType().restype; 2621 return qualifier; 2622 } 2623 2624 public void visitMethodDef(JCMethodDecl tree) { 2625 if (tree.name == names.init && (currentClass.flags_field&ENUM) != 0) { 2626 // Add "String $enum$name, int $enum$ordinal" to the beginning of the 2627 // argument list for each constructor of an enum. 2628 JCVariableDecl nameParam = make_at(tree.pos()). 2629 Param(names.fromString(target.syntheticNameChar() + 2630 "enum" + target.syntheticNameChar() + "name"), 2631 syms.stringType, tree.sym); 2632 nameParam.mods.flags |= SYNTHETIC; nameParam.sym.flags_field |= SYNTHETIC; 2633 JCVariableDecl ordParam = make. 2634 Param(names.fromString(target.syntheticNameChar() + 2635 "enum" + target.syntheticNameChar() + 2636 "ordinal"), 2637 syms.intType, tree.sym); 2638 ordParam.mods.flags |= SYNTHETIC; ordParam.sym.flags_field |= SYNTHETIC; 2639 2640 MethodSymbol m = tree.sym; 2641 tree.params = tree.params.prepend(ordParam).prepend(nameParam); 2642 2643 m.extraParams = m.extraParams.prepend(ordParam.sym); 2644 m.extraParams = m.extraParams.prepend(nameParam.sym); 2645 Type olderasure = m.erasure(types); 2646 m.erasure_field = new MethodType( 2647 olderasure.getParameterTypes().prepend(syms.intType).prepend(syms.stringType), 2648 olderasure.getReturnType(), 2649 olderasure.getThrownTypes(), 2650 syms.methodClass); 2651 } 2652 2653 Type prevRestype = currentRestype; 2654 JCMethodDecl prevMethodDef = currentMethodDef; 2655 MethodSymbol prevMethodSym = currentMethodSym; 2656 int prevVariableIndex = variableIndex; 2657 try { 2658 currentRestype = types.erasure(tree.type.getReturnType()); 2659 currentMethodDef = tree; 2660 currentMethodSym = tree.sym; 2661 variableIndex = 0; 2662 visitMethodDefInternal(tree); 2663 } finally { 2664 currentRestype = prevRestype; 2665 currentMethodDef = prevMethodDef; 2666 currentMethodSym = prevMethodSym; 2667 variableIndex = prevVariableIndex; 2668 } 2669 } 2670 2671 private void visitMethodDefInternal(JCMethodDecl tree) { 2672 if (tree.name == names.init && 2673 !currentClass.isStatic() && 2674 (currentClass.isInner() || currentClass.isDirectlyOrIndirectlyLocal())) { 2675 // We are seeing a constructor of an inner class. 2676 MethodSymbol m = tree.sym; 2677 2678 // Push a new proxy scope for constructor parameters. 2679 // and create definitions for any this$n and proxy parameters. 2680 Map<Symbol, Symbol> prevProxies = proxies; 2681 proxies = new HashMap<>(proxies); 2682 List<VarSymbol> prevOuterThisStack = outerThisStack; 2683 List<VarSymbol> fvs = freevars(currentClass); 2684 JCVariableDecl otdef = null; 2685 if (currentClass.hasOuterInstance()) 2686 otdef = outerThisDef(tree.pos, m); 2687 List<JCVariableDecl> fvdefs = freevarDefs(tree.pos, fvs, m, PARAMETER); 2688 2689 // Recursively translate result type, parameters and thrown list. 2690 tree.restype = translate(tree.restype); 2691 tree.params = translateVarDefs(tree.params); 2692 tree.thrown = translate(tree.thrown); 2693 2694 // when compiling stubs, don't process body 2695 if (tree.body == null) { 2696 result = tree; 2697 return; 2698 } 2699 2700 // Add this$n (if needed) in front of and free variables behind 2701 // constructor parameter list. 2702 tree.params = tree.params.appendList(fvdefs); 2703 if (currentClass.hasOuterInstance()) { 2704 tree.params = tree.params.prepend(otdef); 2705 } 2706 2707 // Determine whether this constructor has a super() invocation 2708 boolean invokesSuper = TreeInfo.hasConstructorCall(tree, names._super); 2709 2710 // Create initializers for this$n and proxies 2711 ListBuffer<JCStatement> added = new ListBuffer<>(); 2712 if (fvs.nonEmpty()) { 2713 List<Type> addedargtypes = List.nil(); 2714 for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) { 2715 m.capturedLocals = 2716 m.capturedLocals.prepend((VarSymbol) 2717 (proxies.get(l.head))); 2718 if (invokesSuper) { 2719 added = added.prepend( 2720 initField(tree.body.pos, proxies.get(l.head), prevProxies.get(l.head))); 2721 } 2722 addedargtypes = addedargtypes.prepend(l.head.erasure(types)); 2723 } 2724 Type olderasure = m.erasure(types); 2725 m.erasure_field = new MethodType( 2726 olderasure.getParameterTypes().appendList(addedargtypes), 2727 olderasure.getReturnType(), 2728 olderasure.getThrownTypes(), 2729 syms.methodClass); 2730 } 2731 2732 // Recursively translate existing local statements 2733 tree.body.stats = translate(tree.body.stats); 2734 2735 // Prepend initializers in front of super() call 2736 if (added.nonEmpty()) { 2737 List<JCStatement> initializers = added.toList(); 2738 TreeInfo.mapSuperCalls(tree.body, supercall -> make.Block(0, initializers.append(supercall))); 2739 } 2740 2741 // pop local variables from proxy stack 2742 proxies = prevProxies; 2743 2744 outerThisStack = prevOuterThisStack; 2745 } else { 2746 super.visitMethodDef(tree); 2747 } 2748 if (tree.name == names.init && ((tree.sym.flags_field & Flags.COMPACT_RECORD_CONSTRUCTOR) != 0 || 2749 (tree.sym.flags_field & (GENERATEDCONSTR | RECORD)) == (GENERATEDCONSTR | RECORD))) { 2750 // lets find out if there is any field waiting to be initialized 2751 ListBuffer<VarSymbol> fields = new ListBuffer<>(); 2752 for (Symbol sym : currentClass.getEnclosedElements()) { 2753 if (sym.kind == Kinds.Kind.VAR && ((sym.flags() & RECORD) != 0)) 2754 fields.append((VarSymbol) sym); 2755 } 2756 for (VarSymbol field: fields) { 2757 if ((field.flags_field & Flags.UNINITIALIZED_FIELD) != 0) { 2758 VarSymbol param = tree.params.stream().filter(p -> p.name == field.name).findFirst().get().sym; 2759 make.at(tree.pos); 2760 tree.body.stats = tree.body.stats.append( 2761 make.Exec( 2762 make.Assign( 2763 make.Select(make.This(field.owner.erasure(types)), field), 2764 make.Ident(param)).setType(field.erasure(types)))); 2765 // we don't need the flag at the field anymore 2766 field.flags_field &= ~Flags.UNINITIALIZED_FIELD; 2767 } 2768 } 2769 } 2770 result = tree; 2771 } 2772 2773 public void visitTypeCast(JCTypeCast tree) { 2774 tree.clazz = translate(tree.clazz); 2775 if (tree.type.isPrimitive() != tree.expr.type.isPrimitive()) 2776 tree.expr = translate(tree.expr, tree.type); 2777 else 2778 tree.expr = translate(tree.expr); 2779 result = tree; 2780 } 2781 2782 /** 2783 * All the exactness checks between primitive types that require a run-time 2784 * check are in {@code java.lang.runtime.ExactConversionsSupport}. Those methods 2785 * are in the form {@code ExactConversionsSupport.is<S>To<T>Exact} where both 2786 * {@code S} and {@code T} are primitive types and correspond to the runtime 2787 * action that will be executed to check whether a certain value (that is passed 2788 * as a parameter) can be converted to {@code T} without loss of information. 2789 * 2790 * Rewrite {@code instanceof if expr : Object} and Type is primitive type: 2791 * 2792 * {@snippet : 2793 * Object v = ... 2794 * if (v instanceof float) 2795 * => 2796 * if (let tmp$123 = v; tmp$123 instanceof Float) 2797 * } 2798 * 2799 * Rewrite {@code instanceof if expr : wrapper reference type} 2800 * 2801 * {@snippet : 2802 * Integer v = ... 2803 * if (v instanceof float) 2804 * => 2805 * if (let tmp$123 = v; tmp$123 != null && ExactConversionsSupport.intToFloatExact(tmp$123.intValue())) 2806 * } 2807 * 2808 * Rewrite {@code instanceof if expr : primitive} 2809 * 2810 * {@snippet : 2811 * int v = ... 2812 * if (v instanceof float) 2813 * => 2814 * if (let tmp$123 = v; ExactConversionsSupport.intToFloatExact(tmp$123)) 2815 * } 2816 * 2817 * More rewritings: 2818 * <ul> 2819 * <li>If the {@code instanceof} check is unconditionally exact rewrite to true.</li> 2820 * <li>If expression type is {@code Byte}, {@code Short}, {@code Integer}, ..., an 2821 * unboxing conversion followed by a widening primitive conversion.</li> 2822 * <li>If expression type is a supertype: {@code Number}, a narrowing reference 2823 * conversion followed by an unboxing conversion.</li> 2824 * </ul> 2825 */ 2826 public void visitTypeTest(JCInstanceOf tree) { 2827 if (tree.expr.type.isPrimitive() || tree.pattern.type.isPrimitive()) { 2828 JCStatement prefixStatement; 2829 JCExpression exactnessCheck; 2830 JCExpression instanceOfExpr = translate(tree.expr); 2831 2832 if (types.isUnconditionallyExactTypeBased(tree.expr.type, tree.pattern.type)) { 2833 // instanceOfExpr; true 2834 prefixStatement = make.Exec(instanceOfExpr); 2835 exactnessCheck = make.Literal(BOOLEAN, 1).setType(syms.booleanType.constType(1)); 2836 } else if (tree.expr.type.isPrimitive()) { 2837 // ExactConversionSupport.isXxxExact(instanceOfExpr) 2838 prefixStatement = null; 2839 exactnessCheck = getExactnessCheck(tree, instanceOfExpr); 2840 } else if (tree.expr.type.isReference()) { 2841 if (types.isUnconditionallyExactTypeBased(types.unboxedType(tree.expr.type), tree.pattern.type)) { 2842 // instanceOfExpr != null 2843 prefixStatement = null; 2844 exactnessCheck = makeBinary(NE, instanceOfExpr, makeNull()); 2845 } else { 2846 // We read the result of instanceOfExpr, so create variable 2847 VarSymbol dollar_s = new VarSymbol(FINAL | SYNTHETIC, 2848 names.fromString("tmp" + variableIndex++ + this.target.syntheticNameChar()), 2849 types.erasure(tree.expr.type), 2850 currentMethodSym); 2851 prefixStatement = make.at(tree.pos()) 2852 .VarDef(dollar_s, instanceOfExpr); 2853 2854 JCExpression nullCheck = 2855 makeBinary(NE, 2856 make.Ident(dollar_s), 2857 makeNull()); 2858 2859 if (types.unboxedType(tree.expr.type).isPrimitive()) { 2860 exactnessCheck = 2861 makeBinary(AND, 2862 nullCheck, 2863 getExactnessCheck(tree, boxIfNeeded(make.Ident(dollar_s), types.unboxedType(tree.expr.type)))); 2864 } else { 2865 exactnessCheck = 2866 makeBinary(AND, 2867 nullCheck, 2868 make.at(tree.pos()) 2869 .TypeTest(make.Ident(dollar_s), make.Type(types.boxedClass(tree.pattern.type).type)) 2870 .setType(syms.booleanType)); 2871 } 2872 } 2873 } else { 2874 throw Assert.error("Non primitive or reference type: " + tree.expr.type); 2875 } 2876 result = (prefixStatement == null ? exactnessCheck : make.LetExpr(List.of(prefixStatement), exactnessCheck)) 2877 .setType(syms.booleanType); 2878 } else { 2879 tree.expr = translate(tree.expr); 2880 tree.pattern = translate(tree.pattern); 2881 result = tree; 2882 } 2883 } 2884 2885 // TypePairs should be in sync with the corresponding record in SwitchBootstraps 2886 record TypePairs(TypeSymbol from, TypeSymbol to) { 2887 public static TypePairs of(Symtab syms, Type from, Type to) { 2888 if (from == syms.byteType || from == syms.shortType || from == syms.charType) { 2889 from = syms.intType; 2890 } 2891 return new TypePairs(from, to); 2892 } 2893 2894 public TypePairs(Type from, Type to) { 2895 this(from.tsym, to.tsym); 2896 } 2897 2898 public static HashMap<TypePairs, String> initialize(Symtab syms) { 2899 HashMap<TypePairs, String> typePairToName = new HashMap<>(); 2900 typePairToName.put(new TypePairs(syms.byteType, syms.charType), "isIntToCharExact"); // redirected 2901 typePairToName.put(new TypePairs(syms.shortType, syms.byteType), "isIntToByteExact"); // redirected 2902 typePairToName.put(new TypePairs(syms.shortType, syms.charType), "isIntToCharExact"); // redirected 2903 typePairToName.put(new TypePairs(syms.charType, syms.byteType), "isIntToByteExact"); // redirected 2904 typePairToName.put(new TypePairs(syms.charType, syms.shortType), "isIntToShortExact"); // redirected 2905 typePairToName.put(new TypePairs(syms.intType, syms.byteType), "isIntToByteExact"); 2906 typePairToName.put(new TypePairs(syms.intType, syms.shortType), "isIntToShortExact"); 2907 typePairToName.put(new TypePairs(syms.intType, syms.charType), "isIntToCharExact"); 2908 typePairToName.put(new TypePairs(syms.intType, syms.floatType), "isIntToFloatExact"); 2909 typePairToName.put(new TypePairs(syms.longType, syms.byteType), "isLongToByteExact"); 2910 typePairToName.put(new TypePairs(syms.longType, syms.shortType), "isLongToShortExact"); 2911 typePairToName.put(new TypePairs(syms.longType, syms.charType), "isLongToCharExact"); 2912 typePairToName.put(new TypePairs(syms.longType, syms.intType), "isLongToIntExact"); 2913 typePairToName.put(new TypePairs(syms.longType, syms.floatType), "isLongToFloatExact"); 2914 typePairToName.put(new TypePairs(syms.longType, syms.doubleType), "isLongToDoubleExact"); 2915 typePairToName.put(new TypePairs(syms.floatType, syms.byteType), "isFloatToByteExact"); 2916 typePairToName.put(new TypePairs(syms.floatType, syms.shortType), "isFloatToShortExact"); 2917 typePairToName.put(new TypePairs(syms.floatType, syms.charType), "isFloatToCharExact"); 2918 typePairToName.put(new TypePairs(syms.floatType, syms.intType), "isFloatToIntExact"); 2919 typePairToName.put(new TypePairs(syms.floatType, syms.longType), "isFloatToLongExact"); 2920 typePairToName.put(new TypePairs(syms.doubleType, syms.byteType), "isDoubleToByteExact"); 2921 typePairToName.put(new TypePairs(syms.doubleType, syms.shortType), "isDoubleToShortExact"); 2922 typePairToName.put(new TypePairs(syms.doubleType, syms.charType), "isDoubleToCharExact"); 2923 typePairToName.put(new TypePairs(syms.doubleType, syms.intType), "isDoubleToIntExact"); 2924 typePairToName.put(new TypePairs(syms.doubleType, syms.longType), "isDoubleToLongExact"); 2925 typePairToName.put(new TypePairs(syms.doubleType, syms.floatType), "isDoubleToFloatExact"); 2926 return typePairToName; 2927 } 2928 } 2929 2930 private JCExpression getExactnessCheck(JCInstanceOf tree, JCExpression argument) { 2931 TypePairs pair = TypePairs.of(syms, types.unboxedTypeOrType(tree.expr.type), tree.pattern.type); 2932 2933 Name exactnessFunction = names.fromString(typePairToName.get(pair)); 2934 2935 // Resolve the exactness method 2936 Symbol ecsym = lookupMethod(tree.pos(), 2937 exactnessFunction, 2938 syms.exactConversionsSupportType, 2939 List.of(pair.from.type)); 2940 2941 // Generate the method call ExactnessChecks.<exactness method>(<argument>); 2942 JCFieldAccess select = make.Select( 2943 make.QualIdent(syms.exactConversionsSupportType.tsym), 2944 exactnessFunction); 2945 select.sym = ecsym; 2946 select.setType(syms.booleanType); 2947 2948 JCExpression exactnessCheck = make.Apply(List.nil(), 2949 select, 2950 List.of(argument)); 2951 exactnessCheck.setType(syms.booleanType); 2952 return exactnessCheck; 2953 } 2954 2955 public void visitNewClass(JCNewClass tree) { 2956 ClassSymbol c = (ClassSymbol)tree.constructor.owner; 2957 2958 // Box arguments, if necessary 2959 boolean isEnum = (tree.constructor.owner.flags() & ENUM) != 0; 2960 List<Type> argTypes = tree.constructor.type.getParameterTypes(); 2961 if (isEnum) argTypes = argTypes.prepend(syms.intType).prepend(syms.stringType); 2962 tree.args = boxArgs(argTypes, tree.args, tree.varargsElement); 2963 tree.varargsElement = null; 2964 2965 // If created class is local, add free variables after 2966 // explicit constructor arguments. 2967 if (c.isDirectlyOrIndirectlyLocal() && !c.isStatic()) { 2968 tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c))); 2969 } 2970 2971 // If an access constructor is used, append null as a last argument. 2972 Symbol constructor = accessConstructor(tree.pos(), tree.constructor); 2973 if (constructor != tree.constructor) { 2974 tree.args = tree.args.append(makeNull()); 2975 tree.constructor = constructor; 2976 } 2977 2978 // If created class has an outer instance, and new is qualified, pass 2979 // qualifier as first argument. If new is not qualified, pass the 2980 // correct outer instance as first argument. 2981 if (c.hasOuterInstance()) { 2982 JCExpression thisArg; 2983 if (tree.encl != null) { 2984 thisArg = attr.makeNullCheck(translate(tree.encl)); 2985 thisArg.type = tree.encl.type; 2986 } else if (c.isDirectlyOrIndirectlyLocal()) { 2987 // local class 2988 thisArg = makeThis(tree.pos(), c.innermostAccessibleEnclosingClass()); 2989 } else { 2990 // nested class 2991 thisArg = makeOwnerThis(tree.pos(), c, false); 2992 } 2993 tree.args = tree.args.prepend(thisArg); 2994 } 2995 tree.encl = null; 2996 2997 // If we have an anonymous class, create its flat version, rather 2998 // than the class or interface following new. 2999 if (tree.def != null) { 3000 translate(tree.def); 3001 3002 tree.clazz = access(make_at(tree.clazz.pos()).Ident(tree.def.sym)); 3003 tree.def = null; 3004 } else { 3005 tree.clazz = access(c, tree.clazz, enclOp, false); 3006 } 3007 result = tree; 3008 } 3009 3010 // Simplify conditionals with known constant controlling expressions. 3011 // This allows us to avoid generating supporting declarations for 3012 // the dead code, which will not be eliminated during code generation. 3013 // Note that Flow.isFalse and Flow.isTrue only return true 3014 // for constant expressions in the sense of JLS 15.27, which 3015 // are guaranteed to have no side-effects. More aggressive 3016 // constant propagation would require that we take care to 3017 // preserve possible side-effects in the condition expression. 3018 3019 // One common case is equality expressions involving a constant and null. 3020 // Since null is not a constant expression (because null cannot be 3021 // represented in the constant pool), equality checks involving null are 3022 // not captured by Flow.isTrue/isFalse. 3023 // Equality checks involving a constant and null, e.g. 3024 // "" == null 3025 // are safe to simplify as no side-effects can occur. 3026 3027 private boolean isTrue(JCTree exp) { 3028 if (exp.type.isTrue()) 3029 return true; 3030 Boolean b = expValue(exp); 3031 return b == null ? false : b; 3032 } 3033 private boolean isFalse(JCTree exp) { 3034 if (exp.type.isFalse()) 3035 return true; 3036 Boolean b = expValue(exp); 3037 return b == null ? false : !b; 3038 } 3039 /* look for (in)equality relations involving null. 3040 * return true - if expression is always true 3041 * false - if expression is always false 3042 * null - if expression cannot be eliminated 3043 */ 3044 private Boolean expValue(JCTree exp) { 3045 while (exp.hasTag(PARENS)) 3046 exp = ((JCParens)exp).expr; 3047 3048 boolean eq; 3049 switch (exp.getTag()) { 3050 case EQ: eq = true; break; 3051 case NE: eq = false; break; 3052 default: 3053 return null; 3054 } 3055 3056 // we have a JCBinary(EQ|NE) 3057 // check if we have two literals (constants or null) 3058 JCBinary b = (JCBinary)exp; 3059 if (b.lhs.type.hasTag(BOT)) return expValueIsNull(eq, b.rhs); 3060 if (b.rhs.type.hasTag(BOT)) return expValueIsNull(eq, b.lhs); 3061 return null; 3062 } 3063 private Boolean expValueIsNull(boolean eq, JCTree t) { 3064 if (t.type.hasTag(BOT)) return Boolean.valueOf(eq); 3065 if (t.hasTag(LITERAL)) return Boolean.valueOf(!eq); 3066 return null; 3067 } 3068 3069 /** Visitor method for conditional expressions. 3070 */ 3071 @Override 3072 public void visitConditional(JCConditional tree) { 3073 JCTree cond = tree.cond = translate(tree.cond, syms.booleanType); 3074 if (isTrue(cond) && noClassDefIn(tree.falsepart)) { 3075 result = convert(translate(tree.truepart, tree.type), tree.type); 3076 addPrunedInfo(cond); 3077 } else if (isFalse(cond) && noClassDefIn(tree.truepart)) { 3078 result = convert(translate(tree.falsepart, tree.type), tree.type); 3079 addPrunedInfo(cond); 3080 } else { 3081 // Condition is not a compile-time constant. 3082 tree.truepart = translate(tree.truepart, tree.type); 3083 tree.falsepart = translate(tree.falsepart, tree.type); 3084 result = tree; 3085 } 3086 } 3087 //where 3088 private JCExpression convert(JCExpression tree, Type pt) { 3089 if (tree.type == pt || tree.type.hasTag(BOT)) 3090 return tree; 3091 JCExpression result = make_at(tree.pos()).TypeCast(make.Type(pt), tree); 3092 result.type = (tree.type.constValue() != null) ? cfolder.coerce(tree.type, pt) 3093 : pt; 3094 return result; 3095 } 3096 3097 /** Visitor method for if statements. 3098 */ 3099 public void visitIf(JCIf tree) { 3100 JCTree cond = tree.cond = translate(tree.cond, syms.booleanType); 3101 if (isTrue(cond) && noClassDefIn(tree.elsepart)) { 3102 result = translate(tree.thenpart); 3103 addPrunedInfo(cond); 3104 } else if (isFalse(cond) && noClassDefIn(tree.thenpart)) { 3105 if (tree.elsepart != null) { 3106 result = translate(tree.elsepart); 3107 } else { 3108 result = make.Skip(); 3109 } 3110 addPrunedInfo(cond); 3111 } else { 3112 // Condition is not a compile-time constant. 3113 tree.thenpart = translate(tree.thenpart); 3114 tree.elsepart = translate(tree.elsepart); 3115 result = tree; 3116 } 3117 } 3118 3119 /** Visitor method for assert statements. Translate them away. 3120 */ 3121 public void visitAssert(JCAssert tree) { 3122 tree.cond = translate(tree.cond, syms.booleanType); 3123 if (!tree.cond.type.isTrue()) { 3124 JCExpression cond = assertFlagTest(tree.pos()); 3125 List<JCExpression> exnArgs = (tree.detail == null) ? 3126 List.nil() : List.of(translate(tree.detail)); 3127 if (!tree.cond.type.isFalse()) { 3128 cond = makeBinary 3129 (AND, 3130 cond, 3131 makeUnary(NOT, tree.cond)); 3132 } 3133 result = 3134 make.If(cond, 3135 make_at(tree). 3136 Throw(makeNewClass(syms.assertionErrorType, exnArgs)), 3137 null); 3138 } else { 3139 result = make.Skip(); 3140 } 3141 } 3142 3143 public void visitApply(JCMethodInvocation tree) { 3144 Symbol meth = TreeInfo.symbol(tree.meth); 3145 List<Type> argtypes = meth.type.getParameterTypes(); 3146 if (meth.name == names.init && meth.owner == syms.enumSym) 3147 argtypes = argtypes.tail.tail; 3148 tree.args = boxArgs(argtypes, tree.args, tree.varargsElement); 3149 tree.varargsElement = null; 3150 Name methName = TreeInfo.name(tree.meth); 3151 if (meth.name==names.init) { 3152 // We are seeing a this(...) or super(...) constructor call. 3153 // If an access constructor is used, append null as a last argument. 3154 Symbol constructor = accessConstructor(tree.pos(), meth); 3155 if (constructor != meth) { 3156 tree.args = tree.args.append(makeNull()); 3157 TreeInfo.setSymbol(tree.meth, constructor); 3158 } 3159 3160 // If we are calling a constructor of a local class, add 3161 // free variables after explicit constructor arguments. 3162 ClassSymbol c = (ClassSymbol)constructor.owner; 3163 if (c.isDirectlyOrIndirectlyLocal() && !c.isStatic()) { 3164 tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c))); 3165 } 3166 3167 // If we are calling a constructor of an enum class, pass 3168 // along the name and ordinal arguments 3169 if ((c.flags_field&ENUM) != 0 || c.getQualifiedName() == names.java_lang_Enum) { 3170 List<JCVariableDecl> params = currentMethodDef.params; 3171 if (currentMethodSym.owner.hasOuterInstance()) 3172 params = params.tail; // drop this$n 3173 tree.args = tree.args 3174 .prepend(make_at(tree.pos()).Ident(params.tail.head.sym)) // ordinal 3175 .prepend(make.Ident(params.head.sym)); // name 3176 } 3177 3178 // If we are calling a constructor of a class with an outer 3179 // instance, and the call 3180 // is qualified, pass qualifier as first argument in front of 3181 // the explicit constructor arguments. If the call 3182 // is not qualified, pass the correct outer instance as 3183 // first argument. If we are a static class, there is no 3184 // such outer instance, so generate an error. 3185 if (c.hasOuterInstance()) { 3186 JCExpression thisArg; 3187 if (tree.meth.hasTag(SELECT)) { 3188 thisArg = attr. 3189 makeNullCheck(translate(((JCFieldAccess) tree.meth).selected)); 3190 tree.meth = make.Ident(constructor); 3191 ((JCIdent) tree.meth).name = methName; 3192 } else if (c.isDirectlyOrIndirectlyLocal() || methName == names._this){ 3193 // local class or this() call 3194 thisArg = makeThis(tree.meth.pos(), c.innermostAccessibleEnclosingClass()); 3195 } else if (currentClass.isStatic()) { 3196 // super() call from static nested class - invalid 3197 log.error(tree.pos(), 3198 Errors.NoEnclInstanceOfTypeInScope(c.type.getEnclosingType().tsym)); 3199 thisArg = make.Literal(BOT, null).setType(syms.botType); 3200 } else { 3201 // super() call of nested class - never pick 'this' 3202 thisArg = makeOwnerThisN(tree.meth.pos(), c, false); 3203 } 3204 tree.args = tree.args.prepend(thisArg); 3205 } 3206 } else { 3207 // We are seeing a normal method invocation; translate this as usual. 3208 tree.meth = translate(tree.meth); 3209 3210 // If the translated method itself is an Apply tree, we are 3211 // seeing an access method invocation. In this case, append 3212 // the method arguments to the arguments of the access method. 3213 if (tree.meth.hasTag(APPLY)) { 3214 JCMethodInvocation app = (JCMethodInvocation)tree.meth; 3215 app.args = tree.args.prependList(app.args); 3216 result = app; 3217 return; 3218 } 3219 } 3220 if (tree.args.stream().anyMatch(c -> c == null)) { 3221 throw new AssertionError("Whooops before: " + tree); 3222 } 3223 result = tree; 3224 } 3225 3226 List<JCExpression> boxArgs(List<Type> parameters, List<JCExpression> _args, Type varargsElement) { 3227 List<JCExpression> args = _args; 3228 if (parameters.isEmpty()) return args; 3229 boolean anyChanges = false; 3230 ListBuffer<JCExpression> result = new ListBuffer<>(); 3231 while (parameters.tail.nonEmpty()) { 3232 JCExpression arg = translate(args.head, parameters.head); 3233 anyChanges |= (arg != args.head); 3234 result.append(arg); 3235 args = args.tail; 3236 parameters = parameters.tail; 3237 } 3238 Type parameter = parameters.head; 3239 if (varargsElement != null) { 3240 anyChanges = true; 3241 ListBuffer<JCExpression> elems = new ListBuffer<>(); 3242 while (args.nonEmpty()) { 3243 JCExpression arg = translate(args.head, varargsElement); 3244 elems.append(arg); 3245 args = args.tail; 3246 } 3247 JCNewArray boxedArgs = make.NewArray(make.Type(varargsElement), 3248 List.nil(), 3249 elems.toList()); 3250 boxedArgs.type = new ArrayType(varargsElement, syms.arrayClass); 3251 result.append(boxedArgs); 3252 } else { 3253 if (args.length() != 1) throw new AssertionError(args); 3254 JCExpression arg = translate(args.head, parameter); 3255 anyChanges |= (arg != args.head); 3256 result.append(arg); 3257 if (!anyChanges) return _args; 3258 } 3259 return result.toList(); 3260 } 3261 3262 /** Expand a boxing or unboxing conversion if needed. */ 3263 @SuppressWarnings("unchecked") // XXX unchecked 3264 <T extends JCExpression> T boxIfNeeded(T tree, Type type) { 3265 Assert.check(!type.hasTag(VOID)); 3266 if (type.hasTag(NONE)) 3267 return tree; 3268 boolean havePrimitive = tree.type.isPrimitive(); 3269 if (havePrimitive == type.isPrimitive()) 3270 return tree; 3271 if (havePrimitive) { 3272 Type unboxedTarget = types.unboxedType(type); 3273 if (!unboxedTarget.hasTag(NONE)) { 3274 if (!types.isSubtype(tree.type, unboxedTarget)) //e.g. Character c = 89; 3275 tree.type = unboxedTarget.constType(tree.type.constValue()); 3276 return (T)boxPrimitive(tree, types.erasure(type)); 3277 } else { 3278 tree = (T)boxPrimitive(tree); 3279 } 3280 } else { 3281 tree = (T)unbox(tree, type); 3282 } 3283 return tree; 3284 } 3285 3286 /** Box up a single primitive expression. */ 3287 JCExpression boxPrimitive(JCExpression tree) { 3288 return boxPrimitive(tree, types.boxedClass(tree.type).type); 3289 } 3290 3291 /** Box up a single primitive expression. */ 3292 JCExpression boxPrimitive(JCExpression tree, Type box) { 3293 make_at(tree.pos()); 3294 Symbol valueOfSym = lookupMethod(tree.pos(), 3295 names.valueOf, 3296 box, 3297 List.<Type>nil() 3298 .prepend(tree.type)); 3299 return make.App(make.QualIdent(valueOfSym), List.of(tree)); 3300 } 3301 3302 /** Unbox an object to a primitive value. */ 3303 JCExpression unbox(JCExpression tree, Type primitive) { 3304 Type unboxedType = types.unboxedType(tree.type); 3305 if (unboxedType.hasTag(NONE)) { 3306 unboxedType = primitive; 3307 if (!unboxedType.isPrimitive()) 3308 throw new AssertionError(unboxedType); 3309 make_at(tree.pos()); 3310 tree = make.TypeCast(types.boxedClass(unboxedType).type, tree); 3311 } else { 3312 // There must be a conversion from unboxedType to primitive. 3313 if (!types.isSubtype(unboxedType, primitive)) 3314 throw new AssertionError(tree); 3315 } 3316 make_at(tree.pos()); 3317 Symbol valueSym = lookupMethod(tree.pos(), 3318 unboxedType.tsym.name.append(names.Value), // x.intValue() 3319 tree.type, 3320 List.nil()); 3321 return make.App(make.Select(tree, valueSym)); 3322 } 3323 3324 /** Visitor method for parenthesized expressions. 3325 * If the subexpression has changed, omit the parens. 3326 */ 3327 public void visitParens(JCParens tree) { 3328 JCTree expr = translate(tree.expr); 3329 result = ((expr == tree.expr) ? tree : expr); 3330 } 3331 3332 public void visitIndexed(JCArrayAccess tree) { 3333 tree.indexed = translate(tree.indexed); 3334 tree.index = translate(tree.index, syms.intType); 3335 result = tree; 3336 } 3337 3338 public void visitAssign(JCAssign tree) { 3339 tree.lhs = translate(tree.lhs, tree); 3340 tree.rhs = translate(tree.rhs, tree.lhs.type); 3341 3342 // If translated left hand side is an Apply, we are 3343 // seeing an access method invocation. In this case, append 3344 // right hand side as last argument of the access method. 3345 if (tree.lhs.hasTag(APPLY)) { 3346 JCMethodInvocation app = (JCMethodInvocation)tree.lhs; 3347 app.args = List.of(tree.rhs).prependList(app.args); 3348 result = app; 3349 } else { 3350 result = tree; 3351 } 3352 } 3353 3354 public void visitAssignop(final JCAssignOp tree) { 3355 final boolean boxingReq = !tree.lhs.type.isPrimitive() && 3356 tree.operator.type.getReturnType().isPrimitive(); 3357 3358 AssignopDependencyScanner depScanner = new AssignopDependencyScanner(tree); 3359 depScanner.scan(tree.rhs); 3360 3361 if (boxingReq || depScanner.dependencyFound) { 3362 // boxing required; need to rewrite as x = (unbox typeof x)(x op y); 3363 // or if x == (typeof x)z then z = (unbox typeof x)((typeof x)z op y) 3364 // (but without recomputing x) 3365 JCTree newTree = abstractLval(tree.lhs, lhs -> { 3366 Tag newTag = tree.getTag().noAssignOp(); 3367 // Erasure (TransTypes) can change the type of 3368 // tree.lhs. However, we can still get the 3369 // unerased type of tree.lhs as it is stored 3370 // in tree.type in Attr. 3371 OperatorSymbol newOperator = operators.resolveBinary(tree, 3372 newTag, 3373 tree.type, 3374 tree.rhs.type); 3375 //Need to use the "lhs" at two places, once on the future left hand side 3376 //and once in the future binary operator. But further processing may change 3377 //the components of the tree in place (see visitSelect for e.g. <Class>.super.<ident>), 3378 //so cloning the tree to avoid interference between the uses: 3379 JCExpression expr = (JCExpression) lhs.clone(); 3380 if (expr.type != tree.type) 3381 expr = make.TypeCast(tree.type, expr); 3382 JCBinary opResult = make.Binary(newTag, expr, tree.rhs); 3383 opResult.operator = newOperator; 3384 opResult.type = newOperator.type.getReturnType(); 3385 JCExpression newRhs = boxingReq ? 3386 make.TypeCast(types.unboxedType(tree.type), opResult) : 3387 opResult; 3388 return make.Assign(lhs, newRhs).setType(tree.type); 3389 }); 3390 result = translate(newTree); 3391 return; 3392 } 3393 tree.lhs = translate(tree.lhs, tree); 3394 tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head); 3395 3396 // If translated left hand side is an Apply, we are 3397 // seeing an access method invocation. In this case, append 3398 // right hand side as last argument of the access method. 3399 if (tree.lhs.hasTag(APPLY)) { 3400 JCMethodInvocation app = (JCMethodInvocation)tree.lhs; 3401 // if operation is a += on strings, 3402 // make sure to convert argument to string 3403 JCExpression rhs = tree.operator.opcode == string_add 3404 ? makeString(tree.rhs) 3405 : tree.rhs; 3406 app.args = List.of(rhs).prependList(app.args); 3407 result = app; 3408 } else { 3409 result = tree; 3410 } 3411 } 3412 3413 class AssignopDependencyScanner extends TreeScanner { 3414 3415 Symbol sym; 3416 boolean dependencyFound = false; 3417 3418 AssignopDependencyScanner(JCAssignOp tree) { 3419 this.sym = TreeInfo.symbol(tree.lhs); 3420 } 3421 3422 @Override 3423 public void scan(JCTree tree) { 3424 if (tree != null && sym != null) { 3425 tree.accept(this); 3426 } 3427 } 3428 3429 @Override 3430 public void visitAssignop(JCAssignOp tree) { 3431 if (TreeInfo.symbol(tree.lhs) == sym) { 3432 dependencyFound = true; 3433 return; 3434 } 3435 super.visitAssignop(tree); 3436 } 3437 3438 @Override 3439 public void visitUnary(JCUnary tree) { 3440 if (TreeInfo.symbol(tree.arg) == sym) { 3441 dependencyFound = true; 3442 return; 3443 } 3444 super.visitUnary(tree); 3445 } 3446 } 3447 3448 /** Lower a tree of the form e++ or e-- where e is an object type */ 3449 JCExpression lowerBoxedPostop(final JCUnary tree) { 3450 // translate to tmp1=lval(e); tmp2=tmp1; tmp1 OP 1; tmp2 3451 // or 3452 // translate to tmp1=lval(e); tmp2=tmp1; (typeof tree)tmp1 OP 1; tmp2 3453 // where OP is += or -= 3454 final boolean cast = TreeInfo.skipParens(tree.arg).hasTag(TYPECAST); 3455 return abstractLval(tree.arg, tmp1 -> abstractRval(tmp1, tree.arg.type, tmp2 -> { 3456 Tag opcode = (tree.hasTag(POSTINC)) 3457 ? PLUS_ASG : MINUS_ASG; 3458 //"tmp1" and "tmp2" may refer to the same instance 3459 //(for e.g. <Class>.super.<ident>). But further processing may 3460 //change the components of the tree in place (see visitSelect), 3461 //so cloning the tree to avoid interference between the two uses: 3462 JCExpression lhs = (JCExpression)tmp1.clone(); 3463 lhs = cast 3464 ? make.TypeCast(tree.arg.type, lhs) 3465 : lhs; 3466 JCExpression update = makeAssignop(opcode, 3467 lhs, 3468 make.Literal(1)); 3469 return makeComma(update, tmp2); 3470 })); 3471 } 3472 3473 public void visitUnary(JCUnary tree) { 3474 boolean isUpdateOperator = tree.getTag().isIncOrDecUnaryOp(); 3475 if (isUpdateOperator && !tree.arg.type.isPrimitive()) { 3476 switch(tree.getTag()) { 3477 case PREINC: // ++ e 3478 // translate to e += 1 3479 case PREDEC: // -- e 3480 // translate to e -= 1 3481 { 3482 JCTree.Tag opcode = (tree.hasTag(PREINC)) 3483 ? PLUS_ASG : MINUS_ASG; 3484 JCAssignOp newTree = makeAssignop(opcode, 3485 tree.arg, 3486 make.Literal(1)); 3487 result = translate(newTree, tree.type); 3488 return; 3489 } 3490 case POSTINC: // e ++ 3491 case POSTDEC: // e -- 3492 { 3493 result = translate(lowerBoxedPostop(tree), tree.type); 3494 return; 3495 } 3496 } 3497 throw new AssertionError(tree); 3498 } 3499 3500 tree.arg = boxIfNeeded(translate(tree.arg, tree), tree.type); 3501 3502 if (tree.hasTag(NOT) && tree.arg.type.constValue() != null) { 3503 tree.type = cfolder.fold1(bool_not, tree.arg.type); 3504 } 3505 3506 // If translated left hand side is an Apply, we are 3507 // seeing an access method invocation. In this case, return 3508 // that access method invocation as result. 3509 if (isUpdateOperator && tree.arg.hasTag(APPLY)) { 3510 result = tree.arg; 3511 } else { 3512 result = tree; 3513 } 3514 } 3515 3516 public void visitBinary(JCBinary tree) { 3517 List<Type> formals = tree.operator.type.getParameterTypes(); 3518 JCTree lhs = tree.lhs = translate(tree.lhs, formals.head); 3519 switch (tree.getTag()) { 3520 case OR: 3521 if (isTrue(lhs)) { 3522 result = lhs; 3523 return; 3524 } 3525 if (isFalse(lhs)) { 3526 result = translate(tree.rhs, formals.tail.head); 3527 return; 3528 } 3529 break; 3530 case AND: 3531 if (isFalse(lhs)) { 3532 result = lhs; 3533 return; 3534 } 3535 if (isTrue(lhs)) { 3536 result = translate(tree.rhs, formals.tail.head); 3537 return; 3538 } 3539 break; 3540 } 3541 tree.rhs = translate(tree.rhs, formals.tail.head); 3542 result = tree; 3543 } 3544 3545 public void visitIdent(JCIdent tree) { 3546 result = access(tree.sym, tree, enclOp, false); 3547 } 3548 3549 /** Translate away the foreach loop. */ 3550 public void visitForeachLoop(JCEnhancedForLoop tree) { 3551 if (types.elemtype(tree.expr.type) == null) 3552 visitIterableForeachLoop(tree); 3553 else 3554 visitArrayForeachLoop(tree); 3555 } 3556 // where 3557 /** 3558 * A statement of the form 3559 * 3560 * <pre> 3561 * for ( T v : arrayexpr ) stmt; 3562 * </pre> 3563 * 3564 * (where arrayexpr is of an array type) gets translated to 3565 * 3566 * <pre>{@code 3567 * for ( { arraytype #arr = arrayexpr; 3568 * int #len = array.length; 3569 * int #i = 0; }; 3570 * #i < #len; i$++ ) { 3571 * T v = (T) arr$[#i]; 3572 * stmt; 3573 * } 3574 * }</pre> 3575 * 3576 * where #arr, #len, and #i are freshly named synthetic local variables. 3577 */ 3578 private void visitArrayForeachLoop(JCEnhancedForLoop tree) { 3579 make_at(tree.expr.pos()); 3580 VarSymbol arraycache = new VarSymbol(SYNTHETIC, 3581 names.fromString("arr" + target.syntheticNameChar()), 3582 tree.expr.type, 3583 currentMethodSym); 3584 JCStatement arraycachedef = make.VarDef(arraycache, tree.expr); 3585 VarSymbol lencache = new VarSymbol(SYNTHETIC, 3586 names.fromString("len" + target.syntheticNameChar()), 3587 syms.intType, 3588 currentMethodSym); 3589 JCStatement lencachedef = make. 3590 VarDef(lencache, make.Select(make.Ident(arraycache), syms.lengthVar)); 3591 VarSymbol index = new VarSymbol(SYNTHETIC, 3592 names.fromString("i" + target.syntheticNameChar()), 3593 syms.intType, 3594 currentMethodSym); 3595 3596 JCVariableDecl indexdef = make.VarDef(index, make.Literal(INT, 0)); 3597 indexdef.init.type = indexdef.type = syms.intType.constType(0); 3598 3599 List<JCStatement> loopinit = List.of(arraycachedef, lencachedef, indexdef); 3600 JCBinary cond = makeBinary(LT, make.Ident(index), make.Ident(lencache)); 3601 3602 JCExpressionStatement step = make.Exec(makeUnary(PREINC, make.Ident(index))); 3603 3604 Type elemtype = types.elemtype(tree.expr.type); 3605 JCExpression loopvarinit = make.Indexed(make.Ident(arraycache), 3606 make.Ident(index)).setType(elemtype); 3607 loopvarinit = transTypes.coerce(attrEnv, loopvarinit, tree.var.type); 3608 JCVariableDecl loopvardef = (JCVariableDecl)make.VarDef(tree.var.mods, 3609 tree.var.name, 3610 tree.var.vartype, 3611 loopvarinit).setType(tree.var.type); 3612 loopvardef.sym = tree.var.sym; 3613 JCBlock body = make. 3614 Block(0, List.of(loopvardef, tree.body)); 3615 3616 result = translate(make. 3617 ForLoop(loopinit, 3618 cond, 3619 List.of(step), 3620 body)); 3621 patchTargets(body, tree, result); 3622 } 3623 /** Patch up break and continue targets. */ 3624 private void patchTargets(JCTree body, final JCTree src, final JCTree dest) { 3625 class Patcher extends TreeScanner { 3626 public void visitBreak(JCBreak tree) { 3627 if (tree.target == src) 3628 tree.target = dest; 3629 } 3630 public void visitYield(JCYield tree) { 3631 if (tree.target == src) 3632 tree.target = dest; 3633 scan(tree.value); 3634 } 3635 public void visitContinue(JCContinue tree) { 3636 if (tree.target == src) 3637 tree.target = dest; 3638 } 3639 public void visitClassDef(JCClassDecl tree) {} 3640 } 3641 new Patcher().scan(body); 3642 } 3643 /** 3644 * A statement of the form 3645 * 3646 * <pre> 3647 * for ( T v : coll ) stmt ; 3648 * </pre> 3649 * 3650 * (where coll implements {@code Iterable<? extends T>}) gets translated to 3651 * 3652 * <pre>{@code 3653 * for ( Iterator<? extends T> #i = coll.iterator(); #i.hasNext(); ) { 3654 * T v = (T) #i.next(); 3655 * stmt; 3656 * } 3657 * }</pre> 3658 * 3659 * where #i is a freshly named synthetic local variable. 3660 */ 3661 private void visitIterableForeachLoop(JCEnhancedForLoop tree) { 3662 make_at(tree.expr.pos()); 3663 Type iteratorTarget = syms.objectType; 3664 Type iterableType = types.asSuper(types.cvarUpperBound(tree.expr.type), 3665 syms.iterableType.tsym); 3666 if (iterableType.getTypeArguments().nonEmpty()) 3667 iteratorTarget = types.erasure(iterableType.getTypeArguments().head); 3668 tree.expr.type = types.erasure(types.skipTypeVars(tree.expr.type, false)); 3669 tree.expr = transTypes.coerce(attrEnv, tree.expr, types.erasure(iterableType)); 3670 Symbol iterator = lookupMethod(tree.expr.pos(), 3671 names.iterator, 3672 tree.expr.type, 3673 List.nil()); 3674 Assert.check(types.isSameType(types.erasure(types.asSuper(iterator.type.getReturnType(), syms.iteratorType.tsym)), types.erasure(syms.iteratorType))); 3675 VarSymbol itvar = new VarSymbol(SYNTHETIC, names.fromString("i" + target.syntheticNameChar()), 3676 types.erasure(syms.iteratorType), 3677 currentMethodSym); 3678 3679 JCStatement init = make. 3680 VarDef(itvar, make.App(make.Select(tree.expr, iterator) 3681 .setType(types.erasure(iterator.type)))); 3682 3683 Symbol hasNext = lookupMethod(tree.expr.pos(), 3684 names.hasNext, 3685 itvar.type, 3686 List.nil()); 3687 JCMethodInvocation cond = make.App(make.Select(make.Ident(itvar), hasNext)); 3688 Symbol next = lookupMethod(tree.expr.pos(), 3689 names.next, 3690 itvar.type, 3691 List.nil()); 3692 JCExpression vardefinit = make.App(make.Select(make.Ident(itvar), next)); 3693 if (tree.var.type.isPrimitive()) 3694 vardefinit = make.TypeCast(types.cvarUpperBound(iteratorTarget), vardefinit); 3695 else 3696 vardefinit = transTypes.coerce(attrEnv, vardefinit, tree.var.type); 3697 JCVariableDecl indexDef = (JCVariableDecl)make.VarDef(tree.var.mods, 3698 tree.var.name, 3699 tree.var.vartype, 3700 vardefinit, 3701 tree.var.declKind).setType(tree.var.type); 3702 indexDef.sym = tree.var.sym; 3703 JCBlock body = make.Block(0, List.of(indexDef, tree.body)); 3704 body.bracePos = TreeInfo.endPos(tree.body); 3705 result = translate(make. 3706 ForLoop(List.of(init), 3707 cond, 3708 List.nil(), 3709 body)); 3710 patchTargets(body, tree, result); 3711 } 3712 3713 public void visitVarDef(JCVariableDecl tree) { 3714 MethodSymbol oldMethodSym = currentMethodSym; 3715 int prevVariableIndex = variableIndex; 3716 tree.mods = translate(tree.mods); 3717 tree.vartype = translate(tree.vartype); 3718 if (currentMethodSym == null) { 3719 // A class or instance field initializer. 3720 currentMethodSym = 3721 new MethodSymbol((tree.mods.flags&STATIC) | BLOCK, 3722 names.empty, null, 3723 currentClass); 3724 } 3725 try { 3726 if (tree.init != null) tree.init = translate(tree.init, tree.type); 3727 result = tree; 3728 } finally { 3729 currentMethodSym = oldMethodSym; 3730 variableIndex = prevVariableIndex; 3731 } 3732 } 3733 3734 public void visitBlock(JCBlock tree) { 3735 MethodSymbol oldMethodSym = currentMethodSym; 3736 if (currentMethodSym == null) { 3737 // Block is a static or instance initializer. 3738 currentMethodSym = 3739 new MethodSymbol(tree.flags | BLOCK, 3740 names.empty, null, 3741 currentClass); 3742 } 3743 int prevVariableIndex = variableIndex; 3744 try { 3745 variableIndex = 0; 3746 super.visitBlock(tree); 3747 } finally { 3748 currentMethodSym = oldMethodSym; 3749 variableIndex = prevVariableIndex; 3750 } 3751 } 3752 3753 public void visitDoLoop(JCDoWhileLoop tree) { 3754 tree.body = translate(tree.body); 3755 tree.cond = translate(tree.cond, syms.booleanType); 3756 result = tree; 3757 } 3758 3759 public void visitWhileLoop(JCWhileLoop tree) { 3760 tree.cond = translate(tree.cond, syms.booleanType); 3761 tree.body = translate(tree.body); 3762 result = tree; 3763 } 3764 3765 public void visitForLoop(JCForLoop tree) { 3766 tree.init = translate(tree.init); 3767 if (tree.cond != null) 3768 tree.cond = translate(tree.cond, syms.booleanType); 3769 tree.step = translate(tree.step); 3770 tree.body = translate(tree.body); 3771 result = tree; 3772 } 3773 3774 public void visitReturn(JCReturn tree) { 3775 if (tree.expr != null) 3776 tree.expr = translate(tree.expr, 3777 currentRestype); 3778 result = tree; 3779 } 3780 3781 @Override 3782 public void visitLambda(JCLambda tree) { 3783 Type prevRestype = currentRestype; 3784 try { 3785 currentRestype = types.erasure(tree.getDescriptorType(types)).getReturnType(); 3786 // represent void results as NO_TYPE, to avoid unnecessary boxing in boxIfNeeded 3787 if (currentRestype.hasTag(VOID)) 3788 currentRestype = Type.noType; 3789 tree.body = tree.getBodyKind() == BodyKind.EXPRESSION ? 3790 translate((JCExpression) tree.body, currentRestype) : 3791 translate(tree.body); 3792 } finally { 3793 currentRestype = prevRestype; 3794 } 3795 result = tree; 3796 } 3797 3798 public void visitSwitch(JCSwitch tree) { 3799 List<JCCase> cases = tree.patternSwitch ? addDefaultIfNeeded(tree.patternSwitch, 3800 tree.wasEnumSelector, 3801 tree.cases) 3802 : tree.cases; 3803 handleSwitch(tree, tree.selector, cases); 3804 } 3805 3806 @Override 3807 public void visitSwitchExpression(JCSwitchExpression tree) { 3808 List<JCCase> cases = addDefaultIfNeeded(tree.patternSwitch, tree.wasEnumSelector, tree.cases); 3809 handleSwitch(tree, tree.selector, cases); 3810 } 3811 3812 private List<JCCase> addDefaultIfNeeded(boolean patternSwitch, boolean wasEnumSelector, 3813 List<JCCase> cases) { 3814 if (cases.stream().flatMap(c -> c.labels.stream()).noneMatch(p -> p.hasTag(Tag.DEFAULTCASELABEL))) { 3815 boolean matchException = useMatchException; 3816 matchException |= patternSwitch && !wasEnumSelector; 3817 Type exception = matchException ? syms.matchExceptionType 3818 : syms.incompatibleClassChangeErrorType; 3819 List<JCExpression> params = matchException ? List.of(makeNull(), makeNull()) 3820 : List.nil(); 3821 JCThrow thr = make.Throw(makeNewClass(exception, params)); 3822 JCCase c = make.Case(JCCase.STATEMENT, List.of(make.DefaultCaseLabel()), null, List.of(thr), null); 3823 cases = cases.prepend(c); 3824 } 3825 3826 return cases; 3827 } 3828 3829 private void handleSwitch(JCTree tree, JCExpression selector, List<JCCase> cases) { 3830 //expand multiple label cases: 3831 ListBuffer<JCCase> convertedCases = new ListBuffer<>(); 3832 3833 for (JCCase c : cases) { 3834 switch (c.labels.size()) { 3835 case 0: //default 3836 case 1: //single label 3837 convertedCases.append(c); 3838 break; 3839 default: //multiple labels, expand: 3840 //case C1, C2, C3: ... 3841 //=> 3842 //case C1: 3843 //case C2: 3844 //case C3: ... 3845 List<JCCaseLabel> patterns = c.labels; 3846 while (patterns.tail.nonEmpty()) { 3847 convertedCases.append(make_at(c.pos()).Case(JCCase.STATEMENT, 3848 List.of(patterns.head), 3849 null, 3850 List.nil(), 3851 null)); 3852 patterns = patterns.tail; 3853 } 3854 c.labels = patterns; 3855 convertedCases.append(c); 3856 break; 3857 } 3858 } 3859 3860 for (JCCase c : convertedCases) { 3861 if (c.caseKind == JCCase.RULE && c.completesNormally) { 3862 JCBreak b = make.at(TreeInfo.endPos(c.stats.last())).Break(null); 3863 b.target = tree; 3864 c.stats = c.stats.append(b); 3865 } 3866 } 3867 3868 cases = convertedCases.toList(); 3869 3870 Type selsuper = types.supertype(selector.type); 3871 boolean enumSwitch = selsuper != null && 3872 (selector.type.tsym.flags() & ENUM) != 0; 3873 boolean stringSwitch = selsuper != null && 3874 types.isSameType(selector.type, syms.stringType); 3875 boolean boxedSwitch = !enumSwitch && !stringSwitch && !selector.type.isPrimitive(); 3876 selector = translate(selector, selector.type); 3877 cases = translateCases(cases); 3878 if (tree.hasTag(SWITCH)) { 3879 ((JCSwitch) tree).selector = selector; 3880 ((JCSwitch) tree).cases = cases; 3881 } else if (tree.hasTag(SWITCH_EXPRESSION)) { 3882 ((JCSwitchExpression) tree).selector = selector; 3883 ((JCSwitchExpression) tree).cases = cases; 3884 } else { 3885 Assert.error(); 3886 } 3887 if (enumSwitch) { 3888 result = visitEnumSwitch(tree, selector, cases); 3889 } else if (stringSwitch) { 3890 result = visitStringSwitch(tree, selector, cases); 3891 } else if (boxedSwitch) { 3892 //An switch over boxed primitive. Pattern matching switches are already translated 3893 //by TransPatterns, so all non-primitive types are only boxed primitives: 3894 result = visitBoxedPrimitiveSwitch(tree, selector, cases); 3895 } else { 3896 result = tree; 3897 } 3898 } 3899 3900 public JCTree visitEnumSwitch(JCTree tree, JCExpression selector, List<JCCase> cases) { 3901 TypeSymbol enumSym = selector.type.tsym; 3902 EnumMapping map = mapForEnum(tree.pos(), enumSym); 3903 make_at(tree.pos()); 3904 Symbol ordinalMethod = lookupMethod(tree.pos(), 3905 names.ordinal, 3906 selector.type, 3907 List.nil()); 3908 JCExpression newSelector; 3909 3910 if (cases.stream().anyMatch(c -> TreeInfo.isNullCaseLabel(c.labels.head))) { 3911 //for enum switches with case null, do: 3912 //switch ($selector != null ? $mapVar[$selector.ordinal()] : -1) {...} 3913 //replacing case null with case -1: 3914 VarSymbol dollar_s = new VarSymbol(FINAL|SYNTHETIC, 3915 names.fromString("s" + variableIndex++ + this.target.syntheticNameChar()), 3916 selector.type, 3917 currentMethodSym); 3918 JCStatement var = make.at(tree.pos()).VarDef(dollar_s, selector).setType(dollar_s.type); 3919 newSelector = map.switchValue( 3920 make.App(make.Select(make.Ident(dollar_s), 3921 ordinalMethod))); 3922 newSelector = 3923 make.LetExpr(List.of(var), 3924 make.Conditional(makeBinary(NE, make.Ident(dollar_s), makeNull()), 3925 newSelector, 3926 makeLit(syms.intType, -1)) 3927 .setType(newSelector.type)) 3928 .setType(newSelector.type); 3929 } else { 3930 newSelector = map.switchValue( 3931 make.App(make.Select(selector, 3932 ordinalMethod))); 3933 } 3934 ListBuffer<JCCase> newCases = new ListBuffer<>(); 3935 for (JCCase c : cases) { 3936 if (c.labels.head.hasTag(CONSTANTCASELABEL)) { 3937 JCExpression pat; 3938 if (TreeInfo.isNullCaseLabel(c.labels.head)) { 3939 pat = makeLit(syms.intType, -1); 3940 } else { 3941 VarSymbol label = (VarSymbol)TreeInfo.symbol(((JCConstantCaseLabel) c.labels.head).expr); 3942 pat = map.caseValue(label); 3943 } 3944 newCases.append(make.Case(JCCase.STATEMENT, List.of(make.ConstantCaseLabel(pat)), null, c.stats, null)); 3945 } else { 3946 newCases.append(c); 3947 } 3948 } 3949 JCTree enumSwitch; 3950 if (tree.hasTag(SWITCH)) { 3951 enumSwitch = make.Switch(newSelector, newCases.toList()); 3952 } else if (tree.hasTag(SWITCH_EXPRESSION)) { 3953 enumSwitch = make.SwitchExpression(newSelector, newCases.toList()); 3954 enumSwitch.setType(tree.type); 3955 } else { 3956 Assert.error(); 3957 throw new AssertionError(); 3958 } 3959 patchTargets(enumSwitch, tree, enumSwitch); 3960 return enumSwitch; 3961 } 3962 3963 public JCTree visitStringSwitch(JCTree tree, JCExpression selector, List<JCCase> caseList) { 3964 int alternatives = caseList.size(); 3965 3966 if (alternatives == 0) { // Strange but legal possibility (only legal for switch statement) 3967 return make.at(tree.pos()).Exec(attr.makeNullCheck(selector)); 3968 } else { 3969 /* 3970 * The general approach used is to translate a single 3971 * string switch statement into a series of two chained 3972 * switch statements: the first a synthesized statement 3973 * switching on the argument string's hash value and 3974 * computing a string's position in the list of original 3975 * case labels, if any, followed by a second switch on the 3976 * computed integer value. The second switch has the same 3977 * code structure as the original string switch statement 3978 * except that the string case labels are replaced with 3979 * positional integer constants starting at 0. 3980 * 3981 * The first switch statement can be thought of as an 3982 * inlined map from strings to their position in the case 3983 * label list. An alternate implementation would use an 3984 * actual Map for this purpose, as done for enum switches. 3985 * 3986 * With some additional effort, it would be possible to 3987 * use a single switch statement on the hash code of the 3988 * argument, but care would need to be taken to preserve 3989 * the proper control flow in the presence of hash 3990 * collisions and other complications, such as 3991 * fallthroughs. Switch statements with one or two 3992 * alternatives could also be specially translated into 3993 * if-then statements to omit the computation of the hash 3994 * code. 3995 * 3996 * The generated code assumes that the hashing algorithm 3997 * of String is the same in the compilation environment as 3998 * in the environment the code will run in. The string 3999 * hashing algorithm in the SE JDK has been unchanged 4000 * since at least JDK 1.2. Since the algorithm has been 4001 * specified since that release as well, it is very 4002 * unlikely to be changed in the future. 4003 * 4004 * Different hashing algorithms, such as the length of the 4005 * strings or a perfect hashing algorithm over the 4006 * particular set of case labels, could potentially be 4007 * used instead of String.hashCode. 4008 */ 4009 4010 ListBuffer<JCStatement> stmtList = new ListBuffer<>(); 4011 4012 // Map from String case labels to their original position in 4013 // the list of case labels. 4014 Map<String, Integer> caseLabelToPosition = new LinkedHashMap<>(alternatives + 1, 1.0f); 4015 4016 // Map of hash codes to the string case labels having that hashCode. 4017 Map<Integer, Set<String>> hashToString = new LinkedHashMap<>(alternatives + 1, 1.0f); 4018 4019 int casePosition = 0; 4020 JCCase nullCase = null; 4021 int nullCaseLabel = -1; 4022 4023 for(JCCase oneCase : caseList) { 4024 if (oneCase.labels.head.hasTag(CONSTANTCASELABEL)) { 4025 if (TreeInfo.isNullCaseLabel(oneCase.labels.head)) { 4026 nullCase = oneCase; 4027 nullCaseLabel = casePosition; 4028 } else { 4029 JCExpression expression = ((JCConstantCaseLabel) oneCase.labels.head).expr; 4030 String labelExpr = (String) expression.type.constValue(); 4031 Integer mapping = caseLabelToPosition.put(labelExpr, casePosition); 4032 Assert.checkNull(mapping); 4033 int hashCode = labelExpr.hashCode(); 4034 4035 Set<String> stringSet = hashToString.get(hashCode); 4036 if (stringSet == null) { 4037 stringSet = new LinkedHashSet<>(1, 1.0f); 4038 stringSet.add(labelExpr); 4039 hashToString.put(hashCode, stringSet); 4040 } else { 4041 boolean added = stringSet.add(labelExpr); 4042 Assert.check(added); 4043 } 4044 } 4045 } 4046 casePosition++; 4047 } 4048 4049 // Synthesize a switch statement that has the effect of 4050 // mapping from a string to the integer position of that 4051 // string in the list of case labels. This is done by 4052 // switching on the hashCode of the string followed by an 4053 // if-then-else chain comparing the input for equality 4054 // with all the case labels having that hash value. 4055 4056 /* 4057 * s$ = top of stack; 4058 * tmp$ = -1; 4059 * switch($s.hashCode()) { 4060 * case caseLabel.hashCode: 4061 * if (s$.equals("caseLabel_1") 4062 * tmp$ = caseLabelToPosition("caseLabel_1"); 4063 * else if (s$.equals("caseLabel_2")) 4064 * tmp$ = caseLabelToPosition("caseLabel_2"); 4065 * ... 4066 * break; 4067 * ... 4068 * } 4069 */ 4070 4071 VarSymbol dollar_s = new VarSymbol(FINAL|SYNTHETIC, 4072 names.fromString("s" + variableIndex++ + target.syntheticNameChar()), 4073 syms.stringType, 4074 currentMethodSym); 4075 stmtList.append(make.at(tree.pos()).VarDef(dollar_s, selector).setType(dollar_s.type)); 4076 4077 VarSymbol dollar_tmp = new VarSymbol(SYNTHETIC, 4078 names.fromString("tmp" + variableIndex++ + target.syntheticNameChar()), 4079 syms.intType, 4080 currentMethodSym); 4081 JCVariableDecl dollar_tmp_def = 4082 (JCVariableDecl)make.VarDef(dollar_tmp, make.Literal(INT, -1)).setType(dollar_tmp.type); 4083 dollar_tmp_def.init.type = dollar_tmp.type = syms.intType; 4084 stmtList.append(dollar_tmp_def); 4085 ListBuffer<JCCase> caseBuffer = new ListBuffer<>(); 4086 // hashCode will trigger nullcheck on original switch expression 4087 JCMethodInvocation hashCodeCall = makeCall(make.Ident(dollar_s), 4088 names.hashCode, 4089 List.nil()).setType(syms.intType); 4090 JCSwitch switch1 = make.Switch(hashCodeCall, 4091 caseBuffer.toList()); 4092 for(Map.Entry<Integer, Set<String>> entry : hashToString.entrySet()) { 4093 int hashCode = entry.getKey(); 4094 Set<String> stringsWithHashCode = entry.getValue(); 4095 Assert.check(stringsWithHashCode.size() >= 1); 4096 4097 JCStatement elsepart = null; 4098 for(String caseLabel : stringsWithHashCode ) { 4099 JCMethodInvocation stringEqualsCall = makeCall(make.Ident(dollar_s), 4100 names.equals, 4101 List.of(make.Literal(caseLabel))); 4102 elsepart = make.If(stringEqualsCall, 4103 make.Exec(make.Assign(make.Ident(dollar_tmp), 4104 make.Literal(caseLabelToPosition.get(caseLabel))). 4105 setType(dollar_tmp.type)), 4106 elsepart); 4107 } 4108 4109 ListBuffer<JCStatement> lb = new ListBuffer<>(); 4110 JCBreak breakStmt = make.Break(null); 4111 breakStmt.target = switch1; 4112 lb.append(elsepart).append(breakStmt); 4113 4114 caseBuffer.append(make.Case(JCCase.STATEMENT, 4115 List.of(make.ConstantCaseLabel(make.Literal(hashCode))), 4116 null, 4117 lb.toList(), 4118 null)); 4119 } 4120 4121 switch1.cases = caseBuffer.toList(); 4122 4123 if (nullCase != null) { 4124 stmtList.append(make.If(makeBinary(NE, make.Ident(dollar_s), makeNull()), switch1, make.Exec(make.Assign(make.Ident(dollar_tmp), 4125 make.Literal(nullCaseLabel)). 4126 setType(dollar_tmp.type))).setType(syms.intType)); 4127 } else { 4128 stmtList.append(switch1); 4129 } 4130 4131 // Make isomorphic switch tree replacing string labels 4132 // with corresponding integer ones from the label to 4133 // position map. 4134 4135 ListBuffer<JCCase> lb = new ListBuffer<>(); 4136 for(JCCase oneCase : caseList ) { 4137 boolean isDefault = !oneCase.labels.head.hasTag(CONSTANTCASELABEL); 4138 JCExpression caseExpr; 4139 if (isDefault) 4140 caseExpr = null; 4141 else if (oneCase == nullCase) { 4142 caseExpr = make.Literal(nullCaseLabel); 4143 } else { 4144 JCExpression expression = ((JCConstantCaseLabel) oneCase.labels.head).expr; 4145 String name = (String) TreeInfo.skipParens(expression) 4146 .type.constValue(); 4147 caseExpr = make.Literal(caseLabelToPosition.get(name)); 4148 } 4149 4150 lb.append(make.Case(JCCase.STATEMENT, caseExpr == null ? List.of(make.DefaultCaseLabel()) 4151 : List.of(make.ConstantCaseLabel(caseExpr)), 4152 null, 4153 oneCase.stats, null)); 4154 } 4155 4156 if (tree.hasTag(SWITCH)) { 4157 JCSwitch switch2 = make.Switch(make.Ident(dollar_tmp), lb.toList()); 4158 // Rewire up old unlabeled break statements to the 4159 // replacement switch being created. 4160 patchTargets(switch2, tree, switch2); 4161 4162 stmtList.append(switch2); 4163 4164 JCBlock res = make.Block(0L, stmtList.toList()); 4165 res.bracePos = TreeInfo.endPos(tree); 4166 return res; 4167 } else { 4168 JCSwitchExpression switch2 = make.SwitchExpression(make.Ident(dollar_tmp), lb.toList()); 4169 4170 // Rewire up old unlabeled break statements to the 4171 // replacement switch being created. 4172 patchTargets(switch2, tree, switch2); 4173 4174 switch2.setType(tree.type); 4175 4176 LetExpr res = make.LetExpr(stmtList.toList(), switch2); 4177 4178 res.needsCond = true; 4179 res.setType(tree.type); 4180 4181 return res; 4182 } 4183 } 4184 } 4185 4186 private JCTree visitBoxedPrimitiveSwitch(JCTree tree, JCExpression selector, List<JCCase> cases) { 4187 JCExpression newSelector; 4188 4189 if (cases.stream().anyMatch(c -> TreeInfo.isNullCaseLabel(c.labels.head))) { 4190 //a switch over a boxed primitive, with a null case. Pick two constants that are 4191 //not used by any branch in the case (c1 and c2), close to other constants that are 4192 //used in the switch. Then do: 4193 //switch ($selector != null ? $selector != c1 ? $selector : c2 : c1) {...} 4194 //replacing case null with case c1 4195 Set<Integer> constants = new LinkedHashSet<>(); 4196 JCCase nullCase = null; 4197 4198 for (JCCase c : cases) { 4199 if (TreeInfo.isNullCaseLabel(c.labels.head)) { 4200 nullCase = c; 4201 } else if (!c.labels.head.hasTag(DEFAULTCASELABEL)) { 4202 constants.add((int) ((JCConstantCaseLabel) c.labels.head).expr.type.constValue()); 4203 } 4204 } 4205 4206 Assert.checkNonNull(nullCase); 4207 4208 int nullValue = constants.isEmpty() ? 0 : constants.iterator().next(); 4209 4210 while (constants.contains(nullValue)) nullValue++; 4211 4212 constants.add(nullValue); 4213 nullCase.labels.head = make.ConstantCaseLabel(makeLit(syms.intType, nullValue)); 4214 4215 int replacementValue = nullValue; 4216 4217 while (constants.contains(replacementValue)) replacementValue++; 4218 4219 VarSymbol dollar_s = new VarSymbol(FINAL|SYNTHETIC, 4220 names.fromString("s" + variableIndex++ + this.target.syntheticNameChar()), 4221 selector.type, 4222 currentMethodSym); 4223 JCStatement var = make.at(tree.pos()).VarDef(dollar_s, selector).setType(dollar_s.type); 4224 JCExpression nullValueReplacement = 4225 make.Conditional(makeBinary(NE, 4226 unbox(make.Ident(dollar_s), syms.intType), 4227 makeLit(syms.intType, nullValue)), 4228 unbox(make.Ident(dollar_s), syms.intType), 4229 makeLit(syms.intType, replacementValue)) 4230 .setType(syms.intType); 4231 JCExpression nullCheck = 4232 make.Conditional(makeBinary(NE, make.Ident(dollar_s), makeNull()), 4233 nullValueReplacement, 4234 makeLit(syms.intType, nullValue)) 4235 .setType(syms.intType); 4236 newSelector = make.LetExpr(List.of(var), nullCheck).setType(syms.intType); 4237 } else { 4238 newSelector = unbox(selector, syms.intType); 4239 } 4240 4241 if (tree.hasTag(SWITCH)) { 4242 ((JCSwitch) tree).selector = newSelector; 4243 } else { 4244 ((JCSwitchExpression) tree).selector = newSelector; 4245 } 4246 4247 return tree; 4248 } 4249 4250 @Override 4251 public void visitBreak(JCBreak tree) { 4252 result = tree; 4253 } 4254 4255 @Override 4256 public void visitYield(JCYield tree) { 4257 tree.value = translate(tree.value, tree.target.type); 4258 result = tree; 4259 } 4260 4261 public void visitNewArray(JCNewArray tree) { 4262 tree.elemtype = translate(tree.elemtype); 4263 for (List<JCExpression> t = tree.dims; t.tail != null; t = t.tail) 4264 if (t.head != null) t.head = translate(t.head, syms.intType); 4265 tree.elems = translate(tree.elems, types.elemtype(tree.type)); 4266 result = tree; 4267 } 4268 4269 public void visitSelect(JCFieldAccess tree) { 4270 // need to special case-access of the form C.super.x 4271 // these will always need an access method, unless C 4272 // is a default interface subclassed by the current class. 4273 boolean qualifiedSuperAccess = 4274 tree.selected.hasTag(SELECT) && 4275 TreeInfo.name(tree.selected) == names._super && 4276 !types.isDirectSuperInterface(((JCFieldAccess)tree.selected).selected.type.tsym, currentClass); 4277 tree.selected = translate(tree.selected); 4278 if (tree.name == names._class && tree.selected.type.isPrimitiveOrVoid()) { 4279 result = classOf(tree.selected); 4280 } 4281 else if (tree.name == names._super && 4282 types.isDirectSuperInterface(tree.selected.type.tsym, currentClass)) { 4283 //default super call!! Not a classic qualified super call 4284 TypeSymbol supSym = tree.selected.type.tsym; 4285 Assert.checkNonNull(types.asSuper(currentClass.type, supSym)); 4286 result = tree; 4287 } 4288 else if (tree.name == names._this || tree.name == names._super) { 4289 result = makeThis(tree.pos(), tree.selected.type.tsym); 4290 } 4291 else 4292 result = access(tree.sym, tree, enclOp, qualifiedSuperAccess); 4293 } 4294 4295 public void visitLetExpr(LetExpr tree) { 4296 tree.defs = translate(tree.defs); 4297 tree.expr = translate(tree.expr, tree.type); 4298 result = tree; 4299 } 4300 4301 // There ought to be nothing to rewrite here; 4302 // we don't generate code. 4303 public void visitAnnotation(JCAnnotation tree) { 4304 result = tree; 4305 } 4306 4307 @Override 4308 public void visitTry(JCTry tree) { 4309 if (tree.resources.nonEmpty()) { 4310 result = makeTwrTry(tree); 4311 return; 4312 } 4313 4314 boolean hasBody = tree.body.getStatements().nonEmpty(); 4315 boolean hasCatchers = tree.catchers.nonEmpty(); 4316 boolean hasFinally = tree.finalizer != null && 4317 tree.finalizer.getStatements().nonEmpty(); 4318 4319 if (!hasCatchers && !hasFinally) { 4320 result = translate(tree.body); 4321 return; 4322 } 4323 4324 if (!hasBody) { 4325 if (hasFinally) { 4326 result = translate(tree.finalizer); 4327 } else { 4328 result = translate(tree.body); 4329 } 4330 return; 4331 } 4332 4333 // no optimizations possible 4334 super.visitTry(tree); 4335 } 4336 4337 /* ************************************************************************ 4338 * main method 4339 *************************************************************************/ 4340 4341 /** Translate a toplevel class and return a list consisting of 4342 * the translated class and translated versions of all inner classes. 4343 * @param env The attribution environment current at the class definition. 4344 * We need this for resolving some additional symbols. 4345 * @param cdef The tree representing the class definition. 4346 */ 4347 public List<JCTree> translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) { 4348 ListBuffer<JCTree> translated = null; 4349 try { 4350 attrEnv = env; 4351 this.make = make; 4352 currentClass = null; 4353 currentRestype = null; 4354 currentMethodDef = null; 4355 outermostClassDef = (cdef.hasTag(CLASSDEF)) ? (JCClassDecl)cdef : null; 4356 outermostMemberDef = null; 4357 this.translated = new ListBuffer<>(); 4358 classdefs = new HashMap<>(); 4359 actualSymbols = new HashMap<>(); 4360 freevarCache = new HashMap<>(); 4361 proxies = new HashMap<>(); 4362 twrVars = WriteableScope.create(syms.noSymbol); 4363 outerThisStack = List.nil(); 4364 accessNums = new HashMap<>(); 4365 accessSyms = new HashMap<>(); 4366 accessConstrs = new HashMap<>(); 4367 accessConstrTags = List.nil(); 4368 accessed = new ListBuffer<>(); 4369 translate(cdef, (JCExpression)null); 4370 for (List<Symbol> l = accessed.toList(); l.nonEmpty(); l = l.tail) 4371 makeAccessible(l.head); 4372 for (EnumMapping map : enumSwitchMap.values()) 4373 map.translate(); 4374 checkConflicts(this.translated.toList()); 4375 checkAccessConstructorTags(); 4376 translated = this.translated; 4377 } finally { 4378 // note that recursive invocations of this method fail hard 4379 attrEnv = null; 4380 this.make = null; 4381 currentClass = null; 4382 currentRestype = null; 4383 currentMethodDef = null; 4384 outermostClassDef = null; 4385 outermostMemberDef = null; 4386 this.translated = null; 4387 classdefs = null; 4388 actualSymbols = null; 4389 freevarCache = null; 4390 proxies = null; 4391 outerThisStack = null; 4392 accessNums = null; 4393 accessSyms = null; 4394 accessConstrs = null; 4395 accessConstrTags = null; 4396 accessed = null; 4397 enumSwitchMap.clear(); 4398 assertionsDisabledClassCache = null; 4399 } 4400 return translated.toList(); 4401 } 4402 4403 // needed for the lambda deserialization method, which is expressed as a big switch on strings 4404 public JCMethodDecl translateMethod(Env<AttrContext> env, JCMethodDecl methodDecl, TreeMaker make) { 4405 try { 4406 this.attrEnv = env; 4407 this.make = make; 4408 this.currentClass = methodDecl.sym.enclClass(); 4409 proxies = new HashMap<>(); 4410 return translate(methodDecl); 4411 } finally { 4412 this.attrEnv = null; 4413 this.make = null; 4414 this.currentClass = null; 4415 // the two fields below are set when visiting the method 4416 this.currentMethodSym = null; 4417 this.currentMethodDef = null; 4418 this.proxies = null; 4419 } 4420 } 4421 } --- EOF ---