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