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