src/share/classes/com/sun/tools/javac/comp/Lower.java

Thu, 15 Aug 2013 22:36:08 +0200

author
jlahoda
date
Thu, 15 Aug 2013 22:36:08 +0200
changeset 1956
f657d400c736
parent 1954
a6378c19836b
child 1975
1ab22e60a738
permissions
-rw-r--r--

8022508: javac crashes if the generics arity of a base class is wrong
Reviewed-by: mcimadamore, vromero

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

mercurial