Java example source code file (LambdaToMethod.java)
This example Java source code file (LambdaToMethod.java) is included in the alvinalexander.com
"Java Source Code
Warehouse" project. The intent of this project is to help you "Learn
Java by Example" TM.
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.javac.comp;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.tree.JCTree.JCMemberReference.ReferenceKind;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.tree.TreeTranslator;
import com.sun.tools.javac.code.Attribute;
import com.sun.tools.javac.code.Kinds;
import com.sun.tools.javac.code.Scope;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.DynamicMethodSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.MethodType;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.comp.LambdaToMethod.LambdaAnalyzerPreprocessor.*;
import com.sun.tools.javac.comp.Lower.BasicFreeVarCollector;
import com.sun.tools.javac.jvm.*;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.source.tree.MemberReferenceTree.ReferenceMode;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import static com.sun.tools.javac.comp.LambdaToMethod.LambdaSymbolKind.*;
import static com.sun.tools.javac.code.Flags.*;
import static com.sun.tools.javac.code.Kinds.*;
import static com.sun.tools.javac.code.TypeTag.*;
import static com.sun.tools.javac.tree.JCTree.Tag.*;
/**
* This pass desugars lambda expressions into static methods
*
* <p>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class LambdaToMethod extends TreeTranslator {
private Attr attr;
private JCDiagnostic.Factory diags;
private Log log;
private Lower lower;
private Names names;
private Symtab syms;
private Resolve rs;
private TreeMaker make;
private Types types;
private TransTypes transTypes;
private Env<AttrContext> attrEnv;
/** the analyzer scanner */
private LambdaAnalyzerPreprocessor analyzer;
/** map from lambda trees to translation contexts */
private Map<JCTree, TranslationContext>> contextMap;
/** current translation context (visitor argument) */
private TranslationContext<?> context;
/** info about the current class being processed */
private KlassInfo kInfo;
/** dump statistics about lambda code generation */
private boolean dumpLambdaToMethodStats;
/** Flag for alternate metafactories indicating the lambda object is intended to be serializable */
public static final int FLAG_SERIALIZABLE = 1 << 0;
/** Flag for alternate metafactories indicating the lambda object has multiple targets */
public static final int FLAG_MARKERS = 1 << 1;
/** Flag for alternate metafactories indicating the lambda object requires multiple bridges */
public static final int FLAG_BRIDGES = 1 << 2;
// <editor-fold defaultstate="collapsed" desc="Instantiating">
protected static final Context.Key<LambdaToMethod> unlambdaKey =
new Context.Key<LambdaToMethod>();
public static LambdaToMethod instance(Context context) {
LambdaToMethod instance = context.get(unlambdaKey);
if (instance == null) {
instance = new LambdaToMethod(context);
}
return instance;
}
private LambdaToMethod(Context context) {
context.put(unlambdaKey, this);
diags = JCDiagnostic.Factory.instance(context);
log = Log.instance(context);
lower = Lower.instance(context);
names = Names.instance(context);
syms = Symtab.instance(context);
rs = Resolve.instance(context);
make = TreeMaker.instance(context);
types = Types.instance(context);
transTypes = TransTypes.instance(context);
analyzer = new LambdaAnalyzerPreprocessor();
Options options = Options.instance(context);
dumpLambdaToMethodStats = options.isSet("dumpLambdaToMethodStats");
attr = Attr.instance(context);
}
// </editor-fold>
private class KlassInfo {
/**
* list of methods to append
*/
private ListBuffer<JCTree> appendedMethodList;
/**
* list of deserialization cases
*/
private final Map<String, ListBuffer deserializeCases;
/**
* deserialize method symbol
*/
private final MethodSymbol deserMethodSym;
/**
* deserialize method parameter symbol
*/
private final VarSymbol deserParamSym;
private final JCClassDecl clazz;
private KlassInfo(JCClassDecl clazz) {
this.clazz = clazz;
appendedMethodList = new ListBuffer<>();
deserializeCases = new HashMap<String, ListBuffer();
MethodType type = new MethodType(List.of(syms.serializedLambdaType), syms.objectType,
List.<Type>nil(), syms.methodClass);
deserMethodSym = makePrivateSyntheticMethod(STATIC, names.deserializeLambda, type, clazz.sym);
deserParamSym = new VarSymbol(FINAL, names.fromString("lambda"),
syms.serializedLambdaType, deserMethodSym);
}
private void addMethod(JCTree decl) {
appendedMethodList = appendedMethodList.prepend(decl);
}
}
// <editor-fold defaultstate="collapsed" desc="translate methods">
@Override
public <T extends JCTree> T translate(T tree) {
TranslationContext<?> newContext = contextMap.get(tree);
return translate(tree, newContext != null ? newContext : context);
}
<T extends JCTree> T translate(T tree, TranslationContext> newContext) {
TranslationContext<?> prevContext = context;
try {
context = newContext;
return super.translate(tree);
}
finally {
context = prevContext;
}
}
<T extends JCTree> List translate(List trees, TranslationContext> newContext) {
ListBuffer<T> buf = new ListBuffer<>();
for (T tree : trees) {
buf.append(translate(tree, newContext));
}
return buf.toList();
}
public JCTree translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) {
this.make = make;
this.attrEnv = env;
this.context = null;
this.contextMap = new HashMap<JCTree, TranslationContext>>();
return translate(cdef);
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="visitor methods">
/**
* Visit a class.
* Maintain the translatedMethodList across nested classes.
* Append the translatedMethodList to the class after it is translated.
* @param tree
*/
@Override
public void visitClassDef(JCClassDecl tree) {
if (tree.sym.owner.kind == PCK) {
//analyze class
tree = analyzer.analyzeAndPreprocessClass(tree);
}
KlassInfo prevKlassInfo = kInfo;
try {
kInfo = new KlassInfo(tree);
super.visitClassDef(tree);
if (!kInfo.deserializeCases.isEmpty()) {
int prevPos = make.pos;
try {
make.at(tree);
kInfo.addMethod(makeDeserializeMethod(tree.sym));
} finally {
make.at(prevPos);
}
}
//add all translated instance methods here
List<JCTree> newMethods = kInfo.appendedMethodList.toList();
tree.defs = tree.defs.appendList(newMethods);
for (JCTree lambda : newMethods) {
tree.sym.members().enter(((JCMethodDecl)lambda).sym);
}
result = tree;
} finally {
kInfo = prevKlassInfo;
}
}
/**
* Translate a lambda into a method to be inserted into the class.
* Then replace the lambda site with an invokedynamic call of to lambda
* meta-factory, which will use the lambda method.
* @param tree
*/
@Override
public void visitLambda(JCLambda tree) {
LambdaTranslationContext localContext = (LambdaTranslationContext)context;
MethodSymbol sym = (MethodSymbol)localContext.translatedSym;
MethodType lambdaType = (MethodType) sym.type;
{
Symbol owner = localContext.owner;
ListBuffer<Attribute.TypeCompound> ownerTypeAnnos = new ListBuffer();
ListBuffer<Attribute.TypeCompound> lambdaTypeAnnos = new ListBuffer();
for (Attribute.TypeCompound tc : owner.getRawTypeAttributes()) {
if (tc.position.onLambda == tree) {
lambdaTypeAnnos.append(tc);
} else {
ownerTypeAnnos.append(tc);
}
}
if (lambdaTypeAnnos.nonEmpty()) {
owner.setTypeAttributes(ownerTypeAnnos.toList());
sym.setTypeAttributes(lambdaTypeAnnos.toList());
}
}
//create the method declaration hoisting the lambda body
JCMethodDecl lambdaDecl = make.MethodDef(make.Modifiers(sym.flags_field),
sym.name,
make.QualIdent(lambdaType.getReturnType().tsym),
List.<JCTypeParameter>nil(),
localContext.syntheticParams,
lambdaType.getThrownTypes() == null ?
List.<JCExpression>nil() :
make.Types(lambdaType.getThrownTypes()),
null,
null);
lambdaDecl.sym = sym;
lambdaDecl.type = lambdaType;
//translate lambda body
//As the lambda body is translated, all references to lambda locals,
//captured variables, enclosing members are adjusted accordingly
//to refer to the static method parameters (rather than i.e. acessing to
//captured members directly).
lambdaDecl.body = translate(makeLambdaBody(tree, lambdaDecl));
//Add the method to the list of methods to be added to this class.
kInfo.addMethod(lambdaDecl);
//now that we have generated a method for the lambda expression,
//we can translate the lambda into a method reference pointing to the newly
//created method.
//
//Note that we need to adjust the method handle so that it will match the
//signature of the SAM descriptor - this means that the method reference
//should be added the following synthetic arguments:
//
// * the "this" argument if it is an instance method
// * enclosing locals captured by the lambda expression
ListBuffer<JCExpression> syntheticInits = new ListBuffer<>();
if (!sym.isStatic()) {
syntheticInits.append(makeThis(
sym.owner.enclClass().asType(),
localContext.owner.enclClass()));
}
//add captured locals
for (Symbol fv : localContext.getSymbolMap(CAPTURED_VAR).keySet()) {
if (fv != localContext.self) {
JCTree captured_local = make.Ident(fv).setType(fv.type);
syntheticInits.append((JCExpression) captured_local);
}
}
//then, determine the arguments to the indy call
List<JCExpression> indy_args = translate(syntheticInits.toList(), localContext.prev);
//build a sam instance using an indy call to the meta-factory
int refKind = referenceKind(sym);
//convert to an invokedynamic call
result = makeMetafactoryIndyCall(context, refKind, sym, indy_args);
}
private JCIdent makeThis(Type type, Symbol owner) {
VarSymbol _this = new VarSymbol(PARAMETER | FINAL | SYNTHETIC,
names._this,
type,
owner);
return make.Ident(_this);
}
/**
* Translate a method reference into an invokedynamic call to the
* meta-factory.
* @param tree
*/
@Override
public void visitReference(JCMemberReference tree) {
ReferenceTranslationContext localContext = (ReferenceTranslationContext)context;
//first determine the method symbol to be used to generate the sam instance
//this is either the method reference symbol, or the bridged reference symbol
Symbol refSym = localContext.needsBridge()
? localContext.bridgeSym
: localContext.isSignaturePolymorphic()
? localContext.sigPolySym
: tree.sym;
//build the bridge method, if needed
if (localContext.needsBridge()) {
bridgeMemberReference(tree, localContext);
}
//the qualifying expression is treated as a special captured arg
JCExpression init;
switch(tree.kind) {
case IMPLICIT_INNER: /** Inner :: new */
case SUPER: /** super :: instMethod */
init = makeThis(
localContext.owner.enclClass().asType(),
localContext.owner.enclClass());
break;
case BOUND: /** Expr :: instMethod */
init = tree.getQualifierExpression();
init = attr.makeNullCheck(init);
break;
case UNBOUND: /** Type :: instMethod */
case STATIC: /** Type :: staticMethod */
case TOPLEVEL: /** Top level :: new */
case ARRAY_CTOR: /** ArrayType :: new */
init = null;
break;
default:
throw new InternalError("Should not have an invalid kind");
}
List<JCExpression> indy_args = init==null? List.nil() : translate(List.of(init), localContext.prev);
//build a sam instance using an indy call to the meta-factory
result = makeMetafactoryIndyCall(localContext, localContext.referenceKind(), refSym, indy_args);
}
/**
* Translate identifiers within a lambda to the mapped identifier
* @param tree
*/
@Override
public void visitIdent(JCIdent tree) {
if (context == null || !analyzer.lambdaIdentSymbolFilter(tree.sym)) {
super.visitIdent(tree);
} else {
int prevPos = make.pos;
try {
make.at(tree);
LambdaTranslationContext lambdaContext = (LambdaTranslationContext) context;
JCTree ltree = lambdaContext.translate(tree);
if (ltree != null) {
result = ltree;
} else {
//access to untranslated symbols (i.e. compile-time constants,
//members defined inside the lambda body, etc.) )
super.visitIdent(tree);
}
} finally {
make.at(prevPos);
}
}
}
@Override
public void visitVarDef(JCVariableDecl tree) {
LambdaTranslationContext lambdaContext = (LambdaTranslationContext)context;
if (context != null && lambdaContext.getSymbolMap(LOCAL_VAR).containsKey(tree.sym)) {
JCExpression init = translate(tree.init);
int prevPos = make.pos;
try {
result = make.at(tree).VarDef((VarSymbol)lambdaContext.getSymbolMap(LOCAL_VAR).get(tree.sym), init);
} finally {
make.at(prevPos);
}
} else if (context != null && lambdaContext.getSymbolMap(TYPE_VAR).containsKey(tree.sym)) {
JCExpression init = translate(tree.init);
VarSymbol xsym = (VarSymbol)lambdaContext.getSymbolMap(TYPE_VAR).get(tree.sym);
int prevPos = make.pos;
try {
result = make.at(tree).VarDef(xsym, init);
} finally {
make.at(prevPos);
}
// Replace the entered symbol for this variable
Scope sc = tree.sym.owner.members();
if (sc != null) {
sc.remove(tree.sym);
sc.enter(xsym);
}
} else {
super.visitVarDef(tree);
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Translation helper methods">
private JCBlock makeLambdaBody(JCLambda tree, JCMethodDecl lambdaMethodDecl) {
return tree.getBodyKind() == JCLambda.BodyKind.EXPRESSION ?
makeLambdaExpressionBody((JCExpression)tree.body, lambdaMethodDecl) :
makeLambdaStatementBody((JCBlock)tree.body, lambdaMethodDecl, tree.canCompleteNormally);
}
private JCBlock makeLambdaExpressionBody(JCExpression expr, JCMethodDecl lambdaMethodDecl) {
Type restype = lambdaMethodDecl.type.getReturnType();
boolean isLambda_void = expr.type.hasTag(VOID);
boolean isTarget_void = restype.hasTag(VOID);
boolean isTarget_Void = types.isSameType(restype, types.boxedClass(syms.voidType).type);
int prevPos = make.pos;
try {
if (isTarget_void) {
//target is void:
// BODY;
JCStatement stat = make.at(expr).Exec(expr);
return make.Block(0, List.<JCStatement>of(stat));
} else if (isLambda_void && isTarget_Void) {
//void to Void conversion:
// BODY; return null;
ListBuffer<JCStatement> stats = new ListBuffer<>();
stats.append(make.at(expr).Exec(expr));
stats.append(make.Return(make.Literal(BOT, null).setType(syms.botType)));
return make.Block(0, stats.toList());
} else {
//non-void to non-void conversion:
// return (TYPE)BODY;
JCExpression retExpr = transTypes.coerce(attrEnv, expr, restype);
return make.at(retExpr).Block(0, List.<JCStatement>of(make.Return(retExpr)));
}
} finally {
make.at(prevPos);
}
}
private JCBlock makeLambdaStatementBody(JCBlock block, final JCMethodDecl lambdaMethodDecl, boolean completeNormally) {
final Type restype = lambdaMethodDecl.type.getReturnType();
final boolean isTarget_void = restype.hasTag(VOID);
boolean isTarget_Void = types.isSameType(restype, types.boxedClass(syms.voidType).type);
class LambdaBodyTranslator extends TreeTranslator {
@Override
public void visitClassDef(JCClassDecl tree) {
//do NOT recurse on any inner classes
result = tree;
}
@Override
public void visitLambda(JCLambda tree) {
//do NOT recurse on any nested lambdas
result = tree;
}
@Override
public void visitReturn(JCReturn tree) {
boolean isLambda_void = tree.expr == null;
if (isTarget_void && !isLambda_void) {
//Void to void conversion:
// { TYPE $loc = RET-EXPR; return; }
VarSymbol loc = makeSyntheticVar(0, names.fromString("$loc"), tree.expr.type, lambdaMethodDecl.sym);
JCVariableDecl varDef = make.VarDef(loc, tree.expr);
result = make.Block(0, List.<JCStatement>of(varDef, make.Return(null)));
} else if (!isTarget_void || !isLambda_void) {
//non-void to non-void conversion:
// return (TYPE)RET-EXPR;
tree.expr = transTypes.coerce(attrEnv, tree.expr, restype);
result = tree;
} else {
result = tree;
}
}
}
JCBlock trans_block = new LambdaBodyTranslator().translate(block);
if (completeNormally && isTarget_Void) {
//there's no return statement and the lambda (possibly inferred)
//return type is java.lang.Void; emit a synthetic return statement
trans_block.stats = trans_block.stats.append(make.Return(make.Literal(BOT, null).setType(syms.botType)));
}
return trans_block;
}
private JCMethodDecl makeDeserializeMethod(Symbol kSym) {
ListBuffer<JCCase> cases = new ListBuffer<>();
ListBuffer<JCBreak> breaks = new ListBuffer<>();
for (Map.Entry<String, ListBuffer entry : kInfo.deserializeCases.entrySet()) {
JCBreak br = make.Break(null);
breaks.add(br);
List<JCStatement> stmts = entry.getValue().append(br).toList();
cases.add(make.Case(make.Literal(entry.getKey()), stmts));
}
JCSwitch sw = make.Switch(deserGetter("getImplMethodName", syms.stringType), cases.toList());
for (JCBreak br : breaks) {
br.target = sw;
}
JCBlock body = make.Block(0L, List.<JCStatement>of(
sw,
make.Throw(makeNewClass(
syms.illegalArgumentExceptionType,
List.<JCExpression>of(make.Literal("Invalid lambda deserialization"))))));
JCMethodDecl deser = make.MethodDef(make.Modifiers(kInfo.deserMethodSym.flags()),
names.deserializeLambda,
make.QualIdent(kInfo.deserMethodSym.getReturnType().tsym),
List.<JCTypeParameter>nil(),
List.of(make.VarDef(kInfo.deserParamSym, null)),
List.<JCExpression>nil(),
body,
null);
deser.sym = kInfo.deserMethodSym;
deser.type = kInfo.deserMethodSym.type;
//System.err.printf("DESER: '%s'\n", deser);
return deser;
}
/** Make an attributed class instance creation expression.
* @param ctype The class type.
* @param args The constructor arguments.
* @param cons The constructor symbol
*/
JCNewClass makeNewClass(Type ctype, List<JCExpression> args, Symbol cons) {
JCNewClass tree = make.NewClass(null,
null, make.QualIdent(ctype.tsym), args, null);
tree.constructor = cons;
tree.type = ctype;
return tree;
}
/** Make an attributed class instance creation expression.
* @param ctype The class type.
* @param args The constructor arguments.
*/
JCNewClass makeNewClass(Type ctype, List<JCExpression> args) {
return makeNewClass(ctype, args,
rs.resolveConstructor(null, attrEnv, ctype, TreeInfo.types(args), List.<Type>nil()));
}
private void addDeserializationCase(int implMethodKind, Symbol refSym, Type targetType, MethodSymbol samSym,
DiagnosticPosition pos, List<Object> staticArgs, MethodType indyType) {
String functionalInterfaceClass = classSig(targetType);
String functionalInterfaceMethodName = samSym.getSimpleName().toString();
String functionalInterfaceMethodSignature = typeSig(types.erasure(samSym.type));
String implClass = classSig(types.erasure(refSym.owner.type));
String implMethodName = refSym.getQualifiedName().toString();
String implMethodSignature = typeSig(types.erasure(refSym.type));
JCExpression kindTest = eqTest(syms.intType, deserGetter("getImplMethodKind", syms.intType), make.Literal(implMethodKind));
ListBuffer<JCExpression> serArgs = new ListBuffer<>();
int i = 0;
for (Type t : indyType.getParameterTypes()) {
List<JCExpression> indexAsArg = new ListBuffer().append(make.Literal(i)).toList();
List<Type> argTypes = new ListBuffer().append(syms.intType).toList();
serArgs.add(make.TypeCast(types.erasure(t), deserGetter("getCapturedArg", syms.objectType, argTypes, indexAsArg)));
++i;
}
JCStatement stmt = make.If(
deserTest(deserTest(deserTest(deserTest(deserTest(
kindTest,
"getFunctionalInterfaceClass", functionalInterfaceClass),
"getFunctionalInterfaceMethodName", functionalInterfaceMethodName),
"getFunctionalInterfaceMethodSignature", functionalInterfaceMethodSignature),
"getImplClass", implClass),
"getImplMethodSignature", implMethodSignature),
make.Return(makeIndyCall(
pos,
syms.lambdaMetafactory,
names.altMetafactory,
staticArgs, indyType, serArgs.toList(), samSym.name)),
null);
ListBuffer<JCStatement> stmts = kInfo.deserializeCases.get(implMethodName);
if (stmts == null) {
stmts = new ListBuffer<>();
kInfo.deserializeCases.put(implMethodName, stmts);
}
/****
System.err.printf("+++++++++++++++++\n");
System.err.printf("*functionalInterfaceClass: '%s'\n", functionalInterfaceClass);
System.err.printf("*functionalInterfaceMethodName: '%s'\n", functionalInterfaceMethodName);
System.err.printf("*functionalInterfaceMethodSignature: '%s'\n", functionalInterfaceMethodSignature);
System.err.printf("*implMethodKind: %d\n", implMethodKind);
System.err.printf("*implClass: '%s'\n", implClass);
System.err.printf("*implMethodName: '%s'\n", implMethodName);
System.err.printf("*implMethodSignature: '%s'\n", implMethodSignature);
****/
stmts.append(stmt);
}
private JCExpression eqTest(Type argType, JCExpression arg1, JCExpression arg2) {
JCBinary testExpr = make.Binary(JCTree.Tag.EQ, arg1, arg2);
testExpr.operator = rs.resolveBinaryOperator(null, JCTree.Tag.EQ, attrEnv, argType, argType);
testExpr.setType(syms.booleanType);
return testExpr;
}
private JCExpression deserTest(JCExpression prev, String func, String lit) {
MethodType eqmt = new MethodType(List.of(syms.objectType), syms.booleanType, List.<Type>nil(), syms.methodClass);
Symbol eqsym = rs.resolveQualifiedMethod(null, attrEnv, syms.objectType, names.equals, List.of(syms.objectType), List.<Type>nil());
JCMethodInvocation eqtest = make.Apply(
List.<JCExpression>nil(),
make.Select(deserGetter(func, syms.stringType), eqsym).setType(eqmt),
List.<JCExpression>of(make.Literal(lit)));
eqtest.setType(syms.booleanType);
JCBinary compound = make.Binary(JCTree.Tag.AND, prev, eqtest);
compound.operator = rs.resolveBinaryOperator(null, JCTree.Tag.AND, attrEnv, syms.booleanType, syms.booleanType);
compound.setType(syms.booleanType);
return compound;
}
private JCExpression deserGetter(String func, Type type) {
return deserGetter(func, type, List.<Type>nil(), List.nil());
}
private JCExpression deserGetter(String func, Type type, List<Type> argTypes, List args) {
MethodType getmt = new MethodType(argTypes, type, List.<Type>nil(), syms.methodClass);
Symbol getsym = rs.resolveQualifiedMethod(null, attrEnv, syms.serializedLambdaType, names.fromString(func), argTypes, List.<Type>nil());
return make.Apply(
List.<JCExpression>nil(),
make.Select(make.Ident(kInfo.deserParamSym).setType(syms.serializedLambdaType), getsym).setType(getmt),
args).setType(type);
}
/**
* Create new synthetic method with given flags, name, type, owner
*/
private MethodSymbol makePrivateSyntheticMethod(long flags, Name name, Type type, Symbol owner) {
return new MethodSymbol(flags | SYNTHETIC | PRIVATE, name, type, owner);
}
/**
* Create new synthetic variable with given flags, name, type, owner
*/
private VarSymbol makeSyntheticVar(long flags, String name, Type type, Symbol owner) {
return makeSyntheticVar(flags, names.fromString(name), type, owner);
}
/**
* Create new synthetic variable with given flags, name, type, owner
*/
private VarSymbol makeSyntheticVar(long flags, Name name, Type type, Symbol owner) {
return new VarSymbol(flags | SYNTHETIC, name, type, owner);
}
/**
* Set varargsElement field on a given tree (must be either a new class tree
* or a method call tree)
*/
private void setVarargsIfNeeded(JCTree tree, Type varargsElement) {
if (varargsElement != null) {
switch (tree.getTag()) {
case APPLY: ((JCMethodInvocation)tree).varargsElement = varargsElement; break;
case NEWCLASS: ((JCNewClass)tree).varargsElement = varargsElement; break;
default: throw new AssertionError();
}
}
}
/**
* Convert method/constructor arguments by inserting appropriate cast
* as required by type-erasure - this is needed when bridging a lambda/method
* reference, as the bridged signature might require downcast to be compatible
* with the generated signature.
*/
private List<JCExpression> convertArgs(Symbol meth, List args, Type varargsElement) {
Assert.check(meth.kind == Kinds.MTH);
List<Type> formals = types.erasure(meth.type).getParameterTypes();
if (varargsElement != null) {
Assert.check((meth.flags() & VARARGS) != 0);
}
return transTypes.translateArgs(args, formals, varargsElement, attrEnv);
}
// </editor-fold>
/**
* Generate an adapter method "bridge" for a method reference which cannot
* be used directly.
*/
private class MemberReferenceBridger {
private final JCMemberReference tree;
private final ReferenceTranslationContext localContext;
private final ListBuffer<JCExpression> args = new ListBuffer<>();
private final ListBuffer<JCVariableDecl> params = new ListBuffer<>();
MemberReferenceBridger(JCMemberReference tree, ReferenceTranslationContext localContext) {
this.tree = tree;
this.localContext = localContext;
}
/**
* Generate the bridge
*/
JCMethodDecl bridge() {
int prevPos = make.pos;
try {
make.at(tree);
Type samDesc = localContext.bridgedRefSig();
List<Type> samPTypes = samDesc.getParameterTypes();
//an extra argument is prepended to the signature of the bridge in case
//the member reference is an instance method reference (in which case
//the receiver expression is passed to the bridge itself).
Type recType = null;
switch (tree.kind) {
case IMPLICIT_INNER:
recType = tree.sym.owner.type.getEnclosingType();
break;
case BOUND:
recType = tree.getQualifierExpression().type;
break;
case UNBOUND:
recType = samPTypes.head;
samPTypes = samPTypes.tail;
break;
}
//generate the parameter list for the bridged member reference - the
//bridge signature will match the signature of the target sam descriptor
VarSymbol rcvr = (recType == null)
? null
: addParameter("rec$", recType, false);
List<Type> refPTypes = tree.sym.type.getParameterTypes();
int refSize = refPTypes.size();
int samSize = samPTypes.size();
// Last parameter to copy from referenced method
int last = localContext.needsVarArgsConversion() ? refSize - 1 : refSize;
List<Type> l = refPTypes;
// Use parameter types of the referenced method, excluding final var args
for (int i = 0; l.nonEmpty() && i < last; ++i) {
addParameter("x$" + i, l.head, true);
l = l.tail;
}
// Flatten out the var args
for (int i = last; i < samSize; ++i) {
addParameter("xva$" + i, tree.varargsElement, true);
}
//generate the bridge method declaration
JCMethodDecl bridgeDecl = make.MethodDef(make.Modifiers(localContext.bridgeSym.flags()),
localContext.bridgeSym.name,
make.QualIdent(samDesc.getReturnType().tsym),
List.<JCTypeParameter>nil(),
params.toList(),
tree.sym.type.getThrownTypes() == null
? List.<JCExpression>nil()
: make.Types(tree.sym.type.getThrownTypes()),
null,
null);
bridgeDecl.sym = (MethodSymbol) localContext.bridgeSym;
bridgeDecl.type = localContext.bridgeSym.type =
types.createMethodTypeWithParameters(samDesc, TreeInfo.types(params.toList()));
//bridge method body generation - this can be either a method call or a
//new instance creation expression, depending on the member reference kind
JCExpression bridgeExpr = (tree.getMode() == ReferenceMode.INVOKE)
? bridgeExpressionInvoke(makeReceiver(rcvr))
: bridgeExpressionNew();
//the body is either a return expression containing a method call,
//or the method call itself, depending on whether the return type of
//the bridge is non-void/void.
bridgeDecl.body = makeLambdaExpressionBody(bridgeExpr, bridgeDecl);
return bridgeDecl;
} finally {
make.at(prevPos);
}
}
//where
private JCExpression makeReceiver(VarSymbol rcvr) {
if (rcvr == null) return null;
JCExpression rcvrExpr = make.Ident(rcvr);
Type rcvrType = tree.sym.enclClass().type;
if (!rcvr.type.tsym.isSubClass(rcvrType.tsym, types)) {
rcvrExpr = make.TypeCast(make.Type(rcvrType), rcvrExpr).setType(rcvrType);
}
return rcvrExpr;
}
/**
* determine the receiver of the bridged method call - the receiver can
* be either the synthetic receiver parameter or a type qualifier; the
* original qualifier expression is never used here, as it might refer
* to symbols not available in the static context of the bridge
*/
private JCExpression bridgeExpressionInvoke(JCExpression rcvr) {
JCExpression qualifier =
tree.sym.isStatic() ?
make.Type(tree.sym.owner.type) :
(rcvr != null) ?
rcvr :
tree.getQualifierExpression();
//create the qualifier expression
JCFieldAccess select = make.Select(qualifier, tree.sym.name);
select.sym = tree.sym;
select.type = tree.sym.erasure(types);
//create the method call expression
JCExpression apply = make.Apply(List.<JCExpression>nil(), select,
convertArgs(tree.sym, args.toList(), tree.varargsElement)).
setType(tree.sym.erasure(types).getReturnType());
apply = transTypes.coerce(apply, localContext.generatedRefSig().getReturnType());
setVarargsIfNeeded(apply, tree.varargsElement);
return apply;
}
/**
* the enclosing expression is either 'null' (no enclosing type) or set
* to the first bridge synthetic parameter
*/
private JCExpression bridgeExpressionNew() {
if (tree.kind == ReferenceKind.ARRAY_CTOR) {
//create the array creation expression
JCNewArray newArr = make.NewArray(
make.Type(types.elemtype(tree.getQualifierExpression().type)),
List.of(make.Ident(params.first())),
null);
newArr.type = tree.getQualifierExpression().type;
return newArr;
} else {
JCExpression encl = null;
switch (tree.kind) {
case UNBOUND:
case IMPLICIT_INNER:
encl = make.Ident(params.first());
}
//create the instance creation expression
JCNewClass newClass = make.NewClass(encl,
List.<JCExpression>nil(),
make.Type(tree.getQualifierExpression().type),
convertArgs(tree.sym, args.toList(), tree.varargsElement),
null);
newClass.constructor = tree.sym;
newClass.constructorType = tree.sym.erasure(types);
newClass.type = tree.getQualifierExpression().type;
setVarargsIfNeeded(newClass, tree.varargsElement);
return newClass;
}
}
private VarSymbol addParameter(String name, Type p, boolean genArg) {
VarSymbol vsym = new VarSymbol(0, names.fromString(name), p, localContext.bridgeSym);
params.append(make.VarDef(vsym, null));
if (genArg) {
args.append(make.Ident(vsym));
}
return vsym;
}
}
/**
* Bridges a member reference - this is needed when:
* * Var args in the referenced method need to be flattened away
* * super is used
*/
private void bridgeMemberReference(JCMemberReference tree, ReferenceTranslationContext localContext) {
kInfo.addMethod(new MemberReferenceBridger(tree, localContext).bridge());
}
private MethodType typeToMethodType(Type mt) {
Type type = types.erasure(mt);
return new MethodType(type.getParameterTypes(),
type.getReturnType(),
type.getThrownTypes(),
syms.methodClass);
}
/**
* Generate an indy method call to the meta factory
*/
private JCExpression makeMetafactoryIndyCall(TranslationContext<?> context,
int refKind, Symbol refSym, List<JCExpression> indy_args) {
JCFunctionalExpression tree = context.tree;
//determine the static bsm args
MethodSymbol samSym = (MethodSymbol) types.findDescriptorSymbol(tree.type.tsym);
List<Object> staticArgs = List.
Other Java examples (source code examples)
Here is a short list of links related to this Java LambdaToMethod.java source code file: