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