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