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