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