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