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