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