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