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