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