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); 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 Type autoCloseableType = types.asSuper(resource.type, syms.autoCloseableType.tsym); 1516 Symbol closeMethod = autoCloseableType.tsym.members().lookup(names.close).sym; 1517 JCExpression closeInvocation = make.Select(resource, closeMethod); 1518 JCMethodInvocation resourceClose = make.Apply(List.<JCExpression>nil(), 1519 closeInvocation, 1520 List.<JCExpression>nil()); 1521 resourceClose.type = closeMethod.type.getReturnType(); 1522 return make.Exec(resourceClose); 1523 } 1524 1525 /** Construct a tree that represents the outer instance 1526 * <C.this>. Never pick the current `this'. 1527 * @param pos The source code position to be used for the tree. 1528 * @param c The qualifier class. 1529 */ 1530 JCExpression makeOuterThis(DiagnosticPosition pos, TypeSymbol c) { 1531 List<VarSymbol> ots = outerThisStack; 1532 if (ots.isEmpty()) { 1533 log.error(pos, "no.encl.instance.of.type.in.scope", c); 1534 assert false; 1535 return makeNull(); 1536 } 1537 VarSymbol ot = ots.head; 1538 JCExpression tree = access(make.at(pos).Ident(ot)); 1539 TypeSymbol otc = ot.type.tsym; 1540 while (otc != c) { 1541 do { 1542 ots = ots.tail; 1543 if (ots.isEmpty()) { 1544 log.error(pos, 1545 "no.encl.instance.of.type.in.scope", 1546 c); 1547 assert false; // should have been caught in Attr 1548 return tree; 1549 } 1550 ot = ots.head; 1551 } while (ot.owner != otc); 1552 if (otc.owner.kind != PCK && !otc.hasOuterInstance()) { 1553 chk.earlyRefError(pos, c); 1554 assert false; // should have been caught in Attr 1555 return makeNull(); 1556 } 1557 tree = access(make.at(pos).Select(tree, ot)); 1558 otc = ot.type.tsym; 1559 } 1560 return tree; 1561 } 1562 1563 /** Construct a tree that represents the closest outer instance 1564 * <C.this> such that the given symbol is a member of C. 1565 * @param pos The source code position to be used for the tree. 1566 * @param sym The accessed symbol. 1567 * @param preciseMatch should we accept a type that is a subtype of 1568 * sym's owner, even if it doesn't contain sym 1569 * due to hiding, overriding, or non-inheritance 1570 * due to protection? 1571 */ 1572 JCExpression makeOwnerThis(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) { 1573 Symbol c = sym.owner; 1574 if (preciseMatch ? sym.isMemberOf(currentClass, types) 1575 : currentClass.isSubClass(sym.owner, types)) { 1576 // in this case, `this' works fine 1577 return make.at(pos).This(c.erasure(types)); 1578 } else { 1579 // need to go via this$n 1580 return makeOwnerThisN(pos, sym, preciseMatch); 1581 } 1582 } 1583 1584 /** 1585 * Similar to makeOwnerThis but will never pick "this". 1586 */ 1587 JCExpression makeOwnerThisN(DiagnosticPosition pos, Symbol sym, boolean preciseMatch) { 1588 Symbol c = sym.owner; 1589 List<VarSymbol> ots = outerThisStack; 1590 if (ots.isEmpty()) { 1591 log.error(pos, "no.encl.instance.of.type.in.scope", c); 1592 assert false; 1593 return makeNull(); 1594 } 1595 VarSymbol ot = ots.head; 1596 JCExpression tree = access(make.at(pos).Ident(ot)); 1597 TypeSymbol otc = ot.type.tsym; 1598 while (!(preciseMatch ? sym.isMemberOf(otc, types) : otc.isSubClass(sym.owner, types))) { 1599 do { 1600 ots = ots.tail; 1601 if (ots.isEmpty()) { 1602 log.error(pos, 1603 "no.encl.instance.of.type.in.scope", 1604 c); 1605 assert false; 1606 return tree; 1607 } 1608 ot = ots.head; 1609 } while (ot.owner != otc); 1610 tree = access(make.at(pos).Select(tree, ot)); 1611 otc = ot.type.tsym; 1612 } 1613 return tree; 1614 } 1615 1616 /** Return tree simulating the assignment <this.name = name>, where 1617 * name is the name of a free variable. 1618 */ 1619 JCStatement initField(int pos, Name name) { 1620 Scope.Entry e = proxies.lookup(name); 1621 Symbol rhs = e.sym; 1622 assert rhs.owner.kind == MTH; 1623 Symbol lhs = e.next().sym; 1624 assert rhs.owner.owner == lhs.owner; 1625 make.at(pos); 1626 return 1627 make.Exec( 1628 make.Assign( 1629 make.Select(make.This(lhs.owner.erasure(types)), lhs), 1630 make.Ident(rhs)).setType(lhs.erasure(types))); 1631 } 1632 1633 /** Return tree simulating the assignment <this.this$n = this$n>. 1634 */ 1635 JCStatement initOuterThis(int pos) { 1636 VarSymbol rhs = outerThisStack.head; 1637 assert rhs.owner.kind == MTH; 1638 VarSymbol lhs = outerThisStack.tail.head; 1639 assert rhs.owner.owner == lhs.owner; 1640 make.at(pos); 1641 return 1642 make.Exec( 1643 make.Assign( 1644 make.Select(make.This(lhs.owner.erasure(types)), lhs), 1645 make.Ident(rhs)).setType(lhs.erasure(types))); 1646 } 1647 1648 /************************************************************************** 1649 * Code for .class 1650 *************************************************************************/ 1651 1652 /** Return the symbol of a class to contain a cache of 1653 * compiler-generated statics such as class$ and the 1654 * $assertionsDisabled flag. We create an anonymous nested class 1655 * (unless one already exists) and return its symbol. However, 1656 * for backward compatibility in 1.4 and earlier we use the 1657 * top-level class itself. 1658 */ 1659 private ClassSymbol outerCacheClass() { 1660 ClassSymbol clazz = outermostClassDef.sym; 1661 if ((clazz.flags() & INTERFACE) == 0 && 1662 !target.useInnerCacheClass()) return clazz; 1663 Scope s = clazz.members(); 1664 for (Scope.Entry e = s.elems; e != null; e = e.sibling) 1665 if (e.sym.kind == TYP && 1666 e.sym.name == names.empty && 1667 (e.sym.flags() & INTERFACE) == 0) return (ClassSymbol) e.sym; 1668 return makeEmptyClass(STATIC | SYNTHETIC, clazz); 1669 } 1670 1671 /** Return symbol for "class$" method. If there is no method definition 1672 * for class$, construct one as follows: 1673 * 1674 * class class$(String x0) { 1675 * try { 1676 * return Class.forName(x0); 1677 * } catch (ClassNotFoundException x1) { 1678 * throw new NoClassDefFoundError(x1.getMessage()); 1679 * } 1680 * } 1681 */ 1682 private MethodSymbol classDollarSym(DiagnosticPosition pos) { 1683 ClassSymbol outerCacheClass = outerCacheClass(); 1684 MethodSymbol classDollarSym = 1685 (MethodSymbol)lookupSynthetic(classDollar, 1686 outerCacheClass.members()); 1687 if (classDollarSym == null) { 1688 classDollarSym = new MethodSymbol( 1689 STATIC | SYNTHETIC, 1690 classDollar, 1691 new MethodType( 1692 List.of(syms.stringType), 1693 types.erasure(syms.classType), 1694 List.<Type>nil(), 1695 syms.methodClass), 1696 outerCacheClass); 1697 enterSynthetic(pos, classDollarSym, outerCacheClass.members()); 1698 1699 JCMethodDecl md = make.MethodDef(classDollarSym, null); 1700 try { 1701 md.body = classDollarSymBody(pos, md); 1702 } catch (CompletionFailure ex) { 1703 md.body = make.Block(0, List.<JCStatement>nil()); 1704 chk.completionError(pos, ex); 1705 } 1706 JCClassDecl outerCacheClassDef = classDef(outerCacheClass); 1707 outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(md); 1708 } 1709 return classDollarSym; 1710 } 1711 1712 /** Generate code for class$(String name). */ 1713 JCBlock classDollarSymBody(DiagnosticPosition pos, JCMethodDecl md) { 1714 MethodSymbol classDollarSym = md.sym; 1715 ClassSymbol outerCacheClass = (ClassSymbol)classDollarSym.owner; 1716 1717 JCBlock returnResult; 1718 1719 // in 1.4.2 and above, we use 1720 // Class.forName(String name, boolean init, ClassLoader loader); 1721 // which requires we cache the current loader in cl$ 1722 if (target.classLiteralsNoInit()) { 1723 // clsym = "private static ClassLoader cl$" 1724 VarSymbol clsym = new VarSymbol(STATIC|SYNTHETIC, 1725 names.fromString("cl" + target.syntheticNameChar()), 1726 syms.classLoaderType, 1727 outerCacheClass); 1728 enterSynthetic(pos, clsym, outerCacheClass.members()); 1729 1730 // emit "private static ClassLoader cl$;" 1731 JCVariableDecl cldef = make.VarDef(clsym, null); 1732 JCClassDecl outerCacheClassDef = classDef(outerCacheClass); 1733 outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(cldef); 1734 1735 // newcache := "new cache$1[0]" 1736 JCNewArray newcache = make. 1737 NewArray(make.Type(outerCacheClass.type), 1738 List.<JCExpression>of(make.Literal(INT, 0).setType(syms.intType)), 1739 null); 1740 newcache.type = new ArrayType(types.erasure(outerCacheClass.type), 1741 syms.arrayClass); 1742 1743 // forNameSym := java.lang.Class.forName( 1744 // String s,boolean init,ClassLoader loader) 1745 Symbol forNameSym = lookupMethod(make_pos, names.forName, 1746 types.erasure(syms.classType), 1747 List.of(syms.stringType, 1748 syms.booleanType, 1749 syms.classLoaderType)); 1750 // clvalue := "(cl$ == null) ? 1751 // $newcache.getClass().getComponentType().getClassLoader() : cl$" 1752 JCExpression clvalue = 1753 make.Conditional( 1754 makeBinary(JCTree.EQ, make.Ident(clsym), makeNull()), 1755 make.Assign( 1756 make.Ident(clsym), 1757 makeCall( 1758 makeCall(makeCall(newcache, 1759 names.getClass, 1760 List.<JCExpression>nil()), 1761 names.getComponentType, 1762 List.<JCExpression>nil()), 1763 names.getClassLoader, 1764 List.<JCExpression>nil())).setType(syms.classLoaderType), 1765 make.Ident(clsym)).setType(syms.classLoaderType); 1766 1767 // returnResult := "{ return Class.forName(param1, false, cl$); }" 1768 List<JCExpression> args = List.of(make.Ident(md.params.head.sym), 1769 makeLit(syms.booleanType, 0), 1770 clvalue); 1771 returnResult = make. 1772 Block(0, List.<JCStatement>of(make. 1773 Call(make. // return 1774 App(make. 1775 Ident(forNameSym), args)))); 1776 } else { 1777 // forNameSym := java.lang.Class.forName(String s) 1778 Symbol forNameSym = lookupMethod(make_pos, 1779 names.forName, 1780 types.erasure(syms.classType), 1781 List.of(syms.stringType)); 1782 // returnResult := "{ return Class.forName(param1); }" 1783 returnResult = make. 1784 Block(0, List.of(make. 1785 Call(make. // return 1786 App(make. 1787 QualIdent(forNameSym), 1788 List.<JCExpression>of(make. 1789 Ident(md.params. 1790 head.sym)))))); 1791 } 1792 1793 // catchParam := ClassNotFoundException e1 1794 VarSymbol catchParam = 1795 new VarSymbol(0, make.paramName(1), 1796 syms.classNotFoundExceptionType, 1797 classDollarSym); 1798 1799 JCStatement rethrow; 1800 if (target.hasInitCause()) { 1801 // rethrow = "throw new NoClassDefFoundError().initCause(e); 1802 JCTree throwExpr = 1803 makeCall(makeNewClass(syms.noClassDefFoundErrorType, 1804 List.<JCExpression>nil()), 1805 names.initCause, 1806 List.<JCExpression>of(make.Ident(catchParam))); 1807 rethrow = make.Throw(throwExpr); 1808 } else { 1809 // getMessageSym := ClassNotFoundException.getMessage() 1810 Symbol getMessageSym = lookupMethod(make_pos, 1811 names.getMessage, 1812 syms.classNotFoundExceptionType, 1813 List.<Type>nil()); 1814 // rethrow = "throw new NoClassDefFoundError(e.getMessage());" 1815 rethrow = make. 1816 Throw(makeNewClass(syms.noClassDefFoundErrorType, 1817 List.<JCExpression>of(make.App(make.Select(make.Ident(catchParam), 1818 getMessageSym), 1819 List.<JCExpression>nil())))); 1820 } 1821 1822 // rethrowStmt := "( $rethrow )" 1823 JCBlock rethrowStmt = make.Block(0, List.of(rethrow)); 1824 1825 // catchBlock := "catch ($catchParam) $rethrowStmt" 1826 JCCatch catchBlock = make.Catch(make.VarDef(catchParam, null), 1827 rethrowStmt); 1828 1829 // tryCatch := "try $returnResult $catchBlock" 1830 JCStatement tryCatch = make.Try(returnResult, 1831 List.of(catchBlock), null); 1832 1833 return make.Block(0, List.of(tryCatch)); 1834 } 1835 // where 1836 /** Create an attributed tree of the form left.name(). */ 1837 private JCMethodInvocation makeCall(JCExpression left, Name name, List<JCExpression> args) { 1838 assert left.type != null; 1839 Symbol funcsym = lookupMethod(make_pos, name, left.type, 1840 TreeInfo.types(args)); 1841 return make.App(make.Select(left, funcsym), args); 1842 } 1843 1844 /** The Name Of The variable to cache T.class values. 1845 * @param sig The signature of type T. 1846 */ 1847 private Name cacheName(String sig) { 1848 StringBuffer buf = new StringBuffer(); 1849 if (sig.startsWith("[")) { 1850 buf = buf.append("array"); 1851 while (sig.startsWith("[")) { 1852 buf = buf.append(target.syntheticNameChar()); 1853 sig = sig.substring(1); 1854 } 1855 if (sig.startsWith("L")) { 1856 sig = sig.substring(0, sig.length() - 1); 1857 } 1858 } else { 1859 buf = buf.append("class" + target.syntheticNameChar()); 1860 } 1861 buf = buf.append(sig.replace('.', target.syntheticNameChar())); 1862 return names.fromString(buf.toString()); 1863 } 1864 1865 /** The variable symbol that caches T.class values. 1866 * If none exists yet, create a definition. 1867 * @param sig The signature of type T. 1868 * @param pos The position to report diagnostics, if any. 1869 */ 1870 private VarSymbol cacheSym(DiagnosticPosition pos, String sig) { 1871 ClassSymbol outerCacheClass = outerCacheClass(); 1872 Name cname = cacheName(sig); 1873 VarSymbol cacheSym = 1874 (VarSymbol)lookupSynthetic(cname, outerCacheClass.members()); 1875 if (cacheSym == null) { 1876 cacheSym = new VarSymbol( 1877 STATIC | SYNTHETIC, cname, types.erasure(syms.classType), outerCacheClass); 1878 enterSynthetic(pos, cacheSym, outerCacheClass.members()); 1879 1880 JCVariableDecl cacheDef = make.VarDef(cacheSym, null); 1881 JCClassDecl outerCacheClassDef = classDef(outerCacheClass); 1882 outerCacheClassDef.defs = outerCacheClassDef.defs.prepend(cacheDef); 1883 } 1884 return cacheSym; 1885 } 1886 1887 /** The tree simulating a T.class expression. 1888 * @param clazz The tree identifying type T. 1889 */ 1890 private JCExpression classOf(JCTree clazz) { 1891 return classOfType(clazz.type, clazz.pos()); 1892 } 1893 1894 private JCExpression classOfType(Type type, DiagnosticPosition pos) { 1895 switch (type.tag) { 1896 case BYTE: case SHORT: case CHAR: case INT: case LONG: case FLOAT: 1897 case DOUBLE: case BOOLEAN: case VOID: 1898 // replace with <BoxedClass>.TYPE 1899 ClassSymbol c = types.boxedClass(type); 1900 Symbol typeSym = 1901 rs.access( 1902 rs.findIdentInType(attrEnv, c.type, names.TYPE, VAR), 1903 pos, c.type, names.TYPE, true); 1904 if (typeSym.kind == VAR) 1905 ((VarSymbol)typeSym).getConstValue(); // ensure initializer is evaluated 1906 return make.QualIdent(typeSym); 1907 case CLASS: case ARRAY: 1908 if (target.hasClassLiterals()) { 1909 VarSymbol sym = new VarSymbol( 1910 STATIC | PUBLIC | FINAL, names._class, 1911 syms.classType, type.tsym); 1912 return make_at(pos).Select(make.Type(type), sym); 1913 } 1914 // replace with <cache == null ? cache = class$(tsig) : cache> 1915 // where 1916 // - <tsig> is the type signature of T, 1917 // - <cache> is the cache variable for tsig. 1918 String sig = 1919 writer.xClassName(type).toString().replace('/', '.'); 1920 Symbol cs = cacheSym(pos, sig); 1921 return make_at(pos).Conditional( 1922 makeBinary(JCTree.EQ, make.Ident(cs), makeNull()), 1923 make.Assign( 1924 make.Ident(cs), 1925 make.App( 1926 make.Ident(classDollarSym(pos)), 1927 List.<JCExpression>of(make.Literal(CLASS, sig) 1928 .setType(syms.stringType)))) 1929 .setType(types.erasure(syms.classType)), 1930 make.Ident(cs)).setType(types.erasure(syms.classType)); 1931 default: 1932 throw new AssertionError(); 1933 } 1934 } 1935 1936 /************************************************************************** 1937 * Code for enabling/disabling assertions. 1938 *************************************************************************/ 1939 1940 // This code is not particularly robust if the user has 1941 // previously declared a member named '$assertionsDisabled'. 1942 // The same faulty idiom also appears in the translation of 1943 // class literals above. We should report an error if a 1944 // previous declaration is not synthetic. 1945 1946 private JCExpression assertFlagTest(DiagnosticPosition pos) { 1947 // Outermost class may be either true class or an interface. 1948 ClassSymbol outermostClass = outermostClassDef.sym; 1949 1950 // note that this is a class, as an interface can't contain a statement. 1951 ClassSymbol container = currentClass; 1952 1953 VarSymbol assertDisabledSym = 1954 (VarSymbol)lookupSynthetic(dollarAssertionsDisabled, 1955 container.members()); 1956 if (assertDisabledSym == null) { 1957 assertDisabledSym = 1958 new VarSymbol(STATIC | FINAL | SYNTHETIC, 1959 dollarAssertionsDisabled, 1960 syms.booleanType, 1961 container); 1962 enterSynthetic(pos, assertDisabledSym, container.members()); 1963 Symbol desiredAssertionStatusSym = lookupMethod(pos, 1964 names.desiredAssertionStatus, 1965 types.erasure(syms.classType), 1966 List.<Type>nil()); 1967 JCClassDecl containerDef = classDef(container); 1968 make_at(containerDef.pos()); 1969 JCExpression notStatus = makeUnary(JCTree.NOT, make.App(make.Select( 1970 classOfType(types.erasure(outermostClass.type), 1971 containerDef.pos()), 1972 desiredAssertionStatusSym))); 1973 JCVariableDecl assertDisabledDef = make.VarDef(assertDisabledSym, 1974 notStatus); 1975 containerDef.defs = containerDef.defs.prepend(assertDisabledDef); 1976 } 1977 make_at(pos); 1978 return makeUnary(JCTree.NOT, make.Ident(assertDisabledSym)); 1979 } 1980 1981 1982 /************************************************************************** 1983 * Building blocks for let expressions 1984 *************************************************************************/ 1985 1986 interface TreeBuilder { 1987 JCTree build(JCTree arg); 1988 } 1989 1990 /** Construct an expression using the builder, with the given rval 1991 * expression as an argument to the builder. However, the rval 1992 * expression must be computed only once, even if used multiple 1993 * times in the result of the builder. We do that by 1994 * constructing a "let" expression that saves the rvalue into a 1995 * temporary variable and then uses the temporary variable in 1996 * place of the expression built by the builder. The complete 1997 * resulting expression is of the form 1998 * <pre> 1999 * (let <b>TYPE</b> <b>TEMP</b> = <b>RVAL</b>; 2000 * in (<b>BUILDER</b>(<b>TEMP</b>))) 2001 * </pre> 2002 * where <code><b>TEMP</b></code> is a newly declared variable 2003 * in the let expression. 2004 */ 2005 JCTree abstractRval(JCTree rval, Type type, TreeBuilder builder) { 2006 rval = TreeInfo.skipParens(rval); 2007 switch (rval.getTag()) { 2008 case JCTree.LITERAL: 2009 return builder.build(rval); 2010 case JCTree.IDENT: 2011 JCIdent id = (JCIdent) rval; 2012 if ((id.sym.flags() & FINAL) != 0 && id.sym.owner.kind == MTH) 2013 return builder.build(rval); 2014 } 2015 VarSymbol var = 2016 new VarSymbol(FINAL|SYNTHETIC, 2017 names.fromString( 2018 target.syntheticNameChar() 2019 + "" + rval.hashCode()), 2020 type, 2021 currentMethodSym); 2022 rval = convert(rval,type); 2023 JCVariableDecl def = make.VarDef(var, (JCExpression)rval); // XXX cast 2024 JCTree built = builder.build(make.Ident(var)); 2025 JCTree res = make.LetExpr(def, built); 2026 res.type = built.type; 2027 return res; 2028 } 2029 2030 // same as above, with the type of the temporary variable computed 2031 JCTree abstractRval(JCTree rval, TreeBuilder builder) { 2032 return abstractRval(rval, rval.type, builder); 2033 } 2034 2035 // same as above, but for an expression that may be used as either 2036 // an rvalue or an lvalue. This requires special handling for 2037 // Select expressions, where we place the left-hand-side of the 2038 // select in a temporary, and for Indexed expressions, where we 2039 // place both the indexed expression and the index value in temps. 2040 JCTree abstractLval(JCTree lval, final TreeBuilder builder) { 2041 lval = TreeInfo.skipParens(lval); 2042 switch (lval.getTag()) { 2043 case JCTree.IDENT: 2044 return builder.build(lval); 2045 case JCTree.SELECT: { 2046 final JCFieldAccess s = (JCFieldAccess)lval; 2047 JCTree selected = TreeInfo.skipParens(s.selected); 2048 Symbol lid = TreeInfo.symbol(s.selected); 2049 if (lid != null && lid.kind == TYP) return builder.build(lval); 2050 return abstractRval(s.selected, new TreeBuilder() { 2051 public JCTree build(final JCTree selected) { 2052 return builder.build(make.Select((JCExpression)selected, s.sym)); 2053 } 2054 }); 2055 } 2056 case JCTree.INDEXED: { 2057 final JCArrayAccess i = (JCArrayAccess)lval; 2058 return abstractRval(i.indexed, new TreeBuilder() { 2059 public JCTree build(final JCTree indexed) { 2060 return abstractRval(i.index, syms.intType, new TreeBuilder() { 2061 public JCTree build(final JCTree index) { 2062 JCTree newLval = make.Indexed((JCExpression)indexed, 2063 (JCExpression)index); 2064 newLval.setType(i.type); 2065 return builder.build(newLval); 2066 } 2067 }); 2068 } 2069 }); 2070 } 2071 case JCTree.TYPECAST: { 2072 return abstractLval(((JCTypeCast)lval).expr, builder); 2073 } 2074 } 2075 throw new AssertionError(lval); 2076 } 2077 2078 // evaluate and discard the first expression, then evaluate the second. 2079 JCTree makeComma(final JCTree expr1, final JCTree expr2) { 2080 return abstractRval(expr1, new TreeBuilder() { 2081 public JCTree build(final JCTree discarded) { 2082 return expr2; 2083 } 2084 }); 2085 } 2086 2087 /************************************************************************** 2088 * Translation methods 2089 *************************************************************************/ 2090 2091 /** Visitor argument: enclosing operator node. 2092 */ 2093 private JCExpression enclOp; 2094 2095 /** Visitor method: Translate a single node. 2096 * Attach the source position from the old tree to its replacement tree. 2097 */ 2098 public <T extends JCTree> T translate(T tree) { 2099 if (tree == null) { 2100 return null; 2101 } else { 2102 make_at(tree.pos()); 2103 T result = super.translate(tree); 2104 if (endPositions != null && result != tree) { 2105 Integer endPos = endPositions.remove(tree); 2106 if (endPos != null) endPositions.put(result, endPos); 2107 } 2108 return result; 2109 } 2110 } 2111 2112 /** Visitor method: Translate a single node, boxing or unboxing if needed. 2113 */ 2114 public <T extends JCTree> T translate(T tree, Type type) { 2115 return (tree == null) ? null : boxIfNeeded(translate(tree), type); 2116 } 2117 2118 /** Visitor method: Translate tree. 2119 */ 2120 public <T extends JCTree> T translate(T tree, JCExpression enclOp) { 2121 JCExpression prevEnclOp = this.enclOp; 2122 this.enclOp = enclOp; 2123 T res = translate(tree); 2124 this.enclOp = prevEnclOp; 2125 return res; 2126 } 2127 2128 /** Visitor method: Translate list of trees. 2129 */ 2130 public <T extends JCTree> List<T> translate(List<T> trees, JCExpression enclOp) { 2131 JCExpression prevEnclOp = this.enclOp; 2132 this.enclOp = enclOp; 2133 List<T> res = translate(trees); 2134 this.enclOp = prevEnclOp; 2135 return res; 2136 } 2137 2138 /** Visitor method: Translate list of trees. 2139 */ 2140 public <T extends JCTree> List<T> translate(List<T> trees, Type type) { 2141 if (trees == null) return null; 2142 for (List<T> l = trees; l.nonEmpty(); l = l.tail) 2143 l.head = translate(l.head, type); 2144 return trees; 2145 } 2146 2147 public void visitTopLevel(JCCompilationUnit tree) { 2148 if (tree.packageAnnotations.nonEmpty()) { 2149 Name name = names.package_info; 2150 long flags = Flags.ABSTRACT | Flags.INTERFACE; 2151 if (target.isPackageInfoSynthetic()) 2152 // package-info is marked SYNTHETIC in JDK 1.6 and later releases 2153 flags = flags | Flags.SYNTHETIC; 2154 JCClassDecl packageAnnotationsClass 2155 = make.ClassDef(make.Modifiers(flags, 2156 tree.packageAnnotations), 2157 name, List.<JCTypeParameter>nil(), 2158 null, List.<JCExpression>nil(), List.<JCTree>nil()); 2159 ClassSymbol c = tree.packge.package_info; 2160 c.flags_field |= flags; 2161 c.attributes_field = tree.packge.attributes_field; 2162 ClassType ctype = (ClassType) c.type; 2163 ctype.supertype_field = syms.objectType; 2164 ctype.interfaces_field = List.nil(); 2165 packageAnnotationsClass.sym = c; 2166 2167 translated.append(packageAnnotationsClass); 2168 } 2169 } 2170 2171 public void visitClassDef(JCClassDecl tree) { 2172 ClassSymbol currentClassPrev = currentClass; 2173 MethodSymbol currentMethodSymPrev = currentMethodSym; 2174 currentClass = tree.sym; 2175 currentMethodSym = null; 2176 classdefs.put(currentClass, tree); 2177 2178 proxies = proxies.dup(currentClass); 2179 List<VarSymbol> prevOuterThisStack = outerThisStack; 2180 2181 // If this is an enum definition 2182 if ((tree.mods.flags & ENUM) != 0 && 2183 (types.supertype(currentClass.type).tsym.flags() & ENUM) == 0) 2184 visitEnumDef(tree); 2185 2186 // If this is a nested class, define a this$n field for 2187 // it and add to proxies. 2188 JCVariableDecl otdef = null; 2189 if (currentClass.hasOuterInstance()) 2190 otdef = outerThisDef(tree.pos, currentClass); 2191 2192 // If this is a local class, define proxies for all its free variables. 2193 List<JCVariableDecl> fvdefs = freevarDefs( 2194 tree.pos, freevars(currentClass), currentClass); 2195 2196 // Recursively translate superclass, interfaces. 2197 tree.extending = translate(tree.extending); 2198 tree.implementing = translate(tree.implementing); 2199 2200 // Recursively translate members, taking into account that new members 2201 // might be created during the translation and prepended to the member 2202 // list `tree.defs'. 2203 List<JCTree> seen = List.nil(); 2204 while (tree.defs != seen) { 2205 List<JCTree> unseen = tree.defs; 2206 for (List<JCTree> l = unseen; l.nonEmpty() && l != seen; l = l.tail) { 2207 JCTree outermostMemberDefPrev = outermostMemberDef; 2208 if (outermostMemberDefPrev == null) outermostMemberDef = l.head; 2209 l.head = translate(l.head); 2210 outermostMemberDef = outermostMemberDefPrev; 2211 } 2212 seen = unseen; 2213 } 2214 2215 // Convert a protected modifier to public, mask static modifier. 2216 if ((tree.mods.flags & PROTECTED) != 0) tree.mods.flags |= PUBLIC; 2217 tree.mods.flags &= ClassFlags; 2218 2219 // Convert name to flat representation, replacing '.' by '$'. 2220 tree.name = Convert.shortName(currentClass.flatName()); 2221 2222 // Add this$n and free variables proxy definitions to class. 2223 for (List<JCVariableDecl> l = fvdefs; l.nonEmpty(); l = l.tail) { 2224 tree.defs = tree.defs.prepend(l.head); 2225 enterSynthetic(tree.pos(), l.head.sym, currentClass.members()); 2226 } 2227 if (currentClass.hasOuterInstance()) { 2228 tree.defs = tree.defs.prepend(otdef); 2229 enterSynthetic(tree.pos(), otdef.sym, currentClass.members()); 2230 } 2231 2232 proxies = proxies.leave(); 2233 outerThisStack = prevOuterThisStack; 2234 2235 // Append translated tree to `translated' queue. 2236 translated.append(tree); 2237 2238 currentClass = currentClassPrev; 2239 currentMethodSym = currentMethodSymPrev; 2240 2241 // Return empty block {} as a placeholder for an inner class. 2242 result = make_at(tree.pos()).Block(0, List.<JCStatement>nil()); 2243 } 2244 2245 /** Translate an enum class. */ 2246 private void visitEnumDef(JCClassDecl tree) { 2247 make_at(tree.pos()); 2248 2249 // add the supertype, if needed 2250 if (tree.extending == null) 2251 tree.extending = make.Type(types.supertype(tree.type)); 2252 2253 // classOfType adds a cache field to tree.defs unless 2254 // target.hasClassLiterals(). 2255 JCExpression e_class = classOfType(tree.sym.type, tree.pos()). 2256 setType(types.erasure(syms.classType)); 2257 2258 // process each enumeration constant, adding implicit constructor parameters 2259 int nextOrdinal = 0; 2260 ListBuffer<JCExpression> values = new ListBuffer<JCExpression>(); 2261 ListBuffer<JCTree> enumDefs = new ListBuffer<JCTree>(); 2262 ListBuffer<JCTree> otherDefs = new ListBuffer<JCTree>(); 2263 for (List<JCTree> defs = tree.defs; 2264 defs.nonEmpty(); 2265 defs=defs.tail) { 2266 if (defs.head.getTag() == JCTree.VARDEF && (((JCVariableDecl) defs.head).mods.flags & ENUM) != 0) { 2267 JCVariableDecl var = (JCVariableDecl)defs.head; 2268 visitEnumConstantDef(var, nextOrdinal++); 2269 values.append(make.QualIdent(var.sym)); 2270 enumDefs.append(var); 2271 } else { 2272 otherDefs.append(defs.head); 2273 } 2274 } 2275 2276 // private static final T[] #VALUES = { a, b, c }; 2277 Name valuesName = names.fromString(target.syntheticNameChar() + "VALUES"); 2278 while (tree.sym.members().lookup(valuesName).scope != null) // avoid name clash 2279 valuesName = names.fromString(valuesName + "" + target.syntheticNameChar()); 2280 Type arrayType = new ArrayType(types.erasure(tree.type), syms.arrayClass); 2281 VarSymbol valuesVar = new VarSymbol(PRIVATE|FINAL|STATIC|SYNTHETIC, 2282 valuesName, 2283 arrayType, 2284 tree.type.tsym); 2285 JCNewArray newArray = make.NewArray(make.Type(types.erasure(tree.type)), 2286 List.<JCExpression>nil(), 2287 values.toList()); 2288 newArray.type = arrayType; 2289 enumDefs.append(make.VarDef(valuesVar, newArray)); 2290 tree.sym.members().enter(valuesVar); 2291 2292 Symbol valuesSym = lookupMethod(tree.pos(), names.values, 2293 tree.type, List.<Type>nil()); 2294 List<JCStatement> valuesBody; 2295 if (useClone()) { 2296 // return (T[]) $VALUES.clone(); 2297 JCTypeCast valuesResult = 2298 make.TypeCast(valuesSym.type.getReturnType(), 2299 make.App(make.Select(make.Ident(valuesVar), 2300 syms.arrayCloneMethod))); 2301 valuesBody = List.<JCStatement>of(make.Return(valuesResult)); 2302 } else { 2303 // template: T[] $result = new T[$values.length]; 2304 Name resultName = names.fromString(target.syntheticNameChar() + "result"); 2305 while (tree.sym.members().lookup(resultName).scope != null) // avoid name clash 2306 resultName = names.fromString(resultName + "" + target.syntheticNameChar()); 2307 VarSymbol resultVar = new VarSymbol(FINAL|SYNTHETIC, 2308 resultName, 2309 arrayType, 2310 valuesSym); 2311 JCNewArray resultArray = make.NewArray(make.Type(types.erasure(tree.type)), 2312 List.of(make.Select(make.Ident(valuesVar), syms.lengthVar)), 2313 null); 2314 resultArray.type = arrayType; 2315 JCVariableDecl decl = make.VarDef(resultVar, resultArray); 2316 2317 // template: System.arraycopy($VALUES, 0, $result, 0, $VALUES.length); 2318 if (systemArraycopyMethod == null) { 2319 systemArraycopyMethod = 2320 new MethodSymbol(PUBLIC | STATIC, 2321 names.fromString("arraycopy"), 2322 new MethodType(List.<Type>of(syms.objectType, 2323 syms.intType, 2324 syms.objectType, 2325 syms.intType, 2326 syms.intType), 2327 syms.voidType, 2328 List.<Type>nil(), 2329 syms.methodClass), 2330 syms.systemType.tsym); 2331 } 2332 JCStatement copy = 2333 make.Exec(make.App(make.Select(make.Ident(syms.systemType.tsym), 2334 systemArraycopyMethod), 2335 List.of(make.Ident(valuesVar), make.Literal(0), 2336 make.Ident(resultVar), make.Literal(0), 2337 make.Select(make.Ident(valuesVar), syms.lengthVar)))); 2338 2339 // template: return $result; 2340 JCStatement ret = make.Return(make.Ident(resultVar)); 2341 valuesBody = List.<JCStatement>of(decl, copy, ret); 2342 } 2343 2344 JCMethodDecl valuesDef = 2345 make.MethodDef((MethodSymbol)valuesSym, make.Block(0, valuesBody)); 2346 2347 enumDefs.append(valuesDef); 2348 2349 if (debugLower) 2350 System.err.println(tree.sym + ".valuesDef = " + valuesDef); 2351 2352 /** The template for the following code is: 2353 * 2354 * public static E valueOf(String name) { 2355 * return (E)Enum.valueOf(E.class, name); 2356 * } 2357 * 2358 * where E is tree.sym 2359 */ 2360 MethodSymbol valueOfSym = lookupMethod(tree.pos(), 2361 names.valueOf, 2362 tree.sym.type, 2363 List.of(syms.stringType)); 2364 assert (valueOfSym.flags() & STATIC) != 0; 2365 VarSymbol nameArgSym = valueOfSym.params.head; 2366 JCIdent nameVal = make.Ident(nameArgSym); 2367 JCStatement enum_ValueOf = 2368 make.Return(make.TypeCast(tree.sym.type, 2369 makeCall(make.Ident(syms.enumSym), 2370 names.valueOf, 2371 List.of(e_class, nameVal)))); 2372 JCMethodDecl valueOf = make.MethodDef(valueOfSym, 2373 make.Block(0, List.of(enum_ValueOf))); 2374 nameVal.sym = valueOf.params.head.sym; 2375 if (debugLower) 2376 System.err.println(tree.sym + ".valueOf = " + valueOf); 2377 enumDefs.append(valueOf); 2378 2379 enumDefs.appendList(otherDefs.toList()); 2380 tree.defs = enumDefs.toList(); 2381 2382 // Add the necessary members for the EnumCompatibleMode 2383 if (target.compilerBootstrap(tree.sym)) { 2384 addEnumCompatibleMembers(tree); 2385 } 2386 } 2387 // where 2388 private MethodSymbol systemArraycopyMethod; 2389 private boolean useClone() { 2390 try { 2391 Scope.Entry e = syms.objectType.tsym.members().lookup(names.clone); 2392 return (e.sym != null); 2393 } 2394 catch (CompletionFailure e) { 2395 return false; 2396 } 2397 } 2398 2399 /** Translate an enumeration constant and its initializer. */ 2400 private void visitEnumConstantDef(JCVariableDecl var, int ordinal) { 2401 JCNewClass varDef = (JCNewClass)var.init; 2402 varDef.args = varDef.args. 2403 prepend(makeLit(syms.intType, ordinal)). 2404 prepend(makeLit(syms.stringType, var.name.toString())); 2405 } 2406 2407 public void visitMethodDef(JCMethodDecl tree) { 2408 if (tree.name == names.init && (currentClass.flags_field&ENUM) != 0) { 2409 // Add "String $enum$name, int $enum$ordinal" to the beginning of the 2410 // argument list for each constructor of an enum. 2411 JCVariableDecl nameParam = make_at(tree.pos()). 2412 Param(names.fromString(target.syntheticNameChar() + 2413 "enum" + target.syntheticNameChar() + "name"), 2414 syms.stringType, tree.sym); 2415 nameParam.mods.flags |= SYNTHETIC; nameParam.sym.flags_field |= SYNTHETIC; 2416 2417 JCVariableDecl ordParam = make. 2418 Param(names.fromString(target.syntheticNameChar() + 2419 "enum" + target.syntheticNameChar() + 2420 "ordinal"), 2421 syms.intType, tree.sym); 2422 ordParam.mods.flags |= SYNTHETIC; ordParam.sym.flags_field |= SYNTHETIC; 2423 2424 tree.params = tree.params.prepend(ordParam).prepend(nameParam); 2425 2426 MethodSymbol m = tree.sym; 2427 Type olderasure = m.erasure(types); 2428 m.erasure_field = new MethodType( 2429 olderasure.getParameterTypes().prepend(syms.intType).prepend(syms.stringType), 2430 olderasure.getReturnType(), 2431 olderasure.getThrownTypes(), 2432 syms.methodClass); 2433 2434 if (target.compilerBootstrap(m.owner)) { 2435 // Initialize synthetic name field 2436 Symbol nameVarSym = lookupSynthetic(names.fromString("$name"), 2437 tree.sym.owner.members()); 2438 JCIdent nameIdent = make.Ident(nameParam.sym); 2439 JCIdent id1 = make.Ident(nameVarSym); 2440 JCAssign newAssign = make.Assign(id1, nameIdent); 2441 newAssign.type = id1.type; 2442 JCExpressionStatement nameAssign = make.Exec(newAssign); 2443 nameAssign.type = id1.type; 2444 tree.body.stats = tree.body.stats.prepend(nameAssign); 2445 2446 // Initialize synthetic ordinal field 2447 Symbol ordinalVarSym = lookupSynthetic(names.fromString("$ordinal"), 2448 tree.sym.owner.members()); 2449 JCIdent ordIdent = make.Ident(ordParam.sym); 2450 id1 = make.Ident(ordinalVarSym); 2451 newAssign = make.Assign(id1, ordIdent); 2452 newAssign.type = id1.type; 2453 JCExpressionStatement ordinalAssign = make.Exec(newAssign); 2454 ordinalAssign.type = id1.type; 2455 tree.body.stats = tree.body.stats.prepend(ordinalAssign); 2456 } 2457 } 2458 2459 JCMethodDecl prevMethodDef = currentMethodDef; 2460 MethodSymbol prevMethodSym = currentMethodSym; 2461 try { 2462 currentMethodDef = tree; 2463 currentMethodSym = tree.sym; 2464 visitMethodDefInternal(tree); 2465 } finally { 2466 currentMethodDef = prevMethodDef; 2467 currentMethodSym = prevMethodSym; 2468 } 2469 } 2470 //where 2471 private void visitMethodDefInternal(JCMethodDecl tree) { 2472 if (tree.name == names.init && 2473 (currentClass.isInner() || 2474 (currentClass.owner.kind & (VAR | MTH)) != 0)) { 2475 // We are seeing a constructor of an inner class. 2476 MethodSymbol m = tree.sym; 2477 2478 // Push a new proxy scope for constructor parameters. 2479 // and create definitions for any this$n and proxy parameters. 2480 proxies = proxies.dup(m); 2481 List<VarSymbol> prevOuterThisStack = outerThisStack; 2482 List<VarSymbol> fvs = freevars(currentClass); 2483 JCVariableDecl otdef = null; 2484 if (currentClass.hasOuterInstance()) 2485 otdef = outerThisDef(tree.pos, m); 2486 List<JCVariableDecl> fvdefs = freevarDefs(tree.pos, fvs, m); 2487 2488 // Recursively translate result type, parameters and thrown list. 2489 tree.restype = translate(tree.restype); 2490 tree.params = translateVarDefs(tree.params); 2491 tree.thrown = translate(tree.thrown); 2492 2493 // when compiling stubs, don't process body 2494 if (tree.body == null) { 2495 result = tree; 2496 return; 2497 } 2498 2499 // Add this$n (if needed) in front of and free variables behind 2500 // constructor parameter list. 2501 tree.params = tree.params.appendList(fvdefs); 2502 if (currentClass.hasOuterInstance()) 2503 tree.params = tree.params.prepend(otdef); 2504 2505 // If this is an initial constructor, i.e., it does not start with 2506 // this(...), insert initializers for this$n and proxies 2507 // before (pre-1.4, after) the call to superclass constructor. 2508 JCStatement selfCall = translate(tree.body.stats.head); 2509 2510 List<JCStatement> added = List.nil(); 2511 if (fvs.nonEmpty()) { 2512 List<Type> addedargtypes = List.nil(); 2513 for (List<VarSymbol> l = fvs; l.nonEmpty(); l = l.tail) { 2514 if (TreeInfo.isInitialConstructor(tree)) 2515 added = added.prepend( 2516 initField(tree.body.pos, proxyName(l.head.name))); 2517 addedargtypes = addedargtypes.prepend(l.head.erasure(types)); 2518 } 2519 Type olderasure = m.erasure(types); 2520 m.erasure_field = new MethodType( 2521 olderasure.getParameterTypes().appendList(addedargtypes), 2522 olderasure.getReturnType(), 2523 olderasure.getThrownTypes(), 2524 syms.methodClass); 2525 } 2526 if (currentClass.hasOuterInstance() && 2527 TreeInfo.isInitialConstructor(tree)) 2528 { 2529 added = added.prepend(initOuterThis(tree.body.pos)); 2530 } 2531 2532 // pop local variables from proxy stack 2533 proxies = proxies.leave(); 2534 2535 // recursively translate following local statements and 2536 // combine with this- or super-call 2537 List<JCStatement> stats = translate(tree.body.stats.tail); 2538 if (target.initializeFieldsBeforeSuper()) 2539 tree.body.stats = stats.prepend(selfCall).prependList(added); 2540 else 2541 tree.body.stats = stats.prependList(added).prepend(selfCall); 2542 2543 outerThisStack = prevOuterThisStack; 2544 } else { 2545 super.visitMethodDef(tree); 2546 } 2547 result = tree; 2548 } 2549 2550 public void visitAnnotatedType(JCAnnotatedType tree) { 2551 tree.underlyingType = translate(tree.underlyingType); 2552 result = tree.underlyingType; 2553 } 2554 2555 public void visitTypeCast(JCTypeCast tree) { 2556 tree.clazz = translate(tree.clazz); 2557 if (tree.type.isPrimitive() != tree.expr.type.isPrimitive()) 2558 tree.expr = translate(tree.expr, tree.type); 2559 else 2560 tree.expr = translate(tree.expr); 2561 result = tree; 2562 } 2563 2564 public void visitNewClass(JCNewClass tree) { 2565 ClassSymbol c = (ClassSymbol)tree.constructor.owner; 2566 2567 // Box arguments, if necessary 2568 boolean isEnum = (tree.constructor.owner.flags() & ENUM) != 0; 2569 List<Type> argTypes = tree.constructor.type.getParameterTypes(); 2570 if (isEnum) argTypes = argTypes.prepend(syms.intType).prepend(syms.stringType); 2571 tree.args = boxArgs(argTypes, tree.args, tree.varargsElement); 2572 tree.varargsElement = null; 2573 2574 // If created class is local, add free variables after 2575 // explicit constructor arguments. 2576 if ((c.owner.kind & (VAR | MTH)) != 0) { 2577 tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c))); 2578 } 2579 2580 // If an access constructor is used, append null as a last argument. 2581 Symbol constructor = accessConstructor(tree.pos(), tree.constructor); 2582 if (constructor != tree.constructor) { 2583 tree.args = tree.args.append(makeNull()); 2584 tree.constructor = constructor; 2585 } 2586 2587 // If created class has an outer instance, and new is qualified, pass 2588 // qualifier as first argument. If new is not qualified, pass the 2589 // correct outer instance as first argument. 2590 if (c.hasOuterInstance()) { 2591 JCExpression thisArg; 2592 if (tree.encl != null) { 2593 thisArg = attr.makeNullCheck(translate(tree.encl)); 2594 thisArg.type = tree.encl.type; 2595 } else if ((c.owner.kind & (MTH | VAR)) != 0) { 2596 // local class 2597 thisArg = makeThis(tree.pos(), c.type.getEnclosingType().tsym); 2598 } else { 2599 // nested class 2600 thisArg = makeOwnerThis(tree.pos(), c, false); 2601 } 2602 tree.args = tree.args.prepend(thisArg); 2603 } 2604 tree.encl = null; 2605 2606 // If we have an anonymous class, create its flat version, rather 2607 // than the class or interface following new. 2608 if (tree.def != null) { 2609 translate(tree.def); 2610 tree.clazz = access(make_at(tree.clazz.pos()).Ident(tree.def.sym)); 2611 tree.def = null; 2612 } else { 2613 tree.clazz = access(c, tree.clazz, enclOp, false); 2614 } 2615 result = tree; 2616 } 2617 2618 // Simplify conditionals with known constant controlling expressions. 2619 // This allows us to avoid generating supporting declarations for 2620 // the dead code, which will not be eliminated during code generation. 2621 // Note that Flow.isFalse and Flow.isTrue only return true 2622 // for constant expressions in the sense of JLS 15.27, which 2623 // are guaranteed to have no side-effects. More aggressive 2624 // constant propagation would require that we take care to 2625 // preserve possible side-effects in the condition expression. 2626 2627 /** Visitor method for conditional expressions. 2628 */ 2629 public void visitConditional(JCConditional tree) { 2630 JCTree cond = tree.cond = translate(tree.cond, syms.booleanType); 2631 if (cond.type.isTrue()) { 2632 result = convert(translate(tree.truepart, tree.type), tree.type); 2633 } else if (cond.type.isFalse()) { 2634 result = convert(translate(tree.falsepart, tree.type), tree.type); 2635 } else { 2636 // Condition is not a compile-time constant. 2637 tree.truepart = translate(tree.truepart, tree.type); 2638 tree.falsepart = translate(tree.falsepart, tree.type); 2639 result = tree; 2640 } 2641 } 2642 //where 2643 private JCTree convert(JCTree tree, Type pt) { 2644 if (tree.type == pt) return tree; 2645 JCTree result = make_at(tree.pos()).TypeCast(make.Type(pt), (JCExpression)tree); 2646 result.type = (tree.type.constValue() != null) ? cfolder.coerce(tree.type, pt) 2647 : pt; 2648 return result; 2649 } 2650 2651 /** Visitor method for if statements. 2652 */ 2653 public void visitIf(JCIf tree) { 2654 JCTree cond = tree.cond = translate(tree.cond, syms.booleanType); 2655 if (cond.type.isTrue()) { 2656 result = translate(tree.thenpart); 2657 } else if (cond.type.isFalse()) { 2658 if (tree.elsepart != null) { 2659 result = translate(tree.elsepart); 2660 } else { 2661 result = make.Skip(); 2662 } 2663 } else { 2664 // Condition is not a compile-time constant. 2665 tree.thenpart = translate(tree.thenpart); 2666 tree.elsepart = translate(tree.elsepart); 2667 result = tree; 2668 } 2669 } 2670 2671 /** Visitor method for assert statements. Translate them away. 2672 */ 2673 public void visitAssert(JCAssert tree) { 2674 DiagnosticPosition detailPos = (tree.detail == null) ? tree.pos() : tree.detail.pos(); 2675 tree.cond = translate(tree.cond, syms.booleanType); 2676 if (!tree.cond.type.isTrue()) { 2677 JCExpression cond = assertFlagTest(tree.pos()); 2678 List<JCExpression> exnArgs = (tree.detail == null) ? 2679 List.<JCExpression>nil() : List.of(translate(tree.detail)); 2680 if (!tree.cond.type.isFalse()) { 2681 cond = makeBinary 2682 (JCTree.AND, 2683 cond, 2684 makeUnary(JCTree.NOT, tree.cond)); 2685 } 2686 result = 2687 make.If(cond, 2688 make_at(detailPos). 2689 Throw(makeNewClass(syms.assertionErrorType, exnArgs)), 2690 null); 2691 } else { 2692 result = make.Skip(); 2693 } 2694 } 2695 2696 public void visitApply(JCMethodInvocation tree) { 2697 Symbol meth = TreeInfo.symbol(tree.meth); 2698 List<Type> argtypes = meth.type.getParameterTypes(); 2699 if (allowEnums && 2700 meth.name==names.init && 2701 meth.owner == syms.enumSym) 2702 argtypes = argtypes.tail.tail; 2703 tree.args = boxArgs(argtypes, tree.args, tree.varargsElement); 2704 tree.varargsElement = null; 2705 Name methName = TreeInfo.name(tree.meth); 2706 if (meth.name==names.init) { 2707 // We are seeing a this(...) or super(...) constructor call. 2708 // If an access constructor is used, append null as a last argument. 2709 Symbol constructor = accessConstructor(tree.pos(), meth); 2710 if (constructor != meth) { 2711 tree.args = tree.args.append(makeNull()); 2712 TreeInfo.setSymbol(tree.meth, constructor); 2713 } 2714 2715 // If we are calling a constructor of a local class, add 2716 // free variables after explicit constructor arguments. 2717 ClassSymbol c = (ClassSymbol)constructor.owner; 2718 if ((c.owner.kind & (VAR | MTH)) != 0) { 2719 tree.args = tree.args.appendList(loadFreevars(tree.pos(), freevars(c))); 2720 } 2721 2722 // If we are calling a constructor of an enum class, pass 2723 // along the name and ordinal arguments 2724 if ((c.flags_field&ENUM) != 0 || c.getQualifiedName() == names.java_lang_Enum) { 2725 List<JCVariableDecl> params = currentMethodDef.params; 2726 if (currentMethodSym.owner.hasOuterInstance()) 2727 params = params.tail; // drop this$n 2728 tree.args = tree.args 2729 .prepend(make_at(tree.pos()).Ident(params.tail.head.sym)) // ordinal 2730 .prepend(make.Ident(params.head.sym)); // name 2731 } 2732 2733 // If we are calling a constructor of a class with an outer 2734 // instance, and the call 2735 // is qualified, pass qualifier as first argument in front of 2736 // the explicit constructor arguments. If the call 2737 // is not qualified, pass the correct outer instance as 2738 // first argument. 2739 if (c.hasOuterInstance()) { 2740 JCExpression thisArg; 2741 if (tree.meth.getTag() == JCTree.SELECT) { 2742 thisArg = attr. 2743 makeNullCheck(translate(((JCFieldAccess) tree.meth).selected)); 2744 tree.meth = make.Ident(constructor); 2745 ((JCIdent) tree.meth).name = methName; 2746 } else if ((c.owner.kind & (MTH | VAR)) != 0 || methName == names._this){ 2747 // local class or this() call 2748 thisArg = makeThis(tree.meth.pos(), c.type.getEnclosingType().tsym); 2749 } else { 2750 // super() call of nested class 2751 thisArg = makeOwnerThis(tree.meth.pos(), c, false); 2752 } 2753 tree.args = tree.args.prepend(thisArg); 2754 } 2755 } else { 2756 // We are seeing a normal method invocation; translate this as usual. 2757 tree.meth = translate(tree.meth); 2758 2759 // If the translated method itself is an Apply tree, we are 2760 // seeing an access method invocation. In this case, append 2761 // the method arguments to the arguments of the access method. 2762 if (tree.meth.getTag() == JCTree.APPLY) { 2763 JCMethodInvocation app = (JCMethodInvocation)tree.meth; 2764 app.args = tree.args.prependList(app.args); 2765 result = app; 2766 return; 2767 } 2768 } 2769 result = tree; 2770 } 2771 2772 List<JCExpression> boxArgs(List<Type> parameters, List<JCExpression> _args, Type varargsElement) { 2773 List<JCExpression> args = _args; 2774 if (parameters.isEmpty()) return args; 2775 boolean anyChanges = false; 2776 ListBuffer<JCExpression> result = new ListBuffer<JCExpression>(); 2777 while (parameters.tail.nonEmpty()) { 2778 JCExpression arg = translate(args.head, parameters.head); 2779 anyChanges |= (arg != args.head); 2780 result.append(arg); 2781 args = args.tail; 2782 parameters = parameters.tail; 2783 } 2784 Type parameter = parameters.head; 2785 if (varargsElement != null) { 2786 anyChanges = true; 2787 ListBuffer<JCExpression> elems = new ListBuffer<JCExpression>(); 2788 while (args.nonEmpty()) { 2789 JCExpression arg = translate(args.head, varargsElement); 2790 elems.append(arg); 2791 args = args.tail; 2792 } 2793 JCNewArray boxedArgs = make.NewArray(make.Type(varargsElement), 2794 List.<JCExpression>nil(), 2795 elems.toList()); 2796 boxedArgs.type = new ArrayType(varargsElement, syms.arrayClass); 2797 result.append(boxedArgs); 2798 } else { 2799 if (args.length() != 1) throw new AssertionError(args); 2800 JCExpression arg = translate(args.head, parameter); 2801 anyChanges |= (arg != args.head); 2802 result.append(arg); 2803 if (!anyChanges) return _args; 2804 } 2805 return result.toList(); 2806 } 2807 2808 /** Expand a boxing or unboxing conversion if needed. */ 2809 @SuppressWarnings("unchecked") // XXX unchecked 2810 <T extends JCTree> T boxIfNeeded(T tree, Type type) { 2811 boolean havePrimitive = tree.type.isPrimitive(); 2812 if (havePrimitive == type.isPrimitive()) 2813 return tree; 2814 if (havePrimitive) { 2815 Type unboxedTarget = types.unboxedType(type); 2816 if (unboxedTarget.tag != NONE) { 2817 if (!types.isSubtype(tree.type, unboxedTarget)) //e.g. Character c = 89; 2818 tree.type = unboxedTarget.constType(tree.type.constValue()); 2819 return (T)boxPrimitive((JCExpression)tree, type); 2820 } else { 2821 tree = (T)boxPrimitive((JCExpression)tree); 2822 } 2823 } else { 2824 tree = (T)unbox((JCExpression)tree, type); 2825 } 2826 return tree; 2827 } 2828 2829 /** Box up a single primitive expression. */ 2830 JCExpression boxPrimitive(JCExpression tree) { 2831 return boxPrimitive(tree, types.boxedClass(tree.type).type); 2832 } 2833 2834 /** Box up a single primitive expression. */ 2835 JCExpression boxPrimitive(JCExpression tree, Type box) { 2836 make_at(tree.pos()); 2837 if (target.boxWithConstructors()) { 2838 Symbol ctor = lookupConstructor(tree.pos(), 2839 box, 2840 List.<Type>nil() 2841 .prepend(tree.type)); 2842 return make.Create(ctor, List.of(tree)); 2843 } else { 2844 Symbol valueOfSym = lookupMethod(tree.pos(), 2845 names.valueOf, 2846 box, 2847 List.<Type>nil() 2848 .prepend(tree.type)); 2849 return make.App(make.QualIdent(valueOfSym), List.of(tree)); 2850 } 2851 } 2852 2853 /** Unbox an object to a primitive value. */ 2854 JCExpression unbox(JCExpression tree, Type primitive) { 2855 Type unboxedType = types.unboxedType(tree.type); 2856 // note: the "primitive" parameter is not used. There muse be 2857 // a conversion from unboxedType to primitive. 2858 make_at(tree.pos()); 2859 Symbol valueSym = lookupMethod(tree.pos(), 2860 unboxedType.tsym.name.append(names.Value), // x.intValue() 2861 tree.type, 2862 List.<Type>nil()); 2863 return make.App(make.Select(tree, valueSym)); 2864 } 2865 2866 /** Visitor method for parenthesized expressions. 2867 * If the subexpression has changed, omit the parens. 2868 */ 2869 public void visitParens(JCParens tree) { 2870 JCTree expr = translate(tree.expr); 2871 result = ((expr == tree.expr) ? tree : expr); 2872 } 2873 2874 public void visitIndexed(JCArrayAccess tree) { 2875 tree.indexed = translate(tree.indexed); 2876 tree.index = translate(tree.index, syms.intType); 2877 result = tree; 2878 } 2879 2880 public void visitAssign(JCAssign tree) { 2881 tree.lhs = translate(tree.lhs, tree); 2882 tree.rhs = translate(tree.rhs, tree.lhs.type); 2883 2884 // If translated left hand side is an Apply, we are 2885 // seeing an access method invocation. In this case, append 2886 // right hand side as last argument of the access method. 2887 if (tree.lhs.getTag() == JCTree.APPLY) { 2888 JCMethodInvocation app = (JCMethodInvocation)tree.lhs; 2889 app.args = List.of(tree.rhs).prependList(app.args); 2890 result = app; 2891 } else { 2892 result = tree; 2893 } 2894 } 2895 2896 public void visitAssignop(final JCAssignOp tree) { 2897 if (!tree.lhs.type.isPrimitive() && 2898 tree.operator.type.getReturnType().isPrimitive()) { 2899 // boxing required; need to rewrite as x = (unbox typeof x)(x op y); 2900 // or if x == (typeof x)z then z = (unbox typeof x)((typeof x)z op y) 2901 // (but without recomputing x) 2902 JCTree newTree = abstractLval(tree.lhs, new TreeBuilder() { 2903 public JCTree build(final JCTree lhs) { 2904 int newTag = tree.getTag() - JCTree.ASGOffset; 2905 // Erasure (TransTypes) can change the type of 2906 // tree.lhs. However, we can still get the 2907 // unerased type of tree.lhs as it is stored 2908 // in tree.type in Attr. 2909 Symbol newOperator = rs.resolveBinaryOperator(tree.pos(), 2910 newTag, 2911 attrEnv, 2912 tree.type, 2913 tree.rhs.type); 2914 JCExpression expr = (JCExpression)lhs; 2915 if (expr.type != tree.type) 2916 expr = make.TypeCast(tree.type, expr); 2917 JCBinary opResult = make.Binary(newTag, expr, tree.rhs); 2918 opResult.operator = newOperator; 2919 opResult.type = newOperator.type.getReturnType(); 2920 JCTypeCast newRhs = make.TypeCast(types.unboxedType(tree.type), 2921 opResult); 2922 return make.Assign((JCExpression)lhs, newRhs).setType(tree.type); 2923 } 2924 }); 2925 result = translate(newTree); 2926 return; 2927 } 2928 tree.lhs = translate(tree.lhs, tree); 2929 tree.rhs = translate(tree.rhs, tree.operator.type.getParameterTypes().tail.head); 2930 2931 // If translated left hand side is an Apply, we are 2932 // seeing an access method invocation. In this case, append 2933 // right hand side as last argument of the access method. 2934 if (tree.lhs.getTag() == JCTree.APPLY) { 2935 JCMethodInvocation app = (JCMethodInvocation)tree.lhs; 2936 // if operation is a += on strings, 2937 // make sure to convert argument to string 2938 JCExpression rhs = (((OperatorSymbol)tree.operator).opcode == string_add) 2939 ? makeString(tree.rhs) 2940 : tree.rhs; 2941 app.args = List.of(rhs).prependList(app.args); 2942 result = app; 2943 } else { 2944 result = tree; 2945 } 2946 } 2947 2948 /** Lower a tree of the form e++ or e-- where e is an object type */ 2949 JCTree lowerBoxedPostop(final JCUnary tree) { 2950 // translate to tmp1=lval(e); tmp2=tmp1; tmp1 OP 1; tmp2 2951 // or 2952 // translate to tmp1=lval(e); tmp2=tmp1; (typeof tree)tmp1 OP 1; tmp2 2953 // where OP is += or -= 2954 final boolean cast = TreeInfo.skipParens(tree.arg).getTag() == JCTree.TYPECAST; 2955 return abstractLval(tree.arg, new TreeBuilder() { 2956 public JCTree build(final JCTree tmp1) { 2957 return abstractRval(tmp1, tree.arg.type, new TreeBuilder() { 2958 public JCTree build(final JCTree tmp2) { 2959 int opcode = (tree.getTag() == JCTree.POSTINC) 2960 ? JCTree.PLUS_ASG : JCTree.MINUS_ASG; 2961 JCTree lhs = cast 2962 ? make.TypeCast(tree.arg.type, (JCExpression)tmp1) 2963 : tmp1; 2964 JCTree update = makeAssignop(opcode, 2965 lhs, 2966 make.Literal(1)); 2967 return makeComma(update, tmp2); 2968 } 2969 }); 2970 } 2971 }); 2972 } 2973 2974 public void visitUnary(JCUnary tree) { 2975 boolean isUpdateOperator = 2976 JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC; 2977 if (isUpdateOperator && !tree.arg.type.isPrimitive()) { 2978 switch(tree.getTag()) { 2979 case JCTree.PREINC: // ++ e 2980 // translate to e += 1 2981 case JCTree.PREDEC: // -- e 2982 // translate to e -= 1 2983 { 2984 int opcode = (tree.getTag() == JCTree.PREINC) 2985 ? JCTree.PLUS_ASG : JCTree.MINUS_ASG; 2986 JCAssignOp newTree = makeAssignop(opcode, 2987 tree.arg, 2988 make.Literal(1)); 2989 result = translate(newTree, tree.type); 2990 return; 2991 } 2992 case JCTree.POSTINC: // e ++ 2993 case JCTree.POSTDEC: // e -- 2994 { 2995 result = translate(lowerBoxedPostop(tree), tree.type); 2996 return; 2997 } 2998 } 2999 throw new AssertionError(tree); 3000 } 3001 3002 tree.arg = boxIfNeeded(translate(tree.arg, tree), tree.type); 3003 3004 if (tree.getTag() == JCTree.NOT && tree.arg.type.constValue() != null) { 3005 tree.type = cfolder.fold1(bool_not, tree.arg.type); 3006 } 3007 3008 // If translated left hand side is an Apply, we are 3009 // seeing an access method invocation. In this case, return 3010 // that access method invocation as result. 3011 if (isUpdateOperator && tree.arg.getTag() == JCTree.APPLY) { 3012 result = tree.arg; 3013 } else { 3014 result = tree; 3015 } 3016 } 3017 3018 public void visitBinary(JCBinary tree) { 3019 List<Type> formals = tree.operator.type.getParameterTypes(); 3020 JCTree lhs = tree.lhs = translate(tree.lhs, formals.head); 3021 switch (tree.getTag()) { 3022 case JCTree.OR: 3023 if (lhs.type.isTrue()) { 3024 result = lhs; 3025 return; 3026 } 3027 if (lhs.type.isFalse()) { 3028 result = translate(tree.rhs, formals.tail.head); 3029 return; 3030 } 3031 break; 3032 case JCTree.AND: 3033 if (lhs.type.isFalse()) { 3034 result = lhs; 3035 return; 3036 } 3037 if (lhs.type.isTrue()) { 3038 result = translate(tree.rhs, formals.tail.head); 3039 return; 3040 } 3041 break; 3042 } 3043 tree.rhs = translate(tree.rhs, formals.tail.head); 3044 result = tree; 3045 } 3046 3047 public void visitIdent(JCIdent tree) { 3048 result = access(tree.sym, tree, enclOp, false); 3049 } 3050 3051 /** Translate away the foreach loop. */ 3052 public void visitForeachLoop(JCEnhancedForLoop tree) { 3053 if (types.elemtype(tree.expr.type) == null) 3054 visitIterableForeachLoop(tree); 3055 else 3056 visitArrayForeachLoop(tree); 3057 } 3058 // where 3059 /** 3060 * A statement of the form 3061 * 3062 * <pre> 3063 * for ( T v : arrayexpr ) stmt; 3064 * </pre> 3065 * 3066 * (where arrayexpr is of an array type) gets translated to 3067 * 3068 * <pre> 3069 * for ( { arraytype #arr = arrayexpr; 3070 * int #len = array.length; 3071 * int #i = 0; }; 3072 * #i < #len; i$++ ) { 3073 * T v = arr$[#i]; 3074 * stmt; 3075 * } 3076 * </pre> 3077 * 3078 * where #arr, #len, and #i are freshly named synthetic local variables. 3079 */ 3080 private void visitArrayForeachLoop(JCEnhancedForLoop tree) { 3081 make_at(tree.expr.pos()); 3082 VarSymbol arraycache = new VarSymbol(0, 3083 names.fromString("arr" + target.syntheticNameChar()), 3084 tree.expr.type, 3085 currentMethodSym); 3086 JCStatement arraycachedef = make.VarDef(arraycache, tree.expr); 3087 VarSymbol lencache = new VarSymbol(0, 3088 names.fromString("len" + target.syntheticNameChar()), 3089 syms.intType, 3090 currentMethodSym); 3091 JCStatement lencachedef = make. 3092 VarDef(lencache, make.Select(make.Ident(arraycache), syms.lengthVar)); 3093 VarSymbol index = new VarSymbol(0, 3094 names.fromString("i" + target.syntheticNameChar()), 3095 syms.intType, 3096 currentMethodSym); 3097 3098 JCVariableDecl indexdef = make.VarDef(index, make.Literal(INT, 0)); 3099 indexdef.init.type = indexdef.type = syms.intType.constType(0); 3100 3101 List<JCStatement> loopinit = List.of(arraycachedef, lencachedef, indexdef); 3102 JCBinary cond = makeBinary(JCTree.LT, make.Ident(index), make.Ident(lencache)); 3103 3104 JCExpressionStatement step = make.Exec(makeUnary(JCTree.PREINC, make.Ident(index))); 3105 3106 Type elemtype = types.elemtype(tree.expr.type); 3107 JCExpression loopvarinit = make.Indexed(make.Ident(arraycache), 3108 make.Ident(index)).setType(elemtype); 3109 JCVariableDecl loopvardef = (JCVariableDecl)make.VarDef(tree.var.mods, 3110 tree.var.name, 3111 tree.var.vartype, 3112 loopvarinit).setType(tree.var.type); 3113 loopvardef.sym = tree.var.sym; 3114 JCBlock body = make. 3115 Block(0, List.of(loopvardef, tree.body)); 3116 3117 result = translate(make. 3118 ForLoop(loopinit, 3119 cond, 3120 List.of(step), 3121 body)); 3122 patchTargets(body, tree, result); 3123 } 3124 /** Patch up break and continue targets. */ 3125 private void patchTargets(JCTree body, final JCTree src, final JCTree dest) { 3126 class Patcher extends TreeScanner { 3127 public void visitBreak(JCBreak tree) { 3128 if (tree.target == src) 3129 tree.target = dest; 3130 } 3131 public void visitContinue(JCContinue tree) { 3132 if (tree.target == src) 3133 tree.target = dest; 3134 } 3135 public void visitClassDef(JCClassDecl tree) {} 3136 } 3137 new Patcher().scan(body); 3138 } 3139 /** 3140 * A statement of the form 3141 * 3142 * <pre> 3143 * for ( T v : coll ) stmt ; 3144 * </pre> 3145 * 3146 * (where coll implements Iterable<? extends T>) gets translated to 3147 * 3148 * <pre> 3149 * for ( Iterator<? extends T> #i = coll.iterator(); #i.hasNext(); ) { 3150 * T v = (T) #i.next(); 3151 * stmt; 3152 * } 3153 * </pre> 3154 * 3155 * where #i is a freshly named synthetic local variable. 3156 */ 3157 private void visitIterableForeachLoop(JCEnhancedForLoop tree) { 3158 make_at(tree.expr.pos()); 3159 Type iteratorTarget = syms.objectType; 3160 Type iterableType = types.asSuper(types.upperBound(tree.expr.type), 3161 syms.iterableType.tsym); 3162 if (iterableType.getTypeArguments().nonEmpty()) 3163 iteratorTarget = types.erasure(iterableType.getTypeArguments().head); 3164 Type eType = tree.expr.type; 3165 tree.expr.type = types.erasure(eType); 3166 if (eType.tag == TYPEVAR && eType.getUpperBound().isCompound()) 3167 tree.expr = make.TypeCast(types.erasure(iterableType), tree.expr); 3168 Symbol iterator = lookupMethod(tree.expr.pos(), 3169 names.iterator, 3170 types.erasure(syms.iterableType), 3171 List.<Type>nil()); 3172 VarSymbol itvar = new VarSymbol(0, names.fromString("i" + target.syntheticNameChar()), 3173 types.erasure(iterator.type.getReturnType()), 3174 currentMethodSym); 3175 JCStatement init = make. 3176 VarDef(itvar, 3177 make.App(make.Select(tree.expr, iterator))); 3178 Symbol hasNext = lookupMethod(tree.expr.pos(), 3179 names.hasNext, 3180 itvar.type, 3181 List.<Type>nil()); 3182 JCMethodInvocation cond = make.App(make.Select(make.Ident(itvar), hasNext)); 3183 Symbol next = lookupMethod(tree.expr.pos(), 3184 names.next, 3185 itvar.type, 3186 List.<Type>nil()); 3187 JCExpression vardefinit = make.App(make.Select(make.Ident(itvar), next)); 3188 if (tree.var.type.isPrimitive()) 3189 vardefinit = make.TypeCast(types.upperBound(iteratorTarget), vardefinit); 3190 else 3191 vardefinit = make.TypeCast(tree.var.type, vardefinit); 3192 JCVariableDecl indexDef = (JCVariableDecl)make.VarDef(tree.var.mods, 3193 tree.var.name, 3194 tree.var.vartype, 3195 vardefinit).setType(tree.var.type); 3196 indexDef.sym = tree.var.sym; 3197 JCBlock body = make.Block(0, List.of(indexDef, tree.body)); 3198 body.endpos = TreeInfo.endPos(tree.body); 3199 result = translate(make. 3200 ForLoop(List.of(init), 3201 cond, 3202 List.<JCExpressionStatement>nil(), 3203 body)); 3204 patchTargets(body, tree, result); 3205 } 3206 3207 public void visitVarDef(JCVariableDecl tree) { 3208 MethodSymbol oldMethodSym = currentMethodSym; 3209 tree.mods = translate(tree.mods); 3210 tree.vartype = translate(tree.vartype); 3211 if (currentMethodSym == null) { 3212 // A class or instance field initializer. 3213 currentMethodSym = 3214 new MethodSymbol((tree.mods.flags&STATIC) | BLOCK, 3215 names.empty, null, 3216 currentClass); 3217 } 3218 if (tree.init != null) tree.init = translate(tree.init, tree.type); 3219 result = tree; 3220 currentMethodSym = oldMethodSym; 3221 } 3222 3223 public void visitBlock(JCBlock tree) { 3224 MethodSymbol oldMethodSym = currentMethodSym; 3225 if (currentMethodSym == null) { 3226 // Block is a static or instance initializer. 3227 currentMethodSym = 3228 new MethodSymbol(tree.flags | BLOCK, 3229 names.empty, null, 3230 currentClass); 3231 } 3232 super.visitBlock(tree); 3233 currentMethodSym = oldMethodSym; 3234 } 3235 3236 public void visitDoLoop(JCDoWhileLoop tree) { 3237 tree.body = translate(tree.body); 3238 tree.cond = translate(tree.cond, syms.booleanType); 3239 result = tree; 3240 } 3241 3242 public void visitWhileLoop(JCWhileLoop tree) { 3243 tree.cond = translate(tree.cond, syms.booleanType); 3244 tree.body = translate(tree.body); 3245 result = tree; 3246 } 3247 3248 public void visitForLoop(JCForLoop tree) { 3249 tree.init = translate(tree.init); 3250 if (tree.cond != null) 3251 tree.cond = translate(tree.cond, syms.booleanType); 3252 tree.step = translate(tree.step); 3253 tree.body = translate(tree.body); 3254 result = tree; 3255 } 3256 3257 public void visitReturn(JCReturn tree) { 3258 if (tree.expr != null) 3259 tree.expr = translate(tree.expr, 3260 types.erasure(currentMethodDef 3261 .restype.type)); 3262 result = tree; 3263 } 3264 3265 public void visitSwitch(JCSwitch tree) { 3266 Type selsuper = types.supertype(tree.selector.type); 3267 boolean enumSwitch = selsuper != null && 3268 (tree.selector.type.tsym.flags() & ENUM) != 0; 3269 boolean stringSwitch = selsuper != null && 3270 types.isSameType(tree.selector.type, syms.stringType); 3271 Type target = enumSwitch ? tree.selector.type : 3272 (stringSwitch? syms.stringType : syms.intType); 3273 tree.selector = translate(tree.selector, target); 3274 tree.cases = translateCases(tree.cases); 3275 if (enumSwitch) { 3276 result = visitEnumSwitch(tree); 3277 } else if (stringSwitch) { 3278 result = visitStringSwitch(tree); 3279 } else { 3280 result = tree; 3281 } 3282 } 3283 3284 public JCTree visitEnumSwitch(JCSwitch tree) { 3285 TypeSymbol enumSym = tree.selector.type.tsym; 3286 EnumMapping map = mapForEnum(tree.pos(), enumSym); 3287 make_at(tree.pos()); 3288 Symbol ordinalMethod = lookupMethod(tree.pos(), 3289 names.ordinal, 3290 tree.selector.type, 3291 List.<Type>nil()); 3292 JCArrayAccess selector = make.Indexed(map.mapVar, 3293 make.App(make.Select(tree.selector, 3294 ordinalMethod))); 3295 ListBuffer<JCCase> cases = new ListBuffer<JCCase>(); 3296 for (JCCase c : tree.cases) { 3297 if (c.pat != null) { 3298 VarSymbol label = (VarSymbol)TreeInfo.symbol(c.pat); 3299 JCLiteral pat = map.forConstant(label); 3300 cases.append(make.Case(pat, c.stats)); 3301 } else { 3302 cases.append(c); 3303 } 3304 } 3305 JCSwitch enumSwitch = make.Switch(selector, cases.toList()); 3306 patchTargets(enumSwitch, tree, enumSwitch); 3307 return enumSwitch; 3308 } 3309 3310 public JCTree visitStringSwitch(JCSwitch tree) { 3311 List<JCCase> caseList = tree.getCases(); 3312 int alternatives = caseList.size(); 3313 3314 if (alternatives == 0) { // Strange but legal possibility 3315 return make.at(tree.pos()).Exec(attr.makeNullCheck(tree.getExpression())); 3316 } else { 3317 /* 3318 * The general approach used is to translate a single 3319 * string switch statement into a series of two chained 3320 * switch statements: the first a synthesized statement 3321 * switching on the argument string's hash value and 3322 * computing a string's position in the list of original 3323 * case labels, if any, followed by a second switch on the 3324 * computed integer value. The second switch has the same 3325 * code structure as the original string switch statement 3326 * except that the string case labels are replaced with 3327 * positional integer constants starting at 0. 3328 * 3329 * The first switch statement can be thought of as an 3330 * inlined map from strings to their position in the case 3331 * label list. An alternate implementation would use an 3332 * actual Map for this purpose, as done for enum switches. 3333 * 3334 * With some additional effort, it would be possible to 3335 * use a single switch statement on the hash code of the 3336 * argument, but care would need to be taken to preserve 3337 * the proper control flow in the presence of hash 3338 * collisions and other complications, such as 3339 * fallthroughs. Switch statements with one or two 3340 * alternatives could also be specially translated into 3341 * if-then statements to omit the computation of the hash 3342 * code. 3343 * 3344 * The generated code assumes that the hashing algorithm 3345 * of String is the same in the compilation environment as 3346 * in the environment the code will run in. The string 3347 * hashing algorithm in the SE JDK has been unchanged 3348 * since at least JDK 1.2. Since the algorithm has been 3349 * specified since that release as well, it is very 3350 * unlikely to be changed in the future. 3351 * 3352 * Different hashing algorithms, such as the length of the 3353 * strings or a perfect hashing algorithm over the 3354 * particular set of case labels, could potentially be 3355 * used instead of String.hashCode. 3356 */ 3357 3358 ListBuffer<JCStatement> stmtList = new ListBuffer<JCStatement>(); 3359 3360 // Map from String case labels to their original position in 3361 // the list of case labels. 3362 Map<String, Integer> caseLabelToPosition = 3363 new LinkedHashMap<String, Integer>(alternatives + 1, 1.0f); 3364 3365 // Map of hash codes to the string case labels having that hashCode. 3366 Map<Integer, Set<String>> hashToString = 3367 new LinkedHashMap<Integer, Set<String>>(alternatives + 1, 1.0f); 3368 3369 int casePosition = 0; 3370 for(JCCase oneCase : caseList) { 3371 JCExpression expression = oneCase.getExpression(); 3372 3373 if (expression != null) { // expression for a "default" case is null 3374 String labelExpr = (String) expression.type.constValue(); 3375 Integer mapping = caseLabelToPosition.put(labelExpr, casePosition); 3376 assert mapping == null; 3377 int hashCode = labelExpr.hashCode(); 3378 3379 Set<String> stringSet = hashToString.get(hashCode); 3380 if (stringSet == null) { 3381 stringSet = new LinkedHashSet<String>(1, 1.0f); 3382 stringSet.add(labelExpr); 3383 hashToString.put(hashCode, stringSet); 3384 } else { 3385 boolean added = stringSet.add(labelExpr); 3386 assert added; 3387 } 3388 } 3389 casePosition++; 3390 } 3391 3392 // Synthesize a switch statement that has the effect of 3393 // mapping from a string to the integer position of that 3394 // string in the list of case labels. This is done by 3395 // switching on the hashCode of the string followed by an 3396 // if-then-else chain comparing the input for equality 3397 // with all the case labels having that hash value. 3398 3399 /* 3400 * s$ = top of stack; 3401 * tmp$ = -1; 3402 * switch($s.hashCode()) { 3403 * case caseLabel.hashCode: 3404 * if (s$.equals("caseLabel_1") 3405 * tmp$ = caseLabelToPosition("caseLabel_1"); 3406 * else if (s$.equals("caseLabel_2")) 3407 * tmp$ = caseLabelToPosition("caseLabel_2"); 3408 * ... 3409 * break; 3410 * ... 3411 * } 3412 */ 3413 3414 VarSymbol dollar_s = new VarSymbol(FINAL|SYNTHETIC, 3415 names.fromString("s" + tree.pos + target.syntheticNameChar()), 3416 syms.stringType, 3417 currentMethodSym); 3418 stmtList.append(make.at(tree.pos()).VarDef(dollar_s, tree.getExpression()).setType(dollar_s.type)); 3419 3420 VarSymbol dollar_tmp = new VarSymbol(SYNTHETIC, 3421 names.fromString("tmp" + tree.pos + target.syntheticNameChar()), 3422 syms.intType, 3423 currentMethodSym); 3424 JCVariableDecl dollar_tmp_def = 3425 (JCVariableDecl)make.VarDef(dollar_tmp, make.Literal(INT, -1)).setType(dollar_tmp.type); 3426 dollar_tmp_def.init.type = dollar_tmp.type = syms.intType; 3427 stmtList.append(dollar_tmp_def); 3428 ListBuffer<JCCase> caseBuffer = ListBuffer.lb(); 3429 // hashCode will trigger nullcheck on original switch expression 3430 JCMethodInvocation hashCodeCall = makeCall(make.Ident(dollar_s), 3431 names.hashCode, 3432 List.<JCExpression>nil()).setType(syms.intType); 3433 JCSwitch switch1 = make.Switch(hashCodeCall, 3434 caseBuffer.toList()); 3435 for(Map.Entry<Integer, Set<String>> entry : hashToString.entrySet()) { 3436 int hashCode = entry.getKey(); 3437 Set<String> stringsWithHashCode = entry.getValue(); 3438 assert stringsWithHashCode.size() >= 1; 3439 3440 JCStatement elsepart = null; 3441 for(String caseLabel : stringsWithHashCode ) { 3442 JCMethodInvocation stringEqualsCall = makeCall(make.Ident(dollar_s), 3443 names.equals, 3444 List.<JCExpression>of(make.Literal(caseLabel))); 3445 elsepart = make.If(stringEqualsCall, 3446 make.Exec(make.Assign(make.Ident(dollar_tmp), 3447 make.Literal(caseLabelToPosition.get(caseLabel))). 3448 setType(dollar_tmp.type)), 3449 elsepart); 3450 } 3451 3452 ListBuffer<JCStatement> lb = ListBuffer.lb(); 3453 JCBreak breakStmt = make.Break(null); 3454 breakStmt.target = switch1; 3455 lb.append(elsepart).append(breakStmt); 3456 3457 caseBuffer.append(make.Case(make.Literal(hashCode), lb.toList())); 3458 } 3459 3460 switch1.cases = caseBuffer.toList(); 3461 stmtList.append(switch1); 3462 3463 // Make isomorphic switch tree replacing string labels 3464 // with corresponding integer ones from the label to 3465 // position map. 3466 3467 ListBuffer<JCCase> lb = ListBuffer.lb(); 3468 JCSwitch switch2 = make.Switch(make.Ident(dollar_tmp), lb.toList()); 3469 for(JCCase oneCase : caseList ) { 3470 // Rewire up old unlabeled break statements to the 3471 // replacement switch being created. 3472 patchTargets(oneCase, tree, switch2); 3473 3474 boolean isDefault = (oneCase.getExpression() == null); 3475 JCExpression caseExpr; 3476 if (isDefault) 3477 caseExpr = null; 3478 else { 3479 caseExpr = make.Literal(caseLabelToPosition.get((String)oneCase. 3480 getExpression(). 3481 type.constValue())); 3482 } 3483 3484 lb.append(make.Case(caseExpr, 3485 oneCase.getStatements())); 3486 } 3487 3488 switch2.cases = lb.toList(); 3489 stmtList.append(switch2); 3490 3491 return make.Block(0L, stmtList.toList()); 3492 } 3493 } 3494 3495 public void visitNewArray(JCNewArray tree) { 3496 tree.elemtype = translate(tree.elemtype); 3497 for (List<JCExpression> t = tree.dims; t.tail != null; t = t.tail) 3498 if (t.head != null) t.head = translate(t.head, syms.intType); 3499 tree.elems = translate(tree.elems, types.elemtype(tree.type)); 3500 result = tree; 3501 } 3502 3503 public void visitSelect(JCFieldAccess tree) { 3504 // need to special case-access of the form C.super.x 3505 // these will always need an access method. 3506 boolean qualifiedSuperAccess = 3507 tree.selected.getTag() == JCTree.SELECT && 3508 TreeInfo.name(tree.selected) == names._super; 3509 tree.selected = translate(tree.selected); 3510 if (tree.name == names._class) 3511 result = classOf(tree.selected); 3512 else if (tree.name == names._this || tree.name == names._super) 3513 result = makeThis(tree.pos(), tree.selected.type.tsym); 3514 else 3515 result = access(tree.sym, tree, enclOp, qualifiedSuperAccess); 3516 } 3517 3518 public void visitLetExpr(LetExpr tree) { 3519 tree.defs = translateVarDefs(tree.defs); 3520 tree.expr = translate(tree.expr, tree.type); 3521 result = tree; 3522 } 3523 3524 // There ought to be nothing to rewrite here; 3525 // we don't generate code. 3526 public void visitAnnotation(JCAnnotation tree) { 3527 result = tree; 3528 } 3529 3530 @Override 3531 public void visitTry(JCTry tree) { 3532 super.visitTry(tree); 3533 result = makeTry(tree); 3534 } 3535 3536 /************************************************************************** 3537 * main method 3538 *************************************************************************/ 3539 3540 /** Translate a toplevel class and return a list consisting of 3541 * the translated class and translated versions of all inner classes. 3542 * @param env The attribution environment current at the class definition. 3543 * We need this for resolving some additional symbols. 3544 * @param cdef The tree representing the class definition. 3545 */ 3546 public List<JCTree> translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) { 3547 ListBuffer<JCTree> translated = null; 3548 try { 3549 attrEnv = env; 3550 this.make = make; 3551 endPositions = env.toplevel.endPositions; 3552 currentClass = null; 3553 currentMethodDef = null; 3554 outermostClassDef = (cdef.getTag() == JCTree.CLASSDEF) ? (JCClassDecl)cdef : null; 3555 outermostMemberDef = null; 3556 this.translated = new ListBuffer<JCTree>(); 3557 classdefs = new HashMap<ClassSymbol,JCClassDecl>(); 3558 actualSymbols = new HashMap<Symbol,Symbol>(); 3559 freevarCache = new HashMap<ClassSymbol,List<VarSymbol>>(); 3560 proxies = new Scope(syms.noSymbol); 3561 outerThisStack = List.nil(); 3562 accessNums = new HashMap<Symbol,Integer>(); 3563 accessSyms = new HashMap<Symbol,MethodSymbol[]>(); 3564 accessConstrs = new HashMap<Symbol,MethodSymbol>(); 3565 accessConstrTags = List.nil(); 3566 accessed = new ListBuffer<Symbol>(); 3567 translate(cdef, (JCExpression)null); 3568 for (List<Symbol> l = accessed.toList(); l.nonEmpty(); l = l.tail) 3569 makeAccessible(l.head); 3570 for (EnumMapping map : enumSwitchMap.values()) 3571 map.translate(); 3572 checkConflicts(this.translated.toList()); 3573 checkAccessConstructorTags(); 3574 translated = this.translated; 3575 } finally { 3576 // note that recursive invocations of this method fail hard 3577 attrEnv = null; 3578 this.make = null; 3579 endPositions = null; 3580 currentClass = null; 3581 currentMethodDef = null; 3582 outermostClassDef = null; 3583 outermostMemberDef = null; 3584 this.translated = null; 3585 classdefs = null; 3586 actualSymbols = null; 3587 freevarCache = null; 3588 proxies = null; 3589 outerThisStack = null; 3590 accessNums = null; 3591 accessSyms = null; 3592 accessConstrs = null; 3593 accessConstrTags = null; 3594 accessed = null; 3595 enumSwitchMap.clear(); 3596 } 3597 return translated.toList(); 3598 } 3599 3600 ////////////////////////////////////////////////////////////// 3601 // The following contributed by Borland for bootstrapping purposes 3602 ////////////////////////////////////////////////////////////// 3603 private void addEnumCompatibleMembers(JCClassDecl cdef) { 3604 make_at(null); 3605 3606 // Add the special enum fields 3607 VarSymbol ordinalFieldSym = addEnumOrdinalField(cdef); 3608 VarSymbol nameFieldSym = addEnumNameField(cdef); 3609 3610 // Add the accessor methods for name and ordinal 3611 MethodSymbol ordinalMethodSym = addEnumFieldOrdinalMethod(cdef, ordinalFieldSym); 3612 MethodSymbol nameMethodSym = addEnumFieldNameMethod(cdef, nameFieldSym); 3613 3614 // Add the toString method 3615 addEnumToString(cdef, nameFieldSym); 3616 3617 // Add the compareTo method 3618 addEnumCompareTo(cdef, ordinalFieldSym); 3619 } 3620 3621 private VarSymbol addEnumOrdinalField(JCClassDecl cdef) { 3622 VarSymbol ordinal = new VarSymbol(PRIVATE|FINAL|SYNTHETIC, 3623 names.fromString("$ordinal"), 3624 syms.intType, 3625 cdef.sym); 3626 cdef.sym.members().enter(ordinal); 3627 cdef.defs = cdef.defs.prepend(make.VarDef(ordinal, null)); 3628 return ordinal; 3629 } 3630 3631 private VarSymbol addEnumNameField(JCClassDecl cdef) { 3632 VarSymbol name = new VarSymbol(PRIVATE|FINAL|SYNTHETIC, 3633 names.fromString("$name"), 3634 syms.stringType, 3635 cdef.sym); 3636 cdef.sym.members().enter(name); 3637 cdef.defs = cdef.defs.prepend(make.VarDef(name, null)); 3638 return name; 3639 } 3640 3641 private MethodSymbol addEnumFieldOrdinalMethod(JCClassDecl cdef, VarSymbol ordinalSymbol) { 3642 // Add the accessor methods for ordinal 3643 Symbol ordinalSym = lookupMethod(cdef.pos(), 3644 names.ordinal, 3645 cdef.type, 3646 List.<Type>nil()); 3647 3648 assert(ordinalSym != null); 3649 assert(ordinalSym instanceof MethodSymbol); 3650 3651 JCStatement ret = make.Return(make.Ident(ordinalSymbol)); 3652 cdef.defs = cdef.defs.append(make.MethodDef((MethodSymbol)ordinalSym, 3653 make.Block(0L, List.of(ret)))); 3654 3655 return (MethodSymbol)ordinalSym; 3656 } 3657 3658 private MethodSymbol addEnumFieldNameMethod(JCClassDecl cdef, VarSymbol nameSymbol) { 3659 // Add the accessor methods for name 3660 Symbol nameSym = lookupMethod(cdef.pos(), 3661 names._name, 3662 cdef.type, 3663 List.<Type>nil()); 3664 3665 assert(nameSym != null); 3666 assert(nameSym instanceof MethodSymbol); 3667 3668 JCStatement ret = make.Return(make.Ident(nameSymbol)); 3669 3670 cdef.defs = cdef.defs.append(make.MethodDef((MethodSymbol)nameSym, 3671 make.Block(0L, List.of(ret)))); 3672 3673 return (MethodSymbol)nameSym; 3674 } 3675 3676 private MethodSymbol addEnumToString(JCClassDecl cdef, 3677 VarSymbol nameSymbol) { 3678 Symbol toStringSym = lookupMethod(cdef.pos(), 3679 names.toString, 3680 cdef.type, 3681 List.<Type>nil()); 3682 3683 JCTree toStringDecl = null; 3684 if (toStringSym != null) 3685 toStringDecl = TreeInfo.declarationFor(toStringSym, cdef); 3686 3687 if (toStringDecl != null) 3688 return (MethodSymbol)toStringSym; 3689 3690 JCStatement ret = make.Return(make.Ident(nameSymbol)); 3691 3692 JCTree resTypeTree = make.Type(syms.stringType); 3693 3694 MethodType toStringType = new MethodType(List.<Type>nil(), 3695 syms.stringType, 3696 List.<Type>nil(), 3697 cdef.sym); 3698 toStringSym = new MethodSymbol(PUBLIC, 3699 names.toString, 3700 toStringType, 3701 cdef.type.tsym); 3702 toStringDecl = make.MethodDef((MethodSymbol)toStringSym, 3703 make.Block(0L, List.of(ret))); 3704 3705 cdef.defs = cdef.defs.prepend(toStringDecl); 3706 cdef.sym.members().enter(toStringSym); 3707 3708 return (MethodSymbol)toStringSym; 3709 } 3710 3711 private MethodSymbol addEnumCompareTo(JCClassDecl cdef, VarSymbol ordinalSymbol) { 3712 Symbol compareToSym = lookupMethod(cdef.pos(), 3713 names.compareTo, 3714 cdef.type, 3715 List.of(cdef.sym.type)); 3716 3717 assert(compareToSym != null); 3718 assert(compareToSym instanceof MethodSymbol); 3719 3720 JCMethodDecl compareToDecl = (JCMethodDecl) TreeInfo.declarationFor(compareToSym, cdef); 3721 3722 ListBuffer<JCStatement> blockStatements = new ListBuffer<JCStatement>(); 3723 3724 JCModifiers mod1 = make.Modifiers(0L); 3725 Name oName = names.fromString("o"); 3726 JCVariableDecl par1 = make.Param(oName, cdef.type, compareToSym); 3727 3728 JCIdent paramId1 = make.Ident(names.java_lang_Object); 3729 paramId1.type = cdef.type; 3730 paramId1.sym = par1.sym; 3731 3732 ((MethodSymbol)compareToSym).params = List.of(par1.sym); 3733 3734 JCIdent par1UsageId = make.Ident(par1.sym); 3735 JCIdent castTargetIdent = make.Ident(cdef.sym); 3736 JCTypeCast cast = make.TypeCast(castTargetIdent, par1UsageId); 3737 cast.setType(castTargetIdent.type); 3738 3739 Name otherName = names.fromString("other"); 3740 3741 VarSymbol otherVarSym = new VarSymbol(mod1.flags, 3742 otherName, 3743 cdef.type, 3744 compareToSym); 3745 JCVariableDecl otherVar = make.VarDef(otherVarSym, cast); 3746 blockStatements.append(otherVar); 3747 3748 JCIdent id1 = make.Ident(ordinalSymbol); 3749 3750 JCIdent fLocUsageId = make.Ident(otherVarSym); 3751 JCExpression sel = make.Select(fLocUsageId, ordinalSymbol); 3752 JCBinary bin = makeBinary(JCTree.MINUS, id1, sel); 3753 JCReturn ret = make.Return(bin); 3754 blockStatements.append(ret); 3755 JCMethodDecl compareToMethod = make.MethodDef((MethodSymbol)compareToSym, 3756 make.Block(0L, 3757 blockStatements.toList())); 3758 compareToMethod.params = List.of(par1); 3759 cdef.defs = cdef.defs.append(compareToMethod); 3760 3761 return (MethodSymbol)compareToSym; 3762 } 3763 ////////////////////////////////////////////////////////////// 3764 // The above contributed by Borland for bootstrapping purposes 3765 ////////////////////////////////////////////////////////////// 3766 }