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