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