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

Mon, 16 Oct 2017 16:07:48 +0800

author
aoqi
date
Mon, 16 Oct 2017 16:07:48 +0800
changeset 2893
ca5783d9a597
parent 2734
ba758e1ffa69
parent 2702
9ca8d8713094
child 3295
859dc787b52b
permissions
-rw-r--r--

merge

aoqi@0 1 /*
aoqi@0 2 * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
aoqi@0 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
aoqi@0 4 *
aoqi@0 5 * This code is free software; you can redistribute it and/or modify it
aoqi@0 6 * under the terms of the GNU General Public License version 2 only, as
aoqi@0 7 * published by the Free Software Foundation. Oracle designates this
aoqi@0 8 * particular file as subject to the "Classpath" exception as provided
aoqi@0 9 * by Oracle in the LICENSE file that accompanied this code.
aoqi@0 10 *
aoqi@0 11 * This code is distributed in the hope that it will be useful, but WITHOUT
aoqi@0 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
aoqi@0 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
aoqi@0 14 * version 2 for more details (a copy is included in the LICENSE file that
aoqi@0 15 * accompanied this code).
aoqi@0 16 *
aoqi@0 17 * You should have received a copy of the GNU General Public License version
aoqi@0 18 * 2 along with this work; if not, write to the Free Software Foundation,
aoqi@0 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
aoqi@0 20 *
aoqi@0 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
aoqi@0 22 * or visit www.oracle.com if you need additional information or have any
aoqi@0 23 * questions.
aoqi@0 24 */
aoqi@0 25 package com.sun.tools.javac.comp;
aoqi@0 26
aoqi@0 27 import com.sun.tools.javac.tree.*;
aoqi@0 28 import com.sun.tools.javac.tree.JCTree.*;
aoqi@0 29 import com.sun.tools.javac.tree.JCTree.JCMemberReference.ReferenceKind;
aoqi@0 30 import com.sun.tools.javac.tree.TreeMaker;
aoqi@0 31 import com.sun.tools.javac.tree.TreeTranslator;
aoqi@0 32 import com.sun.tools.javac.code.Attribute;
aoqi@0 33 import com.sun.tools.javac.code.Kinds;
aoqi@0 34 import com.sun.tools.javac.code.Scope;
aoqi@0 35 import com.sun.tools.javac.code.Symbol;
aoqi@0 36 import com.sun.tools.javac.code.Symbol.ClassSymbol;
aoqi@0 37 import com.sun.tools.javac.code.Symbol.DynamicMethodSymbol;
aoqi@0 38 import com.sun.tools.javac.code.Symbol.MethodSymbol;
aoqi@0 39 import com.sun.tools.javac.code.Symbol.TypeSymbol;
aoqi@0 40 import com.sun.tools.javac.code.Symbol.VarSymbol;
aoqi@0 41 import com.sun.tools.javac.code.Symtab;
aoqi@0 42 import com.sun.tools.javac.code.Type;
aoqi@0 43 import com.sun.tools.javac.code.Type.MethodType;
rfield@2614 44 import com.sun.tools.javac.code.Type.TypeVar;
aoqi@0 45 import com.sun.tools.javac.code.Types;
aoqi@0 46 import com.sun.tools.javac.comp.LambdaToMethod.LambdaAnalyzerPreprocessor.*;
aoqi@0 47 import com.sun.tools.javac.comp.Lower.BasicFreeVarCollector;
aoqi@0 48 import com.sun.tools.javac.jvm.*;
aoqi@0 49 import com.sun.tools.javac.util.*;
aoqi@0 50 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
aoqi@0 51 import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
aoqi@0 52
aoqi@0 53 import java.util.EnumMap;
aoqi@0 54 import java.util.HashMap;
aoqi@0 55 import java.util.HashSet;
aoqi@0 56 import java.util.LinkedHashMap;
aoqi@0 57 import java.util.Map;
aoqi@0 58 import java.util.Set;
aoqi@0 59
aoqi@0 60 import static com.sun.tools.javac.comp.LambdaToMethod.LambdaSymbolKind.*;
aoqi@0 61 import static com.sun.tools.javac.code.Flags.*;
aoqi@0 62 import static com.sun.tools.javac.code.Kinds.*;
aoqi@0 63 import static com.sun.tools.javac.code.TypeTag.*;
aoqi@0 64 import static com.sun.tools.javac.tree.JCTree.Tag.*;
rfield@2614 65 import javax.lang.model.type.TypeKind;
aoqi@0 66
aoqi@0 67 /**
aoqi@0 68 * This pass desugars lambda expressions into static methods
aoqi@0 69 *
aoqi@0 70 * <p><b>This is NOT part of any supported API.
aoqi@0 71 * If you write code that depends on this, you do so at your own risk.
aoqi@0 72 * This code and its internal interfaces are subject to change or
aoqi@0 73 * deletion without notice.</b>
aoqi@0 74 */
aoqi@0 75 public class LambdaToMethod extends TreeTranslator {
aoqi@0 76
aoqi@0 77 private Attr attr;
aoqi@0 78 private JCDiagnostic.Factory diags;
aoqi@0 79 private Log log;
aoqi@0 80 private Lower lower;
aoqi@0 81 private Names names;
aoqi@0 82 private Symtab syms;
aoqi@0 83 private Resolve rs;
aoqi@0 84 private TreeMaker make;
aoqi@0 85 private Types types;
aoqi@0 86 private TransTypes transTypes;
aoqi@0 87 private Env<AttrContext> attrEnv;
aoqi@0 88
aoqi@0 89 /** the analyzer scanner */
aoqi@0 90 private LambdaAnalyzerPreprocessor analyzer;
aoqi@0 91
aoqi@0 92 /** map from lambda trees to translation contexts */
aoqi@0 93 private Map<JCTree, TranslationContext<?>> contextMap;
aoqi@0 94
aoqi@0 95 /** current translation context (visitor argument) */
aoqi@0 96 private TranslationContext<?> context;
aoqi@0 97
aoqi@0 98 /** info about the current class being processed */
aoqi@0 99 private KlassInfo kInfo;
aoqi@0 100
aoqi@0 101 /** dump statistics about lambda code generation */
aoqi@0 102 private boolean dumpLambdaToMethodStats;
aoqi@0 103
aoqi@0 104 /** force serializable representation, for stress testing **/
aoqi@0 105 private final boolean forceSerializable;
aoqi@0 106
aoqi@0 107 /** Flag for alternate metafactories indicating the lambda object is intended to be serializable */
aoqi@0 108 public static final int FLAG_SERIALIZABLE = 1 << 0;
aoqi@0 109
aoqi@0 110 /** Flag for alternate metafactories indicating the lambda object has multiple targets */
aoqi@0 111 public static final int FLAG_MARKERS = 1 << 1;
aoqi@0 112
aoqi@0 113 /** Flag for alternate metafactories indicating the lambda object requires multiple bridges */
aoqi@0 114 public static final int FLAG_BRIDGES = 1 << 2;
aoqi@0 115
aoqi@0 116 // <editor-fold defaultstate="collapsed" desc="Instantiating">
aoqi@0 117 protected static final Context.Key<LambdaToMethod> unlambdaKey =
aoqi@0 118 new Context.Key<LambdaToMethod>();
aoqi@0 119
aoqi@0 120 public static LambdaToMethod instance(Context context) {
aoqi@0 121 LambdaToMethod instance = context.get(unlambdaKey);
aoqi@0 122 if (instance == null) {
aoqi@0 123 instance = new LambdaToMethod(context);
aoqi@0 124 }
aoqi@0 125 return instance;
aoqi@0 126 }
aoqi@0 127 private LambdaToMethod(Context context) {
aoqi@0 128 context.put(unlambdaKey, this);
aoqi@0 129 diags = JCDiagnostic.Factory.instance(context);
aoqi@0 130 log = Log.instance(context);
aoqi@0 131 lower = Lower.instance(context);
aoqi@0 132 names = Names.instance(context);
aoqi@0 133 syms = Symtab.instance(context);
aoqi@0 134 rs = Resolve.instance(context);
aoqi@0 135 make = TreeMaker.instance(context);
aoqi@0 136 types = Types.instance(context);
aoqi@0 137 transTypes = TransTypes.instance(context);
aoqi@0 138 analyzer = new LambdaAnalyzerPreprocessor();
aoqi@0 139 Options options = Options.instance(context);
aoqi@0 140 dumpLambdaToMethodStats = options.isSet("dumpLambdaToMethodStats");
aoqi@0 141 attr = Attr.instance(context);
aoqi@0 142 forceSerializable = options.isSet("forceSerializable");
aoqi@0 143 }
aoqi@0 144 // </editor-fold>
aoqi@0 145
aoqi@0 146 private class KlassInfo {
aoqi@0 147
aoqi@0 148 /**
aoqi@0 149 * list of methods to append
aoqi@0 150 */
aoqi@0 151 private ListBuffer<JCTree> appendedMethodList;
aoqi@0 152
aoqi@0 153 /**
aoqi@0 154 * list of deserialization cases
aoqi@0 155 */
aoqi@0 156 private final Map<String, ListBuffer<JCStatement>> deserializeCases;
aoqi@0 157
aoqi@0 158 /**
aoqi@0 159 * deserialize method symbol
aoqi@0 160 */
aoqi@0 161 private final MethodSymbol deserMethodSym;
aoqi@0 162
aoqi@0 163 /**
aoqi@0 164 * deserialize method parameter symbol
aoqi@0 165 */
aoqi@0 166 private final VarSymbol deserParamSym;
aoqi@0 167
aoqi@0 168 private final JCClassDecl clazz;
aoqi@0 169
aoqi@0 170 private KlassInfo(JCClassDecl clazz) {
aoqi@0 171 this.clazz = clazz;
aoqi@0 172 appendedMethodList = new ListBuffer<>();
aoqi@0 173 deserializeCases = new HashMap<String, ListBuffer<JCStatement>>();
aoqi@0 174 MethodType type = new MethodType(List.of(syms.serializedLambdaType), syms.objectType,
aoqi@0 175 List.<Type>nil(), syms.methodClass);
aoqi@0 176 deserMethodSym = makePrivateSyntheticMethod(STATIC, names.deserializeLambda, type, clazz.sym);
aoqi@0 177 deserParamSym = new VarSymbol(FINAL, names.fromString("lambda"),
aoqi@0 178 syms.serializedLambdaType, deserMethodSym);
aoqi@0 179 }
aoqi@0 180
aoqi@0 181 private void addMethod(JCTree decl) {
aoqi@0 182 appendedMethodList = appendedMethodList.prepend(decl);
aoqi@0 183 }
aoqi@0 184 }
aoqi@0 185
aoqi@0 186 // <editor-fold defaultstate="collapsed" desc="translate methods">
aoqi@0 187 @Override
aoqi@0 188 public <T extends JCTree> T translate(T tree) {
aoqi@0 189 TranslationContext<?> newContext = contextMap.get(tree);
aoqi@0 190 return translate(tree, newContext != null ? newContext : context);
aoqi@0 191 }
aoqi@0 192
aoqi@0 193 <T extends JCTree> T translate(T tree, TranslationContext<?> newContext) {
aoqi@0 194 TranslationContext<?> prevContext = context;
aoqi@0 195 try {
aoqi@0 196 context = newContext;
aoqi@0 197 return super.translate(tree);
aoqi@0 198 }
aoqi@0 199 finally {
aoqi@0 200 context = prevContext;
aoqi@0 201 }
aoqi@0 202 }
aoqi@0 203
aoqi@0 204 <T extends JCTree> List<T> translate(List<T> trees, TranslationContext<?> newContext) {
aoqi@0 205 ListBuffer<T> buf = new ListBuffer<>();
aoqi@0 206 for (T tree : trees) {
aoqi@0 207 buf.append(translate(tree, newContext));
aoqi@0 208 }
aoqi@0 209 return buf.toList();
aoqi@0 210 }
aoqi@0 211
aoqi@0 212 public JCTree translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) {
aoqi@0 213 this.make = make;
aoqi@0 214 this.attrEnv = env;
aoqi@0 215 this.context = null;
aoqi@0 216 this.contextMap = new HashMap<JCTree, TranslationContext<?>>();
aoqi@0 217 return translate(cdef);
aoqi@0 218 }
aoqi@0 219 // </editor-fold>
aoqi@0 220
aoqi@0 221 // <editor-fold defaultstate="collapsed" desc="visitor methods">
aoqi@0 222 /**
aoqi@0 223 * Visit a class.
aoqi@0 224 * Maintain the translatedMethodList across nested classes.
aoqi@0 225 * Append the translatedMethodList to the class after it is translated.
aoqi@0 226 * @param tree
aoqi@0 227 */
aoqi@0 228 @Override
aoqi@0 229 public void visitClassDef(JCClassDecl tree) {
aoqi@0 230 if (tree.sym.owner.kind == PCK) {
aoqi@0 231 //analyze class
aoqi@0 232 tree = analyzer.analyzeAndPreprocessClass(tree);
aoqi@0 233 }
aoqi@0 234 KlassInfo prevKlassInfo = kInfo;
aoqi@0 235 try {
aoqi@0 236 kInfo = new KlassInfo(tree);
aoqi@0 237 super.visitClassDef(tree);
aoqi@0 238 if (!kInfo.deserializeCases.isEmpty()) {
aoqi@0 239 int prevPos = make.pos;
aoqi@0 240 try {
aoqi@0 241 make.at(tree);
aoqi@0 242 kInfo.addMethod(makeDeserializeMethod(tree.sym));
aoqi@0 243 } finally {
aoqi@0 244 make.at(prevPos);
aoqi@0 245 }
aoqi@0 246 }
aoqi@0 247 //add all translated instance methods here
aoqi@0 248 List<JCTree> newMethods = kInfo.appendedMethodList.toList();
aoqi@0 249 tree.defs = tree.defs.appendList(newMethods);
aoqi@0 250 for (JCTree lambda : newMethods) {
aoqi@0 251 tree.sym.members().enter(((JCMethodDecl)lambda).sym);
aoqi@0 252 }
aoqi@0 253 result = tree;
aoqi@0 254 } finally {
aoqi@0 255 kInfo = prevKlassInfo;
aoqi@0 256 }
aoqi@0 257 }
aoqi@0 258
aoqi@0 259 /**
aoqi@0 260 * Translate a lambda into a method to be inserted into the class.
aoqi@0 261 * Then replace the lambda site with an invokedynamic call of to lambda
aoqi@0 262 * meta-factory, which will use the lambda method.
aoqi@0 263 * @param tree
aoqi@0 264 */
aoqi@0 265 @Override
aoqi@0 266 public void visitLambda(JCLambda tree) {
aoqi@0 267 LambdaTranslationContext localContext = (LambdaTranslationContext)context;
jlahoda@2733 268 MethodSymbol sym = localContext.translatedSym;
aoqi@0 269 MethodType lambdaType = (MethodType) sym.type;
aoqi@0 270
aoqi@0 271 {
aoqi@0 272 Symbol owner = localContext.owner;
aoqi@0 273 ListBuffer<Attribute.TypeCompound> ownerTypeAnnos = new ListBuffer<Attribute.TypeCompound>();
aoqi@0 274 ListBuffer<Attribute.TypeCompound> lambdaTypeAnnos = new ListBuffer<Attribute.TypeCompound>();
aoqi@0 275
aoqi@0 276 for (Attribute.TypeCompound tc : owner.getRawTypeAttributes()) {
aoqi@0 277 if (tc.position.onLambda == tree) {
aoqi@0 278 lambdaTypeAnnos.append(tc);
aoqi@0 279 } else {
aoqi@0 280 ownerTypeAnnos.append(tc);
aoqi@0 281 }
aoqi@0 282 }
aoqi@0 283 if (lambdaTypeAnnos.nonEmpty()) {
aoqi@0 284 owner.setTypeAttributes(ownerTypeAnnos.toList());
aoqi@0 285 sym.setTypeAttributes(lambdaTypeAnnos.toList());
aoqi@0 286 }
aoqi@0 287 }
aoqi@0 288
aoqi@0 289 //create the method declaration hoisting the lambda body
aoqi@0 290 JCMethodDecl lambdaDecl = make.MethodDef(make.Modifiers(sym.flags_field),
aoqi@0 291 sym.name,
aoqi@0 292 make.QualIdent(lambdaType.getReturnType().tsym),
aoqi@0 293 List.<JCTypeParameter>nil(),
aoqi@0 294 localContext.syntheticParams,
aoqi@0 295 lambdaType.getThrownTypes() == null ?
aoqi@0 296 List.<JCExpression>nil() :
aoqi@0 297 make.Types(lambdaType.getThrownTypes()),
aoqi@0 298 null,
aoqi@0 299 null);
aoqi@0 300 lambdaDecl.sym = sym;
aoqi@0 301 lambdaDecl.type = lambdaType;
aoqi@0 302
aoqi@0 303 //translate lambda body
aoqi@0 304 //As the lambda body is translated, all references to lambda locals,
aoqi@0 305 //captured variables, enclosing members are adjusted accordingly
aoqi@0 306 //to refer to the static method parameters (rather than i.e. acessing to
aoqi@0 307 //captured members directly).
aoqi@0 308 lambdaDecl.body = translate(makeLambdaBody(tree, lambdaDecl));
aoqi@0 309
aoqi@0 310 //Add the method to the list of methods to be added to this class.
aoqi@0 311 kInfo.addMethod(lambdaDecl);
aoqi@0 312
aoqi@0 313 //now that we have generated a method for the lambda expression,
aoqi@0 314 //we can translate the lambda into a method reference pointing to the newly
aoqi@0 315 //created method.
aoqi@0 316 //
aoqi@0 317 //Note that we need to adjust the method handle so that it will match the
aoqi@0 318 //signature of the SAM descriptor - this means that the method reference
aoqi@0 319 //should be added the following synthetic arguments:
aoqi@0 320 //
aoqi@0 321 // * the "this" argument if it is an instance method
aoqi@0 322 // * enclosing locals captured by the lambda expression
aoqi@0 323
aoqi@0 324 ListBuffer<JCExpression> syntheticInits = new ListBuffer<>();
aoqi@0 325
rfield@2607 326 if (localContext.methodReferenceReceiver != null) {
rfield@2607 327 syntheticInits.append(localContext.methodReferenceReceiver);
rfield@2607 328 } else if (!sym.isStatic()) {
aoqi@0 329 syntheticInits.append(makeThis(
aoqi@0 330 sym.owner.enclClass().asType(),
aoqi@0 331 localContext.owner.enclClass()));
aoqi@0 332 }
aoqi@0 333
aoqi@0 334 //add captured locals
aoqi@0 335 for (Symbol fv : localContext.getSymbolMap(CAPTURED_VAR).keySet()) {
aoqi@0 336 if (fv != localContext.self) {
aoqi@0 337 JCTree captured_local = make.Ident(fv).setType(fv.type);
aoqi@0 338 syntheticInits.append((JCExpression) captured_local);
aoqi@0 339 }
aoqi@0 340 }
aoqi@0 341
aoqi@0 342 //then, determine the arguments to the indy call
aoqi@0 343 List<JCExpression> indy_args = translate(syntheticInits.toList(), localContext.prev);
aoqi@0 344
aoqi@0 345 //build a sam instance using an indy call to the meta-factory
aoqi@0 346 int refKind = referenceKind(sym);
aoqi@0 347
aoqi@0 348 //convert to an invokedynamic call
aoqi@0 349 result = makeMetafactoryIndyCall(context, refKind, sym, indy_args);
aoqi@0 350 }
aoqi@0 351
aoqi@0 352 private JCIdent makeThis(Type type, Symbol owner) {
aoqi@0 353 VarSymbol _this = new VarSymbol(PARAMETER | FINAL | SYNTHETIC,
aoqi@0 354 names._this,
aoqi@0 355 type,
aoqi@0 356 owner);
aoqi@0 357 return make.Ident(_this);
aoqi@0 358 }
aoqi@0 359
aoqi@0 360 /**
aoqi@0 361 * Translate a method reference into an invokedynamic call to the
aoqi@0 362 * meta-factory.
aoqi@0 363 * @param tree
aoqi@0 364 */
aoqi@0 365 @Override
aoqi@0 366 public void visitReference(JCMemberReference tree) {
aoqi@0 367 ReferenceTranslationContext localContext = (ReferenceTranslationContext)context;
aoqi@0 368
aoqi@0 369 //first determine the method symbol to be used to generate the sam instance
aoqi@0 370 //this is either the method reference symbol, or the bridged reference symbol
rfield@2607 371 Symbol refSym = localContext.isSignaturePolymorphic()
aoqi@0 372 ? localContext.sigPolySym
aoqi@0 373 : tree.sym;
aoqi@0 374
aoqi@0 375 //the qualifying expression is treated as a special captured arg
aoqi@0 376 JCExpression init;
aoqi@0 377 switch(tree.kind) {
aoqi@0 378
aoqi@0 379 case IMPLICIT_INNER: /** Inner :: new */
aoqi@0 380 case SUPER: /** super :: instMethod */
aoqi@0 381 init = makeThis(
aoqi@0 382 localContext.owner.enclClass().asType(),
aoqi@0 383 localContext.owner.enclClass());
aoqi@0 384 break;
aoqi@0 385
aoqi@0 386 case BOUND: /** Expr :: instMethod */
aoqi@0 387 init = tree.getQualifierExpression();
aoqi@0 388 init = attr.makeNullCheck(init);
aoqi@0 389 break;
aoqi@0 390
aoqi@0 391 case UNBOUND: /** Type :: instMethod */
aoqi@0 392 case STATIC: /** Type :: staticMethod */
aoqi@0 393 case TOPLEVEL: /** Top level :: new */
aoqi@0 394 case ARRAY_CTOR: /** ArrayType :: new */
aoqi@0 395 init = null;
aoqi@0 396 break;
aoqi@0 397
aoqi@0 398 default:
aoqi@0 399 throw new InternalError("Should not have an invalid kind");
aoqi@0 400 }
aoqi@0 401
aoqi@0 402 List<JCExpression> indy_args = init==null? List.<JCExpression>nil() : translate(List.of(init), localContext.prev);
aoqi@0 403
aoqi@0 404
aoqi@0 405 //build a sam instance using an indy call to the meta-factory
aoqi@0 406 result = makeMetafactoryIndyCall(localContext, localContext.referenceKind(), refSym, indy_args);
aoqi@0 407 }
aoqi@0 408
aoqi@0 409 /**
aoqi@0 410 * Translate identifiers within a lambda to the mapped identifier
aoqi@0 411 * @param tree
aoqi@0 412 */
aoqi@0 413 @Override
aoqi@0 414 public void visitIdent(JCIdent tree) {
aoqi@0 415 if (context == null || !analyzer.lambdaIdentSymbolFilter(tree.sym)) {
aoqi@0 416 super.visitIdent(tree);
aoqi@0 417 } else {
aoqi@0 418 int prevPos = make.pos;
aoqi@0 419 try {
aoqi@0 420 make.at(tree);
aoqi@0 421
aoqi@0 422 LambdaTranslationContext lambdaContext = (LambdaTranslationContext) context;
aoqi@0 423 JCTree ltree = lambdaContext.translate(tree);
aoqi@0 424 if (ltree != null) {
aoqi@0 425 result = ltree;
aoqi@0 426 } else {
aoqi@0 427 //access to untranslated symbols (i.e. compile-time constants,
aoqi@0 428 //members defined inside the lambda body, etc.) )
aoqi@0 429 super.visitIdent(tree);
aoqi@0 430 }
aoqi@0 431 } finally {
aoqi@0 432 make.at(prevPos);
aoqi@0 433 }
aoqi@0 434 }
aoqi@0 435 }
aoqi@0 436
aoqi@0 437 @Override
aoqi@0 438 public void visitVarDef(JCVariableDecl tree) {
aoqi@0 439 LambdaTranslationContext lambdaContext = (LambdaTranslationContext)context;
aoqi@0 440 if (context != null && lambdaContext.getSymbolMap(LOCAL_VAR).containsKey(tree.sym)) {
aoqi@0 441 tree.init = translate(tree.init);
aoqi@0 442 tree.sym = (VarSymbol) lambdaContext.getSymbolMap(LOCAL_VAR).get(tree.sym);
aoqi@0 443 result = tree;
aoqi@0 444 } else if (context != null && lambdaContext.getSymbolMap(TYPE_VAR).containsKey(tree.sym)) {
aoqi@0 445 JCExpression init = translate(tree.init);
aoqi@0 446 VarSymbol xsym = (VarSymbol)lambdaContext.getSymbolMap(TYPE_VAR).get(tree.sym);
aoqi@0 447 int prevPos = make.pos;
aoqi@0 448 try {
aoqi@0 449 result = make.at(tree).VarDef(xsym, init);
aoqi@0 450 } finally {
aoqi@0 451 make.at(prevPos);
aoqi@0 452 }
aoqi@0 453 // Replace the entered symbol for this variable
aoqi@0 454 Scope sc = tree.sym.owner.members();
aoqi@0 455 if (sc != null) {
aoqi@0 456 sc.remove(tree.sym);
aoqi@0 457 sc.enter(xsym);
aoqi@0 458 }
aoqi@0 459 } else {
aoqi@0 460 super.visitVarDef(tree);
aoqi@0 461 }
aoqi@0 462 }
aoqi@0 463
aoqi@0 464 // </editor-fold>
aoqi@0 465
aoqi@0 466 // <editor-fold defaultstate="collapsed" desc="Translation helper methods">
aoqi@0 467
aoqi@0 468 private JCBlock makeLambdaBody(JCLambda tree, JCMethodDecl lambdaMethodDecl) {
aoqi@0 469 return tree.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
aoqi@0 470 makeLambdaExpressionBody((JCExpression)tree.body, lambdaMethodDecl) :
aoqi@0 471 makeLambdaStatementBody((JCBlock)tree.body, lambdaMethodDecl, tree.canCompleteNormally);
aoqi@0 472 }
aoqi@0 473
aoqi@0 474 private JCBlock makeLambdaExpressionBody(JCExpression expr, JCMethodDecl lambdaMethodDecl) {
aoqi@0 475 Type restype = lambdaMethodDecl.type.getReturnType();
aoqi@0 476 boolean isLambda_void = expr.type.hasTag(VOID);
aoqi@0 477 boolean isTarget_void = restype.hasTag(VOID);
aoqi@0 478 boolean isTarget_Void = types.isSameType(restype, types.boxedClass(syms.voidType).type);
aoqi@0 479 int prevPos = make.pos;
aoqi@0 480 try {
aoqi@0 481 if (isTarget_void) {
aoqi@0 482 //target is void:
aoqi@0 483 // BODY;
aoqi@0 484 JCStatement stat = make.at(expr).Exec(expr);
aoqi@0 485 return make.Block(0, List.<JCStatement>of(stat));
aoqi@0 486 } else if (isLambda_void && isTarget_Void) {
aoqi@0 487 //void to Void conversion:
aoqi@0 488 // BODY; return null;
aoqi@0 489 ListBuffer<JCStatement> stats = new ListBuffer<>();
aoqi@0 490 stats.append(make.at(expr).Exec(expr));
aoqi@0 491 stats.append(make.Return(make.Literal(BOT, null).setType(syms.botType)));
aoqi@0 492 return make.Block(0, stats.toList());
aoqi@0 493 } else {
aoqi@0 494 //non-void to non-void conversion:
aoqi@0 495 // return (TYPE)BODY;
aoqi@0 496 JCExpression retExpr = transTypes.coerce(attrEnv, expr, restype);
aoqi@0 497 return make.at(retExpr).Block(0, List.<JCStatement>of(make.Return(retExpr)));
aoqi@0 498 }
aoqi@0 499 } finally {
aoqi@0 500 make.at(prevPos);
aoqi@0 501 }
aoqi@0 502 }
aoqi@0 503
aoqi@0 504 private JCBlock makeLambdaStatementBody(JCBlock block, final JCMethodDecl lambdaMethodDecl, boolean completeNormally) {
aoqi@0 505 final Type restype = lambdaMethodDecl.type.getReturnType();
aoqi@0 506 final boolean isTarget_void = restype.hasTag(VOID);
aoqi@0 507 boolean isTarget_Void = types.isSameType(restype, types.boxedClass(syms.voidType).type);
aoqi@0 508
aoqi@0 509 class LambdaBodyTranslator extends TreeTranslator {
aoqi@0 510
aoqi@0 511 @Override
aoqi@0 512 public void visitClassDef(JCClassDecl tree) {
aoqi@0 513 //do NOT recurse on any inner classes
aoqi@0 514 result = tree;
aoqi@0 515 }
aoqi@0 516
aoqi@0 517 @Override
aoqi@0 518 public void visitLambda(JCLambda tree) {
aoqi@0 519 //do NOT recurse on any nested lambdas
aoqi@0 520 result = tree;
aoqi@0 521 }
aoqi@0 522
aoqi@0 523 @Override
aoqi@0 524 public void visitReturn(JCReturn tree) {
aoqi@0 525 boolean isLambda_void = tree.expr == null;
aoqi@0 526 if (isTarget_void && !isLambda_void) {
aoqi@0 527 //Void to void conversion:
aoqi@0 528 // { TYPE $loc = RET-EXPR; return; }
aoqi@0 529 VarSymbol loc = makeSyntheticVar(0, names.fromString("$loc"), tree.expr.type, lambdaMethodDecl.sym);
aoqi@0 530 JCVariableDecl varDef = make.VarDef(loc, tree.expr);
aoqi@0 531 result = make.Block(0, List.<JCStatement>of(varDef, make.Return(null)));
aoqi@0 532 } else if (!isTarget_void || !isLambda_void) {
aoqi@0 533 //non-void to non-void conversion:
aoqi@0 534 // return (TYPE)RET-EXPR;
aoqi@0 535 tree.expr = transTypes.coerce(attrEnv, tree.expr, restype);
aoqi@0 536 result = tree;
aoqi@0 537 } else {
aoqi@0 538 result = tree;
aoqi@0 539 }
aoqi@0 540
aoqi@0 541 }
aoqi@0 542 }
aoqi@0 543
aoqi@0 544 JCBlock trans_block = new LambdaBodyTranslator().translate(block);
aoqi@0 545 if (completeNormally && isTarget_Void) {
aoqi@0 546 //there's no return statement and the lambda (possibly inferred)
aoqi@0 547 //return type is java.lang.Void; emit a synthetic return statement
aoqi@0 548 trans_block.stats = trans_block.stats.append(make.Return(make.Literal(BOT, null).setType(syms.botType)));
aoqi@0 549 }
aoqi@0 550 return trans_block;
aoqi@0 551 }
aoqi@0 552
aoqi@0 553 private JCMethodDecl makeDeserializeMethod(Symbol kSym) {
aoqi@0 554 ListBuffer<JCCase> cases = new ListBuffer<>();
aoqi@0 555 ListBuffer<JCBreak> breaks = new ListBuffer<>();
aoqi@0 556 for (Map.Entry<String, ListBuffer<JCStatement>> entry : kInfo.deserializeCases.entrySet()) {
aoqi@0 557 JCBreak br = make.Break(null);
aoqi@0 558 breaks.add(br);
aoqi@0 559 List<JCStatement> stmts = entry.getValue().append(br).toList();
aoqi@0 560 cases.add(make.Case(make.Literal(entry.getKey()), stmts));
aoqi@0 561 }
aoqi@0 562 JCSwitch sw = make.Switch(deserGetter("getImplMethodName", syms.stringType), cases.toList());
aoqi@0 563 for (JCBreak br : breaks) {
aoqi@0 564 br.target = sw;
aoqi@0 565 }
aoqi@0 566 JCBlock body = make.Block(0L, List.<JCStatement>of(
aoqi@0 567 sw,
aoqi@0 568 make.Throw(makeNewClass(
aoqi@0 569 syms.illegalArgumentExceptionType,
aoqi@0 570 List.<JCExpression>of(make.Literal("Invalid lambda deserialization"))))));
aoqi@0 571 JCMethodDecl deser = make.MethodDef(make.Modifiers(kInfo.deserMethodSym.flags()),
aoqi@0 572 names.deserializeLambda,
aoqi@0 573 make.QualIdent(kInfo.deserMethodSym.getReturnType().tsym),
aoqi@0 574 List.<JCTypeParameter>nil(),
aoqi@0 575 List.of(make.VarDef(kInfo.deserParamSym, null)),
aoqi@0 576 List.<JCExpression>nil(),
aoqi@0 577 body,
aoqi@0 578 null);
aoqi@0 579 deser.sym = kInfo.deserMethodSym;
aoqi@0 580 deser.type = kInfo.deserMethodSym.type;
aoqi@0 581 //System.err.printf("DESER: '%s'\n", deser);
aoqi@0 582 return deser;
aoqi@0 583 }
aoqi@0 584
aoqi@0 585 /** Make an attributed class instance creation expression.
aoqi@0 586 * @param ctype The class type.
aoqi@0 587 * @param args The constructor arguments.
aoqi@0 588 * @param cons The constructor symbol
aoqi@0 589 */
aoqi@0 590 JCNewClass makeNewClass(Type ctype, List<JCExpression> args, Symbol cons) {
aoqi@0 591 JCNewClass tree = make.NewClass(null,
aoqi@0 592 null, make.QualIdent(ctype.tsym), args, null);
aoqi@0 593 tree.constructor = cons;
aoqi@0 594 tree.type = ctype;
aoqi@0 595 return tree;
aoqi@0 596 }
aoqi@0 597
aoqi@0 598 /** Make an attributed class instance creation expression.
aoqi@0 599 * @param ctype The class type.
aoqi@0 600 * @param args The constructor arguments.
aoqi@0 601 */
aoqi@0 602 JCNewClass makeNewClass(Type ctype, List<JCExpression> args) {
aoqi@0 603 return makeNewClass(ctype, args,
aoqi@0 604 rs.resolveConstructor(null, attrEnv, ctype, TreeInfo.types(args), List.<Type>nil()));
aoqi@0 605 }
aoqi@0 606
aoqi@0 607 private void addDeserializationCase(int implMethodKind, Symbol refSym, Type targetType, MethodSymbol samSym,
aoqi@0 608 DiagnosticPosition pos, List<Object> staticArgs, MethodType indyType) {
aoqi@0 609 String functionalInterfaceClass = classSig(targetType);
aoqi@0 610 String functionalInterfaceMethodName = samSym.getSimpleName().toString();
aoqi@0 611 String functionalInterfaceMethodSignature = typeSig(types.erasure(samSym.type));
aoqi@0 612 String implClass = classSig(types.erasure(refSym.owner.type));
aoqi@0 613 String implMethodName = refSym.getQualifiedName().toString();
aoqi@0 614 String implMethodSignature = typeSig(types.erasure(refSym.type));
aoqi@0 615
aoqi@0 616 JCExpression kindTest = eqTest(syms.intType, deserGetter("getImplMethodKind", syms.intType), make.Literal(implMethodKind));
aoqi@0 617 ListBuffer<JCExpression> serArgs = new ListBuffer<>();
aoqi@0 618 int i = 0;
aoqi@0 619 for (Type t : indyType.getParameterTypes()) {
aoqi@0 620 List<JCExpression> indexAsArg = new ListBuffer<JCExpression>().append(make.Literal(i)).toList();
aoqi@0 621 List<Type> argTypes = new ListBuffer<Type>().append(syms.intType).toList();
aoqi@0 622 serArgs.add(make.TypeCast(types.erasure(t), deserGetter("getCapturedArg", syms.objectType, argTypes, indexAsArg)));
aoqi@0 623 ++i;
aoqi@0 624 }
aoqi@0 625 JCStatement stmt = make.If(
aoqi@0 626 deserTest(deserTest(deserTest(deserTest(deserTest(
aoqi@0 627 kindTest,
aoqi@0 628 "getFunctionalInterfaceClass", functionalInterfaceClass),
aoqi@0 629 "getFunctionalInterfaceMethodName", functionalInterfaceMethodName),
aoqi@0 630 "getFunctionalInterfaceMethodSignature", functionalInterfaceMethodSignature),
aoqi@0 631 "getImplClass", implClass),
aoqi@0 632 "getImplMethodSignature", implMethodSignature),
aoqi@0 633 make.Return(makeIndyCall(
aoqi@0 634 pos,
aoqi@0 635 syms.lambdaMetafactory,
aoqi@0 636 names.altMetafactory,
aoqi@0 637 staticArgs, indyType, serArgs.toList(), samSym.name)),
aoqi@0 638 null);
aoqi@0 639 ListBuffer<JCStatement> stmts = kInfo.deserializeCases.get(implMethodName);
aoqi@0 640 if (stmts == null) {
aoqi@0 641 stmts = new ListBuffer<>();
aoqi@0 642 kInfo.deserializeCases.put(implMethodName, stmts);
aoqi@0 643 }
aoqi@0 644 /****
aoqi@0 645 System.err.printf("+++++++++++++++++\n");
aoqi@0 646 System.err.printf("*functionalInterfaceClass: '%s'\n", functionalInterfaceClass);
aoqi@0 647 System.err.printf("*functionalInterfaceMethodName: '%s'\n", functionalInterfaceMethodName);
aoqi@0 648 System.err.printf("*functionalInterfaceMethodSignature: '%s'\n", functionalInterfaceMethodSignature);
aoqi@0 649 System.err.printf("*implMethodKind: %d\n", implMethodKind);
aoqi@0 650 System.err.printf("*implClass: '%s'\n", implClass);
aoqi@0 651 System.err.printf("*implMethodName: '%s'\n", implMethodName);
aoqi@0 652 System.err.printf("*implMethodSignature: '%s'\n", implMethodSignature);
aoqi@0 653 ****/
aoqi@0 654 stmts.append(stmt);
aoqi@0 655 }
aoqi@0 656
aoqi@0 657 private JCExpression eqTest(Type argType, JCExpression arg1, JCExpression arg2) {
aoqi@0 658 JCBinary testExpr = make.Binary(JCTree.Tag.EQ, arg1, arg2);
aoqi@0 659 testExpr.operator = rs.resolveBinaryOperator(null, JCTree.Tag.EQ, attrEnv, argType, argType);
aoqi@0 660 testExpr.setType(syms.booleanType);
aoqi@0 661 return testExpr;
aoqi@0 662 }
aoqi@0 663
aoqi@0 664 private JCExpression deserTest(JCExpression prev, String func, String lit) {
aoqi@0 665 MethodType eqmt = new MethodType(List.of(syms.objectType), syms.booleanType, List.<Type>nil(), syms.methodClass);
aoqi@0 666 Symbol eqsym = rs.resolveQualifiedMethod(null, attrEnv, syms.objectType, names.equals, List.of(syms.objectType), List.<Type>nil());
aoqi@0 667 JCMethodInvocation eqtest = make.Apply(
aoqi@0 668 List.<JCExpression>nil(),
aoqi@0 669 make.Select(deserGetter(func, syms.stringType), eqsym).setType(eqmt),
aoqi@0 670 List.<JCExpression>of(make.Literal(lit)));
aoqi@0 671 eqtest.setType(syms.booleanType);
aoqi@0 672 JCBinary compound = make.Binary(JCTree.Tag.AND, prev, eqtest);
aoqi@0 673 compound.operator = rs.resolveBinaryOperator(null, JCTree.Tag.AND, attrEnv, syms.booleanType, syms.booleanType);
aoqi@0 674 compound.setType(syms.booleanType);
aoqi@0 675 return compound;
aoqi@0 676 }
aoqi@0 677
aoqi@0 678 private JCExpression deserGetter(String func, Type type) {
aoqi@0 679 return deserGetter(func, type, List.<Type>nil(), List.<JCExpression>nil());
aoqi@0 680 }
aoqi@0 681
aoqi@0 682 private JCExpression deserGetter(String func, Type type, List<Type> argTypes, List<JCExpression> args) {
aoqi@0 683 MethodType getmt = new MethodType(argTypes, type, List.<Type>nil(), syms.methodClass);
aoqi@0 684 Symbol getsym = rs.resolveQualifiedMethod(null, attrEnv, syms.serializedLambdaType, names.fromString(func), argTypes, List.<Type>nil());
aoqi@0 685 return make.Apply(
aoqi@0 686 List.<JCExpression>nil(),
aoqi@0 687 make.Select(make.Ident(kInfo.deserParamSym).setType(syms.serializedLambdaType), getsym).setType(getmt),
aoqi@0 688 args).setType(type);
aoqi@0 689 }
aoqi@0 690
aoqi@0 691 /**
aoqi@0 692 * Create new synthetic method with given flags, name, type, owner
aoqi@0 693 */
aoqi@0 694 private MethodSymbol makePrivateSyntheticMethod(long flags, Name name, Type type, Symbol owner) {
aoqi@0 695 return new MethodSymbol(flags | SYNTHETIC | PRIVATE, name, type, owner);
aoqi@0 696 }
aoqi@0 697
aoqi@0 698 /**
aoqi@0 699 * Create new synthetic variable with given flags, name, type, owner
aoqi@0 700 */
aoqi@0 701 private VarSymbol makeSyntheticVar(long flags, String name, Type type, Symbol owner) {
aoqi@0 702 return makeSyntheticVar(flags, names.fromString(name), type, owner);
aoqi@0 703 }
aoqi@0 704
aoqi@0 705 /**
aoqi@0 706 * Create new synthetic variable with given flags, name, type, owner
aoqi@0 707 */
aoqi@0 708 private VarSymbol makeSyntheticVar(long flags, Name name, Type type, Symbol owner) {
aoqi@0 709 return new VarSymbol(flags | SYNTHETIC, name, type, owner);
aoqi@0 710 }
aoqi@0 711
aoqi@0 712 /**
aoqi@0 713 * Set varargsElement field on a given tree (must be either a new class tree
aoqi@0 714 * or a method call tree)
aoqi@0 715 */
aoqi@0 716 private void setVarargsIfNeeded(JCTree tree, Type varargsElement) {
aoqi@0 717 if (varargsElement != null) {
aoqi@0 718 switch (tree.getTag()) {
aoqi@0 719 case APPLY: ((JCMethodInvocation)tree).varargsElement = varargsElement; break;
aoqi@0 720 case NEWCLASS: ((JCNewClass)tree).varargsElement = varargsElement; break;
aoqi@0 721 default: throw new AssertionError();
aoqi@0 722 }
aoqi@0 723 }
aoqi@0 724 }
aoqi@0 725
aoqi@0 726 /**
aoqi@0 727 * Convert method/constructor arguments by inserting appropriate cast
aoqi@0 728 * as required by type-erasure - this is needed when bridging a lambda/method
aoqi@0 729 * reference, as the bridged signature might require downcast to be compatible
aoqi@0 730 * with the generated signature.
aoqi@0 731 */
aoqi@0 732 private List<JCExpression> convertArgs(Symbol meth, List<JCExpression> args, Type varargsElement) {
aoqi@0 733 Assert.check(meth.kind == Kinds.MTH);
aoqi@0 734 List<Type> formals = types.erasure(meth.type).getParameterTypes();
aoqi@0 735 if (varargsElement != null) {
aoqi@0 736 Assert.check((meth.flags() & VARARGS) != 0);
aoqi@0 737 }
aoqi@0 738 return transTypes.translateArgs(args, formals, varargsElement, attrEnv);
aoqi@0 739 }
aoqi@0 740
aoqi@0 741 // </editor-fold>
aoqi@0 742
aoqi@0 743 /**
rfield@2607 744 * Converts a method reference which cannot be used directly into a lambda
aoqi@0 745 */
rfield@2607 746 private class MemberReferenceToLambda {
aoqi@0 747
aoqi@0 748 private final JCMemberReference tree;
aoqi@0 749 private final ReferenceTranslationContext localContext;
rfield@2607 750 private final Symbol owner;
aoqi@0 751 private final ListBuffer<JCExpression> args = new ListBuffer<>();
aoqi@0 752 private final ListBuffer<JCVariableDecl> params = new ListBuffer<>();
aoqi@0 753
rfield@2607 754 private JCExpression receiverExpression = null;
rfield@2607 755
rfield@2607 756 MemberReferenceToLambda(JCMemberReference tree, ReferenceTranslationContext localContext, Symbol owner) {
aoqi@0 757 this.tree = tree;
aoqi@0 758 this.localContext = localContext;
rfield@2607 759 this.owner = owner;
aoqi@0 760 }
aoqi@0 761
rfield@2607 762 JCLambda lambda() {
aoqi@0 763 int prevPos = make.pos;
aoqi@0 764 try {
aoqi@0 765 make.at(tree);
aoqi@0 766
rfield@2607 767 //body generation - this can be either a method call or a
rfield@2607 768 //new instance creation expression, depending on the member reference kind
rfield@2614 769 VarSymbol rcvr = addParametersReturnReceiver();
rfield@2607 770 JCExpression expr = (tree.getMode() == ReferenceMode.INVOKE)
rfield@2607 771 ? expressionInvoke(rcvr)
rfield@2607 772 : expressionNew();
aoqi@0 773
rfield@2607 774 JCLambda slam = make.Lambda(params.toList(), expr);
rfield@2607 775 slam.targets = tree.targets;
rfield@2607 776 slam.type = tree.type;
rfield@2607 777 slam.pos = tree.pos;
rfield@2607 778 return slam;
aoqi@0 779 } finally {
aoqi@0 780 make.at(prevPos);
aoqi@0 781 }
aoqi@0 782 }
rfield@2607 783
rfield@2614 784 /**
rfield@2614 785 * Generate the parameter list for the converted member reference.
rfield@2614 786 *
rfield@2614 787 * @return The receiver variable symbol, if any
rfield@2614 788 */
rfield@2614 789 VarSymbol addParametersReturnReceiver() {
rfield@2614 790 Type samDesc = localContext.bridgedRefSig();
rfield@2614 791 List<Type> samPTypes = samDesc.getParameterTypes();
rfield@2614 792 List<Type> descPTypes = tree.getDescriptorType(types).getParameterTypes();
rfield@2614 793
rfield@2614 794 // Determine the receiver, if any
rfield@2614 795 VarSymbol rcvr;
rfield@2614 796 switch (tree.kind) {
rfield@2614 797 case BOUND:
rfield@2614 798 // The receiver is explicit in the method reference
rfield@2614 799 rcvr = addParameter("rec$", tree.getQualifierExpression().type, false);
rfield@2614 800 receiverExpression = attr.makeNullCheck(tree.getQualifierExpression());
rfield@2614 801 break;
rfield@2614 802 case UNBOUND:
rfield@2614 803 // The receiver is the first parameter, extract it and
rfield@2614 804 // adjust the SAM and unerased type lists accordingly
rfield@2614 805 rcvr = addParameter("rec$", samDesc.getParameterTypes().head, false);
rfield@2614 806 samPTypes = samPTypes.tail;
rfield@2614 807 descPTypes = descPTypes.tail;
rfield@2614 808 break;
rfield@2614 809 default:
rfield@2614 810 rcvr = null;
rfield@2614 811 break;
rfield@2614 812 }
rfield@2614 813 List<Type> implPTypes = tree.sym.type.getParameterTypes();
rfield@2614 814 int implSize = implPTypes.size();
rfield@2614 815 int samSize = samPTypes.size();
rfield@2614 816 // Last parameter to copy from referenced method, exclude final var args
rfield@2614 817 int last = localContext.needsVarArgsConversion() ? implSize - 1 : implSize;
rfield@2614 818
rfield@2614 819 // Failsafe -- assure match-up
rfield@2614 820 boolean checkForIntersection = tree.varargsElement != null || implSize == descPTypes.size();
rfield@2614 821
rfield@2614 822 // Use parameter types of the implementation method unless the unerased
rfield@2614 823 // SAM parameter type is an intersection type, in that case use the
rfield@2614 824 // erased SAM parameter type so that the supertype relationship
rfield@2614 825 // the implementation method parameters is not obscured.
rfield@2614 826 // Note: in this loop, the lists implPTypes, samPTypes, and descPTypes
rfield@2614 827 // are used as pointers to the current parameter type information
rfield@2614 828 // and are thus not usable afterwards.
rfield@2614 829 for (int i = 0; implPTypes.nonEmpty() && i < last; ++i) {
rfield@2614 830 // By default use the implementation method parmeter type
rfield@2614 831 Type parmType = implPTypes.head;
rfield@2614 832 // If the unerased parameter type is a type variable whose
rfield@2614 833 // bound is an intersection (eg. <T extends A & B>) then
rfield@2614 834 // use the SAM parameter type
rfield@2614 835 if (checkForIntersection && descPTypes.head.getKind() == TypeKind.TYPEVAR) {
rfield@2614 836 TypeVar tv = (TypeVar) descPTypes.head;
rfield@2614 837 if (tv.bound.getKind() == TypeKind.INTERSECTION) {
rfield@2614 838 parmType = samPTypes.head;
rfield@2614 839 }
aoqi@0 840 }
rfield@2614 841 addParameter("x$" + i, parmType, true);
rfield@2614 842
rfield@2614 843 // Advance to the next parameter
rfield@2614 844 implPTypes = implPTypes.tail;
rfield@2614 845 samPTypes = samPTypes.tail;
rfield@2614 846 descPTypes = descPTypes.tail;
rfield@2614 847 }
rfield@2614 848 // Flatten out the var args
rfield@2614 849 for (int i = last; i < samSize; ++i) {
rfield@2614 850 addParameter("xva$" + i, tree.varargsElement, true);
aoqi@0 851 }
aoqi@0 852
rfield@2614 853 return rcvr;
rfield@2614 854 }
rfield@2614 855
rfield@2607 856 JCExpression getReceiverExpression() {
rfield@2607 857 return receiverExpression;
rfield@2607 858 }
rfield@2607 859
rfield@2607 860 private JCExpression makeReceiver(VarSymbol rcvr) {
rfield@2607 861 if (rcvr == null) return null;
rfield@2607 862 JCExpression rcvrExpr = make.Ident(rcvr);
rfield@2607 863 Type rcvrType = tree.sym.enclClass().type;
rfield@2607 864 if (rcvrType == syms.arrayClass.type) {
rfield@2607 865 // Map the receiver type to the actually type, not just "array"
rfield@2607 866 rcvrType = tree.getQualifierExpression().type;
rfield@2381 867 }
rfield@2607 868 if (!rcvr.type.tsym.isSubClass(rcvrType.tsym, types)) {
rfield@2607 869 rcvrExpr = make.TypeCast(make.Type(rcvrType), rcvrExpr).setType(rcvrType);
rfield@2607 870 }
rfield@2607 871 return rcvrExpr;
rfield@2607 872 }
rfield@2381 873
aoqi@0 874 /**
rfield@2607 875 * determine the receiver of the method call - the receiver can
rfield@2607 876 * be a type qualifier, the synthetic receiver parameter or 'super'.
aoqi@0 877 */
rfield@2607 878 private JCExpression expressionInvoke(VarSymbol rcvr) {
aoqi@0 879 JCExpression qualifier =
aoqi@0 880 tree.sym.isStatic() ?
aoqi@0 881 make.Type(tree.sym.owner.type) :
aoqi@0 882 (rcvr != null) ?
rfield@2607 883 makeReceiver(rcvr) :
aoqi@0 884 tree.getQualifierExpression();
aoqi@0 885
aoqi@0 886 //create the qualifier expression
aoqi@0 887 JCFieldAccess select = make.Select(qualifier, tree.sym.name);
aoqi@0 888 select.sym = tree.sym;
aoqi@0 889 select.type = tree.sym.erasure(types);
aoqi@0 890
aoqi@0 891 //create the method call expression
aoqi@0 892 JCExpression apply = make.Apply(List.<JCExpression>nil(), select,
aoqi@0 893 convertArgs(tree.sym, args.toList(), tree.varargsElement)).
aoqi@0 894 setType(tree.sym.erasure(types).getReturnType());
aoqi@0 895
aoqi@0 896 apply = transTypes.coerce(apply, localContext.generatedRefSig().getReturnType());
aoqi@0 897 setVarargsIfNeeded(apply, tree.varargsElement);
aoqi@0 898 return apply;
aoqi@0 899 }
aoqi@0 900
aoqi@0 901 /**
rfield@2607 902 * Lambda body to use for a 'new'.
aoqi@0 903 */
rfield@2607 904 private JCExpression expressionNew() {
aoqi@0 905 if (tree.kind == ReferenceKind.ARRAY_CTOR) {
aoqi@0 906 //create the array creation expression
aoqi@0 907 JCNewArray newArr = make.NewArray(
aoqi@0 908 make.Type(types.elemtype(tree.getQualifierExpression().type)),
aoqi@0 909 List.of(make.Ident(params.first())),
aoqi@0 910 null);
aoqi@0 911 newArr.type = tree.getQualifierExpression().type;
aoqi@0 912 return newArr;
aoqi@0 913 } else {
aoqi@0 914 //create the instance creation expression
rfield@2607 915 //note that method reference syntax does not allow an explicit
rfield@2607 916 //enclosing class (so the enclosing class is null)
rfield@2607 917 JCNewClass newClass = make.NewClass(null,
aoqi@0 918 List.<JCExpression>nil(),
aoqi@0 919 make.Type(tree.getQualifierExpression().type),
aoqi@0 920 convertArgs(tree.sym, args.toList(), tree.varargsElement),
aoqi@0 921 null);
aoqi@0 922 newClass.constructor = tree.sym;
aoqi@0 923 newClass.constructorType = tree.sym.erasure(types);
aoqi@0 924 newClass.type = tree.getQualifierExpression().type;
aoqi@0 925 setVarargsIfNeeded(newClass, tree.varargsElement);
aoqi@0 926 return newClass;
aoqi@0 927 }
aoqi@0 928 }
aoqi@0 929
aoqi@0 930 private VarSymbol addParameter(String name, Type p, boolean genArg) {
rfield@2607 931 VarSymbol vsym = new VarSymbol(PARAMETER | SYNTHETIC, names.fromString(name), p, owner);
rfield@2607 932 vsym.pos = tree.pos;
aoqi@0 933 params.append(make.VarDef(vsym, null));
aoqi@0 934 if (genArg) {
aoqi@0 935 args.append(make.Ident(vsym));
aoqi@0 936 }
aoqi@0 937 return vsym;
aoqi@0 938 }
aoqi@0 939 }
aoqi@0 940
aoqi@0 941 private MethodType typeToMethodType(Type mt) {
aoqi@0 942 Type type = types.erasure(mt);
aoqi@0 943 return new MethodType(type.getParameterTypes(),
aoqi@0 944 type.getReturnType(),
aoqi@0 945 type.getThrownTypes(),
aoqi@0 946 syms.methodClass);
aoqi@0 947 }
aoqi@0 948
aoqi@0 949 /**
aoqi@0 950 * Generate an indy method call to the meta factory
aoqi@0 951 */
aoqi@0 952 private JCExpression makeMetafactoryIndyCall(TranslationContext<?> context,
aoqi@0 953 int refKind, Symbol refSym, List<JCExpression> indy_args) {
aoqi@0 954 JCFunctionalExpression tree = context.tree;
aoqi@0 955 //determine the static bsm args
aoqi@0 956 MethodSymbol samSym = (MethodSymbol) types.findDescriptorSymbol(tree.type.tsym);
aoqi@0 957 List<Object> staticArgs = List.<Object>of(
aoqi@0 958 typeToMethodType(samSym.type),
aoqi@0 959 new Pool.MethodHandle(refKind, refSym, types),
aoqi@0 960 typeToMethodType(tree.getDescriptorType(types)));
aoqi@0 961
aoqi@0 962 //computed indy arg types
aoqi@0 963 ListBuffer<Type> indy_args_types = new ListBuffer<>();
aoqi@0 964 for (JCExpression arg : indy_args) {
aoqi@0 965 indy_args_types.append(arg.type);
aoqi@0 966 }
aoqi@0 967
aoqi@0 968 //finally, compute the type of the indy call
aoqi@0 969 MethodType indyType = new MethodType(indy_args_types.toList(),
aoqi@0 970 tree.type,
aoqi@0 971 List.<Type>nil(),
aoqi@0 972 syms.methodClass);
aoqi@0 973
aoqi@0 974 Name metafactoryName = context.needsAltMetafactory() ?
aoqi@0 975 names.altMetafactory : names.metafactory;
aoqi@0 976
aoqi@0 977 if (context.needsAltMetafactory()) {
aoqi@0 978 ListBuffer<Object> markers = new ListBuffer<>();
aoqi@0 979 for (Type t : tree.targets.tail) {
aoqi@0 980 if (t.tsym != syms.serializableType.tsym) {
aoqi@0 981 markers.append(t.tsym);
aoqi@0 982 }
aoqi@0 983 }
aoqi@0 984 int flags = context.isSerializable() ? FLAG_SERIALIZABLE : 0;
aoqi@0 985 boolean hasMarkers = markers.nonEmpty();
aoqi@0 986 boolean hasBridges = context.bridges.nonEmpty();
aoqi@0 987 if (hasMarkers) {
aoqi@0 988 flags |= FLAG_MARKERS;
aoqi@0 989 }
aoqi@0 990 if (hasBridges) {
aoqi@0 991 flags |= FLAG_BRIDGES;
aoqi@0 992 }
aoqi@0 993 staticArgs = staticArgs.append(flags);
aoqi@0 994 if (hasMarkers) {
aoqi@0 995 staticArgs = staticArgs.append(markers.length());
aoqi@0 996 staticArgs = staticArgs.appendList(markers.toList());
aoqi@0 997 }
aoqi@0 998 if (hasBridges) {
aoqi@0 999 staticArgs = staticArgs.append(context.bridges.length() - 1);
aoqi@0 1000 for (Symbol s : context.bridges) {
aoqi@0 1001 Type s_erasure = s.erasure(types);
aoqi@0 1002 if (!types.isSameType(s_erasure, samSym.erasure(types))) {
aoqi@0 1003 staticArgs = staticArgs.append(s.erasure(types));
aoqi@0 1004 }
aoqi@0 1005 }
aoqi@0 1006 }
aoqi@0 1007 if (context.isSerializable()) {
aoqi@0 1008 int prevPos = make.pos;
aoqi@0 1009 try {
aoqi@0 1010 make.at(kInfo.clazz);
aoqi@0 1011 addDeserializationCase(refKind, refSym, tree.type, samSym,
aoqi@0 1012 tree, staticArgs, indyType);
aoqi@0 1013 } finally {
aoqi@0 1014 make.at(prevPos);
aoqi@0 1015 }
aoqi@0 1016 }
aoqi@0 1017 }
aoqi@0 1018
aoqi@0 1019 return makeIndyCall(tree, syms.lambdaMetafactory, metafactoryName, staticArgs, indyType, indy_args, samSym.name);
aoqi@0 1020 }
aoqi@0 1021
aoqi@0 1022 /**
aoqi@0 1023 * Generate an indy method call with given name, type and static bootstrap
aoqi@0 1024 * arguments types
aoqi@0 1025 */
aoqi@0 1026 private JCExpression makeIndyCall(DiagnosticPosition pos, Type site, Name bsmName,
aoqi@0 1027 List<Object> staticArgs, MethodType indyType, List<JCExpression> indyArgs,
aoqi@0 1028 Name methName) {
aoqi@0 1029 int prevPos = make.pos;
aoqi@0 1030 try {
aoqi@0 1031 make.at(pos);
aoqi@0 1032 List<Type> bsm_staticArgs = List.of(syms.methodHandleLookupType,
aoqi@0 1033 syms.stringType,
aoqi@0 1034 syms.methodTypeType).appendList(bsmStaticArgToTypes(staticArgs));
aoqi@0 1035
aoqi@0 1036 Symbol bsm = rs.resolveInternalMethod(pos, attrEnv, site,
aoqi@0 1037 bsmName, bsm_staticArgs, List.<Type>nil());
aoqi@0 1038
aoqi@0 1039 DynamicMethodSymbol dynSym =
aoqi@0 1040 new DynamicMethodSymbol(methName,
aoqi@0 1041 syms.noSymbol,
aoqi@0 1042 bsm.isStatic() ?
aoqi@0 1043 ClassFile.REF_invokeStatic :
aoqi@0 1044 ClassFile.REF_invokeVirtual,
aoqi@0 1045 (MethodSymbol)bsm,
aoqi@0 1046 indyType,
aoqi@0 1047 staticArgs.toArray());
aoqi@0 1048
aoqi@0 1049 JCFieldAccess qualifier = make.Select(make.QualIdent(site.tsym), bsmName);
aoqi@0 1050 qualifier.sym = dynSym;
aoqi@0 1051 qualifier.type = indyType.getReturnType();
aoqi@0 1052
aoqi@0 1053 JCMethodInvocation proxyCall = make.Apply(List.<JCExpression>nil(), qualifier, indyArgs);
aoqi@0 1054 proxyCall.type = indyType.getReturnType();
aoqi@0 1055 return proxyCall;
aoqi@0 1056 } finally {
aoqi@0 1057 make.at(prevPos);
aoqi@0 1058 }
aoqi@0 1059 }
aoqi@0 1060 //where
aoqi@0 1061 private List<Type> bsmStaticArgToTypes(List<Object> args) {
aoqi@0 1062 ListBuffer<Type> argtypes = new ListBuffer<>();
aoqi@0 1063 for (Object arg : args) {
aoqi@0 1064 argtypes.append(bsmStaticArgToType(arg));
aoqi@0 1065 }
aoqi@0 1066 return argtypes.toList();
aoqi@0 1067 }
aoqi@0 1068
aoqi@0 1069 private Type bsmStaticArgToType(Object arg) {
aoqi@0 1070 Assert.checkNonNull(arg);
aoqi@0 1071 if (arg instanceof ClassSymbol) {
aoqi@0 1072 return syms.classType;
aoqi@0 1073 } else if (arg instanceof Integer) {
aoqi@0 1074 return syms.intType;
aoqi@0 1075 } else if (arg instanceof Long) {
aoqi@0 1076 return syms.longType;
aoqi@0 1077 } else if (arg instanceof Float) {
aoqi@0 1078 return syms.floatType;
aoqi@0 1079 } else if (arg instanceof Double) {
aoqi@0 1080 return syms.doubleType;
aoqi@0 1081 } else if (arg instanceof String) {
aoqi@0 1082 return syms.stringType;
aoqi@0 1083 } else if (arg instanceof Pool.MethodHandle) {
aoqi@0 1084 return syms.methodHandleType;
aoqi@0 1085 } else if (arg instanceof MethodType) {
aoqi@0 1086 return syms.methodTypeType;
aoqi@0 1087 } else {
aoqi@0 1088 Assert.error("bad static arg " + arg.getClass());
aoqi@0 1089 return null;
aoqi@0 1090 }
aoqi@0 1091 }
aoqi@0 1092
aoqi@0 1093 /**
aoqi@0 1094 * Get the opcode associated with this method reference
aoqi@0 1095 */
aoqi@0 1096 private int referenceKind(Symbol refSym) {
aoqi@0 1097 if (refSym.isConstructor()) {
aoqi@0 1098 return ClassFile.REF_newInvokeSpecial;
aoqi@0 1099 } else {
aoqi@0 1100 if (refSym.isStatic()) {
aoqi@0 1101 return ClassFile.REF_invokeStatic;
aoqi@0 1102 } else if ((refSym.flags() & PRIVATE) != 0) {
aoqi@0 1103 return ClassFile.REF_invokeSpecial;
aoqi@0 1104 } else if (refSym.enclClass().isInterface()) {
aoqi@0 1105 return ClassFile.REF_invokeInterface;
aoqi@0 1106 } else {
aoqi@0 1107 return ClassFile.REF_invokeVirtual;
aoqi@0 1108 }
aoqi@0 1109 }
aoqi@0 1110 }
aoqi@0 1111
aoqi@0 1112 // <editor-fold defaultstate="collapsed" desc="Lambda/reference analyzer">
aoqi@0 1113 /**
aoqi@0 1114 * This visitor collects information about translation of a lambda expression.
aoqi@0 1115 * More specifically, it keeps track of the enclosing contexts and captured locals
aoqi@0 1116 * accessed by the lambda being translated (as well as other useful info).
aoqi@0 1117 * It also translates away problems for LambdaToMethod.
aoqi@0 1118 */
aoqi@0 1119 class LambdaAnalyzerPreprocessor extends TreeTranslator {
aoqi@0 1120
aoqi@0 1121 /** the frame stack - used to reconstruct translation info about enclosing scopes */
aoqi@0 1122 private List<Frame> frameStack;
aoqi@0 1123
aoqi@0 1124 /**
aoqi@0 1125 * keep the count of lambda expression (used to generate unambiguous
aoqi@0 1126 * names)
aoqi@0 1127 */
aoqi@0 1128 private int lambdaCount = 0;
aoqi@0 1129
aoqi@0 1130 /**
aoqi@0 1131 * keep the count of lambda expression defined in given context (used to
aoqi@0 1132 * generate unambiguous names for serializable lambdas)
aoqi@0 1133 */
aoqi@0 1134 private class SyntheticMethodNameCounter {
aoqi@0 1135 private Map<String, Integer> map = new HashMap<>();
aoqi@0 1136 int getIndex(StringBuilder buf) {
aoqi@0 1137 String temp = buf.toString();
aoqi@0 1138 Integer count = map.get(temp);
aoqi@0 1139 if (count == null) {
aoqi@0 1140 count = 0;
aoqi@0 1141 }
aoqi@0 1142 ++count;
aoqi@0 1143 map.put(temp, count);
aoqi@0 1144 return count;
aoqi@0 1145 }
aoqi@0 1146 }
aoqi@0 1147 private SyntheticMethodNameCounter syntheticMethodNameCounts =
aoqi@0 1148 new SyntheticMethodNameCounter();
aoqi@0 1149
aoqi@0 1150 private Map<Symbol, JCClassDecl> localClassDefs;
aoqi@0 1151
aoqi@0 1152 /**
aoqi@0 1153 * maps for fake clinit symbols to be used as owners of lambda occurring in
aoqi@0 1154 * a static var init context
aoqi@0 1155 */
aoqi@0 1156 private Map<ClassSymbol, Symbol> clinits =
aoqi@0 1157 new HashMap<ClassSymbol, Symbol>();
aoqi@0 1158
aoqi@0 1159 private JCClassDecl analyzeAndPreprocessClass(JCClassDecl tree) {
aoqi@0 1160 frameStack = List.nil();
aoqi@0 1161 localClassDefs = new HashMap<Symbol, JCClassDecl>();
aoqi@0 1162 return translate(tree);
aoqi@0 1163 }
aoqi@0 1164
aoqi@0 1165 @Override
aoqi@0 1166 public void visitBlock(JCBlock tree) {
aoqi@0 1167 List<Frame> prevStack = frameStack;
aoqi@0 1168 try {
aoqi@0 1169 if (frameStack.nonEmpty() && frameStack.head.tree.hasTag(CLASSDEF)) {
aoqi@0 1170 frameStack = frameStack.prepend(new Frame(tree));
aoqi@0 1171 }
aoqi@0 1172 super.visitBlock(tree);
aoqi@0 1173 }
aoqi@0 1174 finally {
aoqi@0 1175 frameStack = prevStack;
aoqi@0 1176 }
aoqi@0 1177 }
aoqi@0 1178
aoqi@0 1179 @Override
aoqi@0 1180 public void visitClassDef(JCClassDecl tree) {
aoqi@0 1181 List<Frame> prevStack = frameStack;
aoqi@0 1182 SyntheticMethodNameCounter prevSyntheticMethodNameCounts =
aoqi@0 1183 syntheticMethodNameCounts;
aoqi@0 1184 Map<ClassSymbol, Symbol> prevClinits = clinits;
aoqi@0 1185 DiagnosticSource prevSource = log.currentSource();
aoqi@0 1186 try {
aoqi@0 1187 log.useSource(tree.sym.sourcefile);
aoqi@0 1188 syntheticMethodNameCounts = new SyntheticMethodNameCounter();
aoqi@0 1189 prevClinits = new HashMap<ClassSymbol, Symbol>();
aoqi@0 1190 if (tree.sym.owner.kind == MTH) {
aoqi@0 1191 localClassDefs.put(tree.sym, tree);
aoqi@0 1192 }
aoqi@0 1193 if (directlyEnclosingLambda() != null) {
aoqi@0 1194 tree.sym.owner = owner();
aoqi@0 1195 if (tree.sym.hasOuterInstance()) {
aoqi@0 1196 //if a class is defined within a lambda, the lambda must capture
aoqi@0 1197 //its enclosing instance (if any)
aoqi@0 1198 TranslationContext<?> localContext = context();
aoqi@0 1199 while (localContext != null) {
aoqi@0 1200 if (localContext.tree.getTag() == LAMBDA) {
aoqi@0 1201 ((LambdaTranslationContext)localContext)
aoqi@0 1202 .addSymbol(tree.sym.type.getEnclosingType().tsym, CAPTURED_THIS);
aoqi@0 1203 }
aoqi@0 1204 localContext = localContext.prev;
aoqi@0 1205 }
aoqi@0 1206 }
aoqi@0 1207 }
aoqi@0 1208 frameStack = frameStack.prepend(new Frame(tree));
aoqi@0 1209 super.visitClassDef(tree);
aoqi@0 1210 }
aoqi@0 1211 finally {
aoqi@0 1212 log.useSource(prevSource.getFile());
aoqi@0 1213 frameStack = prevStack;
aoqi@0 1214 syntheticMethodNameCounts = prevSyntheticMethodNameCounts;
aoqi@0 1215 clinits = prevClinits;
aoqi@0 1216 }
aoqi@0 1217 }
aoqi@0 1218
aoqi@0 1219 @Override
aoqi@0 1220 public void visitIdent(JCIdent tree) {
aoqi@0 1221 if (context() != null && lambdaIdentSymbolFilter(tree.sym)) {
aoqi@0 1222 if (tree.sym.kind == VAR &&
aoqi@0 1223 tree.sym.owner.kind == MTH &&
aoqi@0 1224 tree.type.constValue() == null) {
aoqi@0 1225 TranslationContext<?> localContext = context();
aoqi@0 1226 while (localContext != null) {
aoqi@0 1227 if (localContext.tree.getTag() == LAMBDA) {
aoqi@0 1228 JCTree block = capturedDecl(localContext.depth, tree.sym);
aoqi@0 1229 if (block == null) break;
aoqi@0 1230 ((LambdaTranslationContext)localContext)
aoqi@0 1231 .addSymbol(tree.sym, CAPTURED_VAR);
aoqi@0 1232 }
aoqi@0 1233 localContext = localContext.prev;
aoqi@0 1234 }
aoqi@0 1235 } else if (tree.sym.owner.kind == TYP) {
aoqi@0 1236 TranslationContext<?> localContext = context();
aoqi@0 1237 while (localContext != null) {
aoqi@0 1238 if (localContext.tree.hasTag(LAMBDA)) {
aoqi@0 1239 JCTree block = capturedDecl(localContext.depth, tree.sym);
aoqi@0 1240 if (block == null) break;
aoqi@0 1241 switch (block.getTag()) {
aoqi@0 1242 case CLASSDEF:
aoqi@0 1243 JCClassDecl cdecl = (JCClassDecl)block;
aoqi@0 1244 ((LambdaTranslationContext)localContext)
aoqi@0 1245 .addSymbol(cdecl.sym, CAPTURED_THIS);
aoqi@0 1246 break;
aoqi@0 1247 default:
aoqi@0 1248 Assert.error("bad block kind");
aoqi@0 1249 }
aoqi@0 1250 }
aoqi@0 1251 localContext = localContext.prev;
aoqi@0 1252 }
aoqi@0 1253 }
aoqi@0 1254 }
aoqi@0 1255 super.visitIdent(tree);
aoqi@0 1256 }
aoqi@0 1257
aoqi@0 1258 @Override
aoqi@0 1259 public void visitLambda(JCLambda tree) {
rfield@2607 1260 analyzeLambda(tree, "lambda.stat");
rfield@2607 1261 }
rfield@2607 1262
rfield@2607 1263 private void analyzeLambda(JCLambda tree, JCExpression methodReferenceReceiver) {
rfield@2607 1264 // Translation of the receiver expression must occur first
rfield@2607 1265 JCExpression rcvr = translate(methodReferenceReceiver);
rfield@2607 1266 LambdaTranslationContext context = analyzeLambda(tree, "mref.stat.1");
rfield@2607 1267 if (rcvr != null) {
rfield@2607 1268 context.methodReferenceReceiver = rcvr;
rfield@2607 1269 }
rfield@2607 1270 }
rfield@2607 1271
rfield@2607 1272 private LambdaTranslationContext analyzeLambda(JCLambda tree, String statKey) {
aoqi@0 1273 List<Frame> prevStack = frameStack;
aoqi@0 1274 try {
rfield@2607 1275 LambdaTranslationContext context = new LambdaTranslationContext(tree);
rfield@2607 1276 if (dumpLambdaToMethodStats) {
rfield@2607 1277 log.note(tree, statKey, context.needsAltMetafactory(), context.translatedSym);
rfield@2607 1278 }
aoqi@0 1279 frameStack = frameStack.prepend(new Frame(tree));
aoqi@0 1280 for (JCVariableDecl param : tree.params) {
aoqi@0 1281 context.addSymbol(param.sym, PARAM);
aoqi@0 1282 frameStack.head.addLocal(param.sym);
aoqi@0 1283 }
aoqi@0 1284 contextMap.put(tree, context);
aoqi@0 1285 super.visitLambda(tree);
aoqi@0 1286 context.complete();
rfield@2607 1287 return context;
aoqi@0 1288 }
aoqi@0 1289 finally {
aoqi@0 1290 frameStack = prevStack;
aoqi@0 1291 }
aoqi@0 1292 }
aoqi@0 1293
aoqi@0 1294 @Override
aoqi@0 1295 public void visitMethodDef(JCMethodDecl tree) {
aoqi@0 1296 List<Frame> prevStack = frameStack;
aoqi@0 1297 try {
aoqi@0 1298 frameStack = frameStack.prepend(new Frame(tree));
aoqi@0 1299 super.visitMethodDef(tree);
aoqi@0 1300 }
aoqi@0 1301 finally {
aoqi@0 1302 frameStack = prevStack;
aoqi@0 1303 }
aoqi@0 1304 }
aoqi@0 1305
aoqi@0 1306 @Override
aoqi@0 1307 public void visitNewClass(JCNewClass tree) {
aoqi@0 1308 TypeSymbol def = tree.type.tsym;
aoqi@0 1309 boolean inReferencedClass = currentlyInClass(def);
aoqi@0 1310 boolean isLocal = def.isLocal();
aoqi@0 1311 if ((inReferencedClass && isLocal || lambdaNewClassFilter(context(), tree))) {
aoqi@0 1312 TranslationContext<?> localContext = context();
aoqi@0 1313 while (localContext != null) {
aoqi@0 1314 if (localContext.tree.getTag() == LAMBDA) {
aoqi@0 1315 ((LambdaTranslationContext)localContext)
aoqi@0 1316 .addSymbol(tree.type.getEnclosingType().tsym, CAPTURED_THIS);
aoqi@0 1317 }
aoqi@0 1318 localContext = localContext.prev;
aoqi@0 1319 }
aoqi@0 1320 }
aoqi@0 1321 if (context() != null && !inReferencedClass && isLocal) {
aoqi@0 1322 LambdaTranslationContext lambdaContext = (LambdaTranslationContext)context();
aoqi@0 1323 captureLocalClassDefs(def, lambdaContext);
aoqi@0 1324 }
aoqi@0 1325 super.visitNewClass(tree);
aoqi@0 1326 }
aoqi@0 1327 //where
aoqi@0 1328 void captureLocalClassDefs(Symbol csym, final LambdaTranslationContext lambdaContext) {
aoqi@0 1329 JCClassDecl localCDef = localClassDefs.get(csym);
aoqi@0 1330 if (localCDef != null && lambdaContext.freeVarProcessedLocalClasses.add(csym)) {
aoqi@0 1331 BasicFreeVarCollector fvc = lower.new BasicFreeVarCollector() {
aoqi@0 1332 @Override
aoqi@0 1333 void addFreeVars(ClassSymbol c) {
aoqi@0 1334 captureLocalClassDefs(c, lambdaContext);
aoqi@0 1335 }
aoqi@0 1336 @Override
aoqi@0 1337 void visitSymbol(Symbol sym) {
aoqi@0 1338 if (sym.kind == VAR &&
aoqi@0 1339 sym.owner.kind == MTH &&
aoqi@0 1340 ((VarSymbol)sym).getConstValue() == null) {
aoqi@0 1341 TranslationContext<?> localContext = context();
aoqi@0 1342 while (localContext != null) {
aoqi@0 1343 if (localContext.tree.getTag() == LAMBDA) {
aoqi@0 1344 JCTree block = capturedDecl(localContext.depth, sym);
aoqi@0 1345 if (block == null) break;
aoqi@0 1346 ((LambdaTranslationContext)localContext).addSymbol(sym, CAPTURED_VAR);
aoqi@0 1347 }
aoqi@0 1348 localContext = localContext.prev;
aoqi@0 1349 }
aoqi@0 1350 }
aoqi@0 1351 }
aoqi@0 1352 };
aoqi@0 1353 fvc.scan(localCDef);
aoqi@0 1354 }
aoqi@0 1355 }
aoqi@0 1356 //where
aoqi@0 1357 boolean currentlyInClass(Symbol csym) {
aoqi@0 1358 for (Frame frame : frameStack) {
aoqi@0 1359 if (frame.tree.hasTag(JCTree.Tag.CLASSDEF)) {
aoqi@0 1360 JCClassDecl cdef = (JCClassDecl) frame.tree;
aoqi@0 1361 if (cdef.sym == csym) {
aoqi@0 1362 return true;
aoqi@0 1363 }
aoqi@0 1364 }
aoqi@0 1365 }
aoqi@0 1366 return false;
aoqi@0 1367 }
aoqi@0 1368
aoqi@0 1369 /**
aoqi@0 1370 * Method references to local class constructors, may, if the local
aoqi@0 1371 * class references local variables, have implicit constructor
aoqi@0 1372 * parameters added in Lower; As a result, the invokedynamic bootstrap
aoqi@0 1373 * information added in the LambdaToMethod pass will have the wrong
aoqi@0 1374 * signature. Hooks between Lower and LambdaToMethod have been added to
aoqi@0 1375 * handle normal "new" in this case. This visitor converts potentially
rfield@2607 1376 * affected method references into a lambda containing a normal
rfield@2607 1377 * expression.
aoqi@0 1378 *
aoqi@0 1379 * @param tree
aoqi@0 1380 */
aoqi@0 1381 @Override
aoqi@0 1382 public void visitReference(JCMemberReference tree) {
rfield@2607 1383 ReferenceTranslationContext rcontext = new ReferenceTranslationContext(tree);
rfield@2607 1384 contextMap.put(tree, rcontext);
rfield@2607 1385 if (rcontext.needsConversionToLambda()) {
rfield@2607 1386 // Convert to a lambda, and process as such
rfield@2607 1387 MemberReferenceToLambda conv = new MemberReferenceToLambda(tree, rcontext, owner());
rfield@2607 1388 analyzeLambda(conv.lambda(), conv.getReceiverExpression());
aoqi@0 1389 } else {
aoqi@0 1390 super.visitReference(tree);
rfield@2607 1391 if (dumpLambdaToMethodStats) {
rfield@2607 1392 log.note(tree, "mref.stat", rcontext.needsAltMetafactory(), null);
rfield@2607 1393 }
aoqi@0 1394 }
aoqi@0 1395 }
aoqi@0 1396
aoqi@0 1397 @Override
aoqi@0 1398 public void visitSelect(JCFieldAccess tree) {
aoqi@0 1399 if (context() != null && tree.sym.kind == VAR &&
aoqi@0 1400 (tree.sym.name == names._this ||
aoqi@0 1401 tree.sym.name == names._super)) {
aoqi@0 1402 // A select of this or super means, if we are in a lambda,
aoqi@0 1403 // we much have an instance context
aoqi@0 1404 TranslationContext<?> localContext = context();
aoqi@0 1405 while (localContext != null) {
aoqi@0 1406 if (localContext.tree.hasTag(LAMBDA)) {
aoqi@0 1407 JCClassDecl clazz = (JCClassDecl)capturedDecl(localContext.depth, tree.sym);
aoqi@0 1408 if (clazz == null) break;
aoqi@0 1409 ((LambdaTranslationContext)localContext).addSymbol(clazz.sym, CAPTURED_THIS);
aoqi@0 1410 }
aoqi@0 1411 localContext = localContext.prev;
aoqi@0 1412 }
aoqi@0 1413 }
aoqi@0 1414 super.visitSelect(tree);
aoqi@0 1415 }
aoqi@0 1416
aoqi@0 1417 @Override
aoqi@0 1418 public void visitVarDef(JCVariableDecl tree) {
aoqi@0 1419 TranslationContext<?> context = context();
aoqi@0 1420 LambdaTranslationContext ltc = (context != null && context instanceof LambdaTranslationContext)?
aoqi@0 1421 (LambdaTranslationContext)context :
aoqi@0 1422 null;
aoqi@0 1423 if (ltc != null) {
aoqi@0 1424 if (frameStack.head.tree.hasTag(LAMBDA)) {
aoqi@0 1425 ltc.addSymbol(tree.sym, LOCAL_VAR);
aoqi@0 1426 }
aoqi@0 1427 // Check for type variables (including as type arguments).
aoqi@0 1428 // If they occur within class nested in a lambda, mark for erasure
aoqi@0 1429 Type type = tree.sym.asType();
aoqi@0 1430 if (inClassWithinLambda() && !types.isSameType(types.erasure(type), type)) {
aoqi@0 1431 ltc.addSymbol(tree.sym, TYPE_VAR);
aoqi@0 1432 }
aoqi@0 1433 }
aoqi@0 1434
aoqi@0 1435 List<Frame> prevStack = frameStack;
aoqi@0 1436 try {
aoqi@0 1437 if (tree.sym.owner.kind == MTH) {
aoqi@0 1438 frameStack.head.addLocal(tree.sym);
aoqi@0 1439 }
aoqi@0 1440 frameStack = frameStack.prepend(new Frame(tree));
aoqi@0 1441 super.visitVarDef(tree);
aoqi@0 1442 }
aoqi@0 1443 finally {
aoqi@0 1444 frameStack = prevStack;
aoqi@0 1445 }
aoqi@0 1446 }
aoqi@0 1447
aoqi@0 1448 /**
aoqi@0 1449 * Return a valid owner given the current declaration stack
aoqi@0 1450 * (required to skip synthetic lambda symbols)
aoqi@0 1451 */
aoqi@0 1452 private Symbol owner() {
aoqi@0 1453 return owner(false);
aoqi@0 1454 }
aoqi@0 1455
aoqi@0 1456 @SuppressWarnings("fallthrough")
aoqi@0 1457 private Symbol owner(boolean skipLambda) {
aoqi@0 1458 List<Frame> frameStack2 = frameStack;
aoqi@0 1459 while (frameStack2.nonEmpty()) {
aoqi@0 1460 switch (frameStack2.head.tree.getTag()) {
aoqi@0 1461 case VARDEF:
aoqi@0 1462 if (((JCVariableDecl)frameStack2.head.tree).sym.isLocal()) {
aoqi@0 1463 frameStack2 = frameStack2.tail;
aoqi@0 1464 break;
aoqi@0 1465 }
aoqi@0 1466 JCClassDecl cdecl = (JCClassDecl)frameStack2.tail.head.tree;
aoqi@0 1467 return initSym(cdecl.sym,
aoqi@0 1468 ((JCVariableDecl)frameStack2.head.tree).sym.flags() & STATIC);
aoqi@0 1469 case BLOCK:
aoqi@0 1470 JCClassDecl cdecl2 = (JCClassDecl)frameStack2.tail.head.tree;
aoqi@0 1471 return initSym(cdecl2.sym,
aoqi@0 1472 ((JCBlock)frameStack2.head.tree).flags & STATIC);
aoqi@0 1473 case CLASSDEF:
aoqi@0 1474 return ((JCClassDecl)frameStack2.head.tree).sym;
aoqi@0 1475 case METHODDEF:
aoqi@0 1476 return ((JCMethodDecl)frameStack2.head.tree).sym;
aoqi@0 1477 case LAMBDA:
aoqi@0 1478 if (!skipLambda)
aoqi@0 1479 return ((LambdaTranslationContext)contextMap
aoqi@0 1480 .get(frameStack2.head.tree)).translatedSym;
aoqi@0 1481 default:
aoqi@0 1482 frameStack2 = frameStack2.tail;
aoqi@0 1483 }
aoqi@0 1484 }
aoqi@0 1485 Assert.error();
aoqi@0 1486 return null;
aoqi@0 1487 }
aoqi@0 1488
aoqi@0 1489 private Symbol initSym(ClassSymbol csym, long flags) {
aoqi@0 1490 boolean isStatic = (flags & STATIC) != 0;
aoqi@0 1491 if (isStatic) {
aoqi@0 1492 /* static clinits are generated in Gen, so we need to use a fake
aoqi@0 1493 * one. Attr creates a fake clinit method while attributing
aoqi@0 1494 * lambda expressions used as initializers of static fields, so
aoqi@0 1495 * let's use that one.
aoqi@0 1496 */
aoqi@0 1497 MethodSymbol clinit = attr.removeClinit(csym);
aoqi@0 1498 if (clinit != null) {
aoqi@0 1499 clinits.put(csym, clinit);
aoqi@0 1500 return clinit;
aoqi@0 1501 }
aoqi@0 1502
aoqi@0 1503 /* if no clinit is found at Attr, then let's try at clinits.
aoqi@0 1504 */
aoqi@0 1505 clinit = (MethodSymbol)clinits.get(csym);
aoqi@0 1506 if (clinit == null) {
aoqi@0 1507 /* no luck, let's create a new one
aoqi@0 1508 */
aoqi@0 1509 clinit = makePrivateSyntheticMethod(STATIC,
aoqi@0 1510 names.clinit,
aoqi@0 1511 new MethodType(List.<Type>nil(), syms.voidType,
aoqi@0 1512 List.<Type>nil(), syms.methodClass),
aoqi@0 1513 csym);
aoqi@0 1514 clinits.put(csym, clinit);
aoqi@0 1515 }
aoqi@0 1516 return clinit;
aoqi@0 1517 } else {
aoqi@0 1518 //get the first constructor and treat it as the instance init sym
aoqi@0 1519 for (Symbol s : csym.members_field.getElementsByName(names.init)) {
aoqi@0 1520 return s;
aoqi@0 1521 }
aoqi@0 1522 }
aoqi@0 1523 Assert.error("init not found");
aoqi@0 1524 return null;
aoqi@0 1525 }
aoqi@0 1526
aoqi@0 1527 private JCTree directlyEnclosingLambda() {
aoqi@0 1528 if (frameStack.isEmpty()) {
aoqi@0 1529 return null;
aoqi@0 1530 }
aoqi@0 1531 List<Frame> frameStack2 = frameStack;
aoqi@0 1532 while (frameStack2.nonEmpty()) {
aoqi@0 1533 switch (frameStack2.head.tree.getTag()) {
aoqi@0 1534 case CLASSDEF:
aoqi@0 1535 case METHODDEF:
aoqi@0 1536 return null;
aoqi@0 1537 case LAMBDA:
aoqi@0 1538 return frameStack2.head.tree;
aoqi@0 1539 default:
aoqi@0 1540 frameStack2 = frameStack2.tail;
aoqi@0 1541 }
aoqi@0 1542 }
aoqi@0 1543 Assert.error();
aoqi@0 1544 return null;
aoqi@0 1545 }
aoqi@0 1546
aoqi@0 1547 private boolean inClassWithinLambda() {
aoqi@0 1548 if (frameStack.isEmpty()) {
aoqi@0 1549 return false;
aoqi@0 1550 }
aoqi@0 1551 List<Frame> frameStack2 = frameStack;
aoqi@0 1552 boolean classFound = false;
aoqi@0 1553 while (frameStack2.nonEmpty()) {
aoqi@0 1554 switch (frameStack2.head.tree.getTag()) {
aoqi@0 1555 case LAMBDA:
aoqi@0 1556 return classFound;
aoqi@0 1557 case CLASSDEF:
aoqi@0 1558 classFound = true;
aoqi@0 1559 frameStack2 = frameStack2.tail;
aoqi@0 1560 break;
aoqi@0 1561 default:
aoqi@0 1562 frameStack2 = frameStack2.tail;
aoqi@0 1563 }
aoqi@0 1564 }
aoqi@0 1565 // No lambda
aoqi@0 1566 return false;
aoqi@0 1567 }
aoqi@0 1568
aoqi@0 1569 /**
aoqi@0 1570 * Return the declaration corresponding to a symbol in the enclosing
aoqi@0 1571 * scope; the depth parameter is used to filter out symbols defined
aoqi@0 1572 * in nested scopes (which do not need to undergo capture).
aoqi@0 1573 */
aoqi@0 1574 private JCTree capturedDecl(int depth, Symbol sym) {
aoqi@0 1575 int currentDepth = frameStack.size() - 1;
aoqi@0 1576 for (Frame block : frameStack) {
aoqi@0 1577 switch (block.tree.getTag()) {
aoqi@0 1578 case CLASSDEF:
aoqi@0 1579 ClassSymbol clazz = ((JCClassDecl)block.tree).sym;
aoqi@0 1580 if (sym.isMemberOf(clazz, types)) {
aoqi@0 1581 return currentDepth > depth ? null : block.tree;
aoqi@0 1582 }
aoqi@0 1583 break;
aoqi@0 1584 case VARDEF:
aoqi@0 1585 if (((JCVariableDecl)block.tree).sym == sym &&
aoqi@0 1586 sym.owner.kind == MTH) { //only locals are captured
aoqi@0 1587 return currentDepth > depth ? null : block.tree;
aoqi@0 1588 }
aoqi@0 1589 break;
aoqi@0 1590 case BLOCK:
aoqi@0 1591 case METHODDEF:
aoqi@0 1592 case LAMBDA:
aoqi@0 1593 if (block.locals != null && block.locals.contains(sym)) {
aoqi@0 1594 return currentDepth > depth ? null : block.tree;
aoqi@0 1595 }
aoqi@0 1596 break;
aoqi@0 1597 default:
aoqi@0 1598 Assert.error("bad decl kind " + block.tree.getTag());
aoqi@0 1599 }
aoqi@0 1600 currentDepth--;
aoqi@0 1601 }
aoqi@0 1602 return null;
aoqi@0 1603 }
aoqi@0 1604
aoqi@0 1605 private TranslationContext<?> context() {
aoqi@0 1606 for (Frame frame : frameStack) {
aoqi@0 1607 TranslationContext<?> context = contextMap.get(frame.tree);
aoqi@0 1608 if (context != null) {
aoqi@0 1609 return context;
aoqi@0 1610 }
aoqi@0 1611 }
aoqi@0 1612 return null;
aoqi@0 1613 }
aoqi@0 1614
aoqi@0 1615 /**
aoqi@0 1616 * This is used to filter out those identifiers that needs to be adjusted
aoqi@0 1617 * when translating away lambda expressions
aoqi@0 1618 */
aoqi@0 1619 private boolean lambdaIdentSymbolFilter(Symbol sym) {
aoqi@0 1620 return (sym.kind == VAR || sym.kind == MTH)
aoqi@0 1621 && !sym.isStatic()
aoqi@0 1622 && sym.name != names.init;
aoqi@0 1623 }
aoqi@0 1624
aoqi@0 1625 /**
aoqi@0 1626 * This is used to filter out those new class expressions that need to
aoqi@0 1627 * be qualified with an enclosing tree
aoqi@0 1628 */
aoqi@0 1629 private boolean lambdaNewClassFilter(TranslationContext<?> context, JCNewClass tree) {
aoqi@0 1630 if (context != null
aoqi@0 1631 && tree.encl == null
aoqi@0 1632 && tree.def == null
aoqi@0 1633 && !tree.type.getEnclosingType().hasTag(NONE)) {
aoqi@0 1634 Type encl = tree.type.getEnclosingType();
aoqi@0 1635 Type current = context.owner.enclClass().type;
aoqi@0 1636 while (!current.hasTag(NONE)) {
aoqi@0 1637 if (current.tsym.isSubClass(encl.tsym, types)) {
aoqi@0 1638 return true;
aoqi@0 1639 }
aoqi@0 1640 current = current.getEnclosingType();
aoqi@0 1641 }
aoqi@0 1642 return false;
aoqi@0 1643 } else {
aoqi@0 1644 return false;
aoqi@0 1645 }
aoqi@0 1646 }
aoqi@0 1647
aoqi@0 1648 private class Frame {
aoqi@0 1649 final JCTree tree;
aoqi@0 1650 List<Symbol> locals;
aoqi@0 1651
aoqi@0 1652 public Frame(JCTree tree) {
aoqi@0 1653 this.tree = tree;
aoqi@0 1654 }
aoqi@0 1655
aoqi@0 1656 void addLocal(Symbol sym) {
aoqi@0 1657 if (locals == null) {
aoqi@0 1658 locals = List.nil();
aoqi@0 1659 }
aoqi@0 1660 locals = locals.prepend(sym);
aoqi@0 1661 }
aoqi@0 1662 }
aoqi@0 1663
aoqi@0 1664 /**
aoqi@0 1665 * This class is used to store important information regarding translation of
aoqi@0 1666 * lambda expression/method references (see subclasses).
aoqi@0 1667 */
aoqi@0 1668 private abstract class TranslationContext<T extends JCFunctionalExpression> {
aoqi@0 1669
aoqi@0 1670 /** the underlying (untranslated) tree */
aoqi@0 1671 final T tree;
aoqi@0 1672
aoqi@0 1673 /** points to the adjusted enclosing scope in which this lambda/mref expression occurs */
aoqi@0 1674 final Symbol owner;
aoqi@0 1675
aoqi@0 1676 /** the depth of this lambda expression in the frame stack */
aoqi@0 1677 final int depth;
aoqi@0 1678
aoqi@0 1679 /** the enclosing translation context (set for nested lambdas/mref) */
aoqi@0 1680 final TranslationContext<?> prev;
aoqi@0 1681
aoqi@0 1682 /** list of methods to be bridged by the meta-factory */
aoqi@0 1683 final List<Symbol> bridges;
aoqi@0 1684
aoqi@0 1685 TranslationContext(T tree) {
aoqi@0 1686 this.tree = tree;
aoqi@0 1687 this.owner = owner();
aoqi@0 1688 this.depth = frameStack.size() - 1;
aoqi@0 1689 this.prev = context();
aoqi@0 1690 ClassSymbol csym =
aoqi@0 1691 types.makeFunctionalInterfaceClass(attrEnv, names.empty, tree.targets, ABSTRACT | INTERFACE);
aoqi@0 1692 this.bridges = types.functionalInterfaceBridges(csym);
aoqi@0 1693 }
aoqi@0 1694
aoqi@0 1695 /** does this functional expression need to be created using alternate metafactory? */
aoqi@0 1696 boolean needsAltMetafactory() {
aoqi@0 1697 return tree.targets.length() > 1 ||
aoqi@0 1698 isSerializable() ||
aoqi@0 1699 bridges.length() > 1;
aoqi@0 1700 }
aoqi@0 1701
aoqi@0 1702 /** does this functional expression require serialization support? */
aoqi@0 1703 boolean isSerializable() {
aoqi@0 1704 if (forceSerializable) {
aoqi@0 1705 return true;
aoqi@0 1706 }
aoqi@0 1707 for (Type target : tree.targets) {
aoqi@0 1708 if (types.asSuper(target, syms.serializableType.tsym) != null) {
aoqi@0 1709 return true;
aoqi@0 1710 }
aoqi@0 1711 }
aoqi@0 1712 return false;
aoqi@0 1713 }
aoqi@0 1714
aoqi@0 1715 /**
aoqi@0 1716 * @return Name of the enclosing method to be folded into synthetic
aoqi@0 1717 * method name
aoqi@0 1718 */
aoqi@0 1719 String enclosingMethodName() {
aoqi@0 1720 return syntheticMethodNameComponent(owner.name);
aoqi@0 1721 }
aoqi@0 1722
aoqi@0 1723 /**
aoqi@0 1724 * @return Method name in a form that can be folded into a
aoqi@0 1725 * component of a synthetic method name
aoqi@0 1726 */
aoqi@0 1727 String syntheticMethodNameComponent(Name name) {
aoqi@0 1728 if (name == null) {
aoqi@0 1729 return "null";
aoqi@0 1730 }
aoqi@0 1731 String methodName = name.toString();
aoqi@0 1732 if (methodName.equals("<clinit>")) {
aoqi@0 1733 methodName = "static";
aoqi@0 1734 } else if (methodName.equals("<init>")) {
aoqi@0 1735 methodName = "new";
aoqi@0 1736 }
aoqi@0 1737 return methodName;
aoqi@0 1738 }
aoqi@0 1739 }
aoqi@0 1740
aoqi@0 1741 /**
aoqi@0 1742 * This class retains all the useful information about a lambda expression;
aoqi@0 1743 * the contents of this class are filled by the LambdaAnalyzer visitor,
aoqi@0 1744 * and the used by the main translation routines in order to adjust references
aoqi@0 1745 * to captured locals/members, etc.
aoqi@0 1746 */
aoqi@0 1747 private class LambdaTranslationContext extends TranslationContext<JCLambda> {
aoqi@0 1748
aoqi@0 1749 /** variable in the enclosing context to which this lambda is assigned */
aoqi@0 1750 final Symbol self;
aoqi@0 1751
aoqi@0 1752 /** variable in the enclosing context to which this lambda is assigned */
aoqi@0 1753 final Symbol assignedTo;
aoqi@0 1754
aoqi@0 1755 Map<LambdaSymbolKind, Map<Symbol, Symbol>> translatedSymbols;
aoqi@0 1756
aoqi@0 1757 /** the synthetic symbol for the method hoisting the translated lambda */
jlahoda@2733 1758 MethodSymbol translatedSym;
aoqi@0 1759
aoqi@0 1760 List<JCVariableDecl> syntheticParams;
aoqi@0 1761
aoqi@0 1762 /**
aoqi@0 1763 * to prevent recursion, track local classes processed
aoqi@0 1764 */
aoqi@0 1765 final Set<Symbol> freeVarProcessedLocalClasses;
aoqi@0 1766
rfield@2607 1767 /**
rfield@2607 1768 * For method references converted to lambdas. The method
rfield@2607 1769 * reference receiver expression. Must be treated like a captured
rfield@2607 1770 * variable.
rfield@2607 1771 */
rfield@2607 1772 JCExpression methodReferenceReceiver;
rfield@2607 1773
aoqi@0 1774 LambdaTranslationContext(JCLambda tree) {
aoqi@0 1775 super(tree);
aoqi@0 1776 Frame frame = frameStack.head;
aoqi@0 1777 switch (frame.tree.getTag()) {
aoqi@0 1778 case VARDEF:
aoqi@0 1779 assignedTo = self = ((JCVariableDecl) frame.tree).sym;
aoqi@0 1780 break;
aoqi@0 1781 case ASSIGN:
aoqi@0 1782 self = null;
aoqi@0 1783 assignedTo = TreeInfo.symbol(((JCAssign) frame.tree).getVariable());
aoqi@0 1784 break;
aoqi@0 1785 default:
aoqi@0 1786 assignedTo = self = null;
aoqi@0 1787 break;
aoqi@0 1788 }
aoqi@0 1789
aoqi@0 1790 // This symbol will be filled-in in complete
aoqi@0 1791 this.translatedSym = makePrivateSyntheticMethod(0, null, null, owner.enclClass());
aoqi@0 1792
aoqi@0 1793 translatedSymbols = new EnumMap<>(LambdaSymbolKind.class);
aoqi@0 1794
aoqi@0 1795 translatedSymbols.put(PARAM, new LinkedHashMap<Symbol, Symbol>());
aoqi@0 1796 translatedSymbols.put(LOCAL_VAR, new LinkedHashMap<Symbol, Symbol>());
aoqi@0 1797 translatedSymbols.put(CAPTURED_VAR, new LinkedHashMap<Symbol, Symbol>());
aoqi@0 1798 translatedSymbols.put(CAPTURED_THIS, new LinkedHashMap<Symbol, Symbol>());
aoqi@0 1799 translatedSymbols.put(TYPE_VAR, new LinkedHashMap<Symbol, Symbol>());
aoqi@0 1800
aoqi@0 1801 freeVarProcessedLocalClasses = new HashSet<>();
aoqi@0 1802 }
aoqi@0 1803
aoqi@0 1804 /**
aoqi@0 1805 * For a serializable lambda, generate a disambiguating string
aoqi@0 1806 * which maximizes stability across deserialization.
aoqi@0 1807 *
aoqi@0 1808 * @return String to differentiate synthetic lambda method names
aoqi@0 1809 */
aoqi@0 1810 private String serializedLambdaDisambiguation() {
aoqi@0 1811 StringBuilder buf = new StringBuilder();
aoqi@0 1812 // Append the enclosing method signature to differentiate
aoqi@0 1813 // overloaded enclosing methods. For lambdas enclosed in
aoqi@0 1814 // lambdas, the generated lambda method will not have type yet,
aoqi@0 1815 // but the enclosing method's name will have been generated
aoqi@0 1816 // with this same method, so it will be unique and never be
aoqi@0 1817 // overloaded.
aoqi@0 1818 Assert.check(
aoqi@0 1819 owner.type != null ||
aoqi@0 1820 directlyEnclosingLambda() != null);
aoqi@0 1821 if (owner.type != null) {
aoqi@0 1822 buf.append(typeSig(owner.type));
aoqi@0 1823 buf.append(":");
aoqi@0 1824 }
aoqi@0 1825
aoqi@0 1826 // Add target type info
aoqi@0 1827 buf.append(types.findDescriptorSymbol(tree.type.tsym).owner.flatName());
aoqi@0 1828 buf.append(" ");
aoqi@0 1829
aoqi@0 1830 // Add variable assigned to
aoqi@0 1831 if (assignedTo != null) {
aoqi@0 1832 buf.append(assignedTo.flatName());
aoqi@0 1833 buf.append("=");
aoqi@0 1834 }
aoqi@0 1835 //add captured locals info: type, name, order
aoqi@0 1836 for (Symbol fv : getSymbolMap(CAPTURED_VAR).keySet()) {
aoqi@0 1837 if (fv != self) {
aoqi@0 1838 buf.append(typeSig(fv.type));
aoqi@0 1839 buf.append(" ");
aoqi@0 1840 buf.append(fv.flatName());
aoqi@0 1841 buf.append(",");
aoqi@0 1842 }
aoqi@0 1843 }
aoqi@0 1844
aoqi@0 1845 return buf.toString();
aoqi@0 1846 }
aoqi@0 1847
aoqi@0 1848 /**
aoqi@0 1849 * For a non-serializable lambda, generate a simple method.
aoqi@0 1850 *
aoqi@0 1851 * @return Name to use for the synthetic lambda method name
aoqi@0 1852 */
aoqi@0 1853 private Name lambdaName() {
aoqi@0 1854 return names.lambda.append(names.fromString(enclosingMethodName() + "$" + lambdaCount++));
aoqi@0 1855 }
aoqi@0 1856
aoqi@0 1857 /**
aoqi@0 1858 * For a serializable lambda, generate a method name which maximizes
aoqi@0 1859 * name stability across deserialization.
aoqi@0 1860 *
aoqi@0 1861 * @return Name to use for the synthetic lambda method name
aoqi@0 1862 */
aoqi@0 1863 private Name serializedLambdaName() {
aoqi@0 1864 StringBuilder buf = new StringBuilder();
aoqi@0 1865 buf.append(names.lambda);
aoqi@0 1866 // Append the name of the method enclosing the lambda.
aoqi@0 1867 buf.append(enclosingMethodName());
aoqi@0 1868 buf.append('$');
aoqi@0 1869 // Append a hash of the disambiguating string : enclosing method
aoqi@0 1870 // signature, etc.
aoqi@0 1871 String disam = serializedLambdaDisambiguation();
aoqi@0 1872 buf.append(Integer.toHexString(disam.hashCode()));
aoqi@0 1873 buf.append('$');
aoqi@0 1874 // The above appended name components may not be unique, append
aoqi@0 1875 // a count based on the above name components.
aoqi@0 1876 buf.append(syntheticMethodNameCounts.getIndex(buf));
aoqi@0 1877 String result = buf.toString();
aoqi@0 1878 //System.err.printf("serializedLambdaName: %s -- %s\n", result, disam);
aoqi@0 1879 return names.fromString(result);
aoqi@0 1880 }
aoqi@0 1881
aoqi@0 1882 /**
aoqi@0 1883 * Translate a symbol of a given kind into something suitable for the
aoqi@0 1884 * synthetic lambda body
aoqi@0 1885 */
jlahoda@2734 1886 Symbol translate(final Symbol sym, LambdaSymbolKind skind) {
aoqi@0 1887 Symbol ret;
aoqi@0 1888 switch (skind) {
aoqi@0 1889 case CAPTURED_THIS:
aoqi@0 1890 ret = sym; // self represented
aoqi@0 1891 break;
aoqi@0 1892 case TYPE_VAR:
aoqi@0 1893 // Just erase the type var
jlahoda@2734 1894 ret = new VarSymbol(sym.flags(), sym.name,
aoqi@0 1895 types.erasure(sym.type), sym.owner);
aoqi@0 1896
aoqi@0 1897 /* this information should also be kept for LVT generation at Gen
aoqi@0 1898 * a Symbol with pos < startPos won't be tracked.
aoqi@0 1899 */
aoqi@0 1900 ((VarSymbol)ret).pos = ((VarSymbol)sym).pos;
aoqi@0 1901 break;
aoqi@0 1902 case CAPTURED_VAR:
jlahoda@2734 1903 ret = new VarSymbol(SYNTHETIC | FINAL | PARAMETER, sym.name, types.erasure(sym.type), translatedSym) {
aoqi@0 1904 @Override
aoqi@0 1905 public Symbol baseSymbol() {
aoqi@0 1906 //keep mapping with original captured symbol
aoqi@0 1907 return sym;
aoqi@0 1908 }
aoqi@0 1909 };
aoqi@0 1910 break;
aoqi@0 1911 case LOCAL_VAR:
jlahoda@2734 1912 ret = new VarSymbol(sym.flags() & FINAL, sym.name, sym.type, translatedSym);
aoqi@0 1913 ((VarSymbol) ret).pos = ((VarSymbol) sym).pos;
aoqi@0 1914 break;
aoqi@0 1915 case PARAM:
jlahoda@2734 1916 ret = new VarSymbol((sym.flags() & FINAL) | PARAMETER, sym.name, types.erasure(sym.type), translatedSym);
aoqi@0 1917 ((VarSymbol) ret).pos = ((VarSymbol) sym).pos;
aoqi@0 1918 break;
aoqi@0 1919 default:
jlahoda@2734 1920 Assert.error(skind.name());
jlahoda@2734 1921 throw new AssertionError();
aoqi@0 1922 }
aoqi@0 1923 if (ret != sym) {
aoqi@0 1924 ret.setDeclarationAttributes(sym.getRawAttributes());
aoqi@0 1925 ret.setTypeAttributes(sym.getRawTypeAttributes());
aoqi@0 1926 }
aoqi@0 1927 return ret;
aoqi@0 1928 }
aoqi@0 1929
aoqi@0 1930 void addSymbol(Symbol sym, LambdaSymbolKind skind) {
aoqi@0 1931 Map<Symbol, Symbol> transMap = getSymbolMap(skind);
aoqi@0 1932 if (!transMap.containsKey(sym)) {
jlahoda@2734 1933 transMap.put(sym, translate(sym, skind));
aoqi@0 1934 }
aoqi@0 1935 }
aoqi@0 1936
aoqi@0 1937 Map<Symbol, Symbol> getSymbolMap(LambdaSymbolKind skind) {
aoqi@0 1938 Map<Symbol, Symbol> m = translatedSymbols.get(skind);
aoqi@0 1939 Assert.checkNonNull(m);
aoqi@0 1940 return m;
aoqi@0 1941 }
aoqi@0 1942
aoqi@0 1943 JCTree translate(JCIdent lambdaIdent) {
aoqi@0 1944 for (Map<Symbol, Symbol> m : translatedSymbols.values()) {
aoqi@0 1945 if (m.containsKey(lambdaIdent.sym)) {
aoqi@0 1946 Symbol tSym = m.get(lambdaIdent.sym);
aoqi@0 1947 JCTree t = make.Ident(tSym).setType(lambdaIdent.type);
aoqi@0 1948 tSym.setTypeAttributes(lambdaIdent.sym.getRawTypeAttributes());
aoqi@0 1949 return t;
aoqi@0 1950 }
aoqi@0 1951 }
aoqi@0 1952 return null;
aoqi@0 1953 }
aoqi@0 1954
aoqi@0 1955 /**
aoqi@0 1956 * The translatedSym is not complete/accurate until the analysis is
aoqi@0 1957 * finished. Once the analysis is finished, the translatedSym is
aoqi@0 1958 * "completed" -- updated with type information, access modifiers,
aoqi@0 1959 * and full parameter list.
aoqi@0 1960 */
aoqi@0 1961 void complete() {
aoqi@0 1962 if (syntheticParams != null) {
aoqi@0 1963 return;
aoqi@0 1964 }
aoqi@0 1965 boolean inInterface = translatedSym.owner.isInterface();
aoqi@0 1966 boolean thisReferenced = !getSymbolMap(CAPTURED_THIS).isEmpty();
aoqi@0 1967
aoqi@0 1968 // If instance access isn't needed, make it static.
aoqi@0 1969 // Interface instance methods must be default methods.
aoqi@0 1970 // Lambda methods are private synthetic.
rfield@2528 1971 // Inherit ACC_STRICT from the enclosing method, or, for clinit,
rfield@2528 1972 // from the class.
aoqi@0 1973 translatedSym.flags_field = SYNTHETIC | LAMBDA_METHOD |
rfield@2528 1974 owner.flags_field & STRICTFP |
rfield@2528 1975 owner.owner.flags_field & STRICTFP |
aoqi@0 1976 PRIVATE |
aoqi@0 1977 (thisReferenced? (inInterface? DEFAULT : 0) : STATIC);
aoqi@0 1978
aoqi@0 1979 //compute synthetic params
aoqi@0 1980 ListBuffer<JCVariableDecl> params = new ListBuffer<>();
jlahoda@2733 1981 ListBuffer<VarSymbol> parameterSymbols = new ListBuffer<>();
aoqi@0 1982
aoqi@0 1983 // The signature of the method is augmented with the following
aoqi@0 1984 // synthetic parameters:
aoqi@0 1985 //
aoqi@0 1986 // 1) reference to enclosing contexts captured by the lambda expression
aoqi@0 1987 // 2) enclosing locals captured by the lambda expression
aoqi@0 1988 for (Symbol thisSym : getSymbolMap(CAPTURED_VAR).values()) {
aoqi@0 1989 params.append(make.VarDef((VarSymbol) thisSym, null));
jlahoda@2733 1990 parameterSymbols.append((VarSymbol) thisSym);
rfield@2607 1991 }
aoqi@0 1992 for (Symbol thisSym : getSymbolMap(PARAM).values()) {
aoqi@0 1993 params.append(make.VarDef((VarSymbol) thisSym, null));
jlahoda@2733 1994 parameterSymbols.append((VarSymbol) thisSym);
aoqi@0 1995 }
aoqi@0 1996 syntheticParams = params.toList();
aoqi@0 1997
jlahoda@2733 1998 translatedSym.params = parameterSymbols.toList();
jlahoda@2733 1999
aoqi@0 2000 // Compute and set the lambda name
aoqi@0 2001 translatedSym.name = isSerializable()
aoqi@0 2002 ? serializedLambdaName()
aoqi@0 2003 : lambdaName();
aoqi@0 2004
aoqi@0 2005 //prepend synthetic args to translated lambda method signature
aoqi@0 2006 translatedSym.type = types.createMethodTypeWithParameters(
aoqi@0 2007 generatedLambdaSig(),
aoqi@0 2008 TreeInfo.types(syntheticParams));
aoqi@0 2009 }
aoqi@0 2010
aoqi@0 2011 Type generatedLambdaSig() {
aoqi@0 2012 return types.erasure(tree.getDescriptorType(types));
aoqi@0 2013 }
aoqi@0 2014 }
aoqi@0 2015
aoqi@0 2016 /**
aoqi@0 2017 * This class retains all the useful information about a method reference;
aoqi@0 2018 * the contents of this class are filled by the LambdaAnalyzer visitor,
aoqi@0 2019 * and the used by the main translation routines in order to adjust method
aoqi@0 2020 * references (i.e. in case a bridge is needed)
aoqi@0 2021 */
rfield@2607 2022 private final class ReferenceTranslationContext extends TranslationContext<JCMemberReference> {
aoqi@0 2023
aoqi@0 2024 final boolean isSuper;
aoqi@0 2025 final Symbol sigPolySym;
aoqi@0 2026
aoqi@0 2027 ReferenceTranslationContext(JCMemberReference tree) {
aoqi@0 2028 super(tree);
aoqi@0 2029 this.isSuper = tree.hasKind(ReferenceKind.SUPER);
aoqi@0 2030 this.sigPolySym = isSignaturePolymorphic()
aoqi@0 2031 ? makePrivateSyntheticMethod(tree.sym.flags(),
aoqi@0 2032 tree.sym.name,
aoqi@0 2033 bridgedRefSig(),
aoqi@0 2034 tree.sym.enclClass())
aoqi@0 2035 : null;
aoqi@0 2036 }
aoqi@0 2037
aoqi@0 2038 /**
aoqi@0 2039 * Get the opcode associated with this method reference
aoqi@0 2040 */
aoqi@0 2041 int referenceKind() {
rfield@2607 2042 return LambdaToMethod.this.referenceKind(tree.sym);
aoqi@0 2043 }
aoqi@0 2044
aoqi@0 2045 boolean needsVarArgsConversion() {
aoqi@0 2046 return tree.varargsElement != null;
aoqi@0 2047 }
aoqi@0 2048
aoqi@0 2049 /**
aoqi@0 2050 * @return Is this an array operation like clone()
aoqi@0 2051 */
aoqi@0 2052 boolean isArrayOp() {
aoqi@0 2053 return tree.sym.owner == syms.arrayClass;
aoqi@0 2054 }
aoqi@0 2055
aoqi@0 2056 boolean receiverAccessible() {
aoqi@0 2057 //hack needed to workaround 292 bug (7087658)
aoqi@0 2058 //when 292 issue is fixed we should remove this and change the backend
aoqi@0 2059 //code to always generate a method handle to an accessible method
aoqi@0 2060 return tree.ownerAccessible;
aoqi@0 2061 }
aoqi@0 2062
aoqi@0 2063 /**
aoqi@0 2064 * The VM does not support access across nested classes (8010319).
aoqi@0 2065 * Were that ever to change, this should be removed.
aoqi@0 2066 */
aoqi@0 2067 boolean isPrivateInOtherClass() {
aoqi@0 2068 return (tree.sym.flags() & PRIVATE) != 0 &&
aoqi@0 2069 !types.isSameType(
aoqi@0 2070 types.erasure(tree.sym.enclClass().asType()),
aoqi@0 2071 types.erasure(owner.enclClass().asType()));
aoqi@0 2072 }
aoqi@0 2073
aoqi@0 2074 /**
aoqi@0 2075 * Signature polymorphic methods need special handling.
aoqi@0 2076 * e.g. MethodHandle.invoke() MethodHandle.invokeExact()
aoqi@0 2077 */
aoqi@0 2078 final boolean isSignaturePolymorphic() {
aoqi@0 2079 return tree.sym.kind == MTH &&
aoqi@0 2080 types.isSignaturePolymorphic((MethodSymbol)tree.sym);
aoqi@0 2081 }
aoqi@0 2082
aoqi@0 2083 /**
rfield@2614 2084 * Erasure destroys the implementation parameter subtype
rfield@2614 2085 * relationship for intersection types
aoqi@0 2086 */
rfield@2614 2087 boolean interfaceParameterIsIntersectionType() {
rfield@2614 2088 List<Type> tl = tree.getDescriptorType(types).getParameterTypes();
rfield@2614 2089 if (tree.kind == ReferenceKind.UNBOUND) {
rfield@2614 2090 tl = tl.tail;
rfield@2614 2091 }
rfield@2614 2092 for (; tl.nonEmpty(); tl = tl.tail) {
rfield@2614 2093 Type pt = tl.head;
rfield@2614 2094 if (pt.getKind() == TypeKind.TYPEVAR) {
rfield@2614 2095 TypeVar tv = (TypeVar) pt;
rfield@2614 2096 if (tv.bound.getKind() == TypeKind.INTERSECTION) {
rfield@2614 2097 return true;
rfield@2614 2098 }
rfield@2614 2099 }
rfield@2614 2100 }
rfield@2614 2101 return false;
rfield@2614 2102 }
rfield@2614 2103
rfield@2614 2104 /**
rfield@2607 2105 * Does this reference need to be converted to a lambda
rfield@2607 2106 * (i.e. var args need to be expanded or "super" is used)
rfield@2381 2107 */
rfield@2607 2108 final boolean needsConversionToLambda() {
rfield@2614 2109 return interfaceParameterIsIntersectionType() ||
rfield@2614 2110 isSuper ||
rfield@2614 2111 needsVarArgsConversion() ||
rfield@2614 2112 isArrayOp() ||
aoqi@0 2113 isPrivateInOtherClass() ||
rfield@2607 2114 !receiverAccessible() ||
rfield@2607 2115 (tree.getMode() == ReferenceMode.NEW &&
rfield@2607 2116 tree.kind != ReferenceKind.ARRAY_CTOR &&
rfield@2607 2117 (tree.sym.owner.isLocal() || tree.sym.owner.isInner()));
aoqi@0 2118 }
aoqi@0 2119
aoqi@0 2120 Type generatedRefSig() {
aoqi@0 2121 return types.erasure(tree.sym.type);
aoqi@0 2122 }
aoqi@0 2123
aoqi@0 2124 Type bridgedRefSig() {
aoqi@0 2125 return types.erasure(types.findDescriptorSymbol(tree.targets.head.tsym).type);
aoqi@0 2126 }
aoqi@0 2127 }
aoqi@0 2128 }
aoqi@0 2129 // </editor-fold>
aoqi@0 2130
aoqi@0 2131 /*
aoqi@0 2132 * These keys provide mappings for various translated lambda symbols
aoqi@0 2133 * and the prevailing order must be maintained.
aoqi@0 2134 */
aoqi@0 2135 enum LambdaSymbolKind {
aoqi@0 2136 PARAM, // original to translated lambda parameters
aoqi@0 2137 LOCAL_VAR, // original to translated lambda locals
aoqi@0 2138 CAPTURED_VAR, // variables in enclosing scope to translated synthetic parameters
aoqi@0 2139 CAPTURED_THIS, // class symbols to translated synthetic parameters (for captured member access)
aoqi@0 2140 TYPE_VAR; // original to translated lambda type variables
aoqi@0 2141 }
aoqi@0 2142
aoqi@0 2143 /**
aoqi@0 2144 * ****************************************************************
aoqi@0 2145 * Signature Generation
aoqi@0 2146 * ****************************************************************
aoqi@0 2147 */
aoqi@0 2148
aoqi@0 2149 private String typeSig(Type type) {
aoqi@0 2150 L2MSignatureGenerator sg = new L2MSignatureGenerator();
aoqi@0 2151 sg.assembleSig(type);
aoqi@0 2152 return sg.toString();
aoqi@0 2153 }
aoqi@0 2154
aoqi@0 2155 private String classSig(Type type) {
aoqi@0 2156 L2MSignatureGenerator sg = new L2MSignatureGenerator();
aoqi@0 2157 sg.assembleClassSig(type);
aoqi@0 2158 return sg.toString();
aoqi@0 2159 }
aoqi@0 2160
aoqi@0 2161 /**
aoqi@0 2162 * Signature Generation
aoqi@0 2163 */
aoqi@0 2164 private class L2MSignatureGenerator extends Types.SignatureGenerator {
aoqi@0 2165
aoqi@0 2166 /**
aoqi@0 2167 * An output buffer for type signatures.
aoqi@0 2168 */
aoqi@0 2169 StringBuilder sb = new StringBuilder();
aoqi@0 2170
aoqi@0 2171 L2MSignatureGenerator() {
aoqi@0 2172 super(types);
aoqi@0 2173 }
aoqi@0 2174
aoqi@0 2175 @Override
aoqi@0 2176 protected void append(char ch) {
aoqi@0 2177 sb.append(ch);
aoqi@0 2178 }
aoqi@0 2179
aoqi@0 2180 @Override
aoqi@0 2181 protected void append(byte[] ba) {
aoqi@0 2182 sb.append(new String(ba));
aoqi@0 2183 }
aoqi@0 2184
aoqi@0 2185 @Override
aoqi@0 2186 protected void append(Name name) {
aoqi@0 2187 sb.append(name.toString());
aoqi@0 2188 }
aoqi@0 2189
aoqi@0 2190 @Override
aoqi@0 2191 public String toString() {
aoqi@0 2192 return sb.toString();
aoqi@0 2193 }
aoqi@0 2194 }
aoqi@0 2195 }

mercurial